file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
base_handler.py
#!/usr/bin/env python3 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright 2017-2019 - Edoardo Morassutto <edoardo.morassutto@gmail.com> # Copyright 2017 - Luca Versari <veluca93@gmail.com> # Copyright 2018 - William Di Luigi <williamdiluigi@gmail.com> import json from datetime import datetime from werkzeug.exceptions import HTTPException, BadRequest from werkzeug.wrappers import Response from ..handler_params import HandlerParams from ..config import Config from ..database import Database from ..logger import Logger class BaseHandler: @staticmethod def raise_exc(cls, code, message): """ Raise an HTTPException with a code and a message sent in a json like { "code": code "message": message } :param cls: HTTPException of the error, for example NotFound, BadRequest, NotAuthorized :param code: A brief message for the exception, like MISSING_PARAMETER :param message: A longer description of the error :return: Nothing, raise the provided exception with the correct response """ response = Response() response.mimetype = "application/json" response.status_code = cls.code response.data = json.dumps({ "code": code, "message": message }) Logger.warning(cls.__name__.upper(), code + ": " + message) raise cls(response=response) def handle(self, endpoint, route_args, request): """ Handle a request in the derived handler. The request is routed to the correct method using *endpoint* :param endpoint: A string with the name of the class method to call with (route_args, request) as parameters, this method should return a Response or call self.raise_exc. *NOTE*: the method MUST be implemented in the derived class :param route_args: The route parameters, the parameters extracted from the matching route in the URL :param request: The Request object, request.args contains the query parameters of the request :return: Return a Response if the request is successful, an HTTPException if an error occurred """ try: data = BaseHandler._call(self.__getattribute__(endpoint), route_args, request) response = Response() if data is not None: response.code = 200 response.mimetype = "application/json" response.data = json.dumps(data) else: response.code = 204 return response except HTTPException as e: return e def parse_body(self, request): """ Parse the body part of the request in JSON :param request: The request to be parsed :return: A dict with the content of the body """ return request.form @staticmethod def get_end_time(user_extra_time): """ Compute the end time for a user :param user_extra_time: Extra time specific for the user in seconds :return: The timestamp at which the contest will be finished for this user """ start = Database.get_meta("start_time", type=int) if start is None: return None contest_duration = Database.get_meta("contest_duration", type=int, default=0) contest_extra_time = Database.get_meta("extra_time", type=int, default=0) if user_extra_time is None: user_extra_time = 0 return start + contest_duration + contest_extra_time + user_extra_time @staticmethod def get_window_end_time(user_extra_time, start_delay): """ Compute the end time for a window started after `start_delay` and with `extra_time` delay for the user. Note that this time may exceed the contest end time, additional checks are required. :param user_extra_time: Extra time specific for the user in seconds :param start_delay: The time (in seconds) after the start of the contest of when the window started :return: The timestamp at which the window ends. If the contest has no window None is returned. """ if start_delay is None: return None start = Database.get_meta("start_time", type=int) if start is None: return None window_duration = Database.get_meta("window_duration", None, type=int) if window_duration is None: return None if user_extra_time is None: user_extra_time = 0 return start + user_extra_time + start_delay + window_duration @staticmethod def format_dates(dct, fields=["date"]): """ Given a dict, format all the *fields* fields from int to iso format. The original dict is modified :param dct: dict to format :param fields: list of the names of the fields to format :return: The modified dict """ for k, v in dct.items(): if isinstance(v, dict): dct[k] = BaseHandler.format_dates(v, fields) elif isinstance(v, list): for item in v: BaseHandler.format_dates(item, fields) elif k in fields and v is not None: dct[k] = datetime.fromtimestamp(v).isoformat() return dct @staticmethod def _call(method, route_args, request): """ This function is MAGIC! It takes a method, reads it's parameters and automagically fetch from the request the values. Type-annotation is also supported for a simple type validation. The values are fetched, in order, from: - route_args - request.form - general_attrs - default values If a parameter is required but not sent a BadRequest (MISSING_PARAMETERS) error is thrown, if a parameter cannot be converted to the annotated type a BadRequest (FORMAT_ERROR) is thrown. :param method: Method to be called :param route_args: Arguments of the route :param request: Request object :return: The return value of method """ kwargs = {} params = HandlerParams.get_handler_params(method) general_attrs = { '_request': request, '_route_args': route_args, '_file': { "content": BaseHandler._get_file_content(request), "name": BaseHandler._get_file_name(request) }, '_ip': BaseHandler.get_ip(request) } missing_parameters = [] for name, data in params.items(): if name in route_args and name[0] != "_": kwargs[name] = route_args[name] elif name in request.form and name[0] != "_": kwargs[name] = request.form[name] elif name in general_attrs: kwargs[name] = general_attrs[name] elif name == "file" and general_attrs["_file"]["name"] is not None: kwargs[name] = general_attrs["_file"] elif data["required"]: missing_parameters.append(name) if len(missing_parameters) > 0: BaseHandler.raise_exc(BadRequest, "MISSING_PARAMETERS", "The missing parameters are: " + ", ".join(missing_parameters)) for key, value in kwargs.items(): type = params[key]["type"] if type is None: continue try: kwargs[key] = type(value) except ValueError: BaseHandler.raise_exc(BadRequest, "FORMAT_ERROR", "The parameter %s cannot be converted to %s" % (key, type.__name__)) Logger.debug( "HTTP", "Received request from %s for endpoint %s%s" % ( general_attrs['_ip'],
"=".join((kv[0], str(kv[1]))) for kv in kwargs.items() if not kv[0].startswith("_") and not kv[0] == "file" ) if len(kwargs) > 0 else "" ) ) return method(**kwargs) @staticmethod def _get_file_name(request): """ Extract the name of the file from the multipart body :param request: The Request object :return: The filename in the request """ if "file" not in request.files: return None return request.files["file"].filename @staticmethod def _get_file_content(request): """ Extract the content of the file from the multipart of the body :param request: The Request object :return: A *bytes* with the content of the file """ if "file" not in request.files: return None return request.files["file"].stream.read() @staticmethod def get_ip(request): """ Return the real IP of the client :param request: The Request object :return: A string with the IP of the client """ num_proxies = Config.num_proxies if num_proxies == 0 or len(request.access_route) < num_proxies: return request.remote_addr return request.access_route[-num_proxies]
method.__name__, ", with parameters " + ", ".join(
random_line_split
base_handler.py
#!/usr/bin/env python3 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright 2017-2019 - Edoardo Morassutto <edoardo.morassutto@gmail.com> # Copyright 2017 - Luca Versari <veluca93@gmail.com> # Copyright 2018 - William Di Luigi <williamdiluigi@gmail.com> import json from datetime import datetime from werkzeug.exceptions import HTTPException, BadRequest from werkzeug.wrappers import Response from ..handler_params import HandlerParams from ..config import Config from ..database import Database from ..logger import Logger class BaseHandler: @staticmethod def raise_exc(cls, code, message): """ Raise an HTTPException with a code and a message sent in a json like { "code": code "message": message } :param cls: HTTPException of the error, for example NotFound, BadRequest, NotAuthorized :param code: A brief message for the exception, like MISSING_PARAMETER :param message: A longer description of the error :return: Nothing, raise the provided exception with the correct response """ response = Response() response.mimetype = "application/json" response.status_code = cls.code response.data = json.dumps({ "code": code, "message": message }) Logger.warning(cls.__name__.upper(), code + ": " + message) raise cls(response=response) def handle(self, endpoint, route_args, request): """ Handle a request in the derived handler. The request is routed to the correct method using *endpoint* :param endpoint: A string with the name of the class method to call with (route_args, request) as parameters, this method should return a Response or call self.raise_exc. *NOTE*: the method MUST be implemented in the derived class :param route_args: The route parameters, the parameters extracted from the matching route in the URL :param request: The Request object, request.args contains the query parameters of the request :return: Return a Response if the request is successful, an HTTPException if an error occurred """ try: data = BaseHandler._call(self.__getattribute__(endpoint), route_args, request) response = Response() if data is not None: response.code = 200 response.mimetype = "application/json" response.data = json.dumps(data) else: response.code = 204 return response except HTTPException as e: return e def parse_body(self, request): """ Parse the body part of the request in JSON :param request: The request to be parsed :return: A dict with the content of the body """ return request.form @staticmethod def get_end_time(user_extra_time): """ Compute the end time for a user :param user_extra_time: Extra time specific for the user in seconds :return: The timestamp at which the contest will be finished for this user """ start = Database.get_meta("start_time", type=int) if start is None: return None contest_duration = Database.get_meta("contest_duration", type=int, default=0) contest_extra_time = Database.get_meta("extra_time", type=int, default=0) if user_extra_time is None: user_extra_time = 0 return start + contest_duration + contest_extra_time + user_extra_time @staticmethod def get_window_end_time(user_extra_time, start_delay):
@staticmethod def format_dates(dct, fields=["date"]): """ Given a dict, format all the *fields* fields from int to iso format. The original dict is modified :param dct: dict to format :param fields: list of the names of the fields to format :return: The modified dict """ for k, v in dct.items(): if isinstance(v, dict): dct[k] = BaseHandler.format_dates(v, fields) elif isinstance(v, list): for item in v: BaseHandler.format_dates(item, fields) elif k in fields and v is not None: dct[k] = datetime.fromtimestamp(v).isoformat() return dct @staticmethod def _call(method, route_args, request): """ This function is MAGIC! It takes a method, reads it's parameters and automagically fetch from the request the values. Type-annotation is also supported for a simple type validation. The values are fetched, in order, from: - route_args - request.form - general_attrs - default values If a parameter is required but not sent a BadRequest (MISSING_PARAMETERS) error is thrown, if a parameter cannot be converted to the annotated type a BadRequest (FORMAT_ERROR) is thrown. :param method: Method to be called :param route_args: Arguments of the route :param request: Request object :return: The return value of method """ kwargs = {} params = HandlerParams.get_handler_params(method) general_attrs = { '_request': request, '_route_args': route_args, '_file': { "content": BaseHandler._get_file_content(request), "name": BaseHandler._get_file_name(request) }, '_ip': BaseHandler.get_ip(request) } missing_parameters = [] for name, data in params.items(): if name in route_args and name[0] != "_": kwargs[name] = route_args[name] elif name in request.form and name[0] != "_": kwargs[name] = request.form[name] elif name in general_attrs: kwargs[name] = general_attrs[name] elif name == "file" and general_attrs["_file"]["name"] is not None: kwargs[name] = general_attrs["_file"] elif data["required"]: missing_parameters.append(name) if len(missing_parameters) > 0: BaseHandler.raise_exc(BadRequest, "MISSING_PARAMETERS", "The missing parameters are: " + ", ".join(missing_parameters)) for key, value in kwargs.items(): type = params[key]["type"] if type is None: continue try: kwargs[key] = type(value) except ValueError: BaseHandler.raise_exc(BadRequest, "FORMAT_ERROR", "The parameter %s cannot be converted to %s" % (key, type.__name__)) Logger.debug( "HTTP", "Received request from %s for endpoint %s%s" % ( general_attrs['_ip'], method.__name__, ", with parameters " + ", ".join( "=".join((kv[0], str(kv[1]))) for kv in kwargs.items() if not kv[0].startswith("_") and not kv[0] == "file" ) if len(kwargs) > 0 else "" ) ) return method(**kwargs) @staticmethod def _get_file_name(request): """ Extract the name of the file from the multipart body :param request: The Request object :return: The filename in the request """ if "file" not in request.files: return None return request.files["file"].filename @staticmethod def _get_file_content(request): """ Extract the content of the file from the multipart of the body :param request: The Request object :return: A *bytes* with the content of the file """ if "file" not in request.files: return None return request.files["file"].stream.read() @staticmethod def get_ip(request): """ Return the real IP of the client :param request: The Request object :return: A string with the IP of the client """ num_proxies = Config.num_proxies if num_proxies == 0 or len(request.access_route) < num_proxies: return request.remote_addr return request.access_route[-num_proxies]
""" Compute the end time for a window started after `start_delay` and with `extra_time` delay for the user. Note that this time may exceed the contest end time, additional checks are required. :param user_extra_time: Extra time specific for the user in seconds :param start_delay: The time (in seconds) after the start of the contest of when the window started :return: The timestamp at which the window ends. If the contest has no window None is returned. """ if start_delay is None: return None start = Database.get_meta("start_time", type=int) if start is None: return None window_duration = Database.get_meta("window_duration", None, type=int) if window_duration is None: return None if user_extra_time is None: user_extra_time = 0 return start + user_extra_time + start_delay + window_duration
identifier_body
base_handler.py
#!/usr/bin/env python3 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright 2017-2019 - Edoardo Morassutto <edoardo.morassutto@gmail.com> # Copyright 2017 - Luca Versari <veluca93@gmail.com> # Copyright 2018 - William Di Luigi <williamdiluigi@gmail.com> import json from datetime import datetime from werkzeug.exceptions import HTTPException, BadRequest from werkzeug.wrappers import Response from ..handler_params import HandlerParams from ..config import Config from ..database import Database from ..logger import Logger class BaseHandler: @staticmethod def raise_exc(cls, code, message): """ Raise an HTTPException with a code and a message sent in a json like { "code": code "message": message } :param cls: HTTPException of the error, for example NotFound, BadRequest, NotAuthorized :param code: A brief message for the exception, like MISSING_PARAMETER :param message: A longer description of the error :return: Nothing, raise the provided exception with the correct response """ response = Response() response.mimetype = "application/json" response.status_code = cls.code response.data = json.dumps({ "code": code, "message": message }) Logger.warning(cls.__name__.upper(), code + ": " + message) raise cls(response=response) def handle(self, endpoint, route_args, request): """ Handle a request in the derived handler. The request is routed to the correct method using *endpoint* :param endpoint: A string with the name of the class method to call with (route_args, request) as parameters, this method should return a Response or call self.raise_exc. *NOTE*: the method MUST be implemented in the derived class :param route_args: The route parameters, the parameters extracted from the matching route in the URL :param request: The Request object, request.args contains the query parameters of the request :return: Return a Response if the request is successful, an HTTPException if an error occurred """ try: data = BaseHandler._call(self.__getattribute__(endpoint), route_args, request) response = Response() if data is not None: response.code = 200 response.mimetype = "application/json" response.data = json.dumps(data) else: response.code = 204 return response except HTTPException as e: return e def parse_body(self, request): """ Parse the body part of the request in JSON :param request: The request to be parsed :return: A dict with the content of the body """ return request.form @staticmethod def get_end_time(user_extra_time): """ Compute the end time for a user :param user_extra_time: Extra time specific for the user in seconds :return: The timestamp at which the contest will be finished for this user """ start = Database.get_meta("start_time", type=int) if start is None: return None contest_duration = Database.get_meta("contest_duration", type=int, default=0) contest_extra_time = Database.get_meta("extra_time", type=int, default=0) if user_extra_time is None: user_extra_time = 0 return start + contest_duration + contest_extra_time + user_extra_time @staticmethod def get_window_end_time(user_extra_time, start_delay): """ Compute the end time for a window started after `start_delay` and with `extra_time` delay for the user. Note that this time may exceed the contest end time, additional checks are required. :param user_extra_time: Extra time specific for the user in seconds :param start_delay: The time (in seconds) after the start of the contest of when the window started :return: The timestamp at which the window ends. If the contest has no window None is returned. """ if start_delay is None: return None start = Database.get_meta("start_time", type=int) if start is None: return None window_duration = Database.get_meta("window_duration", None, type=int) if window_duration is None: return None if user_extra_time is None: user_extra_time = 0 return start + user_extra_time + start_delay + window_duration @staticmethod def format_dates(dct, fields=["date"]): """ Given a dict, format all the *fields* fields from int to iso format. The original dict is modified :param dct: dict to format :param fields: list of the names of the fields to format :return: The modified dict """ for k, v in dct.items(): if isinstance(v, dict): dct[k] = BaseHandler.format_dates(v, fields) elif isinstance(v, list): for item in v: BaseHandler.format_dates(item, fields) elif k in fields and v is not None: dct[k] = datetime.fromtimestamp(v).isoformat() return dct @staticmethod def _call(method, route_args, request): """ This function is MAGIC! It takes a method, reads it's parameters and automagically fetch from the request the values. Type-annotation is also supported for a simple type validation. The values are fetched, in order, from: - route_args - request.form - general_attrs - default values If a parameter is required but not sent a BadRequest (MISSING_PARAMETERS) error is thrown, if a parameter cannot be converted to the annotated type a BadRequest (FORMAT_ERROR) is thrown. :param method: Method to be called :param route_args: Arguments of the route :param request: Request object :return: The return value of method """ kwargs = {} params = HandlerParams.get_handler_params(method) general_attrs = { '_request': request, '_route_args': route_args, '_file': { "content": BaseHandler._get_file_content(request), "name": BaseHandler._get_file_name(request) }, '_ip': BaseHandler.get_ip(request) } missing_parameters = [] for name, data in params.items(): if name in route_args and name[0] != "_": kwargs[name] = route_args[name] elif name in request.form and name[0] != "_": kwargs[name] = request.form[name] elif name in general_attrs: kwargs[name] = general_attrs[name] elif name == "file" and general_attrs["_file"]["name"] is not None: kwargs[name] = general_attrs["_file"] elif data["required"]: missing_parameters.append(name) if len(missing_parameters) > 0: BaseHandler.raise_exc(BadRequest, "MISSING_PARAMETERS", "The missing parameters are: " + ", ".join(missing_parameters)) for key, value in kwargs.items(): type = params[key]["type"] if type is None: continue try: kwargs[key] = type(value) except ValueError: BaseHandler.raise_exc(BadRequest, "FORMAT_ERROR", "The parameter %s cannot be converted to %s" % (key, type.__name__)) Logger.debug( "HTTP", "Received request from %s for endpoint %s%s" % ( general_attrs['_ip'], method.__name__, ", with parameters " + ", ".join( "=".join((kv[0], str(kv[1]))) for kv in kwargs.items() if not kv[0].startswith("_") and not kv[0] == "file" ) if len(kwargs) > 0 else "" ) ) return method(**kwargs) @staticmethod def
(request): """ Extract the name of the file from the multipart body :param request: The Request object :return: The filename in the request """ if "file" not in request.files: return None return request.files["file"].filename @staticmethod def _get_file_content(request): """ Extract the content of the file from the multipart of the body :param request: The Request object :return: A *bytes* with the content of the file """ if "file" not in request.files: return None return request.files["file"].stream.read() @staticmethod def get_ip(request): """ Return the real IP of the client :param request: The Request object :return: A string with the IP of the client """ num_proxies = Config.num_proxies if num_proxies == 0 or len(request.access_route) < num_proxies: return request.remote_addr return request.access_route[-num_proxies]
_get_file_name
identifier_name
i2c.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use erased_serde::Serialize; use std::any::Any; use structopt::StructOpt; use opentitanlib::app::command::CommandDispatch; use opentitanlib::app::TransportWrapper; use opentitanlib::io::i2c::{I2cParams, Transfer}; use opentitanlib::transport::Capability; /// Read plain data bytes from a I2C device. #[derive(Debug, StructOpt)] pub struct I2cRawRead { #[structopt(short = "n", long, help = "Number of bytes to read.")] length: usize, } #[derive(Debug, serde::Serialize)] pub struct I2cRawReadResponse { hexdata: String, } impl CommandDispatch for I2cRawRead { fn run( &self, context: &dyn Any, transport: &TransportWrapper, ) -> Result<Option<Box<dyn Serialize>>> { transport.capabilities()?.request(Capability::I2C).ok()?; let context = context.downcast_ref::<I2cCommand>().unwrap(); let i2c_bus = context.params.create(transport)?; let mut v = vec![0u8; self.length]; i2c_bus.run_transaction(context.addr, &mut [Transfer::Read(&mut v)])?; Ok(Some(Box::new(I2cRawReadResponse { hexdata: hex::encode(v), }))) } } /// Write plain data bytes to a I2C device. #[derive(Debug, StructOpt)] pub struct I2cRawWrite { #[structopt(short, long, help = "Hex data bytes to write.")] hexdata: String, } impl CommandDispatch for I2cRawWrite { fn run( &self, context: &dyn Any, transport: &TransportWrapper, ) -> Result<Option<Box<dyn Serialize>>> { transport.capabilities()?.request(Capability::I2C).ok()?; let context = context.downcast_ref::<I2cCommand>().unwrap(); let i2c_bus = context.params.create(transport)?; i2c_bus.run_transaction( context.addr, &mut [Transfer::Write(&hex::decode(&self.hexdata)?)], )?; Ok(None) } } /// Commands for interacting with a generic I2C bus. #[derive(Debug, StructOpt, CommandDispatch)] pub enum InternalI2cCommand { RawRead(I2cRawRead), RawWrite(I2cRawWrite), } #[derive(Debug, StructOpt)] pub struct
{ #[structopt(flatten)] params: I2cParams, #[structopt(short, long, help = "7-bit address of I2C device (0..0x7F).")] addr: u8, #[structopt(subcommand)] command: InternalI2cCommand, } impl CommandDispatch for I2cCommand { fn run( &self, _context: &dyn Any, transport: &TransportWrapper, ) -> Result<Option<Box<dyn Serialize>>> { // None of the I2C commands care about the prior context, but they do // care about the `bus` parameter in the current node. self.command.run(self, transport) } }
I2cCommand
identifier_name
i2c.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use erased_serde::Serialize; use std::any::Any; use structopt::StructOpt; use opentitanlib::app::command::CommandDispatch; use opentitanlib::app::TransportWrapper; use opentitanlib::io::i2c::{I2cParams, Transfer}; use opentitanlib::transport::Capability; /// Read plain data bytes from a I2C device. #[derive(Debug, StructOpt)] pub struct I2cRawRead { #[structopt(short = "n", long, help = "Number of bytes to read.")] length: usize, } #[derive(Debug, serde::Serialize)] pub struct I2cRawReadResponse { hexdata: String, } impl CommandDispatch for I2cRawRead { fn run( &self, context: &dyn Any, transport: &TransportWrapper, ) -> Result<Option<Box<dyn Serialize>>> { transport.capabilities()?.request(Capability::I2C).ok()?; let context = context.downcast_ref::<I2cCommand>().unwrap(); let i2c_bus = context.params.create(transport)?; let mut v = vec![0u8; self.length]; i2c_bus.run_transaction(context.addr, &mut [Transfer::Read(&mut v)])?; Ok(Some(Box::new(I2cRawReadResponse { hexdata: hex::encode(v), }))) } } /// Write plain data bytes to a I2C device. #[derive(Debug, StructOpt)] pub struct I2cRawWrite { #[structopt(short, long, help = "Hex data bytes to write.")] hexdata: String, } impl CommandDispatch for I2cRawWrite { fn run( &self,
transport: &TransportWrapper, ) -> Result<Option<Box<dyn Serialize>>> { transport.capabilities()?.request(Capability::I2C).ok()?; let context = context.downcast_ref::<I2cCommand>().unwrap(); let i2c_bus = context.params.create(transport)?; i2c_bus.run_transaction( context.addr, &mut [Transfer::Write(&hex::decode(&self.hexdata)?)], )?; Ok(None) } } /// Commands for interacting with a generic I2C bus. #[derive(Debug, StructOpt, CommandDispatch)] pub enum InternalI2cCommand { RawRead(I2cRawRead), RawWrite(I2cRawWrite), } #[derive(Debug, StructOpt)] pub struct I2cCommand { #[structopt(flatten)] params: I2cParams, #[structopt(short, long, help = "7-bit address of I2C device (0..0x7F).")] addr: u8, #[structopt(subcommand)] command: InternalI2cCommand, } impl CommandDispatch for I2cCommand { fn run( &self, _context: &dyn Any, transport: &TransportWrapper, ) -> Result<Option<Box<dyn Serialize>>> { // None of the I2C commands care about the prior context, but they do // care about the `bus` parameter in the current node. self.command.run(self, transport) } }
context: &dyn Any,
random_line_split
i2c.rs
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 use anyhow::Result; use erased_serde::Serialize; use std::any::Any; use structopt::StructOpt; use opentitanlib::app::command::CommandDispatch; use opentitanlib::app::TransportWrapper; use opentitanlib::io::i2c::{I2cParams, Transfer}; use opentitanlib::transport::Capability; /// Read plain data bytes from a I2C device. #[derive(Debug, StructOpt)] pub struct I2cRawRead { #[structopt(short = "n", long, help = "Number of bytes to read.")] length: usize, } #[derive(Debug, serde::Serialize)] pub struct I2cRawReadResponse { hexdata: String, } impl CommandDispatch for I2cRawRead { fn run( &self, context: &dyn Any, transport: &TransportWrapper, ) -> Result<Option<Box<dyn Serialize>>>
} /// Write plain data bytes to a I2C device. #[derive(Debug, StructOpt)] pub struct I2cRawWrite { #[structopt(short, long, help = "Hex data bytes to write.")] hexdata: String, } impl CommandDispatch for I2cRawWrite { fn run( &self, context: &dyn Any, transport: &TransportWrapper, ) -> Result<Option<Box<dyn Serialize>>> { transport.capabilities()?.request(Capability::I2C).ok()?; let context = context.downcast_ref::<I2cCommand>().unwrap(); let i2c_bus = context.params.create(transport)?; i2c_bus.run_transaction( context.addr, &mut [Transfer::Write(&hex::decode(&self.hexdata)?)], )?; Ok(None) } } /// Commands for interacting with a generic I2C bus. #[derive(Debug, StructOpt, CommandDispatch)] pub enum InternalI2cCommand { RawRead(I2cRawRead), RawWrite(I2cRawWrite), } #[derive(Debug, StructOpt)] pub struct I2cCommand { #[structopt(flatten)] params: I2cParams, #[structopt(short, long, help = "7-bit address of I2C device (0..0x7F).")] addr: u8, #[structopt(subcommand)] command: InternalI2cCommand, } impl CommandDispatch for I2cCommand { fn run( &self, _context: &dyn Any, transport: &TransportWrapper, ) -> Result<Option<Box<dyn Serialize>>> { // None of the I2C commands care about the prior context, but they do // care about the `bus` parameter in the current node. self.command.run(self, transport) } }
{ transport.capabilities()?.request(Capability::I2C).ok()?; let context = context.downcast_ref::<I2cCommand>().unwrap(); let i2c_bus = context.params.create(transport)?; let mut v = vec![0u8; self.length]; i2c_bus.run_transaction(context.addr, &mut [Transfer::Read(&mut v)])?; Ok(Some(Box::new(I2cRawReadResponse { hexdata: hex::encode(v), }))) }
identifier_body
test_round.py
import numpy as np import pytest import pandas as pd
class TestSeriesRound: def test_round(self, datetime_series): datetime_series.index.name = "index_name" result = datetime_series.round(2) expected = Series( np.round(datetime_series.values, 2), index=datetime_series.index, name="ts" ) tm.assert_series_equal(result, expected) assert result.name == datetime_series.name def test_round_numpy(self, any_float_dtype): # See GH#12600 ser = Series([1.53, 1.36, 0.06], dtype=any_float_dtype) out = np.round(ser, decimals=0) expected = Series([2.0, 1.0, 0.0], dtype=any_float_dtype) tm.assert_series_equal(out, expected) msg = "the 'out' parameter is not supported" with pytest.raises(ValueError, match=msg): np.round(ser, decimals=0, out=ser) def test_round_numpy_with_nan(self, any_float_dtype): # See GH#14197 ser = Series([1.53, np.nan, 0.06], dtype=any_float_dtype) with tm.assert_produces_warning(None): result = ser.round() expected = Series([2.0, np.nan, 0.0], dtype=any_float_dtype) tm.assert_series_equal(result, expected) def test_round_builtin(self, any_float_dtype): ser = Series( [1.123, 2.123, 3.123], index=range(3), dtype=any_float_dtype, ) result = round(ser) expected_rounded0 = Series( [1.0, 2.0, 3.0], index=range(3), dtype=any_float_dtype ) tm.assert_series_equal(result, expected_rounded0) decimals = 2 expected_rounded = Series( [1.12, 2.12, 3.12], index=range(3), dtype=any_float_dtype ) result = round(ser, decimals) tm.assert_series_equal(result, expected_rounded) @pytest.mark.parametrize("method", ["round", "floor", "ceil"]) @pytest.mark.parametrize("freq", ["s", "5s", "min", "5min", "h", "5h"]) def test_round_nat(self, method, freq): # GH14940 ser = Series([pd.NaT]) expected = Series(pd.NaT) round_method = getattr(ser.dt, method) tm.assert_series_equal(round_method(freq), expected)
from pandas import Series import pandas._testing as tm
random_line_split
test_round.py
import numpy as np import pytest import pandas as pd from pandas import Series import pandas._testing as tm class TestSeriesRound: def
(self, datetime_series): datetime_series.index.name = "index_name" result = datetime_series.round(2) expected = Series( np.round(datetime_series.values, 2), index=datetime_series.index, name="ts" ) tm.assert_series_equal(result, expected) assert result.name == datetime_series.name def test_round_numpy(self, any_float_dtype): # See GH#12600 ser = Series([1.53, 1.36, 0.06], dtype=any_float_dtype) out = np.round(ser, decimals=0) expected = Series([2.0, 1.0, 0.0], dtype=any_float_dtype) tm.assert_series_equal(out, expected) msg = "the 'out' parameter is not supported" with pytest.raises(ValueError, match=msg): np.round(ser, decimals=0, out=ser) def test_round_numpy_with_nan(self, any_float_dtype): # See GH#14197 ser = Series([1.53, np.nan, 0.06], dtype=any_float_dtype) with tm.assert_produces_warning(None): result = ser.round() expected = Series([2.0, np.nan, 0.0], dtype=any_float_dtype) tm.assert_series_equal(result, expected) def test_round_builtin(self, any_float_dtype): ser = Series( [1.123, 2.123, 3.123], index=range(3), dtype=any_float_dtype, ) result = round(ser) expected_rounded0 = Series( [1.0, 2.0, 3.0], index=range(3), dtype=any_float_dtype ) tm.assert_series_equal(result, expected_rounded0) decimals = 2 expected_rounded = Series( [1.12, 2.12, 3.12], index=range(3), dtype=any_float_dtype ) result = round(ser, decimals) tm.assert_series_equal(result, expected_rounded) @pytest.mark.parametrize("method", ["round", "floor", "ceil"]) @pytest.mark.parametrize("freq", ["s", "5s", "min", "5min", "h", "5h"]) def test_round_nat(self, method, freq): # GH14940 ser = Series([pd.NaT]) expected = Series(pd.NaT) round_method = getattr(ser.dt, method) tm.assert_series_equal(round_method(freq), expected)
test_round
identifier_name
test_round.py
import numpy as np import pytest import pandas as pd from pandas import Series import pandas._testing as tm class TestSeriesRound: def test_round(self, datetime_series): datetime_series.index.name = "index_name" result = datetime_series.round(2) expected = Series( np.round(datetime_series.values, 2), index=datetime_series.index, name="ts" ) tm.assert_series_equal(result, expected) assert result.name == datetime_series.name def test_round_numpy(self, any_float_dtype): # See GH#12600 ser = Series([1.53, 1.36, 0.06], dtype=any_float_dtype) out = np.round(ser, decimals=0) expected = Series([2.0, 1.0, 0.0], dtype=any_float_dtype) tm.assert_series_equal(out, expected) msg = "the 'out' parameter is not supported" with pytest.raises(ValueError, match=msg): np.round(ser, decimals=0, out=ser) def test_round_numpy_with_nan(self, any_float_dtype): # See GH#14197 ser = Series([1.53, np.nan, 0.06], dtype=any_float_dtype) with tm.assert_produces_warning(None): result = ser.round() expected = Series([2.0, np.nan, 0.0], dtype=any_float_dtype) tm.assert_series_equal(result, expected) def test_round_builtin(self, any_float_dtype):
@pytest.mark.parametrize("method", ["round", "floor", "ceil"]) @pytest.mark.parametrize("freq", ["s", "5s", "min", "5min", "h", "5h"]) def test_round_nat(self, method, freq): # GH14940 ser = Series([pd.NaT]) expected = Series(pd.NaT) round_method = getattr(ser.dt, method) tm.assert_series_equal(round_method(freq), expected)
ser = Series( [1.123, 2.123, 3.123], index=range(3), dtype=any_float_dtype, ) result = round(ser) expected_rounded0 = Series( [1.0, 2.0, 3.0], index=range(3), dtype=any_float_dtype ) tm.assert_series_equal(result, expected_rounded0) decimals = 2 expected_rounded = Series( [1.12, 2.12, 3.12], index=range(3), dtype=any_float_dtype ) result = round(ser, decimals) tm.assert_series_equal(result, expected_rounded)
identifier_body
list_salesummary.js
var gId = '#dataGrid'; var lastIndex; $(document).ready(function(){ //列表 $(gId).datagrid({ url:getUrlOpt(), idField:'id', fitColumns:true, frozenColumns:[[ {field:'ck',checkbox:true} ]], columns:[ getTableHeadOpt(), getColumnsOpt(), getTotal() ], rownumbers:true, pagination:false, loadMsg:'数据装载中......', onClickRow:function(rowIndex){ if (lastIndex != rowIndex){ $(gId).datagrid('endEdit', lastIndex); $(gId).datagrid('beginEdit', rowIndex); } lastIndex = rowIndex; } }); }); //计算总计 function getTotal() { var opt=[ {field:'totalSalesmoney',title:'出货金额总计',hidden:true,align:'left',formatter:totalFormat}, {field:'totalCostmoney',title:'成本金额总计',hidden:true,align:'left'}, {field:'totalOrderNum',title:'出货数量总计',hidden:true,align:'left'} ]; return opt; } //格式化总计 function totalFormat(value,rowData,rowIndex){ var totalSalesmoney = rowData.totalSalesmoney; var totalCostmoney=rowData.totalCostmoney; var totalOrderNum=rowData.totalOrderNum; $("#num").html(totalOrderNum); $("#sale").html(totalSalesmoney); $("#cost").html(totalCostmoney); return totalSalesmoney; } //获取表头参数 function getTableHeadOpt(){ var opt = []; opt.push({title:'销售汇总报表',colspan:11}); return opt; } //获取列头参数 function getColumnsOpt(){ var opt = [ {field:'goodCode',title:'资料编号',width:15,align:'left'}, {field:'goodTypeName',title:'资料类别',width:10,align:'left'}, {field:'goodName',title:'资料名',width:30,align:'left'}, {field:'unit',title:'单位',width:10,align:'left'}, {field:'purchasePrice',title:'进货价',width:15,align:'left'}, {field:'goodPrice',title:'销售单价',width:15,align:'left'}, {field:'taxRate',title:'资料税率',width:15,align:'left'}, {field:'orderNumber',title:'销售数量',width:20,align:'left'}, {field:'taxDueSum',title:'销售税金',width:15,align:'left',formatter:taxDueSumFormat}, {field:'salesmoney',title:'不含税销售金额',width:20,align:'left'}, {field:'costmoney',title:'成本金额',width:20,align:'left'} ]; return opt; } //Json加载数据路径 function getUrlOpt(){ var url = ctx+'/Salesummary_json!listJson.do?1=1'; return url; } //搜索框检查用户是否按下‘回车键’,按下则调用搜索方法 function checkKey(){ if(event.keyCode=='13'){ searchData(); } } //格式化销售税金显示方式 function taxDueSumFormat(value,rowData,rowIndex){ var taxDueSum = rowData.taxDueSum; if(taxDueSum){ taxDueSum = taxDueSum.toFixed(2); } return taxDueSum; } //搜索功能 function searchData(){ var goodTypeName = $('#goodTypeName').val(); var goodName = $('#goodName').val(); var begin = $('#begin').val(); var end = $('#end').val(); var brandName=$('#brandName').val(); var positionName=$('#warehousePositionName').val(); realoadGrid(goodTypeName,goodName,begin,e
oodTypeName,goodName,begin,end,brandName,positionName){ var queryParams = $(gId).datagrid('options').queryParams; queryParams={"saleWare.goodTypeName":goodTypeName,"saleWare.goodName":goodName,"saleWare.begin":begin,"saleWare.end":end,"saleWare.brandName":brandName,"saleWare.warehousePositionName":positionName}; $(gId).datagrid('options').queryParams = queryParams; $(gId).datagrid('reload'); } //仓库 function selectWarehouse(){ var warehouse = common.getWarehouse(); if(warehouse){ $('#warehouseId').val(warehouse.id); $('#warehouseName').val(warehouse.name); } } //选择仓库 function selectWarehousePosition(){ var warehouseName=$('#warehouseName').val(); if(warehouseName==null||warehouseName=='') { alert('请选择仓库'); } else { WarehousePosition(); } } //仓位 function WarehousePosition(){ var warehousePosition = common.getWarehousePosition(); if(warehousePosition){ $('#warehousePositionName').val(warehousePosition.name); } } //选择资料品牌 function selectBrand(obj){ var obj = $(obj); var dataArr = window.showModalDialog(ctx+"/goodBrand!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px"); if(dataArr!=null){ $(obj).val(dataArr.brandName); $("#brandId").val(dataArr.brandId); $(obj).focus(); } } //选择资料类别弹出窗 function selectType(obj){ var obj = $(obj); var dataArr = window.showModalDialog(ctx+"/goodType!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px"); if(dataArr!=null){ $(obj).val(dataArr.typeName); $(obj).focus(); } } //重新加载 function reloadDataGrid(){ $(gId).datagrid('reload'); }
nd,brandName,positionName); } function cancelSearch(){ $('#goodTypeName').val(''); $('#goodName').val(''); $('#begin').val(''); $('#end').val(''); $('#brandName').val(''); $('#warehouseName').val(''); $('#warehousePositionName').val(''); searchData(); } //确定搜索时重新加载datagrid function realoadGrid(g
identifier_body
list_salesummary.js
var gId = '#dataGrid'; var lastIndex; $(document).ready(function(){ //列表 $(gId).datagrid({ url:getUrlOpt(), idField:'id', fitColumns:true, frozenColumns:[[ {field:'ck',checkbox:true} ]], columns:[ getTableHeadOpt(), getColumnsOpt(), getTotal() ], rownumbers:true, pagination:false, loadMsg:'数据装载中......', onClickRow:function(rowIndex){ if (lastIndex != rowIndex){ $(gId).d
= rowIndex; } }); }); //计算总计 function getTotal() { var opt=[ {field:'totalSalesmoney',title:'出货金额总计',hidden:true,align:'left',formatter:totalFormat}, {field:'totalCostmoney',title:'成本金额总计',hidden:true,align:'left'}, {field:'totalOrderNum',title:'出货数量总计',hidden:true,align:'left'} ]; return opt; } //格式化总计 function totalFormat(value,rowData,rowIndex){ var totalSalesmoney = rowData.totalSalesmoney; var totalCostmoney=rowData.totalCostmoney; var totalOrderNum=rowData.totalOrderNum; $("#num").html(totalOrderNum); $("#sale").html(totalSalesmoney); $("#cost").html(totalCostmoney); return totalSalesmoney; } //获取表头参数 function getTableHeadOpt(){ var opt = []; opt.push({title:'销售汇总报表',colspan:11}); return opt; } //获取列头参数 function getColumnsOpt(){ var opt = [ {field:'goodCode',title:'资料编号',width:15,align:'left'}, {field:'goodTypeName',title:'资料类别',width:10,align:'left'}, {field:'goodName',title:'资料名',width:30,align:'left'}, {field:'unit',title:'单位',width:10,align:'left'}, {field:'purchasePrice',title:'进货价',width:15,align:'left'}, {field:'goodPrice',title:'销售单价',width:15,align:'left'}, {field:'taxRate',title:'资料税率',width:15,align:'left'}, {field:'orderNumber',title:'销售数量',width:20,align:'left'}, {field:'taxDueSum',title:'销售税金',width:15,align:'left',formatter:taxDueSumFormat}, {field:'salesmoney',title:'不含税销售金额',width:20,align:'left'}, {field:'costmoney',title:'成本金额',width:20,align:'left'} ]; return opt; } //Json加载数据路径 function getUrlOpt(){ var url = ctx+'/Salesummary_json!listJson.do?1=1'; return url; } //搜索框检查用户是否按下‘回车键’,按下则调用搜索方法 function checkKey(){ if(event.keyCode=='13'){ searchData(); } } //格式化销售税金显示方式 function taxDueSumFormat(value,rowData,rowIndex){ var taxDueSum = rowData.taxDueSum; if(taxDueSum){ taxDueSum = taxDueSum.toFixed(2); } return taxDueSum; } //搜索功能 function searchData(){ var goodTypeName = $('#goodTypeName').val(); var goodName = $('#goodName').val(); var begin = $('#begin').val(); var end = $('#end').val(); var brandName=$('#brandName').val(); var positionName=$('#warehousePositionName').val(); realoadGrid(goodTypeName,goodName,begin,end,brandName,positionName); } function cancelSearch(){ $('#goodTypeName').val(''); $('#goodName').val(''); $('#begin').val(''); $('#end').val(''); $('#brandName').val(''); $('#warehouseName').val(''); $('#warehousePositionName').val(''); searchData(); } //确定搜索时重新加载datagrid function realoadGrid(goodTypeName,goodName,begin,end,brandName,positionName){ var queryParams = $(gId).datagrid('options').queryParams; queryParams={"saleWare.goodTypeName":goodTypeName,"saleWare.goodName":goodName,"saleWare.begin":begin,"saleWare.end":end,"saleWare.brandName":brandName,"saleWare.warehousePositionName":positionName}; $(gId).datagrid('options').queryParams = queryParams; $(gId).datagrid('reload'); } //仓库 function selectWarehouse(){ var warehouse = common.getWarehouse(); if(warehouse){ $('#warehouseId').val(warehouse.id); $('#warehouseName').val(warehouse.name); } } //选择仓库 function selectWarehousePosition(){ var warehouseName=$('#warehouseName').val(); if(warehouseName==null||warehouseName=='') { alert('请选择仓库'); } else { WarehousePosition(); } } //仓位 function WarehousePosition(){ var warehousePosition = common.getWarehousePosition(); if(warehousePosition){ $('#warehousePositionName').val(warehousePosition.name); } } //选择资料品牌 function selectBrand(obj){ var obj = $(obj); var dataArr = window.showModalDialog(ctx+"/goodBrand!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px"); if(dataArr!=null){ $(obj).val(dataArr.brandName); $("#brandId").val(dataArr.brandId); $(obj).focus(); } } //选择资料类别弹出窗 function selectType(obj){ var obj = $(obj); var dataArr = window.showModalDialog(ctx+"/goodType!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px"); if(dataArr!=null){ $(obj).val(dataArr.typeName); $(obj).focus(); } } //重新加载 function reloadDataGrid(){ $(gId).datagrid('reload'); }
atagrid('endEdit', lastIndex); $(gId).datagrid('beginEdit', rowIndex); } lastIndex
conditional_block
list_salesummary.js
var gId = '#dataGrid'; var lastIndex; $(document).ready(function(){ //列表 $(gId).datagrid({ url:getUrlOpt(), idField:'id', fitColumns:true, frozenColumns:[[ {field:'ck',checkbox:true} ]], columns:[ getTableHeadOpt(), getColumnsOpt(), getTotal() ], rownumbers:true, pagination:false, loadMsg:'数据装载中......', onClickRow:function(rowIndex){ if (lastIndex != rowIndex){ $(gId).datagrid('endEdit', lastIndex); $(gId).datagrid('beginEdit', rowIndex); } lastIndex = rowIndex; } }); }); //计算总计 function getTotal() { var opt=[ {field:'totalSalesmoney',title:'出货金额总计',hidden:true,align:'left',formatter:totalFormat}, {field:'totalCostmoney',title:'成本金额总计',hidden:true,align:'left'}, {field:'totalOrderNum',title:'出货数量总计',hidden:true,align:'left'} ]; return opt; } //格式化总计 function totalFormat(value,rowData,rowIndex){ var totalSalesmoney = rowData.totalSalesmoney; var totalCostmoney=rowData.totalCostmoney; var totalOrderNum=rowData.totalOrderNum; $("#num").html(totalOrderNum); $("#sale").html(totalSalesmoney); $("#cost").html(totalCostmoney); return totalSalesmoney; } //获取表头参数 function getTableHeadOpt(){ var opt = []; opt.push({title:'销售汇总报表',colspan:11}); ret
获取列头参数 function getColumnsOpt(){ var opt = [ {field:'goodCode',title:'资料编号',width:15,align:'left'}, {field:'goodTypeName',title:'资料类别',width:10,align:'left'}, {field:'goodName',title:'资料名',width:30,align:'left'}, {field:'unit',title:'单位',width:10,align:'left'}, {field:'purchasePrice',title:'进货价',width:15,align:'left'}, {field:'goodPrice',title:'销售单价',width:15,align:'left'}, {field:'taxRate',title:'资料税率',width:15,align:'left'}, {field:'orderNumber',title:'销售数量',width:20,align:'left'}, {field:'taxDueSum',title:'销售税金',width:15,align:'left',formatter:taxDueSumFormat}, {field:'salesmoney',title:'不含税销售金额',width:20,align:'left'}, {field:'costmoney',title:'成本金额',width:20,align:'left'} ]; return opt; } //Json加载数据路径 function getUrlOpt(){ var url = ctx+'/Salesummary_json!listJson.do?1=1'; return url; } //搜索框检查用户是否按下‘回车键’,按下则调用搜索方法 function checkKey(){ if(event.keyCode=='13'){ searchData(); } } //格式化销售税金显示方式 function taxDueSumFormat(value,rowData,rowIndex){ var taxDueSum = rowData.taxDueSum; if(taxDueSum){ taxDueSum = taxDueSum.toFixed(2); } return taxDueSum; } //搜索功能 function searchData(){ var goodTypeName = $('#goodTypeName').val(); var goodName = $('#goodName').val(); var begin = $('#begin').val(); var end = $('#end').val(); var brandName=$('#brandName').val(); var positionName=$('#warehousePositionName').val(); realoadGrid(goodTypeName,goodName,begin,end,brandName,positionName); } function cancelSearch(){ $('#goodTypeName').val(''); $('#goodName').val(''); $('#begin').val(''); $('#end').val(''); $('#brandName').val(''); $('#warehouseName').val(''); $('#warehousePositionName').val(''); searchData(); } //确定搜索时重新加载datagrid function realoadGrid(goodTypeName,goodName,begin,end,brandName,positionName){ var queryParams = $(gId).datagrid('options').queryParams; queryParams={"saleWare.goodTypeName":goodTypeName,"saleWare.goodName":goodName,"saleWare.begin":begin,"saleWare.end":end,"saleWare.brandName":brandName,"saleWare.warehousePositionName":positionName}; $(gId).datagrid('options').queryParams = queryParams; $(gId).datagrid('reload'); } //仓库 function selectWarehouse(){ var warehouse = common.getWarehouse(); if(warehouse){ $('#warehouseId').val(warehouse.id); $('#warehouseName').val(warehouse.name); } } //选择仓库 function selectWarehousePosition(){ var warehouseName=$('#warehouseName').val(); if(warehouseName==null||warehouseName=='') { alert('请选择仓库'); } else { WarehousePosition(); } } //仓位 function WarehousePosition(){ var warehousePosition = common.getWarehousePosition(); if(warehousePosition){ $('#warehousePositionName').val(warehousePosition.name); } } //选择资料品牌 function selectBrand(obj){ var obj = $(obj); var dataArr = window.showModalDialog(ctx+"/goodBrand!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px"); if(dataArr!=null){ $(obj).val(dataArr.brandName); $("#brandId").val(dataArr.brandId); $(obj).focus(); } } //选择资料类别弹出窗 function selectType(obj){ var obj = $(obj); var dataArr = window.showModalDialog(ctx+"/goodType!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px"); if(dataArr!=null){ $(obj).val(dataArr.typeName); $(obj).focus(); } } //重新加载 function reloadDataGrid(){ $(gId).datagrid('reload'); }
urn opt; } //
identifier_name
list_salesummary.js
var gId = '#dataGrid'; var lastIndex; $(document).ready(function(){ //列表 $(gId).datagrid({ url:getUrlOpt(), idField:'id', fitColumns:true, frozenColumns:[[ {field:'ck',checkbox:true} ]], columns:[ getTableHeadOpt(), getColumnsOpt(), getTotal() ], rownumbers:true, pagination:false, loadMsg:'数据装载中......', onClickRow:function(rowIndex){ if (lastIndex != rowIndex){ $(gId).datagrid('endEdit', lastIndex); $(gId).datagrid('beginEdit', rowIndex); } lastIndex = rowIndex; } }); }); //计算总计 function getTotal() { var opt=[ {field:'totalSalesmoney',title:'出货金额总计',hidden:true,align:'left',formatter:totalFormat}, {field:'totalCostmoney',title:'成本金额总计',hidden:true,align:'left'},
//格式化总计 function totalFormat(value,rowData,rowIndex){ var totalSalesmoney = rowData.totalSalesmoney; var totalCostmoney=rowData.totalCostmoney; var totalOrderNum=rowData.totalOrderNum; $("#num").html(totalOrderNum); $("#sale").html(totalSalesmoney); $("#cost").html(totalCostmoney); return totalSalesmoney; } //获取表头参数 function getTableHeadOpt(){ var opt = []; opt.push({title:'销售汇总报表',colspan:11}); return opt; } //获取列头参数 function getColumnsOpt(){ var opt = [ {field:'goodCode',title:'资料编号',width:15,align:'left'}, {field:'goodTypeName',title:'资料类别',width:10,align:'left'}, {field:'goodName',title:'资料名',width:30,align:'left'}, {field:'unit',title:'单位',width:10,align:'left'}, {field:'purchasePrice',title:'进货价',width:15,align:'left'}, {field:'goodPrice',title:'销售单价',width:15,align:'left'}, {field:'taxRate',title:'资料税率',width:15,align:'left'}, {field:'orderNumber',title:'销售数量',width:20,align:'left'}, {field:'taxDueSum',title:'销售税金',width:15,align:'left',formatter:taxDueSumFormat}, {field:'salesmoney',title:'不含税销售金额',width:20,align:'left'}, {field:'costmoney',title:'成本金额',width:20,align:'left'} ]; return opt; } //Json加载数据路径 function getUrlOpt(){ var url = ctx+'/Salesummary_json!listJson.do?1=1'; return url; } //搜索框检查用户是否按下‘回车键’,按下则调用搜索方法 function checkKey(){ if(event.keyCode=='13'){ searchData(); } } //格式化销售税金显示方式 function taxDueSumFormat(value,rowData,rowIndex){ var taxDueSum = rowData.taxDueSum; if(taxDueSum){ taxDueSum = taxDueSum.toFixed(2); } return taxDueSum; } //搜索功能 function searchData(){ var goodTypeName = $('#goodTypeName').val(); var goodName = $('#goodName').val(); var begin = $('#begin').val(); var end = $('#end').val(); var brandName=$('#brandName').val(); var positionName=$('#warehousePositionName').val(); realoadGrid(goodTypeName,goodName,begin,end,brandName,positionName); } function cancelSearch(){ $('#goodTypeName').val(''); $('#goodName').val(''); $('#begin').val(''); $('#end').val(''); $('#brandName').val(''); $('#warehouseName').val(''); $('#warehousePositionName').val(''); searchData(); } //确定搜索时重新加载datagrid function realoadGrid(goodTypeName,goodName,begin,end,brandName,positionName){ var queryParams = $(gId).datagrid('options').queryParams; queryParams={"saleWare.goodTypeName":goodTypeName,"saleWare.goodName":goodName,"saleWare.begin":begin,"saleWare.end":end,"saleWare.brandName":brandName,"saleWare.warehousePositionName":positionName}; $(gId).datagrid('options').queryParams = queryParams; $(gId).datagrid('reload'); } //仓库 function selectWarehouse(){ var warehouse = common.getWarehouse(); if(warehouse){ $('#warehouseId').val(warehouse.id); $('#warehouseName').val(warehouse.name); } } //选择仓库 function selectWarehousePosition(){ var warehouseName=$('#warehouseName').val(); if(warehouseName==null||warehouseName=='') { alert('请选择仓库'); } else { WarehousePosition(); } } //仓位 function WarehousePosition(){ var warehousePosition = common.getWarehousePosition(); if(warehousePosition){ $('#warehousePositionName').val(warehousePosition.name); } } //选择资料品牌 function selectBrand(obj){ var obj = $(obj); var dataArr = window.showModalDialog(ctx+"/goodBrand!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px"); if(dataArr!=null){ $(obj).val(dataArr.brandName); $("#brandId").val(dataArr.brandId); $(obj).focus(); } } //选择资料类别弹出窗 function selectType(obj){ var obj = $(obj); var dataArr = window.showModalDialog(ctx+"/goodType!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px"); if(dataArr!=null){ $(obj).val(dataArr.typeName); $(obj).focus(); } } //重新加载 function reloadDataGrid(){ $(gId).datagrid('reload'); }
{field:'totalOrderNum',title:'出货数量总计',hidden:true,align:'left'} ]; return opt; }
random_line_split
fetch-zero-knowledge.js
/** * Fetch configuration data using an API Key and the Application Secret Key. * By doing so, the sconfig servers will just apply firewall rules (if any) and return * the encrypted configuration data. The client will then decrypt the configuration * data using the App Secret Key * Note: Ff no API Key or App Secret is provided, it will look for it in process.env.SCONFIG_KEY and process.env.SCONFIG_SECRET * */
var sconfig = require('sconfig'); sconfig({ key: '{YOUR_API_KEY}', // the 32-char version of an API Key secret: '{YOUR_APP_SECRET}', // the 32 char secret key found under the App Details tab //version: '{YOUR_VERSION}', // version name to fetch, defaults to latest version created // json: true // expect the result data to be JSON. This is true by default. sync: true // persist the configuration data locally in the event of an sconfig server outage }, function(err, config) { if (err) { console.log(err); return; } console.log("OK", config); });
random_line_split
fetch-zero-knowledge.js
/** * Fetch configuration data using an API Key and the Application Secret Key. * By doing so, the sconfig servers will just apply firewall rules (if any) and return * the encrypted configuration data. The client will then decrypt the configuration * data using the App Secret Key * Note: Ff no API Key or App Secret is provided, it will look for it in process.env.SCONFIG_KEY and process.env.SCONFIG_SECRET * */ var sconfig = require('sconfig'); sconfig({ key: '{YOUR_API_KEY}', // the 32-char version of an API Key secret: '{YOUR_APP_SECRET}', // the 32 char secret key found under the App Details tab //version: '{YOUR_VERSION}', // version name to fetch, defaults to latest version created // json: true // expect the result data to be JSON. This is true by default. sync: true // persist the configuration data locally in the event of an sconfig server outage }, function(err, config) { if (err)
console.log("OK", config); });
{ console.log(err); return; }
conditional_block
from_other_type_slice.rs
use malachite_base::named::Named; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base::num::conversion::traits::FromOtherTypeSlice; use malachite_base_test_util::bench::bucketers::vec_len_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_vec_gen; use malachite_base_test_util::runner::Runner; use std::fmt::Display; pub(crate) fn register(runner: &mut Runner) { register_unsigned_unsigned_demos!(runner, demo_from_other_type_slice); register_unsigned_unsigned_benches!(runner, benchmark_from_other_type_slice); } fn
<T: Display + FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, ) { for xs in unsigned_vec_gen::<U>().get(gm, &config).take(limit) { println!( "{}::from_other_type_slice({:?}) = {}", T::NAME, xs, T::from_other_type_slice(&xs) ); } } fn benchmark_from_other_type_slice<T: FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, ) { run_benchmark( &format!("{}.from_other_type_slice(&[{}])", T::NAME, U::NAME), BenchmarkType::Single, unsigned_vec_gen::<U>().get(gm, &config), gm.name(), limit, file_name, &vec_len_bucketer(), &mut [("Malachite", &mut |xs| { no_out!(T::from_other_type_slice(&xs)) })], ); }
demo_from_other_type_slice
identifier_name
from_other_type_slice.rs
use malachite_base::named::Named; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base::num::conversion::traits::FromOtherTypeSlice; use malachite_base_test_util::bench::bucketers::vec_len_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_vec_gen; use malachite_base_test_util::runner::Runner; use std::fmt::Display; pub(crate) fn register(runner: &mut Runner) { register_unsigned_unsigned_demos!(runner, demo_from_other_type_slice); register_unsigned_unsigned_benches!(runner, benchmark_from_other_type_slice); } fn demo_from_other_type_slice<T: Display + FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, ) { for xs in unsigned_vec_gen::<U>().get(gm, &config).take(limit) { println!( "{}::from_other_type_slice({:?}) = {}", T::NAME, xs, T::from_other_type_slice(&xs) ); } } fn benchmark_from_other_type_slice<T: FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, ) { run_benchmark( &format!("{}.from_other_type_slice(&[{}])", T::NAME, U::NAME), BenchmarkType::Single, unsigned_vec_gen::<U>().get(gm, &config), gm.name(), limit, file_name, &vec_len_bucketer(), &mut [("Malachite", &mut |xs| { no_out!(T::from_other_type_slice(&xs)) })],
); }
random_line_split
from_other_type_slice.rs
use malachite_base::named::Named; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base::num::conversion::traits::FromOtherTypeSlice; use malachite_base_test_util::bench::bucketers::vec_len_bucketer; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::unsigned_vec_gen; use malachite_base_test_util::runner::Runner; use std::fmt::Display; pub(crate) fn register(runner: &mut Runner) { register_unsigned_unsigned_demos!(runner, demo_from_other_type_slice); register_unsigned_unsigned_benches!(runner, benchmark_from_other_type_slice); } fn demo_from_other_type_slice<T: Display + FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, ) { for xs in unsigned_vec_gen::<U>().get(gm, &config).take(limit) { println!( "{}::from_other_type_slice({:?}) = {}", T::NAME, xs, T::from_other_type_slice(&xs) ); } } fn benchmark_from_other_type_slice<T: FromOtherTypeSlice<U> + Named, U: PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, )
{ run_benchmark( &format!("{}.from_other_type_slice(&[{}])", T::NAME, U::NAME), BenchmarkType::Single, unsigned_vec_gen::<U>().get(gm, &config), gm.name(), limit, file_name, &vec_len_bucketer(), &mut [("Malachite", &mut |xs| { no_out!(T::from_other_type_slice(&xs)) })], ); }
identifier_body
trigger.tsx
import React, { ComponentType } from "react"; import queryString from "query-string"; import { RouteComponentProps } from "react-router-dom"; import isEqual from "lodash/isEqual"; import MoiraApi from "../../Api/MoiraApi"; import { Trigger, TriggerState } from "../../Domain/Trigger"; import { Event } from "../../Domain/Event"; import { MoiraUrlParams } from "../../Domain/MoiraUrlParams"; import { setMetricMaintenance, setTriggerMaintenance } from "../../Domain/Maintenance"; import { withMoiraApi } from "../../Api/MoiraApiInjection"; import transformPageFromHumanToProgrammer from "../../logic/transformPageFromHumanToProgrammer"; import { TriggerDesktopProps } from "./trigger.desktop"; import { TriggerMobileProps } from "./trigger.mobile"; export type TriggerProps = RouteComponentProps<{ id: string }> & { moiraApi: MoiraApi; view: ComponentType<TriggerDesktopProps | TriggerMobileProps>; }; type State = { loading: boolean; error?: string; page: number; pageCount: number; trigger?: Trigger; triggerState?: TriggerState; triggerEvents: Array<Event>; }; // ToDo решить, нужно ли подтягивать данные с сервера, если что-то изменилось class TriggerPage extends React.Component<TriggerProps, State> { state: State = { loading: true, page: 1, pageCount: 1, triggerEvents: [], }; componentDidMount() { document.title = "Moira - Trigger"; this.loadData(); } componentDidUpdate({ location: prevLocation }: TriggerProps) { const { location: currentLocation } = this.props; if (!isEqual(prevLocation, currentLocation)) { this.loadData(); } } static parseLocationSearch(search: string): MoiraUrlParams { const START_PAGE = 1; const { page } = queryString.parse(search); return { page: Number.isNaN(Number(page)) || typeof page !== "string" ? START_PAGE : Math.abs(parseInt(page, 10)), tags: [], searchText: "", onlyProblems: false, }; } static getEventMetricName(event: Event, triggerName: string): string { if (event.trigger_event) { return triggerName; } return event.metric.length !== 0 ? event.metric : "No metric evaluated"; } static composeEvents( events: Array<Event>, triggerName: string ): { [key: string]: Array<Event>; } { return events.reduce((data: { [key: string]: Array<Event> }, event: Event) => { const metric = this.getEventMetricName(event, triggerName); if (data[metric]) { data[metric].push(event); } else { data[metric] = [event]; } return data; }, {}); } render() { const { loading,
or, page, pageCount, trigger, triggerState, triggerEvents, } = this.state; const { view: TriggerView } = this.props; return ( <TriggerView trigger={trigger} state={triggerState} events={triggerEvents} page={page} pageCount={pageCount} loading={loading} error={error} disableThrottling={this.disableThrottling} setTriggerMaintenance={this.setTriggerMaintenance} setMetricMaintenance={this.setMetricMaintenance} removeMetric={this.removeMetric} removeNoDataMetric={this.removeNoDataMetric} onPageChange={this.changeLocationSearch} /> ); } async loadData() { const { moiraApi, match, location } = this.props; const { page } = TriggerPage.parseLocationSearch(location.search); const { id } = match.params; // ToDo написать проверку id try { const [trigger, triggerState, triggerEvents] = await Promise.all([ moiraApi.getTrigger(id, { populated: true }), moiraApi.getTriggerState(id), moiraApi.getTriggerEvents(id, transformPageFromHumanToProgrammer(page)), ]); const pageCount = Math.ceil(triggerEvents.total / triggerEvents.size); // ToDo написать проверку на превышение страниц document.title = `Moira - Trigger - ${trigger.name}`; this.setState({ page, pageCount: Number.isNaN(pageCount) ? 1 : pageCount, trigger, triggerState, triggerEvents: triggerEvents.list || [], loading: false, }); } catch (error) { this.setState({ loading: false, error: error.message }); } } disableThrottling = async (triggerId: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delThrottling(triggerId); this.loadData(); }; setTriggerMaintenance = async (triggerId: string, maintenance: number) => { const { moiraApi } = this.props; this.setState({ loading: true }); await setTriggerMaintenance(moiraApi, triggerId, maintenance); this.loadData(); }; setMetricMaintenance = async (triggerId: string, metric: string, maintenance: number) => { const { moiraApi } = this.props; this.setState({ loading: true }); await setMetricMaintenance(moiraApi, triggerId, metric, maintenance); this.loadData(); }; removeMetric = async (triggerId: string, metric: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delMetric(triggerId, metric); this.loadData(); }; removeNoDataMetric = async (triggerId: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delNoDataMetric(triggerId); this.loadData(); }; changeLocationSearch = (update: { page: number }) => { const { location, history } = this.props; const locationSearch = TriggerPage.parseLocationSearch(location.search); history.push( `?${queryString.stringify( { ...locationSearch, ...update }, { arrayFormat: "index", encode: true, } )}` ); }; } export default withMoiraApi(TriggerPage);
err
identifier_name
trigger.tsx
import React, { ComponentType } from "react"; import queryString from "query-string"; import { RouteComponentProps } from "react-router-dom"; import isEqual from "lodash/isEqual"; import MoiraApi from "../../Api/MoiraApi"; import { Trigger, TriggerState } from "../../Domain/Trigger"; import { Event } from "../../Domain/Event"; import { MoiraUrlParams } from "../../Domain/MoiraUrlParams"; import { setMetricMaintenance, setTriggerMaintenance } from "../../Domain/Maintenance"; import { withMoiraApi } from "../../Api/MoiraApiInjection"; import transformPageFromHumanToProgrammer from "../../logic/transformPageFromHumanToProgrammer"; import { TriggerDesktopProps } from "./trigger.desktop"; import { TriggerMobileProps } from "./trigger.mobile"; export type TriggerProps = RouteComponentProps<{ id: string }> & { moiraApi: MoiraApi; view: ComponentType<TriggerDesktopProps | TriggerMobileProps>; }; type State = { loading: boolean; error?: string; page: number; pageCount: number; trigger?: Trigger; triggerState?: TriggerState; triggerEvents: Array<Event>; }; // ToDo решить, нужно ли подтягивать данные с сервера, если что-то изменилось class TriggerPage extends React.Component<TriggerProps, State> { state: State = { loading: true, page: 1, pageCount: 1, triggerEvents: [], }; componentDidMount() { document.title = "Moira - Trigger"; this.loadData(); } componentDidUpdate({ location: prevLocation }: TriggerProps) { const { location: currentLocation } = this.props; if (!isEqual(prevLocation, currentLocation)) { this.loadData(); } } static parseLocationSearch(search: string): MoiraUrlParams { const START_PAGE = 1; const { page } = queryString.parse(search); return { page: Number.isNaN(Number(page)) || typeof page !== "string" ? START_PAGE : Math.abs(parseInt(page, 10)), tags: [], searchText: "",
static getEventMetricName(event: Event, triggerName: string): string { if (event.trigger_event) { return triggerName; } return event.metric.length !== 0 ? event.metric : "No metric evaluated"; } static composeEvents( events: Array<Event>, triggerName: string ): { [key: string]: Array<Event>; } { return events.reduce((data: { [key: string]: Array<Event> }, event: Event) => { const metric = this.getEventMetricName(event, triggerName); if (data[metric]) { data[metric].push(event); } else { data[metric] = [event]; } return data; }, {}); } render() { const { loading, error, page, pageCount, trigger, triggerState, triggerEvents, } = this.state; const { view: TriggerView } = this.props; return ( <TriggerView trigger={trigger} state={triggerState} events={triggerEvents} page={page} pageCount={pageCount} loading={loading} error={error} disableThrottling={this.disableThrottling} setTriggerMaintenance={this.setTriggerMaintenance} setMetricMaintenance={this.setMetricMaintenance} removeMetric={this.removeMetric} removeNoDataMetric={this.removeNoDataMetric} onPageChange={this.changeLocationSearch} /> ); } async loadData() { const { moiraApi, match, location } = this.props; const { page } = TriggerPage.parseLocationSearch(location.search); const { id } = match.params; // ToDo написать проверку id try { const [trigger, triggerState, triggerEvents] = await Promise.all([ moiraApi.getTrigger(id, { populated: true }), moiraApi.getTriggerState(id), moiraApi.getTriggerEvents(id, transformPageFromHumanToProgrammer(page)), ]); const pageCount = Math.ceil(triggerEvents.total / triggerEvents.size); // ToDo написать проверку на превышение страниц document.title = `Moira - Trigger - ${trigger.name}`; this.setState({ page, pageCount: Number.isNaN(pageCount) ? 1 : pageCount, trigger, triggerState, triggerEvents: triggerEvents.list || [], loading: false, }); } catch (error) { this.setState({ loading: false, error: error.message }); } } disableThrottling = async (triggerId: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delThrottling(triggerId); this.loadData(); }; setTriggerMaintenance = async (triggerId: string, maintenance: number) => { const { moiraApi } = this.props; this.setState({ loading: true }); await setTriggerMaintenance(moiraApi, triggerId, maintenance); this.loadData(); }; setMetricMaintenance = async (triggerId: string, metric: string, maintenance: number) => { const { moiraApi } = this.props; this.setState({ loading: true }); await setMetricMaintenance(moiraApi, triggerId, metric, maintenance); this.loadData(); }; removeMetric = async (triggerId: string, metric: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delMetric(triggerId, metric); this.loadData(); }; removeNoDataMetric = async (triggerId: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delNoDataMetric(triggerId); this.loadData(); }; changeLocationSearch = (update: { page: number }) => { const { location, history } = this.props; const locationSearch = TriggerPage.parseLocationSearch(location.search); history.push( `?${queryString.stringify( { ...locationSearch, ...update }, { arrayFormat: "index", encode: true, } )}` ); }; } export default withMoiraApi(TriggerPage);
onlyProblems: false, }; }
random_line_split
trigger.tsx
import React, { ComponentType } from "react"; import queryString from "query-string"; import { RouteComponentProps } from "react-router-dom"; import isEqual from "lodash/isEqual"; import MoiraApi from "../../Api/MoiraApi"; import { Trigger, TriggerState } from "../../Domain/Trigger"; import { Event } from "../../Domain/Event"; import { MoiraUrlParams } from "../../Domain/MoiraUrlParams"; import { setMetricMaintenance, setTriggerMaintenance } from "../../Domain/Maintenance"; import { withMoiraApi } from "../../Api/MoiraApiInjection"; import transformPageFromHumanToProgrammer from "../../logic/transformPageFromHumanToProgrammer"; import { TriggerDesktopProps } from "./trigger.desktop"; import { TriggerMobileProps } from "./trigger.mobile"; export type TriggerProps = RouteComponentProps<{ id: string }> & { moiraApi: MoiraApi; view: ComponentType<TriggerDesktopProps | TriggerMobileProps>; }; type State = { loading: boolean; error?: string; page: number; pageCount: number; trigger?: Trigger; triggerState?: TriggerState; triggerEvents: Array<Event>; }; // ToDo решить, нужно ли подтягивать данные с сервера, если что-то изменилось class TriggerPage extends React.Component<TriggerProps, State> { state: State = { loading: true, page: 1, pageCount: 1, triggerEvents: [], }; componentDidMount() { document.title = "Moira - Trigger"; this.loadData(); } componentDidUpdate({ location: prevLocation }: TriggerProps) { const { location: currentLocation } = this.props; if (!isEqual(prevLocation, currentLocation)) { this.loadData(); } } static parseLocationSearch(search: string): MoiraUrlParams { const START_PAGE = 1; const { page } = queryString.parse(search); return { page: Number.isNaN(Number(page)) || typeof page !== "string" ? START_PAGE : Math.abs(parseInt(page, 10)), tags: [], searchText: "", onlyProblems: false, }; } static getEventMetricName(event: Event, triggerName: string): string { if (event.trigger_event) { return triggerName; } return event.metric.length !== 0 ? event.metric : "No metric evaluated"; } static composeEvents( events: Array<Event>, triggerName: string ): { [key: string]: Array<Event>; } { return events.reduce((data: { [key: string]: Ar
error, page, pageCount, trigger, triggerState, triggerEvents, } = this.state; const { view: TriggerView } = this.props; return ( <TriggerView trigger={trigger} state={triggerState} events={triggerEvents} page={page} pageCount={pageCount} loading={loading} error={error} disableThrottling={this.disableThrottling} setTriggerMaintenance={this.setTriggerMaintenance} setMetricMaintenance={this.setMetricMaintenance} removeMetric={this.removeMetric} removeNoDataMetric={this.removeNoDataMetric} onPageChange={this.changeLocationSearch} /> ); } async loadData() { const { moiraApi, match, location } = this.props; const { page } = TriggerPage.parseLocationSearch(location.search); const { id } = match.params; // ToDo написать проверку id try { const [trigger, triggerState, triggerEvents] = await Promise.all([ moiraApi.getTrigger(id, { populated: true }), moiraApi.getTriggerState(id), moiraApi.getTriggerEvents(id, transformPageFromHumanToProgrammer(page)), ]); const pageCount = Math.ceil(triggerEvents.total / triggerEvents.size); // ToDo написать проверку на превышение страниц document.title = `Moira - Trigger - ${trigger.name}`; this.setState({ page, pageCount: Number.isNaN(pageCount) ? 1 : pageCount, trigger, triggerState, triggerEvents: triggerEvents.list || [], loading: false, }); } catch (error) { this.setState({ loading: false, error: error.message }); } } disableThrottling = async (triggerId: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delThrottling(triggerId); this.loadData(); }; setTriggerMaintenance = async (triggerId: string, maintenance: number) => { const { moiraApi } = this.props; this.setState({ loading: true }); await setTriggerMaintenance(moiraApi, triggerId, maintenance); this.loadData(); }; setMetricMaintenance = async (triggerId: string, metric: string, maintenance: number) => { const { moiraApi } = this.props; this.setState({ loading: true }); await setMetricMaintenance(moiraApi, triggerId, metric, maintenance); this.loadData(); }; removeMetric = async (triggerId: string, metric: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delMetric(triggerId, metric); this.loadData(); }; removeNoDataMetric = async (triggerId: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delNoDataMetric(triggerId); this.loadData(); }; changeLocationSearch = (update: { page: number }) => { const { location, history } = this.props; const locationSearch = TriggerPage.parseLocationSearch(location.search); history.push( `?${queryString.stringify( { ...locationSearch, ...update }, { arrayFormat: "index", encode: true, } )}` ); }; } export default withMoiraApi(TriggerPage);
ray<Event> }, event: Event) => { const metric = this.getEventMetricName(event, triggerName); if (data[metric]) { data[metric].push(event); } else { data[metric] = [event]; } return data; }, {}); } render() { const { loading,
identifier_body
trigger.tsx
import React, { ComponentType } from "react"; import queryString from "query-string"; import { RouteComponentProps } from "react-router-dom"; import isEqual from "lodash/isEqual"; import MoiraApi from "../../Api/MoiraApi"; import { Trigger, TriggerState } from "../../Domain/Trigger"; import { Event } from "../../Domain/Event"; import { MoiraUrlParams } from "../../Domain/MoiraUrlParams"; import { setMetricMaintenance, setTriggerMaintenance } from "../../Domain/Maintenance"; import { withMoiraApi } from "../../Api/MoiraApiInjection"; import transformPageFromHumanToProgrammer from "../../logic/transformPageFromHumanToProgrammer"; import { TriggerDesktopProps } from "./trigger.desktop"; import { TriggerMobileProps } from "./trigger.mobile"; export type TriggerProps = RouteComponentProps<{ id: string }> & { moiraApi: MoiraApi; view: ComponentType<TriggerDesktopProps | TriggerMobileProps>; }; type State = { loading: boolean; error?: string; page: number; pageCount: number; trigger?: Trigger; triggerState?: TriggerState; triggerEvents: Array<Event>; }; // ToDo решить, нужно ли подтягивать данные с сервера, если что-то изменилось class TriggerPage extends React.Component<TriggerProps, State> { state: State = { loading: true, page: 1, pageCount: 1, triggerEvents: [], }; componentDidMount() { document.title = "Moira - Trigger"; this.loadData(); } componentDidUpdate({ location: prevLocation }: TriggerProps) { const { location: currentLocation } = this.props; if (!isEqual(prevLocation, currentLocation)) { this.loadData(); } } static parseLocationSearch(search: string): MoiraUrlParams { const START_PAGE = 1; const { page } = queryString.parse(search); return { page: Number.isNaN(Number(page)) || typeof page !== "string" ? START_PAGE : Math.abs(parseInt(page, 10)), tags: [], searchText: "", onlyProblems: false, }; } static getEventMetricName(event: Event, triggerName: string): string { if (event.trigger_event) { return triggerName; } return event.metric.length !== 0 ? event.metric : "No metric evaluated"; } static composeEvents( events: Array<Event>, triggerName: string ): { [key: string]: Array<Event>; } { return events.reduce((data: { [key: string]: Array<Event> }, event: Event) => { const metric = this.getEventMetricName(event, triggerName); if (data[metric]) { data[metric].push(event); } else { data[metric] = [event]; }
er() { const { loading, error, page, pageCount, trigger, triggerState, triggerEvents, } = this.state; const { view: TriggerView } = this.props; return ( <TriggerView trigger={trigger} state={triggerState} events={triggerEvents} page={page} pageCount={pageCount} loading={loading} error={error} disableThrottling={this.disableThrottling} setTriggerMaintenance={this.setTriggerMaintenance} setMetricMaintenance={this.setMetricMaintenance} removeMetric={this.removeMetric} removeNoDataMetric={this.removeNoDataMetric} onPageChange={this.changeLocationSearch} /> ); } async loadData() { const { moiraApi, match, location } = this.props; const { page } = TriggerPage.parseLocationSearch(location.search); const { id } = match.params; // ToDo написать проверку id try { const [trigger, triggerState, triggerEvents] = await Promise.all([ moiraApi.getTrigger(id, { populated: true }), moiraApi.getTriggerState(id), moiraApi.getTriggerEvents(id, transformPageFromHumanToProgrammer(page)), ]); const pageCount = Math.ceil(triggerEvents.total / triggerEvents.size); // ToDo написать проверку на превышение страниц document.title = `Moira - Trigger - ${trigger.name}`; this.setState({ page, pageCount: Number.isNaN(pageCount) ? 1 : pageCount, trigger, triggerState, triggerEvents: triggerEvents.list || [], loading: false, }); } catch (error) { this.setState({ loading: false, error: error.message }); } } disableThrottling = async (triggerId: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delThrottling(triggerId); this.loadData(); }; setTriggerMaintenance = async (triggerId: string, maintenance: number) => { const { moiraApi } = this.props; this.setState({ loading: true }); await setTriggerMaintenance(moiraApi, triggerId, maintenance); this.loadData(); }; setMetricMaintenance = async (triggerId: string, metric: string, maintenance: number) => { const { moiraApi } = this.props; this.setState({ loading: true }); await setMetricMaintenance(moiraApi, triggerId, metric, maintenance); this.loadData(); }; removeMetric = async (triggerId: string, metric: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delMetric(triggerId, metric); this.loadData(); }; removeNoDataMetric = async (triggerId: string) => { const { moiraApi } = this.props; this.setState({ loading: true }); await moiraApi.delNoDataMetric(triggerId); this.loadData(); }; changeLocationSearch = (update: { page: number }) => { const { location, history } = this.props; const locationSearch = TriggerPage.parseLocationSearch(location.search); history.push( `?${queryString.stringify( { ...locationSearch, ...update }, { arrayFormat: "index", encode: true, } )}` ); }; } export default withMoiraApi(TriggerPage);
return data; }, {}); } rend
conditional_block
whoami.py
# -*- coding: utf-8 -*- """ Display logged-in username. Configuration parameters: format: display format for whoami (default '{username}') Format placeholders: {username} display current username Inspired by i3 FAQ: https://faq.i3wm.org/question/1618/add-user-name-to-status-bar.1.html @author ultrabug SAMPLE OUTPUT {'full_text': u'ultrabug'} """ from getpass import getuser class
: """ """ # available configuration parameters format = '{username}' class Meta: deprecated = { 'remove': [ { 'param': 'cache_timeout', 'msg': 'obsolete parameter', }, ], } def whoami(self): """ We use the getpass module to get the current user. """ username = '{}'.format(getuser()) return { 'cached_until': self.py3.CACHE_FOREVER, 'full_text': self.py3.safe_format(self.format, {'username': username}) } if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status)
Py3status
identifier_name
whoami.py
# -*- coding: utf-8 -*- """ Display logged-in username. Configuration parameters: format: display format for whoami (default '{username}') Format placeholders: {username} display current username Inspired by i3 FAQ: https://faq.i3wm.org/question/1618/add-user-name-to-status-bar.1.html @author ultrabug SAMPLE OUTPUT {'full_text': u'ultrabug'}
class Py3status: """ """ # available configuration parameters format = '{username}' class Meta: deprecated = { 'remove': [ { 'param': 'cache_timeout', 'msg': 'obsolete parameter', }, ], } def whoami(self): """ We use the getpass module to get the current user. """ username = '{}'.format(getuser()) return { 'cached_until': self.py3.CACHE_FOREVER, 'full_text': self.py3.safe_format(self.format, {'username': username}) } if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status)
""" from getpass import getuser
random_line_split
whoami.py
# -*- coding: utf-8 -*- """ Display logged-in username. Configuration parameters: format: display format for whoami (default '{username}') Format placeholders: {username} display current username Inspired by i3 FAQ: https://faq.i3wm.org/question/1618/add-user-name-to-status-bar.1.html @author ultrabug SAMPLE OUTPUT {'full_text': u'ultrabug'} """ from getpass import getuser class Py3status: """ """ # available configuration parameters format = '{username}' class Meta: deprecated = { 'remove': [ { 'param': 'cache_timeout', 'msg': 'obsolete parameter', }, ], } def whoami(self): """ We use the getpass module to get the current user. """ username = '{}'.format(getuser()) return { 'cached_until': self.py3.CACHE_FOREVER, 'full_text': self.py3.safe_format(self.format, {'username': username}) } if __name__ == "__main__":
""" Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status)
conditional_block
whoami.py
# -*- coding: utf-8 -*- """ Display logged-in username. Configuration parameters: format: display format for whoami (default '{username}') Format placeholders: {username} display current username Inspired by i3 FAQ: https://faq.i3wm.org/question/1618/add-user-name-to-status-bar.1.html @author ultrabug SAMPLE OUTPUT {'full_text': u'ultrabug'} """ from getpass import getuser class Py3status:
if __name__ == "__main__": """ Run module in test mode. """ from py3status.module_test import module_test module_test(Py3status)
""" """ # available configuration parameters format = '{username}' class Meta: deprecated = { 'remove': [ { 'param': 'cache_timeout', 'msg': 'obsolete parameter', }, ], } def whoami(self): """ We use the getpass module to get the current user. """ username = '{}'.format(getuser()) return { 'cached_until': self.py3.CACHE_FOREVER, 'full_text': self.py3.safe_format(self.format, {'username': username}) }
identifier_body
fs.rs
/* Rust - Std Misc Filesystem Operation Licence : GNU GPL v3 or later Author : Aurélien DESBRIÈRES Mail : aurelien(at)hackers(dot)camp Created on : June 2017 Write with Emacs-nox ───────────────┐ Rust ───────────────────────────────┘ */ // fs.rs
use std::io::prelude::*; use std::os::unix; use std::path::Path; // A simple implementation of `% cat path` fn cat(path: &Path) -> io::Result<String> { let mut f = try!(File::open(path)); let mut s = String::new(); match f.read_to_string(&mut s) { Ok(_) => Ok(s), Err(e) => Err(e), } } // A simple implementation of `% echo s > path` fn echo(s: &str, path: &Path) -> io::Result<()> { let mut f = try!(File::create(path)); f.write_all(s.as_bytes()) } // A simple implementation of `% touch path` (ignores existing files) fn touch(path: &Path) -> io::Result<()> { match OpenOptions::new().create(true).write(true).open(path) { Ok(_) => Ok(()), Err(e) => Err(e), } } fn main() { println!("`mkdir a`"); // Create a directory, returns `io::Result<()>` match fs::create_dir("a") { Err(why) => println!("! {:?}", why.kind()), Ok(_) => {}, } println!("`echo hello > a/b.txt`"); // The previous match can be simplified using the `unwrap_or_else` method echo("hello", &Path::new("a/b.txt")).unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`mkdir -p a/c/d`"); // Recursively create a directory, returns `io::Result<()>` fs::create_dir_all("a/c/d").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`touch a/c/e.txt`"); touch(&Path::new("a/c/e.txt")).unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`ln -s ../b.txt a/c/b.txt`"); // Create a symbolinc link, returns `io::Result<()>` if cfg!(target_family = "unix") { unix::fs::symlink("../b.txt", "a/c/b.txt").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); } println!("`cat a/c/b.txt`"); match cat(&Path::new("a/c/b.txt")) { Err(why) => println!("! {:?}", why.kind()), Ok(s) => println!("> {}", s), } println!("`ls a`"); // Read the constants of a directory, return `io::Result<Vec<Path>>` match fs::read_dir("a") { Err(why) => println!("! {:?}", why.kind()), Ok(paths) => for path in paths { println!("> {:?}", path.unwrap().path()); }, } println!("`rm a/c/e.txt`"); // Remove a file, returns `io::Result<()>` fs::remove_file("a/c/e.txt").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`rmdir a/c/d`"); // Remove an empty directory, returns `io::Result<()>` fs::remove_dir("a/c/d").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); }
use std::fs; use std::fs::{File, OpenOptions}; use std::io;
random_line_split
fs.rs
/* Rust - Std Misc Filesystem Operation Licence : GNU GPL v3 or later Author : Aurélien DESBRIÈRES Mail : aurelien(at)hackers(dot)camp Created on : June 2017 Write with Emacs-nox ───────────────┐ Rust ───────────────────────────────┘ */ // fs.rs use std::fs; use std::fs::{File, OpenOptions}; use std::io; use std::io::prelude::*; use std::os::unix; use std::path::Path; // A simple implementation of `% cat path` fn cat(path: &Path) -> io::Result<String> { let mut f = try!(File::open(path)); let mut s = String::new(); match f.read_to_string(&mut s) { Ok(_) => Ok(s), Err(e) => Err(e), } } // A simple implementation of `% echo s > path` fn echo(s: &str, path: &Path) -> io::Result<()> { let mut f = try!(File::create(path)); f.write_all(s.as_bytes()) } // A simple implementation of `% touch path` (ignores existing files) fn touch(path: &Path) -> io::Result<()> { match OpenOptions::new().create(true).write(true).open(path) { Ok(_) => Ok(()),
atch fs::create_dir("a") { Err(why) => println!("! {:?}", why.kind()), Ok(_) => {}, } println!("`echo hello > a/b.txt`"); // The previous match can be simplified using the `unwrap_or_else` method echo("hello", &Path::new("a/b.txt")).unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`mkdir -p a/c/d`"); // Recursively create a directory, returns `io::Result<()>` fs::create_dir_all("a/c/d").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`touch a/c/e.txt`"); touch(&Path::new("a/c/e.txt")).unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`ln -s ../b.txt a/c/b.txt`"); // Create a symbolinc link, returns `io::Result<()>` if cfg!(target_family = "unix") { unix::fs::symlink("../b.txt", "a/c/b.txt").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); } println!("`cat a/c/b.txt`"); match cat(&Path::new("a/c/b.txt")) { Err(why) => println!("! {:?}", why.kind()), Ok(s) => println!("> {}", s), } println!("`ls a`"); // Read the constants of a directory, return `io::Result<Vec<Path>>` match fs::read_dir("a") { Err(why) => println!("! {:?}", why.kind()), Ok(paths) => for path in paths { println!("> {:?}", path.unwrap().path()); }, } println!("`rm a/c/e.txt`"); // Remove a file, returns `io::Result<()>` fs::remove_file("a/c/e.txt").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`rmdir a/c/d`"); // Remove an empty directory, returns `io::Result<()>` fs::remove_dir("a/c/d").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); }
Err(e) => Err(e), } } fn main() { println!("`mkdir a`"); // Create a directory, returns `io::Result<()>` m
identifier_body
fs.rs
/* Rust - Std Misc Filesystem Operation Licence : GNU GPL v3 or later Author : Aurélien DESBRIÈRES Mail : aurelien(at)hackers(dot)camp Created on : June 2017 Write with Emacs-nox ───────────────┐ Rust ───────────────────────────────┘ */ // fs.rs use std::fs; use std::fs::{File, OpenOptions}; use std::io; use std::io::prelude::*; use std::os::unix; use std::path::Path; // A simple implementation of `% cat path` fn cat(path: &Path) -> io::Result<String> { let mut f = try!(File::open(path)); let mut s = String::new(); match f.read_to_string(&mut s) { Ok(_) => Ok(s), Err(e) => Err(e), } } // A simple implementation of `% echo s > path` fn echo(s: &str, path: &Path) -> io::Result<()> { let mut f = try!(File::create(path)); f.write_all(s.as_bytes()) } // A simple implementation of `% touch path` (ignores existing files) fn touch(path: &Path) -> io::Result<()> { match OpenOptions::new().create(true).write(true).open(
{ Ok(_) => Ok(()), Err(e) => Err(e), } } fn main() { println!("`mkdir a`"); // Create a directory, returns `io::Result<()>` match fs::create_dir("a") { Err(why) => println!("! {:?}", why.kind()), Ok(_) => {}, } println!("`echo hello > a/b.txt`"); // The previous match can be simplified using the `unwrap_or_else` method echo("hello", &Path::new("a/b.txt")).unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`mkdir -p a/c/d`"); // Recursively create a directory, returns `io::Result<()>` fs::create_dir_all("a/c/d").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`touch a/c/e.txt`"); touch(&Path::new("a/c/e.txt")).unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`ln -s ../b.txt a/c/b.txt`"); // Create a symbolinc link, returns `io::Result<()>` if cfg!(target_family = "unix") { unix::fs::symlink("../b.txt", "a/c/b.txt").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); } println!("`cat a/c/b.txt`"); match cat(&Path::new("a/c/b.txt")) { Err(why) => println!("! {:?}", why.kind()), Ok(s) => println!("> {}", s), } println!("`ls a`"); // Read the constants of a directory, return `io::Result<Vec<Path>>` match fs::read_dir("a") { Err(why) => println!("! {:?}", why.kind()), Ok(paths) => for path in paths { println!("> {:?}", path.unwrap().path()); }, } println!("`rm a/c/e.txt`"); // Remove a file, returns `io::Result<()>` fs::remove_file("a/c/e.txt").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); println!("`rmdir a/c/d`"); // Remove an empty directory, returns `io::Result<()>` fs::remove_dir("a/c/d").unwrap_or_else(|why| { println!("! {:?}", why.kind()); }); }
path)
identifier_name
summary.py
#!/usr/bin/python -u #---------------------------------------------------------------------------- # Summarizes a twogtp tournament. # # TODO: - Simplify stuff. The table idea seems bad, in retrospect. # - Do we really care about which openings are won/lost? import os, sys, getopt, re, string from statistics import Statistics #---------------------------------------------------------------------------- def get_value(table, key): if (table.has_key(key)): return table[key] return 0 def add_if_new(list, value): if (list.count(value)==0): list.append(value) # Yes, I'm using globals. Yes, I'm lazy. gamelen = Statistics() elapsedP1 = Statistics() elapsedP2 = Statistics() p1Overtime = Statistics() p2Overtime = Statistics() p1Wins = Statistics() p1WinsBlack = Statistics() p1WinsWhite = Statistics() def analyzeTourney(fname, longOpening, maxvalid, showTable, plotScore, timeLimit, validOpenings):
# for k in sorted(table.keys()): # print k, table[k] def showIterativeResults(numvalid, table, opencount, openings, progs, showTable, p1Timeouts, p2Timeouts): if showTable: print "+-------------+--------+-------+-------+" print "+ OPENING | COUNT | p1 | p2 |" print "+-------------+--------+-------+-------+" b1w = 0 b1l = 0 b2w = 0 b2l = 0 openings.sort() for o in openings: cb1w = get_value(table, (o, 'B', progs[0], 'win')) cb1l = get_value(table, (o, 'B', progs[0], 'loss')) cb2w = get_value(table, (o, 'B', progs[1], 'win')) cb2l = get_value(table, (o, 'B', progs[1], 'loss')) b1w = b1w + cb1w b1l = b1l + cb1l b2w = b2w + cb2w b2l = b2l + cb2l if showTable: print "|%s \t\t%4d\t%3i/%i\t%3i/%i |" % \ (o, opencount[o], cb1w, cb1l, cb2w, cb2l) if showTable: print "+--------------------------------------+" print "| \t\t \t%3i/%i\t%3i/%i |" % (b1w, b1l, b2w, b2l) print "+--------------------------------------+" if (numvalid != 0): print print "===========================================================" print " NumGames: " + str(numvalid) print " GameLen: " + gamelen.dump() print " p1Time: " + elapsedP1.dump() print " p2Time: " + elapsedP2.dump() print "-----------------------------------------------------------" print "Statistics for " + progs[0] + ":" print " All Wins: %.1f%% (+-%.1f)" % \ (p1Wins.mean()*100.0, p1Wins.stderror()*100.0) print " As Black: %.1f%% (+-%.1f)" % \ (p1WinsBlack.mean()*100.0, p1WinsBlack.stderror()*100.0) print " As White: %.1f%% (+-%.1f)" % \ (p1WinsWhite.mean()*100.0, p1WinsWhite.stderror()*100.0) if ((p1Timeouts > 0) or (p2Timeouts > 0)): print "-----------------------------------------------------------" print "Timeouts for " + progs[0] + ": %i/%i, %.1f (+-%.1f) max=%.1f" % \ (p1Timeouts, p1Wins.sum(), p1Overtime.mean(), p1Overtime.stderror(), p1Overtime.max()) print "Timeouts for " + progs[1] + ": %i/%i, %.1f (+-%.1f) max=%.1f" % \ (p2Timeouts, p1Wins.count() - p1Wins.sum(), p2Overtime.mean(), p2Overtime.stderror(), p2Overtime.max()) print "===========================================================" else: print "No valid games." #------------------------------------------------------------------------------ def usage(): print "Usage: ./summary [--count c] [--showTable] [--time max time] --openings [openings file] --file [tournament.result]" sys.exit(-1) def main(): count = 50000 timeLimit = 123456.789 longOpening = False showTable = False plotScore = False resfile = "" openingsFile = "" openings = [] try: options = "clr:sf:" longOptions = ["count=","long","showTable","plot","file=", "time=","openings="] opts, args = getopt.getopt(sys.argv[1:], options, longOptions) except getopt.GetoptError: usage() for o, v in opts: if o in ("--count", "-c"): count = int(v) elif o in ("--file", "-f"): resfile = v elif o in ("--time", "-t"): timeLimit = float(v) elif o in ("--long"): longOpening = True elif o in ("--plot"): plotScore = True elif o in ("--openings"): openingsFile = v elif o in ("--showTable"): showTable = True if (resfile == ""): usage() if (openingsFile != ""): f = open(openingsFile, 'r') lines = f.readlines() f.close() for line in lines: openings.append(string.strip(line)) analyzeTourney(resfile, longOpening, count, showTable, plotScore, timeLimit, openings) main()
print "Analyzing: \'" + fname + "\'..." if plotScore: pf = open("plot.dat", "w") f = open(fname, "r") line = f.readline() linenum = 1 numvalid = 0 table = {} opencount = {} openings = [] progs = [] p1Timeouts = 0.0 p2Timeouts = 0.0 while line != "": if line[0] != "#": array = string.split(line, "\t") fullopening = array[2] black = array[3] white = array[4] bres = array[5] wres = array[6] length = array[7] timeBlack = float(array[8]) timeWhite = float(array[9]) if longOpening: opening = string.strip(fullopening) else: moves = string.split(string.strip(fullopening), ' ') opening = moves[0] considerGame = True if (validOpenings != []): if (not opening in validOpenings): considerGame = False # TODO: check that results are of the form "C+", where C # is one of 'B' or 'W', instead of just checking the first # character. if (not considerGame): print "Game not in valid openings" elif ((numvalid < maxvalid) and (bres == wres) and ((bres[0] == 'B') or (bres[0] == 'W'))): add_if_new(openings, opening) add_if_new(progs, black) add_if_new(progs, white) colors = ['B', 'W'] names = [black, white] winner = names[colors.index(bres[0])] valueForP1 = 0.0 if (winner == progs[0]): valueForP1 = 1.0 if (((timeBlack > timeLimit) and (bres[0] == 'B')) or ((timeWhite > timeLimit) and (bres[0] == 'W'))): overtime = 0.0 if (bres[0] == 'B'): overtime = timeBlack - timeLimit else: overtime = timeWhite - timeLimit if (winner == progs[0]): p1Timeouts = p1Timeouts + 1.0 p1Overtime.add(overtime) else: p2Timeouts = p2Timeouts + 1.0 p2Overtime.add(overtime) gamelen.add(float(length)) p1Wins.add(valueForP1) if (plotScore): print >> pf, str(p1Wins.count()) + "\t" + str(p1Wins.mean()) + "\t" + str(p1Wins.stderror()) if (progs[0] == black): p1WinsBlack.add(valueForP1) else: p1WinsWhite.add(valueForP1) if (progs[0] == black): elapsedP1.add(float(timeBlack)) elapsedP2.add(float(timeWhite)) else: elapsedP1.add(float(timeWhite)) elapsedP2.add(float(timeBlack)) opencount[opening] = get_value(opencount, opening) + 1 for color in colors: who = names[colors.index(color)] if (bres[0] == color): key = opening, color, who, 'win' table[key] = get_value(table, key) + 1 else: key = opening, color, who, 'loss' table[key] = get_value(table, key) + 1 numvalid = numvalid + 1 elif (numvalid >= maxvalid): print "Line " + str(linenum) + ": Past max game limit." else: print "Line " + str(linenum) + ": Ignoring bad game result." line = f.readline() linenum = linenum+1 f.close() if (plotScore): pf.close() print "" for p in progs: print "p" + str(progs.index(p)+1)+ " = " + p showIterativeResults(numvalid, table, opencount, openings, progs, showTable, p1Timeouts, p2Timeouts)
identifier_body
summary.py
#!/usr/bin/python -u #---------------------------------------------------------------------------- # Summarizes a twogtp tournament. # # TODO: - Simplify stuff. The table idea seems bad, in retrospect. # - Do we really care about which openings are won/lost? import os, sys, getopt, re, string from statistics import Statistics #---------------------------------------------------------------------------- def get_value(table, key): if (table.has_key(key)): return table[key] return 0 def add_if_new(list, value): if (list.count(value)==0): list.append(value) # Yes, I'm using globals. Yes, I'm lazy. gamelen = Statistics() elapsedP1 = Statistics() elapsedP2 = Statistics() p1Overtime = Statistics() p2Overtime = Statistics() p1Wins = Statistics() p1WinsBlack = Statistics() p1WinsWhite = Statistics() def analyzeTourney(fname, longOpening, maxvalid, showTable, plotScore, timeLimit, validOpenings): print "Analyzing: \'" + fname + "\'..." if plotScore: pf = open("plot.dat", "w") f = open(fname, "r") line = f.readline() linenum = 1 numvalid = 0 table = {} opencount = {} openings = [] progs = [] p1Timeouts = 0.0 p2Timeouts = 0.0 while line != "": if line[0] != "#": array = string.split(line, "\t") fullopening = array[2] black = array[3] white = array[4] bres = array[5] wres = array[6] length = array[7] timeBlack = float(array[8]) timeWhite = float(array[9]) if longOpening: opening = string.strip(fullopening) else: moves = string.split(string.strip(fullopening), ' ') opening = moves[0] considerGame = True if (validOpenings != []): if (not opening in validOpenings): considerGame = False # TODO: check that results are of the form "C+", where C # is one of 'B' or 'W', instead of just checking the first # character. if (not considerGame): print "Game not in valid openings" elif ((numvalid < maxvalid) and (bres == wres) and ((bres[0] == 'B') or (bres[0] == 'W'))): add_if_new(openings, opening) add_if_new(progs, black) add_if_new(progs, white) colors = ['B', 'W'] names = [black, white] winner = names[colors.index(bres[0])] valueForP1 = 0.0 if (winner == progs[0]): valueForP1 = 1.0 if (((timeBlack > timeLimit) and (bres[0] == 'B')) or ((timeWhite > timeLimit) and (bres[0] == 'W'))): overtime = 0.0 if (bres[0] == 'B'): overtime = timeBlack - timeLimit else: overtime = timeWhite - timeLimit if (winner == progs[0]): p1Timeouts = p1Timeouts + 1.0 p1Overtime.add(overtime) else: p2Timeouts = p2Timeouts + 1.0 p2Overtime.add(overtime) gamelen.add(float(length)) p1Wins.add(valueForP1) if (plotScore): print >> pf, str(p1Wins.count()) + "\t" + str(p1Wins.mean()) + "\t" + str(p1Wins.stderror()) if (progs[0] == black): p1WinsBlack.add(valueForP1) else: p1WinsWhite.add(valueForP1) if (progs[0] == black): elapsedP1.add(float(timeBlack)) elapsedP2.add(float(timeWhite)) else: elapsedP1.add(float(timeWhite)) elapsedP2.add(float(timeBlack)) opencount[opening] = get_value(opencount, opening) + 1 for color in colors: who = names[colors.index(color)] if (bres[0] == color): key = opening, color, who, 'win' table[key] = get_value(table, key) + 1 else: key = opening, color, who, 'loss' table[key] = get_value(table, key) + 1 numvalid = numvalid + 1 elif (numvalid >= maxvalid): print "Line " + str(linenum) + ": Past max game limit." else: print "Line " + str(linenum) + ": Ignoring bad game result." line = f.readline() linenum = linenum+1 f.close() if (plotScore): pf.close() print "" for p in progs: print "p" + str(progs.index(p)+1)+ " = " + p showIterativeResults(numvalid, table, opencount, openings, progs, showTable, p1Timeouts, p2Timeouts) # for k in sorted(table.keys()): # print k, table[k] def showIterativeResults(numvalid, table, opencount, openings, progs, showTable, p1Timeouts, p2Timeouts): if showTable: print "+-------------+--------+-------+-------+" print "+ OPENING | COUNT | p1 | p2 |" print "+-------------+--------+-------+-------+" b1w = 0 b1l = 0 b2w = 0 b2l = 0 openings.sort() for o in openings: cb1w = get_value(table, (o, 'B', progs[0], 'win')) cb1l = get_value(table, (o, 'B', progs[0], 'loss')) cb2w = get_value(table, (o, 'B', progs[1], 'win')) cb2l = get_value(table, (o, 'B', progs[1], 'loss')) b1w = b1w + cb1w b1l = b1l + cb1l b2w = b2w + cb2w b2l = b2l + cb2l if showTable: print "|%s \t\t%4d\t%3i/%i\t%3i/%i |" % \ (o, opencount[o], cb1w, cb1l, cb2w, cb2l) if showTable: print "+--------------------------------------+" print "| \t\t \t%3i/%i\t%3i/%i |" % (b1w, b1l, b2w, b2l) print "+--------------------------------------+" if (numvalid != 0): print print "===========================================================" print " NumGames: " + str(numvalid) print " GameLen: " + gamelen.dump() print " p1Time: " + elapsedP1.dump() print " p2Time: " + elapsedP2.dump() print "-----------------------------------------------------------" print "Statistics for " + progs[0] + ":" print " All Wins: %.1f%% (+-%.1f)" % \ (p1Wins.mean()*100.0, p1Wins.stderror()*100.0) print " As Black: %.1f%% (+-%.1f)" % \ (p1WinsBlack.mean()*100.0, p1WinsBlack.stderror()*100.0) print " As White: %.1f%% (+-%.1f)" % \ (p1WinsWhite.mean()*100.0, p1WinsWhite.stderror()*100.0) if ((p1Timeouts > 0) or (p2Timeouts > 0)): print "-----------------------------------------------------------" print "Timeouts for " + progs[0] + ": %i/%i, %.1f (+-%.1f) max=%.1f" % \ (p1Timeouts, p1Wins.sum(), p1Overtime.mean(), p1Overtime.stderror(), p1Overtime.max()) print "Timeouts for " + progs[1] + ": %i/%i, %.1f (+-%.1f) max=%.1f" % \ (p2Timeouts, p1Wins.count() - p1Wins.sum(), p2Overtime.mean(), p2Overtime.stderror(), p2Overtime.max()) print "===========================================================" else: print "No valid games." #------------------------------------------------------------------------------ def usage(): print "Usage: ./summary [--count c] [--showTable] [--time max time] --openings [openings file] --file [tournament.result]" sys.exit(-1) def
(): count = 50000 timeLimit = 123456.789 longOpening = False showTable = False plotScore = False resfile = "" openingsFile = "" openings = [] try: options = "clr:sf:" longOptions = ["count=","long","showTable","plot","file=", "time=","openings="] opts, args = getopt.getopt(sys.argv[1:], options, longOptions) except getopt.GetoptError: usage() for o, v in opts: if o in ("--count", "-c"): count = int(v) elif o in ("--file", "-f"): resfile = v elif o in ("--time", "-t"): timeLimit = float(v) elif o in ("--long"): longOpening = True elif o in ("--plot"): plotScore = True elif o in ("--openings"): openingsFile = v elif o in ("--showTable"): showTable = True if (resfile == ""): usage() if (openingsFile != ""): f = open(openingsFile, 'r') lines = f.readlines() f.close() for line in lines: openings.append(string.strip(line)) analyzeTourney(resfile, longOpening, count, showTable, plotScore, timeLimit, openings) main()
main
identifier_name
summary.py
#!/usr/bin/python -u #---------------------------------------------------------------------------- # Summarizes a twogtp tournament. # # TODO: - Simplify stuff. The table idea seems bad, in retrospect. # - Do we really care about which openings are won/lost? import os, sys, getopt, re, string from statistics import Statistics #---------------------------------------------------------------------------- def get_value(table, key): if (table.has_key(key)): return table[key] return 0 def add_if_new(list, value): if (list.count(value)==0): list.append(value) # Yes, I'm using globals. Yes, I'm lazy. gamelen = Statistics() elapsedP1 = Statistics() elapsedP2 = Statistics() p1Overtime = Statistics() p2Overtime = Statistics() p1Wins = Statistics() p1WinsBlack = Statistics() p1WinsWhite = Statistics() def analyzeTourney(fname, longOpening, maxvalid, showTable, plotScore, timeLimit, validOpenings): print "Analyzing: \'" + fname + "\'..." if plotScore: pf = open("plot.dat", "w")
table = {} opencount = {} openings = [] progs = [] p1Timeouts = 0.0 p2Timeouts = 0.0 while line != "": if line[0] != "#": array = string.split(line, "\t") fullopening = array[2] black = array[3] white = array[4] bres = array[5] wres = array[6] length = array[7] timeBlack = float(array[8]) timeWhite = float(array[9]) if longOpening: opening = string.strip(fullopening) else: moves = string.split(string.strip(fullopening), ' ') opening = moves[0] considerGame = True if (validOpenings != []): if (not opening in validOpenings): considerGame = False # TODO: check that results are of the form "C+", where C # is one of 'B' or 'W', instead of just checking the first # character. if (not considerGame): print "Game not in valid openings" elif ((numvalid < maxvalid) and (bres == wres) and ((bres[0] == 'B') or (bres[0] == 'W'))): add_if_new(openings, opening) add_if_new(progs, black) add_if_new(progs, white) colors = ['B', 'W'] names = [black, white] winner = names[colors.index(bres[0])] valueForP1 = 0.0 if (winner == progs[0]): valueForP1 = 1.0 if (((timeBlack > timeLimit) and (bres[0] == 'B')) or ((timeWhite > timeLimit) and (bres[0] == 'W'))): overtime = 0.0 if (bres[0] == 'B'): overtime = timeBlack - timeLimit else: overtime = timeWhite - timeLimit if (winner == progs[0]): p1Timeouts = p1Timeouts + 1.0 p1Overtime.add(overtime) else: p2Timeouts = p2Timeouts + 1.0 p2Overtime.add(overtime) gamelen.add(float(length)) p1Wins.add(valueForP1) if (plotScore): print >> pf, str(p1Wins.count()) + "\t" + str(p1Wins.mean()) + "\t" + str(p1Wins.stderror()) if (progs[0] == black): p1WinsBlack.add(valueForP1) else: p1WinsWhite.add(valueForP1) if (progs[0] == black): elapsedP1.add(float(timeBlack)) elapsedP2.add(float(timeWhite)) else: elapsedP1.add(float(timeWhite)) elapsedP2.add(float(timeBlack)) opencount[opening] = get_value(opencount, opening) + 1 for color in colors: who = names[colors.index(color)] if (bres[0] == color): key = opening, color, who, 'win' table[key] = get_value(table, key) + 1 else: key = opening, color, who, 'loss' table[key] = get_value(table, key) + 1 numvalid = numvalid + 1 elif (numvalid >= maxvalid): print "Line " + str(linenum) + ": Past max game limit." else: print "Line " + str(linenum) + ": Ignoring bad game result." line = f.readline() linenum = linenum+1 f.close() if (plotScore): pf.close() print "" for p in progs: print "p" + str(progs.index(p)+1)+ " = " + p showIterativeResults(numvalid, table, opencount, openings, progs, showTable, p1Timeouts, p2Timeouts) # for k in sorted(table.keys()): # print k, table[k] def showIterativeResults(numvalid, table, opencount, openings, progs, showTable, p1Timeouts, p2Timeouts): if showTable: print "+-------------+--------+-------+-------+" print "+ OPENING | COUNT | p1 | p2 |" print "+-------------+--------+-------+-------+" b1w = 0 b1l = 0 b2w = 0 b2l = 0 openings.sort() for o in openings: cb1w = get_value(table, (o, 'B', progs[0], 'win')) cb1l = get_value(table, (o, 'B', progs[0], 'loss')) cb2w = get_value(table, (o, 'B', progs[1], 'win')) cb2l = get_value(table, (o, 'B', progs[1], 'loss')) b1w = b1w + cb1w b1l = b1l + cb1l b2w = b2w + cb2w b2l = b2l + cb2l if showTable: print "|%s \t\t%4d\t%3i/%i\t%3i/%i |" % \ (o, opencount[o], cb1w, cb1l, cb2w, cb2l) if showTable: print "+--------------------------------------+" print "| \t\t \t%3i/%i\t%3i/%i |" % (b1w, b1l, b2w, b2l) print "+--------------------------------------+" if (numvalid != 0): print print "===========================================================" print " NumGames: " + str(numvalid) print " GameLen: " + gamelen.dump() print " p1Time: " + elapsedP1.dump() print " p2Time: " + elapsedP2.dump() print "-----------------------------------------------------------" print "Statistics for " + progs[0] + ":" print " All Wins: %.1f%% (+-%.1f)" % \ (p1Wins.mean()*100.0, p1Wins.stderror()*100.0) print " As Black: %.1f%% (+-%.1f)" % \ (p1WinsBlack.mean()*100.0, p1WinsBlack.stderror()*100.0) print " As White: %.1f%% (+-%.1f)" % \ (p1WinsWhite.mean()*100.0, p1WinsWhite.stderror()*100.0) if ((p1Timeouts > 0) or (p2Timeouts > 0)): print "-----------------------------------------------------------" print "Timeouts for " + progs[0] + ": %i/%i, %.1f (+-%.1f) max=%.1f" % \ (p1Timeouts, p1Wins.sum(), p1Overtime.mean(), p1Overtime.stderror(), p1Overtime.max()) print "Timeouts for " + progs[1] + ": %i/%i, %.1f (+-%.1f) max=%.1f" % \ (p2Timeouts, p1Wins.count() - p1Wins.sum(), p2Overtime.mean(), p2Overtime.stderror(), p2Overtime.max()) print "===========================================================" else: print "No valid games." #------------------------------------------------------------------------------ def usage(): print "Usage: ./summary [--count c] [--showTable] [--time max time] --openings [openings file] --file [tournament.result]" sys.exit(-1) def main(): count = 50000 timeLimit = 123456.789 longOpening = False showTable = False plotScore = False resfile = "" openingsFile = "" openings = [] try: options = "clr:sf:" longOptions = ["count=","long","showTable","plot","file=", "time=","openings="] opts, args = getopt.getopt(sys.argv[1:], options, longOptions) except getopt.GetoptError: usage() for o, v in opts: if o in ("--count", "-c"): count = int(v) elif o in ("--file", "-f"): resfile = v elif o in ("--time", "-t"): timeLimit = float(v) elif o in ("--long"): longOpening = True elif o in ("--plot"): plotScore = True elif o in ("--openings"): openingsFile = v elif o in ("--showTable"): showTable = True if (resfile == ""): usage() if (openingsFile != ""): f = open(openingsFile, 'r') lines = f.readlines() f.close() for line in lines: openings.append(string.strip(line)) analyzeTourney(resfile, longOpening, count, showTable, plotScore, timeLimit, openings) main()
f = open(fname, "r") line = f.readline() linenum = 1 numvalid = 0
random_line_split
summary.py
#!/usr/bin/python -u #---------------------------------------------------------------------------- # Summarizes a twogtp tournament. # # TODO: - Simplify stuff. The table idea seems bad, in retrospect. # - Do we really care about which openings are won/lost? import os, sys, getopt, re, string from statistics import Statistics #---------------------------------------------------------------------------- def get_value(table, key): if (table.has_key(key)): return table[key] return 0 def add_if_new(list, value): if (list.count(value)==0): list.append(value) # Yes, I'm using globals. Yes, I'm lazy. gamelen = Statistics() elapsedP1 = Statistics() elapsedP2 = Statistics() p1Overtime = Statistics() p2Overtime = Statistics() p1Wins = Statistics() p1WinsBlack = Statistics() p1WinsWhite = Statistics() def analyzeTourney(fname, longOpening, maxvalid, showTable, plotScore, timeLimit, validOpenings): print "Analyzing: \'" + fname + "\'..." if plotScore: pf = open("plot.dat", "w") f = open(fname, "r") line = f.readline() linenum = 1 numvalid = 0 table = {} opencount = {} openings = [] progs = [] p1Timeouts = 0.0 p2Timeouts = 0.0 while line != "": if line[0] != "#": array = string.split(line, "\t") fullopening = array[2] black = array[3] white = array[4] bres = array[5] wres = array[6] length = array[7] timeBlack = float(array[8]) timeWhite = float(array[9]) if longOpening: opening = string.strip(fullopening) else: moves = string.split(string.strip(fullopening), ' ') opening = moves[0] considerGame = True if (validOpenings != []): if (not opening in validOpenings): considerGame = False # TODO: check that results are of the form "C+", where C # is one of 'B' or 'W', instead of just checking the first # character. if (not considerGame): print "Game not in valid openings" elif ((numvalid < maxvalid) and (bres == wres) and ((bres[0] == 'B') or (bres[0] == 'W'))): add_if_new(openings, opening) add_if_new(progs, black) add_if_new(progs, white) colors = ['B', 'W'] names = [black, white] winner = names[colors.index(bres[0])] valueForP1 = 0.0 if (winner == progs[0]): valueForP1 = 1.0 if (((timeBlack > timeLimit) and (bres[0] == 'B')) or ((timeWhite > timeLimit) and (bres[0] == 'W'))): overtime = 0.0 if (bres[0] == 'B'): overtime = timeBlack - timeLimit else: overtime = timeWhite - timeLimit if (winner == progs[0]):
else: p2Timeouts = p2Timeouts + 1.0 p2Overtime.add(overtime) gamelen.add(float(length)) p1Wins.add(valueForP1) if (plotScore): print >> pf, str(p1Wins.count()) + "\t" + str(p1Wins.mean()) + "\t" + str(p1Wins.stderror()) if (progs[0] == black): p1WinsBlack.add(valueForP1) else: p1WinsWhite.add(valueForP1) if (progs[0] == black): elapsedP1.add(float(timeBlack)) elapsedP2.add(float(timeWhite)) else: elapsedP1.add(float(timeWhite)) elapsedP2.add(float(timeBlack)) opencount[opening] = get_value(opencount, opening) + 1 for color in colors: who = names[colors.index(color)] if (bres[0] == color): key = opening, color, who, 'win' table[key] = get_value(table, key) + 1 else: key = opening, color, who, 'loss' table[key] = get_value(table, key) + 1 numvalid = numvalid + 1 elif (numvalid >= maxvalid): print "Line " + str(linenum) + ": Past max game limit." else: print "Line " + str(linenum) + ": Ignoring bad game result." line = f.readline() linenum = linenum+1 f.close() if (plotScore): pf.close() print "" for p in progs: print "p" + str(progs.index(p)+1)+ " = " + p showIterativeResults(numvalid, table, opencount, openings, progs, showTable, p1Timeouts, p2Timeouts) # for k in sorted(table.keys()): # print k, table[k] def showIterativeResults(numvalid, table, opencount, openings, progs, showTable, p1Timeouts, p2Timeouts): if showTable: print "+-------------+--------+-------+-------+" print "+ OPENING | COUNT | p1 | p2 |" print "+-------------+--------+-------+-------+" b1w = 0 b1l = 0 b2w = 0 b2l = 0 openings.sort() for o in openings: cb1w = get_value(table, (o, 'B', progs[0], 'win')) cb1l = get_value(table, (o, 'B', progs[0], 'loss')) cb2w = get_value(table, (o, 'B', progs[1], 'win')) cb2l = get_value(table, (o, 'B', progs[1], 'loss')) b1w = b1w + cb1w b1l = b1l + cb1l b2w = b2w + cb2w b2l = b2l + cb2l if showTable: print "|%s \t\t%4d\t%3i/%i\t%3i/%i |" % \ (o, opencount[o], cb1w, cb1l, cb2w, cb2l) if showTable: print "+--------------------------------------+" print "| \t\t \t%3i/%i\t%3i/%i |" % (b1w, b1l, b2w, b2l) print "+--------------------------------------+" if (numvalid != 0): print print "===========================================================" print " NumGames: " + str(numvalid) print " GameLen: " + gamelen.dump() print " p1Time: " + elapsedP1.dump() print " p2Time: " + elapsedP2.dump() print "-----------------------------------------------------------" print "Statistics for " + progs[0] + ":" print " All Wins: %.1f%% (+-%.1f)" % \ (p1Wins.mean()*100.0, p1Wins.stderror()*100.0) print " As Black: %.1f%% (+-%.1f)" % \ (p1WinsBlack.mean()*100.0, p1WinsBlack.stderror()*100.0) print " As White: %.1f%% (+-%.1f)" % \ (p1WinsWhite.mean()*100.0, p1WinsWhite.stderror()*100.0) if ((p1Timeouts > 0) or (p2Timeouts > 0)): print "-----------------------------------------------------------" print "Timeouts for " + progs[0] + ": %i/%i, %.1f (+-%.1f) max=%.1f" % \ (p1Timeouts, p1Wins.sum(), p1Overtime.mean(), p1Overtime.stderror(), p1Overtime.max()) print "Timeouts for " + progs[1] + ": %i/%i, %.1f (+-%.1f) max=%.1f" % \ (p2Timeouts, p1Wins.count() - p1Wins.sum(), p2Overtime.mean(), p2Overtime.stderror(), p2Overtime.max()) print "===========================================================" else: print "No valid games." #------------------------------------------------------------------------------ def usage(): print "Usage: ./summary [--count c] [--showTable] [--time max time] --openings [openings file] --file [tournament.result]" sys.exit(-1) def main(): count = 50000 timeLimit = 123456.789 longOpening = False showTable = False plotScore = False resfile = "" openingsFile = "" openings = [] try: options = "clr:sf:" longOptions = ["count=","long","showTable","plot","file=", "time=","openings="] opts, args = getopt.getopt(sys.argv[1:], options, longOptions) except getopt.GetoptError: usage() for o, v in opts: if o in ("--count", "-c"): count = int(v) elif o in ("--file", "-f"): resfile = v elif o in ("--time", "-t"): timeLimit = float(v) elif o in ("--long"): longOpening = True elif o in ("--plot"): plotScore = True elif o in ("--openings"): openingsFile = v elif o in ("--showTable"): showTable = True if (resfile == ""): usage() if (openingsFile != ""): f = open(openingsFile, 'r') lines = f.readlines() f.close() for line in lines: openings.append(string.strip(line)) analyzeTourney(resfile, longOpening, count, showTable, plotScore, timeLimit, openings) main()
p1Timeouts = p1Timeouts + 1.0 p1Overtime.add(overtime)
conditional_block
main.js
import React from 'react'; import {render} from 'react-dom'; class StaffList extends React.Component { render() { console.log(this.props); var stafflist = Object.values(this.props.staffs).map(staffObject => <Staff staffObject = {JSON.parse(staffObject)}/> ); return( <table> <thead> <tr> <th><center>IDNumber</center></th> <th><center>PersonName</center></th> <th><center>ShiftHours</center></th> <th><center>Position</center></th> </tr> </thead> <tbody> {stafflist} </tbody> </table> ); } } var ControllerButton = { deleteStaff: function(id){ $.ajax({ method: "DELETE", async: false, url: "./api/staff/" + id, }).done(function(msg) { console.log(msg); render(<View />, document.getElementById('target')); }); } }; class Staff extends React.Component { render() { return( <tr id={"staff-"+this.props.staffObject['IDNumber']}> <td><center>{this.props.staffObject['IDNumber']}</center></td> <td><center>{this.props.staffObject['PersonName']}</center></td> <td><center>{this.props.staffObject['ShiftHours']}</center></td> <td><center>{this.props.staffObject['Position']}</center></td> <td><center><a onClick={ControllerButton.deleteStaff.bind(this, this.props.staffObject['IDNumber'])}>Delete</a></center></td> </tr> ); } } class View extends React.Component { getStaffList() { var list = {}; $.ajax({ method: "GET", async: false, url: "./api/staff", }).done(function(msg) { console.log(msg); list = JSON.parse(msg); });
render() { return( <StaffList staffs = {this.getStaffList()} /> ); } } render(<View />, document.getElementById('target'));
return list; }
random_line_split
main.js
import React from 'react'; import {render} from 'react-dom'; class StaffList extends React.Component {
() { console.log(this.props); var stafflist = Object.values(this.props.staffs).map(staffObject => <Staff staffObject = {JSON.parse(staffObject)}/> ); return( <table> <thead> <tr> <th><center>IDNumber</center></th> <th><center>PersonName</center></th> <th><center>ShiftHours</center></th> <th><center>Position</center></th> </tr> </thead> <tbody> {stafflist} </tbody> </table> ); } } var ControllerButton = { deleteStaff: function(id){ $.ajax({ method: "DELETE", async: false, url: "./api/staff/" + id, }).done(function(msg) { console.log(msg); render(<View />, document.getElementById('target')); }); } }; class Staff extends React.Component { render() { return( <tr id={"staff-"+this.props.staffObject['IDNumber']}> <td><center>{this.props.staffObject['IDNumber']}</center></td> <td><center>{this.props.staffObject['PersonName']}</center></td> <td><center>{this.props.staffObject['ShiftHours']}</center></td> <td><center>{this.props.staffObject['Position']}</center></td> <td><center><a onClick={ControllerButton.deleteStaff.bind(this, this.props.staffObject['IDNumber'])}>Delete</a></center></td> </tr> ); } } class View extends React.Component { getStaffList() { var list = {}; $.ajax({ method: "GET", async: false, url: "./api/staff", }).done(function(msg) { console.log(msg); list = JSON.parse(msg); }); return list; } render() { return( <StaffList staffs = {this.getStaffList()} /> ); } } render(<View />, document.getElementById('target'));
render
identifier_name
boaview.py
#!/usr/bin/env python3 import sys import click from boadata import __version__ from boadata.cli import try_load, try_apply_sql, qt_app
@click.argument("uri") @click.option("-s", "--sql", required=False, help="SQL to run on the object.") @click.option("-t", "--type", default=None, help="What type is the object.") @click.option("-p", "--parameter", help="Additional parameters for loader, specified as key=value", multiple=True) def run_app(uri, type, parameter, **kwargs): kwargs = {key: value for key, value in kwargs.items() if value is not None} do = try_load(uri, type, parameters=parameter) do = try_apply_sql(do, kwargs) with qt_app(): from boadata.gui.qt import DataObjectWindow window = DataObjectWindow(do) window.show() window.setWindowTitle(do.uri) if __name__ == "__main__": run_app()
@click.command() @click.version_option(__version__)
random_line_split
boaview.py
#!/usr/bin/env python3 import sys import click from boadata import __version__ from boadata.cli import try_load, try_apply_sql, qt_app @click.command() @click.version_option(__version__) @click.argument("uri") @click.option("-s", "--sql", required=False, help="SQL to run on the object.") @click.option("-t", "--type", default=None, help="What type is the object.") @click.option("-p", "--parameter", help="Additional parameters for loader, specified as key=value", multiple=True) def run_app(uri, type, parameter, **kwargs):
if __name__ == "__main__": run_app()
kwargs = {key: value for key, value in kwargs.items() if value is not None} do = try_load(uri, type, parameters=parameter) do = try_apply_sql(do, kwargs) with qt_app(): from boadata.gui.qt import DataObjectWindow window = DataObjectWindow(do) window.show() window.setWindowTitle(do.uri)
identifier_body
boaview.py
#!/usr/bin/env python3 import sys import click from boadata import __version__ from boadata.cli import try_load, try_apply_sql, qt_app @click.command() @click.version_option(__version__) @click.argument("uri") @click.option("-s", "--sql", required=False, help="SQL to run on the object.") @click.option("-t", "--type", default=None, help="What type is the object.") @click.option("-p", "--parameter", help="Additional parameters for loader, specified as key=value", multiple=True) def run_app(uri, type, parameter, **kwargs): kwargs = {key: value for key, value in kwargs.items() if value is not None} do = try_load(uri, type, parameters=parameter) do = try_apply_sql(do, kwargs) with qt_app(): from boadata.gui.qt import DataObjectWindow window = DataObjectWindow(do) window.show() window.setWindowTitle(do.uri) if __name__ == "__main__":
run_app()
conditional_block
boaview.py
#!/usr/bin/env python3 import sys import click from boadata import __version__ from boadata.cli import try_load, try_apply_sql, qt_app @click.command() @click.version_option(__version__) @click.argument("uri") @click.option("-s", "--sql", required=False, help="SQL to run on the object.") @click.option("-t", "--type", default=None, help="What type is the object.") @click.option("-p", "--parameter", help="Additional parameters for loader, specified as key=value", multiple=True) def
(uri, type, parameter, **kwargs): kwargs = {key: value for key, value in kwargs.items() if value is not None} do = try_load(uri, type, parameters=parameter) do = try_apply_sql(do, kwargs) with qt_app(): from boadata.gui.qt import DataObjectWindow window = DataObjectWindow(do) window.show() window.setWindowTitle(do.uri) if __name__ == "__main__": run_app()
run_app
identifier_name
gradients.js
#!/usr/bin/env node-canvas /*jslint indent: 2, node: true */ "use strict"; var Canvas = require('../lib/canvas'); var canvas = new Canvas(320, 320); var ctx = canvas.getContext('2d'); var fs = require('fs'); var eu = require('./util'); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.scale(3, 3); // Create gradients var lingrad = ctx.createLinearGradient(0, 0, 0, 150); lingrad.addColorStop(0, '#00ABEB'); lingrad.addColorStop(0.5, '#fff'); lingrad.addColorStop(0.5, '#26C000'); lingrad.addColorStop(1, '#fff'); var lingrad2 = ctx.createLinearGradient(0, 50, 0, 95); lingrad2.addColorStop(0.5, '#000'); lingrad2.addColorStop(1, 'rgba(0,0,0,0)'); // assign gradients to fill and stroke styles ctx.fillStyle = lingrad; ctx.strokeStyle = lingrad2; // draw shapes ctx.fillRect(10, 10, 130, 130); ctx.strokeRect(50, 50, 50, 50); // Default gradient stops ctx.fillStyle = '#008000'; ctx.fillRect(150, 0, 150, 150); lingrad = ctx.createLinearGradient(150, 0, 300, 150);
ctx.fillRect(0, 150, 150, 150); lingrad = ctx.createRadialGradient(30, 180, 50, 30, 180, 100); lingrad.addColorStop(0, '#00ABEB'); lingrad.addColorStop(0.5, '#fff'); lingrad.addColorStop(0.5, '#26C000'); lingrad.addColorStop(1, '#fff'); ctx.fillStyle = lingrad; ctx.fillRect(10, 160, 130, 130); canvas.vgSwapBuffers(); eu.handleTermination(); eu.waitForInput();
ctx.fillStyle = lingrad; ctx.fillRect(160, 10, 130, 130); // Radial gradients ctx.fillStyle = '#a00000';
random_line_split
__init__.py
# -*- encoding: utf-8 -*- ########################################################################### # Module Writen to OpenERP, Open Source Management Solution # Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>). # All Rights Reserved ###############Credits###################################################### # Coded by: Humberto Arocha humberto@openerp.com.ve # Angelica Barrios angelicaisabelb@gmail.com # Jordi Esteve <jesteve@zikzakmedia.com> # Planified by: Humberto Arocha # Finance by: LUBCAN COL S.A.S http://www.lubcancol.com # Audited by: Humberto Arocha humberto@openerp.com.ve ############################################################################# # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version.
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ############################################################################## import wizard
# # This program is distributed in the hope that it will be useful,
random_line_split
right-to-tradeskill.ts
import { isUndefined } from 'lodash'; import { Command } from '../../../../base/Command'; import { Player } from '../../../../../shared/models/player'; export class RightToTradeskill extends Command { public name = '~RtT'; public format = 'TradeskillSlot TradeskillDestSlot AlchUUID';
(player: Player, { room, args }) { if(this.isBusy(player)) return; const [tsSlot, tsDestSlot, alchUUID] = args.split(' '); if(!tsSlot || isUndefined(tsDestSlot) || !alchUUID) return false; const container = room.state.findNPC(alchUUID); if(!container) return player.sendClientMessage('That person is not here.'); const item = player.rightHand; if(!item) return; const added = this.addItemToContainer(player, player.tradeSkillContainers[tsSlot], item, +tsDestSlot); if(!added) return; player.setRightHand(null); } }
execute
identifier_name
right-to-tradeskill.ts
import { isUndefined } from 'lodash'; import { Command } from '../../../../base/Command'; import { Player } from '../../../../../shared/models/player';
execute(player: Player, { room, args }) { if(this.isBusy(player)) return; const [tsSlot, tsDestSlot, alchUUID] = args.split(' '); if(!tsSlot || isUndefined(tsDestSlot) || !alchUUID) return false; const container = room.state.findNPC(alchUUID); if(!container) return player.sendClientMessage('That person is not here.'); const item = player.rightHand; if(!item) return; const added = this.addItemToContainer(player, player.tradeSkillContainers[tsSlot], item, +tsDestSlot); if(!added) return; player.setRightHand(null); } }
export class RightToTradeskill extends Command { public name = '~RtT'; public format = 'TradeskillSlot TradeskillDestSlot AlchUUID';
random_line_split
loops.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use self::Context::*; use rustc::session::Session; use rustc::hir::map::Map; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::hir::{self, Node, Destination}; use syntax::ast; use syntax_pos::Span; use errors::Applicability; #[derive(Clone, Copy, Debug, PartialEq)] enum LoopKind { Loop(hir::LoopSource), WhileLoop, } impl LoopKind { fn name(self) -> &'static str { match self { LoopKind::Loop(hir::LoopSource::Loop) => "loop", LoopKind::Loop(hir::LoopSource::WhileLet) => "while let", LoopKind::Loop(hir::LoopSource::ForLoop) => "for", LoopKind::WhileLoop => "while", } } } #[derive(Clone, Copy, Debug, PartialEq)] enum Context { Normal, Loop(LoopKind), Closure, LabeledBlock, AnonConst, } #[derive(Copy, Clone)] struct CheckLoopVisitor<'a, 'hir: 'a> { sess: &'a Session, hir_map: &'a Map<'hir>, cx: Context, } pub fn check_crate(sess: &Session, map: &Map) { let krate = map.krate(); krate.visit_all_item_likes(&mut CheckLoopVisitor { sess, hir_map: map, cx: Normal, }.as_deep_visitor()); } impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { fn
<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> { NestedVisitorMap::OnlyBodies(&self.hir_map) } fn visit_item(&mut self, i: &'hir hir::Item) { self.with_context(Normal, |v| intravisit::walk_item(v, i)); } fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) { self.with_context(Normal, |v| intravisit::walk_impl_item(v, i)); } fn visit_anon_const(&mut self, c: &'hir hir::AnonConst) { self.with_context(AnonConst, |v| intravisit::walk_anon_const(v, c)); } fn visit_expr(&mut self, e: &'hir hir::Expr) { match e.node { hir::ExprKind::While(ref e, ref b, _) => { self.with_context(Loop(LoopKind::WhileLoop), |v| { v.visit_expr(&e); v.visit_block(&b); }); } hir::ExprKind::Loop(ref b, _, source) => { self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b)); } hir::ExprKind::Closure(_, ref function_decl, b, _, _) => { self.visit_fn_decl(&function_decl); self.with_context(Closure, |v| v.visit_nested_body(b)); } hir::ExprKind::Block(ref b, Some(_label)) => { self.with_context(LabeledBlock, |v| v.visit_block(&b)); } hir::ExprKind::Break(label, ref opt_expr) => { opt_expr.as_ref().map(|e| self.visit_expr(e)); if self.require_label_in_labeled_block(e.span, &label, "break") { // If we emitted an error about an unlabeled break in a labeled // block, we don't need any further checking for this break any more return; } let loop_id = match label.target_id.into() { Ok(loop_id) => loop_id, Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID, Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => { self.emit_unlabled_cf_in_while_condition(e.span, "break"); ast::DUMMY_NODE_ID }, Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID, }; if loop_id != ast::DUMMY_NODE_ID { if let Node::Block(_) = self.hir_map.find(loop_id).unwrap() { return } } if opt_expr.is_some() { let loop_kind = if loop_id == ast::DUMMY_NODE_ID { None } else { Some(match self.hir_map.expect_expr(loop_id).node { hir::ExprKind::While(..) => LoopKind::WhileLoop, hir::ExprKind::Loop(_, _, source) => LoopKind::Loop(source), ref r => span_bug!(e.span, "break label resolved to a non-loop: {:?}", r), }) }; match loop_kind { None | Some(LoopKind::Loop(hir::LoopSource::Loop)) => (), Some(kind) => { struct_span_err!(self.sess, e.span, E0571, "`break` with value from a `{}` loop", kind.name()) .span_label(e.span, "can only break with a value inside \ `loop` or breakable block") .span_suggestion_with_applicability( e.span, &format!( "instead, use `break` on its own \ without a value inside this `{}` loop", kind.name() ), "break".to_string(), Applicability::MaybeIncorrect, ) .emit(); } } } self.require_break_cx("break", e.span); } hir::ExprKind::Continue(destination) => { self.require_label_in_labeled_block(e.span, &destination, "continue"); match destination.target_id { Ok(loop_id) => { if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() { struct_span_err!(self.sess, e.span, E0696, "`continue` pointing to a labeled block") .span_label(e.span, "labeled blocks cannot be `continue`'d") .span_note(block.span, "labeled block the continue points to") .emit(); } } Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => { self.emit_unlabled_cf_in_while_condition(e.span, "continue"); } Err(_) => {} } self.require_break_cx("continue", e.span) }, _ => intravisit::walk_expr(self, e), } } } impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> { fn with_context<F>(&mut self, cx: Context, f: F) where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>) { let old_cx = self.cx; self.cx = cx; f(self); self.cx = old_cx; } fn require_break_cx(&self, name: &str, span: Span) { match self.cx { LabeledBlock | Loop(_) => {} Closure => { struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name) .span_label(span, "cannot break inside of a closure") .emit(); } Normal | AnonConst => { struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name) .span_label(span, "cannot break outside of a loop") .emit(); } } } fn require_label_in_labeled_block(&mut self, span: Span, label: &Destination, cf_type: &str) -> bool { if self.cx == LabeledBlock { if label.label.is_none() { struct_span_err!(self.sess, span, E0695, "unlabeled `{}` inside of a labeled block", cf_type) .span_label(span, format!("`{}` statements that would diverge to or through \ a labeled block need to bear a label", cf_type)) .emit(); return true; } } return false; } fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) { struct_span_err!(self.sess, span, E0590, "`break` or `continue` with no label in the condition of a `while` loop") .span_label(span, format!("unlabeled `{}` in the condition of a `while` loop", cf_type)) .emit(); } }
nested_visit_map
identifier_name
loops.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use self::Context::*; use rustc::session::Session; use rustc::hir::map::Map; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::hir::{self, Node, Destination}; use syntax::ast; use syntax_pos::Span; use errors::Applicability; #[derive(Clone, Copy, Debug, PartialEq)] enum LoopKind { Loop(hir::LoopSource), WhileLoop, } impl LoopKind { fn name(self) -> &'static str { match self { LoopKind::Loop(hir::LoopSource::Loop) => "loop", LoopKind::Loop(hir::LoopSource::WhileLet) => "while let", LoopKind::Loop(hir::LoopSource::ForLoop) => "for", LoopKind::WhileLoop => "while", } } } #[derive(Clone, Copy, Debug, PartialEq)] enum Context { Normal, Loop(LoopKind), Closure, LabeledBlock, AnonConst, } #[derive(Copy, Clone)] struct CheckLoopVisitor<'a, 'hir: 'a> { sess: &'a Session, hir_map: &'a Map<'hir>, cx: Context, } pub fn check_crate(sess: &Session, map: &Map) { let krate = map.krate(); krate.visit_all_item_likes(&mut CheckLoopVisitor { sess, hir_map: map, cx: Normal, }.as_deep_visitor()); } impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> { NestedVisitorMap::OnlyBodies(&self.hir_map) } fn visit_item(&mut self, i: &'hir hir::Item) { self.with_context(Normal, |v| intravisit::walk_item(v, i)); } fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) { self.with_context(Normal, |v| intravisit::walk_impl_item(v, i)); } fn visit_anon_const(&mut self, c: &'hir hir::AnonConst) { self.with_context(AnonConst, |v| intravisit::walk_anon_const(v, c)); } fn visit_expr(&mut self, e: &'hir hir::Expr) { match e.node { hir::ExprKind::While(ref e, ref b, _) => { self.with_context(Loop(LoopKind::WhileLoop), |v| { v.visit_expr(&e); v.visit_block(&b); }); } hir::ExprKind::Loop(ref b, _, source) => { self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b)); } hir::ExprKind::Closure(_, ref function_decl, b, _, _) => { self.visit_fn_decl(&function_decl); self.with_context(Closure, |v| v.visit_nested_body(b)); } hir::ExprKind::Block(ref b, Some(_label)) => { self.with_context(LabeledBlock, |v| v.visit_block(&b)); } hir::ExprKind::Break(label, ref opt_expr) => { opt_expr.as_ref().map(|e| self.visit_expr(e)); if self.require_label_in_labeled_block(e.span, &label, "break") { // If we emitted an error about an unlabeled break in a labeled // block, we don't need any further checking for this break any more return; } let loop_id = match label.target_id.into() { Ok(loop_id) => loop_id, Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID, Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => { self.emit_unlabled_cf_in_while_condition(e.span, "break"); ast::DUMMY_NODE_ID }, Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID, }; if loop_id != ast::DUMMY_NODE_ID { if let Node::Block(_) = self.hir_map.find(loop_id).unwrap() { return } } if opt_expr.is_some() { let loop_kind = if loop_id == ast::DUMMY_NODE_ID { None } else { Some(match self.hir_map.expect_expr(loop_id).node { hir::ExprKind::While(..) => LoopKind::WhileLoop, hir::ExprKind::Loop(_, _, source) => LoopKind::Loop(source), ref r => span_bug!(e.span, "break label resolved to a non-loop: {:?}", r), }) }; match loop_kind { None | Some(LoopKind::Loop(hir::LoopSource::Loop)) => (), Some(kind) => { struct_span_err!(self.sess, e.span, E0571, "`break` with value from a `{}` loop", kind.name()) .span_label(e.span, "can only break with a value inside \ `loop` or breakable block") .span_suggestion_with_applicability( e.span, &format!( "instead, use `break` on its own \ without a value inside this `{}` loop", kind.name() ), "break".to_string(), Applicability::MaybeIncorrect, ) .emit(); } } } self.require_break_cx("break", e.span); } hir::ExprKind::Continue(destination) => { self.require_label_in_labeled_block(e.span, &destination, "continue"); match destination.target_id { Ok(loop_id) => { if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() { struct_span_err!(self.sess, e.span, E0696, "`continue` pointing to a labeled block") .span_label(e.span, "labeled blocks cannot be `continue`'d") .span_note(block.span, "labeled block the continue points to") .emit(); } } Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => { self.emit_unlabled_cf_in_while_condition(e.span, "continue"); } Err(_) => {} } self.require_break_cx("continue", e.span) }, _ => intravisit::walk_expr(self, e), } } } impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> { fn with_context<F>(&mut self, cx: Context, f: F) where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>) { let old_cx = self.cx; self.cx = cx; f(self); self.cx = old_cx; } fn require_break_cx(&self, name: &str, span: Span) { match self.cx { LabeledBlock | Loop(_) => {}
Normal | AnonConst => { struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name) .span_label(span, "cannot break outside of a loop") .emit(); } } } fn require_label_in_labeled_block(&mut self, span: Span, label: &Destination, cf_type: &str) -> bool { if self.cx == LabeledBlock { if label.label.is_none() { struct_span_err!(self.sess, span, E0695, "unlabeled `{}` inside of a labeled block", cf_type) .span_label(span, format!("`{}` statements that would diverge to or through \ a labeled block need to bear a label", cf_type)) .emit(); return true; } } return false; } fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) { struct_span_err!(self.sess, span, E0590, "`break` or `continue` with no label in the condition of a `while` loop") .span_label(span, format!("unlabeled `{}` in the condition of a `while` loop", cf_type)) .emit(); } }
Closure => { struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name) .span_label(span, "cannot break inside of a closure") .emit(); }
random_line_split
loops.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use self::Context::*; use rustc::session::Session; use rustc::hir::map::Map; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::hir::{self, Node, Destination}; use syntax::ast; use syntax_pos::Span; use errors::Applicability; #[derive(Clone, Copy, Debug, PartialEq)] enum LoopKind { Loop(hir::LoopSource), WhileLoop, } impl LoopKind { fn name(self) -> &'static str { match self { LoopKind::Loop(hir::LoopSource::Loop) => "loop", LoopKind::Loop(hir::LoopSource::WhileLet) => "while let", LoopKind::Loop(hir::LoopSource::ForLoop) => "for", LoopKind::WhileLoop => "while", } } } #[derive(Clone, Copy, Debug, PartialEq)] enum Context { Normal, Loop(LoopKind), Closure, LabeledBlock, AnonConst, } #[derive(Copy, Clone)] struct CheckLoopVisitor<'a, 'hir: 'a> { sess: &'a Session, hir_map: &'a Map<'hir>, cx: Context, } pub fn check_crate(sess: &Session, map: &Map)
impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> { NestedVisitorMap::OnlyBodies(&self.hir_map) } fn visit_item(&mut self, i: &'hir hir::Item) { self.with_context(Normal, |v| intravisit::walk_item(v, i)); } fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) { self.with_context(Normal, |v| intravisit::walk_impl_item(v, i)); } fn visit_anon_const(&mut self, c: &'hir hir::AnonConst) { self.with_context(AnonConst, |v| intravisit::walk_anon_const(v, c)); } fn visit_expr(&mut self, e: &'hir hir::Expr) { match e.node { hir::ExprKind::While(ref e, ref b, _) => { self.with_context(Loop(LoopKind::WhileLoop), |v| { v.visit_expr(&e); v.visit_block(&b); }); } hir::ExprKind::Loop(ref b, _, source) => { self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b)); } hir::ExprKind::Closure(_, ref function_decl, b, _, _) => { self.visit_fn_decl(&function_decl); self.with_context(Closure, |v| v.visit_nested_body(b)); } hir::ExprKind::Block(ref b, Some(_label)) => { self.with_context(LabeledBlock, |v| v.visit_block(&b)); } hir::ExprKind::Break(label, ref opt_expr) => { opt_expr.as_ref().map(|e| self.visit_expr(e)); if self.require_label_in_labeled_block(e.span, &label, "break") { // If we emitted an error about an unlabeled break in a labeled // block, we don't need any further checking for this break any more return; } let loop_id = match label.target_id.into() { Ok(loop_id) => loop_id, Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID, Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => { self.emit_unlabled_cf_in_while_condition(e.span, "break"); ast::DUMMY_NODE_ID }, Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID, }; if loop_id != ast::DUMMY_NODE_ID { if let Node::Block(_) = self.hir_map.find(loop_id).unwrap() { return } } if opt_expr.is_some() { let loop_kind = if loop_id == ast::DUMMY_NODE_ID { None } else { Some(match self.hir_map.expect_expr(loop_id).node { hir::ExprKind::While(..) => LoopKind::WhileLoop, hir::ExprKind::Loop(_, _, source) => LoopKind::Loop(source), ref r => span_bug!(e.span, "break label resolved to a non-loop: {:?}", r), }) }; match loop_kind { None | Some(LoopKind::Loop(hir::LoopSource::Loop)) => (), Some(kind) => { struct_span_err!(self.sess, e.span, E0571, "`break` with value from a `{}` loop", kind.name()) .span_label(e.span, "can only break with a value inside \ `loop` or breakable block") .span_suggestion_with_applicability( e.span, &format!( "instead, use `break` on its own \ without a value inside this `{}` loop", kind.name() ), "break".to_string(), Applicability::MaybeIncorrect, ) .emit(); } } } self.require_break_cx("break", e.span); } hir::ExprKind::Continue(destination) => { self.require_label_in_labeled_block(e.span, &destination, "continue"); match destination.target_id { Ok(loop_id) => { if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() { struct_span_err!(self.sess, e.span, E0696, "`continue` pointing to a labeled block") .span_label(e.span, "labeled blocks cannot be `continue`'d") .span_note(block.span, "labeled block the continue points to") .emit(); } } Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => { self.emit_unlabled_cf_in_while_condition(e.span, "continue"); } Err(_) => {} } self.require_break_cx("continue", e.span) }, _ => intravisit::walk_expr(self, e), } } } impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> { fn with_context<F>(&mut self, cx: Context, f: F) where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>) { let old_cx = self.cx; self.cx = cx; f(self); self.cx = old_cx; } fn require_break_cx(&self, name: &str, span: Span) { match self.cx { LabeledBlock | Loop(_) => {} Closure => { struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name) .span_label(span, "cannot break inside of a closure") .emit(); } Normal | AnonConst => { struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name) .span_label(span, "cannot break outside of a loop") .emit(); } } } fn require_label_in_labeled_block(&mut self, span: Span, label: &Destination, cf_type: &str) -> bool { if self.cx == LabeledBlock { if label.label.is_none() { struct_span_err!(self.sess, span, E0695, "unlabeled `{}` inside of a labeled block", cf_type) .span_label(span, format!("`{}` statements that would diverge to or through \ a labeled block need to bear a label", cf_type)) .emit(); return true; } } return false; } fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) { struct_span_err!(self.sess, span, E0590, "`break` or `continue` with no label in the condition of a `while` loop") .span_label(span, format!("unlabeled `{}` in the condition of a `while` loop", cf_type)) .emit(); } }
{ let krate = map.krate(); krate.visit_all_item_likes(&mut CheckLoopVisitor { sess, hir_map: map, cx: Normal, }.as_deep_visitor()); }
identifier_body
path.py
import unicodedata import re class PathExtension: """ Enables readable url path names instead of ids for object traversal. Names are stored as meta.pool_filename and generated from title by default. Automatic generation can be disabled by setting *meta.customfilename* to False for each object. Extensions like *.html* are not stored. Path matching works independent from extensions. """ maxlength = 55 # max path length containerNamespace = True # unique filenames for container or global extension = None def Init(self): if self.id == 0: # skip roots return self.ListenEvent("commit", "TitleToFilename") self._SetName() def TitleToFilename(self, **kw): """ Uses title for filename """ customfilename = self.data.get("customfilename", None) # might not exist if customfilename: self._SetName() return # create url compatible filename from title filename = self.EscapeFilename(self.meta.title) # make unique filename filename = self.UniqueFilename(filename) if self.AddExtension(filename) == self.meta.pool_filename: # no change return if filename: # update self.meta["pool_filename"] = self.AddExtension(filename) else: # reset filename self.meta["pool_filename"] = "" self._SetName() self.Signal("pathupdate", path=self.meta["pool_filename"]) def UniqueFilename(self, name): """ Converts name to valid path/url """ if name == "file": name = "file_" if self.containerNamespace: unitref = self.parent.id else: unitref = None cnt = 1 root = self.root while root.search.FilenameToID(self.AddExtension(name), unitref, parameter=dict(id=self.id), operators=dict(id="!=")) != 0: if cnt>1: name = name.rstrip("1234567890-") name = name+"-"+str(cnt) cnt += 1 return name def EscapeFilename(self, path): """ Converts name to valid path/url Path length between *self.maxlength-20* and *self.maxlength* chars. Tries to cut longer names at spaces. (based on django's slugify) """ path = unicodedata.normalize("NFKD", path).encode("ascii", "ignore") path = path.decode("utf-8") path = re.sub('[^\w\s-]', '', path).strip().lower() path = re.sub('[-\s]+', '_', path) # avoid ids as filenames try: int(path) path += "_n" except: pass # cut long filenames cutlen = 20 if len(path) <= self.maxlength: return path # cut at '_' pos = path[self.maxlength-cutlen:].find("_") if pos > cutlen: # no '_' found. cut at maxlength. return path[:self.maxlength] return path[:self.maxlength-cutlen+pos] def AddExtension(self, filename): if not self.extension: return filename return "%s.%s" % (filename, self.extension) # system functions ----------------------------------------------------------------- def __getitem__(self, id): """ Traversal lookup based on object.pool_filename and object.id. Trailing extensions are ignored if self.extension is None. `file` is a reserved name and used in the current object to map file downloads. """ if id == "file": raise KeyError(id) if self.extension is None: id = id.split(".") if len(id)>2: id = (".").join(id[:-1]) else: id = id[0] try: id = int(id) except ValueError: name = id id = 0 if name: id = self.root.search.FilenameToID(name, self.id) if not id: raise KeyError(id) obj = self.GetObj(id) if obj is None: raise KeyError(id) return obj def _SetName(self): self.__name__ = self.meta["pool_filename"] if not self.__name__: self.__name__ = str(self.id) class RootPathExtension(object): """ Extension for nive root objects to handle alternative url names """ extension = None # system functions ----------------------------------------------------------------- def __getitem__(self, id): """ Traversal lookup based on object.pool_filename and object.id. Trailing extensions are ignored. `file` is a reserved name and used in the current object to map file downloads. """ if id == "file": raise KeyError(id) if self.extension is None: id = id.split(".") if len(id)>2: id = (".").join(id[:-1]) else: id = id[0] try: id = int(id) except: name = id id = 0 if name: id = self.search.FilenameToID(name, self.id) if not id: raise KeyError(id) obj = self.GetObj(id) if not obj: raise KeyError(id) return obj
""" def Init(self): self.ListenEvent("commit", "UpdateRouting") self.ListenEvent("dataloaded", "UpdateRouting") self.UpdateRouting() def UpdateRouting(self, **kw): # check url name of root if self.meta.get("pool_filename"): name = self.meta.get("pool_filename") if name != self.__name__: # close cached root self.app._CloseRootObj(name=self.__name__) # update __name__ and hash self.__name__ = str(name) self.path = name # unique root id generated from name . negative integer. self.idhash = abs(hash(self.__name__))*-1 from nive.tool import Tool, ToolView from nive.definitions import ToolConf, FieldConf, ViewConf, IApplication tool_configuration = ToolConf( id = "rewriteFilename", context = "nive.extensions.path.RewriteFilenamesTool", name = "Rewrite pool_filename based on title", description = "Rewrites all or empty filenames based on form selection.", apply = (IApplication,), mimetype = "text/html", data = [ FieldConf(id="types", datatype="checkbox", default="", settings=dict(codelist="types"), name="Object types", description=""), FieldConf(id="testrun", datatype="bool", default=1, name="Testrun, no commits", description=""), FieldConf(id="resetall", datatype="string", default="", size=15, name="Reset all filenames", description="<b>Urls will change! Enter 'reset all'</b>"), FieldConf(id="tag", datatype="string", default="rewriteFilename", hidden=1) ], views = [ ViewConf(name="", view=ToolView, attr="form", permission="admin", context="nive.extensions.path.RewriteFilenamesTool") ] ) class RewriteFilenamesTool(Tool): def _Run(self, **values): parameter = dict() if values.get("resetall")!="reset all": parameter["pool_filename"] = "" if values.get("types"): tt = values.get("types") if not isinstance(tt, list): tt = [tt] parameter["pool_type"] = tt operators = dict(pool_type="IN", pool_filename="=") fields = ("id", "title", "pool_type", "pool_filename") root = self.app.root recs = root.search.Search(parameter, fields, max=10000, operators=operators, sort="id", ascending=0) if len(recs["items"]) == 0: return "<h2>None found!</h2>", False user = values["original"]["user"] testrun = values["testrun"] result = [] cnt = 0 for rec in recs["items"]: obj = root.LookupObj(rec["id"]) if obj is None or not hasattr(obj, "TitleToFilename"): continue filename = obj.meta["pool_filename"] obj.TitleToFilename() if filename!=obj.meta["pool_filename"]: result.append(filename+" <> "+obj.meta["pool_filename"]) if testrun==False: obj.dbEntry.Commit(user=user) #obj.CommitInternal(user=user) cnt += 1 return "OK. %d filenames updated, %d different!<br>%s" % (cnt, len(result), "<br>".join(result)), True
class PersistentRootPath(object): """ Extension for nive root objects to handle alternative url names
random_line_split
path.py
import unicodedata import re class PathExtension: """ Enables readable url path names instead of ids for object traversal. Names are stored as meta.pool_filename and generated from title by default. Automatic generation can be disabled by setting *meta.customfilename* to False for each object. Extensions like *.html* are not stored. Path matching works independent from extensions. """ maxlength = 55 # max path length containerNamespace = True # unique filenames for container or global extension = None def Init(self): if self.id == 0: # skip roots return self.ListenEvent("commit", "TitleToFilename") self._SetName() def TitleToFilename(self, **kw): """ Uses title for filename """ customfilename = self.data.get("customfilename", None) # might not exist if customfilename: self._SetName() return # create url compatible filename from title filename = self.EscapeFilename(self.meta.title) # make unique filename filename = self.UniqueFilename(filename) if self.AddExtension(filename) == self.meta.pool_filename: # no change return if filename: # update self.meta["pool_filename"] = self.AddExtension(filename) else: # reset filename self.meta["pool_filename"] = "" self._SetName() self.Signal("pathupdate", path=self.meta["pool_filename"]) def UniqueFilename(self, name):
def EscapeFilename(self, path): """ Converts name to valid path/url Path length between *self.maxlength-20* and *self.maxlength* chars. Tries to cut longer names at spaces. (based on django's slugify) """ path = unicodedata.normalize("NFKD", path).encode("ascii", "ignore") path = path.decode("utf-8") path = re.sub('[^\w\s-]', '', path).strip().lower() path = re.sub('[-\s]+', '_', path) # avoid ids as filenames try: int(path) path += "_n" except: pass # cut long filenames cutlen = 20 if len(path) <= self.maxlength: return path # cut at '_' pos = path[self.maxlength-cutlen:].find("_") if pos > cutlen: # no '_' found. cut at maxlength. return path[:self.maxlength] return path[:self.maxlength-cutlen+pos] def AddExtension(self, filename): if not self.extension: return filename return "%s.%s" % (filename, self.extension) # system functions ----------------------------------------------------------------- def __getitem__(self, id): """ Traversal lookup based on object.pool_filename and object.id. Trailing extensions are ignored if self.extension is None. `file` is a reserved name and used in the current object to map file downloads. """ if id == "file": raise KeyError(id) if self.extension is None: id = id.split(".") if len(id)>2: id = (".").join(id[:-1]) else: id = id[0] try: id = int(id) except ValueError: name = id id = 0 if name: id = self.root.search.FilenameToID(name, self.id) if not id: raise KeyError(id) obj = self.GetObj(id) if obj is None: raise KeyError(id) return obj def _SetName(self): self.__name__ = self.meta["pool_filename"] if not self.__name__: self.__name__ = str(self.id) class RootPathExtension(object): """ Extension for nive root objects to handle alternative url names """ extension = None # system functions ----------------------------------------------------------------- def __getitem__(self, id): """ Traversal lookup based on object.pool_filename and object.id. Trailing extensions are ignored. `file` is a reserved name and used in the current object to map file downloads. """ if id == "file": raise KeyError(id) if self.extension is None: id = id.split(".") if len(id)>2: id = (".").join(id[:-1]) else: id = id[0] try: id = int(id) except: name = id id = 0 if name: id = self.search.FilenameToID(name, self.id) if not id: raise KeyError(id) obj = self.GetObj(id) if not obj: raise KeyError(id) return obj class PersistentRootPath(object): """ Extension for nive root objects to handle alternative url names """ def Init(self): self.ListenEvent("commit", "UpdateRouting") self.ListenEvent("dataloaded", "UpdateRouting") self.UpdateRouting() def UpdateRouting(self, **kw): # check url name of root if self.meta.get("pool_filename"): name = self.meta.get("pool_filename") if name != self.__name__: # close cached root self.app._CloseRootObj(name=self.__name__) # update __name__ and hash self.__name__ = str(name) self.path = name # unique root id generated from name . negative integer. self.idhash = abs(hash(self.__name__))*-1 from nive.tool import Tool, ToolView from nive.definitions import ToolConf, FieldConf, ViewConf, IApplication tool_configuration = ToolConf( id = "rewriteFilename", context = "nive.extensions.path.RewriteFilenamesTool", name = "Rewrite pool_filename based on title", description = "Rewrites all or empty filenames based on form selection.", apply = (IApplication,), mimetype = "text/html", data = [ FieldConf(id="types", datatype="checkbox", default="", settings=dict(codelist="types"), name="Object types", description=""), FieldConf(id="testrun", datatype="bool", default=1, name="Testrun, no commits", description=""), FieldConf(id="resetall", datatype="string", default="", size=15, name="Reset all filenames", description="<b>Urls will change! Enter 'reset all'</b>"), FieldConf(id="tag", datatype="string", default="rewriteFilename", hidden=1) ], views = [ ViewConf(name="", view=ToolView, attr="form", permission="admin", context="nive.extensions.path.RewriteFilenamesTool") ] ) class RewriteFilenamesTool(Tool): def _Run(self, **values): parameter = dict() if values.get("resetall")!="reset all": parameter["pool_filename"] = "" if values.get("types"): tt = values.get("types") if not isinstance(tt, list): tt = [tt] parameter["pool_type"] = tt operators = dict(pool_type="IN", pool_filename="=") fields = ("id", "title", "pool_type", "pool_filename") root = self.app.root recs = root.search.Search(parameter, fields, max=10000, operators=operators, sort="id", ascending=0) if len(recs["items"]) == 0: return "<h2>None found!</h2>", False user = values["original"]["user"] testrun = values["testrun"] result = [] cnt = 0 for rec in recs["items"]: obj = root.LookupObj(rec["id"]) if obj is None or not hasattr(obj, "TitleToFilename"): continue filename = obj.meta["pool_filename"] obj.TitleToFilename() if filename!=obj.meta["pool_filename"]: result.append(filename+" <> "+obj.meta["pool_filename"]) if testrun==False: obj.dbEntry.Commit(user=user) #obj.CommitInternal(user=user) cnt += 1 return "OK. %d filenames updated, %d different!<br>%s" % (cnt, len(result), "<br>".join(result)), True
""" Converts name to valid path/url """ if name == "file": name = "file_" if self.containerNamespace: unitref = self.parent.id else: unitref = None cnt = 1 root = self.root while root.search.FilenameToID(self.AddExtension(name), unitref, parameter=dict(id=self.id), operators=dict(id="!=")) != 0: if cnt>1: name = name.rstrip("1234567890-") name = name+"-"+str(cnt) cnt += 1 return name
identifier_body
path.py
import unicodedata import re class PathExtension: """ Enables readable url path names instead of ids for object traversal. Names are stored as meta.pool_filename and generated from title by default. Automatic generation can be disabled by setting *meta.customfilename* to False for each object. Extensions like *.html* are not stored. Path matching works independent from extensions. """ maxlength = 55 # max path length containerNamespace = True # unique filenames for container or global extension = None def Init(self): if self.id == 0: # skip roots return self.ListenEvent("commit", "TitleToFilename") self._SetName() def TitleToFilename(self, **kw): """ Uses title for filename """ customfilename = self.data.get("customfilename", None) # might not exist if customfilename: self._SetName() return # create url compatible filename from title filename = self.EscapeFilename(self.meta.title) # make unique filename filename = self.UniqueFilename(filename) if self.AddExtension(filename) == self.meta.pool_filename: # no change return if filename: # update self.meta["pool_filename"] = self.AddExtension(filename) else: # reset filename self.meta["pool_filename"] = "" self._SetName() self.Signal("pathupdate", path=self.meta["pool_filename"]) def UniqueFilename(self, name): """ Converts name to valid path/url """ if name == "file": name = "file_" if self.containerNamespace: unitref = self.parent.id else: unitref = None cnt = 1 root = self.root while root.search.FilenameToID(self.AddExtension(name), unitref, parameter=dict(id=self.id), operators=dict(id="!=")) != 0: if cnt>1: name = name.rstrip("1234567890-") name = name+"-"+str(cnt) cnt += 1 return name def EscapeFilename(self, path): """ Converts name to valid path/url Path length between *self.maxlength-20* and *self.maxlength* chars. Tries to cut longer names at spaces. (based on django's slugify) """ path = unicodedata.normalize("NFKD", path).encode("ascii", "ignore") path = path.decode("utf-8") path = re.sub('[^\w\s-]', '', path).strip().lower() path = re.sub('[-\s]+', '_', path) # avoid ids as filenames try: int(path) path += "_n" except: pass # cut long filenames cutlen = 20 if len(path) <= self.maxlength: return path # cut at '_' pos = path[self.maxlength-cutlen:].find("_") if pos > cutlen: # no '_' found. cut at maxlength. return path[:self.maxlength] return path[:self.maxlength-cutlen+pos] def AddExtension(self, filename): if not self.extension: return filename return "%s.%s" % (filename, self.extension) # system functions ----------------------------------------------------------------- def __getitem__(self, id): """ Traversal lookup based on object.pool_filename and object.id. Trailing extensions are ignored if self.extension is None. `file` is a reserved name and used in the current object to map file downloads. """ if id == "file": raise KeyError(id) if self.extension is None: id = id.split(".") if len(id)>2: id = (".").join(id[:-1]) else: id = id[0] try: id = int(id) except ValueError: name = id id = 0 if name: id = self.root.search.FilenameToID(name, self.id) if not id: raise KeyError(id) obj = self.GetObj(id) if obj is None: raise KeyError(id) return obj def _SetName(self): self.__name__ = self.meta["pool_filename"] if not self.__name__: self.__name__ = str(self.id) class RootPathExtension(object): """ Extension for nive root objects to handle alternative url names """ extension = None # system functions ----------------------------------------------------------------- def __getitem__(self, id): """ Traversal lookup based on object.pool_filename and object.id. Trailing extensions are ignored. `file` is a reserved name and used in the current object to map file downloads. """ if id == "file": raise KeyError(id) if self.extension is None: id = id.split(".") if len(id)>2: id = (".").join(id[:-1]) else: id = id[0] try: id = int(id) except: name = id id = 0 if name: id = self.search.FilenameToID(name, self.id) if not id: raise KeyError(id) obj = self.GetObj(id) if not obj: raise KeyError(id) return obj class PersistentRootPath(object): """ Extension for nive root objects to handle alternative url names """ def Init(self): self.ListenEvent("commit", "UpdateRouting") self.ListenEvent("dataloaded", "UpdateRouting") self.UpdateRouting() def
(self, **kw): # check url name of root if self.meta.get("pool_filename"): name = self.meta.get("pool_filename") if name != self.__name__: # close cached root self.app._CloseRootObj(name=self.__name__) # update __name__ and hash self.__name__ = str(name) self.path = name # unique root id generated from name . negative integer. self.idhash = abs(hash(self.__name__))*-1 from nive.tool import Tool, ToolView from nive.definitions import ToolConf, FieldConf, ViewConf, IApplication tool_configuration = ToolConf( id = "rewriteFilename", context = "nive.extensions.path.RewriteFilenamesTool", name = "Rewrite pool_filename based on title", description = "Rewrites all or empty filenames based on form selection.", apply = (IApplication,), mimetype = "text/html", data = [ FieldConf(id="types", datatype="checkbox", default="", settings=dict(codelist="types"), name="Object types", description=""), FieldConf(id="testrun", datatype="bool", default=1, name="Testrun, no commits", description=""), FieldConf(id="resetall", datatype="string", default="", size=15, name="Reset all filenames", description="<b>Urls will change! Enter 'reset all'</b>"), FieldConf(id="tag", datatype="string", default="rewriteFilename", hidden=1) ], views = [ ViewConf(name="", view=ToolView, attr="form", permission="admin", context="nive.extensions.path.RewriteFilenamesTool") ] ) class RewriteFilenamesTool(Tool): def _Run(self, **values): parameter = dict() if values.get("resetall")!="reset all": parameter["pool_filename"] = "" if values.get("types"): tt = values.get("types") if not isinstance(tt, list): tt = [tt] parameter["pool_type"] = tt operators = dict(pool_type="IN", pool_filename="=") fields = ("id", "title", "pool_type", "pool_filename") root = self.app.root recs = root.search.Search(parameter, fields, max=10000, operators=operators, sort="id", ascending=0) if len(recs["items"]) == 0: return "<h2>None found!</h2>", False user = values["original"]["user"] testrun = values["testrun"] result = [] cnt = 0 for rec in recs["items"]: obj = root.LookupObj(rec["id"]) if obj is None or not hasattr(obj, "TitleToFilename"): continue filename = obj.meta["pool_filename"] obj.TitleToFilename() if filename!=obj.meta["pool_filename"]: result.append(filename+" <> "+obj.meta["pool_filename"]) if testrun==False: obj.dbEntry.Commit(user=user) #obj.CommitInternal(user=user) cnt += 1 return "OK. %d filenames updated, %d different!<br>%s" % (cnt, len(result), "<br>".join(result)), True
UpdateRouting
identifier_name
path.py
import unicodedata import re class PathExtension: """ Enables readable url path names instead of ids for object traversal. Names are stored as meta.pool_filename and generated from title by default. Automatic generation can be disabled by setting *meta.customfilename* to False for each object. Extensions like *.html* are not stored. Path matching works independent from extensions. """ maxlength = 55 # max path length containerNamespace = True # unique filenames for container or global extension = None def Init(self): if self.id == 0: # skip roots return self.ListenEvent("commit", "TitleToFilename") self._SetName() def TitleToFilename(self, **kw): """ Uses title for filename """ customfilename = self.data.get("customfilename", None) # might not exist if customfilename: self._SetName() return # create url compatible filename from title filename = self.EscapeFilename(self.meta.title) # make unique filename filename = self.UniqueFilename(filename) if self.AddExtension(filename) == self.meta.pool_filename: # no change return if filename: # update self.meta["pool_filename"] = self.AddExtension(filename) else: # reset filename self.meta["pool_filename"] = "" self._SetName() self.Signal("pathupdate", path=self.meta["pool_filename"]) def UniqueFilename(self, name): """ Converts name to valid path/url """ if name == "file": name = "file_" if self.containerNamespace:
else: unitref = None cnt = 1 root = self.root while root.search.FilenameToID(self.AddExtension(name), unitref, parameter=dict(id=self.id), operators=dict(id="!=")) != 0: if cnt>1: name = name.rstrip("1234567890-") name = name+"-"+str(cnt) cnt += 1 return name def EscapeFilename(self, path): """ Converts name to valid path/url Path length between *self.maxlength-20* and *self.maxlength* chars. Tries to cut longer names at spaces. (based on django's slugify) """ path = unicodedata.normalize("NFKD", path).encode("ascii", "ignore") path = path.decode("utf-8") path = re.sub('[^\w\s-]', '', path).strip().lower() path = re.sub('[-\s]+', '_', path) # avoid ids as filenames try: int(path) path += "_n" except: pass # cut long filenames cutlen = 20 if len(path) <= self.maxlength: return path # cut at '_' pos = path[self.maxlength-cutlen:].find("_") if pos > cutlen: # no '_' found. cut at maxlength. return path[:self.maxlength] return path[:self.maxlength-cutlen+pos] def AddExtension(self, filename): if not self.extension: return filename return "%s.%s" % (filename, self.extension) # system functions ----------------------------------------------------------------- def __getitem__(self, id): """ Traversal lookup based on object.pool_filename and object.id. Trailing extensions are ignored if self.extension is None. `file` is a reserved name and used in the current object to map file downloads. """ if id == "file": raise KeyError(id) if self.extension is None: id = id.split(".") if len(id)>2: id = (".").join(id[:-1]) else: id = id[0] try: id = int(id) except ValueError: name = id id = 0 if name: id = self.root.search.FilenameToID(name, self.id) if not id: raise KeyError(id) obj = self.GetObj(id) if obj is None: raise KeyError(id) return obj def _SetName(self): self.__name__ = self.meta["pool_filename"] if not self.__name__: self.__name__ = str(self.id) class RootPathExtension(object): """ Extension for nive root objects to handle alternative url names """ extension = None # system functions ----------------------------------------------------------------- def __getitem__(self, id): """ Traversal lookup based on object.pool_filename and object.id. Trailing extensions are ignored. `file` is a reserved name and used in the current object to map file downloads. """ if id == "file": raise KeyError(id) if self.extension is None: id = id.split(".") if len(id)>2: id = (".").join(id[:-1]) else: id = id[0] try: id = int(id) except: name = id id = 0 if name: id = self.search.FilenameToID(name, self.id) if not id: raise KeyError(id) obj = self.GetObj(id) if not obj: raise KeyError(id) return obj class PersistentRootPath(object): """ Extension for nive root objects to handle alternative url names """ def Init(self): self.ListenEvent("commit", "UpdateRouting") self.ListenEvent("dataloaded", "UpdateRouting") self.UpdateRouting() def UpdateRouting(self, **kw): # check url name of root if self.meta.get("pool_filename"): name = self.meta.get("pool_filename") if name != self.__name__: # close cached root self.app._CloseRootObj(name=self.__name__) # update __name__ and hash self.__name__ = str(name) self.path = name # unique root id generated from name . negative integer. self.idhash = abs(hash(self.__name__))*-1 from nive.tool import Tool, ToolView from nive.definitions import ToolConf, FieldConf, ViewConf, IApplication tool_configuration = ToolConf( id = "rewriteFilename", context = "nive.extensions.path.RewriteFilenamesTool", name = "Rewrite pool_filename based on title", description = "Rewrites all or empty filenames based on form selection.", apply = (IApplication,), mimetype = "text/html", data = [ FieldConf(id="types", datatype="checkbox", default="", settings=dict(codelist="types"), name="Object types", description=""), FieldConf(id="testrun", datatype="bool", default=1, name="Testrun, no commits", description=""), FieldConf(id="resetall", datatype="string", default="", size=15, name="Reset all filenames", description="<b>Urls will change! Enter 'reset all'</b>"), FieldConf(id="tag", datatype="string", default="rewriteFilename", hidden=1) ], views = [ ViewConf(name="", view=ToolView, attr="form", permission="admin", context="nive.extensions.path.RewriteFilenamesTool") ] ) class RewriteFilenamesTool(Tool): def _Run(self, **values): parameter = dict() if values.get("resetall")!="reset all": parameter["pool_filename"] = "" if values.get("types"): tt = values.get("types") if not isinstance(tt, list): tt = [tt] parameter["pool_type"] = tt operators = dict(pool_type="IN", pool_filename="=") fields = ("id", "title", "pool_type", "pool_filename") root = self.app.root recs = root.search.Search(parameter, fields, max=10000, operators=operators, sort="id", ascending=0) if len(recs["items"]) == 0: return "<h2>None found!</h2>", False user = values["original"]["user"] testrun = values["testrun"] result = [] cnt = 0 for rec in recs["items"]: obj = root.LookupObj(rec["id"]) if obj is None or not hasattr(obj, "TitleToFilename"): continue filename = obj.meta["pool_filename"] obj.TitleToFilename() if filename!=obj.meta["pool_filename"]: result.append(filename+" <> "+obj.meta["pool_filename"]) if testrun==False: obj.dbEntry.Commit(user=user) #obj.CommitInternal(user=user) cnt += 1 return "OK. %d filenames updated, %d different!<br>%s" % (cnt, len(result), "<br>".join(result)), True
unitref = self.parent.id
conditional_block
base.py
import curses import random class Screen(object): def __init__(self, maxy, maxx): self.setmaxyx(maxy, maxx) self.pos = (0, 0) def clear(self, *args): if not args: y, x = self.getmaxyx() self.lines = [] for i in range(y): self.lines.append(list([' '] * x)) else: y, x, y0, x0 = args for i in range(y0, y0 + y): try: line = self.lines[i] except IndexError: # Following lines are out of range, no need to go over them. # We don't raise an exception here because it's not # an error in curses. break line[x0:x0 + x] = [' '] * x def keypad(self, val): pass def getmaxyx(self): return self.maxyx def addstr(self, y, x, s, a=None): if not s: return line = self.lines[y] sl = slice(x, x + len(s)) if len(line[sl]) != len(s): raise CursesError('addstr got a too long string: "%s"' % s) if line[sl][0] != ' ' or len(set(line[sl])) != 1: if line[sl] != list(s): raise CursesError('trying to overwrite "%s" with "%s", y: %d' % (''.join(line[sl]), s, y)) line[sl] = list(s) def refresh(self): pass def getch(self): return commands.get() def get_line(self, ind): return ''.join(self.lines[ind]).strip() def move(self, y, x): self.pos = (y, x) def getyx(self): return self.pos def setmaxyx(self, maxy, maxx): self.maxyx = (maxy, maxx) self.clear() class Window(Screen): def __init__(self, *args): if len(args) == 2: y0, x0 = args sy, sx = get_screen().getmaxyx() y, x = sy - y0, sx - x0 elif len(args) == 4: y, x, y0, x0 = args else: raise CursesError('Bad arguments for newwin: %s' % args) self.maxyx = (y, x) self.begyx = (y0, x0) self.pos = (0, 0) def getbegyx(self): return self.begyx def resize(self, y, x): self.maxyx = (y, x) def addstr(self, y, x, s, a=None): y0, x0 = self.getbegyx()
y, x = self.getmaxyx() get_screen().clear(y, x, y0, x0) class CursesError(Exception): pass screen = None def get_screen(): return screen def initscr(): global screen screen = Screen(100, 100) return screen def newwin(*args): return Window(*args) class CommandsManager(object): def __init__(self): self.reset() def reset(self): self.commands = [] def add(self, command): if isinstance(command, list): self.commands += command else: self.commands.append(command) def get(self): try: return self.commands.pop(0) except IndexError: raise CursesError('Run out of commands') commands = CommandsManager() def keyname(code): ch = chr(code) if ch == '\n': return '^J' return ch def patch_curses(): if getattr(curses, 'patched', False): return curses.initscr = initscr curses.noecho = lambda: None curses.cbreak = lambda: None curses.curs_set = lambda val: None curses.newwin = newwin curses.nocbreak = lambda: None curses.echo = lambda: None curses.endwin = lambda: None curses.keyname = keyname curses.start_color = lambda: None curses.patched = True def get_random_lines(num=None, width=None): letters = [chr(c) for c in range(97, 123)] + [' '] if not num or not width: y, x = get_screen().getmaxyx() if not num: num = y + 50 if not width: width = x - 1 def get_line(): line = ''.join([random.choice(letters) for j in range(random.randint(1, width))]).strip() return line or get_line() return [get_line() for i in range(num)]
get_screen().addstr(y + y0, x + x0, s, a) def clear(self): y0, x0 = self.getbegyx()
random_line_split
base.py
import curses import random class Screen(object): def __init__(self, maxy, maxx): self.setmaxyx(maxy, maxx) self.pos = (0, 0) def clear(self, *args): if not args: y, x = self.getmaxyx() self.lines = [] for i in range(y): self.lines.append(list([' '] * x)) else: y, x, y0, x0 = args for i in range(y0, y0 + y): try: line = self.lines[i] except IndexError: # Following lines are out of range, no need to go over them. # We don't raise an exception here because it's not # an error in curses. break line[x0:x0 + x] = [' '] * x def keypad(self, val): pass def getmaxyx(self): return self.maxyx def addstr(self, y, x, s, a=None): if not s: return line = self.lines[y] sl = slice(x, x + len(s)) if len(line[sl]) != len(s): raise CursesError('addstr got a too long string: "%s"' % s) if line[sl][0] != ' ' or len(set(line[sl])) != 1: if line[sl] != list(s): raise CursesError('trying to overwrite "%s" with "%s", y: %d' % (''.join(line[sl]), s, y)) line[sl] = list(s) def refresh(self): pass def getch(self): return commands.get() def get_line(self, ind): return ''.join(self.lines[ind]).strip() def move(self, y, x): self.pos = (y, x) def getyx(self): return self.pos def setmaxyx(self, maxy, maxx): self.maxyx = (maxy, maxx) self.clear() class Window(Screen): def __init__(self, *args): if len(args) == 2: y0, x0 = args sy, sx = get_screen().getmaxyx() y, x = sy - y0, sx - x0 elif len(args) == 4: y, x, y0, x0 = args else: raise CursesError('Bad arguments for newwin: %s' % args) self.maxyx = (y, x) self.begyx = (y0, x0) self.pos = (0, 0) def getbegyx(self): return self.begyx def resize(self, y, x): self.maxyx = (y, x) def addstr(self, y, x, s, a=None): y0, x0 = self.getbegyx() get_screen().addstr(y + y0, x + x0, s, a) def clear(self): y0, x0 = self.getbegyx() y, x = self.getmaxyx() get_screen().clear(y, x, y0, x0) class CursesError(Exception): pass screen = None def get_screen(): return screen def initscr(): global screen screen = Screen(100, 100) return screen def newwin(*args): return Window(*args) class CommandsManager(object): def __init__(self): self.reset() def
(self): self.commands = [] def add(self, command): if isinstance(command, list): self.commands += command else: self.commands.append(command) def get(self): try: return self.commands.pop(0) except IndexError: raise CursesError('Run out of commands') commands = CommandsManager() def keyname(code): ch = chr(code) if ch == '\n': return '^J' return ch def patch_curses(): if getattr(curses, 'patched', False): return curses.initscr = initscr curses.noecho = lambda: None curses.cbreak = lambda: None curses.curs_set = lambda val: None curses.newwin = newwin curses.nocbreak = lambda: None curses.echo = lambda: None curses.endwin = lambda: None curses.keyname = keyname curses.start_color = lambda: None curses.patched = True def get_random_lines(num=None, width=None): letters = [chr(c) for c in range(97, 123)] + [' '] if not num or not width: y, x = get_screen().getmaxyx() if not num: num = y + 50 if not width: width = x - 1 def get_line(): line = ''.join([random.choice(letters) for j in range(random.randint(1, width))]).strip() return line or get_line() return [get_line() for i in range(num)]
reset
identifier_name
base.py
import curses import random class Screen(object): def __init__(self, maxy, maxx): self.setmaxyx(maxy, maxx) self.pos = (0, 0) def clear(self, *args): if not args: y, x = self.getmaxyx() self.lines = [] for i in range(y): self.lines.append(list([' '] * x)) else: y, x, y0, x0 = args for i in range(y0, y0 + y): try: line = self.lines[i] except IndexError: # Following lines are out of range, no need to go over them. # We don't raise an exception here because it's not # an error in curses. break line[x0:x0 + x] = [' '] * x def keypad(self, val): pass def getmaxyx(self): return self.maxyx def addstr(self, y, x, s, a=None): if not s: return line = self.lines[y] sl = slice(x, x + len(s)) if len(line[sl]) != len(s): raise CursesError('addstr got a too long string: "%s"' % s) if line[sl][0] != ' ' or len(set(line[sl])) != 1: if line[sl] != list(s): raise CursesError('trying to overwrite "%s" with "%s", y: %d' % (''.join(line[sl]), s, y)) line[sl] = list(s) def refresh(self): pass def getch(self): return commands.get() def get_line(self, ind): return ''.join(self.lines[ind]).strip() def move(self, y, x): self.pos = (y, x) def getyx(self): return self.pos def setmaxyx(self, maxy, maxx): self.maxyx = (maxy, maxx) self.clear() class Window(Screen): def __init__(self, *args): if len(args) == 2: y0, x0 = args sy, sx = get_screen().getmaxyx() y, x = sy - y0, sx - x0 elif len(args) == 4: y, x, y0, x0 = args else: raise CursesError('Bad arguments for newwin: %s' % args) self.maxyx = (y, x) self.begyx = (y0, x0) self.pos = (0, 0) def getbegyx(self): return self.begyx def resize(self, y, x): self.maxyx = (y, x) def addstr(self, y, x, s, a=None): y0, x0 = self.getbegyx() get_screen().addstr(y + y0, x + x0, s, a) def clear(self): y0, x0 = self.getbegyx() y, x = self.getmaxyx() get_screen().clear(y, x, y0, x0) class CursesError(Exception): pass screen = None def get_screen(): return screen def initscr(): global screen screen = Screen(100, 100) return screen def newwin(*args): return Window(*args) class CommandsManager(object): def __init__(self): self.reset() def reset(self): self.commands = [] def add(self, command): if isinstance(command, list): self.commands += command else: self.commands.append(command) def get(self): try: return self.commands.pop(0) except IndexError: raise CursesError('Run out of commands') commands = CommandsManager() def keyname(code): ch = chr(code) if ch == '\n': return '^J' return ch def patch_curses(): if getattr(curses, 'patched', False): return curses.initscr = initscr curses.noecho = lambda: None curses.cbreak = lambda: None curses.curs_set = lambda val: None curses.newwin = newwin curses.nocbreak = lambda: None curses.echo = lambda: None curses.endwin = lambda: None curses.keyname = keyname curses.start_color = lambda: None curses.patched = True def get_random_lines(num=None, width=None): letters = [chr(c) for c in range(97, 123)] + [' '] if not num or not width: y, x = get_screen().getmaxyx() if not num:
if not width: width = x - 1 def get_line(): line = ''.join([random.choice(letters) for j in range(random.randint(1, width))]).strip() return line or get_line() return [get_line() for i in range(num)]
num = y + 50
conditional_block
base.py
import curses import random class Screen(object): def __init__(self, maxy, maxx): self.setmaxyx(maxy, maxx) self.pos = (0, 0) def clear(self, *args): if not args: y, x = self.getmaxyx() self.lines = [] for i in range(y): self.lines.append(list([' '] * x)) else: y, x, y0, x0 = args for i in range(y0, y0 + y): try: line = self.lines[i] except IndexError: # Following lines are out of range, no need to go over them. # We don't raise an exception here because it's not # an error in curses. break line[x0:x0 + x] = [' '] * x def keypad(self, val): pass def getmaxyx(self): return self.maxyx def addstr(self, y, x, s, a=None): if not s: return line = self.lines[y] sl = slice(x, x + len(s)) if len(line[sl]) != len(s): raise CursesError('addstr got a too long string: "%s"' % s) if line[sl][0] != ' ' or len(set(line[sl])) != 1: if line[sl] != list(s): raise CursesError('trying to overwrite "%s" with "%s", y: %d' % (''.join(line[sl]), s, y)) line[sl] = list(s) def refresh(self): pass def getch(self): return commands.get() def get_line(self, ind): return ''.join(self.lines[ind]).strip() def move(self, y, x): self.pos = (y, x) def getyx(self):
def setmaxyx(self, maxy, maxx): self.maxyx = (maxy, maxx) self.clear() class Window(Screen): def __init__(self, *args): if len(args) == 2: y0, x0 = args sy, sx = get_screen().getmaxyx() y, x = sy - y0, sx - x0 elif len(args) == 4: y, x, y0, x0 = args else: raise CursesError('Bad arguments for newwin: %s' % args) self.maxyx = (y, x) self.begyx = (y0, x0) self.pos = (0, 0) def getbegyx(self): return self.begyx def resize(self, y, x): self.maxyx = (y, x) def addstr(self, y, x, s, a=None): y0, x0 = self.getbegyx() get_screen().addstr(y + y0, x + x0, s, a) def clear(self): y0, x0 = self.getbegyx() y, x = self.getmaxyx() get_screen().clear(y, x, y0, x0) class CursesError(Exception): pass screen = None def get_screen(): return screen def initscr(): global screen screen = Screen(100, 100) return screen def newwin(*args): return Window(*args) class CommandsManager(object): def __init__(self): self.reset() def reset(self): self.commands = [] def add(self, command): if isinstance(command, list): self.commands += command else: self.commands.append(command) def get(self): try: return self.commands.pop(0) except IndexError: raise CursesError('Run out of commands') commands = CommandsManager() def keyname(code): ch = chr(code) if ch == '\n': return '^J' return ch def patch_curses(): if getattr(curses, 'patched', False): return curses.initscr = initscr curses.noecho = lambda: None curses.cbreak = lambda: None curses.curs_set = lambda val: None curses.newwin = newwin curses.nocbreak = lambda: None curses.echo = lambda: None curses.endwin = lambda: None curses.keyname = keyname curses.start_color = lambda: None curses.patched = True def get_random_lines(num=None, width=None): letters = [chr(c) for c in range(97, 123)] + [' '] if not num or not width: y, x = get_screen().getmaxyx() if not num: num = y + 50 if not width: width = x - 1 def get_line(): line = ''.join([random.choice(letters) for j in range(random.randint(1, width))]).strip() return line or get_line() return [get_line() for i in range(num)]
return self.pos
identifier_body
test_householder_reflection.py
""" Python unit-test """ import unittest import numpy as np import numpy.testing as npt from .. import qr_decomposition class TestHouseholderReflection(unittest.TestCase): """Test case for QR decomposition using Householder reflection.""" def test_wikipedia_example1(self): """Test of Wikipedia example The example for the following QR decomposition is taken from https://en.wikipedia.org/wiki/Qr_decomposition#Example_2. """ A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=np.float64)
R_desired = np.array([[14, 21, -14], [0, 175, -70], [0, 0, -35]], dtype=np.float64) npt.assert_almost_equal(Q, Q_desired, 4) npt.assert_almost_equal(R, R_desired, 4) if __name__ == "__main__": unittest.main()
(Q, R) = qr_decomposition.householder_reflection(A) Q_desired = np.array([[0.8571, -0.3943, 0.3314], [0.4286, 0.9029, -0.0343], [-0.2857, 0.1714, 0.9429]], dtype=np.float64)
random_line_split
test_householder_reflection.py
""" Python unit-test """ import unittest import numpy as np import numpy.testing as npt from .. import qr_decomposition class TestHouseholderReflection(unittest.TestCase): """Test case for QR decomposition using Householder reflection.""" def test_wikipedia_example1(self): """Test of Wikipedia example The example for the following QR decomposition is taken from https://en.wikipedia.org/wiki/Qr_decomposition#Example_2. """ A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=np.float64) (Q, R) = qr_decomposition.householder_reflection(A) Q_desired = np.array([[0.8571, -0.3943, 0.3314], [0.4286, 0.9029, -0.0343], [-0.2857, 0.1714, 0.9429]], dtype=np.float64) R_desired = np.array([[14, 21, -14], [0, 175, -70], [0, 0, -35]], dtype=np.float64) npt.assert_almost_equal(Q, Q_desired, 4) npt.assert_almost_equal(R, R_desired, 4) if __name__ == "__main__":
unittest.main()
conditional_block
test_householder_reflection.py
""" Python unit-test """ import unittest import numpy as np import numpy.testing as npt from .. import qr_decomposition class TestHouseholderReflection(unittest.TestCase): """Test case for QR decomposition using Householder reflection.""" def test_wikipedia_example1(self):
if __name__ == "__main__": unittest.main()
"""Test of Wikipedia example The example for the following QR decomposition is taken from https://en.wikipedia.org/wiki/Qr_decomposition#Example_2. """ A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=np.float64) (Q, R) = qr_decomposition.householder_reflection(A) Q_desired = np.array([[0.8571, -0.3943, 0.3314], [0.4286, 0.9029, -0.0343], [-0.2857, 0.1714, 0.9429]], dtype=np.float64) R_desired = np.array([[14, 21, -14], [0, 175, -70], [0, 0, -35]], dtype=np.float64) npt.assert_almost_equal(Q, Q_desired, 4) npt.assert_almost_equal(R, R_desired, 4)
identifier_body
test_householder_reflection.py
""" Python unit-test """ import unittest import numpy as np import numpy.testing as npt from .. import qr_decomposition class TestHouseholderReflection(unittest.TestCase): """Test case for QR decomposition using Householder reflection.""" def
(self): """Test of Wikipedia example The example for the following QR decomposition is taken from https://en.wikipedia.org/wiki/Qr_decomposition#Example_2. """ A = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=np.float64) (Q, R) = qr_decomposition.householder_reflection(A) Q_desired = np.array([[0.8571, -0.3943, 0.3314], [0.4286, 0.9029, -0.0343], [-0.2857, 0.1714, 0.9429]], dtype=np.float64) R_desired = np.array([[14, 21, -14], [0, 175, -70], [0, 0, -35]], dtype=np.float64) npt.assert_almost_equal(Q, Q_desired, 4) npt.assert_almost_equal(R, R_desired, 4) if __name__ == "__main__": unittest.main()
test_wikipedia_example1
identifier_name
cmd_away.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.config import ConfigValidationError from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.utils import trimStringToByteLength from zope.interface import implementer from typing import Any, Callable, Dict, List, Optional, Tuple, Union @implementer(IPlugin, IModuleData, ICommand) class AwayCommand(ModuleData, Command): name = "AwayCommand" core = True def userCommands(self) -> List[Tuple[str, int, Command]]: return [ ("AWAY", 1, self) ] def actions(self) -> List[Tuple[str, int, Callable]]: return [ ("commandextra-PRIVMSG", 10, self.notifyAway), ("commandextra-NOTICE", 10, self.notifyAway), ("extrawhois", 10, self.addWhois), ("buildisupport", 1, self.buildISupport), ("usermetadataupdate", 10, self.sendAwayNotice) ] def verifyConfig(self, config: Dict[str, Any]) -> None: if "away_length" in config: if not isinstance(config["away_length"], int) or config["away_length"] < 0: raise ConfigValidationError("away_length", "invalid number") elif config["away_length"] > 200: config["away_length"] = 200 self.ircd.logConfigValidationWarning("away_length", "value is too large", 200) def notifyAway(self, user: "IRCUser", data: Dict[Any, Any]) -> None: if "targetusers" not in data: return for u in data["targetusers"].keys(): if u.metadataKeyExists("away"): user.sendMessage(irc.RPL_AWAY, u.nick, u.metadataValue("away")) def addWhois(self, user: "IRCUser", targetUser: "IRCUser") -> None: if targetUser.metadataKeyExists("away"): user.sendMessage(irc.RPL_AWAY, targetUser.nick, targetUser.metadataValue("away")) def buildISupport(self, data: Dict[str, Union[str, int]]) -> None: data["AWAYLEN"] = self.ircd.config.get("away_length", 200) def sendAwayNotice(self, user: "IRCUser", key: str, oldValue: str, value: str, fromServer: Optional["IRCServer"]) -> None: if key == "away": if value: user.sendMessage(irc.RPL_NOWAWAY, "You have been marked as being away") else:
def parseParams(self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[Any, Any]]: if not params: return {} message = " ".join(params) message = trimStringToByteLength(message, self.ircd.config.get("away_length", 200)) return { "message": message } def execute(self, user: "IRCUser", data: Dict[Any, Any]) -> bool: if "message" in data and data["message"]: user.setMetadata("away", data["message"]) else: user.setMetadata("away", None) return True awayCommand = AwayCommand()
user.sendMessage(irc.RPL_UNAWAY, "You are no longer marked as being away")
conditional_block
cmd_away.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc
from zope.interface import implementer from typing import Any, Callable, Dict, List, Optional, Tuple, Union @implementer(IPlugin, IModuleData, ICommand) class AwayCommand(ModuleData, Command): name = "AwayCommand" core = True def userCommands(self) -> List[Tuple[str, int, Command]]: return [ ("AWAY", 1, self) ] def actions(self) -> List[Tuple[str, int, Callable]]: return [ ("commandextra-PRIVMSG", 10, self.notifyAway), ("commandextra-NOTICE", 10, self.notifyAway), ("extrawhois", 10, self.addWhois), ("buildisupport", 1, self.buildISupport), ("usermetadataupdate", 10, self.sendAwayNotice) ] def verifyConfig(self, config: Dict[str, Any]) -> None: if "away_length" in config: if not isinstance(config["away_length"], int) or config["away_length"] < 0: raise ConfigValidationError("away_length", "invalid number") elif config["away_length"] > 200: config["away_length"] = 200 self.ircd.logConfigValidationWarning("away_length", "value is too large", 200) def notifyAway(self, user: "IRCUser", data: Dict[Any, Any]) -> None: if "targetusers" not in data: return for u in data["targetusers"].keys(): if u.metadataKeyExists("away"): user.sendMessage(irc.RPL_AWAY, u.nick, u.metadataValue("away")) def addWhois(self, user: "IRCUser", targetUser: "IRCUser") -> None: if targetUser.metadataKeyExists("away"): user.sendMessage(irc.RPL_AWAY, targetUser.nick, targetUser.metadataValue("away")) def buildISupport(self, data: Dict[str, Union[str, int]]) -> None: data["AWAYLEN"] = self.ircd.config.get("away_length", 200) def sendAwayNotice(self, user: "IRCUser", key: str, oldValue: str, value: str, fromServer: Optional["IRCServer"]) -> None: if key == "away": if value: user.sendMessage(irc.RPL_NOWAWAY, "You have been marked as being away") else: user.sendMessage(irc.RPL_UNAWAY, "You are no longer marked as being away") def parseParams(self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[Any, Any]]: if not params: return {} message = " ".join(params) message = trimStringToByteLength(message, self.ircd.config.get("away_length", 200)) return { "message": message } def execute(self, user: "IRCUser", data: Dict[Any, Any]) -> bool: if "message" in data and data["message"]: user.setMetadata("away", data["message"]) else: user.setMetadata("away", None) return True awayCommand = AwayCommand()
from txircd.config import ConfigValidationError from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.utils import trimStringToByteLength
random_line_split
cmd_away.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.config import ConfigValidationError from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.utils import trimStringToByteLength from zope.interface import implementer from typing import Any, Callable, Dict, List, Optional, Tuple, Union @implementer(IPlugin, IModuleData, ICommand) class AwayCommand(ModuleData, Command): name = "AwayCommand" core = True def userCommands(self) -> List[Tuple[str, int, Command]]: return [ ("AWAY", 1, self) ] def actions(self) -> List[Tuple[str, int, Callable]]: return [ ("commandextra-PRIVMSG", 10, self.notifyAway), ("commandextra-NOTICE", 10, self.notifyAway), ("extrawhois", 10, self.addWhois), ("buildisupport", 1, self.buildISupport), ("usermetadataupdate", 10, self.sendAwayNotice) ] def verifyConfig(self, config: Dict[str, Any]) -> None: if "away_length" in config: if not isinstance(config["away_length"], int) or config["away_length"] < 0: raise ConfigValidationError("away_length", "invalid number") elif config["away_length"] > 200: config["away_length"] = 200 self.ircd.logConfigValidationWarning("away_length", "value is too large", 200) def notifyAway(self, user: "IRCUser", data: Dict[Any, Any]) -> None:
def addWhois(self, user: "IRCUser", targetUser: "IRCUser") -> None: if targetUser.metadataKeyExists("away"): user.sendMessage(irc.RPL_AWAY, targetUser.nick, targetUser.metadataValue("away")) def buildISupport(self, data: Dict[str, Union[str, int]]) -> None: data["AWAYLEN"] = self.ircd.config.get("away_length", 200) def sendAwayNotice(self, user: "IRCUser", key: str, oldValue: str, value: str, fromServer: Optional["IRCServer"]) -> None: if key == "away": if value: user.sendMessage(irc.RPL_NOWAWAY, "You have been marked as being away") else: user.sendMessage(irc.RPL_UNAWAY, "You are no longer marked as being away") def parseParams(self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[Any, Any]]: if not params: return {} message = " ".join(params) message = trimStringToByteLength(message, self.ircd.config.get("away_length", 200)) return { "message": message } def execute(self, user: "IRCUser", data: Dict[Any, Any]) -> bool: if "message" in data and data["message"]: user.setMetadata("away", data["message"]) else: user.setMetadata("away", None) return True awayCommand = AwayCommand()
if "targetusers" not in data: return for u in data["targetusers"].keys(): if u.metadataKeyExists("away"): user.sendMessage(irc.RPL_AWAY, u.nick, u.metadataValue("away"))
identifier_body
cmd_away.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.config import ConfigValidationError from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.utils import trimStringToByteLength from zope.interface import implementer from typing import Any, Callable, Dict, List, Optional, Tuple, Union @implementer(IPlugin, IModuleData, ICommand) class
(ModuleData, Command): name = "AwayCommand" core = True def userCommands(self) -> List[Tuple[str, int, Command]]: return [ ("AWAY", 1, self) ] def actions(self) -> List[Tuple[str, int, Callable]]: return [ ("commandextra-PRIVMSG", 10, self.notifyAway), ("commandextra-NOTICE", 10, self.notifyAway), ("extrawhois", 10, self.addWhois), ("buildisupport", 1, self.buildISupport), ("usermetadataupdate", 10, self.sendAwayNotice) ] def verifyConfig(self, config: Dict[str, Any]) -> None: if "away_length" in config: if not isinstance(config["away_length"], int) or config["away_length"] < 0: raise ConfigValidationError("away_length", "invalid number") elif config["away_length"] > 200: config["away_length"] = 200 self.ircd.logConfigValidationWarning("away_length", "value is too large", 200) def notifyAway(self, user: "IRCUser", data: Dict[Any, Any]) -> None: if "targetusers" not in data: return for u in data["targetusers"].keys(): if u.metadataKeyExists("away"): user.sendMessage(irc.RPL_AWAY, u.nick, u.metadataValue("away")) def addWhois(self, user: "IRCUser", targetUser: "IRCUser") -> None: if targetUser.metadataKeyExists("away"): user.sendMessage(irc.RPL_AWAY, targetUser.nick, targetUser.metadataValue("away")) def buildISupport(self, data: Dict[str, Union[str, int]]) -> None: data["AWAYLEN"] = self.ircd.config.get("away_length", 200) def sendAwayNotice(self, user: "IRCUser", key: str, oldValue: str, value: str, fromServer: Optional["IRCServer"]) -> None: if key == "away": if value: user.sendMessage(irc.RPL_NOWAWAY, "You have been marked as being away") else: user.sendMessage(irc.RPL_UNAWAY, "You are no longer marked as being away") def parseParams(self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[Any, Any]]: if not params: return {} message = " ".join(params) message = trimStringToByteLength(message, self.ircd.config.get("away_length", 200)) return { "message": message } def execute(self, user: "IRCUser", data: Dict[Any, Any]) -> bool: if "message" in data and data["message"]: user.setMetadata("away", data["message"]) else: user.setMetadata("away", None) return True awayCommand = AwayCommand()
AwayCommand
identifier_name
GoogleMap.js
import React from 'react'; import { GoogleMapLoader, GoogleMap, Marker } from 'react-google-maps'; const noop = () => {}; // Wrap all `react-google-maps` components with `withGoogleMap` HOC // and name it GettingStartedGoogleMap const Map = ({ lat, lng, onMapLoad, marker, onMapClick = noop, containerElementProps }) => ( <div style={{ height: '100%' }}> <GoogleMapLoader containerElement={ <div {...containerElementProps} style={{ height: '100%', }} /> } googleMapElement={ <GoogleMap ref={onMapLoad} defaultZoom={12} defaultCenter={{ lat, lng }} onClick={onMapClick} > <Marker position={{ lat, lng }} /> </GoogleMap> } /> </div> );
Map.propTypes = {}; export default Map;
random_line_split
pypi.py
"""PyPi blueprint.""" import os from flask import Blueprint, current_app, g, request blueprint = Blueprint('pypi', __name__, url_prefix='/pypi') def register_package(localproxy): """Register a new package. Creates a folder on the filesystem so a new package can be uploaded. Arguments: localproxy (``werkzeug.local.LocalProxy``): The localproxy object is needed to read the ``form`` properties from the request Returns: ``'ok'`` """ package_dir = os.path.join(current_app.config['BASEDIR'], localproxy.form['name'].lower()) if not os.path.isdir(package_dir):
return 'ok' def upload_package(localproxy): """Save a new package and it's md5 sum in a previously registered path. Arguments: localproxy (``werkzeug.local.LocalProxy``):The localproxy object is needed to read the ``form`` properties from the request Returns: ``'ok'`` """ contents = localproxy.files['content'] digest = localproxy.form['md5_digest'] file_path = os.path.join(current_app.config['BASEDIR'], localproxy.form['name'].lower(), contents.filename.lower()) contents.save(file_path) with open('{}.md5'.format(file_path), 'w') as md5_digest: md5_digest.write(digest) return 'ok' @blueprint.route('', methods=['POST']) def post_pypi(): """Find a package and return the contents of it. Upon calling this endpoint the ``PRIVATE_EGGS`` set will be updated, and proper action will be taken based on the request. """ actions = { 'submit': register_package, 'file_upload': upload_package, } if g.database.new_egg(request.form['name'].lower()): return actions[request.form[':action']](request)
os.mkdir(package_dir)
conditional_block
pypi.py
"""PyPi blueprint.""" import os from flask import Blueprint, current_app, g, request blueprint = Blueprint('pypi', __name__, url_prefix='/pypi') def register_package(localproxy): """Register a new package. Creates a folder on the filesystem so a new package can be uploaded. Arguments: localproxy (``werkzeug.local.LocalProxy``): The localproxy object is needed to read the ``form`` properties from the request Returns: ``'ok'`` """ package_dir = os.path.join(current_app.config['BASEDIR'], localproxy.form['name'].lower()) if not os.path.isdir(package_dir): os.mkdir(package_dir) return 'ok' def upload_package(localproxy): """Save a new package and it's md5 sum in a previously registered path. Arguments: localproxy (``werkzeug.local.LocalProxy``):The localproxy object is needed to read the ``form`` properties from the request
digest = localproxy.form['md5_digest'] file_path = os.path.join(current_app.config['BASEDIR'], localproxy.form['name'].lower(), contents.filename.lower()) contents.save(file_path) with open('{}.md5'.format(file_path), 'w') as md5_digest: md5_digest.write(digest) return 'ok' @blueprint.route('', methods=['POST']) def post_pypi(): """Find a package and return the contents of it. Upon calling this endpoint the ``PRIVATE_EGGS`` set will be updated, and proper action will be taken based on the request. """ actions = { 'submit': register_package, 'file_upload': upload_package, } if g.database.new_egg(request.form['name'].lower()): return actions[request.form[':action']](request)
Returns: ``'ok'`` """ contents = localproxy.files['content']
random_line_split
pypi.py
"""PyPi blueprint.""" import os from flask import Blueprint, current_app, g, request blueprint = Blueprint('pypi', __name__, url_prefix='/pypi') def register_package(localproxy): """Register a new package. Creates a folder on the filesystem so a new package can be uploaded. Arguments: localproxy (``werkzeug.local.LocalProxy``): The localproxy object is needed to read the ``form`` properties from the request Returns: ``'ok'`` """ package_dir = os.path.join(current_app.config['BASEDIR'], localproxy.form['name'].lower()) if not os.path.isdir(package_dir): os.mkdir(package_dir) return 'ok' def upload_package(localproxy): """Save a new package and it's md5 sum in a previously registered path. Arguments: localproxy (``werkzeug.local.LocalProxy``):The localproxy object is needed to read the ``form`` properties from the request Returns: ``'ok'`` """ contents = localproxy.files['content'] digest = localproxy.form['md5_digest'] file_path = os.path.join(current_app.config['BASEDIR'], localproxy.form['name'].lower(), contents.filename.lower()) contents.save(file_path) with open('{}.md5'.format(file_path), 'w') as md5_digest: md5_digest.write(digest) return 'ok' @blueprint.route('', methods=['POST']) def post_pypi():
"""Find a package and return the contents of it. Upon calling this endpoint the ``PRIVATE_EGGS`` set will be updated, and proper action will be taken based on the request. """ actions = { 'submit': register_package, 'file_upload': upload_package, } if g.database.new_egg(request.form['name'].lower()): return actions[request.form[':action']](request)
identifier_body
pypi.py
"""PyPi blueprint.""" import os from flask import Blueprint, current_app, g, request blueprint = Blueprint('pypi', __name__, url_prefix='/pypi') def
(localproxy): """Register a new package. Creates a folder on the filesystem so a new package can be uploaded. Arguments: localproxy (``werkzeug.local.LocalProxy``): The localproxy object is needed to read the ``form`` properties from the request Returns: ``'ok'`` """ package_dir = os.path.join(current_app.config['BASEDIR'], localproxy.form['name'].lower()) if not os.path.isdir(package_dir): os.mkdir(package_dir) return 'ok' def upload_package(localproxy): """Save a new package and it's md5 sum in a previously registered path. Arguments: localproxy (``werkzeug.local.LocalProxy``):The localproxy object is needed to read the ``form`` properties from the request Returns: ``'ok'`` """ contents = localproxy.files['content'] digest = localproxy.form['md5_digest'] file_path = os.path.join(current_app.config['BASEDIR'], localproxy.form['name'].lower(), contents.filename.lower()) contents.save(file_path) with open('{}.md5'.format(file_path), 'w') as md5_digest: md5_digest.write(digest) return 'ok' @blueprint.route('', methods=['POST']) def post_pypi(): """Find a package and return the contents of it. Upon calling this endpoint the ``PRIVATE_EGGS`` set will be updated, and proper action will be taken based on the request. """ actions = { 'submit': register_package, 'file_upload': upload_package, } if g.database.new_egg(request.form['name'].lower()): return actions[request.form[':action']](request)
register_package
identifier_name
partnersRoutes.ts
import loadable from "@loadable/component" import { graphql } from "react-relay" import { AppRouteConfig } from "v2/System/Router/Route" const GalleriesRoute = loadable( () => import(/* webpackChunkName: "partnersBundle" */ "./Routes/GalleriesRoute"), { resolveComponent: component => component.GalleriesRouteFragmentContainer } ) const InstitutionsRoute = loadable(
), { resolveComponent: component => component.InstitutionsRouteFragmentContainer, } ) export const partnersRoutes: AppRouteConfig[] = [ { path: "/galleries", getComponent: () => GalleriesRoute, onClientSideRender: () => { return GalleriesRoute.preload() }, query: graphql` query partnersRoutes_GalleriesRouteQuery { viewer { ...GalleriesRoute_viewer } } `, }, { path: "/institutions", getComponent: () => InstitutionsRoute, onClientSideRender: () => { return InstitutionsRoute.preload() }, query: graphql` query partnersRoutes_InstitutionsRouteQuery { viewer { ...InstitutionsRoute_viewer } } `, }, ]
() => import( /* webpackChunkName: "partnersBundle" */ "./Routes/InstitutionsRoute"
random_line_split
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] use anyhow::{anyhow, Error, Result}; use cloned::cloned; use context::CoreContext; use derived_data_manager::DerivationContext; use futures::{future, TryFutureExt, TryStreamExt}; use manifest::ManifestOps; use mononoke_types::{BonsaiChangeset, ChangesetId, FileUnodeId, MPath}; use std::collections::HashMap; use thiserror::Error; mod derive; mod mapping; pub use mapping::RootUnodeManifestId; #[derive(Debug, Error)] pub enum ErrorKind { #[error("Invalid bonsai changeset: {0}")] InvalidBonsai(String), } /// A rename source for a file that is renamed. #[derive(Debug, Clone)] pub struct UnodeRenameSource { /// Index of the parent changeset in the list of parents in the bonsai /// changeset. pub parent_index: usize, /// Path of the file in the parent changeset (i.e., the path it was /// renamed from). pub from_path: MPath, /// Unode ID of the file in the parent changeset. pub unode_id: FileUnodeId, } /// Given a bonsai changeset, find sources for all of the renames that /// happened in this changeset. /// /// Returns a mapping from paths in the current changeset to the source of the /// rename in the parent changesets. pub async fn find_unode_rename_sources( ctx: &CoreContext, derivation_ctx: &DerivationContext, bonsai: &BonsaiChangeset, ) -> Result<HashMap<MPath, UnodeRenameSource>, Error> { // Collect together a map of (source_path -> [dest_paths]) for each parent // changeset. let mut references: HashMap<ChangesetId, HashMap<&MPath, Vec<&MPath>>> = HashMap::new(); for (to_path, file_change) in bonsai.file_changes() { if let Some((from_path, csid)) = file_change.copy_from() { references .entry(*csid) .or_insert_with(HashMap::new) .entry(from_path) .or_insert_with(Vec::new) .push(to_path); } } let blobstore = derivation_ctx.blobstore(); let sources_futs = references.into_iter().map(|(csid, mut paths)| { cloned!(blobstore); async move { let parent_index = bonsai.parents().position(|p| p == csid).ok_or_else(|| { anyhow!( "bonsai changeset {} contains invalid copy from parent: {}", bonsai.get_changeset_id(), csid ) })?; let mf_root = derivation_ctx .derive_dependency::<RootUnodeManifestId>(ctx, csid) .await?; let from_paths: Vec<_> = paths.keys().cloned().cloned().collect(); let unodes = mf_root .manifest_unode_id() .find_entries(ctx.clone(), blobstore, from_paths) .try_collect::<Vec<_>>() .await?; let mut sources = Vec::new(); for (from_path, entry) in unodes { if let (Some(from_path), Some(unode_id)) = (from_path, entry.into_leaf()) { if let Some(to_paths) = paths.remove(&from_path)
} } Ok(sources) } }); future::try_join_all(sources_futs) .map_ok(|unodes| unodes.into_iter().flatten().collect()) .await } /// Given bonsai changeset find unodes for all renames that happened in this changesest. /// /// Returns mapping from paths in current changeset to file unodes in parents changesets /// that were coppied to a given path. /// /// This version of the function is incorrect: it fails to take into account /// files that are copied multiple times. The function is retained for /// blame_v1 compatibility. pub async fn find_unode_renames_incorrect_for_blame_v1( ctx: &CoreContext, derivation_ctx: &DerivationContext, bonsai: &BonsaiChangeset, ) -> Result<HashMap<MPath, FileUnodeId>, Error> { let mut references: HashMap<ChangesetId, HashMap<MPath, MPath>> = HashMap::new(); for (to_path, file_change) in bonsai.file_changes() { if let Some((from_path, csid)) = file_change.copy_from() { references .entry(*csid) .or_default() .insert(from_path.clone(), to_path.clone()); } } let unodes = references.into_iter().map(|(csid, mut paths)| async move { let mf_root = derivation_ctx .derive_dependency::<RootUnodeManifestId>(ctx, csid) .await?; let from_paths: Vec<_> = paths.keys().cloned().collect(); let blobstore = derivation_ctx.blobstore(); mf_root .manifest_unode_id() .clone() .find_entries(ctx.clone(), blobstore.clone(), from_paths) .map_ok(|(from_path, entry)| Some((from_path?, entry.into_leaf()?))) .try_filter_map(future::ok) .try_collect::<Vec<_>>() .map_ok(move |unodes| { unodes .into_iter() .filter_map(|(from_path, unode_id)| Some((paths.remove(&from_path)?, unode_id))) .collect::<HashMap<_, _>>() }) .await }); future::try_join_all(unodes) .map_ok(|unodes| unodes.into_iter().flatten().collect()) .await } #[cfg(test)] mod tests { use anyhow::Result; use blobrepo::BlobRepo; use blobstore::Loadable; use borrowed::borrowed; use context::CoreContext; use fbinit::FacebookInit; use mononoke_types::MPath; use repo_derived_data::RepoDerivedDataRef; use tests_utils::CreateCommitContext; #[fbinit::test] async fn test_find_unode_rename_sources(fb: FacebookInit) -> Result<()> { let ctx = CoreContext::test_mock(fb); let repo: BlobRepo = test_repo_factory::build_empty()?; borrowed!(ctx, repo); let c1 = CreateCommitContext::new_root(ctx, repo) .add_file("file1", "content") .commit() .await?; let c2 = CreateCommitContext::new(ctx, repo, vec![c1]) .add_file("file2", "content") .commit() .await?; let c3 = CreateCommitContext::new(ctx, repo, vec![c1]) .add_file("file3", "content") .commit() .await?; let c4 = CreateCommitContext::new(ctx, repo, vec![c2, c3]) .add_file_with_copy_info("file1a", "content a", (c2, "file1")) .delete_file("file1") .add_file_with_copy_info("file2a", "content a", (c2, "file2")) .add_file_with_copy_info("file2b", "content b", (c2, "file2")) .add_file_with_copy_info("file3a", "content a", (c3, "file3")) .add_file_with_copy_info("file3b", "content b", (c3, "file3")) .commit() .await?; let bonsai = c4.load(ctx, repo.blobstore()).await?; let derivation_ctx = repo.repo_derived_data().manager().derivation_context(None); let renames = crate::find_unode_rename_sources(ctx, &derivation_ctx, &bonsai).await?; let check = |path: &str, parent_index: usize, from_path: &str| { let source = renames .get(&MPath::new(path).unwrap()) .expect("path should exist"); assert_eq!(source.parent_index, parent_index); assert_eq!(source.from_path, MPath::new(from_path).unwrap()); }; check("file1a", 0, "file1"); check("file2a", 0, "file2"); check("file2b", 0, "file2"); check("file3a", 1, "file3"); check("file3b", 1, "file3"); assert_eq!(renames.len(), 5); Ok(()) } }
{ for to_path in to_paths { sources.push(( to_path.clone(), UnodeRenameSource { parent_index, from_path: from_path.clone(), unode_id, }, )); } }
conditional_block
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] use anyhow::{anyhow, Error, Result}; use cloned::cloned; use context::CoreContext; use derived_data_manager::DerivationContext; use futures::{future, TryFutureExt, TryStreamExt}; use manifest::ManifestOps; use mononoke_types::{BonsaiChangeset, ChangesetId, FileUnodeId, MPath}; use std::collections::HashMap; use thiserror::Error; mod derive; mod mapping; pub use mapping::RootUnodeManifestId; #[derive(Debug, Error)] pub enum ErrorKind { #[error("Invalid bonsai changeset: {0}")] InvalidBonsai(String), } /// A rename source for a file that is renamed. #[derive(Debug, Clone)] pub struct UnodeRenameSource { /// Index of the parent changeset in the list of parents in the bonsai /// changeset. pub parent_index: usize, /// Path of the file in the parent changeset (i.e., the path it was /// renamed from). pub from_path: MPath, /// Unode ID of the file in the parent changeset. pub unode_id: FileUnodeId, } /// Given a bonsai changeset, find sources for all of the renames that /// happened in this changeset. /// /// Returns a mapping from paths in the current changeset to the source of the /// rename in the parent changesets. pub async fn find_unode_rename_sources( ctx: &CoreContext, derivation_ctx: &DerivationContext, bonsai: &BonsaiChangeset, ) -> Result<HashMap<MPath, UnodeRenameSource>, Error> { // Collect together a map of (source_path -> [dest_paths]) for each parent // changeset. let mut references: HashMap<ChangesetId, HashMap<&MPath, Vec<&MPath>>> = HashMap::new(); for (to_path, file_change) in bonsai.file_changes() { if let Some((from_path, csid)) = file_change.copy_from() { references .entry(*csid) .or_insert_with(HashMap::new) .entry(from_path) .or_insert_with(Vec::new) .push(to_path); } } let blobstore = derivation_ctx.blobstore(); let sources_futs = references.into_iter().map(|(csid, mut paths)| { cloned!(blobstore); async move { let parent_index = bonsai.parents().position(|p| p == csid).ok_or_else(|| { anyhow!( "bonsai changeset {} contains invalid copy from parent: {}", bonsai.get_changeset_id(), csid ) })?; let mf_root = derivation_ctx .derive_dependency::<RootUnodeManifestId>(ctx, csid) .await?; let from_paths: Vec<_> = paths.keys().cloned().cloned().collect(); let unodes = mf_root .manifest_unode_id() .find_entries(ctx.clone(), blobstore, from_paths) .try_collect::<Vec<_>>() .await?; let mut sources = Vec::new(); for (from_path, entry) in unodes { if let (Some(from_path), Some(unode_id)) = (from_path, entry.into_leaf()) { if let Some(to_paths) = paths.remove(&from_path) { for to_path in to_paths { sources.push(( to_path.clone(), UnodeRenameSource { parent_index, from_path: from_path.clone(), unode_id, }, )); } } } } Ok(sources) } }); future::try_join_all(sources_futs) .map_ok(|unodes| unodes.into_iter().flatten().collect()) .await } /// Given bonsai changeset find unodes for all renames that happened in this changesest. /// /// Returns mapping from paths in current changeset to file unodes in parents changesets /// that were coppied to a given path. /// /// This version of the function is incorrect: it fails to take into account /// files that are copied multiple times. The function is retained for /// blame_v1 compatibility. pub async fn find_unode_renames_incorrect_for_blame_v1( ctx: &CoreContext, derivation_ctx: &DerivationContext, bonsai: &BonsaiChangeset, ) -> Result<HashMap<MPath, FileUnodeId>, Error> { let mut references: HashMap<ChangesetId, HashMap<MPath, MPath>> = HashMap::new(); for (to_path, file_change) in bonsai.file_changes() { if let Some((from_path, csid)) = file_change.copy_from() { references .entry(*csid) .or_default() .insert(from_path.clone(), to_path.clone()); } } let unodes = references.into_iter().map(|(csid, mut paths)| async move { let mf_root = derivation_ctx .derive_dependency::<RootUnodeManifestId>(ctx, csid) .await?; let from_paths: Vec<_> = paths.keys().cloned().collect(); let blobstore = derivation_ctx.blobstore(); mf_root .manifest_unode_id() .clone() .find_entries(ctx.clone(), blobstore.clone(), from_paths) .map_ok(|(from_path, entry)| Some((from_path?, entry.into_leaf()?))) .try_filter_map(future::ok) .try_collect::<Vec<_>>() .map_ok(move |unodes| { unodes .into_iter()
.collect::<HashMap<_, _>>() }) .await }); future::try_join_all(unodes) .map_ok(|unodes| unodes.into_iter().flatten().collect()) .await } #[cfg(test)] mod tests { use anyhow::Result; use blobrepo::BlobRepo; use blobstore::Loadable; use borrowed::borrowed; use context::CoreContext; use fbinit::FacebookInit; use mononoke_types::MPath; use repo_derived_data::RepoDerivedDataRef; use tests_utils::CreateCommitContext; #[fbinit::test] async fn test_find_unode_rename_sources(fb: FacebookInit) -> Result<()> { let ctx = CoreContext::test_mock(fb); let repo: BlobRepo = test_repo_factory::build_empty()?; borrowed!(ctx, repo); let c1 = CreateCommitContext::new_root(ctx, repo) .add_file("file1", "content") .commit() .await?; let c2 = CreateCommitContext::new(ctx, repo, vec![c1]) .add_file("file2", "content") .commit() .await?; let c3 = CreateCommitContext::new(ctx, repo, vec![c1]) .add_file("file3", "content") .commit() .await?; let c4 = CreateCommitContext::new(ctx, repo, vec![c2, c3]) .add_file_with_copy_info("file1a", "content a", (c2, "file1")) .delete_file("file1") .add_file_with_copy_info("file2a", "content a", (c2, "file2")) .add_file_with_copy_info("file2b", "content b", (c2, "file2")) .add_file_with_copy_info("file3a", "content a", (c3, "file3")) .add_file_with_copy_info("file3b", "content b", (c3, "file3")) .commit() .await?; let bonsai = c4.load(ctx, repo.blobstore()).await?; let derivation_ctx = repo.repo_derived_data().manager().derivation_context(None); let renames = crate::find_unode_rename_sources(ctx, &derivation_ctx, &bonsai).await?; let check = |path: &str, parent_index: usize, from_path: &str| { let source = renames .get(&MPath::new(path).unwrap()) .expect("path should exist"); assert_eq!(source.parent_index, parent_index); assert_eq!(source.from_path, MPath::new(from_path).unwrap()); }; check("file1a", 0, "file1"); check("file2a", 0, "file2"); check("file2b", 0, "file2"); check("file3a", 1, "file3"); check("file3b", 1, "file3"); assert_eq!(renames.len(), 5); Ok(()) } }
.filter_map(|(from_path, unode_id)| Some((paths.remove(&from_path)?, unode_id)))
random_line_split
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] use anyhow::{anyhow, Error, Result}; use cloned::cloned; use context::CoreContext; use derived_data_manager::DerivationContext; use futures::{future, TryFutureExt, TryStreamExt}; use manifest::ManifestOps; use mononoke_types::{BonsaiChangeset, ChangesetId, FileUnodeId, MPath}; use std::collections::HashMap; use thiserror::Error; mod derive; mod mapping; pub use mapping::RootUnodeManifestId; #[derive(Debug, Error)] pub enum ErrorKind { #[error("Invalid bonsai changeset: {0}")] InvalidBonsai(String), } /// A rename source for a file that is renamed. #[derive(Debug, Clone)] pub struct
{ /// Index of the parent changeset in the list of parents in the bonsai /// changeset. pub parent_index: usize, /// Path of the file in the parent changeset (i.e., the path it was /// renamed from). pub from_path: MPath, /// Unode ID of the file in the parent changeset. pub unode_id: FileUnodeId, } /// Given a bonsai changeset, find sources for all of the renames that /// happened in this changeset. /// /// Returns a mapping from paths in the current changeset to the source of the /// rename in the parent changesets. pub async fn find_unode_rename_sources( ctx: &CoreContext, derivation_ctx: &DerivationContext, bonsai: &BonsaiChangeset, ) -> Result<HashMap<MPath, UnodeRenameSource>, Error> { // Collect together a map of (source_path -> [dest_paths]) for each parent // changeset. let mut references: HashMap<ChangesetId, HashMap<&MPath, Vec<&MPath>>> = HashMap::new(); for (to_path, file_change) in bonsai.file_changes() { if let Some((from_path, csid)) = file_change.copy_from() { references .entry(*csid) .or_insert_with(HashMap::new) .entry(from_path) .or_insert_with(Vec::new) .push(to_path); } } let blobstore = derivation_ctx.blobstore(); let sources_futs = references.into_iter().map(|(csid, mut paths)| { cloned!(blobstore); async move { let parent_index = bonsai.parents().position(|p| p == csid).ok_or_else(|| { anyhow!( "bonsai changeset {} contains invalid copy from parent: {}", bonsai.get_changeset_id(), csid ) })?; let mf_root = derivation_ctx .derive_dependency::<RootUnodeManifestId>(ctx, csid) .await?; let from_paths: Vec<_> = paths.keys().cloned().cloned().collect(); let unodes = mf_root .manifest_unode_id() .find_entries(ctx.clone(), blobstore, from_paths) .try_collect::<Vec<_>>() .await?; let mut sources = Vec::new(); for (from_path, entry) in unodes { if let (Some(from_path), Some(unode_id)) = (from_path, entry.into_leaf()) { if let Some(to_paths) = paths.remove(&from_path) { for to_path in to_paths { sources.push(( to_path.clone(), UnodeRenameSource { parent_index, from_path: from_path.clone(), unode_id, }, )); } } } } Ok(sources) } }); future::try_join_all(sources_futs) .map_ok(|unodes| unodes.into_iter().flatten().collect()) .await } /// Given bonsai changeset find unodes for all renames that happened in this changesest. /// /// Returns mapping from paths in current changeset to file unodes in parents changesets /// that were coppied to a given path. /// /// This version of the function is incorrect: it fails to take into account /// files that are copied multiple times. The function is retained for /// blame_v1 compatibility. pub async fn find_unode_renames_incorrect_for_blame_v1( ctx: &CoreContext, derivation_ctx: &DerivationContext, bonsai: &BonsaiChangeset, ) -> Result<HashMap<MPath, FileUnodeId>, Error> { let mut references: HashMap<ChangesetId, HashMap<MPath, MPath>> = HashMap::new(); for (to_path, file_change) in bonsai.file_changes() { if let Some((from_path, csid)) = file_change.copy_from() { references .entry(*csid) .or_default() .insert(from_path.clone(), to_path.clone()); } } let unodes = references.into_iter().map(|(csid, mut paths)| async move { let mf_root = derivation_ctx .derive_dependency::<RootUnodeManifestId>(ctx, csid) .await?; let from_paths: Vec<_> = paths.keys().cloned().collect(); let blobstore = derivation_ctx.blobstore(); mf_root .manifest_unode_id() .clone() .find_entries(ctx.clone(), blobstore.clone(), from_paths) .map_ok(|(from_path, entry)| Some((from_path?, entry.into_leaf()?))) .try_filter_map(future::ok) .try_collect::<Vec<_>>() .map_ok(move |unodes| { unodes .into_iter() .filter_map(|(from_path, unode_id)| Some((paths.remove(&from_path)?, unode_id))) .collect::<HashMap<_, _>>() }) .await }); future::try_join_all(unodes) .map_ok(|unodes| unodes.into_iter().flatten().collect()) .await } #[cfg(test)] mod tests { use anyhow::Result; use blobrepo::BlobRepo; use blobstore::Loadable; use borrowed::borrowed; use context::CoreContext; use fbinit::FacebookInit; use mononoke_types::MPath; use repo_derived_data::RepoDerivedDataRef; use tests_utils::CreateCommitContext; #[fbinit::test] async fn test_find_unode_rename_sources(fb: FacebookInit) -> Result<()> { let ctx = CoreContext::test_mock(fb); let repo: BlobRepo = test_repo_factory::build_empty()?; borrowed!(ctx, repo); let c1 = CreateCommitContext::new_root(ctx, repo) .add_file("file1", "content") .commit() .await?; let c2 = CreateCommitContext::new(ctx, repo, vec![c1]) .add_file("file2", "content") .commit() .await?; let c3 = CreateCommitContext::new(ctx, repo, vec![c1]) .add_file("file3", "content") .commit() .await?; let c4 = CreateCommitContext::new(ctx, repo, vec![c2, c3]) .add_file_with_copy_info("file1a", "content a", (c2, "file1")) .delete_file("file1") .add_file_with_copy_info("file2a", "content a", (c2, "file2")) .add_file_with_copy_info("file2b", "content b", (c2, "file2")) .add_file_with_copy_info("file3a", "content a", (c3, "file3")) .add_file_with_copy_info("file3b", "content b", (c3, "file3")) .commit() .await?; let bonsai = c4.load(ctx, repo.blobstore()).await?; let derivation_ctx = repo.repo_derived_data().manager().derivation_context(None); let renames = crate::find_unode_rename_sources(ctx, &derivation_ctx, &bonsai).await?; let check = |path: &str, parent_index: usize, from_path: &str| { let source = renames .get(&MPath::new(path).unwrap()) .expect("path should exist"); assert_eq!(source.parent_index, parent_index); assert_eq!(source.from_path, MPath::new(from_path).unwrap()); }; check("file1a", 0, "file1"); check("file2a", 0, "file2"); check("file2b", 0, "file2"); check("file3a", 1, "file3"); check("file3b", 1, "file3"); assert_eq!(renames.len(), 5); Ok(()) } }
UnodeRenameSource
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] use anyhow::{anyhow, Error, Result}; use cloned::cloned; use context::CoreContext; use derived_data_manager::DerivationContext; use futures::{future, TryFutureExt, TryStreamExt}; use manifest::ManifestOps; use mononoke_types::{BonsaiChangeset, ChangesetId, FileUnodeId, MPath}; use std::collections::HashMap; use thiserror::Error; mod derive; mod mapping; pub use mapping::RootUnodeManifestId; #[derive(Debug, Error)] pub enum ErrorKind { #[error("Invalid bonsai changeset: {0}")] InvalidBonsai(String), } /// A rename source for a file that is renamed. #[derive(Debug, Clone)] pub struct UnodeRenameSource { /// Index of the parent changeset in the list of parents in the bonsai /// changeset. pub parent_index: usize, /// Path of the file in the parent changeset (i.e., the path it was /// renamed from). pub from_path: MPath, /// Unode ID of the file in the parent changeset. pub unode_id: FileUnodeId, } /// Given a bonsai changeset, find sources for all of the renames that /// happened in this changeset. /// /// Returns a mapping from paths in the current changeset to the source of the /// rename in the parent changesets. pub async fn find_unode_rename_sources( ctx: &CoreContext, derivation_ctx: &DerivationContext, bonsai: &BonsaiChangeset, ) -> Result<HashMap<MPath, UnodeRenameSource>, Error>
/// Given bonsai changeset find unodes for all renames that happened in this changesest. /// /// Returns mapping from paths in current changeset to file unodes in parents changesets /// that were coppied to a given path. /// /// This version of the function is incorrect: it fails to take into account /// files that are copied multiple times. The function is retained for /// blame_v1 compatibility. pub async fn find_unode_renames_incorrect_for_blame_v1( ctx: &CoreContext, derivation_ctx: &DerivationContext, bonsai: &BonsaiChangeset, ) -> Result<HashMap<MPath, FileUnodeId>, Error> { let mut references: HashMap<ChangesetId, HashMap<MPath, MPath>> = HashMap::new(); for (to_path, file_change) in bonsai.file_changes() { if let Some((from_path, csid)) = file_change.copy_from() { references .entry(*csid) .or_default() .insert(from_path.clone(), to_path.clone()); } } let unodes = references.into_iter().map(|(csid, mut paths)| async move { let mf_root = derivation_ctx .derive_dependency::<RootUnodeManifestId>(ctx, csid) .await?; let from_paths: Vec<_> = paths.keys().cloned().collect(); let blobstore = derivation_ctx.blobstore(); mf_root .manifest_unode_id() .clone() .find_entries(ctx.clone(), blobstore.clone(), from_paths) .map_ok(|(from_path, entry)| Some((from_path?, entry.into_leaf()?))) .try_filter_map(future::ok) .try_collect::<Vec<_>>() .map_ok(move |unodes| { unodes .into_iter() .filter_map(|(from_path, unode_id)| Some((paths.remove(&from_path)?, unode_id))) .collect::<HashMap<_, _>>() }) .await }); future::try_join_all(unodes) .map_ok(|unodes| unodes.into_iter().flatten().collect()) .await } #[cfg(test)] mod tests { use anyhow::Result; use blobrepo::BlobRepo; use blobstore::Loadable; use borrowed::borrowed; use context::CoreContext; use fbinit::FacebookInit; use mononoke_types::MPath; use repo_derived_data::RepoDerivedDataRef; use tests_utils::CreateCommitContext; #[fbinit::test] async fn test_find_unode_rename_sources(fb: FacebookInit) -> Result<()> { let ctx = CoreContext::test_mock(fb); let repo: BlobRepo = test_repo_factory::build_empty()?; borrowed!(ctx, repo); let c1 = CreateCommitContext::new_root(ctx, repo) .add_file("file1", "content") .commit() .await?; let c2 = CreateCommitContext::new(ctx, repo, vec![c1]) .add_file("file2", "content") .commit() .await?; let c3 = CreateCommitContext::new(ctx, repo, vec![c1]) .add_file("file3", "content") .commit() .await?; let c4 = CreateCommitContext::new(ctx, repo, vec![c2, c3]) .add_file_with_copy_info("file1a", "content a", (c2, "file1")) .delete_file("file1") .add_file_with_copy_info("file2a", "content a", (c2, "file2")) .add_file_with_copy_info("file2b", "content b", (c2, "file2")) .add_file_with_copy_info("file3a", "content a", (c3, "file3")) .add_file_with_copy_info("file3b", "content b", (c3, "file3")) .commit() .await?; let bonsai = c4.load(ctx, repo.blobstore()).await?; let derivation_ctx = repo.repo_derived_data().manager().derivation_context(None); let renames = crate::find_unode_rename_sources(ctx, &derivation_ctx, &bonsai).await?; let check = |path: &str, parent_index: usize, from_path: &str| { let source = renames .get(&MPath::new(path).unwrap()) .expect("path should exist"); assert_eq!(source.parent_index, parent_index); assert_eq!(source.from_path, MPath::new(from_path).unwrap()); }; check("file1a", 0, "file1"); check("file2a", 0, "file2"); check("file2b", 0, "file2"); check("file3a", 1, "file3"); check("file3b", 1, "file3"); assert_eq!(renames.len(), 5); Ok(()) } }
{ // Collect together a map of (source_path -> [dest_paths]) for each parent // changeset. let mut references: HashMap<ChangesetId, HashMap<&MPath, Vec<&MPath>>> = HashMap::new(); for (to_path, file_change) in bonsai.file_changes() { if let Some((from_path, csid)) = file_change.copy_from() { references .entry(*csid) .or_insert_with(HashMap::new) .entry(from_path) .or_insert_with(Vec::new) .push(to_path); } } let blobstore = derivation_ctx.blobstore(); let sources_futs = references.into_iter().map(|(csid, mut paths)| { cloned!(blobstore); async move { let parent_index = bonsai.parents().position(|p| p == csid).ok_or_else(|| { anyhow!( "bonsai changeset {} contains invalid copy from parent: {}", bonsai.get_changeset_id(), csid ) })?; let mf_root = derivation_ctx .derive_dependency::<RootUnodeManifestId>(ctx, csid) .await?; let from_paths: Vec<_> = paths.keys().cloned().cloned().collect(); let unodes = mf_root .manifest_unode_id() .find_entries(ctx.clone(), blobstore, from_paths) .try_collect::<Vec<_>>() .await?; let mut sources = Vec::new(); for (from_path, entry) in unodes { if let (Some(from_path), Some(unode_id)) = (from_path, entry.into_leaf()) { if let Some(to_paths) = paths.remove(&from_path) { for to_path in to_paths { sources.push(( to_path.clone(), UnodeRenameSource { parent_index, from_path: from_path.clone(), unode_id, }, )); } } } } Ok(sources) } }); future::try_join_all(sources_futs) .map_ok(|unodes| unodes.into_iter().flatten().collect()) .await }
identifier_body
seventeen.rs
use std::string::ToString; fn singler<'a>(digit: u32) -> &'a str { match digit { 0 => "zero", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine", _ => "", } } fn twentor<'a>(num: u32) -> &'a str { match num { 0...9 => singler(num), 10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen", 14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen", 18 => "eighteen", 19 => "nineteen", _ => "", } } fn hunnert<'a>(num: u32) -> String { match num { 0...19 => twentor(num).to_string(), 20 => "twenty".to_string(), 21...29 => format!("twenty-{}", singler(num % 20)), 30 => "thirty".to_string(), 31...39 => format!("thirty-{}", singler(num % 30)), 40 => "forty".to_string(), 41...49 => format!("forty-{}", singler(num % 40)), 50 => "fifty".to_string(), 51...59 => format!("fifty-{}", singler(num % 50)), 60 => "sixty".to_string(), 61...69 => format!("sixty-{}", singler(num % 60)), 70 => "seventy".to_string(), 71...79 => format!("seventy-{}", singler(num % 70)), 80 => "eighty".to_string(),
} fn thouse(num: u32) -> String { match num { 0...99 => hunnert(num).to_string(), 100 => "one hundred".to_string(), 101...199 => format!("one hundred and {}", hunnert(num % 100)), 200 => "two hundred".to_string(), 201...299 => format!("two hundred and {}", hunnert(num % 100)), 300 => "three hundred".to_string(), 301...399 => format!("three hundred and {}", hunnert(num % 100)), 400 => "four hundred".to_string(), 401...499 => format!("four hundred and {}", hunnert(num % 100)), 500 => "five hundred".to_string(), 501...599 => format!("five hundred and {}", hunnert(num % 100)), 600 => "six hundred".to_string(), 601...699 => format!("six hundred and {}", hunnert(num % 100)), 700 => "seven hundred".to_string(), 701...799 => format!("seven hundred and {}", hunnert(num % 100)), 800 => "eight hundred".to_string(), 801...899 => format!("eight hundred and {}", hunnert(num % 100)), 900 => "nine hundred".to_string(), 901...999 => format!("nine hundred and {}", hunnert(num % 100)), 1000 => "one thousand".to_string(), _ => "".to_string(), } } fn count(s: String) -> u32 { s.chars().fold(0, |memo, ch| { memo + match ch { 'a'...'z' => 1, _ => 0, } }) } pub fn run() { let sum: u32 = (1..1001).map(|i| count(thouse(i))).sum(); println!("Sum of number words: {}", sum); }
81...89 => format!("eighty-{}", singler(num % 80)), 90 => "ninety".to_string(), 91...99 => format!("ninety-{}", singler(num % 90)), _ => "".to_string(), }
random_line_split
seventeen.rs
use std::string::ToString; fn singler<'a>(digit: u32) -> &'a str { match digit { 0 => "zero", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine", _ => "", } } fn twentor<'a>(num: u32) -> &'a str
fn hunnert<'a>(num: u32) -> String { match num { 0...19 => twentor(num).to_string(), 20 => "twenty".to_string(), 21...29 => format!("twenty-{}", singler(num % 20)), 30 => "thirty".to_string(), 31...39 => format!("thirty-{}", singler(num % 30)), 40 => "forty".to_string(), 41...49 => format!("forty-{}", singler(num % 40)), 50 => "fifty".to_string(), 51...59 => format!("fifty-{}", singler(num % 50)), 60 => "sixty".to_string(), 61...69 => format!("sixty-{}", singler(num % 60)), 70 => "seventy".to_string(), 71...79 => format!("seventy-{}", singler(num % 70)), 80 => "eighty".to_string(), 81...89 => format!("eighty-{}", singler(num % 80)), 90 => "ninety".to_string(), 91...99 => format!("ninety-{}", singler(num % 90)), _ => "".to_string(), } } fn thouse(num: u32) -> String { match num { 0...99 => hunnert(num).to_string(), 100 => "one hundred".to_string(), 101...199 => format!("one hundred and {}", hunnert(num % 100)), 200 => "two hundred".to_string(), 201...299 => format!("two hundred and {}", hunnert(num % 100)), 300 => "three hundred".to_string(), 301...399 => format!("three hundred and {}", hunnert(num % 100)), 400 => "four hundred".to_string(), 401...499 => format!("four hundred and {}", hunnert(num % 100)), 500 => "five hundred".to_string(), 501...599 => format!("five hundred and {}", hunnert(num % 100)), 600 => "six hundred".to_string(), 601...699 => format!("six hundred and {}", hunnert(num % 100)), 700 => "seven hundred".to_string(), 701...799 => format!("seven hundred and {}", hunnert(num % 100)), 800 => "eight hundred".to_string(), 801...899 => format!("eight hundred and {}", hunnert(num % 100)), 900 => "nine hundred".to_string(), 901...999 => format!("nine hundred and {}", hunnert(num % 100)), 1000 => "one thousand".to_string(), _ => "".to_string(), } } fn count(s: String) -> u32 { s.chars().fold(0, |memo, ch| { memo + match ch { 'a'...'z' => 1, _ => 0, } }) } pub fn run() { let sum: u32 = (1..1001).map(|i| count(thouse(i))).sum(); println!("Sum of number words: {}", sum); }
{ match num { 0...9 => singler(num), 10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen", 14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen", 18 => "eighteen", 19 => "nineteen", _ => "", } }
identifier_body
seventeen.rs
use std::string::ToString; fn singler<'a>(digit: u32) -> &'a str { match digit { 0 => "zero", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine", _ => "", } } fn twentor<'a>(num: u32) -> &'a str { match num { 0...9 => singler(num), 10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen", 14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen", 18 => "eighteen", 19 => "nineteen", _ => "", } } fn hunnert<'a>(num: u32) -> String { match num { 0...19 => twentor(num).to_string(), 20 => "twenty".to_string(), 21...29 => format!("twenty-{}", singler(num % 20)), 30 => "thirty".to_string(), 31...39 => format!("thirty-{}", singler(num % 30)), 40 => "forty".to_string(), 41...49 => format!("forty-{}", singler(num % 40)), 50 => "fifty".to_string(), 51...59 => format!("fifty-{}", singler(num % 50)), 60 => "sixty".to_string(), 61...69 => format!("sixty-{}", singler(num % 60)), 70 => "seventy".to_string(), 71...79 => format!("seventy-{}", singler(num % 70)), 80 => "eighty".to_string(), 81...89 => format!("eighty-{}", singler(num % 80)), 90 => "ninety".to_string(), 91...99 => format!("ninety-{}", singler(num % 90)), _ => "".to_string(), } } fn thouse(num: u32) -> String { match num { 0...99 => hunnert(num).to_string(), 100 => "one hundred".to_string(), 101...199 => format!("one hundred and {}", hunnert(num % 100)), 200 => "two hundred".to_string(), 201...299 => format!("two hundred and {}", hunnert(num % 100)), 300 => "three hundred".to_string(), 301...399 => format!("three hundred and {}", hunnert(num % 100)), 400 => "four hundred".to_string(), 401...499 => format!("four hundred and {}", hunnert(num % 100)), 500 => "five hundred".to_string(), 501...599 => format!("five hundred and {}", hunnert(num % 100)), 600 => "six hundred".to_string(), 601...699 => format!("six hundred and {}", hunnert(num % 100)), 700 => "seven hundred".to_string(), 701...799 => format!("seven hundred and {}", hunnert(num % 100)), 800 => "eight hundred".to_string(), 801...899 => format!("eight hundred and {}", hunnert(num % 100)), 900 => "nine hundred".to_string(), 901...999 => format!("nine hundred and {}", hunnert(num % 100)), 1000 => "one thousand".to_string(), _ => "".to_string(), } } fn
(s: String) -> u32 { s.chars().fold(0, |memo, ch| { memo + match ch { 'a'...'z' => 1, _ => 0, } }) } pub fn run() { let sum: u32 = (1..1001).map(|i| count(thouse(i))).sum(); println!("Sum of number words: {}", sum); }
count
identifier_name
test_views.py
""" Tests for django-registration's built-in views. """ from django.core.urlresolvers import reverse from django.test import override_settings, TestCase from ..models import RegistrationProfile @override_settings(ROOT_URLCONF='registration.tests.urls') class ActivationViewTests(TestCase): """ Tests for aspects of the activation view not currently exercised by any built-in workflow. """ @override_settings(ACCOUNT_ACTIVATION_DAYS=7) def test_activation(self):
""" Activation of an account functions properly when using a simple string URL as the success redirect. """ data = { 'username': 'bob', 'email': 'bob@example.com', 'password1': 'secret', 'password2': 'secret' } resp = self.client.post( reverse('registration_register'), data=data ) profile = RegistrationProfile.objects.get( user__username=data['username'] ) resp = self.client.get( reverse( 'registration_activate', args=(), kwargs={'activation_key': profile.activation_key} ) ) self.assertRedirects(resp, '/')
identifier_body
test_views.py
""" Tests for django-registration's built-in views. """ from django.core.urlresolvers import reverse from django.test import override_settings, TestCase from ..models import RegistrationProfile @override_settings(ROOT_URLCONF='registration.tests.urls') class ActivationViewTests(TestCase): """ Tests for aspects of the activation view not currently exercised by any built-in workflow. """ @override_settings(ACCOUNT_ACTIVATION_DAYS=7) def test_activation(self): """ Activation of an account functions properly when using a simple string URL as the success redirect. """ data = { 'username': 'bob', 'email': 'bob@example.com', 'password1': 'secret', 'password2': 'secret' } resp = self.client.post( reverse('registration_register'), data=data ) profile = RegistrationProfile.objects.get( user__username=data['username'] )
'registration_activate', args=(), kwargs={'activation_key': profile.activation_key} ) ) self.assertRedirects(resp, '/')
resp = self.client.get( reverse(
random_line_split
test_views.py
""" Tests for django-registration's built-in views. """ from django.core.urlresolvers import reverse from django.test import override_settings, TestCase from ..models import RegistrationProfile @override_settings(ROOT_URLCONF='registration.tests.urls') class
(TestCase): """ Tests for aspects of the activation view not currently exercised by any built-in workflow. """ @override_settings(ACCOUNT_ACTIVATION_DAYS=7) def test_activation(self): """ Activation of an account functions properly when using a simple string URL as the success redirect. """ data = { 'username': 'bob', 'email': 'bob@example.com', 'password1': 'secret', 'password2': 'secret' } resp = self.client.post( reverse('registration_register'), data=data ) profile = RegistrationProfile.objects.get( user__username=data['username'] ) resp = self.client.get( reverse( 'registration_activate', args=(), kwargs={'activation_key': profile.activation_key} ) ) self.assertRedirects(resp, '/')
ActivationViewTests
identifier_name
error.tsx
import React, { FunctionComponent } from "react" import path from "path" import { Box, Text } from "ink" import { IStructuredError } from "../../../../structured-errors/types" interface IFileProps { filePath: string location: IStructuredError["location"] } const File: FunctionComponent<IFileProps> = ({ filePath, location }) => { const lineNumber = location?.start.line let locString = `` if (typeof lineNumber !== `undefined`) { locString += `:${lineNumber}` const columnNumber = location?.start.column
locString += `:${columnNumber}` } } return ( <Text color="blue"> {path.relative(process.cwd(), filePath)} {locString} </Text> ) } interface IDocsLinkProps { docsUrl: string | undefined } const DocsLink: FunctionComponent<IDocsLinkProps> = ({ docsUrl }) => { // TODO: when there's no specific docsUrl, add helpful message describing how // to submit an issue if (docsUrl === `https://gatsby.dev/issue-how-to`) return null return ( <Box marginTop={1}> <Text>See our docs page for more info on this error: {docsUrl}</Text> </Box> ) } export interface IErrorProps { details: IStructuredError } export const Error: FunctionComponent<IErrorProps> = React.memo( ({ details }) => ( // const stackLength = get(details, `stack.length`, 0 <Box marginY={1} flexDirection="column"> <Box flexDirection="column"> <Box flexDirection="column"> <Box> <Box marginRight={1}> <Text color="black" backgroundColor="red"> {` ${details.level} `} {details.code ? `#${details.code} ` : ``} </Text> <Text color="red">{details.type ? ` ` + details.type : ``}</Text> </Box> </Box> <Box marginTop={1}> <Text>{details.text}</Text> </Box> {details.filePath && ( <Box marginTop={1}> <Text>File:{` `}</Text> <File filePath={details.filePath} location={details.location} /> </Box> )} </Box> <DocsLink docsUrl={details.docsUrl} /> </Box> {/* TODO: use this to replace errorFormatter.render in reporter.error func {stackLength > 0 && ( <Box> <Color> <Box flexDirection="column"> <Box>Error stack:</Box> {details.stack.map((item, id) => ( <Box key={id}> {item.fileName && `${item.fileName} line ${item.lineNumber}`} </Box> ))} </Box> </Color> </Box> )} */} </Box> ) )
if (typeof columnNumber !== `undefined`) {
random_line_split
error.tsx
import React, { FunctionComponent } from "react" import path from "path" import { Box, Text } from "ink" import { IStructuredError } from "../../../../structured-errors/types" interface IFileProps { filePath: string location: IStructuredError["location"] } const File: FunctionComponent<IFileProps> = ({ filePath, location }) => { const lineNumber = location?.start.line let locString = `` if (typeof lineNumber !== `undefined`)
return ( <Text color="blue"> {path.relative(process.cwd(), filePath)} {locString} </Text> ) } interface IDocsLinkProps { docsUrl: string | undefined } const DocsLink: FunctionComponent<IDocsLinkProps> = ({ docsUrl }) => { // TODO: when there's no specific docsUrl, add helpful message describing how // to submit an issue if (docsUrl === `https://gatsby.dev/issue-how-to`) return null return ( <Box marginTop={1}> <Text>See our docs page for more info on this error: {docsUrl}</Text> </Box> ) } export interface IErrorProps { details: IStructuredError } export const Error: FunctionComponent<IErrorProps> = React.memo( ({ details }) => ( // const stackLength = get(details, `stack.length`, 0 <Box marginY={1} flexDirection="column"> <Box flexDirection="column"> <Box flexDirection="column"> <Box> <Box marginRight={1}> <Text color="black" backgroundColor="red"> {` ${details.level} `} {details.code ? `#${details.code} ` : ``} </Text> <Text color="red">{details.type ? ` ` + details.type : ``}</Text> </Box> </Box> <Box marginTop={1}> <Text>{details.text}</Text> </Box> {details.filePath && ( <Box marginTop={1}> <Text>File:{` `}</Text> <File filePath={details.filePath} location={details.location} /> </Box> )} </Box> <DocsLink docsUrl={details.docsUrl} /> </Box> {/* TODO: use this to replace errorFormatter.render in reporter.error func {stackLength > 0 && ( <Box> <Color> <Box flexDirection="column"> <Box>Error stack:</Box> {details.stack.map((item, id) => ( <Box key={id}> {item.fileName && `${item.fileName} line ${item.lineNumber}`} </Box> ))} </Box> </Color> </Box> )} */} </Box> ) )
{ locString += `:${lineNumber}` const columnNumber = location?.start.column if (typeof columnNumber !== `undefined`) { locString += `:${columnNumber}` } }
conditional_block
post_anju.py
#!/usr/bin/env python #-*- coding:utf-8 -*- from poster.encode import multipart_encode from poster.streaminghttp import register_openers import urllib2,urllib,sys,time import cookielib,mechanize import re DEBUG =0 reload(sys) sys.setdefaultencoding('utf8') #@UndefinedVariable register_openers() headers = { 'Host':'agent.anjuke.com', 'User-Agent' : 'Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20100101 Firefox/4.0.1', #'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', #'Accept-Language':'zh-cn,zh;q=0.5', #'Accept-Encoding':'gzip, deflate', #'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7', 'Keep-Alive':'115', 'Connection':'keep-alive', } #datagen11, headers = multipart_encode({"fileUploadInput": open("/home/myapp/Screenshot-1.jpg","rb"),"backFunction": "$.c.Uploader.finish"}) class httpPost(): data = {} def __init__(self,dataDic): self.cookie = cookielib.CookieJar() httpsHandler = urllib2.HTTPHandler() httpsHandler.set_http_debuglevel(DEBUG) self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie),httpsHandler) self.data = dataDic def login1(self): self.brow = mechanize.Browser() httpHandler = mechanize.HTTPHandler() httpsHandler = mechanize.HTTPSHandler() httpHandler.set_http_debuglevel(DEBUG) self.cookiejar = mechanize.LWPCookieJar() #self.cookiejar = "Cookie lzstat_uv=34741959842666604402|1786789; Hm_lvt_976797cb85805d626fc5642aa5244ba0=1304534271541; ASPSESSIONIDQCDRAQBB=JHCHINLAHGMAIGBIFMNANLGF; lzstat_ss=2189193215_2_1304564199_1786789; Hm_lpvt_976797cb85805d626fc5642aa5244ba0=1304535401191" self.opener = mechanize.OpenerFactory(mechanize.SeekableResponseOpener).build_opener( httpHandler,httpsHandler, mechanize.HTTPCookieProcessor(self.cookiejar), mechanize.HTTPRefererProcessor, mechanize.HTTPEquivProcessor, mechanize.HTTPRefreshProcessor, ) self.opener.addheaders = [("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"), ("From", "")] #self.opener.addheaders = [( # "Referer", self.data['postUrl'] # )] login={} login['method'] = self.data['method'] login['name'] = self.data['name'] login['pwd'] = self.data['pwd'] loginUrl = self.data['loginUrl']+'?'+urllib.urlencode(login) print loginUrl response = mechanize.urlopen("http://esf.soufun.com/") response = mechanize.urlopen(loginUrl) print response.read().decode('gb2312') def login(self): self.cookie = cookielib.CookieJar() httpsHandler = urllib2.HTTPHandler() httpsHandler.set_http_debuglevel(DEBUG) self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie),httpsHandler) login={} login['act'] = self.data['act'] login['loginName'] = self.data['loginName'] login['history'] = '' login['loginPasswd'] = self.data['loginPasswd'] loginUrl = self.data['loginUrl'] req = urllib2.Request(loginUrl,urllib.urlencode(login),headers) r = self.opener.open(req) res = None for item in self.cookie: #print item.name,item.value
return res #aQQ_ajklastuser junyue_liuhua #print self.opener.open('http://my.anjuke.com/v2/user/broker/checked/').read() #open('login.txt','w').write(r.read().encode('utf-8')) def post(self): pass #postData = {} #postData['loginUrl'] = 'http://agent.anjuke.com/v2/login/' #postData['act'] = 'login' #postData['loginName'] = 'junyue_liuhua' #postData['loginPasswd'] = 'lh_131415' #http = httpPost(postData) #http.login()
if item.name == 'aQQ_ajklastuser': res = item.value
conditional_block
post_anju.py
#!/usr/bin/env python #-*- coding:utf-8 -*- from poster.encode import multipart_encode from poster.streaminghttp import register_openers import urllib2,urllib,sys,time import cookielib,mechanize import re DEBUG =0 reload(sys) sys.setdefaultencoding('utf8') #@UndefinedVariable register_openers() headers = { 'Host':'agent.anjuke.com', 'User-Agent' : 'Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20100101 Firefox/4.0.1', #'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', #'Accept-Language':'zh-cn,zh;q=0.5', #'Accept-Encoding':'gzip, deflate', #'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7', 'Keep-Alive':'115', 'Connection':'keep-alive', } #datagen11, headers = multipart_encode({"fileUploadInput": open("/home/myapp/Screenshot-1.jpg","rb"),"backFunction": "$.c.Uploader.finish"}) class httpPost(): data = {} def
(self,dataDic): self.cookie = cookielib.CookieJar() httpsHandler = urllib2.HTTPHandler() httpsHandler.set_http_debuglevel(DEBUG) self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie),httpsHandler) self.data = dataDic def login1(self): self.brow = mechanize.Browser() httpHandler = mechanize.HTTPHandler() httpsHandler = mechanize.HTTPSHandler() httpHandler.set_http_debuglevel(DEBUG) self.cookiejar = mechanize.LWPCookieJar() #self.cookiejar = "Cookie lzstat_uv=34741959842666604402|1786789; Hm_lvt_976797cb85805d626fc5642aa5244ba0=1304534271541; ASPSESSIONIDQCDRAQBB=JHCHINLAHGMAIGBIFMNANLGF; lzstat_ss=2189193215_2_1304564199_1786789; Hm_lpvt_976797cb85805d626fc5642aa5244ba0=1304535401191" self.opener = mechanize.OpenerFactory(mechanize.SeekableResponseOpener).build_opener( httpHandler,httpsHandler, mechanize.HTTPCookieProcessor(self.cookiejar), mechanize.HTTPRefererProcessor, mechanize.HTTPEquivProcessor, mechanize.HTTPRefreshProcessor, ) self.opener.addheaders = [("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"), ("From", "")] #self.opener.addheaders = [( # "Referer", self.data['postUrl'] # )] login={} login['method'] = self.data['method'] login['name'] = self.data['name'] login['pwd'] = self.data['pwd'] loginUrl = self.data['loginUrl']+'?'+urllib.urlencode(login) print loginUrl response = mechanize.urlopen("http://esf.soufun.com/") response = mechanize.urlopen(loginUrl) print response.read().decode('gb2312') def login(self): self.cookie = cookielib.CookieJar() httpsHandler = urllib2.HTTPHandler() httpsHandler.set_http_debuglevel(DEBUG) self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie),httpsHandler) login={} login['act'] = self.data['act'] login['loginName'] = self.data['loginName'] login['history'] = '' login['loginPasswd'] = self.data['loginPasswd'] loginUrl = self.data['loginUrl'] req = urllib2.Request(loginUrl,urllib.urlencode(login),headers) r = self.opener.open(req) res = None for item in self.cookie: #print item.name,item.value if item.name == 'aQQ_ajklastuser': res = item.value return res #aQQ_ajklastuser junyue_liuhua #print self.opener.open('http://my.anjuke.com/v2/user/broker/checked/').read() #open('login.txt','w').write(r.read().encode('utf-8')) def post(self): pass #postData = {} #postData['loginUrl'] = 'http://agent.anjuke.com/v2/login/' #postData['act'] = 'login' #postData['loginName'] = 'junyue_liuhua' #postData['loginPasswd'] = 'lh_131415' #http = httpPost(postData) #http.login()
__init__
identifier_name
post_anju.py
#!/usr/bin/env python #-*- coding:utf-8 -*- from poster.encode import multipart_encode from poster.streaminghttp import register_openers import urllib2,urllib,sys,time import cookielib,mechanize import re DEBUG =0 reload(sys) sys.setdefaultencoding('utf8') #@UndefinedVariable register_openers() headers = { 'Host':'agent.anjuke.com', 'User-Agent' : 'Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20100101 Firefox/4.0.1', #'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', #'Accept-Language':'zh-cn,zh;q=0.5', #'Accept-Encoding':'gzip, deflate', #'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7', 'Keep-Alive':'115', 'Connection':'keep-alive', } #datagen11, headers = multipart_encode({"fileUploadInput": open("/home/myapp/Screenshot-1.jpg","rb"),"backFunction": "$.c.Uploader.finish"}) class httpPost(): data = {} def __init__(self,dataDic): self.cookie = cookielib.CookieJar() httpsHandler = urllib2.HTTPHandler() httpsHandler.set_http_debuglevel(DEBUG) self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie),httpsHandler) self.data = dataDic def login1(self): self.brow = mechanize.Browser() httpHandler = mechanize.HTTPHandler() httpsHandler = mechanize.HTTPSHandler() httpHandler.set_http_debuglevel(DEBUG) self.cookiejar = mechanize.LWPCookieJar() #self.cookiejar = "Cookie lzstat_uv=34741959842666604402|1786789; Hm_lvt_976797cb85805d626fc5642aa5244ba0=1304534271541; ASPSESSIONIDQCDRAQBB=JHCHINLAHGMAIGBIFMNANLGF; lzstat_ss=2189193215_2_1304564199_1786789; Hm_lpvt_976797cb85805d626fc5642aa5244ba0=1304535401191" self.opener = mechanize.OpenerFactory(mechanize.SeekableResponseOpener).build_opener( httpHandler,httpsHandler, mechanize.HTTPCookieProcessor(self.cookiejar), mechanize.HTTPRefererProcessor, mechanize.HTTPEquivProcessor, mechanize.HTTPRefreshProcessor, ) self.opener.addheaders = [("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"), ("From", "")] #self.opener.addheaders = [( # "Referer", self.data['postUrl'] # )] login={} login['method'] = self.data['method']
response = mechanize.urlopen(loginUrl) print response.read().decode('gb2312') def login(self): self.cookie = cookielib.CookieJar() httpsHandler = urllib2.HTTPHandler() httpsHandler.set_http_debuglevel(DEBUG) self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie),httpsHandler) login={} login['act'] = self.data['act'] login['loginName'] = self.data['loginName'] login['history'] = '' login['loginPasswd'] = self.data['loginPasswd'] loginUrl = self.data['loginUrl'] req = urllib2.Request(loginUrl,urllib.urlencode(login),headers) r = self.opener.open(req) res = None for item in self.cookie: #print item.name,item.value if item.name == 'aQQ_ajklastuser': res = item.value return res #aQQ_ajklastuser junyue_liuhua #print self.opener.open('http://my.anjuke.com/v2/user/broker/checked/').read() #open('login.txt','w').write(r.read().encode('utf-8')) def post(self): pass #postData = {} #postData['loginUrl'] = 'http://agent.anjuke.com/v2/login/' #postData['act'] = 'login' #postData['loginName'] = 'junyue_liuhua' #postData['loginPasswd'] = 'lh_131415' #http = httpPost(postData) #http.login()
login['name'] = self.data['name'] login['pwd'] = self.data['pwd'] loginUrl = self.data['loginUrl']+'?'+urllib.urlencode(login) print loginUrl response = mechanize.urlopen("http://esf.soufun.com/")
random_line_split
post_anju.py
#!/usr/bin/env python #-*- coding:utf-8 -*- from poster.encode import multipart_encode from poster.streaminghttp import register_openers import urllib2,urllib,sys,time import cookielib,mechanize import re DEBUG =0 reload(sys) sys.setdefaultencoding('utf8') #@UndefinedVariable register_openers() headers = { 'Host':'agent.anjuke.com', 'User-Agent' : 'Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20100101 Firefox/4.0.1', #'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', #'Accept-Language':'zh-cn,zh;q=0.5', #'Accept-Encoding':'gzip, deflate', #'Accept-Charset':'GB2312,utf-8;q=0.7,*;q=0.7', 'Keep-Alive':'115', 'Connection':'keep-alive', } #datagen11, headers = multipart_encode({"fileUploadInput": open("/home/myapp/Screenshot-1.jpg","rb"),"backFunction": "$.c.Uploader.finish"}) class httpPost(): data = {} def __init__(self,dataDic): self.cookie = cookielib.CookieJar() httpsHandler = urllib2.HTTPHandler() httpsHandler.set_http_debuglevel(DEBUG) self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie),httpsHandler) self.data = dataDic def login1(self):
def login(self): self.cookie = cookielib.CookieJar() httpsHandler = urllib2.HTTPHandler() httpsHandler.set_http_debuglevel(DEBUG) self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie),httpsHandler) login={} login['act'] = self.data['act'] login['loginName'] = self.data['loginName'] login['history'] = '' login['loginPasswd'] = self.data['loginPasswd'] loginUrl = self.data['loginUrl'] req = urllib2.Request(loginUrl,urllib.urlencode(login),headers) r = self.opener.open(req) res = None for item in self.cookie: #print item.name,item.value if item.name == 'aQQ_ajklastuser': res = item.value return res #aQQ_ajklastuser junyue_liuhua #print self.opener.open('http://my.anjuke.com/v2/user/broker/checked/').read() #open('login.txt','w').write(r.read().encode('utf-8')) def post(self): pass #postData = {} #postData['loginUrl'] = 'http://agent.anjuke.com/v2/login/' #postData['act'] = 'login' #postData['loginName'] = 'junyue_liuhua' #postData['loginPasswd'] = 'lh_131415' #http = httpPost(postData) #http.login()
self.brow = mechanize.Browser() httpHandler = mechanize.HTTPHandler() httpsHandler = mechanize.HTTPSHandler() httpHandler.set_http_debuglevel(DEBUG) self.cookiejar = mechanize.LWPCookieJar() #self.cookiejar = "Cookie lzstat_uv=34741959842666604402|1786789; Hm_lvt_976797cb85805d626fc5642aa5244ba0=1304534271541; ASPSESSIONIDQCDRAQBB=JHCHINLAHGMAIGBIFMNANLGF; lzstat_ss=2189193215_2_1304564199_1786789; Hm_lpvt_976797cb85805d626fc5642aa5244ba0=1304535401191" self.opener = mechanize.OpenerFactory(mechanize.SeekableResponseOpener).build_opener( httpHandler,httpsHandler, mechanize.HTTPCookieProcessor(self.cookiejar), mechanize.HTTPRefererProcessor, mechanize.HTTPEquivProcessor, mechanize.HTTPRefreshProcessor, ) self.opener.addheaders = [("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"), ("From", "")] #self.opener.addheaders = [( # "Referer", self.data['postUrl'] # )] login={} login['method'] = self.data['method'] login['name'] = self.data['name'] login['pwd'] = self.data['pwd'] loginUrl = self.data['loginUrl']+'?'+urllib.urlencode(login) print loginUrl response = mechanize.urlopen("http://esf.soufun.com/") response = mechanize.urlopen(loginUrl) print response.read().decode('gb2312')
identifier_body
flash.py
""" "Flash" messaging support. A "flash" message is a message displayed on a web page that is removed next request. """ __all__ = ['add_message', 'get_messages', 'get_flash', 'flash_middleware_factory'] import itertools import webob from wsgiapptools import cookies ENVIRON_KEY = 'wsgiapptools.flash' COOKIE_NAME = 'flash' def
(environ, message, type=None): """ Add the flash message to the Flash manager in the WSGI environ." """ return get_flash(environ).add_message(message, type) def get_messages(environ): """ Get the flasg messages from the Flash manager in the WSGI environ. """ return get_flash(environ).get_messages() def get_flash(environ): """ Get the flash manager from the environ. """ return environ[ENVIRON_KEY] class Flash(object): """ Flash message manager, associated with a WSGI environ. """ def __init__(self, environ): self.request = webob.Request(environ) self.flashes = [] def add_message(self, message, type=None): """ Add a new flash message. Note: this can be called multiple times to set multiple messages. The messages can be retrieved, using get_messages below, and will be returned in the order they were added. """ if type is None: type = '' self.flashes.append('%s:%s'% (type, message)) def get_messages(self): """ Retrieve flash messages found in the request's cookies, returning them as a list of (type, message) tuples and deleting the cookies. """ messages = [] cookies_mgr = cookies.get_cookies(self.request.environ) for i in itertools.count(): cookie_name = '%s.%d'% (COOKIE_NAME, i) # Try to find the next message. Leave the loop if it does not exist. message = self.request.cookies.get(cookie_name) if not message: break # Remove the cookie, presumably it will be displayed shortly. cookies_mgr.delete_cookie(cookie_name) # Parse and yield the message. try: type, message = message.split(':', 1) except ValueError: # Skip an unparseable cookie value. pass else: messages.append((type or None, message)) return messages def flash_middleware_factory(app): """ Create a flash middleware WSGI application around the given WSGI application. """ def middleware(environ, start_response): def _start_response(status, response_headers, exc_info=None): # Iterate the new flash messages in the WSGI, setting a 'flash' # cookie for each one. flash = environ[ENVIRON_KEY] cookies_mgr = cookies.get_cookies(environ) for i, flash in enumerate(flash.flashes): cookies_mgr.set_cookie(('%s.%d'% (COOKIE_NAME, i), flash)) # Call wrapped app's start_response. return start_response(status, response_headers, exc_info) environ[ENVIRON_KEY] = Flash(environ) return app(environ, _start_response) return middleware
add_message
identifier_name
flash.py
""" "Flash" messaging support. A "flash" message is a message displayed on a web page that is removed next request. """ __all__ = ['add_message', 'get_messages', 'get_flash', 'flash_middleware_factory'] import itertools import webob from wsgiapptools import cookies ENVIRON_KEY = 'wsgiapptools.flash' COOKIE_NAME = 'flash' def add_message(environ, message, type=None): """ Add the flash message to the Flash manager in the WSGI environ." """ return get_flash(environ).add_message(message, type) def get_messages(environ): """ Get the flasg messages from the Flash manager in the WSGI environ. """ return get_flash(environ).get_messages() def get_flash(environ): """ Get the flash manager from the environ. """ return environ[ENVIRON_KEY] class Flash(object): """ Flash message manager, associated with a WSGI environ. """ def __init__(self, environ): self.request = webob.Request(environ) self.flashes = [] def add_message(self, message, type=None): """ Add a new flash message. Note: this can be called multiple times to set multiple messages. The messages can be retrieved, using get_messages below, and will be returned in the order they were added. """ if type is None: type = '' self.flashes.append('%s:%s'% (type, message)) def get_messages(self): """ Retrieve flash messages found in the request's cookies, returning them as a list of (type, message) tuples and deleting the cookies. """ messages = [] cookies_mgr = cookies.get_cookies(self.request.environ) for i in itertools.count(): cookie_name = '%s.%d'% (COOKIE_NAME, i) # Try to find the next message. Leave the loop if it does not exist. message = self.request.cookies.get(cookie_name) if not message:
# Remove the cookie, presumably it will be displayed shortly. cookies_mgr.delete_cookie(cookie_name) # Parse and yield the message. try: type, message = message.split(':', 1) except ValueError: # Skip an unparseable cookie value. pass else: messages.append((type or None, message)) return messages def flash_middleware_factory(app): """ Create a flash middleware WSGI application around the given WSGI application. """ def middleware(environ, start_response): def _start_response(status, response_headers, exc_info=None): # Iterate the new flash messages in the WSGI, setting a 'flash' # cookie for each one. flash = environ[ENVIRON_KEY] cookies_mgr = cookies.get_cookies(environ) for i, flash in enumerate(flash.flashes): cookies_mgr.set_cookie(('%s.%d'% (COOKIE_NAME, i), flash)) # Call wrapped app's start_response. return start_response(status, response_headers, exc_info) environ[ENVIRON_KEY] = Flash(environ) return app(environ, _start_response) return middleware
break
conditional_block
flash.py
""" "Flash" messaging support. A "flash" message is a message displayed on a web page that is removed next request. """ __all__ = ['add_message', 'get_messages', 'get_flash', 'flash_middleware_factory'] import itertools import webob from wsgiapptools import cookies ENVIRON_KEY = 'wsgiapptools.flash' COOKIE_NAME = 'flash' def add_message(environ, message, type=None): """ Add the flash message to the Flash manager in the WSGI environ." """ return get_flash(environ).add_message(message, type) def get_messages(environ): """ Get the flasg messages from the Flash manager in the WSGI environ. """ return get_flash(environ).get_messages() def get_flash(environ): """ Get the flash manager from the environ.
class Flash(object): """ Flash message manager, associated with a WSGI environ. """ def __init__(self, environ): self.request = webob.Request(environ) self.flashes = [] def add_message(self, message, type=None): """ Add a new flash message. Note: this can be called multiple times to set multiple messages. The messages can be retrieved, using get_messages below, and will be returned in the order they were added. """ if type is None: type = '' self.flashes.append('%s:%s'% (type, message)) def get_messages(self): """ Retrieve flash messages found in the request's cookies, returning them as a list of (type, message) tuples and deleting the cookies. """ messages = [] cookies_mgr = cookies.get_cookies(self.request.environ) for i in itertools.count(): cookie_name = '%s.%d'% (COOKIE_NAME, i) # Try to find the next message. Leave the loop if it does not exist. message = self.request.cookies.get(cookie_name) if not message: break # Remove the cookie, presumably it will be displayed shortly. cookies_mgr.delete_cookie(cookie_name) # Parse and yield the message. try: type, message = message.split(':', 1) except ValueError: # Skip an unparseable cookie value. pass else: messages.append((type or None, message)) return messages def flash_middleware_factory(app): """ Create a flash middleware WSGI application around the given WSGI application. """ def middleware(environ, start_response): def _start_response(status, response_headers, exc_info=None): # Iterate the new flash messages in the WSGI, setting a 'flash' # cookie for each one. flash = environ[ENVIRON_KEY] cookies_mgr = cookies.get_cookies(environ) for i, flash in enumerate(flash.flashes): cookies_mgr.set_cookie(('%s.%d'% (COOKIE_NAME, i), flash)) # Call wrapped app's start_response. return start_response(status, response_headers, exc_info) environ[ENVIRON_KEY] = Flash(environ) return app(environ, _start_response) return middleware
""" return environ[ENVIRON_KEY]
random_line_split
flash.py
""" "Flash" messaging support. A "flash" message is a message displayed on a web page that is removed next request. """ __all__ = ['add_message', 'get_messages', 'get_flash', 'flash_middleware_factory'] import itertools import webob from wsgiapptools import cookies ENVIRON_KEY = 'wsgiapptools.flash' COOKIE_NAME = 'flash' def add_message(environ, message, type=None): """ Add the flash message to the Flash manager in the WSGI environ." """ return get_flash(environ).add_message(message, type) def get_messages(environ): """ Get the flasg messages from the Flash manager in the WSGI environ. """ return get_flash(environ).get_messages() def get_flash(environ): """ Get the flash manager from the environ. """ return environ[ENVIRON_KEY] class Flash(object):
def flash_middleware_factory(app): """ Create a flash middleware WSGI application around the given WSGI application. """ def middleware(environ, start_response): def _start_response(status, response_headers, exc_info=None): # Iterate the new flash messages in the WSGI, setting a 'flash' # cookie for each one. flash = environ[ENVIRON_KEY] cookies_mgr = cookies.get_cookies(environ) for i, flash in enumerate(flash.flashes): cookies_mgr.set_cookie(('%s.%d'% (COOKIE_NAME, i), flash)) # Call wrapped app's start_response. return start_response(status, response_headers, exc_info) environ[ENVIRON_KEY] = Flash(environ) return app(environ, _start_response) return middleware
""" Flash message manager, associated with a WSGI environ. """ def __init__(self, environ): self.request = webob.Request(environ) self.flashes = [] def add_message(self, message, type=None): """ Add a new flash message. Note: this can be called multiple times to set multiple messages. The messages can be retrieved, using get_messages below, and will be returned in the order they were added. """ if type is None: type = '' self.flashes.append('%s:%s'% (type, message)) def get_messages(self): """ Retrieve flash messages found in the request's cookies, returning them as a list of (type, message) tuples and deleting the cookies. """ messages = [] cookies_mgr = cookies.get_cookies(self.request.environ) for i in itertools.count(): cookie_name = '%s.%d'% (COOKIE_NAME, i) # Try to find the next message. Leave the loop if it does not exist. message = self.request.cookies.get(cookie_name) if not message: break # Remove the cookie, presumably it will be displayed shortly. cookies_mgr.delete_cookie(cookie_name) # Parse and yield the message. try: type, message = message.split(':', 1) except ValueError: # Skip an unparseable cookie value. pass else: messages.append((type or None, message)) return messages
identifier_body
build.rs
// Copyright 2016 Joe Wilm, The Alacritty Project Contributors // // 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. extern crate gl_generator; use gl_generator::{Registry, Api, Profile, Fallbacks, GlobalGenerator};
use std::fs::File; use std::path::Path; fn main() { let dest = env::var("OUT_DIR").unwrap(); let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap(); Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [ "GL_ARB_blend_func_extended" ]) .write_bindings(GlobalGenerator, &mut file) .unwrap(); }
use std::env;
random_line_split
build.rs
// Copyright 2016 Joe Wilm, The Alacritty Project Contributors // // 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. extern crate gl_generator; use gl_generator::{Registry, Api, Profile, Fallbacks, GlobalGenerator}; use std::env; use std::fs::File; use std::path::Path; fn main()
{ let dest = env::var("OUT_DIR").unwrap(); let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap(); Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [ "GL_ARB_blend_func_extended" ]) .write_bindings(GlobalGenerator, &mut file) .unwrap(); }
identifier_body
build.rs
// Copyright 2016 Joe Wilm, The Alacritty Project Contributors // // 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. extern crate gl_generator; use gl_generator::{Registry, Api, Profile, Fallbacks, GlobalGenerator}; use std::env; use std::fs::File; use std::path::Path; fn
() { let dest = env::var("OUT_DIR").unwrap(); let mut file = File::create(&Path::new(&dest).join("gl_bindings.rs")).unwrap(); Registry::new(Api::Gl, (4, 5), Profile::Core, Fallbacks::All, [ "GL_ARB_blend_func_extended" ]) .write_bindings(GlobalGenerator, &mut file) .unwrap(); }
main
identifier_name
reducer.ts
import { defaultBucketAgg } from '../../../../query_def'; import { ElasticsearchQuery } from '../../../../types'; import { metricAggregationConfig } from '../../MetricAggregationsEditor/utils'; import { BucketAggregation, Terms } from '../aggregations'; import { initQuery } from '../../state'; import { bucketAggregationConfig } from '../utils'; import { removeEmpty } from '../../../../utils'; import { Action } from '@reduxjs/toolkit'; import { addBucketAggregation, changeBucketAggregationField, changeBucketAggregationSetting, changeBucketAggregationType, removeBucketAggregation, } from './actions'; import { changeMetricType } from '../../MetricAggregationsEditor/state/actions'; export const createReducer = (defaultTimeField: string) => (state: ElasticsearchQuery['bucketAggs'], action: Action): ElasticsearchQuery['bucketAggs'] => { if (addBucketAggregation.match(action)) { const newAgg: Terms = { id: action.payload, type: 'terms', settings: bucketAggregationConfig['terms'].defaultSettings, }; // If the last bucket aggregation is a `date_histogram` we add the new one before it. const lastAgg = state![state!.length - 1]; if (lastAgg?.type === 'date_histogram') { return [...state!.slice(0, state!.length - 1), newAgg, lastAgg]; } return [...state!, newAgg]; }
return state!.filter((bucketAgg) => bucketAgg.id !== action.payload); } if (changeBucketAggregationType.match(action)) { return state!.map((bucketAgg) => { if (bucketAgg.id !== action.payload.id) { return bucketAgg; } /* TODO: The previous version of the query editor was keeping some of the old bucket aggregation's configurations in the new selected one (such as field or some settings). It the future would be nice to have the same behavior but it's hard without a proper definition, as Elasticsearch will error sometimes if some settings are not compatible. */ return { id: bucketAgg.id, type: action.payload.newType, settings: bucketAggregationConfig[action.payload.newType].defaultSettings, } as BucketAggregation; }); } if (changeBucketAggregationField.match(action)) { return state!.map((bucketAgg) => { if (bucketAgg.id !== action.payload.id) { return bucketAgg; } return { ...bucketAgg, field: action.payload.newField, }; }); } if (changeMetricType.match(action)) { // If we are switching to a metric which requires the absence of bucket aggregations // we remove all of them. if (metricAggregationConfig[action.payload.type].isSingleMetric) { return []; } else if (state!.length === 0) { // Else, if there are no bucket aggregations we restore a default one. // This happens when switching from a metric that requires the absence of bucket aggregations to // one that requires it. return [{ ...defaultBucketAgg('2'), field: defaultTimeField }]; } return state; } if (changeBucketAggregationSetting.match(action)) { return state!.map((bucketAgg) => { if (bucketAgg.id !== action.payload.bucketAgg.id) { return bucketAgg; } const newSettings = removeEmpty({ ...bucketAgg.settings, [action.payload.settingName]: action.payload.newValue, }); return { ...bucketAgg, settings: { ...newSettings, }, }; }); } if (initQuery.match(action)) { if (state?.length || 0 > 0) { return state; } return [{ ...defaultBucketAgg('2'), field: defaultTimeField }]; } return state; };
if (removeBucketAggregation.match(action)) {
random_line_split
reducer.ts
import { defaultBucketAgg } from '../../../../query_def'; import { ElasticsearchQuery } from '../../../../types'; import { metricAggregationConfig } from '../../MetricAggregationsEditor/utils'; import { BucketAggregation, Terms } from '../aggregations'; import { initQuery } from '../../state'; import { bucketAggregationConfig } from '../utils'; import { removeEmpty } from '../../../../utils'; import { Action } from '@reduxjs/toolkit'; import { addBucketAggregation, changeBucketAggregationField, changeBucketAggregationSetting, changeBucketAggregationType, removeBucketAggregation, } from './actions'; import { changeMetricType } from '../../MetricAggregationsEditor/state/actions'; export const createReducer = (defaultTimeField: string) => (state: ElasticsearchQuery['bucketAggs'], action: Action): ElasticsearchQuery['bucketAggs'] => { if (addBucketAggregation.match(action)) { const newAgg: Terms = { id: action.payload, type: 'terms', settings: bucketAggregationConfig['terms'].defaultSettings, }; // If the last bucket aggregation is a `date_histogram` we add the new one before it. const lastAgg = state![state!.length - 1]; if (lastAgg?.type === 'date_histogram') { return [...state!.slice(0, state!.length - 1), newAgg, lastAgg]; } return [...state!, newAgg]; } if (removeBucketAggregation.match(action)) { return state!.filter((bucketAgg) => bucketAgg.id !== action.payload); } if (changeBucketAggregationType.match(action)) { return state!.map((bucketAgg) => { if (bucketAgg.id !== action.payload.id) { return bucketAgg; } /* TODO: The previous version of the query editor was keeping some of the old bucket aggregation's configurations in the new selected one (such as field or some settings). It the future would be nice to have the same behavior but it's hard without a proper definition, as Elasticsearch will error sometimes if some settings are not compatible. */ return { id: bucketAgg.id, type: action.payload.newType, settings: bucketAggregationConfig[action.payload.newType].defaultSettings, } as BucketAggregation; }); } if (changeBucketAggregationField.match(action)) { return state!.map((bucketAgg) => { if (bucketAgg.id !== action.payload.id) { return bucketAgg; } return { ...bucketAgg, field: action.payload.newField, }; }); } if (changeMetricType.match(action)) { // If we are switching to a metric which requires the absence of bucket aggregations // we remove all of them. if (metricAggregationConfig[action.payload.type].isSingleMetric) { return []; } else if (state!.length === 0) { // Else, if there are no bucket aggregations we restore a default one. // This happens when switching from a metric that requires the absence of bucket aggregations to // one that requires it. return [{ ...defaultBucketAgg('2'), field: defaultTimeField }]; } return state; } if (changeBucketAggregationSetting.match(action)) { return state!.map((bucketAgg) => { if (bucketAgg.id !== action.payload.bucketAgg.id)
const newSettings = removeEmpty({ ...bucketAgg.settings, [action.payload.settingName]: action.payload.newValue, }); return { ...bucketAgg, settings: { ...newSettings, }, }; }); } if (initQuery.match(action)) { if (state?.length || 0 > 0) { return state; } return [{ ...defaultBucketAgg('2'), field: defaultTimeField }]; } return state; };
{ return bucketAgg; }
conditional_block
make_new_database.py
__author__ = 'austin' import dataset import os import time import sys def
(new_database_name, media_folder): file_ext = (".mp4", ".avi", ".flv", ".wmv", ".mpg", ".mov", ".mkv", ".mpeg") start_time = time.time() # FOR TESTING ... start time db = dataset.connect('sqlite:///{}.vdb'.format(new_database_name)) table = db[new_database_name] for root, dirs, files in os.walk(media_folder): for file in files: if file.endswith(file_ext): if table.find_one(title=file[:-4]) is None: table.insert(dict(title=file[:-4], location=(root + '/' + file), genre='none', length='none', ispresent=True)) print(root + '/' + file) else: pass else: pass end_time = time.time() print("{} files in {} seconds".format(len(db[new_database_name]), end_time - start_time)) exit(0) # TODO need to specify different exit codes on different errors, so we can handle these errors def main(): new_database_name = sys.argv[1] media_folder = sys.argv[2] make_new_database(new_database_name, media_folder) if __name__ == "__main__": main()
make_new_database
identifier_name
make_new_database.py
__author__ = 'austin' import dataset import os import time import sys def make_new_database(new_database_name, media_folder): file_ext = (".mp4", ".avi", ".flv", ".wmv", ".mpg", ".mov", ".mkv", ".mpeg") start_time = time.time() # FOR TESTING ... start time db = dataset.connect('sqlite:///{}.vdb'.format(new_database_name)) table = db[new_database_name] for root, dirs, files in os.walk(media_folder): for file in files: if file.endswith(file_ext):
else: pass end_time = time.time() print("{} files in {} seconds".format(len(db[new_database_name]), end_time - start_time)) exit(0) # TODO need to specify different exit codes on different errors, so we can handle these errors def main(): new_database_name = sys.argv[1] media_folder = sys.argv[2] make_new_database(new_database_name, media_folder) if __name__ == "__main__": main()
if table.find_one(title=file[:-4]) is None: table.insert(dict(title=file[:-4], location=(root + '/' + file), genre='none', length='none', ispresent=True)) print(root + '/' + file) else: pass
conditional_block
make_new_database.py
__author__ = 'austin' import dataset import os import time import sys def make_new_database(new_database_name, media_folder):
def main(): new_database_name = sys.argv[1] media_folder = sys.argv[2] make_new_database(new_database_name, media_folder) if __name__ == "__main__": main()
file_ext = (".mp4", ".avi", ".flv", ".wmv", ".mpg", ".mov", ".mkv", ".mpeg") start_time = time.time() # FOR TESTING ... start time db = dataset.connect('sqlite:///{}.vdb'.format(new_database_name)) table = db[new_database_name] for root, dirs, files in os.walk(media_folder): for file in files: if file.endswith(file_ext): if table.find_one(title=file[:-4]) is None: table.insert(dict(title=file[:-4], location=(root + '/' + file), genre='none', length='none', ispresent=True)) print(root + '/' + file) else: pass else: pass end_time = time.time() print("{} files in {} seconds".format(len(db[new_database_name]), end_time - start_time)) exit(0) # TODO need to specify different exit codes on different errors, so we can handle these errors
identifier_body
make_new_database.py
__author__ = 'austin' import dataset import os import time import sys def make_new_database(new_database_name, media_folder): file_ext = (".mp4", ".avi", ".flv", ".wmv", ".mpg", ".mov", ".mkv", ".mpeg") start_time = time.time() # FOR TESTING ... start time db = dataset.connect('sqlite:///{}.vdb'.format(new_database_name)) table = db[new_database_name]
location=(root + '/' + file), genre='none', length='none', ispresent=True)) print(root + '/' + file) else: pass else: pass end_time = time.time() print("{} files in {} seconds".format(len(db[new_database_name]), end_time - start_time)) exit(0) # TODO need to specify different exit codes on different errors, so we can handle these errors def main(): new_database_name = sys.argv[1] media_folder = sys.argv[2] make_new_database(new_database_name, media_folder) if __name__ == "__main__": main()
for root, dirs, files in os.walk(media_folder): for file in files: if file.endswith(file_ext): if table.find_one(title=file[:-4]) is None: table.insert(dict(title=file[:-4],
random_line_split
cryptotestutils.d.ts
/** * @license * Copyright 2019 Google LLC. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * Code distributed by Google as part of this project is also * subject to an additional IP rights grant found at
import { KeyStorage } from '../manager.js'; export interface TestableKey { encrypt(buffer: ArrayBuffer, iv: Uint8Array): PromiseLike<ArrayBuffer>; decrypt(buffer: ArrayBuffer, iv: Uint8Array): PromiseLike<ArrayBuffer>; } /** * Implementation of KeyStorage using a Map, used for testing only. */ export declare class WebCryptoMemoryKeyStorage implements KeyStorage { storageMap: Map<string, Key>; constructor(); find(keyFingerPrint: string): PromiseLike<Key | null>; write(keyFingerprint: string, key: DeviceKey | WrappedKey): Promise<string>; static getInstance(): WebCryptoMemoryKeyStorage; }
* http://polymer.github.io/PATENTS.txt */ import { DeviceKey, Key, WrappedKey } from '../keys.js';
random_line_split
cryptotestutils.d.ts
/** * @license * Copyright 2019 Google LLC. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * Code distributed by Google as part of this project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */ import { DeviceKey, Key, WrappedKey } from '../keys.js'; import { KeyStorage } from '../manager.js'; export interface TestableKey { encrypt(buffer: ArrayBuffer, iv: Uint8Array): PromiseLike<ArrayBuffer>; decrypt(buffer: ArrayBuffer, iv: Uint8Array): PromiseLike<ArrayBuffer>; } /** * Implementation of KeyStorage using a Map, used for testing only. */ export declare class
implements KeyStorage { storageMap: Map<string, Key>; constructor(); find(keyFingerPrint: string): PromiseLike<Key | null>; write(keyFingerprint: string, key: DeviceKey | WrappedKey): Promise<string>; static getInstance(): WebCryptoMemoryKeyStorage; }
WebCryptoMemoryKeyStorage
identifier_name
blob_storage.rs
use services::blob_storage::BlobStorageService; use std::rc::Rc; use errors::prelude::*; pub enum BlobStorageCommand { OpenReader( String, // type String, // config Box<Fn(IndyResult<i32 /* handle */>) + Send>),
Box<Fn(IndyResult<i32 /* handle */>) + Send>), } pub struct BlobStorageCommandExecutor { blob_storage_service: Rc<BlobStorageService> } impl BlobStorageCommandExecutor { pub fn new(blob_storage_service: Rc<BlobStorageService>) -> BlobStorageCommandExecutor { BlobStorageCommandExecutor { blob_storage_service } } pub fn execute(&self, command: BlobStorageCommand) { match command { BlobStorageCommand::OpenReader(type_, config, cb) => { info!("OpenReader command received"); cb(self.open_reader(&type_, &config)); } BlobStorageCommand::OpenWriter(writer_type, writer_config, cb) => { info!("OpenWriter command received"); cb(self.open_writer(&writer_type, &writer_config)); } } } fn open_reader(&self, type_: &str, config: &str) -> IndyResult<i32> { debug!("open_reader >>> type_: {:?}, config: {:?}", type_, config); let res = self.blob_storage_service.open_reader(type_, config).map_err(IndyError::from); debug!("open_reader << res: {:?}", res); res } fn open_writer(&self, type_: &str, config: &str) -> IndyResult<i32> { debug!("open_writer >>> type_: {:?}, config: {:?}", type_, config); let res = self.blob_storage_service.open_writer(type_, config).map_err(IndyError::from); debug!("open_writer << res: {:?}", res); res } }
OpenWriter( String, // writer type String, // writer config JSON
random_line_split