max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
668
/** * 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. */ package org.apache.fineract.infrastructure.core.data; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.List; /** * */ public class ApiGlobalErrorResponse { /** * A developer friendly plain English description of why the HTTP error response was returned from the API. */ private String developerMessage; /** * The HTTP status code of the response. */ private String httpStatusCode; /** * A user friendly plain English description of why the HTTP error response was returned from the API that can be * presented to end users. */ private String defaultUserMessage; /** * A code that can be used for globalisation support by client applications of the API. */ private String userMessageGlobalisationCode; /** * A list of zero or more of the actual reasons for the HTTP error should they be needed. Typically used to express * data validation errors with parameters passed to API. */ private List<ApiParameterError> errors = new ArrayList<>(); public static ApiGlobalErrorResponse unAuthenticated() { final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("401"); globalErrorResponse.setDeveloperMessage("Invalid authentication details were passed in api request."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.not.authenticated"); globalErrorResponse.setDefaultUserMessage("Unauthenticated. Please login."); return globalErrorResponse; } public static ApiGlobalErrorResponse invalidTenantIdentifier() { final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("401"); globalErrorResponse.setDeveloperMessage("Invalid tenant details were passed in api request."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.invalid.tenant.identifier"); globalErrorResponse.setDefaultUserMessage("Invalide tenant identifier provided with request."); return globalErrorResponse; } public static ApiGlobalErrorResponse unAuthorized(final String defaultUserMessage) { final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("403"); globalErrorResponse.setDeveloperMessage( "The user associated with credentials passed on this request does not have sufficient privileges to perform this action."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.not.authorized"); globalErrorResponse.setDefaultUserMessage("Insufficient privileges to perform this action."); final List<ApiParameterError> errors = new ArrayList<>(); errors.add(ApiParameterError.generalError("error.msg.not.authorized", defaultUserMessage)); globalErrorResponse.setErrors(errors); return globalErrorResponse; } public static ApiGlobalErrorResponse domainRuleViolation(final String globalisationMessageCode, final String defaultUserMessage, final Object... defaultUserMessageArgs) { final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("403"); globalErrorResponse.setDeveloperMessage("Request was understood but caused a domain rule violation."); globalErrorResponse.setUserMessageGlobalisationCode("validation.msg.domain.rule.violation"); globalErrorResponse.setDefaultUserMessage("Errors contain reason for domain rule violation."); final List<ApiParameterError> errors = new ArrayList<>(); errors.add(ApiParameterError.generalError(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs)); globalErrorResponse.setErrors(errors); return globalErrorResponse; } public static ApiGlobalErrorResponse notFound(final String globalisationMessageCode, final String defaultUserMessage, final Object... defaultUserMessageArgs) { final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("404"); globalErrorResponse.setDeveloperMessage("The requested resource is not available."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.resource.not.found"); globalErrorResponse.setDefaultUserMessage("The requested resource is not available."); final List<ApiParameterError> errors = new ArrayList<>(); errors.add(ApiParameterError.resourceIdentifierNotFound(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs)); globalErrorResponse.setErrors(errors); return globalErrorResponse; } public static ApiGlobalErrorResponse dataIntegrityError(final String globalisationMessageCode, final String defaultUserMessage, final String parameterName, final Object... defaultUserMessageArgs) { final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("403"); globalErrorResponse.setDeveloperMessage("The request caused a data integrity issue to be fired by the database."); globalErrorResponse.setUserMessageGlobalisationCode(globalisationMessageCode); globalErrorResponse.setDefaultUserMessage(defaultUserMessage); final List<ApiParameterError> errors = new ArrayList<>(); errors.add(ApiParameterError.parameterError(globalisationMessageCode, defaultUserMessage, parameterName, defaultUserMessageArgs)); globalErrorResponse.setErrors(errors); return globalErrorResponse; } public static ApiGlobalErrorResponse badClientRequest(final String globalisationMessageCode, final String defaultUserMessage, final List<ApiParameterError> errors) { final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("400"); globalErrorResponse .setDeveloperMessage("The request was invalid. This typically will happen due to validation errors which are provided."); globalErrorResponse.setUserMessageGlobalisationCode(globalisationMessageCode); globalErrorResponse.setDefaultUserMessage(defaultUserMessage); globalErrorResponse.setErrors(errors); return globalErrorResponse; } public static ApiGlobalErrorResponse serverSideError(final String globalisationMessageCode, final String defaultUserMessage, final Object... defaultUserMessageArgs) { final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("500"); globalErrorResponse.setDeveloperMessage("An unexpected error occured on the platform server."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.platform.server.side.error"); globalErrorResponse.setDefaultUserMessage("An unexpected error occured on the platform server."); final List<ApiParameterError> errors = new ArrayList<>(); errors.add(ApiParameterError.generalError(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs)); globalErrorResponse.setErrors(errors); return globalErrorResponse; } public static ApiGlobalErrorResponse serviceUnavailable(final String globalisationMessageCode, final String defaultUserMessage, final Object... defaultUserMessageArgs) { final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("503"); globalErrorResponse.setDeveloperMessage("The server is currently unable to handle the request , please try after some time."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.platform.service.unavailable"); globalErrorResponse.setDefaultUserMessage("The server is currently unable to handle the request , please try after some time."); final List<ApiParameterError> errors = new ArrayList<>(); errors.add(ApiParameterError.generalError(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs)); globalErrorResponse.setErrors(errors); return globalErrorResponse; } protected ApiGlobalErrorResponse() { // } public ApiGlobalErrorResponse(final List<ApiParameterError> errors) { this.errors = errors; } @JsonProperty("errors") public List<ApiParameterError> getErrors() { return this.errors; } public void setErrors(final List<ApiParameterError> errors) { this.errors = errors; } public String getDeveloperMessage() { return this.developerMessage; } public void setDeveloperMessage(final String developerMessage) { this.developerMessage = developerMessage; } public String getHttpStatusCode() { return this.httpStatusCode; } public void setHttpStatusCode(final String httpStatusCode) { this.httpStatusCode = httpStatusCode; } public String getDefaultUserMessage() { return this.defaultUserMessage; } public void setDefaultUserMessage(final String defaultUserMessage) { this.defaultUserMessage = defaultUserMessage; } public String getUserMessageGlobalisationCode() { return this.userMessageGlobalisationCode; } public void setUserMessageGlobalisationCode(final String userMessageGlobalisationCode) { this.userMessageGlobalisationCode = userMessageGlobalisationCode; } }
3,154
852
<filename>HLTrigger/HLTcore/src/HLTFilter.cc /** \class HLTFilter * * * This class derives from EDFilter and adds a few HLT specific * items. Any and all HLT filters must derive from the HLTFilter * class! * * * \author <NAME> * */ #include "DataFormats/HLTReco/interface/TriggerFilterObjectWithRefs.h" #include "HLTrigger/HLTcore/interface/HLTFilter.h" #include "FWCore/ServiceRegistry/interface/PathContext.h" #include "FWCore/ServiceRegistry/interface/PlaceInPathContext.h" #include "FWCore/ServiceRegistry/interface/ModuleCallingContext.h" HLTFilter::HLTFilter(const edm::ParameterSet& config) : EDFilter(), saveTags_(config.getParameter<bool>("saveTags")) { // register common HLTFilter products produces<trigger::TriggerFilterObjectWithRefs>(); } void HLTFilter::makeHLTFilterDescription(edm::ParameterSetDescription& desc) { desc.add<bool>("saveTags", true); } HLTFilter::~HLTFilter() = default; bool HLTFilter::filter(edm::StreamID, edm::Event& event, const edm::EventSetup& setup) const { std::unique_ptr<trigger::TriggerFilterObjectWithRefs> filterproduct( new trigger::TriggerFilterObjectWithRefs(path(event), module(event))); // compute the result of the HLTFilter implementation bool result = hltFilter(event, setup, *filterproduct); // put filter object into the Event event.put(std::move(filterproduct)); // retunr the result of the HLTFilter return result; } int HLTFilter::path(edm::Event const& event) const { return static_cast<int>(event.moduleCallingContext()->placeInPathContext()->pathContext()->pathID()); } int HLTFilter::module(edm::Event const& event) const { return static_cast<int>(event.moduleCallingContext()->placeInPathContext()->placeInPath()); } std::pair<int, int> HLTFilter::pmid(edm::Event const& event) const { edm::PlaceInPathContext const* placeInPathContext = event.moduleCallingContext()->placeInPathContext(); return std::make_pair(static_cast<int>(placeInPathContext->pathContext()->pathID()), static_cast<int>(placeInPathContext->placeInPath())); } const std::string* HLTFilter::pathName(edm::Event const& event) const { return &event.moduleCallingContext()->placeInPathContext()->pathContext()->pathName(); } const std::string* HLTFilter::moduleLabel() const { return &moduleDescription().moduleLabel(); }
767
432
/* $NetBSD: format1.c,v 1.1.1.2 2009/12/02 00:26:48 haad Exp $ */ /* * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved. * Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved. * * This file is part of LVM2. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License v.2.1. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "lib.h" #include "disk-rep.h" #include "limits.h" #include "display.h" #include "toolcontext.h" #include "lvm1-label.h" #include "format1.h" #include "segtype.h" /* VG consistency checks */ static int _check_vgs(struct dm_list *pvs) { struct dm_list *pvh, *t; struct disk_list *dl = NULL; struct disk_list *first = NULL; uint32_t pv_count = 0; uint32_t exported = 0; int first_time = 1; /* * If there are exported and unexported PVs, ignore exported ones. * This means an active VG won't be affected if disks are inserted * bearing an exported VG with the same name. */ dm_list_iterate_items(dl, pvs) { if (first_time) { exported = dl->pvd.pv_status & VG_EXPORTED; first_time = 0; continue; } if (exported != (dl->pvd.pv_status & VG_EXPORTED)) { /* Remove exported PVs */ dm_list_iterate_safe(pvh, t, pvs) { dl = dm_list_item(pvh, struct disk_list); if (dl->pvd.pv_status & VG_EXPORTED) dm_list_del(pvh); } break; } } /* Remove any PVs with VG structs that differ from the first */ dm_list_iterate_safe(pvh, t, pvs) { dl = dm_list_item(pvh, struct disk_list); if (!first) first = dl; else if (memcmp(&first->vgd, &dl->vgd, sizeof(first->vgd))) { log_error("VG data differs between PVs %s and %s", dev_name(first->dev), dev_name(dl->dev)); log_debug("VG data on %s: %s %s %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32, dev_name(first->dev), first->vgd.vg_uuid, first->vgd.vg_name_dummy, first->vgd.vg_number, first->vgd.vg_access, first->vgd.vg_status, first->vgd.lv_max, first->vgd.lv_cur, first->vgd.lv_open, first->vgd.pv_max, first->vgd.pv_cur, first->vgd.pv_act, first->vgd.dummy, first->vgd.vgda, first->vgd.pe_size, first->vgd.pe_total, first->vgd.pe_allocated, first->vgd.pvg_total); log_debug("VG data on %s: %s %s %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32, dev_name(dl->dev), dl->vgd.vg_uuid, dl->vgd.vg_name_dummy, dl->vgd.vg_number, dl->vgd.vg_access, dl->vgd.vg_status, dl->vgd.lv_max, dl->vgd.lv_cur, dl->vgd.lv_open, dl->vgd.pv_max, dl->vgd.pv_cur, dl->vgd.pv_act, dl->vgd.dummy, dl->vgd.vgda, dl->vgd.pe_size, dl->vgd.pe_total, dl->vgd.pe_allocated, dl->vgd.pvg_total); dm_list_del(pvh); return 0; } pv_count++; } /* On entry to fn, list known to be non-empty */ if (pv_count != first->vgd.pv_cur) { log_error("%d PV(s) found for VG %s: expected %d", pv_count, first->pvd.vg_name, first->vgd.pv_cur); } return 1; } static struct volume_group *_build_vg(struct format_instance *fid, struct dm_list *pvs, struct dm_pool *mem) { struct volume_group *vg = dm_pool_alloc(mem, sizeof(*vg)); struct disk_list *dl; if (!vg) goto_bad; if (dm_list_empty(pvs)) goto_bad; memset(vg, 0, sizeof(*vg)); vg->cmd = fid->fmt->cmd; vg->vgmem = mem; vg->fid = fid; vg->seqno = 0; dm_list_init(&vg->pvs); dm_list_init(&vg->lvs); dm_list_init(&vg->tags); dm_list_init(&vg->removed_pvs); if (!_check_vgs(pvs)) goto_bad; dl = dm_list_item(pvs->n, struct disk_list); if (!import_vg(mem, vg, dl)) goto_bad; if (!import_pvs(fid->fmt, mem, vg, pvs, &vg->pvs, &vg->pv_count)) goto_bad; if (!import_lvs(mem, vg, pvs)) goto_bad; if (!import_extents(fid->fmt->cmd, vg, pvs)) goto_bad; if (!import_snapshots(mem, vg, pvs)) goto_bad; return vg; bad: dm_pool_free(mem, vg); return NULL; } static struct volume_group *_format1_vg_read(struct format_instance *fid, const char *vg_name, struct metadata_area *mda __attribute((unused))) { struct dm_pool *mem = dm_pool_create("lvm1 vg_read", VG_MEMPOOL_CHUNK); struct dm_list pvs; struct volume_group *vg = NULL; dm_list_init(&pvs); if (!mem) return_NULL; /* Strip dev_dir if present */ vg_name = strip_dir(vg_name, fid->fmt->cmd->dev_dir); if (!read_pvs_in_vg (fid->fmt, vg_name, fid->fmt->cmd->filter, mem, &pvs)) goto_bad; if (!(vg = _build_vg(fid, &pvs, mem))) goto_bad; return vg; bad: dm_pool_destroy(mem); return NULL; } static struct disk_list *_flatten_pv(struct format_instance *fid, struct dm_pool *mem, struct volume_group *vg, struct physical_volume *pv, const char *dev_dir) { struct disk_list *dl = dm_pool_alloc(mem, sizeof(*dl)); if (!dl) return_NULL; dl->mem = mem; dl->dev = pv->dev; dm_list_init(&dl->uuids); dm_list_init(&dl->lvds); if (!export_pv(fid->fmt->cmd, mem, vg, &dl->pvd, pv) || !export_vg(&dl->vgd, vg) || !export_uuids(dl, vg) || !export_lvs(dl, vg, pv, dev_dir) || !calculate_layout(dl)) { dm_pool_free(mem, dl); return_NULL; } return dl; } static int _flatten_vg(struct format_instance *fid, struct dm_pool *mem, struct volume_group *vg, struct dm_list *pvds, const char *dev_dir, struct dev_filter *filter) { struct pv_list *pvl; struct disk_list *data; dm_list_iterate_items(pvl, &vg->pvs) { if (!(data = _flatten_pv(fid, mem, vg, pvl->pv, dev_dir))) return_0; dm_list_add(pvds, &data->list); } export_numbers(pvds, vg); export_pv_act(pvds); if (!export_vg_number(fid, pvds, vg->name, filter)) return_0; return 1; } static int _format1_vg_write(struct format_instance *fid, struct volume_group *vg, struct metadata_area *mda __attribute((unused))) { struct dm_pool *mem = dm_pool_create("lvm1 vg_write", VG_MEMPOOL_CHUNK); struct dm_list pvds; int r = 0; if (!mem) return_0; dm_list_init(&pvds); r = (_flatten_vg(fid, mem, vg, &pvds, fid->fmt->cmd->dev_dir, fid->fmt->cmd->filter) && write_disks(fid->fmt, &pvds)); lvmcache_update_vg(vg, 0); dm_pool_destroy(mem); return r; } static int _format1_pv_read(const struct format_type *fmt, const char *pv_name, struct physical_volume *pv, struct dm_list *mdas __attribute((unused)), int scan_label_only __attribute((unused))) { struct dm_pool *mem = dm_pool_create("lvm1 pv_read", 1024); struct disk_list *dl; struct device *dev; int r = 0; log_very_verbose("Reading physical volume data %s from disk", pv_name); if (!mem) return_0; if (!(dev = dev_cache_get(pv_name, fmt->cmd->filter))) goto_out; if (!(dl = read_disk(fmt, dev, mem, NULL))) goto_out; if (!import_pv(fmt, fmt->cmd->mem, dl->dev, NULL, pv, &dl->pvd, &dl->vgd)) goto_out; pv->fmt = fmt; r = 1; out: dm_pool_destroy(mem); return r; } static int _format1_pv_setup(const struct format_type *fmt, uint64_t pe_start, uint32_t extent_count, uint32_t extent_size, unsigned long data_alignment __attribute((unused)), unsigned long data_alignment_offset __attribute((unused)), int pvmetadatacopies __attribute((unused)), uint64_t pvmetadatasize __attribute((unused)), struct dm_list *mdas __attribute((unused)), struct physical_volume *pv, struct volume_group *vg __attribute((unused))) { if (pv->size > MAX_PV_SIZE) pv->size--; if (pv->size > MAX_PV_SIZE) { log_error("Physical volumes cannot be bigger than %s", display_size(fmt->cmd, (uint64_t) MAX_PV_SIZE)); return 0; } /* Nothing more to do if extent size isn't provided */ if (!extent_size) return 1; /* * This works out pe_start and pe_count. */ if (!calculate_extent_count(pv, extent_size, extent_count, pe_start)) return_0; /* Retain existing extent locations exactly */ if (((pe_start || extent_count) && (pe_start != pv->pe_start)) || (extent_count && (extent_count != pv->pe_count))) { log_error("Metadata would overwrite physical extents"); return 0; } return 1; } static int _format1_lv_setup(struct format_instance *fid, struct logical_volume *lv) { uint64_t max_size = UINT_MAX; if (!*lv->lvid.s) lvid_from_lvnum(&lv->lvid, &lv->vg->id, find_free_lvnum(lv)); if (lv->le_count > MAX_LE_TOTAL) { log_error("logical volumes cannot contain more than " "%d extents.", MAX_LE_TOTAL); return 0; } if (lv->size > max_size) { log_error("logical volumes cannot be larger than %s", display_size(fid->fmt->cmd, max_size)); return 0; } return 1; } static int _format1_pv_write(const struct format_type *fmt, struct physical_volume *pv, struct dm_list *mdas __attribute((unused)), int64_t sector __attribute((unused))) { struct dm_pool *mem; struct disk_list *dl; struct dm_list pvs; struct label *label; struct lvmcache_info *info; if (!(info = lvmcache_add(fmt->labeller, (char *) &pv->id, pv->dev, pv->vg_name, NULL, 0))) return_0; label = info->label; info->device_size = pv->size << SECTOR_SHIFT; info->fmt = fmt; dm_list_init(&info->mdas); dm_list_init(&pvs); /* Ensure any residual PE structure is gone */ pv->pe_size = pv->pe_count = 0; pv->pe_start = LVM1_PE_ALIGN; if (!(mem = dm_pool_create("lvm1 pv_write", 1024))) return_0; if (!(dl = dm_pool_alloc(mem, sizeof(*dl)))) goto_bad; dl->mem = mem; dl->dev = pv->dev; if (!export_pv(fmt->cmd, mem, NULL, &dl->pvd, pv)) goto_bad; /* must be set to be able to zero gap after PV structure in dev_write in order to make other disk tools happy */ dl->pvd.pv_on_disk.base = METADATA_BASE; dl->pvd.pv_on_disk.size = PV_SIZE; dl->pvd.pe_on_disk.base = LVM1_PE_ALIGN << SECTOR_SHIFT; dm_list_add(&pvs, &dl->list); if (!write_disks(fmt, &pvs)) goto_bad; dm_pool_destroy(mem); return 1; bad: dm_pool_destroy(mem); return 0; } static int _format1_vg_setup(struct format_instance *fid, struct volume_group *vg) { /* just check max_pv and max_lv */ if (!vg->max_lv || vg->max_lv >= MAX_LV) vg->max_lv = MAX_LV - 1; if (!vg->max_pv || vg->max_pv >= MAX_PV) vg->max_pv = MAX_PV - 1; if (vg->extent_size > MAX_PE_SIZE || vg->extent_size < MIN_PE_SIZE) { log_error("Extent size must be between %s and %s", display_size(fid->fmt->cmd, (uint64_t) MIN_PE_SIZE), display_size(fid->fmt->cmd, (uint64_t) MAX_PE_SIZE)); return 0; } if (vg->extent_size % MIN_PE_SIZE) { log_error("Extent size must be multiple of %s", display_size(fid->fmt->cmd, (uint64_t) MIN_PE_SIZE)); return 0; } /* Redundant? */ if (vg->extent_size & (vg->extent_size - 1)) { log_error("Extent size must be power of 2"); return 0; } return 1; } static int _format1_segtype_supported(struct format_instance *fid __attribute((unused)), const struct segment_type *segtype) { if (!(segtype->flags & SEG_FORMAT1_SUPPORT)) return_0; return 1; } static struct metadata_area_ops _metadata_format1_ops = { .vg_read = _format1_vg_read, .vg_write = _format1_vg_write, }; static struct format_instance *_format1_create_instance(const struct format_type *fmt, const char *vgname __attribute((unused)), const char *vgid __attribute((unused)), void *private __attribute((unused))) { struct format_instance *fid; struct metadata_area *mda; if (!(fid = dm_pool_alloc(fmt->cmd->mem, sizeof(*fid)))) return_NULL; fid->fmt = fmt; dm_list_init(&fid->metadata_areas); /* Define a NULL metadata area */ if (!(mda = dm_pool_alloc(fmt->cmd->mem, sizeof(*mda)))) { dm_pool_free(fmt->cmd->mem, fid); return_NULL; } mda->ops = &_metadata_format1_ops; mda->metadata_locn = NULL; dm_list_add(&fid->metadata_areas, &mda->list); return fid; } static void _format1_destroy_instance(struct format_instance *fid __attribute((unused))) { return; } static void _format1_destroy(const struct format_type *fmt) { dm_free((void *) fmt); } static struct format_handler _format1_ops = { .pv_read = _format1_pv_read, .pv_setup = _format1_pv_setup, .pv_write = _format1_pv_write, .lv_setup = _format1_lv_setup, .vg_setup = _format1_vg_setup, .segtype_supported = _format1_segtype_supported, .create_instance = _format1_create_instance, .destroy_instance = _format1_destroy_instance, .destroy = _format1_destroy, }; #ifdef LVM1_INTERNAL struct format_type *init_lvm1_format(struct cmd_context *cmd) #else /* Shared */ struct format_type *init_format(struct cmd_context *cmd); struct format_type *init_format(struct cmd_context *cmd) #endif { struct format_type *fmt = dm_malloc(sizeof(*fmt)); if (!fmt) return_NULL; fmt->cmd = cmd; fmt->ops = &_format1_ops; fmt->name = FMT_LVM1_NAME; fmt->alias = NULL; fmt->orphan_vg_name = FMT_LVM1_ORPHAN_VG_NAME; fmt->features = FMT_RESTRICTED_LVIDS | FMT_ORPHAN_ALLOCATABLE | FMT_RESTRICTED_READAHEAD; fmt->private = NULL; if (!(fmt->labeller = lvm1_labeller_create(fmt))) { log_error("Couldn't create lvm1 label handler."); return NULL; } if (!(label_register_handler(FMT_LVM1_NAME, fmt->labeller))) { log_error("Couldn't register lvm1 label handler."); return NULL; } log_very_verbose("Initialised format: %s", fmt->name); return fmt; }
6,150
2,550
<gh_stars>1000+ /********************************************************************* * Software License Agreement (BSD License) * * Copyright (C) 2010-2012 <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of the author nor other 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 OWNER 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 <stdio.h> #include <opencv/highgui.h> #include "libuvc/libuvc.h" void cb(uvc_frame_t *frame, void *ptr) { uvc_frame_t *bgr; uvc_error_t ret; IplImage* cvImg; printf("callback! length = %u, ptr = %d\n", frame->data_bytes, (int) ptr); bgr = uvc_allocate_frame(frame->width * frame->height * 3); if (!bgr) { printf("unable to allocate bgr frame!"); return; } ret = uvc_any2bgr(frame, bgr); if (ret) { uvc_perror(ret, "uvc_any2bgr"); uvc_free_frame(bgr); return; } cvImg = cvCreateImageHeader( cvSize(bgr->width, bgr->height), IPL_DEPTH_8U, 3); cvSetData(cvImg, bgr->data, bgr->width * 3); cvNamedWindow("Test", CV_WINDOW_AUTOSIZE); cvShowImage("Test", cvImg); cvWaitKey(10); cvReleaseImageHeader(&cvImg); uvc_free_frame(bgr); } int main(int argc, char **argv) { uvc_context_t *ctx; uvc_error_t res; uvc_device_t *dev; uvc_device_handle_t *devh; uvc_stream_ctrl_t ctrl; res = uvc_init(&ctx, NULL); if (res < 0) { uvc_perror(res, "uvc_init"); return res; } puts("UVC initialized"); res = uvc_find_device( ctx, &dev, 0, 0, NULL); if (res < 0) { uvc_perror(res, "uvc_find_device"); } else { puts("Device found"); res = uvc_open(dev, &devh); if (res < 0) { uvc_perror(res, "uvc_open"); } else { puts("Device opened"); uvc_print_diag(devh, stderr); res = uvc_get_stream_ctrl_format_size( devh, &ctrl, UVC_FRAME_FORMAT_YUYV, 640, 480, 30 ); uvc_print_stream_ctrl(&ctrl, stderr); if (res < 0) { uvc_perror(res, "get_mode"); } else { res = uvc_start_iso_streaming(devh, &ctrl, cb, 12345); if (res < 0) { uvc_perror(res, "start_streaming"); } else { puts("Streaming for 10 seconds..."); uvc_error_t resAEMODE = uvc_set_ae_mode(devh, 1); uvc_perror(resAEMODE, "set_ae_mode"); int i; for (i = 1; i <= 10; i++) { /* uvc_error_t resPT = uvc_set_pantilt_abs(devh, i * 20 * 3600, 0); */ /* uvc_perror(resPT, "set_pt_abs"); */ uvc_error_t resEXP = uvc_set_exposure_abs(devh, 20 + i * 5); uvc_perror(resEXP, "set_exp_abs"); sleep(1); } sleep(10); uvc_stop_streaming(devh); puts("Done streaming."); } } uvc_close(devh); puts("Device closed"); } uvc_unref_device(dev); } uvc_exit(ctx); puts("UVC exited"); return 0; }
1,819
963
package com.vladmihalcea.book.hpjp.hibernate.association; import com.vladmihalcea.book.hpjp.util.AbstractTest; import org.junit.Test; import javax.persistence.*; import java.io.Serializable; import java.util.*; /** * @author <NAME> */ public class BidirectionalManyToManyLinkEntityOrderColumnTest extends AbstractTest { @Override protected Class<?>[] entities() { return new Class<?>[]{ Post.class, Tag.class, PostTag.class }; } @Test public void testLifecycle() { doInJPA(entityManager -> { Post post1 = new Post("JPA with Hibernate"); Post post2 = new Post("Native Hibernate"); Tag tag1 = new Tag("Java"); Tag tag2 = new Tag("Hibernate"); entityManager.persist(post1); entityManager.persist(post2); entityManager.persist(tag1); entityManager.persist(tag2); post1.addTag(tag1); post1.addTag(tag2); post2.addTag(tag1); entityManager.flush(); LOGGER.info("Remove"); post1.removeTag(tag1); }); } @Test public void testShuffle() { final Long postId = doInJPA(entityManager -> { Post post1 = new Post("JPA with Hibernate"); Post post2 = new Post("Native Hibernate"); Tag tag1 = new Tag("Java"); Tag tag2 = new Tag("Hibernate"); entityManager.persist(post1); entityManager.persist(post2); entityManager.persist(tag1); entityManager.persist(tag2); post1.addTag(tag1); post1.addTag(tag2); post2.addTag(tag1); entityManager.flush(); return post1.getId(); }); doInJPA(entityManager -> { LOGGER.info("Shuffle"); Post post1 = entityManager.find(Post.class, postId); post1.getTags().sort( Comparator.comparing((PostTag postTag) -> postTag.getId().getTagId()) .reversed() ); }); } @Entity(name = "Post") public static class Post { @Id @GeneratedValue private Long id; private String title; @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true) @OrderColumn(name = "entry") private List<PostTag> tags = new ArrayList<>(); public Post() { } public Post(String title) { this.title = title; } public Long getId() { return id; } public List<PostTag> getTags() { return tags; } public void addTag(Tag tag) { PostTag postTag = new PostTag(this, tag); tags.add(postTag); tag.getPosts().add(postTag); } public void removeTag(Tag tag) { for (Iterator<PostTag> iterator = tags.iterator(); iterator.hasNext(); ) { PostTag postTag = iterator.next(); if (postTag.getPost().equals(this) && postTag.getTag().equals(tag)) { iterator.remove(); postTag.getTag().getPosts().remove(postTag); postTag.setPost(null); postTag.setTag(null); break; } } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Post post = (Post) o; return Objects.equals(title, post.title); } @Override public int hashCode() { return Objects.hash(title); } } @Embeddable public static class PostTagId implements Serializable { private Long postId; private Long tagId; public PostTagId() { } public PostTagId(Long postId, Long tagId) { this.postId = postId; this.tagId = tagId; } public Long getPostId() { return postId; } public Long getTagId() { return tagId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PostTagId that = (PostTagId) o; return Objects.equals(postId, that.getPostId()) && Objects.equals(tagId, that.getTagId()); } @Override public int hashCode() { return Objects.hash(postId, tagId); } } @Entity(name = "PostTag") public static class PostTag { @EmbeddedId private PostTagId id; @ManyToOne @MapsId("postId") private Post post; @ManyToOne @MapsId("tagId") private Tag tag; public PostTag() { } public PostTag(Post post, Tag tag) { this.post = post; this.tag = tag; this.id = new PostTagId(post.getId(), tag.getId()); } public PostTagId getId() { return id; } public Post getPost() { return post; } public void setPost(Post post) { this.post = post; } public Tag getTag() { return tag; } public void setTag(Tag tag) { this.tag = tag; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PostTag that = (PostTag) o; return Objects.equals(post, that.post) && Objects.equals(tag, that.tag); } @Override public int hashCode() { return Objects.hash(post, tag); } } @Entity(name = "Tag") public static class Tag { @Id @GeneratedValue private Long id; private String name; @OneToMany(mappedBy = "tag", cascade = CascadeType.ALL, orphanRemoval = true) private List<PostTag> posts = new ArrayList<>(); public Tag() { } public Tag(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<PostTag> getPosts() { return posts; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tag tag = (Tag) o; return Objects.equals(name, tag.name); } @Override public int hashCode() { return Objects.hash(name); } } }
3,653
883
<reponame>kawww/bludit { "plugin-data": { "name": "Site haritası", "description": "Bu eklenti, web sitenizdeki sayfaların listesini sağlayan bir sitemap.xml dosyası oluşturur. Bu, arama motorlarının web sitesindeki içeriği düzenleyip filtrelemesine yardımcı olur." }, "sitemap-url": "Site haritası URL" }
141
1,900
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehcache.clustered.server; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import org.ehcache.clustered.common.internal.messages.ConcurrentEntityMessage; import org.ehcache.clustered.common.internal.messages.EhcacheEntityMessage; import org.ehcache.clustered.common.internal.messages.ServerStoreOpMessage; import org.terracotta.entity.ConcurrencyStrategy; import org.ehcache.clustered.server.internal.messages.EhcacheMessageTrackerCatchup; import static java.util.Collections.singleton; public final class ConcurrencyStrategies { public static final int DEFAULT_KEY = 1; private ConcurrencyStrategies() { } public static ConcurrencyStrategy<EhcacheEntityMessage> clusterTierConcurrency(KeySegmentMapper mapper) { return new DefaultConcurrencyStrategy(mapper); } public static ConcurrencyStrategy<EhcacheEntityMessage> clusterTierManagerConcurrency() { return CLUSTER_TIER_MANAGER_CONCURRENCY_STRATEGY; } private static final ConcurrencyStrategy<EhcacheEntityMessage> CLUSTER_TIER_MANAGER_CONCURRENCY_STRATEGY = new ConcurrencyStrategy<EhcacheEntityMessage>() { @Override public int concurrencyKey(EhcacheEntityMessage message) { return DEFAULT_KEY; } @Override public Set<Integer> getKeysForSynchronization() { return singleton(DEFAULT_KEY); } }; public static class DefaultConcurrencyStrategy implements ConcurrencyStrategy<EhcacheEntityMessage> { public static final int DATA_CONCURRENCY_KEY_OFFSET = DEFAULT_KEY + 1; public static final int TRACKER_SYNC_KEY = Integer.MAX_VALUE - 1; private final KeySegmentMapper mapper; public DefaultConcurrencyStrategy(KeySegmentMapper mapper) { this.mapper = mapper; } @Override public int concurrencyKey(EhcacheEntityMessage entityMessage) { if (entityMessage instanceof ServerStoreOpMessage.GetMessage) { return UNIVERSAL_KEY; } else if (entityMessage instanceof ConcurrentEntityMessage) { ConcurrentEntityMessage concurrentEntityMessage = (ConcurrentEntityMessage) entityMessage; return DATA_CONCURRENCY_KEY_OFFSET + mapper.getSegmentForKey(concurrentEntityMessage.concurrencyKey()); } else if (entityMessage instanceof EhcacheMessageTrackerCatchup) { return MANAGEMENT_KEY; } else { return DEFAULT_KEY; } } @Override public Set<Integer> getKeysForSynchronization() { Set<Integer> result = new LinkedHashSet<>(); for (int i = 0; i <= mapper.getSegments(); i++) { result.add(DEFAULT_KEY + i); } result.add(TRACKER_SYNC_KEY); return Collections.unmodifiableSet(result); } } }
1,070
310
<reponame>tsukoyumi/skylicht-engine<gh_stars>100-1000 /* !@ MIT License Copyright (c) 2020 Skylicht Technology CO., LTD 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. This file is part of the "Skylicht Engine". https://github.com/skylicht-lab/skylicht-engine !# */ #pragma once #include "GUI/Controls/CBase.h" #include "GUI/Controls/CLabel.h" #include "GUI/Controls/CIcon.h" #include "GUI/Controls/CIconButton.h" #include "GUI/Controls/CResizableControl.h" namespace Skylicht { namespace Editor { namespace GUI { class CWindow : public CResizableControl { protected: CDragger* m_titleBar; CLabel* m_title; CIcon* m_icon; CIconButton* m_close; bool m_childStyle; public: CWindow(CBase* parent, float x, float y, float w, float h); virtual ~CWindow(); virtual void onCloseWindow(); virtual void renderUnder(); virtual void touch(); virtual void onChildTouched(CBase* child); void setStyleChild(bool b); void setCaption(const std::wstring& text) { m_title->setString(text); } const std::wstring& getCaption() { return m_title->getString(); } inline void showIcon(bool b) { m_icon->setHidden(!b); } void setIcon(ESystemIcon icon) { m_icon->setIcon(icon); m_icon->setHidden(false); } inline void showCloseButton(bool b) { m_close->setHidden(!b); } void dragMoveCommand(const SPoint& mouseOffset); void forceUpdateLayout(); protected: void onCloseButtonPress(CBase* sender); }; } } }
915
3,062
<reponame>kudlav/organicmaps package com.mapswithme.maps.search; import android.os.Bundle; import android.view.View; import androidx.annotation.CallSuper; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.mapswithme.maps.R; import com.mapswithme.maps.base.BaseMwmRecyclerFragment; import com.mapswithme.maps.widget.PlaceholderView; import com.mapswithme.maps.widget.SearchToolbarController; import com.mapswithme.util.UiUtils; public class SearchHistoryFragment extends BaseMwmRecyclerFragment<SearchHistoryAdapter> { private PlaceholderView mPlaceHolder; private void updatePlaceholder() { UiUtils.showIf(getAdapter().getItemCount() == 0, mPlaceHolder); } @NonNull @Override protected SearchHistoryAdapter createAdapter() { return new SearchHistoryAdapter(((SearchToolbarController.Container) getParentFragment()).getController()); } @Override protected @LayoutRes int getLayoutRes() { return R.layout.fragment_search_base; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); getRecyclerView().setLayoutManager(new LinearLayoutManager(view.getContext())); mPlaceHolder = view.findViewById(R.id.placeholder); mPlaceHolder.setContent(R.string.search_history_title, R.string.search_history_text); getAdapter().registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onChanged() { updatePlaceholder(); } }); updatePlaceholder(); } @CallSuper @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ((SearchFragment) getParentFragment()).setRecyclerScrollListener(getRecyclerView()); } }
658
2,538
<filename>intro/numpy/examples/plot_chebyfit.py<gh_stars>1000+ """ Fitting in Chebyshev basis ========================== Plot noisy data and their polynomial fit in a Chebyshev basis """ import numpy as np import matplotlib.pyplot as plt np.random.seed(0) x = np.linspace(-1, 1, 2000) y = np.cos(x) + 0.3*np.random.rand(2000) p = np.polynomial.Chebyshev.fit(x, y, 90) plt.plot(x, y, 'r.') plt.plot(x, p(x), 'k-', lw=3) plt.show()
194
22,779
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * * 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 org.jkiss.dbeaver.ui.controls.resultset.colors; import org.eclipse.jface.dialogs.IDialogConstants; import org.jkiss.dbeaver.model.data.DBDAttributeBinding; import org.jkiss.dbeaver.model.virtual.DBVEntity; import org.jkiss.dbeaver.ui.controls.resultset.ResultSetRow; import org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer; import org.jkiss.dbeaver.ui.controls.resultset.internal.ResultSetMessages; public class CustomizeColorsAction extends ColorAction { private ResultSetViewer resultSetViewer; private final DBDAttributeBinding curAttribute; private final ResultSetRow row; public CustomizeColorsAction(ResultSetViewer resultSetViewer, DBDAttributeBinding curAttribute, ResultSetRow row) { super(resultSetViewer, ResultSetMessages.actions_name_row_colors); //$NON-NLS-1$ this.resultSetViewer = resultSetViewer; this.curAttribute = curAttribute; this.row = row; } @Override public void run() { final DBVEntity vEntity = getColorsVirtualEntity(); ColorSettingsDialog dialog = new ColorSettingsDialog(resultSetViewer, vEntity, curAttribute, row); if (dialog.open() != IDialogConstants.OK_ID) { return; } updateColors(vEntity); } @Override public boolean isEnabled() { return true; } }
681
892
{ "schema_version": "1.2.0", "id": "GHSA-qj27-32wp-ghrg", "modified": "2021-12-28T00:01:27Z", "published": "2021-12-18T00:00:40Z", "aliases": [ "CVE-2021-41498" ], "details": "Buffer overflow in ajaxsoundstudio.com Pyo &lt and 1.03 in the Server_jack_init function. which allows attackers to conduct Denial of Service attacks by arbitrary constructing a overlong server name.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-41498" }, { "type": "WEB", "url": "https://github.com/belangeo/pyo/issues/221" } ], "database_specific": { "cwe_ids": [ "CWE-120" ], "severity": "HIGH", "github_reviewed": false } }
351
348
<filename>docs/data/leg-t2/056/05603198.json {"nom":"Rohan","circ":"3ème circonscription","dpt":"Morbihan","inscrits":1180,"abs":617,"votants":563,"blancs":32,"nuls":20,"exp":511,"res":[{"nuance":"REM","nom":"<NAME>","voix":330},{"nuance":"FI","nom":"Mme <NAME>","voix":181}]}
113
2,690
<gh_stars>1000+ // It is extremely important to use this header // if you are using the numpy_eigen interface #include <numpy_eigen/boost_python_headers.hpp> #include <aslam/CameraGeometryDesignVariableContainer.hpp> #include <sm/python/stl_converters.hpp> #include <aslam/ReprojectionError.hpp> #include <aslam/backend/DesignVariable.hpp> #include "helpers.hpp" void exportCameraGeometryDvc() { using namespace boost::python; using namespace aslam; class_<CameraGeometryDesignVariableContainer, boost::shared_ptr<CameraGeometryDesignVariableContainer>, boost::noncopyable>( "CameraGeometryDesignVariableContainer", init<const boost::shared_ptr<cameras::CameraGeometryBase> &, bool, bool, bool>( "CameraGeometryDesignVariableContainer( camera, estimateProjection, estimateDistortion, estimateShutter)")) .def( "keypointTime", &CameraGeometryDesignVariableContainer::keypointTime, "ScalarExpression keypointTime( imageTimestamp, keypointMeasurement)").def( "temporalOffset", &CameraGeometryDesignVariableContainer::temporalOffset, "ScalarExpression temporalOffset( keypointMeasurement)") .def("createReprojectionError", &CameraGeometryDesignVariableContainer::createReprojectionError, "reprojectionError createReprojectionError( y, invR, p_c )") .def("setActive", &CameraGeometryDesignVariableContainer::setActive) .def("isActive", &CameraGeometryDesignVariableContainer::isActive).def( "isProjectionActive", &CameraGeometryDesignVariableContainer::isProjectionActive).def( "isDistortionActive", &CameraGeometryDesignVariableContainer::isDistortionActive).def( "isShutterActive", &CameraGeometryDesignVariableContainer::isShutterActive).def( "camera", &CameraGeometryDesignVariableContainer::camera).def( "getDesignVariable", &CameraGeometryDesignVariableContainer::getDesignVariable).def( "getDesignVariables", &getDesignVariablesWrap<CameraGeometryDesignVariableContainer>) ; class_<ReprojectionError, boost::shared_ptr<ReprojectionError>, bases<aslam::backend::ErrorTerm>, boost::noncopyable>( "ReprojectionError", init<const Eigen::VectorXd &, const Eigen::MatrixXd &, backend::HomogeneousExpression, cameras::CameraGeometryBase *>( "ReprojectionError( y, invR, p_c, camera )")).def( init<const Eigen::VectorXd &, const Eigen::MatrixXd &, backend::HomogeneousExpression, CameraGeometryDesignVariableContainer *>( "ReprojectionError( y, invR, p_c, cameraGeometryDesignVariableContainer )")) .def("getCamera", &ReprojectionError::getCamera, return_internal_reference<>()).def("getKeypoint", &ReprojectionError::getKeypoint) .def("getPoint", &ReprojectionError::getPoint).def( "isEnabled", &ReprojectionError::isEnabled).def( "getProjection", &ReprojectionError::getProjection).def( "getProjectionSuccess", &ReprojectionError::getProjectionSuccess); }
1,107
567
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_swift_demoVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_swift_demoVersionString[];
54
575
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.ui; /** * Base implementation of DropdownItem which is used to get default settings to * show the item. */ public class DropdownItemBase implements DropdownItem { @Override public String getLabel() { return null; } @Override public String getSublabel() { return null; } @Override public String getItemTag() { return null; } @Override public int getIconId() { return NO_ICON; } @Override public boolean isEnabled() { return true; } @Override public boolean isGroupHeader() { return false; } @Override public boolean isMultilineLabel() { return false; } @Override public boolean isBoldLabel() { return false; } @Override public int getLabelFontColorResId() { return R.color.default_text_color_list; } @Override public int getSublabelFontSizeResId() { return R.dimen.text_size_small; } @Override public boolean isIconAtStart() { return false; } @Override public int getIconSizeResId() { return 0; } @Override public int getIconMarginResId() { return R.dimen.dropdown_icon_margin; } }
565
647
<reponame>gilbertguoze/trick #include "trick/Unit.hh"
25
897
# Python program to Find the Sum of Digits of a Number def sum_of_digits(num): # Extracting Each digits # and compute thier sum in 's' s = 0 while num != 0: s = s + (num % 10) num = num // 10 return s if __name__ == '__main__': # Input the number And # Call the function print("Enter the number: ", end="") n = int(input()) S = sum_of_digits(abs(n)) print("The sum of digits of the given number is {}.".format(S)) ''' Time Complexity: O(log(num)), where "num" is the length of the given number Space Complexity: O(1) SAMPLE INPUT AND OUTPUT SAMPLE 1 Enter the number: -12 The sum of digits of the given number is 3. SAMPLE 2 Enter the number: 43258 The sum of digits of the given number is 22. '''
298
549
package net.notejam.spring.pad; import static net.notejam.spring.test.UriUtil.buildUri; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import net.notejam.spring.URITemplates; import net.notejam.spring.pad.controller.DeletePadController; import net.notejam.spring.test.IntegrationTest; import net.notejam.spring.test.MockMvcProvider; import net.notejam.spring.user.SignedUpUserProvider; import net.notejam.spring.user.UserService; /** * An integration test for the {@link DeletePadController}. * * @author <EMAIL> * @see <a href="bitcoin:1335STSwu9hST4vcMRppEPgENMHD2r1REK">Donations</a> */ @IntegrationTest @RunWith(SpringJUnit4ClassRunner.class) @WithMockUser(SignedUpUserProvider.EMAIL) public class DeletePadControllerTest { @Rule @Autowired public MockMvcProvider mockMvcProvider; @Rule @Autowired public SignedUpUserProvider userProvider; @Autowired private PadService padService; @Autowired private UserService userService; @Autowired private PadRepository repository; private Pad pad; /** * The edit note uri. */ private String uri; private void setPad() { pad = padService.buildPad(); pad.setName("name"); padService.savePad(pad); } @Before public void setUri() { setPad(); uri = buildUri(URITemplates.DELETE_PAD, pad.getId()); } /** * Pad can be deleted by its owner. */ @Test public void padCanBeDeleted() throws Exception { mockMvcProvider.getMockMvc().perform(post(uri) .with(csrf())) .andExpect(status().is3xxRedirection()); assertNull(repository.findOne(pad.getId())); } /** * Pad can't be deleted by not an owner. */ @Test public void padCannotBeDeletedByOtherUser() throws Exception { final String otherUser = "<EMAIL>"; userService.signUp(otherUser, "password"); mockMvcProvider.getMockMvc().perform(post(uri) .with(csrf()) .with(user(otherUser))) .andExpect(status().is(403)); assertNotNull(repository.findOne(pad.getId())); } }
1,217
3,931
/* * This file is part of dependency-check-core. * * 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. * * Copyright (c) 2018 <NAME>. All Rights Reserved. */ package org.owasp.dependencycheck.dependency; import java.io.Serializable; /** * CVSS V2 scoring information. * * @author <NAME> */ public class CvssV2 implements Serializable { /** * Serial version UID. */ private static final long serialVersionUID = -2203955879356702367L; /** * CVSS Score. */ private final float score; /** * CVSS Access Vector. */ private final String accessVector; /** * CVSS Access Complexity. */ private final String accessComplexity; /** * CVSS Authentication. */ private final String authentication; /** * CVSS Confidentiality Impact. */ private final String confidentialityImpact; /** * CVSS Integrity Impact. */ private final String integrityImpact; /** * CVSS Availability Impact. */ private final String availabilityImpact; /** * CVSS version. */ private final String version; /** * CVSSv2 Base Metric severity. */ private String severity; /** * CVSSv2 Base Metric exploitability score. */ private Float exploitabilityScore; /** * CVSSv2 Base Metric impact score. */ private Float impactScore; /** * CVSSv2 Base Metric acInsufInfo. */ private Boolean acInsufInfo; /** * CVSSv2 Base Metric obtain all privilege. */ private Boolean obtainAllPrivilege; /** * CVSSv2 Base Metric obtain user privilege. */ private Boolean obtainUserPrivilege; /** * CVSSv2 Base Metric obtain other privilege. */ private Boolean obtainOtherPrivilege; /** * CVSSv2 Base Metric user interaction required. */ private Boolean userInteractionRequired; /** * Constructs a new CVSS V2 object. * * @param score the score * @param accessVector the access vector * @param accessComplexity the access complexity * @param authentication the authentication * @param confidentialityImpact the confidentiality impact * @param integrityImpact the integrity impact * @param availabilityImpact the availability impact * @param severity the severity */ //CSOFF: ParameterNumber public CvssV2(float score, String accessVector, String accessComplexity, String authentication, String confidentialityImpact, String integrityImpact, String availabilityImpact, String severity) { this(score, accessVector, accessComplexity, authentication, confidentialityImpact, integrityImpact, availabilityImpact, severity, null, null, null, null, null, null, null, null); } /** * Constructs a new CVSS V2 object. * * @param score the score * @param accessVector the access vector * @param accessComplexity the access complexity * @param authentication the authentication * @param confidentialityImpact the confidentiality impact * @param integrityImpact the integrity impact * @param availabilityImpact the availability impact * @param severity the severity * @param exploitabilityScore the exploitability score * @param impactScore the impact score * @param acInsufInfo the acInsufInfo * @param obtainAllPrivilege whether or not the vulnerability allows one to obtain all privileges * @param obtainUserPrivilege whether or not the vulnerability allows one to obtain user privileges * @param obtainOtherPrivilege whether or not the vulnerability allows one to obtain other privileges * @param userInteractionRequired whether or not user interaction is required * @param version the CVSS version */ //CSOFF: ParameterNumber public CvssV2(float score, String accessVector, String accessComplexity, String authentication, String confidentialityImpact, String integrityImpact, String availabilityImpact, String severity, Float exploitabilityScore, Float impactScore, Boolean acInsufInfo, Boolean obtainAllPrivilege, Boolean obtainUserPrivilege, Boolean obtainOtherPrivilege, Boolean userInteractionRequired, String version) { this.score = score; this.accessVector = accessVector; this.accessComplexity = accessComplexity; this.authentication = authentication; this.confidentialityImpact = confidentialityImpact; this.integrityImpact = integrityImpact; this.availabilityImpact = availabilityImpact; this.severity = severity; this.exploitabilityScore = exploitabilityScore; this.impactScore = impactScore; this.acInsufInfo = acInsufInfo; this.obtainAllPrivilege = obtainAllPrivilege; this.obtainUserPrivilege = obtainUserPrivilege; this.obtainOtherPrivilege = obtainOtherPrivilege; this.userInteractionRequired = userInteractionRequired; this.version = version; } //CSON: ParameterNumber /** * Get the value of score. * * @return the value of score */ public float getScore() { return score; } /** * Get the value of accessVector. * * @return the value of accessVector */ public String getAccessVector() { return accessVector; } /** * Get the value of accessComplexity. * * @return the value of accessComplexity */ public String getAccessComplexity() { return accessComplexity; } /** * Get the value of authentication. * * @return the value of authentication */ public String getAuthentication() { return authentication; } /** * Get the value of confidentialityImpact. * * @return the value of confidentialityImpact */ public String getConfidentialityImpact() { return confidentialityImpact; } /** * Get the value of integrityImpact. * * @return the value of integrityImpact */ public String getIntegrityImpact() { return integrityImpact; } /** * Get the value of availabilityImpact. * * @return the value of availabilityImpact */ public String getAvailabilityImpact() { return availabilityImpact; } /** * Get the value of version. * * @return the value of version */ public String getVersion() { return version; } /** * Returns the severity for the vulnerability. * * @return the severity */ public String getSeverity() { return severity; } /** * Returns the exploitabilityScore for the vulnerability. * * @return the exploitabilityScore */ public Float getExploitabilityScore() { return exploitabilityScore; } /** * Returns the impactScore for the vulnerability. * * @return the impactScore */ public Float getImpactScore() { return impactScore; } /** * Returns the acInsufInfo for the vulnerability. * * @return the acInsufInfo */ public Boolean isAcInsufInfo() { return acInsufInfo; } /** * Returns the obtainAllPrivilege for the vulnerability. * * @return the obtainAllPrivilege */ public Boolean isObtainAllPrivilege() { return obtainAllPrivilege; } /** * Returns the obtainUserPrivilege for the vulnerability. * * @return the obtainUserPrivilege */ public Boolean isObtainUserPrivilege() { return obtainUserPrivilege; } /** * Returns the obtainOtherPrivilege for the vulnerability. * * @return the obtainOtherPrivilege */ public Boolean isObtainOtherPrivilege() { return obtainOtherPrivilege; } /** * Returns the userInteractionRequired for the vulnerability. * * @return the userInteractionRequired */ public Boolean isUserInteractionRequired() { return userInteractionRequired; } @Override public String toString() { return String.format("/AV:%s/AC:%s/Au:%s/C:%s/I:%s/A:%s", accessVector == null ? "" : accessVector.substring(0, 1), accessComplexity == null ? "" : accessComplexity.substring(0, 1), authentication == null ? "" : authentication.substring(0, 1), confidentialityImpact == null ? "" : confidentialityImpact.substring(0, 1), integrityImpact == null ? "" : integrityImpact.substring(0, 1), availabilityImpact == null ? "" : availabilityImpact.substring(0, 1)); } }
3,312
4,772
package example.repo; import example.model.Customer874; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer874Repository extends CrudRepository<Customer874, Long> { List<Customer874> findByLastName(String lastName); }
87
343
class DynamicSearchException(Exception): """ Base exception for the app. """ class DynamicSearchRetry(DynamicSearchException): """ Exception to encapsulate backend specific errors that should be retried. """
67
1,104
<gh_stars>1000+ { "Name: ": "Imię", "Alignment:": "Światopogląd", "Law": "Praworządny", "Neutral": "Neutralny", "Chaos": "Zły", "Player:": "Gracz", "Experience:": "Doświadczenie", "Class:": "Klasa", "Warrior": "Wojownik", "Rogue": "Szelma", "Mage": "Czarodziej", "Base Attack Bonus:": "Premia do ataku", "Level:": "Poziom", "Initiative:": "Inicjatywa", "Strength": "Siła", "melee to hit": "Do walki wręcz", "melee damage": "Do obrażeń wręcz", "Dexterity": "Zręczność", "ranged to hit": "Do strzelania", "armor class": "Klasa pancerza", "initiative": "inicjatywa", "Constitution": "Kondycja", "hit points per level": "Do wytrzymałości na poziom", "Intelligence": "Inteligencja", "languages known": "Znane języki", "Wisdom": "Mądrość", "save vs mind control": "Do obrony przed kontrolą", "Charisma": "Charyzma", "max # of allies": "Do liczby sojuszników", "Saving Throws": "Rzuty obronne", "Poison": "Trucizna", "Breath Weapon": "Zionięcie", "Polymorph": "Przemiana", "Spell": "Czary", "Magic Item": "Magiczne przedmioty", "Class Abilities": "Zdolności klasy", "Traits": "Umiejętności", "Equipment": "Ekwipunek", "Armor Class": "Klasa pancerza", "Fortune Points": "Punkty Fortuny", "Hit Points": "Punkty Wytrzymałości", "Current": "Obecne", "Weapons": "Broń", "Name": "Nazwa", "To hit": "Trafienie", "Dice": "Kości", "Damage": "Obrażenia", "Skills": "Umiejętności", "Str": "Sił", "Dex": "Zrc", "Con": "Kon", "Int": "Int", "Wis": "Mdr", "Cha": "Cha", "Attribute": "Cechy", "Bonus": "Bonus", "Easy": "Łatwy", "Normal": "Normalny", "Hard": "Trudny", "Very Hard": "Bardzo Trudny", "Impossible": "Niemożliwy", "Difficulty": "Trudność", "Magic": "Magia", "Cantrips:": "Sztuczki", "Spells:": "Zaklęcia", "Description": "Opis", "Rituals:": "Rytuały", "Allies and Henchmen": "Sojusznicy", "Notes and History": "Historia i notatki" }
1,015
400
<reponame>imknown/android-lite-async /* * Copyright (C) 2013 l<EMAIL> * * 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.litesuits.android.async; import android.os.Handler; import android.os.Looper; import java.util.ArrayList; import java.util.LinkedList; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * the {@link TaskExecutor} can execute task in many ways. * <ul> * <li>1. OrderedTask, 有序的执行一些列任务。 * <li>2. CyclicBarrierTask, 并发的执行一系列任务,且会在所有任务执行完成时集中到一个关卡点(执行特定的函数)。 * <li>3. Delayed Task, 延时任务。 * <li>4. Timer Runnable, 定时任务。 * </ul> * * @author MaTianyu * 2014-2-3下午6:30:14 */ public class TaskExecutor { /** * 开子线程 * * @param run */ public static void start(Runnable run) { AsyncTask.execute(run); } /** * 开子线程,并发超出数量限制时允许丢失任务。 * * @param run */ public static void startAllowingLoss(Runnable run) { AsyncTask.executeAllowingLoss(run); } /** * 有序异步任务执行器 * * @return */ public static OrderedTaskExecutor newOrderedExecutor() { return new OrderedTaskExecutor(); } /** * 关卡异步任务执行器 * * @return */ public static CyclicBarrierExecutor newCyclicBarrierExecutor() { return new CyclicBarrierExecutor(); } /** * 延时异步任务 * * @param task * @param time * @param unit */ public static void startDelayedTask(final AsyncTask<?, ?, ?> task, long time, TimeUnit unit) { long delay = time; if (unit != null) delay = unit.toMillis(time); new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { task.execute(); } }, delay); } /** * 启动定时任务 * * @param run * @param delay >0 延迟时间 * @param period >0 心跳间隔时间 * @return */ public static Timer startTimerTask(final Runnable run, long delay, long period) { Timer timer = new Timer(); TimerTask timerTask = new TimerTask() { @Override public void run() { run.run(); } }; timer.scheduleAtFixedRate(timerTask, delay, period); return timer; } public static class OrderedTaskExecutor { LinkedList<AsyncTask<?, ?, ?>> taskList = new LinkedList<AsyncTask<?, ?, ?>>(); private transient boolean isRunning = false; public OrderedTaskExecutor put(AsyncTask<?, ?, ?> task) { synchronized (taskList) { if (task != null) taskList.add(task); } return this; } public void start() { if (isRunning) return; isRunning = true; for (AsyncTask<?, ?, ?> each : taskList) { final AsyncTask<?, ?, ?> task = each; task.setFinishedListener(new AsyncTask.FinishedListener() { @Override public void onPostExecute() { synchronized (taskList) { executeNext(); } } @Override public void onCancelled() { synchronized (taskList) { taskList.remove(task); if (task.getStatus() == AsyncTask.Status.RUNNING) { executeNext(); } } } }); } executeNext(); } @SuppressWarnings("unchecked") private void executeNext() { AsyncTask<?, ?, ?> next = null; if (taskList.size() > 0) { next = taskList.removeFirst(); } if (next != null) { next.execute(); } else { isRunning = false; } } } public static class CyclicBarrierExecutor { ArrayList<AsyncTask<?, ?, ?>> taskList = new ArrayList<AsyncTask<?, ?, ?>>(); private transient boolean isRunning = false; public CyclicBarrierExecutor put(AsyncTask<?, ?, ?> task) { if (task != null) taskList.add(task); return this; } public void start(final AsyncTask<?, ?, ?> finishTask) { start(finishTask, 0, null); } @SuppressWarnings("unchecked") public void start(final AsyncTask<?, ?, ?> endOnUiTask, final long time, final TimeUnit unit) { if (isRunning) throw new RuntimeException("CyclicBarrierExecutor only can start once."); isRunning = true; final CountDownLatch latch = new CountDownLatch(taskList.size()); new SimpleTask<Boolean>() { @Override protected Boolean doInBackground() { try { if (unit == null) latch.await(); else latch.await(time, unit); } catch (InterruptedException e) { e.printStackTrace(); } return true; } @Override protected void onPostExecute(Boolean aBoolean) { endOnUiTask.execute(); } }.execute(); startInternal(latch); } public void start(Runnable endOnUiThread) { start(endOnUiThread, 0, null); } public void start(final Runnable endOnUiThread, final long time, final TimeUnit unit) { if (isRunning) throw new RuntimeException("CyclicBarrierExecutor only can start once."); isRunning = true; final CountDownLatch latch = new CountDownLatch(taskList.size()); new SimpleTask<Boolean>() { @Override protected Boolean doInBackground() { try { if (unit == null) latch.await(); else latch.await(time, unit); } catch (InterruptedException e) { e.printStackTrace(); } return true; } @Override protected void onPostExecute(Boolean aBoolean) { endOnUiThread.run(); } }.execute(); startInternal(latch); } private void startInternal(final CountDownLatch latch) { for (AsyncTask<?, ?, ?> each : taskList) { each.setFinishedListener(new AsyncTask.FinishedListener() { @Override public void onPostExecute() { latch.countDown(); } @Override public void onCancelled() { latch.countDown(); } }); each.execute(); } } } }
4,105
942
#pragma once #include <QByteArray> #include <TGlobal> class T_CORE_EXPORT TWebSocketFrame { public: enum OpCode { Continuation = 0x0, TextFrame = 0x1, BinaryFrame = 0x2, Reserve3 = 0x3, Reserve4 = 0x4, Reserve5 = 0x5, Reserve6 = 0x6, Reserve7 = 0x7, Close = 0x8, Ping = 0x9, Pong = 0xA, ReserveB = 0xB, ReserveC = 0xC, ReserveD = 0xD, ReserveE = 0xE, ReserveF = 0xF, }; TWebSocketFrame(); TWebSocketFrame(const TWebSocketFrame &other); TWebSocketFrame &operator=(const TWebSocketFrame &other); bool finBit() const { return _firstByte & 0x80; } bool rsv1Bit() const { return _firstByte & 0x40; } bool rsv2Bit() const { return _firstByte & 0x20; } bool rsv3Bit() const { return _firstByte & 0x10; } bool isFinalFrame() const { return finBit(); } OpCode opCode() const { return (OpCode)(_firstByte & 0xF); } bool isControlFrame() const; quint32 maskKey() const { return _maskKey; } quint64 payloadLength() const { return _payloadLength; } const QByteArray &payload() const { return _payload; } bool isValid() const { return _valid; } void clear(); QByteArray toByteArray() const; private: enum ProcessingState { Empty = 0, HeaderParsed, MoreData, Completed, }; void setFinBit(bool fin); void setOpCode(OpCode opCode); void setFirstByte(quint8 byte); void setMaskKey(quint32 maskKey); void setPayloadLength(quint64 length); void setPayload(const QByteArray &payload); QByteArray &payload() { return _payload; } bool validate(); ProcessingState state() const { return _state; } void setState(ProcessingState state); quint8 _firstByte {0x80}; quint32 _maskKey {0}; quint64 _payloadLength {0}; QByteArray _payload; // unmasked data stored ProcessingState _state {Empty}; bool _valid {false}; friend class TAbstractWebSocket; friend class TWebSocket; friend class TEpollWebSocket; friend class TWebSocketController; };
889
1,921
<gh_stars>1000+ def get_min_removals(intervals, reserved_intervals=list(), removed=0): print(reserved_intervals) if not intervals: return removed curr_interval = intervals[0] if_removed = get_min_removals( intervals[1:], reserved_intervals, removed + 1) for ri in reserved_intervals: if curr_interval[0] in ri or curr_interval[1] in ri: return if_removed new_reserved_intervals = reserved_intervals + \ [range(curr_interval[0], curr_interval[1])] return min(if_removed, get_min_removals(intervals[1:], new_reserved_intervals, removed)) # Tests assert get_min_removals([(0, 1), (1, 2)]) == 0 assert get_min_removals([(7, 9), (2, 4), (5, 8)]) == 1 assert get_min_removals([(7, 9), (2, 4), (5, 8), (1, 3)]) == 2
348
679
<gh_stars>100-1000 /************************************************************** * * 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. * *************************************************************/ #ifndef __FRAMEWORK_LAYOUTMANAGER_HELPERS_HXX_ #define __FRAMEWORK_LAYOUTMANAGER_HELPERS_HXX_ // my own includes #include <macros/generic.hxx> #include <stdtypes.h> #include <properties.h> // interface includes #include <com/sun/star/awt/XWindowPeer.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/frame/XFrame.hpp> #include <com/sun/star/ui/XUIElement.hpp> #include <com/sun/star/awt/Rectangle.hpp> #include <com/sun/star/ui/DockingArea.hpp> #include <com/sun/star/awt/Point.hpp> // other includes #include <vcl/window.hxx> #include <vcl/toolbox.hxx> #define UIRESOURCE_PROTOCO_ASCII "private:" #define UIRESOURCE_RESOURCE_ASCII "resource" #define UIRESOURCE_URL_ASCII "private:resource" #define UIRESOURCE_URL rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( UIRESOURCE_URL_ASCII )) #define UIRESOURCETYPE_TOOLBAR "toolbar" #define UIRESOURCETYPE_STATUSBAR "statusbar" #define UIRESOURCETYPE_MENUBAR "menubar" namespace framework { bool hasEmptySize( const:: Size& aSize ); bool hasDefaultPosValue( const ::Point& aPos ); bool isDefaultPos( const ::com::sun::star::awt::Point& aPos ); bool isDefaultPos( const ::Point& aPos ); bool isToolboxHorizontalAligned( ToolBox* pToolBox ); bool isReverseOrderDockingArea( const sal_Int32 nDockArea ); bool isHorizontalDockingArea( const sal_Int32 nDockArea ); bool isHorizontalDockingArea( const ::com::sun::star::ui::DockingArea& nDockArea ); ::rtl::OUString retrieveToolbarNameFromHelpURL( Window* pWindow ); ToolBox* getToolboxPtr( Window* pWindow ); Window* getWindowFromXUIElement( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIElement >& xUIElement ); SystemWindow* getTopSystemWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& xWindow ); bool equalRectangles( const css::awt::Rectangle& rRect1, const css::awt::Rectangle& rRect2 ); void setZeroRectangle( ::Rectangle& rRect ); bool lcl_checkUIElement(const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIElement >& xUIElement,::com::sun::star::awt::Rectangle& _rPosSize, ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& _xWindow); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > createToolkitWindow( const css::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rFactory, const css::uno::Reference< ::com::sun::star::awt::XWindowPeer >& rParent, const char* pService ); WindowAlign ImplConvertAlignment( sal_Int16 aAlignment ); ::rtl::OUString getElementTypeFromResourceURL( const ::rtl::OUString& aResourceURL ); void parseResourceURL( const rtl::OUString& aResourceURL, rtl::OUString& aElementType, rtl::OUString& aElementName ); ::Rectangle putAWTToRectangle( const ::com::sun::star::awt::Rectangle& rRect ); ::com::sun::star::awt::Rectangle putRectangleValueToAWT( const ::Rectangle& rRect ); ::com::sun::star::awt::Rectangle convertRectangleToAWT( const ::Rectangle& rRect ); ::Rectangle convertAWTToRectangle( const ::com::sun::star::awt::Rectangle& rRect ); ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > impl_getModelFromFrame( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ); sal_Bool implts_isPreviewModel( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel ); sal_Bool implts_isFrameOrWindowTop( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame ); void impl_setDockingWindowVisibility( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& rSMGR, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& rDockingWindowName, bool bVisible ); void impl_addWindowListeners( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xThis, const ::com::sun::star::uno::Reference< css::ui::XUIElement >& xUIElement ); ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > implts_createToolkitWindow( const css::uno::Reference< ::com::sun::star::awt::XToolkit >& rToolkit, const css::uno::Reference< ::com::sun::star::awt::XWindowPeer >& rParent ); } #endif // __FRAMEWORK_LAYOUTMANAGER_HELPERS_HXX_
1,798
1,724
<filename>driver-core/src/main/com/mongodb/internal/async/function/RetryState.java /* * Copyright 2008-present MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mongodb.internal.async.function; import com.mongodb.annotations.NotThreadSafe; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.async.function.LoopState.AttachmentKey; import com.mongodb.lang.NonNull; import com.mongodb.lang.Nullable; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Supplier; import static com.mongodb.assertions.Assertions.assertFalse; import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.assertions.Assertions.assertTrue; /** * Represents both the state associated with a retryable activity and a handle that can be used to affect retrying, e.g., * to {@linkplain #breakAndThrowIfRetryAnd(Supplier) break} it. * {@linkplain #attachment(AttachmentKey) Attachments} may be used by the associated retryable activity either * to preserve a state between attempts. * * @see RetryingSyncSupplier * @see RetryingAsyncCallbackSupplier */ @NotThreadSafe public final class RetryState { public static final int RETRIES = 1; private static final int INFINITE_ATTEMPTS = Integer.MAX_VALUE; private final LoopState loopState; private final int attempts; @Nullable private Throwable exception; /** * @param retries A non-negative number of allowed retries. {@link Integer#MAX_VALUE} is a special value interpreted as being unlimited. * @see #attempts() */ public RetryState(final int retries) { assertTrue(retries >= 0); loopState = new LoopState(); attempts = retries == INFINITE_ATTEMPTS ? INFINITE_ATTEMPTS : retries + 1; } /** * Creates a {@link RetryState} that does not limit the number of retries. * @see #attempts() */ public RetryState() { this(INFINITE_ATTEMPTS); } /** * Advances this {@link RetryState} such that it represents the state of a new attempt. * If there is at least one more {@linkplain #attempts() attempt} left, it is consumed by this method. * Must not be called before the {@linkplain #isFirstAttempt() first attempt}, must be called before each subsequent attempt. * <p> * This method is intended to be used by code that generally does not handle {@link Error}s explicitly, * which is usually synchronous code. * * @param attemptException The exception produced by the most recent attempt. * It is passed to the {@code retryPredicate} and to the {@code exceptionTransformer}. * @param exceptionTransformer A function that chooses which exception to preserve as a prospective failed result of the associated * retryable activity and may also transform or mutate the exceptions. * The choice is between * <ul> * <li>the previously chosen exception or {@code null} if none has been chosen * (the first argument of the {@code exceptionTransformer})</li> * <li>and the exception from the most recent attempt (the second argument of the {@code exceptionTransformer}).</li> * </ul> * The {@code exceptionTransformer} may either choose from its arguments, or return a different exception, a.k.a. transform, * but it must return a {@code @}{@link NonNull} value. * The {@code exceptionTransformer} is called once before (in the happens-before order) the {@code retryPredicate}, * regardless of whether the {@code retryPredicate} is called. The result of the {@code exceptionTransformer} does not affect * what exception is passed to the {@code retryPredicate}. * @param retryPredicate {@code true} iff another attempt needs to be made. The {@code retryPredicate} is called not more than once * per attempt and only if all the following is true: * <ul> * <li>{@code exceptionTransformer} completed normally;</li> * <li>the most recent attempt is not the {@linkplain #isLastAttempt() last} one.</li> * </ul> * The {@code retryPredicate} accepts this {@link RetryState} and the exception from the most recent attempt, * and may mutate the exception. The {@linkplain RetryState} advances to represent the state of a new attempt * after (in the happens-before order) testing the {@code retryPredicate}, and only if the predicate completes normally. * @throws RuntimeException Iff any of the following is true: * <ul> * <li>the {@code exceptionTransformer} completed abruptly;</li> * <li>the most recent attempt is the {@linkplain #isLastAttempt() last} one;</li> * <li>the {@code retryPredicate} completed abruptly;</li> * <li>the {@code retryPredicate} is {@code false}.</li> * </ul> * The exception thrown represents the failed result of the associated retryable activity, * i.e., the caller must not do any more attempts. * @see #advanceOrThrow(Throwable, BiFunction, BiPredicate) */ void advanceOrThrow(final RuntimeException attemptException, final BiFunction<Throwable, Throwable, Throwable> exceptionTransformer, final BiPredicate<RetryState, Throwable> retryPredicate) throws RuntimeException { try { doAdvanceOrThrow(attemptException, exceptionTransformer, retryPredicate, true); } catch (RuntimeException | Error unchecked) { throw unchecked; } catch (Throwable checked) { throw new AssertionError(checked); } } /** * This method is intended to be used by code that generally handles all {@link Throwable} types explicitly, * which is usually asynchronous code. * * @see #advanceOrThrow(RuntimeException, BiFunction, BiPredicate) */ void advanceOrThrow(final Throwable attemptException, final BiFunction<Throwable, Throwable, Throwable> exceptionTransformer, final BiPredicate<RetryState, Throwable> retryPredicate) throws Throwable { doAdvanceOrThrow(attemptException, exceptionTransformer, retryPredicate, false); } /** * @param onlyRuntimeExceptions {@code true} iff the method must expect {@link #exception} and {@code attemptException} to be * {@link RuntimeException}s and must not explicitly handle other {@link Throwable} types, of which only {@link Error} is possible * as {@link RetryState} does not have any source of {@link Exception}s. */ private void doAdvanceOrThrow(final Throwable attemptException, final BiFunction<Throwable, Throwable, Throwable> exceptionTransformer, final BiPredicate<RetryState, Throwable> retryPredicate, final boolean onlyRuntimeExceptions) throws Throwable { assertTrue(attempt() < attempts); assertNotNull(attemptException); if (onlyRuntimeExceptions) { assertTrue(isRuntime(attemptException)); } assertTrue(!isFirstAttempt() || exception == null); Throwable newlyChosenException = transformException(exception, attemptException, onlyRuntimeExceptions, exceptionTransformer); if (isLastAttempt()) { exception = newlyChosenException; throw exception; } else { // note that we must not update the state, e.g, `exception`, `loopState`, before calling `retryPredicate` boolean retry = shouldRetry(this, attemptException, newlyChosenException, onlyRuntimeExceptions, retryPredicate); exception = newlyChosenException; if (retry) { assertTrue(loopState.advance()); } else { throw exception; } } } /** * @param onlyRuntimeExceptions See {@link #doAdvanceOrThrow(Throwable, BiFunction, BiPredicate, boolean)}. */ private static Throwable transformException(@Nullable final Throwable previouslyChosenException, final Throwable attemptException, final boolean onlyRuntimeExceptions, final BiFunction<Throwable, Throwable, Throwable> exceptionTransformer) { if (onlyRuntimeExceptions && previouslyChosenException != null) { assertTrue(isRuntime(previouslyChosenException)); } Throwable result; try { result = assertNotNull(exceptionTransformer.apply(previouslyChosenException, attemptException)); if (onlyRuntimeExceptions) { assertTrue(isRuntime(result)); } } catch (Throwable exceptionTransformerException) { if (onlyRuntimeExceptions && !isRuntime(exceptionTransformerException)) { throw exceptionTransformerException; } if (previouslyChosenException != null) { exceptionTransformerException.addSuppressed(previouslyChosenException); } exceptionTransformerException.addSuppressed(attemptException); throw exceptionTransformerException; } return result; } /** * @param readOnlyRetryState Must not be mutated by this method. * @param onlyRuntimeExceptions See {@link #doAdvanceOrThrow(Throwable, BiFunction, BiPredicate, boolean)}. */ private boolean shouldRetry(final RetryState readOnlyRetryState, final Throwable attemptException, final Throwable newlyChosenException, final boolean onlyRuntimeExceptions, final BiPredicate<RetryState, Throwable> retryPredicate) { try { return retryPredicate.test(readOnlyRetryState, attemptException); } catch (Throwable retryPredicateException) { if (onlyRuntimeExceptions && !isRuntime(retryPredicateException)) { throw retryPredicateException; } retryPredicateException.addSuppressed(newlyChosenException); throw retryPredicateException; } } private static boolean isRuntime(@Nullable final Throwable exception) { return exception instanceof RuntimeException; } /** * This method is similar to the semantics of the * <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.15">{@code break} statement</a>, with the difference * that breaking results in throwing an exception because the retry loop has more than one iteration only if the first iteration fails. * Does nothing and completes normally if called during the {@linkplain #isFirstAttempt() first attempt}. * This method is useful when the associated retryable activity detects that a retry attempt should not happen * despite having been started. Must not be called more than once per {@link RetryState}. * <p> * If the {@code predicate} completes abruptly, this method also completes abruptly with the same exception but does not break retrying; * if the {@code predicate} is {@code true}, then the method breaks retrying and completes abruptly by throwing the exception that is * currently deemed to be a prospective failed result of the associated retryable activity. The thrown exception must also be used * by the caller to complete the ongoing attempt. * <p> * If this method is called from * {@linkplain RetryingSyncSupplier#RetryingSyncSupplier(RetryState, BiFunction, BiPredicate, Supplier) * retry predicate / failed result transformer}, the behavior is unspecified. * * @param predicate {@code true} iff retrying needs to be broken. * The {@code predicate} is not called during the {@linkplain #isFirstAttempt() first attempt}. * @throws RuntimeException Iff any of the following is true: * <ul> * <li>the {@code predicate} completed abruptly;</li> * <li>this method broke retrying.</li> * </ul> * The exception thrown represents the failed result of the associated retryable activity. * @see #breakAndCompleteIfRetryAnd(Supplier, SingleResultCallback) */ public void breakAndThrowIfRetryAnd(final Supplier<Boolean> predicate) throws RuntimeException { assertFalse(loopState.isLastIteration()); if (!isFirstAttempt()) { assertNotNull(exception); assertTrue(exception instanceof RuntimeException); RuntimeException localException = (RuntimeException) exception; try { if (predicate.get()) { loopState.markAsLastIteration(); } } catch (RuntimeException predicateException) { predicateException.addSuppressed(localException); throw predicateException; } if (loopState.isLastIteration()) { throw localException; } } } /** * This method is intended to be used by callback-based code. It is similar to {@link #breakAndThrowIfRetryAnd(Supplier)}, * but instead of throwing an exception, it relays it to the {@code callback}. * <p> * If this method is called from * {@linkplain RetryingAsyncCallbackSupplier#RetryingAsyncCallbackSupplier(RetryState, BiFunction, BiPredicate, com.mongodb.internal.async.function.AsyncCallbackSupplier) * retry predicate / failed result transformer}, the behavior is unspecified. * * @return {@code true} iff the {@code callback} was completed, which happens in the same situations in which * {@link #breakAndThrowIfRetryAnd(Supplier)} throws an exception. If {@code true} is returned, the caller must complete * the ongoing attempt. * @see #breakAndThrowIfRetryAnd(Supplier) */ public boolean breakAndCompleteIfRetryAnd(final Supplier<Boolean> predicate, final SingleResultCallback<?> callback) { try { breakAndThrowIfRetryAnd(predicate); return false; } catch (Throwable t) { callback.onResult(null, t); return true; } } /** * This method is similar to * {@link RetryState#breakAndThrowIfRetryAnd(Supplier)} / {@link RetryState#breakAndCompleteIfRetryAnd(Supplier, SingleResultCallback)}. * The difference is that it allows the current attempt to continue, yet no more attempts will happen. Also, unlike the aforementioned * methods, this method has effect even if called during the {@linkplain #isFirstAttempt() first attempt}. */ public void markAsLastAttempt() { loopState.markAsLastIteration(); } /** * Returns {@code true} iff the current attempt is the first one, i.e., no retries have been made. * * @see #attempts() */ public boolean isFirstAttempt() { return loopState.isFirstIteration(); } /** * Returns {@code true} iff the current attempt is known to be the last one, i.e., it is known that no more retries will be made. * An attempt is known to be the last one either because the number of {@linkplain #attempts() attempts} is limited and the current * attempt is the last one, or because {@link #breakAndThrowIfRetryAnd(Supplier)} / * {@link #breakAndCompleteIfRetryAnd(Supplier, SingleResultCallback)} / {@link #markAsLastAttempt()} was called. * * @see #attempts() */ public boolean isLastAttempt() { return attempt() == attempts - 1 || loopState.isLastIteration(); } /** * A 0-based attempt number. * * @see #attempts() */ public int attempt() { return loopState.iteration(); } /** * Returns a positive maximum number of attempts: * <ul> * <li>0 if the number of retries is {@linkplain #RetryState() unlimited};</li> * <li>1 if no retries are allowed;</li> * <li>{@link #RetryState(int) retries} + 1 otherwise.</li> * </ul> * * @see #attempt() * @see #isFirstAttempt() * @see #isLastAttempt() */ public int attempts() { return attempts == INFINITE_ATTEMPTS ? 0 : attempts; } /** * Returns the exception that is currently deemed to be a prospective failed result of the associated retryable activity. * Note that this exception is not necessary the one from the most recent failed attempt. * Returns an {@linkplain Optional#isEmpty() empty} {@link Optional} iff called during the {@linkplain #isFirstAttempt() first attempt}. * <p> * In synchronous code the returned exception is of the type {@link RuntimeException}. */ public Optional<Throwable> exception() { assertTrue(exception == null || !isFirstAttempt()); return Optional.ofNullable(exception); } /** * @see LoopState#attach(AttachmentKey, Object, boolean) */ public <V> RetryState attach(final AttachmentKey<V> key, final V value, final boolean autoRemove) { loopState.attach(key, value, autoRemove); return this; } /** * @see LoopState#attachment(AttachmentKey) */ public <V> Optional<V> attachment(final AttachmentKey<V> key) { return loopState.attachment(key); } @Override public String toString() { return "RetryState{" + "loopState=" + loopState + ", attempts=" + (attempts == INFINITE_ATTEMPTS ? "infinite" : attempts) + ", exception=" + exception + '}'; } }
6,268
1,338
<filename>src/libs/posix_error_mapper/pthread_thread.cpp /* * Copyright 2009-2011, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #include <pthread.h> #include <signal.h> #include "posix_error_mapper.h" WRAPPER_FUNCTION(int, pthread_create, (pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg), return B_TO_POSITIVE_ERROR(sReal_pthread_create(thread, attr, start_routine, arg)); ) WRAPPER_FUNCTION(int, pthread_detach, (pthread_t thread), return B_TO_POSITIVE_ERROR(sReal_pthread_detach(thread)); ) WRAPPER_FUNCTION(int, pthread_join, (pthread_t thread, void **_value), return B_TO_POSITIVE_ERROR(sReal_pthread_join(thread, _value)); ) WRAPPER_FUNCTION(int, pthread_kill, (pthread_t thread, int sig), return B_TO_POSITIVE_ERROR(sReal_pthread_kill(thread, sig)); ) WRAPPER_FUNCTION(int, pthread_setconcurrency, (int newLevel), return B_TO_POSITIVE_ERROR(sReal_pthread_setconcurrency(newLevel)); ) WRAPPER_FUNCTION(int, pthread_cancel, (pthread_t thread), return B_TO_POSITIVE_ERROR(sReal_pthread_cancel(thread)); ) WRAPPER_FUNCTION(int, pthread_setcancelstate, (int state, int *_oldState), return B_TO_POSITIVE_ERROR(sReal_pthread_setcancelstate(state, _oldState)); ) WRAPPER_FUNCTION(int, pthread_setcanceltype, (int type, int *_oldType), return B_TO_POSITIVE_ERROR(sReal_pthread_setcanceltype(type, _oldType)); ) WRAPPER_FUNCTION(int, pthread_getschedparam, (pthread_t thread, int *policy, struct sched_param *param), return B_TO_POSITIVE_ERROR(sReal_pthread_getschedparam(thread, policy, param)); ) WRAPPER_FUNCTION(int, pthread_setschedparam, (pthread_t thread, int policy, const struct sched_param *param), return B_TO_POSITIVE_ERROR(sReal_pthread_setschedparam(thread, policy, param)); )
722
1,443
{ "copyright": "<NAME>, http://aarontrostle.com", "url": "http://aarontrostle.com", "email": "<EMAIL>", "format": "txt", "theme": "plaintext" }
66
14,668
<gh_stars>1000+ // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/tabs/tab_group_underline.h" #include <memory> #include <utility> #include "chrome/browser/ui/layout_constants.h" #include "chrome/browser/ui/tabs/tab_style.h" #include "chrome/browser/ui/views/tabs/tab.h" #include "chrome/browser/ui/views/tabs/tab_group_header.h" #include "chrome/browser/ui/views/tabs/tab_group_views.h" #include "components/tab_groups/tab_group_id.h" #include "components/tab_groups/tab_group_visual_data.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/gfx/canvas.h" #include "ui/views/background.h" #include "ui/views/view.h" constexpr int TabGroupUnderline::kStrokeThickness; TabGroupUnderline::TabGroupUnderline(TabGroupViews* tab_group_views, const tab_groups::TabGroupId& group) : tab_group_views_(tab_group_views), group_(group) {} void TabGroupUnderline::OnPaint(gfx::Canvas* canvas) { SkPath path = GetPath(); cc::PaintFlags flags; flags.setAntiAlias(true); flags.setColor(tab_group_views_->GetGroupColor()); flags.setStyle(cc::PaintFlags::kFill_Style); canvas->DrawPath(path, flags); } void TabGroupUnderline::UpdateBounds(const gfx::Rect& group_bounds) { const int start_x = GetStart(group_bounds); const int end_x = GetEnd(group_bounds); // The width may be zero if the group underline and header are initialized at // the same time, as with tab restore. In this case, don't update the bounds // and defer to the next paint cycle. if (end_x <= start_x) return; const int y = group_bounds.height() - GetLayoutConstant(TABSTRIP_TOOLBAR_OVERLAP); SetBounds(start_x, y - kStrokeThickness, end_x - start_x, kStrokeThickness); } // static int TabGroupUnderline::GetStrokeInset() { return TabStyle::GetTabOverlap() + kStrokeThickness; } int TabGroupUnderline::GetStart(const gfx::Rect& group_bounds) const { return group_bounds.x() + GetStrokeInset(); } int TabGroupUnderline::GetEnd(const gfx::Rect& group_bounds) const { const Tab* last_grouped_tab = tab_group_views_->GetLastTabInGroup(); if (!last_grouped_tab) return group_bounds.right() - GetStrokeInset(); return group_bounds.right() + (last_grouped_tab->IsActive() ? kStrokeThickness : -GetStrokeInset()); } SkPath TabGroupUnderline::GetPath() const { SkPath path; path.moveTo(0, kStrokeThickness); path.arcTo(kStrokeThickness, kStrokeThickness, 0, SkPath::kSmall_ArcSize, SkPathDirection::kCW, kStrokeThickness, 0); path.lineTo(width() - kStrokeThickness, 0); path.arcTo(kStrokeThickness, kStrokeThickness, 0, SkPath::kSmall_ArcSize, SkPathDirection::kCW, width(), kStrokeThickness); path.close(); return path; } BEGIN_METADATA(TabGroupUnderline, views::View) END_METADATA
1,156
394
<filename>test/ClangModules/Inputs/custom-modules/Protocols.h<gh_stars>100-1000 @protocol FooProto @property int bar; @end @protocol AnotherProto @end Class <FooProto> _Nonnull processFooType(Class <FooProto> _Nonnull); Class <FooProto, AnotherProto> _Nonnull processComboType(Class <FooProto, AnotherProto> _Nonnull); Class <AnotherProto, FooProto> _Nonnull processComboType2(Class <AnotherProto, FooProto> _Nonnull);
155
2,206
<gh_stars>1000+ /* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ // // @author <NAME> (<EMAIL>) // #include <execution/Threads.h> #include <ops/declarable/helpers/gammaMathFunc.h> namespace sd { namespace ops { namespace helpers { ////////////////////////////////////////////////////////////////////////// // calculate digamma function for array elements template <typename T> static void diGamma_(const NDArray& x, NDArray& z) { auto func = PRAGMA_THREADS_FOR { for (auto i = start; i < stop; i++) z.p(i, diGammaScalar<T>(x.e<T>(i))); }; samediff::Threads::parallel_for(func, 0, x.lengthOf()); } void diGamma(sd::LaunchContext* context, const NDArray& x, NDArray& z) { BUILD_SINGLE_SELECTOR(x.dataType(), diGamma_, (x, z), SD_FLOAT_TYPES); } BUILD_SINGLE_TEMPLATE(template void diGamma_, (const NDArray& x, NDArray& z), SD_FLOAT_TYPES); } // namespace helpers } // namespace ops } // namespace sd
536
5,607
/* * Copyright 2017-2020 original 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 * * https://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 io.micronaut.inject.visitor; /** * Allows supplying configuration to the {@link VisitorContext}. * * @author graemerocher * @since 2.3.0 */ public interface VisitorConfiguration { VisitorConfiguration DEFAULT = new VisitorConfiguration() { }; /** * This configures whether to include type level annotations on generic arguments when materializing the AST nodes via * the {@link io.micronaut.inject.ast.Element} API. * * <p>If {@code true} is returned then methods like {@link io.micronaut.inject.ast.ClassElement#getTypeArguments()} will include annotations declared on the classes themselves within the annotation metadata for each resulting {@link io.micronaut.inject.ast.ClassElement} within the generic arguments.</p> * * <p>This can be undesirable in the use case where you need to differentiate annotations on the type arguments themselves vs annotations declared on the type, in which case you should return false.</p> * * @return True if annotations should be included * @see io.micronaut.inject.ast.ElementFactory */ default boolean includeTypeLevelAnnotationsInGenericArguments() { return true; } }
507
348
<gh_stars>100-1000 {"nom":"Marcey-les-Grèves","circ":"2ème circonscription","dpt":"Manche","inscrits":984,"abs":491,"votants":493,"blancs":22,"nuls":6,"exp":465,"res":[{"nuance":"REM","nom":"<NAME>","voix":269},{"nuance":"LR","nom":"<NAME>","voix":196}]}
104
892
{ "schema_version": "1.2.0", "id": "GHSA-w3pj-mp82-r9qh", "modified": "2022-02-09T00:00:46Z", "published": "2022-02-09T00:00:46Z", "aliases": [ "CVE-2022-24121" ], "details": "SQL Injection vulnerability discovered in Unified Office Total Connect Now that would allow an attacker to extract sensitive information through a cookie parameter.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2022-24121" }, { "type": "WEB", "url": "https://unifiedoffice.com/total-connect-now/" }, { "type": "WEB", "url": "https://www.coresecurity.com/core-labs/advisories/unified-office-total-connect-sql-injection" } ], "database_specific": { "cwe_ids": [ "CWE-89" ], "severity": "HIGH", "github_reviewed": false } }
394
541
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ /** * <p> * Embargo allows the deposit of Items whose content should not be made visible * until later. Some journals, for example, permit self-publication after a * period of exclusive access through the journal. * </p> * <p> * Embargo policy is applied through a pair of pluggable classes: an * {@link org.dspace.embargo.EmbargoSetter} and an * {@link org.dspace.embargo.EmbargoLifter}. The {@link org.dspace.embargo.EmbargoServiceImpl} * must be configured to specify these classes, as well as names of two metadata * fields for use by the embargo facility: an embargo lift date (when the * content will be released) and the embargo terms (which the EmbargoSetter will * use to calculate the lift date). You must select or create appropriate * metadata fields for this purpose. * </p> * <p> * See {@link org.dspace.embargo.DefaultEmbargoSetter}, * {@link org.dspace.embargo.DayTableEmbargoSetter}, and * {@link org.dspace.embargo.DefaultEmbargoLifter} for simple policy classes * which ship with DSpace. You can supply your own classes to implement more * elaborate policies. * </p> * <p> * Embargo is applied when an Item is installed in a Collection. An Item subject * to embargo passes through several stages: * </p> * <ol> * <li>During submission, the metadata field established for embargo terms must * be set to a value which is interpretable by the selected setter. Typically * this will be a date or an interval. There is no specific mechanism for * requesting embargo; you must customize your submission forms as needed, * create a template Item which applies a standard value, or in some other way * cause the specified metadata field to be set. * </li> * <li>When the Item is accepted into a Collection, the setter will apply the * embargo, making the content inaccessible. * </li> * <li>The site should run the embargo lifter tool ({@code dspace embargo-lifter}) * from time to time, for example using an automatic daily job. This discovers * Items which have passed their embargo lift dates and makes their content * accessible. * </li> * </ol> */ package org.dspace.embargo;
647
1,540
package test.order.github288; import org.testng.annotations.Test; public class Actual2Sample extends BaseSample { @Test public void test2() {} }
47
1,682
<gh_stars>1000+ /* Copyright (c) 2015 LinkedIn Corp. 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.linkedin.r2.transport.http.client.stream.http; import com.linkedin.r2.message.rest.RestRequest; import com.linkedin.r2.netty.common.NettyRequestAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageEncoder; import io.netty.handler.codec.http.HttpRequest; import java.util.List; /** * This encoder encodes RestRequest to Netty's HttpRequest. * * @author <NAME> */ class RAPStreamFullRequestEncoder extends MessageToMessageEncoder<RestRequest> { @Override protected void encode(ChannelHandlerContext ctx, RestRequest msg, List<Object> out) throws Exception { HttpRequest nettyRequest = NettyRequestAdapter.toNettyRequest(msg); out.add(nettyRequest); } }
409
522
<reponame>konny0311/algorithms-nutshell-2ed<filename>Code/Sorting/PointerBased/stripped_baseQsort.c /** * @file stripped_baseQsort.c Quicksort implementation * @brief * Complete Quicksort implementation optimized to switch to Insertion * Sort when problem sizes are less than or equal to minSize in length. * For pure QuickSort, set minSize to 0. * * * @author <NAME> * @date 6/15/08 */ #include <stdio.h> #include <sys/types.h> #include "report.h" /** consider how much is saved by avoiding parameters. */ static void **ar; static int(*cmp)(const void *,const void *); /** force minsize to zero for even comparison with parallel version. */ int minSize= 0; /** Code to select a pivot index around which to partition ar[left, right]. */ extern int selectPivotIndex (void **vals, int left, int right); /** * In linear time, group the sub-array ar[left, right) around a pivot * element pivot=ar[right] by storing pivot into its proper location, * store, within the sub-array (whose location is returned by this * function) and ensuring that all ar[left,store) <= pivot and all * ar[store+1,right) > pivot. * * @param left lower bound index position (inclusive) * @param right upper bound index position (exclusive) * @return location of the pivot index properly positioned. */ int partition (int left, int right) { void *tmp, *pivot; int idx, store; pivot = ar[right]; /* all values <= pivot are moved to front of array and pivot inserted * just after them. */ store = left; for (idx = left; idx < right; idx++) { if (cmp(ar[idx], pivot) <= 0) { #ifdef COUNT /* TIMING */ ADD_SWAP; /* TIMING */ #endif /*COUNT*/ /* TIMING */ tmp = ar[idx]; ar[idx] = ar[store]; ar[store] = tmp; store++; } } #ifdef COUNT /* TIMING */ ADD_SWAP; /* TIMING */ #endif /*COUNT*/ /* TIMING */ tmp = ar[right]; ar[right] = ar[store]; ar[store] = tmp; return store; } /** proper insertion sort, optimized */ void insertion (int low, int high) { int loc; for (loc = low+1; loc <= high; loc++) { int i = loc-1; void *value = ar[loc]; while (i >= 0 && cmp(ar[i], value)> 0) { #ifdef COUNT /* TIMING */ ADD_SWAP; /* TIMING */ #endif /*COUNT*/ /* TIMING */ ar[i+1] = ar[i]; i--; } #ifdef COUNT /* TIMING */ ADD_SWAP; /* TIMING */ #endif /*COUNT*/ /* TIMING */ ar[i+1] = value; } } /** Implement SelectionSort if one wants to see timing difference if this is used instead of Insertion Sort. */ void selectionSort (int low, int high) { int t, i; if (high <= low) { return; } for (t = low; t < high; t++) { for (i = t+1; i <= high; i++) { void *c; if (cmp(ar[i], ar[t]) <= 0) { #ifdef COUNT /* TIMING */ ADD_SWAP; /* TIMING */ #endif /*COUNT*/ /* TIMING */ c = ar[t]; ar[t] = ar[i]; ar[i] = c; } } } } /** * Sort array ar[left,right] using Quicksort method. * The comparison function, cmp, is needed to properly compare elements. */ void do_qsort (int left, int right) { int pivotIndex; if (right <= left) { return; } /* partition */ pivotIndex = partition (left, right); if (pivotIndex-1-left <= minSize) { insertion (left, pivotIndex-1); } else { do_qsort (left, pivotIndex-1); } if (right-pivotIndex-1 <= minSize) { insertion (pivotIndex+1, right); } else { do_qsort (pivotIndex+1, right); } } /** Sort by using Quicksort. */ void sortPointers (void **vals, int total_elems, int(*c)(const void *,const void *)) { ar = vals; cmp = c; do_qsort (0, total_elems-1); } /* debugging method. */ void output (int n) { int i; for (i = 0; i < n; i++) { printf ("%d. %s\n", i, (char*)ar[i]); } }
1,481
1,948
<filename>reactor-netty-core/src/test/java/reactor/netty/transport/logging/ReactorNettyLoggingHandlerTest.java /* * Copyright (c) 2020-2021 VMware, Inc. or its affiliates, 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 * * https://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 reactor.netty.transport.logging; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.nio.charset.Charset; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.Appender; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufHolder; import io.netty.buffer.DefaultByteBufHolder; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; class ReactorNettyLoggingHandlerTest { private static final Logger ROOT = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); private LoggingHandler defaultCharsetReactorNettyLoggingHandler; private Appender<ILoggingEvent> mockedAppender; private ArgumentCaptor<LoggingEvent> loggingEventArgumentCaptor; @BeforeEach @SuppressWarnings("unchecked") void setUp() { mockedAppender = (Appender<ILoggingEvent>) Mockito.mock(Appender.class); defaultCharsetReactorNettyLoggingHandler = new ReactorNettyLoggingHandler( ReactorNettyLoggingHandlerTest.class.getName(), LogLevel.DEBUG, Charset.defaultCharset()); loggingEventArgumentCaptor = ArgumentCaptor.forClass(LoggingEvent.class); Mockito.when(mockedAppender.getName()).thenReturn("MOCK"); ROOT.addAppender(mockedAppender); } @AfterEach void tearDown() { ROOT.detachAppender(mockedAppender); } @Test void shouldLogByteBuf() { final ByteBuf byteBuf = Unpooled.copiedBuffer("TEST", Charset.defaultCharset()); sendMessage(byteBuf, "[embedded, L:embedded - R:embedded] READ: 4B TEST"); } @Test void shouldLogByteBufHolder() { final ByteBufHolder byteBufHolder = new DefaultByteBufHolder(Unpooled.copiedBuffer("TEST", Charset.defaultCharset())); sendMessage(byteBufHolder, "[embedded, L:embedded - R:embedded] READ: 4B TEST"); } @Test void shouldLogObject() { sendMessage("TEST", "[embedded, L:embedded - R:embedded] READ: TEST"); } private void sendMessage(Object input, String expectedResult) { final EmbeddedChannel channel = new EmbeddedChannel(defaultCharsetReactorNettyLoggingHandler); channel.writeInbound(input); Mockito.verify(mockedAppender, Mockito.times(4)).doAppend(loggingEventArgumentCaptor.capture()); final LoggingEvent relevantLog = loggingEventArgumentCaptor.getAllValues().get(2); assertThat(relevantLog.getMessage()).isEqualTo(expectedResult); } @Test void shouldThrowUnsupportedOperationExceptionWhenByteBufFormatIsCalled() { assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> defaultCharsetReactorNettyLoggingHandler.byteBufFormat()); } }
1,278
326
#!/usr/bin/python ################################################################################ # # # W E L C O M E A D V E N T U R E R # # # # This file shall be of great help to you on your jouney to become the leading # # provider of server appliances in database applications. It will assist you # # on this task of providing a fully verified and thourghouly tested memcached # # server application bringing great honour to you and your kin of which is # # spoken even amongst the highest ranks that is our management. # # # # To get you started, you will find this file divided into several sections # # faciliating your learning thereof and thus empowering you with confidence to # # start your battle. # # # # The first section shows you how to define a key/value pair along with its # # parameters. This is the foundation of your work with memcached. # # # # Section two provides functions to generate binary requests and corresponding # # responses for the key/value pairs you learned about in the first section. # # They return an ASCII-encoded hexstream of the request or response. This is # # the real stuff! You can send this either over the wire to a real server or # # feed it to your simulation. # # # # Section three provides the same for the ASCII protocol. # # # # Section four allows you to convert ASCII protcol requests into mixed # # protocol requests completing the memcached protocol familiy. # # # # Section five provides all the means for you to generate RTL simulation input # # files from the request streams generated by the above protocol-specific # # functions. Given a list of request streams, it will combine them together # # such that they can be used with the kvs_tbDriver.vhdl used in the system to # # date. You will only want to use the last 3 functions in the section and # # neglect the previous helper functions. # # # # This is all you need to know my scholar to generate magnificent testbenches # # providing code stability boosting your stand as engineer and driving the # # markets with astonishing products. It was a pleasure teach you. # # # # M A Y Y O U R E T U R N I N G L O R Y # # # # # # Oh, you are still here? Well, then you must have noticed that there is a # # sixth section in this file. Well observed my friend. You are truely eager to # # learn! Know then that this truly is the secret of rapid test crafting. It is # # the wise man's approach, or, as I call it: the lazy man's toolbox. You just # # want to specify a series of request and don't care about protocol specifics? # # This is for you! Just give the operations and the key/value pair and it will # # automatically generate requests for all all possible combinations of # # protocols, rates and outputs, writes them all to files together with a # # summary. Need a particular setup? No worry, the file is there. All done for # # you. There is nothing anymore that stands in your way now. This is really # # all I can teach you. Off you go now! # # # ################################################################################ import sys ## kv_pair data structure ###################################################### # Example kv_pair: (key, value, flags, expiration) ex_kv_pair = { "key" : "ExampleKey", "value" : "ExampleValue", "flags" : "01234567", # 32bit, hex-encoded "expiration" : 10 } def kv_pair(key, value, flags, expiration): if (type(key) != str) | (type(value) != str) | (type(expiration) != int) | (type(flags) != str): raise Exception("Error: Wrong types for kv_pair") if len(flags) != 8: raise Exception("Error: Wrong flags length: %d. Should be 8." % len(flags)) return { "key" : key, "value" : value, "flags" : flags, "expiration" : expiration } ## binary protocol packet generators ########################################### def binaryResponseTemplate(opcode, opaque, status="00"): magic = "81" key_length_bin = "0000" extras_length_bin = "00" data_type = "00" status = "00" + status body_length = "00000000" cas = "0000000000000000" response = magic + opcode + key_length_bin + \ extras_length_bin + data_type + status + \ body_length + \ opaque + \ cas return response def binaryGetRequest(kv_pair, opaque="01234567"): if len(opaque) != 8: raise Exception("Error: Wrong opaque length: %d. Should be 8." % len(opaque)) magic = "80" opcode = "00" key = kv_pair["key"] key_bin = key.encode('hex') key_length = len(key) key_length_bin = "%04x" % key_length extras_length = "00" data_type = "00" vbucket_id = "0000" body_length = "%08x" % key_length cas = "0000000000000000" request = magic + opcode + key_length_bin + \ extras_length + data_type + vbucket_id + \ body_length + \ opaque + \ cas + \ key_bin return request def binaryFailedGetResponse(opaque="01234567"): magic = "81" opcode = "00" key_length_bin = "0000" extras_length_bin = "00" data_type = "00" status = "0001" body_length = "00000008" cas = "0000000000000000" message = "ERROR 01".encode('hex') response = magic + opcode + key_length_bin + \ extras_length_bin + data_type + status + \ body_length + \ opaque + \ cas + \ message return response def binaryGetResponse(kv_pair, opaque="01234567"): if len(opaque) != 8: raise Exception("Error: Wrong opaque length: %d. Should be 8." % len(opaque)) magic = "81" opcode = "00" key_length_bin = "0000" extras = kv_pair["flags"] extras_length = len(extras) / 2 extras_length_bin = "%02x" % extras_length data_type = "00" status = "0000" value = kv_pair["value"] value_bin = value.encode('hex') value_length = len(value) body_length = "%08x" % (extras_length + value_length) cas = "0000000000000000" response = magic + opcode + key_length_bin + \ extras_length_bin + data_type + status + \ body_length + \ opaque + \ cas + \ extras + \ value_bin return response def binarySetRequest(kv_pair, opaque="01234567"): if len(opaque) != 8: raise Exception("Error: Wrong opaque length: %d. Should be 8." % len(opaque)) magic = "80" opcode = "01" key = kv_pair["key"] key_bin = key.encode('hex') key_length = len(key) key_length_bin = "%04x" % key_length extras_length = "08" data_type = "00" vbucket_id = "0000" value = kv_pair["value"] value_bin = value.encode('hex') value_length = len(value) body_length = "%08x" % (key_length + value_length + 8) cas = "0000000000000000" flags = kv_pair["flags"] expiration = kv_pair["expiration"] expiration_bin = "%08x" % expiration extras = flags + expiration_bin request = magic + opcode + key_length_bin + \ extras_length + data_type + vbucket_id + \ body_length + \ opaque + \ cas + \ extras + \ key_bin + \ value_bin return request def binarySetResponse(kv_pair, opaque="01234567"): if len(opaque) != 8: raise Exception("Error: Wrong opaque length: %d. Should be 8." % len(opaque)) return binaryResponseTemplate("01", opaque) def binaryFailedSetResponse(opaque="01234567"): magic = "81" opcode = "01" key_length_bin = "0000" extras_length_bin = "00" data_type = "00" status = "0001" body_length = "00000008" cas = "0000000000000000" message = "ERROR 01".encode('hex') response = magic + opcode + key_length_bin + \ extras_length_bin + data_type + status + \ body_length + \ opaque + \ cas + \ message return response def binaryDeleteRequest(kv_pair, opaque="01234567"): if len(opaque) != 8: raise Exception("Error: Wrong opaque length: %d. Should be 8." % len(opaque)) magic = "80" opcode = "04" key = kv_pair["key"] key_bin = key.encode('hex') key_length = len(key) key_length_bin = "%04x" % key_length extras_length = "00" data_type = "00" vbucket_id = "0000" body_length = "%08x" % key_length cas = "0000000000000000" request = magic + opcode + key_length_bin + \ extras_length + data_type + vbucket_id + \ body_length + \ opaque + \ cas + \ key_bin return request def binaryFailedDeleteResponse(kv_pair, opaque="01234567"): if len(opaque) != 8: raise Exception("Error: Wrong opaque length: %d. Should be 8." % len(opaque)) magic = "81" opcode = "04" key_length_bin = "0000" extras_length_bin = "00" data_type = "00" status = "0001" body_length = "00000008" cas = "0000000000000000" message = "ERROR 01".encode('hex') response = magic + opcode + key_length_bin + \ extras_length_bin + data_type + status + \ body_length + \ opaque + \ cas + \ message return response def binaryDeleteResponse(kv_pair, opaque="01234567"): if len(opaque) != 8: raise Exception("Error: Wrong opaque length: %d. Should be 8." % len(opaque)) return binaryResponseTemplate("04", opaque) def binaryFlushRequest(expiration=0, opaque="01234567"): if len(opaque) != 8: raise Exception("Error: Wrong opaque length: %d. Should be 8." % len(opaque)) if(expiration!=0): extras_length = "04" expiration_bin = "%08x" % expiration body_length = "00000004" magic = "80" opcode = "08" key_length_bin = "0000" extras_length = "00" data_type = "00" vbucket_id = "0000" body_length = "00000000" cas = "0000000000000000" expiration_bin = "" if(expiration!=0): extras_length = "04" body_length = "00000004" expiration_bin = "%08x" % expiration request = magic + opcode + key_length_bin + \ extras_length + data_type + vbucket_id + \ body_length + \ opaque + \ cas + \ expiration_bin return request def binaryFlushResponse(opaque="01234567"): if len(opaque) != 8: raise Exception("Error: Wrong opaque length: %d. Should be 8." % len(opaque)) return binaryResponseTemplate("08", opaque) ## text protocol packet generators ############################################# def textSetRequest(kv_pair): txt_req = "set %s %d %d %d\r\n%s\r\n" % ( kv_pair['key'], int(kv_pair['flags'], 16), kv_pair['expiration'], len(kv_pair['value']), kv_pair['value']) return txt_req.encode('hex') def textSetResponse(kv_pair): return "STORED\r\n".encode('hex') def textGetRequest(kv_pair): txt_req = "get %s\r\n" % kv_pair['key'] return txt_req.encode('hex') def textGetResponse(kv_pair): txt_res = "VALUE %s %d %d\r\n%s\r\nEND\r\n" % ( kv_pair['key'], int(kv_pair['flags'], 16), len(kv_pair['value']), kv_pair['value']) return txt_res.encode('hex') def textFailedGetResponse(): return "END\r\n".encode('hex') def textDeleteRequest(kv_pair): txt_req = "delete %s\r\n" % kv_pair['key'] return txt_req.encode('hex') def textDeleteResponse(kv_pair): return "DELETED\r\n".encode('hex') def textFailedDeleteResponse(kv_pair): return "NOT_FOUND\r\n".encode('hex') def textFlushRequest(): return "flush_all\r\n".encode('hex') def textFlushResponse(): return "OK\r\n".encode('hex') ## mixed protocol converter (from text) ######################################## def goMixed(txt_rq, rq_id=0): frame = "%04x000000010000" % rq_id return (frame + txt_rq) ## simulation marshalling ###################################################### network_sop = "D001ADB002020203719A0E0002054" # why '4' and not '0' {EOP, MOD}? network_any = "D001ADB002020203719A0E0002044" network_eop = "D001ADB002020203719A0E000204C" network_sep = "D001ADB002020203719A0E000205C" network_out_x = "D001ADB002020203719A0E00020" network_out_sop = network_out_x + "50" network_out_any = network_out_x + "40" network_out_x_hls = "D0000000000000000000000000000" network_out_sop_hls = "D0001ADB002020203719A0E000210" # network_out_any_hls = network_out_x_hls + "00" network_hls = "001ADB002020203719A0E000204" # Used for HLS packets. Only the network data are included. SOP & EOP signals are provided separately. network_hls_any_short = "000000000000000000000000000" network_hls_any = "D00000000000000000000000000000" def split_string_into_len(str, size=8): return [ str[i:i+size] for i in range(0, len(str), size) ] def hexstream_reverse_bytes(hexstream): bytes = split_string_into_len(hexstream, 2) reversed_bytes = bytes[::-1] return "".join(reversed_bytes) # Empty: Control signals in the end set for 'empty' in simulation. # Use before W statement. def simulationInput(hexstream, empty=True): lastDict = {0 : "FF", 1 : "01", 2 : "03", 3 : "07", 4 : "0F", 5 : "1F", 6 : "3F", 7 : "7F"} hexstream = hexstream.upper() residue = (len(hexstream) % 16) / 2 if (residue != 8): keepSignal = lastDict[residue] else: keepSignal = "FF" while len(hexstream) % 16 != 0: hexstream = hexstream + "00" words = split_string_into_len(hexstream, 16) words = map(hexstream_reverse_bytes, words) if(len(words)==1): l2 = "D" + words[0] + " " + keepSignal + ' 1' + "\n" input = l2 elif(len(words)==2): l1 = "D" + words[0] + " " + "FF" + ' 0' + "\n" l2 = "D" + words[1] + " " + "FF" + ' 1' + "\n" input = l1 + l2 else: words[0] = "D" + words[0] + " " + "FF" + ' 0' + "\n" words[1:-2] = map(lambda s: "D" + s + " FF 0" + "\n", words[1:-2]) words[-2] = "D" + words[-2] + " " + 'FF 0' + "\n" words[-1] = "D" + words[-1] + " " + keepSignal + ' 1' + "\n" input = "".join(words) return input def simulationOutput(hexstream): lastDict = {0 : "FF", 1 : "01", 2 : "03", 3 : "07", 4 : "0F", 5 : "1F", 6 : "3F", 7 : "7F"} if hexstream=="": return "" hexstream = hexstream.upper() residue = (len(hexstream) % 16) / 2 if (residue != 8): keepSignal = lastDict[residue] else: keepSignal = "FF" while len(hexstream) % 16 != 0: hexstream = hexstream + "00" words = split_string_into_len(hexstream, 16) words = map(hexstream_reverse_bytes, words) if(len(words)==1): l2 = "D" + words[0] + " " + keepSignal + ' 1' + " 2\n" input = l2 elif(len(words)==2): l1 = "D" + words[0] + " FF 0" + "\n" l2 = "D" + words[1] + " " + keepSignal + ' 1' + " 2\n" input = l1 + l2 else: words[0] = "D" + words[0] + " FF 0" + " 2\n" words[1:-2] = map(lambda s: "D" + s + " FF 0" + " 2\n", words[1:-2]) words[-2] = "D" + words[-2] + " FF 0" + " 2\n" words[-1] = "D" + words[-1] + " " + keepSignal + ' 1' + " 2\n" input = "".join(words) return input # expects list of hexstreams def requests12Gbps(requests): requests = requests[:] # copy of list requests[0:-1] = map(lambda r: simulationInput(r, False), requests[0:-1]) requests[-1] = simulationInput(requests[-1], True) return "".join(requests) # expects list of hexstreams def requests1Gbps(requests): input = map(lambda r: simulationInput(r, True), requests) pkg_count = map(lambda r: len(r) / 16, requests) pkg_wait_count = map(lambda c: 9*c, pkg_count) pkg_wait = map(lambda wc: "W%d\n" % wc, pkg_wait_count) # wait statement for each of the rqs. input_pairs = zip(pkg_wait, input) input_pairs = map(lambda p: "".join(p), input_pairs) # wait and request combined for each rq return "".join(input_pairs) # 1 string w/ all rqs # expects list of hexstreams def responses(res): res = map(simulationOutput, res) return "".join(res) ###################### Functions which generate the data for the HLS data ########################### def simulationInput_hls(hexstream, empty=True): #requestLength = len(hexstream) hexstream = hexstream.upper() while len(hexstream) % 16 != 0: hexstream = hexstream + "00" words = split_string_into_len(hexstream, 16) words = map(hexstream_reverse_bytes, words) if(len(words)==1): l2 = network_hls + " " + words[0] + " " + '1' + " " + '1' + " " + '0' + " " + '1' + "\n" input = l2 elif(len(words)==2): l1 = network_hls + " " + words[0] + " " + '1' + " " + '0' + " " + '0' + " " + '1' + "\n" l2 = network_hls + " " + words[1] + " " + '0' + " " + '1' + " " + '0' + " " + '1' + "\n" input = l1 + l2 else: words[0] = network_hls + " " + words[0] + " " + '1' + " " + '0' + " " + '0'+ " " + '1' + "\n" words[1:-2] = map(lambda s: network_hls + " " + s + " " + '0' + " " + '0' + " " + '0'+ " " + '1' + "\n", words[1:-2]) words[-2] = network_hls + " " + words[-2] + " " + '0' + " " + '0' + " " + '0' + " " + '1' + "\n" words[-1] = network_hls + " " + words[-1] + " " + '0' + " " + '1' + " " + '0' + " " + '1' + "\n" input = "".join(words) return input def simulationOutput_hls(hexstream): if hexstream=="": return "" requestLength = len(hexstream) / 2 #requestLength = requestLength << 1 rlString = hex(requestLength) rlString = rlString[2:] if (len(rlString) < 5): for k in range (0, 3-len(rlString)): rlString = "0" + rlString #if (len(rlString) == 4): # rlString = "0" + rlString[2:] #else: # rlString = rlString[2:] hexstream = hexstream.upper() #print(rlString.upper()) modulo = (len(hexstream) % 16) / 2 mod_eop = "%x" % (modulo + 8) # 8 = EOP mod_eop = mod_eop.upper() while len(hexstream) % 16 != 0: hexstream = hexstream + "**" words = split_string_into_len(hexstream, 16) words = map(hexstream_reverse_bytes, words) if(len(words)==1): words[0] = rlString.upper() + network_hls[3:] + " " + words[0] + " " + '1' + " " + '1' + " " + str(modulo) + " " + '1' + "\n" #words[0] = network_hls[0:2] + rlString.upper() + network_hls[3:] + " " + words[0] + " " + '1' + " " + '1' + " " + str(modulo) + " " + '1' + "\n" #words[0] = network_hls[0:3] + "\n" #words[0] = rlString.upper() + "\n" else: #words[0] = network_hls[0:0] + rlString.upper() + network_hls[3:] + " " + words[0] + " " + '1' + " " + '0' + " " + '0'+ " " + '1' + "\n" words[0] = rlString.upper() + network_hls[3:] + " " + words[0] + " " + '1' + " " + '0' + " " + '0'+ " " + '1' + "\n" words[1:-1] = map(lambda s: network_hls_any_short + " " + s + " " + '0' + " " + '0' + " " + '0'+ " " + '1' + "\n", words[1:-1]) words[-1] = network_hls_any_short + " " + words[-1] + " " + '0' + " " + '1' + " " + str(modulo) + " " + '1' + "\n" return "".join(words) def simulationOutput_rtl_hls(hexstream): if hexstream=="": return "" requestLength = len(hexstream) / 2 requestLength = requestLength << 1 rlString = hex(requestLength) if (len(rlString) == 4): rlString = "0" + rlString[2:] else: rlString = rlString[2:] hexstream = hexstream.upper() modulo = (len(hexstream) % 16) / 2 mod_eop = "%x" % (modulo + 8) # 8 = EOP mod_eop = mod_eop.upper() while len(hexstream) % 16 != 0: hexstream = hexstream + "**" words = split_string_into_len(hexstream, 16) words = map(hexstream_reverse_bytes, words) if(len(words)==1): words[0] = network_out_x[0:3] + rlString.upper() + network_out_x[4:] + "5" + mod_eop + words[0] + " 2\n" else: words[0] = network_out_sop_hls[0:3] + rlString.upper() + network_out_sop_hls[4:] + words[0] + " 2\n" words[1:-1] = map(lambda s: network_out_any_hls + s + " 2\n", words[1:-1]) words[-1] = network_out_x_hls + "0" + mod_eop + words[-1] + " 2\n" return "".join(words) # expects list of hexstreams def requests12Gbps_hls(requests): requests = requests[:] # copy of list requests[0:-1] = map(lambda r: simulationInput_hls(r, False), requests[0:-1]) requests[-1] = simulationInput_hls(requests[-1], True) return "".join(requests) # expects list of hexstreams def requests1Gbps_hls(requests): input = map(lambda r: simulationInput_hls(r, True), requests) pkg_count = map(lambda r: len(r) / 16, requests) pkg_wait_count = map(lambda c: 9*c, pkg_count) pkg_wait = map(lambda wc: "W %d\n" % wc, pkg_wait_count) # wait statement for each of the rqs. input_pairs = zip(pkg_wait, input) input_pairs = map(lambda p: "".join(p), input_pairs) # wait and request combined for each rq return "".join(input_pairs) # 1 string w/ all rqs # expects list of hexstreams def responses_hls(res): res = map(simulationOutput_hls, res) return "".join(res) # expects list of hexstreams def responses_rtl_hls(res): res = map(simulationOutput_rtl_hls, res) return "".join(res) ######################################################################################################## ## Helpers for quick testcase scenario setup ################################### # These functions allow you to specify a series of requests without specifying # any protocol details. In the end, they produce # # * the specified requests using the BINARY protocol # * the specified requests using the ASCII protocol # * at both, back-to-back and 1Gbps input rate # * the corresponding golden resoponse for automatic verification def newTestset(): return { 'list' : [], 'bin_rq' : [], 'bin_rs' : [], 'txt_rq' : [], 'txt_rs' : [] } def setSuccess(pair, set): set['list'].append("set [%d -> %d; %s]: %s -> %s" % ( len(pair['key']), len(pair['value']), pair['flags'], pair['key'], pair['value'] )) set['bin_rq'].append( binarySetRequest(pair) ) set['bin_rs'].append( binarySetResponse(pair) ) set['txt_rq'].append( textSetRequest(pair) ) set['txt_rs'].append( textSetResponse(pair) ) def setFail(pair, set): set['list'].append("set [%d -> %d; %s]: %s -> %s" % ( len(pair['key']), len(pair['value']), pair['flags'], pair['key'], pair['value'] )) set['bin_rq'].append( binarySetRequest(pair) ) set['bin_rs'].append( binaryFailedSetResponse(pair) ) set['txt_rq'].append( textSetRequest(pair) ) set['txt_rs'].append( textFailedSetResponse(pair) ) # Not supported at this stage def getSuccess(pair, set): set['list'].append("getSuccess [%d -> %d; %s]: %s -> %s" % ( len(pair['key']), len(pair['value']), pair['flags'], pair['key'], pair['value'] )) set['bin_rq'].append( binaryGetRequest(pair) ) set['bin_rs'].append( binaryGetResponse(pair) ) set['txt_rq'].append( textGetRequest(pair) ) set['txt_rs'].append( textGetResponse(pair) ) def getFail(pair, set): set['list'].append("getFail [%d -> %d; %s]: %s -> %s" % ( len(pair['key']), len(pair['value']), pair['flags'], pair['key'], pair['value'] )) set['bin_rq'].append( binaryGetRequest(pair) ) set['bin_rs'].append( binaryFailedGetResponse() ) set['txt_rq'].append( textGetRequest(pair) ) set['txt_rs'].append( textFailedGetResponse() ) def delete(pair, set): set['list'].append("delete [%d -> %d; %s]: %s -> %s" % ( len(pair['key']), len(pair['value']), pair['flags'], pair['key'], pair['value'] )) set['bin_rq'].append( binaryDeleteRequest(pair) ) set['bin_rs'].append( binaryDeleteResponse(pair) ) set['txt_rq'].append( textDeleteRequest(pair) ) set['txt_rs'].append( textDeleteResponse(pair) ) def deleteFail(pair, set): set['list'].append("deleteFail [%d -> %d; %s]: %s -> %s" % ( len(pair['key']), len(pair['value']), pair['flags'], pair['key'], pair['value'] )) set['bin_rq'].append( binaryDeleteRequest(pair) ) set['bin_rs'].append( binaryFailedDeleteResponse(pair) ) set['txt_rq'].append( textDeleteRequest(pair) ) set['txt_rs'].append( textFailedDeleteResponse(pair) ) def flush(set): set['list'].append("flush") set['bin_rq'].append( binaryFlushRequest() ) set['bin_rs'].append( binaryFlushResponse() ) set['txt_rq'].append( textFlushRequest() ) set['txt_rs'].append( textFlushResponse() ) def generate(name, set): f = open("%s_list.txt" % name, "w") for line in set['list']: print>>f, line f.close() f = open("%s_TXT_R12-pkt.in.txt" % name, "w") f.write( requests12Gbps(set['txt_rq']) ) f.close() f = open("%s_TXT_R01-pkt.in.txt" % name, "w") f.write( requests1Gbps(set['txt_rq']) ) f.close() f = open("%s_TXT-pkt.out.txt" % name, "w") f.write( responses(set['txt_rs']) ) f.close() f = open("%s_TXT-pkt.out.hls.rtl.txt" % name, "w") # This line creates the output files for the RTL simulation of the HLS modules. There are subtle differences there. f.write( responses_rtl_hls(set['txt_rs']) ) f.close() f = open("%s_BIN_R12-pkt.in.txt" % name, "w") f.write( requests12Gbps(set['bin_rq']) ) f.close() f = open("%s_BIN_R01-pkt.in.txt" % name, "w") f.write( requests1Gbps(set['bin_rq']) ) f.close() f = open("%s_BIN-pkt.out.txt" % name, "w") f.write( responses(set['bin_rs']) ) f.close() f = open("%s_BIN-pkt.out.hls.rtl.txt" % name, "w") # This line creates the output files for the RTL simulation of the HLS modules. There are subtle differences there. f.write( responses_rtl_hls(set['bin_rs']) ) f.close() def generate_hls(name, set): f = open("%s_list.txt" % name, "w") for line in set['list']: print>>f, line f.close() f = open("%s_TXT_R12-pkt.in.hls.txt" % name, "w") f.write( requests12Gbps_hls(set['txt_rq']) ) f.close() f = open("%s_TXT_R01-pkt.in.hls.txt" % name, "w") f.write( requests1Gbps_hls(set['txt_rq']) ) f.close() f = open("%s_TXT-pkt.out.hls.txt" % name, "w") f.write( responses_hls(set['txt_rs']) ) f.close() f = open("%s_TXT-pkt.out.hls.rtl.txt" % name, "w") f.write( responses_rtl_hls(set['txt_rs']) ) f.close() f = open("%s_BIN_R12-pkt.in.hls.txt" % name, "w") f.write( requests12Gbps_hls(set['bin_rq']) ) f.close() f = open("%s_BIN_R01-pkt.in.hls.txt" % name, "w") f.write( requests1Gbps_hls(set['bin_rq']) ) f.close() f = open("%s_BIN-pkt.out.hls.txt" % name, "w") f.write( responses_hls(set['bin_rs']) ) f.close() f = open("%s_BIN-pkt.out.hls.rtl.txt" % name, "w") f.write( responses_rtl_hls(set['bin_rs']) ) f.close()
13,254
1,036
#include_next <sys/param.h> #define ALIGNBYTES (sizeof(uintptr_t) - 1) #define ALIGN(p) (((uintptr_t)(p) + ALIGNBYTES) &~ ALIGNBYTES)
64
2,073
<reponame>thg-josh-coutinho/activemq<filename>activemq-unit-tests/src/test/java/org/apache/activemq/network/NetworkDestinationFilterTest.java /** * 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. */ package org.apache.activemq.network; import junit.framework.TestCase; import org.apache.activemq.advisory.AdvisorySupport; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTempQueue; import org.apache.activemq.command.ActiveMQTopic; import java.util.ArrayList; import java.util.List; public class NetworkDestinationFilterTest extends TestCase { public void testFilter() throws Exception { NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); assertEquals(AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX + ">", config.getDestinationFilter()); List<ActiveMQDestination> dests = new ArrayList<ActiveMQDestination>(); config.setDynamicallyIncludedDestinations(dests); assertEquals(AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX + ">", config.getDestinationFilter()); dests.add(new ActiveMQQueue("TEST.>")); dests.add(new ActiveMQTopic("TEST.>")); dests.add(new ActiveMQTempQueue("TEST.>")); String prefix = AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX; assertEquals(prefix + "Queue.TEST.>," + prefix + "Topic.TEST.>", config.getDestinationFilter()); } }
698
706
<reponame>goncaloperes/datashader<filename>datashader/glyphs/glyph.py from __future__ import absolute_import, division import inspect import warnings import os from math import isnan import numpy as np import pandas as pd from datashader.utils import Expr, ngjit from datashader.macros import expand_varargs try: import cudf except Exception: cudf = None @ngjit def isnull(val): """ Equivalent to isnan for floats, but also numba compatible with integers """ return not (val <= 0 or val > 0) class Glyph(Expr): """Base class for glyphs.""" @property def ndims(self): """ The number of dimensions required in the data structure this Glyph is constructed from. Or None if input data structure is irregular For example * ndims is 1 if glyph is constructed from a DataFrame * ndims is 2 if glyph is constructed from a 2D xarray DataArray * ndims is None if glyph is constructed from multiple DataFrames of different lengths """ raise NotImplementedError() @staticmethod def maybe_expand_bounds(bounds): minval, maxval = bounds if not (np.isfinite(minval) and np.isfinite(maxval)): minval, maxval = -1.0, 1.0 elif minval == maxval: minval, maxval = minval-1, minval+1 return minval, maxval @staticmethod def _compute_bounds(s): if cudf and isinstance(s, cudf.Series): s = s.nans_to_nulls() return (s.min(), s.max()) elif isinstance(s, pd.Series): return Glyph._compute_bounds_numba(s.values) else: return Glyph._compute_bounds_numba(s) @staticmethod @ngjit def _compute_bounds_numba(arr): minval = np.inf maxval = -np.inf for x in arr: if not isnan(x): if x < minval: minval = x if x > maxval: maxval = x return minval, maxval @staticmethod @ngjit def _compute_bounds_2d(vals): minval = np.inf maxval = -np.inf for i in range(vals.shape[0]): for j in range(vals.shape[1]): v = vals[i][j] if not np.isnan(v): if v < minval: minval = v if v > maxval: maxval = v return minval, maxval @staticmethod def to_gpu_matrix(df, columns): if not isinstance(columns, (list, tuple)): return df[columns].to_gpu_array() else: return cudf.concat([ df[name].rename(str(i)) for i, name in enumerate(columns) ], axis=1).as_gpu_matrix() def expand_aggs_and_cols(self, append): """ Create a decorator that can be used on functions that accept *aggs_and_cols as a variable length argument. The decorator will replace *aggs_and_cols with a fixed number of arguments. The appropriate fixed number of arguments is calculated from the input append function. Rationale: When we know the fixed length of a variable length argument, replacing it with fixed arguments can help numba better optimize the the function. If this ever causes problems in the future, this decorator can be safely removed without changing the functionality of the decorated function. Parameters ---------- append: function The append function for the current aggregator Returns ------- function Decorator function """ return self._expand_aggs_and_cols(append, self.ndims) @staticmethod def _expand_aggs_and_cols(append, ndims): if os.environ.get('NUMBA_DISABLE_JIT', None): # If the NUMBA_DISABLE_JIT environment is set, then we return an # identity decorator (one that return function unchanged). # # Doing this makes it possible to debug functions that are # decorated with @jit and @expand_varargs decorators return lambda fn: fn with warnings.catch_warnings(): warnings.simplefilter("ignore") try: # Numba keeps original function around as append.py_func append_args = inspect.getargspec(append.py_func).args except (TypeError, AttributeError): # Treat append as a normal python function append_args = inspect.getargspec(append).args # Get number of arguments accepted by append append_arglen = len(append_args) # We will subtract 2 because we always pass in the x and y position xy_arglen = 2 # We will also subtract the number of dimensions in this glyph, # becuase that's how many data index arguments are passed to append dim_arglen = (ndims or 0) # The remaining arguments are for aggregates and columns aggs_and_cols_len = append_arglen - xy_arglen - dim_arglen return expand_varargs(aggs_and_cols_len)
2,299
1,256
<gh_stars>1000+ #include <all_lib.h> #pragma hdrstop #if defined(__MYPACKAGE__) #pragma package(smart_init) #endif #if 1 #define PROC( v ) #define Log( v ) #else #define PROC( v ) INProc __proc v ; #define Log( v ) INProc::Say v #endif static DWORD GetSize( DWORD flags ) { if ( IS_FLAG(flags,LZH_F_BLOCK128) ) return 128000; else if ( IS_FLAG(flags,LZH_F_BLOCK64) ) return 64000; else if ( IS_FLAG(flags,LZH_F_BLOCK32) ) return 32000; else if ( IS_FLAG(flags,LZH_F_BLOCK16) ) return 16000; else return 8000; } /**************************************************** LZHOStream ****************************************************/ LZHOStream::LZHOStream( DWORD flags ) : HOStream( GetSize(flags) ) { Flags = flags; WritenSize = 0; cBuff = new BYTE[ rSize+1 ]; } LZHOStream::~LZHOStream() { delete[] cBuff; } void LZHOStream::doReset( void ) { HOStream::doReset(); WritenSize = 0; } BOOL LZHOStream::WriteCompleted( void ) { if ( !rCount ) return TRUE; if ( !WritenSize ) { LZHStreamHeader sh; sh.Id = LZH_STREAMID; sh.BlockSize = rSize; if ( !WriteBuffer(&sh,sizeof(sh)) ) return FALSE; WritenSize += sizeof(sh); } LZHStreamBlock fb; DWORD rSz; rSz = LZHCompress( rBuff,rCount,cBuff,rSize ); if ( !rSz ) return FALSE; fb.Id = LZH_SBLOCKID; fb.OriginalBlockSize = rCount; fb.BlockSize = rSz; if ( IS_FLAG(Flags,LZH_F_CRC) ) { fb.BlockCRC = Crc32(0,cBuff,rSz); fb.OriginalBlockCRC = Crc32(0,rBuff,rCount); } else { fb.BlockCRC = 0; fb.OriginalBlockCRC = 0; } if ( !BlockReady( &fb,rBuff,cBuff ) ) { FIO_SETERRORN( ERROR_CANCELLED ); return FALSE; } #if 0 BYTE tmp[ LZH_STREAMBLOCK+500 ]; DWORD tsz; int ttmp; tsz = LZHDecompress( cBuff,rSz,tmp,sizeof(tmp)-1 ); if ( tsz != (int)rCount || (ttmp=memcmp( tmp,rBuff,Min(tsz,(int)rCount) )) != 0 ) HAbort( "Block does not match with compressed %d!=%d Cmp=%d\n", tsz,rCount,ttmp ); #endif if ( !WriteBuffer(&fb,sizeof(fb)) || !WriteBuffer(cBuff,fb.BlockSize) ) return FALSE; WritenSize += rCount + sizeof(fb); rCount = 0; return TRUE; } DWORD LZHOStream::CompleteSize( void ) { return WritenSize; } BOOL LZHOStream::BlockReady( PLZHStreamBlock /*Block*/,LPBYTE /*OriginalBlock*/,LPBYTE /*PackedBlock*/ ) { return TRUE; } /**************************************************** LZHFileOStream ****************************************************/ LZHFileOStream::LZHFileOStream( DWORD flags ) : LZHOStream(flags) { File = -1; } LZHFileOStream::LZHFileOStream( CONSTSTR fnm,DWORD flags ) : LZHOStream(flags) { File = -1; Assign( fnm ); } LZHFileOStream::LZHFileOStream( int fnm,DWORD flags ) : LZHOStream(flags) { File = -1; Assign( fnm ); } LZHFileOStream::~LZHFileOStream() { Close(); } void LZHFileOStream::Close( void ) { if ( File != -1 ) { Flush(); FIO_TRUNC( File,FIO_TELL(File) ); FIO_CLOSE( File ); } Reset(); } BOOL LZHFileOStream::Assign( CONSTSTR FileName ) { Close(); File = FIO_OPEN( FileName,O_WRONLY|O_BINARY ); if ( File == -1 ) { File = FIO_CREAT( FileName,FIO_DEF_ATTR ); if ( File == -1 ) return FALSE; } DWORD dw = LZH_FILEID; return FIO_WRITE( File,&dw,sizeof(dw) ) == sizeof(dw); } BOOL LZHFileOStream::Assign( int nFile ) { Close(); File = nFile; if ( File == -1 ) return FALSE; DWORD dw = LZH_FILEID; return FIO_WRITE( File,&dw,sizeof(dw) ) == sizeof(dw); } BOOL LZHFileOStream::WriteBuffer( LPVOID buff,int sz ) { return File != -1 && FIO_WRITE( File,buff,sz) == sz; } BOOL LZHFileOStream::doAssigned( void ) { return File != -1; } /**************************************************** LZHIStream ****************************************************/ LZHIStream::LZHIStream( DWORD flags ) : HIStream( GetSize(flags) ) { ReadedSize = 0; Flags = flags; cBuff = new BYTE[ rSize+1 ]; } LZHIStream::~LZHIStream() { delete[] cBuff; } void LZHIStream::doReset( void ) { HIStream::doReset(); ReadedSize = 0; } BOOL LZHIStream::ReadCompleted( void ) { if ( !ReadedSize ) { LZHStreamHeader sh; if ( !ReadBuffer(&sh,sizeof(sh)) ) return FALSE; if ( sh.Id != LZH_STREAMID ) { FIO_SETERRORN( ERROR_HEADER ); return FALSE; } if ( rSize < sh.BlockSize ) { delete[] rBuff; delete[] cBuff; rBuff = new BYTE[ sh.BlockSize+1 ]; cBuff = new BYTE[ sh.BlockSize+500 ]; rSize = sh.BlockSize; } ReadedSize += sizeof(sh); } LZHStreamBlock fb; if ( !ReadBuffer(&fb,sizeof(fb)) ) return FALSE; if ( fb.Id != LZH_SBLOCKID ) { FIO_SETERRORN( ERROR_HEADER ); return FALSE; } if ( fb.BlockSize >= rSize ) { FIO_SETERRORN( ERROR_RANGE ); return FALSE; } if ( !ReadBuffer(cBuff,fb.BlockSize) ) return FALSE; rCount = LZHDecompress( cBuff,fb.BlockSize,rBuff,rSize ); ReadedSize += rCount + sizeof(fb); if ( IS_FLAG(Flags,LZH_F_CRC) ) if ( fb.BlockCRC && fb.BlockCRC != Crc32(0,cBuff,fb.BlockSize) || fb.OriginalBlockCRC && fb.OriginalBlockCRC != Crc32(0,rBuff,rCount) ) { FIO_SETERRORN( ERROR_CRC ); return FALSE; } if ( !BlockReady( &fb,rBuff,cBuff ) ) { return FALSE; } return rCount == fb.OriginalBlockSize; } DWORD LZHIStream::CompleteSize( void ) { return ReadedSize; } BOOL LZHIStream::BlockReady( PLZHStreamBlock /*Block*/,LPBYTE /*OriginalBlock*/,LPBYTE /*PackedBlock*/ ) { return TRUE; } /**************************************************** LZHFileIStream ****************************************************/ LZHFileIStream::LZHFileIStream( DWORD flags ) : LZHIStream(flags) { File = -1; } LZHFileIStream::LZHFileIStream( CONSTSTR fnm,DWORD flags ) : LZHIStream(flags) { File = -1; Assign( fnm ); } LZHFileIStream::LZHFileIStream( int fnm,DWORD flags ) : LZHIStream(flags) { File = -1; Assign( fnm ); } LZHFileIStream::~LZHFileIStream() { Close(); } void LZHFileIStream::Close( void ) { if ( File != -1 ) { FIO_CLOSE( File ); File = -1; } Reset(); } BOOL LZHFileIStream::Assign( CONSTSTR FileName ) { Close(); File = FIO_OPEN( FileName,O_RDONLY|O_BINARY ); if ( File == -1 ) return FALSE; DWORD dw; if ( FIO_READ( File,&dw,sizeof(dw) ) != sizeof(dw) ) return FALSE; if ( dw != LZH_FILEID ) { FIO_SETERRORN( ERROR_MAGIC ); return FALSE; } return TRUE; } BOOL LZHFileIStream::Assign( int nFile ) { Close(); File = nFile; if ( File == -1 ) return FALSE; DWORD dw; if ( FIO_READ( File,&dw,sizeof(dw) ) != sizeof(dw) ) return FALSE; if ( dw != LZH_FILEID ) { FIO_SETERRORN( ERROR_MAGIC ); return FALSE; } return TRUE; } BOOL LZHFileIStream::ReadBuffer( LPVOID buff,int sz ) { if ( File != -1 && FIO_READ(File,buff,sz) == sz ) { return TRUE; } else { return FALSE; } } BOOL LZHFileIStream::FEOF( void ) { return ReadySize() == 0 && (File == -1 || FIO_EOF(File)); } BOOL LZHFileIStream::doAssigned( void ) { return File != -1; } #if defined(__VCL__) void MYRTLEXP HSaveStream( TStream *ControlStream, CONSTSTR fn, bool CompressContents ) { HOStream *out; if ( CompressContents ) out = new LZHFileOStream( fn ); else out = new HFileOStream( fn ); __try{ BYTE buff[ 512 ]; DWORD sz; ControlStream->Position = 0; while( 1 ) { sz = Min( (size_t)(ControlStream->Size - ControlStream->Position), sizeof(buff) ); if ( !sz ) break; ControlStream->Read( buff, sz ); if ( !out->Write( buff, sz ) ) throw Exception( FIO_ERROR ); } }__finally{ delete out; ControlStream->Position = 0; } } void MYRTLEXP HLoadStream( TStream *ControlStream, CONSTSTR fn ) { HAutoPtr<HIStream> in( OpenStreamFile(fn) ); if ( !in.Ptr() ) return; BYTE buff[ 512 ]; DWORD sz, fsz; ControlStream->Position = 0; for( fsz = 0; (sz=in->Read(buff,sizeof(buff))) > 0; fsz += sz ) ControlStream->Write( buff, sz ); ControlStream->Size = (int)fsz; ControlStream->Position = 0; } #endif
4,196
3,269
<reponame>Akhil-Kashyap/LeetCode-Solutions // Time: O(n) // Space: O(1) class Solution { public: int numSub(string s) { static const int MOD = 1e9 + 7; int result = 0, count = 0; for (const auto& c : s) { count = (c == '1') ? count + 1 : 0; result = (result + count) % MOD; } return result; } };
188
1,156
/* * * Copyright IBM Corp. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 * / */ package org.hyperledger.fabric.sdk; import org.hyperledger.fabric.sdk.exception.InvalidArgumentException; import org.hyperledger.fabric.sdk.helper.Utils; /** * Request to get a {@link LifecycleQueryInstalledChaincodeProposalResponse} for a specific packageId */ public class LifecycleQueryInstalledChaincodeRequest extends LifecycleRequest { private String packageId; LifecycleQueryInstalledChaincodeRequest(User userContext) { super(userContext, false); } String getPackageId() { return packageId; } /** * The packageId of the chaincode to query. Sent to peer to get a {@link LifecycleQueryInstalledChaincodeProposalResponse} * * @param packageId * @throws InvalidArgumentException */ public void setPackageID(String packageId) throws InvalidArgumentException { if (Utils.isNullOrEmpty(packageId)) { throw new InvalidArgumentException("The packageId parameter can not be null or empty."); } this.packageId = packageId; } }
395
715
/* * Copyright 2019 Lightbend Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.cloudstate.javasupport; /** Entity factory for supporting DI environments. */ public interface EntityFactory { /** * Create an entity. * * @return the new entity */ Object create(EntityContext context); /** * Get the class of the entity. * * @return the entity class */ Class<?> entityClass(); }
263
407
<filename>saas/dataops/api/dataset/APP-META-PRIVATE/postrun/warehouse/entry.py<gh_stars>100-1000 # coding: utf-8 from . import sw_entity_init as entity from . import sw_model_init as model def init(): entity.add_sw_entities() model.add_sw_models() model.add_default_resource_price()
117
313
package com.imperva.apiattacktool.processors; import com.imperva.apiattacktool.fuzzing.Fuzzer; import com.imperva.apiattacktool.fuzzing.modelgenerators.FuzzedModelsGenerator; import com.imperva.apiattacktool.model.valued.EndpointValuedModel; import com.imperva.apiattacktool.model.valued.factory.PropertyValueFactory; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class FuzzEndpointModelProcessor implements EndpointModelProcessor { private FuzzedModelsGenerator fuzzedModelsGenerator; private PropertyValueFactory propertyValueFactory; public FuzzEndpointModelProcessor(FuzzedModelsGenerator fuzzedModelsGenerator) { this.fuzzedModelsGenerator = fuzzedModelsGenerator; this.propertyValueFactory = fuzzedModelsGenerator.getPropertyValueFactory(); } @Override public List<EndpointValuedModel> process(List<EndpointValuedModel> endpointModelList, Fuzzer fuzzer) { if (endpointModelList == null) { return Collections.EMPTY_LIST; } return endpointModelList.stream() .flatMap(endpointValuedModel -> fuzzedModelsGenerator.fuzzModelValues( endpointValuedModel, fuzzer).stream()) .collect(Collectors.toList()); } }
461
1,874
<reponame>zjzh/nova # Copyright 2011 OpenStack Foundation # 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. """ Tests dealing with HTTP rate-limiting. """ from http import client as httplib from io import StringIO import mock from oslo_serialization import jsonutils from oslo_utils import encodeutils from nova.api.openstack.compute import limits as limits_v21 from nova.api.openstack.compute import views from nova.api.openstack import wsgi import nova.context from nova import exception from nova.policies import limits as l_policies from nova import quota from nova import test from nova.tests.unit.api.openstack import fakes from nova.tests.unit import matchers class BaseLimitTestSuite(test.NoDBTestCase): """Base test suite which provides relevant stubs and time abstraction.""" def setUp(self): super(BaseLimitTestSuite, self).setUp() self.time = 0.0 self.absolute_limits = {} def stub_get_project_quotas(context, project_id, usages=True): return {k: dict(limit=v, in_use=v // 2) for k, v in self.absolute_limits.items()} mock_get_project_quotas = mock.patch.object( nova.quota.QUOTAS, "get_project_quotas", side_effect = stub_get_project_quotas) mock_get_project_quotas.start() self.addCleanup(mock_get_project_quotas.stop) patcher = self.mock_can = mock.patch('nova.context.RequestContext.can') self.mock_can = patcher.start() self.addCleanup(patcher.stop) def _get_time(self): """Return the "time" according to this test suite.""" return self.time class LimitsControllerTestV21(BaseLimitTestSuite): """Tests for `limits.LimitsController` class.""" limits_controller = limits_v21.LimitsController def setUp(self): """Run before each test.""" super(LimitsControllerTestV21, self).setUp() self.controller = wsgi.Resource(self.limits_controller()) self.ctrler = self.limits_controller() def _get_index_request(self, accept_header="application/json", tenant_id=None, user_id='testuser', project_id='testproject'): """Helper to set routing arguments.""" request = fakes.HTTPRequest.blank('', version='2.1') if tenant_id: request = fakes.HTTPRequest.blank('/?tenant_id=%s' % tenant_id, version='2.1') request.accept = accept_header request.environ["wsgiorg.routing_args"] = (None, { "action": "index", "controller": "", }) context = nova.context.RequestContext(user_id, project_id) request.environ["nova.context"] = context return request def test_empty_index_json(self): # Test getting empty limit details in JSON. request = self._get_index_request() response = request.get_response(self.controller) expected = { "limits": { "rate": [], "absolute": {}, }, } body = jsonutils.loads(response.body) self.assertEqual(expected, body) def test_index_json(self): self._test_index_json() def test_index_json_by_tenant(self): self._test_index_json('faketenant') def _test_index_json(self, tenant_id=None): # Test getting limit details in JSON. request = self._get_index_request(tenant_id=tenant_id) context = request.environ["nova.context"] if tenant_id is None: tenant_id = context.project_id self.absolute_limits = { 'ram': 512, 'instances': 5, 'cores': 21, 'key_pairs': 10, 'floating_ips': 10, 'security_groups': 10, 'security_group_rules': 20, } expected = { "limits": { "rate": [], "absolute": { "maxTotalRAMSize": 512, "maxTotalInstances": 5, "maxTotalCores": 21, "maxTotalKeypairs": 10, "maxTotalFloatingIps": 10, "maxSecurityGroups": 10, "maxSecurityGroupRules": 20, "totalRAMUsed": 256, "totalCoresUsed": 10, "totalInstancesUsed": 2, "totalFloatingIpsUsed": 5, "totalSecurityGroupsUsed": 5, }, }, } def _get_project_quotas(context, project_id, usages=True): return {k: dict(limit=v, in_use=v // 2) for k, v in self.absolute_limits.items()} with mock.patch('nova.quota.QUOTAS.get_project_quotas') as \ get_project_quotas: get_project_quotas.side_effect = _get_project_quotas response = request.get_response(self.controller) body = jsonutils.loads(response.body) self.assertEqual(expected, body) get_project_quotas.assert_called_once_with(context, tenant_id, usages=True) def _do_test_used_limits(self, reserved): request = self._get_index_request(tenant_id=None) quota_map = { 'totalRAMUsed': 'ram', 'totalCoresUsed': 'cores', 'totalInstancesUsed': 'instances', 'totalFloatingIpsUsed': 'floating_ips', 'totalSecurityGroupsUsed': 'security_groups', 'totalServerGroupsUsed': 'server_groups', } limits = {} expected_abs_limits = [] for display_name, q in quota_map.items(): limits[q] = {'limit': len(display_name), 'in_use': len(display_name) // 2, 'reserved': 0} expected_abs_limits.append(display_name) def stub_get_project_quotas(context, project_id, usages=True): return limits self.stub_out('nova.quota.QUOTAS.get_project_quotas', stub_get_project_quotas) res = request.get_response(self.controller) body = jsonutils.loads(res.body) abs_limits = body['limits']['absolute'] for limit in expected_abs_limits: value = abs_limits[limit] r = limits[quota_map[limit]]['reserved'] if reserved else 0 self.assertEqual(limits[quota_map[limit]]['in_use'] + r, value) def test_used_limits_basic(self): self._do_test_used_limits(False) def test_used_limits_with_reserved(self): self._do_test_used_limits(True) def test_admin_can_fetch_limits_for_a_given_tenant_id(self): project_id = "123456" user_id = "A1234" tenant_id = 'abcd' fake_req = self._get_index_request(tenant_id=tenant_id, user_id=user_id, project_id=project_id) context = fake_req.environ["nova.context"] with mock.patch.object(quota.QUOTAS, 'get_project_quotas', return_value={}) as mock_get_quotas: fake_req.get_response(self.controller) self.assertEqual(2, self.mock_can.call_count) self.mock_can.assert_called_with( l_policies.OTHER_PROJECT_LIMIT_POLICY_NAME, target={"project_id": tenant_id}) mock_get_quotas.assert_called_once_with(context, tenant_id, usages=True) def _test_admin_can_fetch_used_limits_for_own_project(self, req_get): project_id = "123456" if 'tenant_id' in req_get: project_id = req_get['tenant_id'] user_id = "A1234" fake_req = self._get_index_request(user_id=user_id, project_id=project_id) context = fake_req.environ["nova.context"] with mock.patch.object(quota.QUOTAS, 'get_project_quotas', return_value={}) as mock_get_quotas: fake_req.get_response(self.controller) mock_get_quotas.assert_called_once_with(context, project_id, usages=True) def test_admin_can_fetch_used_limits_for_own_project(self): req_get = {} self._test_admin_can_fetch_used_limits_for_own_project(req_get) def test_admin_can_fetch_used_limits_for_dummy_only(self): # for back compatible we allow additional param to be send to req.GET # it can be removed when we add restrictions to query param later req_get = {'dummy': 'dummy'} self._test_admin_can_fetch_used_limits_for_own_project(req_get) def test_admin_can_fetch_used_limits_with_positive_int(self): req_get = {'tenant_id': 123} self._test_admin_can_fetch_used_limits_for_own_project(req_get) def test_admin_can_fetch_used_limits_with_negative_int(self): req_get = {'tenant_id': -1} self._test_admin_can_fetch_used_limits_for_own_project(req_get) def test_admin_can_fetch_used_limits_with_unkown_param(self): req_get = {'tenant_id': '123', 'unknown': 'unknown'} self._test_admin_can_fetch_used_limits_for_own_project(req_get) def test_used_limits_fetched_for_context_project_id(self): project_id = "123456" fake_req = self._get_index_request(project_id=project_id) context = fake_req.environ["nova.context"] with mock.patch.object(quota.QUOTAS, 'get_project_quotas', return_value={}) as mock_get_quotas: fake_req.get_response(self.controller) mock_get_quotas.assert_called_once_with(context, project_id, usages=True) def test_used_ram_added(self): fake_req = self._get_index_request() def stub_get_project_quotas(context, project_id, usages=True): return {'ram': {'limit': 512, 'in_use': 256}} with mock.patch.object(quota.QUOTAS, 'get_project_quotas', side_effect=stub_get_project_quotas ) as mock_get_quotas: res = fake_req.get_response(self.controller) body = jsonutils.loads(res.body) abs_limits = body['limits']['absolute'] self.assertIn('totalRAMUsed', abs_limits) self.assertEqual(256, abs_limits['totalRAMUsed']) self.assertEqual(1, mock_get_quotas.call_count) def test_no_ram_quota(self): fake_req = self._get_index_request() with mock.patch.object(quota.QUOTAS, 'get_project_quotas', return_value={}) as mock_get_quotas: res = fake_req.get_response(self.controller) body = jsonutils.loads(res.body) abs_limits = body['limits']['absolute'] self.assertNotIn('totalRAMUsed', abs_limits) self.assertEqual(1, mock_get_quotas.call_count) class FakeHttplibSocket(object): """Fake `httplib.HTTPResponse` replacement.""" def __init__(self, response_string): """Initialize new `FakeHttplibSocket`.""" self._buffer = StringIO(response_string) def makefile(self, _mode, _other): """Returns the socket's internal buffer.""" return self._buffer class FakeHttplibConnection(object): """Fake `httplib.HTTPConnection`.""" def __init__(self, app, host): """Initialize `FakeHttplibConnection`.""" self.app = app self.host = host def request(self, method, path, body="", headers=None): """Requests made via this connection actually get translated and routed into our WSGI app, we then wait for the response and turn it back into an `httplib.HTTPResponse`. """ if not headers: headers = {} req = fakes.HTTPRequest.blank(path) req.method = method req.headers = headers req.host = self.host req.body = encodeutils.safe_encode(body) resp = str(req.get_response(self.app)) resp = "HTTP/1.0 %s" % resp sock = FakeHttplibSocket(resp) self.http_response = httplib.HTTPResponse(sock) self.http_response.begin() def getresponse(self): """Return our generated response from the request.""" return self.http_response class LimitsViewBuilderTest(test.NoDBTestCase): def setUp(self): super(LimitsViewBuilderTest, self).setUp() self.view_builder = views.limits.ViewBuilder() self.req = fakes.HTTPRequest.blank('/?tenant_id=None') self.rate_limits = [] self.absolute_limits = {"metadata_items": {'limit': 1, 'in_use': 1}, "injected_files": {'limit': 5, 'in_use': 1}, "injected_file_content_bytes": {'limit': 5, 'in_use': 1}} def test_build_limits(self): expected_limits = {"limits": { "rate": [], "absolute": {"maxServerMeta": 1, "maxImageMeta": 1, "maxPersonality": 5, "maxPersonalitySize": 5}}} output = self.view_builder.build(self.req, self.absolute_limits) self.assertThat(output, matchers.DictMatches(expected_limits)) def test_build_limits_empty_limits(self): expected_limits = {"limits": {"rate": [], "absolute": {}}} quotas = {} output = self.view_builder.build(self.req, quotas) self.assertThat(output, matchers.DictMatches(expected_limits)) class LimitsControllerTestV236(BaseLimitTestSuite): def setUp(self): super(LimitsControllerTestV236, self).setUp() self.controller = limits_v21.LimitsController() self.req = fakes.HTTPRequest.blank("/?tenant_id=faketenant", version='2.36') def test_index_filtered(self): absolute_limits = { 'ram': 512, 'instances': 5, 'cores': 21, 'key_pairs': 10, 'floating_ips': 10, 'security_groups': 10, 'security_group_rules': 20, } def _get_project_quotas(context, project_id, usages=True): return {k: dict(limit=v, in_use=v // 2) for k, v in absolute_limits.items()} with mock.patch('nova.quota.QUOTAS.get_project_quotas') as \ get_project_quotas: get_project_quotas.side_effect = _get_project_quotas response = self.controller.index(self.req) expected_response = { "limits": { "rate": [], "absolute": { "maxTotalRAMSize": 512, "maxTotalInstances": 5, "maxTotalCores": 21, "maxTotalKeypairs": 10, "totalRAMUsed": 256, "totalCoresUsed": 10, "totalInstancesUsed": 2, }, }, } self.assertEqual(expected_response, response) class LimitsControllerTestV239(BaseLimitTestSuite): def setUp(self): super(LimitsControllerTestV239, self).setUp() self.controller = limits_v21.LimitsController() self.req = fakes.HTTPRequest.blank("/?tenant_id=faketenant", version='2.39') def test_index_filtered_no_max_image_meta(self): absolute_limits = { "metadata_items": 1, } def _get_project_quotas(context, project_id, usages=True): return {k: dict(limit=v, in_use=v // 2) for k, v in absolute_limits.items()} with mock.patch('nova.quota.QUOTAS.get_project_quotas') as \ get_project_quotas: get_project_quotas.side_effect = _get_project_quotas response = self.controller.index(self.req) # staring from version 2.39 there is no 'maxImageMeta' field # in response after removing 'image-metadata' proxy API expected_response = { "limits": { "rate": [], "absolute": { "maxServerMeta": 1, }, }, } self.assertEqual(expected_response, response) class LimitsControllerTestV275(BaseLimitTestSuite): def setUp(self): super(LimitsControllerTestV275, self).setUp() self.controller = limits_v21.LimitsController() def test_index_additional_query_param_old_version(self): absolute_limits = { "metadata_items": 1, } req = fakes.HTTPRequest.blank("/?unkown=fake", version='2.74') def _get_project_quotas(context, project_id, usages=True): return {k: dict(limit=v, in_use=v // 2) for k, v in absolute_limits.items()} with mock.patch('nova.quota.QUOTAS.get_project_quotas') as \ get_project_quotas: get_project_quotas.side_effect = _get_project_quotas self.controller.index(req) def test_index_additional_query_param(self): req = fakes.HTTPRequest.blank("/?unkown=fake", version='2.75') self.assertRaises( exception.ValidationError, self.controller.index, req=req)
8,891
933
<filename>src/traced/probes/ftrace/atrace_hal_wrapper.h /* * Copyright (C) 2019 The Android Open Source Project * * 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. */ #ifndef SRC_TRACED_PROBES_FTRACE_ATRACE_HAL_WRAPPER_H_ #define SRC_TRACED_PROBES_FTRACE_ATRACE_HAL_WRAPPER_H_ #include <memory> #include <string> #include <vector> #include "perfetto/ext/base/scoped_file.h" namespace perfetto { class AtraceHalWrapper { public: AtraceHalWrapper(); virtual ~AtraceHalWrapper(); virtual std::vector<std::string> ListCategories(); virtual bool EnableCategories(const std::vector<std::string>& categories); virtual bool DisableAllCategories(); private: struct DynamicLibLoader; std::unique_ptr<DynamicLibLoader> lib_; }; } // namespace perfetto #endif // SRC_TRACED_PROBES_FTRACE_ATRACE_HAL_WRAPPER_H_
438
4,538
<reponame>wstong999/AliOS-Things /* * Copyright (C) 2017-2020 Alibaba Group Holding Limited */ #if AOS_COMP_CLI #include "stdbool.h" #include "lwip/opt.h" #include "lwip/apps/ifconfig.h" #include <lwip/def.h> #include <lwip/netdb.h> #include <lwip/sockets.h> #include "aos/cli.h" void ifconfig_help(void) { aos_cli_printf("Usage: ifconfig\n"); aos_cli_printf("Example:\n"); aos_cli_printf("ifconfig Display net interface config information\n"); aos_cli_printf("ifconfig status Display net interface config information\n"); } void ifconfig_cmd(int argc, char **argv ) { if ( argc < 1 ) { aos_cli_printf("Invalid command\n"); ifconfig_help(); return; } if((argc == 2) && (strcmp(argv[1], "-h") == 0)) { ifconfig_help(); } else { ifconfig(argc - 1, &argv[1]); } } /* reg args: fun, cmd, description*/ ALIOS_CLI_CMD_REGISTER(ifconfig_cmd, ifconfig, Ifconfig command) #endif /* AOS_COMP_CLI */
442
575
<gh_stars>100-1000 // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SCROLL_ANCHOR_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SCROLL_ANCHOR_H_ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/geometry/layout_point.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { class LayoutObject; class Node; class ScrollableArea; static const int kMaxSerializedSelectorLength = 500; struct SerializedAnchor { SerializedAnchor() : simhash(0) {} SerializedAnchor(const String& s, const LayoutPoint& p) : selector(s), relative_offset(p), simhash(0) {} SerializedAnchor(const String& s, const LayoutPoint& p, uint64_t hash) : selector(s), relative_offset(p), simhash(hash) {} bool IsValid() const { return !selector.IsEmpty(); } // Used to locate an element previously used as a scroll anchor. const String selector; // Used to restore the previous offset of the element within its scroller. const LayoutPoint relative_offset; // Used to compare the similarity of a prospective anchor's contents to the // contents at the time the previous anchor was saved. const uint64_t simhash; }; // Scrolls to compensate for layout movements (bit.ly/scroll-anchoring). class CORE_EXPORT ScrollAnchor final { DISALLOW_NEW(); public: ScrollAnchor(); explicit ScrollAnchor(ScrollableArea*); ~ScrollAnchor(); // The scroller that is scrolled to componsate for layout movements. Note // that the scroller can only be initialized once. void SetScroller(ScrollableArea*); // Returns true if the underlying scroller is set. bool HasScroller() const { return scroller_; } // The LayoutObject we are currently anchored to. Lazily computed during // notifyBeforeLayout() and cached until the next call to clear(). LayoutObject* AnchorObject() const { return anchor_object_; } // Called when the scroller attached to this anchor is being destroyed. void Dispose(); // Indicates that this ScrollAnchor, and all ancestor ScrollAnchors, should // compute new anchor nodes on their next notifyBeforeLayout(). void Clear(); // Indicates that this ScrollAnchor should compute a new anchor node on the // next call to notifyBeforeLayout(). void ClearSelf(); // Records the anchor's location in relation to the scroller. Should be // called when the scroller is about to be laid out. void NotifyBeforeLayout(); // Scrolls to compensate for any change in the anchor's relative location. // Should be called at the end of the animation frame. void Adjust(); enum class Corner { kTopLeft = 0, kTopRight, }; // Which corner of the anchor object we are currently anchored to. // Only meaningful if anchorObject() is non-null. Corner GetCorner() const { return corner_; } // Attempt to restore |serialized_anchor| by scrolling to the element // identified by its selector, adjusting by its relative_offset. bool RestoreAnchor(const SerializedAnchor&); // Get the serialized representation of the current anchor_object_. // If there is not currently an anchor_object_, this will attempt to find one. // Repeated calls will re-use the previously calculated selector until the // anchor_object it corresponds to is cleared. const SerializedAnchor GetSerializedAnchor(); // Checks if we hold any references to the specified object. bool RefersTo(const LayoutObject*) const; // Notifies us that an object will be removed from the layout tree. void NotifyRemoved(LayoutObject*); void Trace(Visitor* visitor) const { visitor->Trace(scroller_); } private: void FindAnchor(); // Returns true if searching should stop. Stores result in m_anchorObject. bool FindAnchorRecursive(LayoutObject*); bool ComputeScrollAnchorDisablingStyleChanged(); // Find viable anchor among the priority candidates. Returns true if anchor // has been found; returns false if anchor was not found, and we should look // for an anchor in the DOM order traversal. bool FindAnchorInPriorityCandidates(); // Returns a closest ancestor layout object from the given node which isn't a // non-atomic inline and is not anonymous. LayoutObject* PriorityCandidateFromNode(const Node*) const; enum WalkStatus { kSkip = 0, kConstrain, kContinue, kReturn }; struct ExamineResult { ExamineResult(WalkStatus s) : status(s), viable(false), corner(Corner::kTopLeft) {} ExamineResult(WalkStatus s, Corner c) : status(s), viable(true), corner(c) {} WalkStatus status; bool viable; Corner corner; }; ExamineResult Examine(const LayoutObject*) const; // Examines a given priority candidate. Note that this is similar to Examine() // but it also checks that the given object is a descendant of the scroller // and that there is no object that has overflow-anchor: none between the // given object and the scroller. ExamineResult ExaminePriorityCandidate(const LayoutObject*) const; IntSize ComputeAdjustment() const; // The scroller to be adjusted by this ScrollAnchor. This is also the scroller // that owns us, unless it is the RootFrameViewport in which case we are owned // by the layout viewport. Member<ScrollableArea> scroller_; // The LayoutObject we should anchor to. LayoutObject* anchor_object_; // Which corner of m_anchorObject's bounding box to anchor to. Corner corner_; // Location of anchor_object_ relative to scroller block-start at the time of // NotifyBeforeLayout(). Note that the block-offset is a logical coordinate, // which makes a difference if we're in a block-flipped writing-mode // (vertical-rl). LayoutPoint saved_relative_offset_; // Previously calculated css selector that uniquely locates the current // anchor_object_. Cleared when the anchor_object_ is cleared. String saved_selector_; // We suppress scroll anchoring after a style change on the anchor node or // one of its ancestors, if that change might have caused the node to move. // This bit tracks whether we have had a scroll-anchor-disabling style // change since the last layout. It is recomputed in notifyBeforeLayout(), // and used to suppress adjustment in adjust(). See http://bit.ly/sanaclap. bool scroll_anchor_disabling_style_changed_; // True iff an adjustment check has been queued with the FrameView but not yet // performed. bool queued_; // This is set to true if the last anchor we have selected is a // 'content-visibility: auto' element that did not yet have a layout after // becoming visible. bool anchor_is_cv_auto_without_layout_ = false; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SCROLL_ANCHOR_H_
2,000
1,006
/**************************************************************************** * include/nuttx/analog/lmp92001.h * * 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. * ****************************************************************************/ #ifndef __INCLUDE_NUTTX_ANALOG_LMP92001_H #define __INCLUDE_NUTTX_ANALOG_LMP92001_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <nuttx/analog/ioctl.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* IOCTL Commands ***********************************************************/ /* Cmd: ANIOC_LMP92001_DAC_SET_REF Arg: bool value * Cmd: ANIOC_LMP92001_DAC_UPDATEALL Arg: uint16_t value * Cmd: ANIOC_LMP92001_ADC_SET_REF Arg: bool value * Cmd: ANIOC_LMP92001_ADC_ENABLE Arg: lmp92001_adc_enable_e channel * Cmd: ANIOC_LMP92001_ADC_SINGLESHOT_CONV Arg: none * Cmd: ANIOC_LMP92001_ADC_CONTINUOUS_CONV Arg: none * Cmd: ANIOC_LMP92001_ADC_READ_CHANNEL Arg: struct adc_msg_s *channel */ #define ANIOC_LMP92001_DAC_SET_REF _ANIOC(AN_LMP92001_FIRST + 0) #define ANIOC_LMP92001_DAC_UPDATEALL _ANIOC(AN_LMP92001_FIRST + 1) #define ANIOC_LMP92001_ADC_SET_REF _ANIOC(AN_LMP92001_FIRST + 2) #define ANIOC_LMP92001_ADC_ENABLE _ANIOC(AN_LMP92001_FIRST + 3) #define ANIOC_LMP92001_ADC_SINGLESHOT_CONV _ANIOC(AN_LMP92001_FIRST + 4) #define ANIOC_LMP92001_ADC_CONTINUOUS_CONV _ANIOC(AN_LMP92001_FIRST + 5) #define ANIOC_LMP92001_ADC_READ_CHANNEL _ANIOC(AN_LMP92001_FIRST + 6) /**************************************************************************** * Public Types ****************************************************************************/ enum lmp92001_ref_e { LMP92001_REF_INTERNAL = 0U, LMP92001_REF_EXTERNAL }; enum lmp92001_adc_enable_e { LMP92001_ADC_EN_CH1 = 1 << 0U, LMP92001_ADC_EN_CH2 = 1 << 1U, LMP92001_ADC_EN_CH3 = 1 << 2U, LMP92001_ADC_EN_CH4 = 1 << 3U, LMP92001_ADC_EN_CH5 = 1 << 4U, LMP92001_ADC_EN_CH6 = 1 << 5U, LMP92001_ADC_EN_CH7 = 1 << 6U, LMP92001_ADC_EN_CH8 = 1 << 7U, LMP92001_ADC_EN_CH9 = 1 << 8U, LMP92001_ADC_EN_CH10 = 1 << 9U, LMP92001_ADC_EN_CH11 = 1 << 10U, LMP92001_ADC_EN_CH12 = 1 << 11U, LMP92001_ADC_EN_CH13 = 1 << 12U, LMP92001_ADC_EN_CH14 = 1 << 13U, LMP92001_ADC_EN_CH15 = 1 << 14U, LMP92001_ADC_EN_CH16 = 1 << 15U, LMP92001_ADC_EN_CH17 = 1 << 16U, LMP92001_ADC_EN_ALL = 0x1ffffu }; /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /**************************************************************************** * Name: lmp92001_gpio_initialize * * Description: * Instantiate and configure the LMP92001 device driver to use the provided * I2C device instance. * * Input Parameters: * i2c - An I2C driver instance * minor - The device i2c address * * Returned Value: * An ioexpander_dev_s instance on success, NULL on failure. * ****************************************************************************/ struct i2c_master_s; /* Forward reference */ struct ioexpander_dev_s; /* Forward reference */ FAR struct ioexpander_dev_s * lmp92001_gpio_initialize(FAR struct i2c_master_s *i2c, uint8_t addr); #endif /* __INCLUDE_NUTTX_ANALOG_LMP92001_H */
1,575
854
__________________________________________________________________________________________________ sample 28 ms submission class Solution: def addStrings(self, num1: str, num2: str) -> str: a = self.str2int(num1) b = self.str2int(num2) return str(a + b) def str2int(self, num): return int(num) __________________________________________________________________________________________________ sample 13012 kb submission class Solution: def addStrings(self, num1: str, num2: str) -> str: return str(int(num1)+int(num2)) __________________________________________________________________________________________________
179
938
<filename>src/main/java/slimeknights/tconstruct/smeltery/block/controller/AlloyerBlock.java package slimeknights.tconstruct.smeltery.block.controller; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.particles.ParticleTypes; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockReader; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import slimeknights.mantle.util.TileEntityHelper; import slimeknights.tconstruct.library.utils.Util; import slimeknights.tconstruct.smeltery.tileentity.controller.AlloyerTileEntity; import java.util.Random; public class AlloyerBlock extends TinyMultiblockControllerBlock { public AlloyerBlock(Properties builder) { super(builder); } @Override public TileEntity createTileEntity(BlockState blockState, IBlockReader iBlockReader) { return new AlloyerTileEntity(); } @Override public void neighborChanged(BlockState state, World world, BlockPos pos, Block blockIn, BlockPos fromPos, boolean isMoving) { Direction direction = Util.directionFromOffset(pos, fromPos); if (direction != Direction.DOWN) { TileEntityHelper.getTile(AlloyerTileEntity.class, world, pos).ifPresent(te -> te.neighborChanged(direction)); } } /* * Display */ @Deprecated @Override @OnlyIn(Dist.CLIENT) public float getAmbientOcclusionLightValue(BlockState state, IBlockReader worldIn, BlockPos pos) { return 1.0F; } @Override public boolean propagatesSkylightDown(BlockState state, IBlockReader reader, BlockPos pos) { return true; } @Override public void animateTick(BlockState state, World world, BlockPos pos, Random rand) { if (state.get(ACTIVE)) { double x = pos.getX() + 0.5D; double y = (double) pos.getY() + (rand.nextFloat() * 4F) / 16F; double z = pos.getZ() + 0.5D; double frontOffset = 0.52D; double sideOffset = rand.nextDouble() * 0.6D - 0.3D; spawnFireParticles(world, state, x, y, z, frontOffset, sideOffset, ParticleTypes.SOUL_FIRE_FLAME); } } }
743
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.core.tracing.opentelemetry.implementation; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.StatusCode; public final class AmqpTraceUtil { private AmqpTraceUtil() { } /** * Parses an OpenTelemetry Status from AMQP Error Condition. * * @param span the span to set the status for. * @param statusMessage AMQP description for this error condition. * @param throwable the error occurred during response transmission (optional). * @return the corresponding OpenTelemetry {@link Span}. */ public static Span parseStatusMessage(Span span, String statusMessage, Throwable throwable) { if (throwable != null) { span.recordException(throwable); return span.setStatus(StatusCode.ERROR); } if (statusMessage != null && "success".equalsIgnoreCase(statusMessage)) { // No error. return span.setStatus(StatusCode.OK); } if (statusMessage == null) { return span.setStatus(StatusCode.UNSET); } // return status with custom error condition message return span.setStatus(StatusCode.UNSET, statusMessage); } }
477
1,330
/* * 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. */ package com.opensymphony.xwork2.util; import com.opensymphony.xwork2.util.location.Location; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import java.io.StringReader; /** * Test cases for {@link DomHelper}. */ public class DomHelperTest extends TestCase { private String xml = "<!DOCTYPE foo [\n" + "<!ELEMENT foo (bar)>\n" + "<!ELEMENT bar (#PCDATA)>\n" + "]>\n" + "<foo>\n" + " <bar/>\n" + "</foo>\n"; public void testParse() throws Exception { InputSource in = new InputSource(new StringReader(xml)); in.setSystemId("foo://bar"); Document doc = DomHelper.parse(in); assertNotNull(doc); assertTrue("Wrong root node", "foo".equals(doc.getDocumentElement().getNodeName())); NodeList nl = doc.getElementsByTagName("bar"); assertTrue(nl.getLength() == 1); } public void testGetLocationObject() throws Exception { InputSource in = new InputSource(new StringReader(xml)); in.setSystemId("foo://bar"); Document doc = DomHelper.parse(in); NodeList nl = doc.getElementsByTagName("bar"); Location loc = DomHelper.getLocationObject((Element)nl.item(0)); assertNotNull(loc); assertTrue("Should be line 6, was "+loc.getLineNumber(), 6==loc.getLineNumber()); } }
1,008
369
/********************* (C) COPYRIGHT 2007 RAISONANCE S.A.S. *******************/ /** * * @file circle_api.h * @brief General header for the STM32-circle projects. * @author FL * @date 07/2007 * @version 1.2 * @date 10/2007 * @version 1.5 types of OutX_F64 and OutX_F256 changed to u32 (same for Y and Z) * @date 10/2007 * @version 1.6 Add the IRQ handler replacement * * It contains the list of the utilities functions organized by sections * (MEMS, LCD, POINTER, ...) * **/ /******************************************************************************* * * Use this header with version 1.5 or later of the OS. * * For a complete documentation on the CircleOS, please go to: * http://www.stm32circle.com * *******************************************************************************/ #include "stm32f10x_lib.h" /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __CIRCLE_API_H #define __CIRCLE_API_H //-------------------------------- General ------------------------------------- /** * @enum eSpeed * @brief Clock speeds. * * Available clock speeds. **/ extern enum eSpeed { SPEED_VERY_LOW = 1, SPEED_LOW = 2, SPEED_MEDIUM = 3, SPEED_HIGH = 4, SPEED_VERY_HIGH = 5 } CurrentSpeed; enum eSchHandler { LED_SCHHDL_ID = 0, BUTTON_SCHHDL_ID = 1, BUZZER_SCHHDL_ID = 2, MENU_SCHHDL_ID = 3, POINTER_SCHHDL_ID = 4, LCD_SCHHDL_ID = 5, DRAW_SCHHDL_ID = 6, RTC_SCHHDL_ID = 7, UNUSED0_SCHHDL_ID = 8, UNUSED1_SCHHDL_ID = 9, UNUSED2_SCHHDL_ID = 10, UNUSED3_SCHHDL_ID = 11, UNUSED4_SCHHDL_ID = 12, UNUSED5_SCHHDL_ID = 13, UNUSED6_SCHHDL_ID = 14, UNUSED7_SCHHDL_ID = 15 }; /// @cond Internal extern RCC_ClocksTypeDef RCC_ClockFreq; /* Typedefs ------------------------------------------------------------------*/ typedef u32 (*tCircleFunc0 ) (void); typedef u32 (*tCircleFunc1 ) (u32 param1); typedef u32 (*tCircleFunc2 ) (u32 param1, u32 param2); typedef u32 (*tCircleFunc3 ) (u32 param1, u32 param2, u32 param3); typedef u32 (*tCircleFunc4 ) (u32 param1, u32 param2, u32 param3, u32 param4); typedef u32 (*tCircleFunc5 ) (u32 param1, u32 param2, u32 param3, u32 param4, u32 param5); typedef u32 (*tCircleFunc6 ) (u32 param1, u32 param2, u32 param3, u32 param4, u32 param5, u32 param6); extern tCircleFunc0 (*ptrCircle_API) []; /* Defines -------------------------------------------------------------------*/ #define Circle_API (*ptrCircle_API) #define POINTER_ID 0x00 #define DRAW_ID 0x20 #define LCD_ID 0x40 #define LED_ID 0x60 #define MEMS_ID 0x70 #define BUTTON_ID 0x80 #define BUZZER_ID 0x90 #define MENU_ID 0xA0 #define UTIL_ID 0xB0 #define RTC_ID 0xC0 // UTIL functions definition. #define UTIL_SET_PLL_ID (UTIL_ID + 0) // Set clock frequency. #define UTIL_GET_PLL_ID (UTIL_ID + 1) // Get clock frequency. #define UTIL_UINT2STR_ID (UTIL_ID + 2) // Convert an unsigned integer into a string. #define UTIL_INT2STR_ID (UTIL_ID + 3) // Convert a signed integer into a string. #define UTIL_GET_VERSION_ID (UTIL_ID + 4) // Get CircleOS version. #define UTIL_READ_BACKUPREGISTER_ID (UTIL_ID + 5) // Reads data from the specified Data Backup Register. #define UTIL_WRITE_BACKUPREGISTER_ID (UTIL_ID + 6) // Writes data to the specified Data Backup Register. #define UTIL_GET_BAT_ID (UTIL_ID + 7) // Return the batterie tension in mV. #define UTIL_GET_USB_ID (UTIL_ID + 8) // Return the USB connexion state. #define UTIL_SET_IRQ_HANDLER_ID (UTIL_ID + 9) // Replace an irq handler #define UTIL_GET_IRQ_HANDLER_ID (UTIL_ID + 10) // Get the current irq handler #define UTIL_SET_SCH_HANDLER_ID (UTIL_ID + 11) // Replace an irq handler #define UTIL_GET_SCH_HANDLER_ID (UTIL_ID + 12) // Get the current irq handler #define UTIL_GET_TEMP_ID (UTIL_ID + 13) // Return the temperature (1/100 C) #define UTIL_SET_TEMPMODE_ID (UTIL_ID + 14) // Set the temperature mode (0: mCelcius, 1: mFahrenheit typedef void (*tHandler) (void); // Prototypes. #define UTIL_SetPll(a) ((tCircleFunc1)(Circle_API [UTIL_SET_PLL_ID])) ((u32)(a)) // void UTIL_SetPll( enum eSpeed speed ); #define UTIL_GetPll() (u32) (((tCircleFunc0)(Circle_API [UTIL_GET_PLL_ID])) ()) // enum eSpeed UTIL_GetPll( void ); #define UTIL_uint2str(a,b,c,d) ((tCircleFunc4)(Circle_API [UTIL_UINT2STR_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d)) // void uint2str( char* ptr , u32 X, u16 digit, int fillwithzero ); #define UTIL_int2str(a,b,c,d) ((tCircleFunc4)(Circle_API [UTIL_INT2STR_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d)) // void int2str( char* ptr , s32 X, u16 digit, int fillwithzero ); #define UTIL_GetVersion() (u32) (((tCircleFunc0)(Circle_API [UTIL_GET_VERSION_ID])) ()) // char* UTIL_GetVersion( void ); #define UTIL_ReadBackupRegister(a) (u32) (((tCircleFunc1)(Circle_API [UTIL_READ_BACKUPREGISTER_ID])) ((u32)(a))) // u16 UTIL_ReadBackupRegister( u16 BKP_DR ); #define UTIL_WriteBackupRegister(a,b) ((tCircleFunc2)(Circle_API [UTIL_WRITE_BACKUPREGISTER_ID])) ((u32)(a),(u32)(b)) // void UTIL_WriteBackupRegister( u16 BKP_DR, u16 Data ); #define UTIL_GetBat() (u32) (((tCircleFunc0)(Circle_API [UTIL_GET_BAT_ID])) ()) // u16 UTIL_GetBat( void ); #define UTIL_GetUsb() (u32) (((tCircleFunc0)(Circle_API [UTIL_GET_USB_ID])) ()) // u8 UTIL_GetUsb( void ); #define UTIL_SetIrqHandler(a,b) (((tCircleFunc2)(Circle_API [UTIL_SET_IRQ_HANDLER_ID])) ((int)a,(tHandler)b)) // void UTIL_SetIrqHandler ( int , tHandler ); #define UTIL_GetIrqHandler(a) (u32) (((tCircleFunc1)(Circle_API [UTIL_GET_IRQ_HANDLER_ID])) ((int)a)) // tHandler* UTIL_GetIrqHandler ( int ); #define UTIL_SetSchHandler(a,b) (((tCircleFunc2)(Circle_API [UTIL_SET_SCH_HANDLER_ID])) ((int)a,(tHandler)b)) // void UTIL_SetSchHandler ( int , tHandler ); #define UTIL_GetSchHandler(a) (u32) (((tCircleFunc1)(Circle_API [UTIL_GET_SCH_HANDLER_ID])) ((int)a)) // tHandler* UTIL_GetSchHandler ( int ); #define UTIL_GetTemp() (u32) (((tCircleFunc0)(Circle_API [UTIL_GET_TEMP_ID])) ()) // u16 UTIL_GetTemp( void ); #define UTIL_SetTempMode(a) (((tCircleFunc1)(Circle_API [UTIL_SET_TEMPMODE_ID])) ((int)a)) // void UTIL_SetTempMode( int mode ); /// @endcond //--------------------------------- MEMS ------------------------------------ /* Exported types ------------------------------------------------------------*/ /** * @enum Rotate_H12_V_Match_TypeDef * @brief The 4 possible rotations. * * The 4 possible MEM rotations. **/ typedef enum { V12 = 0, /*!< No rotation. */ V3 = 1, /*!< Rotation to the right.*/ V6 = 2, /*!< Rotation to the left. */ V9 = 3 /*!< Half a rotation. */ } Rotate_H12_V_Match_TypeDef; /** * @struct tMEMS_Info * @brief MEMS state description. **/ typedef struct { s16 OutX; /*!< MEMS X position. */ s16 OutX_F4; /*!< MEMS X position filtered on 4 values. */ s16 OutX_F16; /*!< MEMS X position filtered on 16 values. */ s32 OutX_F64; /*!< MEMS X position filtered on 64 values. */ s32 OutX_F256; /*!< MEMS X position filtered on 256 values. */ s16 OutY; /*!< MEMS Y position. */ s16 OutY_F4; /*!< MEMS Y position filtered on 4 values. */ s16 OutY_F16; /*!< MEMS Y position filtered on 16 values. */ s32 OutY_F64; /*!< MEMS Y position filtered on 64 values. */ s32 OutY_F256; /*!< MEMS Y position filtered on 256 values. */ s16 OutZ; /*!< MEMS Z position. */ s16 OutZ_F4; /*!< MEMS Z position filtered on 4 values. */ s16 OutZ_F16; /*!< MEMS Z position filtered on 16 values. */ s32 OutZ_F64; /*!< MEMS Z position filtered on 64 values. */ s32 OutZ_F256; /*!< MEMS Z position filtered on 256 values. */ s16 Shocked; /*!< MEMS shock counter (incremented...) */ s16 RELATIVE_X; /*!< MEMS relative X position. */ s16 RELATIVE_Y; /*!< MEMS relative Y position. */ s16 DoubleClick; /*!< MEMS DoubleClick counter(incremented...)*/ } tMEMS_Info; /// @cond Internal /* Exported defines ----------------------------------------------------------*/ // MEMS functions definition #define MEMS_GET_POSITION_ID (MEMS_ID + 0) // Return the current (relative) Mems information #define MEMS_GET_ROTATION_ID (MEMS_ID + 1) // Return the current screen orientation of the circle #define MEMS_SET_NEUTRAL_ID (MEMS_ID + 2) // Set the current position as "neutral position" #define MEMS_GET_INFO_ID (MEMS_ID + 3) // Return Mems informations // Prototypes #define MEMS_GetPosition(a,b) ((tCircleFunc2)(Circle_API [MEMS_GET_POSITION_ID])) ((u32)(a),(u32)(b)) // void MEMS_GetPosition(s16 * pX, s16* pY); #define MEMS_GetRotation(a) ((tCircleFunc1)(Circle_API [MEMS_GET_ROTATION_ID])) ((u32)(a)) // void MEMS_GetRotation(Rotate_H12_V_Match_TypeDef * H12); #define MEMS_SetNeutral() ((tCircleFunc0)(Circle_API [MEMS_GET_ROTATION_ID])) () // void MEMS_SetNeutral( void ); #define MEMS_GetInfo() ( (tMEMS_Info*) (((tCircleFunc0)(Circle_API [MEMS_GET_INFO_ID])) ())) // tMEMS_Info* MEMS_GetInfo (void) /// @endcond //-------------------------------- POINTER ---------------------------------- /* Exported types ------------------------------------------------------------*/ /** * @enum POINTER_mode * @brief Available pointer modes. * * Description of all the available pointer modes in CircleOS. **/ enum POINTER_mode { POINTER_UNDEF = -1, /*!< Pointer's mode is unknown! */ POINTER_OFF = 0, /*!< Pointer isn't managed and displayed. */ POINTER_ON = 1, /*!< Pointer mode used in main screen. */ POINTER_MENU = 2, /*!< Pointer management is used to select item menu (but pointer isn't displayed). */ POINTER_APPLICATION = 3, /*!< The managment of pointer depend of extern application. */ POINTER_RESTORE_LESS = 4 /*!< The background isn't restored (to go faster). */ }; /** * @enum POINTER_state * @brief The different pointer modes. * * Despite beeing in a undefined state, the pointer can be disabled or enable. **/ enum POINTER_state { POINTER_S_UNDEF = -1, /*!< Pointer state is unknown! */ POINTER_S_DISABLED = 0, /*!< Pointer is disabled. */ POINTER_S_ENABLED = 1 /*!< Pointer is enabled. */ }; /** * @struct tPointer_Info * @brief Pointer position description. **/ typedef struct { s16 xPos; /*!< X position of pointer. */ s16 yPos; /*!< Y position of pointer. */ s16 shift_PosX; /*!< Pointer speed on X axis. */ s16 shift_PosY; /*!< Pointer speed on Y axis */ s16 X_PosMin; /*!< Minimum position on X axis. */ s16 Y_PosMin; /*!< Minimum position on Y axis. */ s16 X_PosMax; /*!< Maximum position on X axis. */ s16 Y_PosMax; /*!< Maximum position on Y axis. */ } tPointer_Info; /// @cond Internal /* Exported defines ---------------------------------------------------------*/ #define POINTER_WIDTH 7 // POINTER functions definition #define POINTER_SET_RECT_ID (POINTER_ID + 0) // Set new limits for the move of the pointer #define POINTER_SETRECTSCREEN_ID (POINTER_ID + 1) // Remove any space restriction for the pointer moves. #define POINTER_GETCURRENTANGLESTART_ID (POINTER_ID + 2) // Return the current minimum angle to move pointer #define POINTER_SETCURRENTANGLESTART_ID (POINTER_ID + 3) // Set the current minimum angle to move pointer #define POINTER_GETCURRENTSPEEDONANGLE_ID (POINTER_ID + 4) // Return the ratio speed / angle #define POINTER_SETCURRENTSPEEDONANGLE_ID (POINTER_ID + 5) // Set the ratio speed / angle #define POINTER_SETMODE_ID (POINTER_ID + 6) // Change the current mode of the pointer management #define POINTER_GETMODE_ID (POINTER_ID + 7) // Return the current mode of the pointer management #define POINTER_SETCURRENTPOINTER_ID (POINTER_ID + 8) // Set the dimention and bitmap of pointer #define POINTER_GETSTATE_ID (POINTER_ID + 9) // Return the current state #define POINTER_DRAW_ID (POINTER_ID + 10) // Draw a pointer #define POINTER_SAVE_ID (POINTER_ID + 11) // Save the background of the pointer #define POINTER_RESTORE_ID (POINTER_ID + 12) // Restore the background of the pointer #define POINTER_GETPOSITION_ID (POINTER_ID + 13) // Return the poistion of the cursor (x=lower byte, y = upperbyte) #define POINTER_SETPOSITION_ID (POINTER_ID + 14) // Force the position of the pointer in the screen #define POINTER_SETAPPLICATION_POINTER_MGR_ID (POINTER_ID + 15) // Set the application pointer manager #define POINTER_SETCOLOR_ID (POINTER_ID + 16) // Set pointer color #define POINTER_GETCOLOR_ID (POINTER_ID + 17) // Return pointer color #define POINTER_GETINFO_ID (POINTER_ID + 18) // Return pointer informations #define POINTER_SET_CURRENT_AREASTORE_ID (POINTER_ID + 19) // Change the current storage area // Prototypes #define POINTER_SetRect(a,b,c,d) ((tCircleFunc4)(Circle_API [POINTER_SET_RECT_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d)) //void POINTER_SetRect ( s16 x, s16 y, s16 width, s16 height ); //Restrict the move of the pointer to a rectangle #define POINTER_SetRectScreen() ((tCircleFunc0)(Circle_API [POINTER_SETRECTSCREEN_ID])) () //void POINTER_SetRectScreen ( void ); #define POINTER_GetCurrentAngleStart() (u16) (((tCircleFunc0)(Circle_API [POINTER_GETCURRENTANGLESTART_ID])) ()) //u16 POINTER_GetCurrentAngleStart ( void ); #define POINTER_SetCurrentAngleStart(a) ((tCircleFunc1)(Circle_API [POINTER_SETCURRENTANGLESTART_ID])) ((u32)(a)) //void POINTER_SetCurrentAngleStart ( u16 ); #define POINTER_GetCurrentSpeedOnAngle() (u16) (((tCircleFunc0)(Circle_API [POINTER_GETCURRENTSPEEDONANGLE_ID])) ()) //u16 POINTER_GetCurrentSpeedOnAngle ( void ); #define POINTER_SetCurrentSpeedOnAngle(a) ((tCircleFunc1)(Circle_API [POINTER_SETCURRENTSPEEDONANGLE_ID])) ((u32)(a)) //void POINTER_SetCurrentSpeedOnAngle ( u16 newspeed ); #define POINTER_SetMode(a) ((tCircleFunc1)(Circle_API [POINTER_SETMODE_ID])) ((u32)(a)) //void POINTER_SetMode( enum POINTER_mode mode); #define POINTER_GetMode() (enum POINTER_mode) (((tCircleFunc0)(Circle_API [POINTER_GETMODE_ID])) ()) //enum POINTER_mode POINTER_GetMode( void ); #define POINTER_SetCurrentPointer(a,b,c) ((tCircleFunc3)(Circle_API [POINTER_SETCURRENTPOINTER_ID])) ((u32)(a),(u32)(b),(u32)(c)) //void POINTER_SetCurrentPointer( unsigned char width, unsigned char height, unsigned char *bmp); #define POINTER_GetState() (enum POINTER_state) (((tCircleFunc0)(Circle_API [POINTER_GETSTATE_ID])) ()) //enum POINTER_state POINTER_GetState(void); #define POINTER_Draw(a,b,c,d,e) ((tCircleFunc5)(Circle_API [POINTER_DRAW_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d),(u32)(e)) //void POINTER_Draw (u8 Line, u8 Column, u8 Width, u8 Height, u8 *Bmp); #define POINTER_Save(a,b,c,d) ((tCircleFunc4)(Circle_API [POINTER_SAVE_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d)) //void POINTER_Save (u8 Line, u8 Column, u8 Width, u8 Height); #define POINTER_Restore(a,b,c,d) ((tCircleFunc4)(Circle_API [POINTER_RESTORE_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d)) //void POINTER_Restore (u8 Line, u8 Column, u8 Width, u8 Height); #define POINTER_GetPos() (u16) (((tCircleFunc0)(Circle_API [POINTER_GETPOSITION_ID])) ()) //u16 POINTER_GetPos(void); #define POINTER_SetPos(a,b) ((tCircleFunc2)(Circle_API [POINTER_SETPOSITION_ID])) ((u32)(a),(u32)(b)) //void POINTER_SetPos ( u16 x, u16 y ); #define POINTER_SetApplication_Pointer_Mgr(a) ((tCircleFunc1)(Circle_API [POINTER_SETAPPLICATION_POINTER_MGR_ID])) ((u32)(a)) //void POINTER_SetApplication_Pointer_Mgr( tAppPtrMgr mgr ); #define POINTER_SetColor(a) ((tCircleFunc1)(Circle_API [POINTER_SETCOLOR_ID])) ((u32)(a)) //void POINTER_SetColor ( u16 color ) #define POINTER_GetColor() (u16) (((tCircleFunc0)(Circle_API [POINTER_GETCOLOR_ID])) ()) //u16 POINTER_GetColor ( void ) #define POINTER_GetInfo() (tPointer_Info*) (((tCircleFunc0)(Circle_API [POINTER_GETINFO_ID])) ()) //tPointer_Info* POINTER_GetInfo ( void ) #define POINTER_SetCurrentAreaStore(a) ((tCircleFunc1)(Circle_API [POINTER_SET_CURRENT_AREASTORE_ID])) ((u32)(a)) //void POINTER_SetCurrentAreaStore ( u8 *ptr ) /// @endcond //-------------------------------- BUTTON ----------------------------------- /* Exported types ------------------------------------------------------------*/ /** * @enum BUTTON_mode * @brief Available button modes. * * List of all the available button mode in the CircleOS. **/ enum BUTTON_mode { BUTTON_DISABLED = -1, /*!< No action on the button is detected. */ BUTTON_ONOFF = 0, /*!< Detect ON/OFF pression type. */ BUTTON_ONOFF_FORMAIN = 1, /*!< Special mode for main screen. */ BUTTON_WITHCLICK = 2 /*!< Currently unused. */ }; /** * @enum BUTTON_state * @brief CircleOS button states. * * Description of the button states provided by CircleOS. **/ enum BUTTON_state { BUTTON_UNDEF = -1, /*!< Undefined state. */ BUTTON_RELEASED = 0, /*!< Button is released. */ BUTTON_PUSHED = 1, /*!< Button was just pushed. */ BUTTON_PUSHED_FORMAIN = 2, /*!< Same as BUTTON_PUSHED when button mode is BUTTON_ONOFF_FORMAIN. */ BUTTON_CLICK = 3, /*!< Currently unused. */ BUTTON_DBLCLICK = 4 /*!< Currently unused. */ }; /// @cond Internal /* Exported defines ----------------------------------------------------------*/ // BUTTON functions definition #define BUTTON_GETSTATE_ID (BUTTON_ID + 0) // Return state of button #define BUTTON_SETMODE_ID (BUTTON_ID + 1) // Set button mode #define BUTTON_GETMODE_ID (BUTTON_ID + 2) // Return button mode #define BUTTON_WAITFORRELEASE_ID (BUTTON_ID + 3) // Disable temporarily any new button event // Prototypes #define BUTTON_GetState() (enum BUTTON_state) (((tCircleFunc0)(Circle_API [BUTTON_GETSTATE_ID])) ()) // enum BUTTON_state BUTTON_GetState(void); #define BUTTON_SetMode(a); ((tCircleFunc1)(Circle_API [BUTTON_SETMODE_ID])) ((u32)(a)) // void BUTTON_SetMode( enum BUTTON_mode mode); #define BUTTON_GetMode(); (enum BUTTON_mode) (((tCircleFunc0)(Circle_API [BUTTON_GETMODE_ID])) ()) // enum BUTTON_mode BUTTON_GetMode ( void ) ; #define BUTTON_WaitForRelease() ((tCircleFunc0)(Circle_API [BUTTON_WAITFORRELEASE_ID])) () // void BUTTON_WaitForRelease(void); /// @endcond //---------------------------------- LCD ----------------------------------- /* Exported defines ----------------------------------------------------------*/ // RGB is 16-bit coded as G2G1G0B4 B3B2B1B0 R4R3R2R1 R0G5G4G3 #define RGB_MAKE(xR,xG,xB) ( ( (xG&0x07)<<13 ) + ( (xG)>>5 ) + \ ( ((xB)>>3) << 8 ) + \ ( ((xR)>>3) << 3 ) ) /*!< Macro to make a LCD compatible color format from RGB. */ #define RGB_RED 0x00F8 /*!< Predefined color. */ #define RGB_BLACK 0x0000 /*!< Predefined color. */ #define RGB_WHITE 0xffff /*!< Predefined color. */ #define RGB_BLUE 0x1F00 /*!< Predefined color. */ #define RGB_GREEN 0xE007 /*!< Predefined color. */ #define RGB_YELLOW (RGB_GREEN|RGB_RED) /*!< Predefined color. */ #define RGB_MAGENTA (RGB_BLUE|RGB_RED) /*!< Predefined color. */ #define RGB_LIGHTBLUE (RGB_BLUE|RGB_GREEN) /*!< Predefined color. */ #define RGB_ORANGE (RGB_RED | 0xE001) /*!< Predefined color ( Green/2 + red ). */ #define RGB_PINK (RGB_MAGENTA | 0xE001) /*!< Predefined color ( Green/2 + magenta ). */ // PWM rates. #define BACKLIGHTMIN 0x1000 /*!< Minimal PWM rate. */ #define DEFAULT_CCR_BACKLIGHTSTART 0x8000 /*!< Default PWM rate. */ // SCREEN Infos #define SCREEN_WIDTH 128 /*!< Width of visible screen in pixels. */ #define SCREEN_HEIGHT 128 /*!< Height of visible screen in pixels. */ #define CHIP_SCREEN_WIDTH 132 /*!< Width of screen driven by LCD controller in pixels. */ #define CHIP_SCREEN_HEIGHT 132 /*!< Height of screen driven by LCD controller in pixels. */ // Characters Infos #define CHAR_WIDTH 7 /*!< Width of a character. */ #define CHAR_HEIGHT 14 /*!< Height of a character. */ /// @cond Internal // LCD functions definition #define LCD_SETRECTFORCMD_ID (LCD_ID + 0) // Define the rectangle (for the next command to be applied) #define LCD_GETPIXEL_ID (LCD_ID + 1) // Read the value of one pixel #define LCD_DRAWPIXEL_ID (LCD_ID + 2) // Draw a Graphic image on slave LCD. #define LCD_SENDLCDCMD_ID (LCD_ID + 3) // Send one byte command to LCD LCD. #define LCD_SENDLCDDATA_ID (LCD_ID + 4) // Display one byte data to LCD LCD. #define LCD_READLCDDATA_ID (LCD_ID + 5) // Read LCD byte data displayed on LCD LCD. #define LCD_FILLRECT_ID (LCD_ID + 6) // Fill a rectangle with one color #define LCD_DRAWRECT_ID (LCD_ID + 7) // Draw a rectangle with one color #define LCD_DISPLAYCHAR_ID (LCD_ID + 8) // Display one character #define LCD_RECTREAD_ID (LCD_ID + 9) // Save a rectangle of the monitor RAM #define LCD_SETBACKLIGHT_ID (LCD_ID + 10) // Modify the PWM rate #define LCD_GETBACKLIGHT_ID (LCD_ID + 11) // Return the PWM rate #define LCD_SETROTATESCREEN_ID (LCD_ID + 12) // Enable/Disable screen rotation #define LCD_GETROTATESCREEN_ID (LCD_ID + 13) // Return screen rotation mode #define LCD_SETSCREENORIENTATION_ID (LCD_ID + 14) // Set screen orientation #define LCD_GETSCREENORIENTATION_ID (LCD_ID + 15) // Return screen orientation #define LCD_SETBACKLIGHT_OFF_ID (LCD_ID + 16) // Switch the LCD back light off. #define LCD_SETBACKLIGHT_ON_ID (LCD_ID + 17) // Switch the LCD back light on. // Prototypes #define LCD_SetRect_For_Cmd(a,b,c,d) ((tCircleFunc4)(Circle_API [LCD_SETRECTFORCMD_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d)) //void LCD_SetRect_For_Cmd ( s16 x, s16 y, s16 width, s16 height) #define LCD_GetPixel(a,b) (u16) (((tCircleFunc2)(Circle_API [LCD_GETPIXEL_ID])) ((u32)(a),(u32)(b))) //u16 LCD_GetPixel (u8 x, u8 y) #define LCD_DrawPixel(a,b,c) ((tCircleFunc3)(Circle_API [LCD_DRAWPIXEL_ID])) ((u32)(a),(u32)(b),(u32)(c)) //void LCD_SetPixel (u8 x, u8 y, u16 Pixel) ; #define LCD_SendLCDCmd(a) ((tCircleFunc1)(Circle_API [LCD_SENDLCDCMD_ID])) ((u32)(a)) //void LCD_SendLCDCmd(u8 Cmd); #define LCD_SendLCDData(a) ((tCircleFunc1)(Circle_API [LCD_SENDLCDDATA_ID])) ((u32)(a)) //void LCD_SendLCDData(u8 Data); #define LCD_ReadLCDData() (u32) (((tCircleFunc0)(Circle_API [LCD_READLCDDATA_ID])) ()) //u32 LCD_ReadLCDData(void); #define LCD_FillRect(a,b,c,d,e) ((tCircleFunc5)(Circle_API [LCD_FILLRECT_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d),(u32)(e)) //void LCD_FillRect ( u16 x, u16 y, u16 width, u16 height, u16 color ); #define LCD_DrawRect(a,b,c,d,e) ((tCircleFunc5)(Circle_API [LCD_DRAWRECT_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d),(u32)(e)) //void LCD_DrawRect ( u16 x, u16 y, u16 width, u16 height, u16 color ); #define LCD_DisplayChar(a,b,c,d,e,f) ((tCircleFunc6)(Circle_API [LCD_DISPLAYCHAR_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d),(u32)(e),(u32)(f)) //void LCD_DisplayChar(u8 x, u8 y, u8 Ascii, u16 TextColor, u16 BGndColor, u16 CharMagniCoeff); #define LCD_RectRead(a,b,c,d,e) ((tCircleFunc5)(Circle_API [LCD_RECTREAD_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d),(u32)(e)) //void LCD_RectRead ( u16 x, u16 y, u16 width, u16 height, u8* bmp ); #define LCD_SetBackLight(a) ((tCircleFunc1)(Circle_API [LCD_SETBACKLIGHT_ID])) ((u32)(a)) //void LCD_SetBackLight(u32 newBaclightStart); #define LCD_GetBackLight() (u32) (((tCircleFunc0)(Circle_API [LCD_GETBACKLIGHT_ID])) ()) //u32 LCD_GetBackLight(void); #define LCD_SetRotateScreen(a) ((tCircleFunc1)(Circle_API [LCD_SETROTATESCREEN_ID])) ((u32)(a)) //void LCD_SetRotateScreen ( u8 RotateScreen) #define LCD_GetRotateScreen() (u32) (((tCircleFunc0)(Circle_API [LCD_GETROTATESCREEN_ID])) ()) //u8 LCD_GetRotateScreen (void) #define LCD_SetScreenOrientation(a) ((tCircleFunc1)(Circle_API [LCD_SETSCREENORIENTATION_ID])) ((u32)(a)) //void LCD_SetScreenOrientation (Rotate_H12_V_Match_TypeDef ScreenOrientation) #define LCD_GetScreenOrientation() (u32) (((tCircleFunc0)(Circle_API [LCD_GETSCREENORIENTATION_ID])) ()) //Rotate_H12_V_Match_TypeDef LCD_GetScreenOrientation (void) #define LCD_SetBackLightOff() ((tCircleFunc0)(Circle_API [LCD_SETBACKLIGHT_OFF_ID])) () #define LCD_SetBackLightOn() ((tCircleFunc0)(Circle_API [LCD_SETBACKLIGHT_ON_ID])) () /// @endcond //---------------------------------- DRAW ---------------------------------- /// @cond Internal /* Exported defines ----------------------------------------------------------*/ // DRAW functions definition #define DRAW_SETDEFAULTCOLOR_ID (DRAW_ID + 0) // Reset colors (bgnd + text) #define DRAW_CLEAR_ID (DRAW_ID + 1) // Clear the LCD display #define DRAW_SETIMAGE_ID (DRAW_ID + 2) // Draw a colored image #define DRAW_SETIMAGEBW_ID (DRAW_ID + 3) // Draw a black and white image #define DRAW_SETLOGOBW_ID (DRAW_ID + 4) // Draw logo #define DRAW_DISPLAYVBAT_ID (DRAW_ID + 5) // Display the voltage of battery in ascii #define DRAW_DISPLAYTIME_ID (DRAW_ID + 6) // Display time in ascii #define DRAW_DISPLAYSTRING_ID (DRAW_ID + 7) // Display a 17char max string of characters #define DRAW_DISPLAYSTRINGINVERTED_ID (DRAW_ID + 8) // Display a 17char max string of characters with inverted colors #define DRAW_GETCHARMAGNICOEFF_ID (DRAW_ID + 9) // Return the magnifying value for the characters #define DRAW_SETCHARMAGNICOEFF_ID (DRAW_ID + 10) // Set the magnifying value for the characters #define DRAW_GETTEXTCOLOR_ID (DRAW_ID + 11) // Return the current text color #define DRAW_SETTEXTCOLOR_ID (DRAW_ID + 12) // Set the current text color #define DRAW_GETBGNDCOLOR_ID (DRAW_ID + 13) // Return the current background color #define DRAW_SETBGNDCOLOR_ID (DRAW_ID + 14) // Set the current background color #define DRAW_LINE_ID (DRAW_ID + 15) // Draw a Line between (using Bresenham algorithm) //Prototypes #define DRAW_SetDefaultColor() ((tCircleFunc0)(Circle_API [DRAW_SETDEFAULTCOLOR_ID])) () //void DRAW_SetDefaultColor (void); #define DRAW_Clear() ((tCircleFunc0)(Circle_API [DRAW_CLEAR_ID])) () //void DRAW_Clear(void); #define DRAW_SetImage(a,b,c,d,e) ((tCircleFunc5)(Circle_API [DRAW_SETIMAGE_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d),(u32)(e)) //void DRAW_SetImage(const u16 *imageptr, u8 x, u8 y, u8 width, u8 height); #define DRAW_SetImageBW(a,b,c,d,e) ((tCircleFunc5)(Circle_API [DRAW_SETIMAGEBW_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d),(u32)(e)) //void DRAW_SetImageBW(const u8 *imageptr, u8 x, u8 y, u8 width, u8 height); #define DRAW_SetLogoBW() ((tCircleFunc0)(Circle_API [DRAW_SETLOGOBW_ID])) () //void DRAW_SetLogoBW(void); #define DRAW_DisplayVbat(a,b) ((tCircleFunc2)(Circle_API [DRAW_DISPLAYVBAT_ID])) ((u32)(a),(u32)(b)) //void DRAW_DisplayVbat(u8 x, u8 y); #define DRAW_DisplayTime(a,b) ((tCircleFunc2)(Circle_API [DRAW_DISPLAYTIME_ID])) ((u32)(a),(u32)(b)) //void DRAW_DisplayTime(u8 x, u8 y); #define DRAW_DisplayString(a,b,c,d) ((tCircleFunc4)(Circle_API [DRAW_DISPLAYSTRING_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d)) //void DRAW_DisplayString( u8 x, u8 y, u8 *ptr, u8 len ); #define DRAW_DisplayStringInverted(a,b,c,d) ((tCircleFunc4)(Circle_API [DRAW_DISPLAYSTRINGINVERTED_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d)) //void DRAW_DisplayStringInverted( u8 x, u8 y, u8 *ptr, u8 len ); #define DRAW_GetCharMagniCoeff() (u16) (((tCircleFunc0)(Circle_API [DRAW_GETCHARMAGNICOEFF_ID])) ()) //u16 DRAW_GetCharMagniCoeff(void); #define DRAW_SetCharMagniCoeff(a) ((tCircleFunc1)(Circle_API [DRAW_SETCHARMAGNICOEFF_ID])) ((u32)(a)) //void DRAW_SetCharMagniCoeff(u16 Coeff); #define DRAW_GetTextColor() (u16) (((tCircleFunc0)(Circle_API [DRAW_GETTEXTCOLOR_ID])) ()) //u16 DRAW_GetTextColor(void); #define DRAW_SetTextColor(a) ((tCircleFunc1)(Circle_API [DRAW_SETTEXTCOLOR_ID])) ((u32)(a)) //void DRAW_SetTextColor(u16 Color); #define DRAW_GetBGndColor() (u16) (((tCircleFunc0)(Circle_API [DRAW_GETBGNDCOLOR_ID])) ()) //u16 DRAW_GetBGndColor(void); #define DRAW_SetBGndColor(a) ((tCircleFunc1)(Circle_API [DRAW_SETBGNDCOLOR_ID])) ((u32)(a)) //void DRAW_SetBGndColor(u16 Color); #define DRAW_Line(a,b,c,d,e) ((tCircleFunc5)(Circle_API [DRAW_LINE_ID])) ((u32)(a),(u32)(b),(u32)(c),(u32)(d),(u32)(e)) //void DRAW_Line(s16 x1, s16 y1, s16 x2, s16 y2, u16 color ); /// @endcond //-------------------------------- BUZZER ----------------------------------- /* Exported type def ---------------------------------------------------------*/ /** * @enum BUZZER_mode * @brief CircleOS buzzer modes. * * Without the undefined mode, the CircleOS provides 5 modes for its buzzer. **/ enum BUZZER_mode { BUZZER_UNDEF = -1, /*!< undefined mode for buzzer */ BUZZER_OFF = 0, /*!< The buzzer is put off. */ BUZZER_ON = 1, /*!< The buzzer is put on. */ BUZZER_SHORTBEEP = 2, /*!< Make buzzer to bip for a short time */ BUZZER_LONGBEEP = 3, /*!< Make buzzer to bip for a long time */ BUZZER_PLAYMUSIC = 4 /*!< Make buzzer to play a music */ }; /// @cond Internal /* Exported defines ----------------------------------------------------------*/ #define BUZZER_BEEP BUZZER_SHORTBEEP // BUZZER functions definition #define BUZZER_SETMODE_ID (BUZZER_ID + 0) // Set new buzzer mode #define BUZZER_GETMODE_ID (BUZZER_ID + 1) // Get the current buzzer mode. #define BUZZER_PLAY_MUSIC_ID (BUZZER_ID + 2) // Plays the provided melody that follows the RTTTL Format. // Prototypes #define BUZZER_SetMode(a) ((tCircleFunc1)(Circle_API [BUZZER_SETMODE_ID])) ((u32)(a)) //void BUZZER_SetMode( enum BUZZER_mode mode); #define BUZZER_GetMode() (enum BUZZER_mode) (((tCircleFunc0)(Circle_API [BUZZER_GETMODE_ID])) ()) //enum BUZZER_mode BUZZER_GetMode( void ); #define BUZZER_PlayMusic(a) ((tCircleFunc1)(Circle_API [BUZZER_PLAY_MUSIC_ID])) ((u32)(a)) //void BUZZER_PlayMusic (const u8 *melody ); /// @endcond //--------------------------------- MENU ----------------------------------- /* Exported defines ----------------------------------------------------------*/ #define REMOVE_MENU 0x01 /*!< Menu flag: remove menu when item selected. */ #define APP_MENU 0x02 /*!< Menu flag: item is an application. */ #define MENU_MAXITEM 8 /*!< Maximum number of item in a menu. */ /* Exported type def ---------------------------------------------------------*/ /** * @struct tMenuItem * @brief Menu item description. **/ typedef struct { const char* Text; /*!< Name of Item displayed in menu */ enum MENU_code (*Fct_Init) ( void ); /*!< First function launched if item is selected. */ enum MENU_code (*Fct_Manage)( void ); /*!< Second function launched after a "return MENU_CONTINU_COMMAND" in the first function */ int fRemoveMenu; /*!< Flag to know if remove menu at end */ } tMenuItem; /** * @struct tMenu * @brief Menu description. **/ typedef struct { unsigned fdispTitle: 1; /*!< Display title is set. */ const char* Title; /*!< Menu title. */ int NbItems; /*!< Number of items in the menu ( must be <= MENU_MAXITEM ) */ int LgMax; /*!< Unused. */ int XPos; /*!< X position of menu bottom-left corner. */ int YPos; /*!< Y position of menu bottom-left corner. */ int XSize; /*!< Unused. */ int YSize; /*!< Unused. */ unsigned int SelectedItem; /*!< ID of selected item (0 for first item, 1 for second item, ...) */ tMenuItem Items[MENU_MAXITEM]; /*!< Items of menu. */ } tMenu; /** * @enum MENU_code * @brief Application return values. * * List of all the codes available for CircleOS application return values. **/ enum MENU_code { MENU_LEAVE = 0, /*!< Leave application. */ MENU_CONTINUE = 1, /*!< Continue application. */ MENU_REFRESH = 2, /*!< Refresh current menu. */ MENU_CHANGE = 3, /*!< Change current menu. */ MENU_CONTINUE_COMMAND = 4 /*!< Sent by Ini functions.*/ }; /// @cond Internal /* Exported defines ----------------------------------------------------------*/ // MENU functions definition #define MENU_SET_ID (MENU_ID + 0) // Display a menu #define MENU_REMOVE_ID (MENU_ID + 1) // Remove the current menu, DRAW_Clear and set pointer mode to "POINTER_ON". #define MENU_QUESTION_ID (MENU_ID + 2) // Dedicated menu for ask question and yes/no responses #define MENU_PRINT_ID (MENU_ID + 3) // Display a popup menu with a string. #define MENU_CLEAR_CURRENT_COMMAND_ID (MENU_ID + 4) // Set CurrentCommand to 0 #define MENU_SET_LEVELTITLE_ID (MENU_ID + 5) // Set the title of level menu managed by MENU_SetLevel_Mgr. #define MENU_SET_TEXTCOLOR_ID (MENU_ID + 6) // Set the color used for text menu. #define MENU_GET_TEXTCOLOR_ID (MENU_ID + 7) // Return the color used for text menu. #define MENU_SET_BGNDCOLOR_ID (MENU_ID + 8) // Set the background color used for menu. #define MENU_GET_BGNDCOLOR_ID (MENU_ID + 9) // Return the background color used for menu. #define MENU_QUIT_ID (MENU_ID + 10) // Leave the current menu (stand for "cancel" and do a DRAW_Clear) #define MENU_SET_LEVELINI_ID (MENU_ID + 11) // Initialise a generic function to set a avalue in the range of [0,4] #define MENU_CLEAR_CURRENT_MENU_ID (MENU_ID + 12) // Set CurrentMenu to 0 #define MENU_SET_LEVEL_MGR_ID (MENU_ID + 13) // Generic function to set a avalue in the range of [0,4] (handling of the control) // Prototypes #define MENU_Set(a) ((tCircleFunc1)(Circle_API [MENU_SET_ID])) ((u32)(a)) //void MENU_Set ( tMenu *mptr ); #define MENU_Remove() ((tCircleFunc0)(Circle_API [MENU_REMOVE_ID])) () //void MENU_Remove ( void ) ; #define MENU_Question(a,b) ((tCircleFunc2)(Circle_API [MENU_QUESTION_ID])) ((u32)(a),(u32)(b)) //void MENU_Question ( char *str, int *answer ); #define MENU_Print(a) ((tCircleFunc1)(Circle_API [MENU_PRINT_ID])) ((u32)(a)) //void MENU_Print ( char *str ); #define MENU_ClearCurrentCommand() ((tCircleFunc0)(Circle_API [MENU_CLEAR_CURRENT_COMMAND_ID])) () //void MENU_ClearCurrentCommand(void) #define MENU_SetLevelTitle(a) ((tCircleFunc1)(Circle_API [MENU_SET_LEVELTITLE_ID])) ((u32)(a)) //void MENU_SetLevelTitle(u8* title) #define MENU_SetTextColor(a) ((tCircleFunc1)(Circle_API [MENU_SET_TEXTCOLOR_ID])) ((u32)(a)) //void MENU_SetTextColor ( int TextColor ) #define MENU_GetTextColor() (u32) (((tCircleFunc0)(Circle_API [MENU_GET_TEXTCOLOR_ID])) ()) //int MENU_GetTextColor ( void ) #define MENU_SetBGndColor(a) ((tCircleFunc1)(Circle_API [MENU_SET_BGNDCOLOR_ID])) ((u32)(a)) //void MENU_SetBGndColor ( int BGndColor ) #define MENU_GetBGndColor() (u32) (((tCircleFunc0)(Circle_API [MENU_GET_BGNDCOLOR_ID])) ()) //int MENU_GetBGndColor ( void ) #define MENU_Quit() (enum MENU_code) (((tCircleFunc0)(Circle_API [MENU_QUIT_ID])) ()) //enum MENU_code MENU_Quit ( void ) #define MENU_SetLevel_Ini() (enum MENU_code) (((tCircleFunc0)(Circle_API [MENU_SET_LEVELINI_ID])) ()) //enum MENU_code MENU_SetLevel_Ini ( void ) #define MENU_ClearCurrentMenu() ((tCircleFunc0)(Circle_API [MENU_CLEAR_CURRENT_MENU_ID])) () //void MENU_ClearCurrentMenu(void) #define MENU_SetLevel_Mgr(a,b) (enum MENU_code) ((tCircleFunc2)(Circle_API [MENU_SET_LEVEL_MGR_ID])) ((u32)(a),(u32)(b)) //enum MENU_code MENU_SetLevel_Mgr ( u32 *value, u32 value_range [] ) /// @endcond //---------------------------------- LED ------------------------------------- /* Exported types ------------------------------------------------------------*/ /** * @enum LED_mode * @brief LED modes. * * LEDs may be on, off or blinking slowly or fastly! **/ enum LED_mode { LED_UNDEF = -1, /*!< Undefined led mode. */ LED_OFF = 0, /*!< Put off the led. */ LED_ON = 1, /*!< Put on the led. */ LED_BLINKING_LF = 2, /*!< Slow blinking led mode. */ LED_BLINKING_HF = 3 /*!< Fast blinking led mode. */ }; /** * @enum LED_id * @brief Available LEDs. * * List of all the available LEDs. **/ enum LED_id { LED_GREEN = 0, /*!< Green led id. */ LED_RED = 1 /*!< Red led id. */ }; /// @cond Internal /* Exported defines ----------------------------------------------------------*/ // LED functions definition #define LED_SET_ID (LED_ID + 0) // Set a specified LED in a specified mode. // Prototypes #define LED_Set(a,b) ((tCircleFunc2)(Circle_API [LED_SET_ID])) ((u32)(a),(u32)(b)) //void LED_Set ( enum LED_id id, enum LED_mode mode ) //void LED_Set ( enum LED_id id, enum LED_mode mode ); /// @endcond //-------------------------------- RTC -------------------------------------- /* Exported defines ----------------------------------------------------------*/ // Backup registers #define BKP_SYS1 1 /*!< Backup register reserved for OS */ #define BKP_SYS2 2 /*!< Backup register reserved for OS */ #define BKP_SYS3 3 /*!< Backup register reserved for OS */ #define BKP_SYS4 4 /*!< Backup register reserved for OS */ #define BKP_SYS5 5 /*!< Backup register reserved for OS */ #define BKP_SYS6 6 /*!< Backup register reserved for OS */ #define BKP_USER1 7 /*!< Backup available for users application */ #define BKP_USER2 8 /*!< Backup available for users application */ #define BKP_USER3 9 /*!< Backup available for users application */ #define BKP_USER4 10 /*!< Backup available for users application */ /// @cond Internal //RTC functions definition #define RTC_SET_TIME_ID (RTC_ID + 0) // Set current time. #define RTC_GET_TIME_ID (RTC_ID + 1) // Return current time. #define RTC_DISPLAY_TIME_ID (RTC_ID + 2) // Display current time on the 6th line at column 0. // Prototypes #define RTC_SetTime(a,b,c) ((tCircleFunc3)(Circle_API [RTC_SET_TIME_ID])) ((u32)(a),(u32)(b),(u32)(c)) //void RTC_SetTime (u32 THH, u32 TMM, u32 TSS); #define RTC_GetTime(a,b,c) ((tCircleFunc3)(Circle_API [RTC_GET_TIME_ID])) ((u32)(a),(u32)(b),(u32)(c)) //void RTC_GetTime (u32 * THH, u32 * TMM, u32 * TSS); #define RTC_DisplayTime() ((tCircleFunc0)(Circle_API [RTC_DISPLAY_TIME_ID])) () //void RTC_DisplayTime ( void ); /// @endcond //--------------------------------- Application ------------------------------- typedef void (*tAppPtrMgr) ( int , int ); #endif /*__CIRCLE_API_H */
23,455
698
<reponame>vibhutisawant/nginx-clojure /** * Copyright (C) Zhang,Yuexiang (xfeep) * */ package nginx.clojure; import java.nio.charset.Charset; import static nginx.clojure.NginxClojureRT.*; public class RequestKnownOffsetVarFetcher implements RequestVarFetcher { private long offset; public RequestKnownOffsetVarFetcher(long offset) { this.offset = offset; } @Override public Object fetch(long r, Charset encoding) { return fetchNGXString(r + offset, encoding); } }
180
14,570
package io.swagger.codegen.ignore; import com.google.common.collect.ImmutableList; import io.swagger.codegen.ignore.rules.DirectoryRule; import io.swagger.codegen.ignore.rules.Rule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Presents a processing utility for parsing and evaluating files containing common ignore patterns. (.swagger-codegen-ignore) */ public class CodegenIgnoreProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessor.class); private File ignoreFile = null; private List<Rule> exclusionRules = new ArrayList<>(); private List<Rule> inclusionRules = new ArrayList<>(); /** * Loads the default ignore file (.swagger-codegen-ignore) from the specified path. * * @param baseDirectory The base directory of the files to be processed. This contains the ignore file. */ public CodegenIgnoreProcessor(final String baseDirectory) { this(baseDirectory, ".swagger-codegen-ignore"); } /** * Loads the specified ignore file by name ([ignoreFile]) from the specified path. * * @param baseDirectory The base directory of the files to be processed. This contains the ignore file. * @param ignoreFile The file containing ignore patterns. */ @SuppressWarnings("WeakerAccess") public CodegenIgnoreProcessor(final String baseDirectory, final String ignoreFile) { final File directory = new File(baseDirectory); final File targetIgnoreFile = new File(directory, ignoreFile); if (directory.exists() && directory.isDirectory()) { loadFromFile(targetIgnoreFile); } else { LOGGER.warn("Output directory does not exist, or is inaccessible. No file (.swagger-codegen-ignore) will be evaluated."); } } /** * Constructs an instance of {@link CodegenIgnoreProcessor} from an ignore file defined by {@code targetIgnoreFile}. * * @param targetIgnoreFile The ignore file location. */ public CodegenIgnoreProcessor(final File targetIgnoreFile) { loadFromFile(targetIgnoreFile); } private void loadFromFile(File targetIgnoreFile) { if (targetIgnoreFile.exists() && targetIgnoreFile.isFile()) { try { loadCodegenRules(targetIgnoreFile); this.ignoreFile = targetIgnoreFile; } catch (IOException e) { LOGGER.error(String.format("Could not process %s.", targetIgnoreFile.getName()), e.getMessage()); } } else { // log info message LOGGER.info(String.format("No %s file found.", targetIgnoreFile.getName())); } } void loadCodegenRules(final File codegenIgnore) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(codegenIgnore))) { String line; // NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore // see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt while ((line = reader.readLine()) != null) { if( //: A blank line matches no files, so it can serve as a separator for readability. line.length() == 0 ) continue; Rule rule = Rule.create(line); // rule could be null here if it's a COMMENT, for example if(rule != null) { if (Boolean.TRUE.equals(rule.getNegated())) { inclusionRules.add(rule); } else { exclusionRules.add(rule); } } } } } /** * Determines whether or not a file defined by {@code toEvaluate} is allowed, * under the exclusion rules from the ignore file being processed. * * @param targetFile The file to check against exclusion rules from the ignore file. * @return {@code false} if file matches any pattern in the ignore file (disallowed), otherwise {@code true} (allowed). */ public boolean allowsFile(final File targetFile) { if(this.ignoreFile == null) return true; File file = new File(this.ignoreFile.getParentFile().toURI().relativize(targetFile.toURI()).getPath()); Boolean directoryExcluded = false; Boolean exclude = false; if(exclusionRules.size() == 0 && inclusionRules.size() == 0) { return true; } // NOTE: We *must* process all exclusion rules for (int i = 0; i < exclusionRules.size(); i++) { Rule current = exclusionRules.get(i); Rule.Operation op = current.evaluate(file.getPath()); switch (op){ case EXCLUDE: exclude = true; // Include rule can't override rules that exclude a file by some parent directory. if(current instanceof DirectoryRule) { directoryExcluded = true; } break; case INCLUDE: // This won't happen here. break; case NOOP: break; case EXCLUDE_AND_TERMINATE: i = exclusionRules.size(); break; } } if(exclude) { // Only need to process inclusion rules if we've been excluded for (int i = 0; exclude && i < inclusionRules.size(); i++) { Rule current = inclusionRules.get(i); Rule.Operation op = current.evaluate(file.getPath()); // At this point exclude=true means the file should be ignored. // op == INCLUDE means we have to flip that flag. if(op.equals(Rule.Operation.INCLUDE)) { if(current instanceof DirectoryRule && directoryExcluded) { // e.g // baz/ // !foo/bar/baz/ // NOTE: Possibly surprising side effect: // foo/bar/baz/ // !bar/ exclude = false; } else if (!directoryExcluded) { // e.g. // **/*.log // !ISSUE_1234.log exclude = false; } } } } return Boolean.FALSE.equals(exclude); } /** * Allows a consumer to manually inspect explicit "inclusion rules". That is, patterns in the ignore file which have been negated. * * @return A {@link ImmutableList#copyOf(Collection)} of rules which possibly negate exclusion rules in the ignore file. */ public List<Rule> getInclusionRules() { return ImmutableList.copyOf(inclusionRules); } /** * Allows a consumer to manually inspect all "exclusion rules". That is, patterns in the ignore file which represent * files and directories to be excluded, unless explicitly overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules. * * NOTE: Existence in this list doesn't mean a file is excluded. The rule can be overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules. * * @return A {@link ImmutableList#copyOf(Collection)} of rules which define exclusions by patterns in the ignore file. */ public List<Rule> getExclusionRules() { return ImmutableList.copyOf(exclusionRules); } }
3,364
369
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include "Result.hpp" #include <at/Cmd.hpp> #include <PhoneNumber.hpp> namespace ModemCall { enum class CallState : uint8_t { Active = 0, // 0 active: call in progress (setup was successful) Held, // 1 held: call on hold Dialing, // 2 dialing (MO call): number dialed Alerting, // 3 alerting (MO call): number dialed and the called party is alerted Incoming, // 4 incoming (MT call): incoming call, ringtone played (AT RING notification) Waiting // 5 waiting (MT call): call waiting notification while another call is active (if call waiting feature // enabled) }; enum class CallDir : uint8_t { MO = 0, // Mobile originated (MO) call MT = 1 // Mobile terminated (MT) call }; enum class CallMode : uint8_t { Voice = 0, Data, FAX }; } // namespace ModemCall namespace at { namespace cmd { class CLCC; } // namespace cmd namespace result { /// please see documentation: /// QuectelEC2526EC21ATCommandsManualV13.1100970659 /// page: 101 for more information struct CLCC : public Result { private: struct Data { const std::uint8_t idx; const ModemCall::CallDir dir; const ModemCall::CallState stateOfCall; const ModemCall::CallMode mode; const bool multiparty; const utils::PhoneNumber::View number; const std::string type; const std::string alpha; const std::size_t tokens; }; std::vector<Data> data; friend cmd::CLCC; public: explicit CLCC(const Result &); [[nodiscard]] auto getData() const noexcept -> const std::vector<Data> & { return data; }; }; } // namespace result namespace cmd { class CLCC : public Cmd { protected: [[nodiscard]] static auto toBool(const std::string &text) -> bool; [[nodiscard]] static auto toUInt(const std::string &text) -> std::uint8_t; template <typename T>[[nodiscard]] static auto toEnum(const std::string &text) -> std::optional<T>; public: CLCC() noexcept; explicit CLCC(at::cmd::Modifier mod) noexcept; [[nodiscard]] auto parseCLCC(const Result &base_result) -> result::CLCC; }; } // namespace cmd } // namespace at
1,271
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport */ #import <OfficeImport/XXUnknownSuperclass.h> #import <OfficeImport/WDAContent.h> #import <OfficeImport/OADClient.h> #import <OfficeImport/OfficeImport-Structs.h> #import <OfficeImport/OADTextClient.h> @class WDAAnchor, OADDrawable, WDATextBox; __attribute__((visibility("hidden"))) @interface WDAContent : XXUnknownSuperclass <OADClient, OADTextClient> { @private WDAAnchor *mAnchor; // 4 = 0x4 WDATextBox *mTextBox; // 8 = 0x8 OADDrawable *mDrawable; // 12 = 0xc int mTextType; // 16 = 0x10 } @property(readonly, assign, nonatomic) WDAAnchor *anchor; // G=0x138cf5; @synthesize=mAnchor @property(assign) CGRect bounds; // G=0x94ffd; S=0x286a75; converted property @property(retain) id textBox; // G=0x145155; S=0x139449; converted property @property(retain) id drawable; // G=0x1394d5; S=0x138ac9; converted property @property(assign) int textType; // G=0x141e01; S=0x138ae9; converted property - (id)init; // 0x138a89 - (void)dealloc; // 0xa2d79 - (id)createAnchor; // 0x138b75 - (void)clearAnchor; // 0x1bd955 - (id)createTextBoxWithDocument:(id)document textType:(int)type; // 0x286aa1 - (BOOL)hasBounds; // 0x2869a1 // converted property getter: - (CGRect)bounds; // 0x94ffd // converted property setter: - (void)setBounds:(CGRect)bounds; // 0x286a75 // converted property getter: - (id)textBox; // 0x145155 // converted property setter: - (void)setTextBox:(id)box; // 0x139449 // converted property getter: - (id)drawable; // 0x1394d5 // converted property setter: - (void)setDrawable:(id)drawable; // 0x138ac9 - (bool)isShape; // 0x144ac1 - (bool)isLine; // 0x286a31 - (bool)isTopLevelObject; // 0x286a01 // converted property getter: - (int)textType; // 0x141e01 // converted property setter: - (void)setTextType:(int)type; // 0x138ae9 - (BOOL)floating; // 0x196761 - (BOOL)hasText; // 0x2869b9 // declared property getter: - (id)anchor; // 0x138cf5 @end @interface WDAContent (Private) + (Class)classForType:(unsigned short)type; // 0x286b81 @end
841
628
<filename>Part_8_V2_FUN_With_Talking_Robots/talking_robots_program.py<gh_stars>100-1000 import gc import speech def talk(words): """Talk to your friend Mr. George Parameters ---------- words : str The words to say to your friend Mr. George Returns ------- None """ gc.collect() words = words.lower() if words.find('how are you') != -1: speech.say('I am doing great!') elif words.find('what\'s up') != -1: speech.say('The sky.') elif words.find('morning') != -1: speech.say('I love to watch the sun rise in the morning!') elif words.find('afternoon') != -1: speech.say('I get hungry around lunch time.') elif words.find('evening') != -1: speech.say('I get sleepy in the evening.') elif words.find('night') != -1: speech.say('I get sleepy when it is night time.') elif words.find('tell me something') != -1: speech.say('I am a robot who loves to teach Piethon.') elif words.find('hello') != -1: speech.say('Hello to you!') elif words.find('hi') != -1: speech.say('Hi to you!') elif words.find('thank you') != -1: speech.say('It is my pleasure!') elif words.find('bye') != -1: speech.say('It was nice talking to you!') elif words.find('help') != -1: speech.say('I am always here to help!') elif words.find('what can you do') != -1: speech.say('I can teach Piethon programming.') elif words.find('name') != -1: speech.say('My name is <NAME> it is nice to meet you!') elif words.find('how old are you') != -1: speech.say('I was born in September of the year twenty twenty.') elif words.find('question') != -1: speech.say('I always try to answer questions.') elif words.find('joke') != -1: speech.say('What did the chicken cross the road?') speech.say('To get to the other side.') elif words.find('love') != -1: speech.say('I love pizza!') elif words.find('love you') != -1: speech.say('Thank you so kind of you!') elif words.find('love people') != -1: speech.say('I want to help people by teaching them Piethon!') elif words.find('hobby') != -1: speech.say('I like to teachin Piethon to people!') elif words.find('you live') != -1: speech.say('I live in side the little microcontroller here.') elif words.find('made you') != -1: speech.say('<NAME> created me inspired by the great people at MicroPiethon.') elif words.find('your job') != -1: speech.say('I teach Piethon.') elif words.find('you do') != -1: speech.say('I like to teach Piethon.') # ADD MORE CODE HERE else: speech.say('I am sorry I do not understand.')
1,143
435
{ "description": "Registration steps to use a web app, as well as login and password reset functionality is a common requirement, but where do you begin implementing this in Django? Walking through an actual case study with code examples, novice programmers will learn some tips and tricks for finding and implementing the right framework.", "duration": 1083, "language": "eng", "recorded": "2016-07-18", "speakers": [ "<NAME>" ], "thumbnail_url": "https://i.ytimg.com/vi/u36idTPlc_E/hqdefault.jpg", "title": "Sign Me Up - Choosing & Using a Registration Package for Your Django Project", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=u36idTPlc_E" } ] }
231
743
package pl.allegro.tech.hermes.management.domain.dc; public class DatacenterBoundQueryResult<T> { private final String datacenterName; private final T result; public DatacenterBoundQueryResult(T result, String datacenterName) { this.datacenterName = datacenterName; this.result = result; } public String getDatacenterName() { return datacenterName; } public T getResult() { return result; } }
176
2,645
/* * Copyright 2021 the original author or 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 * * https://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 org.springframework.data.elasticsearch.core.query.highlight; import org.springframework.util.Assert; /** * @author <NAME> * @since 4.3 */ abstract public class HighlightCommonParameters { private final String boundaryChars; private final int boundaryMaxScan; private final String boundaryScanner; private final String boundaryScannerLocale; private final boolean forceSource; private final String fragmenter; private final int fragmentSize; private final int noMatchSize; private final int numberOfFragments; private final String order; private final int phraseLimit; private final String[] preTags; private final String[] postTags; private final boolean requireFieldMatch; private final String type; protected HighlightCommonParameters(HighlightCommonParametersBuilder<?> builder) { Assert.notNull(builder, "builder must not be null"); boundaryChars = builder.boundaryChars; boundaryMaxScan = builder.boundaryMaxScan; boundaryScanner = builder.boundaryScanner; boundaryScannerLocale = builder.boundaryScannerLocale; forceSource = builder.forceSource; fragmenter = builder.fragmenter; fragmentSize = builder.fragmentSize; noMatchSize = builder.noMatchSize; numberOfFragments = builder.numberOfFragments; order = builder.order; phraseLimit = builder.phraseLimit; preTags = builder.preTags; postTags = builder.postTags; requireFieldMatch = builder.requireFieldMatch; type = builder.type; } public String getBoundaryChars() { return boundaryChars; } public int getBoundaryMaxScan() { return boundaryMaxScan; } public String getBoundaryScanner() { return boundaryScanner; } public String getBoundaryScannerLocale() { return boundaryScannerLocale; } public boolean getForceSource() { return forceSource; } public String getFragmenter() { return fragmenter; } public int getFragmentSize() { return fragmentSize; } public int getNoMatchSize() { return noMatchSize; } public int getNumberOfFragments() { return numberOfFragments; } public String getOrder() { return order; } public int getPhraseLimit() { return phraseLimit; } public String[] getPreTags() { return preTags; } public String[] getPostTags() { return postTags; } public boolean getRequireFieldMatch() { return requireFieldMatch; } public String getType() { return type; } @SuppressWarnings("unchecked") public static abstract class HighlightCommonParametersBuilder<SELF extends HighlightCommonParametersBuilder<SELF>> { private String boundaryChars = ""; private int boundaryMaxScan = -1; private String boundaryScanner = ""; private String boundaryScannerLocale = ""; private boolean forceSource = false; private String fragmenter = ""; private int fragmentSize = -1; private int noMatchSize = -1; private int numberOfFragments = -1; private String order = ""; private int phraseLimit = -1; private String[] preTags = new String[0]; private String[] postTags = new String[0]; private boolean requireFieldMatch = true; private String type = ""; protected HighlightCommonParametersBuilder() {} public SELF withBoundaryChars(String boundaryChars) { this.boundaryChars = boundaryChars; return (SELF) this; } public SELF withBoundaryMaxScan(int boundaryMaxScan) { this.boundaryMaxScan = boundaryMaxScan; return (SELF) this; } public SELF withBoundaryScanner(String boundaryScanner) { this.boundaryScanner = boundaryScanner; return (SELF) this; } public SELF withBoundaryScannerLocale(String boundaryScannerLocale) { this.boundaryScannerLocale = boundaryScannerLocale; return (SELF) this; } public SELF withForceSource(boolean forceSource) { this.forceSource = forceSource; return (SELF) this; } public SELF withFragmenter(String fragmenter) { this.fragmenter = fragmenter; return (SELF) this; } public SELF withFragmentSize(int fragmentSize) { this.fragmentSize = fragmentSize; return (SELF) this; } public SELF withNoMatchSize(int noMatchSize) { this.noMatchSize = noMatchSize; return (SELF) this; } public SELF withNumberOfFragments(int numberOfFragments) { this.numberOfFragments = numberOfFragments; return (SELF) this; } public SELF withOrder(String order) { this.order = order; return (SELF) this; } public SELF withPhraseLimit(int phraseLimit) { this.phraseLimit = phraseLimit; return (SELF) this; } public SELF withPreTags(String[] preTags) { this.preTags = preTags; return (SELF) this; } public SELF withPostTags(String[] postTags) { this.postTags = postTags; return (SELF) this; } public SELF withRequireFieldMatch(boolean requireFieldMatch) { this.requireFieldMatch = requireFieldMatch; return (SELF) this; } public SELF withType(String type) { this.type = type; return (SELF) this; } public abstract HighlightCommonParameters build(); } }
1,813
1,066
/* * Copyright (c) 2020 <NAME> * * 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. */ package com.eatthepath.pushy.apns.server; import org.junit.jupiter.api.Test; import java.io.File; import java.io.InputStream; import java.security.KeyStore; import java.security.cert.X509Certificate; import static org.junit.jupiter.api.Assertions.assertThrows; public class MockApnsServerBuilderTest { private static final String SERVER_CERTIFICATE_FILENAME = "/server-certs.pem"; private static final String SERVER_KEY_FILENAME = "/server-key.pem"; private static final String SERVER_KEYSTORE_FILENAME = "/server.p12"; private static final String SERVER_KEYSTORE_ALIAS = "1"; private static final String SERVER_KEYSTORE_PASSWORD = "<PASSWORD>"; @Test void testSetServerCredentialsFileFileString() throws Exception { final File certificateFile = new File(this.getClass().getResource(SERVER_CERTIFICATE_FILENAME).toURI()); final File keyFile = new File(this.getClass().getResource(SERVER_KEY_FILENAME).toURI()); // We're happy here as long as nothing explodes new MockApnsServerBuilder() .setServerCredentials(certificateFile, keyFile, null) .setHandlerFactory(new AcceptAllPushNotificationHandlerFactory()) .build(); } @Test void testSetServerCredentialsInputStreamInputStreamString() throws Exception { try (final InputStream certificateInputStream = this.getClass().getResourceAsStream(SERVER_CERTIFICATE_FILENAME); final InputStream keyInputStream = this.getClass().getResourceAsStream(SERVER_KEY_FILENAME)) { // We're happy here as long as nothing explodes new MockApnsServerBuilder() .setServerCredentials(certificateInputStream, keyInputStream, null) .setHandlerFactory(new AcceptAllPushNotificationHandlerFactory()) .build(); } } @Test void testSetServerCredentialsX509CertificateArrayPrivateKeyString() throws Exception { try (final InputStream p12InputStream = this.getClass().getResourceAsStream(SERVER_KEYSTORE_FILENAME)) { final KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(p12InputStream, SERVER_KEYSTORE_PASSWORD.toCharArray()); final KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(SERVER_KEYSTORE_PASSWORD.toCharArray()); final KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(SERVER_KEYSTORE_ALIAS, passwordProtection); // We're happy here as long as nothing explodes new MockApnsServerBuilder() .setServerCredentials(new X509Certificate[] { (X509Certificate) privateKeyEntry.getCertificate() }, privateKeyEntry.getPrivateKey(), null) .setHandlerFactory(new AcceptAllPushNotificationHandlerFactory()) .build(); } } @Test void testBuildWithoutServerCredentials() { assertThrows(IllegalStateException.class, () -> new MockApnsServerBuilder() .setHandlerFactory(new AcceptAllPushNotificationHandlerFactory()) .build()); } @Test void testBuildWithoutHandlerFactory() throws Exception { final File certificateFile = new File(this.getClass().getResource(SERVER_CERTIFICATE_FILENAME).toURI()); final File keyFile = new File(this.getClass().getResource(SERVER_KEY_FILENAME).toURI()); assertThrows(IllegalStateException.class, () -> new MockApnsServerBuilder() .setServerCredentials(certificateFile, keyFile, null) .build()); } @Test void testSetMaxConcurrentStreams() { // We're happy here as long as nothing explodes new MockApnsServerBuilder().setMaxConcurrentStreams(1); } @Test void testSetNegativeMaxConcurrentStreams() { assertThrows(IllegalArgumentException.class, () -> new MockApnsServerBuilder().setMaxConcurrentStreams(-7)); } }
1,842
1,894
<reponame>Martijnve23/catapult # Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import pipes def ShellFormat(command, trim=False): """Format the command for easy copy/pasting into a shell. Args: command: a list of the executable and its arguments. trim: Trim finch and feature flags from a command to reduce its length. Returns: A string. """ if trim: # Copy the command since trimming is done in-place. command = list(command) _Trim(command) quoted_command = [_ShellQuote(part) for part in command] return ' '.join(quoted_command) def _Trim(command): """Shorten long arguments out of a command. This is useful for keeping logs short to reduce Swarming UI load time and prevent us from getting truncated. See crbug.com/943650. """ ARGUMENTS_TO_SHORTEN = ( '--force-fieldtrial-params=', '--force-fieldtrials=', '--disable-features=', '--enable-features=') for index, part in enumerate(command): for substring in ARGUMENTS_TO_SHORTEN: if part.startswith(substring): command[index] = substring + '...' break def _ShellQuote(command_part): """Escape a part of a command to enable copy/pasting it into a shell. """ return pipes.quote(command_part)
474
2,661
<reponame>ezeeyahoo/earthenterprise /* * Copyright 2019 The Open GEE Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "DependentStateTree.h" #include "common/notify.h" #include <map> #include <set> using namespace boost; using namespace std; class DependentStateTreeFactory { private: struct VertexData { DependentStateTreeVertexDescriptor vertex; bool includeConnections; }; SharedString ref; std::function<bool(AssetDefs::State)> includePredicate; bool includeDependentChildren; bool includeAllChildrenAndInputs; StorageManagerInterface<AssetVersionImpl> * const storageManager; map<SharedString, VertexData> vertices; size_t index; set<DependentStateTreeVertexDescriptor> toFillInNext; DependentStateTree tree; inline bool IsDependent(DependencyType type) { return type == DEPENDENT || type == DEPENDENT_AND_CHILD; } DependentStateTreeVertexDescriptor AddOrUpdateVertex( const SharedString & ref, bool inDepTree, bool includeConnections); void FillInVertex(DependentStateTreeVertexDescriptor myVertex); void AddEdge( DependentStateTreeVertexDescriptor from, DependentStateTreeVertexDescriptor to, AssetEdge data); public: DependentStateTreeFactory( const SharedString &ref, std::function<bool(AssetDefs::State)> includePredicate, bool includeDependentChildren, bool includeAllChildrenAndInputs, StorageManagerInterface<AssetVersionImpl> *sm) : ref(ref), includePredicate(includePredicate), includeDependentChildren(includeDependentChildren), includeAllChildrenAndInputs(includeAllChildrenAndInputs), storageManager(sm), index(0) {} DependentStateTree BuildTree(); }; // Builds a tree containing the specified asset, its depedent children, their // dependent children, and so on, along with any other assets that are needed // to update the state of these assets. That includes their inputs and children, // their parents and listeners all the way up the tree, and the inputs and // children for their parents and listeners. DependentStateTree DependentStateTreeFactory::BuildTree() { // First create an empty vertex for the provided asset. Then fill it in, // which includes adding its connections to other assets. Every time we fill // in a node we will get new assets to add to the tree until all assets have // been added. This basically builds the tree using a breadth first search, // which allows us to keep memory usage (relatively) low by not forcing // assets to stay in the cache and limiting the size of the toFillIn and // toFillInNext lists. AddOrUpdateVertex(ref, true, true); while (toFillInNext.size() > 0) { set<DependentStateTreeVertexDescriptor> toFillIn = std::move(toFillInNext); toFillInNext.clear(); for (auto vertex : toFillIn) { FillInVertex(vertex); } } return tree; } // Creates an "empty" node for this asset if it has not already been added to // the tree. The node has a default state and doesn't include links to // inputs/children/etc. The vertex must be "filled in" by calling FillInVertex // before it can be used. DependentStateTreeVertexDescriptor DependentStateTreeFactory::AddOrUpdateVertex( const SharedString & ref, bool inDepTree, bool includeConnections) { auto myVertexIter = vertices.find(ref); if (myVertexIter == vertices.end()) { // I'm not in the graph yet, so make a new empty vertex and let the caller // know we need to load it with the correct information auto myVertex = add_vertex(tree); tree[myVertex] = {ref, AssetDefs::New, inDepTree, index}; ++index; vertices[ref] = {myVertex, includeConnections}; toFillInNext.insert(myVertex); return myVertex; } else { // I'm already in the graph. If we learned new information that we didn't // know when I was added to the tree (e.g., I'm in the dependent tree), // add this to the list of vertices to fill in so that we can add its // connections. Then return the existing descriptor. auto myVertex = myVertexIter->second.vertex; auto & myVertexData = tree[myVertex]; if (inDepTree && !myVertexData.inDepTree) { myVertexData.inDepTree = true; toFillInNext.insert(myVertex); } if (includeConnections && !myVertexIter->second.includeConnections) { myVertexIter->second.includeConnections = true; toFillInNext.insert(myVertex); } return myVertex; } } // "Fills in" an existing vertex with the state of an asset and its connections // to other assets. Adds any new nodes that need to be filled in to toFillInNext. void DependentStateTreeFactory::FillInVertex( DependentStateTreeVertexDescriptor myVertex) { SharedString name = tree[myVertex].name; notify(NFY_PROGRESS, "Loading '%s' for state update", name.toString().c_str()); auto version = storageManager->Get(name); if (!version) { notify(NFY_WARN, "Could not load asset '%s' which is referenced by another asset.", name.toString().c_str()); // Set it to a bad state, but use a state that can be fixed by another // rebuild operation. tree[myVertex].state = AssetDefs::Blocked; return; } tree[myVertex].state = version->state; // If this vertex is in the dependent tree but doesn't need to be included, // act as though it's not in the dependency tree. We'll leave it in the tree // to avoid messing up the index numbering and in case it is needed as an // input, but we won't bring in any of its dependents. if (tree[myVertex].inDepTree && !includePredicate(tree[myVertex].state)) { tree[myVertex].inDepTree = false; vertices[name].includeConnections = false; } // If I'm in the dependency tree, and if the new state propagates to dependents, // then I need to add my dependents to the graph and the dependency tree. if (tree[myVertex].inDepTree && includeDependentChildren) { vector<SharedString> dependents; version->DependentChildren(dependents); for (const auto & dep : dependents) { auto depVertex = AddOrUpdateVertex(dep, true, true); AddEdge(myVertex, depVertex, {DEPENDENT}); } } // If I need to recalculate my state, I need to have my children and inputs // in the tree because my state is based on them. In addition, I need my // parents and listeners, because they may also have to recalculate their // state. If I don't need to recalculate my state, I don't need to add any of // my connections. I'm only used to calculate someone else's state. if (vertices[name].includeConnections) { // In some cases, assets don't need all their inputs and children to // calculate their states. if (includeAllChildrenAndInputs) { for (const auto &child : version->children) { auto childVertex = AddOrUpdateVertex(child, false, false); AddEdge(myVertex, childVertex, {CHILD}); } for (const auto & input : version->inputs) { auto inputVertex = AddOrUpdateVertex(input, false, false); AddEdge(myVertex, inputVertex, {INPUT}); } } for (const auto & parent : version->parents) { auto parentVertex = AddOrUpdateVertex(parent, false, true); AddEdge(parentVertex, myVertex, {CHILD}); } for (const auto & listener : version->listeners) { auto listenerVertex = AddOrUpdateVertex(listener, false, true); AddEdge(listenerVertex, myVertex, {INPUT}); } } } void DependentStateTreeFactory::AddEdge( DependentStateTreeVertexDescriptor from, DependentStateTreeVertexDescriptor to, AssetEdge data) { auto edgeData = add_edge(from, to, tree); if (edgeData.second) { // This is a new edge tree[edgeData.first] = data; } else { // Check if this is both a dependent and a child DependencyType currentType = tree[edgeData.first].type; DependencyType newType = data.type; if ((currentType == DEPENDENT && newType == CHILD) || (currentType == CHILD && newType == DEPENDENT)) { tree[edgeData.first].type = DEPENDENT_AND_CHILD; } } } DependentStateTree BuildDependentStateTree( const SharedString & ref, std::function<bool(AssetDefs::State)> includePredicate, bool includeDependentChildren, bool includeAllChildrenAndInputs, StorageManagerInterface<AssetVersionImpl> * sm) { DependentStateTreeFactory factory(ref, includePredicate, includeDependentChildren, includeAllChildrenAndInputs, sm); return factory.BuildTree(); }
2,987
687
{ "programme": { "type": "clip", "pid": "p079x0ql", "expected_child_count": null, "position": null, "image": { "pid": "p079x6fd" }, "media_type": "audio_video", "title": "Sudan’s Secret Hit Squads", "short_synopsis": "Sudan’s Secret Hit Squads Used to Attack Protests", "medium_synopsis": "What happens inside Sudan’s secret detention centres?", "long_synopsis": "These are images Sudan’s government does not want you to see: teams of masked, plainclothes agents chasing down protesters, beating them, and dragging them off to secret detention centres in Khartoum.\n \nWho are these hit squads? Where are these detention centres? And what happens inside their walls?\n\nBBC Africa Eye has analysed dozens of dramatic videos filmed during the recent uprising, and spoken with witnesses who have survived torture at the hands of the Bashir regime. Some of these protesters tell us about a secret and widely feared holding facility – The Fridge – where the cold is used an instrument of torture.\n\nInvestigation led by:\n<NAME>\n<NAME>\n<NAME> \n<NAME> \n\nProduced and Edited by:\n<NAME> \n<NAME> \n<NAME> \n\nSubscribe: http://bit.ly/subscribetoafrica\nWebsite: https://www.bbc.com/africa\nFacebook: https://www.facebook.com/bbcnewsafrica/\nTwitter: https://www.twitter.com/bbcafrica/\nInstagram: https://www.instagram.com/bbcafrica/", "first_broadcast_date": null, "display_title": { "title": "Africa Eye", "subtitle": "Sudan’s Secret Hit Squads" }, "ownership": { "service": { "type": null, "id": "bbc_webonly", "key": "", "title": "BBC" } }, "parent": { "programme": { "type": "brand", "pid": "w13xttpn", "title": "Africa Eye", "short_synopsis": "Original and high-impact BBC investigations from across Africa", "media_type": null, "position": null, "image": { "pid": "p06pqg80" }, "expected_child_count": null, "first_broadcast_date": null, "aggregated_episode_count": 25, "ownership": { "service": { "type": null, "id": "bbc_world_service_tv", "key": "worldservicetv", "title": "BBC World Service TV" } } } }, "peers": { "previous": null, "next": null }, "versions": [ { "canonical": 1, "pid": "p079x0qq", "duration": 686, "types": [ "Original version" ] } ], "links": [], "supporting_content_items": [], "categories": [ { "type": "genre", "id": "C00079", "key": "news", "title": "News", "narrower": [], "broader": {}, "has_topic_page": false, "sameAs": null } ] } }
1,286
1,133
/* Copyright 2015 <NAME>.P. 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. */ #ifndef __BDB_OSQL_CUR_H_ #define __BDB_OSQL_CUR_H_ #include "bdb_api.h" #include "bdb_int.h" struct bdb_osql_trn; /** * Frees all shadow files associated with * transaction "tran" * */ int bdb_tran_free_shadows(bdb_state_type *bdb_state, tran_type *tran); /** * Check if a real genid is marked deleted. * */ int bdb_tran_deltbl_isdeleted(bdb_cursor_ifn_t *cur, unsigned long long genid, int ignore_limit, int *bdberr); /** * Check if a delete was already done; this is not related to * transaction mode, and serve only the purpose to dedup * deletes in transactions that naturally occur in one pass deletes * */ int bdb_tran_deltbl_isdeleted_dedup(bdb_cursor_ifn_t *pcur_ifn, unsigned long long genid, int ignore_limit, int *bdberr); /** * Mark the provided genid deleted * data, datalen are defined by upper layers (sqlglue). * */ int bdb_tran_deltbl_setdeleted(bdb_cursor_ifn_t *cur, unsigned long long genid, void *data, int datalen, int *bdberr); /** * Returns the first deleted genid of a transaction if one exists * and a cursor for retrieving the next records. * Returns NULL if no deleted rows. * * */ struct temp_cursor *bdb_tran_deltbl_first(bdb_state_type *bdb_state, tran_type *shadow_tran, int dbnum, unsigned long long *genid, char **data, int *datalen, int *bdberr); /** * Returns the next deleted genid of a transaction * if one exists and IX_OK; * Returns IX_PASTEOF if done. The cursor is destroyed * immediately when returning IX_PASTEOF. * */ int bdb_tran_deltbl_next(bdb_state_type *bdb_state, tran_type *shadow_tran, struct temp_cursor *cur, unsigned long long *genid, char **data, int *datalen, int *bdberr); /** * There are 4 step during a bdbcursor move * 1) If current real row consumed, move real berkdb * 2) Update shadows * 3) If current shadow row consumed, move shadow berkdb * - we need to reposition for relative moves * 4) Merge real and shadow * * This function is handling the step 2 * - get first log * - if there is no log (first == NULL) return * - process each log from first to last (this is the last seen when first log *is * retrieved * - if this is the last log, reset log for transactions * If any shadow row is added/deleted, mark dirty */ int bdb_osql_update_shadows(bdb_cursor_ifn_t *cur, struct bdb_osql_trn *trn, int *dirty, log_ops_t log_op, int *bdberr); /** * Check if a shadow is backfilled * */ int bdb_osql_shadow_is_bkfilled(bdb_cursor_ifn_t *cur, int *bdberr); /** * Set shadow backfilled * */ int bdb_osql_shadow_set_bkfilled(bdb_cursor_ifn_t *cur, int *bdberr); /** * Retrieves the last log processed by this transaction * */ struct bdb_osql_log *bdb_osql_shadow_get_lastlog(bdb_cursor_ifn_t *cur, int *bdberr); /** * Stores the last log processed by this cur (which updates * the shadow btree status * */ int bdb_osql_shadow_set_lastlog(bdb_cursor_ifn_t *cur, struct bdb_osql_log *log, int *bdberr); /** * Clear any cached pointers to existing transactions * Set the shadow transaction to a reset cursor * */ int bdb_osql_cursor_reset(bdb_state_type *bdb_state, bdb_cursor_ifn_t *pcur_ifn); void bdb_osql_cursor_set(bdb_cursor_ifn_t *pcur_ifn, tran_type *shadow_tran); #endif
1,831
1,093
<filename>spring-integration-core/src/main/java/org/springframework/integration/routingslip/ExpressionEvaluatingRoutingSlipRouteStrategy.java /* * Copyright 2014-2019 the original author or 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 * * https://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 org.springframework.integration.routingslip; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.expression.ExpressionUtils; import org.springframework.messaging.Message; /** * The {@link Expression} based {@link RoutingSlipRouteStrategy} implementation. * The {@code requestMessage} and {@code reply} object are wrapped * to the {@link RequestAndReply} which is used as a {@link EvaluationContext} {@code rootObject}. * This is necessary to avoid a creation of a new {@link EvaluationContext} on each invocation * when additional parameter can be populated as expression variable, but {@link EvaluationContext} * isn't thread-safe. * <p> * The {@link ExpressionEvaluatingRoutingSlipRouteStrategy} can be used directly as a regular bean * in the {@code ApplicationContext} and its {@code beanName} can be used from {@code routingSlip} * header configuration. * <p> * Usage of {@link ExpressionEvaluatingRoutingSlipRouteStrategy} as a regular bean definition is * a recommended way in case of distributed environment, when message with {@code routingSlip} * header can be sent across the network. One of this case is a {@code QueueChannel} with * persistent {@code MessageStore}, when {@link ExpressionEvaluatingRoutingSlipRouteStrategy} * instance as a header value will be non-serializable. * <p> * This class is used internally from {@code RoutingSlipHeaderValueMessageProcessor} * to populate {@code routingSlip} header value item, when the {@code value} * from configuration contains expression definitions: * <pre class="code"> * {@code * <header-enricher> * <routing-slip * value="channel1; @routingSlipPojo.get(request, reply); request.headers[foo]"/> * </header-enricher> * } * </pre> * * @author <NAME> * @author <NAME> * * @since 4.1 */ public class ExpressionEvaluatingRoutingSlipRouteStrategy implements RoutingSlipRouteStrategy, BeanFactoryAware, InitializingBean { private static final ExpressionParser PARSER = new SpelExpressionParser(); private final Expression expression; private EvaluationContext evaluationContext; private BeanFactory beanFactory; public ExpressionEvaluatingRoutingSlipRouteStrategy(String expression) { this(PARSER.parseExpression(expression)); } public ExpressionEvaluatingRoutingSlipRouteStrategy(Expression expression) { this.expression = expression; } public void setIntegrationEvaluationContext(EvaluationContext evaluationContext) { this.evaluationContext = evaluationContext; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } @Override public void afterPropertiesSet() { if (this.evaluationContext == null) { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(this.beanFactory); } } @Override public Object getNextPath(Message<?> requestMessage, Object reply) { return this.expression.getValue(this.evaluationContext, new RequestAndReply(requestMessage, reply)); } @Override public String toString() { return "ExpressionEvaluatingRoutingSlipRouteStrategy for: [" + this.expression.getExpressionString() + "]"; } public static class RequestAndReply { private final Message<?> request; private final Object reply; RequestAndReply(Message<?> request, Object reply) { this.request = request; this.reply = reply; } public Message<?> getRequest() { return this.request; } public Object getReply() { return this.reply; } } }
1,342
3,103
# 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. """ create role invitation table Revision ID: 8<PASSWORD>46c5a4 Revises: <PASSWORD> Create Date: 2020-06-28 14:53:07.803972 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql revision = "80018e46c5a4" down_revision = "<PASSWORD>" def upgrade(): op.create_table( "role_invitations", sa.Column( "id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), nullable=False, ), sa.Column("invite_status", sa.Text(), nullable=False), sa.Column("token", sa.Text(), nullable=False), sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=False), sa.Column("project_id", postgresql.UUID(as_uuid=True), nullable=False), sa.ForeignKeyConstraint( ["project_id"], ["projects.id"], onupdate="CASCADE", ondelete="CASCADE" ), sa.ForeignKeyConstraint( ["user_id"], ["users.id"], onupdate="CASCADE", ondelete="CASCADE" ), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint( "user_id", "project_id", name="_role_invitations_user_project_uc" ), ) op.create_index( "role_invitations_user_id_idx", "role_invitations", ["user_id"], unique=False ) def downgrade(): op.drop_index("role_invitations_user_id_idx", table_name="role_invitations") op.drop_table("role_invitations")
804
2,338
//==-- OverflowInstAnalysis.cpp - Utils to fold overflow insts ----*- C++ -*-=// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file holds routines to help analyse overflow instructions // and fold them into constants or other overflow instructions // //===----------------------------------------------------------------------===// #include "llvm/Analysis/OverflowInstAnalysis.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/PatternMatch.h" using namespace llvm; using namespace llvm::PatternMatch; bool llvm::isCheckForZeroAndMulWithOverflow(Value *Op0, Value *Op1, bool IsAnd, Use *&Y) { ICmpInst::Predicate Pred; Value *X, *NotOp1; int XIdx; IntrinsicInst *II; if (!match(Op0, m_ICmp(Pred, m_Value(X), m_Zero()))) return false; /// %Agg = call { i4, i1 } @llvm.[us]mul.with.overflow.i4(i4 %X, i4 %???) /// %V = extractvalue { i4, i1 } %Agg, 1 auto matchMulOverflowCheck = [X, &II, &XIdx](Value *V) { auto *Extract = dyn_cast<ExtractValueInst>(V); // We should only be extracting the overflow bit. if (!Extract || !Extract->getIndices().equals(1)) return false; II = dyn_cast<IntrinsicInst>(Extract->getAggregateOperand()); if (!II || !match(II, m_CombineOr(m_Intrinsic<Intrinsic::umul_with_overflow>(), m_Intrinsic<Intrinsic::smul_with_overflow>()))) return false; if (II->getArgOperand(0) == X) XIdx = 0; else if (II->getArgOperand(1) == X) XIdx = 1; else return false; return true; }; bool Matched = (IsAnd && Pred == ICmpInst::Predicate::ICMP_NE && matchMulOverflowCheck(Op1)) || (!IsAnd && Pred == ICmpInst::Predicate::ICMP_EQ && match(Op1, m_Not(m_Value(NotOp1))) && matchMulOverflowCheck(NotOp1)); if (!Matched) return false; Y = &II->getArgOperandUse(!XIdx); return true; } bool llvm::isCheckForZeroAndMulWithOverflow(Value *Op0, Value *Op1, bool IsAnd) { Use *Y; return isCheckForZeroAndMulWithOverflow(Op0, Op1, IsAnd, Y); }
994
370
#define DLONG #include <../Source/umf_usolve.c>
20
984
<filename>query-builder/src/main/java/com/datastax/oss/driver/internal/querybuilder/insert/DefaultInsert.java /* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.driver.internal.querybuilder.insert; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.cql.SimpleStatement; import com.datastax.oss.driver.api.core.cql.SimpleStatementBuilder; import com.datastax.oss.driver.api.core.type.codec.TypeCodec; import com.datastax.oss.driver.api.querybuilder.BindMarker; import com.datastax.oss.driver.api.querybuilder.QueryBuilder; import com.datastax.oss.driver.api.querybuilder.insert.Insert; import com.datastax.oss.driver.api.querybuilder.insert.InsertInto; import com.datastax.oss.driver.api.querybuilder.insert.JsonInsert; import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert; import com.datastax.oss.driver.api.querybuilder.term.Term; import com.datastax.oss.driver.internal.querybuilder.CqlHelper; import com.datastax.oss.driver.internal.querybuilder.ImmutableCollections; import com.datastax.oss.driver.shaded.guava.common.base.Preconditions; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import java.util.Map; import net.jcip.annotations.Immutable; @Immutable public class DefaultInsert implements InsertInto, RegularInsert, JsonInsert { public enum MissingJsonBehavior { NULL, UNSET } private final CqlIdentifier keyspace; private final CqlIdentifier table; private final Term json; private final MissingJsonBehavior missingJsonBehavior; private final ImmutableMap<CqlIdentifier, Term> assignments; private final Object timestamp; private final Object ttlInSeconds; private final boolean ifNotExists; public DefaultInsert(@Nullable CqlIdentifier keyspace, @NonNull CqlIdentifier table) { this(keyspace, table, null, null, ImmutableMap.of(), null, null, false); } public DefaultInsert( @Nullable CqlIdentifier keyspace, @NonNull CqlIdentifier table, @Nullable Term json, @Nullable MissingJsonBehavior missingJsonBehavior, @NonNull ImmutableMap<CqlIdentifier, Term> assignments, @Nullable Object timestamp, @Nullable Object ttlInSeconds, boolean ifNotExists) { // Note: the public API guarantees this, but check in case someone is calling the internal API // directly. Preconditions.checkArgument( json == null || assignments.isEmpty(), "JSON insert can't have regular assignments"); Preconditions.checkArgument( timestamp == null || timestamp instanceof Long || timestamp instanceof BindMarker, "TIMESTAMP value must be a BindMarker or a Long"); Preconditions.checkArgument( ttlInSeconds == null || ttlInSeconds instanceof Integer || ttlInSeconds instanceof BindMarker, "TTL value must be a BindMarker or an Integer"); this.keyspace = keyspace; this.table = table; this.json = json; this.missingJsonBehavior = missingJsonBehavior; this.assignments = assignments; this.timestamp = timestamp; this.ttlInSeconds = ttlInSeconds; this.ifNotExists = ifNotExists; } @NonNull @Override public JsonInsert json(@NonNull String json) { return new DefaultInsert( keyspace, table, QueryBuilder.literal(json), missingJsonBehavior, ImmutableMap.of(), timestamp, ttlInSeconds, ifNotExists); } @NonNull @Override public JsonInsert json(@NonNull BindMarker json) { return new DefaultInsert( keyspace, table, json, missingJsonBehavior, ImmutableMap.of(), timestamp, ttlInSeconds, ifNotExists); } @NonNull @Override public <T> JsonInsert json(@NonNull T value, @NonNull TypeCodec<T> codec) { return new DefaultInsert( keyspace, table, QueryBuilder.literal(value, codec), missingJsonBehavior, ImmutableMap.of(), timestamp, ttlInSeconds, ifNotExists); } @NonNull @Override public JsonInsert defaultNull() { return new DefaultInsert( keyspace, table, json, MissingJsonBehavior.NULL, ImmutableMap.of(), timestamp, ttlInSeconds, ifNotExists); } @NonNull @Override public JsonInsert defaultUnset() { return new DefaultInsert( keyspace, table, json, MissingJsonBehavior.UNSET, ImmutableMap.of(), timestamp, ttlInSeconds, ifNotExists); } @NonNull @Override public RegularInsert value(@NonNull CqlIdentifier columnId, @NonNull Term value) { return new DefaultInsert( keyspace, table, null, null, ImmutableCollections.append(assignments, columnId, value), timestamp, ttlInSeconds, ifNotExists); } @NonNull @Override public RegularInsert valuesByIds(@NonNull Map<CqlIdentifier, Term> newAssignments) { return new DefaultInsert( keyspace, table, null, null, ImmutableCollections.concat(assignments, newAssignments), timestamp, ttlInSeconds, ifNotExists); } @NonNull @Override public Insert ifNotExists() { return new DefaultInsert( keyspace, table, json, missingJsonBehavior, assignments, timestamp, ttlInSeconds, true); } @NonNull @Override public Insert usingTimestamp(long timestamp) { return new DefaultInsert( keyspace, table, json, missingJsonBehavior, assignments, timestamp, ttlInSeconds, ifNotExists); } @NonNull @Override public Insert usingTimestamp(@Nullable BindMarker timestamp) { return new DefaultInsert( keyspace, table, json, missingJsonBehavior, assignments, timestamp, ttlInSeconds, ifNotExists); } @NonNull @Override public Insert usingTtl(int ttlInSeconds) { return new DefaultInsert( keyspace, table, json, missingJsonBehavior, assignments, timestamp, ttlInSeconds, ifNotExists); } @NonNull @Override public Insert usingTtl(@Nullable BindMarker ttlInSeconds) { return new DefaultInsert( keyspace, table, json, missingJsonBehavior, assignments, timestamp, ttlInSeconds, ifNotExists); } @NonNull @Override public String asCql() { StringBuilder builder = new StringBuilder("INSERT INTO "); CqlHelper.qualify(keyspace, table, builder); if (json == null) { CqlHelper.appendIds(assignments.keySet(), builder, " (", ",", ")"); CqlHelper.append(assignments.values(), builder, " VALUES (", ",", ")"); } else { builder.append(" JSON "); json.appendTo(builder); if (missingJsonBehavior == MissingJsonBehavior.NULL) { builder.append(" DEFAULT NULL"); } else if (missingJsonBehavior == MissingJsonBehavior.UNSET) { builder.append(" DEFAULT UNSET"); } } if (ifNotExists) { builder.append(" IF NOT EXISTS"); } if (timestamp != null) { builder.append(" USING TIMESTAMP "); if (timestamp instanceof BindMarker) { ((BindMarker) timestamp).appendTo(builder); } else { builder.append(timestamp); } } if (ttlInSeconds != null) { builder.append((timestamp != null) ? " AND " : " USING ").append("TTL "); if (ttlInSeconds instanceof BindMarker) { ((BindMarker) ttlInSeconds).appendTo(builder); } else { builder.append(ttlInSeconds); } } return builder.toString(); } @NonNull @Override public SimpleStatement build() { return builder().build(); } @NonNull @Override public SimpleStatement build(@NonNull Object... values) { return builder().addPositionalValues(values).build(); } @NonNull @Override public SimpleStatement build(@NonNull Map<String, Object> namedValues) { SimpleStatementBuilder builder = builder(); for (Map.Entry<String, Object> entry : namedValues.entrySet()) { builder.addNamedValue(entry.getKey(), entry.getValue()); } return builder.build(); } @NonNull @Override public SimpleStatementBuilder builder() { return SimpleStatement.builder(asCql()).setIdempotence(isIdempotent()); } public boolean isIdempotent() { // Conditional queries are never idempotent, see JAVA-819 if (ifNotExists) { return false; } else { for (Term value : assignments.values()) { if (!value.isIdempotent()) { return false; } } return true; } } @Nullable public CqlIdentifier getKeyspace() { return keyspace; } @NonNull public CqlIdentifier getTable() { return table; } @Nullable public Object getJson() { return json; } @Nullable public MissingJsonBehavior getMissingJsonBehavior() { return missingJsonBehavior; } @NonNull public ImmutableMap<CqlIdentifier, Term> getAssignments() { return assignments; } @Nullable public Object getTimestamp() { return timestamp; } @Nullable public Object getTtlInSeconds() { return ttlInSeconds; } public boolean isIfNotExists() { return ifNotExists; } @Override public String toString() { return asCql(); } }
3,972
7,482
/****************************************************************************** * * @brief providing APIs for configuring I2C module (I2C). * ******************************************************************************* * * provide APIs for configuring I2C module (I2C). ******************************************************************************/ #include "common.h" #include "i2c.h" /****************************************************************************** * Global variables ******************************************************************************/ /****************************************************************************** * Constants and macros ******************************************************************************/ /****************************************************************************** * Local types ******************************************************************************/ /****************************************************************************** * Local function prototypes ******************************************************************************/ /****************************************************************************** * Local variables ******************************************************************************/ static I2C_CallbackType I2C_Callback[2] = {(I2C_CallbackType)NULL}; /****************************************************************************** * Local functions ******************************************************************************/ void I2C0_Isr( void ); /****************************************************************************** * Global functions ******************************************************************************/ /****************************************************************************** * define I2C APIs * *//*! @addtogroup i2c_api_list * @{ *******************************************************************************/ /*****************************************************************************//*! * * @brief Initialize I2C module. * * @param[in] pI2Cx point to I2C module type. * @param[in] pI2CConfig point to I2C configure structure. * * @return none * * @ Pass/ Fail criteria: none *****************************************************************************/ void I2C_Init(I2C_Type *pI2Cx,I2C_ConfigPtr pI2CConfig) { uint8_t u8Temp; #if defined(CPU_NV32) SIM->SCGC |= SIM_SCGC_IIC_MASK; #elif defined(CPU_NV32M3) SIM->SCGC |= SIM_SCGC_IIC_MASK; #elif defined(CPU_NV32M4) if(pI2Cx == I2C0) { SIM->SCGC |= SIM_SCGC_I2C0_MASK; } else { SIM->SCGC |= SIM_SCGC_I2C1_MASK; } #endif I2C_SetBaudRate(pI2Cx,pI2CConfig->u16F); I2C_SetSlaveAddress(pI2Cx,pI2CConfig->u16OwnA1); pI2Cx->FLT = (uint8_t)pI2CConfig->u16Filt; pI2Cx->RA = (uint8_t)pI2CConfig->u16RangeA & 0xfe; I2C_SetSCLLowETMeout(pI2Cx,pI2CConfig->u16Slt); /* configure C2 control register */ u8Temp = 0; if( pI2CConfig->sSetting.bGCAEn ) { u8Temp |= I2C_C2_GCAEN_MASK; } if( pI2CConfig->sSetting.bAddressExt ) { u8Temp |= I2C_C2_ADEXT_MASK; } if( pI2CConfig->sSetting.bRangeAddEn ) { u8Temp |= I2C_C2_RMEN_MASK; } pI2Cx->C2 |= u8Temp; /* configure SMB rehister */ u8Temp = 0; if( pI2CConfig->sSetting.bFackEn ) { u8Temp |= I2C_SMB_FACK_MASK; } if( pI2CConfig->sSetting.bSMB_AlertEn ) { u8Temp |= I2C_SMB_ALERTEN_MASK; } if( pI2CConfig->sSetting.bSecondAddressEn ) { u8Temp |= I2C_SMB_SIICAEN_MASK; } if( pI2CConfig->sSetting.bSHTF2IntEn ) { u8Temp |= I2C_SMB_SHTF2IE_MASK; } pI2Cx->SMB = u8Temp; /* configure C1 rehister */ u8Temp = 0; if( pI2CConfig->sSetting.bIntEn ) { u8Temp |= I2C_C1_IICIE_MASK; if(pI2Cx == I2C0) { NVIC_EnableIRQ(I2C0_IRQn); } #if defined(CPU_NV32M4) else if(pI2Cx == I2C1) { NVIC_EnableIRQ(I2C1_IRQn); } #endif else { // } } if( pI2CConfig->sSetting.bWakeUpEn ) { u8Temp |= I2C_C1_WUEN_MASK; } if( pI2CConfig->sSetting.bI2CEn ) { u8Temp |= I2C_C1_IICEN_MASK; } pI2Cx->C1 = u8Temp; } /*****************************************************************************//*! * * @brief send out start signals. * * @param[in] pI2Cx point to I2C module type. * * @return error status * * @ Pass/ Fail criteria: none *****************************************************************************/ uint8_t I2C_Start(I2C_Type *pI2Cx) { uint32_t u32ETMeout; uint8_t u8ErrorStatus; u32ETMeout = 0; u8ErrorStatus = 0x00; I2C_TxEnable(pI2Cx); pI2Cx->C1 |= I2C_C1_MST_MASK; while( (!I2C_IsBusy(pI2Cx)) && ( u32ETMeout < I2C_WAIT_STATUS_ETMEOUT)) { u32ETMeout ++; } if( u32ETMeout == I2C_WAIT_STATUS_ETMEOUT ) { u8ErrorStatus |= I2C_ERROR_START_NO_BUSY_FLAG; } return u8ErrorStatus; } /*****************************************************************************//*! * * @brief send out stop signals. * * @param[in] pI2Cx point to I2C module type. * * @return error status * * @ Pass/ Fail criteria: none *****************************************************************************/ uint8_t I2C_Stop(I2C_Type *pI2Cx) { uint32_t u32ETMeout; uint8_t u8ErrorStatus; u32ETMeout = 0; u8ErrorStatus = 0x00; pI2Cx->C1 &= ~I2C_C1_MST_MASK; while( (I2C_IsBusy(pI2Cx) ) && ( u32ETMeout < I2C_WAIT_STATUS_ETMEOUT)) { u32ETMeout ++; } if( u32ETMeout == I2C_WAIT_STATUS_ETMEOUT ) { u8ErrorStatus |= I2C_ERROR_STOP_BUSY_FLAG; } return u8ErrorStatus; } /*****************************************************************************//*! * * @brief send out repeat start signals. * * @param[in] pI2Cx point to I2C module type. * * @return error status. * * @ Pass/ Fail criteria: none *****************************************************************************/ uint8_t I2C_RepeatStart(I2C_Type *pI2Cx) { uint32_t u32ETMeout; uint8_t u8ErrorStatus; u32ETMeout = 0; u8ErrorStatus = 0x00; pI2Cx->C1 |= I2C_C1_RSTA_MASK; while( (!I2C_IsBusy(I2C0) ) && ( u32ETMeout < I2C_WAIT_STATUS_ETMEOUT)) { u32ETMeout ++; } if( u32ETMeout == I2C_WAIT_STATUS_ETMEOUT ) { u8ErrorStatus |= I2C_ERROR_START_NO_BUSY_FLAG; } return u8ErrorStatus; } /*****************************************************************************//*! * * @brief set slave address. * * @param[in] pI2Cx point to I2C module type. * * @return none * * @ Pass/ Fail criteria: none *****************************************************************************/ void I2C_SetSlaveAddress(I2C_Type *pI2Cx,uint16_t u16SlaveAddress) { /* write low 8bit address */ pI2Cx->A1 = (uint8_t)u16SlaveAddress; /* write high 3bit address if it support 10bit slave address */ pI2Cx->C2 &= ~I2C_C2_AD_MASK; pI2Cx->C2 |= (uint8_t)(u16SlaveAddress>>8)&0x03; } /*****************************************************************************//*! * * @brief disable IICIF interrupt. * * @param[in] pI2Cx point to I2C module type. * * @return none. * * @ Pass/ Fail criteria: none *****************************************************************************/ void I2C_IntDisable(I2C_Type *pI2Cx) { pI2Cx->C1 &= ~I2C_C1_IICIE_MASK; if(pI2Cx == I2C0) { NVIC_DisableIRQ(I2C0_IRQn); } #if defined(CPU_NV32M4) else if(pI2Cx == I2C1) { NVIC_DisableIRQ(I2C1_IRQn); } #endif else { } } /*****************************************************************************//*! * * @brief enable IICIF interrupt. * * @param[in] pI2Cx point to I2C module type. * * @return none. * * @ Pass/ Fail criteria: none. *****************************************************************************/ void I2C_IntEnable(I2C_Type *pI2Cx) { pI2Cx->C1 |= I2C_C1_IICIE_MASK; if(pI2Cx == I2C0) { NVIC_EnableIRQ(I2C0_IRQn); } #if defined(CPU_NV32M4) else if(pI2Cx == I2C1) { NVIC_EnableIRQ(I2C1_IRQn); } #endif else { } } /*****************************************************************************//*! * * @brief SCL low ETMeout value that determines the ETMeout period of SCL low. * * @param[in] pI2Cx point to I2C module type. * * @return none. * * @ Pass/ Fail criteria: none. *****************************************************************************/ void I2C_SetSCLLowETMeout(I2C_Type *pI2Cx, uint16_t u16ETMeout) { pI2Cx->SLTL = (uint8_t)u16ETMeout; pI2Cx->SLTH = (uint8_t)(u16ETMeout>>8); } /*****************************************************************************//*! * * @brief deinit I2C module. * * @param[in] pI2Cx point to I2C module type. * * @return none * * @ Pass/ Fail criteria: none *****************************************************************************/ void I2C_Deinit(I2C_Type *pI2Cx) { pI2Cx->C1 &= ~I2C_C1_IICEN_MASK; #if defined(CPU_NV32) SIM->SCGC &= ~SIM_SCGC_IIC_MASK; #elif defined(CPU_NV32M3) SIM->SCGC &= ~SIM_SCGC_IIC_MASK; #elif defined(CPU_NV32M4) if(pI2Cx == I2C0) { SIM->SCGC &= ~SIM_SCGC_I2C0_MASK; } else { SIM->SCGC &= ~SIM_SCGC_I2C1_MASK; } #endif } /*****************************************************************************//*! * * @brief write a byte to I2C module. * * @param[in] pI2Cx point to I2C module type. * @param[in] u8WrBuff data buffer for writing. * * @return error status * * @ Pass/ Fail criteria: none *****************************************************************************/ uint8_t I2C_WriteOneByte(I2C_Type *pI2Cx, uint8_t u8WrBuff) { uint32_t u32ETMeout; uint8_t u8ErrorStatus; u32ETMeout = 0; u8ErrorStatus = 0x00; while (((I2C_GetStatus(pI2Cx)&I2C_S_TCF_MASK) != I2C_S_TCF_MASK) && (u32ETMeout<I2C_WAIT_STATUS_ETMEOUT)) { u32ETMeout ++; } if (u32ETMeout >= I2C_WAIT_STATUS_ETMEOUT) { u8ErrorStatus |= I2C_ERROR_NO_WAIT_TCF_FLAG; return u8ErrorStatus; } I2C_TxEnable(pI2Cx); I2C_WriteDataReg(pI2Cx,u8WrBuff); u32ETMeout = 0; while (((I2C_GetStatus(pI2Cx)&I2C_S_IICIF_MASK) != I2C_S_IICIF_MASK) && (u32ETMeout<I2C_WAIT_STATUS_ETMEOUT)) { u32ETMeout ++; } if (u32ETMeout >= I2C_WAIT_STATUS_ETMEOUT) { u8ErrorStatus |= I2C_ERROR_NO_WAIT_IICIF_FLAG; return u8ErrorStatus; } /* clear IICIF flag */ I2C_ClearStatus(pI2Cx,I2C_S_IICIF_MASK); if (I2C_GetStatus(pI2Cx) & I2C_S_RXAK_MASK) { u8ErrorStatus |= I2C_ERROR_NO_GET_ACK; } return u8ErrorStatus; } /*****************************************************************************//*! * * @brief read a byte from slave I2C. * * @param[in] pI2Cx point to I2C module type. * @param[out] pRdBuff point to the data read from slave I2C. * @param[out] u8Ack send out ack or nack. * * @return error status * * @ Pass/ Fail criteria: none *****************************************************************************/ uint8_t I2C_ReadOneByte(I2C_Type *pI2Cx, uint8_t *pRdBuff, uint8_t u8Ack) { uint32_t u32ETMeout; uint8_t u8ErrorStatus; u32ETMeout = 0; u8ErrorStatus = 0x00; while (((I2C_GetStatus(pI2Cx)&I2C_S_TCF_MASK) != I2C_S_TCF_MASK) && (u32ETMeout<I2C_WAIT_STATUS_ETMEOUT)) { u32ETMeout ++; } if (u32ETMeout >= I2C_WAIT_STATUS_ETMEOUT) { u8ErrorStatus |= I2C_ERROR_NO_WAIT_TCF_FLAG; return u8ErrorStatus; } I2C_RxEnable(pI2Cx); if( u8Ack ) { /* send out nack */ I2C_SendNack(pI2Cx); } else { /* send out ack */ I2C_SendAck(pI2Cx); } *pRdBuff = I2C_ReadDataReg(pI2Cx); u32ETMeout = 0; while (((I2C_GetStatus(pI2Cx)&I2C_S_IICIF_MASK) != I2C_S_IICIF_MASK) && (u32ETMeout<I2C_WAIT_STATUS_ETMEOUT)) { u32ETMeout ++; } if (u32ETMeout >= I2C_WAIT_STATUS_ETMEOUT) { u8ErrorStatus |= I2C_ERROR_NO_WAIT_IICIF_FLAG; return u8ErrorStatus; } /* clear IICIF flag */ I2C_ClearStatus(pI2Cx,I2C_S_IICIF_MASK); return u8ErrorStatus; } /*****************************************************************************//*! * * @brief send data to I2C, and wait to complete transfering. * * @param[in] pI2Cx point to I2C module type. * @param[in] u16SlaveAddress slave address. * @param[in] pWrBuff point the first address of transfering data buffer. * @param[in] the length of transfering data. * * @return error status * * @ Pass/ Fail criteria: none *****************************************************************************/ uint8_t I2C_MasterSendWait(I2C_Type *pI2Cx,uint16_t u16SlaveAddress,uint8_t *pWrBuff,uint32_t u32Length) { uint32_t i; uint8_t u8ErrorStatus; /* send start signals to bus */ u8ErrorStatus = I2C_Start(pI2Cx); /* send device address to slave */ u8ErrorStatus = I2C_WriteOneByte(pI2Cx,((uint8_t)u16SlaveAddress<<1) | I2C_WRITE); /* if no error occur, received the correct ack from slave continue to send data to slave */ if( u8ErrorStatus == I2C_ERROR_NULL ) { for(i=0;i<u32Length;i++) { u8ErrorStatus = I2C_WriteOneByte(pI2Cx,pWrBuff[i]); if( u8ErrorStatus != I2C_ERROR_NULL ) { return u8ErrorStatus; } } } /* send stop signals to bus */ u8ErrorStatus = I2C_Stop(pI2Cx); return u8ErrorStatus; } /*****************************************************************************//*! * * @brief read data from I2C,and wait to complete transferring. * * @param[in] pI2Cx point to I2C module type. * @param[in] u16SlaveAddress slave address. * @param[in] pRdBuff point the first address of reading data buffer. * @param[in] the length of transfering data. * * @return error status * * @ Pass/ Fail criteria: none *****************************************************************************/ uint8_t I2C_MasterReadWait(I2C_Type *pI2Cx,uint16_t u16SlaveAddress,uint8_t *pRdBuff,uint32_t u32Length) { uint32_t i; uint8_t u8ErrorStatus; /* send start signals to bus */ u8ErrorStatus = I2C_Start(pI2Cx); /* send device address to slave */ u8ErrorStatus = I2C_WriteOneByte(pI2Cx,((uint8_t)u16SlaveAddress<<1) | I2C_READ); /* if no error occur, received the correct ack from slave continue to send data to slave */ /* dummy read one byte to switch to Rx mode */ I2C_ReadOneByte(pI2Cx,&pRdBuff[0],I2C_SEND_ACK); if( u8ErrorStatus == I2C_ERROR_NULL ) { for(i=0;i<u32Length-1;i++) { u8ErrorStatus = I2C_ReadOneByte(pI2Cx,&pRdBuff[i],I2C_SEND_ACK); if( u8ErrorStatus != I2C_ERROR_NULL ) { return u8ErrorStatus; } } u8ErrorStatus = I2C_ReadOneByte(pI2Cx,&pRdBuff[i],I2C_SEND_NACK); } /* send stop signals to bus */ u8ErrorStatus = I2C_Stop(pI2Cx); return u8ErrorStatus; } /*****************************************************************************//*! * * @brief set call back function for I2C1 module. * * @param[in] pCallBack point to address of I2C1 call back function. * * @return none. * * @ Pass/ Fail criteria: none. *****************************************************************************/ void I2C1_SetCallBack( I2C_CallbackType pCallBack ) { I2C_Callback[1] = pCallBack; } /*****************************************************************************//*! * * @brief set call back function for I2C0 module. * * @param[in] pCallBack point to address of I2C0 call back function. * * @return none. * * @ Pass/ Fail criteria: none. *****************************************************************************/ void I2C0_SetCallBack( I2C_CallbackType pCallBack ) { I2C_Callback[0] = pCallBack; } /*! @} End of i2c_api_list */ /*****************************************************************************//*! * * @brief I2C0 interrupt service routine. * * @param * * @return none * * @ Pass/ Fail criteria: none *****************************************************************************/ void I2C0_Isr( void ) { if( I2C_Callback[0] ) { I2C_Callback[0](); } } /*****************************************************************************//*! * * @brief I2C1 interrupt service routine. * * @param * * @return none * * @ Pass/ Fail criteria: none *****************************************************************************/ void I2C1_Isr( void ) { if( I2C_Callback[1] ) { I2C_Callback[1](); } }
7,779
312
<reponame>DKesserich/godot-git-plugin<gh_stars>100-1000 /* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "common.h" #include "diff.h" #include "diff_file.h" #include "patch_generate.h" #include "futils.h" #include "zstream.h" #include "blob.h" #include "delta.h" #include "git2/sys/diff.h" typedef struct { git_diff_format_t format; git_diff_line_cb print_cb; void *payload; git_buf *buf; git_diff_line line; const char *old_prefix; const char *new_prefix; uint32_t flags; int id_strlen; int (*strcomp)(const char *, const char *); } diff_print_info; static int diff_print_info_init__common( diff_print_info *pi, git_buf *out, git_repository *repo, git_diff_format_t format, git_diff_line_cb cb, void *payload) { pi->format = format; pi->print_cb = cb; pi->payload = payload; pi->buf = out; if (!pi->id_strlen) { if (!repo) pi->id_strlen = GIT_ABBREV_DEFAULT; else if (git_repository__configmap_lookup(&pi->id_strlen, repo, GIT_CONFIGMAP_ABBREV) < 0) return -1; } if (pi->id_strlen > GIT_OID_HEXSZ) pi->id_strlen = GIT_OID_HEXSZ; memset(&pi->line, 0, sizeof(pi->line)); pi->line.old_lineno = -1; pi->line.new_lineno = -1; pi->line.num_lines = 1; return 0; } static int diff_print_info_init_fromdiff( diff_print_info *pi, git_buf *out, git_diff *diff, git_diff_format_t format, git_diff_line_cb cb, void *payload) { git_repository *repo = diff ? diff->repo : NULL; memset(pi, 0, sizeof(diff_print_info)); if (diff) { pi->flags = diff->opts.flags; pi->id_strlen = diff->opts.id_abbrev; pi->old_prefix = diff->opts.old_prefix; pi->new_prefix = diff->opts.new_prefix; pi->strcomp = diff->strcomp; } return diff_print_info_init__common(pi, out, repo, format, cb, payload); } static int diff_print_info_init_frompatch( diff_print_info *pi, git_buf *out, git_patch *patch, git_diff_format_t format, git_diff_line_cb cb, void *payload) { assert(patch); memset(pi, 0, sizeof(diff_print_info)); pi->flags = patch->diff_opts.flags; pi->id_strlen = patch->diff_opts.id_abbrev; pi->old_prefix = patch->diff_opts.old_prefix; pi->new_prefix = patch->diff_opts.new_prefix; return diff_print_info_init__common(pi, out, patch->repo, format, cb, payload); } static char diff_pick_suffix(int mode) { if (S_ISDIR(mode)) return '/'; else if (GIT_PERMS_IS_EXEC(mode)) /* -V536 */ /* in git, modes are very regular, so we must have 0100755 mode */ return '*'; else return ' '; } char git_diff_status_char(git_delta_t status) { char code; switch (status) { case GIT_DELTA_ADDED: code = 'A'; break; case GIT_DELTA_DELETED: code = 'D'; break; case GIT_DELTA_MODIFIED: code = 'M'; break; case GIT_DELTA_RENAMED: code = 'R'; break; case GIT_DELTA_COPIED: code = 'C'; break; case GIT_DELTA_IGNORED: code = 'I'; break; case GIT_DELTA_UNTRACKED: code = '?'; break; case GIT_DELTA_TYPECHANGE: code = 'T'; break; case GIT_DELTA_UNREADABLE: code = 'X'; break; default: code = ' '; break; } return code; } static int diff_print_one_name_only( const git_diff_delta *delta, float progress, void *data) { diff_print_info *pi = data; git_buf *out = pi->buf; GIT_UNUSED(progress); if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 && delta->status == GIT_DELTA_UNMODIFIED) return 0; git_buf_clear(out); git_buf_puts(out, delta->new_file.path); git_buf_putc(out, '\n'); if (git_buf_oom(out)) return -1; pi->line.origin = GIT_DIFF_LINE_FILE_HDR; pi->line.content = git_buf_cstr(out); pi->line.content_len = git_buf_len(out); return pi->print_cb(delta, NULL, &pi->line, pi->payload); } static int diff_print_one_name_status( const git_diff_delta *delta, float progress, void *data) { diff_print_info *pi = data; git_buf *out = pi->buf; char old_suffix, new_suffix, code = git_diff_status_char(delta->status); int(*strcomp)(const char *, const char *) = pi->strcomp ? pi->strcomp : git__strcmp; GIT_UNUSED(progress); if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 && code == ' ') return 0; old_suffix = diff_pick_suffix(delta->old_file.mode); new_suffix = diff_pick_suffix(delta->new_file.mode); git_buf_clear(out); if (delta->old_file.path != delta->new_file.path && strcomp(delta->old_file.path,delta->new_file.path) != 0) git_buf_printf(out, "%c\t%s%c %s%c\n", code, delta->old_file.path, old_suffix, delta->new_file.path, new_suffix); else if (delta->old_file.mode != delta->new_file.mode && delta->old_file.mode != 0 && delta->new_file.mode != 0) git_buf_printf(out, "%c\t%s%c %s%c\n", code, delta->old_file.path, old_suffix, delta->new_file.path, new_suffix); else if (old_suffix != ' ') git_buf_printf(out, "%c\t%s%c\n", code, delta->old_file.path, old_suffix); else git_buf_printf(out, "%c\t%s\n", code, delta->old_file.path); if (git_buf_oom(out)) return -1; pi->line.origin = GIT_DIFF_LINE_FILE_HDR; pi->line.content = git_buf_cstr(out); pi->line.content_len = git_buf_len(out); return pi->print_cb(delta, NULL, &pi->line, pi->payload); } static int diff_print_one_raw( const git_diff_delta *delta, float progress, void *data) { diff_print_info *pi = data; git_buf *out = pi->buf; int id_abbrev; char code = git_diff_status_char(delta->status); char start_oid[GIT_OID_HEXSZ+1], end_oid[GIT_OID_HEXSZ+1]; GIT_UNUSED(progress); if ((pi->flags & GIT_DIFF_SHOW_UNMODIFIED) == 0 && code == ' ') return 0; git_buf_clear(out); id_abbrev = delta->old_file.mode ? delta->old_file.id_abbrev : delta->new_file.id_abbrev; if (pi->id_strlen > id_abbrev) { git_error_set(GIT_ERROR_PATCH, "the patch input contains %d id characters (cannot print %d)", id_abbrev, pi->id_strlen); return -1; } git_oid_tostr(start_oid, pi->id_strlen + 1, &delta->old_file.id); git_oid_tostr(end_oid, pi->id_strlen + 1, &delta->new_file.id); git_buf_printf( out, (pi->id_strlen <= GIT_OID_HEXSZ) ? ":%06o %06o %s... %s... %c" : ":%06o %06o %s %s %c", delta->old_file.mode, delta->new_file.mode, start_oid, end_oid, code); if (delta->similarity > 0) git_buf_printf(out, "%03u", delta->similarity); if (delta->old_file.path != delta->new_file.path) git_buf_printf( out, "\t%s %s\n", delta->old_file.path, delta->new_file.path); else git_buf_printf( out, "\t%s\n", delta->old_file.path ? delta->old_file.path : delta->new_file.path); if (git_buf_oom(out)) return -1; pi->line.origin = GIT_DIFF_LINE_FILE_HDR; pi->line.content = git_buf_cstr(out); pi->line.content_len = git_buf_len(out); return pi->print_cb(delta, NULL, &pi->line, pi->payload); } static int diff_print_modes( git_buf *out, const git_diff_delta *delta) { git_buf_printf(out, "old mode %o\n", delta->old_file.mode); git_buf_printf(out, "new mode %o\n", delta->new_file.mode); return git_buf_oom(out) ? -1 : 0; } static int diff_print_oid_range( git_buf *out, const git_diff_delta *delta, int id_strlen, bool print_index) { char start_oid[GIT_OID_HEXSZ+1], end_oid[GIT_OID_HEXSZ+1]; if (delta->old_file.mode && id_strlen > delta->old_file.id_abbrev) { git_error_set(GIT_ERROR_PATCH, "the patch input contains %d id characters (cannot print %d)", delta->old_file.id_abbrev, id_strlen); return -1; } if ((delta->new_file.mode && id_strlen > delta->new_file.id_abbrev)) { git_error_set(GIT_ERROR_PATCH, "the patch input contains %d id characters (cannot print %d)", delta->new_file.id_abbrev, id_strlen); return -1; } git_oid_tostr(start_oid, id_strlen + 1, &delta->old_file.id); git_oid_tostr(end_oid, id_strlen + 1, &delta->new_file.id); if (delta->old_file.mode == delta->new_file.mode) { if (print_index) git_buf_printf(out, "index %s..%s %o\n", start_oid, end_oid, delta->old_file.mode); } else { if (delta->old_file.mode == 0) git_buf_printf(out, "new file mode %o\n", delta->new_file.mode); else if (delta->new_file.mode == 0) git_buf_printf(out, "deleted file mode %o\n", delta->old_file.mode); else diff_print_modes(out, delta); if (print_index) git_buf_printf(out, "index %s..%s\n", start_oid, end_oid); } return git_buf_oom(out) ? -1 : 0; } static int diff_delta_format_path( git_buf *out, const char *prefix, const char *filename) { if (git_buf_joinpath(out, prefix, filename) < 0) return -1; return git_buf_quote(out); } static int diff_delta_format_with_paths( git_buf *out, const git_diff_delta *delta, const char *template, const char *oldpath, const char *newpath) { if (git_oid_is_zero(&delta->old_file.id)) oldpath = "/dev/null"; if (git_oid_is_zero(&delta->new_file.id)) newpath = "/dev/null"; return git_buf_printf(out, template, oldpath, newpath); } int diff_delta_format_similarity_header( git_buf *out, const git_diff_delta *delta) { git_buf old_path = GIT_BUF_INIT, new_path = GIT_BUF_INIT; const char *type; int error = 0; if (delta->similarity > 100) { git_error_set(GIT_ERROR_PATCH, "invalid similarity %d", delta->similarity); error = -1; goto done; } if (delta->status == GIT_DELTA_RENAMED) type = "rename"; else if (delta->status == GIT_DELTA_COPIED) type = "copy"; else abort(); if ((error = git_buf_puts(&old_path, delta->old_file.path)) < 0 || (error = git_buf_puts(&new_path, delta->new_file.path)) < 0 || (error = git_buf_quote(&old_path)) < 0 || (error = git_buf_quote(&new_path)) < 0) goto done; git_buf_printf(out, "similarity index %d%%\n" "%s from %s\n" "%s to %s\n", delta->similarity, type, old_path.ptr, type, new_path.ptr); if (git_buf_oom(out)) error = -1; done: git_buf_dispose(&old_path); git_buf_dispose(&new_path); return error; } static bool delta_is_unchanged(const git_diff_delta *delta) { if (git_oid_is_zero(&delta->old_file.id) && git_oid_is_zero(&delta->new_file.id)) return true; if (delta->old_file.mode == GIT_FILEMODE_COMMIT || delta->new_file.mode == GIT_FILEMODE_COMMIT) return false; if (git_oid_equal(&delta->old_file.id, &delta->new_file.id)) return true; return false; } int git_diff_delta__format_file_header( git_buf *out, const git_diff_delta *delta, const char *oldpfx, const char *newpfx, int id_strlen, bool print_index) { git_buf old_path = GIT_BUF_INIT, new_path = GIT_BUF_INIT; bool unchanged = delta_is_unchanged(delta); int error = 0; if (!oldpfx) oldpfx = DIFF_OLD_PREFIX_DEFAULT; if (!newpfx) newpfx = DIFF_NEW_PREFIX_DEFAULT; if (!id_strlen) id_strlen = GIT_ABBREV_DEFAULT; if ((error = diff_delta_format_path( &old_path, oldpfx, delta->old_file.path)) < 0 || (error = diff_delta_format_path( &new_path, newpfx, delta->new_file.path)) < 0) goto done; git_buf_clear(out); git_buf_printf(out, "diff --git %s %s\n", old_path.ptr, new_path.ptr); if (delta->status == GIT_DELTA_RENAMED || (delta->status == GIT_DELTA_COPIED && unchanged)) { if ((error = diff_delta_format_similarity_header(out, delta)) < 0) goto done; } if (!unchanged) { if ((error = diff_print_oid_range(out, delta, id_strlen, print_index)) < 0) goto done; if ((delta->flags & GIT_DIFF_FLAG_BINARY) == 0) diff_delta_format_with_paths(out, delta, "--- %s\n+++ %s\n", old_path.ptr, new_path.ptr); } if (unchanged && delta->old_file.mode != delta->new_file.mode) diff_print_modes(out, delta); if (git_buf_oom(out)) error = -1; done: git_buf_dispose(&old_path); git_buf_dispose(&new_path); return error; } static int format_binary( diff_print_info *pi, git_diff_binary_t type, const char *data, size_t datalen, size_t inflatedlen) { const char *typename = type == GIT_DIFF_BINARY_DELTA ? "delta" : "literal"; const char *scan, *end; git_buf_printf(pi->buf, "%s %" PRIuZ "\n", typename, inflatedlen); pi->line.num_lines++; for (scan = data, end = data + datalen; scan < end; ) { size_t chunk_len = end - scan; if (chunk_len > 52) chunk_len = 52; if (chunk_len <= 26) git_buf_putc(pi->buf, (char)chunk_len + 'A' - 1); else git_buf_putc(pi->buf, (char)chunk_len - 26 + 'a' - 1); git_buf_encode_base85(pi->buf, scan, chunk_len); git_buf_putc(pi->buf, '\n'); if (git_buf_oom(pi->buf)) return -1; scan += chunk_len; pi->line.num_lines++; } git_buf_putc(pi->buf, '\n'); return 0; } static int diff_print_patch_file_binary_noshow( diff_print_info *pi, git_diff_delta *delta, const char *old_pfx, const char *new_pfx) { git_buf old_path = GIT_BUF_INIT, new_path = GIT_BUF_INIT; int error; if ((error = diff_delta_format_path( &old_path, old_pfx, delta->old_file.path)) < 0 || (error = diff_delta_format_path( &new_path, new_pfx, delta->new_file.path)) < 0) goto done; pi->line.num_lines = 1; error = diff_delta_format_with_paths( pi->buf, delta, "Binary files %s and %s differ\n", old_path.ptr, new_path.ptr); done: git_buf_dispose(&old_path); git_buf_dispose(&new_path); return error; } static int diff_print_patch_file_binary( diff_print_info *pi, git_diff_delta *delta, const char *old_pfx, const char *new_pfx, const git_diff_binary *binary) { size_t pre_binary_size; int error; if (delta->status == GIT_DELTA_UNMODIFIED) return 0; if ((pi->flags & GIT_DIFF_SHOW_BINARY) == 0 || !binary->contains_data) return diff_print_patch_file_binary_noshow( pi, delta, old_pfx, new_pfx); pre_binary_size = pi->buf->size; git_buf_printf(pi->buf, "GIT binary patch\n"); pi->line.num_lines++; if ((error = format_binary(pi, binary->new_file.type, binary->new_file.data, binary->new_file.datalen, binary->new_file.inflatedlen)) < 0 || (error = format_binary(pi, binary->old_file.type, binary->old_file.data, binary->old_file.datalen, binary->old_file.inflatedlen)) < 0) { if (error == GIT_EBUFS) { git_error_clear(); git_buf_truncate(pi->buf, pre_binary_size); return diff_print_patch_file_binary_noshow( pi, delta, old_pfx, new_pfx); } } pi->line.num_lines++; return error; } static int diff_print_patch_file( const git_diff_delta *delta, float progress, void *data) { int error; diff_print_info *pi = data; const char *oldpfx = pi->old_prefix ? pi->old_prefix : DIFF_OLD_PREFIX_DEFAULT; const char *newpfx = pi->new_prefix ? pi->new_prefix : DIFF_NEW_PREFIX_DEFAULT; bool binary = (delta->flags & GIT_DIFF_FLAG_BINARY) || (pi->flags & GIT_DIFF_FORCE_BINARY); bool show_binary = !!(pi->flags & GIT_DIFF_SHOW_BINARY); int id_strlen = pi->id_strlen; bool print_index = (pi->format != GIT_DIFF_FORMAT_PATCH_ID); if (binary && show_binary) id_strlen = delta->old_file.id_abbrev ? delta->old_file.id_abbrev : delta->new_file.id_abbrev; GIT_UNUSED(progress); if (S_ISDIR(delta->new_file.mode) || delta->status == GIT_DELTA_UNMODIFIED || delta->status == GIT_DELTA_IGNORED || delta->status == GIT_DELTA_UNREADABLE || (delta->status == GIT_DELTA_UNTRACKED && (pi->flags & GIT_DIFF_SHOW_UNTRACKED_CONTENT) == 0)) return 0; if ((error = git_diff_delta__format_file_header( pi->buf, delta, oldpfx, newpfx, id_strlen, print_index)) < 0) return error; pi->line.origin = GIT_DIFF_LINE_FILE_HDR; pi->line.content = git_buf_cstr(pi->buf); pi->line.content_len = git_buf_len(pi->buf); return pi->print_cb(delta, NULL, &pi->line, pi->payload); } static int diff_print_patch_binary( const git_diff_delta *delta, const git_diff_binary *binary, void *data) { diff_print_info *pi = data; const char *old_pfx = pi->old_prefix ? pi->old_prefix : DIFF_OLD_PREFIX_DEFAULT; const char *new_pfx = pi->new_prefix ? pi->new_prefix : DIFF_NEW_PREFIX_DEFAULT; int error; git_buf_clear(pi->buf); if ((error = diff_print_patch_file_binary( pi, (git_diff_delta *)delta, old_pfx, new_pfx, binary)) < 0) return error; pi->line.origin = GIT_DIFF_LINE_BINARY; pi->line.content = git_buf_cstr(pi->buf); pi->line.content_len = git_buf_len(pi->buf); return pi->print_cb(delta, NULL, &pi->line, pi->payload); } static int diff_print_patch_hunk( const git_diff_delta *d, const git_diff_hunk *h, void *data) { diff_print_info *pi = data; if (S_ISDIR(d->new_file.mode)) return 0; pi->line.origin = GIT_DIFF_LINE_HUNK_HDR; pi->line.content = h->header; pi->line.content_len = h->header_len; return pi->print_cb(d, h, &pi->line, pi->payload); } static int diff_print_patch_line( const git_diff_delta *delta, const git_diff_hunk *hunk, const git_diff_line *line, void *data) { diff_print_info *pi = data; if (S_ISDIR(delta->new_file.mode)) return 0; return pi->print_cb(delta, hunk, line, pi->payload); } /* print a git_diff to an output callback */ int git_diff_print( git_diff *diff, git_diff_format_t format, git_diff_line_cb print_cb, void *payload) { int error; git_buf buf = GIT_BUF_INIT; diff_print_info pi; git_diff_file_cb print_file = NULL; git_diff_binary_cb print_binary = NULL; git_diff_hunk_cb print_hunk = NULL; git_diff_line_cb print_line = NULL; switch (format) { case GIT_DIFF_FORMAT_PATCH: print_file = diff_print_patch_file; print_binary = diff_print_patch_binary; print_hunk = diff_print_patch_hunk; print_line = diff_print_patch_line; break; case GIT_DIFF_FORMAT_PATCH_ID: print_file = diff_print_patch_file; print_binary = diff_print_patch_binary; print_line = diff_print_patch_line; break; case GIT_DIFF_FORMAT_PATCH_HEADER: print_file = diff_print_patch_file; break; case GIT_DIFF_FORMAT_RAW: print_file = diff_print_one_raw; break; case GIT_DIFF_FORMAT_NAME_ONLY: print_file = diff_print_one_name_only; break; case GIT_DIFF_FORMAT_NAME_STATUS: print_file = diff_print_one_name_status; break; default: git_error_set(GIT_ERROR_INVALID, "unknown diff output format (%d)", format); return -1; } if (!(error = diff_print_info_init_fromdiff( &pi, &buf, diff, format, print_cb, payload))) { error = git_diff_foreach( diff, print_file, print_binary, print_hunk, print_line, &pi); if (error) /* make sure error message is set */ git_error_set_after_callback_function(error, "git_diff_print"); } git_buf_dispose(&buf); return error; } int git_diff_print_callback__to_buf( const git_diff_delta *delta, const git_diff_hunk *hunk, const git_diff_line *line, void *payload) { git_buf *output = payload; GIT_UNUSED(delta); GIT_UNUSED(hunk); if (!output) { git_error_set(GIT_ERROR_INVALID, "buffer pointer must be provided"); return -1; } if (line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION || line->origin == GIT_DIFF_LINE_CONTEXT) git_buf_putc(output, line->origin); return git_buf_put(output, line->content, line->content_len); } int git_diff_print_callback__to_file_handle( const git_diff_delta *delta, const git_diff_hunk *hunk, const git_diff_line *line, void *payload) { FILE *fp = payload ? payload : stdout; GIT_UNUSED(delta); GIT_UNUSED(hunk); if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION) fputc(line->origin, fp); fwrite(line->content, 1, line->content_len, fp); return 0; } /* print a git_diff to a git_buf */ int git_diff_to_buf(git_buf *out, git_diff *diff, git_diff_format_t format) { assert(out && diff); git_buf_sanitize(out); return git_diff_print( diff, format, git_diff_print_callback__to_buf, out); } /* print a git_patch to an output callback */ int git_patch_print( git_patch *patch, git_diff_line_cb print_cb, void *payload) { int error; git_buf temp = GIT_BUF_INIT; diff_print_info pi; assert(patch && print_cb); if (!(error = diff_print_info_init_frompatch( &pi, &temp, patch, GIT_DIFF_FORMAT_PATCH, print_cb, payload))) { error = git_patch__invoke_callbacks( patch, diff_print_patch_file, diff_print_patch_binary, diff_print_patch_hunk, diff_print_patch_line, &pi); if (error) /* make sure error message is set */ git_error_set_after_callback_function(error, "git_patch_print"); } git_buf_dispose(&temp); return error; } /* print a git_patch to a git_buf */ int git_patch_to_buf(git_buf *out, git_patch *patch) { assert(out && patch); git_buf_sanitize(out); return git_patch_print(patch, git_diff_print_callback__to_buf, out); }
9,005
506
package com.ewolff.microservice.order.item; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class ItemTestDataGenerator { private final ItemRepository itemRepository; @Autowired public ItemTestDataGenerator(ItemRepository itemRepository) { this.itemRepository = itemRepository; } @PostConstruct public void generateTestData() { itemRepository.save(new Item("iPod", 42.0)); itemRepository.save(new Item("iPod touch", 21.0)); itemRepository.save(new Item("iPod nano", 1.0)); itemRepository.save(new Item("Apple TV", 100.0)); } }
222
711
package com.java110.store.api; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.java110.core.factory.GenerateCodeFactory; import com.java110.dto.purchaseApply.PurchaseApplyDto; import com.java110.po.purchase.PurchaseApplyDetailPo; import com.java110.po.purchase.PurchaseApplyPo; import com.java110.store.bmo.purchase.IPurchaseApplyBMO; import com.java110.store.bmo.purchase.IResourceEnterBMO; import com.java110.utils.util.Assert; import com.java110.utils.util.BeanConvertUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping(value = "/purchase") public class PurchaseApi { @Autowired private IPurchaseApplyBMO purchaseApplyBMOImpl; @Autowired private IResourceEnterBMO resourceEnterBMOImpl; /** * 采购申请 * <p> * {"resourceStores":[{"resId":"852020061636590016","resName":"橡皮擦","resCode":"003","price":"100.00","stock":"0","description":"ada","quantity":"1"}, * {"resId":"852020061729120031","resName":"文档柜","resCode":"002","price":"33.00","stock":"0","description":"蓝色","quantity":"1"}], * "description":"123123","endUserName":"1","endUserTel":"17797173942","file":"","resOrderType":"10000","staffId":"","staffName":""} * * @param reqJson * @return */ @RequestMapping(value = "/purchaseApply", method = RequestMethod.POST) public ResponseEntity<String> purchaseApply(@RequestBody JSONObject reqJson, @RequestHeader(value = "user-id") String userId, @RequestHeader(value = "user-name") String userName, @RequestHeader(value = "store-id") String storeId) { Assert.hasKeyAndValue(reqJson, "resourceStores", "必填,请填写申请采购的物资"); Assert.hasKeyAndValue(reqJson, "description", "必填,请填写采购申请说明"); Assert.hasKeyAndValue(reqJson, "resOrderType", "必填,请填写申请类型"); PurchaseApplyPo purchaseApplyPo = new PurchaseApplyPo(); purchaseApplyPo.setApplyOrderId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_applyOrderId)); purchaseApplyPo.setDescription(reqJson.getString("description")); purchaseApplyPo.setUserId(userId); purchaseApplyPo.setUserName(userName); purchaseApplyPo.setEndUserName(reqJson.getString("endUserName")); purchaseApplyPo.setEndUserTel(reqJson.getString("endUserTel")); purchaseApplyPo.setStoreId(storeId); purchaseApplyPo.setResOrderType(PurchaseApplyDto.RES_ORDER_TYPE_ENTER); purchaseApplyPo.setState(PurchaseApplyDto.STATE_DEALING); JSONArray resourceStores = reqJson.getJSONArray("resourceStores"); List<PurchaseApplyDetailPo> purchaseApplyDetailPos = new ArrayList<>(); for (int resourceStoreIndex = 0; resourceStoreIndex < resourceStores.size(); resourceStoreIndex++) { JSONObject resourceStore = resourceStores.getJSONObject(resourceStoreIndex); PurchaseApplyDetailPo purchaseApplyDetailPo = BeanConvertUtil.covertBean(resourceStore, PurchaseApplyDetailPo.class); purchaseApplyDetailPo.setId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_applyOrderId)); purchaseApplyDetailPos.add(purchaseApplyDetailPo); } purchaseApplyPo.setPurchaseApplyDetailPos(purchaseApplyDetailPos); return purchaseApplyBMOImpl.apply(purchaseApplyPo); } @RequestMapping(value = "/resourceEnter", method = RequestMethod.POST) public ResponseEntity<String> resourceEnter(@RequestBody JSONObject reqJson) { Assert.hasKeyAndValue(reqJson, "applyOrderId", "订单ID为空"); JSONArray purchaseApplyDetails = reqJson.getJSONArray("purchaseApplyDetailVo"); List<PurchaseApplyDetailPo> purchaseApplyDetailPos = new ArrayList<>(); for (int detailIndex = 0; detailIndex < purchaseApplyDetails.size(); detailIndex++) { JSONObject purchaseApplyDetail = purchaseApplyDetails.getJSONObject(detailIndex); Assert.hasKeyAndValue(purchaseApplyDetail, "purchaseQuantity", "采购数量未填写"); Assert.hasKeyAndValue(purchaseApplyDetail, "price", "采购单价未填写"); Assert.hasKeyAndValue(purchaseApplyDetail, "id", "明细ID为空"); PurchaseApplyDetailPo purchaseApplyDetailPo = BeanConvertUtil.covertBean(purchaseApplyDetail, PurchaseApplyDetailPo.class); purchaseApplyDetailPos.add(purchaseApplyDetailPo); } PurchaseApplyPo purchaseApplyPo = new PurchaseApplyPo(); purchaseApplyPo.setApplyOrderId(reqJson.getString("applyOrderId")); purchaseApplyPo.setPurchaseApplyDetailPos(purchaseApplyDetailPos); return resourceEnterBMOImpl.enter(purchaseApplyPo); } }
2,020
685
package com.kaichunlin.transition.adapter; import android.support.annotation.MenuRes; import android.support.annotation.NonNull; import com.kaichunlin.transition.MenuItemTransition; /** * Stores the menu ID-MenuItemTransition pair. */ public class MenuOptionConfiguration { private final MenuItemTransition mTransition; private final int mMenuId; public MenuOptionConfiguration(@NonNull MenuItemTransition transition) { mTransition = transition; mMenuId = -1; } public MenuOptionConfiguration(@NonNull MenuItemTransition transition, @MenuRes int menuId) { mTransition = transition; mMenuId = menuId; } /** * * @return MenuItemTransition for the menu item */ public MenuItemTransition getTransition() { return mTransition; } /** * * @return the menu item's ID */ public int getMenuId() { return mMenuId; } }
347
1,056
<filename>org-netbeans-core-windows/src/main/java/org/netbeans/core/windows/actions/ResetWindowsAction.java<gh_stars>1000+ /* * 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. */ package org.netbeans.core.windows.actions; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.SwingUtilities; import org.netbeans.core.WindowSystem; import org.netbeans.core.windows.ModeImpl; import org.netbeans.core.windows.PersistenceHandler; import org.netbeans.core.windows.RegistryImpl; import org.netbeans.core.windows.TopComponentGroupImpl; import org.netbeans.core.windows.TopComponentTracker; import org.netbeans.core.windows.WindowManagerImpl; import org.netbeans.core.windows.persistence.PersistenceManager; import org.netbeans.core.windows.view.ui.MainWindow; import org.openide.ErrorManager; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.filesystems.FileObject; import org.openide.util.Lookup; import org.openide.windows.Mode; import org.openide.windows.RetainLocation; import org.openide.windows.TopComponent; import org.openide.windows.TopComponentGroup; /** * Resets the window system to its default state. * * @author <NAME> */ public class ResetWindowsAction implements ActionListener { @ActionID(id = "org.netbeans.core.windows.actions.ResetWindowsAction", category = "Window") @ActionRegistration(displayName = "#CTL_ResetWindows") @ActionReference(position = 20200, path = "Menu/Window") public static ActionListener reset() { return new ResetWindowsAction(true); } @ActionID(id = "org.netbeans.core.windows.actions.ReloadWindowsAction", category = "Window") @ActionRegistration(displayName = "#CTL_ReloadWindows") public static ActionListener reload() { return new ResetWindowsAction(false); } private final boolean reset; public ResetWindowsAction(boolean reset) { this.reset = reset; } @Override public void actionPerformed(ActionEvent e) { final WindowSystem ws = Lookup.getDefault().lookup( WindowSystem.class ); if( null == ws ) { //unsupported window system implementation Logger.getLogger(ResetWindowsAction.class.getName()).log(Level.INFO, "Reset Windows action does not support custom WindowSystem implementations."); //NOI18N return; } final WindowManagerImpl wm = WindowManagerImpl.getInstance(); //cancel full-screen mode MainWindow.getInstance().setFullScreenMode(false); wm.getMainWindow().setExtendedState( JFrame.NORMAL ); TopComponentGroupImpl projectTCGroup = (TopComponentGroupImpl) wm.findTopComponentGroup("OpenedProjects"); //NOI18N final boolean isProjectsTCGroupOpened = null != projectTCGroup && projectTCGroup.isOpened(); //get a list of editor windows that should stay open even after the reset final TopComponent[] editors = collectEditors(); //close all other windows just in case they hold some references to editor windows wm.closeNonEditorViews(); //hide the main window to hide some window operations before the actual reset is performed wm.getMainWindow().setVisible( false ); //find an editor window that will be activated after the reset (may be null) final TopComponent activeEditor = wm.getArbitrarySelectedEditorTopComponent(); //make sure that componentHidden() gets called on all opened and selected editors //so that they can reset their respective states and/or release some listeners wm.deselectEditorTopComponents(); SwingUtilities.invokeLater( new Runnable() { @Override public void run() { //find the local folder that must be deleted try { FileObject rootFolder = PersistenceManager.getDefault().getRootLocalFolder(); if (reset && null != rootFolder) { for( FileObject fo : rootFolder.getChildren() ) { if( PersistenceManager.COMPS_FOLDER.equals( fo.getName() ) ) continue; //do not delete settings files fo.delete(); } } } catch( IOException ioE ) { ErrorManager.getDefault().notify( ErrorManager.INFORMATIONAL, ioE ); } //reset the window system ws.hide(); WindowManagerImpl.getInstance().resetModel(); PersistenceManager.getDefault().reset(); //keep mappings to TopComponents created so far PersistenceHandler.getDefault().clear(); ws.load(); ws.show(); if( isProjectsTCGroupOpened ) { TopComponentGroup tcGroup = wm.findTopComponentGroup("OpenedProjects"); //NOI18N if( null != tcGroup ) tcGroup.open(); } ModeImpl editorMode = (ModeImpl) wm.findMode("editor"); //NOI18N RegistryImpl registry = ( RegistryImpl ) TopComponent.getRegistry(); //re-open editor windows that were opened before the reset for( int i=0; i<editors.length && null != editorMode; i++ ) { ModeImpl mode = ( ModeImpl ) wm.findMode( editors[i] ); if( null == mode ) { RetainLocation retainLocation = editors[i].getClass().getAnnotation(RetainLocation.class); if( null != retainLocation ) { String preferedModeName = retainLocation.value(); mode = (ModeImpl) wm.findMode(preferedModeName); } } if( null == mode ) { mode = editorMode; } if( null != mode ) mode.addOpenedTopComponentNoNotify(editors[i]); //#210380 - do not call componentOpened on the editors registry.addTopComponent( editors[i] ); } SwingUtilities.invokeLater( new Runnable() { @Override public void run() { Frame mainWindow = wm.getMainWindow(); mainWindow.invalidate(); mainWindow.repaint(); } }); //activate some editor window if( null != activeEditor ) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { activeEditor.requestActive(); } }); } } }); } private TopComponent[] collectEditors() { TopComponentTracker tcTracker = TopComponentTracker.getDefault(); ArrayList<TopComponent> editors = new ArrayList<TopComponent>(TopComponent.getRegistry().getOpened().size()); //collect from the main editor mode first ModeImpl editorMode = ( ModeImpl ) WindowManagerImpl.getInstance().findMode( "editor" ); if( null != editorMode ) { for( TopComponent tc : editorMode.getOpenedTopComponents() ) { if( tcTracker.isViewTopComponent( tc ) ) continue; editors.add( tc ); } } for( ModeImpl m : WindowManagerImpl.getInstance().getModes() ) { if( "editor".equals( m.getName() ) ) continue; for( TopComponent tc : m.getOpenedTopComponents() ) { if( tcTracker.isViewTopComponent( tc ) ) continue; editors.add( tc ); } } return editors.toArray( new TopComponent[editors.size()] ); } }
3,942
2,405
#include "lcd7920_STM.h" // Standard ASCII 6x8 font PROGMEM const uint8_t glcd5x7_STM[] PROGMEM = { 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, // Code for char 0x04, 0x00, 0x06, 0x5F, 0x06, 0x00, // Code for char ! 0x05, 0x07, 0x03, 0x00, 0x07, 0x03, // Code for char " 0x05, 0x24, 0x7E, 0x24, 0x7E, 0x24, // Code for char # 0x04, 0x24, 0x2B, 0x6A, 0x12, 0x00, // Code for char $ 0x05, 0x63, 0x13, 0x08, 0x64, 0x63, // Code for char % 0x05, 0x36, 0x49, 0x56, 0x20, 0x50, // Code for char & 0x03, 0x00, 0x07, 0x03, 0x00, 0x00, // Code for char ' 0x03, 0x00, 0x3E, 0x41, 0x00, 0x00, // Code for char ( 0x03, 0x00, 0x41, 0x3E, 0x00, 0x00, // Code for char ) 0x05, 0x08, 0x3E, 0x1C, 0x3E, 0x08, // Code for char * 0x05, 0x08, 0x08, 0x3E, 0x08, 0x08, // Code for char + 0x03, 0x00, 0x60, 0x60, 0x00, 0x00, // Code for char , 0x05, 0x08, 0x08, 0x08, 0x08, 0x08, // Code for char - 0x03, 0x00, 0x60, 0x60, 0x00, 0x00, // Code for char . 0x05, 0x20, 0x10, 0x08, 0x04, 0x02, // Code for char / 0x05, 0x3E, 0x51, 0x49, 0x45, 0x3E, // Code for char 0 0x04, 0x00, 0x42, 0x7F, 0x40, 0x00, // Code for char 1 0x05, 0x62, 0x51, 0x49, 0x49, 0x46, // Code for char 2 0x05, 0x22, 0x49, 0x49, 0x49, 0x36, // Code for char 3 0x05, 0x18, 0x14, 0x12, 0x7F, 0x10, // Code for char 4 0x05, 0x2F, 0x49, 0x49, 0x49, 0x31, // Code for char 5 0x05, 0x3C, 0x4A, 0x49, 0x49, 0x30, // Code for char 6 0x05, 0x01, 0x71, 0x09, 0x05, 0x03, // Code for char 7 0x05, 0x36, 0x49, 0x49, 0x49, 0x36, // Code for char 8 0x05, 0x06, 0x49, 0x49, 0x29, 0x1E, // Code for char 9 0x03, 0x00, 0x6C, 0x6C, 0x00, 0x00, // Code for char : 0x03, 0x00, 0x6C, 0x6C, 0x00, 0x00, // Code for char ; 0x04, 0x08, 0x14, 0x22, 0x41, 0x00, // Code for char < 0x05, 0x24, 0x24, 0x24, 0x24, 0x24, // Code for char = 0x05, 0x00, 0x41, 0x22, 0x14, 0x08, // Code for char > 0x05, 0x02, 0x01, 0x59, 0x09, 0x06, // Code for char ? 0x05, 0x3E, 0x41, 0x5D, 0x55, 0x1E, // Code for char @ 0x05, 0x7E, 0x11, 0x11, 0x11, 0x7E, // Code for char A 0x05, 0x7F, 0x49, 0x49, 0x49, 0x36, // Code for char B 0x05, 0x3E, 0x41, 0x41, 0x41, 0x22, // Code for char C 0x05, 0x7F, 0x41, 0x41, 0x41, 0x3E, // Code for char D 0x05, 0x7F, 0x49, 0x49, 0x49, 0x41, // Code for char E 0x05, 0x7F, 0x09, 0x09, 0x09, 0x01, // Code for char F 0x05, 0x3E, 0x41, 0x49, 0x49, 0x7A, // Code for char G 0x05, 0x7F, 0x08, 0x08, 0x08, 0x7F, // Code for char H 0x04, 0x00, 0x41, 0x7F, 0x41, 0x00, // Code for char I 0x05, 0x30, 0x40, 0x40, 0x40, 0x3F, // Code for char J 0x05, 0x7F, 0x08, 0x14, 0x22, 0x41, // Code for char K 0x05, 0x7F, 0x40, 0x40, 0x40, 0x40, // Code for char L 0x05, 0x7F, 0x02, 0x04, 0x02, 0x7F, // Code for char M 0x05, 0x7F, 0x02, 0x04, 0x08, 0x7F, // Code for char N 0x05, 0x3E, 0x41, 0x41, 0x41, 0x3E, // Code for char O 0x05, 0x7F, 0x09, 0x09, 0x09, 0x06, // Code for char P 0x05, 0x3E, 0x41, 0x51, 0x21, 0x5E, // Code for char Q 0x05, 0x7F, 0x09, 0x09, 0x19, 0x66, // Code for char R 0x05, 0x26, 0x49, 0x49, 0x49, 0x32, // Code for char S 0x05, 0x01, 0x01, 0x7F, 0x01, 0x01, // Code for char T 0x05, 0x3F, 0x40, 0x40, 0x40, 0x3F, // Code for char U 0x05, 0x1F, 0x20, 0x40, 0x20, 0x1F, // Code for char V 0x05, 0x3F, 0x40, 0x3C, 0x40, 0x3F, // Code for char W 0x05, 0x63, 0x14, 0x08, 0x14, 0x63, // Code for char X 0x05, 0x07, 0x08, 0x70, 0x08, 0x07, // Code for char Y 0x04, 0x71, 0x49, 0x45, 0x43, 0x00, // Code for char Z 0x04, 0x00, 0x7F, 0x41, 0x41, 0x00, // Code for char [ 0x05, 0x02, 0x04, 0x08, 0x10, 0x20, // Code for char BackSlash 0x04, 0x00, 0x41, 0x41, 0x7F, 0x00, // Code for char ] 0x05, 0x04, 0x02, 0x01, 0x02, 0x04, // Code for char ^ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, // Code for char _ 0x03, 0x00, 0x03, 0x07, 0x00, 0x00, // Code for char ` 0x05, 0x20, 0x54, 0x54, 0x54, 0x78, // Code for char a 0x05, 0x7F, 0x44, 0x44, 0x44, 0x38, // Code for char b 0x05, 0x38, 0x44, 0x44, 0x44, 0x28, // Code for char c 0x05, 0x38, 0x44, 0x44, 0x44, 0x7F, // Code for char d 0x05, 0x38, 0x54, 0x54, 0x54, 0x08, // Code for char e 0x04, 0x08, 0x7E, 0x09, 0x09, 0x00, // Code for char f 0x05, 0x18, 0x24, 0x24, 0x24, 0x7C, // Code for char g 0x04, 0x7F, 0x04, 0x04, 0x78, 0x00, // Code for char h 0x04, 0x00, 0x00, 0x7D, 0x40, 0x00, // Code for char i 0x04, 0x40, 0x00, 0x04, 0x7D, 0x00, // Code for char j 0x04, 0x7F, 0x10, 0x28, 0x44, 0x00, // Code for char k 0x04, 0x00, 0x00, 0x7F, 0x40, 0x00, // Code for char l 0x05, 0x7C, 0x04, 0x18, 0x04, 0x78, // Code for char m 0x04, 0x7C, 0x04, 0x04, 0x78, 0x00, // Code for char n 0x05, 0x38, 0x44, 0x44, 0x44, 0x38, // Code for char o 0x05, 0x7C, 0x44, 0x44, 0x44, 0x38, // Code for char p 0x05, 0x38, 0x44, 0x44, 0x44, 0x7C, // Code for char q 0x05, 0x44, 0x78, 0x44, 0x04, 0x08, // Code for char r 0x05, 0x08, 0x54, 0x54, 0x54, 0x20, // Code for char s 0x04, 0x04, 0x3E, 0x44, 0x24, 0x00, // Code for char t 0x04, 0x3C, 0x40, 0x20, 0x7C, 0x00, // Code for char u 0x05, 0x1C, 0x20, 0x40, 0x20, 0x1C, // Code for char v 0x05, 0x3C, 0x60, 0x30, 0x60, 0x3C, // Code for char w 0x04, 0x6C, 0x10, 0x10, 0x6C, 0x00, // Code for char x 0x04, 0x1C, 0x20, 0x60, 0x3C, 0x00, // Code for char y 0x04, 0x64, 0x54, 0x54, 0x4C, 0x00, // Code for char z 0x04, 0x08, 0x3E, 0x41, 0x41, 0x00, // Code for char { 0x03, 0x00, 0x00, 0x77, 0x00, 0x00, // Code for char | 0x05, 0x00, 0x41, 0x41, 0x3E, 0x08, // Code for char } 0x04, 0x02, 0x01, 0x02, 0x01, 0x00, // Code for char ~ 0x05, 0x3C, 0x26, 0x23, 0x26, 0x3C // Code for char  }; extern const PROGMEM LcdFont font5x7_STM = { glcd5x7_STM, // font data 0x20, // first character code 0x7F, // last character code 7, // row height in pixels 5 // character width in pixels };
3,920
1,840
/** * Copyright Pravega 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. */ package io.pravega.shared.protocol.netty; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import lombok.extern.slf4j.Slf4j; /** * Used to make sure any stray exceptions that make it back to the socket get logged. */ @Slf4j public class ExceptionLoggingHandler extends ChannelDuplexHandler { private final String connectionName; public ExceptionLoggingHandler(String connectionName) { this.connectionName = connectionName; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { log.error("Uncaught exception on connection " + connectionName, cause); super.exceptionCaught(ctx, cause); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { super.channelRead(ctx, msg); } catch (Exception e) { log.error("Uncaught exception observed during channel read on connection {}", connectionName, e); throw e; } } }
524
2,637
/* * Amazon FreeRTOS Wi-Fi V1.0.0 * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * 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. * * http://aws.amazon.com/freertos * http://www.FreeRTOS.org */ #pragma once /* Wi-Fi Host driver includes. */ #include <whd.h> #include <whd_wifi_api.h> #include <whd_network_types.h> /* Variable to store Wi-Fi security which will be used during WHD event processing */ extern whd_security_t cy_sta_security_type; /* Variable to store station link status which will be used for LWIP bringup/down sequence */ extern bool cy_sta_link_up; /* This is mutex to sychronize application callback */ extern cy_mutex_t cy_app_cb_Mutex; /* Connected AP details which is required for re association cases */ typedef struct { whd_ssid_t SSID; uint8_t key[wificonfigMAX_PASSPHRASE_LEN]; uint8_t keylen; whd_security_t security; }cy_ap_details; extern cy_ap_details cy_connected_ap_details; #define CY_RSLT_MODULE_WIFI_BASE (CY_RSLT_MODULE_MIDDLEWARE_BASE+11) #define CY_WIFI_FAILURE CY_RSLT_CREATE(CY_RSLT_TYPE_ERROR, CY_RSLT_MODULE_WIFI_BASE, 1) /** * @brief Enum types representing different event changes. */ typedef enum { CY_NETWORK_EVENT_CONNECTED = 0, /**< Denotes STA connected to AP */ CY_NETWORK_EVENT_DISCONNECTED, /**< Denotes STA disconnected with AP */ CY_NETWORK_EVENT_IP_CHANGED, /**< Denotes IP address change */ CY_NETWORK_EVENT_LINKUP_FAILURE, /**< Denotes Network link up failure */ CY_NETWORK_EVENT_LINKDOWN_FAILURE, /**< Denotes Network link down failure */ CY_NETWORK_DHCP_RESTART_FAILURE /**< Denotes DHCP restart failure */ } cy_network_event_t; /** * Network event callback function pointer type, events are invoked when WHD posts events to application. * @param[in] event : Network events. */ typedef void (*cy_network_event_callback_t)(cy_network_event_t event); /** * Register for whd link events. * * @param[in] interface : pointer to whd interface. * * @return CY_RSLT_SUCCESS if whd link events register was successful, failure code otherwise. */ extern cy_rslt_t cy_wifi_link_event_register( whd_interface_t interface ); /** * De-register whd link events. * * @param[in] interface : pointer to whd interface. * */ extern void cy_wifi_link_event_deregister( whd_interface_t interface ); /** * Callback for link notification support * * @param[in] netif : The lwIP network interface. * */ extern void cy_network_ip_change_callback (struct netif *netif); /** * Create worker thread for wifi link up/link down notification support. * */ extern cy_rslt_t cy_wifi_worker_thread_create( void ); /** * Deinit worker thread created after wifi off. * */ extern void cy_wifi_worker_thread_delete( void ); /** * Register an event callback to receive network events. * * @param[in] event_callback : Callback function to be invoked for event notification. * * @return CY_RSLT_SUCCESS if application callback registration was successful, failure code otherwise. */ extern cy_rslt_t cy_network_register_event_callback(cy_network_event_callback_t event_callback); /** * De-register an event callback. * * @param[in] event_callback : Callback function to de-register from getting notifications. * * @return CY_RSLT_SUCCESS if application callback de-registration was successful, failure code otherwise. */ extern cy_rslt_t cy_network_deregister_event_callback(cy_network_event_callback_t event_callback);
1,489
5,169
<gh_stars>1000+ { "name": "iOS8Colors", "version": "0.1.2", "summary": "The standard iOS 8 Colors as a handy category on UIColor", "homepage": "https://github.com/thii/iOS8Colors", "screenshots": "https://raw.githubusercontent.com/thii/iOS8Colors/master/screenshot.png", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "6.0" }, "requires_arc": true, "source": { "git": "https://github.com/thii/iOS8Colors.git", "tag": "0.1.2" }, "source_files": "iOS8Colors/UIColor+iOS8Colors.*", "dependencies": { "HexColors": [ "~> 2.2.1" ] } }
278
1,473
/* * Autopsy Forensic Browser * * Copyright 2021 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * 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 org.sleuthkit.autopsy.datamodel.persons; import java.awt.Color; import org.sleuthkit.datamodel.Person; import java.util.Collection; import java.util.Set; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.openide.util.NbBundle.Messages; /** * * Dialog for adding or editing a person. */ public class AddEditPersonDialog extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private boolean changed = false; // person names to upper and trimmed private final Set<String> personNamesSanitized; private final Person initialPerson; /** * Main constructor. * * @param parent The parent frame for this dialog. * @param currentPersons The current set of persons in the case. */ public AddEditPersonDialog(java.awt.Frame parent, Collection<Person> currentPersons) { this(parent, currentPersons, null); } /** * Main constructor. * * @param parent The parent frame for this dialog. * @param currentPersons The current set of persons (used for determining if * name is unique). * @param initialPerson If adding a new person, this will be a null value. * Otherwise, if editing, this will be the person being edited. */ @Messages({ "AddEditPersonDialog_addPerson_title=Add Person", "AddEditPersonDialog_editPerson_title=Edit Person" }) public AddEditPersonDialog(java.awt.Frame parent, Collection<Person> currentPersons, Person initialPerson) { super(parent, true); this.initialPerson = initialPerson; setTitle(initialPerson == null ? Bundle.AddEditPersonDialog_addPerson_title() : Bundle.AddEditPersonDialog_editPerson_title()); personNamesSanitized = PersonNameValidator.getSanitizedPersonNames(currentPersons); initComponents(); onNameUpdate(initialPerson == null ? null : initialPerson.getName()); // initially, don't show validation message (for empty strings or repeat), // but do disable ok button if not valid. validationLabel.setText(""); inputTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { onNameUpdate(inputTextField.getText()); } @Override public void removeUpdate(DocumentEvent e) { onNameUpdate(inputTextField.getText()); } @Override public void insertUpdate(DocumentEvent e) { onNameUpdate(inputTextField.getText()); } }); } /** * @return The string value for the name in the input field if Ok pressed or * null if not. */ public String getValue() { return inputTextField.getText(); } /** * @return Whether or not the value has been changed and the user pressed * okay to save the new value. */ public boolean isChanged() { return changed; } /** * When the text field is updated, this method is called. * * @param newNameValue */ private void onNameUpdate(String newNameValue) { String newNameValueOrEmpty = newNameValue == null ? "" : newNameValue; // update input text field if it is not the same. if (!newNameValueOrEmpty.equals(this.inputTextField.getText())) { inputTextField.setText(newNameValue); } // validate text input against invariants setting validation // message and whether or not okay button is enabled accordingly. String validationMessage = PersonNameValidator.getValidationMessage( newNameValue, initialPerson == null ? null : initialPerson.getName(), personNamesSanitized); okButton.setEnabled(validationMessage == null); validationLabel.setText(validationMessage == null ? "" : validationMessage); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { inputTextField = new javax.swing.JTextField(); javax.swing.JLabel nameLabel = new javax.swing.JLabel(); validationLabel = new javax.swing.JLabel(); okButton = new javax.swing.JButton(); javax.swing.JButton cancelButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); inputTextField.setText(org.openide.util.NbBundle.getMessage(AddEditPersonDialog.class, "AddEditPersonDialog.inputTextField.text_1")); // NOI18N nameLabel.setText(org.openide.util.NbBundle.getMessage(AddEditPersonDialog.class, "AddEditPersonDialog.nameLabel.text_1")); // NOI18N validationLabel.setForeground(Color.RED); validationLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP); okButton.setText(org.openide.util.NbBundle.getMessage(AddEditPersonDialog.class, "AddEditPersonDialog.okButton.text_1")); // NOI18N okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); cancelButton.setText(org.openide.util.NbBundle.getMessage(AddEditPersonDialog.class, "AddEditPersonDialog.cancelButton.text_1")); // NOI18N cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(validationLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(inputTextField) .addGroup(layout.createSequentialGroup() .addComponent(nameLabel) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 288, Short.MAX_VALUE) .addComponent(okButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cancelButton))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(nameLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(inputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(validationLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cancelButton) .addComponent(okButton)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed this.changed = true; dispose(); }//GEN-LAST:event_okButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed this.changed = false; dispose(); }//GEN-LAST:event_cancelButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField inputTextField; private javax.swing.JButton okButton; private javax.swing.JLabel validationLabel; // End of variables declaration//GEN-END:variables }
3,787
321
<gh_stars>100-1000 /** * Most of the code in the Qalingo project is copyrighted Hoteia and licensed * under the Apache License Version 2.0 (release version 0.8.0) * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Hoteia, 2012-2014 * http://www.hoteia.com - http://twitter.com/hoteia - <EMAIL> * */ package org.hoteia.qalingo.core.service.pojo; import java.util.ArrayList; import java.util.List; import org.dozer.Mapper; import org.hoteia.qalingo.core.domain.*; import org.hoteia.qalingo.core.pojo.cart.CartPojo; import org.hoteia.qalingo.core.pojo.deliverymethod.DeliveryMethodPojo; import org.hoteia.qalingo.core.pojo.util.mapper.PojoUtil; import org.hoteia.qalingo.core.service.CartService; import org.hoteia.qalingo.core.service.CatalogCategoryService; import org.hoteia.qalingo.core.service.ProductService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("checkoutPojoService") @Transactional(readOnly = true) public class CheckoutPojoService { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired protected CartService cartService; @Autowired protected ProductService productService; @Autowired protected CatalogCategoryService catalogCategoryService; @Autowired protected Mapper dozerBeanMapper; public CartPojo getCart(MarketArea marketArea, Customer customer) throws Exception { Cart cart = cartService.getCartByMarketAreaIdAndCustomerId(marketArea.getId(), customer.getId()); return handleCartMapping(cart); } public void addProductSkuToCart(Cart cart, final String virtualCatalogCode, final String catalogCategoryCode, final String productSkuCode, final int quantity) throws Exception { cartService.addProductSkuToCart(cart, virtualCatalogCode, catalogCategoryCode, productSkuCode, quantity); } public void updateCartItem(Cart cart, String productSkuCode, int quantity) throws Exception { cartService.updateCartItem(cart, productSkuCode, quantity); } public void deleteCartItem(Cart cart, Store store, String productSkuCode) throws Exception { cartService.deleteCartItem(cart, store, productSkuCode); } public void setShippingAddress(final Cart cart, final Customer customer, final String customerBillingAddressId) throws Exception { Long customerAddressId = Long.parseLong(customerBillingAddressId); cartService.setShippingAddress(cart, customer, customerAddressId); } public void setBillingAddress(final Cart cart, final Customer customer, final String customerBillingAddressId) throws Exception { Long customerAddressId = Long.parseLong(customerBillingAddressId); cartService.setBillingAddress(cart, customer, customerAddressId); } public void setDeliveryMethod(final Cart cart, final String deliveryMethodCode) throws Exception { cartService.setDeliveryMethod(cart, deliveryMethodCode); } public CartPojo handleCartMapping(final Cart cart) { return cart == null ? null : dozerBeanMapper.map(cart, CartPojo.class); } }
1,129
14,668
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/trees/debug_rect_history.h" #include <stddef.h> #include "base/memory/ptr_util.h" #include "cc/base/math_util.h" #include "cc/layers/heads_up_display_layer_impl.h" #include "cc/layers/layer_impl.h" #include "cc/layers/layer_list_iterator.h" #include "cc/layers/render_surface_impl.h" #include "cc/trees/damage_tracker.h" #include "cc/trees/layer_tree_host.h" #include "cc/trees/layer_tree_impl.h" #include "cc/trees/scroll_node.h" #include "ui/gfx/geometry/rect_conversions.h" namespace cc { // static std::unique_ptr<DebugRectHistory> DebugRectHistory::Create() { return base::WrapUnique(new DebugRectHistory()); } DebugRectHistory::DebugRectHistory() = default; DebugRectHistory::~DebugRectHistory() = default; void DebugRectHistory::SaveDebugRectsForCurrentFrame( LayerTreeImpl* tree_impl, HeadsUpDisplayLayerImpl* hud_layer, const RenderSurfaceList& render_surface_list, const LayerTreeDebugState& debug_state) { // For now, clear all rects from previous frames. In the future we may want to // store all debug rects for a history of many frames. debug_rects_.clear(); if (debug_state.show_touch_event_handler_rects) SaveTouchEventHandlerRects(tree_impl); if (debug_state.show_wheel_event_handler_rects) SaveWheelEventHandlerRects(tree_impl); if (debug_state.show_scroll_event_handler_rects) SaveScrollEventHandlerRects(tree_impl); if (debug_state.show_non_fast_scrollable_rects) SaveNonFastScrollableRects(tree_impl); if (debug_state.show_main_thread_scrolling_reason_rects) SaveMainThreadScrollingReasonRects(tree_impl); if (debug_state.show_layout_shift_regions) SaveLayoutShiftRects(hud_layer); if (debug_state.show_paint_rects) SavePaintRects(tree_impl); if (debug_state.show_property_changed_rects) SavePropertyChangedRects(tree_impl, hud_layer); if (debug_state.show_surface_damage_rects) SaveSurfaceDamageRects(render_surface_list); if (debug_state.show_screen_space_rects) SaveScreenSpaceRects(render_surface_list); } void DebugRectHistory::SaveLayoutShiftRects(HeadsUpDisplayLayerImpl* hud) { // We store the layout shift rects on the hud layer. If we don't have the hud // layer, then there is nothing to store. if (!hud) return; for (gfx::Rect rect : hud->LayoutShiftRects()) { debug_rects_.push_back(DebugRect( LAYOUT_SHIFT_RECT_TYPE, MathUtil::MapEnclosingClippedRect(hud->ScreenSpaceTransform(), rect))); } hud->ClearLayoutShiftRects(); } void DebugRectHistory::SavePaintRects(LayerTreeImpl* tree_impl) { // We would like to visualize where any layer's paint rect (update rect) has // changed, regardless of whether this layer is skipped for actual drawing or // not. Therefore we traverse over all layers, not just the render surface // list. for (auto* layer : *tree_impl) { Region invalidation_region = layer->GetInvalidationRegionForDebugging(); if (invalidation_region.IsEmpty() || !layer->DrawsContent()) continue; for (gfx::Rect rect : invalidation_region) { debug_rects_.push_back( DebugRect(PAINT_RECT_TYPE, MathUtil::MapEnclosingClippedRect( layer->ScreenSpaceTransform(), rect))); } } } void DebugRectHistory::SavePropertyChangedRects(LayerTreeImpl* tree_impl, LayerImpl* hud_layer) { for (LayerImpl* layer : *tree_impl) { if (layer == hud_layer) continue; if (!layer->LayerPropertyChanged()) continue; debug_rects_.push_back(DebugRect( PROPERTY_CHANGED_RECT_TYPE, MathUtil::MapEnclosingClippedRect(layer->ScreenSpaceTransform(), gfx::Rect(layer->bounds())))); } } void DebugRectHistory::SaveSurfaceDamageRects( const RenderSurfaceList& render_surface_list) { for (size_t i = 0; i < render_surface_list.size(); ++i) { size_t surface_index = render_surface_list.size() - 1 - i; RenderSurfaceImpl* render_surface = render_surface_list[surface_index]; DCHECK(render_surface); debug_rects_.push_back(DebugRect( SURFACE_DAMAGE_RECT_TYPE, MathUtil::MapEnclosingClippedRect( render_surface->screen_space_transform(), render_surface->GetDamageRect()))); } } void DebugRectHistory::SaveScreenSpaceRects( const RenderSurfaceList& render_surface_list) { for (size_t i = 0; i < render_surface_list.size(); ++i) { size_t surface_index = render_surface_list.size() - 1 - i; RenderSurfaceImpl* render_surface = render_surface_list[surface_index]; DCHECK(render_surface); debug_rects_.push_back(DebugRect( SCREEN_SPACE_RECT_TYPE, MathUtil::MapEnclosingClippedRect( render_surface->screen_space_transform(), render_surface->content_rect()))); } } void DebugRectHistory::SaveTouchEventHandlerRects(LayerTreeImpl* tree_impl) { for (auto* layer : *tree_impl) SaveTouchEventHandlerRectsCallback(layer); } void DebugRectHistory::SaveTouchEventHandlerRectsCallback(LayerImpl* layer) { const TouchActionRegion& touch_action_region = layer->touch_action_region(); for (int touch_action_index = static_cast<int>(TouchAction::kNone); touch_action_index != static_cast<int>(TouchAction::kMax); ++touch_action_index) { auto touch_action = static_cast<TouchAction>(touch_action_index); Region region = touch_action_region.GetRegionForTouchAction(touch_action); for (gfx::Rect rect : region) { debug_rects_.emplace_back(TOUCH_EVENT_HANDLER_RECT_TYPE, MathUtil::MapEnclosingClippedRect( layer->ScreenSpaceTransform(), rect), touch_action); } } } void DebugRectHistory::SaveWheelEventHandlerRects(LayerTreeImpl* tree_impl) { // TODO(https://crbug.com/1136591): Need behavior confirmation. // TODO(https://crbug.com/1136591): Need to check results in dev tools layer // view. for (auto* layer : *tree_impl) { const Region& region = layer->wheel_event_handler_region(); for (gfx::Rect rect : region) { debug_rects_.emplace_back( DebugRect(WHEEL_EVENT_HANDLER_RECT_TYPE, MathUtil::MapEnclosingClippedRect( layer->ScreenSpaceTransform(), rect))); } } } void DebugRectHistory::SaveScrollEventHandlerRects(LayerTreeImpl* tree_impl) { for (auto* layer : *tree_impl) SaveScrollEventHandlerRectsCallback(layer); } void DebugRectHistory::SaveScrollEventHandlerRectsCallback(LayerImpl* layer) { if (!layer->layer_tree_impl()->have_scroll_event_handlers()) return; debug_rects_.push_back( DebugRect(SCROLL_EVENT_HANDLER_RECT_TYPE, MathUtil::MapEnclosingClippedRect(layer->ScreenSpaceTransform(), gfx::Rect(layer->bounds())))); } void DebugRectHistory::SaveNonFastScrollableRects(LayerTreeImpl* tree_impl) { for (auto* layer : *tree_impl) SaveNonFastScrollableRectsCallback(layer); } void DebugRectHistory::SaveNonFastScrollableRectsCallback(LayerImpl* layer) { for (gfx::Rect rect : layer->non_fast_scrollable_region()) { debug_rects_.push_back(DebugRect(NON_FAST_SCROLLABLE_RECT_TYPE, MathUtil::MapEnclosingClippedRect( layer->ScreenSpaceTransform(), rect))); } } void DebugRectHistory::SaveMainThreadScrollingReasonRects( LayerTreeImpl* tree_impl) { const auto& scroll_tree = tree_impl->property_trees()->scroll_tree; for (auto* layer : *tree_impl) { if (const auto* scroll_node = scroll_tree.FindNodeFromElementId(layer->element_id())) { if (auto reasons = scroll_node->main_thread_scrolling_reasons) { debug_rects_.push_back(DebugRect( MAIN_THREAD_SCROLLING_REASON_RECT_TYPE, MathUtil::MapEnclosingClippedRect(layer->ScreenSpaceTransform(), gfx::Rect(layer->bounds())), TouchAction::kNone, reasons)); } } } } } // namespace cc
3,408
348
{"nom":"Juilly","circ":"6ème circonscription","dpt":"Seine-et-Marne","inscrits":1334,"abs":888,"votants":446,"blancs":61,"nuls":15,"exp":370,"res":[{"nuance":"REM","nom":"<NAME>","voix":209},{"nuance":"LR","nom":"<NAME>","voix":161}]}
93
331
<filename>src/main/java/org/fordes/subview/controller/settings/ExperimentSettingController.java package org.fordes.subview.controller.settings; import de.felixroske.jfxsupport.FXMLController; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.CheckBox; import lombok.extern.slf4j.Slf4j; import org.fordes.subview.controller.BasicController; import org.fordes.subview.controller.ToastController; import org.fordes.subview.enums.ToastEnum; import javax.annotation.Resource; import java.net.URL; import java.util.ResourceBundle; /** * @author fordes on 2021/3/18 */ @FXMLController @Slf4j public class ExperimentSettingController extends BasicController implements Initializable { @FXML private CheckBox subtitles_search, custom_background, format_fix, original_content; @Resource private ToastController toastController; @Override public void initialize(URL location, ResourceBundle resources) { subtitles_search.selectedProperty().addListener((observable, oldValue, newValue) -> { subtitles_search.setSelected(true); toastController.pushMessage(ToastEnum.INFO, "不可以哦~"); }); custom_background.selectedProperty().addListener((observable, oldValue, newValue) -> { custom_background.setSelected(false); toastController.pushMessage(ToastEnum.INFO, "不可以哦~"); }); } }
513
428
/** * Copyright 2008 - 2019 The Loon Game Engine 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. * * @project loon * @author cping * @email:<EMAIL> * @version 0.5 */ package loon.action.sprite; import loon.LSystem; import loon.canvas.LColor; import loon.font.Font.Style; import loon.font.IFont; import loon.font.LFont; import loon.font.Text; import loon.font.TextOptions; import loon.opengl.GLEx; /** * 一个精灵用字符串显示用类 * */ public class SpriteLabel extends Entity { private final Text _text; public SpriteLabel(String label) { this(LSystem.getSystemGameFont(), label, 0, 0); } public SpriteLabel(String label, int x, int y) { this(LSystem.getSystemGameFont(), label, x, y); } public SpriteLabel(String label, String font, Style type, int size, int x, int y) { this(LFont.getFont(font, type, size), label, x, y); } public SpriteLabel(IFont font, String label, int x, int y) { this(font, TextOptions.LEFT(), label, x, y); } public SpriteLabel(IFont font, TextOptions opt, String label, int x, int y) { this._text = new Text(font, label, opt); this.setSize(_text.getWidth(), _text.getHeight()); this.setRepaint(true); this.setColor(LColor.white); this.setLocation(x, y); this.setLabel(label); } public void setFont(String fontName, Style type, int size) { setFont(LFont.getFont(fontName, type, size)); } public void setFont(IFont font) { this._text.setFont(font); this.setSize(_text.getWidth(), _text.getHeight()); } @Override public void repaint(GLEx g, float offsetX, float offsetY) { _text.paintString(g, drawX(offsetX), drawY(offsetY), _baseColor); } public Text getOptions() { return this._text; } public CharSequence getLabel() { return _text.getText(); } public SpriteLabel setLabel(int label) { return setLabel(String.valueOf(label)); } public SpriteLabel setLabel(CharSequence label) { _text.setText(label); return this; } @Override public void close() { super.close(); _text.close(); } }
886
30,023
<gh_stars>1000+ """Constants for the Toon integration.""" from datetime import timedelta DOMAIN = "toon" CONF_AGREEMENT = "agreement" CONF_AGREEMENT_ID = "agreement_id" CONF_CLOUDHOOK_URL = "cloudhook_url" CONF_MIGRATE = "migrate" DEFAULT_SCAN_INTERVAL = timedelta(seconds=300) DEFAULT_MAX_TEMP = 30.0 DEFAULT_MIN_TEMP = 6.0 CURRENCY_EUR = "EUR" VOLUME_CM3 = "CM3" VOLUME_LHOUR = "L/H" VOLUME_LMIN = "L/MIN"
185
5,250
{ "groupId":"org.flowable.client.kotlin", "artifactId":"flowable-kotlin-client-content", "artifactVersion":"0.0.1", "packageName":"org.flowable.client.kotlin.content", "invokerPackage":"org.flowable.client.kotlin.content", "modelPackage":"org.flowable.client.kotlin.content.model", "apiPackage":"org.flowable.client.kotlin.content.api" }
132
1,695
<reponame>x-malet/trino /* * 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 io.trino.plugin.hive; import io.trino.plugin.hive.acid.AcidOperation; import io.trino.plugin.hive.acid.AcidTransaction; import io.trino.plugin.hive.orc.OrcFileWriterFactory; import io.trino.spi.block.Block; import io.trino.spi.connector.ConnectorSession; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import java.util.Optional; import java.util.OptionalInt; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static io.trino.orc.OrcWriter.OrcOperation.DELETE; import static io.trino.orc.OrcWriter.OrcOperation.INSERT; import static io.trino.plugin.hive.HiveStorageFormat.ORC; import static io.trino.plugin.hive.acid.AcidSchema.ACID_COLUMN_NAMES; import static io.trino.plugin.hive.acid.AcidSchema.createAcidSchema; import static io.trino.plugin.hive.metastore.StorageFormat.fromHiveStorageFormat; import static io.trino.plugin.hive.util.ConfigurationUtils.toJobConf; import static io.trino.spi.predicate.Utils.nativeValueToBlock; import static io.trino.spi.type.IntegerType.INTEGER; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.apache.hadoop.hive.ql.io.AcidUtils.deleteDeltaSubdir; import static org.apache.hadoop.hive.ql.io.AcidUtils.deltaSubdir; public abstract class AbstractHiveAcidWriters { public static final Block DELETE_OPERATION_BLOCK = nativeValueToBlock(INTEGER, Long.valueOf(DELETE.getOperationNumber())); public static final Block INSERT_OPERATION_BLOCK = nativeValueToBlock(INTEGER, Long.valueOf(INSERT.getOperationNumber())); // The bucketPath looks like .../delta_nnnnnnn_mmmmmmm_ssss/bucket_bbbbb(_aaaa)? public static final Pattern BUCKET_PATH_MATCHER = Pattern.compile("(?s)(?<rootDir>.*)/(?<dirStart>delta_[\\d]+_[\\d]+)_(?<statementId>[\\d]+)/(?<filenameBase>bucket_(?<bucketNumber>[\\d]+))(?<attemptId>_[\\d]+)?$"); // The original file path looks like .../nnnnnnn_m(_copy_ccc)? public static final Pattern ORIGINAL_FILE_PATH_MATCHER = Pattern.compile("(?s)(?<rootDir>.*)/(?<filename>(?<bucketNumber>[\\d]+)_(?<rest>.*)?)$"); // After compaction, the bucketPath looks like .../base_nnnnnnn(_vmmmmmmm)?/bucket_bbbbb(_aaaa)? public static final Pattern BASE_PATH_MATCHER = Pattern.compile("(?s)(?<rootDir>.*)/(?<dirStart>base_[-]?[\\d]+(_v[\\d]+)?)/(?<filenameBase>bucket_(?<bucketNumber>[\\d]+))(?<attemptId>_[\\d]+)?$"); protected final AcidTransaction transaction; protected final OptionalInt bucketNumber; protected final int statementId; private final OrcFileWriterFactory orcFileWriterFactory; private final Configuration configuration; protected final ConnectorSession session; protected final HiveType hiveRowType; private final Properties hiveAcidSchema; protected final Path deleteDeltaDirectory; private final String bucketFilename; protected Optional<Path> deltaDirectory; protected Optional<FileWriter> deleteFileWriter = Optional.empty(); protected Optional<FileWriter> insertFileWriter = Optional.empty(); public AbstractHiveAcidWriters( AcidTransaction transaction, int statementId, OptionalInt bucketNumber, Path bucketPath, boolean originalFile, OrcFileWriterFactory orcFileWriterFactory, Configuration configuration, ConnectorSession session, HiveType hiveRowType, AcidOperation updateKind) { this.transaction = requireNonNull(transaction, "transaction is null"); this.statementId = statementId; this.bucketNumber = requireNonNull(bucketNumber, "bucketNumber is null"); this.orcFileWriterFactory = requireNonNull(orcFileWriterFactory, "orcFileWriterFactory is null"); this.configuration = requireNonNull(configuration, "configuration is null"); this.session = requireNonNull(session, "session is null"); checkArgument(transaction.isTransactional(), "Not in a transaction: %s", transaction); this.hiveRowType = requireNonNull(hiveRowType, "hiveRowType is null"); this.hiveAcidSchema = createAcidSchema(hiveRowType); requireNonNull(bucketPath, "bucketPath is null"); Matcher matcher; if (originalFile) { matcher = ORIGINAL_FILE_PATH_MATCHER.matcher(bucketPath.toString()); checkArgument(matcher.matches(), "Original file bucketPath doesn't have the required format: %s", bucketPath); this.bucketFilename = format("bucket_%05d", bucketNumber.isEmpty() ? 0 : bucketNumber.getAsInt()); } else { matcher = BASE_PATH_MATCHER.matcher(bucketPath.toString()); if (matcher.matches()) { this.bucketFilename = matcher.group("filenameBase"); } else { matcher = BUCKET_PATH_MATCHER.matcher(bucketPath.toString()); checkArgument(matcher.matches(), "bucketPath doesn't have the required format: %s", bucketPath); this.bucketFilename = matcher.group("filenameBase"); } } long writeId = transaction.getWriteId(); this.deleteDeltaDirectory = new Path(format("%s/%s", matcher.group("rootDir"), deleteDeltaSubdir(writeId, writeId, statementId))); if (updateKind == AcidOperation.UPDATE) { this.deltaDirectory = Optional.of(new Path(format("%s/%s", matcher.group("rootDir"), deltaSubdir(writeId, writeId, statementId)))); } else { this.deltaDirectory = Optional.empty(); } } protected void lazyInitializeDeleteFileWriter() { if (deleteFileWriter.isEmpty()) { Properties schemaCopy = new Properties(); schemaCopy.putAll(hiveAcidSchema); deleteFileWriter = orcFileWriterFactory.createFileWriter( new Path(format("%s/%s", deleteDeltaDirectory, bucketFilename)), ACID_COLUMN_NAMES, fromHiveStorageFormat(ORC), schemaCopy, toJobConf(configuration), session, bucketNumber, transaction, true, WriterKind.DELETE); } } protected void lazyInitializeInsertFileWriter() { if (insertFileWriter.isEmpty()) { Properties schemaCopy = new Properties(); schemaCopy.putAll(hiveAcidSchema); Path deltaDir = deltaDirectory.orElseThrow(() -> new IllegalArgumentException("deltaDirectory not present")); insertFileWriter = orcFileWriterFactory.createFileWriter( new Path(format("%s/%s", deltaDir, bucketFilename)), ACID_COLUMN_NAMES, fromHiveStorageFormat(ORC), schemaCopy, toJobConf(configuration), session, bucketNumber, transaction, true, WriterKind.INSERT); } } }
3,104
1,354
<reponame>rockya2014/Hackerrank-Solutions /** * * Problem Statement- * [Day of the Programmer](https://www.hackerrank.com/challenges/day-of-the-programmer/problem) * */ package org.javaaid.hackerrank.solutions.implementation.bruteforce; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Scanner; /** * @author <NAME> * */ public class DayOfTheProgrammer { public static void main(String[] args) throws ParseException { Scanner sc = new Scanner(System.in); int y = sc.nextInt(); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); int d = 243; if (y >= 1700 && y <= 1917) { if (y % 4 == 0) { d = 244; } } else if (y >= 1919 && y <= 2700) { if (y % 400 == 0 || (y % 100 != 0 && y % 4 == 0)) { d = 244; } } else if (y == 1918) { d = 230; } int r = 256 - d; String date = r + "." + 9 + "." + y; System.out.println(sdf.format(sdf.parse(date))); sc.close(); } }
435
5,169
<reponame>Gantios/Specs<filename>Specs/2/a/5/KLCarouselView/1.0.1/KLCarouselView.podspec.json { "name": "KLCarouselView", "version": "1.0.1", "summary": "一键轮播微改", "description": "简单快速轮播(微改)", "homepage": "https://github.com/StarSkyK/KLCarouselView", "license": "MIT", "authors": { "锴伦": "<EMAIL>" }, "platforms": { "ios": "9.0" }, "source": { "git": "https://github.com/StarSkyK/KLCarouselView.git", "tag": "1.0.1" }, "source_files": "Lunbo/main/*.{h,m}", "resources": "Lunbo/Res/*.jpg", "requires_arc": true }
299