blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
sequencelengths
1
1
author_id
stringlengths
1
132
e2f31f47bc3e6ca77641e3545093fb0f071d4f07
ee4f74535a92687f51ebc77eee24408d8c925488
/blog/models.py
9966438cc7b73478e3cdafeec56ccc5a5f2f2eff
[]
no_license
sandeepshiven/portfolio_project
ae617d2703c072e0e8c7ff1e1bf92de1b963f0e5
09e53d2594aed81876be84eea4339a5f2150bfb5
refs/heads/master
2022-12-01T02:20:39.305145
2019-12-19T14:26:19
2019-12-19T14:26:19
227,981,293
0
0
null
2022-11-22T04:55:01
2019-12-14T07:07:26
HTML
UTF-8
Python
false
false
382
py
from django.db import models # Create your models here. class Blog(models.Model): title = models.CharField(max_length=50) pub_date = models.DateTimeField() body = models.TextField() image = models.ImageField(upload_to = 'images/') def __str__(self): return self.title def summary(self): return self.body[:200]+"................."
eb3dd994a59471aa0ad713fb833febeade24fb65
f13acd0d707ea9ab0d2f2f010717b35adcee142f
/Others/snuke/snuke21/a.py
68e931ecf644f095aa53460d65c107a576f9d12e
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
KATO-Hiro/AtCoder
126b9fe89fa3a7cffcbd1c29d42394e7d02fa7c7
bf43320bc1af606bfbd23c610b3432cddd1806b9
refs/heads/master
2023-08-18T20:06:42.876863
2023-08-17T23:45:21
2023-08-17T23:45:21
121,067,516
4
0
CC0-1.0
2023-09-14T21:59:38
2018-02-11T00:32:45
Python
UTF-8
Python
false
false
325
py
# -*- coding: utf-8 -*- def main(): from math import sqrt n = int(input()) q = 1 + 8 * n if int(sqrt(q)) ** 2 == q: if (-1 + int(sqrt(q))) % 2 == 0: print((-1 + int(sqrt(q))) // 2) else: print(-1) else: print(-1) if __name__ == '__main__': main()
b155d7cd688658411d1e3a3aa742052fb2a20181
01ac3dadac08b258af33f3e8d2f64229a8d5259a
/unit_tests/neb/pys_chk/RIB2PLYP/BOLi_LiBO_FIRE.py
820a1bcc1dd2f97c4fbdcadf0531dd269d6c5171
[]
no_license
jminuse/clancelot
245f468dd87afe4e2d6ba2d518fe7b20754af7ac
82b4b3afc742d65aaddfce936f94137b0e4f628c
refs/heads/master
2021-01-23T14:03:46.811820
2016-09-20T19:14:50
2016-09-20T19:14:50
36,739,780
1
3
null
2016-04-04T14:38:50
2015-06-02T14:42:47
Python
UTF-8
Python
false
false
387
py
import sys import files, neb fptr = 'BOLi_LiBO' frames = files.read_xyz('/fs/home/hch54/clancelot/unit_tests/neb/xyz/'+fptr+'.xyz') opt = 'FIRE' route = '! RI-B2PLYP D3BJ def2-TZVP def2-TZVP/C Grid3 FinalGrid5' run_name = fptr[:fptr.find('.xyz')] + '_' + opt neb.neb(run_name, frames, route, opt=opt, maxiter=1000, gtol=0.00183726383934, DFT='orca', alpha=0.1, dt=0.1, mem=40, Nmax=20)
c4cb5e306919ee5c35fed911e857689a646c585b
1e9ad304868c2bda918c19eba3d7b122bac3923b
/kubernetes/test/test_v1_service_status.py
d5f786c2cbf01b2f85e8b1121bed9faa4be4318d
[ "Apache-2.0" ]
permissive
pineking/client-python
c77e5bd3d476ac852e6dffa96056008baa0f597f
74a64d7325518f4298600d4bb300f92843c29347
refs/heads/master
2021-01-22T22:16:27.368406
2017-03-15T08:21:21
2017-03-15T08:21:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
867
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.5.1-660c2a2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1_service_status import V1ServiceStatus class TestV1ServiceStatus(unittest.TestCase): """ V1ServiceStatus unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1ServiceStatus(self): """ Test V1ServiceStatus """ model = kubernetes.client.models.v1_service_status.V1ServiceStatus() if __name__ == '__main__': unittest.main()
06f0a4da06e156333a6a8b4a2dbbca61d50e8de5
99117515c0410cea29357adfdf71aa628241ece1
/posts/tests.py
77595ac51b8b58c5fe0042066b95086632b8d949
[ "MIT" ]
permissive
kangsLee/9XD
e3a774184381a03722f09a4bed86132b67845118
f80ea88f85f4cc677c7d1b404101e2ffe8b538ea
refs/heads/master
2021-04-28T23:42:13.918903
2016-12-30T16:16:29
2016-12-30T16:16:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
839
py
from test_plus.test import TestCase from posts.factories import PostFactory class PostsTest(TestCase): def test_get_list(self): post = PostFactory() post_list_url = self.reverse('post:list') self.get_check_200(post_list_url) self.assertResponseContains(post.title, html=False) self.assertResponseContains(post.author.name, html=False) write_url = self.reverse('post:create') self.assertResponseContains(write_url, html=False) def test_get_writing_page_with_login(self): user = self.make_user('jelly jelly') with self.login(username=user.username): write_post_url = self.reverse('post:create') self.get_check_200(write_post_url) def test_get_writing_page_with_anonymous(self): self.assertLoginRequired('post:create')
e61d55be1f72641485b0dfbb597f67d9e51f18f0
564d6a4d305a8ac6a7e01c761831fb2081c02d0f
/sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_03_01/operations/_express_route_gateways_operations.py
7ec7e728a183ae5f3851338bd9622272365624d5
[ "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later", "MIT" ]
permissive
paultaiton/azure-sdk-for-python
69af4d889bac8012b38f5b7e8108707be679b472
d435a1a25fd6097454b7fdfbbdefd53e05029160
refs/heads/master
2023-01-30T16:15:10.647335
2020-11-14T01:09:50
2020-11-14T01:09:50
283,343,691
0
0
MIT
2020-07-28T22:43:43
2020-07-28T22:43:43
null
UTF-8
Python
false
false
21,746
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class ExpressRouteGatewaysOperations(object): """ExpressRouteGatewaysOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2020_03_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_by_subscription( self, **kwargs # type: Any ): # type: (...) -> "models.ExpressRouteGatewayList" """Lists ExpressRoute gateways under a given subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: ExpressRouteGatewayList, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_03_01.models.ExpressRouteGatewayList :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.ExpressRouteGatewayList"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-03-01" accept = "application/json" # Construct URL url = self.list_by_subscription.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteGatewayList', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteGateways'} # type: ignore def list_by_resource_group( self, resource_group_name, # type: str **kwargs # type: Any ): # type: (...) -> "models.ExpressRouteGatewayList" """Lists ExpressRoute gateways in a given resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ExpressRouteGatewayList, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_03_01.models.ExpressRouteGatewayList :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.ExpressRouteGatewayList"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-03-01" accept = "application/json" # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteGatewayList', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways'} # type: ignore def _create_or_update_initial( self, resource_group_name, # type: str express_route_gateway_name, # type: str put_express_route_gateway_parameters, # type: "models.ExpressRouteGateway" **kwargs # type: Any ): # type: (...) -> "models.ExpressRouteGateway" cls = kwargs.pop('cls', None) # type: ClsType["models.ExpressRouteGateway"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-03-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'expressRouteGatewayName': self._serialize.url("express_route_gateway_name", express_route_gateway_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(put_express_route_gateway_parameters, 'ExpressRouteGateway') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('ExpressRouteGateway', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('ExpressRouteGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}'} # type: ignore def begin_create_or_update( self, resource_group_name, # type: str express_route_gateway_name, # type: str put_express_route_gateway_parameters, # type: "models.ExpressRouteGateway" **kwargs # type: Any ): # type: (...) -> LROPoller["models.ExpressRouteGateway"] """Creates or updates a ExpressRoute gateway in a specified resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param express_route_gateway_name: The name of the ExpressRoute gateway. :type express_route_gateway_name: str :param put_express_route_gateway_parameters: Parameters required in an ExpressRoute gateway PUT operation. :type put_express_route_gateway_parameters: ~azure.mgmt.network.v2020_03_01.models.ExpressRouteGateway :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either ExpressRouteGateway or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2020_03_01.models.ExpressRouteGateway] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["models.ExpressRouteGateway"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, express_route_gateway_name=express_route_gateway_name, put_express_route_gateway_parameters=put_express_route_gateway_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ExpressRouteGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}'} # type: ignore def get( self, resource_group_name, # type: str express_route_gateway_name, # type: str **kwargs # type: Any ): # type: (...) -> "models.ExpressRouteGateway" """Fetches the details of a ExpressRoute gateway in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param express_route_gateway_name: The name of the ExpressRoute gateway. :type express_route_gateway_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ExpressRouteGateway, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_03_01.models.ExpressRouteGateway :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.ExpressRouteGateway"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-03-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'expressRouteGatewayName': self._serialize.url("express_route_gateway_name", express_route_gateway_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str express_route_gateway_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-03-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'expressRouteGatewayName': self._serialize.url("express_route_gateway_name", express_route_gateway_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str express_route_gateway_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes the specified ExpressRoute gateway in a resource group. An ExpressRoute gateway resource can only be deleted when there are no connection subresources. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param express_route_gateway_name: The name of the ExpressRoute gateway. :type express_route_gateway_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, express_route_gateway_name=express_route_gateway_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteGateways/{expressRouteGatewayName}'} # type: ignore
9931d68bde183982f725f119901d39bc281b0f83
5d36864f5f9f1b737c4718703ee53c3aa715e398
/CourseGrading/3.2.11整数列表排序.py
1505665fa902de210a4dfcebd676dabf3f5b4234
[]
no_license
xzl995/Python
d909274c9aba8ae9f18029a5f2069b1bb3418b9a
48d4add7a1d46b2e3773bdf096e834852115014d
refs/heads/master
2020-04-14T11:51:35.407548
2019-01-02T10:54:55
2019-01-02T10:54:55
163,824,702
4
1
null
null
null
null
UTF-8
Python
false
false
457
py
""" 【问题描述】 输入一组整数,从小到大排序后,输出排序结果。 【输入形式】 一行。一组用空格隔开的整数。 【输出形式】 一行。一组用一个空格隔开的整数,从小到大排列。 【样例输入】 9 8 7 6 【样例输出】 6 7 8 9 【提示】 用列表的sort方法。 """ num = input().split() list = [] for n in num: list.append(int(n)) list.sort() print(" ".join(str(i) for i in list))
26626eb142093d221f57181092ec5e01fd199ae3
2fe58e7f6bfc3efdb78ca56f72a4e2a75a24c270
/eric/eric6/WebBrowser/Download/DownloadItem.py
7c3396e56dc7d5e82befafebf3eaab050ad5c2a0
[]
no_license
testerclub/eric6-20.3
3053e0e6962060b213f5df329ee331a4893d18e6
bba0b9f13fa3eb84938422732d751219bc3e29e2
refs/heads/master
2023-03-18T08:24:03.472297
2020-03-14T06:44:14
2020-03-14T06:44:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
21,022
py
# -*- coding: utf-8 -*- # Copyright (c) 2010 - 2020 Detlev Offenbach <[email protected]> # """ Module implementing a widget controlling a download. """ import os from PyQt5.QtCore import ( pyqtSlot, pyqtSignal, Qt, QTime, QUrl, QStandardPaths, QFileInfo, QDateTime ) from PyQt5.QtGui import QPalette, QDesktopServices from PyQt5.QtWidgets import QWidget, QStyle, QDialog from PyQt5.QtWebEngineWidgets import QWebEngineDownloadItem from E5Gui import E5FileDialog from .Ui_DownloadItem import Ui_DownloadItem from .DownloadUtilities import timeString, dataString, speedString from WebBrowser.WebBrowserWindow import WebBrowserWindow import UI.PixmapCache import Utilities.MimeTypes class DownloadItem(QWidget, Ui_DownloadItem): """ Class implementing a widget controlling a download. @signal statusChanged() emitted upon a status change of a download @signal downloadFinished(success) emitted when a download finished @signal progress(int, int) emitted to signal the download progress """ statusChanged = pyqtSignal() downloadFinished = pyqtSignal(bool) progress = pyqtSignal(int, int) Downloading = 0 DownloadSuccessful = 1 DownloadCancelled = 2 def __init__(self, downloadItem=None, pageUrl=None, parent=None): """ Constructor @param downloadItem reference to the download object containing the download data. @type QWebEngineDownloadItem @param pageUrl URL of the calling page @type QUrl @param parent reference to the parent widget @type QWidget """ super(DownloadItem, self).__init__(parent) self.setupUi(self) p = self.infoLabel.palette() p.setColor(QPalette.Text, Qt.darkGray) self.infoLabel.setPalette(p) self.progressBar.setMaximum(0) self.pauseButton.setIcon(UI.PixmapCache.getIcon("pause.png")) self.stopButton.setIcon(UI.PixmapCache.getIcon("stopLoading.png")) self.openButton.setIcon(UI.PixmapCache.getIcon("open.png")) self.openButton.setEnabled(False) self.openButton.setVisible(False) if not hasattr(QWebEngineDownloadItem, "pause"): # pause/resume was defined in Qt 5.10.0 / PyQt 5.10.0 self.pauseButton.setEnabled(False) self.pauseButton.setVisible(False) self.__state = DownloadItem.Downloading icon = self.style().standardIcon(QStyle.SP_FileIcon) self.fileIcon.setPixmap(icon.pixmap(48, 48)) self.__downloadItem = downloadItem if pageUrl is None: self.__pageUrl = QUrl() else: self.__pageUrl = pageUrl self.__bytesReceived = 0 self.__bytesTotal = -1 self.__downloadTime = QTime() self.__fileName = "" self.__originalFileName = "" self.__finishedDownloading = False self.__gettingFileName = False self.__canceledFileSelect = False self.__autoOpen = False self.__downloadedDateTime = QDateTime() self.__initialize() def __initialize(self): """ Private method to initialize the widget. """ if self.__downloadItem is None: return self.__finishedDownloading = False self.__bytesReceived = 0 self.__bytesTotal = -1 # start timer for the download estimation self.__downloadTime.start() # attach to the download item object self.__url = self.__downloadItem.url() self.__downloadItem.downloadProgress.connect(self.__downloadProgress) self.__downloadItem.finished.connect(self.__finished) # reset info self.datetimeLabel.clear() self.datetimeLabel.hide() self.infoLabel.clear() self.progressBar.setValue(0) if ( self.__downloadItem.state() == QWebEngineDownloadItem.DownloadRequested ): self.__getFileName() if not self.__fileName: self.__downloadItem.cancel() else: self.__downloadItem.setPath(self.__fileName) self.__downloadItem.accept() else: fileName = self.__downloadItem.path() self.__setFileName(fileName) def __getFileName(self): """ Private method to get the file name to save to from the user. """ if self.__gettingFileName: return savePage = self.__downloadItem.type() == ( QWebEngineDownloadItem.SavePage ) documentLocation = QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation) downloadDirectory = ( WebBrowserWindow.downloadManager().downloadDirectory() ) if self.__fileName: fileName = self.__fileName originalFileName = self.__originalFileName self.__toDownload = True ask = False else: defaultFileName, originalFileName = self.__saveFileName( documentLocation if savePage else downloadDirectory) fileName = defaultFileName self.__originalFileName = originalFileName ask = True self.__autoOpen = False if not savePage: from .DownloadAskActionDialog import DownloadAskActionDialog url = self.__downloadItem.url() mimetype = Utilities.MimeTypes.mimeType(originalFileName) dlg = DownloadAskActionDialog( QFileInfo(originalFileName).fileName(), mimetype, "{0}://{1}".format(url.scheme(), url.authority()), self) if dlg.exec_() == QDialog.Rejected or dlg.getAction() == "cancel": self.progressBar.setVisible(False) self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True self.__setDateTime() return if dlg.getAction() == "scan": self.__mainWindow.requestVirusTotalScan(url) self.progressBar.setVisible(False) self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("VirusTotal scan scheduled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return self.__autoOpen = dlg.getAction() == "open" tempLocation = QStandardPaths.writableLocation( QStandardPaths.TempLocation) fileName = ( tempLocation + '/' + QFileInfo(fileName).completeBaseName() ) if ask and not self.__autoOpen: self.__gettingFileName = True fileName = E5FileDialog.getSaveFileName( None, self.tr("Save File"), defaultFileName, "") self.__gettingFileName = False if not fileName: self.progressBar.setVisible(False) self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}") .format(QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True self.__setDateTime() return self.__setFileName(fileName) def __setFileName(self, fileName): """ Private method to set the file name to save the download into. @param fileName name of the file to save into @type str """ fileInfo = QFileInfo(fileName) WebBrowserWindow.downloadManager().setDownloadDirectory( fileInfo.absoluteDir().absolutePath()) self.filenameLabel.setText(fileInfo.fileName()) self.__fileName = fileName # check file path for saving saveDirPath = QFileInfo(self.__fileName).dir() if not saveDirPath.exists(): if not saveDirPath.mkpath(saveDirPath.absolutePath()): self.progressBar.setVisible(False) self.on_stopButton_clicked() self.infoLabel.setText(self.tr( "Download directory ({0}) couldn't be created.") .format(saveDirPath.absolutePath())) self.__setDateTime() return self.filenameLabel.setText(QFileInfo(self.__fileName).fileName()) def __saveFileName(self, directory): """ Private method to calculate a name for the file to download. @param directory name of the directory to store the file into (string) @return proposed filename and original filename (string, string) """ path = self.__downloadItem.path() info = QFileInfo(path) baseName = info.completeBaseName() endName = info.suffix() origName = baseName if endName: origName += '.' + endName name = os.path.join(directory, baseName) if endName: name += '.' + endName return name, origName @pyqtSlot(bool) def on_pauseButton_clicked(self, checked): """ Private slot to pause the download. @param checked flag indicating the state of the button @type bool """ if checked: self.__downloadItem.pause() else: self.__downloadItem.resume() @pyqtSlot() def on_stopButton_clicked(self): """ Private slot to stop the download. """ self.cancelDownload() def cancelDownload(self): """ Public slot to stop the download. """ self.setUpdatesEnabled(False) self.stopButton.setEnabled(False) self.stopButton.setVisible(False) self.openButton.setEnabled(False) self.openButton.setVisible(False) self.pauseButton.setEnabled(False) self.pauseButton.setVisible(False) self.setUpdatesEnabled(True) self.__state = DownloadItem.DownloadCancelled self.__downloadItem.cancel() self.__setDateTime() self.downloadFinished.emit(False) @pyqtSlot() def on_openButton_clicked(self): """ Private slot to open the downloaded file. """ self.openFile() def openFile(self): """ Public slot to open the downloaded file. """ info = QFileInfo(self.__fileName) url = QUrl.fromLocalFile(info.absoluteFilePath()) QDesktopServices.openUrl(url) def openFolder(self): """ Public slot to open the folder containing the downloaded file. """ info = QFileInfo(self.__fileName) url = QUrl.fromLocalFile(info.absolutePath()) QDesktopServices.openUrl(url) def __downloadProgress(self, bytesReceived, bytesTotal): """ Private method to show the download progress. @param bytesReceived number of bytes received (integer) @param bytesTotal number of total bytes (integer) """ self.__bytesReceived = bytesReceived self.__bytesTotal = bytesTotal currentValue = 0 totalValue = 0 if bytesTotal > 0: currentValue = bytesReceived * 100 / bytesTotal totalValue = 100 self.progressBar.setValue(currentValue) self.progressBar.setMaximum(totalValue) self.progress.emit(currentValue, totalValue) self.__updateInfoLabel() def downloadProgress(self): """ Public method to get the download progress. @return current download progress @rtype int """ return self.progressBar.value() def bytesTotal(self): """ Public method to get the total number of bytes of the download. @return total number of bytes (integer) """ if self.__bytesTotal == -1: self.__bytesTotal = self.__downloadItem.totalBytes() return self.__bytesTotal def bytesReceived(self): """ Public method to get the number of bytes received. @return number of bytes received (integer) """ return self.__bytesReceived def remainingTime(self): """ Public method to get an estimation for the remaining time. @return estimation for the remaining time (float) """ if not self.downloading(): return -1.0 if self.bytesTotal() == -1: return -1.0 cSpeed = self.currentSpeed() if cSpeed != 0: timeRemaining = (self.bytesTotal() - self.bytesReceived()) / cSpeed else: timeRemaining = 1 # ETA should never be 0 if timeRemaining == 0: timeRemaining = 1 return timeRemaining def currentSpeed(self): """ Public method to get an estimation for the download speed. @return estimation for the download speed (float) """ if not self.downloading(): return -1.0 return self.__bytesReceived * 1000.0 / self.__downloadTime.elapsed() def __updateInfoLabel(self): """ Private method to update the info label. """ bytesTotal = self.bytesTotal() running = not self.downloadedSuccessfully() speed = self.currentSpeed() timeRemaining = self.remainingTime() info = "" if running: remaining = "" if bytesTotal > 0: remaining = timeString(timeRemaining) info = self.tr( "{0} of {1} ({2}/sec) {3}" ).format( dataString(self.__bytesReceived), bytesTotal == -1 and self.tr("?") or dataString(bytesTotal), speedString(speed), remaining ) else: if self.__bytesReceived == bytesTotal or bytesTotal == -1: info = self.tr( "{0} downloaded" ).format(dataString(self.__bytesReceived)) else: info = self.tr( "{0} of {1} - Stopped" ).format(dataString(self.__bytesReceived), dataString(bytesTotal)) self.infoLabel.setText(info) def downloading(self): """ Public method to determine, if a download is in progress. @return flag indicating a download is in progress (boolean) """ return self.__state == DownloadItem.Downloading def downloadedSuccessfully(self): """ Public method to check for a successful download. @return flag indicating a successful download (boolean) """ return self.__state == DownloadItem.DownloadSuccessful def downloadCanceled(self): """ Public method to check, if the download was cancelled. @return flag indicating a canceled download (boolean) """ return self.__state == DownloadItem.DownloadCancelled def __finished(self): """ Private slot to handle the download finished. """ self.__finishedDownloading = True noError = (self.__downloadItem.state() == QWebEngineDownloadItem.DownloadCompleted) self.progressBar.setVisible(False) self.pauseButton.setEnabled(False) self.pauseButton.setVisible(False) self.stopButton.setEnabled(False) self.stopButton.setVisible(False) self.openButton.setEnabled(noError) self.openButton.setVisible(noError) self.__state = DownloadItem.DownloadSuccessful self.__updateInfoLabel() self.__setDateTime() self.__adjustSize() self.statusChanged.emit() self.downloadFinished.emit(True) if self.__autoOpen: self.openFile() def canceledFileSelect(self): """ Public method to check, if the user canceled the file selection. @return flag indicating cancellation (boolean) """ return self.__canceledFileSelect def setIcon(self, icon): """ Public method to set the download icon. @param icon reference to the icon to be set (QIcon) """ self.fileIcon.setPixmap(icon.pixmap(48, 48)) def fileName(self): """ Public method to get the name of the output file. @return name of the output file (string) """ return self.__fileName def absoluteFilePath(self): """ Public method to get the absolute path of the output file. @return absolute path of the output file (string) """ return QFileInfo(self.__fileName).absoluteFilePath() def getData(self): """ Public method to get the relevant download data. @return dictionary containing the URL, save location, done flag, the URL of the related web page and the date and time of the download @rtype dict of {"URL": QUrl, "Location": str, "Done": bool, "PageURL": QUrl, "Downloaded": QDateTime} """ return { "URL": self.__url, "Location": QFileInfo(self.__fileName).filePath(), "Done": self.downloadedSuccessfully(), "PageURL": self.__pageUrl, "Downloaded": self.__downloadedDateTime } def setData(self, data): """ Public method to set the relevant download data. @param data dictionary containing the URL, save location, done flag, the URL of the related web page and the date and time of the download @type dict of {"URL": QUrl, "Location": str, "Done": bool, "PageURL": QUrl, "Downloaded": QDateTime} """ self.__url = data["URL"] self.__fileName = data["Location"] self.__pageUrl = data["PageURL"] self.filenameLabel.setText(QFileInfo(self.__fileName).fileName()) self.infoLabel.setText(self.__fileName) try: self.__setDateTime(data["Downloaded"]) except KeyError: self.__setDateTime(QDateTime()) self.pauseButton.setEnabled(False) self.pauseButton.setVisible(False) self.stopButton.setEnabled(False) self.stopButton.setVisible(False) self.openButton.setEnabled(data["Done"]) self.openButton.setVisible(data["Done"]) if data["Done"]: self.__state = DownloadItem.DownloadSuccessful else: self.__state = DownloadItem.DownloadCancelled self.progressBar.setVisible(False) self.__adjustSize() def getInfoData(self): """ Public method to get the text of the info label. @return text of the info label (string) """ return self.infoLabel.text() def getPageUrl(self): """ Public method to get the URL of the download page. @return URL of the download page (QUrl) """ return self.__pageUrl def __adjustSize(self): """ Private method to adjust the size of the download item. """ self.ensurePolished() msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height()) def __setDateTime(self, dateTime=None): """ Private method to set the download date and time. @param dateTime date and time to be set @type QDateTime """ if dateTime is None: self.__downloadedDateTime = QDateTime.currentDateTime() else: self.__downloadedDateTime = dateTime if self.__downloadedDateTime.isValid(): labelText = self.__downloadedDateTime.toString("yyyy-MM-dd hh:mm") self.datetimeLabel.setText(labelText) self.datetimeLabel.show() else: self.datetimeLabel.clear() self.datetimeLabel.hide()
135ba6b27144192daf557049497729eec9ce5091
5bcee9248d0bdebb134c61b4d0a3f3113337a569
/IV_term/02_lesson_2704/02_turtle_commands.py
34fc4f3dc65273ce01d64bb61b8de0376dda47e6
[]
no_license
100ballovby/6V_Lesson
c2edbc652ea2ebec07eeed60060c16ae4b4792e4
4b6dfda323a628558bd63bd5569960004fc335dd
refs/heads/master
2023-05-08T07:49:14.569854
2021-05-25T06:40:53
2021-05-25T06:40:53
330,888,686
0
0
null
null
null
null
UTF-8
Python
false
false
498
py
from turtle import * tina = Turtle() tina.shape('turtle') tina.fd(100) # .fd(step), .forward(step) пойти вперед step шагов tina.lt(45) # .lt(deg), .left(deg) повернуть влево на deg градусов tina.bk(120) # .bk(step), .backward(step) пойти назад step шагов tina.rt(90) # .rt(deg), right(deg) повернуть вправо на deg градусов tina.up() # не рисовать tina.fd(150) tina.down() # рисовать done()
37f76c51e0f3b2f6ee42258c7c21005a91451284
d9dddd43e61ade0eab50098df79a3b116c76fbb8
/terrender/__init__.py
74040da3f042dcd7419a268e959b07218bfcee45
[]
no_license
Mortal/terrender
18d704ae20e1b647818e1e1b5e6a3660f49765f2
c1103a7f62d7f4b696a98e38aff303b02a1a0b30
refs/heads/master
2021-01-21T22:05:44.684318
2018-07-09T12:13:05
2018-10-08T08:00:50
95,161,822
0
0
null
null
null
null
UTF-8
Python
false
false
94
py
APP_NAME = 'terrender' DESCRIPTION = '''\ Render terrains to vector formats '''.rstrip('\n')
f1ae77ce6c8a31bdb0e7fbe79377aaef1b871b5d
b0bb5a3e1bd4efc3bdc035f477c2b14c40b3d62a
/blog/templatetags/blog_tags.py
f6655ef002989018795274f5d168b3d84b2eb876
[]
no_license
yuansuixin/Myblog_Python
45c0bd610ab3dbbcdc10b4b4b9e45589f178ce29
a6b0c526371def0aab8fd7251517a97ce215168c
refs/heads/master
2021-09-05T21:02:37.227342
2018-01-31T01:31:14
2018-01-31T01:31:14
114,453,469
0
0
null
null
null
null
UTF-8
Python
false
false
871
py
from django import template from ..models import Post,Category,Tag from django.db.models.aggregates import Count from blog.models import Category register = template.Library() @register.simple_tag def get_recent_posts(num=5): return Post.objects.all().order_by('-created_time')[:num] @register.simple_tag def archives(): return Post.objects.dates('created_time', 'month', order='DESC') @register.simple_tag def get_categories(): # 别忘了在顶部引入 Category 类 # 记得在顶部引入 count 函数 # Count 计算分类下的文章数,其接受的参数为需要计数的模型的名称 return Category.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0) @register.simple_tag def get_tags(): # 记得在顶部引入 Tag model return Tag.objects.annotate(num_posts=Count('post')).filter(num_posts__gt=0)
5e3a365993b2027bd0ca4a439c8b29a1a03cc4e5
db54727e37a0928ed698171e862ad274b99a02b1
/get_angelist_jobs_by_location.py
a8f0282858b2fbff8abaa29e875b1ae5bc664c2a
[ "MIT" ]
permissive
tibbetts/sfba-compensation
6514a58c004b468c5eb0b204087d5a1d8d168a12
89a36391c7dd778b6343e67c2f8d587651b1d7f2
refs/heads/master
2020-04-05T23:46:12.264717
2016-06-01T05:09:35
2016-06-01T05:09:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,524
py
import urllib2 import json import datetime import csv import time #https://api.angel.co/1/tags/151282/jobs?access_token=xxx access_token = "<FILL IN>" # DO NOT SHARE WITH ANYONE! location_tag = 151282 # San Francisco Bay Area # location_tag = 1664 # New York City def request_until_succeed(url): req = urllib2.Request(url) success = False while success is False: try: response = urllib2.urlopen(req) if response.getcode() == 200: success = True except Exception, e: print e time.sleep(5) print "Error for URL %s: %s" % (url, datetime.datetime.now()) return response.read() # Needed to write tricky unicode correctly to csv; not present in tutorial def unicode_normalize(text): return text.translate({ 0x2018:0x27, 0x2019:0x27, 0x201C:0x22, 0x201D:0x22, 0xa0:0x20 }).encode('utf-8') def getAngelListPageFeedData(location_tag, access_token, page_num): # construct the URL string url = "https://api.angel.co/1/tags/%s/jobs?access_token=%s&page=%s" % (location_tag, access_token, page_num) # retrieve data data = json.loads(request_until_succeed(url)) return data def processAngelListPageFeedStatus(job): # The status is now a Python dictionary, so for top-level items, # we can simply call the key. # Additionally, some items may not always exist, # so must check for existence first job_id = job['id'] job_title = '' if 'title' not in job.keys() else unicode_normalize(job['title']) job_type = '' if 'job_type' not in job.keys() else unicode_normalize(job['job_type']) job_city = [unicode_normalize(tag['display_name']) for tag in job['tags'] if tag['tag_type'] == 'LocationTag'][0].decode('utf-8') salary_min = '' if 'salary_min' not in job.keys() else job['salary_min'] salary_max = '' if 'salary_max' not in job.keys() else job['salary_max'] equity_cliff = '' if 'equity_cliff' not in job.keys() else job['equity_cliff'] equity_vest = '' if 'equity_vest' not in job.keys() else job['equity_vest'] equity_min = '' if 'equity_min' not in job.keys() else job['equity_min'] equity_max = '' if 'equity_max' not in job.keys() else job['equity_max'] roles = ', '.join([unicode_normalize(tag['display_name']) for tag in job['tags'] if tag['tag_type'] == 'RoleTag']).decode('utf-8') skills = ', '.join([unicode_normalize(tag['display_name']) for tag in job['tags'] if tag['tag_type'] == 'SkillTag']).decode('utf-8') # Time needs special care since a) it's in UTC and # b) it's not easy to use in statistical programs. updated_at = datetime.datetime.strptime(job['updated_at'],'%Y-%m-%dT%H:%M:%SZ') updated_at = updated_at + datetime.timedelta(hours=-8) # PST updated_at = updated_at.strftime('%Y-%m-%d %H:%M:%S') # best time format for spreadsheet programs # return a tuple of all processed data return (job_id, job_title, job_type, job_city, salary_min, salary_max, equity_cliff, equity_vest, equity_min, equity_max, roles, skills, updated_at) def scrapeAngelListPageFeedStatus(location_tag, access_token): with open('%s_angelist_jobs.csv' % location_tag, 'wb') as file: w = csv.writer(file) w.writerow(['job_id', 'job_title', 'job_type', 'job_city', 'salary_min', 'salary_max', 'equity_cliff', 'equity_vest', 'equity_min', 'equity_max', 'roles', 'skills', 'updated_at']) has_next_page = True page = 1 num_processed = 0 # keep a count on how many we've processed scrape_starttime = datetime.datetime.now() print "Scraping %s AngelList Page: %s\n" % (location_tag, scrape_starttime) while has_next_page: data = getAngelListPageFeedData(location_tag, access_token, page) for job in data['jobs']: w.writerow(processAngelListPageFeedStatus(job)) # output progress occasionally to make sure code is not stalling num_processed += 1 if num_processed % 100 == 0: print "%s Jobs Processed: %s" % (num_processed, datetime.datetime.now()) # if there is no next page, we're done. if data['last_page'] == page: has_next_page = False else: page += 1 #print "\nDone!\n%s Jobs Processed in %s" % (num_processed, datetime.datetime.now() - scrape_starttime) if __name__ == '__main__': scrapeAngelListPageFeedStatus(location_tag, access_token) # The CSV can be opened in all major statistical programs. Have fun! :)
9734b8d821852dd069ae730eb6e5581f79278c28
3bdcb60b0bffeeb6ff7b0ddca4792b682158bb12
/Sentencias Condicionales/4.1.8-90.py
c0d1ba9b3e6d0df836a98fc9e064ff10920a2037
[]
no_license
FrankCasanova/Python
03c811801ec8ecd5ace66914f984a94f12befe06
03f15100991724a49437df3ce704837812173fc5
refs/heads/master
2023-05-23T01:37:12.632204
2021-06-10T15:20:38
2021-06-10T15:20:38
278,167,039
0
0
null
null
null
null
UTF-8
Python
false
false
784
py
#CORRECCIÓN DE PROGRAMA. from math import pi radio = float(input('Dame el radio de un circulo: ')) #menú print('Escoge una opción: ') print('a) Calcular el diámetro: ') print('b) Calcular el perímetro: ') print('c) Calcular el área: ') opción = input('Teclea a, b o c y pulsa intro: ') if opción.lower() == 'a': diámetro = 2*pi print('El diámetro es {0}'.format(diámetro)) else: if opción.lower() == 'b': perímetro = 2*pi*radio print('El perímetro es {0}'.format(perímetro)) else: if opción.lower() == 'c': área = pi*radio**2 print('El área es {0}'.format(área)) else: print('Solo hay 3 opciónes: a, b o c.') print('Tú has tecleado {0}'.format(opción))
ea92fcc7c3a19e5cc1c4276c6e75738bd12b4d5b
9d58364bd43fbb4edf60fba3425e9dc006097e22
/product/serializers.py
e6571d2151ef723f8b3eab7b9cfa5344cf3c8373
[]
no_license
darkblank/commerce-toy
a92ee2634777fa9997cb52c57f2fd8a68877677c
be8b4b7633204c83615853835c3772369e37766a
refs/heads/master
2022-12-03T14:18:54.966662
2020-08-12T22:29:49
2020-08-12T22:29:49
287,127,153
0
0
null
null
null
null
UTF-8
Python
false
false
1,166
py
from rest_framework import serializers from product.models import Product, ProductOption from user.serializers import ProviderSerializer class ProductOptionSerializer(serializers.ModelSerializer): class Meta: model = ProductOption fields = ( 'id', 'stock', 'name', ) class ProductSerializer(serializers.ModelSerializer): provider = ProviderSerializer() options = ProductOptionSerializer(many=True) class Meta: model = Product fields = ( 'id', 'name', 'price', 'shipping_price', 'is_on_sale', 'can_bundle', 'created_at', 'updated_at', 'provider', 'options', ) class ProductWithoutOptionsSerializer(ProductSerializer): class Meta: model = Product fields = ( 'id', 'name', 'price', 'shipping_price', 'is_on_sale', 'can_bundle', 'created_at', 'updated_at', 'provider', ) class ProductOptionWithProductSerializer(ProductOptionSerializer): product = ProductWithoutOptionsSerializer() class Meta: model = ProductOption fields = ( 'id', 'stock', 'name', 'product', )
c37f6418fac1b3ca989225a2b5d667bc7a56df58
0e478f3d8b6c323c093455428c9094c45de13bac
/src/OTLMOW/PostenMapping/Model/Post060352270.py
1361d8f30b13daab25781738ad6daac5b6a201ce
[ "MIT" ]
permissive
davidvlaminck/OTLMOW
c6eae90b2cab8a741271002cde454427ca8b75ba
48f8c357c475da1d2a1bc7820556843d4b37838d
refs/heads/main
2023-01-12T05:08:40.442734
2023-01-10T15:26:39
2023-01-10T15:26:39
432,681,113
3
1
MIT
2022-06-20T20:36:00
2021-11-28T10:28:24
Python
UTF-8
Python
false
false
3,846
py
# coding=utf-8 from OTLMOW.PostenMapping.StandaardPost import StandaardPost from OTLMOW.PostenMapping.StandaardPostMapping import StandaardPostMapping # Generated with PostenCreator. To modify: extend, do not edit class Post060352270(StandaardPost): def __init__(self): super().__init__( nummer='0603.52270', beschrijving='Bestrating van gebakken straatstenen, standaardkwaliteitsklasse B volgens 6-3.6, dikformaat, hoogte ca. 70 mm', meetstaateenheid='M2', mappings=[StandaardPostMapping( typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen', attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen.formaatVanBestratingselement', dotnotation='formaatVanBestratingselement', defaultWaarde='dikformaat-(ca.-200-x-ca.-65-mm)', range='', usagenote='', isMeetstaatAttr=0, isAltijdInTeVullen=0, isBasisMapping=1, mappingStatus='gemapt 2.0', mappingOpmerking='', standaardpostnummer='0603.52270') , StandaardPostMapping( typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen', attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/abstracten#Laag.laagRol', dotnotation='laagRol', defaultWaarde='straatlaag', range='', usagenote='', isMeetstaatAttr=0, isAltijdInTeVullen=0, isBasisMapping=1, mappingStatus='gemapt 2.0', mappingOpmerking='', standaardpostnummer='0603.52270') , StandaardPostMapping( typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen', attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen.standaardkwaliteitsklasse', dotnotation='standaardkwaliteitsklasse', defaultWaarde='b', range='', usagenote='', isMeetstaatAttr=0, isAltijdInTeVullen=0, isBasisMapping=1, mappingStatus='gemapt 2.0', mappingOpmerking='', standaardpostnummer='0603.52270') , StandaardPostMapping( typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen', attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/abstracten#LaagDikte.dikte', dotnotation='dikte', defaultWaarde='7', range='', usagenote='cm^^cdt:ucumunit', isMeetstaatAttr=0, isAltijdInTeVullen=0, isBasisMapping=1, mappingStatus='gemapt 2.0', mappingOpmerking='', standaardpostnummer='0603.52270') , StandaardPostMapping( typeURI='https://wegenenverkeer.data.vlaanderen.be/ns/onderdeel#BestratingVanGebakkenStraatsteen', attribuutURI='https://wegenenverkeer.data.vlaanderen.be/ns/abstracten#Laag.oppervlakte', dotnotation='oppervlakte', defaultWaarde='', range='', usagenote='m2^^cdt:ucumunit', isMeetstaatAttr=1, isAltijdInTeVullen=1, isBasisMapping=1, mappingStatus='gemapt 2.0', mappingOpmerking='', standaardpostnummer='0603.52270')])
9e5d5b8517e58b290fe195b2aab1e2d9938074d6
aced407b41f6669f69e9eb8bd599260d50c0bd3f
/server/libs/top/api/rest/TaobaokeMobileListurlGetRequest.py
b09b1da208bf08fea60e8912f9988fb2a936ad96
[]
no_license
alswl/music_sofa
42f7d15431f11b97bf67b604cfde0a0e9e3860cc
c4e5425ef6c80c3e57c91ba568f7cbfe63faa378
refs/heads/master
2016-09-12T18:37:34.357510
2016-05-20T11:49:52
2016-05-20T11:49:52
58,946,171
1
1
null
null
null
null
UTF-8
Python
false
false
312
py
''' Created by auto_sdk on 2013-11-07 12:53:22 ''' from top.api.base import RestApi class TaobaokeMobileListurlGetRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.q = None def getapiname(self): return 'taobao.taobaoke.mobile.listurl.get'
c9364b17c64e0b99950c44eaf940ac5a5081aea4
b1403c5a0f8dcf5eec881367f3928c6faf047b1d
/PRINCIPIANTE/1051-1100/1098.py
d3a71591410aff0c977f88c66d582bdb8e28a005
[]
no_license
apesquero/URI
ba56f9d597e0e781bf85dc14eeeedf9bc206fbc4
8c45813d99eb903405ebe1a0e2c6618e87025641
refs/heads/master
2021-06-19T23:56:51.798180
2021-01-01T18:43:20
2021-01-01T18:43:20
138,192,837
0
0
null
null
null
null
UTF-8
Python
false
false
131
py
# -*- coding: utf-8 -*- i = 0 while i <= 2: for x in range(3): print("I={:g} J={:g}" .format(i, x+1+i)) i += 0.2
865ae8442eadb66eb5b33a7c998542e89eb501ce
c1aac38b1ee7bf7b8621050bd4837a60744bfd9f
/ay_hw_4/main_test.py
2b487bd9621a3f4e1763f4d5ad1fd4560b536838
[]
no_license
callmeorangecat/INF_552
3b0a007a37963fcd57396dab96d3f17ee20b0eb6
cdcaf20e549bfa2d5942f91f2ce3b4a93d1beba9
refs/heads/master
2021-02-17T15:04:32.222974
2020-02-21T20:31:54
2020-02-21T20:31:54
245,105,595
0
1
null
2020-03-05T08:16:29
2020-03-05T08:16:28
null
UTF-8
Python
false
false
1,999
py
# __author__ = 'Aaron Yang' __email__ = '[email protected]' __date__ = '9/27/2019 11:13 PM' import numpy as np import matplotlib.pyplot as plt from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split if __name__ == "__main__": x = np.random.uniform(-3, 3, size=100) X = x.reshape(-1, 1) # assume the relationship between X and Y is linear y = 0.5X + 3 + ε y = 3 + 0.5 * x + np.random.normal(0, 0.5, 100) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=2333) print(X_train.shape) # Since the formula of MSE is 1 /n * (∑((y_hat - y_true)^2)) and RSS is ∑((y_hat - y_true)^2) # so MSE = 1 / n * (RSS), we can use MSE to evaluate our algorithm for convenience # get MSE(RSS) fpr the linear regression lin_reg = LinearRegression() lin_reg.fit(X_train, y_train) lin_p1 = lin_reg.predict(X_train) lin_p2 = lin_reg.predict(X_test) # get MSE(RSS) for the cubic regression cubic_reg = Pipeline([("polynomial_features", PolynomialFeatures(degree=3)), ("linear_regression", LinearRegression())]) cubic_reg.fit(X_train, y_train) cub_p1 = cubic_reg.predict(X_train) cub_p2 = cubic_reg.predict(X_test) # plot figures plt.scatter(x, y) plt.plot(X_train.tolist(), lin_p1, color='r', label="linear Train") plt.scatter(X_train.tolist(), cub_p1.tolist(), color='g', label="cubic Train") # plt.plot(X_test.tolist(), y_p1, color='r', label="linear Test") # plt.plot(X_test.tolist(), y_p2, color='g', label="cubic Test") plt.legend() print("MSE for linear regression: ", mean_squared_error(y_train, lin_p1)) print("MSE for cubic regression: ", mean_squared_error(y_train, cub_p1)) print("------------------") print("MSE for linear regression: ", mean_squared_error(y_test, lin_p2)) print("MSE for cubic regression: ", mean_squared_error(y_test, cub_p2)) plt.show()
e58bbef1e15f9f5ad7ab00b1d2269ab475394474
726d164e2dcf0c13beacf5ac23db1f76e34645f1
/src/scripts/mcce/count_conf.py
a84c651e305eb12a71987d33c9e42616df9aab6f
[]
no_license
zxiaoyao/br_pscript
57bde5940d0d18704052f705c2025e4ba73e1b29
a3023b33a4332d0d77389f1d64c5af1b19a80a95
refs/heads/master
2020-06-01T13:39:39.192776
2015-06-09T04:26:39
2015-06-09T04:26:39
16,268,020
0
0
null
null
null
null
UTF-8
Python
false
false
849
py
#!/usr/bin/python def count_conf(): '''Count the number of conformers in step2_out.pdb." Assuming the atoms in a conformer are in consecutive lines in step2_out.pdb. ''' atoms = open("step2_out.pdb").readlines() for line in atoms: if line[:6] != 'ATOM ' and line[:6] != 'HETATM': continue if line[27:30] == '000': continue confid_old = line[21:30] break count = 0 for line in atoms: if line[:6] != 'ATOM ' and line[:6] != 'HETATM': continue if line[27:30] == '000': continue confid_new = line[21:30] if confid_new == confid_old: continue else: count = count + 1 confid_old = confid_new count = count + 1 return count if __name__ == "__main__": counter = count_conf() print 'there are ', counter, 'confermers'
d966c7c4b7e38e02139b6160072dee1765279666
beaae5a6429c688923404fa86a546cad1fbeb34d
/cumulusci/salesforce_api/tests/test_metadata.py
164db8d2a3060dab47c7e16cfe5ac6b3e54d8ad2
[]
permissive
justindonnaruma/CumulusCI
ae71c386b48ebead6ac32d10958a8adb3e37a9c9
cc097c1f6f102a104f83ad9a9684af9d6bc0af31
refs/heads/master
2022-07-22T03:35:40.064602
2018-07-30T13:24:11
2018-07-30T13:24:11
142,879,837
0
0
BSD-3-Clause
2022-07-06T20:48:29
2018-07-30T13:32:23
Python
UTF-8
Python
false
false
31,584
py
import ast import httplib import os import shutil import tempfile import unittest import urllib from xml.dom.minidom import parseString import requests import responses from nose.tools import raises from cumulusci.tests.util import create_project_config from cumulusci.tests.util import DummyOrgConfig from cumulusci.core.config import TaskConfig from cumulusci.core.tasks import BaseTask from cumulusci.salesforce_api.exceptions import MetadataApiError from cumulusci.salesforce_api.metadata import BaseMetadataApiCall from cumulusci.salesforce_api.metadata import ApiDeploy from cumulusci.salesforce_api.metadata import ApiListMetadata from cumulusci.salesforce_api.metadata import ApiRetrieveUnpackaged from cumulusci.salesforce_api.metadata import ApiRetrieveInstalledPackages from cumulusci.salesforce_api.metadata import ApiRetrievePackaged from cumulusci.salesforce_api.package_zip import BasePackageZipBuilder from cumulusci.salesforce_api.package_zip import CreatePackageZipBuilder from cumulusci.salesforce_api.package_zip import InstallPackageZipBuilder from cumulusci.salesforce_api.tests.metadata_test_strings import deploy_status_envelope from cumulusci.salesforce_api.tests.metadata_test_strings import deploy_result from cumulusci.salesforce_api.tests.metadata_test_strings import list_metadata_start_envelope from cumulusci.salesforce_api.tests.metadata_test_strings import retrieve_packaged_start_envelope from cumulusci.salesforce_api.tests.metadata_test_strings import retrieve_unpackaged_start_envelope from cumulusci.salesforce_api.tests.metadata_test_strings import retrieve_result from cumulusci.salesforce_api.tests.metadata_test_strings import result_envelope from cumulusci.salesforce_api.tests.metadata_test_strings import status_envelope class DummyResponse(object): pass class DummyPackageZipBuilder(BasePackageZipBuilder): def _populate_zip(self): return class BaseTestMetadataApi(unittest.TestCase): api_class = BaseMetadataApiCall envelope_start = None envelope_status = status_envelope envelope_result = result_envelope def setUp(self): # Set up the mock values self.repo_name = 'TestRepo' self.repo_owner = 'TestOwner' self.repo_api_url = 'https://api.github.com/repos/{}/{}'.format( self.repo_owner, self.repo_name, ) self.branch = 'master' # Create the project config self.project_config = create_project_config( self.repo_name, self.repo_owner, ) if not self.envelope_start: self.envelope_start = self.api_class.soap_envelope_start def _create_task(self, task_config=None, org_config=None): if not task_config: task_config = {} if not org_config: org_config = {} task = BaseTask( project_config = self.project_config, task_config = TaskConfig(task_config), org_config = DummyOrgConfig(org_config), ) return task def _mock_call_mdapi(self, api, response, status_code=None): if not status_code: status_code = 200 responses.add( method=responses.POST, url=api._build_endpoint_url(), body=response, status=status_code, content_type='text/xml; charset=utf-8', ) return response def _create_instance(self, task, api_version=None): return self.api_class( task, api_version = api_version, ) def test_init(self): task = self._create_task() api = self._create_instance(task) self.assertEquals(api.task, task) self.assertEquals(api.api_version, self.project_config.project__package__api_version) def test_build_endpoint_url(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', } task = self._create_task(org_config=org_config) api = self._create_instance(task) self.assertEquals( api._build_endpoint_url(), '{}/services/Soap/m/{}/{}'.format( org_config['instance_url'], self.project_config.project__package__api_version, task.org_config.org_id, ) ) def test_build_endpoint_url_mydomain(self): org_config = { 'instance_url': 'https://test-org.na12.my.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', } task = self._create_task(org_config=org_config) api = self._create_instance(task) self.assertEquals( api._build_endpoint_url(), 'https://na12.salesforce.com/services/Soap/m/{}/{}'.format( self.project_config.project__package__api_version, task.org_config.org_id, ) ) def test_build_endpoint_url_apiversion(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', } task = self._create_task(org_config=org_config) api_version = "42.0" api = self._create_instance(task, api_version=api_version) self.assertEquals( api._build_endpoint_url(), '{}/services/Soap/m/{}/{}'.format( org_config['instance_url'], api_version, task.org_config.org_id, ) ) def test_build_envelope_result(self): task = self._create_task() api = self._create_instance(task) if not self.api_class.soap_envelope_result: api.soap_envelope_result = '{process_id}' expected_response = '123' else: expected_response = self.envelope_result.format( process_id = '123' ) api.process_id = '123' self.assertEquals( api._build_envelope_result(), expected_response, ) def test_build_envelope_start(self): task = self._create_task() api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' expected_response = str(self.project_config.project__package__api_version) else: expected_response = self._expected_envelope_start() self.assertEquals( api._build_envelope_start(), expected_response, ) def _expected_envelope_start(self): return self.envelope_start.format( api_version = self.project_config.project__package__api_version ) def test_build_envelope_status(self): task = self._create_task() api = self._create_instance(task) process_id = '123' if not self.api_class.soap_envelope_status: api.soap_envelope_status = '{process_id}' expected_response = process_id else: expected_response = self.envelope_status.format( process_id = process_id, ) api.process_id = process_id self.assertEquals( api._build_envelope_status(), expected_response, ) def test_build_headers(self): action = 'foo' message = '12345678' task = self._create_task() api = self._create_instance(task) self.assertEquals( api._build_headers(action, message), { u'Content-Type': u'text/xml; charset=UTF-8', u'Content-Length': '8', u'SOAPAction': u'foo', } ) @responses.activate @raises(MetadataApiError) def test_call_faultcode(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' response = '<?xml version="1.0" encoding="UTF-8"?><faultcode>foo</faultcode>' self._mock_call_mdapi(api, response) resp = api() @responses.activate def test_call_success(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } status_code = httplib.INTERNAL_SERVER_ERROR # HTTP Error 500 task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' if not self.api_class.soap_envelope_status: api.soap_envelope_status = '{process_id}' if not self.api_class.soap_envelope_result: api.soap_envelope_result = '{process_id}' response = '<?xml version="1.0" encoding="UTF-8"?><id>1234567890</id>' self._mock_call_mdapi(api, response) response_status = '<?xml version="1.0" encoding="UTF-8"?><done>true</done>' self._mock_call_mdapi(api, response_status) response_result = '<?xml version="1.0" encoding="UTF-8"?><foo>bar</foo>' response_result = self._response_call_success_result(response_result) self._mock_call_mdapi(api, response_result) resp = api() self.assertEquals( resp, self._expected_call_success_result(response_result), ) def _expected_call_success_result(self, response_result): return response_result def _response_call_success_result(self, response_result): return response_result def test_get_element_value(self): task = self._create_task() api = self._create_instance(task) dom = parseString('<foo>bar</foo>') self.assertEquals( api._get_element_value(dom, 'foo'), 'bar', ) def test_get_element_value_not_found(self): task = self._create_task() api = self._create_instance(task) dom = parseString('<foo>bar</foo>') self.assertEquals( api._get_element_value(dom, 'baz'), None, ) def test_get_element_value_empty(self): task = self._create_task() api = self._create_instance(task) dom = parseString('<foo />') self.assertEquals( api._get_element_value(dom, 'foo'), None, ) def test_get_check_interval(self): task = self._create_task() api = self._create_instance(task) api.check_num = 1 self.assertEquals( api._get_check_interval(), 1, ) api.check_num = 10 self.assertEquals( api._get_check_interval(), 4, ) @responses.activate @raises(MetadataApiError) def test_get_response_faultcode(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' response = '<?xml version="1.0" encoding="UTF-8"?><faultcode>foo</faultcode>' self._mock_call_mdapi(api, response) resp = api._get_response() @responses.activate @raises(MetadataApiError) def test_get_response_faultcode_and_string(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' response = '<?xml version="1.0" encoding="UTF-8"?>' response += '\n<test>' response += '\n <faultcode>foo</faultcode>' response += '\n <faultstring>bar</faultstring>' response += '\n</test>' self._mock_call_mdapi(api, response) resp = api._get_response() @responses.activate @raises(MetadataApiError) def test_get_response_faultcode_invalid_session_no_refresh(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' response = '<?xml version="1.0" encoding="UTF-8"?><faultcode>sf:INVALID_SESSION_ID</faultcode>' self._mock_call_mdapi(api, response) resp = api._get_response() self.assertEquals( api.status, 'Failed', ) @responses.activate def test_get_response_faultcode_invalid_session_refresh(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', 'refresh_token': 'abcdefghij', } task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' if not self.api_class.soap_envelope_status: api.soap_envelope_status = '{process_id}' mock_responses = [] mock_responses.append( '<?xml version="1.0" encoding="UTF-8"?><id>123</id>' ) mock_responses.append( '<?xml version="1.0" encoding="UTF-8"?><faultcode>sf:INVALID_SESSION_ID</faultcode>' ) mock_responses.append( '<?xml version="1.0" encoding="UTF-8"?><foo>bar</foo>' ) for response in mock_responses: self._mock_call_mdapi(api, response) resp = api._get_response() self.assertEquals( resp.content, mock_responses[2], ) @responses.activate @raises(MetadataApiError) def test_get_response_start_error_500(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } status_code = httplib.INTERNAL_SERVER_ERROR # HTTP Error 500 task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' if not self.api_class.soap_envelope_status: api.soap_envelope_status = '{process_id}' response = '<?xml version="1.0" encoding="UTF-8"?><foo>start</foo>' self._mock_call_mdapi(api, response, status_code) resp = api._get_response() @responses.activate @raises(MetadataApiError) def test_get_response_status_error_500(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } status_code = httplib.INTERNAL_SERVER_ERROR # HTTP Error 500 task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' if not self.api_class.soap_envelope_status: api.soap_envelope_status = '{process_id}' response = '<?xml version="1.0" encoding="UTF-8"?><id>1234567890</id>' self._mock_call_mdapi(api, response) response_status = '<?xml version="1.0" encoding="UTF-8"?><foo>status</foo>' self._mock_call_mdapi(api, response, status_code) resp = api._get_response() @responses.activate @raises(MetadataApiError) def test_get_response_status_error_500(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } status_code = httplib.INTERNAL_SERVER_ERROR # HTTP Error 500 task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' if not self.api_class.soap_envelope_status: api.soap_envelope_status = '{process_id}' response = '<?xml version="1.0" encoding="UTF-8"?><id>1234567890</id>' self._mock_call_mdapi(api, response) response_status = '<?xml version="1.0" encoding="UTF-8"?><foo>status</foo>' self._mock_call_mdapi(api, response, status_code) resp = api._get_response() @responses.activate def test_get_response_status_no_loop(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } status_code = httplib.INTERNAL_SERVER_ERROR # HTTP Error 500 task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' if not self.api_class.soap_envelope_status: api.soap_envelope_status = '{process_id}' if not self.api_class.soap_envelope_result: api.soap_envelope_result = '{process_id}' response = '<?xml version="1.0" encoding="UTF-8"?><id>1234567890</id>' self._mock_call_mdapi(api, response) response_status = '<?xml version="1.0" encoding="UTF-8"?><done>true</done>' self._mock_call_mdapi(api, response_status) response_result = '<?xml version="1.0" encoding="UTF-8"?><foo>bar</foo>' self._mock_call_mdapi(api, response_result) resp = api._get_response() self.assertEquals( resp.content, response_result, ) @responses.activate def test_get_response_status_loop_twice(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } status_code = httplib.INTERNAL_SERVER_ERROR # HTTP Error 500 task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' if not self.api_class.soap_envelope_status: api.soap_envelope_status = '{process_id}' if not self.api_class.soap_envelope_result: api.soap_envelope_result = '{process_id}' api.check_interval = 0 response = '<?xml version="1.0" encoding="UTF-8"?><id>1234567890</id>' self._mock_call_mdapi(api, response) response_status = '<?xml version="1.0" encoding="UTF-8"?><done>false</done>' self._mock_call_mdapi(api, response_status) response_status = '<?xml version="1.0" encoding="UTF-8"?><done>false</done>' self._mock_call_mdapi(api, response_status) response_status = '<?xml version="1.0" encoding="UTF-8"?><done>true</done>' self._mock_call_mdapi(api, response_status) response_result = '<?xml version="1.0" encoding="UTF-8"?><foo>bar</foo>' self._mock_call_mdapi(api, response_result) resp = api._get_response() self.assertEquals( resp.content, response_result, ) self.assertEquals( api.status, 'Done', ) self.assertEquals( api.check_num, 4, ) def test_process_response_status_no_done_element(self): task = self._create_task() api = self._create_instance(task) response = DummyResponse() response.status_code = 200 response.content = '<?xml version="1.0" encoding="UTF-8"?><foo>status</foo>' res = api._process_response_status(response) self.assertEquals( api.status, 'Failed', ) self.assertEquals( res.content, response.content, ) def test_process_response_status_done_is_true(self): task = self._create_task() api = self._create_instance(task) response = DummyResponse() response.status_code = 200 response.content = '<?xml version="1.0" encoding="UTF-8"?><done>true</done>' res = api._process_response_status(response) self.assertEquals( api.status, 'Done', ) self.assertEquals( res.content, response.content, ) def test_process_response_status_pending(self): task = self._create_task() api = self._create_instance(task) response = DummyResponse() response.status_code = 200 response.content = '<?xml version="1.0" encoding="UTF-8"?><done>false</done>' res = api._process_response_status(response) self.assertEquals( api.status, 'Pending', ) self.assertEquals( res.content, response.content, ) def test_process_response_status_in_progress(self): task = self._create_task() api = self._create_instance(task) response = DummyResponse() response.status_code = 200 response.content = '<?xml version="1.0" encoding="UTF-8"?><done>false</done>' api.status = 'InProgress' res = api._process_response_status(response) self.assertEquals( api.status, 'InProgress', ) self.assertEquals( res.content, response.content, ) def test_process_response_status_in_progress_state_detail(self): task = self._create_task() api = self._create_instance(task) response = DummyResponse() response.status_code = 200 response.content = '<?xml version="1.0" encoding="UTF-8"?><test><done>false</done><stateDetail>Deploy log goes here</stateDetail></test>' api.status = 'InProgress' res = api._process_response_status(response) self.assertEquals( api.status, 'InProgress', ) self.assertEquals( res.content, response.content, ) class TestBaseMetadataApiCall(BaseTestMetadataApi): def test_build_envelope_start_no_envelope(self): task = self._create_task() api = self._create_instance(task) self.assertEquals( api._build_envelope_start(), None, ) def test_build_envelope_status_no_envelope(self): task = self._create_task() api = self._create_instance(task) self.assertEquals( api._build_envelope_status(), None, ) def test_build_envelope_result_no_envelope(self): task = self._create_task() api = self._create_instance(task) self.assertEquals( api._build_envelope_result(), None, ) @raises(NotImplementedError) def test_get_response_no_start_env(self): task = self._create_task() api = self._create_instance(task) api._get_response() @responses.activate def test_get_response_no_status(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } task = self._create_task(org_config=org_config) api = self._create_instance(task) api.soap_envelope_start = '{api_version}' response = '<?xml version="1.0" encoding="UTF-8"?><foo />' self._mock_call_mdapi(api, response) resp = api._get_response() self.assertEquals( resp.content, response ) class TestApiDeploy(BaseTestMetadataApi): api_class = ApiDeploy envelope_status = deploy_status_envelope def setUp(self): super(TestApiDeploy, self).setUp() self.package_zip = DummyPackageZipBuilder()() def _expected_envelope_start(self): return self.envelope_start.format( package_zip = self.package_zip, purge_on_delete = 'true', ) def _response_call_success_result(self, response_result): return deploy_result.format( status = 'Succeeded', extra = '', ) def _expected_call_success_result(self, response_result): return 'Success' def _create_instance(self, task, api_version=None, purge_on_delete=None): return self.api_class( task, self.package_zip, api_version = api_version, ) class TestApiListMetadata(BaseTestMetadataApi): api_class = ApiListMetadata envelope_start = list_metadata_start_envelope def setUp(self): super(TestApiListMetadata, self).setUp() self.metadata_type = 'CustomObject' self.metadata = None self.folder = None self.api_version = self.project_config.project__package__api_version def _expected_call_success_result(self, result_response): return {'CustomObject': []} def _create_instance(self, task, api_version=None): if api_version is None: api_version = self.api_version return self.api_class( task, metadata_type = self.metadata_type, metadata = self.metadata, folder = self.folder, as_of_version = api_version, ) class TestApiRetrieveUnpackaged(BaseTestMetadataApi): api_class = ApiRetrieveUnpackaged envelope_start = retrieve_unpackaged_start_envelope def setUp(self): super(TestApiRetrieveUnpackaged, self).setUp() self.package_xml = """<?xml version="1.0" encoding="UTF-8"?> <Package xmlns="http://soap.sforce.com/2006/04/metadata"> <version>41.0</version> </Package>""" self.result_zip = DummyPackageZipBuilder() def _response_call_success_result(self, response_result): return retrieve_result.format(zip = self.result_zip(), extra = '') def _expected_call_success_result(self, response_result): return self.result_zip.zip def _create_instance(self, task, api_version=None): return self.api_class( task, self.package_xml, api_version = api_version, ) @responses.activate def test_call_success(self): org_config = { 'instance_url': 'https://na12.salesforce.com', 'id': 'https://login.salesforce.com/id/00D000000000000ABC/005000000000000ABC', 'access_token': '0123456789', } status_code = httplib.INTERNAL_SERVER_ERROR # HTTP Error 500 task = self._create_task(org_config=org_config) api = self._create_instance(task) if not self.api_class.soap_envelope_start: api.soap_envelope_start = '{api_version}' if not self.api_class.soap_envelope_status: api.soap_envelope_status = '{process_id}' if not self.api_class.soap_envelope_result: api.soap_envelope_result = '{process_id}' response = '<?xml version="1.0" encoding="UTF-8"?><id>1234567890</id>' self._mock_call_mdapi(api, response) response_status = '<?xml version="1.0" encoding="UTF-8"?><done>true</done>' self._mock_call_mdapi(api, response_status) response_result = '<?xml version="1.0" encoding="UTF-8"?><foo>bar</foo>' response_result = self._response_call_success_result(response_result) self._mock_call_mdapi(api, response_result) zip_file = api() self.assertEquals( zip_file.namelist(), self._expected_call_success_result(response_result).namelist(), ) class TestApiRetrieveInstalledPackages(BaseTestMetadataApi): api_class = ApiRetrieveInstalledPackages def _create_instance(self, task, api_version=None): api = self.api_class( task, ) return api def _expected_call_success_result(self, result_response): return {} def test_process_response_no_zipstr(self): task = self._create_task() api = self._create_instance(task) response = DummyResponse response.status_code = 200 response.content = deploy_result.format( status = 'testing', extra = '', ) resp = api._process_response(response) self.assertEquals( resp, {}, ) def _process_response_zipstr_no_packages(self): task = self._create_task() api = self._create_instance(task) response = DummyResponse response.status_code = 200 response.content = deploy_result.format( zip = CreatePackageZipBuilder('testing'), extra = '', ) resp = api._process_response(response) self.assertEquals( resp, {}, ) def _process_response_zipstr_one_package(self): task = self._create_task() api = self._create_instance(task) response = DummyResponse response.status_code = 200 response.content = deploy_result.format( zip = InstallPackageZipBuilder('foo', '1.1'), extra = '', ) resp = api._process_response(response) self.assertEquals( resp, {'foo': '1.1'}, ) class TestApiRetrievePackaged(TestApiRetrieveUnpackaged): api_class = ApiRetrievePackaged envelope_start = retrieve_packaged_start_envelope def setUp(self): super(TestApiRetrievePackaged, self).setUp() self.package_name = 'Test Package' def _expected_envelope_start(self): return self.envelope_start.format( api_version = self.project_config.project__package__api_version, package_name = self.package_name, ) def _create_instance(self, task, api_version=None): return self.api_class( task, self.package_name, api_version, )
7ee3973c5a0010f5130adefd271d210b00f5b470
4a9035a8c74fa3d12b6717d94dbb2fa9727e4d29
/doc/LectureNotes/_build/jupyter_execute/chapter6.py
a03e1b223398711946ad19d2a175bf99719bac26
[ "CC0-1.0" ]
permissive
smithis7/Physics321
6f877fc89f6a99a8bea1022551e6e878e9902881
406297c2a87b10557075435e38e8cb7f38088229
refs/heads/master
2023-04-11T12:38:26.201740
2021-04-23T20:53:16
2021-04-23T20:53:16
331,421,603
0
0
CC0-1.0
2021-04-23T20:53:16
2021-01-20T20:19:36
HTML
UTF-8
Python
false
false
130,666
py
# Two-body problems, from the Gravitational Force to Two-body Scattering ## Introduction and Definitions Central forces are forces which are directed towards or away from a reference point. A familiar force is the gravitional force with the motion of our Earth around the Sun as a classic. The Sun, being approximately sixth order of magnitude heavier than the Earth serves as our origin. A force like the gravitational force is a function of the relative distance $\boldsymbol{r}=\boldsymbol{r}_1-\boldsymbol{r}_2$ only, where $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ are the positions relative to a defined origin for object one and object two, respectively. These forces depend on the spatial degrees of freedom only (the positions of the interacting objects/particles). As discussed earlier, from such forces we can infer that the total internal energy, the total linear momentum and total angular momentum are so-called constants of the motion, that is they stay constant over time. We say that energy, linear and anuglar momentum are conserved. With a scalar potential $V(\boldsymbol{r})$ we define the force as the gradient of the potential $$ \boldsymbol{F}(\boldsymbol{r})=-\boldsymbol{\nabla}V(\boldsymbol{r}). $$ In general these potentials depend only on the magnitude of the relative position and we will write the potential as $V(r)$ where $r$ is defined as, $$ r = |\boldsymbol{r}_1-\boldsymbol{r}_2|. $$ In three dimensions our vectors are defined as (for a given object/particle $i$) $$ \boldsymbol{r}_i = x_i\boldsymbol{e}_1+y_i\boldsymbol{e}_2+z_i\boldsymbol{e}_3, $$ while in two dimensions we have $$ \boldsymbol{r}_i = x_i\boldsymbol{e}_1+y_i\boldsymbol{e}_2. $$ In two dimensions the radius $r$ is defined as $$ r = |\boldsymbol{r}_1-\boldsymbol{r}_2|=\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}. $$ If we consider the gravitational potential involving two masses $1$ and $2$, we have $$ V_{12}(r)=V(r)=-\frac{Gm_1m_2}{|\boldsymbol{r}_1-\boldsymbol{r}_2|}=-\frac{Gm_1m_2}{r}. $$ Calculating the gradient of this potential we obtain the force $$ \boldsymbol{F}(\boldsymbol{r})=-\frac{Gm_1m_2}{|\boldsymbol{r}_1-\boldsymbol{r}_1|^2}\hat{\boldsymbol{r}}_{12}=-\frac{Gm_am_b}{r^2}\hat{\boldsymbol{r}}, $$ where we have the unit vector $$ \hat{\boldsymbol{r}}=\hat{\boldsymbol{r}}_{12}=\frac{\boldsymbol{r}_2-\boldsymbol{r}_1}{|\boldsymbol{r}_1-\boldsymbol{r}_2|}. $$ Here $G=6.67\times 10^{-11}$ Nm$^2$/kg$^2$, and $\boldsymbol{F}$ is the force on $2$ due to $1$. By inspection, one can see that the force on $2$ due to $1$ and the force on $1$ due to $2$ are equal and opposite. The net potential energy for a large number of masses would be $$ V=\sum_{i<j}V_{ij}=\frac{1}{2}\sum_{i\ne j}V_{ij}. $$ In general, the central forces that we will study can be written mathematically as $$ \boldsymbol{F}(\boldsymbol{r})=f(r)\hat{r}, $$ where $f(r)$ is a scalar function. For the above gravitational force this scalar term is $-Gm_1m_2/r^2$. In general we will simply write this scalar function $f(r)=\alpha/r^2$ where $\alpha$ is a constant that can be either negative or positive. We will also see examples of other types of potentials in the examples below. Besides general expressions for the potentials/forces, we will discuss in detail different types of motion that arise, from circular to elliptical or hyperbolic or parabolic. By transforming to either polar coordinates or spherical coordinates, we will be able to obtain analytical solutions for the equations of motion and thereby obtain new insights about the properties of a system. Where possible, we will compare our analytical equations with numerical studies. However, before we arrive at these lovely insights, we need to introduce some mathematical manipulations and definitions. We conclude this chapter with a discussion of two-body scattering. ## Center of Mass and Relative Coordinates Thus far, we have considered the trajectory as if the force is centered around a fixed point. For two bodies interacting only with one another, both masses circulate around the center of mass. One might think that solutions would become more complex when both particles move, but we will see here that the problem can be reduced to one with a single body moving according to a fixed force by expressing the trajectories for $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ into the center-of-mass coordinate $\boldsymbol{R}$ and the relative coordinate $\boldsymbol{r}$. We define the center-of-mass (CoM) coordinate as $$ \boldsymbol{R}\equiv\frac{m_1\boldsymbol{r}_1+m_2\boldsymbol{r}_2}{m_1+m_2}, $$ and the relative coordinate as $$ \boldsymbol{r}\equiv\boldsymbol{r}_1-\boldsymbol{r_2}. $$ We can then rewrite $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ in terms of the relative and CoM coordinates as $$ \boldsymbol{r}_1=\boldsymbol{R}+\frac{m_2}{M}\boldsymbol{r}, $$ and $$ \boldsymbol{r}_2=\boldsymbol{R}-\frac{m_1}{M}\boldsymbol{r}. $$ ### Conservation of total Linear Momentum In our discussions on conservative forces we defined the total linear momentum as $$ \boldsymbol{P}=\sum_{i=1}^Nm_i\frac{d\boldsymbol{r}_i}{dt}, $$ where $N=2$ in our case. With the above definition of the center of mass position, we see that we can rewrite the total linear momentum as (multiplying the CoM coordinate with $M$) $$ \boldsymbol{P}=M\frac{d\boldsymbol{R}}{dt}=M\dot{\boldsymbol{R}}. $$ The net force acting on the system is given by the time derivative of the linear momentum (assuming mass is time independent) and we have $$ \boldsymbol{F}^{\mathrm{net}}=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}}. $$ The net force acting on the system is given by the sum of the forces acting on the two bodies, that is we have $$ \boldsymbol{F}^{\mathrm{net}}=\boldsymbol{F}_1+\boldsymbol{F}_2=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}}. $$ In our case the forces are given by the internal forces only. The force acting on object $1$ is thus $\boldsymbol{F}_{12}$ and the one acting on object $2$ is $\boldsymbol{F}_{12}$. We have also defined that $\boldsymbol{F}_{12}=-\boldsymbol{F}_{21}$. This means thar we have $$ \boldsymbol{F}_1+\boldsymbol{F}_2=\boldsymbol{F}_{12}+\boldsymbol{F}_{21}=0=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}}. $$ We could alternatively had write this $$ \ddot{\boldsymbol{R}}_{\rm cm}=\frac{1}{m_1+m_2}\left\{m_1\ddot{\boldsymbol{r}}_1+m_2\ddot{\boldsymbol{r}}_2\right\}=\frac{1}{m_1+m_2}\left\{\boldsymbol{F}_{12}+\boldsymbol{F}_{21}\right\}=0. $$ This has the important consequence that the CoM velocity is a constant of the motion. And since the total linear momentum is given by the time-derivative of the CoM coordinate times the total mass $M=m_1+m_2$, it means that linear momentum is also conserved. Stated differently, the center-of-mass coordinate $\boldsymbol{R}$ moves at a fixed velocity. This has also another important consequence for our forces. If we assume that our force depends only on the relative coordinate, it means that the gradient of the potential with respect to the center of mass position is zero, that is $$ M\ddot{d\boldsymbol{R}}=-\boldsymbol{\nabla}_{\boldsymbol{R}}V =0! $$ If we now switch to the equation of motion for the relative coordinate, we have $$ \ddot{\boldsymbol{r}}=\ddot{\boldsymbol{r}}_1-\ddot{\boldsymbol{r}}_2=\left(\frac{\boldsymbol{F}_{12}}{m_1}-\frac{\boldsymbol{F}_{21}}{m_2}\right)=\left(\frac{1}{m_1}+\frac{1}{m_2}\right)\boldsymbol{F}_{12}, $$ which we can rewrite in terms of the reduced mass $$ \mu=\frac{m_1m_2}{m_1+m_2}, $$ as $$ \mu \ddot{\boldsymbol{r}}=\boldsymbol{F}_{12}. $$ This has a very important consequence for our coming analysis of the equations of motion for the two-body problem. Since the acceleration for the CoM coordinate is zero, we can now treat the trajectory as a one-body problem where the mass is given by the reduced mass $\mu$ plus a second trivial problem for the center of mass. The reduced mass is especially convenient when one is considering forces that depend only on the relative coordinate (like the Gravitational force or the electrostatic force between two charges) because then for say the gravitational force we have $$ \mu \ddot{\boldsymbol{r}}=-\frac{Gm_1m_2}{r^2}\hat{\boldsymbol{r}}=-\frac{GM\mu}{r^2}\hat{\boldsymbol{r}}, $$ where we have defined $M= m_1+m_2$. It means that the acceleration of the relative coordinate is $$ \ddot{\boldsymbol{r}}=-\frac{GM}{r^2}\hat{\boldsymbol{r}}, $$ and we have that for the gravitational problem, the reduced mass then falls out and the trajectory depends only on the total mass $M$. The standard strategy is to transform into the center of mass frame, then treat the problem as one of a single particle of mass $\mu$ undergoing a force $\boldsymbol{F}_{12}$. Scattering angles, see our discussion of scattering problems below, can also be expressed in this frame. Before we proceed to our definition of the CoM frame we need to set up the expression for the energy in terms of the relative and CoM coordinates. ### Kinetic and total Energy The kinetic energy and momenta also have analogues in center-of-mass coordinates. We have defined the total linear momentum as $$ \boldsymbol{P}=\sum_{i=1}^Nm_i\frac{d\boldsymbol{r}_i}{dt}=M\dot{\boldsymbol{R}}. $$ For the relative momentum $\boldsymbol{q}$, we have that the time derivative of $\boldsymbol{r}$ is $$ \dot{\boldsymbol{r}} =\dot{\boldsymbol{r}}_1-\dot{\boldsymbol{r}}_2, $$ We know also that the momenta $\boldsymbol{p}_1=m_1\dot{\boldsymbol{r}}_1$ and $\boldsymbol{p}_2=m_2\dot{\boldsymbol{r}}_2$. Using these expressions we can rewrite $$ \dot{\boldsymbol{r}} =\frac{\boldsymbol{p}_1}{m_1}-\frac{\boldsymbol{p}_2}{m_2}, $$ which gives $$ \dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{m_1m_2}, $$ and dividing both sides with $M$ we have $$ \frac{m_1m_2}{M}\dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{M}. $$ Introducing the reduced mass $\mu=m_1m_2/M$ we have finally $$ \mu\dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{M}. $$ And $\mu\dot{\boldsymbol{r}}$ defines the relative momentum $\boldsymbol{q}=\mu\dot{\boldsymbol{r}}$. With these definitions we can then calculate the kinetic energy in terms of the relative and CoM coordinates. We have that $$ K=\frac{p_1^2}{2m_1}+\frac{p_2^2}{2m_2}, $$ and with $\boldsymbol{p}_1=m_1\dot{\boldsymbol{r}}_1$ and $\boldsymbol{p}_2=m_2\dot{\boldsymbol{r}}_2$ and using $$ \dot{\boldsymbol{r}}_1=\dot{\boldsymbol{R}}+\frac{m_2}{M}\dot{\boldsymbol{r}}, $$ and $$ \dot{\boldsymbol{r}}_2=\dot{\boldsymbol{R}}-\frac{m_1}{M}\dot{\boldsymbol{r}}, $$ we obtain after squaring the expressions for $\dot{\boldsymbol{r}}_1$ and $\dot{\boldsymbol{r}}_2$ $$ K=\frac{(m_1+m_2)\dot{\boldsymbol{R}}^2}{2}+\frac{(m_1+m_2)m_1m_2\dot{\boldsymbol{r}}^2}{2M^2}, $$ which we simplify to $$ K=\frac{\dot{\boldsymbol{P}}^2}{2M}+\frac{\mu\dot{\boldsymbol{q}}^2}{2}. $$ Below we will define a reference frame, the so-called CoM-frame, where $\boldsymbol{R}=0$. This is going to simplify our equations further. ### Conservation of Angular Momentum The angular momentum (the total one) is the sum of the individual angular momenta. In our case we have two bodies only, meaning that our angular momentum is defined as $$ \boldsymbol{L} = \boldsymbol{r}_1 \times \boldsymbol{p}_1+\boldsymbol{r}_2 \times \boldsymbol{p}_2, $$ and using that $m_1\dot{\boldsymbol{r}}_1=\boldsymbol{p}_1$ and $m_2\dot{\boldsymbol{r}}_2=\boldsymbol{p}_2$ we have $$ \boldsymbol{L} = m_1\boldsymbol{r}_1 \times \dot{\boldsymbol{r}}_1+m_2\boldsymbol{r}_2 \times \dot{\boldsymbol{r}}_2. $$ We define now the CoM-Frame where we set $\boldsymbol{R}=0$. This means that the equations for $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ in terms of the relative motion simplify and we have $$ \boldsymbol{r}_1=\frac{m_2}{M}\boldsymbol{r}, $$ and $$ \boldsymbol{r}_2=-\frac{m_1}{M}\boldsymbol{r}. $$ resulting in $$ \boldsymbol{L} = m_1 \frac{m_2}{M}\boldsymbol{r}\times\frac{m_2}{M}\boldsymbol{r} +m_2 \frac{m_1}{M}\boldsymbol{r} \times \frac{m_1}{M}\dot{\boldsymbol{r}}. $$ We see that can rewrite this equation as $$ \boldsymbol{L}=\boldsymbol{r}\times \mu\dot{\boldsymbol{r}}=\mu\boldsymbol{r}\times \dot{\boldsymbol{r}}. $$ If we now use a central force, we have that $$ \mu\dot{\boldsymbol{r}}=\boldsymbol{F}(\boldsymbol{r})=f(r)\hat{\boldsymbol{r}}, $$ and inserting this in the equation for the angular momentum we have $$ \boldsymbol{L}=\boldsymbol{r}\times f(r)\hat{\boldsymbol{r}}, $$ which equals zero since we are taking the cross product of the vector $\boldsymbol{r}$ with itself. Angular momentum is thus conserved and in addition to the total linear momentum being conserved, we know that energy is also conserved with forces that depend only on position and the relative coordinate only. Since angular momentum is conserved, we can idealize the motion of our two objects as two bodies moving in a plane spanned by the relative coordinate and the relative momentum. The angular momentum is perpendicular to the plane spanned by these two vectors. It means also, since $\boldsymbol{L}$ is conserved, that we can reduce our problem to a motion in say the $xy$-plane. What we have done then is to reduce a two-body problem in three-dimensions with six degrees of freedom (the six coordinates of the two objects) to a problem defined entirely by the relative coordinate in two dimensions. We have thus moved from a problem with six degrees of freedom to one with two degrees of freedom only. Since we deal with central forces that depend only on the relative coordinate, we will show below that transforming to polar coordinates, we cna find analytical solution to the equation of motion $$ \mu\dot{\boldsymbol{r}}=\boldsymbol{F}(\boldsymbol{r})=f(r)\hat{\boldsymbol{r}}. $$ Note the boldfaced symbols for the relative position $\boldsymbol{r}$. Our vector $\boldsymbol{r}$ is defined as $$ \boldsymbol{r}=x\boldsymbol{e}_1+y\boldsymbol{e}_2 $$ and introducing polar coordinates $r\in[0,\infty)$ and $\phi\in [0,2\pi]$ and the transformation $$ r=\sqrt{x^2+y^2}, $$ and $x=r\cos\phi$ and $y=r\sin\phi$, we will rewrite our equation of motion by transforming from Cartesian coordinates to Polar coordinates. By so doing, we end up with two differential equations which can be solved analytically (it depends on the form of the potential). What follows now is a rewrite of these equations and the introduction of Kepler's laws as well. ## Deriving Elliptical Orbits Kepler's laws state that a gravitational orbit should be an ellipse with the source of the gravitational field at one focus. Deriving this is surprisingly messy. To do this, we first use angular momentum conservation to transform the equations of motion so that it is in terms of $r$ and $\phi$ instead of $r$ and $t$. The overall strategy is to 1. Find equations of motion for $r$ and $t$ with no angle ($\phi$) mentioned, i.e. $d^2r/dt^2=\cdots$. Angular momentum conservation will be used, and the equation will involve the angular momentum $L$. 2. Use angular momentum conservation to find an expression for $\dot{\phi}$ in terms of $r$. 3. Use the chain rule to convert the equations of motions for $r$, an expression involving $r,\dot{r}$ and $\ddot{r}$, to one involving $r,dr/d\phi$ and $d^2r/d\phi^2$. This is quitecomplicated because the expressions will also involve a substitution $u=1/r$ so that one finds an expression in terms of $u$ and $\phi$. 4. Once $u(\phi)$ is found, you need to show that this can be converted to the familiar form for an ellipse. We will now rewrite the above equation of motion (note the boldfaced vector $\boldsymbol{r}$) $$ \mu \ddot{\boldsymbol{r}}=\boldsymbol{F}(\boldsymbol{r}), $$ in polar coordinates. What follows here is a repeated application of the chain rule for derivatives. We start with derivative for $r$ as function of time in a cartesian basis <!-- Equation labels as ordinary links --> <div id="eq:radialeqofmotion"></div> $$ \begin{eqnarray} \label{eq:radialeqofmotion} \tag{1} \frac{d}{dt}r^2&=&\frac{d}{dt}(x^2+y^2)=2x\dot{x}+2y\dot{y}=2r\dot{r},\\ \nonumber \dot{r}&=&\frac{x}{r}\dot{x}+\frac{y}{r}\dot{y},\\ \nonumber \ddot{r}&=&\frac{x}{r}\ddot{x}+\frac{y}{r}\ddot{y} +\frac{\dot{x}^2+\dot{y}^2}{r} -\frac{\dot{r}^2}{r}. \end{eqnarray} $$ Note that there are no vectors involved here. Recognizing that the numerator of the third term is the velocity squared, and that it can be written in polar coordinates, <!-- Equation labels as ordinary links --> <div id="_auto1"></div> $$ \begin{equation} v^2=\dot{x}^2+\dot{y}^2=\dot{r}^2+r^2\dot{\phi}^2, \label{_auto1} \tag{2} \end{equation} $$ one can write $\ddot{r}$ as <!-- Equation labels as ordinary links --> <div id="eq:radialeqofmotion2"></div> $$ \begin{equation} \label{eq:radialeqofmotion2} \tag{3} \ddot{r}=\frac{F_x\cos\phi+F_y\sin\phi}{m}+\frac{\dot{r}^2+r^2\dot{\phi}^2}{r}-\frac{\dot{r}^2}{r} \end{equation} $$ $$ \nonumber =\frac{F}{m}+\frac{r^2\dot{\phi}^2}{r} $$ <!-- Equation labels as ordinary links --> <div id="_auto2"></div> $$ \begin{equation} \label{_auto2} \tag{4} \end{equation} $$ or $$ m\ddot{r}=F+\frac{L^2}{mr^3}. $$ This derivation used the fact that the force was radial, $F=F_r=F_x\cos\phi+F_y\sin\phi$, and that angular momentum is $L=mrv_{\phi}=mr^2\dot{\phi}$. The term $L^2/mr^3=mv^2/r$ behaves like an additional force. Sometimes this is referred to as a centrifugal force, but it is not a force. Instead, it is the consequence of considering the motion in a rotating (and therefore accelerating) frame. Now, we switch to the particular case of an attractive inverse square force, $F=-\alpha/r^2$, and show that the trajectory, $r(\phi)$, is an ellipse. To do this we transform derivatives w.r.t. time to derivatives w.r.t. $\phi$ using the chain rule combined with angular momentum conservation, $\dot{\phi}=L/mr^2$. <!-- Equation labels as ordinary links --> <div id="eq:rtotheta"></div> $$ \begin{eqnarray} \label{eq:rtotheta} \tag{5} \dot{r}&=&\frac{dr}{d\phi}\dot{\phi}=\frac{dr}{d\phi}\frac{L}{mr^2},\\ \nonumber \ddot{r}&=&\frac{d^2r}{d\phi^2}\dot{\phi}^2 +\frac{dr}{d\phi}\left(\frac{d}{dr}\frac{L}{mr^2}\right)\dot{r}\\ \nonumber &=&\frac{d^2r}{d\phi^2}\left(\frac{L}{mr^2}\right)^2 -2\frac{dr}{d\phi}\frac{L}{mr^3}\dot{r}\\ \nonumber &=&\frac{d^2r}{d\phi^2}\left(\frac{L}{mr^2}\right)^2 -\frac{2}{r}\left(\frac{dr}{d\phi}\right)^2\left(\frac{L}{mr^2}\right)^2 \end{eqnarray} $$ Equating the two expressions for $\ddot{r}$ in Eq.s ([3](#eq:radialeqofmotion2)) and ([5](#eq:rtotheta)) eliminates all the derivatives w.r.t. time, and provides a differential equation with only derivatives w.r.t. $\phi$, <!-- Equation labels as ordinary links --> <div id="eq:rdotdot"></div> $$ \begin{equation} \label{eq:rdotdot} \tag{6} \frac{d^2r}{d\phi^2}\left(\frac{L}{mr^2}\right)^2 -\frac{2}{r}\left(\frac{dr}{d\phi}\right)^2\left(\frac{L}{mr^2}\right)^2 =\frac{F}{m}+\frac{L^2}{m^2r^3}, \end{equation} $$ that when solved yields the trajectory, i.e. $r(\phi)$. Up to this point the expressions work for any radial force, not just forces that fall as $1/r^2$. The trick to simplifying this differential equation for the inverse square problems is to make a substitution, $u\equiv 1/r$, and rewrite the differential equation for $u(\phi)$. $$ \begin{eqnarray} r&=&1/u,\\ \nonumber \frac{dr}{d\phi}&=&-\frac{1}{u^2}\frac{du}{d\phi},\\ \nonumber \frac{d^2r}{d\phi^2}&=&\frac{2}{u^3}\left(\frac{du}{d\phi}\right)^2-\frac{1}{u^2}\frac{d^2u}{d\phi^2}. \end{eqnarray} $$ Plugging these expressions into Eq. ([6](#eq:rdotdot)) gives an expression in terms of $u$, $du/d\phi$, and $d^2u/d\phi^2$. After some tedious algebra, <!-- Equation labels as ordinary links --> <div id="_auto3"></div> $$ \begin{equation} \frac{d^2u}{d\phi^2}=-u-\frac{F m}{L^2u^2}. \label{_auto3} \tag{7} \end{equation} $$ For the attractive inverse square law force, $F=-\alpha u^2$, <!-- Equation labels as ordinary links --> <div id="_auto4"></div> $$ \begin{equation} \frac{d^2u}{d\phi^2}=-u+\frac{m\alpha}{L^2}. \label{_auto4} \tag{8} \end{equation} $$ The solution has two arbitrary constants, $A$ and $\phi_0$, <!-- Equation labels as ordinary links --> <div id="eq:Ctrajectory"></div> $$ \begin{eqnarray} \label{eq:Ctrajectory} \tag{9} u&=&\frac{m\alpha}{L^2}+A\cos(\phi-\phi_0),\\ \nonumber r&=&\frac{1}{(m\alpha/L^2)+A\cos(\phi-\phi_0)}. \end{eqnarray} $$ The radius will be at a minimum when $\phi=\phi_0$ and at a maximum when $\phi=\phi_0+\pi$. The constant $A$ is related to the eccentricity of the orbit. When $A=0$ the radius is a constant $r=L^2/(m\alpha)$, and the motion is circular. If one solved the expression $mv^2/r=-\alpha/r^2$ for a circular orbit, using the substitution $v=L/(mr)$, one would reproduce the expression $r=L^2/(m\alpha)$. The form describing the elliptical trajectory in Eq. ([9](#eq:Ctrajectory)) can be identified as an ellipse with one focus being the center of the ellipse by considering the definition of an ellipse as being the points such that the sum of the two distances between the two foci are a constant. Making that distance $2D$, the distance between the two foci as $2a$, and putting one focus at the origin, $$ \begin{eqnarray} 2D&=&r+\sqrt{(r\cos\phi-2a)^2+r^2\sin^2\phi},\\ \nonumber 4D^2+r^2-4Dr&=&r^2+4a^2-4ar\cos\phi,\\ \nonumber r&=&\frac{D^2-a^2}{D+a\cos\phi}=\frac{1}{D/(D^2-a^2)-a\cos\phi/(D^2-a^2)}. \end{eqnarray} $$ By inspection, this is the same form as Eq. ([9](#eq:Ctrajectory)) with $D/(D^2-a^2)=m\alpha/L^2$ and $a/(D^2-a^2)=A$. Let us remind ourselves about what an ellipse is before we proceed. %matplotlib inline import numpy as np from matplotlib import pyplot as plt from math import pi u=1. #x-position of the center v=0.5 #y-position of the center a=2. #radius on the x-axis b=1.5 #radius on the y-axis t = np.linspace(0, 2*pi, 100) plt.plot( u+a*np.cos(t) , v+b*np.sin(t) ) plt.grid(color='lightgray',linestyle='--') plt.show() ## Effective or Centrifugal Potential The total energy of a particle is $$ \begin{eqnarray} E&=&V(r)+\frac{1}{2}mv_\phi^2+\frac{1}{2}m\dot{r}^2\\ \nonumber &=&V(r)+\frac{1}{2}mr^2\dot{\phi}^2+\frac{1}{2}m\dot{r}^2\\ \nonumber &=&V(r)+\frac{L^2}{2mr^2}+\frac{1}{2}m\dot{r}^2. \end{eqnarray} $$ The second term then contributes to the energy like an additional repulsive potential. The term is sometimes referred to as the "centrifugal" potential, even though it is actually the kinetic energy of the angular motion. Combined with $V(r)$, it is sometimes referred to as the "effective" potential, $$ \begin{eqnarray} V_{\rm eff}(r)&=&V(r)+\frac{L^2}{2mr^2}. \end{eqnarray} $$ Note that if one treats the effective potential like a real potential, one would expect to be able to generate an effective force, $$ \begin{eqnarray} F_{\rm eff}&=&-\frac{d}{dr}V(r) -\frac{d}{dr}\frac{L^2}{2mr^2}\\ \nonumber &=&F(r)+\frac{L^2}{mr^3}=F(r)+m\frac{v_\perp^2}{r}, \end{eqnarray} $$ which is indeed matches the form for $m\ddot{r}$ in Eq. ([3](#eq:radialeqofmotion2)), which included the **centrifugal** force. The following code plots this effective potential for a simple choice of parameters, with a standard gravitational potential $-\alpha/r$. Here we have chosen $L=m=\alpha=1$. # Common imports import numpy as np from math import * import matplotlib.pyplot as plt Deltax = 0.01 #set up arrays xinitial = 0.3 xfinal = 5.0 alpha = 1.0 # spring constant m = 1.0 # mass, you can change these AngMom = 1.0 # The angular momentum n = ceil((xfinal-xinitial)/Deltax) x = np.zeros(n) for i in range(n): x[i] = xinitial+i*Deltax V = np.zeros(n) V = -alpha/x+0.5*AngMom*AngMom/(m*x*x) # Plot potential fig, ax = plt.subplots() ax.set_xlabel('r[m]') ax.set_ylabel('V[J]') ax.plot(x, V) fig.tight_layout() plt.show() ### Gravitational force example Using the above parameters, we can now study the evolution of the system using for example the velocity Verlet method. This is done in the code here for an initial radius equal to the minimum of the potential well. We seen then that the radius is always the same and corresponds to a circle (the radius is always constant). # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt import os # Where to save the figures and data files PROJECT_ROOT_DIR = "Results" FIGURE_ID = "Results/FigureFiles" DATA_ID = "DataFiles/" if not os.path.exists(PROJECT_ROOT_DIR): os.mkdir(PROJECT_ROOT_DIR) if not os.path.exists(FIGURE_ID): os.makedirs(FIGURE_ID) if not os.path.exists(DATA_ID): os.makedirs(DATA_ID) def image_path(fig_id): return os.path.join(FIGURE_ID, fig_id) def data_path(dat_id): return os.path.join(DATA_ID, dat_id) def save_fig(fig_id): plt.savefig(image_path(fig_id) + ".png", format='png') # Simple Gravitational Force -alpha/r DeltaT = 0.01 #set up arrays tfinal = 100.0 n = ceil(tfinal/DeltaT) # set up arrays for t, v and r t = np.zeros(n) v = np.zeros(n) r = np.zeros(n) # Constants of the model, setting all variables to one for simplicity alpha = 1.0 AngMom = 1.0 # The angular momentum m = 1.0 # scale mass to one c1 = AngMom*AngMom/(m*m) c2 = AngMom*AngMom/m rmin = (AngMom*AngMom/m/alpha) # Initial conditions r0 = rmin v0 = 0.0 r[0] = r0 v[0] = v0 # Start integrating using the Velocity-Verlet method for i in range(n-1): # Set up acceleration a = -alpha/(r[i]**2)+c1/(r[i]**3) # update velocity, time and position using the Velocity-Verlet method r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a anew = -alpha/(r[i+1]**2)+c1/(r[i+1]**3) v[i+1] = v[i] + 0.5*DeltaT*(a+anew) t[i+1] = t[i] + DeltaT # Plot position as function of time fig, ax = plt.subplots(2,1) ax[0].set_xlabel('time') ax[0].set_ylabel('radius') ax[0].plot(t,r) ax[1].set_xlabel('time') ax[1].set_ylabel('Velocity') ax[1].plot(t,v) save_fig("RadialGVV") plt.show() Changing the value of the initial position to a value where the energy is positive, leads to an increasing radius with time, a so-called unbound orbit. Choosing on the other hand an initial radius that corresponds to a negative energy and different from the minimum value leads to a radius that oscillates back and forth between two values. ### Harmonic Oscillator in two dimensions Consider a particle of mass $m$ in a 2-dimensional harmonic oscillator with potential $$ V=\frac{1}{2}kr^2=\frac{1}{2}k(x^2+y^2). $$ If the orbit has angular momentum $L$, we can find the radius and angular velocity of the circular orbit as well as the b) the angular frequency of small radial perturbations. We consider the effective potential. The radius of a circular orbit is at the minimum of the potential (where the effective force is zero). The potential is plotted here with the parameters $k=m=0.1$ and $L=1.0$. # Common imports import numpy as np from math import * import matplotlib.pyplot as plt Deltax = 0.01 #set up arrays xinitial = 0.5 xfinal = 3.0 k = 1.0 # spring constant m = 1.0 # mass, you can change these AngMom = 1.0 # The angular momentum n = ceil((xfinal-xinitial)/Deltax) x = np.zeros(n) for i in range(n): x[i] = xinitial+i*Deltax V = np.zeros(n) V = 0.5*k*x*x+0.5*AngMom*AngMom/(m*x*x) # Plot potential fig, ax = plt.subplots() ax.set_xlabel('r[m]') ax.set_ylabel('V[J]') ax.plot(x, V) fig.tight_layout() plt.show() $$ \begin{eqnarray*} V_{\rm eff}&=&\frac{1}{2}kr^2+\frac{L^2}{2mr^2} \end{eqnarray*} $$ The effective potential looks like that of a harmonic oscillator for large $r$, but for small $r$, the centrifugal potential repels the particle from the origin. The combination of the two potentials has a minimum for at some radius $r_{\rm min}$. $$ \begin{eqnarray*} 0&=&kr_{\rm min}-\frac{L^2}{mr_{\rm min}^3},\\ r_{\rm min}&=&\left(\frac{L^2}{mk}\right)^{1/4},\\ \dot{\phi}&=&\frac{L}{mr_{\rm min}^2}=\sqrt{k/m}. \end{eqnarray*} $$ For particles at $r_{\rm min}$ with $\dot{r}=0$, the particle does not accelerate and $r$ stays constant, i.e. a circular orbit. The radius of the circular orbit can be adjusted by changing the angular momentum $L$. For the above parameters this minimum is at $r_{\rm min}=1$. Now consider small vibrations about $r_{\rm min}$. The effective spring constant is the curvature of the effective potential. $$ \begin{eqnarray*} k_{\rm eff}&=&\left.\frac{d^2}{dr^2}V_{\rm eff}(r)\right|_{r=r_{\rm min}}=k+\frac{3L^2}{mr_{\rm min}^4}\\ &=&4k,\\ \omega&=&\sqrt{k_{\rm eff}/m}=2\sqrt{k/m}=2\dot{\phi}. \end{eqnarray*} $$ Here, the second step used the result of the last step from part (a). Because the radius oscillates with twice the angular frequency, the orbit has two places where $r$ reaches a minimum in one cycle. This differs from the inverse-square force where there is one minimum in an orbit. One can show that the orbit for the harmonic oscillator is also elliptical, but in this case the center of the potential is at the center of the ellipse, not at one of the foci. The solution is also simple to write down exactly in Cartesian coordinates. The $x$ and $y$ equations of motion separate, $$ \begin{eqnarray*} \ddot{x}&=&-kx,\\ \ddot{y}&=&-ky. \end{eqnarray*} $$ So the general solution can be expressed as $$ \begin{eqnarray*} x&=&A\cos\omega_0 t+B\sin\omega_0 t,\\ y&=&C\cos\omega_0 t+D\sin\omega_0 t. \end{eqnarray*} $$ The code here finds the solution for $x$ and $y$ using the code we developed in homework 5 and 6 and the midterm. Note that this code is tailored to run in Cartesian coordinates. There is thus no angular momentum dependent term. DeltaT = 0.01 #set up arrays tfinal = 10.0 n = ceil(tfinal/DeltaT) # set up arrays t = np.zeros(n) v = np.zeros((n,2)) r = np.zeros((n,2)) radius = np.zeros(n) # Constants of the model k = 1.0 # spring constant m = 1.0 # mass, you can change these omega02 = sqrt(k/m) # Frequency AngMom = 1.0 # The angular momentum rmin = (AngMom*AngMom/k/m)**0.25 # Initial conditions as compact 2-dimensional arrays x0 = rmin-0.5; y0= sqrt(rmin*rmin-x0*x0) r0 = np.array([x0,y0]) v0 = np.array([0.0,0.0]) r[0] = r0 v[0] = v0 # Start integrating using the Velocity-Verlet method for i in range(n-1): # Set up the acceleration a = -r[i]*omega02 # update velocity, time and position using the Velocity-Verlet method r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a anew = -r[i+1]*omega02 v[i+1] = v[i] + 0.5*DeltaT*(a+anew) t[i+1] = t[i] + DeltaT # Plot position as function of time radius = np.sqrt(r[:,0]**2+r[:,1]**2) fig, ax = plt.subplots(3,1) ax[0].set_xlabel('time') ax[0].set_ylabel('radius squared') ax[0].plot(t,r[:,0]**2+r[:,1]**2) ax[1].set_xlabel('time') ax[1].set_ylabel('x position') ax[1].plot(t,r[:,0]) ax[2].set_xlabel('time') ax[2].set_ylabel('y position') ax[2].plot(t,r[:,1]) fig.tight_layout() save_fig("2DimHOVV") plt.show() With some work using double angle formulas, one can calculate $$ \begin{eqnarray*} r^2&=&x^2+y^2\\ \nonumber &=&(A^2+C^2)\cos^2(\omega_0t)+(B^2+D^2)\sin^2\omega_0t+(AB+CD)\cos(\omega_0t)\sin(\omega_0t)\\ \nonumber &=&\alpha+\beta\cos 2\omega_0 t+\gamma\sin 2\omega_0 t,\\ \alpha&=&\frac{A^2+B^2+C^2+D^2}{2},~~\beta=\frac{A^2-B^2+C^2-D^2}{2},~~\gamma=AB+CD,\\ r^2&=&\alpha+(\beta^2+\gamma^2)^{1/2}\cos(2\omega_0 t-\delta),~~~\delta=\arctan(\gamma/\beta), \end{eqnarray*} $$ and see that radius oscillates with frequency $2\omega_0$. The factor of two comes because the oscillation $x=A\cos\omega_0t$ has two maxima for $x^2$, one at $t=0$ and one a half period later. The following code shows first how we can solve this problem using the radial degrees of freedom only. DeltaT = 0.01 #set up arrays tfinal = 10.0 n = ceil(tfinal/DeltaT) # set up arrays for t, v and r t = np.zeros(n) v = np.zeros(n) r = np.zeros(n) E = np.zeros(n) # Constants of the model AngMom = 1.0 # The angular momentum m = 1.0 k = 1.0 omega02 = k/m c1 = AngMom*AngMom/(m*m) c2 = AngMom*AngMom/m rmin = (AngMom*AngMom/k/m)**0.25 # Initial conditions r0 = rmin v0 = 0.0 r[0] = r0 v[0] = v0 E[0] = 0.5*m*v0*v0+0.5*k*r0*r0+0.5*c2/(r0*r0) # Start integrating using the Velocity-Verlet method for i in range(n-1): # Set up acceleration a = -r[i]*omega02+c1/(r[i]**3) # update velocity, time and position using the Velocity-Verlet method r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a anew = -r[i+1]*omega02+c1/(r[i+1]**3) v[i+1] = v[i] + 0.5*DeltaT*(a+anew) t[i+1] = t[i] + DeltaT E[i+1] = 0.5*m*v[i+1]*v[i+1]+0.5*k*r[i+1]*r[i+1]+0.5*c2/(r[i+1]*r[i+1]) # Plot position as function of time fig, ax = plt.subplots(2,1) ax[0].set_xlabel('time') ax[0].set_ylabel('radius') ax[0].plot(t,r) ax[1].set_xlabel('time') ax[1].set_ylabel('Energy') ax[1].plot(t,E) save_fig("RadialHOVV") plt.show() ## Stability of Orbits The effective force can be extracted from the effective potential, $V_{\rm eff}$. Beginning from the equations of motion, Eq. ([1](#eq:radialeqofmotion)), for $r$, $$ \begin{eqnarray} m\ddot{r}&=&F+\frac{L^2}{mr^3}\\ \nonumber &=&F_{\rm eff}\\ \nonumber &=&-\partial_rV_{\rm eff},\\ \nonumber F_{\rm eff}&=&-\partial_r\left[V(r)+(L^2/2mr^2)\right]. \end{eqnarray} $$ For a circular orbit, the radius must be fixed as a function of time, so one must be at a maximum or a minimum of the effective potential. However, if one is at a maximum of the effective potential the radius will be unstable. For the attractive Coulomb force the effective potential will be dominated by the $-\alpha/r$ term for large $r$ because the centrifugal part falls off more quickly, $\sim 1/r^2$. At low $r$ the centrifugal piece wins and the effective potential is repulsive. Thus, the potential must have a minimum somewhere with negative potential. The circular orbits are then stable to perturbation. The effective potential is sketched for two cases, a $1/r$ attractive potential and a $1/r^3$ attractive potential. The $1/r$ case has a stable minimum, whereas the circular orbit in the $1/r^3$ case is unstable. If one considers a potential that falls as $1/r^3$, the situation is reversed and the point where $\partial_rV$ disappears will be a local maximum rather than a local minimum. **Fig to come here with code** The repulsive centrifugal piece dominates at large $r$ and the attractive Coulomb piece wins out at small $r$. The circular orbit is then at a maximum of the effective potential and the orbits are unstable. It is the clear that for potentials that fall as $r^n$, that one must have $n>-2$ for the orbits to be stable. Consider a potential $V(r)=\beta r$. For a particle of mass $m$ with angular momentum $L$, find the angular frequency of a circular orbit. Then find the angular frequency for small radial perturbations. For the circular orbit you search for the position $r_{\rm min}$ where the effective potential is minimized, $$ \begin{eqnarray*} \partial_r\left\{\beta r+\frac{L^2}{2mr^2}\right\}&=&0,\\ \beta&=&\frac{L^2}{mr_{\rm min}^3},\\ r_{\rm min}&=&\left(\frac{L^2}{\beta m}\right)^{1/3},\\ \dot{\phi}&=&\frac{L}{mr_{\rm min}^2}=\frac{\beta^{2/3}}{(mL)^{1/3}} \end{eqnarray*} $$ Now, we can find the angular frequency of small perturbations about the circular orbit. To do this we find the effective spring constant for the effective potential, $$ \begin{eqnarray*} k_{\rm eff}&=&\partial_r^2 \left.V_{\rm eff}\right|_{r_{\rm min}}\\ &=&\frac{3L^2}{mr_{\rm min}^4},\\ \omega&=&\sqrt{\frac{k_{\rm eff}}{m}}\\ &=&\frac{\beta^{2/3}}{(mL)^{1/3}}\sqrt{3}. \end{eqnarray*} $$ If the two frequencies, $\dot{\phi}$ and $\omega$, differ by an integer factor, the orbit's trajectory will repeat itself each time around. This is the case for the inverse-square force, $\omega=\dot{\phi}$, and for the harmonic oscillator, $\omega=2\dot{\phi}$. In this case, $\omega=\sqrt{3}\dot{\phi}$, and the angles at which the maxima and minima occur change with each orbit. ### Code example with gravitional force The code example here is meant to illustrate how we can make a plot of the final orbit. We solve the equations in polar coordinates (the example here uses the minimum of the potential as initial value) and then we transform back to cartesian coordinates and plot $x$ versus $y$. We see that we get a perfect circle when we place ourselves at the minimum of the potential energy, as expected. # Simple Gravitational Force -alpha/r DeltaT = 0.01 #set up arrays tfinal = 8.0 n = ceil(tfinal/DeltaT) # set up arrays for t, v and r t = np.zeros(n) v = np.zeros(n) r = np.zeros(n) phi = np.zeros(n) x = np.zeros(n) y = np.zeros(n) # Constants of the model, setting all variables to one for simplicity alpha = 1.0 AngMom = 1.0 # The angular momentum m = 1.0 # scale mass to one c1 = AngMom*AngMom/(m*m) c2 = AngMom*AngMom/m rmin = (AngMom*AngMom/m/alpha) # Initial conditions, place yourself at the potential min r0 = rmin v0 = 0.0 # starts at rest r[0] = r0 v[0] = v0 phi[0] = 0.0 # Start integrating using the Velocity-Verlet method for i in range(n-1): # Set up acceleration a = -alpha/(r[i]**2)+c1/(r[i]**3) # update velocity, time and position using the Velocity-Verlet method r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a anew = -alpha/(r[i+1]**2)+c1/(r[i+1]**3) v[i+1] = v[i] + 0.5*DeltaT*(a+anew) t[i+1] = t[i] + DeltaT phi[i+1] = t[i+1]*c2/(r0**2) # Find cartesian coordinates for easy plot x = r*np.cos(phi) y = r*np.sin(phi) fig, ax = plt.subplots(3,1) ax[0].set_xlabel('time') ax[0].set_ylabel('radius') ax[0].plot(t,r) ax[1].set_xlabel('time') ax[1].set_ylabel('Angle $\cos{\phi}$') ax[1].plot(t,np.cos(phi)) ax[2].set_ylabel('y') ax[2].set_xlabel('x') ax[2].plot(x,y) save_fig("Phasespace") plt.show() Try to change the initial value for $r$ and see what kind of orbits you get. In order to test different energies, it can be useful to look at the plot of the effective potential discussed above. However, for orbits different from a circle the above code would need modifications in order to allow us to display say an ellipse. For the latter, it is much easier to run our code in cartesian coordinates, as done here. In this code we test also energy conservation and see that it is conserved to numerical precision. The code here is a simple extension of the code we developed for homework 4. # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt DeltaT = 0.01 #set up arrays tfinal = 10.0 n = ceil(tfinal/DeltaT) # set up arrays t = np.zeros(n) v = np.zeros((n,2)) r = np.zeros((n,2)) E = np.zeros(n) # Constants of the model m = 1.0 # mass, you can change these alpha = 1.0 # Initial conditions as compact 2-dimensional arrays x0 = 0.5; y0= 0. r0 = np.array([x0,y0]) v0 = np.array([0.0,1.0]) r[0] = r0 v[0] = v0 rabs = sqrt(sum(r[0]*r[0])) E[0] = 0.5*m*(v[0,0]**2+v[0,1]**2)-alpha/rabs # Start integrating using the Velocity-Verlet method for i in range(n-1): # Set up the acceleration rabs = sqrt(sum(r[i]*r[i])) a = -alpha*r[i]/(rabs**3) # update velocity, time and position using the Velocity-Verlet method r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a rabs = sqrt(sum(r[i+1]*r[i+1])) anew = -alpha*r[i+1]/(rabs**3) v[i+1] = v[i] + 0.5*DeltaT*(a+anew) E[i+1] = 0.5*m*(v[i+1,0]**2+v[i+1,1]**2)-alpha/rabs t[i+1] = t[i] + DeltaT # Plot position as function of time fig, ax = plt.subplots(3,1) ax[0].set_ylabel('y') ax[0].set_xlabel('x') ax[0].plot(r[:,0],r[:,1]) ax[1].set_xlabel('time') ax[1].set_ylabel('y position') ax[1].plot(t,r[:,0]) ax[2].set_xlabel('time') ax[2].set_ylabel('y position') ax[2].plot(t,r[:,1]) fig.tight_layout() save_fig("2DimGravity") plt.show() print(E) ## Scattering and Cross Sections Scattering experiments don't measure entire trajectories. For elastic collisions, they measure the distribution of final scattering angles at best. Most experiments use targets thin enough so that the number of scatterings is typically zero or one. The cross section, $\sigma$, describes the cross-sectional area for particles to scatter with an individual target atom or nucleus. Cross section measurements form the basis for MANY fields of physics. BThe cross section, and the differential cross section, encapsulates everything measurable for a collision where all that is measured is the final state, e.g. the outgoing particle had momentum $\boldsymbol{p}_f$. y studying cross sections, one can infer information about the potential interaction between the two particles. Inferring, or constraining, the potential from the cross section is a classic {\it inverse} problem. Collisions are either elastic or inelastic. Elastic collisions are those for which the two bodies are in the same internal state before and after the collision. If the collision excites one of the participants into a higher state, or transforms the particles into different species, or creates additional particles, the collision is inelastic. Here, we consider only elastic collisions. For Coulomb forces, the cross section is infinite because the range of the Coulomb force is infinite, but for interactions such as the strong interaction in nuclear or particle physics, there is no long-range force and cross-sections are finite. Even for Coulomb forces, the part of the cross section that corresponds to a specific scattering angle, $d\sigma/d\Omega$, which is a function of the scattering angle $\phi_s$ is still finite. If a particle travels through a thin target, the chance the particle scatters is $P_{\rm scatt}=\sigma dN/dA$, where $dN/dA$ is the number of scattering centers per area the particle encounters. If the density of the target is $\rho$ particles per volume, and if the thickness of the target is $t$, the areal density (number of target scatterers per area) is $dN/dA=\rho t$. Because one wishes to quantify the collisions independently of the target, experimentalists measure scattering probabilities, then divide by the areal density to obtain cross-sections, $$ \begin{eqnarray} \sigma=\frac{P_{\rm scatt}}{dN/dA}. \end{eqnarray} $$ Instead of merely stating that a particle collided, one can measure the probability the particle scattered by a given angle. The scattering angle $\phi_s$ is defined so that at zero the particle is unscattered and at $\phi_s=\pi$ the particle is scattered directly backward. Scattering angles are often described in the center-of-mass frame, but that is a detail we will neglect for this first discussion, where we will consider the scattering of particles moving classically under the influence of fixed potentials $U(\boldsymbol{r})$. Because the distribution of scattering angles can be measured, one expresses the differential cross section, <!-- Equation labels as ordinary links --> <div id="_auto5"></div> $$ \begin{equation} \frac{d^2\sigma}{d\cos\phi_s~d\phi}. \label{_auto5} \tag{10} \end{equation} $$ Usually, the literature expresses differential cross sections as <!-- Equation labels as ordinary links --> <div id="_auto6"></div> $$ \begin{equation} d\sigma/d\Omega=\frac{d\sigma}{d\cos\phi d\phi}=\frac{1}{2\pi}\frac{d\sigma}{d\cos\phi}, \label{_auto6} \tag{11} \end{equation} $$ where the last equivalency is true when the scattering does not depend on the azimuthal angle $\phi$, as is the case for spherically symmetric potentials. The differential solid angle $d\Omega$ can be thought of as the area subtended by a measurement, $dA_d$, divided by $r^2$, where $r$ is the distance to the detector, $$ \begin{eqnarray} dA_d=r^2 d\Omega. \end{eqnarray} $$ With this definition $d\sigma/d\Omega$ is independent of the distance from which one places the detector, or the size of the detector (as long as it is small). Differential scattering cross sections are calculated by assuming a random distribution of impact parameters $b$. These represent the distance in the $xy$ plane for particles moving in the $z$ direction relative to the scattering center. An impact parameter $b=0$ refers to being aimed directly at the target's center. The impact parameter describes the transverse distance from the $z=0$ axis for the trajectory when it is still far away from the scattering center and has not yet passed it. The differential cross section can be expressed in terms of the impact parameter, <!-- Equation labels as ordinary links --> <div id="_auto7"></div> $$ \begin{equation} d\sigma=2\pi bdb, \label{_auto7} \tag{12} \end{equation} $$ which is the area of a thin ring of radius $b$ and thickness $db$. In classical physics, one can calculate the trajectory given the incoming kinetic energy $E$ and the impact parameter if one knows the mass and potential. From the trajectory, one then finds the scattering angle $\phi_s(b)$. The differential cross section is then <!-- Equation labels as ordinary links --> <div id="_auto8"></div> $$ \begin{equation} \frac{d\sigma}{d\Omega}=\frac{1}{2\pi}\frac{d\sigma}{d\cos\phi_s}=b\frac{db}{d\cos\phi_s}=\frac{b}{(d/db)\cos\phi_s(b)}. \label{_auto8} \tag{13} \end{equation} $$ Typically, one would calculate $\cos\phi_s$ and $(d/db)\cos\phi_s$ as functions of $b$. This is sufficient to plot the differential cross section as a function of $\phi_s$. The total cross section is <!-- Equation labels as ordinary links --> <div id="_auto9"></div> $$ \begin{equation} \sigma_{\rm tot}=\int d\Omega\frac{d\sigma}{d\Omega}=2\pi\int d\cos\phi_s~\frac{d\sigma}{d\Omega}. \label{_auto9} \tag{14} \end{equation} $$ Even if the total cross section is infinite, e.g. Coulomb forces, one can still have a finite differential cross section as we will see later on. An asteroid of mass $m$ and kinetic energy $E$ approaches a planet of radius $R$ and mass $M$. What is the cross section for the asteroid to impact the planet? ### Solution Calculate the maximum impact parameter, $b_{\rm max}$, for which the asteroid will hit the planet. The total cross section for impact is $\sigma_{\rm impact}=\pi b_{\rm max}^2$. The maximum cross-section can be found with the help of angular momentum conservation. The asteroid's incoming momentum is $p_0=\sqrt{2mE}$ and the angular momentum is $L=p_0b$. If the asteroid just grazes the planet, it is moving with zero radial kinetic energy at impact. Combining energy and angular momentum conservation and having $p_f$ refer to the momentum of the asteroid at a distance $R$, $$ \begin{eqnarray*} \frac{p_f^2}{2m}-\frac{GMm}{R}&=&E,\\ p_fR&=&p_0b_{\rm max}, \end{eqnarray*} $$ allows one to solve for $b_{\rm max}$, $$ \begin{eqnarray*} b_{\rm max}&=&R\frac{p_f}{p_0}\\ &=&R\frac{\sqrt{2m(E+GMm/R)}}{\sqrt{2mE}}\\ \sigma_{\rm impact}&=&\pi R^2\frac{E+GMm/R}{E}. \end{eqnarray*} $$ ## Rutherford Scattering This refers to the calculation of $d\sigma/d\Omega$ due to an inverse square force, $F_{12}=\pm\alpha/r^2$ for repulsive/attractive interaction. Rutherford compared the scattering of $\alpha$ particles ($^4$He nuclei) off of a nucleus and found the scattering angle at which the formula began to fail. This corresponded to the impact parameter for which the trajectories would strike the nucleus. This provided the first measure of the size of the atomic nucleus. At the time, the distribution of the positive charge (the protons) was considered to be just as spread out amongst the atomic volume as the electrons. After Rutherford's experiment, it was clear that the radius of the nucleus tended to be roughly 4 orders of magnitude smaller than that of the atom, which is less than the size of a football relative to Spartan Stadium. The incoming and outgoing angles of the trajectory are at $\pm\phi'$. They are related to the scattering angle by $2\phi'=\pi+\phi_s$. In order to calculate differential cross section, we must find how the impact parameter is related to the scattering angle. This requires analysis of the trajectory. We consider our previous expression for the trajectory where we derived the elliptic form for the trajectory, Eq. ([9](#eq:Ctrajectory)). For that case we considered an attractive force with the particle's energy being negative, i.e. it was bound. However, the same form will work for positive energy, and repulsive forces can be considered by simple flipping the sign of $\alpha$. For positive energies, the trajectories will be hyperbolas, rather than ellipses, with the asymptotes of the trajectories representing the directions of the incoming and outgoing tracks. Rewriting Eq. ([9](#eq:Ctrajectory)), <!-- Equation labels as ordinary links --> <div id="eq:ruthtraj"></div> $$ \begin{equation}\label{eq:ruthtraj} \tag{15} r=\frac{1}{\frac{m\alpha}{L^2}+A\cos\phi}. \end{equation} $$ Once $A$ is large enough, which will happen when the energy is positive, the denominator will become negative for a range of $\phi$. This is because the scattered particle will never reach certain angles. The asymptotic angles $\phi'$ are those for which the denominator goes to zero, <!-- Equation labels as ordinary links --> <div id="_auto10"></div> $$ \begin{equation} \cos\phi'=-\frac{m\alpha}{AL^2}. \label{_auto10} \tag{16} \end{equation} $$ The trajectory's point of closest approach is at $\phi=0$ and the two angles $\phi'$, which have this value of $\cos\phi'$, are the angles of the incoming and outgoing particles. From Fig (**to come**), one can see that the scattering angle $\phi_s$ is given by, <!-- Equation labels as ordinary links --> <div id="eq:sthetover2"></div> $$ \begin{eqnarray} \label{eq:sthetover2} \tag{17} 2\phi'-\pi&=&\phi_s,~~~\phi'=\frac{\pi}{2}+\frac{\phi_s}{2},\\ \nonumber \sin(\phi_s/2)&=&-\cos\phi'\\ \nonumber &=&\frac{m\alpha}{AL^2}. \end{eqnarray} $$ Now that we have $\phi_s$ in terms of $m,\alpha,L$ and $A$, we wish to re-express $L$ and $A$ in terms of the impact parameter $b$ and the energy $E$. This will set us up to calculate the differential cross section, which requires knowing $db/d\phi_s$. It is easy to write the angular momentum as <!-- Equation labels as ordinary links --> <div id="_auto11"></div> $$ \begin{equation} L^2=p_0^2b^2=2mEb^2. \label{_auto11} \tag{18} \end{equation} $$ Finding $A$ is more complicated. To accomplish this we realize that the point of closest approach occurs at $\phi=0$, so from Eq. ([15](#eq:ruthtraj)) <!-- Equation labels as ordinary links --> <div id="eq:rminofA"></div> $$ \begin{eqnarray} \label{eq:rminofA} \tag{19} \frac{1}{r_{\rm min}}&=&\frac{m\alpha}{L^2}+A,\\ \nonumber A&=&\frac{1}{r_{\rm min}}-\frac{m\alpha}{L^2}. \end{eqnarray} $$ Next, $r_{\rm min}$ can be found in terms of the energy because at the point of closest approach the kinetic energy is due purely to the motion perpendicular to $\hat{r}$ and <!-- Equation labels as ordinary links --> <div id="_auto12"></div> $$ \begin{equation} E=-\frac{\alpha}{r_{\rm min}}+\frac{L^2}{2mr_{\rm min}^2}. \label{_auto12} \tag{20} \end{equation} $$ One can solve the quadratic equation for $1/r_{\rm min}$, <!-- Equation labels as ordinary links --> <div id="_auto13"></div> $$ \begin{equation} \frac{1}{r_{\rm min}}=\frac{m\alpha}{L^2}+\sqrt{(m\alpha/L^2)^2+2mE/L^2}. \label{_auto13} \tag{21} \end{equation} $$ We can plug the expression for $r_{\rm min}$ into the expression for $A$, Eq. ([19](#eq:rminofA)), <!-- Equation labels as ordinary links --> <div id="_auto14"></div> $$ \begin{equation} A=\sqrt{(m\alpha/L^2)^2+2mE/L^2}=\sqrt{(\alpha^2/(4E^2b^4)+1/b^2} \label{_auto14} \tag{22} \end{equation} $$ Finally, we insert the expression for $A$ into that for the scattering angle, Eq. ([17](#eq:sthetover2)), <!-- Equation labels as ordinary links --> <div id="eq:scattangle"></div> $$ \begin{eqnarray} \label{eq:scattangle} \tag{23} \sin(\phi_s/2)&=&\frac{m\alpha}{AL^2}\\ \nonumber &=&\frac{a}{\sqrt{a^2+b^2}}, ~~a\equiv \frac{\alpha}{2E} \end{eqnarray} $$ The differential cross section can now be found by differentiating the expression for $\phi_s$ with $b$, <!-- Equation labels as ordinary links --> <div id="eq:rutherford"></div> $$ \begin{eqnarray} \label{eq:rutherford} \tag{24} \frac{1}{2}\cos(\phi_s/2)d\phi_s&=&\frac{ab~db}{(a^2+b^2)^{3/2}}=\frac{bdb}{a^2}\sin^3(\phi_s/2),\\ \nonumber d\sigma&=&2\pi bdb=\frac{\pi a^2}{\sin^3(\phi_s/2)}\cos(\phi_s/2)d\phi_s\\ \nonumber &=&\frac{\pi a^2}{2\sin^4(\phi_s/2)}\sin\phi_s d\phi_s\\ \nonumber \frac{d\sigma}{d\cos\phi_s}&=&\frac{\pi a^2}{2\sin^4(\phi_s/2)},\\ \nonumber \frac{d\sigma}{d\Omega}&=&\frac{a^2}{4\sin^4(\phi_s/2)}. \end{eqnarray} $$ where $a= \alpha/2E$. This the Rutherford formula for the differential cross section. It diverges as $\phi_s\rightarrow 0$ because scatterings with arbitrarily large impact parameters still scatter to arbitrarily small scattering angles. The expression for $d\sigma/d\Omega$ is the same whether the interaction is positive or negative. Consider a particle of mass $m$ and charge $z$ with kinetic energy $E$ (Let it be the center-of-mass energy) incident on a heavy nucleus of mass $M$ and charge $Z$ and radius $R$. Find the angle at which the Rutherford scattering formula breaks down. ### Solution Let $\alpha=Zze^2/(4\pi\epsilon_0)$. The scattering angle in Eq. ([23](#eq:scattangle)) is $$ \sin(\phi_s/2)=\frac{a}{\sqrt{a^2+b^2}}, ~~a\equiv \frac{\alpha}{2E}. $$ The impact parameter $b$ for which the point of closest approach equals $R$ can be found by using angular momentum conservation, $$ \begin{eqnarray*} p_0b&=&b\sqrt{2mE}=Rp_f=R\sqrt{2m(E-\alpha/R)},\\ b&=&R\frac{\sqrt{2m(E-\alpha/R)}}{\sqrt{2mE}}\\ &=&R\sqrt{1-\frac{\alpha}{ER}}. \end{eqnarray*} $$ Putting these together $$ \phi_s=2\sin^{-1}\left\{ \frac{a}{\sqrt{a^2+R^2(1-\alpha/(RE))}} \right\},~~~a=\frac{\alpha}{2E}. $$ It was from this departure of the experimentally measured $d\sigma/d\Omega$ from the Rutherford formula that allowed Rutherford to infer the radius of the gold nucleus, $R$. Just like electrodynamics, one can define "fields", which for a small additional mass $m$ are the force per mass and the additional potential energy per mass. The {\it gravitational field} related to the force has dimensions of force per mass, or acceleration, and can be labeled $\boldsymbol{g}(\boldsymbol{r})$. The potential energy per mass has dimensions of energy per mass. This is analogous to the electromagnetic potential, which is the potential energy per charge, and the electric field which is the force per charge. Because the field $\boldsymbol{g}$ obeys the same inverse square law for a point mass as the electric field does for a point charge, the gravitational field also satisfies a version of Gauss's law, <!-- Equation labels as ordinary links --> <div id="eq:GravGauss"></div> $$ \begin{equation} \label{eq:GravGauss} \tag{25} \oint d\boldsymbol{A}\cdot\boldsymbol{g}=-4\pi GM_{\rm inside}. \end{equation} $$ Here, $M_{\rm inside}$ is the net mass inside a closed area. Gauss's law can be understood by considering a nozzle that sprays paint in all directions uniformly from a point source. Let $B$ be the number of gallons per minute of paint leaving the nozzle. If the nozzle is at the center of a sphere of radius $r$, the paint per square meter per minute that is deposited on some part of the sphere is $$ \begin{eqnarray} F(r)&=&\frac{B}{4\pi r^2}. \end{eqnarray} $$ Now, let $F$ also be assigned a direction, so that it becomes a vector pointing along the direction of the flying paint. For any surface that surrounds the nozzle, not necessarily a sphere, one can state that <!-- Equation labels as ordinary links --> <div id="eq:paint"></div> $$ \begin{eqnarray} \label{eq:paint} \tag{26} \oint \boldsymbol{dA}\cdot\boldsymbol{F}&=&B, \end{eqnarray} $$ regardless of the shape of the surface. This follows because the rate at which paint is deposited on the surface should equal the rate at which it leaves the nozzle. The dot product ensures that only the component of $\boldsymbol{F}$ into the surface contributes to the deposition of paint. Similarly, if $\boldsymbol{F}$ is any radial inverse-square forces, that falls as $B/(4\pi r^2)$, then one can apply Eq. ([26](#eq:paint)). For gravitational fields, $B/(4\pi)$ is replaced by $GM$, and one quickly "derives" Gauss's law for gravity, Eq. ([25](#eq:GravGauss)). Consider Earth to have its mass $M$ uniformly distributed in a sphere of radius $R$. Find the magnitude of the gravitational acceleration as a function of the radius $r$ in terms of the acceleration of gravity at the surface $g(R)$. Assume $r<R$, i.e. you are inside the surface. {\bf Solution}: Take the ratio of Eq. ([25](#eq:GravGauss)) for two radii, $R$ and $r<R$, $$ \begin{eqnarray*} \frac{4\pi r^2 g(r)}{4\pi R^2 g(R)}&=&\frac{4\pi GM_{\rm inside~r}}{4\pi GM_{\rm inside~R}}\\ \nonumber &=&\frac{r^3}{R^3}\\ \nonumber g(r)&=&g(R)\frac{r}{R}~. \end{eqnarray*} $$ The potential energy per mass is similar conceptually to the voltage, or electric potential energy per charge, that was studied in electromagnetism, if $V\equiv U/m$, $\boldsymbol{g}=-\nabla V$. ## Tidal Forces Consider a spherical planet of radius $r$ a distance $D$ from another body of mass $M$. The magnitude of the force due to $M$ on an small object of mass $\delta m$ on surface of the planet can be calculated by performing a Taylor expansion about the center of the spherical planet. <!-- Equation labels as ordinary links --> <div id="_auto15"></div> $$ \begin{equation} F=-\frac{GM\delta m}{D^2}+2\frac{GM\delta m}{D^3}\Delta D+\cdots \label{_auto15} \tag{27} \end{equation} $$ If the $z$ direction points toward the large object, $\Delta D$ can be referred to as $z$. In the accelerating frame of an observer at the center of the planet, <!-- Equation labels as ordinary links --> <div id="_auto16"></div> $$ \begin{equation} \delta m\frac{d^2 z}{dt^2}=F-\delta ma'+{\rm other~forces~acting~on~} \delta m, \label{_auto16} \tag{28} \end{equation} $$ where $a'$ is the acceleration of the observer. Because $\delta ma'$ equals the gravitational force on $\delta m$ if it were located at the planet's center, one can write <!-- Equation labels as ordinary links --> <div id="_auto17"></div> $$ \begin{equation} m\frac{d^2z}{dt^2}=2\frac{GM\delta m}{D^3}z+{\rm other~forces~acting~on~}\delta m. \label{_auto17} \tag{29} \end{equation} $$ Here the other forces could represent the forces acting on $\delta m$ from the spherical planet such as the gravitational force or the contact force with the surface. If $\phi$ is the angle w.r.t. the $z$ axis, the effective force acting on $\delta m$ is <!-- Equation labels as ordinary links --> <div id="_auto18"></div> $$ \begin{equation} F_{\rm eff}\approx 2\frac{GM\delta m}{D^3}r\cos\phi\hat{z}+{\rm other~forces~acting~on~}\delta m. \label{_auto18} \tag{30} \end{equation} $$ This first force is the "tidal" force. It pulls objects outward from the center of the object. If the object were covered with water, it would distort the objects shape so that the shape would be elliptical, stretched out along the axis pointing toward the large mass $M$. The force is always along (either parallel or antiparallel to) the $\hat{z}$ direction. Consider the Earth to be a sphere of radius $R$ covered with water, with the gravitational acceleration at the surface noted by $g$. Now assume that a distant body provides an additional constant gravitational acceleration $\boldsymbol{a}$ pointed along the $z$ axis. Find the distortion of the radius as a function of $\phi$. Ignore planetary rotation and assume $a<<g$. {\bf Solution}: Because Earth would then accelerate with $a$, the field $a$ would seem invisible in the accelerating frame. A tidal force would only appear if $a$ depended on position, i.e. $\nabla \boldsymbol{a}\ne 0$. Now consider that the field is no longer constant, but that instead $a=-kz$ with $|kR|<<g$. {\bf Solution}: The surface of the planet needs to be at constant potential (if the planet is not accelerating). The force per mass, $-kz$ is like a spring, and the potential per mass is $kz^2/2$. Otherwise water would move to a point of lower potential. Thus, the potential energy for a sample mass $\delta m$ is $$ \begin{eqnarray*} V(R)+\delta m gh(\phi)-\frac{\delta m}{2}kr^2\cos^2\phi={\rm Constant}\\ V(R)+\delta mgh(\phi)-\frac{\delta m}{2}kR^2\cos^2\phi-\delta m kRh(\phi)\cos^2\phi-\frac{\delta m}{2}kh^2(\phi)\cos^2\phi={\rm Constant}. \end{eqnarray*} $$ Here, the potential due to the external field is $(1/2)kz^2$ so that $-\nabla U=-kz$. One now needs to solve for $h(\phi)$. Absorbing all the constant terms from both sides of the equation into one constant $C$, and because both $h$ and $kR$ are small, we can through away terms of order $h^2$ or $kRh$. This gives $$ \begin{eqnarray*} gh(\phi)-\frac{1}{2}kR^2\cos^2\phi&=&C,\\ h(\phi)&=&\frac{C}{g}+\frac{1}{2g}kR^2\cos^2\phi,\\ h(\phi)&=&\frac{1}{2g}kR^2(\cos^2\phi-1/3). \end{eqnarray*} $$ The term with the factor of $1/3$ replaced the constant and was chosen so that the average height of the water would be zero. The Sun's mass is $27\times 10^6$ the Moon's mass, but the Sun is 390 times further away from Earth as the Sun. What is ratio of the tidal force of the Sun to that of the Moon. {\bf Solution}: The gravitational force due to an object $M$ a distance $D$ away goes as $M/D^2$, but the tidal force is only the difference of that force over a distance $R$, $$ F_{\rm tidal}\propto \frac{M}{D^3}R. $$ Therefore the ratio of force is $$ \begin{eqnarray*} \frac{F_{\rm Sun's~tidal~force}}{F_{\rm Moon's~tidal~force}} &=&\frac{M_{\rm sun}/D_{\rm sun}^3}{M_{\rm moon}/D_{\rm moon}^3}\\ &=&\frac{27\times 10^6}{390^3}=0.46. \end{eqnarray*} $$ The Moon more strongly affects tides than the Sun. ## Exercises ### The Earth-Sun System We start with a simpler case first, the Earth-Sun system in two dimensions only. The gravitational force $F_G$ on the earth from the sun is $$ \boldsymbol{F}_G=-\frac{GM_{\odot}M_E}{r^3}\boldsymbol{r}, $$ where $G$ is the gravitational constant, $$ M_E=6\times 10^{24}\mathrm{Kg}, $$ the mass of Earth, $$ M_{\odot}=2\times 10^{30}\mathrm{Kg}, $$ the mass of the Sun and $$ r=1.5\times 10^{11}\mathrm{m}, $$ is the distance between Earth and the Sun. The latter defines what we call an astronomical unit **AU**. From Newton's second law we have then for the $x$ direction $$ \frac{d^2x}{dt^2}=-\frac{F_{x}}{M_E}, $$ and $$ \frac{d^2y}{dt^2}=-\frac{F_{y}}{M_E}, $$ for the $y$ direction. Here we will use that $x=r\cos{(\theta)}$, $y=r\sin{(\theta)}$ and $$ r = \sqrt{x^2+y^2}. $$ We can rewrite these equations $$ F_{x}=-\frac{GM_{\odot}M_E}{r^2}\cos{(\theta)}=-\frac{GM_{\odot}M_E}{r^3}x, $$ and $$ F_{y}=-\frac{GM_{\odot}M_E}{r^2}\sin{(\theta)}=-\frac{GM_{\odot}M_E}{r^3}y, $$ as four first-order coupled differential equations $$ \frac{dv_x}{dt}=-\frac{GM_{\odot}}{r^3}x, $$ and $$ \frac{dx}{dt}=v_x, $$ and $$ \frac{dv_y}{dt}=-\frac{GM_{\odot}}{r^3}y, $$ and $$ \frac{dy}{dt}=v_y. $$ The four coupled differential equations $$ \frac{dv_x}{dt}=-\frac{GM_{\odot}}{r^3}x, $$ and $$ \frac{dx}{dt}=v_x, $$ and $$ \frac{dv_y}{dt}=-\frac{GM_{\odot}}{r^3}y, $$ and $$ \frac{dy}{dt}=v_y, $$ can be turned into dimensionless equations or we can introduce astronomical units with $1$ AU = $1.5\times 10^{11}$. Using the equations from circular motion (with $r =1\mathrm{AU}$) $$ \frac{M_E v^2}{r} = F = \frac{GM_{\odot}M_E}{r^2}, $$ we have $$ GM_{\odot}=v^2r, $$ and using that the velocity of Earth (assuming circular motion) is $v = 2\pi r/\mathrm{yr}=2\pi\mathrm{AU}/\mathrm{yr}$, we have $$ GM_{\odot}= v^2r = 4\pi^2 \frac{(\mathrm{AU})^3}{\mathrm{yr}^2}. $$ The four coupled differential equations can then be discretized using Euler's method as (with step length $h$) $$ v_{x,i+1}=v_{x,i}-h\frac{4\pi^2}{r_i^3}x_i, $$ and $$ x_{i+1}=x_i+hv_{x,i}, $$ and $$ v_{y,i+1}=v_{y,i}-h\frac{4\pi^2}{r_i^3}y_i, $$ and $$ y_{i+1}=y_i+hv_{y,i}, $$ The code here implements Euler's method for the Earth-Sun system using a more compact way of representing the vectors. Alternatively, you could have spelled out all the variables $v_x$, $v_y$, $x$ and $y$ as one-dimensional arrays. # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt import os # Where to save the figures and data files PROJECT_ROOT_DIR = "Results" FIGURE_ID = "Results/FigureFiles" DATA_ID = "DataFiles/" if not os.path.exists(PROJECT_ROOT_DIR): os.mkdir(PROJECT_ROOT_DIR) if not os.path.exists(FIGURE_ID): os.makedirs(FIGURE_ID) if not os.path.exists(DATA_ID): os.makedirs(DATA_ID) def image_path(fig_id): return os.path.join(FIGURE_ID, fig_id) def data_path(dat_id): return os.path.join(DATA_ID, dat_id) def save_fig(fig_id): plt.savefig(image_path(fig_id) + ".png", format='png') DeltaT = 0.01 #set up arrays tfinal = 10 # in years n = ceil(tfinal/DeltaT) # set up arrays for t, a, v, and x t = np.zeros(n) v = np.zeros((n,2)) r = np.zeros((n,2)) # Initial conditions as compact 2-dimensional arrays r0 = np.array([1.0,0.0]) v0 = np.array([0.0,2*pi]) r[0] = r0 v[0] = v0 Fourpi2 = 4*pi*pi # Start integrating using Euler's method for i in range(n-1): # Set up the acceleration # Here you could have defined your own function for this rabs = sqrt(sum(r[i]*r[i])) a = -Fourpi2*r[i]/(rabs**3) # update velocity, time and position using Euler's forward method v[i+1] = v[i] + DeltaT*a r[i+1] = r[i] + DeltaT*v[i] t[i+1] = t[i] + DeltaT # Plot position as function of time fig, ax = plt.subplots() #ax.set_xlim(0, tfinal) ax.set_xlabel('x[AU]') ax.set_ylabel('y[AU]') ax.plot(r[:,0], r[:,1]) fig.tight_layout() save_fig("EarthSunEuler") plt.show() We notice here that Euler's method doesn't give a stable orbit with for example $\Delta t =0.01$. It means that we cannot trust Euler's method. Euler's method does not conserve energy. It is an example of an integrator which is not [symplectic](https://en.wikipedia.org/wiki/Symplectic_integrator). Here we present thus two methods, which with simple changes allow us to avoid these pitfalls. The simplest possible extension is the so-called Euler-Cromer method. The changes we need to make to our code are indeed marginal here. We need simply to replace r[i+1] = r[i] + DeltaT*v[i] in the above code with the velocity at the new time $t_{i+1}$ r[i+1] = r[i] + DeltaT*v[i+1] By this simple caveat we get stable orbits. Below we derive the Euler-Cromer method as well as one of the most utlized algorithms for solving the above type of problems, the so-called Velocity-Verlet method. Let us repeat Euler's method. We have a differential equation <!-- Equation labels as ordinary links --> <div id="_auto19"></div> $$ \begin{equation} y'(t_i)=f(t_i,y_i) \label{_auto19} \tag{31} \end{equation} $$ and if we truncate at the first derivative, we have from the Taylor expansion <!-- Equation labels as ordinary links --> <div id="eq:euler"></div> $$ \begin{equation} y_{i+1}=y(t_i) + (\Delta t) f(t_i,y_i) + O(\Delta t^2), \label{eq:euler} \tag{32} \end{equation} $$ which when complemented with $t_{i+1}=t_i+\Delta t$ forms the algorithm for the well-known Euler method. Note that at every step we make an approximation error of the order of $O(\Delta t^2)$, however the total error is the sum over all steps $N=(b-a)/(\Delta t)$ for $t\in [a,b]$, yielding thus a global error which goes like $NO(\Delta t^2)\approx O(\Delta t)$. To make Euler's method more precise we can obviously decrease $\Delta t$ (increase $N$), but this can lead to loss of numerical precision. Euler's method is not recommended for precision calculation, although it is handy to use in order to get a first view on how a solution may look like. Euler's method is asymmetric in time, since it uses information about the derivative at the beginning of the time interval. This means that we evaluate the position at $y_1$ using the velocity at $v_0$. A simple variation is to determine $x_{n+1}$ using the velocity at $v_{n+1}$, that is (in a slightly more generalized form) <!-- Equation labels as ordinary links --> <div id="_auto20"></div> $$ \begin{equation} y_{n+1}=y_{n}+ v_{n+1}+O(\Delta t^2) \label{_auto20} \tag{33} \end{equation} $$ and <!-- Equation labels as ordinary links --> <div id="_auto21"></div> $$ \begin{equation} v_{n+1}=v_{n}+(\Delta t) a_{n}+O(\Delta t^2). \label{_auto21} \tag{34} \end{equation} $$ The acceleration $a_n$ is a function of $a_n(y_n, v_n, t_n)$ and needs to be evaluated as well. This is the Euler-Cromer method. It is easy to change the above code and see that with the same time step we get stable results. Let us stay with $x$ (position) and $v$ (velocity) as the quantities we are interested in. We have the Taylor expansion for the position given by $$ x_{i+1} = x_i+(\Delta t)v_i+\frac{(\Delta t)^2}{2}a_i+O((\Delta t)^3). $$ The corresponding expansion for the velocity is $$ v_{i+1} = v_i+(\Delta t)a_i+\frac{(\Delta t)^2}{2}v^{(2)}_i+O((\Delta t)^3). $$ Via Newton's second law we have normally an analytical expression for the derivative of the velocity, namely $$ a_i= \frac{d^2 x}{dt^2}\vert_{i}=\frac{d v}{dt}\vert_{i}= \frac{F(x_i,v_i,t_i)}{m}. $$ If we add to this the corresponding expansion for the derivative of the velocity $$ v^{(1)}_{i+1} = a_{i+1}= a_i+(\Delta t)v^{(2)}_i+O((\Delta t)^2)=a_i+(\Delta t)v^{(2)}_i+O((\Delta t)^2), $$ and retain only terms up to the second derivative of the velocity since our error goes as $O(h^3)$, we have $$ (\Delta t)v^{(2)}_i\approx a_{i+1}-a_i. $$ We can then rewrite the Taylor expansion for the velocity as $$ v_{i+1} = v_i+\frac{(\Delta t)}{2}\left( a_{i+1}+a_{i}\right)+O((\Delta t)^3). $$ Our final equations for the position and the velocity become then $$ x_{i+1} = x_i+(\Delta t)v_i+\frac{(\Delta t)^2}{2}a_{i}+O((\Delta t)^3), $$ and $$ v_{i+1} = v_i+\frac{(\Delta t)}{2}\left(a_{i+1}+a_{i}\right)+O((\Delta t)^3). $$ Note well that the term $a_{i+1}$ depends on the position at $x_{i+1}$. This means that you need to calculate the position at the updated time $t_{i+1}$ before the computing the next velocity. Note also that the derivative of the velocity at the time $t_i$ used in the updating of the position can be reused in the calculation of the velocity update as well. We can now easily add the Verlet method to our original code as DeltaT = 0.01 #set up arrays tfinal = 10 n = ceil(tfinal/DeltaT) # set up arrays for t, a, v, and x t = np.zeros(n) v = np.zeros((n,2)) r = np.zeros((n,2)) # Initial conditions as compact 2-dimensional arrays r0 = np.array([1.0,0.0]) v0 = np.array([0.0,2*pi]) r[0] = r0 v[0] = v0 Fourpi2 = 4*pi*pi # Start integrating using the Velocity-Verlet method for i in range(n-1): # Set up forces, air resistance FD, note now that we need the norm of the vecto # Here you could have defined your own function for this rabs = sqrt(sum(r[i]*r[i])) a = -Fourpi2*r[i]/(rabs**3) # update velocity, time and position using the Velocity-Verlet method r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a rabs = sqrt(sum(r[i+1]*r[i+1])) anew = -4*(pi**2)*r[i+1]/(rabs**3) v[i+1] = v[i] + 0.5*DeltaT*(a+anew) t[i+1] = t[i] + DeltaT # Plot position as function of time fig, ax = plt.subplots() ax.set_xlabel('x[AU]') ax.set_ylabel('y[AU]') ax.plot(r[:,0], r[:,1]) fig.tight_layout() save_fig("EarthSunVV") plt.show() You can easily generalize the calculation of the forces by defining a function which takes in as input the various variables. We leave this as a challenge to you. Running the above code for various time steps we see that the Velocity-Verlet is fully stable for various time steps. We can also play around with different initial conditions in order to find the escape velocity from an orbit around the sun with distance one astronomical unit, 1 AU. The theoretical value for the escape velocity, is given by $$ v = \sqrt{8\pi^2}{r}, $$ and with $r=1$ AU, this means that the escape velocity is $2\pi\sqrt{2}$ AU/yr. To obtain this we required that the kinetic energy of Earth equals the potential energy given by the gravitational force. Setting $$ \frac{1}{2}M_{\mathrm{Earth}}v^2=\frac{GM_{\odot}}{r}, $$ and with $GM_{\odot}=4\pi^2$ we obtain the above relation for the velocity. Setting an initial velocity say equal to $9$ in the above code, yields a planet (Earth) which escapes a stable orbit around the sun, as seen by running the code here. DeltaT = 0.01 #set up arrays tfinal = 100 n = ceil(tfinal/DeltaT) # set up arrays for t, a, v, and x t = np.zeros(n) v = np.zeros((n,2)) r = np.zeros((n,2)) # Initial conditions as compact 2-dimensional arrays r0 = np.array([1.0,0.0]) # setting initial velocity larger than escape velocity v0 = np.array([0.0,9.0]) r[0] = r0 v[0] = v0 Fourpi2 = 4*pi*pi # Start integrating using the Velocity-Verlet method for i in range(n-1): # Set up forces, air resistance FD, note now that we need the norm of the vecto # Here you could have defined your own function for this rabs = sqrt(sum(r[i]*r[i])) a = -Fourpi2*r[i]/(rabs**3) # update velocity, time and position using the Velocity-Verlet method r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a rabs = sqrt(sum(r[i+1]*r[i+1])) anew = -4*(pi**2)*r[i+1]/(rabs**3) v[i+1] = v[i] + 0.5*DeltaT*(a+anew) t[i+1] = t[i] + DeltaT # Plot position as function of time fig, ax = plt.subplots() ax.set_xlabel('x[AU]') ax.set_ylabel('y[AU]') ax.plot(r[:,0], r[:,1]) fig.tight_layout() save_fig("EscapeEarthSunVV") plt.show() ### Testing Energy conservation The code here implements Euler's method for the Earth-Sun system using a more compact way of representing the vectors. Alternatively, you could have spelled out all the variables $v_x$, $v_y$, $x$ and $y$ as one-dimensional arrays. It tests conservation of potential and kinetic energy as functions of time, in addition to the total energy, again as function of time **Note**: in all codes we have used scaled equations so that the gravitational constant times the mass of the sum is given by $4\pi^2$ and the mass of the earth is set to **one** in the calculations of kinetic and potential energies. Else, we would get very large results. # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt import os # Where to save the figures and data files PROJECT_ROOT_DIR = "Results" FIGURE_ID = "Results/FigureFiles" DATA_ID = "DataFiles/" if not os.path.exists(PROJECT_ROOT_DIR): os.mkdir(PROJECT_ROOT_DIR) if not os.path.exists(FIGURE_ID): os.makedirs(FIGURE_ID) if not os.path.exists(DATA_ID): os.makedirs(DATA_ID) def image_path(fig_id): return os.path.join(FIGURE_ID, fig_id) def data_path(dat_id): return os.path.join(DATA_ID, dat_id) def save_fig(fig_id): plt.savefig(image_path(fig_id) + ".png", format='png') # Initial values, time step, positions and velocites DeltaT = 0.0001 #set up arrays tfinal = 100 # in years n = ceil(tfinal/DeltaT) # set up arrays for t, a, v, and x t = np.zeros(n) v = np.zeros((n,2)) r = np.zeros((n,2)) # setting up the kinetic, potential and total energy, note only functions of time EKinetic = np.zeros(n) EPotential = np.zeros(n) ETotal = np.zeros(n) # Initial conditions as compact 2-dimensional arrays r0 = np.array([1.0,0.0]) v0 = np.array([0.0,2*pi]) r[0] = r0 v[0] = v0 Fourpi2 = 4*pi*pi # Setting up variables for the calculation of energies # distance that defines rabs in potential energy rabs0 = sqrt(sum(r[0]*r[0])) # Initial kinetic energy. Note that we skip the mass of the Earth here, that is MassEarth=1 in all codes EKinetic[0] = 0.5*sum(v0*v0) # Initial potential energy (note negative sign, why?) EPotential[0] = -4*pi*pi/rabs0 # Initial total energy ETotal[0] = EPotential[0]+EKinetic[0] # Start integrating using Euler's method for i in range(n-1): # Set up the acceleration # Here you could have defined your own function for this rabs = sqrt(sum(r[i]*r[i])) a = -Fourpi2*r[i]/(rabs**3) # update Energies, velocity, time and position using Euler's forward method v[i+1] = v[i] + DeltaT*a r[i+1] = r[i] + DeltaT*v[i] t[i+1] = t[i] + DeltaT EKinetic[i+1] = 0.5*sum(v[i+1]*v[i+1]) EPotential[i+1] = -4*pi*pi/sqrt(sum(r[i+1]*r[i+1])) ETotal[i+1] = EPotential[i+1]+EKinetic[i+1] # Plot energies as functions of time fig, axs = plt.subplots(3, 1) axs[0].plot(t, EKinetic) axs[0].set_xlim(0, tfinal) axs[0].set_ylabel('Kinetic energy') axs[1].plot(t, EPotential) axs[1].set_ylabel('Potential Energy') axs[2].plot(t, ETotal) axs[2].set_xlabel('Time [yr]') axs[2].set_ylabel('Total Energy') fig.tight_layout() save_fig("EarthSunEuler") plt.show() We see very clearly that Euler's method does not conserve energy!! Try to reduce the time step $\Delta t$. What do you see? With the Euler-Cromer method, the only thing we need is to update the position at a time $t+1$ with the update velocity from the same time. Thus, the change in the code is extremely simply, and **energy is suddenly conserved**. Note that the error runs like $O(\Delta t)$ and this is why we see the larger oscillations. But within this oscillating energy envelope, we see that the energies swing between a max and a min value and never exceed these values. # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt import os # Where to save the figures and data files PROJECT_ROOT_DIR = "Results" FIGURE_ID = "Results/FigureFiles" DATA_ID = "DataFiles/" if not os.path.exists(PROJECT_ROOT_DIR): os.mkdir(PROJECT_ROOT_DIR) if not os.path.exists(FIGURE_ID): os.makedirs(FIGURE_ID) if not os.path.exists(DATA_ID): os.makedirs(DATA_ID) def image_path(fig_id): return os.path.join(FIGURE_ID, fig_id) def data_path(dat_id): return os.path.join(DATA_ID, dat_id) def save_fig(fig_id): plt.savefig(image_path(fig_id) + ".png", format='png') # Initial values, time step, positions and velocites DeltaT = 0.0001 #set up arrays tfinal = 100 # in years n = ceil(tfinal/DeltaT) # set up arrays for t, a, v, and x t = np.zeros(n) v = np.zeros((n,2)) r = np.zeros((n,2)) # setting up the kinetic, potential and total energy, note only functions of time EKinetic = np.zeros(n) EPotential = np.zeros(n) ETotal = np.zeros(n) # Initial conditions as compact 2-dimensional arrays r0 = np.array([1.0,0.0]) v0 = np.array([0.0,2*pi]) r[0] = r0 v[0] = v0 Fourpi2 = 4*pi*pi # Setting up variables for the calculation of energies # distance that defines rabs in potential energy rabs0 = sqrt(sum(r[0]*r[0])) # Initial kinetic energy. Note that we skip the mass of the Earth here, that is MassEarth=1 in all codes EKinetic[0] = 0.5*sum(v0*v0) # Initial potential energy EPotential[0] = -4*pi*pi/rabs0 # Initial total energy ETotal[0] = EPotential[0]+EKinetic[0] # Start integrating using Euler's method for i in range(n-1): # Set up the acceleration # Here you could have defined your own function for this rabs = sqrt(sum(r[i]*r[i])) a = -Fourpi2*r[i]/(rabs**3) # update velocity, time and position using Euler's forward method v[i+1] = v[i] + DeltaT*a # Only change when we add the Euler-Cromer method r[i+1] = r[i] + DeltaT*v[i+1] t[i+1] = t[i] + DeltaT EKinetic[i+1] = 0.5*sum(v[i+1]*v[i+1]) EPotential[i+1] = -4*pi*pi/sqrt(sum(r[i+1]*r[i+1])) ETotal[i+1] = EPotential[i+1]+EKinetic[i+1] # Plot energies as functions of time fig, axs = plt.subplots(3, 1) axs[0].plot(t, EKinetic) axs[0].set_xlim(0, tfinal) axs[0].set_ylabel('Kinetic energy') axs[1].plot(t, EPotential) axs[1].set_ylabel('Potential Energy') axs[2].plot(t, ETotal) axs[2].set_xlabel('Time [yr]') axs[2].set_ylabel('Total Energy') fig.tight_layout() save_fig("EarthSunEulerCromer") plt.show() ### Adding the velocity Verlet method Our final equations for the position and the velocity become then $$ x_{i+1} = x_i+(\Delta t)v_i+\frac{(\Delta t)^2}{2}a_{i}+O((\Delta t)^3), $$ and $$ v_{i+1} = v_i+\frac{(\Delta t)}{2}\left(a_{i+1}+a_{i}\right)+O((\Delta t)^3). $$ Note well that the term $a_{i+1}$ depends on the position at $x_{i+1}$. This means that you need to calculate the position at the updated time $t_{i+1}$ before the computing the next velocity. Note also that the derivative of the velocity at the time $t_i$ used in the updating of the position can be reused in the calculation of the velocity update as well. We can now easily add the Verlet method to our original code as DeltaT = 0.001 #set up arrays tfinal = 100 n = ceil(tfinal/DeltaT) # set up arrays for t, a, v, and x t = np.zeros(n) v = np.zeros((n,2)) r = np.zeros((n,2)) # Initial conditions as compact 2-dimensional arrays r0 = np.array([1.0,0.0]) v0 = np.array([0.0,2*pi]) r[0] = r0 v[0] = v0 Fourpi2 = 4*pi*pi # setting up the kinetic, potential and total energy, note only functions of time EKinetic = np.zeros(n) EPotential = np.zeros(n) ETotal = np.zeros(n) # Setting up variables for the calculation of energies # distance that defines rabs in potential energy rabs0 = sqrt(sum(r[0]*r[0])) # Initial kinetic energy. Note that we skip the mass of the Earth here, that is MassEarth=1 in all codes EKinetic[0] = 0.5*sum(v0*v0) # Initial potential energy EPotential[0] = -4*pi*pi/rabs0 # Initial total energy ETotal[0] = EPotential[0]+EKinetic[0] # Start integrating using the Velocity-Verlet method for i in range(n-1): # Set up forces, air resistance FD, note now that we need the norm of the vecto # Here you could have defined your own function for this rabs = sqrt(sum(r[i]*r[i])) a = -Fourpi2*r[i]/(rabs**3) # update velocity, time and position using the Velocity-Verlet method r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a rabs = sqrt(sum(r[i+1]*r[i+1])) anew = -4*(pi**2)*r[i+1]/(rabs**3) v[i+1] = v[i] + 0.5*DeltaT*(a+anew) t[i+1] = t[i] + DeltaT EKinetic[i+1] = 0.5*sum(v[i+1]*v[i+1]) EPotential[i+1] = -4*pi*pi/sqrt(sum(r[i+1]*r[i+1])) ETotal[i+1] = EPotential[i+1]+EKinetic[i+1] # Plot energies as functions of time fig, axs = plt.subplots(3, 1) axs[0].plot(t, EKinetic) axs[0].set_xlim(0, tfinal) axs[0].set_ylabel('Kinetic energy') axs[1].plot(t, EPotential) axs[1].set_ylabel('Potential Energy') axs[2].plot(t, ETotal) axs[2].set_xlabel('Time [yr]') axs[2].set_ylabel('Total Energy') fig.tight_layout() save_fig("EarthSunVelocityVerlet") plt.show() And we see that due to the smaller truncation error that energy conservation is improved as a function of time. Try out different time steps $\Delta t$ and see if the results improve or worsen. ### Exercise: Center-of-Mass and Relative Coordinates and Reference Frames We define the two-body center-of-mass coordinate and relative coordinate by expressing the trajectories for $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ into the center-of-mass coordinate $\boldsymbol{R}_{\rm cm}$ $$ \boldsymbol{R}_{\rm cm}\equiv\frac{m_1\boldsymbol{r}_1+m_2\boldsymbol{r}_2}{m_1+m_2}, $$ and the relative coordinate $$ \boldsymbol{r}\equiv\boldsymbol{r}_1-\boldsymbol{r_2}. $$ Here, we assume the two particles interact only with one another, so $\boldsymbol{F}_{12}=-\boldsymbol{F}_{21}$ (where $\boldsymbol{F}_{ij}$ is the force on $i$ due to $j$. * 2a (5pt) Show that the equations of motion then become $\ddot{\boldsymbol{R}}_{\rm cm}=0$ and $\mu\ddot{\boldsymbol{r}}=\boldsymbol{F}_{12}$, with the reduced mass $\mu=m_1m_2/(m_1+m_2)$. The first expression simply states that the center of mass coordinate $\boldsymbol{R}_{\rm cm}$ moves at a fixed velocity. The second expression can be rewritten in terms of the reduced mass $\mu$. Let us first start with some basic definitions. We have the center of mass coordinate $\boldsymbol{R}$ defined as (for two particles) $$ \boldsymbol{R}=\frac{m_1\boldsymbol{r}_1+m_2\boldsymbol{r}_2}{M}, $$ where $m_1$ and $m_2$ are the masses of the two objects and $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ their respective positions defined according to a chosen origin. Here $M=m_1+m_2$ is the total mass. The relative position is defined as $$ \boldsymbol{r} =\boldsymbol{r}_1-\boldsymbol{r}_2, $$ and we then define $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ in terms of the relative and center of mass positions as $$ \boldsymbol{r}_1=\boldsymbol{R}+\frac{m_2}{M}\boldsymbol{r}, $$ and $$ \boldsymbol{r}_2=\boldsymbol{R}-\frac{m_1}{M}\boldsymbol{r}, $$ The total linear momentum is then defined as $$ \boldsymbol{P}=\sum_{i=1}^Nm_i\frac{\boldsymbol{r}_i}{dt}, $$ where $N=2$ in our case. With the above definition of the center of mass position, we see that we can rewrite the total linear momentum as (multiplying the center of mass position with $M$) $$ \boldsymbol{P}=M\frac{d\boldsymbol{R}}{dt}=M\dot{\boldsymbol{R}}. $$ This result is also an answer to a part of exercise 2b, see below. The net force acting on the system is given by the time derivative of the linear momentum (assuming mass is time independent) and we have $$ \boldsymbol{F}^{\mathrm{net}}=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}}. $$ The net force acting on the system is given by the sum of the forces acting on the two object, that is we have $$ \boldsymbol{F}^{\mathrm{net}}=\boldsymbol{F}_1+\boldsymbol{F}_2=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}}. $$ In our case the forces are given by the internal forces only. The force acting on object $1$ is thus $\boldsymbol{F}_{12}$ and the one acting on object $2$ is $\boldsymbol{F}_{12}$. We have also defined that $\boldsymbol{F}_{12}=-\boldsymbol{F}_{21}$. This means thar we have $$ \boldsymbol{F}_1+\boldsymbol{F}_2=\boldsymbol{F}_{12}+\boldsymbol{F}_{21}=0=\dot{\boldsymbol{P}}=M\ddot{\boldsymbol{R}}, $$ which is what we wanted to show. The center of mass velocity is thus a constant of the motion. We could also define the so-called center of mass reference frame where we simply set $\boldsymbol{R}=0$. This has also another important consequence for our forces. If we assume that our force depends only on the positions, it means that the gradient of the potential with respect to the center of mass position is zero, that is $$ M\ddot{d\boldsymbol{R}}=-\boldsymbol{\nabla}_{\boldsymbol{R}}V =0! $$ An alternative way is $$ \begin{eqnarray} \ddot{\boldsymbol{R}}_{\rm cm}&=&\frac{1}{m_1+m_2}\left\{m_1\ddot{\boldsymbol{r}}_1+m_2\ddot{\boldsymbol{r}}_2\right\}\\ \nonumber &=&\frac{1}{m_1+m_2}\left\{\boldsymbol{F}_{12}+\boldsymbol{F}_{21}\right\}=0.\\ \ddot{\boldsymbol{r}}&=&\ddot{\boldsymbol{r}}_1-\ddot{\boldsymbol{r}}_2=\left(\frac{\boldsymbol{F}_{12}}{m_1}-\frac{\boldsymbol{F}_{21}}{m_2}\right)\\ \nonumber &=&\left(\frac{1}{m_1}+\frac{1}{m_2}\right)\boldsymbol{F}_{12}. \end{eqnarray} $$ The first expression simply states that the center of mass coordinate $\boldsymbol{R}_{\rm cm}$ moves at a fixed velocity. The second expression can be rewritten in terms of the reduced mass $\mu$. $$ \begin{eqnarray} \mu \ddot{\boldsymbol{r}}&=&\boldsymbol{F}_{12},\\ \frac{1}{\mu}&=&\frac{1}{m_1}+\frac{1}{m_2},~~~~\mu=\frac{m_1m_2}{m_1+m_2}. \end{eqnarray} $$ Thus, one can treat the trajectory as a one-body problem where the reduced mass is $\mu$, and a second trivial problem for the center of mass. The reduced mass is especially convenient when one is considering gravitational problems, as we have seen during the lectures of weeks 11-13. * 2b (5pt) Show that the linear momenta for the center-of-mass $\boldsymbol{P}$ motion and the relative motion $\boldsymbol{q}$ are given by $\boldsymbol{P}=M\dot{\boldsymbol{R}}_{\rm cm}$ with $M=m_1+m_2$ and $\boldsymbol{q}=\mu\dot{\boldsymbol{r}}$. The linear momentum of the relative motion is defined $\boldsymbol{q} = (m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2)/(m_1+m_2)$. In 2a we showed, as an intermediate step that the total linear momentum is given by $$ \boldsymbol{P}=\sum_{i=1}^Nm_i\frac{d\boldsymbol{r}_i}{dt}=M\dot{\boldsymbol{R}}. $$ For the relative momentum $\boldsymbol{q}$, we have that the time derivative of $\boldsymbol{r}$ is $$ \dot{\boldsymbol{r}} =\dot{\boldsymbol{r}}_1-\dot{\boldsymbol{r}}_2, $$ We now also that the momenta $\boldsymbol{p}_1=m_1\dot{\boldsymbol{r}}_1$ and $\boldsymbol{p}_2=m_2\dot{\boldsymbol{r}}_2$. Using these expressions we can rewrite $$ \dot{\boldsymbol{r}} =\frac{\boldsymbol{p}_1}{m_1}-\frac{\boldsymbol{p}_2}{m_2}, $$ which we can rewrite as $$ \dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{m_1m_2}, $$ and dividing both sides with $M$ we have $$ \frac{m_1m_2}{M}\dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{M}. $$ Introducing the reduced mass $\mu=m_1m_2/M$ we have finally $$ \mu\dot{\boldsymbol{r}} =\frac{m_2\boldsymbol{p}_1-m_1\boldsymbol{p}_2}{M}. $$ And $\mu\dot{\boldsymbol{r}}$ defines the relative momentum $\boldsymbol{q}=\mu\dot{\boldsymbol{r}}$. When we introduce the Lagrangian formalism we will see that it is much easier to derive these equations. * 2c (5pt) Show then that the kinetic energy for two objects can then be written as $$ K=\frac{P^2}{2M}+\frac{q^2}{2\mu}. $$ Here we just need to use our definitions of kinetic energy in terms of the coordinates $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$. We have that $$ K=\frac{p_1^2}{2m_1}+\frac{p_2^2}{2m_2}, $$ and with $\boldsymbol{p}_1=m_1\dot{\boldsymbol{r}}_1$ and $\boldsymbol{p}_2=m_2\dot{\boldsymbol{r}}_2$ and using $$ \dot{\boldsymbol{r}}_1=\dot{\boldsymbol{R}}+\frac{m_2}{M}\dot{\boldsymbol{r}}, $$ and $$ \dot{\boldsymbol{r}}_2=\dot{\boldsymbol{R}}-\frac{m_1}{M}\dot{\boldsymbol{r}}, $$ we obtain (after squaring the expressions for $\dot{\boldsymbol{r}}_1$ and $\dot{\boldsymbol{r}}_2$) we have $$ K=\frac{(m_1+m_2)\dot{\boldsymbol{R}}^2}{2}+\frac{(m_1+m_2)m_1m_2\dot{\boldsymbol{r}}^2}{2M^2}, $$ which we simplify to $$ K=\frac{\dot{\boldsymbol{P}}^2}{2M}+\frac{\mu\dot{\boldsymbol{q}}^2}{2}, $$ which is what we wanted to show. * 2d (5pt) Show that the total angular momentum for two-particles in the center-of-mass frame $\boldsymbol{R}=0$, is given by $$ \boldsymbol{L}=\boldsymbol{r}\times \mu\dot{\boldsymbol{r}}. $$ Here we need again that $$ \boldsymbol{r} =\boldsymbol{r}_1-\boldsymbol{r}_2, $$ and we then define $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ in terms of the relative and center of mass positions with $\boldsymbol{R}=0$ $$ \boldsymbol{r}_1=\frac{m_2}{M}\boldsymbol{r}, $$ and $$ \boldsymbol{r}_2=-\frac{m_1}{M}\boldsymbol{r}, $$ The angular momentum (the total one) is the sum of the individual angular momenta (see homework 4) and we have $$ \boldsymbol{L} = \boldsymbol{r}_1 \times \boldsymbol{p}_1+\boldsymbol{r}_2 \times \boldsymbol{p}_2, $$ and using that $m_1\dot{\boldsymbol{r}}_1=\boldsymbol{p}_1$ and $m_2\dot{\boldsymbol{r}}_2=\boldsymbol{p}_2$ we have $$ \boldsymbol{L} = m_1\boldsymbol{r}_1 \times \dot{\boldsymbol{r}}_1+m_2\boldsymbol{r}_2 \times \dot{\boldsymbol{r}}_2. $$ Inserting the equations for $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ in terms of the relative motion, we have $$ \boldsymbol{L} = m_1 \frac{m_2}{M}\boldsymbol{r}\times\frac{m_2}{M}\boldsymbol{r} +m_2 \frac{m_1}{M}\boldsymbol{r} \times \frac{m_1}{M}\dot{\boldsymbol{r}}. $$ We see that can rewrite this equation as $$ \boldsymbol{L}=\boldsymbol{r}\times \mu\dot{\boldsymbol{r}}, $$ which is what we wanted to derive. ### Exercise: Conservation of Energy The equations of motion in the center-of-mass frame in two dimensions with $x=r\cos{(\phi)}$ and $y=r\sin{(\phi)}$ and $r\in [0,\infty)$, $\phi\in [0,2\pi]$ and $r=\sqrt{x^2+y^2}$ are given by $$ \mu \ddot{r}=-\frac{dV(r)}{dr}+\mu r\dot{\phi}^2, $$ and $$ \dot{\phi}=\frac{L}{\mu r^2}. $$ Here $V(r)$ is any central force which depends only on the relative coordinate. * 1a (5pt) Show that you can rewrite the radial equation in terms of an effective potential $V_{\mathrm{eff}}(r)=V(r)+L^2/(2\mu r^2)$. Here we use that $$ \dot{\phi}=\frac{L}{\mu r^2}. $$ and rewrite the above equation of motion as $$ \mu \ddot{r}=-\frac{dV(r)}{dr}+\frac{L^2}{\mu r^3}. $$ If we now define an effective potential $$ V_{\mathrm{eff}}=V(r)+\frac{L^2}{2\mu r^2}, $$ we can rewrite our equation of motion in terms of $$ \mu \ddot{r}=-\frac{dV_{\mathrm{eff}}(r)}{dr}=-\frac{dV(r)}{dr}+\frac{L^2}{\mu r^3}. $$ The addition due to the angular momentum comes from the kinetic energy when we rewrote it in terms of polar coordinates. It introduces a so-called centrifugal barrier due to the angular momentum. This centrifugal barrier pushes the object farther away from the origin. Alternatively, <!-- Equation labels as ordinary links --> <div id="_auto22"></div> $$ \begin{equation} -\frac{dV_{\text{eff}}(r)}{dr} = \mu \ddot{r} =-\frac{dV(r)}{dr}+\mu\dot{\phi}^2r \label{_auto22} \tag{35} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto23"></div> $$ \begin{equation} -\frac{dV_{\text{eff}}(r)}{dr} = -\frac{dV(r)}{dr}+\mu\left( \frac{L}{\mu r^2}\right) ^2r \label{_auto23} \tag{36} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto24"></div> $$ \begin{equation} = -\frac{dV(r)}{dr}+\mu\frac{L^2}{\mu}r^{-3} \label{_auto24} \tag{37} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto25"></div> $$ \begin{equation} = -\frac{d\left( V(r)+\frac{1}{2} \frac{L^2}{\mu r^2}\right) }{dr}. \label{_auto25} \tag{38} \end{equation} $$ Integrating we obtain <!-- Equation labels as ordinary links --> <div id="_auto26"></div> $$ \begin{equation} V_{\text{eff}}(r) = V(r) + \frac{L^2}{2\mu r^2} + C \label{_auto26} \tag{39} \end{equation} $$ Imposing the extra condition that $V_{\text{eff}}(r\rightarrow \infty) = V(r\rightarrow \infty)$, <!-- Equation labels as ordinary links --> <div id="_auto27"></div> $$ \begin{equation} V_{\text{eff}}(r) = V(r) + \frac{L^2}{2\mu r^2} \label{_auto27} \tag{40} \end{equation} $$ Write out the final differential equation for the radial degrees of freedom when we specify that $V(r)=-\alpha/r$. Plot the effective potential. You can choose values for $\alpha$ and $L$ and discuss (see Taylor section 8.4 and example 8.2) the physics of the system for two energies, one larger than zero and one smaller than zero. This is similar to what you did in the first midterm, except that the potential is different. We insert now the explicit potential form $V(r)=-\alpha/r$. This gives us the following equation of motion $$ \mu \ddot{r}=-\frac{dV_{\mathrm{eff}}(r)}{dr}=-\frac{d(-\alpha/r)}{dr}+\frac{L^2}{\mu r^3}=-\frac{\alpha}{r^2}+\frac{L^2}{\mu r^3}. $$ The following code plots this effective potential for a simple choice of parameters, with a standard gravitational potential $-\alpha/r$. Here we have chosen $L=m=\alpha=1$. # Common imports import numpy as np from math import * import matplotlib.pyplot as plt Deltax = 0.01 #set up arrays xinitial = 0.3 xfinal = 5.0 alpha = 1.0 # spring constant m = 1.0 # mass, you can change these AngMom = 1.0 # The angular momentum n = ceil((xfinal-xinitial)/Deltax) x = np.zeros(n) for i in range(n): x[i] = xinitial+i*Deltax V = np.zeros(n) V = -alpha/x+0.5*AngMom*AngMom/(m*x*x) # Plot potential fig, ax = plt.subplots() ax.set_xlabel('r[m]') ax.set_ylabel('V[J]') ax.plot(x, V) fig.tight_layout() plt.show() If we select a potential energy below zero (and not necessarily one which corresponds to the minimum point), the object will oscillate between two values of $r$, a value $r_{\mathrm{min}}$ and a value $r_{\mathrm{max}}$. We can assume that for example the kinetic energy is zero at these two points. The object will thus oscillate back and forth between these two points. As we will see in connection with the solution of the equations of motion, this case corresponds to elliptical orbits. If we select $r$ equal to the minimum of the potential and use initial conditions for the velocity that correspond to circular motion, the object will have a constant value of $r$ given by the value at the minimum and the orbit is a circle. If we select a potential energy larger than zero, then, since the kinetic energy is always larger or equal to zero, the object will move away from the origin. See also the discussion in Taylor, sections 8.4-8.6. ### Exercise: Harmonic oscillator again Consider a particle of mass $m$ in a $2$-dimensional harmonic oscillator with potential $$ V(r)=\frac{1}{2}kr^2=\frac{1}{2}k(x^2+y^2). $$ We assume the orbit has a final non-zero angular momentum $L$. The effective potential looks like that of a harmonic oscillator for large $r$, but for small $r$, the centrifugal potential repels the particle from the origin. The combination of the two potentials has a minimum for at some radius $r_{\rm min}$. Set up the effective potential and plot it. Find $r_{\rm min}$ and $\dot{\phi}$. Show that the latter is given by $\dot{\phi}=\sqrt{k/m}$. At $r_{\rm min}$ the particle does not accelerate and $r$ stays constant and the motion is circular. With fixed $k$ and $m$, which parameter can we adjust to change the value of $r$ at $r_{\rm min}$? We consider the effective potential. The radius of a circular orbit is at the minimum of the potential (where the effective force is zero). The potential is plotted here with the parameters $k=m=1.0$ and $L=1.0$. # Common imports import numpy as np from math import * import matplotlib.pyplot as plt Deltax = 0.01 #set up arrays xinitial = 0.5 xfinal = 3.0 k = 1.0 # spring constant m = 1.0 # mass, you can change these AngMom = 1.0 # The angular momentum n = ceil((xfinal-xinitial)/Deltax) x = np.zeros(n) for i in range(n): x[i] = xinitial+i*Deltax V = np.zeros(n) V = 0.5*k*x*x+0.5*AngMom*AngMom/(m*x*x) # Plot potential fig, ax = plt.subplots() ax.set_xlabel('r[m]') ax.set_ylabel('V[J]') ax.plot(x, V) fig.tight_layout() plt.show() We have an effective potential $$ \begin{eqnarray*} V_{\rm eff}&=&\frac{1}{2}kr^2+\frac{L^2}{2mr^2} \end{eqnarray*} $$ The effective potential looks like that of a harmonic oscillator for large $r$, but for small $r$, the centrifugal potential repels the particle from the origin. The combination of the two potentials has a minimum for at some radius $r_{\rm min}$. $$ \begin{eqnarray*} 0&=&kr_{\rm min}-\frac{L^2}{mr_{\rm min}^3},\\ r_{\rm min}&=&\left(\frac{L^2}{mk}\right)^{1/4},\\ \dot{\theta}&=&\frac{L}{mr_{\rm min}^2}=\sqrt{k/m}. \end{eqnarray*} $$ For particles at $r_{\rm min}$ with $\dot{r}=0$, the particle does not accelerate and $r$ stays constant, i.e. a circular orbit. The radius of the circular orbit can be adjusted by changing the angular momentum $L$. For the above parameters this minimum is at $r_{\rm min}=1$. Now consider small vibrations about $r_{\rm min}$. The effective spring constant is the curvature of the effective potential. Use the curvature at $r_{\rm min}$ to find the effective spring constant (hint, look at exercise 4 in homework 6) $k_{\mathrm{eff}}$. Show also that $\omega=\sqrt{k_{\mathrm{eff}}/m}=2\dot{\phi}$ $$ \begin{eqnarray*} k_{\rm eff}&=&\left.\frac{d^2}{dr^2}V_{\rm eff}(r)\right|_{r=r_{\rm min}}=k+\frac{3L^2}{mr_{\rm min}^4}\\ &=&4k,\\ \omega&=&\sqrt{k_{\rm eff}/m}=2\sqrt{k/m}=2\dot{\theta}. \end{eqnarray*} $$ Because the radius oscillates with twice the angular frequency, the orbit has two places where $r$ reaches a minimum in one cycle. This differs from the inverse-square force where there is one minimum in an orbit. One can show that the orbit for the harmonic oscillator is also elliptical, but in this case the center of the potential is at the center of the ellipse, not at one of the foci. The solution to the equations of motion in Cartesian coordinates is simple. The $x$ and $y$ equations of motion separate, and we have $\ddot{x}=-kx/m$ and $\ddot{y}=-ky/m$. The harmonic oscillator is indeed a system where the degrees of freedom separate and we can find analytical solutions. Define a natural frequency $\omega_0=\sqrt{k/m}$ and show that (where $A$, $B$, $C$ and $D$ are arbitrary constants defined by the initial conditions) $$ \begin{eqnarray*} x&=&A\cos\omega_0 t+B\sin\omega_0 t,\\ y&=&C\cos\omega_0 t+D\sin\omega_0 t. \end{eqnarray*} $$ The solution is also simple to write down exactly in Cartesian coordinates. The $x$ and $y$ equations of motion separate, $$ \begin{eqnarray*} \ddot{x}&=&-kx,\\ \ddot{y}&=&-ky. \end{eqnarray*} $$ We know from our studies of the harmonic oscillator that the general solution can be expressed as $$ \begin{eqnarray*} x&=&A\cos\omega_0 t+B\sin\omega_0 t,\\ y&=&C\cos\omega_0 t+D\sin\omega_0 t. \end{eqnarray*} $$ With the solutions for $x$ and $y$, and $r^2=x^2+y^2$ and the definitions $\alpha=\frac{A^2+B^2+C^2+D^2}{2}$, $\beta=\frac{A^2-B^2+C^2-D^2}{2}$ and $\gamma=AB+CD$, show that $$ r^2=\alpha+(\beta^2+\gamma^2)^{1/2}\cos(2\omega_0 t-\delta), $$ with $$ \delta=\arctan(\gamma/\beta). $$ We start with $r^2 & = x^2+y^2$ and square the above analytical solutions and after some **exciting algebraic manipulations** we arrive at <!-- Equation labels as ordinary links --> <div id="_auto28"></div> $$ \begin{equation} r^2 = x^2+y^2 \label{_auto28} \tag{41} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto29"></div> $$ \begin{equation} = \left( A\cos\omega_0 t+B\sin\omega_0 t\right) ^2 + \left( C\cos\omega_0 t+D\sin\omega_0 t\right) ^2 \label{_auto29} \tag{42} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto30"></div> $$ \begin{equation} = A^2\cos^2\omega_0 t+B^2\sin^2\omega_0 t + 2AB\sin\omega_0 t \cos\omega_0 t + C^2\cos^2\omega_0 t+D^2\sin^2\omega_0 t + 2CD\sin\omega_0 t \cos\omega_0 t \label{_auto30} \tag{43} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto31"></div> $$ \begin{equation} = (A^2+C^2)\cos^2\omega_0 t + (B^2+D^2)\sin^2\omega_0 t + 2(AC + BD)\sin\omega_0 t \cos\omega_0 t \label{_auto31} \tag{44} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto32"></div> $$ \begin{equation} = (B^2+D^2) + (A^2+C^2-B^2-D^2)\cos^2\omega_0 t + 2(AC + BD)2\sin2\omega_0 t \label{_auto32} \tag{45} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto33"></div> $$ \begin{equation} = (B^2+D^2) + (A^2+C^2-B^2-D^2)\frac{1+\cos{2\omega_0 t}}{2} + 2(AC + BD)\frac{1}{2}\sin2\omega_0 t \label{_auto33} \tag{46} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto34"></div> $$ \begin{equation} = \frac{2B^2+2D^2+A^2+C^2-B^2-D^2}{2} + (A^2+C^2-B^2-D^2)\frac{\cos{2\omega_0 t}}{2} + (AC + BD)\sin2\omega_0 t \label{_auto34} \tag{47} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto35"></div> $$ \begin{equation} = \frac{B^2+D^2+A^2+C^2}{2} + \frac{A^2+C^2-B^2-D^2}{2}\cos{2\omega_0 t} + (AC + BD)\sin2\omega_0 t \label{_auto35} \tag{48} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto36"></div> $$ \begin{equation} = \alpha + \beta\cos{2\omega_0 t} + \gamma\sin2\omega_0 t \label{_auto36} \tag{49} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto37"></div> $$ \begin{equation} = \alpha + \sqrt{\beta^2+\gamma^2}\left( \frac{\beta}{\sqrt{\beta^2+\gamma^2}}\cos{2\omega_0 t} + \frac{\gamma}{\sqrt{\beta^2+\gamma^2}}\sin2\omega_0 t\right) \label{_auto37} \tag{50} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto38"></div> $$ \begin{equation} = \alpha + \sqrt{\beta^2+\gamma^2}\left( \cos{\delta}\cos{2\omega_0 t} + \sin{\delta}\sin2\omega_0 t\right) \label{_auto38} \tag{51} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto39"></div> $$ \begin{equation} = \alpha + \sqrt{\beta^2+\gamma^2}\cos{\left( 2\omega_0 t - \delta\right) }, \label{_auto39} \tag{52} \end{equation} $$ which is what we wanted to show. ### Exercise: Numerical Solution of the Harmonic Oscillator Using the code we developed in homeworks 5 and/or 6 for the Earth-Sun system, we can solve the above harmonic oscillator problem in two dimensions using our code from this homework. We need however to change the acceleration from the gravitational force to the one given by the harmonic oscillator potential. * 3a (20pt) Use for example the code in the exercise set to set up the acceleration and use the initial conditions fixed by for example $r_{\rm min}$ from exercise 2. Which value should the initial velocity take if you place yourself at $r_{\rm min}$ and you require a circular motion? Hint: see the first midterm, part 2. There you used the centripetal acceleration. Instead of solving the equations in the cartesian frame we will now rewrite the above code in terms of the radial degrees of freedom only. Our differential equation is now $$ \mu \ddot{r}=-\frac{dV(r)}{dr}+\mu\dot{\phi}^2, $$ and $$ \dot{\phi}=\frac{L}{\mu r^2}. $$ * 3b (20pt) We will use $r_{\rm min}$ to fix a value of $L$, as seen in exercise 2. This fixes also $\dot{\phi}$. Write a code which now implements the radial equation for $r$ using the same $r_{\rm min}$ as you did in 3a. Compare the results with those from 3a with the same initial conditions. Do they agree? Use only one set of initial conditions. The code here finds the solution for $x$ and $y$ using the code we developed in homework 5 and 6 and the midterm. Note that this code is tailored to run in Cartesian coordinates. There is thus no angular momentum dependent term. Here we have chosen initial conditions that correspond to the minimum of the effective potential $r_{\mathrm{min}}$. We have chosen $x_0=r_{\mathrm{min}}$ and $y_0=0$. Similarly, we use the centripetal acceleration to determine the initial velocity so that we have a circular motion (see back to the last question of the midterm). This means that we set the centripetal acceleration $v^2/r$ equal to the force from the harmonic oscillator $-k\boldsymbol{r}$. Taking the magnitude of $\boldsymbol{r}$ we have then $v^2/r=k/mr$, which gives $v=\pm\omega_0r$. Since the code here solves the equations of motion in cartesian coordinates and the harmonic oscillator potential leads to forces in the $x$- and $y$-directions that are decoupled, we have to select the initial velocities and positions so that we don't get that for example $y(t)=0$. We set $x_0$ to be different from zero and $v_{y0}$ to be different from zero. # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt import os # Where to save the figures and data files PROJECT_ROOT_DIR = "Results" FIGURE_ID = "Results/FigureFiles" DATA_ID = "DataFiles/" if not os.path.exists(PROJECT_ROOT_DIR): os.mkdir(PROJECT_ROOT_DIR) if not os.path.exists(FIGURE_ID): os.makedirs(FIGURE_ID) if not os.path.exists(DATA_ID): os.makedirs(DATA_ID) def image_path(fig_id): return os.path.join(FIGURE_ID, fig_id) def data_path(dat_id): return os.path.join(DATA_ID, dat_id) def save_fig(fig_id): plt.savefig(image_path(fig_id) + ".png", format='png') DeltaT = 0.001 #set up arrays tfinal = 10.0 n = ceil(tfinal/DeltaT) # set up arrays t = np.zeros(n) v = np.zeros((n,2)) r = np.zeros((n,2)) radius = np.zeros(n) # Constants of the model k = 1.0 # spring constant m = 1.0 # mass, you can change these omega02 = k/m # Frequency AngMom = 1.0 # The angular momentum # Potential minimum rmin = (AngMom*AngMom/k/m)**0.25 # Initial conditions as compact 2-dimensional arrays, x0=rmin and y0 = 0 x0 = rmin; y0= 0.0 r0 = np.array([x0,y0]) vy0 = sqrt(omega02)*rmin; vx0 = 0.0 v0 = np.array([vx0,vy0]) r[0] = r0 v[0] = v0 # Start integrating using the Velocity-Verlet method for i in range(n-1): # Set up the acceleration a = -r[i]*omega02 # update velocity, time and position using the Velocity-Verlet method r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a anew = -r[i+1]*omega02 v[i+1] = v[i] + 0.5*DeltaT*(a+anew) t[i+1] = t[i] + DeltaT # Plot position as function of time radius = np.sqrt(r[:,0]**2+r[:,1]**2) fig, ax = plt.subplots(3,1) ax[0].set_xlabel('time') ax[0].set_ylabel('radius squared') ax[0].plot(t,r[:,0]**2+r[:,1]**2) ax[1].set_xlabel('time') ax[1].set_ylabel('x position') ax[1].plot(t,r[:,0]) ax[2].set_xlabel('time') ax[2].set_ylabel('y position') ax[2].plot(t,r[:,1]) fig.tight_layout() save_fig("2DimHOVV") plt.show() We see that the radius (to within a given error), we obtain a constant radius. The following code shows first how we can solve this problem using the radial degrees of freedom only. Here we need to add the explicit centrifugal barrier. Note that the variable $r$ depends only on time. There is no $x$ and $y$ directions since we have transformed the equations to polar coordinates. DeltaT = 0.01 #set up arrays tfinal = 10.0 n = ceil(tfinal/DeltaT) # set up arrays for t, v and r t = np.zeros(n) v = np.zeros(n) r = np.zeros(n) E = np.zeros(n) # Constants of the model AngMom = 1.0 # The angular momentum m = 1.0 k = 1.0 omega02 = k/m c1 = AngMom*AngMom/(m*m) c2 = AngMom*AngMom/m rmin = (AngMom*AngMom/k/m)**0.25 # Initial conditions r0 = rmin v0 = 0.0 r[0] = r0 v[0] = v0 E[0] = 0.5*m*v0*v0+0.5*k*r0*r0+0.5*c2/(r0*r0) # Start integrating using the Velocity-Verlet method for i in range(n-1): # Set up acceleration a = -r[i]*omega02+c1/(r[i]**3) # update velocity, time and position using the Velocity-Verlet method r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a anew = -r[i+1]*omega02+c1/(r[i+1]**3) v[i+1] = v[i] + 0.5*DeltaT*(a+anew) t[i+1] = t[i] + DeltaT E[i+1] = 0.5*m*v[i+1]*v[i+1]+0.5*k*r[i+1]*r[i+1]+0.5*c2/(r[i+1]*r[i+1]) # Plot position as function of time fig, ax = plt.subplots(2,1) ax[0].set_xlabel('time') ax[0].set_ylabel('radius') ax[0].plot(t,r) ax[1].set_xlabel('time') ax[1].set_ylabel('Energy') ax[1].plot(t,E) save_fig("RadialHOVV") plt.show() ### Exercise: Equations for an ellipse Consider an ellipse defined by the sum of the distances from the two foci being $2D$, which expressed in a Cartesian coordinates with the middle of the ellipse being at the origin becomes $$ \sqrt{(x-a)^2+y^2}+\sqrt{(x+a)^2+y^2}=2D. $$ Here the two foci are at $(a,0)$ and $(-a,0)$. Show that this form is can be written as $$ \frac{x^2}{D^2}+\frac{y^2}{D^2-a^2}=1. $$ We start by squaring the two sides and, again, after some **exciting algebraic manipulations** we arrive at $$ \sqrt{(x-a)^2+y^2}+\sqrt{(x+a)^2+y^2} =2D \\ (x-a)^2 + y^2 + (x+a)^2 + y^2 + 2\sqrt{(x-a)^2 + y^2}\sqrt{(x+a)^2+y^2} = 4D^2 \\ 2y^2 + 2x^2 + 2a^2 + 2\sqrt{(x-a)^2(x+a)^2 + y^4 + y^2[(x-a)^2+(x+a)^2]} = 4D^2 \\ y^2 + x^2 + a^2 + \sqrt{(x^2-a^2)^2 + y^4 + y^2(2x^2+2a^2)} = 2D^2 \\ \sqrt{(x^2-a^2)^2 + y^4 + y^2(2x^2+2a^2)} = 2D^2 -( y^2 + x^2 + a^2 ) \\ (x^2-a^2)^2 + y^4 + y^2(2x^2+2a^2) = 4D^4 + y^4 + x^4 + a^4 - 4D^2( y^2 + x^2 + a^2 ) + 2(y^2x^2+y^2a^2+x^2a^2) \\ x^4-2x^2a^2+a^4 + y^4 + 2y^2x^2+2y^2a^2 = 4D^4 + y^4 + x^4 + a^4 - 4D^2y^2 -4D^2 x^2 -4D^2 a^2 + 2y^2x^2+2y^2a^2+2x^2a^2 \\ 4D^4 - 4D^2y^2 -4D^2 x^2 -4D^2 a^2 +4x^2a^2 = 0 \\ D^4 - D^2y^2 -D^2 x^2 -D^2 a^2 +x^2a^2 = 0 \\ D^2(D^2-a^2) - x^2(D^2-a^2) = D^2y^2 \\ D^2 - x^2 = \frac{D^2y^2}{D^2-a^2} \\ 1 - \frac{x^2}{D^2} = \frac{y^2}{D^2-a^2} \\ \frac{x^2}{D^2} + \frac{y^2}{D^2-a^2} = 1, $$ where the last line is indeed the equation for an ellipse. ### Exercise: Attractive Potential Consider a particle in an attractive potential $$ U(r)=-\alpha/r. $$ The quantity $r$ is the absolute value of the relative position. We will use the reduced mass $\mu$ and the angular momentum $L$, as discussed during the lectures. With the transformation of a two-body problem to the center-of-mass frame, the actual equations look like an *effective* one-body problem. The energy of the system is $E$ and the minimum of the effective potential is $r_{\rm min}$. The analytical solution to the radial equation of motion is $$ r(\phi) = \frac{1}{\frac{\mu\alpha}{L^2}+A\cos{(\phi)}}. $$ Find the value of $A$. Hint: Use the fact that at $r_{\rm min}$ there is no radial kinetic energy and $E=-\alpha/r_{\rm min}+L^2/2mr_{\rm min}^2$. At $r_{\mathrm{min}}$ and $r_{\mathrm{max}}$ , all the kinetic energy is stored in the velocity in the direction perpendicular to $r$ since the radial velocity is set to zero . We can calculate using angular momentum and from there, find 𝐴 in terms of the energy $E$ which is constant. But first, we need to find $r_{\mathrm{min}}$ from the conservation of energy (noting that the radial velocity $\ddot{r}$ at the mininum is zero): $$ E = U(r) + \frac{1}{2} \mu(\ddot{r}^2 + (r\ddot{\phi})^2) \\ E = \frac{-\alpha}{r_{\min}} + \frac{1}{2} \mu\left( \frac{L}{\mu r_{\min}}\right) ^2 \\ E r_{\min}^2 - \frac{1}{2}\mu\left( \frac{L}{\mu}\right) ^2 + \alpha r_{\min} = 0 \\ r_{\min}^2 + \frac{\alpha}{E} r_{\min} - \frac{L^2}{2E\mu} = 0 \\ r_{\min} = - \frac{\alpha}{2E} \pm \frac{1}{2} \sqrt{\frac{\alpha^2}{E^2} + 2\frac{L^2}{E\mu}} $$ Since we're looking for the minimum, the ± sign must be negative (then 𝑟min will not be negative since 𝐸<0 ). Therefore, we have $$ \frac{1}{\frac{\mu\alpha}{L^2}+A} = -\frac{\alpha}{2E} - \frac{1}{2} \sqrt{\frac{\alpha^2}{E^2} + 2\frac{L^2}{E\mu}} \\ A = - \frac{\mu\alpha}{L^2} - \frac{2E}{\alpha + \sqrt{\alpha^2 + 2\frac{L^2E}{\mu}}} $$ ### Exercise: Inverse-square force Consider again the same effective potential as in the previous exercise. This leads to an attractive inverse-square-law force, $F=-\alpha/r^2$. Consider a particle of mass $m$ with angular momentum $L$. Taylor sections 8.4-8.7 are relevant background material. See also the harmonic oscillator potential from hw8. The equation of motion for the radial degrees of freedom is (see also hw8) in the center-of-mass frame in two dimensions with $x=r\cos{(\phi)}$ and $y=r\sin{(\phi)}$ and $r\in [0,\infty)$, $\phi\in [0,2\pi]$ and $r=\sqrt{x^2+y^2}$ are given by $$ \ddot{r}=-\frac{1}{m}\frac{dV(r)}{dr}+r\dot{\phi}^2, $$ and $$ \dot{\phi}=\frac{L}{m r^2}. $$ Here $V(r)$ is any central force which depends only on the relative coordinate. Find the radius of a circular orbit by solving for the position of the minimum of the effective potential. <!-- Equation labels as ordinary links --> <div id="_auto40"></div> $$ \begin{equation} \frac{1}{m}\frac{dV(r)}{dr} = r\dot{\phi}^2 \label{_auto40} \tag{53} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto41"></div> $$ \begin{equation} \frac{1}{m}\left( -\frac{-\alpha}{r^2}\right) = r \frac{L^2}{m^2r^4} \label{_auto41} \tag{54} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto42"></div> $$ \begin{equation} \frac{\alpha}{mr^2} = \frac{L^2}{m^2r^3} \label{_auto42} \tag{55} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto43"></div> $$ \begin{equation} r = \frac{L^2}{m\alpha} \label{_auto43} \tag{56} \end{equation} $$ At the minimum, the radial velocity is zero and it is only the [centripetal velocity](https://en.wikipedia.org/wiki/Centripetal_force) which is nonzero. This implies that $\ddot{r}=0$. What is the angular frequency, $\dot{\theta}$, of the orbit? Solve this by setting $\ddot{r}=0=F/m+\dot{\theta}^2r$. <!-- Equation labels as ordinary links --> <div id="_auto44"></div> $$ \begin{equation} \dot{\theta}^2 r = - \frac{F}{m} \label{_auto44} \tag{57} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto45"></div> $$ \begin{equation} \dot{\theta}^2 r = - \frac{-\frac{\alpha}{r^2}}{m} \label{_auto45} \tag{58} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto46"></div> $$ \begin{equation} \dot{\theta}^2 = \frac{\alpha}{mr^3} \label{_auto46} \tag{59} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto47"></div> $$ \begin{equation} \dot{\theta} = \pm \sqrt{\frac{\alpha}{mr^3}} \label{_auto47} \tag{60} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto48"></div> $$ \begin{equation} \dot{\theta} = \pm \sqrt{\frac{\alpha}{m\frac{L^6}{m^3\alpha^3}}} \label{_auto48} \tag{61} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto49"></div> $$ \begin{equation} \dot{\theta} = \pm \sqrt{\frac{\alpha^4m^2}{L^6}} \label{_auto49} \tag{62} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto50"></div> $$ \begin{equation} \dot{\theta} = \pm \frac{\alpha^2m}{L^3} \label{_auto50} \tag{63} \end{equation} $$ Find the effective spring constant for the particle at the minimum. We have shown in class that from the taylor expansion, we have $$ k = \frac{d^2V_{\text{eff}}}{dr^2} $$ Therefore, all we have to do is find the second derivative of $V_{\text{eff}}$ around the minimum point of $V_{\text{eff}}$ where $\dot{r} = \ddot{r} = 0$. <!-- Equation labels as ordinary links --> <div id="_auto51"></div> $$ \begin{equation} k = \frac{d^2V_{\text{eff}}}{dr^2} \label{_auto51} \tag{64} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto52"></div> $$ \begin{equation} = \frac{d^2\left( -\frac{\alpha}{r} + \frac{1}{2} \frac{L^2}{mr^2}\right) }{dr^2} \label{_auto52} \tag{65} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto53"></div> $$ \begin{equation} = -\frac{2\alpha}{r^3} + \frac{3L^2}{mr^4} \label{_auto53} \tag{66} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto54"></div> $$ \begin{equation} = -\frac{2\alpha}{\frac{L^6}{m^3\alpha^3}} + \frac{3L^2}{m\frac{L^8}{m^4\alpha^4}} \label{_auto54} \tag{67} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto55"></div> $$ \begin{equation} = -\frac{2m^3\alpha^4}{L^6} + \frac{3m^3\alpha^4}{L^6} \label{_auto55} \tag{68} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto56"></div> $$ \begin{equation} = \frac{m^3\alpha^4}{L^6} \label{_auto56} \tag{69} \end{equation} $$ What is the angular frequency for small vibrations about the minimum? How does this compare with the answer to (3b)? For small deviations $\delta r$ of $r$, $$ m\frac{d^2\left( \delta r \right) }{dt^2} = -k \delta r $$ The solution of this differential equation is of the form $$ \delta r = A \cos(\omega t + \phi) $$ where <!-- Equation labels as ordinary links --> <div id="_auto57"></div> $$ \begin{equation} \omega = \sqrt{\frac{k}{m}} \label{_auto57} \tag{70} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto58"></div> $$ \begin{equation} = \sqrt{\frac{m^2\alpha^4}{L^6}} \label{_auto58} \tag{71} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto59"></div> $$ \begin{equation} = \frac{m\alpha^2}{L^3} \label{_auto59} \tag{72} \end{equation} $$ This is in fact equal to the expression for $\dot{\theta}$. This means that small perturbations oscillate in sync with the orbit and this traces out an ellipse with a very small eccentricity, a very nice physical result. ### Exercise: Inverse-square force again Consider again a particle of mass $m$ in the same attractive potential, $U(r)=-\alpha/r$, with angular momentum $L$ with just the right energy so that $$ A=m\alpha/L^2 $$ where $A$ comes from the expression $$ r=\frac{1}{(m\alpha/L^2)+A\cos{(\phi)}}. $$ The trajectory can then be rewritten as $$ r=\frac{2r_0}{1+\cos\theta},~~~r_0=\frac{L^2}{2m\alpha}. $$ Show that for this case the total energy $E$ approaches zero. <!-- Equation labels as ordinary links --> <div id="_auto60"></div> $$ \begin{equation} E = - \frac{\alpha}{r} + \frac{1}{2} m \left( (\dot{\theta}r)^2+\dot{r}^2\right) \label{_auto60} \tag{73} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto61"></div> $$ \begin{equation} = - \frac{\alpha}{r} + \frac{1}{2} m \left[ \left( \frac{L}{mr^2}r\right) ^2+\left( \frac{dr}{d\theta}\dot{\theta}\right) ^2\right] \label{_auto61} \tag{74} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto62"></div> $$ \begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) + \frac{1}{2} m \left[ \left( \frac{L(1+\cos\theta)}{2mr_0}\right) ^2+\left( 2r_0\frac{-1}{(1+\cos\theta)^2}(-\sin\theta)\frac{L}{mr^2}\right) ^2\right] \label{_auto62} \tag{75} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto63"></div> $$ \begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) + \frac{1}{2} m \left[ \left( \frac{L(1+\cos\theta)}{2mr_0}\right) ^2+\left( 2r_0\frac{-1}{(1+\cos\theta)^2}(-\sin\theta)\frac{L(1+\cos\theta)^2}{4mr_0^2}\right) ^2\right] \label{_auto63} \tag{76} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto64"></div> $$ \begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) + \frac{1}{2} m \left[ \left( \frac{L(1+\cos\theta)}{2mr_0}\right) ^2+\left( \sin\theta\frac{L}{2mr_0}\right) ^2\right] \label{_auto64} \tag{77} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto65"></div> $$ \begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) + \frac{1}{2} m \left[ \left( \frac{L(1+\cos\theta)}{2mr_0}\right) ^2+\left( \sin\theta\frac{L}{2mr_0}\right) ^2\right] \label{_auto65} \tag{78} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto66"></div> $$ \begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) + \frac{1}{2} m \frac{L^2}{4m^2r_0^2} \left[ \left( 1+\cos\theta\right) ^2+\left( \sin\theta\right) ^2\right] \label{_auto66} \tag{79} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto67"></div> $$ \begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) + \frac{1}{2} \frac{L^2}{4mr_0^2} \left( 1 + \cos^2\theta + 2\cos \theta + \sin^2\theta\right) \label{_auto67} \tag{80} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto68"></div> $$ \begin{equation} = - \frac{\alpha}{2r_0}(1+\cos\theta) + \frac{1}{2} \frac{L^2}{4mr_0^2} \left( 2 + 2\cos \theta \right) \label{_auto68} \tag{81} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto69"></div> $$ \begin{equation} = (1+\cos\theta) \left( - \frac{\alpha}{2r_0} + \frac{L^2}{4mr_0^2}\right) \label{_auto69} \tag{82} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto70"></div> $$ \begin{equation} = (1+\cos\theta) \left( - \frac{\alpha}{2\frac{L^2}{2m\alpha}} + \frac{L^2}{4m\frac{L^4}{4m^2\alpha^2}}\right) \label{_auto70} \tag{83} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto71"></div> $$ \begin{equation} = (1+\cos\theta) \left( - \frac{m\alpha^2}{L^2} + \frac{m\alpha^2}{L^2}\right) \label{_auto71} \tag{84} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto72"></div> $$ \begin{equation} = 0 \label{_auto72} \tag{85} \end{equation} $$ With zero energy $E=0$, write this trajectory in a more recognizable parabolic form, that is express $x_0$ and $R$ in terms of $r_0$ using $$ x=x_0-\frac{y^2}{R}. $$ We have that <!-- Equation labels as ordinary links --> <div id="_auto73"></div> $$ \begin{equation} x = r \cos\theta \label{_auto73} \tag{86} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto74"></div> $$ \begin{equation} y = r \sin \theta. \label{_auto74} \tag{87} \end{equation} $$ Using the general solution with eccintricity $\epsilon=1$, we have $$ r(\theta)=\frac{c}{1+\cos\theta}, $$ and multiplying both sides with $1+\cos\theta$ and using that $x=r\cos\theta$, $$ r = c -x, $$ and using that $r^2=x^2+y^2$, we square both sides $$ r^2 = x^2+y^2=c^2 +x^2-2cx, $$ leading to $$ y^2=c^2-2cx, $$ and using that we defined $$ c=2r_0=\frac{L^2}{m\alpha}, $$ we divide by $2c$ and we get the final answer $$ x = r_0 - \frac{y^2}{4r_0} $$ ### Exercise: Parabolic and hyperbolic orbits The solution to the radial function for an inverse-square-law force, see for example Taylor equation (8.59) or the equation above, is $$ r(\phi) = \frac{c}{1+\epsilon\cos{(\phi)}}. $$ For $\epsilon=1$ (or the energy $E=0$) the orbit reduces to a parabola as we saw in the previous exercise, while for $\epsilon > 1$ (or energy positive) the orbit becomes a hyperbola. The equation for a hyperbola in Cartesian coordinates is $$ \frac{(x-\delta)^2}{\alpha^2}-\frac{y^2}{\beta^2}=1. $$ For a hyperbola, identify the constants $\alpha$, $\beta$ and $\delta$ in terms of the constants $c$ and $\epsilon$ for $r(\phi)$. <!-- Equation labels as ordinary links --> <div id="_auto75"></div> $$ \begin{equation} x = r\cos\phi \label{_auto75} \tag{88} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto76"></div> $$ \begin{equation} = \frac{c\cos\phi}{1+\epsilon\cos\phi} \label{_auto76} \tag{89} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto77"></div> $$ \begin{equation} y = r\sin\phi \label{_auto77} \tag{90} \end{equation} $$ <!-- Equation labels as ordinary links --> <div id="_auto78"></div> $$ \begin{equation} = \frac{c\sin\phi}{1+\epsilon\cos\phi} \label{_auto78} \tag{91} \end{equation} $$ Here $\epsilon>1$. We use our equation for $r$, multiply with the denominator $1+\epsilon\cos\phi$ on both sides and have $$ r(1+\epsilon\cos\phi)=c, $$ use $x=r\cos\phi$ and square and use that $r^2=x^2+y^2$ and we have $$ r^2=x^2+y^2=c^2+\epsilon^2x^2-2cx\epsilon, $$ and reorder $$ x^2(\epsilon^2-1)-y^2-2cx\epsilon= -c^2. $$ We complete the square in $x$ by adding and subtracting on both sides $\epsilon^2c^2/(\epsilon^2-1)$ and we obtain $$ (\epsilon^2-1)(x-\delta)^2-y^2= -c^2+\frac{\epsilon^2c^2}{\epsilon^2-1}. $$ Here we have defined $$ \delta = \frac{c\epsilon}{\epsilon^2-1}, $$ and introducing the constants $$ \alpha = \frac{c}{\epsilon^2-1}, $$ and $$ \beta = \frac{c}{\sqrt{\epsilon^2-1}}, $$ we can rewrite the above equation as $$ \frac{(x-\delta)^2}{\alpha^2}-\frac{y^2}{\beta^2}=1, $$ which is nothing but the equation for a hyperbola. ### Exercise: Testing orbit types In this exercise we can use the program for $r(\phi)$ we developed in hw8. We will use an inverse-square-law force as in the previous four exercises. The aim is to see that the orbits we get for $E<0$ become ellipses (or circles), parabola for $E=0$ and hyperbola for $E>0$. An example code is shown here. Here we have defined the constants $L=m=\alpha=1$. Feel free to set new values. **You need also to set the initial conditions** in order to study the different types of orbits. It may be useful to plot the potential here and find the values for the initial conditions that fit $E<0$, $E=0$ and $E>0$. # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt # Simple Gravitational Force -alpha/r DeltaT = 0.01 #set up arrays tfinal = 100.0 n = ceil(tfinal/DeltaT) # set up arrays for t, v and r t = np.zeros(n) v = np.zeros(n) r = np.zeros(n) # Constants of the model, setting all variables to one for simplicity alpha = 1.0 AngMom = 1.0 # The angular momentum m = 1.0 # scale mass to one c1 = AngMom*AngMom/(m*m) c2 = AngMom*AngMom/m # You need to specify the initial conditions # Here we have chosen the conditions which lead to circular orbit and thereby a constant r r0 = (AngMom*AngMom/m/alpha) v0 = 0.0 r[0] = r0 v[0] = v0 # Start integrating using the Velocity-Verlet method for i in range(n-1): # Set up acceleration a = -alpha/(r[i]**2)+c1/(r[i]**3) # update velocity, time and position using the Velocity-Verlet method r[i+1] = r[i] + DeltaT*v[i]+0.5*(DeltaT**2)*a anew = -alpha/(r[i+1]**2)+c1/(r[i+1]**3) v[i+1] = v[i] + 0.5*DeltaT*(a+anew) t[i+1] = t[i] + DeltaT # Plot position as function of time fig, ax = plt.subplots(2,1) ax[0].set_xlabel('time') ax[0].set_ylabel('radius') ax[0].plot(t,r) ax[1].set_xlabel('time') ax[1].set_ylabel('Velocity') ax[1].plot(t,v) plt.show() Run your code and study and discuss the situations where you have elliptical, parabolic and hyperbolic orbits. Discuss the physics of these cases. The results from the four previous exercises 4 may be useful here. In the code here we have chosen initial conditions which correspond to circular motion. This corresponds to $$ r_{\mathrm{min}} = \frac{L^2}{m\alpha}. $$ Note well that the velocity is now the radial velocity. If we want to study the angular velocity we would need to add the equations for this quantity. The solution to exercises 1-4 give you the minimum $r$ values needed to find the elliptical, parabolic and hyperbolic orbits. For elliptical orbits you should have $\frac{L^2}{2m\alpha} < r_{\mathrm{min}} <\frac{L^2}{m\alpha}$. For parabolic orbits $r_{\mathrm{min}} =\frac{L^2}{m\alpha}$ and for hyperbolic orbits we have $0<r_{\mathrm{min}} <\frac{L^2}{m\alpha}$. Try out these different initial conditions in order to test these different types of motion. ### Exercise: New reference frame Show that if one transforms to a reference frame where the total momentum is zero, $\boldsymbol{p}_1=-\boldsymbol{p}_2$, that the relative momentum $\boldsymbol{q}$ corresponds to either $\boldsymbol{p}_1$ or $-\boldsymbol{p}_2$. This means that in this frame the magnitude of $\boldsymbol{q}$ is one half the magnitude of $\boldsymbol{p}_1-\boldsymbol{p}_2$. ### Exercise: Center of mass and relative coordinates Given the center of mass and relative coordinates $\boldsymbol{R}$ and $\boldsymbol{r}$, respectively, for particles of mass $m_1$ and $m_2$, find the coordinates $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$ in terms of the masses, $\boldsymbol{R}$ and $\boldsymbol{r}$. ### Exercise: Two-body problems Consider a particle of mass $m$ moving in a potential $$ V(r)=\alpha\ln(r/\alpha), $$ where $\alpha$ is a constant. * (a) If the particle is moving in a circular orbit of radius $R$, find the angular frequency $\dot{\theta}$. Solve this by setting $F=-m\dot{\theta}^2r$ (force and acceleration point inward). * (b) Express the angular momentum $L$ in terms of the constant $\alpha$, the mass $m$ and the radius $R$. Also express $R$ in terms of $L$, $\alpha$ and $m$. * (c) Sketch the effective radial potential, $V_{\rm eff}(r)$, for a particle with angular momentum $L$. (No longer necessarily moving in a circular orbit.) * (d) Find the position of the minimum of $V_{\rm eff}$ in terms of $L$, $\alpha$ and $m$, then compare to the result of (b). * (e) What is the effective spring constant for a particle at the minimum of $V_{\rm eff}$? Express your answer in terms of $L$, $m$ and $\alpha$. * (f) What is the angular frequency, $\omega$, for small oscillations of $r$ about the $R_{\rm min}$? Express your answer in terms of $\dot{\theta}$ from part (3a).
3134c8be734f985ea89efce1776e9cb0a8765cc1
89f3169a2393bff8880f657d9bb4c12b40729e9a
/2020-11/abc062_b.py
19c743500148144716c92f15603587e44fabd2c1
[]
no_license
YutaGoto/daily_atcoder
c087adbb7fa03f0cdc4291c806f21b1b93130d86
113d4e25f1d3bb0e665f9154bc0afaecae5ea7bf
refs/heads/main
2023-06-19T00:56:12.359473
2021-07-16T12:33:06
2021-07-16T12:33:06
273,282,766
0
0
null
null
null
null
UTF-8
Python
false
false
126
py
h, w = map(int, input().split()) print('#'*(w+2)) for _ in range(h): a = input() print('#'+a+'#') print('#'*(w+2))
59f73e7d1222effb04a6343a2dd82ffeabb56260
3b2971ac117cf597e60233afffbf088989d7abdb
/tests/settings.py
6f66deb4674338780d11af86a8f3faa9ca1eabd7
[ "BSD-3-Clause" ]
permissive
ubernostrum/pwned-passwords-django
7b8e27ce774e1d698eef382a67664301be61bdbd
c615c2b80eab2f6554b6f113e99c658dd722c5cd
refs/heads/trunk
2023-04-10T05:33:44.797687
2023-03-27T05:25:45
2023-03-27T05:25:45
124,067,069
116
8
BSD-3-Clause
2023-09-11T06:26:23
2018-03-06T11:15:11
Python
UTF-8
Python
false
false
722
py
""" Minimal Django settings file for test runs. """ from django.utils.crypto import get_random_string INSTALLED_APPS = ["pwned_passwords_django"] ROOT_URLCONF = "tests.urls" DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}} MIDDLEWARE = [ "pwned_passwords_django.middleware.pwned_passwords_middleware", ] AUTH_PASSWORD_VALIDATORS = [ {"NAME": "pwned_passwords_django.validators.PwnedPasswordsValidator"} ] LOGGING = { "version": 1, "disable_existing_loggers": True, "handlers": {"null": {"class": "logging.NullHandler"}}, "loggers": { "pwned_passwords_django.api": {"handlers": ["null"], "propagate": False} }, } SECRET_KEY = get_random_string(12)
9fc65a9e22b154df1f46b9485b329b31a238ff3b
96f32051b1fcd322534fdf1f590704b7f48e08e3
/otx_epub/migrations/0003_auto_20161027_2317.py
22756320fbeb9f4e40103f15ce8d9ebe93f84e72
[ "Apache-2.0" ]
permissive
NYULibraries/dlts-enm-tct-backend
0f1ebad7d7334d41b4f24b2243639314c6ed1353
07455a660fb2cb8bc91a54f7f12d150923678157
refs/heads/master
2020-05-18T14:36:31.041830
2017-09-30T17:51:16
2017-09-30T17:51:16
84,251,389
0
0
null
null
null
null
UTF-8
Python
false
false
1,094
py
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-10-28 03:17 from __future__ import unicode_literals from django.db import migrations, models import otx_epub.storage class Migration(migrations.Migration): dependencies = [ ('otx_epub', '0002_epub_contents'), ] operations = [ migrations.AlterField( model_name='epub', name='contents', field=models.FilePathField(allow_files=False, allow_folders=True, path='/vagrant/nyu/media/epub_decompressed', recursive=True), ), migrations.AlterField( model_name='epub', name='manifest', field=models.CharField(blank=True, max_length=255), ), migrations.AlterField( model_name='epub', name='oebps_folder', field=models.CharField(blank=True, max_length=255), ), migrations.AlterField( model_name='epub', name='source', field=models.FileField(storage=otx_epub.storage.OverwriteStorage(), upload_to='epubs'), ), ]
9c9273b0557cfea35937de7e9f7ed2c0f11e495f
09f8a3825c5109a6cec94ae34ea17d9ace66f381
/cohesity_management_sdk/models/view_intent.py
e28eef393c010d4f1cd356037269faaa14fa16a2
[ "Apache-2.0" ]
permissive
cohesity/management-sdk-python
103ee07b2f047da69d7b1edfae39d218295d1747
e4973dfeb836266904d0369ea845513c7acf261e
refs/heads/master
2023-08-04T06:30:37.551358
2023-07-19T12:02:12
2023-07-19T12:02:12
134,367,879
24
20
Apache-2.0
2023-08-31T04:37:28
2018-05-22T06:04:19
Python
UTF-8
Python
false
false
1,660
py
# -*- coding: utf-8 -*- # Copyright 2023 Cohesity Inc. class ViewIntent(object): """Implementation of the 'ViewIntent' model. Specifies the Intent of the View. Attributes: template_id (long|int): Specifies the template Id from which the View is created. template_name (string): Specifies the template name from which the View is created. """ # Create a mapping from Model property names to API property names _names = { "template_id":'TemplateId', "template_name":'TemplateName', } def __init__(self, template_id=None, template_name=None, ): """Constructor for the ViewIntent class""" # Initialize members of the class self.template_id = template_id self.template_name = template_name @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary template_id = dictionary.get('TemplateId') template_name = dictionary.get('TemplateName') # Return an object of this model return cls( template_id, template_name )
ea98fab7c614bb2763e13a4a538ea3249fe899bf
afc3558e47ea4c82cb70190743472274eae7aeb1
/configs/textrecog/master/master_resnet31_12e_toy.py
adf14636518c6aa154da397106d2aae8b008226c
[ "Apache-2.0" ]
permissive
open-mmlab/mmocr
86a77fb77ca80cede9c41a9a22080eeeaf364002
9551af6e5a2482e72a2af1e3b8597fd54b999d69
refs/heads/main
2023-08-03T14:06:11.075037
2023-07-26T02:32:14
2023-07-26T02:32:14
355,559,187
3,734
801
Apache-2.0
2023-09-12T03:17:12
2021-04-07T13:40:21
Python
UTF-8
Python
false
false
1,164
py
_base_ = [ '_base_master_resnet31.py', '../_base_/datasets/toy_data.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_adam_base.py', ] optim_wrapper = dict(optimizer=dict(lr=4e-4)) train_cfg = dict(max_epochs=12) # learning policy param_scheduler = [ dict(type='LinearLR', end=100, by_epoch=False), dict(type='MultiStepLR', milestones=[11], end=12), ] # dataset settings train_list = [_base_.toy_rec_train] test_list = [_base_.toy_rec_test] train_dataset = dict( type='ConcatDataset', datasets=train_list, pipeline=_base_.train_pipeline) test_dataset = dict( type='ConcatDataset', datasets=test_list, pipeline=_base_.test_pipeline) train_dataloader = dict( batch_size=2, num_workers=1, persistent_workers=True, sampler=dict(type='DefaultSampler', shuffle=True), dataset=train_dataset) val_dataloader = dict( batch_size=2, num_workers=1, persistent_workers=True, drop_last=False, sampler=dict(type='DefaultSampler', shuffle=False), dataset=test_dataset) test_dataloader = val_dataloader val_evaluator = dict(dataset_prefixes=['Toy']) test_evaluator = val_evaluator
21df06ff4d70b2fe784d4a83c9a4ea9391b1f1a8
71297da3cf9e0cc5e2e3eb29477ed77150bf93fa
/baekjoon/10984.py
0e27694252233b2a2f65c64c0406100c715057e8
[]
no_license
Kangjinwoojwk/algorithm
7c8e4189c384f7104225284e9e0a2e2a5cdd18df
c92da7410523d340240bbe9256cecf710c4e641e
refs/heads/master
2022-11-15T19:11:33.918644
2022-11-10T03:13:50
2022-11-10T03:13:50
184,699,850
0
0
null
null
null
null
UTF-8
Python
false
false
215
py
for tc in range(int(input())): A, G = 0, 0 for i in range(int(input())): a, b = map(float, input().split()) A += a G += a * b G /= A print('{} {}'.format(int(A), round(G, 1)))
56f43f8aff84049b1d9ce85fb3c2d3fb0e5bc6ab
0431fb263e38422585edca273fb47ef92fd22243
/dataloaders/data_atari.py
50f23b17a6e6faf07dfeb81276ef50ed9522166d
[]
no_license
RRoundTable/EEN-with-Keras
a6c3352eafc05fcb7ed41463d637a684de9a0b27
ae71903afa05135f5eb6e2797854969f5a082958
refs/heads/master
2020-04-28T03:17:25.762629
2019-04-27T12:19:13
2019-04-27T12:19:13
174,930,756
2
0
null
null
null
null
UTF-8
Python
false
false
7,310
py
import numpy, os, random, glob, pdb, gc import pickle as pickle from scipy import misc #import torch, torchvision from tensorflow.python.keras.backend import * import copy, time class ImageLoader(object): def _load_set(self, split, n_episodes): datalist = [] datapath = '{}/{}'.format(self.arg.get("datapath"), split) flist = os.listdir(datapath) print('loading {} new episodes for {} set'.format(n_episodes, split)) for i in range(1, n_episodes): if split == 'train': fdname = random.choice(flist) else: fdname = flist[i] abs_fdname = '{}/{}'.format(datapath, fdname) episode = None while (episode == None): # print('loading {}'.format(abs_fdname)) try: episode = numpy.load(abs_fdname) except: print('problem loading {}'.format(abs_fdname)) break states = episode['states'] actions = episode['actions'] assert(len(states) == len(actions)) assert(len(states) > 0) datalist.append({'states': states, 'actions': actions}) episode.close() gc.collect() return datalist def __init__(self, arg): super(ImageLoader, self).__init__() self.arg = arg self.datalist = [] self.h = arg.get('height') self.w = arg.get('width') self.nc = arg.get('nc') self.ncond = arg.get('ncond', 4) self.npred = arg.get('npred', 4) self.datalist_train = self._load_set('train', 500) self.datalist_valid = self._load_set('valid', 200) self.datalist_test = self._load_set('test', 200) self.iter_video_ptr = 0 self.iter_sample_ptr = self.ncond self.train_batch_cntr = 0 print("Dataloader for Atari constructed done") def reset_ptrs(self): self.iter_video_ptr = 0 self.iter_sample_ptr = self.ncond def _sample_time(self, video, actions, num_cond, num_pred): start_pos = random.randint(num_cond+1, video.shape[0]-num_pred-2) cond_frames = video[start_pos-num_cond:start_pos] pred_frames = video[start_pos:start_pos+num_pred] actions = actions[start_pos:start_pos+num_pred] return cond_frames, pred_frames, actions def _iterate_time(self, video, start_pos, actions, num_cond, num_pred): cond_frames = video[start_pos-num_cond:start_pos] pred_frames = video[start_pos:start_pos+num_pred] actions = actions[start_pos:start_pos+num_pred] return cond_frames, pred_frames, actions def get_batch(self, split): cond_frames, pred_frames, actions = [], [], [] if split == 'train': # since the training set is large, we fetch new episodes every so often if self.train_batch_cntr == 1000: self.datalist_train = self._load_set('train', 500) self.train_batch_cntr = 0 else: self.train_batch_cntr += 1 this_set = self.datalist_train elif split == 'valid': this_set = self.datalist_valid elif split == 'test': this_set = self.datalist_test # rolling id = 1 while id <= self.arg.get("batchsize"): sample = random.choice(this_set) sample_video = sample.get('states') sample_actions = sample.get('actions') if len(sample_actions) > self.ncond + self.npred + 2: selected_cond_frames, selected_pred_frames, selected_actions = self._sample_time( sample_video, sample_actions, self.ncond, self.npred) assert(len(selected_actions) > 0) cond_frames.append(selected_cond_frames) pred_frames.append(selected_pred_frames) actions.append(selected_actions) id += 1 # processing on the numpy array level cond_frames = numpy.array(cond_frames, dtype='float') / 255.0 pred_frames = numpy.array(pred_frames, dtype='float') / 255.0 actions = numpy.array(actions, dtype='float') # return tensor cond_frames_ts = torch.from_numpy(cond_frames).float() pred_frames_ts = torch.from_numpy(pred_frames).float() actions_ts = torch.from_numpy(actions.squeeze()).float() return cond_frames_ts.cuda(), pred_frames_ts.cuda(), actions_ts.cuda() def get_paired_batch(self, split): # hardcoded assert(self.npred == 2) assert(self.ncond == 4) cond, target, action = self.get_batch(split) cond1 = cond target1 = target[:, 0].unsqueeze(1) action1 = action[:, 0] cond2 = torch.cat((cond[:, 1:], target1), 1) target2 = target[:, 1].unsqueeze(1) action2 = action[:, 1] return cond1.clone(), target1.clone(), action1.clone(), cond2.clone(), target2.clone(), action2.clone() def get_iterated_batch(self, split): if split == 'train': this_set = self.datalist_train elif split == 'valid': this_set = self.datalist_valid elif split == 'test': this_set = self.datalist_test cond_frames, pred_frames, actions = [], [], [] # rolling id = 1 while id <= self.arg.get("batchsize"): if self.iter_video_ptr == len(this_set): return None, None, None sample = this_set[self.iter_video_ptr] sample_video = sample.get('states') sample_actions = sample.get('actions') if self.iter_sample_ptr + self.npred > sample_video.shape[0]: self.iter_video_ptr += 1 self.iter_sample_ptr = self.ncond else: selected_cond_frames, selected_pred_frames, selected_actions = self._iterate_time( sample_video, self.iter_sample_ptr, sample_actions, self.ncond, self.npred) assert(len(selected_actions) > 0) cond_frames.append(selected_cond_frames) pred_frames.append(selected_pred_frames) actions.append(selected_actions) id += 1 self.iter_sample_ptr += 10 # processing on the numpy array level cond_frames = numpy.array(cond_frames, dtype='float') / 255.0 pred_frames = numpy.array(pred_frames, dtype='float') / 255.0 actions = numpy.array(actions, dtype='float') # return tensor cond_frames_ts = torch.from_numpy(cond_frames).float() pred_frames_ts = torch.from_numpy(pred_frames).float() actions_ts = torch.from_numpy(actions.squeeze()).float() return cond_frames_ts.cuda(), pred_frames_ts.cuda(), actions_ts.cuda() def plot_seq(self, cond, pred): cond_pred = torch.cat((cond, pred), 1) cond_pred = cond_pred.view(-1, self.nc, self.h, self.w) grid = torchvision.utils.make_grid(cond_pred, self.ncond+self.npred, pad_value=1, normalize=True) return grid
262b31f426537ac6065fa5fbe714726118f635a2
18940c73497d11c1386a19a2e90719356f8ed9b2
/python_solutions/90-subsets-2.py
aaa5aa73c476b0fb0652047257cab595e27aa005
[]
no_license
yunieyuna/Solutions-for-Leetcode-Problems
9741ba1a48341157fded637bb6e269fd9a659b5a
47910878328591844ab2c9b97ff8c89e2b98c319
refs/heads/master
2020-09-13T17:37:25.632463
2020-07-02T02:07:19
2020-07-02T02:07:19
222,857,462
0
0
null
null
null
null
UTF-8
Python
false
false
604
py
# https://leetcode.com/problems/subsets-ii/ class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: dic = {} for i in nums: dic[i] = dic.get(i, 0) + 1 res = [[]] for i, v in dic.items(): temp = res.copy() for j in res: temp.extend(j + [i]*(k + 1) for k in range(v)) res = temp return res """ Runtime: 44 ms, faster than 24.50% of Python3 online submissions for Subsets II. Memory Usage: 12.5 MB, less than 100.00% of Python3 online submissions for Subsets II. """
aa2be9b8e11e4a867f9c1d4feb7c3716361366ab
ee27325f6a3e6a2d1f5e004aa60f5974ad864ae9
/contrib/python/plotly/py3/plotly/graph_objs/histogram/marker/_colorbar.py
de0bf149cc077a8134605f4109788fffa81089f6
[ "MIT", "Apache-2.0" ]
permissive
alvinahmadov/catboost
f32d2b16be9db7439e429c88feb5676de842fc89
a6e0caa4779b31199f535cf43b09879d7c653abe
refs/heads/master
2023-06-12T19:29:52.028508
2023-05-11T18:33:03
2023-05-11T18:33:03
202,584,937
0
0
Apache-2.0
2019-08-15T17:35:23
2019-08-15T17:35:23
null
UTF-8
Python
false
false
80,205
py
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class ColorBar(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "histogram.marker" _path_str = "histogram.marker.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "labelalias", "len", "lenmode", "minexponent", "nticks", "orientation", "outlinecolor", "outlinewidth", "separatethousands", "showexponent", "showticklabels", "showtickprefix", "showticksuffix", "thickness", "thicknessmode", "tick0", "tickangle", "tickcolor", "tickfont", "tickformat", "tickformatstopdefaults", "tickformatstops", "ticklabeloverflow", "ticklabelposition", "ticklabelstep", "ticklen", "tickmode", "tickprefix", "ticks", "ticksuffix", "ticktext", "ticktextsrc", "tickvals", "tickvalssrc", "tickwidth", "title", "titlefont", "titleside", "x", "xanchor", "xpad", "y", "yanchor", "ypad", } # bgcolor # ------- @property def bgcolor(self): """ Sets the color of padded area. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["bgcolor"] @bgcolor.setter def bgcolor(self, val): self["bgcolor"] = val # bordercolor # ----------- @property def bordercolor(self): """ Sets the axis line color. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["bordercolor"] @bordercolor.setter def bordercolor(self, val): self["bordercolor"] = val # borderwidth # ----------- @property def borderwidth(self): """ Sets the width (in px) or the border enclosing this color bar. The 'borderwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["borderwidth"] @borderwidth.setter def borderwidth(self, val): self["borderwidth"] = val # dtick # ----- @property def dtick(self): """ Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" The 'dtick' property accepts values of any type Returns ------- Any """ return self["dtick"] @dtick.setter def dtick(self, val): self["dtick"] = val # exponentformat # -------------- @property def exponentformat(self): """ Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. The 'exponentformat' property is an enumeration that may be specified as: - One of the following enumeration values: ['none', 'e', 'E', 'power', 'SI', 'B'] Returns ------- Any """ return self["exponentformat"] @exponentformat.setter def exponentformat(self, val): self["exponentformat"] = val # labelalias # ---------- @property def labelalias(self): """ Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. The 'labelalias' property accepts values of any type Returns ------- Any """ return self["labelalias"] @labelalias.setter def labelalias(self, val): self["labelalias"] = val # len # --- @property def len(self): """ Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. The 'len' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["len"] @len.setter def len(self, val): self["len"] = val # lenmode # ------- @property def lenmode(self): """ Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. The 'lenmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['fraction', 'pixels'] Returns ------- Any """ return self["lenmode"] @lenmode.setter def lenmode(self, val): self["lenmode"] = val # minexponent # ----------- @property def minexponent(self): """ Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". The 'minexponent' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["minexponent"] @minexponent.setter def minexponent(self, val): self["minexponent"] = val # nticks # ------ @property def nticks(self): """ Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". The 'nticks' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [0, 9223372036854775807] Returns ------- int """ return self["nticks"] @nticks.setter def nticks(self, val): self["nticks"] = val # orientation # ----------- @property def orientation(self): """ Sets the orientation of the colorbar. The 'orientation' property is an enumeration that may be specified as: - One of the following enumeration values: ['h', 'v'] Returns ------- Any """ return self["orientation"] @orientation.setter def orientation(self, val): self["orientation"] = val # outlinecolor # ------------ @property def outlinecolor(self): """ Sets the axis line color. The 'outlinecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["outlinecolor"] @outlinecolor.setter def outlinecolor(self, val): self["outlinecolor"] = val # outlinewidth # ------------ @property def outlinewidth(self): """ Sets the width (in px) of the axis line. The 'outlinewidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["outlinewidth"] @outlinewidth.setter def outlinewidth(self, val): self["outlinewidth"] = val # separatethousands # ----------------- @property def separatethousands(self): """ If "true", even 4-digit integers are separated The 'separatethousands' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["separatethousands"] @separatethousands.setter def separatethousands(self, val): self["separatethousands"] = val # showexponent # ------------ @property def showexponent(self): """ If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. The 'showexponent' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showexponent"] @showexponent.setter def showexponent(self, val): self["showexponent"] = val # showticklabels # -------------- @property def showticklabels(self): """ Determines whether or not the tick labels are drawn. The 'showticklabels' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showticklabels"] @showticklabels.setter def showticklabels(self, val): self["showticklabels"] = val # showtickprefix # -------------- @property def showtickprefix(self): """ If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. The 'showtickprefix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showtickprefix"] @showtickprefix.setter def showtickprefix(self, val): self["showtickprefix"] = val # showticksuffix # -------------- @property def showticksuffix(self): """ Same as `showtickprefix` but for tick suffixes. The 'showticksuffix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showticksuffix"] @showticksuffix.setter def showticksuffix(self, val): self["showticksuffix"] = val # thickness # --------- @property def thickness(self): """ Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. The 'thickness' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["thickness"] @thickness.setter def thickness(self, val): self["thickness"] = val # thicknessmode # ------------- @property def thicknessmode(self): """ Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. The 'thicknessmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['fraction', 'pixels'] Returns ------- Any """ return self["thicknessmode"] @thicknessmode.setter def thicknessmode(self, val): self["thicknessmode"] = val # tick0 # ----- @property def tick0(self): """ Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. The 'tick0' property accepts values of any type Returns ------- Any """ return self["tick0"] @tick0.setter def tick0(self, val): self["tick0"] = val # tickangle # --------- @property def tickangle(self): """ Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. The 'tickangle' property is a angle (in degrees) that may be specified as a number between -180 and 180. Numeric values outside this range are converted to the equivalent value (e.g. 270 is converted to -90). Returns ------- int|float """ return self["tickangle"] @tickangle.setter def tickangle(self, val): self["tickangle"] = val # tickcolor # --------- @property def tickcolor(self): """ Sets the tick color. The 'tickcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["tickcolor"] @tickcolor.setter def tickcolor(self, val): self["tickcolor"] = val # tickfont # -------- @property def tickfont(self): """ Sets the color bar's tick label font The 'tickfont' property is an instance of Tickfont that may be specified as: - An instance of :class:`plotly.graph_objs.histogram.marker.colorbar.Tickfont` - A dict of string/value properties that will be passed to the Tickfont constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- plotly.graph_objs.histogram.marker.colorbar.Tickfont """ return self["tickfont"] @tickfont.setter def tickfont(self, val): self["tickfont"] = val # tickformat # ---------- @property def tickformat(self): """ Sets the tick label formatting rule using d3 formatting mini- languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" The 'tickformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickformat"] @tickformat.setter def tickformat(self, val): self["tickformat"] = val # tickformatstops # --------------- @property def tickformatstops(self): """ The 'tickformatstops' property is a tuple of instances of Tickformatstop that may be specified as: - A list or tuple of instances of plotly.graph_objs.histogram.marker.colorbar.Tickformatstop - A list or tuple of dicts of string/value properties that will be passed to the Tickformatstop constructor Supported dict properties: dtickrange range [*min*, *max*], where "min", "max" - dtick values which describe some zoom level, it is possible to omit "min" or "max" value by passing "null" enabled Determines whether or not this stop is used. If `false`, this stop is ignored even within its `dtickrange`. name When used in a template, named items are created in the output figure in addition to any items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false` to hide it). Has no effect outside of a template. templateitemname Used to refer to a named item in this array in the template. Named items from the template will be created even without a matching item in the input figure, but you can modify one by making an item with `templateitemname` matching its `name`, alongside your modifications (including `visible: false` or `enabled: false` to hide it). If there is no template or no matching item, this item will be hidden unless you explicitly show it with `visible: true`. value string - dtickformat for described zoom level, the same as "tickformat" Returns ------- tuple[plotly.graph_objs.histogram.marker.colorbar.Tickformatstop] """ return self["tickformatstops"] @tickformatstops.setter def tickformatstops(self, val): self["tickformatstops"] = val # tickformatstopdefaults # ---------------------- @property def tickformatstopdefaults(self): """ When used in a template (as layout.template.data.histogram.mark er.colorbar.tickformatstopdefaults), sets the default property values to use for elements of histogram.marker.colorbar.tickformatstops The 'tickformatstopdefaults' property is an instance of Tickformatstop that may be specified as: - An instance of :class:`plotly.graph_objs.histogram.marker.colorbar.Tickformatstop` - A dict of string/value properties that will be passed to the Tickformatstop constructor Supported dict properties: Returns ------- plotly.graph_objs.histogram.marker.colorbar.Tickformatstop """ return self["tickformatstopdefaults"] @tickformatstopdefaults.setter def tickformatstopdefaults(self, val): self["tickformatstopdefaults"] = val # ticklabeloverflow # ----------------- @property def ticklabeloverflow(self): """ Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. The 'ticklabeloverflow' property is an enumeration that may be specified as: - One of the following enumeration values: ['allow', 'hide past div', 'hide past domain'] Returns ------- Any """ return self["ticklabeloverflow"] @ticklabeloverflow.setter def ticklabeloverflow(self, val): self["ticklabeloverflow"] = val # ticklabelposition # ----------------- @property def ticklabelposition(self): """ Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". The 'ticklabelposition' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', 'outside top', 'inside top', 'outside left', 'inside left', 'outside right', 'inside right', 'outside bottom', 'inside bottom'] Returns ------- Any """ return self["ticklabelposition"] @ticklabelposition.setter def ticklabelposition(self, val): self["ticklabelposition"] = val # ticklabelstep # ------------- @property def ticklabelstep(self): """ Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". The 'ticklabelstep' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 9223372036854775807] Returns ------- int """ return self["ticklabelstep"] @ticklabelstep.setter def ticklabelstep(self, val): self["ticklabelstep"] = val # ticklen # ------- @property def ticklen(self): """ Sets the tick length (in px). The 'ticklen' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ticklen"] @ticklen.setter def ticklen(self, val): self["ticklen"] = val # tickmode # -------- @property def tickmode(self): """ Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). The 'tickmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['auto', 'linear', 'array'] Returns ------- Any """ return self["tickmode"] @tickmode.setter def tickmode(self, val): self["tickmode"] = val # tickprefix # ---------- @property def tickprefix(self): """ Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickprefix"] @tickprefix.setter def tickprefix(self, val): self["tickprefix"] = val # ticks # ----- @property def ticks(self): """ Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. The 'ticks' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', ''] Returns ------- Any """ return self["ticks"] @ticks.setter def ticks(self, val): self["ticks"] = val # ticksuffix # ---------- @property def ticksuffix(self): """ Sets a tick label suffix. The 'ticksuffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["ticksuffix"] @ticksuffix.setter def ticksuffix(self, val): self["ticksuffix"] = val # ticktext # -------- @property def ticktext(self): """ Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ticktext"] @ticktext.setter def ticktext(self, val): self["ticktext"] = val # ticktextsrc # ----------- @property def ticktextsrc(self): """ Sets the source reference on Chart Studio Cloud for `ticktext`. The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ticktextsrc"] @ticktextsrc.setter def ticktextsrc(self, val): self["ticktextsrc"] = val # tickvals # -------- @property def tickvals(self): """ Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. The 'tickvals' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["tickvals"] @tickvals.setter def tickvals(self, val): self["tickvals"] = val # tickvalssrc # ----------- @property def tickvalssrc(self): """ Sets the source reference on Chart Studio Cloud for `tickvals`. The 'tickvalssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["tickvalssrc"] @tickvalssrc.setter def tickvalssrc(self, val): self["tickvalssrc"] = val # tickwidth # --------- @property def tickwidth(self): """ Sets the tick width (in px). The 'tickwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["tickwidth"] @tickwidth.setter def tickwidth(self, val): self["tickwidth"] = val # title # ----- @property def title(self): """ The 'title' property is an instance of Title that may be specified as: - An instance of :class:`plotly.graph_objs.histogram.marker.colorbar.Title` - A dict of string/value properties that will be passed to the Title constructor Supported dict properties: font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. Returns ------- plotly.graph_objs.histogram.marker.colorbar.Title """ return self["title"] @title.setter def title(self, val): self["title"] = val # titlefont # --------- @property def titlefont(self): """ Deprecated: Please use histogram.marker.colorbar.title.font instead. Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.histogram.marker.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- """ return self["titlefont"] @titlefont.setter def titlefont(self, val): self["titlefont"] = val # titleside # --------- @property def titleside(self): """ Deprecated: Please use histogram.marker.colorbar.title.side instead. Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- """ return self["titleside"] @titleside.setter def titleside(self, val): self["titleside"] = val # x # - @property def x(self): """ Sets the x position of the color bar (in plot fraction). Defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". The 'x' property is a number and may be specified as: - An int or float in the interval [-2, 3] Returns ------- int|float """ return self["x"] @x.setter def x(self, val): self["x"] = val # xanchor # ------- @property def xanchor(self): """ Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'center', 'right'] Returns ------- Any """ return self["xanchor"] @xanchor.setter def xanchor(self, val): self["xanchor"] = val # xpad # ---- @property def xpad(self): """ Sets the amount of padding (in px) along the x direction. The 'xpad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["xpad"] @xpad.setter def xpad(self, val): self["xpad"] = val # y # - @property def y(self): """ Sets the y position of the color bar (in plot fraction). Defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". The 'y' property is a number and may be specified as: - An int or float in the interval [-2, 3] Returns ------- int|float """ return self["y"] @y.setter def y(self, val): self["y"] = val # yanchor # ------- @property def yanchor(self): """ Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". The 'yanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['top', 'middle', 'bottom'] Returns ------- Any """ return self["yanchor"] @yanchor.setter def yanchor(self, val): self["yanchor"] = val # ypad # ---- @property def ypad(self): """ Sets the amount of padding (in px) along the y direction. The 'ypad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ypad"] @ypad.setter def ypad(self, val): self["ypad"] = val # Self properties description # --------------------------- @property def _prop_descriptions(self): return """\ bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". orientation Sets the orientation of the colorbar. outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.histogram.marke r.colorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.histog ram.marker.colorbar.tickformatstopdefaults), sets the default property values to use for elements of histogram.marker.colorbar.tickformatstops ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.histogram.marker.colorbar. Title` instance or dict with compatible properties titlefont Deprecated: Please use histogram.marker.colorbar.title.font instead. Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. titleside Deprecated: Please use histogram.marker.colorbar.title.side instead. Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". Note that the title's location used to be set by the now deprecated `titleside` attribute. x Sets the x position of the color bar (in plot fraction). Defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". xpad Sets the amount of padding (in px) along the x direction. y Sets the y position of the color bar (in plot fraction). Defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". ypad Sets the amount of padding (in px) along the y direction. """ _mapped_properties = { "titlefont": ("title", "font"), "titleside": ("title", "side"), } def __init__( self, arg=None, bgcolor=None, bordercolor=None, borderwidth=None, dtick=None, exponentformat=None, labelalias=None, len=None, lenmode=None, minexponent=None, nticks=None, orientation=None, outlinecolor=None, outlinewidth=None, separatethousands=None, showexponent=None, showticklabels=None, showtickprefix=None, showticksuffix=None, thickness=None, thicknessmode=None, tick0=None, tickangle=None, tickcolor=None, tickfont=None, tickformat=None, tickformatstops=None, tickformatstopdefaults=None, ticklabeloverflow=None, ticklabelposition=None, ticklabelstep=None, ticklen=None, tickmode=None, tickprefix=None, ticks=None, ticksuffix=None, ticktext=None, ticktextsrc=None, tickvals=None, tickvalssrc=None, tickwidth=None, title=None, titlefont=None, titleside=None, x=None, xanchor=None, xpad=None, y=None, yanchor=None, ypad=None, **kwargs, ): """ Construct a new ColorBar object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.histogram.marker.ColorBar` bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". orientation Sets the orientation of the colorbar. outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.histogram.marke r.colorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.histog ram.marker.colorbar.tickformatstopdefaults), sets the default property values to use for elements of histogram.marker.colorbar.tickformatstops ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.histogram.marker.colorbar. Title` instance or dict with compatible properties titlefont Deprecated: Please use histogram.marker.colorbar.title.font instead. Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. titleside Deprecated: Please use histogram.marker.colorbar.title.side instead. Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". Note that the title's location used to be set by the now deprecated `titleside` attribute. x Sets the x position of the color bar (in plot fraction). Defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". xpad Sets the amount of padding (in px) along the x direction. y Sets the y position of the color bar (in plot fraction). Defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". ypad Sets the amount of padding (in px) along the y direction. Returns ------- ColorBar """ super(ColorBar, self).__init__("colorbar") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.histogram.marker.ColorBar constructor must be a dict or an instance of :class:`plotly.graph_objs.histogram.marker.ColorBar`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("bgcolor", None) _v = bgcolor if bgcolor is not None else _v if _v is not None: self["bgcolor"] = _v _v = arg.pop("bordercolor", None) _v = bordercolor if bordercolor is not None else _v if _v is not None: self["bordercolor"] = _v _v = arg.pop("borderwidth", None) _v = borderwidth if borderwidth is not None else _v if _v is not None: self["borderwidth"] = _v _v = arg.pop("dtick", None) _v = dtick if dtick is not None else _v if _v is not None: self["dtick"] = _v _v = arg.pop("exponentformat", None) _v = exponentformat if exponentformat is not None else _v if _v is not None: self["exponentformat"] = _v _v = arg.pop("labelalias", None) _v = labelalias if labelalias is not None else _v if _v is not None: self["labelalias"] = _v _v = arg.pop("len", None) _v = len if len is not None else _v if _v is not None: self["len"] = _v _v = arg.pop("lenmode", None) _v = lenmode if lenmode is not None else _v if _v is not None: self["lenmode"] = _v _v = arg.pop("minexponent", None) _v = minexponent if minexponent is not None else _v if _v is not None: self["minexponent"] = _v _v = arg.pop("nticks", None) _v = nticks if nticks is not None else _v if _v is not None: self["nticks"] = _v _v = arg.pop("orientation", None) _v = orientation if orientation is not None else _v if _v is not None: self["orientation"] = _v _v = arg.pop("outlinecolor", None) _v = outlinecolor if outlinecolor is not None else _v if _v is not None: self["outlinecolor"] = _v _v = arg.pop("outlinewidth", None) _v = outlinewidth if outlinewidth is not None else _v if _v is not None: self["outlinewidth"] = _v _v = arg.pop("separatethousands", None) _v = separatethousands if separatethousands is not None else _v if _v is not None: self["separatethousands"] = _v _v = arg.pop("showexponent", None) _v = showexponent if showexponent is not None else _v if _v is not None: self["showexponent"] = _v _v = arg.pop("showticklabels", None) _v = showticklabels if showticklabels is not None else _v if _v is not None: self["showticklabels"] = _v _v = arg.pop("showtickprefix", None) _v = showtickprefix if showtickprefix is not None else _v if _v is not None: self["showtickprefix"] = _v _v = arg.pop("showticksuffix", None) _v = showticksuffix if showticksuffix is not None else _v if _v is not None: self["showticksuffix"] = _v _v = arg.pop("thickness", None) _v = thickness if thickness is not None else _v if _v is not None: self["thickness"] = _v _v = arg.pop("thicknessmode", None) _v = thicknessmode if thicknessmode is not None else _v if _v is not None: self["thicknessmode"] = _v _v = arg.pop("tick0", None) _v = tick0 if tick0 is not None else _v if _v is not None: self["tick0"] = _v _v = arg.pop("tickangle", None) _v = tickangle if tickangle is not None else _v if _v is not None: self["tickangle"] = _v _v = arg.pop("tickcolor", None) _v = tickcolor if tickcolor is not None else _v if _v is not None: self["tickcolor"] = _v _v = arg.pop("tickfont", None) _v = tickfont if tickfont is not None else _v if _v is not None: self["tickfont"] = _v _v = arg.pop("tickformat", None) _v = tickformat if tickformat is not None else _v if _v is not None: self["tickformat"] = _v _v = arg.pop("tickformatstops", None) _v = tickformatstops if tickformatstops is not None else _v if _v is not None: self["tickformatstops"] = _v _v = arg.pop("tickformatstopdefaults", None) _v = tickformatstopdefaults if tickformatstopdefaults is not None else _v if _v is not None: self["tickformatstopdefaults"] = _v _v = arg.pop("ticklabeloverflow", None) _v = ticklabeloverflow if ticklabeloverflow is not None else _v if _v is not None: self["ticklabeloverflow"] = _v _v = arg.pop("ticklabelposition", None) _v = ticklabelposition if ticklabelposition is not None else _v if _v is not None: self["ticklabelposition"] = _v _v = arg.pop("ticklabelstep", None) _v = ticklabelstep if ticklabelstep is not None else _v if _v is not None: self["ticklabelstep"] = _v _v = arg.pop("ticklen", None) _v = ticklen if ticklen is not None else _v if _v is not None: self["ticklen"] = _v _v = arg.pop("tickmode", None) _v = tickmode if tickmode is not None else _v if _v is not None: self["tickmode"] = _v _v = arg.pop("tickprefix", None) _v = tickprefix if tickprefix is not None else _v if _v is not None: self["tickprefix"] = _v _v = arg.pop("ticks", None) _v = ticks if ticks is not None else _v if _v is not None: self["ticks"] = _v _v = arg.pop("ticksuffix", None) _v = ticksuffix if ticksuffix is not None else _v if _v is not None: self["ticksuffix"] = _v _v = arg.pop("ticktext", None) _v = ticktext if ticktext is not None else _v if _v is not None: self["ticktext"] = _v _v = arg.pop("ticktextsrc", None) _v = ticktextsrc if ticktextsrc is not None else _v if _v is not None: self["ticktextsrc"] = _v _v = arg.pop("tickvals", None) _v = tickvals if tickvals is not None else _v if _v is not None: self["tickvals"] = _v _v = arg.pop("tickvalssrc", None) _v = tickvalssrc if tickvalssrc is not None else _v if _v is not None: self["tickvalssrc"] = _v _v = arg.pop("tickwidth", None) _v = tickwidth if tickwidth is not None else _v if _v is not None: self["tickwidth"] = _v _v = arg.pop("title", None) _v = title if title is not None else _v if _v is not None: self["title"] = _v _v = arg.pop("titlefont", None) _v = titlefont if titlefont is not None else _v if _v is not None: self["titlefont"] = _v _v = arg.pop("titleside", None) _v = titleside if titleside is not None else _v if _v is not None: self["titleside"] = _v _v = arg.pop("x", None) _v = x if x is not None else _v if _v is not None: self["x"] = _v _v = arg.pop("xanchor", None) _v = xanchor if xanchor is not None else _v if _v is not None: self["xanchor"] = _v _v = arg.pop("xpad", None) _v = xpad if xpad is not None else _v if _v is not None: self["xpad"] = _v _v = arg.pop("y", None) _v = y if y is not None else _v if _v is not None: self["y"] = _v _v = arg.pop("yanchor", None) _v = yanchor if yanchor is not None else _v if _v is not None: self["yanchor"] = _v _v = arg.pop("ypad", None) _v = ypad if ypad is not None else _v if _v is not None: self["ypad"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
419827681f3f82c9700097168df022ee151b4639
2f2e9cd97d65751757ae0a92e8bb882f3cbc5b5b
/33.搜索旋转排序数组.py
e67b6bd61499c8507cb2cb4f53db5ccbe9e2e868
[]
no_license
mqinbin/python_leetcode
77f0a75eb29f8d2f9a789958e0120a7df4d0d0d3
73e0c81867f38fdf4051d8f58d0d3dc245be081e
refs/heads/main
2023-03-10T18:27:36.421262
2021-02-25T07:24:10
2021-02-25T07:24:10
314,410,703
0
0
null
null
null
null
UTF-8
Python
false
false
1,257
py
# # @lc app=leetcode.cn id=33 lang=python3 # # [33] 搜索旋转排序数组 # # @lc code=start class Solution: def search(self, nums: List[int], target: int) -> int: # if len(nums) == 1 : # return 0 if target == nums[0] else -1 left , right = 0 , len(nums) while left < right: rotatePos = (left + right) // 2 if rotatePos == len(nums) - 1: break if nums[rotatePos]>nums[rotatePos+1]: rotatePos += 1 break if nums[rotatePos]>nums[left]: left = rotatePos + 1 else: right = rotatePos def foundIndex(nums, left, right,target): while left < right: mid = (left + right) // 2 if nums[mid] == target: return mid if target>nums[mid]: left = mid + 1 else: right = mid return -1 leftPart = foundIndex(nums,0,rotatePos,target) if leftPart != -1: return leftPart rightPart = foundIndex(nums,rotatePos,len(nums),target) return rightPart # @lc code=end
eec69491952dc2206c921236c774340265028549
cf7d6cc5efd2d3545a538c1bf12e927a60b8600e
/iniciante/1478.py
2fbb42d314bb183909e20c8d6e3ab7903c9700a9
[]
no_license
DarknessRdg/URI
1a4d821cc43c715f5092076a1753b13f42f3ceac
459361f9e055efb6eb291fb030dde47cb08688ab
refs/heads/master
2022-05-08T06:46:44.618627
2022-04-24T03:46:43
2022-04-24T03:46:43
200,585,901
2
0
null
null
null
null
UTF-8
Python
false
false
952
py
def main(): ordem = int(input()) while ordem != 0: matriz = [] for i in range(1, ordem + 1): matriz += [[i] * ordem] for i in range(ordem): for j in range(ordem): if i == j: matriz[i][j] = 1 if i < j: matriz[i][j] = matriz[i][j - 1] + 1 if i > j: if j == 0: continue else: matriz[i][j] = matriz[i][j - 1] - 1 for i in range(ordem): for j in range(ordem): matriz[i][j] = str(matriz[i][j]) tamanho = len(matriz[i][j]) if j == 0: if tamanho == 1: print(' ' + matriz[i][j], end='') elif tamanho == 2: print(' ' + matriz[i][j], end='') else: print(matriz[i][j], end='') else: if tamanho == 1: print(' ' + matriz[i][j], end='') elif tamanho == 2: print(' ' + matriz[i][j], end='') else: print(' ' + matriz[i][j], end='') print() print() ordem = int(input()) if __name__ == '__main__': main()
44877423e0a7b2fbd5c6d3490744498281831dd6
14373275670c1f3065ce9ae195df142146e2c1a4
/stubs/influxdb-client/influxdb_client/domain/range_threshold.pyi
bc6b3aa97fdc891511d30c007c3c8dd1a4f27782
[ "Apache-2.0", "MIT" ]
permissive
sobolevn/typeshed
eb7af17c06a9722f23c337e6b9a4726223155d58
d63a82640390a9c130e0fe7d409e8b0b836b7c31
refs/heads/master
2023-08-04T05:59:29.447015
2023-06-14T21:27:53
2023-06-14T21:27:53
216,265,622
2
0
Apache-2.0
2022-02-08T10:40:53
2019-10-19T20:21:25
Python
UTF-8
Python
false
false
1,004
pyi
from _typeshed import Incomplete from influxdb_client.domain.threshold_base import ThresholdBase class RangeThreshold(ThresholdBase): openapi_types: Incomplete attribute_map: Incomplete discriminator: Incomplete def __init__( self, type: str = "range", min: Incomplete | None = None, max: Incomplete | None = None, within: Incomplete | None = None, level: Incomplete | None = None, all_values: Incomplete | None = None, ) -> None: ... @property def type(self): ... @type.setter def type(self, type) -> None: ... @property def min(self): ... @min.setter def min(self, min) -> None: ... @property def max(self): ... @max.setter def max(self, max) -> None: ... @property def within(self): ... @within.setter def within(self, within) -> None: ... def to_dict(self): ... def to_str(self): ... def __eq__(self, other): ... def __ne__(self, other): ...
82ef0c669736d69b2da60bea4943dc6b93cf54f9
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_luaus.py
db10b77fa904fbdc865fafa175f9a8538ee5ee10
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
224
py
from xai.brain.wordbase.nouns._luau import _LUAU #calss header class _LUAUS(_LUAU, ): def __init__(self,): _LUAU.__init__(self) self.name = "LUAUS" self.specie = 'nouns' self.basic = "luau" self.jsondata = {}
5c0db854454cabafcab66f84b62cc0ae6df4a7a6
4c7a9d9af1f5a68e718fd626281b979590f7a434
/v6/combine_filter.py
54dd64244b4450e2414f2e8e536e9122c58768c3
[]
no_license
bcrafton/bp-analysis
59f077f09d4c10445b2f1e2889842a681de44129
9290df4bc8ae6a527586328eee0ad86fd370989e
refs/heads/master
2020-05-31T12:27:23.673875
2019-07-02T15:46:58
2019-07-02T15:46:58
190,281,254
0
0
null
null
null
null
UTF-8
Python
false
false
611
py
import numpy as np def combine_filter(f1, f2, stride=1): h1, w1, fin1, fout1 = np.shape(f1) h2, w2, fin2, fout2 = np.shape(f2) oh = h1 + 2*(h2 // 2) * stride ow = w1 + 2*(w2 // 2) * stride ofin = fin1 ofout = fout2 fout = np.zeros(shape=(oh, ow, ofin, ofout)) for x in range(h2): for y in range(w2): for c in range(fout2): sh = x * stride ; eh = x * stride + h1 sw = y * stride ; ew = y * stride + w1 fout[sh:eh, sw:ew, :, c] += np.sum(f2[x, y, :, c] * f1, axis=3) return fout
6b124e1471d862488e655f3811a9cdfd0dc281cb
e4aab0a71dc5c047d8b1576380b16364e03e7c0d
/post scripts/deluge.py
4a1106e8a5d1e3b050a700159f20b48d25f02268
[ "Apache-2.0" ]
permissive
Joecastra/Watcher3
8ca66c44846030f0eb771d9d6ddeb9c37f637a4e
ce25d475f83ed36d6772f0cc35ef020d5e47c94b
refs/heads/master
2021-01-19T11:05:55.454351
2017-04-10T20:17:24
2017-04-10T20:17:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,359
py
#!/usr/bin/env python3 # ======================================== # # ============= INSTRUCTIONS ============= # # Add file to Deluge's Execute plugin for event Torrent Complete # Add api information to conf: watcherapi = 'APIKEY' watcheraddress = u'http://localhost:9090/' category = 'Watcher' # DO NOT TOUCH ANYTHING BELOW THIS LINE! # # ======================================== # import json import os import sys import urllib.request import urllib.parse data = {} args = sys.argv download_dir = args[3] while download_dir[-1] in ['/', '\\']: download_dir = download_dir[:-1] parent_folder = os.path.split(download_dir)[-1] if parent_folder.lower() != category.lower(): # Not watcher category sys.exit(0) data['apikey'] = watcherapi data['name'] = args[2] data['path'] = u'{}/{}'.format(download_dir, args[2]) data['downloadid'] = args[1] data['guid'] = args[1] data['mode'] = 'complete' url = u'{}/postprocessing/'.format(watcheraddress) post_data = urllib.parse.urlencode(data).encode('ascii') request = urllib.request.Request(url, post_data, headers={'User-Agent': 'Mozilla/5.0'}) response = json.loads(urllib.request.urlopen(request, timeout=600).read()) if response['status'] == 'finished': sys.exit(0) elif response['status'] == 'incomplete': sys.exit(1) else: sys.exit(1) sys.exit(0) # pylama:ignore=E402
58913959884ae744d8d208372316ac4a7ab7379f
e6ea71d6acbb41bd40d3a17b352e19c6369d5c4b
/senpai/stage_instance.py
736cc80fa7d0ffe07b80e08582726f18cda05304
[ "MIT" ]
permissive
alexyy802/waifucord
bbfb50515ca23bf711e940ac8921092ff6d1e12e
c3bb883a6a148effb127781a885e839697df6a8b
refs/heads/master
2023-09-02T13:19:44.478472
2021-10-29T06:51:51
2021-10-29T06:51:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,004
py
""" The MIT License (MIT) Copyright (c) 2021-present waifucord Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import annotations from typing import Optional, TYPE_CHECKING from .utils import MISSING, cached_slot_property from .mixins import Hashable from .errors import InvalidArgument from .enums import StagePrivacyLevel, try_enum __all__ = ("StageInstance",) if TYPE_CHECKING: from .chan.channel import StageInstance as StageInstancePayload from .state import ConnectionState from .channel import StageChannel from .guild import Guild class StageInstance(Hashable): """Represents a stage instance of a stage channel in a guild. .. versionadded:: 2.0 .. container:: operations .. describe:: x == y Checks if two stage instances are equal. .. describe:: x != y Checks if two stage instances are not equal. .. describe:: hash(x) Returns the stage instance's hash. Attributes ----------- id: :class:`int` The stage instance's ID. guild: :class:`Guild` The guild that the stage instance is running in. channel_id: :class:`int` The ID of the channel that the stage instance is running in. topic: :class:`str` The topic of the stage instance. privacy_level: :class:`StagePrivacyLevel` The privacy level of the stage instance. discoverable_disabled: :class:`bool` Whether discoverability for the stage instance is disabled. """ __slots__ = ( "_state", "id", "guild", "channel_id", "topic", "privacy_level", "discoverable_disabled", "_cs_channel", ) def __init__( self, *, state: ConnectionState, guild: Guild, data: StageInstancePayload ) -> None: self._state = state self.guild = guild self._update(data) def _update(self, data: StageInstancePayload): self.id: int = int(data["id"]) self.channel_id: int = int(data["channel_id"]) self.topic: str = data["topic"] self.privacy_level: StagePrivacyLevel = try_enum( StagePrivacyLevel, data["privacy_level"] ) self.discoverable_disabled: bool = data.get("discoverable_disabled", False) def __repr__(self) -> str: return f"<StageInstance id={self.id} guild={self.guild!r} channel_id={self.channel_id} topic={self.topic!r}>" @cached_slot_property("_cs_channel") def channel(self) -> Optional[StageChannel]: """Optional[:class:`StageChannel`]: The channel that stage instance is running in.""" # the returned channel will always be a StageChannel or None return self._state.get_channel(self.channel_id) # type: ignore def is_public(self) -> bool: return self.privacy_level is StagePrivacyLevel.public async def edit( self, *, topic: str = MISSING, privacy_level: StagePrivacyLevel = MISSING, reason: Optional[str] = None, ) -> None: """|coro| Edits the stage instance. You must have the :attr:`~Permissions.manage_channels` permission to use this. Parameters ----------- topic: :class:`str` The stage instance's new topic. privacy_level: :class:`StagePrivacyLevel` The stage instance's new privacy level. reason: :class:`str` The reason the stage instance was edited. Shows up on the audit log. Raises ------ InvalidArgument If the ``privacy_level`` parameter is not the proper type. Forbidden You do not have permissions to edit the stage instance. HTTPException Editing a stage instance failed. """ payload = {} if topic is not MISSING: payload["topic"] = topic if privacy_level is not MISSING: if not isinstance(privacy_level, StagePrivacyLevel): raise InvalidArgument( "privacy_level field must be of type PrivacyLevel" ) payload["privacy_level"] = privacy_level.value if payload: await self._state.http.edit_stage_instance( self.channel_id, **payload, reason=reason ) async def delete(self, *, reason: Optional[str] = None) -> None: """|coro| Deletes the stage instance. You must have the :attr:`~Permissions.manage_channels` permission to use this. Parameters ----------- reason: :class:`str` The reason the stage instance was deleted. Shows up on the audit log. Raises ------ Forbidden You do not have permissions to delete the stage instance. HTTPException Deleting the stage instance failed. """ await self._state.http.delete_stage_instance(self.channel_id, reason=reason)
f08f5e37c8d43e03f7302f3dc075c370c0ebb88c
c70d020907e538492665c7fe75d7b2b90c88ba93
/python/pygobject/basis.py
9507a9e5cafe13baefa28c73ed1d79d857155810
[]
no_license
4179e1/misc
7250de0bc0d9ab5641f48ec87f038f8b5dbed29b
1fb4d38b75fcc7692da605a6d3ec72e735116de1
refs/heads/master
2023-08-10T23:37:10.362847
2023-07-08T14:27:53
2023-07-08T14:27:53
14,710,900
3
3
null
2023-02-23T02:03:23
2013-11-26T08:21:00
Roff
UTF-8
Python
false
false
151
py
#!/usr/bin/env python from gi.repository import Gtk win = Gtk.Window() win.connect ("delete-event", Gtk.main_quit) win.show_all() Gtk.main()
aae7967595c33684d0cddfce97bc78285b719b53
67c0bc2b2292857fcc19b3c6e6da5570dc09749c
/chapter_6_visualization/audio_path.py
b8f4132d681a1663b16025bb3e2816c9f6d25d96
[ "Apache-2.0" ]
permissive
jim-schwoebel/voicebook
9d28f638fa6a31cb8c4915f9871c07da261b3ea6
0e8eae0f01487f15589c0daa2cf7ca3c6f3b8ad3
refs/heads/master
2022-12-11T13:41:24.005431
2021-04-15T13:51:35
2021-04-15T13:51:35
137,778,789
363
84
Apache-2.0
2022-12-08T03:58:01
2018-06-18T16:37:37
Python
UTF-8
Python
false
false
3,273
py
''' ================================================ ## VOICEBOOK REPOSITORY ## ================================================ repository name: voicebook repository version: 1.0 repository link: https://github.com/jim-schwoebel/voicebook author: Jim Schwoebel author contact: [email protected] description: a book and repo to get you started programming voice applications in Python - 10 chapters and 200+ scripts. license category: opensource license: Apache 2.0 license organization name: NeuroLex Laboratories, Inc. location: Seattle, WA website: https://neurolex.ai release date: 2018-09-28 This code (voicebook) is hereby released under a Apache 2.0 license license. For more information, check out the license terms below. ================================================ ## LICENSE TERMS ## ================================================ Copyright 2018 NeuroLex Laboratories, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ ## SERVICE STATEMENT ## ================================================ If you are using the code written for a larger project, we are happy to consult with you and help you with deployment. Our team has >10 world experts in Kafka distributed architectures, microservices built on top of Node.js / Python / Docker, and applying machine learning to model speech and text data. We have helped a wide variety of enterprises - small businesses, researchers, enterprises, and/or independent developers. If you would like to work with us let us know @ [email protected]. ================================================ ## AUDIO_PATH.PY ## ================================================ Give some simple visual feedback when recording an audio stream. ''' import sounddevice as sd import soundfile as sf import random, time, librosa, os import numpy as np import matplotlib.pyplot as plt from drawnow import drawnow def make_fig(): plt.scatter(x, y) def record_data(filename, duration, fs, channels): # synchronous recording myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=channels) sd.wait() sf.write(filename, myrecording, fs) y, sr = librosa.load(filename) rmse=np.mean(librosa.feature.rmse(y)[0]) os.remove(filename) return rmse*1000 # initialize plot plt.ion() # enable interactivity fig = plt.figure() # make a figure x = list() y = list() for i in range(100): # record 20ms of data sample=record_data('sample.wav',0.02, 44100, 1) x.append(i) y.append(sample) drawnow(make_fig) plt.savefig('stream.png') os.system('open stream.png')
db6175fa2394c30524ad292439ef8721022ae025
851c474c9d91875b0fa8fe46d591bb6550b1c550
/eye/migrations/0003_auto_20200818_0030.py
62e72256111c4d71a8e8f0ef2e19f772bd42a5f2
[]
no_license
songlei1979/BigEye4
1a8e9c71cae3e3bd3fb5432c05b73997ba9590c2
825e79ebd43d71203c827490d5ffe36c861e4dec
refs/heads/master
2022-12-03T22:19:25.224277
2020-08-26T05:44:19
2020-08-26T05:44:19
288,315,654
0
0
null
null
null
null
UTF-8
Python
false
false
449
py
# Generated by Django 3.0.8 on 2020-08-18 00:30 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('eye', '0002_auto_20200812_1007'), ] operations = [ migrations.AlterModelTable( name='allocation', table='eye_allocation', ), migrations.AlterModelTable( name='assignment', table='eye_assignment', ), ]
3803da3b8f058178d20d30d5aa287d146a64bf84
7579431f002103a74b5ae6bccf76458b221e78ab
/Dynammic Programming/Egg Dropping Puzzle.py
0cea9ac5597a588db4fd63558fc43eea55a49cab
[]
no_license
mukundajmera/competitiveprogramming
5c187e9681b320482c7b8cdfa71be95f9f9184c1
85774aea5a20a9cf4a97c66237d2faa570edd96b
refs/heads/main
2023-03-21T14:01:03.653953
2021-03-22T19:41:54
2021-03-22T19:41:54
319,270,423
1
0
null
null
null
null
UTF-8
Python
false
false
1,375
py
# User function Template for python3 # Function to get minimum number of trials needed in worst # case with n eggs and k floors import math def eggDrop(n, k): # code here # create table of n+1, k+1 dp = [[None] * (n + 1) for i in range(k + 1)] # fill # floor 0 with egg is zero # floor 1 with egg is 1 for i in range(1, n + 1): # floor 1 with egg is 1 dp[1][i] = 1 # floor 0 with egg is zero dp[0][i] = 0 for j in range(k + 1): # egg 1 for each floor is 1 dp[j][1] = j # check for egg with n value with f floors # min (max( case1 (break), case2 (do not break))) + 1 # min(dp[i][j], (max( dp[x-1,n-1], dp[f-x,e])) + 1) for floor in range(2, k + 1): for egg in range(2, n + 1): dp[floor][egg] = math.inf # iter for x for rem in range(1, floor + 1): dp[floor][egg] = min(dp[floor][egg], 1 + max(dp[rem - 1][egg - 1], dp[floor - rem][egg])) # print(dp) # print(dp[k][n]) return dp[k][n] # { # Driver Code Starts # Initial Template for Python 3 import atexit import io import sys # Contributed by : Nagendra Jha if __name__ == '__main__': test_cases = int(input()) for cases in range(test_cases): n, k = map(int, input().strip().split()) print(eggDrop(n, k)) # } Driver Code Ends
103b7a688f8a7e8cf5d5dddf9358f9b4c41bf7fa
7fc03f7d28ea7bbdca650a51a23fc0b13cbefde1
/supervised_learning/0x11-attention/6-main.py
756a7098a53ec467f39ff16efa42dd77ce531301
[]
no_license
HeimerR/holbertonschool-machine_learning
54c410e40d38635de482773f15e26ce1c2c95e46
e10b4e9b6f3fa00639e6e9e5b35f0cdb43a339a3
refs/heads/master
2021-07-24T09:33:25.833269
2021-01-14T00:21:45
2021-01-14T00:21:45
236,603,791
0
6
null
null
null
null
UTF-8
Python
false
false
594
py
#!/usr/bin/env python3 import numpy as np import tensorflow as tf MultiHeadAttention = __import__('6-multi_head_attention').MultiHeadAttention mha = MultiHeadAttention(512, 8) print(mha.dm) print(mha.h) print(mha.depth) print(mha.Wq) print(mha.Wk) print(mha.Wv) print(mha.linear) Q = tf.convert_to_tensor(np.random.uniform(size=(50, 15, 256)).astype('float32')) K = tf.convert_to_tensor(np.random.uniform(size=(50, 15, 256)).astype('float32')) V = tf.convert_to_tensor(np.random.uniform(size=(50, 15, 256)).astype('float32')) output, weights = mha(Q, K, V, None) print(output) print(weights)
b0680c3e15836ae1c131b441d324db4d218d5f96
04f8c7d9eb20745def8568fcbd2401392187ebf0
/www/www/settings_prod.py
2df597cfc30b7934a40ca8e4d06329af96778cbd
[]
no_license
boogiiieee/Victoria
5f01d8c01e92d78b756324ee8da2208ab9c63bc6
c76996698bbbd88309ed35f47d19e09fec19eb94
refs/heads/master
2021-09-04T03:13:00.208173
2018-01-15T04:05:29
2018-01-15T04:05:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
699
py
# -*- coding: utf-8 -*- ''' from settings import * DEBUG = False TEMPLATE_DEBUG = DEBUG MANAGERS = ( ('', ''), ('', ''), ) MEDIA_ROOT = '/var/www/home/' STATIC_ROOT = '/var/www/home/' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': 'postgresql2.locum.ru', 'PORT': '5432', } } ALLOWED_HOSTS = ['127.0.0.1:8000', 'localhost', '', ''] ROBOTS_SITEMAP_URLS = ['/sitemap.xml'] ROBOTS_SITEMAP_HOST = '' DEFAULT_FROM_EMAIL = '' EMAIL_SUBJECT_PREFIX = '' EMAIL_HOST = '' EMAIL_PORT = 25 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = True '''
c7390cd06f4184861f8f1c7715515e955cf21374
9427fa36416d835e28faa8e52a11140b6512e9c7
/dæmatímaverk/dæmatími_tuples/tuples5.py
9a17ed22e2776c27573687cc7d5525fb0ac8cac2
[]
no_license
fannarl/traveler
e5f274e404c10fe799b87e36eb4eb37e64fb8db8
8bc121d9fc26374f1b0dcee6da815ed732f2d889
refs/heads/master
2020-03-28T23:23:31.216234
2018-12-14T17:22:30
2018-12-14T17:22:30
149,289,261
0
0
null
null
null
null
UTF-8
Python
false
false
654
py
def get_list(): a_list = input("Enter elements of list separated by commas: ").strip().split(',') return a_list def get_integer(prompt): val = int(input(prompt)) return val def transform(list1, list2, r1, r2): new_list = [] for i in range(r1,r2): new_list.append(list1[i]) for i in range(len(new_list)): list1.remove(list1[r1]) list2.extend(reversed(new_list)) # Main program starts here - DO NOT change it list1 = get_list() list2 = get_list() index1 = get_integer("Enter from value: ") index2 = get_integer("Enter to value: ") transform(list1, list2, index1, index2) print(list1) print(list2)
0696c8ebc33ac64b9ec37ab7fb5a23ad490a88fc
194a1e2ac246c5f9926b014c00d4c733f0cdaf0c
/tests/wallet/test_singleton_lifecycle.py
965eaeab5e49fb9b8403e58e5fcd5a088a688c53
[ "Apache-2.0" ]
permissive
chia-os/btcgreen-blockchain
03e889cd0268284b7673917ab725ad71f980b650
2688e74de423ec59df302299e993b4674d69489e
refs/heads/main
2023-08-29T14:40:11.962821
2021-08-17T06:33:34
2021-08-17T06:33:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,191
py
import asyncio from typing import List, Tuple from blspy import G2Element from clvm_tools import binutils from btcgreen.types.blockchain_format.program import Program, INFINITE_COST from btcgreen.types.announcement import Announcement from btcgreen.types.blockchain_format.coin import Coin from btcgreen.types.blockchain_format.sized_bytes import bytes32 from btcgreen.types.coin_solution import CoinSolution from btcgreen.types.spend_bundle import SpendBundle from btcgreen.util.condition_tools import ConditionOpcode from btcgreen.util.ints import uint64 from btcgreen.wallet.puzzles.load_clvm import load_clvm from tests.core.full_node.test_conditions import bt, check_spend_bundle_validity, initial_blocks SINGLETON_MOD = load_clvm("singleton_top_layer.clvm") LAUNCHER_PUZZLE = load_clvm("singleton_launcher.clvm") P2_SINGLETON_MOD = load_clvm("p2_singleton.clvm") POOL_MEMBER_MOD = load_clvm("pool_member_innerpuz.clvm") POOL_WAITINGROOM_MOD = load_clvm("pool_waitingroom_innerpuz.clvm") LAUNCHER_PUZZLE_HASH = LAUNCHER_PUZZLE.get_tree_hash() SINGLETON_MOD_HASH = SINGLETON_MOD.get_tree_hash() POOL_REWARD_PREFIX_MAINNET = bytes32.fromhex("ccd5bb71183532bff220ba46c268991a00000000000000000000000000000000") def check_coin_solution(coin_solution: CoinSolution): # breakpoint() try: cost, result = coin_solution.puzzle_reveal.run_with_cost(INFINITE_COST, coin_solution.solution) except Exception as ex: print(ex) # breakpoint() print(ex) def adaptor_for_singleton_inner_puzzle(puzzle: Program) -> Program: # this is prety slow return Program.to(binutils.assemble("(a (q . %s) 3)" % binutils.disassemble(puzzle))) def launcher_conditions_and_spend_bundle( parent_coin_id: bytes32, launcher_amount: uint64, initial_singleton_inner_puzzle: Program, metadata: List[Tuple[str, str]], launcher_puzzle: Program = LAUNCHER_PUZZLE, ) -> Tuple[Program, bytes32, List[Program], SpendBundle]: launcher_puzzle_hash = launcher_puzzle.get_tree_hash() launcher_coin = Coin(parent_coin_id, launcher_puzzle_hash, launcher_amount) singleton_full_puzzle = SINGLETON_MOD.curry( SINGLETON_MOD_HASH, launcher_coin.name(), launcher_puzzle_hash, initial_singleton_inner_puzzle ) singleton_full_puzzle_hash = singleton_full_puzzle.get_tree_hash() message_program = Program.to([singleton_full_puzzle_hash, launcher_amount, metadata]) expected_announcement = Announcement(launcher_coin.name(), message_program.get_tree_hash()) expected_conditions = [] expected_conditions.append( Program.to( binutils.assemble(f"(0x{ConditionOpcode.ASSERT_COIN_ANNOUNCEMENT.hex()} 0x{expected_announcement.name()})") ) ) expected_conditions.append( Program.to( binutils.assemble(f"(0x{ConditionOpcode.CREATE_COIN.hex()} 0x{launcher_puzzle_hash} {launcher_amount})") ) ) launcher_solution = Program.to([singleton_full_puzzle_hash, launcher_amount, metadata]) coin_solution = CoinSolution(launcher_coin, launcher_puzzle, launcher_solution) spend_bundle = SpendBundle([coin_solution], G2Element()) lineage_proof = Program.to([parent_coin_id, launcher_amount]) return lineage_proof, launcher_coin.name(), expected_conditions, spend_bundle def singleton_puzzle(launcher_id: Program, launcher_puzzle_hash: bytes32, inner_puzzle: Program) -> Program: return SINGLETON_MOD.curry(SINGLETON_MOD_HASH, launcher_id, launcher_puzzle_hash, inner_puzzle) def singleton_puzzle_hash(launcher_id: Program, launcher_puzzle_hash: bytes32, inner_puzzle: Program) -> bytes32: return singleton_puzzle(launcher_id, launcher_puzzle_hash, inner_puzzle).get_tree_hash() def solution_for_singleton_puzzle(lineage_proof: Program, my_amount: int, inner_solution: Program) -> Program: return Program.to([lineage_proof, my_amount, inner_solution]) def p2_singleton_puzzle(launcher_id: Program, launcher_puzzle_hash: bytes32) -> Program: return P2_SINGLETON_MOD.curry(SINGLETON_MOD_HASH, launcher_id, launcher_puzzle_hash) def p2_singleton_puzzle_hash(launcher_id: Program, launcher_puzzle_hash: bytes32) -> bytes32: return p2_singleton_puzzle(launcher_id, launcher_puzzle_hash).get_tree_hash() def test_only_odd_coins_0(): blocks = initial_blocks() farmed_coin = list(blocks[-1].get_included_reward_coins())[0] metadata = [("foo", "bar")] ANYONE_CAN_SPEND_PUZZLE = Program.to(1) launcher_amount = uint64(1) launcher_puzzle = LAUNCHER_PUZZLE launcher_puzzle_hash = launcher_puzzle.get_tree_hash() initial_singleton_puzzle = adaptor_for_singleton_inner_puzzle(ANYONE_CAN_SPEND_PUZZLE) lineage_proof, launcher_id, condition_list, launcher_spend_bundle = launcher_conditions_and_spend_bundle( farmed_coin.name(), launcher_amount, initial_singleton_puzzle, metadata, launcher_puzzle ) conditions = Program.to(condition_list) coin_solution = CoinSolution(farmed_coin, ANYONE_CAN_SPEND_PUZZLE, conditions) spend_bundle = SpendBundle.aggregate([launcher_spend_bundle, SpendBundle([coin_solution], G2Element())]) run = asyncio.get_event_loop().run_until_complete coins_added, coins_removed = run(check_spend_bundle_validity(bt.constants, blocks, spend_bundle)) coin_set_added = set([_.coin for _ in coins_added]) coin_set_removed = set([_.coin for _ in coins_removed]) launcher_coin = launcher_spend_bundle.coin_solutions[0].coin assert launcher_coin in coin_set_added assert launcher_coin in coin_set_removed assert farmed_coin in coin_set_removed # breakpoint() singleton_expected_puzzle_hash = singleton_puzzle_hash(launcher_id, launcher_puzzle_hash, initial_singleton_puzzle) expected_singleton_coin = Coin(launcher_coin.name(), singleton_expected_puzzle_hash, launcher_amount) assert expected_singleton_coin in coin_set_added # next up: spend the expected_singleton_coin # it's an adapted `ANYONE_CAN_SPEND_PUZZLE` # then try a bad lineage proof # then try writing two odd coins # then try writing zero odd coins # then, destroy the singleton with the -113 hack return 0
5078630d55858cd9668eb7877bb6ed87f89a2020
acb8e84e3b9c987fcab341f799f41d5a5ec4d587
/langs/0/a3y.py
c12946f262d52a5b5e020798136feaac117c0a6b
[]
no_license
G4te-Keep3r/HowdyHackers
46bfad63eafe5ac515da363e1c75fa6f4b9bca32
fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2
refs/heads/master
2020-08-01T12:08:10.782018
2016-11-13T20:45:50
2016-11-13T20:45:50
73,624,224
0
1
null
null
null
null
UTF-8
Python
false
false
486
py
import sys def printFunction(lineRemaining): if lineRemaining[0] == '"' and lineRemaining[-1] == '"': if len(lineRemaining) > 2: #data to print lineRemaining = lineRemaining[1:-1] print ' '.join(lineRemaining) else: print def main(fileName): with open(fileName) as f: for line in f: data = line.split() if data[0] == 'a3Y': printFunction(data[1:]) else: print 'ERROR' return if __name__ == '__main__': main(sys.argv[1])
673ee013002ca17e8e0fec41ab801aa3d9ac69ce
356fd94e07539437ced3514c664be5e8cec40a88
/amicus/simplify/analyst/encode.py
fbab552e5f889a64fcf105e2cc999c37750559d2
[ "Apache-2.0" ]
permissive
WithPrecedent/amicus
6740de4c4c43c0ca3b6f71ff1892322b92f61678
0de6d90c34b8402f4464dcba784349514b3b8e42
refs/heads/main
2023-04-25T04:18:58.842285
2021-05-19T19:01:00
2021-05-19T19:01:00
339,543,031
1
0
null
null
null
null
UTF-8
Python
false
false
9,607
py
""" simplify.analyst.encode Corey Rayburn Yung <[email protected]> Copyright 2021, Corey Rayburn Yung License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0) Contents: """ from __future__ import annotations import dataclasses from typing import (Any, Callable, ClassVar, Dict, Hashable, Iterable, List, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Set, Tuple, Type, Union) import amicus from amicus import project @dataclasses.dataclass class Encode(amicus.project.Step): """Wrapper for a Technique. An instance will try to return attributes from 'contents' if the attribute is not found in the Step instance. Args: name (str): designates the name of a class instance that is used for internal referencing throughout amicus. For example, if an amicus instance needs settings from a Configuration instance, 'name' should match the appropriate section name in a Configuration instance. Defaults to None. contents (Technique): stored Technique instance used by the 'implement' method. iterations (Union[int, str]): number of times the 'implement' method should be called. If 'iterations' is 'infinite', the 'implement' method will continue indefinitely unless the method stops further iteration. Defaults to 1. parameters (Mapping[Any, Any]]): parameters to be attached to 'contents' when the 'implement' method is called. Defaults to an empty dict. parallel (ClassVar[bool]): indicates whether this Component design is meant to be at the end of a parallel workflow structure. Defaults to True. """ name: str = 'encode' contents: Encoder = None container: str = 'analyst' parameters: Union[Mapping[str, Any], project.Parameters] = ( project.Parameters()) @dataclasses.dataclass class Encoder(amicus.quirks.Loader, amicus.project.Technique): """Wrapper for an encoder from category-encoders. Args: name (str): designates the name of a class instance that is used for internal referencing throughout amicus. For example, if an amicus instance needs settings from a Configuration instance, 'name' should match the appropriate section name in a Configuration instance. Defaults to None. contents (Technique): stored Technique instance used by the 'implement' method. iterations (Union[int, str]): number of times the 'implement' method should be called. If 'iterations' is 'infinite', the 'implement' method will continue indefinitely unless the method stops further iteration. Defaults to 1. parameters (Mapping[Any, Any]]): parameters to be attached to 'contents' when the 'implement' method is called. Defaults to an empty dict. parallel (ClassVar[bool]): indicates whether this Component design is meant to be at the end of a parallel workflow structure. Defaults to False. """ name: str = None contents: Union[Callable, Type, object, str] = None container: str = 'encode' iterations: Union[int, str] = 1 parameters: Union[Mapping[str, Any], project.Parameters] = ( project.Parameters()) module: str = None """ Public Methods """ def implement(self, project: amicus.Project) -> amicus.Project: """[summary] Args: project (amicus.Project): [description] Returns: amicus.Project: [description] """ self.contents = self.contents(**self.parameters) data = project.data data.x_train = self.contents.fit(data.x_train, data.y_train) data.x_train = self.contents.transform(data.x_train) if data.x_test is not None: data.x_test = self.contents.transform(data.x_test) if data.x_validate is not None: data.x_validate = self.contents.transform(data.x_validate) project.data = data return project catalog = amicus.base.Catalog( contents = { 'backward_encode': Encoder( name = 'backward encoder', contents = 'BackwardDifferenceEncoder', parameters = project.Parameters( name = 'backward_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'base_n_encode': Encoder( name = 'base n encoder', contents = 'BaseNEncoder', parameters = project.Parameters( name = 'base_n_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'binary_encode': Encoder( name = 'binary encoder', contents = 'BinaryEncoder', parameters = project.Parameters( name = 'binary_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'cat_boost_encode': Encoder( name = 'category boost encoder', contents = 'CatBoostEncoder', parameters = project.Parameters( name = 'cat_boost_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'count_encode': Encoder( name = 'count encoder', contents = 'CountEncoder', parameters = project.Parameters( name = 'count_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'glmm_encode': Encoder( name = 'glmm encoder', contents = 'GLMMEncoder', parameters = project.Parameters( name = 'glmm_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'hashing_encode': Encoder( name = 'hashing encoder', contents = 'HashingEncoder', parameters = project.Parameters( name = 'hashing_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'helmert_encode': Encoder( name = 'helmert encoder', contents = 'HelmertEncoder', parameters = project.Parameters( name = 'helmert_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'james_stein_encode': Encoder( name = 'james stein encoder', contents = 'JamesSteinEncoder', parameters = project.Parameters( name = 'james_stein_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'leave_one_out': Encoder( name = 'leave one encoder', contents = 'LeaveOneOutEncoder', parameters = project.Parameters( name = 'leave_one_out_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'm_estimate_encode': Encoder( name = 'm estimate encoder', contents = 'MEstimateEncoder', parameters = project.Parameters( name = 'm_estimate_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'one_hot_encode': Encoder( name = 'backward encoder', contents = 'OneHotEncoder', parameters = project.Parameters( name = 'one_hot_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'ordinal_encode': Encoder( name = 'ordinal encoder', contents = 'OrdinalEncoder', parameters = project.Parameters( name = 'ordinal_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'sum_encode': Encoder( name = 'sum encoder', contents = 'SumEncoder', parameters = project.Parameters( name = 'sum_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'polynomial_encode': Encoder( name = 'polynomial encoder', contents = 'PolynomialEncoder', parameters = project.Parameters( name = 'polynomial_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'target_encode': Encoder( name = 'target encoder', contents = 'TargetEncoder', parameters = project.Parameters( name = 'target_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders'), 'weight_of_evidence_encode': Encoder( name = 'weight of evidence encoder', contents = 'WOEEncoder', parameters = project.Parameters( name = 'weight_of_evidence_encode', implementation = {'cols': 'data.categoricals'}), module = 'category_encoders')})
8a7146223b544962aa2917ea4cf93337f3460901
3740de0d6e43ea140fc09ab314e4c492603ba185
/scripts/sources/s_checklist_scenariobased_step07.py
f74d1ac5806b3df08f57092c9a18ef1c0abce61d
[ "MIT" ]
permissive
s0ap/arpmRes
29c60c65fd3e11be1cc31d46494e5b3ebf6e05ab
ddcc4de713b46e3e9dcb77cc08c502ce4df54f76
refs/heads/master
2022-02-16T05:01:22.118959
2019-08-20T16:45:02
2019-08-20T16:45:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,564
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.2.0 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # s_checklist_scenariobased_step07 [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_checklist_scenariobased_step07&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-7). # + import numpy as np import pandas as pd from arpym.portfolio import spectral_index from arpym.statistics import meancov_sp, quantile_sp # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step07-parameters) # + # indicates which projection to continue from # True: use copula-marginal projections # False: use historical projections copula_marginal = True lam = 3e-7 # parameter of exponential utility function c_quantile = 0.95 # confidence level for the quantile satisfaction measure c_es = 0.95 # confidence level for the negative expected shortfall # - # ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step07-implementation-step00): Load data # + path = '../../../databases/temporary-databases/' if copula_marginal: # Projection db_projection_tools = pd.read_csv(path + 'db_projection_tools.csv') j_ = int(db_projection_tools['j_'][0]) db_scenprob = pd.read_csv(path + 'db_scenario_probs.csv') p = db_scenprob['p'].values # Pricing db_pricing = pd.read_csv(path + 'db_pricing.csv') pi_tnow_thor = db_pricing.values # Aggregation db_exante_perf = pd.read_csv(path + 'db_exante_perf.csv') y_h = db_exante_perf.values.squeeze() else: # Projection db_projection_tools = pd.read_csv(path + 'db_projection_bootstrap_tools.csv') j_ = int(db_projection_tools['j_'][0]) db_scenprob = pd.read_csv(path + 'db_scenario_probs_bootstrap.csv') p = db_scenprob['p'].values # Pricing db_pricing = pd.read_csv(path + 'db_pricing_historical.csv') pi_tnow_thor = db_pricing.values # Aggregation db_exante_perf = pd.read_csv(path + 'db_exante_perf_historical.csv') y_h = db_exante_perf.values.squeeze() db_holdings = pd.read_csv(path + 'db_holdings.csv') h = np.squeeze(db_holdings.values) # - # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step07-implementation-step01): Calculate certainty equivalent satisfaction measure # + # expected utility expected_utility = p @ (-np.exp(-lam * y_h)) # expected utility computation # certainty equivalent satisfaction measure cert_eq_yh = -(1 / lam) * np.log(-expected_utility) # - # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step07-implementation-step02): Quantile satisfaction measure # quantile q_yh = quantile_sp(1 - c_quantile, y_h, p, method='kernel_smoothing') # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step07-implementation-step03): Expected shortfall satisfaction measure # + # indicator function def indicator(x): return (0 <= x and x <= 1 - c_es) # spectrum function def spectr_es(x): return (1 / (1 - c_es)) * indicator(x) # negative expected shortfall es_yh, _ = spectral_index(spectr_es, pi_tnow_thor, p, h) # - # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step07-implementation-step04): Expectation and variance satisfaction measures # expectation satisfaction measure mean_yh, var_yh = meancov_sp(y_h, p) # opposite of variance is satisfaction measure neg_var_yh = -var_yh # ## [Step 5](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_scenariobased_step07-implementation-step05): Save database # + out = pd.DataFrame({'cert_eq_yh': pd.Series(cert_eq_yh), 'q_yh': pd.Series(q_yh), 'es_yh': pd.Series(es_yh), 'mean_yh': pd.Series(mean_yh), 'neg_var_yh': pd.Series(neg_var_yh), 'c_es': pd.Series(c_es), 'c_quantile': pd.Series(c_quantile)}) if copula_marginal: out.to_csv(path + 'db_quantile_and_satis.csv', index=False) else: out.to_csv(path + 'db_quantile_and_satis_historical.csv', index=False) del out
df39f1b43eaa8211c126ff9d37b5062dbbbf6b0a
7f99fb1f9d051dbcd13770e7a08e92f90e6027ca
/Analyzer/fakeRateGetRatesMuons_DiBoson_cfg.py
505ad378830fb34d6a4008d8b48de6479a3b79a3
[]
no_license
kmtos/AnalyzerGeneratorRecoVariousFunctions
be54dd360a37b4ef1aeef2ee692ada4351b7db2e
acd8cde2f5657674c73eae9af28f3235b9b3f7c5
refs/heads/master
2021-01-10T08:34:49.953330
2018-07-26T12:36:41
2018-07-26T12:36:41
50,570,873
0
0
null
null
null
null
UTF-8
Python
false
false
3,085
py
### PDG IDs ### A_PDGID = 36 MU_PDGID = 13 TAU_PDGID = 15 ANY_PDGID = 0 ### Tau decay types ### TAU_HAD = 0 TAU_MU = 1 TAU_E = 2 TAU_ALL = 3 ### Tau hadronic decay types ### TAU_ALL_HAD = -1 TAU_1PRONG_0NEUTRAL = 0 TAU_1PRONG_1NEUTRAL = 1 TAU_1PRONG_2NEUTRAL = 2 TAU_1PRONG_3NEUTRAL = 3 TAU_1PRONG_NNEUTRAL = 4 TAU_2PRONG_0NEUTRAL = 5 TAU_2PRONG_1NEUTRAL = 6 TAU_2PRONG_2NEUTRAL = 7 TAU_2PRONG_3NEUTRAL = 8 TAU_2PRONG_NNEUTRAL = 9 TAU_3PRONG_0NEUTRAL = 10 TAU_3PRONG_1NEUTRAL = 11 TAU_3PRONG_2NEUTRAL = 12 TAU_3PRONG_3NEUTRAL = 13 TAU_3PRONG_NNEUTRAL = 14 TAU_RARE = 15 ### No consideration of pT rank ### ANY_PT_RANK = -1 ################# # Initialization ################# import FWCore.ParameterSet.Config as cms import FWCore.Utilities.FileUtils as FileUtils process = cms.Process("CleanJetsAnalyzer") ################################################### # initialize MessageLogger and output report ################################################### process.load("FWCore.MessageLogger.MessageLogger_cfi") process.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(100) process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True), SkipEvent = cms.untracked.vstring('ProductNotFound') ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) #################### # Input File List #################### process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring( 'root://eoscms/FILE_PATHRegionB_selection_NUM.root') ) process.ggh = cms.EDAnalyzer("FakeRateMiniAODGetRatesMuons", outFileName = cms.string('/afs/cern.ch/work/k/ktos/public/CMSSW_8_0_17/src/AnalyzerGeneratorRecoVariousFunctions/Analyzer/BSUB/DIRNAME/DIRNAME_Plots_NUM.root'), mu1Tag = cms.InputTag("GetMuOne"), muonsTag = cms.InputTag("MuonsIDdxydz"), tauTag = cms.InputTag("slimmedTausMuonCleaned"), tauIsoTag = cms.string("byMediumIsolationMVArun2v1DBoldDMwLT"), decayModeFindingTag = cms.string("decayModeFinding"), checkTau = cms.bool(False), checkTauIso = cms.bool(False), passTauIso = cms.bool(False), mu3dRMin = cms.double(0.0), mu3dRMax = cms.double(0.8), tauPtCut = cms.double(10.0), mu3dROverlapCut = cms.double(.4), requireRemovedMuon = cms.bool(True), checkInvMass = cms.bool(True), checkInvMassMin = cms.double(81), checkInvMassMax = cms.double(101), relIsoCutVal = cms.double(0.25), passRelIso = cms.bool(True), mu12dRCut = cms.double(600), oppositeSign = cms.bool(True), passdR = cms.bool(True), mu2PtCut = cms.double(3), passMu2PtCutForMu3Rate = cms.bool(True), isMC = cms.bool(True), xsec = cms.double(XSEC), lumi = cms.double(LUMI_DATA), summedWeights = cms.double(SUMMED_WEIGHTS), pileupSummaryInfo = cms.InputTag("slimmedAddPileupInfo", "", "PAT"), genEventInfoToken = cms.InputTag("generator", "", "SIM"), PileupFileName = cms.string('/afs/cern.ch/user/k/ktos/GroupDir/CMSSW_8_0_17/src/AnalyzerGeneratorRecoVariousFunctions/Analyzer/FILE_TESTS/PileupWeights.root') ) process.p2 = cms.Path( process.ggh )
49a564d5f2ae3ade119c6bd9772c475fc668c306
f2ba48da8c66c454470dd1441904797e5fbc509c
/WDLJ/zgw_goods/zgw_goods/run_crawl/run_wag.py
b2fd1cef7aaa4327c6c57db1d3e7c346770e5c8c
[]
no_license
awmace/Demo
862800b81e4088615a92d2da0a576a5660e0fec9
9734e50578bda139d3781478b7170af723c5881a
refs/heads/master
2023-03-06T09:01:02.321914
2021-02-20T07:41:25
2021-02-20T07:41:25
340,599,537
0
0
null
null
null
null
UTF-8
Python
false
false
79
py
import os os.system('scrapy crawl uploadwuage') os.system('scrapy crawl wuage')
b5ccbc7a42bed9f50e10a78f16edea638f7d2b4d
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_070/ch164_2020_06_19_01_22_22_398779.py
bd37e300eab69845e9b34b2c8a398225a70f5f0d
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
113
py
def traduz(ingles, eng2port): port = [] for i in ingles: port.append(eng2port[i]) return port
a94dad9094cd2893b487f36a7115d0663e3c5db0
526bf18a8695862067c817f432ab197ceb645f39
/migrations/versions/76fb82b8961b_cars_add_location_diller.py
985f450b99df7550155f2a0c2b4945f918d451e9
[]
no_license
sintimaski/bfs-be
a7fd623911a2220face49a0ef84574f3fd7a09a8
964a9c7e9cc876aaf8b0723d6b3f26bd378c3721
refs/heads/master
2023-08-02T09:00:44.855055
2021-09-22T13:07:01
2021-09-22T13:07:01
339,531,610
0
0
null
null
null
null
UTF-8
Python
false
false
704
py
"""common add location diller Revision ID: 76fb82b8961b Revises: 920ac7659cb4 Create Date: 2020-09-15 08:23:44.523023 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "76fb82b8961b" down_revision = "920ac7659cb4" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "car_product", sa.Column("location_diller", sa.Text(), nullable=True) ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("car_product", "location_diller") # ### end Alembic commands ###
b6a81ff24dc21edef75de72eabcc703386468603
33c51931bc7d6f73da5a64ecc0e7cb751e7fc62c
/karesansui/db/model/option.py
b43f24a1ca8043122b981e017ab2dccc30551e60
[ "MIT", "GPL-1.0-or-later" ]
permissive
qmutz/karesansui
e86ed107f313f8c4140797a2c3250c5f16b524c2
f4ba1cf6f88cf76c3e4dbc444139d73134f7c9d1
refs/heads/develop
2023-05-06T14:52:38.668631
2019-02-01T03:57:00
2019-02-01T03:57:00
316,682,704
0
0
MIT
2021-06-03T14:59:45
2020-11-28T07:43:33
null
UTF-8
Python
false
false
6,806
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of Karesansui Core. # # Copyright (C) 2009-2012 HDE, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # import sqlalchemy from sqlalchemy.orm import mapper, clear_mappers, relation import karesansui import karesansui.db.model from karesansui.lib.const import DEFAULT_LANGS def get_option_table(metadata, now): """<comment-ja> Option のテーブル定義を返却します。 @param metadata: MetaData @type metadata: sqlalchemy.schema.MetaData @param now: now @type now: Datatime @return: sqlalchemy.schema.Table </comment-ja> <comment-en> TODO: English Comment </comment-en> """ return sqlalchemy.Table('option', metadata, sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True, autoincrement=True, ), sqlalchemy.Column('created_user_id', sqlalchemy.Integer, sqlalchemy.ForeignKey('user.id'), ), sqlalchemy.Column('modified_user_id', sqlalchemy.Integer, sqlalchemy.ForeignKey('user.id'), ), sqlalchemy.Column('key', sqlalchemy.String(12), nullable=False, unique=True, ), sqlalchemy.Column('value', sqlalchemy.Text, nullable=True, ), sqlalchemy.Column('created', sqlalchemy.DateTime, default=now, ), sqlalchemy.Column('modified', sqlalchemy.DateTime, default=now, onupdate=now, ), ) class Option(karesansui.db.model.Model): """<comment-ja> Optionテーブルモデルクラス </comment-ja> <comment-en> TODO: English Comment </comment-en> """ def __init__(self, created_user, modified_user, key, value=None): """<comment-ja> @param created_user: 作成者 @type created_user: User @param modified_user: 最終更新者 @type modified_user: User @param key: option key @type key: str @param value: option value @type value: str(Text) </comment-ja> <comment-en> TODO: English Comment </comment-en> """ self.created_user = created_user self.modified_user = modified_user self.key = key self.value = value def get_json(self, languages): ret = {} ret["id"] = self.id ret["key"] = self.key ret["value"] = self.value ret["created_user_id"] = self.created_user_id ret["created_user"] = self.created_user.get_json(languages) ret["modified_user_id"] = self.modified_user_id ret["modified_user"] = self.modified_user.get_json(languages) try: ret["created"] = self.created.strftime( DEFAULT_LANGS[languages]['DATE_FORMAT'][1]) except: ret["created"] = "unknown" try: ret["modified"] = self.modified.strftime( DEFAULT_LANGS[languages]['DATE_FORMAT'][1]) except: ret["modified"] = "unknown" return ret def __repr__(self): return "Option<'key=%s, value=%s>" \ % (self.key, self.value) def reload_mapper(metadata, now): """<comment-ja> Option(Model)のマッパーをリロードします。 @param metadata: リロードしたいMetaData @type metadata: sqlalchemy.schema.MetaData @param now: now @type now: Datatime </comment-ja> <comment-en> TODO: English Comment </comment-en> """ t_option = get_option_table(metadata, now) t_user = metadata.tables['user'] mapper(Option, t_option, properties={ 'created_user' : relation(karesansui.db.model.user.User, primaryjoin=t_option.c.created_user_id==t_user.c.id), 'modified_user' : relation(karesansui.db.model.user.User, primaryjoin=t_option.c.modified_user_id==t_user.c.id), }) if __name__ == '__main__': import sqlalchemy.orm bind_name = 'sqlite:///:memory:' engine = sqlalchemy.create_engine(bind_name, encoding="utf-8", convert_unicode=True, #assert_unicode='warn', # DEBUG echo=True, echo_pool=False ) metadata = sqlalchemy.MetaData(bind=engine) if metadata.bind.name == 'sqlite': _now = sqlalchemy.func.datetime('now', 'localtime') else: _now = sqlalchemy.func.now() reload_mapper(metadata, _now) import pdb; pdb.set_trace() metadata.drop_all() metadata.create_all() Session = sqlalchemy.orm.sessionmaker(bind=engine, autoflush=False) session = Session() # INSERT # SELECT One # UPDATE # DELETE
fd67b2cea25f2c76efaf85561698eed8bbd55edd
88e06bab1989c81a2dd649bb09b144fa7c958f89
/leet_subarray_with_k_different_integers.py
e67b6bb2f63e7f22e17fc918d64b415ae5cb16f5
[]
no_license
VaibhavD143/Coding
4499526b22ee4ef13f66c3abcea671c80a8f748a
5de3bae8891c7d174cbc847a37c3afb00dd28f0e
refs/heads/master
2023-08-06T21:56:44.934954
2021-10-09T18:31:29
2021-10-09T18:31:29
263,890,286
0
0
null
null
null
null
UTF-8
Python
false
false
1,572
py
""" Intution: l1 is left-most valid index for substring ending at rth index l2 is left-most index from where substring becomes invalid ending at rth index so we can generate l2-l1 substrings ending at rth index Valid : have exactly K distinct elements """ from collections import defaultdict class Solution: def subarraysWithKDistinct(self, lst: List[int], K: int) -> int: l1 = l2 = res = 0 dist1 = dist2 = 0 ha1 = {} ha2 = {} for r in range(len(lst)): if ha1.get(lst[r],0) == 0: dist1+=1 if ha2.get(lst[r],0) == 0: dist2+=1 ha1[lst[r]] = ha1.get(lst[r],0)+1 ha2[lst[r]] = ha2.get(lst[r],0)+1 while dist1>K: ha1[lst[l1]] -=1 if ha1[lst[l1]] == 0: dist1-=1 l1+=1 while dist2>=K: ha2[lst[l2]] -=1 if ha2[lst[l2]] == 0: dist2-=1 l2+=1 res+=l2-l1 return res # return self.atMostK(A,K)-self.atMostK(A,K-1) def atMostK(self,lst,k): l = res = 0 ha = defaultdict(int) dist = 0 for r in range(len(lst)): if ha[lst[r]] == 0: dist+=1 ha[lst[r]]+=1 while dist>k: ha[lst[l]]-=1 if ha[lst[l]] == 0: dist-=1 l+=1 res+= r-l+1 return res
cfeefe2c257d1544d9c955d1dc11614118070a9c
15e8a393f6c71ba77094a1718f4f89050409c7ae
/library/templatetags/book_tags.py
9a7f4c4fe3a48fb66d691bf5f46e69dbe8b81227
[]
no_license
emilte/johansson
21a3e20208c67725776af0f94de4c29150935b50
d16bdde26e840814562f668904b2f5588c0a13ad
refs/heads/master
2023-07-23T21:01:32.830302
2021-09-05T14:56:01
2021-09-05T14:56:01
390,360,563
0
0
null
2021-08-30T00:42:49
2021-07-28T13:26:31
SCSS
UTF-8
Python
false
false
2,133
py
# imports import PIL import random from django import template from django.conf import settings from django.utils import timezone from django.templatetags.static import static from django.contrib.auth.models import Permission # End: imports ----------------------------------------------------------------- register = template.Library() # https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/ @register.inclusion_tag('library/components/book.html') def display_book(request, perms, book, **kwargs): return { 'request': request, 'perms': perms, 'book': book, 'classes': kwargs.get('classes'), } @register.inclusion_tag('library/components/book_filter_form.html') def display_book_filter(request, perms, form, **kwargs): return { 'request': request, 'perms': perms, 'form': form, 'classes': kwargs.get('classes'), 'action': kwargs.get('action'), } # https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/ # @register.simple_tag # def get_image(model, fielname): # if not model or not getattr(model, fieldname): # return static('/root/img/image-placeholder.png') # return getattr(model, fieldname).url # # # https://stackoverflow.com/questions/16348003/displaying-a-timedelta-object-in-a-django-template # @register.filter() # def smooth_timedelta(timedeltaobj): # """Convert a datetime.timedelta object into Days, Hours, Minutes, Seconds.""" # if not timedeltaobj: # return None # secs = timedeltaobj.total_seconds() # timetot = "" # if secs > 86400: # 60sec * 60min * 24hrs # days = secs // 86400 # timetot += "{} dager".format(int(days)) # secs = secs - days*86400 # # if secs > 3600: # hrs = secs // 3600 # timetot += " {} timer".format(int(hrs)) # secs = secs - hrs*3600 # # if secs > 60: # mins = secs // 60 # timetot += " {} minutter".format(int(mins)) # secs = secs - mins*60 # # if secs > 0: # timetot += " {} sekunder".format(int(secs)) # return timetot #
f38c4e2a896f8c73c898cc11185b6085feb8c88d
e9f40b2ae17b5bf7f7fba339b00cb59e2cce34fa
/uclbrt/qrmaster/syn_2/qrmaster.py
d246e2572213241f40433b368df2c79a4a91ce75
[]
no_license
linyouwei/pycharm
0d8dbfd83fcc88077137bcbec063186ce0fb622c
246fe3ab855f7614fd05f2d31239170077791822
refs/heads/master
2021-01-19T17:38:35.698089
2018-03-26T10:12:50
2018-03-26T10:12:50
101,077,696
0
1
null
null
null
null
UTF-8
Python
false
false
9,302
py
# encoding=utf-8 import requests import hashlib from bs4 import BeautifulSoup import json import re class QrmasterClass: # 切换集群 qrm_client = '' qrm_bpass = '' def __init__(self, qrm_client, qrm_bpass): self.qrm_client = qrm_client self.qrm_bpass = qrm_bpass def change_commuity(self, s, qrm_community_data): info = s.get(self.qrm_client + '/userCenter.html') main_info = BeautifulSoup(info.text, "html.parser") com_list = main_info.find('ul', id='communitySwitch') no_a = com_list.find('ul', class_='dropdown-menu') a_list = no_a.find_all('a') group_no = 0 for i in a_list: if qrm_community_data['cname'] in i.string: group_no = i['data-value'] # 获取no,发送请求 group_data = { 'no': group_no, 'return': '/userCenter.html' } s.get(self.qrm_client + '/Home/CommunityPage/entry.html', params=group_data) s.get(self.qrm_client + '/userCenter.html') return s # 申请审核 def qrm_apply_verity(self, s): img_url = self.up_image(s) apply_data = { "isforeign": "0", "companyname": "畅联", "address": "guangdong", "representative": "555", "telephone": "13480251015", "fax": "", "business": "444", "bpath": img_url, "areaCode": "86" } response = s.post(self.qrm_client + '/Home/CommunityCenter/postAuthenticationCompany', data=apply_data).json() # 上传图片 def up_image(self, s): img_file = { 'config': (None, 'comVerify'), 'file': open(r'./verify.png', 'rb')} response = s.post(self.qrm_client + '/Home/File/upload', files=img_file).json() file_url = response['data']['filename'] return file_url # 同步美住客栈 def syn_community(self, s, mz_login_account): s = QrmasterClass.syn_login_meizhu(self, s, mz_login_account) resp_data = s.post(self.qrm_client + '/Home/Sync/getHotel').json() com_data = resp_data['data'][-1] # 此时得到的com_data 中的communityid是为0 params = { "hotelid": com_data["hotelentity_id"], "hotelname": com_data["name"], "communityid": com_data["communityid"], "universaltime_id": com_data["universaltime_id"], "communityname": com_data["name"] } data = { "hotels": '[' + json.dumps(params, ensure_ascii=False) + ']' } syn_url = self.qrm_client + '/Home/Sync/syncCommunity' s.post(syn_url, data=data) # 重复请求getHotel 得到community_no resp_data = s.post(self.qrm_client + '/Home/Sync/getHotel').json() com_data = resp_data['data'][-1] com_data['communityid'] = com_data['communityid'] # 同步房间 hotel_data = { 'hotelId': com_data["hotelentity_id"], 'communityId': com_data["communityid"], } res = s.post(self.qrm_client + '/Home/Sync/getRoom', data=hotel_data).json() print(res) room_dict = {} room_list = [] room_str = '' for room in res['data'][0]['room']: room_dict['id'] = room['id'] room_dict['name'] = room['name'] room_list.append(room_dict) room_str = room_str + json.dumps(room_dict) + ',' add_room_data = { 'hotelId': com_data["hotelentity_id"], 'communityId': com_data["communityid"], 'builderName': '楼栋1', 'builderNum': '1', 'floorName': '楼层1', 'floorNum': '1', 'roomsAdd': '[' + room_str[0:room_str.__len__() - 1] + ']', } s.post(self.qrm_client + '/Home/Sync/syncRoomAdd', data=add_room_data) #修改锁的类型为二维码 def update_room_type(self, s): req_url = self.qrm_client + '/Home/Room/saveRoom' room_data = self.get_all_room_info(s) for i in range(room_data.__len__()): for single_room in room_data: single_room['locktype'] = '1' s.post(req_url, data=single_room) #得到锁掌柜所有的房间信息 def get_all_room_info(self, s): # 得到每个房间页面的请求链接 req_index_url = self.qrm_client + '/room.html' room_html = s.get(req_index_url) soup = BeautifulSoup(room_html.text, "html.parser") div_tag = soup.find('div', id='doc-center-page') # print(table.tbody.tr.next_sibling.next_sibling) page_url = div_tag.find_all('a') page_url = page_url[:-page_url.__len__():-1] page_url_list = [] for i in page_url: page_url_list.append(i['href']) page_url_list.append('room_1.html') list_data = [] for url in page_url_list: # 房间id:'room' 房间名:'name'房间号:'no' 锁编号:'num' 锁类型'locktype' req_url = self.qrm_client + '/' + url data = s.get(req_url) soup = BeautifulSoup(data.text, "html.parser") table_soup = soup.find('table', id='roomTable') tr_list = table_soup.tbody.find_all('tr') # 计算tr的数量,得到有多少个房间 num = 0 for i in tr_list: num += 1 tr_soup = table_soup.tbody.tr td_soup = tr_soup.td count = 0 while True: data = {} for i in range(16): td_soup = td_soup.next_sibling data_room = {} data_room['room'] = td_soup['data-value'] data_room['name'] = td_soup['data-name'] data_room['no'] = td_soup['data-no'] data_room['num'] = td_soup['data-num'] data_room['locktype'] = td_soup['data-locktype'] list_data.append(data_room) count += 1 if count == num: break tr_soup = tr_soup.next_sibling td_soup = tr_soup.td return list_data # 在锁掌柜登陆美住账号 def syn_login_meizhu(self, s, mz_login_account): meizhu = mz_login_account['mobile'] mz_login_account.pop('mobile') mz_login_account['meizhu'] = meizhu print(mz_login_account) sync_switch_url = self.qrm_client + '/Home/Sync/switchAccount' s.post(sync_switch_url, data=mz_login_account) return s # 锁掌柜bpass def qrm_bpass_login(self, s, qrm_bpass_data): html_doc = s.get(self.qrm_bpass+'/Bpass/Public/login.html').text soup = BeautifulSoup(html_doc, 'html.parser') img = soup.find("img", {"id": "imgcode"}) img_path = self.qrm_bpass + img["src"] # req.get()得到一个response对象,对象存服务器返回的信息, # 返回的页面会存在.content和.text对象。 # .content返回的是字节码 # .text存的是Beautifulsoup根据猜测的编码方式将content内容编码成字符串。 while True: image = s.get(img_path, stream=True).content with open('./qrm_vcode.jpg', 'wb') as fd: fd.write(image) vcode = input("请输入验证码") qrm_bpass_data['vcode'] = vcode r = s.post(self.qrm_bpass +'/Bpass/Public/doLogin', data=qrm_bpass_data).json() if r['status'] == 200: break #锁掌柜通过认证 def pass_group_verity(self, req, qrm_community_data): query_verify_url = self.qrm_bpass + '/Bpass/ComAuthority/company.html' group_data = { 'type': '', 'status': '', 'name': qrm_community_data['cname'], 'no': '' } print(group_data) query_group = req.get(query_verify_url, params=group_data) soup = BeautifulSoup(query_group.text, 'html.parser') s_table = soup.find('table', id='questionTalbe') a_list = s_table.find_all('a') a_href = a_list[-1]['href'] reObj1 = re.compile('[0-9]+') id = reObj1.findall(a_href)[0] page_id = reObj1.findall(a_href)[1] # 通过审核 verify_page_url = self.qrm_bpass + '/Bpass/ComAuthority/companyStatus/id/' + id + '/userloginID/' + page_id + '.html' verify_data = { "id": (None, id), "status": (None, "3"), "agencyId": (None, "1"), "representative": (None, "33323"), "hotelSign": (None, "00000"), "brandTypeId": (None, "1"), "typeSignId": (None, "1"), "authorityNote": (None, "22244"), } req.post(verify_page_url, files=verify_data) # 新建美住客栈,通过审核,新建房间,在锁掌柜同步集群,同步房间,修改房间为二维码房间,
132f1bff7f32b051fa9726e0c877ce090d8c5506
c264153f9188d3af187905d846fa20296a0af85d
/Python/Python3网络爬虫开发实战/《Python3网络爬虫开发实战》随书源代码/jiepai/spider.py
7ca771da154f16c51cbbbec444ee1ad0371ecea2
[]
no_license
IS-OSCAR-YU/ebooks
5cd3c1089a221759793524df647e231a582b19ba
b125204c4fe69b9ca9ff774c7bc166d3cb2a875b
refs/heads/master
2023-05-23T02:46:58.718636
2021-06-16T12:15:13
2021-06-16T12:15:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,905
py
import os from multiprocessing.pool import Pool import requests from urllib.parse import urlencode from hashlib import md5 def get_page(offset): params = { 'offset': offset, 'format': 'json', 'keyword': '街拍', 'autoload': 'true', 'count': '20', 'cur_tab': '1', } url = 'http://www.toutiao.com/search_content/?' + urlencode(params) try: response = requests.get(url) if response.status_code == 200: return response.json() except requests.ConnectionError: return None def get_images(json): if json.get('data'): for item in json.get('data'): title = item.get('title') images = item.get('image_detail') for image in images: yield { 'image': image.get('url'), 'title': title } def save_image(item): if not os.path.exists(item.get('title')): os.mkdir(item.get('title')) try: response = requests.get(item.get('image')) if response.status_code == 200: file_path = '{0}/{1}.{2}'.format(item.get('title'), md5(response.content).hexdigest(), 'jpg') if not os.path.exists(file_path): with open(file_path, 'wb') as f: f.write(response.content) else: print('Already Downloaded', file_path) except requests.ConnectionError: print('Failed to Save Image') def main(offset): json = get_page(offset) for item in get_images(json): print(item) save_image(item) GROUP_START = 1 GROUP_END = 20 if __name__ == '__main__': pool = Pool() groups = ([x * 20 for x in range(GROUP_START, GROUP_END + 1)]) pool.map(main, groups) pool.close() pool.join()
335096cb45cac78881b05c35bf2129c9b91761c7
76742bf1c7dee6a01a0a41402fe734eeb0da3d74
/venv/bin/sphinx-autogen
7607e9cf2f5bad91acbff30af728168c78ff5ba7
[]
no_license
Zacharilius/tangoProject
e5490c80af3caaabe2cf132a40387db2574713dc
305fa20e344f8ad24514dff959be3e4e3632645e
refs/heads/master
2021-01-22T23:26:51.921743
2015-03-17T17:52:22
2015-03-17T17:52:22
29,359,319
0
0
null
null
null
null
UTF-8
Python
false
false
280
#!/home/zacharilius/Documents/GitHub/tangoProject/venv/bin/python # -*- coding: utf-8 -*- import re import sys from sphinx.ext.autosummary.generate import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())
741026f4fb0abd4abf264a986c30c02d470275ad
21c6989099b95e608c73b246c5ccc97dfac688da
/testserver.py
b7d29e7363de0bf4c74e4e5fc18ed0a4cdfda7d1
[]
no_license
ashcrow/taboot-tailer
a8200dedab4084041ec1f931b93d53360e5789f2
4c403cfaeb38e7a3b10478b74b28e5b31b1d4e5b
refs/heads/master
2021-01-21T01:18:05.144141
2014-05-23T15:39:45
2014-05-23T15:39:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
505
py
#!/usr/bin/env python import SimpleHTTPServer import SocketServer def main(): SocketServer.TCPServer.allow_reuse_address = True httpd = SocketServer.TCPServer(( "127.0.0.1", 5000), SimpleHTTPServer.SimpleHTTPRequestHandler) print "Do not use this server for anything but testing!" print "Serving on 127.0.0.1:5000. Hit ctrl+c to exit." try: httpd.serve_forever() except KeyboardInterrupt: httpd.shutdown() if __name__ == '__main__': main()
988107dcdf49e79a36105bd8984988e97d0bd846
f3b233e5053e28fa95c549017bd75a30456eb50c
/ptp1b_input/L84/84-85_wat_20Abox/set_1ns_equi.py
3b6c86ee4db3d4d1da891eb4aea66a5c7fe219e7
[]
no_license
AnguseZhang/Input_TI
ddf2ed40ff1c0aa24eea3275b83d4d405b50b820
50ada0833890be9e261c967d00948f998313cb60
refs/heads/master
2021-05-25T15:02:38.858785
2020-02-18T16:57:04
2020-02-18T16:57:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
916
py
import os dir = '/mnt/scratch/songlin3/run/ptp1b/L84/wat_20Abox/ti_one-step/84_85/' filesdir = dir + 'files/' temp_equiin = filesdir + 'temp_equi.in' temp_pbs = filesdir + 'temp_1ns_equi.pbs' lambd = [ 0.00922, 0.04794, 0.11505, 0.20634, 0.31608, 0.43738, 0.56262, 0.68392, 0.79366, 0.88495, 0.95206, 0.99078] for j in lambd: os.system("rm -r %6.5f" %(j)) os.system("mkdir %6.5f" %(j)) os.chdir("%6.5f" %(j)) os.system("rm *") workdir = dir + "%6.5f" %(j) + '/' #equiin eqin = workdir + "%6.5f_equi.in" %(j) os.system("cp %s %s" %(temp_equiin, eqin)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, eqin)) #PBS pbs = workdir + "%6.5f_1ns_equi.pbs" %(j) os.system("cp %s %s" %(temp_pbs, pbs)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, pbs)) #top os.system("cp ../84-85_merged.prmtop .") os.system("cp ../0.5_equi_0.rst .") #submit pbs os.system("qsub %s" %(pbs)) os.chdir(dir)
be50f1b323652c40e6b49cf9a2bd79de2d808a78
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_crocks.py
1a3f520d65582f3f690bc163e29107237760a5b2
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
231
py
from xai.brain.wordbase.nouns._crock import _CROCK #calss header class _CROCKS(_CROCK, ): def __init__(self,): _CROCK.__init__(self) self.name = "CROCKS" self.specie = 'nouns' self.basic = "crock" self.jsondata = {}
e072e242996c7e1919533e5daa584cf59c3457e6
2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02
/PyTorch/built-in/others/CLIP_for_PyTorch/transformers/tests/utils/test_modeling_tf_core.py
8edfc8eab02d4c58c3426a1fd71fe3e503ffa4c0
[ "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference", "GPL-1.0-or-later" ]
permissive
Ascend/ModelZoo-PyTorch
4c89414b9e2582cef9926d4670108a090c839d2d
92acc188d3a0f634de58463b6676e70df83ef808
refs/heads/master
2023-07-19T12:40:00.512853
2023-07-17T02:48:18
2023-07-17T02:48:18
483,502,469
23
6
Apache-2.0
2022-10-15T09:29:12
2022-04-20T04:11:18
Python
UTF-8
Python
false
false
15,226
py
# coding=utf-8 # Copyright 2019 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import os import tempfile from importlib import import_module from transformers import is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import _tf_gpu_memory_limit, require_tf, slow from ..test_modeling_tf_common import ids_tensor if is_tf_available(): import numpy as np import tensorflow as tf from transformers import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TFSharedEmbeddings, ) if _tf_gpu_memory_limit is not None: gpus = tf.config.list_physical_devices("GPU") for gpu in gpus: # Restrict TensorFlow to only allocate x GB of memory on the GPUs try: tf.config.set_logical_device_configuration( gpu, [tf.config.LogicalDeviceConfiguration(memory_limit=_tf_gpu_memory_limit)] ) logical_gpus = tf.config.list_logical_devices("GPU") print("Logical GPUs", logical_gpus) except RuntimeError as e: # Virtual devices must be set before GPUs have been initialized print(e) @require_tf class TFCoreModelTesterMixin: model_tester = None all_model_classes = () all_generative_model_classes = () test_mismatched_shapes = True test_resize_embeddings = True test_head_masking = True is_encoder_decoder = False def _prepare_for_class(self, inputs_dict, model_class, return_labels=False) -> dict: inputs_dict = copy.deepcopy(inputs_dict) if model_class in get_values(TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING): inputs_dict = { k: tf.tile(tf.expand_dims(v, 1), (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)) if isinstance(v, tf.Tensor) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING): inputs_dict["labels"] = tf.ones(self.model_tester.batch_size, dtype=tf.int32) elif model_class in get_values(TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING): inputs_dict["start_positions"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) inputs_dict["end_positions"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) elif model_class in [ *get_values(TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING), *get_values(TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING), ]: inputs_dict["labels"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) elif model_class in get_values(TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING): inputs_dict["next_sentence_label"] = tf.zeros(self.model_tester.batch_size, dtype=tf.int32) elif model_class in [ *get_values(TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING), *get_values(TF_MODEL_FOR_CAUSAL_LM_MAPPING), *get_values(TF_MODEL_FOR_MASKED_LM_MAPPING), *get_values(TF_MODEL_FOR_PRETRAINING_MAPPING), *get_values(TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING), ]: inputs_dict["labels"] = tf.zeros( (self.model_tester.batch_size, self.model_tester.seq_length), dtype=tf.int32 ) return inputs_dict @slow def test_graph_mode(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs = self._prepare_for_class(inputs_dict, model_class) model = model_class(config) @tf.function def run_in_graph_mode(): return model(inputs) outputs = run_in_graph_mode() self.assertIsNotNone(outputs) @slow def test_xla_mode(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs = self._prepare_for_class(inputs_dict, model_class) model = model_class(config) @tf.function(experimental_compile=True) def run_in_graph_mode(): return model(inputs) outputs = run_in_graph_mode() self.assertIsNotNone(outputs) @slow def test_saved_model_creation(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.output_hidden_states = False config.output_attentions = False if hasattr(config, "use_cache"): config.use_cache = False model_class = self.all_model_classes[0] class_inputs_dict = self._prepare_for_class(inputs_dict, model_class) model = model_class(config) model(class_inputs_dict) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname, saved_model=True) saved_model_dir = os.path.join(tmpdirname, "saved_model", "1") self.assertTrue(os.path.exists(saved_model_dir)) @slow def test_saved_model_creation_extended(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.output_hidden_states = True config.output_attentions = True if hasattr(config, "use_cache"): config.use_cache = True encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", self.model_tester.seq_length) encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) for model_class in self.all_model_classes: class_inputs_dict = self._prepare_for_class(inputs_dict, model_class) model = model_class(config) num_out = len(model(class_inputs_dict)) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname, saved_model=True) saved_model_dir = os.path.join(tmpdirname, "saved_model", "1") model = tf.keras.models.load_model(saved_model_dir) outputs = model(class_inputs_dict) if self.is_encoder_decoder: output_hidden_states = outputs["encoder_hidden_states"] output_attentions = outputs["encoder_attentions"] else: output_hidden_states = outputs["hidden_states"] output_attentions = outputs["attentions"] self.assertEqual(len(outputs), num_out) expected_num_layers = getattr( self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(output_hidden_states), expected_num_layers) self.assertListEqual( list(output_hidden_states[0].shape[-2:]), [self.model_tester.seq_length, self.model_tester.hidden_size], ) self.assertEqual(len(output_attentions), self.model_tester.num_hidden_layers) self.assertListEqual( list(output_attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], ) @slow def test_mixed_precision(self): tf.keras.mixed_precision.experimental.set_policy("mixed_float16") config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: class_inputs_dict = self._prepare_for_class(inputs_dict, model_class) model = model_class(config) outputs = model(class_inputs_dict) self.assertIsNotNone(outputs) tf.keras.mixed_precision.experimental.set_policy("float32") @slow def test_train_pipeline_custom_model(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() # head_mask and decoder_head_mask has different shapes than other input args if "head_mask" in inputs_dict: del inputs_dict["head_mask"] if "decoder_head_mask" in inputs_dict: del inputs_dict["decoder_head_mask"] if "cross_attn_head_mask" in inputs_dict: del inputs_dict["cross_attn_head_mask"] tf_main_layer_classes = set( module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__),) for module_member_name in dir(module) if module_member_name.endswith("MainLayer") for module_member in (getattr(module, module_member_name),) if isinstance(module_member, type) and tf.keras.layers.Layer in module_member.__bases__ and getattr(module_member, "_keras_serializable", False) ) for main_layer_class in tf_main_layer_classes: # T5MainLayer needs an embed_tokens parameter when called without the inputs_embeds parameter if "T5" in main_layer_class.__name__: # Take the same values than in TFT5ModelTester for this shared layer shared = TFSharedEmbeddings(self.model_tester.vocab_size, self.model_tester.hidden_size, name="shared") config.use_cache = False main_layer = main_layer_class(config, embed_tokens=shared) else: main_layer = main_layer_class(config) symbolic_inputs = { name: tf.keras.Input(tensor.shape[1:], dtype=tensor.dtype) for name, tensor in inputs_dict.items() } if hasattr(self.model_tester, "num_labels"): num_labels = self.model_tester.num_labels else: num_labels = 2 X = tf.data.Dataset.from_tensor_slices( (inputs_dict, np.ones((self.model_tester.batch_size, self.model_tester.seq_length, num_labels, 1))) ).batch(1) hidden_states = main_layer(symbolic_inputs)[0] outputs = tf.keras.layers.Dense(num_labels, activation="softmax", name="outputs")(hidden_states) model = tf.keras.models.Model(inputs=symbolic_inputs, outputs=[outputs]) model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["binary_accuracy"]) model.fit(X, epochs=1) with tempfile.TemporaryDirectory() as tmpdirname: filepath = os.path.join(tmpdirname, "keras_model.h5") model.save(filepath) if "T5" in main_layer_class.__name__: model = tf.keras.models.load_model( filepath, custom_objects={ main_layer_class.__name__: main_layer_class, "TFSharedEmbeddings": TFSharedEmbeddings, }, ) else: model = tf.keras.models.load_model( filepath, custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(model, tf.keras.Model) model(inputs_dict) @slow def test_graph_mode_with_inputs_embeds(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) inputs = copy.deepcopy(inputs_dict) if not self.is_encoder_decoder: input_ids = inputs["input_ids"] del inputs["input_ids"] else: encoder_input_ids = inputs["input_ids"] decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) del inputs["input_ids"] inputs.pop("decoder_input_ids", None) if not self.is_encoder_decoder: inputs["inputs_embeds"] = model.get_input_embeddings()(input_ids) else: inputs["inputs_embeds"] = model.get_input_embeddings()(encoder_input_ids) inputs["decoder_inputs_embeds"] = model.get_input_embeddings()(decoder_input_ids) inputs = self._prepare_for_class(inputs, model_class) @tf.function def run_in_graph_mode(): return model(inputs) outputs = run_in_graph_mode() self.assertIsNotNone(outputs) def _generate_random_bad_tokens(self, num_bad_tokens, model): # special tokens cannot be bad tokens special_tokens = [] if model.config.bos_token_id is not None: special_tokens.append(model.config.bos_token_id) if model.config.pad_token_id is not None: special_tokens.append(model.config.pad_token_id) if model.config.eos_token_id is not None: special_tokens.append(model.config.eos_token_id) # create random bad tokens that are not special tokens bad_tokens = [] while len(bad_tokens) < num_bad_tokens: token = tf.squeeze(ids_tensor((1, 1), self.model_tester.vocab_size), 0).numpy()[0] if token not in special_tokens: bad_tokens.append(token) return bad_tokens def _check_generated_ids(self, output_ids): for token_id in output_ids[0].numpy().tolist(): self.assertGreaterEqual(token_id, 0) self.assertLess(token_id, self.model_tester.vocab_size) def _check_match_tokens(self, generated_ids, bad_words_ids): # for all bad word tokens for bad_word_ids in bad_words_ids: # for all slices in batch for generated_ids_slice in generated_ids: # for all word idx for i in range(len(bad_word_ids), len(generated_ids_slice)): # if tokens match if generated_ids_slice[i - len(bad_word_ids) : i] == bad_word_ids: return True return False
f83c4b3c6faf3ef8350d51cee7b1ed1509e0e084
a51062d546e0936c5b2ac5cbfb3f91fc7bf342d7
/openff/evaluator/properties/__init__.py
a1178d3374263026cb4e256232bb78964f451d98
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
joegomes/openff-evaluator
4e748a9f43001a8e738851a9160837f6618fc8e5
9ccd3d017af0c6c1b556b1e77a8eccd0d1dfbcd1
refs/heads/master
2023-04-22T01:02:47.038298
2021-05-05T18:49:49
2021-05-05T18:49:49
364,670,685
0
0
NOASSERTION
2021-05-05T18:49:50
2021-05-05T18:27:10
null
UTF-8
Python
false
false
423
py
from .binding import HostGuestBindingAffinity from .density import Density, ExcessMolarVolume from .dielectric import DielectricConstant from .enthalpy import EnthalpyOfMixing, EnthalpyOfVaporization from .solvation import SolvationFreeEnergy __all__ = [ HostGuestBindingAffinity, Density, ExcessMolarVolume, DielectricConstant, EnthalpyOfMixing, EnthalpyOfVaporization, SolvationFreeEnergy, ]
2323ad3b44127d58791d33e46cf34b22f637af99
553b86e3b1ed21e64ea4feeb690af0701a17ba5f
/prob1.py
807fc0a8bb9f9d250e350cde7f495af6014e156a
[]
no_license
shihyuuuuuuu/LeetCode_practice
d1c4b7851abfa42fcc4b56f835444792aca3f222
dbc7e988ca9fd6f3a9541a36a0ad543c97b884af
refs/heads/master
2023-01-03T21:25:14.426989
2020-11-03T07:09:29
2020-11-03T07:09:29
254,667,846
0
0
null
null
null
null
UTF-8
Python
false
false
940
py
class Solution: # Prettier def twoSum(self, nums: List[int], target: int) -> List[int]: d = {} for cnt, i in enumerate(nums): if d.get(target - i, -1) != -1: return [d[target-i], cnt] else: d[i] = cnt # Faster, more memory def twoSum(self, nums: List[int], target: int) -> List[int]: num_dict = {} for idx, i in enumerate(nums): num_dict[i] = idx for idx, i in enumerate(nums): if((target - i) in num_dict and num_dict[target-i] != idx): return [idx, num_dict[target-i]] # Slower, less memory def twoSum_ver2(self, nums: List[int], target: int) -> List[int]: for idx1, i in enumerate(nums): for idx2, j in enumerate(nums[idx1+1:]): if(i + j == target): return [idx1, idx1+idx2+1]
62225756896d2b4614a6f4732d1f5e155553fb11
f931249f3766bd871eede76a950484701915c32d
/collective_decision/tests/test_models.py
aa2bd906a88f75c7dc22581ed4b16733fcad544b
[]
no_license
cleliofavoccia/Share
aa509c9cfa1aa3789237b411b2b94d952d848322
cf0b982a6df2b8b4318d12d344ef0827394eedfd
refs/heads/main
2023-07-11T08:29:59.016252
2021-08-09T10:13:53
2021-08-09T10:13:53
373,621,787
0
0
null
null
null
null
UTF-8
Python
false
false
5,125
py
"""Tests of collective_decision django models""" from django.test import TestCase from django.db import IntegrityError from user.models import User from group.models import Group from group_member.models import GroupMember from product.models import Product from ..models import Estimation, Decision class EstimationModelTest(TestCase): """Tests on Estimation object""" @classmethod def setUp(cls): """Set up a context to test Estimation object""" user = User.objects.create_user( username='Frodon', email='[email protected]', password='sam' ) group = Group.objects.create(name="La communauté de l'anneau ") cls.group_member = GroupMember.objects.create(user=user, group=group) cls.product = Product.objects.create( name='PS5', group=group ) cls.estimation = Estimation.objects.create( cost=3, group_member=cls.group_member, product=cls.product ) def test_estimation_has_group_member(self): """Test Estimation object has relation with GroupMember object""" user = User.objects.get(username='Frodon') estimation_group_member = Estimation.objects.get( group_member=GroupMember.objects.get( user=user ) ) self.assertEqual(self.estimation, estimation_group_member) def test_estimation_has_product(self): """Test Estimation object has relation with Product object""" product = Product.objects.get(name='PS5') estimation_product = Estimation.objects.get(product=product) self.assertEqual(self.estimation, estimation_product) def test_delete_estimation_not_delete_group_member_and_product(self): """Test if Estimation object is deleted, GroupMember and Product objects are not deleted""" estimation = self.estimation estimation.delete() group_member = self.group_member product = self.product self.assertTrue(group_member) self.assertTrue(product) def test_constraints_one_estimation_per_product_and_group_member(self): """Test if constraint of one Estimation object between product and group_member is respected""" try: estimation_two = Estimation.objects.create( cost=6, group_member=self.group_member, product=self.product ) estimation_two.save() except IntegrityError: estimation_two = 'IntegrityError' self.assertEqual(estimation_two, 'IntegrityError') class DecisionModelTest(TestCase): """Tests on Decision object""" @classmethod def setUp(cls): """Set up a context to test Decision object""" user = User.objects.create_user( username='Frodon', email='[email protected]', password='sam' ) cls.group = Group.objects.create(name="La communauté de l'anneau") cls.group_member = GroupMember.objects.create( user=user, group=cls.group ) cls.decision = Decision.objects.create( delete_group_vote=True, modify_group_vote=False, delete_member_vote=True, group_member=cls.group_member, group=cls.group ) def test_decision_has_group_member(self): """Test Decision object has relation with GroupMember object""" user = User.objects.get(username='Frodon') decision_group_member = Decision.objects.get( group_member=GroupMember.objects.get( user=user ) ) self.assertEqual(self.decision, decision_group_member) def test_decision_has_group(self): """Test Decision object has relation with Group object""" group = Group.objects.get(name="La communauté de l'anneau") decision_group = Decision.objects.get(group=group) self.assertEqual(self.decision, decision_group) def test_delete_decision_not_delete_group_member_and_group(self): """Test if Decision object is deleted, GroupMember and Group objects are not deleted""" decision = self.decision decision.delete() group_member = self.group_member group = self.group self.assertTrue(group_member) self.assertTrue(group) def test_constraints_one_decision_per_group_and_group_member(self): """Test if constraint of one Decision object between group and group_member is respected""" try: decision_two = Decision.objects.create( delete_group_vote=True, modify_group_vote=True, delete_member_vote=True, group_member=self.group_member, group=self.group ) decision_two.save() except IntegrityError: decision_two = 'IntegrityError' self.assertEqual(decision_two, 'IntegrityError')
be6cbbd046838c6b3ea18f1e70cb6f08612db43e
0c1d6b8dff8bedfffa8703015949b6ca6cc83f86
/lib/worklists/operator/CT/v3.0/business/ADSL/test/data.py
011c359518dc97400db6bdb1e079f6fba7538eb2
[]
no_license
samwei8/TR069
6b87252bd53f23c37186c9433ce4d79507b8c7dd
7f6b8d598359c6049a4e6cb1eb1db0899bce7f5c
refs/heads/master
2021-06-21T11:07:47.345271
2017-08-08T07:14:55
2017-08-08T07:14:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
456
py
#coding:utf-8 # -----------------------------doc-------------------------- # 工单 描述 WORKLIST_DOC = """ """ # -----------------------------args-------------------------- # 工单 参数 WORKLIST_ARGS = { "ConnectionType": ("IP_Routed", "1"), "ServiceList": ("INTERNET", "2"), "Username": ("admin", "3"), "Password": ("admin", "4"), "Enable": ("true", "5") }
47ea0ceecd6c900370bb212ceedfa5d6e9398339
2b1b4b92b5b6dadc6dfb556e867b042c97a4d738
/CMGTools/H2TauTau/python/proto/plotter/HistDrawer.py
afd02f94b7ea7778cb69f5c3d0a53fba6df59986
[]
no_license
emanueledimarco/cmg-cmssw
65f6d20ccd9bfec74856397407b96dee9830afc6
b54ebd03ab8bad9c7694d867e3f3c54a1ad910c4
refs/heads/CMGTools_from7412_monox
2021-01-18T17:57:17.833303
2016-02-24T15:27:58
2016-02-24T15:27:58
21,276,131
1
0
null
2017-10-25T21:50:09
2014-06-27T13:11:29
C++
UTF-8
Python
false
false
6,022
py
import re import os import copy from math import log10, floor from ROOT import TCanvas, TPaveText, TBox, gStyle from CMGTools.RootTools.DataMC.Stack import Stack from CMGTools.H2TauTau.proto.plotter.CMS_lumi import CMS_lumi from CMGTools.H2TauTau.proto.plotter.officialStyle import officialStyle officialStyle(gStyle) def ensureDir(directory): if not os.path.exists(directory): os.makedirs(directory) class HistDrawer: ocan = None can = None pad = None padr = None @classmethod def buildCanvas(cls): can = cls.can pad = cls.pad padr = cls.padr if not can: can = cls.can = TCanvas('can', '', 800, 800) can.Divide(1, 2, 0.0, 0.0) pad = cls.pad = can.GetPad(1) padr = cls.padr = can.GetPad(2) # Set Pad sizes pad.SetPad(0.0, 0.32, 1., 1.0) padr.SetPad(0.0, 0.00, 1., 0.34) pad.SetTopMargin(0.08) pad.SetLeftMargin(0.16) pad.SetBottomMargin(0.03) pad.SetRightMargin(0.05) padr.SetBottomMargin(0.35) padr.SetLeftMargin(0.16) padr.SetRightMargin(0.05) can.cd() can.Draw() pad.Draw() padr.Draw() return can, pad, padr @classmethod def buildCanvasSingle(cls): ocan = TCanvas('ocan', '', 600, 600) ocan.cd() ocan.Draw() return ocan @staticmethod def datasetInfo(plot): year = '' year = '2015' lumi = plot.lumi if hasattr(plot, 'lumi') else 0. unit = plot.lumi_unit if hasattr(plot, 'lumi_unit') else 'pb' energy = plot.com_energy if hasattr(plot, 'com_energy') else 13 return year, lumi, energy, unit @staticmethod def CMSPrelim(plot, pad, channel, legend='right'): pad.cd() year, lumi, energy, unit = HistDrawer.datasetInfo(plot) theStr = '{lumi:3.3} {unit}^{{-1}} ({energy:d} TeV)'.format(year=year, unit=unit, lumi=lumi, energy=energy) CMS_lumi(pad, theStr, iPosX=0) lowY = 0.77 r = pad.GetRightMargin() l = pad.GetLeftMargin() posX = l + 0.045*(1-l-r) posXhigh = 0.25 if legend == 'left': posX = 1. - r - 0.08 posXhigh = 1. - r - 0.02 plot.chan = TPaveText(posX, lowY, posXhigh, lowY+0.18, "NDC") plot.chan.SetBorderSize(0) plot.chan.SetFillStyle(0) plot.chan.SetTextAlign(12) plot.chan.SetTextSize(0.6*pad.GetTopMargin()) # To have it the same size as CMS_lumi plot.chan.SetTextFont(42) plot.chan.AddText(channel) plot.chan.Draw('same') unitpat = re.compile('.*\((.*)\)\s*$') keeper = [] @staticmethod def draw(plot, do_ratio=True, channel='TauMu', plot_dir='plots', plot_name=None, SetLogy=0, mssm=False, blindxmin=None, blindxmax=None, unit=None): print plot Stack.STAT_ERRORS = True can = pad = padr = None if do_ratio: can, pad, padr = HistDrawer.buildCanvas() else: can = HistDrawer.buildCanvasSingle() pad.cd() pad.SetLogy(SetLogy) plot.DrawStack('HIST') h = plot.supportHist h.GetXaxis().SetLabelColor(1) # h.GetXaxis().SetLabelSize(1) unitsperbin = h.GetXaxis().GetBinWidth(1) ytitle = 'Events' if unit: round_to_n = lambda x, n: round(x, -int(floor(log10(abs(x)))) + (n - 1)) ytitle += round_to_n(unitsperbin, 3) h.GetYaxis().SetTitle('Events') h.GetYaxis().SetTitleOffset(1.0) h.GetXaxis().SetTitleOffset(2.0) if do_ratio: padr.cd() ratio = copy.deepcopy(plot) ratio.legendOn = False if blindxmin or blindxmax: if not blindxmin: blindxmin = 0 if not blindxmax: blindxmax = plot.GetXaxis().GetXmax() if do_ratio: ratio.Blind(blindxmin, blindxmax, True) plot.Blind(blindxmin, blindxmax, False) if do_ratio: ratio.DrawDataOverMCMinus1(-0.5, 0.5) hr = ratio.dataOverMCHist # ytp_ratio = float(pad.YtoPixel(0.)/padr.YtoPixel(0)) # print 'YTP ratio', ytp_ratio # xtp_ratio = float(pad.XtoPixel(0.)/padr.XtoPixel(0)) # print 'XTP ratio', xtp_ratio ytp_ratio = 2. xtp_ratio = 2. # hr.GetYaxis().SetNdivisions(4) hr.GetYaxis().SetTitleSize(h.GetYaxis().GetTitleSize() * xtp_ratio) hr.GetXaxis().SetTitleSize(h.GetXaxis().GetTitleSize() * ytp_ratio) hr.GetYaxis().SetTitleOffset(h.GetYaxis().GetTitleOffset() / xtp_ratio) hr.GetXaxis().SetTitleOffset(h.GetXaxis().GetTitleOffset() / ytp_ratio) hr.GetYaxis().SetLabelSize(h.GetYaxis().GetLabelSize() * xtp_ratio) hr.GetXaxis().SetLabelSize(h.GetXaxis().GetLabelSize() * ytp_ratio) h.GetXaxis().SetLabelColor(0) h.GetXaxis().SetLabelSize(0) padr.Update() # blinding if blindxmin or blindxmax: pad.cd() max = plot.stack.totalHist.GetMaximum() box = TBox(blindxmin, 0, blindxmax, max) box.SetFillColor(1) box.SetFillStyle(3004) box.Draw() HistDrawer.keeper.append(box) print channel if channel == 'TauMu': HistDrawer.CMSPrelim(plot, pad, '#tau_{#mu}#tau_{h}', legend=plot.legendPos) elif channel == 'TauEle': HistDrawer.CMSPrelim(plot, pad, '#tau_{e}#tau_{h}', legend=plot.legendPos) can.cd() plotname = plot_dir + '/' ensureDir(plot_dir) plotname += plot_name if plot_name else plot.name can.SaveAs(plotname + '.png') pad.SetLogy(0) return ratio drawRatio = draw
8f54020865428b31e51ea2f36018f18b202ee386
b46dff381a329b5456359d9edcbb279e7c710999
/tilelit/tests/test_tilelit.py
f6f7297882115d058d6e9d9ba83007ba751485e7
[ "MIT" ]
permissive
uw-biomedical-ml/tilelit
d8c48cfaf95ea90c23fe4dbc7862d76747e00628
36062279e321a30a194982dc61df6946614e7e22
refs/heads/master
2021-09-17T22:08:43.761931
2018-07-05T22:27:58
2018-07-05T22:27:58
114,414,633
3
2
null
null
null
null
UTF-8
Python
false
false
792
py
from __future__ import absolute_import, division, print_function import os.path as op import numpy as np import pandas as pd import numpy.testing as npt import tilelit as ti import skimage.data as skd from skimage import transform as tf def test_tile(): static = skd.coins() ty = np.random.randn() * 0.05 * static.shape[0] tx = np.random.randn() * 0.05 * static.shape[1] rot = np.random.randn() * np.pi/20 affine = tf.AffineTransform(rotation=rot, translation=(tx, ty)) moving = tf.warp(static, affine.inverse) img_initial, aff_initial = \ ti.initial_alignment(static, moving, gaussian_blur=5) img_final, aff_final = \ ti.fine_alignment(static, img_initial, starting_affine=aff_initial) npt.assert_almost_equal(aff_final, affine.params)
06196dc14bd12901227bf7210937a9df76502363
4a8c1f7d9935609b780aff95c886ef7781967be0
/topcoder/Rookie SRM 1/OverallScores.py
d32100bb4d37fadd8b01c0ab9f613199978513d7
[]
no_license
recuraki/PythonJunkTest
d5e5f5957ac5dd0c539ef47759b1fe5ef7a2c52a
2556c973d468a6988d307ce85c5f2f8ab15e759a
refs/heads/master
2023-08-09T17:42:21.875768
2023-07-18T23:06:31
2023-07-18T23:06:31
13,790,016
0
0
null
null
null
null
UTF-8
Python
false
false
3,359
py
# -*- coding: utf-8 -*- import math,string,itertools,fractions,heapq,collections,re,array,bisect class OverallScores: def findWinner(self, N, scores): dat = [0] * N for i in range(len(scores) // N): for j in range(N): dat[j] += scores[j + i * N] maind = -1 maval = -1 for i in range(N): if dat[i] > maval: maind = i maval = dat[i] return maind # CUT begin # TEST CODE FOR PYTHON {{{ import sys, time, math def tc_equal(expected, received): try: _t = type(expected) received = _t(received) if _t == list or _t == tuple: if len(expected) != len(received): return False return all(tc_equal(e, r) for (e, r) in zip(expected, received)) elif _t == float: eps = 1e-9 d = abs(received - expected) return not math.isnan(received) and not math.isnan(expected) and d <= eps * max(1.0, abs(expected)) else: return expected == received except: return False def pretty_str(x): if type(x) == str: return '"%s"' % x elif type(x) == tuple: return '(%s)' % (','.join( (pretty_str(y) for y in x) ) ) else: return str(x) def do_test(N, scores, __expected): startTime = time.time() instance = OverallScores() exception = None try: __result = instance.findWinner(N, scores); except: import traceback exception = traceback.format_exc() elapsed = time.time() - startTime # in sec if exception is not None: sys.stdout.write("RUNTIME ERROR: \n") sys.stdout.write(exception + "\n") return 0 if tc_equal(__expected, __result): sys.stdout.write("PASSED! " + ("(%.3f seconds)" % elapsed) + "\n") return 1 else: sys.stdout.write("FAILED! " + ("(%.3f seconds)" % elapsed) + "\n") sys.stdout.write(" Expected: " + pretty_str(__expected) + "\n") sys.stdout.write(" Received: " + pretty_str(__result) + "\n") return 0 def run_tests(): sys.stdout.write("OverallScores (400 Points)\n\n") passed = cases = 0 case_set = set() for arg in sys.argv[1:]: case_set.add(int(arg)) with open("OverallScores.sample", "r") as f: while True: label = f.readline() if not label.startswith("--"): break N = int(f.readline().rstrip()) scores = [] for i in range(0, int(f.readline())): scores.append(int(f.readline().rstrip())) scores = tuple(scores) f.readline() __answer = int(f.readline().rstrip()) cases += 1 if len(case_set) > 0 and (cases - 1) in case_set: continue sys.stdout.write(" Testcase #%d ... " % (cases - 1)) passed += do_test(N, scores, __answer) sys.stdout.write("\nPassed : %d / %d cases\n" % (passed, cases)) T = time.time() - 1614260880 PT, TT = (T / 60.0, 75.0) points = 400 * (0.3 + (0.7 * TT * TT) / (10.0 * PT * PT + TT * TT)) sys.stdout.write("Time : %d minutes %d secs\n" % (int(T/60), T%60)) sys.stdout.write("Score : %.2f points\n" % points) if __name__ == '__main__': run_tests() # }}} # CUT end
2a722ec1fe9fcda7804a6102c78858b391aa6dfe
377dc973a58d30154cf485de141223d7ca5424dd
/havok_classes/hkaSkeletonLocalFrameOnBone.py
24e0e76c53f139086cdd47e4f2731f50d18ed9ba
[ "MIT" ]
permissive
sawich/havok-reflection
d6a5552f2881bb4070ad824fb7180ad296edf4c4
1d5b768fb533b3eb36fc9e42793088abeffbad59
refs/heads/master
2021-10-11T12:56:44.506674
2019-01-25T22:37:31
2019-01-25T22:37:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
582
py
from .hkLocalFrame import hkLocalFrame import struct class hkaSkeletonLocalFrameOnBone(object): localFrame: any boneIndex: int def __init__(self, infile): self.localFrame = any(infile) # TYPE_POINTER:TYPE_STRUCT self.boneIndex = struct.unpack('>h', infile.read(2)) # TYPE_INT16:TYPE_VOID def __repr__(self): return "<{class_name} localFrame={localFrame}, boneIndex={boneIndex}>".format(**{ "class_name": self.__class__.__name__, "localFrame": self.localFrame, "boneIndex": self.boneIndex, })
0953423a781578e7260493e3b17df08f46cb8ffa
0f9a97d48a9f0179bcf1e3d80c08340096eb561e
/ДЗ-5. Функции и рекурсия/C. Периметр треугольника.py
218540cdf273e3aecc918c967a3df0f90da0aa53
[]
no_license
dmitryokh/python
96d8ec8c3f2d3428b90d510a1003aecf102b13d0
8efe761412779bed9a7516832d3152843088fa43
refs/heads/master
2020-04-24T03:08:42.865813
2019-02-20T11:41:52
2019-02-20T11:41:52
171,661,235
0
0
null
null
null
null
UTF-8
Python
false
false
315
py
from math import sqrt def distance(x1, y1, x2, y2): return(sqrt((x2 - x1)**2 + (y2 - y1)**2)) x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) x3 = int(input()) y3 = int(input()) a = distance(x1, y1, x2, y2) b = distance(x1, y1, x3, y3) c = distance(x3, y3, x2, y2) print(a + b + c)
46b795561c7cd2ef9084ec78d43889d97b023575
747f759311d404af31c0f80029e88098193f6269
/addons/stock/wizard/stock_location_product.py
1f9777a72c1d926463d1fd0cf913ed81086e71dc
[]
no_license
sgeerish/sirr_production
9b0d0f7804a928c0c582ddb4ccb7fcc084469a18
1081f3a5ff8864a31b2dcd89406fac076a908e78
refs/heads/master
2020-05-19T07:21:37.047958
2013-09-15T13:03:36
2013-09-15T13:03:36
9,648,444
0
1
null
null
null
null
UTF-8
Python
false
false
2,423
py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from osv import fields, osv class stock_location_product(osv.osv_memory): _name = "stock.location.product" _description = "Products by Location" _columns = { 'from_date': fields.datetime('From'), 'to_date': fields.datetime('To'), } def action_open_window(self, cr, uid, ids, context=None): """ To open location wise product information specific to given duration @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: An ID or list of IDs if we want more than one @param context: A standard dictionary @return: Invoice type """ mod_obj = self.pool.get('ir.model.data') for location_obj in self.read(cr, uid, ids, ['from_date', 'to_date']): return { 'name': False, 'view_type': 'form', 'view_mode': 'tree,form', 'res_model': 'product.product', 'type': 'ir.actions.act_window', 'context': {'location': context['active_id'], 'from_date': location_obj['from_date'], 'to_date': location_obj['to_date'], }, 'domain': [('qty_available', '>', 0)], } stock_location_product() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
e4def48c4cf436a2b2d384bd315d99b9a0f1b56a
09e57dd1374713f06b70d7b37a580130d9bbab0d
/benchmark/startQiskit_noisy1310.py
f6c89f3e4f5a2d30ec73a1b5f825e843ad9d4a87
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
4,424
py
# qubit number=5 # total number=56 import cirq import qiskit from qiskit.providers.aer import QasmSimulator from qiskit.test.mock import FakeVigo from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2,floor, sqrt, pi import numpy as np import networkx as nx def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f^\pm # NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate # or multi_control_Z_gate (issue #127) controls = QuantumRegister(n, "ofc") oracle = QuantumCircuit(controls, name="Zf") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.h(controls[n]) if n >= 2: oracle.mcu1(pi, controls[1:], controls[0]) for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.barrier() return oracle def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[0]) # number=3 prog.h(input_qubit[1]) # number=4 prog.h(input_qubit[2]) # number=50 prog.cz(input_qubit[4],input_qubit[2]) # number=51 prog.h(input_qubit[2]) # number=52 prog.h(input_qubit[2]) # number=5 prog.h(input_qubit[3]) # number=6 prog.h(input_qubit[4]) # number=21 Zf = build_oracle(n, f) repeat = floor(sqrt(2 ** n) * pi / 4) for i in range(repeat): prog.append(Zf.to_gate(), [input_qubit[i] for i in range(n)]) prog.h(input_qubit[0]) # number=1 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.h(input_qubit[0]) # number=28 prog.z(input_qubit[3]) # number=42 prog.cz(input_qubit[1],input_qubit[0]) # number=29 prog.h(input_qubit[0]) # number=30 prog.h(input_qubit[0]) # number=43 prog.cz(input_qubit[1],input_qubit[0]) # number=44 prog.h(input_qubit[0]) # number=45 prog.cx(input_qubit[1],input_qubit[0]) # number=35 prog.h(input_qubit[0]) # number=53 prog.cz(input_qubit[1],input_qubit[0]) # number=54 prog.h(input_qubit[0]) # number=55 prog.x(input_qubit[0]) # number=39 prog.cx(input_qubit[1],input_qubit[0]) # number=40 prog.cx(input_qubit[1],input_qubit[0]) # number=37 prog.h(input_qubit[0]) # number=46 prog.cz(input_qubit[1],input_qubit[0]) # number=47 prog.h(input_qubit[0]) # number=48 prog.cx(input_qubit[1],input_qubit[0]) # number=27 prog.x(input_qubit[1]) # number=10 prog.x(input_qubit[2]) # number=11 prog.x(input_qubit[3]) # number=12 if n>=2: prog.mcu1(pi,input_qubit[1:],input_qubit[0]) prog.x(input_qubit[0]) # number=13 prog.cx(input_qubit[0],input_qubit[1]) # number=22 prog.y(input_qubit[2]) # number=41 prog.x(input_qubit[1]) # number=23 prog.cx(input_qubit[0],input_qubit[1]) # number=24 prog.rx(1.0398671683382215,input_qubit[2]) # number=31 prog.x(input_qubit[2]) # number=15 prog.x(input_qubit[3]) # number=16 prog.h(input_qubit[0]) # number=17 prog.h(input_qubit[1]) # number=18 prog.h(input_qubit[2]) # number=19 prog.h(input_qubit[3]) # number=20 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog if __name__ == '__main__': key = "00000" f = lambda rep: str(int(rep == key)) prog = make_circuit(5,f) backend = FakeVigo() sample_shot =7924 info = execute(prog, backend=backend, shots=sample_shot).result().get_counts() backend = FakeVigo() circuit1 = transpile(prog,backend,optimization_level=2) writefile = open("../data/startQiskit_noisy1310.csv","w") print(info,file=writefile) print("results end", file=writefile) print(circuit1.depth(),file=writefile) print(circuit1,file=writefile) writefile.close()
9ad89e902ed284ef9edf8837805fb2c2d6c96dce
f0f2a548457e345d5432c8ddcd37daa25ee56957
/apml-client/show-stats.py
c989e874560d2414b6478337566c10ae269a4f02
[ "MIT" ]
permissive
blxlrsmb/myap.ml
edf2703df34de27282dbf0d7821f83b629e1ccc8
b21270d54b453cd53e160a017f21d52e444ff62b
refs/heads/master
2021-01-24T20:52:38.420997
2016-06-19T06:19:44
2016-06-19T06:19:44
36,968,412
1
0
null
null
null
null
UTF-8
Python
false
false
450
py
#!/usr/bin/env python2 # -*- coding: UTF-8 -*- # File: show-stats.py # Date: Sat Jun 06 20:16:34 2015 +0800 # Author: Yuxin Wu <[email protected]> from logger import EventLogger ev = EventLogger() pkgs = ev.packages names = set() cnt = 0 for p in pkgs: names = names.union(set(p['key'].keys())) cnt += sum(p['key'].itervalues()) names = names.union(set(p['mouse'].keys())) cnt += sum(p['mouse'].itervalues()) print names print cnt
bc68bd06515bf96079aa0ed7e1770b5be7c25b5c
b50ff836c3010b42821624e79cb21e4d9594f588
/selfdrive/car/vin.py
76fd34ca6d80e8aecc040376a6369041889c537f
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
dnv26/openpilot
5fe441eb9ef93a56b5a2522ace58c3ae415c7813
b1db54ea553ccc41cfb54bdf66a1c31ab52432f2
refs/heads/HKG_6.5
2020-09-09T06:37:33.909558
2019-11-14T21:47:55
2019-11-14T21:47:55
221,376,282
8
31
MIT
2020-05-09T02:30:46
2019-11-13T05:01:02
C++
UTF-8
Python
false
false
3,245
py
#!/usr/bin/env python3 import selfdrive.messaging as messaging from selfdrive.boardd.boardd import can_list_to_can_capnp VIN_UNKNOWN = "0" * 17 # sanity checks on response messages from vin query def is_vin_response_valid(can_dat, step, cnt): if len(can_dat) != 8: # ISO-TP meesages are all 8 bytes return False if step == 0: # VIN does not fit in a single message and it's 20 bytes of data if can_dat[0] != 0x10 or can_dat[1] != 0x14: return False if step == 1 and cnt == 0: # first response after a CONTINUE query is sent if can_dat[0] != 0x21: return False if step == 1 and cnt == 1: # second response after a CONTINUE query is sent if can_dat[0] != 0x22: return False return True class VinQuery(): def __init__(self, bus): self.bus = bus # works on standard 11-bit addresses for diagnostic. Tested on Toyota and Subaru; # Honda uses the extended 29-bit addresses, and unfortunately only works from OBDII self.query_ext_msgs = [[0x18DB33F1, 0, b'\x02\x09\x02'.ljust(8, b"\x00"), bus], [0x18DA10f1, 0, b'\x30'.ljust(8, b"\x00"), bus]] self.query_nor_msgs = [[0x7df, 0, b'\x02\x09\x02'.ljust(8, b"\x00"), bus], [0x7e0, 0, b'\x30'.ljust(8, b"\x00"), bus]] self.cnts = [1, 2] # number of messages to wait for at each iteration self.step = 0 self.cnt = 0 self.responded = False self.never_responded = True self.dat = b"" self.vin = VIN_UNKNOWN def check_response(self, msg): # have we got a VIN query response? if msg.src == self.bus and msg.address in [0x18daf110, 0x7e8]: self.never_responded = False # basic sanity checks on ISO-TP response if is_vin_response_valid(msg.dat, self.step, self.cnt): self.dat += bytes(msg.dat[2:]) if self.step == 0 else bytes(msg.dat[1:]) self.cnt += 1 if self.cnt == self.cnts[self.step]: self.responded = True self.step += 1 def send_query(self, sendcan): # keep sending VIN qury if ECU isn't responsing. # sendcan is probably not ready due to the zmq slow joiner syndrome if self.never_responded or (self.responded and self.step < len(self.cnts)): sendcan.send(can_list_to_can_capnp([self.query_ext_msgs[self.step]], msgtype='sendcan')) sendcan.send(can_list_to_can_capnp([self.query_nor_msgs[self.step]], msgtype='sendcan')) self.responded = False self.cnt = 0 def get_vin(self): # only report vin if procedure is finished if self.step == len(self.cnts) and self.cnt == self.cnts[-1]: self.vin = self.dat[3:].decode('utf8') return self.vin def get_vin(logcan, sendcan, bus, query_time=1.): vin_query = VinQuery(bus) frame = 0 # 1s max of VIN query time while frame < query_time * 100: a = messaging.recv_one(logcan) for can in a.can: vin_query.check_response(can) vin_query.send_query(sendcan) frame += 1 return vin_query.get_vin() if __name__ == "__main__": from selfdrive.services import service_list logcan = messaging.sub_sock(service_list['can'].port) sendcan = messaging.pub_sock(service_list['sendcan'].port) print(get_vin(logcan, sendcan, 0))
8fd9e5477942786209d08d62c024179c66489083
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5640146288377856_0/Python/trapped/a_small.py
d6f1fa475144b794563c801431c358bd4fcbb062
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
538
py
T = int(raw_input()) def solve(r, c, w): if w == 1: return r*c if w == c: return (r-1) + c # following only for small case: r=1 if w > c//2: return w+1 if w == c//2: return w+1+(c%2) return 1+ solve(r, c-w, w) '''if c%2 == 1: ans = 1 + (c//2)//w ans += solve(r, c//2, w) else: ans = 1 + (c//2 - 1)//w ans += solve(r, c//2, w) return ans''' for t in range(1,T+1): r, c, w = map(int, raw_input().strip().split()) print "Case #%d: %d"%(t, solve(r,c,w))
c8d8db5bcecf909d177c3caf44457684046f456e
e5606385fc77c1fbb30be223637b2b62372d6635
/news/urls.py
20fbb45caaed199e495d3c073c27917d6aaccb6c
[]
no_license
bhoj001/DJ_Test_App
6b2f116523af72a15370e303af745d7df7d7951c
a20d5ae9049a5d432ba219eb96036953c5512bf5
refs/heads/master
2020-03-24T00:25:57.714156
2018-07-25T11:29:15
2018-07-25T11:29:15
142,290,934
0
0
null
null
null
null
UTF-8
Python
false
false
202
py
from django.conf.urls import url from tango_with_django import views urlpatterns = [ url(r'^home$', views.home, name='home'), url(r'^$', views.index, name='index'), ]
1abb6b3b06ad3d28a1bc8ffef2a528725d178bbd
9214a22c37f9751f66005d9033c68eadca43d6ee
/app/.history/datasets/spotify_fetch_20201212160615.py
2d534dc61d069d9f1b881c5e1a14e0cc57cb80ae
[]
no_license
bsalgado98/lockdown-music
0800922ea25c9b07ea4b034297e67725776de070
a407265b7caa83667c92ee13c2adec1645acdafa
refs/heads/main
2023-01-29T09:55:38.137972
2020-12-17T01:01:49
2020-12-17T01:01:49
322,133,071
0
0
null
null
null
null
UTF-8
Python
false
false
687
py
import spotipy from spotipy.oauth2 import SpotifyClientCredentials import json import csv auth_manager = SpotifyClientCredentials() sp = spotipy.Spotify(auth_manager=auth_manager) def get_artist_genre(artist): results = sp.search(q='artist:' + artist, type='artist') # print(json.dumps(results, indent=4, sort_keys=True)) artists = results['artists'] items = artists['items'] print(artists) grammys = [] with open('the_grammy_awards.csv', mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) line_count = 0 for row in csv_reader: grammys.append(row) artist = grammys[0].get('artist') genres = get_artist_genre(artist) # print(genres)
e58b99b41a4f3a5a38ecf00da40037bd8fa7eae3
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
/alipay/aop/api/response/AlipayPcreditLoanHousemortgageRealtychainNotifyResponse.py
c8ce7d57930cb013c46e118af02437d5099697ec
[ "Apache-2.0" ]
permissive
alipay/alipay-sdk-python-all
8bd20882852ffeb70a6e929038bf88ff1d1eff1c
1fad300587c9e7e099747305ba9077d4cd7afde9
refs/heads/master
2023-08-27T21:35:01.778771
2023-08-23T07:12:26
2023-08-23T07:12:26
133,338,689
247
70
Apache-2.0
2023-04-25T04:54:02
2018-05-14T09:40:54
Python
UTF-8
Python
false
false
506
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayPcreditLoanHousemortgageRealtychainNotifyResponse(AlipayResponse): def __init__(self): super(AlipayPcreditLoanHousemortgageRealtychainNotifyResponse, self).__init__() def parse_response_content(self, response_content): response = super(AlipayPcreditLoanHousemortgageRealtychainNotifyResponse, self).parse_response_content(response_content)
146ee16ca9aaaf47c04e5aa73ebb2fc961973fc6
3ec8ade4cedc4601a1dea1933182675bc35f543a
/demo/models.py
4376f3134a7a3e28177d207c2299c172e8bd3723
[]
no_license
artrey/drf-comments
d9fce0b14c28ef9810cc17caeb03b2435cc075b6
ee875f820dc691df984ef8f292e8f9e532ca4689
refs/heads/master
2023-07-20T12:31:14.879634
2021-08-20T17:12:12
2021-08-20T17:12:12
398,344,295
0
0
null
null
null
null
UTF-8
Python
false
false
270
py
from django.core.validators import MaxValueValidator from django.db import models class Comment(models.Model): author = models.CharField(max_length=100) text = models.TextField() rating = models.PositiveSmallIntegerField(validators=[MaxValueValidator(5)])
75124e86e3e6d2e88fb785d3c12f62938022879e
ac7c02f29a837fdd67d2bdc77bba182080e98ed8
/codekata/ASCII.py
0a5f9b4a9ab3339cbd9a961167afabd66480eb85
[]
no_license
YaminiNarayanan-359/guvi
7630c309a86365e4367fda1ddab4e966e7d1ac5b
a52b6353100b4e9b83a003e6a327fbfb174daac4
refs/heads/master
2020-06-03T00:08:00.389609
2019-07-16T06:59:53
2019-07-16T06:59:53
191,355,064
0
0
null
null
null
null
UTF-8
Python
false
false
28
py
u=input() d=ord(u) print(d)
a7323120d71625d329147a0ad58c8fbe841c5d7e
edcd74f8f65119bdbe737360c2ca33b4a6da160a
/python/test-multiprocessing/multiprocessing_simple.py
f23b32c4e12ab97388c5ee1cb1354982163bc9f4
[]
no_license
hyunjun/practice
72e83de6a1d5e04ddcd16526f16110ea2dd00373
5376dd48b1cefb4faba9d2ef6a8a497b6b1d6c67
refs/heads/master
2023-08-31T07:00:37.320351
2023-08-17T07:29:24
2023-08-17T07:29:24
2,704,126
3
2
null
2022-12-14T20:25:07
2011-11-03T18:28:44
Python
UTF-8
Python
false
false
276
py
# https://pymotw.com/3/multiprocessing/basics.html import multiprocessing def worker(): """worker function""" print('Worker') if __name__ == '__main__': jobs = [] for i in range(5): p = multiprocessing.Process(target=worker) jobs.append(p) p.start()
49fd37eab918232db078265207ad4f60b6097bb1
b80bd48e12f2361ea51284fba0a08ea61673cfd4
/drip/models.py
beec587cc63ff535831ebb3038532e3041054c3d
[]
no_license
pdc/caption
25829912241224ec93697537900f6199fb14121b
6677de9f0bf40d5f331da8a3fb1fb45c7404d704
refs/heads/master
2016-09-06T16:55:30.264130
2013-02-28T20:01:55
2013-02-28T20:01:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
751
py
# -*-coding: UTF-8-*- from django.db import models from django.contrib.auth.models import User from articles.models import Article class DripAuthor(models.Model): uid = models.IntegerField(editable=False, primary_key=True) name = models.CharField(max_length=60, unique=True) mail = models.EmailField(max_length=64, blank=True) def __unicode__(self): return u'{0} ({1})'.format(self.name, self.uid) class DripNode(models.Model): article = models.OneToOneField(Article, null=False, editable=False, related_name='drip') author = models.ForeignKey(DripAuthor) nid = models.IntegerField(editable=False, primary_key=True) def __unicode__(self): return u'{0} ({1})'.format(self.article.title, self.nid)
7964d51dadf0214da7cc67756d0945ff15a2053c
f30e9ca8c5777196bf8e56d82ecddb80418d21ba
/test_fena/v1_12/test_blocks.py
7f1ca52716e4415e719a8986dcf5cb915ef2c9b7
[ "MIT" ]
permissive
Aquafina-water-bottle/Fena
029a1d6be64bdf1bd75d647d83e524821dfc7a3c
00a2b1dbc6f8abd968c46c637d6ad30d5fcde919
HEAD
2018-10-22T13:36:24.838025
2018-07-19T18:16:17
2018-07-19T18:16:17
96,073,393
0
0
null
null
null
null
UTF-8
Python
false
false
5,790
py
from test_fena.test_common import test_block def test_blocks(): # block states as simple values test_block("stonebrick[0]", "minecraft:stonebrick 0") test_block("stonebrick[1]", "minecraft:stonebrick 1") test_block("stonebrick[-1]", "minecraft:stonebrick -1") test_block("stonebrick[*]", "minecraft:stonebrick *") test_block("stonebrick[]", "minecraft:stonebrick *") test_block("stonebrick", "minecraft:stonebrick *") test_block("minecraft:stonebrick[0]", "minecraft:stonebrick 0") test_block("minecraft:stonebrick[1]", "minecraft:stonebrick 1") test_block("minecraft:stonebrick[-1]", "minecraft:stonebrick -1") test_block("minecraft:stonebrick[*]", "minecraft:stonebrick *") test_block("minecraft:stonebrick[]", "minecraft:stonebrick *") test_block("minecraft:stonebrick", "minecraft:stonebrick *") # actual block states test_block("stonebrick[variant=mossy_stonebrick]", "minecraft:stonebrick variant=mossy_stonebrick") test_block("stone_brick_stairs[facing=south,half=top]", "minecraft:stone_brick_stairs facing=south,half=top") test_block("stone_brick_stairs[facing=south, half=top]", "minecraft:stone_brick_stairs facing=south,half=top") test_block("stone_brick_stairs[facing = south, half = top]", "minecraft:stone_brick_stairs facing=south,half=top") test_block("stone_brick_stairs [ facing = south, half = top ] ", "minecraft:stone_brick_stairs facing=south,half=top") test_block("minecraft:stonebrick[variant=mossy_stonebrick]", "minecraft:stonebrick variant=mossy_stonebrick") test_block("minecraft:stone_brick_stairs[facing=south,half=top]", "minecraft:stone_brick_stairs facing=south,half=top") test_block("minecraft:stone_brick_stairs[facing=south, half=top]", "minecraft:stone_brick_stairs facing=south,half=top") test_block("minecraft:stone_brick_stairs[facing = south, half = top]", "minecraft:stone_brick_stairs facing=south,half=top") test_block("minecraft:stone_brick_stairs [ facing = south, half = top ] ", "minecraft:stone_brick_stairs facing=south,half=top") # nbt tags test_block(r'chest[0]{}', r'minecraft:chest 0 replace {}') test_block(r'chest[1]{}', r'minecraft:chest 1 replace {}') test_block(r'chest[-1]{}', r'minecraft:chest -1 replace {}') test_block(r'chest[*]{}', r'minecraft:chest * replace {}') test_block(r'chest[]{}', r'minecraft:chest * replace {}') test_block(r'chest{}', r'minecraft:chest * replace {}') test_block(r'minecraft:chest[0]', r'minecraft:chest 0') test_block(r'minecraft:chest[1]', r'minecraft:chest 1') test_block(r'minecraft:chest[-1]', r'minecraft:chest -1') test_block(r'minecraft:chest[*]', r'minecraft:chest *') test_block(r'minecraft:chest[]', r'minecraft:chest *') test_block(r'minecraft:chest', r'minecraft:chest *') test_block(r'chest[facing=west]{}', r'minecraft:chest facing=west replace {}') test_block(r'chest[facing=west]{Lock:"lol"}', r'minecraft:chest facing=west replace {Lock:"lol"}') test_block(r'minecraft:chest[facing=west]{}', r'minecraft:chest facing=west replace {}') test_block(r'minecraft:chest[facing=west]{Lock:"lol"}', r'minecraft:chest facing=west replace {Lock:"lol"}') test_block(r'chest[0]{Lock:"lol"}', r'minecraft:chest 0 replace {Lock:"lol"}') test_block(r'chest[1]{Lock:"lol"}', r'minecraft:chest 1 replace {Lock:"lol"}') test_block(r'chest[-1]{Lock:"lol"}', r'minecraft:chest -1 replace {Lock:"lol"}') test_block(r'chest[*]{Lock:"lol"}', r'minecraft:chest * replace {Lock:"lol"}') test_block(r'chest[]{Lock:"lol"}', r'minecraft:chest * replace {Lock:"lol"}') test_block(r'chest{Lock:"lol"}', r'minecraft:chest * replace {Lock:"lol"}') test_block(r'minecraft:chest[0]{Lock:"lol"}', r'minecraft:chest 0 replace {Lock:"lol"}') test_block(r'minecraft:chest[1]{Lock:"lol"}', r'minecraft:chest 1 replace {Lock:"lol"}') test_block(r'minecraft:chest[-1]{Lock:"lol"}', r'minecraft:chest -1 replace {Lock:"lol"}') test_block(r'minecraft:chest[*]{Lock:"lol"}', r'minecraft:chest * replace {Lock:"lol"}') test_block(r'minecraft:chest[]{Lock:"lol"}', r'minecraft:chest * replace {Lock:"lol"}') test_block(r'minecraft:chest{Lock:"lol"}', r'minecraft:chest * replace {Lock:"lol"}') # errors test_block('not_a_block', expect_error=True) test_block("wrong_id:stonebrick", expect_error=True) test_block("stonebrick:stonebrick", expect_error=True) test_block('stonebrick[0,1]', expect_error=True) test_block('stonebrick[0=0,1=1]', expect_error=True) test_block('stonebrick[asdf=0,nou=1]', expect_error=True) test_block("stone_brick_stairs[=]", expect_error=True) test_block("stone_brick_stairs[facing]", expect_error=True) test_block("stone_brick_stairs[facing=]", expect_error=True) test_block("stone_brick_stairs[facing=south=north]", expect_error=True) test_block("stone_brick_stairs[facing=south half=top]", expect_error=True) test_block('minecraft:not_a_block', expect_error=True) test_block('minecraft:stonebrick[0,1]', expect_error=True) test_block('minecraft:stonebrick[0=0,1=1]', expect_error=True) test_block('minecraft:stonebrick[asdf=0,nou=1]', expect_error=True) test_block("minecraft:stone_brick_stairs[=]", expect_error=True) test_block("minecraft:stone_brick_stairs[facing]", expect_error=True) test_block("minecraft:stone_brick_stairs[facing=]", expect_error=True) test_block("minecraft:stone_brick_stairs[facing=south=north]", expect_error=True) test_block("minecraft:stone_brick_stairs[facing=south half=top]", expect_error=True)
2015f26b503e42442766db3c50645d21d6ecccab
2635edb96afa8117d4584a470061e447b79adc6e
/test/booknotes_test.py
3682f6f5b88bb82f90d549216fa699601c455763
[]
no_license
Mark-Seaman/Sensei-2018
673609731ecb5ebb782dab94b2cf3d7c22940424
06b02892cfe1bf1d25cb4224e86eb693c82b0f29
refs/heads/master
2022-02-18T19:14:10.343093
2022-01-15T20:06:21
2022-01-15T20:06:21
158,728,468
0
0
null
2022-01-16T21:06:09
2018-11-22T16:51:55
HTML
UTF-8
Python
false
false
273
py
from os import environ from os.path import join from bin.shell import file_tree_list, shell, check_shell_lines def booknotes_list_test(): return shell('x booknotes list') def booknotes_lines_test(): return check_shell_lines('x booknotes content', 2700, 2800)
d6f031e3334ef1f7763c833a88e5aee446318a00
c28beb6795c688c0eeaaa3a8bf66edc7e336f9b6
/SkeinPyPy_NewUI/skeinforge_application/skeinforge_plugins/craft_plugins/cool.py
d8572d363f20cfab84c7572737a028d6804b28fe
[]
no_license
alx/SkeinPyPy
80427f81853fb302a2f3636e3cd8a2375fd8eff4
5d4e8c7ed16d43bf0ede972f5b05a56199567826
refs/heads/master
2021-01-20T22:02:59.076693
2012-03-15T10:21:07
2012-03-15T10:21:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
19,101
py
""" This page is in the table of contents. Cool is a craft tool to cool the shape. Cool works well with a stepper extruder, it does not work well with a DC motor extruder. If enabled, before each layer that takes less then "Minimum Layer Time" to print the tool head will orbit around the printed area for 'Minimum Layer Time' minus 'the time it takes to print the layer' before it starts printing the layer. This is great way to let layers with smaller area cool before you start printing on top of them (so you do not overheat the area). The cool manual page is at: http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Cool Allan Ecker aka The Masked Retriever's has written the "Skeinforge Quicktip: Cool" at: http://blog.thingiverse.com/2009/07/28/skeinforge-quicktip-cool/ ==Operation== The default 'Activate Cool' checkbox is on. When it is on, the functions described below will work, when it is off, the functions will not be called. ==Settings== ===Bridge Cool=== Default is one degree Celcius. If the layer is a bridge layer, then cool will lower the temperature by 'Bridge Cool' degrees Celcius. ===Cool Type=== Default is 'Slow Down'. ====Orbit==== When selected, cool will add orbits with the extruder off to give the layer time to cool, so that the next layer is not extruded on a molten base. The orbits will be around the largest island on that layer. Orbit should only be chosen if you can not upgrade to a stepper extruder. ====Slow Down==== When selected, cool will slow down the extruder so that it will take the minimum layer time to extrude the layer. DC motors do not operate properly at slow flow rates, so if you have a DC motor extruder, you should upgrade to a stepper extruder, but if you can't do that, you can try using the 'Orbit' option. ===Maximum Cool=== Default is 2 degrees Celcius. If it takes less time to extrude the layer than the minimum layer time, then cool will lower the temperature by the 'Maximum Cool' setting times the layer time over the minimum layer time. ===Minimum Layer Time=== Default is 60 seconds. Defines the minimum amount of time the extruder will spend on a layer, this is an important setting. ===Minimum Orbital Radius=== Default is 10 millimeters. When the orbit cool type is selected, if the area of the largest island is as large as the square of the "Minimum Orbital Radius" then the orbits will be just within the island. If the island is smaller, then the orbits will be in a square of the "Minimum Orbital Radius" around the center of the island. This is so that the hot extruder does not stay too close to small islands. ===Name of Alteration Files=== Cool looks for alteration files in the alterations folder in the .skeinforge folder in the home directory. Cool does not care if the text file names are capitalized, but some file systems do not handle file name cases properly, so to be on the safe side you should give them lower case names. If it doesn't find the file it then looks in the alterations folder in the skeinforge_plugins folder. The cool start and end text idea is from: http://makerhahn.blogspot.com/2008/10/yay-minimug.html ====Name of Cool End File==== Default is cool_end.gcode. If there is a file with the name of the "Name of Cool End File" setting, it will be added to the end of the orbits. ====Name of Cool Start File==== Default is cool_start.gcode. If there is a file with the name of the "Name of Cool Start File" setting, it will be added to the start of the orbits. ===Orbital Outset=== Default is 2 millimeters. When the orbit cool type is selected, the orbits will be outset around the largest island by 'Orbital Outset' millimeters. If 'Orbital Outset' is negative, the orbits will be inset instead. ===Turn Fan On at Beginning=== Default is on. When selected, cool will turn the fan on at the beginning of the fabrication by adding the M106 command. ===Turn Fan Off at Ending=== Default is on. When selected, cool will turn the fan off at the ending of the fabrication by adding the M107 command. ==Examples== The following examples cool the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and cool.py. > python cool.py This brings up the cool dialog. > python cool.py Screw Holder Bottom.stl The cool tool is parsing the file: Screw Holder Bottom.stl .. The cool tool has created the file: .. Screw Holder Bottom_cool.gcode """ from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module. import __init__ from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret from fabmetheus_utilities import archive from fabmetheus_utilities import euclidean from fabmetheus_utilities import gcodec from fabmetheus_utilities import intercircle from fabmetheus_utilities import settings from skeinforge_application.skeinforge_utilities import skeinforge_craft from skeinforge_application.skeinforge_utilities import skeinforge_polyfile from skeinforge_application.skeinforge_utilities import skeinforge_profile import os import sys __author__ = 'Enrique Perez ([email protected])' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def getCraftedText(fileName, text, repository=None): 'Cool a gcode linear move text.' return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), repository) def getCraftedTextFromText(gcodeText, repository=None): 'Cool a gcode linear move text.' if gcodec.isProcedureDoneOrFileIsEmpty(gcodeText, 'cool'): return gcodeText if repository == None: repository = settings.getReadRepository(CoolRepository()) if not repository.activateCool.value: return gcodeText return CoolSkein().getCraftedGcode(gcodeText, repository) def getNewRepository(): 'Get new repository.' return CoolRepository() def writeOutput(fileName, shouldAnalyze=True): 'Cool a gcode linear move file. Chain cool the gcode if it is not already cooled.' skeinforge_craft.writeChainTextWithNounMessage(fileName, 'cool', shouldAnalyze) class CoolRepository: 'A class to handle the cool settings.' def __init__(self): 'Set the default settings, execute title & settings fileName.' skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.cool.html', self ) self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Cool', self, '') self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute( 'http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Cool') self.activateCool = settings.BooleanSetting().getFromValue('Activate Cool', self, True) self.bridgeCool = settings.FloatSpin().getFromValue(0.0, 'Bridge Cool (Celcius):', self, 10.0, 1.0) self.coolType = settings.MenuButtonDisplay().getFromName('Cool Type:', self) self.orbit = settings.MenuRadio().getFromMenuButtonDisplay(self.coolType, 'Orbit', self, False) self.slowDown = settings.MenuRadio().getFromMenuButtonDisplay(self.coolType, 'Slow Down', self, True) self.maximumCool = settings.FloatSpin().getFromValue(0.0, 'Maximum Cool (Celcius):', self, 10.0, 2.0) self.minimumLayerTime = settings.FloatSpin().getFromValue(0.0, 'Minimum Layer Time (seconds):', self, 120.0, 10.0) self.minimumOrbitalRadius = settings.FloatSpin().getFromValue( 0.0, 'Minimum Orbital Radius (millimeters):', self, 20.0, 10.0) settings.LabelSeparator().getFromRepository(self) settings.LabelDisplay().getFromName('- Name of Alteration Files -', self ) self.nameOfCoolEndFile = settings.StringSetting().getFromValue('Name of Cool End File:', self, 'cool_end.gcode') self.nameOfCoolStartFile = settings.StringSetting().getFromValue('Name of Cool Start File:', self, 'cool_start.gcode') settings.LabelSeparator().getFromRepository(self) self.orbitalOutset = settings.FloatSpin().getFromValue(1.0, 'Orbital Outset (millimeters):', self, 5.0, 2.0) self.turnFanOnAtBeginning = settings.BooleanSetting().getFromValue('Turn Fan On at Beginning', self, True) self.turnFanOffAtEnding = settings.BooleanSetting().getFromValue('Turn Fan Off at Ending', self, True) self.executeTitle = 'Cool' def execute(self): 'Cool button has been clicked.' fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode( self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled) for fileName in fileNames: writeOutput(fileName) class CoolSkein: 'A class to cool a skein of extrusions.' def __init__(self): self.boundaryLayer = None self.coolTemperature = None self.distanceFeedRate = gcodec.DistanceFeedRate() self.feedRateMinute = 960.0 self.highestZ = 1.0 self.isBridgeLayer = False self.isExtruderActive = False self.layerCount = settings.LayerCount() self.lineIndex = 0 self.lines = None self.multiplier = 1.0 self.oldFlowRate = None self.oldFlowRateString = None self.oldLocation = None self.oldTemperature = None def addCoolOrbits(self, remainingOrbitTime): 'Add the minimum radius cool orbits.' if len(self.boundaryLayer.loops) < 1: return insetBoundaryLoops = self.boundaryLayer.loops if abs(self.repository.orbitalOutset.value) > 0.1 * abs(self.edgeWidth): insetBoundaryLoops = intercircle.getInsetLoopsFromLoops(self.boundaryLayer.loops, -self.repository.orbitalOutset.value) if len(insetBoundaryLoops) < 1: insetBoundaryLoops = self.boundaryLayer.loops largestLoop = euclidean.getLargestLoop(insetBoundaryLoops) loopArea = euclidean.getAreaLoopAbsolute(largestLoop) if loopArea < self.minimumArea: center = 0.5 * (euclidean.getMaximumByComplexPath(largestLoop) + euclidean.getMinimumByComplexPath(largestLoop)) centerXBounded = max(center.real, self.boundingRectangle.cornerMinimum.real) centerXBounded = min(centerXBounded, self.boundingRectangle.cornerMaximum.real) centerYBounded = max(center.imag, self.boundingRectangle.cornerMinimum.imag) centerYBounded = min(centerYBounded, self.boundingRectangle.cornerMaximum.imag) center = complex(centerXBounded, centerYBounded) maximumCorner = center + self.halfCorner minimumCorner = center - self.halfCorner largestLoop = euclidean.getSquareLoopWiddershins(minimumCorner, maximumCorner) pointComplex = euclidean.getXYComplexFromVector3(self.oldLocation) if pointComplex != None: largestLoop = euclidean.getLoopStartingClosest(self.edgeWidth, pointComplex, largestLoop) intercircle.addOrbitsIfLarge( self.distanceFeedRate, largestLoop, self.orbitalFeedRatePerSecond, remainingOrbitTime, self.highestZ) def addCoolTemperature(self, remainingOrbitTime): 'Parse a gcode line and add it to the cool skein.' layerCool = self.repository.maximumCool.value * remainingOrbitTime / self.repository.minimumLayerTime.value if self.isBridgeLayer: layerCool = max(self.repository.bridgeCool.value, layerCool) if self.oldTemperature != None and layerCool != 0.0: self.coolTemperature = self.oldTemperature - layerCool self.addTemperature(self.coolTemperature) def addFlowRate(self, flowRate): 'Add a multipled line of flow rate if different.' self.distanceFeedRate.addLine('M108 S' + euclidean.getFourSignificantFigures(flowRate)) def addGcodeFromFeedRateMovementZ(self, feedRateMinute, point, z): 'Add a movement to the output.' self.distanceFeedRate.addLine(self.distanceFeedRate.getLinearGcodeMovementWithFeedRate(feedRateMinute, point, z)) def addOrbitsIfNecessary(self, remainingOrbitTime): 'Parse a gcode line and add it to the cool skein.' if remainingOrbitTime > 0.0 and self.boundaryLayer != None: self.addCoolOrbits(remainingOrbitTime) def addTemperature(self, temperature): 'Add a line of temperature.' self.distanceFeedRate.addLine('M104 S' + euclidean.getRoundedToThreePlaces(temperature)) def getCoolMove(self, line, location, splitLine): 'Get cool line according to time spent on layer.' self.feedRateMinute = gcodec.getFeedRateMinute(self.feedRateMinute, splitLine) return self.distanceFeedRate.getLineWithFeedRate(self.multiplier * self.feedRateMinute, line, splitLine) def getCraftedGcode(self, gcodeText, repository): 'Parse gcode text and store the cool gcode.' self.repository = repository self.coolEndLines = settings.getAlterationFileLines(repository.nameOfCoolEndFile.value) self.coolStartLines = settings.getAlterationFileLines(repository.nameOfCoolStartFile.value) self.halfCorner = complex(repository.minimumOrbitalRadius.value, repository.minimumOrbitalRadius.value) self.lines = archive.getTextLines(gcodeText) self.minimumArea = 4.0 * repository.minimumOrbitalRadius.value * repository.minimumOrbitalRadius.value self.parseInitialization() self.boundingRectangle = gcodec.BoundingRectangle().getFromGcodeLines(self.lines[self.lineIndex :], 0.5 * self.edgeWidth) margin = 0.2 * self.edgeWidth halfCornerMargin = self.halfCorner + complex(margin, margin) self.boundingRectangle.cornerMaximum -= halfCornerMargin self.boundingRectangle.cornerMinimum += halfCornerMargin for self.lineIndex in xrange(self.lineIndex, len(self.lines)): line = self.lines[self.lineIndex] self.parseLine(line) if repository.turnFanOffAtEnding.value: self.distanceFeedRate.addLine('M107') return gcodec.getGcodeWithoutDuplication('M108', self.distanceFeedRate.output.getvalue()) def getLayerTime(self): 'Get the time the extruder spends on the layer.' feedRateMinute = self.feedRateMinute layerTime = 0.0 lastThreadLocation = self.oldLocation for lineIndex in xrange(self.lineIndex, len(self.lines)): line = self.lines[lineIndex] splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) firstWord = gcodec.getFirstWord(splitLine) if firstWord == 'G1': location = gcodec.getLocationFromSplitLine(lastThreadLocation, splitLine) feedRateMinute = gcodec.getFeedRateMinute(feedRateMinute, splitLine) if lastThreadLocation != None: feedRateSecond = feedRateMinute / 60.0 layerTime += location.distance(lastThreadLocation) / feedRateSecond lastThreadLocation = location elif firstWord == '(<bridgeRotation>': self.isBridgeLayer = True elif firstWord == '(</layer>)': return layerTime return layerTime def getLayerTimeActive(self): 'Get the time the extruder spends on the layer while active.' feedRateMinute = self.feedRateMinute isExtruderActive = self.isExtruderActive layerTime = 0.0 lastThreadLocation = self.oldLocation for lineIndex in xrange(self.lineIndex, len(self.lines)): line = self.lines[lineIndex] splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) firstWord = gcodec.getFirstWord(splitLine) if firstWord == 'G1': location = gcodec.getLocationFromSplitLine(lastThreadLocation, splitLine) feedRateMinute = gcodec.getFeedRateMinute(feedRateMinute, splitLine) if lastThreadLocation != None and isExtruderActive: feedRateSecond = feedRateMinute / 60.0 layerTime += location.distance(lastThreadLocation) / feedRateSecond lastThreadLocation = location elif firstWord == 'M101': isExtruderActive = True elif firstWord == 'M103': isExtruderActive = False elif firstWord == '(<bridgeRotation>': self.isBridgeLayer = True elif firstWord == '(</layer>)': return layerTime return layerTime def parseInitialization(self): 'Parse gcode initialization and store the parameters.' for self.lineIndex in xrange(len(self.lines)): line = self.lines[self.lineIndex] splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) firstWord = gcodec.getFirstWord(splitLine) self.distanceFeedRate.parseSplitLine(firstWord, splitLine) if firstWord == 'M108': self.oldFlowRate = float(splitLine[1][1 :]) elif firstWord == '(<edgeWidth>': self.edgeWidth = float(splitLine[1]) if self.repository.turnFanOnAtBeginning.value: self.distanceFeedRate.addLine('M106') elif firstWord == '(</extruderInitialization>)': self.distanceFeedRate.addTagBracketedProcedure('cool') return elif firstWord == '(<operatingFlowRate>': self.oldFlowRate = float(splitLine[1]) elif firstWord == '(<orbitalFeedRatePerSecond>': self.orbitalFeedRatePerSecond = float(splitLine[1]) self.distanceFeedRate.addLine(line) def parseLine(self, line): 'Parse a gcode line and add it to the cool skein.' splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) if len(splitLine) < 1: return firstWord = splitLine[0] if firstWord == 'G1': location = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) self.highestZ = max(location.z, self.highestZ) if self.isExtruderActive: line = self.getCoolMove(line, location, splitLine) self.oldLocation = location elif firstWord == 'M101': self.isExtruderActive = True elif firstWord == 'M103': self.isExtruderActive = False elif firstWord == 'M104': self.oldTemperature = gcodec.getDoubleAfterFirstLetter(splitLine[1]) elif firstWord == 'M108': self.oldFlowRate = float(splitLine[1][1 :]) self.addFlowRate(self.multiplier * self.oldFlowRate) return elif firstWord == '(<boundaryPoint>': self.boundaryLoop.append(gcodec.getLocationFromSplitLine(None, splitLine).dropAxis()) elif firstWord == '(<layer>': self.layerCount.printProgressIncrement('cool') self.distanceFeedRate.addLine(line) self.distanceFeedRate.addLinesSetAbsoluteDistanceMode(self.coolStartLines) layerTime = self.getLayerTime() remainingOrbitTime = max(self.repository.minimumLayerTime.value - layerTime, 0.0) self.addCoolTemperature(remainingOrbitTime) if self.repository.orbit.value: self.addOrbitsIfNecessary(remainingOrbitTime) else: self.setMultiplier(remainingOrbitTime) if self.oldFlowRate != None: self.addFlowRate(self.multiplier * self.oldFlowRate) z = float(splitLine[1]) self.boundaryLayer = euclidean.LoopLayer(z) self.highestZ = max(z, self.highestZ) self.distanceFeedRate.addLinesSetAbsoluteDistanceMode(self.coolEndLines) return elif firstWord == '(</layer>)': self.isBridgeLayer = False self.multiplier = 1.0 if self.coolTemperature != None: self.addTemperature(self.oldTemperature) self.coolTemperature = None if self.oldFlowRate != None: self.addFlowRate(self.oldFlowRate) elif firstWord == '(<nestedRing>)': self.boundaryLoop = [] self.boundaryLayer.loops.append(self.boundaryLoop) self.distanceFeedRate.addLine(line) def setMultiplier(self, remainingOrbitTime): 'Set the feed and flow rate multiplier.' layerTimeActive = self.getLayerTimeActive() self.multiplier = min(1.0, layerTimeActive / (remainingOrbitTime + layerTimeActive)) def main(): 'Display the cool dialog.' if len(sys.argv) > 1: writeOutput(' '.join(sys.argv[1 :])) else: settings.startMainLoopFromConstructor(getNewRepository()) if __name__ == '__main__': main()
8ab6f785b6f34c9e36b99994af2bb9339cfbb8db
9b64f0f04707a3a18968fd8f8a3ace718cd597bc
/huaweicloud-sdk-iam/huaweicloudsdkiam/v3/model/show_user_mfa_device_request.py
e917b2945cce19343061600282e1586bd29f038b
[ "Apache-2.0" ]
permissive
jaminGH/huaweicloud-sdk-python-v3
eeecb3fb0f3396a475995df36d17095038615fba
83ee0e4543c6b74eb0898079c3d8dd1c52c3e16b
refs/heads/master
2023-06-18T11:49:13.958677
2021-07-16T07:57:47
2021-07-16T07:57:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,931
py
# coding: utf-8 import re import six class ShowUserMfaDeviceRequest: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'user_id': 'str' } attribute_map = { 'user_id': 'user_id' } def __init__(self, user_id=None): """ShowUserMfaDeviceRequest - a model defined in huaweicloud sdk""" self._user_id = None self.discriminator = None self.user_id = user_id @property def user_id(self): """Gets the user_id of this ShowUserMfaDeviceRequest. 待查询的IAM用户ID,获取方式请参见:[获取用户ID](https://support.huaweicloud.com/api-iam/iam_17_0002.html)。 :return: The user_id of this ShowUserMfaDeviceRequest. :rtype: str """ return self._user_id @user_id.setter def user_id(self, user_id): """Sets the user_id of this ShowUserMfaDeviceRequest. 待查询的IAM用户ID,获取方式请参见:[获取用户ID](https://support.huaweicloud.com/api-iam/iam_17_0002.html)。 :param user_id: The user_id of this ShowUserMfaDeviceRequest. :type: str """ self._user_id = user_id def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): import simplejson as json return json.dumps(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ShowUserMfaDeviceRequest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
d5476304cb3aab788f50565a72061d73b9a6a5ed
5aaa7bdc5085987f925748e6b9afc694a3e9b908
/y63p.py
f9fbeee2e07e974b15c4185a22fd4c85e17a50fb
[]
no_license
swarnanjali/pythonproject
e086af8e2b03f8dae9e155f958c99c4ebb722445
10932592b601c7b27ce7eebeeb59e3876ac8fafb
refs/heads/master
2020-06-22T10:31:43.354583
2019-07-10T14:47:26
2019-07-10T14:47:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
t=input() s='' n=[] for i in t: if i not in n: s+=i n.append(i) elif i in n: break print(len(n))
cd4860ec2a8cda26dffcb523f58de782eb9b010c
53181572c4b22df4b569a9901bcd5347a3459499
/ceit_191116/py200111/output_2_format.py
67686883b4583dec92ce8b20bb65683a5a040e91
[]
no_license
edu-athensoft/ceit4101python_student
80ef067b77421fce76d04f778d5c6de8b12f676c
33cfa438c062d45e8d246b853e93d3c14b92ff2d
refs/heads/master
2020-07-30T01:04:21.084384
2020-07-27T02:21:57
2020-07-27T02:21:57
210,027,310
0
0
null
null
null
null
UTF-8
Python
false
false
349
py
""" output formatting string format() positional arguments """ name1 = 'Obama' name2 = 'Helen' name3 = 'Marie' name4 = "Cindy" greeting1 = "morning!" greeting2 = "afternoon!" greeting3 = "evening!" print("Good {1}, {0}! Long time no see".format(name3, greeting3)) print("Good {2}, {0} and {1} ! Long time no see".format(name3, name4, greeting3))
c17f393578dbf4d70079ed8f1bf7e03fa2ae8362
326e1a4dde10d287b8978ee6c7d1946934c1c0c1
/main/helper/constants.py
b6d72fef11557b099c01a5e5e402d89a8405d198
[]
no_license
volgoweb/tt
ee7a7021bf541f8dc544095c458c8a54c0956d58
7d2bc6b1a6ca3218f13f45ba3ccfda6482b3233c
HEAD
2016-08-06T00:57:27.681694
2015-03-05T07:59:31
2015-03-05T07:59:31
24,623,981
1
0
null
null
null
null
UTF-8
Python
false
false
139
py
# -*- coding: utf-8 -*- constants = { # ответ при неудаче аякс запроса 'BAD_AJAX_RESPONSE' : 'ERROR', }
730f11cd40ad83877318044f913b110a4afb45f1
5a75325ffdc14ca1eb08fa32225ba2b5b1347010
/compose/django/cull_backups.py
a05a182ed41edc94c1e0e8a196199c79d301f5c9
[ "MIT" ]
permissive
teamhero/hawc
cdc3f058aeef104c9305af67a54579f7f6362111
528f4ec605e8f406e0d147ba240a6a604f80a713
refs/heads/master
2021-05-23T06:09:01.679227
2019-03-11T14:30:39
2019-03-11T14:30:39
94,796,508
0
2
NOASSERTION
2020-04-03T23:47:21
2017-06-19T16:14:52
Python
UTF-8
Python
false
false
792
py
#!/usr/bin/env python3 import os from datetime import date, datetime today = date.today() print('Checking db backups for removal: {}'.format(today)) root = '/data/backups' for fn in os.listdir(root): if '.sql.gz' not in fn: continue d1 = datetime.strptime(fn, 'hawc-%Y-%m-%dT%H_%M.sql.gz').date() days = (today - d1).days if days <= 14: # keep all <= 14 days keep = True elif days <= 90: # keep one weekly for 3 months (or first of month) keep = (d1.day == 1 or d1.weekday() == 0) else: # keep only the first of the month keep = (d1.day == 1) if not keep: fn = os.path.join(root, fn) print('Removing %s' % fn) os.system('rm {}'.format(fn)) print('db backup removal complete')
1359004d9f80c9154062c624edc743d5280a1316
ecd27923efba50703a7bfbfa2ba37a8cc78560ea
/automatic_scraper/config/bid/liriqing/liaoning_huludao_ggzy_config.py
6d9fe5faedd7b9732ff28010a2a073fb58b59ae8
[]
no_license
yougecn/work
fb691b072a736731083777e489712dee199e6c75
1b58525e5ee8a3bdecca87fdee35a80e93d89856
refs/heads/master
2022-03-03T19:14:17.234929
2018-04-17T12:29:19
2018-04-17T12:29:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,379
py
# coding: utf-8 import time import logging import re logger = logging.getLogger(__name__) author = "liriqing" web_title = u"葫芦岛市公共资源交易" data_source = 'http://www.hldggzyjyzx.com.cn' start_urls = [ #招标公告 "http://www.hldggzyjyzx.com.cn/Front/jyxx/071001/071001001/", "http://www.hldggzyjyzx.com.cn/Front/jyxx/071002/071002001/", "http://www.hldggzyjyzx.com.cn/Front/jyxx/071002/071002002/", #更正公告 "http://www.hldggzyjyzx.com.cn/Front/jyxx/071002/071002003/", #中标候选人 "http://www.hldggzyjyzx.com.cn/Front/jyxx/071001/071001002/", #中标 "http://www.hldggzyjyzx.com.cn/Front/jyxx/071001/071001003/", "http://www.hldggzyjyzx.com.cn/Front/jyxx/071002/071002004/" ] db_config = { 'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'password': 'asd123', 'database': 'bid_data', 'table': 'zhaotoubiao' } # 列表页模板 index_pattern = { "_list": {'pattern': "//tr[@height='15']", 'type': 'xpath', 'target': 'html', 'custom_func_name': ''}, "_next_page": {'pattern': "//td[text()='下页 >' and @onclick]", 'type': 'xpath', 'target': 'html', 'custom_func_name': ''}, "title": {'pattern': "//a", 'type': 'xpath', 'target': 'text', 'custom_func_name': ''}, } # 详情页模板 detail_pattern = { "sc": {'pattern': "//table[@bgcolor='#ffffff']", 'type': 'xpath', 'target': 'html', 'custom_func_name': ''}, "_issue_time": {'pattern': "//font[@class='webfont']", 'type': 'xpath', 'target': 'text', 'custom_func_name': ''}, # "pub_date_fmt": "%Y-%m-%d %H:%M:%S", } def init(item): """初始化时执行""" logger.info(u'init item: %s', item) item['_web_title'] = item['web_title'] del item['web_title'] item['region']=u'辽宁-葫芦岛市' item['_delay_between_pages'] = 3 def process_list_item(list_element, item): """处理列表页元素 :param list_element: _list模板解析出的html元素 :param item: 获取列表页后,根据_list模板获取每一个详情html代码后执行 有些内容可在列表页获取,可自定义在此处理,如: item['pub_date'] = pq(list_element).find('span').text() """ #item['issue_time'] = int(time.mktime(time.strptime(item['issue_time'], "%Y-%m-%d"))) if '071001001' in item['_current_start_url'] or '071002001' in item['_current_start_url'] or '071002002' in item['_current_start_url']: item['bid_type']=1 elif '071001002' in item['_current_start_url']: item['bid_type']=4 elif '071002003' in item['_current_start_url']: item['bid_type'] = 2 elif '071001003' in item['_current_start_url'] or '071002004' in item['_current_start_url']: item['bid_type'] = 0 # 停止翻页 # if item['_current_page'] == 10: # item['_click_next'] = False def process_detail_item(item): """处理详情页 :param item: 获取详情页信息,存入item后执行 可在此处理程序无法处理的情况 如详情页无法解析发布时间,需要使用正则表达式从content中提取等 """ time_data=re.search(r'(\d+)/(\d+)/(\d+)',item['_issue_time'].strip(),re.S).group() item['issue_time'] = int(time.mktime(time.strptime(time_data, "%Y/%m/%d"))) if len(item['sc']) > 0: item['is_get'] = 1 else: item['is_get'] = 0
dfa29b530d8cfec3c71ef5b903b2669318bf08a0
8f7615603d4d923fd2cda41a2105b85b596ab4c5
/leetcode/easy/605-Can_place_flowers.py
0768c8acf6ccd14529365904c51987083054bec6
[ "MIT" ]
permissive
shubhamoli/solutions
e7ec922047c16cfdc10070aa5b884a278b12d8c5
5a24fdeb6e5f43b821ef0510fe3b343ddda18f22
refs/heads/master
2021-01-05T04:13:35.302613
2020-06-27T18:28:18
2020-06-27T18:28:18
240,875,585
1
0
null
null
null
null
UTF-8
Python
false
false
820
py
""" Leetcode #605 """ from typing import List class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: if not flowerbed: return False # the idea here is check for 0 and if left and right of 0 are also 0 # then plant N = len(flowerbed) i = 0 count = 0 while i < N: if (flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and (i == N - 1 or flowerbed[i+1] == 0)): flowerbed[i] = 1 count += 1 if count >= n: return True i += 1 return False if __name__ == "__main__": solution = Solution() assert solution.canPlaceFlowers([1,0,0,0,1], 1) == True assert solution.canPlaceFlowers([1,0,0,0,1], 2) == False
2844cf4b13b35cbfb70349ea571ed31560c361e4
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/synthetic/stdlib-big-881.py
32893ae51d75e73a580c1f5cc1e4256b561b48b9
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
9,003
py
# ChocoPy library functions def int_to_str(x: int) -> str: digits:[str] = None result:str = "" # Set-up digit mapping digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] # Write sign if necessary if x < 0: result = "-" x = -x # Write digits using a recursive call if x >= 10: result = result + int_to_str(x // 10) result = result + digits[x % 10] return result def int_to_str2(x: int, x2: int) -> str: digits:[str] = None digits2:[str] = None result:str = "" result2:str = "" # Set-up digit mapping digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] # Write sign if necessary if x < 0: result = "-" x = -x # Write digits using a recursive call if x >= 10: result = result + int_to_str(x // 10) result = result + digits[x % 10] return result def int_to_str3(x: int, x2: int, x3: int) -> str: digits:[str] = None digits2:[str] = None digits3:[str] = None result:str = "" result2:str = "" result3:str = "" # Set-up digit mapping digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] # Write sign if necessary if x < 0: result = "-" x = -x # Write digits using a recursive call if x >= 10: result = result + int_to_str(x // 10) result = result + digits[x % 10] return result def int_to_str4(x: int, x2: int, x3: int, x4: int) -> str: digits:[str] = None digits2:[str] = None digits3:[str] = None digits4:[str] = None result:str = "" result2:str = "" result3:str = "" result4:str = "" # Set-up digit mapping digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] # Write sign if necessary if x < 0: result = "-" x = -x # Write digits using a recursive call if x >= 10: result = result + int_to_str(x // 10) result = result + digits[x % 10] return result def int_to_str5(x: int, x2: int, x3: int, x4: int, x5: int) -> str: digits:[str] = None digits2:[str] = None digits3:[str] = None digits4:[str] = None digits5:[str] = None result:str = "" result2:str = "" result3:str = "" result4:str = "" result5:str = "" # Set-up digit mapping digits = ["0", "1", "2", "3", "4", $STRING, "6", "7", "8", "9"] # Write sign if necessary if x < 0: result = "-" x = -x # Write digits using a recursive call if x >= 10: result = result + int_to_str(x // 10) result = result + digits[x % 10] return result def str_to_int(x: str) -> int: result:int = 0 digit:int = 0 char:str = "" sign:int = 1 first_char:bool = True # Parse digits for char in x: if char == "-": if not first_char: return 0 # Error sign = -1 elif char == "0": digit = 0 elif char == "1": digit = 1 elif char == "2": digit = 2 elif char == "3": digit = 3 elif char == "3": digit = 3 elif char == "4": digit = 4 elif char == "5": digit = 5 elif char == "6": digit = 6 elif char == "7": digit = 7 elif char == "8": digit = 8 elif char == "9": digit = 9 else: return 0 # On error first_char = False result = result * 10 + digit # Compute result return result * sign def str_to_int2(x: str, x2: str) -> int: result:int = 0 result2:int = 0 digit:int = 0 digit2:int = 0 char:str = "" char2:str = "" sign:int = 1 sign2:int = 1 first_char:bool = True first_char2:bool = True # Parse digits for char in x: if char == "-": if not first_char: return 0 # Error sign = -1 elif char == "0": digit = 0 elif char == "1": digit = 1 elif char == "2": digit = 2 elif char == "3": digit = 3 elif char == "3": digit = 3 elif char == "4": digit = 4 elif char == "5": digit = 5 elif char == "6": digit = 6 elif char == "7": digit = 7 elif char == "8": digit = 8 elif char == "9": digit = 9 else: return 0 # On error first_char = False result = result * 10 + digit # Compute result return result * sign def str_to_int3(x: str, x2: str, x3: str) -> int: result:int = 0 result2:int = 0 result3:int = 0 digit:int = 0 digit2:int = 0 digit3:int = 0 char:str = "" char2:str = "" char3:str = "" sign:int = 1 sign2:int = 1 sign3:int = 1 first_char:bool = True first_char2:bool = True first_char3:bool = True # Parse digits for char in x: if char == "-": if not first_char: return 0 # Error sign = -1 elif char == "0": digit = 0 elif char == "1": digit = 1 elif char == "2": digit = 2 elif char == "3": digit = 3 elif char == "3": digit = 3 elif char == "4": digit = 4 elif char == "5": digit = 5 elif char == "6": digit = 6 elif char == "7": digit = 7 elif char == "8": digit = 8 elif char == "9": digit = 9 else: return 0 # On error first_char = False result = result * 10 + digit # Compute result return result * sign def str_to_int4(x: str, x2: str, x3: str, x4: str) -> int: result:int = 0 result2:int = 0 result3:int = 0 result4:int = 0 digit:int = 0 digit2:int = 0 digit3:int = 0 digit4:int = 0 char:str = "" char2:str = "" char3:str = "" char4:str = "" sign:int = 1 sign2:int = 1 sign3:int = 1 sign4:int = 1 first_char:bool = True first_char2:bool = True first_char3:bool = True first_char4:bool = True # Parse digits for char in x: if char == "-": if not first_char: return 0 # Error sign = -1 elif char == "0": digit = 0 elif char == "1": digit = 1 elif char == "2": digit = 2 elif char == "3": digit = 3 elif char == "3": digit = 3 elif char == "4": digit = 4 elif char == "5": digit = 5 elif char == "6": digit = 6 elif char == "7": digit = 7 elif char == "8": digit = 8 elif char == "9": digit = 9 else: return 0 # On error first_char = False result = result * 10 + digit # Compute result return result * sign def str_to_int5(x: str, x2: str, x3: str, x4: str, x5: str) -> int: result:int = 0 result2:int = 0 result3:int = 0 result4:int = 0 result5:int = 0 digit:int = 0 digit2:int = 0 digit3:int = 0 digit4:int = 0 digit5:int = 0 char:str = "" char2:str = "" char3:str = "" char4:str = "" char5:str = "" sign:int = 1 sign2:int = 1 sign3:int = 1 sign4:int = 1 sign5:int = 1 first_char:bool = True first_char2:bool = True first_char3:bool = True first_char4:bool = True first_char5:bool = True # Parse digits for char in x: if char == "-": if not first_char: return 0 # Error sign = -1 elif char == "0": digit = 0 elif char == "1": digit = 1 elif char == "2": digit = 2 elif char == "3": digit = 3 elif char == "3": digit = 3 elif char == "4": digit = 4 elif char == "5": digit = 5 elif char == "6": digit = 6 elif char == "7": digit = 7 elif char == "8": digit = 8 elif char == "9": digit = 9 else: return 0 # On error first_char = False result = result * 10 + digit # Compute result return result * sign # Input parameters c:int = 42 c2:int = 42 c3:int = 42 c4:int = 42 c5:int = 42 n:int = 10 n2:int = 10 n3:int = 10 n4:int = 10 n5:int = 10 # Run [-nc, nc] with step size c s:str = "" s2:str = "" s3:str = "" s4:str = "" s5:str = "" i:int = 0 i2:int = 0 i3:int = 0 i4:int = 0 i5:int = 0 i = -n * c # Crunch while i <= n * c: s = int_to_str(i) print(s) i = str_to_int(s) + c
fce93dd6490570c79d10bd6acd01a91479394c8c
7ae20e08e736e6df546cb5a80df2baf067686b52
/tasks/sprint-5/Финал B - Remove Node/my_solution.py
4cbe757f866c016c572fa865b916b06f74304bf0
[]
no_license
Grey2k/yandex.praktikum-alghoritms
faf466374c932733cc1c5049a2df719d8fd33ac7
97b1b4858265b44266a33b834e1e9a1349739048
refs/heads/master
2023-08-28T02:46:16.502298
2021-09-28T19:08:35
2021-09-28T19:08:35
334,646,281
10
1
null
null
null
null
UTF-8
Python
false
false
2,728
py
# from node import Node def remove(root, key): if root is None: return root node_to_remove, parent_of_node_to_remove = find_node(root, None, key) # If noting to remove returns original root if node_to_remove is None: return root # Removing found node return remove_node(root, parent_of_node_to_remove, node_to_remove) def remove_node(root, node_parent, node): left = node.left right = node.right # 0 Case - Node is root without children if node is root and left is None and right is None: root = None return root # 1 Case - Node is root and has children if node is root: if left is None: root = right return root else: max_node = find_max_and_remove(left) root = max_node # if maximum is not left part itself if max_node is not left: max_node.left = left max_node.right = right return root # 2 Case - Node has no children if left is None and right is None: if node_parent.left is node: node_parent.left = None else: node_parent.right = None return root # 2 Case - Node has children if left is None: if node_parent.left is node: node_parent.left = right else: node_parent.right = right else: max_node = find_max_and_remove(left) if node_parent.left is node: node_parent.left = max_node else: node_parent.right = max_node # if maximum is not left part itself if max_node is not left: max_node.left = left max_node.right = right return root def find_max_and_remove(node): parent = node if parent.right is None: return parent while True: if parent.right.right is None: found = parent.right parent.right = None return found parent = parent.right def find_node(root, parent, key): if root is None: return None, None if root.value == key: return root, parent if root.value < key: return find_node(root.right, root, key) if root.value > key: return find_node(root.left, root, key) # noinspection Assert def test(): node1 = Node(None, None, 2) node2 = Node(node1, None, 3) node3 = Node(None, node2, 1) node4 = Node(None, None, 6) node5 = Node(node4, None, 8) node6 = Node(node5, None, 10) node7 = Node(node3, node6, 5) new_head = remove(node7, 10) assert new_head.value == 5 assert new_head.right is node5 assert new_head.right.value == 8
9afc47d3742c9bd1433e0d1f78a7a3bc61f0e45d
65b6e3dada91a0acb589d25358badb02c845b67f
/examples/ex_graph.py
dafeb6b4aa33fafca13629a3f11db2e1e0c8e08c
[ "BSD-3-Clause" ]
permissive
polestar37/src
5b9bacb1e1e5118835d47c0f44fa5ad78fb0ad04
5dd54527356901b24b6ea3caff644a26aeb3c3c6
refs/heads/master
2021-01-15T22:39:44.730414
2017-06-22T23:06:15
2017-06-22T23:06:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,635
py
# ----------------------------------------------------------------------- # This is an example illustrating how to use the user graphing functionality # in Python # (c) Hex-Rays # from idaapi import * class GraphCloser(action_handler_t): def __init__(self, graph): action_handler_t.__init__(self) self.graph = graph def activate(self, ctx): self.graph.Close() def update(self, ctx): return AST_ENABLE_ALWAYS class ColorChanger(action_handler_t): def __init__(self, graph): action_handler_t.__init__(self) self.graph = graph def activate(self, ctx): self.graph.color = self.graph.color ^ 0xffffff self.graph.Refresh() return 1 def update(self, ctx): return AST_ENABLE_ALWAYS class MyGraph(GraphViewer): def __init__(self, funcname, result): self.title = "call graph of " + funcname GraphViewer.__init__(self, self.title) self.funcname = funcname self.result = result self.color = 0xff00ff def OnRefresh(self): self.Clear() id = self.AddNode((self.funcname, self.color)) for x in self.result.keys(): callee = self.AddNode((x, self.color)) self.AddEdge(id, callee) return True def OnGetText(self, node_id): return self[node_id] def Show(self): if not GraphViewer.Show(self): return False # graph closer actname = "graph_closer:%s" % self.title register_action(action_desc_t(actname, "Close: %s" % self.title, GraphCloser(self))) attach_action_to_popup(self.GetTCustomControl(), None, actname) # color changer actname = "color_changer:%s" % self.title register_action(action_desc_t(actname, "Change colors: %s" % self.title, ColorChanger(self))) attach_action_to_popup(self.GetTCustomControl(), None, actname) return True def show_graph(): f = idaapi.get_func(here()) if not f: print "Must be in a function" return # Iterate through all function instructions and take only call instructions result = {} for x in [x for x in FuncItems(f.startEA) if idaapi.is_call_insn(x)]: for xref in XrefsFrom(x, idaapi.XREF_FAR): if not xref.iscode: continue t = GetFunctionName(xref.to) if not t: t = hex(xref.to) result[t] = True g = MyGraph(GetFunctionName(f.startEA), result) if g.Show(): return g else: return None g = show_graph() if g: print "Graph created and displayed!"
[ "Arnaud Diederen [email protected]" ]
Arnaud Diederen [email protected]
5441634d49305645e4e9a6c7fbaffd964e776814
ad2251276aec376b480a31373165cf5b63a109c0
/input/litdata/bouwens2017.py
bbd597895d8fcf211e9ab49763d96822106933fe
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
mirochaj/ares
1b6bbe39c423762eb3051d65718394e8e839cd14
f323300b56ae61fab56eda1e5179cfc991eaa74f
refs/heads/main
2023-08-19T04:14:29.928747
2022-11-09T22:46:08
2022-11-09T22:46:08
249,536,610
16
13
MIT
2023-08-28T23:00:00
2020-03-23T20:25:55
Python
UTF-8
Python
false
false
1,534
py
""" Bouwens et al., 2017, ApJ, 843, 129 Table 4 and volume estimate from text. """ info = \ { 'reference': 'Bouwens et al., 2017, ApJ, 843, 129', 'data': 'Table 5', 'label': 'Bouwens+ (2017)' } import numpy as np redshifts = [6.] wavelength = 1600. # I think? ULIM = -1e10 tmp_data = {} tmp_data['lf'] = \ { 6.0: {'M': list(np.arange(-20.75, -12.25, 0.5)), 'phi': [0.0002, 0.0009, 0.0007, 0.0018, 0.0036, 0.0060, 0.0071, 0.0111, 0.0170, 0.0142, 0.0415, 0.0599, 0.0817, 0.1052, 0.1275, 0.1464, 0.1584], 'err': [(0.0002, 0.0002), (0.0004, 0.0004), (0.0004, 0.0004), (0.0006, 0.0006), (0.0009, 0.0009), (0.0012, 0.0012), (0.0066, 0.0014), (0.0101, 0.0022), (0.0165, 0.0039), (0.0171, 0.0054), (0.0354, 0.0069), (0.0757, 0.0106), (0.1902, 0.0210), (0.5414, 0.0434), (1.6479, 0.0747), (5.4369, 0.1077), (19.8047, 0.1343)], }, } units = {'lf': 1.} data = {} data['lf'] = {} for key in tmp_data['lf']: #mask = np.array(tmp_data['lf'][key]['err']) == ULIM N = len(tmp_data['lf'][key]['M']) mask = np.array([tmp_data['lf'][key]['err'][i] == ULIM for i in range(N)]) data['lf'][key] = {} data['lf'][key]['M'] = np.ma.array(tmp_data['lf'][key]['M'], mask=mask) data['lf'][key]['phi'] = np.ma.array(tmp_data['lf'][key]['phi'], mask=mask) data['lf'][key]['err'] = tmp_data['lf'][key]['err']
88f232fac4f287de895c8cbfeeff0607dcc04412
bc54edd6c2aec23ccfe36011bae16eacc1598467
/simscale_sdk/models/one_of_advanced_concepts_momentum_sources.py
e65a552e5e7b0f64ea0e3a14eb179f8092694ec8
[ "MIT" ]
permissive
SimScaleGmbH/simscale-python-sdk
4d9538d5efcadae718f12504fb2c7051bbe4b712
6fe410d676bf53df13c461cb0b3504278490a9bb
refs/heads/master
2023-08-17T03:30:50.891887
2023-08-14T08:09:36
2023-08-14T08:09:36
331,949,105
17
5
null
null
null
null
UTF-8
Python
false
false
9,735
py
# coding: utf-8 """ SimScale API The version of the OpenAPI document: 0.0.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from simscale_sdk.configuration import Configuration class OneOfAdvancedConceptsMomentumSources(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'type': 'str', 'name': 'str', 'average_velocity': 'DimensionalVectorSpeed', 'topological_reference': 'TopologicalReference', 'geometry_primitive_uuids': 'list[str]', 'fan_direction': 'DimensionalVectorDimensionless', 'fan_pressure': 'DimensionalFunctionPressure' } attribute_map = { 'type': 'type', 'name': 'name', 'average_velocity': 'averageVelocity', 'topological_reference': 'topologicalReference', 'geometry_primitive_uuids': 'geometryPrimitiveUuids', 'fan_direction': 'fanDirection', 'fan_pressure': 'fanPressure' } discriminator_value_class_map = { 'AVERAGE_VELOCITY': 'AverageVelocityMomentumSource', 'FAN_PRESSURE_DROP': 'FanPressureDropMomentumSource' } def __init__(self, type='FAN_PRESSURE_DROP', name=None, average_velocity=None, topological_reference=None, geometry_primitive_uuids=None, fan_direction=None, fan_pressure=None, local_vars_configuration=None): # noqa: E501 """OneOfAdvancedConceptsMomentumSources - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._type = None self._name = None self._average_velocity = None self._topological_reference = None self._geometry_primitive_uuids = None self._fan_direction = None self._fan_pressure = None self.discriminator = 'type' self.type = type if name is not None: self.name = name if average_velocity is not None: self.average_velocity = average_velocity if topological_reference is not None: self.topological_reference = topological_reference if geometry_primitive_uuids is not None: self.geometry_primitive_uuids = geometry_primitive_uuids if fan_direction is not None: self.fan_direction = fan_direction if fan_pressure is not None: self.fan_pressure = fan_pressure @property def type(self): """Gets the type of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 Schema name: FanPressureDropMomentumSource # noqa: E501 :return: The type of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :rtype: str """ return self._type @type.setter def type(self, type): """Sets the type of this OneOfAdvancedConceptsMomentumSources. Schema name: FanPressureDropMomentumSource # noqa: E501 :param type: The type of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and type is None: # noqa: E501 raise ValueError("Invalid value for `type`, must not be `None`") # noqa: E501 self._type = type @property def name(self): """Gets the name of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :return: The name of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this OneOfAdvancedConceptsMomentumSources. :param name: The name of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :type: str """ self._name = name @property def average_velocity(self): """Gets the average_velocity of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :return: The average_velocity of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :rtype: DimensionalVectorSpeed """ return self._average_velocity @average_velocity.setter def average_velocity(self, average_velocity): """Sets the average_velocity of this OneOfAdvancedConceptsMomentumSources. :param average_velocity: The average_velocity of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :type: DimensionalVectorSpeed """ self._average_velocity = average_velocity @property def topological_reference(self): """Gets the topological_reference of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :return: The topological_reference of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :rtype: TopologicalReference """ return self._topological_reference @topological_reference.setter def topological_reference(self, topological_reference): """Sets the topological_reference of this OneOfAdvancedConceptsMomentumSources. :param topological_reference: The topological_reference of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :type: TopologicalReference """ self._topological_reference = topological_reference @property def geometry_primitive_uuids(self): """Gets the geometry_primitive_uuids of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :return: The geometry_primitive_uuids of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :rtype: list[str] """ return self._geometry_primitive_uuids @geometry_primitive_uuids.setter def geometry_primitive_uuids(self, geometry_primitive_uuids): """Sets the geometry_primitive_uuids of this OneOfAdvancedConceptsMomentumSources. :param geometry_primitive_uuids: The geometry_primitive_uuids of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :type: list[str] """ self._geometry_primitive_uuids = geometry_primitive_uuids @property def fan_direction(self): """Gets the fan_direction of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :return: The fan_direction of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :rtype: DimensionalVectorDimensionless """ return self._fan_direction @fan_direction.setter def fan_direction(self, fan_direction): """Sets the fan_direction of this OneOfAdvancedConceptsMomentumSources. :param fan_direction: The fan_direction of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :type: DimensionalVectorDimensionless """ self._fan_direction = fan_direction @property def fan_pressure(self): """Gets the fan_pressure of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :return: The fan_pressure of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :rtype: DimensionalFunctionPressure """ return self._fan_pressure @fan_pressure.setter def fan_pressure(self, fan_pressure): """Sets the fan_pressure of this OneOfAdvancedConceptsMomentumSources. :param fan_pressure: The fan_pressure of this OneOfAdvancedConceptsMomentumSources. # noqa: E501 :type: DimensionalFunctionPressure """ self._fan_pressure = fan_pressure def get_real_child_model(self, data): """Returns the real base class specified by the discriminator""" discriminator_key = self.attribute_map[self.discriminator] discriminator_value = data[discriminator_key] return self.discriminator_value_class_map.get(discriminator_value) def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, OneOfAdvancedConceptsMomentumSources): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, OneOfAdvancedConceptsMomentumSources): return True return self.to_dict() != other.to_dict()
[ "simscale" ]
simscale
e3b7c0253fc3545cc8614c084a9fd36fb3322e26
e2a8c529c7e92108c11f01cbef168b5b9137521a
/ChromeGo/XX-Net/code/default/launcher/post_update.py
d05d8c507d1b2ec9887e5be04d71ed6fe7e89b0b
[ "BSD-2-Clause" ]
permissive
glxdegit/fanqiang
c28a514988eaaf6485c682bc346aa276e8b0c0b3
85691ef7a5ec99fbd81f8bdb09db7b60379e3c38
refs/heads/master
2022-07-07T06:41:24.681743
2020-05-16T02:25:22
2020-05-16T02:25:22
264,363,999
3
2
null
2020-05-16T05:11:06
2020-05-16T05:11:06
null
UTF-8
Python
false
false
2,603
py
import os import sys import re import stat import shutil current_path = os.path.dirname(os.path.abspath(__file__)) root_path = os.path.abspath(os.path.join(current_path, os.pardir)) top_path = os.path.abspath(os.path.join(root_path, os.pardir, os.pardir)) from xlog import getLogger xlog = getLogger("launcher") import config def check(): import update_from_github current_version = update_from_github.current_version() last_run_version = config.get(["modules", "launcher", "last_run_version"], "0.0.0") if last_run_version == "0.0.0": postUpdateStat = "isNew" elif last_run_version != current_version: postUpdateStat = "isPostUpdate" run(last_run_version) else: return config.set(["update", "postUpdateStat"], postUpdateStat) config.set(["modules", "launcher", "last_run_version"], current_version) config.save() def older_or_equal(version, reference_version): try: p = re.compile(r'([0-9]+)\.([0-9]+)\.([0-9]+)') m1 = p.match(version) m2 = p.match(reference_version) v1 = map(int, map(m1.group, [1, 2, 3])) v2 = map(int, map(m2.group, [1, 2, 3])) return v1 <= v2 except: xlog.warn("older_or_equal fail: %s, %s" % (version, reference_version)) # e.g. "get_version_fail" when post_update.run(last_run_version), "last_run_version" in \data\launcher\config.yaml return False # is not older def run(last_run_version): if config.get(["modules", "launcher", "auto_start"], 0): import autorun autorun.enable() if os.path.isdir(os.path.join(top_path, 'launcher')): shutil.rmtree(os.path.join(top_path, 'launcher')) # launcher is for auto-update from 2.X if older_or_equal(last_run_version, '3.0.4'): xlog.info("migrating to 3.x.x") for filename in os.listdir(top_path): filepath = os.path.join(top_path, filename) if os.path.isfile(filepath): if sys.platform != 'win32' and filename == 'start': st = os.stat(filepath) os.chmod(filepath, st.st_mode | stat.S_IEXEC) if filename in ['start.sh', 'start.command', 'start.lnk', 'LICENSE.txt', 'download.md', 'version.txt', 'xxnet', 'xxnet.bat', 'xxnet.vbs']: os.remove(filepath) else: if filename in ['goagent', 'python27', 'gae_proxy', 'php_proxy', 'x_tunnel', 'python3', 'Python3', 'lib', 'SwitchySharp']: shutil.rmtree(filepath)
45aab77aeb697bf1ad193b75e81fb1b11904a171
2995ab9f4d8e4292763f215709bd3da266c812d4
/proyecto_ibis/ibis/users/migrations/0003_auto_20210611_1201.py
696f1309a1b6218a8098ff72531e3d4b7f7bf16a
[]
no_license
mrinxx/Ibis
a45c84184c03c5983cfb67ba303235162f22abfb
4435fad66bf8082eb9a3b41b0b2d415607cd207a
refs/heads/main
2023-06-01T19:40:16.092648
2021-06-14T20:48:10
2021-06-14T20:48:10
376,138,283
0
0
null
null
null
null
UTF-8
Python
false
false
634
py
# Generated by Django 3.2.4 on 2021-06-11 12:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0002_remove_guardian_image'), ] operations = [ migrations.RemoveField( model_name='alumn', name='address', ), migrations.RemoveField( model_name='alumn', name='city', ), migrations.RemoveField( model_name='alumn', name='last_name', ), migrations.RemoveField( model_name='alumn', name='name', ), ]