input
stringlengths 11
7.65k
| target
stringlengths 22
8.26k
|
---|---|
async def open(self): pass
|
def test_execute(self):
opt = Optional(None, execute=dict)
self.assertEqual(deoption(opt), {})
self.assertEqual(deoption(opt, execute=dict), {})
self.assertEqual(deoption(None, execute=dict), {})
|
async def open(self): pass
|
def test_optional_arguments(self):
self.assertEqual(self.myfunc('a'), self.expected)
self.assertEqual(self.myfunc('a', 5), self.expected)
self.assertEqual(self.myfunc('a', second=5), self.expected)
self.assertEqual(self.myfunc('a', 5, 5), self.expected)
self.assertEqual(self.myfunc('a', fourth=[]), self.expected)
|
async def open(self): pass
|
def test_edges(self):
self.assertEqual(self.myfunc('a', third=None), self.expected)
|
async def open(self): pass
|
def test_exceptions(self):
self.assert_(issubclass(DeoptionError, TypeError))
self.assertRaises(TypeError,
lambda: Optional()
)
self.assertRaises(TypeError,
lambda: Optional(NotPassed, NotPassed)
)
|
async def open(self): pass
|
def list_query_results_for_management_group(
self,
management_group_name: str,
query_options: Optional["_models.QueryOptions"] = None,
**kwargs: Any
) -> AsyncIterable["_models.PolicyTrackedResourcesQueryResults"]:
"""Queries policy tracked resources under the management group.
:param management_group_name: Management group name.
:type management_group_name: str
:param query_options: Parameter group.
:type query_options: ~azure.mgmt.policyinsights.models.QueryOptions
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
|
async def open(self): pass
|
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_query_results_for_management_group.metadata['url'] # type: ignore
path_format_arguments = {
'managementGroupsNamespace': self._serialize.url("management_groups_namespace", management_groups_namespace, 'str'),
'managementGroupName': self._serialize.url("management_group_name", management_group_name, 'str'),
'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if _top is not None:
query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0)
if _filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str')
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.post(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
|
async def open(self): pass
|
async def extract_data(pipeline_response):
deserialized = self._deserialize('PolicyTrackedResourcesQueryResults', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
|
async def open(self): pass
|
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
|
async def open(self): pass
|
def list_query_results_for_subscription(
self,
query_options: Optional["_models.QueryOptions"] = None,
**kwargs: Any
) -> AsyncIterable["_models.PolicyTrackedResourcesQueryResults"]:
"""Queries policy tracked resources under the subscription.
:param query_options: Parameter group.
:type query_options: ~azure.mgmt.policyinsights.models.QueryOptions
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
|
async def open(self): pass
|
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_query_results_for_subscription.metadata['url'] # type: ignore
path_format_arguments = {
'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, '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]
if _top is not None:
query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0)
if _filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str')
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.post(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
|
async def open(self): pass
|
def list_query_results_for_resource_group(
self,
resource_group_name: str,
query_options: Optional["_models.QueryOptions"] = None,
**kwargs: Any
) -> AsyncIterable["_models.PolicyTrackedResourcesQueryResults"]:
"""Queries policy tracked resources under the resource group.
:param resource_group_name: Resource group name.
:type resource_group_name: str
:param query_options: Parameter group.
:type query_options: ~azure.mgmt.policyinsights.models.QueryOptions
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
|
async def open(self): pass
|
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_query_results_for_resource_group.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, '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]
if _top is not None:
query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0)
if _filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str')
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.post(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
|
async def open(self): pass
|
async def extract_data(pipeline_response):
deserialized = self._deserialize('PolicyTrackedResourcesQueryResults', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
|
async def open(self): pass
|
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.QueryFailure, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
|
async def open(self): pass
|
def list_query_results_for_resource(
self,
resource_id: str,
query_options: Optional["_models.QueryOptions"] = None,
**kwargs: Any
) -> AsyncIterable["_models.PolicyTrackedResourcesQueryResults"]:
"""Queries policy tracked resources under the resource.
:param resource_id: Resource ID.
:type resource_id: str
:param query_options: Parameter group.
:type query_options: ~azure.mgmt.policyinsights.models.QueryOptions
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either PolicyTrackedResourcesQueryResults or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.policyinsights.models.PolicyTrackedResourcesQueryResults]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyTrackedResourcesQueryResults"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
|
async def open(self): pass
|
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_query_results_for_resource.metadata['url'] # type: ignore
path_format_arguments = {
'resourceId': self._serialize.url("resource_id", resource_id, 'str', skip_quote=True),
'policyTrackedResourcesResource': self._serialize.url("policy_tracked_resources_resource", policy_tracked_resources_resource, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if _top is not None:
query_parameters['$top'] = self._serialize.query("top", _top, 'int', minimum=0)
if _filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", _filter, 'str')
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.post(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
|
async def open(self): pass
|
def create_channel(
cls,
host: str = "appengine.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs,
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
Raises:
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
quota_project_id=quota_project_id,
default_scopes=cls.AUTH_SCOPES,
scopes=scopes,
default_host=cls.DEFAULT_HOST,
**kwargs,
)
|
async def open(self): pass
|
def grpc_channel(self) -> grpc.Channel:
"""Return the channel designed to connect to this service.
"""
return self._grpc_channel
|
async def open(self): pass
|
def operations_client(self) -> operations_v1.OperationsClient:
"""Create the client designed to process long-running operations.
This property caches on the instance; repeated calls return the same
client.
"""
# Quick check: Only create a new client if we do not already have one.
if self._operations_client is None:
self._operations_client = operations_v1.OperationsClient(self.grpc_channel)
# Return the client from cache.
return self._operations_client
|
async def open(self): pass
|
def list_instances(
self,
) -> Callable[[appengine.ListInstancesRequest], appengine.ListInstancesResponse]:
r"""Return a callable for the list instances method over gRPC.
Lists the instances of a version.
Tip: To aggregate details about instances over time, see the
`Stackdriver Monitoring
API <https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list>`__.
Returns:
Callable[[~.ListInstancesRequest],
~.ListInstancesResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_instances" not in self._stubs:
self._stubs["list_instances"] = self.grpc_channel.unary_unary(
"/google.appengine.v1.Instances/ListInstances",
request_serializer=appengine.ListInstancesRequest.serialize,
response_deserializer=appengine.ListInstancesResponse.deserialize,
)
return self._stubs["list_instances"]
|
async def open(self): pass
|
def get_instance(
self,
) -> Callable[[appengine.GetInstanceRequest], instance.Instance]:
r"""Return a callable for the get instance method over gRPC.
Gets instance information.
Returns:
Callable[[~.GetInstanceRequest],
~.Instance]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_instance" not in self._stubs:
self._stubs["get_instance"] = self.grpc_channel.unary_unary(
"/google.appengine.v1.Instances/GetInstance",
request_serializer=appengine.GetInstanceRequest.serialize,
response_deserializer=instance.Instance.deserialize,
)
return self._stubs["get_instance"]
|
async def open(self): pass
|
def delete_instance(
self,
) -> Callable[[appengine.DeleteInstanceRequest], operations_pb2.Operation]:
r"""Return a callable for the delete instance method over gRPC.
Stops a running instance.
The instance might be automatically recreated based on the
scaling settings of the version. For more information, see "How
Instances are Managed" (`standard
environment <https://cloud.google.com/appengine/docs/standard/python/how-instances-are-managed>`__
\| `flexible
environment <https://cloud.google.com/appengine/docs/flexible/python/how-instances-are-managed>`__).
To ensure that instances are not re-created and avoid getting
billed, you can stop all instances within the target version by
changing the serving status of the version to ``STOPPED`` with
the
```apps.services.versions.patch`` <https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions/patch>`__
method.
Returns:
Callable[[~.DeleteInstanceRequest],
~.Operation]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "delete_instance" not in self._stubs:
self._stubs["delete_instance"] = self.grpc_channel.unary_unary(
"/google.appengine.v1.Instances/DeleteInstance",
request_serializer=appengine.DeleteInstanceRequest.serialize,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["delete_instance"]
|
async def open(self): pass
|
def debug_instance(
self,
) -> Callable[[appengine.DebugInstanceRequest], operations_pb2.Operation]:
r"""Return a callable for the debug instance method over gRPC.
Enables debugging on a VM instance. This allows you
to use the SSH command to connect to the virtual machine
where the instance lives. While in "debug mode", the
instance continues to serve live traffic. You should
delete the instance when you are done debugging and then
allow the system to take over and determine if another
instance should be started.
Only applicable for instances in App Engine flexible
environment.
Returns:
Callable[[~.DebugInstanceRequest],
~.Operation]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "debug_instance" not in self._stubs:
self._stubs["debug_instance"] = self.grpc_channel.unary_unary(
"/google.appengine.v1.Instances/DebugInstance",
request_serializer=appengine.DebugInstanceRequest.serialize,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["debug_instance"]
|
async def open(self): pass
|
def close(self):
self.grpc_channel.close()
|
async def open(self): pass
|
def reset(cls):
cls.info = [
[
"Keyboard Control:",
" auto repeat: on key click percent: 0 LED mask: 00000002",
" XKB indicators:",
" 00: Caps Lock: off 01: Num Lock: on 02: Scroll Lock: off",
" 03: Compose: off 04: Kana: off 05: Sleep: off",
],
[
"Keyboard Control:",
" auto repeat: on key click percent: 0 LED mask: 00000002",
" XKB indicators:",
" 00: Caps Lock: on 01: Num Lock: on 02: Scroll Lock: off",
" 03: Compose: off 04: Kana: off 05: Sleep: off",
],
]
cls.index = 0
cls.is_error = False
|
async def open(self): pass
|
def call_process(cls, cmd):
if cls.is_error:
raise subprocess.CalledProcessError(-1, cmd=cmd, output="Couldn't call xset.")
if cmd[1:] == ["q"]:
track = cls.info[cls.index]
output = "\n".join(track)
return output
|
async def open(self): pass
|
def patched_cnli(monkeypatch):
MockCapsNumLockIndicator.reset()
monkeypatch.setattr(
"libqtile.widget.caps_num_lock_indicator.subprocess", MockCapsNumLockIndicator
)
monkeypatch.setattr(
"libqtile.widget.caps_num_lock_indicator.subprocess.CalledProcessError",
subprocess.CalledProcessError,
)
monkeypatch.setattr(
"libqtile.widget.caps_num_lock_indicator.base.ThreadPoolText.call_process",
MockCapsNumLockIndicator.call_process,
)
return caps_num_lock_indicator
|
async def open(self): pass
|
def test_cnli(fake_qtile, patched_cnli, fake_window):
widget = patched_cnli.CapsNumLockIndicator()
fakebar = FakeBar([widget], window=fake_window)
widget._configure(fake_qtile, fakebar)
text = widget.poll()
assert text == "Caps off Num on"
|
async def open(self): pass
|
def test_cnli_caps_on(fake_qtile, patched_cnli, fake_window):
widget = patched_cnli.CapsNumLockIndicator()
# Simulate Caps on
MockCapsNumLockIndicator.index = 1
fakebar = FakeBar([widget], window=fake_window)
widget._configure(fake_qtile, fakebar)
text = widget.poll()
assert text == "Caps on Num on"
|
async def open(self): pass
|
def draw_axis(img, charuco_corners, charuco_ids, board):
vecs = np.load("./calib.npz") # I already calibrated the camera
mtx, dist, _, _ = [vecs[i] for i in ('mtx', 'dist', 'rvecs', 'tvecs')]
ret, rvec, tvec = cv2.aruco.estimatePoseCharucoBoard(
charuco_corners, charuco_ids, board, mtx, dist)
if ret is not None and ret is True:
cv2.aruco.drawAxis(img, mtx, dist, rvec, tvec, 0.1)
|
async def open(self): pass
|
def get_image(camera):
ret, img = camera.read()
return img
|
async def open(self): pass
|
def make_grayscale(img):
ret = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return ret
|
async def open(self): pass
|
def main():
camera = cv2.VideoCapture(0)
img = get_image(camera)
while True:
cv2.imshow('calibration', img)
cv2.waitKey(10)
img = get_image(camera)
gray = make_grayscale(img)
corners, ids, rejected = cv2.aruco.detectMarkers(gray, aruco_dict,
corners, ids)
cv2.aruco.drawDetectedMarkers(img, corners, ids)
if ids is not None and corners is not None \
and len(ids) > 0 and len(ids) == len(corners):
diamond_corners, diamond_ids = \
cv2.aruco.detectCharucoDiamond(img, corners, ids,
0.05 / 0.03, cameraMatrix=mtx,
distCoeffs=dist)
cv2.aruco.drawDetectedDiamonds(img, diamond_corners, diamond_ids)
'''if diamond_ids is not None and len(diamond_ids) >= 4:
break'''
board = cv2.aruco.CharucoBoard_create(9, 6, 0.05, 0.03,
aruco_dict)
if diamond_corners is not None and diamond_ids is not None \
and len(diamond_corners) == len(diamond_ids):
count, char_corners, char_ids = \
cv2.aruco.interpolateCornersCharuco(diamond_corners,
diamond_ids, gray,
board)
if count >= 3:
draw_axis(img, char_corners, char_ids, board)
|
async def open(self): pass
|
def process_weight(sym, arg, aux):
for stride in RpnParam.anchor_generate.stride:
add_anchor_to_arg(
sym, arg, aux, RpnParam.anchor_generate.max_side,
stride, RpnParam.anchor_generate.scale,
RpnParam.anchor_generate.ratio)
|
async def open(self): pass
|
def __init__(self):
self.generate = self._generate()
|
async def open(self): pass
|
def __init__(self):
self.stride = (4, 8, 16, 32, 64)
self.short = (200, 100, 50, 25, 13)
self.long = (334, 167, 84, 42, 21)
|
async def open(self): pass
|
def do_register_opts(opts, group=None, ignore_errors=False):
try:
cfg.CONF.register_opts(opts, group=group)
except:
if not ignore_errors:
raise
|
async def open(self): pass
|
def do_register_cli_opts(opt, ignore_errors=False):
# TODO: This function has broken name, it should work with lists :/
if not isinstance(opt, (list, tuple)):
opts = [opt]
else:
opts = opt
try:
cfg.CONF.register_cli_opts(opts)
except:
if not ignore_errors:
raise
|
async def open(self): pass
|
def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform})
|
async def open(self): pass
|
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, "voir", "view")
self.schema = "<cle>"
self.aide_courte = "affiche le détail d'un chemin"
self.aide_longue = \
"Cette commande permet d'obtenir plus d'informations sur " \
"un chemin (ses flags actifs, ses salles et sorties...)."
|
async def open(self): pass
|
def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
})
|
async def open(self): pass
|
def ajouter(self):
"""Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
cle = self.noeud.get_masque("cle")
cle.proprietes["regex"] = r"'[a-z0-9_:]{3,}'"
|
async def open(self): pass
|
def make_data(cuda=False):
train_x = torch.linspace(0, 1, 100)
train_y = torch.sin(train_x * (2 * pi))
train_y.add_(torch.randn_like(train_y), alpha=1e-2)
test_x = torch.rand(51)
test_y = torch.sin(test_x * (2 * pi))
if cuda:
train_x = train_x.cuda()
train_y = train_y.cuda()
test_x = test_x.cuda()
test_y = test_y.cuda()
return train_x, train_y, test_x, test_y
|
async def open(self): pass
|
def __init__(self, train_x, train_y, likelihood):
super(GPRegressionModel, self).__init__(train_x, train_y, likelihood)
self.mean_module = ConstantMean(prior=SmoothedBoxPrior(-1e-5, 1e-5))
self.base_covar_module = ScaleKernel(RBFKernel(lengthscale_prior=SmoothedBoxPrior(exp(-5), exp(6), sigma=0.1)))
self.covar_module = InducingPointKernel(
self.base_covar_module, inducing_points=torch.linspace(0, 1, 32), likelihood=likelihood
)
|
async def open(self): pass
|
def forward(self, x):
mean_x = self.mean_module(x)
covar_x = self.covar_module(x)
return MultivariateNormal(mean_x, covar_x)
|
async def open(self): pass
|
def setUp(self):
if os.getenv("UNLOCK_SEED") is None or os.getenv("UNLOCK_SEED").lower() == "false":
self.rng_state = torch.get_rng_state()
torch.manual_seed(0)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0)
random.seed(0)
|
async def open(self): pass
|
def tearDown(self):
if hasattr(self, "rng_state"):
torch.set_rng_state(self.rng_state)
|
async def open(self): pass
|
def test_sgpr_mean_abs_error(self):
# Suppress numerical warnings
warnings.simplefilter("ignore", NumericalWarning)
train_x, train_y, test_x, test_y = make_data()
likelihood = GaussianLikelihood()
gp_model = GPRegressionModel(train_x, train_y, likelihood)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)
# Optimize the model
gp_model.train()
likelihood.train()
optimizer = optim.Adam(gp_model.parameters(), lr=0.1)
for _ in range(30):
optimizer.zero_grad()
output = gp_model(train_x)
loss = -mll(output, train_y)
loss.backward()
optimizer.step()
for param in gp_model.parameters():
self.assertTrue(param.grad is not None)
self.assertGreater(param.grad.norm().item(), 0)
# Test the model
gp_model.eval()
likelihood.eval()
test_preds = likelihood(gp_model(test_x)).mean
mean_abs_error = torch.mean(torch.abs(test_y - test_preds))
self.assertLess(mean_abs_error.squeeze().item(), 0.05)
|
async def open(self): pass
|
def test_sgpr_fast_pred_var(self):
# Suppress numerical warnings
warnings.simplefilter("ignore", NumericalWarning)
train_x, train_y, test_x, test_y = make_data()
likelihood = GaussianLikelihood()
gp_model = GPRegressionModel(train_x, train_y, likelihood)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)
# Optimize the model
gp_model.train()
likelihood.train()
optimizer = optim.Adam(gp_model.parameters(), lr=0.1)
for _ in range(50):
optimizer.zero_grad()
output = gp_model(train_x)
loss = -mll(output, train_y)
loss.backward()
optimizer.step()
for param in gp_model.parameters():
self.assertTrue(param.grad is not None)
self.assertGreater(param.grad.norm().item(), 0)
# Test the model
gp_model.eval()
likelihood.eval()
with gpytorch.settings.max_preconditioner_size(5), gpytorch.settings.max_cg_iterations(50):
with gpytorch.settings.fast_pred_var(True):
fast_var = gp_model(test_x).variance
fast_var_cache = gp_model(test_x).variance
self.assertLess(torch.max((fast_var_cache - fast_var).abs()), 1e-3)
with gpytorch.settings.fast_pred_var(False):
slow_var = gp_model(test_x).variance
self.assertLess(torch.max((fast_var_cache - slow_var).abs()), 1e-3)
|
async def open(self): pass
|
def test_sgpr_mean_abs_error_cuda(self):
# Suppress numerical warnings
warnings.simplefilter("ignore", NumericalWarning)
if not torch.cuda.is_available():
return
with least_used_cuda_device():
train_x, train_y, test_x, test_y = make_data(cuda=True)
likelihood = GaussianLikelihood().cuda()
gp_model = GPRegressionModel(train_x, train_y, likelihood).cuda()
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)
# Optimize the model
gp_model.train()
likelihood.train()
optimizer = optim.Adam(gp_model.parameters(), lr=0.1)
optimizer.n_iter = 0
for _ in range(25):
optimizer.zero_grad()
output = gp_model(train_x)
loss = -mll(output, train_y)
loss.backward()
optimizer.n_iter += 1
optimizer.step()
for param in gp_model.parameters():
self.assertTrue(param.grad is not None)
self.assertGreater(param.grad.norm().item(), 0)
# Test the model
gp_model.eval()
likelihood.eval()
test_preds = likelihood(gp_model(test_x)).mean
mean_abs_error = torch.mean(torch.abs(test_y - test_preds))
self.assertLess(mean_abs_error.squeeze().item(), 0.02)
|
async def open(self): pass
|
def test_subclass(self):
class X(Structure):
_fields_ = [("a", c_int)]
class Y(X):
_fields_ = [("b", c_int)]
class Z(X):
pass
self.assertEqual(sizeof(X), sizeof(c_int))
self.assertEqual(sizeof(Y), sizeof(c_int)*2)
self.assertEqual(sizeof(Z), sizeof(c_int))
self.assertEqual(X._fields_, [("a", c_int)])
self.assertEqual(Y._fields_, [("b", c_int)])
self.assertEqual(Z._fields_, [("a", c_int)])
|
async def open(self): pass
|
def test_subclass_delayed(self):
class X(Structure):
pass
self.assertEqual(sizeof(X), 0)
X._fields_ = [("a", c_int)]
class Y(X):
pass
self.assertEqual(sizeof(Y), sizeof(X))
Y._fields_ = [("b", c_int)]
class Z(X):
pass
self.assertEqual(sizeof(X), sizeof(c_int))
self.assertEqual(sizeof(Y), sizeof(c_int)*2)
self.assertEqual(sizeof(Z), sizeof(c_int))
self.assertEqual(X._fields_, [("a", c_int)])
self.assertEqual(Y._fields_, [("b", c_int)])
self.assertEqual(Z._fields_, [("a", c_int)])
|
async def open(self): pass
|
def test_simple_structs(self):
for code, tp in self.formats.items():
class X(Structure):
_fields_ = [("x", c_char),
("y", tp)]
self.assertEqual((sizeof(X), code),
(calcsize("c%c0%c" % (code, code)), code))
|
async def open(self): pass
|
def test_unions(self):
for code, tp in self.formats.items():
class X(Union):
_fields_ = [("x", c_char),
("y", tp)]
self.assertEqual((sizeof(X), code),
(calcsize("%c" % (code)), code))
|
async def open(self): pass
|
def test_struct_alignment(self):
class X(Structure):
_fields_ = [("x", c_char * 3)]
self.assertEqual(alignment(X), calcsize("s"))
self.assertEqual(sizeof(X), calcsize("3s"))
class Y(Structure):
_fields_ = [("x", c_char * 3),
("y", c_int)]
self.assertEqual(alignment(Y), calcsize("i"))
self.assertEqual(sizeof(Y), calcsize("3si"))
class SI(Structure):
_fields_ = [("a", X),
("b", Y)]
self.assertEqual(alignment(SI), max(alignment(Y), alignment(X)))
self.assertEqual(sizeof(SI), calcsize("3s0i 3si 0i"))
class IS(Structure):
_fields_ = [("b", Y),
("a", X)]
self.assertEqual(alignment(SI), max(alignment(X), alignment(Y)))
self.assertEqual(sizeof(IS), calcsize("3si 3s 0i"))
class XX(Structure):
_fields_ = [("a", X),
("b", X)]
self.assertEqual(alignment(XX), alignment(X))
self.assertEqual(sizeof(XX), calcsize("3s 3s 0s"))
|
async def open(self): pass
|
def test_emtpy(self):
# I had problems with these
#
# Although these are patological cases: Empty Structures!
class X(Structure):
_fields_ = []
class Y(Union):
_fields_ = []
# Is this really the correct alignment, or should it be 0?
self.assertTrue(alignment(X) == alignment(Y) == 1)
self.assertTrue(sizeof(X) == sizeof(Y) == 0)
class XX(Structure):
_fields_ = [("a", X),
("b", X)]
self.assertEqual(alignment(XX), 1)
self.assertEqual(sizeof(XX), 0)
|
async def open(self): pass
|
def test_fields(self):
# test the offset and size attributes of Structure/Unoin fields.
class X(Structure):
_fields_ = [("x", c_int),
("y", c_char)]
self.assertEqual(X.x.offset, 0)
self.assertEqual(X.x.size, sizeof(c_int))
self.assertEqual(X.y.offset, sizeof(c_int))
self.assertEqual(X.y.size, sizeof(c_char))
# readonly
self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
class X(Union):
_fields_ = [("x", c_int),
("y", c_char)]
self.assertEqual(X.x.offset, 0)
self.assertEqual(X.x.size, sizeof(c_int))
self.assertEqual(X.y.offset, 0)
self.assertEqual(X.y.size, sizeof(c_char))
# readonly
self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
# XXX Should we check nested data types also?
# offset is always relative to the class...
|
async def open(self): pass
|
def test_packed(self):
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 1
self.assertEqual(sizeof(X), 9)
self.assertEqual(X.b.offset, 1)
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 2
self.assertEqual(sizeof(X), 10)
self.assertEqual(X.b.offset, 2)
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 4
self.assertEqual(sizeof(X), 12)
self.assertEqual(X.b.offset, 4)
import struct
longlong_size = struct.calcsize("q")
longlong_align = struct.calcsize("bq") - longlong_size
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 8
self.assertEqual(sizeof(X), longlong_align + longlong_size)
self.assertEqual(X.b.offset, min(8, longlong_align))
d = {"_fields_": [("a", "b"),
("b", "q")],
"_pack_": -1}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
# Issue 15989
d = {"_fields_": [("a", c_byte)],
"_pack_": _testcapi.INT_MAX + 1}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
d = {"_fields_": [("a", c_byte)],
"_pack_": _testcapi.UINT_MAX + 2}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
|
async def open(self): pass
|
def test_initializers(self):
class Person(Structure):
_fields_ = [("name", c_char*6),
("age", c_int)]
self.assertRaises(TypeError, Person, 42)
self.assertRaises(ValueError, Person, b"asldkjaslkdjaslkdj")
self.assertRaises(TypeError, Person, "Name", "HI")
# short enough
self.assertEqual(Person(b"12345", 5).name, b"12345")
# exact fit
self.assertEqual(Person(b"123456", 5).name, b"123456")
# too long
self.assertRaises(ValueError, Person, b"1234567", 5)
|
async def open(self): pass
|
def test_conflicting_initializers(self):
class POINT(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
# conflicting positional and keyword args
self.assertRaises(TypeError, POINT, 2, 3, x=4)
self.assertRaises(TypeError, POINT, 2, 3, y=4)
# too many initializers
self.assertRaises(TypeError, POINT, 2, 3, 4)
|
async def open(self): pass
|
def test_keyword_initializers(self):
class POINT(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
pt = POINT(1, 2)
self.assertEqual((pt.x, pt.y), (1, 2))
pt = POINT(y=2, x=1)
self.assertEqual((pt.x, pt.y), (1, 2))
|
async def open(self): pass
|
def test_invalid_field_types(self):
class POINT(Structure):
pass
self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)])
|
async def open(self): pass
|
def declare_with_name(name):
class S(Structure):
_fields_ = [(name, c_int)]
|
async def open(self): pass
|
def test_intarray_fields(self):
class SomeInts(Structure):
_fields_ = [("a", c_int * 4)]
# can use tuple to initialize array (but not list!)
self.assertEqual(SomeInts((1, 2)).a[:], [1, 2, 0, 0])
self.assertEqual(SomeInts((1, 2)).a[::], [1, 2, 0, 0])
self.assertEqual(SomeInts((1, 2)).a[::-1], [0, 0, 2, 1])
self.assertEqual(SomeInts((1, 2)).a[::2], [1, 0])
self.assertEqual(SomeInts((1, 2)).a[1:5:6], [2])
self.assertEqual(SomeInts((1, 2)).a[6:4:-1], [])
self.assertEqual(SomeInts((1, 2, 3, 4)).a[:], [1, 2, 3, 4])
self.assertEqual(SomeInts((1, 2, 3, 4)).a[::], [1, 2, 3, 4])
# too long
# XXX Should raise ValueError?, not RuntimeError
self.assertRaises(RuntimeError, SomeInts, (1, 2, 3, 4, 5))
|
async def open(self): pass
|
def test_nested_initializers(self):
# test initializing nested structures
class Phone(Structure):
_fields_ = [("areacode", c_char*6),
("number", c_char*12)]
class Person(Structure):
_fields_ = [("name", c_char * 12),
("phone", Phone),
("age", c_int)]
p = Person(b"Someone", (b"1234", b"5678"), 5)
self.assertEqual(p.name, b"Someone")
self.assertEqual(p.phone.areacode, b"1234")
self.assertEqual(p.phone.number, b"5678")
self.assertEqual(p.age, 5)
|
async def open(self): pass
|
def test_structures_with_wchar(self):
try:
c_wchar
except NameError:
return # no unicode
class PersonW(Structure):
_fields_ = [("name", c_wchar * 12),
("age", c_int)]
p = PersonW("Someone \xe9")
self.assertEqual(p.name, "Someone \xe9")
self.assertEqual(PersonW("1234567890").name, "1234567890")
self.assertEqual(PersonW("12345678901").name, "12345678901")
# exact fit
self.assertEqual(PersonW("123456789012").name, "123456789012")
#too long
self.assertRaises(ValueError, PersonW, "1234567890123")
|
async def open(self): pass
|
def test_init_errors(self):
class Phone(Structure):
_fields_ = [("areacode", c_char*6),
("number", c_char*12)]
class Person(Structure):
_fields_ = [("name", c_char * 12),
("phone", Phone),
("age", c_int)]
cls, msg = self.get_except(Person, b"Someone", (1, 2))
self.assertEqual(cls, RuntimeError)
self.assertEqual(msg,
"(Phone) <class 'TypeError'>: "
"expected string, int found")
cls, msg = self.get_except(Person, b"Someone", (b"a", b"b", b"c"))
self.assertEqual(cls, RuntimeError)
if issubclass(Exception, object):
self.assertEqual(msg,
"(Phone) <class 'TypeError'>: too many initializers")
else:
self.assertEqual(msg, "(Phone) TypeError: too many initializers")
|
async def open(self): pass
|
def create_class(length):
class S(Structure):
_fields_ = [('x' * length, c_int)]
|
async def open(self): pass
|
def get_except(self, func, *args):
try:
func(*args)
except Exception as detail:
return detail.__class__, str(detail)
|
async def open(self): pass
|
def test_abstract_class(self):
class X(Structure):
_abstract_ = "something"
# try 'X()'
cls, msg = self.get_except(eval, "X()", locals())
self.assertEqual((cls, msg), (TypeError, "abstract class"))
|
async def open(self): pass
|
def test_methods(self):
|
async def open(self): pass
|
def test_positional_args(self):
# see also http://bugs.python.org/issue5042
class W(Structure):
_fields_ = [("a", c_int), ("b", c_int)]
class X(W):
_fields_ = [("c", c_int)]
class Y(X):
pass
class Z(Y):
_fields_ = [("d", c_int), ("e", c_int), ("f", c_int)]
z = Z(1, 2, 3, 4, 5, 6)
self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
(1, 2, 3, 4, 5, 6))
z = Z(1)
self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
(1, 0, 0, 0, 0, 0))
self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7))
|
async def open(self): pass
|
def test(self):
# a Structure with a POINTER field
class S(Structure):
_fields_ = [("array", POINTER(c_int))]
s = S()
# We can assign arrays of the correct type
s.array = (c_int * 3)(1, 2, 3)
items = [s.array[i] for i in range(3)]
self.assertEqual(items, [1, 2, 3])
# The following are bugs, but are included here because the unittests
# also describe the current behaviour.
#
# This fails with SystemError: bad arg to internal function
# or with IndexError (with a patch I have)
s.array[0] = 42
items = [s.array[i] for i in range(3)]
self.assertEqual(items, [42, 2, 3])
s.array[0] = 1
|
async def open(self): pass
|
def test_none_to_pointer_fields(self):
class S(Structure):
_fields_ = [("x", c_int),
("p", POINTER(c_int))]
s = S()
s.x = 12345678
s.p = None
self.assertEqual(s.x, 12345678)
|
async def open(self): pass
|
def test_contains_itself(self):
class Recursive(Structure):
pass
try:
Recursive._fields_ = [("next", Recursive)]
except AttributeError as details:
self.assertTrue("Structure or union cannot contain itself" in
str(details))
else:
self.fail("Structure or union cannot contain itself")
|
async def open(self): pass
|
def test_vice_versa(self):
class First(Structure):
pass
class Second(Structure):
pass
First._fields_ = [("second", Second)]
try:
Second._fields_ = [("first", First)]
except AttributeError as details:
self.assertTrue("_fields_ is final" in
str(details))
else:
self.fail("AttributeError not raised")
|
async def open(self): pass
|
def config(self):
settings = {
# Use SYSTEMMPI since openfoam-org doesn't have USERMPI
'mplib': 'SYSTEMMPI',
# Add links into bin/, lib/ (eg, for other applications)
'link': False,
}
# OpenFOAM v2.4 and earlier lacks WM_LABEL_OPTION
if self.spec.satisfies('@:2.4'):
settings['label-size'] = False
return settings
|
async def open(self): pass
|
def __init__(self,title,richtext,text):
self.title=title
self.richtext=richtext
self.text=text
|
async def open(self): pass
|
def setup_run_environment(self, env):
bashrc = self.prefix.etc.bashrc
try:
env.extend(EnvironmentModifications.from_sourcing_file(
bashrc, clean=True
))
except Exception as e:
msg = 'unexpected error when sourcing OpenFOAM bashrc [{0}]'
tty.warn(msg.format(str(e)))
|
async def open(self): pass
|
def __init__(self):
self.factory = yui.YUI.widgetFactory()
self.dialog = self.factory.createPopupDialog()
mainvbox = self.factory.createVBox(self.dialog)
frame = self.factory.createFrame(mainvbox,"Test frame")
HBox = self.factory.createHBox(frame)
self.aboutbutton = self.factory.createPushButton(HBox,"&About")
self.closebutton = self.factory.createPushButton(self.factory.createRight(HBox), "&Close")
|
async def open(self): pass
|
def setup_dependent_build_environment(self, env, dependent_spec):
"""Location of the OpenFOAM project directory.
This is identical to the WM_PROJECT_DIR value, but we avoid that
variable since it would mask the normal OpenFOAM cleanup of
previous versions.
"""
env.set('FOAM_PROJECT_DIR', self.projectdir)
|
async def open(self): pass
|
def ask_YesOrNo(self, info):
yui.YUI.widgetFactory
mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory("mga"))
dlg = mgafactory.createDialogBox(yui.YMGAMessageBox.B_TWO)
dlg.setTitle(info.title)
dlg.setText(info.text, info.richtext)
dlg.setButtonLabel("Yes", yui.YMGAMessageBox.B_ONE)
dlg.setButtonLabel("No", yui.YMGAMessageBox.B_TWO)
dlg.setMinSize(50, 5);
return dlg.show() == yui.YMGAMessageBox.B_ONE
|
async def open(self): pass
|
def setup_dependent_run_environment(self, env, dependent_spec):
"""Location of the OpenFOAM project directory.
This is identical to the WM_PROJECT_DIR value, but we avoid that
variable since it would mask the normal OpenFOAM cleanup of
previous versions.
"""
env.set('FOAM_PROJECT_DIR', self.projectdir)
|
async def open(self): pass
|
def aboutDialog(self):
yui.YUI.widgetFactory;
mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory("mga"))
dlg = mgafactory.createAboutDialog("About dialog title example", "1.0.0", "GPLv3",
"Angelo Naselli", "This beautiful test example shows how it is easy to play with libyui bindings", "")
dlg.show();
|
async def open(self): pass
|
def projectdir(self):
"""Absolute location of project directory: WM_PROJECT_DIR/"""
return self.prefix # <- install directly under prefix
|
async def open(self): pass
|
def handleevent(self):
"""
Event-handler for the 'widgets' demo
"""
while True:
event = self.dialog.waitForEvent()
if event.eventType() == yui.YEvent.CancelEvent:
self.dialog.destroy()
break
if event.widget() == self.closebutton:
info = Info("Quit confirmation", 1, "Are you sure you want to quit?")
if self.ask_YesOrNo(info):
self.dialog.destroy()
break
if event.widget() == self.aboutbutton:
self.aboutDialog()
|
async def open(self): pass
|
def foam_arch(self):
if not self._foam_arch:
self._foam_arch = OpenfoamOrgArch(self.spec, **self.config)
return self._foam_arch
|
async def open(self): pass
|
def archbin(self):
"""Relative location of architecture-specific executables"""
return join_path('platforms', self.foam_arch, 'bin')
|
async def open(self): pass
|
def archlib(self):
"""Relative location of architecture-specific libraries"""
return join_path('platforms', self.foam_arch, 'lib')
|
async def open(self): pass
|
def rename_source(self):
"""This is fairly horrible.
The github tarfiles have weird names that do not correspond to the
canonical name. We need to rename these, but leave a symlink for
spack to work with.
"""
# Note that this particular OpenFOAM requires absolute directories
# to build correctly!
parent = os.path.dirname(self.stage.source_path)
original = os.path.basename(self.stage.source_path)
target = 'OpenFOAM-{0}'.format(self.version)
# Could also grep through etc/bashrc for WM_PROJECT_VERSION
with working_dir(parent):
if original != target and not os.path.lexists(target):
os.rename(original, target)
os.symlink(target, original)
tty.info('renamed {0} -> {1}'.format(original, target))
|
async def open(self): pass
|
def patch(self):
"""Adjust OpenFOAM build for spack.
Where needed, apply filter as an alternative to normal patching."""
self.rename_source()
add_extra_files(self, self.common, self.assets)
# Avoid WM_PROJECT_INST_DIR for ThirdParty, site or jobControl.
# Use openfoam-site.patch to handle jobControl, site.
#
# Filtering: bashrc,cshrc (using a patch is less flexible)
edits = {
'WM_THIRD_PARTY_DIR':
r'$WM_PROJECT_DIR/ThirdParty #SPACK: No separate third-party',
'WM_VERSION': str(self.version), # consistency
'FOAMY_HEX_MESH': '', # This is horrible (unset variable?)
}
rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc
edits,
posix=join_path('etc', 'bashrc'),
cshell=join_path('etc', 'cshrc'))
|
async def open(self): pass
|
def configure(self, spec, prefix):
"""Make adjustments to the OpenFOAM configuration files in their various
locations: etc/bashrc, etc/config.sh/FEATURE and customizations that
don't properly fit get placed in the etc/prefs.sh file (similiarly for
csh).
"""
# Filtering bashrc, cshrc
edits = {}
edits.update(self.foam_arch.foam_dict())
rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc
edits,
posix=join_path('etc', 'bashrc'),
cshell=join_path('etc', 'cshrc'))
# MPI content, with absolute paths
user_mpi = mplib_content(spec)
# Content for etc/prefs.{csh,sh}
self.etc_prefs = {
r'MPI_ROOT': spec['mpi'].prefix, # Absolute
r'MPI_ARCH_FLAGS': '"%s"' % user_mpi['FLAGS'],
r'MPI_ARCH_INC': '"%s"' % user_mpi['PINC'],
r'MPI_ARCH_LIBS': '"%s"' % user_mpi['PLIBS'],
}
# Content for etc/config.{csh,sh}/ files
self.etc_config = {
'CGAL': {},
'scotch': {},
'metis': {},
'paraview': [],
'gperftools': [], # Currently unused
}
if True:
self.etc_config['scotch'] = {
'SCOTCH_ARCH_PATH': spec['scotch'].prefix,
# For src/parallel/decompose/Allwmake
'SCOTCH_VERSION': 'scotch-{0}'.format(spec['scotch'].version),
}
if '+metis' in spec:
self.etc_config['metis'] = {
'METIS_ARCH_PATH': spec['metis'].prefix,
}
# Write prefs files according to the configuration.
# Only need prefs.sh for building, but install both for end-users
if self.etc_prefs:
write_environ(
self.etc_prefs,
posix=join_path('etc', 'prefs.sh'),
cshell=join_path('etc', 'prefs.csh'))
# Adjust components to use SPACK variants
for component, subdict in self.etc_config.items():
# Versions up to 3.0 used an etc/config/component.sh naming
# convention instead of etc/config.sh/component
if spec.satisfies('@:3.0'):
write_environ(
subdict,
posix=join_path('etc', 'config', component) + '.sh',
cshell=join_path('etc', 'config', component) + '.csh')
else:
write_environ(
subdict,
posix=join_path('etc', 'config.sh', component),
cshell=join_path('etc', 'config.csh', component))
|
async def open(self): pass
|
def build(self, spec, prefix):
"""Build using the OpenFOAM Allwmake script, with a wrapper to source
its environment first.
Only build if the compiler is known to be supported.
"""
self.foam_arch.has_rule(self.stage.source_path)
self.foam_arch.create_rules(self.stage.source_path, self)
args = []
if self.parallel: # Build in parallel? - pass via the environment
os.environ['WM_NCOMPPROCS'] = str(make_jobs)
builder = Executable(self.build_script)
builder(*args)
|
async def open(self): pass
|
def install(self, spec, prefix):
"""Install under the projectdir"""
mkdirp(self.projectdir)
projdir = os.path.basename(self.projectdir)
# Filtering: bashrc, cshrc
edits = {
'WM_PROJECT_INST_DIR': os.path.dirname(self.projectdir),
'WM_PROJECT_DIR': join_path('$WM_PROJECT_INST_DIR', projdir),
}
# All top-level files, except spack build info and possibly Allwmake
if '+source' in spec:
ignored = re.compile(r'^spack-.*')
else:
ignored = re.compile(r'^(Allwmake|spack-).*')
files = [
f for f in glob.glob("*")
if os.path.isfile(f) and not ignored.search(f)
]
for f in files:
install(f, self.projectdir)
# Having wmake and ~source is actually somewhat pointless...
# Install 'etc' before 'bin' (for symlinks)
# META-INFO for 1812 and later (or backported)
dirs = ['META-INFO', 'etc', 'bin', 'wmake']
if '+source' in spec:
dirs.extend(['applications', 'src', 'tutorials'])
for d in dirs:
if os.path.isdir(d):
install_tree(
d,
join_path(self.projectdir, d),
symlinks=True)
dirs = ['platforms']
if '+source' in spec:
dirs.extend(['doc'])
# Install platforms (and doc) skipping intermediate targets
relative_ignore_paths = ['src', 'applications', 'html', 'Guides']
ignore = lambda p: p in relative_ignore_paths
for d in dirs:
install_tree(
d,
join_path(self.projectdir, d),
ignore=ignore,
symlinks=True)
etc_dir = join_path(self.projectdir, 'etc')
rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc
edits,
posix=join_path(etc_dir, 'bashrc'),
cshell=join_path(etc_dir, 'cshrc'))
self.install_links()
|
async def open(self): pass
|
def install_links(self):
"""Add symlinks into bin/, lib/ (eg, for other applications)"""
# Make build log visible - it contains OpenFOAM-specific information
with working_dir(self.projectdir):
os.symlink(
join_path(os.path.relpath(self.install_log_path)),
join_path('log.' + str(self.foam_arch)))
if not self.config['link']:
return
# ln -s platforms/linux64GccXXX/lib lib
with working_dir(self.projectdir):
if os.path.isdir(self.archlib):
os.symlink(self.archlib, 'lib')
# (cd bin && ln -s ../platforms/linux64GccXXX/bin/* .)
with working_dir(join_path(self.projectdir, 'bin')):
for f in [
f for f in glob.glob(join_path('..', self.archbin, "*"))
if os.path.isfile(f)
]:
os.symlink(f, os.path.basename(f))
|
async def open(self): pass
|
def linear_search(lst,size,value):
i = 0
while i < size:
if lst[i] == value:
return i
i = i + 1
return -1
|
async def open(self): pass
|
def main():
lst = [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]
size = len(lst)
original_list = ""
value = int(input("\nInput a value to search for: "))
print("\nOriginal Array: ")
for i in lst:
original_list += str(i) + " "
print(original_list)
print("\nLinear Search Big O Notation:\n--> Best Case: O(1)\n--> Average Case: O(n)\n--> Worst Case: O(n)\n")
index = linear_search(lst,size,value)
if index == -1:
print(str(value) + " was not found in that array\n")
else:
print(str(value) + " was found at index " + str(index))
|
async def open(self): pass
|
def setUp(self):
self.credentials = {
'username': 'testuser',
'password': 'test1234',
'email': '[email protected]'}
# Create a test Group
my_group, created = Group.objects.get_or_create(name='test_group')
# Add user to test Group
User.objects.get(pk=1).groups.add(my_group)
|
async def open(self): pass
|
def __init__(self, *args, **kwargs):
BaseConverter.__init__(self, *args, **kwargs)
self.type_ = "string"
self.regex = '[^(/;)]+'
|
async def open(self): pass
|
def test_user_login(self):
c = Client()
# User points the browser to the landing page
res = c.post('/', follow=True)
# the user is not logged in
self.assertFalse(res.context['user'].is_authenticated)
# and is redirected to the login page
self.assertRedirects(res, '/login/')
# The login page is being rendered by the correct template
self.assertTemplateUsed(res, 'registration/login.html')
# asks the user to login using a set of valid credentials
res = c.post('/login/', data=self.credentials, follow=True)
# The system acknowledges him
self.assertTrue(res.context['user'].is_authenticated)
# and moves him at the dashboard
self.assertTemplateUsed(res, 'app/dashboard.html')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.