max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
321
<filename>apis/api-web/api-web-bo-business/src/main/java/org/hoteia/qalingo/web/mvc/controller/ajax/CatalogAjaxController.java /** * 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.web.mvc.controller.ajax; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.hoteia.qalingo.core.RequestConstants; import org.hoteia.qalingo.core.domain.CatalogCategoryMaster; import org.hoteia.qalingo.core.domain.CatalogCategoryMasterProductSkuRel; import org.hoteia.qalingo.core.domain.CatalogCategoryMaster_; import org.hoteia.qalingo.core.domain.CatalogCategoryVirtual; import org.hoteia.qalingo.core.domain.CatalogCategoryVirtualProductSkuRel; import org.hoteia.qalingo.core.domain.CatalogCategoryVirtualProductSkuRel_; import org.hoteia.qalingo.core.domain.CatalogCategoryVirtual_; import org.hoteia.qalingo.core.domain.CatalogMaster; import org.hoteia.qalingo.core.domain.CatalogVirtual; import org.hoteia.qalingo.core.domain.MarketArea; import org.hoteia.qalingo.core.domain.ProductMarketing; import org.hoteia.qalingo.core.domain.ProductMarketing_; import org.hoteia.qalingo.core.domain.ProductSku; import org.hoteia.qalingo.core.domain.ProductSkuStorePrice_; import org.hoteia.qalingo.core.domain.ProductSku_; import org.hoteia.qalingo.core.domain.enumtype.BoUrls; import org.hoteia.qalingo.core.fetchplan.FetchPlan; import org.hoteia.qalingo.core.fetchplan.SpecificFetchMode; import org.hoteia.qalingo.core.pojo.catalog.BoCatalogCategoryPojo; import org.hoteia.qalingo.core.pojo.catalog.CatalogPojo; import org.hoteia.qalingo.core.pojo.product.ProductMarketingPojo; import org.hoteia.qalingo.core.pojo.product.ProductSkuPojo; import org.hoteia.qalingo.core.service.CatalogCategoryService; import org.hoteia.qalingo.core.service.CatalogService; import org.hoteia.qalingo.core.service.ProductService; import org.hoteia.qalingo.core.service.pojo.CatalogPojoService; import org.hoteia.qalingo.core.web.resolver.RequestData; import org.hoteia.qalingo.web.mvc.controller.AbstractBusinessBackofficeController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * */ @Controller("catalogAjaxController") public class CatalogAjaxController extends AbstractBusinessBackofficeController { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired protected CatalogService catalogService; @Autowired private CatalogPojoService catalogPojoService; @Autowired protected ProductService productService; @Autowired protected CatalogCategoryService catalogCategoryService; protected List<SpecificFetchMode> categoryMasterFetchPlans = new ArrayList<SpecificFetchMode>(); protected List<SpecificFetchMode> categoryVirtualFetchPlans = new ArrayList<SpecificFetchMode>(); protected List<SpecificFetchMode> productMarketingFetchPlans = new ArrayList<SpecificFetchMode>(); protected List<SpecificFetchMode> productSkuFetchPlans = new ArrayList<SpecificFetchMode>(); public CatalogAjaxController() { categoryMasterFetchPlans.add(new SpecificFetchMode(CatalogCategoryMaster_.catalogCategories.getName())); categoryMasterFetchPlans.add(new SpecificFetchMode(CatalogCategoryMaster_.parentCatalogCategory.getName())); categoryMasterFetchPlans.add(new SpecificFetchMode(CatalogCategoryMaster_.attributes.getName())); categoryMasterFetchPlans.add(new SpecificFetchMode(CatalogCategoryMaster_.catalogCategoryType.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.catalogCategories.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.parentCatalogCategory.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.attributes.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.categoryMaster.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.parentCatalogCategory.getName() + "." + CatalogCategoryVirtual_.categoryMaster.getName())); categoryVirtualFetchPlans.add(new SpecificFetchMode(CatalogCategoryVirtual_.categoryMaster.getName() + "." + CatalogCategoryMaster_.catalogCategoryType.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.productBrand.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.productMarketingType.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.attributes.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.productSkus.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.productSkus.getName() + "." + ProductSku_.prices.getName())); productMarketingFetchPlans.add(new SpecificFetchMode(ProductMarketing_.productSkus.getName() + "." + ProductSku_.prices.getName() + "." + ProductSkuStorePrice_.currency.getName())); productSkuFetchPlans.add(new SpecificFetchMode(ProductSku_.productMarketing.getName())); productSkuFetchPlans.add(new SpecificFetchMode(ProductSku_.attributes.getName())); } @RequestMapping(value = BoUrls.GET_CATALOG_AJAX_URL, method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody public CatalogPojo getCatalog(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final RequestData requestData = requestUtil.getRequestData(request); final MarketArea currentMarketArea = requestData.getMarketArea(); final String catalogType = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_TYPE); CatalogPojo catalogPojo = new CatalogPojo(); if("master".equals(catalogType)){ final CatalogMaster catalogMaster = catalogService.getMasterCatalogById(currentMarketArea.getCatalog().getCatalogMaster().getId()); Set<CatalogCategoryMaster> catalogCategories = new HashSet<CatalogCategoryMaster>(); if(catalogMaster.getCatalogCategories() != null){ for (Iterator<CatalogCategoryMaster> iterator = catalogMaster.getCatalogCategories().iterator(); iterator.hasNext();) { CatalogCategoryMaster categoryMaster = (CatalogCategoryMaster) iterator.next(); CatalogCategoryMaster reloadedCategoryMaster = catalogCategoryService.getMasterCatalogCategoryById(categoryMaster.getId(), new FetchPlan(categoryMasterFetchPlans)); Set<CatalogCategoryMaster> reloadedSubCategories = new HashSet<CatalogCategoryMaster>(); if(reloadedCategoryMaster.getSortedChildCatalogCategories() != null){ for (Iterator<CatalogCategoryMaster> iteratorSubCategories = reloadedCategoryMaster.getSortedChildCatalogCategories().iterator(); iteratorSubCategories.hasNext();) { CatalogCategoryMaster subCategory = (CatalogCategoryMaster) iteratorSubCategories.next(); CatalogCategoryMaster reloadedSubCategory = catalogCategoryService.getMasterCatalogCategoryById(subCategory.getId(), new FetchPlan(categoryMasterFetchPlans)); reloadedSubCategories.add(reloadedSubCategory); } } reloadedCategoryMaster.setCatalogCategories(reloadedSubCategories); catalogCategories.add(reloadedCategoryMaster); } } catalogMaster.setCatalogCategories(new HashSet<CatalogCategoryMaster>(catalogCategories)); try { catalogPojo = (CatalogPojo) catalogPojoService.buildMasterCatalog(catalogMaster); } catch (Exception e) { logger.error("", e); } } else if("virtual".equals(catalogType)){ final CatalogVirtual catalogVirtual = catalogService.getVirtualCatalogById(currentMarketArea.getCatalog().getId()); Set<CatalogCategoryVirtual> catalogCategories = new HashSet<CatalogCategoryVirtual>(); if(catalogVirtual.getCatalogCategories() != null){ for (Iterator<CatalogCategoryVirtual> iterator = catalogVirtual.getCatalogCategories().iterator(); iterator.hasNext();) { CatalogCategoryVirtual categoryVirtual = (CatalogCategoryVirtual) iterator.next(); CatalogCategoryVirtual reloadedCategoryVirtual = catalogCategoryService.getVirtualCatalogCategoryById(categoryVirtual.getId(), new FetchPlan(categoryVirtualFetchPlans)); Set<CatalogCategoryVirtual> reloadedSubCategories = new HashSet<CatalogCategoryVirtual>(); if(reloadedCategoryVirtual.getSortedChildCatalogCategories() != null){ for (Iterator<CatalogCategoryVirtual> iteratorSubCategories = reloadedCategoryVirtual.getSortedChildCatalogCategories().iterator(); iteratorSubCategories.hasNext();) { CatalogCategoryVirtual subCategory = (CatalogCategoryVirtual) iteratorSubCategories.next(); CatalogCategoryVirtual reloadedSubCategory = catalogCategoryService.getVirtualCatalogCategoryById(subCategory.getId(), new FetchPlan(categoryVirtualFetchPlans)); reloadedSubCategories.add(reloadedSubCategory); } } reloadedCategoryVirtual.setCatalogCategories(reloadedSubCategories); catalogCategories.add(reloadedCategoryVirtual); } } catalogVirtual.setCatalogCategories(new HashSet<CatalogCategoryVirtual>(catalogCategories)); try { catalogPojo = (CatalogPojo) catalogPojoService.buildVirtualCatalog(catalogVirtual); } catch (Exception e) { logger.error("", e); } } return catalogPojo; } @RequestMapping(value = BoUrls.GET_PRODUCT_LIST_AJAX_URL, method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody public BoCatalogCategoryPojo getProductListByCategory(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final RequestData requestData = requestUtil.getRequestData(request); final String categoryCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_CATEGORY_CODE); final String catalogType = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_TYPE); BoCatalogCategoryPojo catalogCategoryPojo = new BoCatalogCategoryPojo(); if("master".equals(catalogType)){ FetchPlan fetchPlanWithProducts = new FetchPlan(categoryMasterFetchPlans); fetchPlanWithProducts.getFetchModes().add(new SpecificFetchMode(CatalogCategoryVirtual_.catalogCategoryProductSkuRels.getName())); fetchPlanWithProducts.getFetchModes().add(new SpecificFetchMode("catalogCategoryProductSkuRels.pk.productSku")); fetchPlanWithProducts.getFetchModes().add(new SpecificFetchMode(CatalogCategoryVirtual_.assets.getName())); CatalogCategoryMaster reloadedCategory = catalogCategoryService.getMasterCatalogCategoryByCode(categoryCode, requestData.getMasterCatalogCode(), fetchPlanWithProducts); catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); final List<ProductSku> productSkus = reloadedCategory.getSortedProductSkus(); catalogCategoryPojo.setProductMarketings(buildSortedProduct(productSkus)); } else if("virtual".equals(catalogType)){ FetchPlan fetchPlanWithProducts = new FetchPlan(categoryVirtualFetchPlans); fetchPlanWithProducts.getFetchModes().add(new SpecificFetchMode(CatalogCategoryVirtual_.catalogCategoryProductSkuRels.getName())); fetchPlanWithProducts.getFetchModes().add(new SpecificFetchMode(CatalogCategoryVirtual_.catalogCategoryProductSkuRels.getName() + "." + CatalogCategoryVirtualProductSkuRel_.pk.getName() + "." + org.hoteia.qalingo.core.domain.CatalogCategoryVirtualProductSkuPk_.productSku.getName())); CatalogCategoryVirtual reloadedCategory = catalogCategoryService.getVirtualCatalogCategoryByCode(categoryCode, requestData.getVirtualCatalogCode(), requestData.getMasterCatalogCode(), fetchPlanWithProducts); catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); final List<ProductSku> productSkus = reloadedCategory.getSortedProductSkus(); catalogCategoryPojo.setProductMarketings(buildSortedProduct(productSkus)); } return catalogCategoryPojo; } @RequestMapping(value = BoUrls.GET_PRODUCT_LIST_FOR_CATALOG_CATEGORY_AJAX_URL, method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody public BoCatalogCategoryPojo getProductListForCategory(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final RequestData requestData = requestUtil.getRequestData(request); final String categoryCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_CATEGORY_CODE); final String catalogType = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_TYPE); BoCatalogCategoryPojo catalogCategoryPojo = new BoCatalogCategoryPojo(); if("master".equals(catalogType)){ CatalogCategoryMaster reloadedCategory = catalogCategoryService.getMasterCatalogCategoryByCode(categoryCode, requestData.getMasterCatalogCode(), new FetchPlan(categoryMasterFetchPlans)); catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); List<ProductSku> productSkus = productService.findProductSkusNotInThisMasterCatalogCategoryId(reloadedCategory.getId(), new FetchPlan(productSkuFetchPlans)); catalogCategoryPojo.setProductMarketings(buildSortedProduct(productSkus)); } else if("virtual".equals(catalogType)){ CatalogCategoryVirtual reloadedCategory = catalogCategoryService.getVirtualCatalogCategoryByCode(categoryCode, requestData.getVirtualCatalogCode(), requestData.getMasterCatalogCode(), new FetchPlan(categoryVirtualFetchPlans)); catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); List<ProductSku> productSkus = productService.findProductSkusNotInThisVirtualCatalogCategoryId(reloadedCategory.getId(), new FetchPlan(productSkuFetchPlans)); catalogCategoryPojo.setProductMarketings(buildSortedProduct(productSkus)); } return catalogCategoryPojo; } @RequestMapping(value = BoUrls.SET_PRODUCT_LIST_FOR_CATALOG_CATEGORY_AJAX_URL, method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody public BoCatalogCategoryPojo setProductListForCategory(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final RequestData requestData = requestUtil.getRequestData(request); final String categoryCode = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_CATEGORY_CODE); final String catalogType = request.getParameter(RequestConstants.REQUEST_PARAMETER_CATALOG_TYPE); final String skuCodes = request.getParameter(RequestConstants.REQUEST_PARAMETER_SKU_CODE_LIST); BoCatalogCategoryPojo catalogCategoryPojo = new BoCatalogCategoryPojo(); if("master".equals(catalogType)){ CatalogCategoryMaster reloadedCategory = catalogCategoryService.getMasterCatalogCategoryByCode(categoryCode, requestData.getMasterCatalogCode(), new FetchPlan(categoryMasterFetchPlans)); if(StringUtils.isNotEmpty(skuCodes)){ List<String> productSkuCodes = reloadedCategory.getProductSkuCodes(); String[] skuCodesSplit = skuCodes.split(";"); for (int i = 0; i < skuCodesSplit.length; i++) { String skuCode = skuCodesSplit[i]; if(productSkuCodes != null && !productSkuCodes.contains(skuCode)){ final ProductSku reloadedProductSku = productService.getProductSkuByCode(skuCode, new FetchPlan(productSkuFetchPlans)); if(reloadedProductSku != null){ reloadedCategory.getCatalogCategoryProductSkuRels().add(new CatalogCategoryMasterProductSkuRel(reloadedCategory, reloadedProductSku)); reloadedCategory = catalogCategoryService.saveOrUpdateCatalogCategory(reloadedCategory); } } } } catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); } else if("virtual".equals(catalogType)){ CatalogCategoryVirtual reloadedCategory = catalogCategoryService.getVirtualCatalogCategoryByCode(categoryCode, requestData.getVirtualCatalogCode(), requestData.getMasterCatalogCode(), new FetchPlan(categoryVirtualFetchPlans)); if(StringUtils.isNotEmpty(skuCodes)){ List<String> productSkuCodes = reloadedCategory.getProductSkuCodes(); String[] skuCodesSplit = skuCodes.split(";"); for (int i = 0; i < skuCodesSplit.length; i++) { String skuCode = skuCodesSplit[i]; if(productSkuCodes != null && !productSkuCodes.contains(skuCode)){ final ProductSku reloadedProductSku = productService.getProductSkuByCode(skuCode, new FetchPlan(productSkuFetchPlans)); if(reloadedProductSku != null){ reloadedCategory.getCatalogCategoryProductSkuRels().add(new CatalogCategoryVirtualProductSkuRel(reloadedCategory, reloadedProductSku)); reloadedCategory = catalogCategoryService.saveOrUpdateCatalogCategory(reloadedCategory); } } } } catalogCategoryPojo = (BoCatalogCategoryPojo) catalogPojoService.buildCatalogCategory(reloadedCategory); } return catalogCategoryPojo; } protected List<ProductMarketingPojo> buildSortedProduct(List<ProductSku> productSkus){ List<Long> productSkuIds = new ArrayList<Long>(); for (Iterator<ProductSku> iterator = productSkus.iterator(); iterator.hasNext();) { ProductSku productSku = (ProductSku) iterator.next(); productSkuIds.add(productSku.getId()); } Map<String, ProductMarketingPojo> productMarketingMap = new HashMap<String, ProductMarketingPojo>(); for (Iterator<ProductSku> iteratorProductSku = productSkus.iterator(); iteratorProductSku.hasNext();) { final ProductSku productSku = (ProductSku) iteratorProductSku.next(); final ProductSku reloadedProductSku = productService.getProductSkuByCode(productSku.getCode(), new FetchPlan(productSkuFetchPlans)); final ProductMarketing reloadedProductMarketing = productService.getProductMarketingById(reloadedProductSku.getProductMarketing().getId(), new FetchPlan(productMarketingFetchPlans)); ProductMarketingPojo productMarketingPojo = catalogPojoService.buildProductMarketing(reloadedProductMarketing); // CLEAN NOT AVAILABLE SKU List<ProductSkuPojo> productSkuPojos = new ArrayList<ProductSkuPojo>(productMarketingPojo.getProductSkus()); for (Iterator<ProductSkuPojo> iterator = productSkuPojos.iterator(); iterator.hasNext();) { ProductSkuPojo productSkuPojo = (ProductSkuPojo) iterator.next(); if(!productSkuIds.contains(productSkuPojo.getId())){ productMarketingPojo.getProductSkus().remove(productSkuPojo); } } productMarketingMap.put(productMarketingPojo.getCode(), productMarketingPojo); } List<ProductMarketingPojo> sortedProductMarketings = new LinkedList<ProductMarketingPojo>(productMarketingMap.values()); Collections.sort(sortedProductMarketings, new Comparator<ProductMarketingPojo>() { @Override public int compare(ProductMarketingPojo o1, ProductMarketingPojo o2) { if (o1 != null && o2 != null) { return o1.getCode().compareTo(o2.getCode()); } return 0; } }); return sortedProductMarketings; } }
8,657
488
<filename>tests/nonsmoke/functional/CompileTests/C_tests/test2020_08.c<gh_stars>100-1000 void foo(double); void foobar() { #if 0 foo(0x0'0.0p0); foo(0x0'0.0p0F); foo(0x0'0.0P+0l); #endif }
118
348
{"nom":"Wormhout","circ":"14ème circonscription","dpt":"Nord","inscrits":4558,"abs":2275,"votants":2283,"blancs":117,"nuls":65,"exp":2101,"res":[{"nuance":"LR","nom":"<NAME>","voix":1524},{"nuance":"REM","nom":"<NAME>","voix":577}]}
94
3,755
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE from collections import Counter import datetime import inspect import json import re import time import frappe import sqlparse from frappe import _ RECORDER_INTERCEPT_FLAG = "recorder-intercept" RECORDER_REQUEST_SPARSE_HASH = "recorder-requests-sparse" RECORDER_REQUEST_HASH = "recorder-requests" def sql(*args, **kwargs): start_time = time.time() result = frappe.db._sql(*args, **kwargs) end_time = time.time() stack = list(get_current_stack_frames()) if frappe.db.db_type == "postgres": query = frappe.db._cursor.query else: query = frappe.db._cursor._executed query = sqlparse.format(query.strip(), keyword_case="upper", reindent=True) # Collect EXPLAIN for executed query if query.lower().strip().split()[0] in ("select", "update", "delete"): # Only SELECT/UPDATE/DELETE queries can be "EXPLAIN"ed explain_result = frappe.db._sql("EXPLAIN {}".format(query), as_dict=True) else: explain_result = [] data = { "query": query, "stack": stack, "explain_result": explain_result, "time": start_time, "duration": float("{:.3f}".format((end_time - start_time) * 1000)), } frappe.local._recorder.register(data) return result def get_current_stack_frames(): try: current = inspect.currentframe() frames = inspect.getouterframes(current, context=10) for frame, filename, lineno, function, context, index in list(reversed(frames))[:-2]: if "/apps/" in filename: yield { "filename": re.sub(".*/apps/", "", filename), "lineno": lineno, "function": function, } except Exception: pass def record(): if __debug__: if frappe.cache().get_value(RECORDER_INTERCEPT_FLAG): frappe.local._recorder = Recorder() def dump(): if __debug__: if hasattr(frappe.local, "_recorder"): frappe.local._recorder.dump() class Recorder: def __init__(self): self.uuid = frappe.generate_hash(length=10) self.time = datetime.datetime.now() self.calls = [] self.path = frappe.request.path self.cmd = frappe.local.form_dict.cmd or "" self.method = frappe.request.method self.headers = dict(frappe.local.request.headers) self.form_dict = frappe.local.form_dict _patch() def register(self, data): self.calls.append(data) def dump(self): request_data = { "uuid": self.uuid, "path": self.path, "cmd": self.cmd, "time": self.time, "queries": len(self.calls), "time_queries": float( "{:0.3f}".format(sum(call["duration"] for call in self.calls)) ), "duration": float( "{:0.3f}".format((datetime.datetime.now() - self.time).total_seconds() * 1000) ), "method": self.method, } frappe.cache().hset(RECORDER_REQUEST_SPARSE_HASH, self.uuid, request_data) frappe.publish_realtime( event="recorder-dump-event", message=json.dumps(request_data, default=str) ) self.mark_duplicates() request_data["calls"] = self.calls request_data["headers"] = self.headers request_data["form_dict"] = self.form_dict frappe.cache().hset(RECORDER_REQUEST_HASH, self.uuid, request_data) def mark_duplicates(self): counts = Counter([call["query"] for call in self.calls]) for index, call in enumerate(self.calls): call["index"] = index call["exact_copies"] = counts[call["query"]] def _patch(): frappe.db._sql = frappe.db.sql frappe.db.sql = sql def do_not_record(function): def wrapper(*args, **kwargs): if hasattr(frappe.local, "_recorder"): del frappe.local._recorder frappe.db.sql = frappe.db._sql return function(*args, **kwargs) return wrapper def administrator_only(function): def wrapper(*args, **kwargs): if frappe.session.user != "Administrator": frappe.throw(_("Only Administrator is allowed to use Recorder")) return function(*args, **kwargs) return wrapper @frappe.whitelist() @do_not_record @administrator_only def status(*args, **kwargs): return bool(frappe.cache().get_value(RECORDER_INTERCEPT_FLAG)) @frappe.whitelist() @do_not_record @administrator_only def start(*args, **kwargs): frappe.cache().set_value(RECORDER_INTERCEPT_FLAG, 1) @frappe.whitelist() @do_not_record @administrator_only def stop(*args, **kwargs): frappe.cache().delete_value(RECORDER_INTERCEPT_FLAG) @frappe.whitelist() @do_not_record @administrator_only def get(uuid=None, *args, **kwargs): if uuid: result = frappe.cache().hget(RECORDER_REQUEST_HASH, uuid) else: result = list(frappe.cache().hgetall(RECORDER_REQUEST_SPARSE_HASH).values()) return result @frappe.whitelist() @do_not_record @administrator_only def export_data(*args, **kwargs): return list(frappe.cache().hgetall(RECORDER_REQUEST_HASH).values()) @frappe.whitelist() @do_not_record @administrator_only def delete(*args, **kwargs): frappe.cache().delete_value(RECORDER_REQUEST_SPARSE_HASH) frappe.cache().delete_value(RECORDER_REQUEST_HASH)
1,931
1,727
class Point: def __init__(self, x, y): self.x = x self.y = y def __lt__(self, other): return self.x < other.x def __str__(self): return "(" + str(self.x) + "," + str(self.y) + ")" def test(): points = [Point(2, 1), Point(1, 1)] points.sort() for p in points: print(p) test()
173
1,800
package com.example.pluginsharelib; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.LinearLayout; import java.io.Serializable; /** * 仅仅用来测试插件程序中Intent是否可以使用宿主程序中的VO * @author cailiming * */ public class SharePOJO implements Serializable { public SharePOJO(String name) { this.name = name; } public String name; }
165
852
#include <functional> #include <cmath> #include <map> #include "DataFormats/Common/interface/RefToBase.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "TrackingTools/GeomPropagators/interface/AnalyticalImpactPointExtrapolator.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "TrackingTools/TransientTrack/interface/TransientTrack.h" #include "TrackingTools/TransientTrack/interface/TransientTrackBuilder.h" #include "TrackingTools/Records/interface/TransientTrackRecord.h" #include "RecoVertex/VertexPrimitives/interface/ConvertToFromReco.h" #include "RecoJets/JetAssociationAlgorithms/interface/JetSignalVertexCompatibilityAlgo.h" using namespace reco; // helper template <typename T> inline bool JetSignalVertexCompatibilityAlgo::RefToBaseLess<T>::operator()(const edm::RefToBase<T> &r1, const edm::RefToBase<T> &r2) const { return r1.id() < r2.id() || (r1.id() == r2.id() && r1.key() < r2.key()); } JetSignalVertexCompatibilityAlgo::JetSignalVertexCompatibilityAlgo(double cut, double temperature) : cut(cut), temperature(temperature) {} JetSignalVertexCompatibilityAlgo::~JetSignalVertexCompatibilityAlgo() {} double JetSignalVertexCompatibilityAlgo::trackVertexCompat(const Vertex &vtx, const TransientTrack &track) { GlobalPoint point1 = RecoVertex::convertPos(vtx.position()); AnalyticalImpactPointExtrapolator extrap(track.field()); TrajectoryStateOnSurface tsos = extrap.extrapolate(track.impactPointState(), point1); if (!tsos.isValid()) return 1.0e6; GlobalPoint point2 = tsos.globalPosition(); ROOT::Math::SVector<double, 3> dir(point1.x() - point2.x(), point1.y() - point2.y(), point1.z() - point2.z()); GlobalError cov = RecoVertex::convertError(vtx.covariance()) + tsos.cartesianError().position(); return ROOT::Math::Mag2(dir) / std::sqrt(ROOT::Math::Similarity(cov.matrix(), dir)); } const TransientTrack &JetSignalVertexCompatibilityAlgo::convert(const TrackBaseRef &track) const { TransientTrackMap::iterator pos = trackMap.lower_bound(track); if (pos != trackMap.end() && pos->first == track) return pos->second; // the castTo will only work with regular, i.e. no GsfTracks // the interface is not intrinsically polymorph... return trackMap.insert(pos, std::make_pair(track, trackBuilder->build(track.castTo<TrackRef>())))->second; } double JetSignalVertexCompatibilityAlgo::activation(double compat) const { return 1. / (std::exp((compat - cut) / temperature) + 1.); } std::vector<float> JetSignalVertexCompatibilityAlgo::compatibility(const reco::VertexCollection &vertices, const reco::TrackRefVector &tracks) const { std::vector<float> result(vertices.size(), 0.); float sum = 0.; for (TrackRefVector::const_iterator track = tracks.begin(); track != tracks.end(); ++track) { const TransientTrack &transientTrack = convert(TrackBaseRef(*track)); for (unsigned int i = 0; i < vertices.size(); i++) { double compat = trackVertexCompat(vertices[i], transientTrack); double contribution = activation(compat) * (*track)->pt(); result[i] += contribution; sum += contribution; } } if (sum < 1.0e-9) { for (unsigned int i = 0; i < result.size(); i++) result[i] = 1.0 / result.size(); } else { for (unsigned int i = 0; i < result.size(); i++) result[i] /= sum; } return result; } void JetSignalVertexCompatibilityAlgo::resetEvent(const TransientTrackBuilder *builder) { trackMap.clear(); trackBuilder = builder; }
1,389
766
<filename>src/libfsm/print/irdot.c /* * Copyright 2018 <NAME> * * See LICENCE for the full copyright terms. */ #include <assert.h> #include <stdlib.h> #include <limits.h> #include <errno.h> #include <stdio.h> #include <ctype.h> #include <print/esc.h> #include <adt/set.h> #include <fsm/fsm.h> #include <fsm/pred.h> #include <fsm/print.h> #include <fsm/walk.h> #include <fsm/options.h> #include "libfsm/internal.h" #include "ir.h" static unsigned int ir_indexof(const struct ir *ir, const struct ir_state *cs) { assert(ir != NULL); assert(cs != NULL); return cs - &ir->states[0]; } static const char * strategy_name(enum ir_strategy strategy) { switch (strategy) { case IR_NONE: return "NONE"; case IR_SAME: return "SAME"; case IR_COMPLETE: return "COMPLETE"; case IR_PARTIAL: return "PARTIAL"; case IR_DOMINANT: return "DOMINANT"; case IR_ERROR: return "ERROR"; case IR_TABLE: return "TABLE"; default: return "?"; } } static void print_endpoint(FILE *f, const struct fsm_options *opt, unsigned char c) { assert(f != NULL); assert(opt != NULL); dot_escputc_html(f, opt, c); } static void print_state(FILE *f, unsigned to, unsigned self) { assert(f != NULL); if (to == self) { fprintf(f, "(self)"); } else { fprintf(f, "S%u", to); } } static void print_errorrows(FILE *f, const struct fsm_options *opt, const struct ir *ir, const struct ir_error *error) { size_t k; assert(f != NULL); assert(opt != NULL); assert(ir != NULL); assert(error != NULL); assert(error->ranges != NULL); (void)ir; /* unused */ for (k = 0; k < error->n; k++) { fprintf(f, "\t\t <TR>"); if (error->ranges[k].start == error->ranges[k].end) { fprintf(f, "<TD COLSPAN='2' ALIGN='LEFT'>"); print_endpoint(f, opt, error->ranges[k].start); fprintf(f, "</TD>"); } else { fprintf(f, "<TD ALIGN='LEFT'>"); print_endpoint(f, opt, error->ranges[k].start); fprintf(f, "</TD>"); fprintf(f, "<TD ALIGN='LEFT'>"); print_endpoint(f, opt, error->ranges[k].end); fprintf(f, "</TD>"); } if (k + 1 < error->n) { fprintf(f, "<TD ALIGN='LEFT'>&#x21B4;</TD>"); } else { fprintf(f, "<TD ALIGN='LEFT'>(error)</TD>"); } fprintf(f, "</TR>\n"); } } static void print_grouprows(FILE *f, const struct fsm_options *opt, const struct ir *ir, unsigned self, const struct ir_group *groups, size_t n) { size_t j, k; assert(f != NULL); assert(opt != NULL); assert(ir != NULL); assert(groups != NULL); (void)ir; /* unused */ for (j = 0; j < n; j++) { assert(groups[j].ranges != NULL); for (k = 0; k < groups[j].n; k++) { fprintf(f, "\t\t <TR>"); if (groups[j].ranges[k].start == groups[j].ranges[k].end) { fprintf(f, "<TD COLSPAN='2' ALIGN='LEFT'>"); print_endpoint(f, opt, groups[j].ranges[k].start); fprintf(f, "</TD>"); } else { fprintf(f, "<TD ALIGN='LEFT'>"); print_endpoint(f, opt, groups[j].ranges[k].start); fprintf(f, "</TD>"); fprintf(f, "<TD ALIGN='LEFT'>"); print_endpoint(f, opt, groups[j].ranges[k].end); fprintf(f, "</TD>"); } if (k + 1 < groups[j].n) { fprintf(f, "<TD ALIGN='LEFT'>&#x21B4;</TD>"); } else { fprintf(f, "<TD ALIGN='LEFT' PORT='group%u'>", (unsigned) j); print_state(f, groups[j].to, self); fprintf(f, "</TD>"); } fprintf(f, "</TR>\n"); } } } static void print_grouplinks(FILE *f, const struct ir *ir, unsigned self, const struct ir_group *groups, size_t n) { unsigned j; assert(f != NULL); assert(ir != NULL); assert(groups != NULL); (void)ir; /* unused */ for (j = 0; j < n; j++) { if (groups[j].to == self) { /* no edge drawn */ } else { fprintf(f, "\tcs%u:group%u -> cs%u;\n", self, j, groups[j].to); } } } static void print_cs(FILE *f, const struct fsm_options *opt, const struct ir *ir, const struct ir_state *cs) { assert(f != NULL); assert(opt != NULL); assert(ir != NULL); assert(cs != NULL); if (cs->isend) { fprintf(f, "\tcs%u [ peripheries = 2 ];\n", ir_indexof(ir, cs)); } fprintf(f, "\tcs%u [ label =\n", ir_indexof(ir, cs)); fprintf(f, "\t\t<<TABLE BORDER='0' CELLPADDING='2' CELLSPACING='0'>\n"); fprintf(f, "\t\t <TR><TD COLSPAN='2' ALIGN='LEFT'>S%u</TD><TD ALIGN='LEFT'>%s</TD></TR>\n", ir_indexof(ir, cs), strategy_name(cs->strategy)); if (cs->example != NULL) { fprintf(f, "\t\t <TR><TD COLSPAN='2' ALIGN='LEFT'>example</TD><TD ALIGN='LEFT'>"); escputs(f, opt, dot_escputc_html, cs->example); fprintf(f, "</TD></TR>\n"); } /* TODO: leaf callback for dot output */ switch (cs->strategy) { case IR_NONE: break; case IR_SAME: fprintf(f, "\t\t <TR><TD COLSPAN='2' ALIGN='LEFT'>to</TD><TD ALIGN='LEFT'>"); print_state(f, cs->u.same.to, ir_indexof(ir, cs)); fprintf(f, "</TD></TR>\n"); break; case IR_COMPLETE: print_grouprows(f, opt, ir, ir_indexof(ir, cs), cs->u.complete.groups, cs->u.complete.n); break; case IR_PARTIAL: print_grouprows(f, opt, ir, ir_indexof(ir, cs), cs->u.partial.groups, cs->u.partial.n); break; case IR_DOMINANT: fprintf(f, "\t\t <TR><TD COLSPAN='2' ALIGN='LEFT'>mode</TD><TD ALIGN='LEFT' PORT='mode'>"); print_state(f, cs->u.dominant.mode, ir_indexof(ir, cs)); fprintf(f, "</TD></TR>\n"); print_grouprows(f, opt, ir, ir_indexof(ir, cs), cs->u.dominant.groups, cs->u.dominant.n); break; case IR_ERROR: fprintf(f, "\t\t <TR><TD COLSPAN='2' ALIGN='LEFT'>mode</TD><TD ALIGN='LEFT' PORT='mode'>"); print_state(f, cs->u.error.mode, ir_indexof(ir, cs)); fprintf(f, "</TD></TR>\n"); print_errorrows(f, opt, ir, &cs->u.error.error); print_grouprows(f, opt, ir, ir_indexof(ir, cs), cs->u.error.groups, cs->u.error.n); break; case IR_TABLE: /* TODO */ break; default: ; } fprintf(f, "\t\t</TABLE>> ];\n"); switch (cs->strategy) { case IR_NONE: break; case IR_SAME: if (cs->u.same.to == ir_indexof(ir, cs)) { /* no edge drawn */ } else { fprintf(f, "\tcs%u -> cs%u;\n", ir_indexof(ir, cs), cs->u.same.to); } break; case IR_COMPLETE: print_grouplinks(f, ir, ir_indexof(ir, cs), cs->u.complete.groups, cs->u.complete.n); break; case IR_PARTIAL: print_grouplinks(f, ir, ir_indexof(ir, cs), cs->u.partial.groups, cs->u.partial.n); break; case IR_DOMINANT: if (cs->u.dominant.mode == ir_indexof(ir, cs)) { /* no edge drawn */ } else { fprintf(f, "\tcs%u:mode -> cs%u;\n", ir_indexof(ir, cs), cs->u.dominant.mode); } print_grouplinks(f, ir, ir_indexof(ir, cs), cs->u.dominant.groups, cs->u.dominant.n); break; case IR_ERROR: if (cs->u.error.mode == ir_indexof(ir, cs)) { /* no edge drawn */ } else { fprintf(f, "\tcs%u:mode -> cs%u;\n", ir_indexof(ir, cs), cs->u.error.mode); } print_grouplinks(f, ir, ir_indexof(ir, cs), cs->u.error.groups, cs->u.error.n); break; case IR_TABLE: break; default: ; } } void fsm_print_ir(FILE *f, const struct fsm *fsm) { struct ir *ir; size_t i; assert(f != NULL); assert(fsm != NULL); ir = make_ir(fsm); if (ir == NULL) { return; } fprintf(f, "digraph G {\n"); fprintf(f, "\tnode [ shape = box, style = rounded ];\n"); fprintf(f, "\trankdir = LR;\n"); fprintf(f, "\troot = start;\n"); fprintf(f, "\n"); fprintf(f, "\tstart [ shape = none, label = \"\" ];\n"); if (ir->n > 0) { fprintf(f, "\tstart -> cs%u;\n", ir->start); fprintf(f, "\n"); } for (i = 0; i < ir->n; i++) { print_cs(f, fsm->opt, ir, &ir->states[i]); } fprintf(f, "}\n"); free_ir(fsm, ir); }
3,476
4,901
<filename>examples/Contacts/src/java/org/contacts/Store.java /* * 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.contacts; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; class Store { private static final String STARTER_CONTACTS = "org/contacts/starter_contacts.txt"; private final Set<Contact> contacts = new HashSet<>(); public Store() { // Use a URL to get the starter contacts to create a dependency on jre_net_lib. URL starterContacts = Store.class.getClassLoader().getResource(STARTER_CONTACTS); try ( InputStream in = starterContacts.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"))) { while (true) { String name = reader.readLine(); if (name == null) { break; } String number = reader.readLine(); if (number == null) { break; } contacts.add(new Contact(name, number)); } } catch (IOException e) { throw new AssertionError("Unexpected IOException reading starter contacts", e); } } public int numContacts() { return contacts.size(); } public void addContact(Contact c) { contacts.add(c); } public List<Contact> getOrderedContacts() { List<Contact> ordered = new ArrayList<>(contacts); Collections.sort(ordered); return ordered; } }
705
942
<reponame>KatsutoshiOtogawa/treefrog-framework #include "tqueue.h" #include <QThreadStorage> namespace { QThreadStorage<THazardPtr> hzptrTls; } THazardPtr &Tf::hazardPtrForQueue() { return hzptrTls.localData(); }
90
469
package com.google.androidbrowserhelper.trusted; import android.content.Context; import android.content.SharedPreferences; import androidx.annotation.Nullable; /** * Manages shared preferences for {@link LauncherActivity} and related infrastructure. */ public class TwaSharedPreferencesManager { private static final String PREFS_NAME = "TrustedWebActivityLauncherPrefs"; private static final String KEY_PROVIDER_PACKAGE = "KEY_PROVIDER_PACKAGE"; private final SharedPreferences mSharedPreferences; public TwaSharedPreferencesManager(Context context) { mSharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); } /** * Writes the package name of the provider in which a TWA was launched the last time. */ public void writeLastLaunchedProviderPackageName(String packageName) { mSharedPreferences.edit().putString(KEY_PROVIDER_PACKAGE, packageName).apply(); } /** * Reads the package name of the provider in which a TWA was launched the last time. */ @Nullable public String readLastLaunchedProviderPackageName() { return mSharedPreferences.getString(KEY_PROVIDER_PACKAGE, null); } }
388
3,799
<filename>lifecycle/lifecycle-compiler/src/test/test-data/TooManyArgs1.java package foo; import static androidx.lifecycle.Lifecycle.Event.ON_ANY; import androidx.lifecycle.Lifecycle.Event; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.OnLifecycleEvent; public class TooManyArgs1 implements LifecycleObserver { @OnLifecycleEvent(ON_ANY) public void onAny(LifecycleOwner provider, Event event, int x) { } }
165
322
#if !defined(ARDUINO) void setup(); void loop(); int main() { setup(); for (;;) loop(); return 0; } #define F(X) X struct FakeSerial { void begin(long baud) { (void) baud; } bool operator!() const { return false; } } Serial; #endif #include "verbosity.ino"
105
8,865
package com.taobao.atlas.dexmerge; /** * Created by xieguo on 15-9-16. */ public class MergeException extends Exception{ /** * Nested exception. */ private transient Throwable throwable; /** * Creates a <tt>LowDiskException</tt> that wraps another exception. * * @param msg The associated message. * @param throwable The nested exception. */ public MergeException(String msg, Throwable throwable) { super(msg, throwable); this.throwable = throwable; } /** * Creates a <tt>LowDiskException</tt> object with the specified message. * * @param msg The message. */ public MergeException(String msg) { super(msg); this.throwable = null; } /** * Returns any nested exceptions included in this exception. * * @return The nested exception; <tt>null</tt> if there is * no nested exception. */ public Throwable getNestedException() { return(throwable); } }
403
2,177
import asyncore import asynchat import socket import re #from cStringIO import StringIO from time import time, sleep import sys import os #asynchat.async_chat.ac_out_buffer_size = 1024*1024 class http_client(asynchat.async_chat): def __init__(self, url, headers=None, start_from=0): asynchat.async_chat.__init__(self) self.args = {'headers': headers, 'start_from': start_from} m = re.match(r'http://([^/:]+)(?::(\d+))?(/.*)?$', url) assert m, 'Invalid url: %s' % url host, port, path = m.groups() port = int(port or 80) path = path or '/' if socket.gethostbyname(host) == '172.16.17.32': # fuck shanghai dian DNS self.log_error('gethostbyname failed') self.size = None return request_headers = {'host': host, 'connection': 'close'} if start_from: request_headers['RANGE'] = 'bytes=%d-' % start_from if headers: request_headers.update(headers) headers = request_headers self.request = 'GET %s HTTP/1.1\r\n%s\r\n\r\n' % (path, '\r\n'.join('%s: %s' % (k, headers[k]) for k in headers)) self.op = 'GET' self.headers = {} # for response headers #self.buffer = StringIO() self.buffer = [] self.buffer_size = 0 self.cache_size = 1024*1024 self.size = None self.completed = 0 self.set_terminator("\r\n\r\n") self.reading_headers = True self.create_socket(socket.AF_INET, socket.SOCK_STREAM) try: self.connect((host, port)) except: self.close() self.log_error('connect_failed') def handle_connect(self): self.start_time = time() self.push(self.request) def handle_close(self): asynchat.async_chat.handle_close(self) self.flush_data() if self.reading_headers: self.log_error('incomplete http response') return self.handle_status_update(self.size, self.completed, force_update=True) self.handle_speed_update(self.completed, self.start_time, force_update=True) if self.size is not None and self.completed < self.size: self.log_error('incomplete download') def handle_connection_error(self): self.handle_error() def handle_error(self): self.close() self.flush_data() error_message = sys.exc_info()[1] self.log_error('there is some error: %s' % error_message) #raise def collect_incoming_data(self, data): if self.reading_headers: #self.buffer.write(data) self.buffer.append(data) self.buffer_size += len(data) return elif self.cache_size: #self.buffer.write(data) self.buffer.append(data) self.buffer_size += len(data) #if self.buffer.tell() > self.cache_size: if self.buffer_size > self.cache_size: #self.handle_data(self.buffer.getvalue()) self.handle_data(''.join(self.buffer)) #self.buffer.truncate(0) #self.buffer.clear() del self.buffer[:] self.buffer_size = 0 else: self.handle_data(data) self.completed += len(data) self.handle_status_update(self.size, self.completed) self.handle_speed_update(self.completed, self.start_time) if self.size == self.completed: self.close() self.flush_data() self.handle_status_update(self.size, self.completed, force_update=True) self.handle_speed_update(self.completed, self.start_time, force_update=True) def handle_data(self, data): print len(data) pass def flush_data(self): #if self.buffer.tell(): if self.buffer_size: #self.handle_data(self.buffer.getvalue()) self.handle_data(''.join(self.buffer)) #self.buffer.truncate(0) del self.buffer[:] self.buffer_size = 0 def parse_headers(self, header): lines = header.split('\r\n') status_line = lines.pop(0) #print status_line protocal, status_code, status_text = re.match(r'^HTTP/([\d.]+) (\d+) (.+)$', status_line).groups() status_code = int(status_code) self.status_code = status_code self.status_text = status_text #headers = dict(h.split(': ', 1) for h in lines) for k, v in (h.split(': ', 1) for h in lines): self.headers[k.lower()] = v if status_code in (200, 206): pass elif status_code == 302: return self.handle_http_relocate(self.headers['location']) else: return self.handle_http_status_error() self.size = self.headers.get('content-length', None) if self.size is not None: self.size = int(self.size) self.handle_http_headers() def found_terminator(self): if self.reading_headers: self.reading_headers = False #self.parse_headers("".join(self.buffer.getvalue())) self.parse_headers("".join(self.buffer)) #self.buffer.truncate(0) del self.buffer[:] self.buffer_size = 0 self.set_terminator(None) else: raise NotImplementedError() def handle_http_headers(self): pass def handle_http_status_error(self): self.close() def handle_http_relocate(self, location): self.close() relocate_times = getattr(self, 'relocate_times', 0) max_relocate_times = getattr(self, 'max_relocate_times', 2) if relocate_times >= max_relocate_times: raise Exception('too many relocate times') new_client = self.__class__(location, **self.args) new_client.relocate_times = relocate_times + 1 new_client.max_relocate_times = max_relocate_times self.next_client = new_client def handle_status_update(self, total, completed, force_update=False): pass def handle_speed_update(self, completed, start_time, force_update=False): pass def log_error(self, message): print 'log_error', message self.error_message = message class ProgressBar: def __init__(self, total=0): self.total = total self.completed = 0 self.start = time() self.speed = 0 self.bar_width = 0 self.displayed = False def update(self): self.displayed = True bar_size = 40 if self.total: percent = int(self.completed*100/self.total) if percent > 100: percent = 100 dots = bar_size * percent / 100 plus = percent - dots / bar_size * 100 if plus > 0.8: plus = '=' elif plus > 0.4: plu = '>' else: plus = '' bar = '=' * dots + plus else: percent = 0 bar = '-' speed = self.speed if speed < 1000: speed = '%sB/s' % int(speed) elif speed < 1000*10: speed = '%.1fK/s' % (speed/1000.0) elif speed < 1000*1000: speed = '%dK/s' % int(speed/1000) elif speed < 1000*1000*100: speed = '%.1fM/s' % (speed/1000.0/1000.0) else: speed = '%dM/s' % int(speed/1000/1000) seconds = time() - self.start if seconds < 10: seconds = '%.1fs' % seconds elif seconds < 60: seconds = '%ds' % int(seconds) elif seconds < 60*60: seconds = '%dm%ds' % (int(seconds/60), int(seconds)%60) elif seconds < 60*60*24: seconds = '%dh%dm%ds' % (int(seconds)/60/60, (int(seconds)/60)%60, int(seconds)%60) else: seconds = int(seconds) days = seconds/60/60/24 seconds -= days*60*60*24 hours = seconds/60/60 seconds -= hours*60*60 minutes = seconds/60 seconds -= minutes*60 seconds = '%dd%dh%dm%ds' % (days, hours, minutes, seconds) completed = ','.join((x[::-1] for x in reversed(re.findall('..?.?', str(self.completed)[::-1])))) bar = '{0:>3}%[{1:<40}] {2:<12} {3:>4} in {4:>6s}'.format(percent, bar, completed, speed, seconds) new_bar_width = len(bar) bar = bar.ljust(self.bar_width) self.bar_width = new_bar_width sys.stdout.write('\r'+bar) sys.stdout.flush() def update_status(self, total, completed): self.total = total self.completed = completed self.update() def update_speed(self, start, speed): self.start = start self.speed = speed self.update() def done(self): if self.displayed: print self.displayed = False def download(url, path, headers=None, resuming=False): class download_client(http_client): def __init__(self, url, headers=headers, start_from=0): self.output = None self.bar = ProgressBar() http_client.__init__(self, url, headers=headers, start_from=start_from) self.start_from = start_from self.last_status_time = time() self.last_speed_time = time() self.last_size = 0 self.path = path def handle_close(self): http_client.handle_close(self) if self.output: self.output.close() self.output = None def handle_http_status_error(self): http_client.handle_http_status_error(self) self.log_error('http status error: %s, %s' % (self.status_code, self.status_text)) def handle_data(self, data): if not self.output: if self.start_from: self.output = open(path, 'ab') else: self.output = open(path, 'wb') self.output.write(data) def handle_status_update(self, total, completed, force_update=False): if total is None: return if time() - self.last_status_time > 1 or force_update: #print '%.02f' % (completed*100.0/total) self.bar.update_status(total+start_from, completed+start_from) self.last_status_time = time() def handle_speed_update(self, completed, start_time, force_update=False): now = time() period = now - self.last_speed_time if period > 1 or force_update: #print '%.02f, %.02f' % ((completed-self.last_size)/period, completed/(now-start_time)) self.bar.update_speed(start_time, (completed-self.last_size)/period) self.last_speed_time = time() self.last_size = completed def log_error(self, message): self.bar.done() http_client.log_error(self, message) def __del__(self): # XXX: sometimes handle_close() is not called, don't know why... #http_client.__del__(self) if self.output: self.output.close() self.output = None max_retry_times = 25 retry_times = 0 start_from = 0 if resuming and os.path.exists(path): start_from = os.path.getsize(path) # TODO: fix status bar for resuming while True: client = download_client(url, start_from=start_from) asyncore.loop() while hasattr(client, 'next_client'): client = client.next_client client.bar.done() if getattr(client, 'error_message', None): retry_times += 1 if retry_times >= max_retry_times: raise Exception(client.error_message) if client.size and client.completed: start_from = os.path.getsize(path) print 'retry', retry_times sleep(retry_times) else: break def main(): url, path = sys.argv[1:] download(url, path) if __name__ == '__main__': main()
4,128
954
/** * Copyright 2003-2006 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 event 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.jdon.controller.model; import java.io.Serializable; import java.util.Iterator; import java.util.NoSuchElementException; /** * All model's primary key(or identifier) collection of every page that will be * displayed it carry the model's primary key collection from persistence lay to * presentation lay . * * restriction : the class type pf your model primary key must be equal to the * data type of primary key of the table. * * * * com.jdon.model.query.PageIteratorSolver supply event factory that create this * class in persistence lay * * the class is stateful. * * * * @version 1.4 */ public class PageIterator implements Iterator, Serializable{ /** * */ private static final long serialVersionUID = -5131890503660837181L; public final static Object[] EMPTY = new Object[0]; /** * the count of all models that fit for query condition */ private int allCount = 0; /** * all database table's primary key colletion in current page the type of * the primary key is the primary key's type in the database table schema. * * default elements's type should be Model's key (identifier) * but we can put Model instances into the elements by seting elementsTypeIsKey to false * */ private Object[] elements = EMPTY; /** * when iterating current page, current record position. */ private int currentIndex = -1; /** * next record (model) */ private Object nextElement = null; /** * previous */ private Object previousElement = null; /** * current page start */ private int startIndex = -1; /** * current page end */ private int endIndex = -1; /** * the line count in event page */ private int count = 0; /** * default elements's type should be Model's key (identifier) * but we can put Model instances into the elements. */ private boolean elementsTypeIsKey = true; /** * Block Construtor * default construtor, this is event block construtor * the keys's lengt is always greater than the page length that will be * displayed. * * @param allCount the all count for all results. * @param keys primary keys collection for every block * @param start the start index in the keys. * @param endIndex the end index in the keys * @param actualCount the count of the primary keys collection. */ public PageIterator(int allCount, Object[] keys, int startIndex, int endIndex, int count) { this.allCount = allCount; this.elements = keys; if (startIndex >= 0) { this.startIndex = startIndex; this.currentIndex = startIndex - 1; } this.endIndex = endIndex; this.count = count; } /** * Page Construtor * this is user customization construtor, * the keys's lengt is always equals the page length that will be displayed. * * @param allCount all count for all results * @param keys primary keys collection for event page defined by client's count value. */ public PageIterator(int allCount, Object[] keys) { this.allCount = allCount; this.elements = keys; this.endIndex = keys.length; } /** * Page Construtor2 * this is for old version * @param allCount all count for all results * @param keys primary keys collection for event page defined by client's count value. * @param startIndex the start index of in the primary keys collection * @param hasNextPage if has next page. */ public PageIterator(int allCount, Object[] keys, int startIndex, boolean hasNextPage) { this(allCount, keys); } /** * Page Construtor * this is for old version * allCount must be enter later by setAllcount * */ public PageIterator(Object[] keys, int startIndex, boolean hasNextPage) { this(0, keys); } /** * empty construtor this construtor can ensure the jsp view page don't * happened nullException! * */ public PageIterator() { } public int getAllCount() { return allCount; } public void setAllCount(int allCount) { this.allCount = allCount; } /** * reset * */ public void reset() { elements = EMPTY; currentIndex = -1; startIndex = -1; endIndex = -1; nextElement = null; previousElement = null; count = 0; allCount = 0; } public void setIndex(int index){ if((index >= startIndex) || (index < endIndex)) currentIndex = index; else System.err.println("PageIterator error: setIndex error: index=" + index + " exceed the 0 or Max length=" + elements.length); } /** * Returns true if there are more elements in the iteration. * * @return true if the iterator has more elements. */ public boolean hasNext() { if (currentIndex == endIndex) { return false; } // Otherwise, see if nextElement is null. If so, try to load the next // element to make sure it exists. if (nextElement == null) { nextElement = getNextElement(); if (nextElement == null) { return false; } } return true; } /** * Returns the next element of primary key collection. * * @return the next element. * @throws NoSuchElementException * if there are no more elements. */ public Object next() throws java.util.NoSuchElementException { Object element = null; if (nextElement != null) { element = nextElement; nextElement = null; } else { element = getNextElement(); if (element == null) { throw new java.util.NoSuchElementException(); } } return element; } /** * Returns true if there are previous elements in the iteration. * * @return */ public boolean hasPrevious() { // If we are at the start of the list there are no previous elements. if (currentIndex == startIndex) { return false; } // Otherwise, see if previous Element is null. If so, try to load the // previous element to make sure it exists. if (previousElement == null) { previousElement = getPreviousElement(); // If getting the previous element failed, return false. if (previousElement == null) { return false; } } return true; } /** * * Returns the previous element of primary key collection. * * @return */ public Object previous() { Object element = null; if (previousElement != null) { element = previousElement; previousElement = null; } else { element = getPreviousElement(); if (element == null) { throw new java.util.NoSuchElementException(); } } return element; } /** * Returns the previous element, or null if there are no more elements to * return. * * @return the previous element. */ private Object getPreviousElement() { Object element = null; while (currentIndex >= startIndex && element == null) { currentIndex--; element = getElement(); } return element; } /** * Not supported for security reasons. */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * Returns the next available element of primary key collection, or null if * there are no more elements to return. * * @return the next available element. */ public Object getNextElement() { Object element = null; while (currentIndex+1 < endIndex && element == null) { currentIndex++; element = getElement(); } return element; } private Object getElement(){ Object element = null; if ((currentIndex >=0 ) && (currentIndex < elements.length)){ element = elements[currentIndex]; }else System.err.println("PageIterator error: currentIndex=" + currentIndex + " exceed the 0 or Max length=" + elements.length); return element; } public int getSize() { return elements.length; } /** * @return Returns the keys. */ public Object[] getKeys() { return elements; } /** * @param keys The keys to set. */ public void setKeys(Object[] keys) { this.elements = keys; } /** * @return Returns the actualCount. */ public int getCount() { return count; } public boolean isElementsTypeIsKey() { return elementsTypeIsKey; } public void setElementsTypeIsKey(boolean elementsTypeIsKey) { this.elementsTypeIsKey = elementsTypeIsKey; } }
4,364
2,443
/* * 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.alipay.sofa.rpc.tracer.sofatracer.log.type; /** * RpcTracerLogEnum * * @author <a href=mailto:<EMAIL>><NAME></a> */ public enum RpcTracerLogEnum { // RPC 日志 RPC_CLIENT_DIGEST("rpc_client_digest_log_name", "rpc-client-digest.log", "rpc_client_digest_rolling"), RPC_SERVER_DIGEST("rpc_server_digest_log_name", "rpc-server-digest.log", "rpc_server_digest_rolling"), RPC_CLIENT_STAT("rpc_client_stat_log_name", "rpc-client-stat.log", "rpc_client_stat_rolling"), RPC_SERVER_STAT("rpc_server_stat_log_name", "rpc-server-stat.log", "rpc_server_stat_rolling"), RPC_2_JVM_DIGEST("rpc_2_jvm_digest_log_name", "rpc-2-jvm-digest.log", "rpc_2_jvm_digest_rolling"), RPC_2_JVM_STAT("rpc_2_jvm_stat_log_name", "rpc-2-jvm-stat.log", "rpc_2_jvm_stat_rolling"); /*** * 获取保留天数 getLogReverseDay 关键字 */ private String logReverseKey; /*** * 默认生成的日志名字 .log 结尾同时作为一个类型 */ private String defaultLogName; /*** * 日志的滚动策略 */ private String rollingKey; RpcTracerLogEnum(String logReverseKey, String defaultLogName, String rollingKey) { this.logReverseKey = logReverseKey; this.defaultLogName = defaultLogName; this.rollingKey = rollingKey; } public String getLogReverseKey() { return logReverseKey; } public String getDefaultLogName() { return defaultLogName; } public String getRollingKey() { return rollingKey; } }
918
1,590
{ "$id": "InstallInstructionScriptInput", "type": "object", "properties": { "packageName": { // The package name. May be skipped if sdk automation don't know the info yet. "type": "string" }, "artifacts": { // List of artifact's path. May be skipped if sdk automation don't know the info yet. "type": "array", "items": { "type": "string" } }, "isPublic": { // Is the download url public accessible. // If it's false, the download command template will be // az rest --resource <client-id> -u "{URL}" --output-file {FILENAME} "type": "boolean" }, "downloadUrlPrefix": { // All the artifacts will be uploaded and user could access the artifact via // a link composed by this prefix and artifact filename. "type": "string" }, "downloadCommandTemplate": { // Download command template. Replace {URL} and {FILENAME} to get the real command. "type": "string" }, "trigger": { "$ref": "TriggerType#" } } }
403
1,068
package forezp.com.douyalibrary.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * sd卡 * Created by b508a on 2015/12/28. */ public class SdCardUtisl { /** * 设备是否读到SD卡 * * @return true 能读到SD卡 false无法读到SD卡 */ public static boolean checkSDCard() { String strStorageState = android.os.Environment.getExternalStorageState(); if (android.os.Environment.MEDIA_MOUNTED.equals(strStorageState)) { return true; } else { return false; } } /** * 显示文件大小信息 * * @param file * @return 文件大小 */ public static String fileSizeMsg(File file) { int subIndex = 0; String fileSize = ""; if (file.isFile()) { long length = file.length(); if (length >= 1073741824) { subIndex = (String.valueOf((float) length / 1073741824)).indexOf("."); fileSize = ((float) length / 1073741824 + "000").substring(0, subIndex + 3) + "GB"; } else if (length >= 1048576) { subIndex = (String.valueOf((float) length / 1048576)).indexOf("."); fileSize = ((float) length / 1048576 + "000").substring(0, subIndex + 3) + "MB"; } else if (length >= 1024) { subIndex = (String.valueOf((float) length / 1024)).indexOf("."); fileSize = ((float) length / 1024 + "000").substring(0, subIndex + 3) + "KB"; } else if (length < 1024) { fileSize = String.valueOf(length) + "B"; } } return fileSize; } /** * 将数据写入指定的文件夹 * * @param data * @param path * @throws Exception */ public static void writeToFile(byte[] data, String path) throws Exception { if (data.length == 0) { return; } File file = new File(path); FileOutputStream fos = null; try { if (!file.exists()) { // file.delete(); file.createNewFile(); } fos = new FileOutputStream(file); fos.write(data); fos.flush(); } catch (Exception e) { throw e; } finally { try { if (fos != null) { fos.close(); } } catch (Exception e2) { } } } /** * 对象序列 * * @param obj * @return */ public static byte[] serialIn(Object obj) { if (obj == null) { return null; } ByteArrayOutputStream baos = null; ObjectOutputStream oos = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(obj); return baos.toByteArray(); } catch (Exception e) { } finally { try { if (baos != null) baos.close(); if (oos != null) oos.close(); } catch (IOException e) { } } return null; } /** * 返序列化 * * @param buf * @return */ public static Object serialOut(byte[] buf) { if (buf == null) { return null; } ByteArrayInputStream baos = null; ObjectInputStream ois = null; try { baos = new ByteArrayInputStream(buf); ois = new ObjectInputStream(baos); Object o = ois.readObject(); if (o != null) { return o; } else { return null; } } catch (Exception e) { return null; } finally { try { if (baos != null) baos.close(); if (ois != null) ois.close(); } catch (IOException e) { } } } }
2,261
2,757
/*++ Copyright (c) 2004, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. Module Name: MemoryAllocationHob.c Abstract: GUIDs for HOBs used in memory allcation --*/ #include "Tiano.h" #include EFI_GUID_DEFINITION(MemoryAllocationHob) EFI_GUID gEfiHobMemeryAllocBspStoreGuid = EFI_HOB_MEMORY_ALLOC_BSP_STORE_GUID; EFI_GUID gEfiHobMemeryAllocStackGuid = EFI_HOB_MEMORY_ALLOC_STACK_GUID; EFI_GUID gEfiHobMemeryAllocModuleGuid = EFI_HOB_MEMORY_ALLOC_MODULE_GUID; EFI_GUID_STRING(&gEfiHobMemeryAllocBspStoreGuid, "BSP Store HOB", "HOB for BSP Store Memory Allocation"); EFI_GUID_STRING(&gEfiHobMemeryAllocStackGuid, "Stack HOB", "HOB for Stack Memory Allocation"); EFI_GUID_STRING(&gEfiHobMemeryAllocModuleGuid, "Memry Allocation Module HOB", "HOB for Memory Allocation Module");
698
474
package org.javacord.core.entity.webhook; import com.fasterxml.jackson.databind.JsonNode; import org.javacord.api.DiscordApi; import org.javacord.api.entity.webhook.IncomingWebhook; import org.javacord.api.entity.webhook.WebhookType; import org.javacord.core.util.rest.RestEndpoint; import org.javacord.core.util.rest.RestMethod; import org.javacord.core.util.rest.RestRequest; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; /** * The implementation of {@link IncomingWebhook}. */ public class IncomingWebhookImpl extends WebhookImpl implements IncomingWebhook { private final String token; /** * Creates a new incoming webhook. * * @param api The discord api instance. * @param data The json data of the webhook. */ public IncomingWebhookImpl(DiscordApi api, JsonNode data) { super(api, data); token = data.get("token").asText(); } /** * Gets the incoming webhooks with a token from a json array. * * @param api The discord api instance. * @param jsonArray The json array of the webhooks. * @return A list of all the incoming webhooks from the array. */ public static List<IncomingWebhook> createIncomingWebhooksFromJsonArray(DiscordApi api, JsonNode jsonArray) { List<IncomingWebhook> webhooks = new ArrayList<>(); for (JsonNode webhookJson : jsonArray) { if (WebhookType.fromValue(webhookJson.get("type").asInt()) == WebhookType.INCOMING && webhookJson.hasNonNull("token")) { // check if it has a token to create IncomingWebhook webhooks.add(new IncomingWebhookImpl(api, webhookJson)); } } return Collections.unmodifiableList(webhooks); } @Override public Optional<IncomingWebhook> asIncomingWebhook() { // important, as this is only possible with incoming webhooks with token return Optional.of(this); } @Override public CompletableFuture<Void> delete(String reason) { return new RestRequest<Void>(getApi(), RestMethod.DELETE, RestEndpoint.WEBHOOK) .setUrlParameters(getIdAsString(), getToken()) .setAuditLogReason(reason) .execute(result -> null); } /** * Gets the secure token of the webhook. * * @return The secure token of the webhook. */ public String getToken() { return token; } }
998
1,831
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/common/configuration/Node.h" #include <folly/dynamic.h> #include "logdevice/common/EpochMetaData.h" #include "logdevice/common/FailureDomainNodeSet.h" #include "logdevice/common/commandline_util_chrono.h" namespace facebook { namespace logdevice { namespace configuration { Node::Node(const Node& other) { name = other.name; address = other.address; gossip_address = other.gossip_address; ssl_address = other.ssl_address; admin_address = other.admin_address; server_to_server_address = other.server_to_server_address; server_thrift_api_address = other.server_thrift_api_address; client_thrift_api_address = other.client_thrift_api_address; generation = other.generation; location = other.location; roles = other.roles; tags = other.tags; metadata_node = other.metadata_node; if (hasRole(NodeRole::SEQUENCER)) { sequencer_attributes = std::make_unique<SequencerNodeAttributes>(*other.sequencer_attributes); } if (hasRole(NodeRole::STORAGE)) { storage_attributes = std::make_unique<StorageNodeAttributes>(*other.storage_attributes); } } Node& Node::operator=(const Node& node) { *this = Node(node); return *this; } /* static */ Node Node::withTestDefaults(node_index_t idx, bool sequencer, bool storage) { Node n; n.name = folly::sformat("server-{}", idx); std::string addr = folly::sformat("127.0.0.{}", idx); n.address = Sockaddr(addr, 4440); n.gossip_address = Sockaddr(addr, 4441); n.admin_address = Sockaddr(addr, 64440); n.server_to_server_address = Sockaddr(addr, 4442); n.server_thrift_api_address = Sockaddr(addr, 7441); n.client_thrift_api_address = Sockaddr(addr, 7440); if (sequencer) { n.addSequencerRole(); } if (storage) { n.addStorageRole(); } return n; } std::string Node::locationStr() const { if (!location.has_value()) { return ""; } return location.value().toString(); } std::string storageStateToString(StorageState v) { switch (v) { case StorageState::READ_WRITE: return "read-write"; case StorageState::READ_ONLY: return "read-only"; case StorageState::DISABLED: return "disabled"; } // Make the server fail if this func is called with a StorageState // that is not included in one of these switch cases. ld_check(false); return ""; } bool storageStateFromString(const std::string& str, StorageState* out) { ld_check(out); if (str == "read-write") { *out = StorageState::READ_WRITE; } else if (str == "read-only") { *out = StorageState::READ_ONLY; } else if (str == "disabled" || str == "none") { *out = StorageState::DISABLED; } else { return false; } return true; } std::string toString(NodeRole& v) { switch (v) { case NodeRole::SEQUENCER: return "sequencer"; case NodeRole::STORAGE: return "storage"; } // Make the server fail if this func is called with a NodeRole // that is not included in one of these switch cases. ld_check(false); return ""; } bool nodeRoleFromString(const std::string& str, NodeRole* out) { ld_check(out); if (str == "sequencer") { *out = NodeRole::SEQUENCER; } else if (str == "storage") { *out = NodeRole::STORAGE; } else { return false; } return true; } Node& Node::setTags(std::unordered_map<std::string, std::string> tags) { this->tags = std::move(tags); return *this; } Node& Node::setLocation(const std::string& location) { this->location = NodeLocation(); this->location.value().fromDomainString(location); return *this; } Node& Node::setIsMetadataNode(bool metadata_node) { this->metadata_node = metadata_node; return *this; } Node& Node::setGeneration(node_gen_t generation) { this->generation = generation; return *this; } Node& Node::setName(std::string name) { this->name = std::move(name); return *this; } Node& Node::setAddress(Sockaddr address) { this->address = std::move(address); return *this; } Node& Node::setGossipAddress(Sockaddr gossip_address) { this->gossip_address = std::move(gossip_address); return *this; } Node& Node::setSSLAddress(Sockaddr ssl_address) { this->ssl_address = std::move(ssl_address); return *this; } }}} // namespace facebook::logdevice::configuration
1,675
984
<reponame>jpisaac/phoenix /* * 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.phoenix.pherf.configuration; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; @XmlRootElement(name = "datamodel") public class DataModel { private String name; private List<Scenario> scenarios; private List<Column> dataMappingColumns; public DataModel() { } public List<Scenario> getScenarios() { return scenarios; } @XmlElementWrapper(name = "datamapping") @XmlElement(name = "column") public void setDataMappingColumns(List<Column> dataMappingColumns) { this.dataMappingColumns = dataMappingColumns; } public List<Column> getDataMappingColumns() { return dataMappingColumns; } @XmlElementWrapper(name = "scenarios") @XmlElement(name = "scenario") public void setScenarios(List<Scenario> scenarios) { this.scenarios = scenarios; } public String getName() { return name; } @XmlAttribute() public void setName(String name) { this.name = name; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); for (Scenario scenario : getScenarios()) { stringBuilder.append("Scenario: " + scenario.getName()); stringBuilder.append("[" + scenario + "]"); } return stringBuilder.toString(); } }
801
320
<gh_stars>100-1000 #ifndef LOCALFILEREFERENCE_HH #define LOCALFILEREFERENCE_HH #include <string> namespace openmsx { class File; class Filename; /** Helper class to use files in APIs other than openmsx::File. * The openMSX File class has support for (g)zipped files (or maybe in the * future files over http, ftp, ...). Sometimes you need to pass a filename * to an API that doesn't support this (for example SDL_LoadWav()). This * class allows to create a temporary local uncompressed version of such * files. Use it like this: * * LocalFileReference file(filename); // can be any filename supported * // by openmsx::File * my_function(file.getFilename()); // my_function() can now work on * // a regular local file * * Note: In the past this functionality was available in the openmsx::File * class. The current implementation of that class always keep an open * file reference to the corresponding file. This gave problems on * (some versions of) windows if the external function tries to open * the file in read-write mode (for example IMG_Load() does this). The * implementation of this class does not keep a reference to the file. */ class LocalFileReference { public: LocalFileReference() = default; explicit LocalFileReference(const Filename& filename); explicit LocalFileReference(Filename&& filename); explicit LocalFileReference(std::string filename); explicit LocalFileReference(File& file); ~LocalFileReference(); // non-copyable, but moveable LocalFileReference(const LocalFileReference&) = delete; LocalFileReference& operator=(const LocalFileReference&) = delete; LocalFileReference(LocalFileReference&&) noexcept; LocalFileReference& operator=(LocalFileReference&&) noexcept; /** Returns path to a local uncompressed version of this file. * This path only remains valid as long as this object is in scope. */ [[nodiscard]] const std::string& getFilename() const; private: void init(File& file); void cleanup(); private: std::string tmpFile; std::string tmpDir; }; } // namespace openmsx #endif
686
668
<gh_stars>100-1000 import json import os import time from traceback import print_exc from subprocess import check_output, STDOUT from vscode_notebook import SETTINGS_PATH, VERSION from .message import print_err, print_info class Settings: """ Settings module """ default_json = { 'public_folders': ['*'], 'private_folders': ['diary'], 'is_encrypted': False, 'version': VERSION, 'do_git_backup': False, 'git_push_interval_minutes': 1440, 'last_git_push': 0, 'note_extensions': ['txt', 'md'] } json = default_json.copy() where_star = 'public' file = SETTINGS_PATH def __init__(self, file=None): if file: self.file = file self.load_file() def load_file(self): """ Loads file as JSON """ try: fp = open(self.file, 'r') data = fp.read() self.json = json.loads(data) fp.close() self.find_star() except Exception as e: # load default settings print_err('JSON Exception occurred: ' + str(e)) def find_star(self): if Settings._find_in_array('*', self.json['private_folders']): self.where_star = 'private' else: # default behavior public self.where_star = 'public' def check_folder_private(self, dirname): st = Settings._find_in_array(dirname, self.json['private_folders']) if st: return True st = Settings._find_in_array(dirname, self.json['public_folders']) if st: return False # star situation return True if self.where_star == 'private' else False def change_encrypted_status(self, status): self.load_file() self.json['is_encrypted'] = status self.save_settings() def get_encrypted_status(self): return self.json['is_encrypted'] def save_settings(self): Settings._write_settings(self.json, self.file) def upgrade_settings(self): if VERSION > self.json['version']: new = self.default_json.copy() new.update(self.json) # only adds new keys self.json = new.copy() self.json['version'] = VERSION # upgrade version again self.save_settings() return True return False def is_git_setup(self): curpath = os.path.dirname(os.path.realpath(__file__)) git_path = curpath.rstrip('/\\') + '/../.git' # print(git_path) return os.path.isdir(git_path) def do_git_push(self): if not self.json['do_git_backup']: return False mins = int(round(time.time()) / 60.0) if mins < (self.json['last_git_push'] + self.json['git_push_interval_minutes']): return False # start backup print_info('Starting git backup') # check remote out = check_output("git remote", shell=True).decode() if not out: print_err('Error with git remote: ' + str(out)) return False if out and out.find('notebookbackup') == -1: print_err('notebookbackup remote not found') return False # push to remote commit_msg = "auto backup " + str(mins) # push only if changes out = check_output("git status -s", stderr=STDOUT, shell=True).decode() if not out: print_info('No changes detected, hence skipping git backup') return # save last push min in advance old_mins = self.json['last_git_push'] self.json['last_git_push'] = mins self.save_settings() # actual push try: print_info('Pushing to remote') out = check_output("git add -A && git commit -m \"{}\" && git push notebookbackup master".format(commit_msg), stderr=STDOUT, shell=True).decode() print_info('GIT LOG:\n\n' + out) except Exception: # revert back print_exc() print_err('git push did not happen') self.json['last_git_push'] = old_mins self.save_settings() @staticmethod def _find_in_array(item, arr): status = False for i in arr: if item == i: status = True break return status @staticmethod def _create_default_file(): Settings._write_settings(Settings.json, Settings.file) @staticmethod def _write_settings(setting, file): data = json.dumps(setting, indent=4, sort_keys=True) fp = open(file, 'w') fp.write(data) fp.close()
1,515
325
<filename>PyFin/POpt/Optimizer.py # -*- coding: utf-8 -*- u""" Created on 2016-4-1 @author: cheng.li """ from enum import Enum from enum import unique import numpy as np import pandas as pd import scipy.optimize as opt from PyFin.POpt.Calculators import calculate_annualized_return from PyFin.POpt.Calculators import calculate_volatility from PyFin.POpt.Calculators import calculate_sharp from PyFin.POpt.Calculators import calculate_sortino def portfolio_returns(weights, nav_table, rebalance): if rebalance: return_table = np.log(nav_table.values[1:, :] / nav_table.values[:-1, :]) returns = np.dot(return_table, weights) / sum(weights) else: final_nav = np.dot(nav_table, weights) / sum(weights) returns = np.log(final_nav[1:] / final_nav[:-1]) return returns def utility_calculator(returns, opt_type, multiplier): # switch between different target types if opt_type == OptTarget.RETURN: return np.exp(calculate_annualized_return(returns, multiplier)) - 1.0 elif opt_type == OptTarget.VOL: return -calculate_volatility(returns, multiplier) elif opt_type == OptTarget.SHARP: return calculate_sharp(returns, multiplier) elif opt_type == OptTarget.SORTINO: return calculate_sortino(returns, multiplier) @unique class OptTarget(str, Enum): RETURN = 'RETURN' VOL = 'VOL' SHARP = 'SHARP' SORTINO = 'SORTINO' def portfolio_optimization(weights, nav_table, opt_type, multiplier, rebalance=False, lb=0., ub=1.): if not rebalance and opt_type == OptTarget.SORTINO: raise ValueError("Portfolio optimization target can't be set as " "maximize sortino ratio") if opt_type == OptTarget.SORTINO or \ opt_type == OptTarget.RETURN or \ opt_type == OptTarget.VOL or \ opt_type == OptTarget.SHARP or \ (rebalance and opt_type == OptTarget.SORTINO): x0 = weights bounds = [(lb, ub) for _ in weights] def eq_cond(x, *args): return sum(x) - 1.0 def func(weights): returns = portfolio_returns(weights, nav_table, rebalance) return -utility_calculator(returns, opt_type, multiplier) out, fx, its, imode, smode = opt.fmin_slsqp(func=func, x0=x0, bounds=bounds, eqcons=[eq_cond], full_output=True, iprint=-1, acc=1e-12, iter=300000) out = {col: weight for col, weight in zip(nav_table.columns, out)} return pd.DataFrame(out, index=['weight']), fx, its, imode, smode
1,439
763
<filename>projects/batfish/src/test/java/org/batfish/dataplane/rib/IsisRibTest.java package org.batfish.dataplane.rib; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import com.google.common.collect.ImmutableList; import java.util.List; import org.batfish.datamodel.Ip; import org.batfish.datamodel.IsisRoute; import org.batfish.datamodel.Prefix; import org.batfish.datamodel.RoutingProtocol; import org.batfish.datamodel.isis.IsisLevel; import org.junit.Test; public class IsisRibTest { @Test public void testRoutePreferenceComparator() { IsisRoute baseRoute = new IsisRoute.Builder() .setAdmin(115) .setArea("0") .setLevel(IsisLevel.LEVEL_1) .setMetric(10) .setNetwork(Prefix.parse("1.1.1.1/32")) .setNextHopIp(Ip.parse("2.2.2.2")) .setOverload(false) .setProtocol(RoutingProtocol.ISIS_L1) .setSystemId("id") .build(); IsisRoute highAdmin = baseRoute.toBuilder().setAdmin(200).build(); IsisRoute level2 = baseRoute.toBuilder().setLevel(IsisLevel.LEVEL_2).build(); IsisRoute overloaded = baseRoute.toBuilder().setOverload(true).build(); IsisRoute highMetric = baseRoute.toBuilder().setMetric(20).build(); List<IsisRoute> increasingPreferenceOrder = ImmutableList.of(highAdmin, level2, overloaded, highMetric, baseRoute); for (int i = 0; i < increasingPreferenceOrder.size(); i++) { for (int j = 0; j < increasingPreferenceOrder.size(); j++) { int comparison = IsisRib.routePreferenceComparator.compare( increasingPreferenceOrder.get(i), increasingPreferenceOrder.get(j)); assertThat(Integer.signum(comparison), equalTo(Integer.signum(i - j))); } } } }
768
348
<reponame>chamberone/Leaflet.PixiOverlay<filename>docs/data/leg-t2/048/04801100.json<gh_stars>100-1000 {"nom":"Montbel","circ":"1ère circonscription","dpt":"Lozère","inscrits":134,"abs":67,"votants":67,"blancs":3,"nuls":3,"exp":61,"res":[{"nuance":"LR","nom":"<NAME>","voix":41},{"nuance":"REM","nom":"<NAME>","voix":20}]}
133
719
<gh_stars>100-1000 package com.googlecode.objectify.impl.translate; import com.google.cloud.datastore.Value; import com.google.cloud.datastore.ValueType; import com.googlecode.objectify.impl.Path; /** * Simplest base class for most value translations. Easy to subclass. * * @author <NAME> <<EMAIL>> */ abstract public class SimpleTranslatorFactory<P, D> extends ValueTranslatorFactory<P, D> { private final ValueType[] datastoreValueTypes; /** */ public SimpleTranslatorFactory(final Class<? extends P> pojoType, final ValueType... datastoreValueTypes) { super(pojoType); this.datastoreValueTypes = datastoreValueTypes; } abstract protected P toPojo(final Value<D> value); abstract protected Value<D> toDatastore(final P value); @Override final protected ValueTranslator<P, D> createValueTranslator(final TypeKey<P> tk, final CreateContext ctx, final Path path) { return new ValueTranslator<P, D>(datastoreValueTypes) { @Override protected P loadValue(final Value<D> value, final LoadContext ctx, final Path path) throws SkipException { return toPojo(value); } @Override protected Value<D> saveValue(final P value, final SaveContext ctx, final Path path) throws SkipException { return toDatastore(value); } }; } }
416
3,859
// // XHAlbumRichTextView.h // MessageDisplayExample // // Created by HUAJIE-1 on 14-5-19. // Copyright (c) 2014年 嗨,我是曾宪华(@xhzengAIB),曾加入YY Inc.担任高级移动开发工程师,拍立秀App联合创始人,热衷于简洁、而富有理性的事物 QQ:543413507 主页:http://zengxianhua.com All rights reserved. // #import <UIKit/UIKit.h> #import <MessageDisplayKit/SETextView.h> #import "XHAlbum.h" typedef void(^CommentButtonDidSelectedBlock)(UIButton *sender); @interface XHAlbumRichTextView : UIView @property (nonatomic, strong) NSFont *font; @property (nonatomic, strong) NSColor *textColor; @property (nonatomic, assign) NSTextAlignment textAlignment; @property (nonatomic, assign) CGFloat lineSpacing; @property (nonatomic, strong) SETextView *richTextView; @property (nonatomic, strong) XHAlbum *displayAlbum; @property (nonatomic, copy) CommentButtonDidSelectedBlock commentButtonDidSelectedCompletion; + (CGFloat)calculateRichTextHeightWithAlbum:(XHAlbum *)currentAlbum; @end
429
910
package com.github.megatronking.svg.sample.extend; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.github.megatronking.svg.sample.R; import com.github.megatronking.svg.support.extend.SVGView; public class SVGViewAlphaSampleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_extend_view_alpha_sample); setTitle(getIntent().getStringExtra("title")); // set in code SVGView view1 = (SVGView) findViewById(R.id.extend_view1); view1.setSvgAlpha(0.5f); SVGView view2 = (SVGView) findViewById(R.id.extend_view2); view2.setSvgAlpha(0.5f); view2.setBackgroundResource(R.drawable.ic_android_red); } }
382
1,694
<filename>header6.6.1/WCPayQryBankList4BindCgiDelegate-Protocol.h<gh_stars>1000+ // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import "WCPayBaseCgiDelegate-Protocol.h" @class QryBankList4BindRes, WCPayECardCgiError, WCPayQryBankList4BindCgi; @protocol WCPayQryBankList4BindCgiDelegate <WCPayBaseCgiDelegate> - (void)qryBankList4BindCgi:(WCPayQryBankList4BindCgi *)arg1 didFailWithError:(WCPayECardCgiError *)arg2; - (void)qryBankList4BindCgi:(WCPayQryBankList4BindCgi *)arg1 didGetResponse:(QryBankList4BindRes *)arg2; @end
274
4,081
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.job; /** * A context containing useful parameters for the job master to use when selecting the worker * that a job should execute on. * * The constructor of this class should always call {@code #super(JobServerContext)} in order to * initialize the other variables in the context - namely the filesystem client, context and * UfsManager */ public class SelectExecutorsContext extends JobServerContext { private final long mJobId; /** * Creates a new instance of {@link SelectExecutorsContext}. * * @param jobId the id of the job * @param jobServerContext the context of the Alluxio job master */ public SelectExecutorsContext(long jobId, JobServerContext jobServerContext) { super(jobServerContext); mJobId = jobId; } /** * @return the job Id */ public long getJobId() { return mJobId; } }
382
484
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.1. You may not use this file * except in compliance with the Zeebe Community License 1.1. */ package io.camunda.zeebe.engine.state.migration; import io.camunda.zeebe.engine.state.ZbColumnFamilies; import io.camunda.zeebe.engine.state.immutable.ZeebeState; import io.camunda.zeebe.engine.state.mutable.MutableZeebeState; /** Reads out the temporary variable column and creates an EventTrigger for reach of them. */ public class TemporaryVariableMigration implements MigrationTask { @Override public String getIdentifier() { return TemporaryVariableMigration.class.getSimpleName(); } @Override public boolean needsToRun(final ZeebeState zeebeState) { return !zeebeState.isEmpty(ZbColumnFamilies.TEMPORARY_VARIABLE_STORE); } @Override public void runMigration(final MutableZeebeState zeebeState) { zeebeState .getMigrationState() .migrateTemporaryVariables( zeebeState.getEventScopeInstanceState(), zeebeState.getElementInstanceState()); } }
396
317
<gh_stars>100-1000 /** * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved. * * You may not modify, use, reproduce, or distribute this software except in * compliance with the terms of the License at: * https://github.com/javaee/tutorial-examples/LICENSE.txt */ package javaeetutorial.batch.webserverlog.items; /* Represents a log line in the filtered log file * Used as output items in the ItemWriter implementation */ public class LogFilteredLine { private final String ipaddr; private final String url; /* Construct from an input log line */ public LogFilteredLine(LogLine ll) { this.ipaddr = ll.getIpaddr(); this.url = ll.getUrl(); } /* Construct from an output log line */ public LogFilteredLine(String line) { String[] result = line.split(", "); this.ipaddr = result[0]; this.url = result[1]; } @Override public String toString() { return ipaddr + ", " + url; } }
357
324
<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. */ package org.jclouds.internal; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.jclouds.reflect.Reflection2.typeToken; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.fail; import java.io.Closeable; import java.io.IOException; import org.jclouds.domain.Credentials; import org.jclouds.lifecycle.Closer; import org.jclouds.providers.ProviderMetadata; import org.jclouds.rest.ApiContext; import org.jclouds.rest.Utils; import org.testng.annotations.Test; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.reflect.TypeToken; /** */ @Test(groups = "unit", testName = "BaseViewTest") public class BaseViewTest { static Supplier<Credentials> creds = Suppliers.ofInstance(new Credentials("identity", null)); private static class Water extends ContextImpl { protected Water() { super("water", createMock(ProviderMetadata.class), creds, createMock(Utils.class), createMock(Closer.class)); } public void close() { } } private static class PeanutButter extends ContextImpl { protected PeanutButter() { super("peanutbutter", createMock(ProviderMetadata.class), creds, createMock(Utils.class), createMock(Closer.class)); } public void close() { } } private static class Wine extends BaseView { protected Wine() { super(new Water(), typeToken(Water.class)); } } private static class DummyApi implements Closeable { @Override public void close() throws IOException { } } public static class DummyView extends BaseView { protected DummyView(ApiContext<DummyApi> context) { super(context, new TypeToken<ApiContext<DummyApi>>() { private static final long serialVersionUID = 1L; }); } } public void testWaterTurnedIntoWine() { Wine wine = new Wine(); assertEquals(wine.getBackendType(), typeToken(Water.class)); assertEquals(wine.unwrap(typeToken(Water.class)).getClass(), Water.class); assertEquals(wine.unwrap().getClass(), Water.class); } public void testPeanutButterDidntTurnIntoWine() { Wine wine = new Wine(); assertNotEquals(wine.getBackendType(), typeToken(PeanutButter.class)); try { wine.unwrap(typeToken(PeanutButter.class)); fail(); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "org.jclouds.internal.BaseViewTest$PeanutButter is not a supertype of backend type org.jclouds.internal.BaseViewTest$Water"); } } public void testCannotUnwrapIfNotApiContext() { Wine wine = new Wine(); try { wine.unwrapApi(DummyApi.class); fail(); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "backend type: org.jclouds.internal.BaseViewTest$Water should be an ApiContext"); } } @SuppressWarnings("unchecked") public void testUnwrapApi() { DummyApi beer = new DummyApi(); ApiContext<DummyApi> beerContext = createMock(ApiContext.class); expect(beerContext.getApi()).andReturn(beer); replay(beerContext); DummyView bar = new DummyView(beerContext); DummyApi result = bar.unwrapApi(DummyApi.class); assertEquals(result, beer); verify(beerContext); } }
1,567
392
<gh_stars>100-1000 /******************************************************************************* * Copyright (c) 2015 * * 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 jsettlers.input.tasks; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import jsettlers.common.movable.ESoldierType; /** * @author codingberlin * @author <NAME> */ public class UpgradeSoldiersGuiTask extends SimpleGuiTask { private ESoldierType soldierType; public UpgradeSoldiersGuiTask() { } public UpgradeSoldiersGuiTask(byte playerId, ESoldierType soldierType) { super(EGuiAction.UPGRADE_SOLDIERS, playerId); this.soldierType = soldierType; } public ESoldierType getSoldierType() { return soldierType; } @Override protected void serializeTask(DataOutputStream dos) throws IOException { super.serializeTask(dos); dos.writeInt(soldierType.ordinal); } @Override protected void deserializeTask(DataInputStream dis) throws IOException { super.deserializeTask(dis); soldierType = ESoldierType.VALUES[dis.readInt()]; } }
594
1,796
package github.nisrulz.sample.junittests; public class CoffeeOrder { private float coffeePrice; private int coffeeCount; private float totalPrice; public CoffeeOrder(float coffeePrice) { coffeeCount = 0; totalPrice = 0; this.coffeePrice = coffeePrice; } public void setCoffeeCount(int count) { if (count >= 0) { this.coffeeCount = count; } calculateTotalPrice(); } public int getCoffeeCount() { return coffeeCount+1; } public void incrementCoffeeCount() { coffeeCount++; calculateTotalPrice(); } public float getTotalPrice() { return totalPrice; } public void decrementCoffeeCount() { if (coffeeCount > 0) { coffeeCount--; calculateTotalPrice(); } } private void calculateTotalPrice() { totalPrice = coffeePrice * coffeeCount; } }
399
8,865
/* * Copyright (C) 2008 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. */ #include <errno.h> #include <fcntl.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <cutils/klog.h> static int klog_fd = -1; static int klog_level = KLOG_DEFAULT_LEVEL; int klog_get_level(void) { return klog_level; } void klog_set_level(int level) { klog_level = level; } void klog_init(void) { if (klog_fd >= 0) return; /* Already initialized */ klog_fd = open("/dev/kmsg", O_WRONLY | O_CLOEXEC); if (klog_fd >= 0) { return; } static const char* name = "/dev/__kmsg__"; if (mknod(name, S_IFCHR | 0600, (1 << 8) | 11) == 0) { klog_fd = open(name, O_WRONLY | O_CLOEXEC); unlink(name); } } #define LOG_BUF_MAX 512 void klog_writev(int level, const struct iovec* iov, int iov_count) { if (level > klog_level) return; if (klog_fd < 0) klog_init(); if (klog_fd < 0) return; TEMP_FAILURE_RETRY(writev(klog_fd, iov, iov_count)); } void klog_write(int level, const char* fmt, ...) { if (level > klog_level) return; char buf[LOG_BUF_MAX]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); buf[LOG_BUF_MAX - 1] = 0; struct iovec iov[1]; iov[0].iov_base = buf; iov[0].iov_len = strlen(buf); klog_writev(level, iov, 1); }
826
471
/* Permission to use this file under wxWindows licence granted by the copyright holder, see eggtrayicon.c for details. */ /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* eggtrayicon.h * Copyright (C) 2002 <NAME> <<EMAIL>> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __EGG_TRAY_ICON_H__ #define __EGG_TRAY_ICON_H__ #include <gtk/gtkplug.h> #include <gdk/gdkx.h> G_BEGIN_DECLS #define EGG_TYPE_TRAY_ICON (egg_tray_icon_get_type ()) #define EGG_TRAY_ICON(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), EGG_TYPE_TRAY_ICON, EggTrayIcon)) #define EGG_TRAY_ICON_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), EGG_TYPE_TRAY_ICON, EggTrayIconClass)) #define EGG_IS_TRAY_ICON(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), EGG_TYPE_TRAY_ICON)) #define EGG_IS_TRAY_ICON_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), EGG_TYPE_TRAY_ICON)) #define EGG_TRAY_ICON_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), EGG_TYPE_TRAY_ICON, EggTrayIconClass)) typedef struct _EggTrayIcon EggTrayIcon; typedef struct _EggTrayIconClass EggTrayIconClass; struct _EggTrayIcon { GtkPlug parent_instance; guint stamp; Atom selection_atom; Atom manager_atom; Atom system_tray_opcode_atom; Window manager_window; }; struct _EggTrayIconClass { GtkPlugClass parent_class; }; GType egg_tray_icon_get_type (void); EggTrayIcon *egg_tray_icon_new_for_screen (GdkScreen *screen, const gchar *name); EggTrayIcon *egg_tray_icon_new (const gchar *name); guint egg_tray_icon_send_message (EggTrayIcon *icon, gint timeout, const char *message, gint len); void egg_tray_icon_cancel_message (EggTrayIcon *icon, guint id); G_END_DECLS #endif /* __EGG_TRAY_ICON_H__ */
1,246
368
// // push_server_handler.h // my_push_server // // Created by luoning on 14-11-11. // Copyright (c) 2014年 luoning. All rights reserved. // #ifndef __my_push_server__push_server_handler__ #define __my_push_server__push_server_handler__ #include <stdio.h> #include "socket/base_handler.hpp" class CPushServerHandler : public CBaseHandler { public: CPushServerHandler() {} virtual ~CPushServerHandler() {} void OnAccept(uint32_t nsockid, S_SOCKET sock, const char* szIP, int32_t nPort); void OnClose(uint32_t nsockid); private: }; #endif /* defined(__my_push_server__push_server_handler__) */
238
644
<gh_stars>100-1000 // // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <CoreGraphics/CoreGraphics.h> NS_ASSUME_NONNULL_BEGIN @interface HTMLFormatter : NSObject /** Builds an attributed string from a string containing html. @param htmlString The html string to use. @param allowedTags The html tags that should be allowed. @param fontSize The default font size to use. Note: It is recommended to include "p" and "body" tags in `allowedTags` as these are often added when parsing. */ - (NSAttributedString * _Nonnull)formatHTML:(NSString * _Nonnull)htmlString withAllowedTags:(NSArray<NSString *> * _Nonnull)allowedTags fontSize:(CGFloat)fontSize; @end NS_ASSUME_NONNULL_END
424
575
<reponame>Ron423c/chromium<filename>components/paint_preview/player/android/java/src/org/chromium/components/paintpreview/player/frame/PlayerFrameBitmapState.java // Copyright 2020 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.components.paintpreview.player.frame; import android.graphics.Bitmap; import android.graphics.Rect; import android.util.Size; import androidx.annotation.VisibleForTesting; import org.chromium.base.Callback; import org.chromium.base.MemoryPressureLevel; import org.chromium.base.UnguessableToken; import org.chromium.base.memory.MemoryPressureMonitor; import org.chromium.base.task.SequencedTaskRunner; import org.chromium.components.paintpreview.player.PlayerCompositorDelegate; import java.util.HashSet; import java.util.Set; /** * Manages the bitmaps shown in the PlayerFrameView at a given scale factor. */ public class PlayerFrameBitmapState { private final UnguessableToken mGuid; /** Dimension of tiles. */ private final Size mTileSize; /** The scale factor of bitmaps. */ private float mScaleFactor; /** Bitmaps that make up the contents. */ private CompressibleBitmap[][] mBitmapMatrix; /** Whether a request for a bitmap tile is pending. */ private BitmapRequestHandler[][] mPendingBitmapRequests; /** * Whether we currently need a bitmap tile. This is used for deleting bitmaps that we don't * need and freeing up memory. */ private boolean[][] mRequiredBitmaps; /** * Whether a bitmap is visible for a given request. */ private boolean[][] mVisibleBitmaps; /** Delegate for accessing native to request bitmaps. */ private final PlayerCompositorDelegate mCompositorDelegate; private final PlayerFrameBitmapStateController mStateController; private Set<Integer> mInitialMissingVisibleBitmaps = new HashSet<>(); private final SequencedTaskRunner mTaskRunner; PlayerFrameBitmapState(UnguessableToken guid, int tileWidth, int tileHeight, float scaleFactor, Size contentSize, PlayerCompositorDelegate compositorDelegate, PlayerFrameBitmapStateController stateController, SequencedTaskRunner taskRunner) { mGuid = guid; mTileSize = new Size(tileWidth, tileHeight); mScaleFactor = scaleFactor; mCompositorDelegate = compositorDelegate; mStateController = stateController; mTaskRunner = taskRunner; // Each tile is as big as the initial view port. Here we determine the number of // columns and rows for the current scale factor. int rows = (int) Math.ceil((contentSize.getHeight() * scaleFactor) / tileHeight); int cols = (int) Math.ceil((contentSize.getWidth() * scaleFactor) / tileWidth); mBitmapMatrix = new CompressibleBitmap[rows][cols]; mPendingBitmapRequests = new BitmapRequestHandler[rows][cols]; mRequiredBitmaps = new boolean[rows][cols]; mVisibleBitmaps = new boolean[rows][cols]; } @VisibleForTesting boolean[][] getRequiredBitmapsForTest() { return mRequiredBitmaps; } CompressibleBitmap[][] getMatrix() { return mBitmapMatrix; } Size getTileDimensions() { return mTileSize; } /** * Locks the state out of further updates. */ void lock() { mRequiredBitmaps = null; mCompositorDelegate.cancelAllBitmapRequests(); } /** * Returns whether this state can be updated. */ boolean isLocked() { return mRequiredBitmaps == null && mBitmapMatrix != null; } /** * Clears state so in-flight requests abort upon return. */ void destroy() { mRequiredBitmaps = null; mPendingBitmapRequests = null; for (int i = 0; i < mBitmapMatrix.length; i++) { for (int j = 0; j < mBitmapMatrix[i].length; j++) { if (mBitmapMatrix[i][j] != null) { mBitmapMatrix[i][j].destroy(); } } } mBitmapMatrix = null; } /** * Whether this bitmap state has loaded all the initial bitmaps. */ boolean isReadyToShow() { return mInitialMissingVisibleBitmaps == null; } /** * Skips waiting for all visible bitmaps before showing. */ void skipWaitingForVisibleBitmaps() { mInitialMissingVisibleBitmaps = null; } /** * Requests bitmaps for tiles that overlap with the provided rect. Also requests bitmaps for * adjacent tiles. * @param viewportRect The rect of the viewport for which bitmaps are needed. */ void requestBitmapForRect(Rect viewportRect) { if (mRequiredBitmaps == null || mBitmapMatrix == null) return; clearBeforeRequest(); final int rowStart = Math.max(0, (int) Math.floor((double) viewportRect.top / mTileSize.getHeight())); final int rowEnd = Math.min(mRequiredBitmaps.length, (int) Math.ceil((double) viewportRect.bottom / mTileSize.getHeight())); final int colStart = Math.max(0, (int) Math.floor((double) viewportRect.left / mTileSize.getWidth())); final int colEnd = Math.min(mRequiredBitmaps[0].length, (int) Math.ceil((double) viewportRect.right / mTileSize.getWidth())); for (int col = colStart; col < colEnd; col++) { for (int row = rowStart; row < rowEnd; row++) { mVisibleBitmaps[row][col] = true; if (requestBitmapForTile(row, col) && mInitialMissingVisibleBitmaps != null) { mInitialMissingVisibleBitmaps.add(row * mBitmapMatrix.length + col); } } } // Only fetch out-of-viewport bitmaps eagerly if not under memory pressure. if (MemoryPressureMonitor.INSTANCE.getLastReportedPressure() < MemoryPressureLevel.MODERATE) { // Request bitmaps for adjacent tiles that are not currently in the view port. The // reason that we do this in a separate loop is to make sure bitmaps for tiles inside // the view port are fetched first. for (int col = colStart; col < colEnd; col++) { for (int row = rowStart; row < rowEnd; row++) { requestBitmapForAdjacentTiles(row, col); } } } cancelUnrequiredPendingRequests(); } /** * Releases and deletes all out-of-viewport tiles. */ void releaseNotVisibleTiles() { if (mBitmapMatrix == null || mVisibleBitmaps == null) return; for (int row = 0; row < mBitmapMatrix.length; row++) { for (int col = 0; col < mBitmapMatrix[row].length; col++) { CompressibleBitmap bitmap = mBitmapMatrix[row][col]; if (!mVisibleBitmaps[row][col] && bitmap != null) { bitmap.destroy(); mBitmapMatrix[row][col] = null; } } } } private void requestBitmapForAdjacentTiles(int row, int col) { if (mBitmapMatrix == null) return; if (row > 0) { requestBitmapForTile(row - 1, col); } if (row < mBitmapMatrix.length - 1) { requestBitmapForTile(row + 1, col); } if (col > 0) { requestBitmapForTile(row, col - 1); } if (col < mBitmapMatrix[row].length - 1) { requestBitmapForTile(row, col + 1); } } private boolean requestBitmapForTile(int row, int col) { if (mRequiredBitmaps == null) return false; mRequiredBitmaps[row][col] = true; if (mPendingBitmapRequests != null && mPendingBitmapRequests[row][col] != null) { mPendingBitmapRequests[row][col].setVisible(mVisibleBitmaps[row][col]); return false; } if (mBitmapMatrix == null || mPendingBitmapRequests == null || mBitmapMatrix[row][col] != null || mPendingBitmapRequests[row][col] != null) { return false; } final int y = row * mTileSize.getHeight(); final int x = col * mTileSize.getWidth(); BitmapRequestHandler bitmapRequestHandler = new BitmapRequestHandler(row, col, mScaleFactor, mVisibleBitmaps[row][col]); mPendingBitmapRequests[row][col] = bitmapRequestHandler; int requestId = mCompositorDelegate.requestBitmap(mGuid, new Rect(x, y, x + mTileSize.getWidth(), y + mTileSize.getHeight()), mScaleFactor, bitmapRequestHandler, bitmapRequestHandler::onError); // It is possible that the request failed immediately, so make sure the request still // exists. if (mPendingBitmapRequests[row][col] != null) { mPendingBitmapRequests[row][col].setRequestId(requestId); } return true; } /** * Remove previously fetched bitmaps that are no longer required according to * {@link #mRequiredBitmaps}. */ private void deleteUnrequiredBitmaps() { if (mBitmapMatrix == null || mRequiredBitmaps == null) return; for (int row = 0; row < mBitmapMatrix.length; row++) { for (int col = 0; col < mBitmapMatrix[row].length; col++) { CompressibleBitmap bitmap = mBitmapMatrix[row][col]; if (!mRequiredBitmaps[row][col] && bitmap != null) { bitmap.destroy(); mBitmapMatrix[row][col] = null; } } } } /** * Marks the bitmap at row and col as being loaded. If all bitmaps that were initially requested * for loading are present then this swaps the currently loading bitmap state to be the visible * bitmap state. * @param row The row of the bitmap that was loaded. * @param col The column of the bitmap that was loaded. */ private void markBitmapReceived(int row, int col) { if (mBitmapMatrix == null) return; if (mInitialMissingVisibleBitmaps != null) { mInitialMissingVisibleBitmaps.remove(row * mBitmapMatrix.length + col); if (!mInitialMissingVisibleBitmaps.isEmpty()) return; mInitialMissingVisibleBitmaps = null; } mStateController.stateUpdated(this); } private void clearBeforeRequest() { if (mVisibleBitmaps == null || mRequiredBitmaps == null) return; assert mVisibleBitmaps.length == mRequiredBitmaps.length; assert (mVisibleBitmaps.length > 0) ? mVisibleBitmaps[0].length == mRequiredBitmaps[0].length : true; for (int row = 0; row < mVisibleBitmaps.length; row++) { for (int col = 0; col < mVisibleBitmaps[row].length; col++) { mVisibleBitmaps[row][col] = false; mRequiredBitmaps[row][col] = false; } } } private void cancelUnrequiredPendingRequests() { if (mPendingBitmapRequests == null || mRequiredBitmaps == null) return; assert mPendingBitmapRequests.length == mRequiredBitmaps.length; assert (mPendingBitmapRequests.length > 0) ? mPendingBitmapRequests[0].length == mRequiredBitmaps[0].length : true; for (int row = 0; row < mPendingBitmapRequests.length; row++) { for (int col = 0; col < mPendingBitmapRequests[row].length; col++) { if (mPendingBitmapRequests[row][col] != null && !mRequiredBitmaps[row][col]) { // If the cancellation failed, the bitmap is being processed already. If this // happens don't delete the request. if (mPendingBitmapRequests[row][col].cancel()) { mPendingBitmapRequests[row][col] = null; } } } } } /** * Used as the callback for bitmap requests from the Paint Preview compositor. */ private class BitmapRequestHandler implements Callback<Bitmap> { int mRequestRow; int mRequestCol; float mRequestScaleFactor; boolean mVisible; int mRequestId; private BitmapRequestHandler( int requestRow, int requestCol, float requestScaleFactor, boolean visible) { mRequestRow = requestRow; mRequestCol = requestCol; mRequestScaleFactor = requestScaleFactor; mVisible = visible; } private void setVisible(boolean visible) { mVisible = visible; } private void setRequestId(int requestId) { mRequestId = requestId; } private boolean cancel() { return mCompositorDelegate.cancelBitmapRequest(mRequestId); } /** * Called when bitmap is successfully composited. * @param result */ @Override public void onResult(Bitmap result) { if (result == null) { onError(); return; } if (mBitmapMatrix == null || mPendingBitmapRequests == null || mRequiredBitmaps == null || mPendingBitmapRequests[mRequestRow][mRequestCol] == null || !mRequiredBitmaps[mRequestRow][mRequestCol]) { result.recycle(); deleteUnrequiredBitmaps(); markBitmapReceived(mRequestRow, mRequestCol); if (mPendingBitmapRequests != null) { mPendingBitmapRequests[mRequestRow][mRequestCol] = null; } return; } mBitmapMatrix[mRequestRow][mRequestCol] = new CompressibleBitmap(result, mTaskRunner, mVisible); deleteUnrequiredBitmaps(); markBitmapReceived(mRequestRow, mRequestCol); mPendingBitmapRequests[mRequestRow][mRequestCol] = null; } /** * Called when there was an error compositing the bitmap. */ public void onError() { markBitmapReceived(mRequestRow, mRequestCol); if (mPendingBitmapRequests == null) return; // TODO(crbug.com/1021590): Handle errors. assert mBitmapMatrix != null; assert mBitmapMatrix[mRequestRow][mRequestCol] == null; assert mPendingBitmapRequests[mRequestRow][mRequestCol] != null; mPendingBitmapRequests[mRequestRow][mRequestCol] = null; } } @VisibleForTesting public boolean checkRequiredBitmapsLoadedForTest() { if (mBitmapMatrix == null || mRequiredBitmaps == null) return false; for (int row = 0; row < mBitmapMatrix.length; row++) { for (int col = 0; col < mBitmapMatrix[0].length; col++) { if (mRequiredBitmaps[row][col] && mBitmapMatrix[row][col] == null) { return false; } } } return true; } }
6,512
1,002
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. // This file was automatically generated. Please do not edit it manually. #include "pch.h" #include "TintEffect.h" #if (defined _WIN32_WINNT_WIN10) && (WINVER >= _WIN32_WINNT_WIN10) namespace ABI { namespace Microsoft { namespace Graphics { namespace Canvas { namespace Effects { TintEffect::TintEffect(ICanvasDevice* device, ID2D1Effect* effect) : CanvasEffect(EffectId(), 2, 1, true, device, effect, static_cast<ITintEffect*>(this)) { if (!SharedDeviceState::GetInstance()->IsID2D1Factory5Supported()) ThrowHR(E_NOTIMPL, Strings::NotSupportedOnThisVersionOfWindows); if (!effect) { // Set default values SetBoxedProperty<float[4]>(D2D1_TINT_PROP_COLOR, Color{ 255, 255, 255, 255 }); SetBoxedProperty<boolean>(D2D1_TINT_PROP_CLAMP_OUTPUT, static_cast<boolean>(false)); } } IMPLEMENT_EFFECT_PROPERTY(TintEffect, Color, float[4], Color, D2D1_TINT_PROP_COLOR) IMPLEMENT_EFFECT_PROPERTY(TintEffect, ClampOutput, boolean, boolean, D2D1_TINT_PROP_CLAMP_OUTPUT) IMPLEMENT_EFFECT_PROPERTY(TintEffect, ColorHdr, float[4], Numerics::Vector4, D2D1_TINT_PROP_COLOR) IMPLEMENT_EFFECT_SOURCE_PROPERTY(TintEffect, Source, 0) IMPLEMENT_EFFECT_PROPERTY_MAPPING(TintEffect, { L"Color", D2D1_TINT_PROP_COLOR, GRAPHICS_EFFECT_PROPERTY_MAPPING_COLOR_TO_VECTOR4 }, { L"ClampOutput", D2D1_TINT_PROP_CLAMP_OUTPUT, GRAPHICS_EFFECT_PROPERTY_MAPPING_DIRECT }, { L"ColorHdr", D2D1_TINT_PROP_COLOR, GRAPHICS_EFFECT_PROPERTY_MAPPING_UNKNOWN }) IFACEMETHODIMP TintEffectFactory::ActivateInstance(IInspectable** instance) { return ExceptionBoundary([&] { auto effect = Make<TintEffect>(); CheckMakeResult(effect); ThrowIfFailed(effect.CopyTo(instance)); }); } IFACEMETHODIMP TintEffectFactory::get_IsSupported(_Out_ boolean* result) { return ExceptionBoundary([&] { CheckInPointer(result); *result = SharedDeviceState::GetInstance()->IsID2D1Factory5Supported(); }); } ActivatableClassWithFactory(TintEffect, TintEffectFactory); }}}}} #endif // _WIN32_WINNT_WIN10
1,166
854
/* * This file is part of Kintinuous. * * Copyright (C) 2015 The National University of Ireland Maynooth and * Massachusetts Institute of Technology * * The use of the code within this file and all code within files that * make up the software that is Kintinuous is permitted for * non-commercial purposes only. The full terms and conditions that * apply to the code within this file are detailed within the LICENSE.txt * file and at <http://www.cs.nuim.ie/research/vision/data/kintinuous/code.php> * unless explicitly stated. By downloading this file you agree to * comply with these terms. * * If you wish to use any of this code for commercial purposes then * please email <EMAIL>. */ #include "LiveLogReader.h" LiveLogReader::LiveLogReader() : lastFrameTime(0), lastGot(-1) { decompressionBuffer = new Bytef[Resolution::get().numPixels() * 2]; deCompImage = cvCreateImage(cvSize(Resolution::get().width(), Resolution::get().height()), IPL_DEPTH_8U, 3); std::cout << "Creating live capture... "; std::cout.flush(); asus = new OpenNI2Interface(Resolution::get().width(), Resolution::get().height()); if(!asus->ok()) { std::cout << "failed!" << std::endl; std::cout << asus->error(); exit(0); } else { std::cout << "success!" << std::endl; std::cout << "Waiting for first frame"; std::cout.flush(); int lastDepth = asus->latestDepthIndex.getValue(); do { usleep(33333); std::cout << "."; std::cout.flush(); lastDepth = asus->latestDepthIndex.getValue(); } while(lastDepth == -1); std::cout << " got it!" << std::endl; } } LiveLogReader::~LiveLogReader() { delete asus; delete [] decompressionBuffer; cvReleaseImage(&deCompImage); } bool LiveLogReader::grabNext(bool & returnVal, int & currentFrame) { int lastDepth = asus->latestDepthIndex.getValue(); if(lastDepth == -1) { return true; } int bufferIndex = lastDepth % 10; if(bufferIndex == lastGot) { return true; } if(lastFrameTime == asus->frameBuffers[bufferIndex].second) { return true; } memcpy(&decompressionBuffer[0], asus->frameBuffers[bufferIndex].first.first, Resolution::get().numPixels() * 2); memcpy(deCompImage->imageData, asus->frameBuffers[bufferIndex].first.second, Resolution::get().numPixels() * 3); lastFrameTime = asus->frameBuffers[bufferIndex].second; timestamp = lastFrameTime; isCompressed = false; decompressedImage = (unsigned char *)deCompImage->imageData; decompressedDepth = (unsigned short *)&decompressionBuffer[0]; compressedImage = 0; compressedDepth = 0; compressedImageSize = Resolution::get().numPixels() * 3; compressedDepthSize = Resolution::get().numPixels() * 2; if(ConfigArgs::get().flipColors) { cv::Mat3b rgb(Resolution::get().rows(), Resolution::get().cols(), (cv::Vec<unsigned char, 3> *)decompressedImage, Resolution::get().width() * 3); cv::cvtColor(rgb, rgb, CV_RGB2BGR); } ThreadDataPack::get().trackerFrame.assignAndNotifyAll(currentFrame); return true; }
1,254
909
<filename>scala/scala-impl/src/org/jetbrains/plugins/scala/testingSupport/test/TestKind.java package org.jetbrains.plugins.scala.testingSupport.test; import org.jetbrains.annotations.NonNls; public enum TestKind { ALL_IN_PACKAGE("All in package"), CLAZZ("Class"), TEST_NAME("Test name"), REGEXP("Regular expression"); // NOTE: this value is only used to persist the enum, do not change it or migrate old settings very carefully private final String value; TestKind(@NonNls String value) { this.value = value; } @Override public String toString() { return value; } public static TestKind parse(String s) { if (ALL_IN_PACKAGE.value.equals(s)) return ALL_IN_PACKAGE; else if (CLAZZ.value.equals(s)) return CLAZZ; else if (TEST_NAME.value.equals(s)) return TEST_NAME; else if (REGEXP.value.equals(s)) return REGEXP; else return null; } }
370
2,661
/* * Copyright 2017 Google Inc. * Copyright 2020 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. */ #ifndef FUSION_GST_BADFEATUREPOLICY_H__ #define FUSION_GST_BADFEATUREPOLICY_H__ #include <vector> #include <khException.h> class SoftErrorPolicy { public: class TooManyException : public khException { public: TooManyException(const std::vector<std::string> &errors) : khException(kh::tr("Too many soft errors")), errors_(errors) { } virtual ~TooManyException(void) throw() { } std::vector<std::string> errors_; }; unsigned int NumSoftErrors(void) const { return error_messages_.size(); } const std::vector<std::string>& Errors(void) const { return error_messages_; } SoftErrorPolicy(unsigned int max_soft_before_fatal); void HandleSoftError(const QString &error); private: const unsigned int max_soft_before_fatal_; std::vector<std::string> error_messages_; }; #endif // FUSION_GST_BADFEATUREPOLICY_H__
484
3,227
// Copyright (c) 2005 INRIA Sophia-Antipolis (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org). //
46
1,014
<filename>Database/Cryptocurrencies/SALT.json<gh_stars>1000+ { "SALT-USD": { "short_name": "SALT USD", "cryptocurrency": "SALT", "currency": "USD", "summary": "SALT (SALT) is a cryptocurrency and operates on the Ethereum platform. SALT has a current supply of 120,000,000 with 80,283,615.21092688 in circulation. The last known price of SALT is 0.69228775 USD and is up 9.52 over the last 24 hours. It is currently trading on 8 active market(s) with $314,067.76 traded over the last 24 hours. More information can be found at https://www.saltlending.com/.", "exchange": "CCC", "market": "ccc_market" } }
255
348
{"nom":"Ladapeyre","circ":"1ère circonscription","dpt":"Creuse","inscrits":265,"abs":145,"votants":120,"blancs":15,"nuls":4,"exp":101,"res":[{"nuance":"REM","nom":"<NAME>","voix":53},{"nuance":"LR","nom":"<NAME>","voix":48}]}
88
374
<filename>Foundation/NSZone/NSZone.h /* Copyright (c) 2006-2008 <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. */ #import <objc/runtime.h> #import <Foundation/NSObjCRuntime.h> @class NSString; typedef void *NSZone; FOUNDATION_EXPORT NSUInteger NSPageSize(void); FOUNDATION_EXPORT NSUInteger NSLogPageSize(void); FOUNDATION_EXPORT NSUInteger NSRoundDownToMultipleOfPageSize(NSUInteger byteCount); FOUNDATION_EXPORT NSUInteger NSRoundUpToMultipleOfPageSize(NSUInteger byteCount); FOUNDATION_EXPORT NSUInteger NSRealMemoryAvailable(void); FOUNDATION_EXPORT void *NSAllocateMemoryPages(NSUInteger byteCount); FOUNDATION_EXPORT void NSDeallocateMemoryPages(void *pointer, NSUInteger byteCount); FOUNDATION_EXPORT void NSCopyMemoryPages(const void *src, void *dst, NSUInteger byteCount); FOUNDATION_EXPORT NSZone *NSCreateZone(NSUInteger startSize, NSUInteger granularity, BOOL canFree); FOUNDATION_EXPORT NSZone *NSDefaultMallocZone(void); FOUNDATION_EXPORT void NSRecycleZone(NSZone *zone); FOUNDATION_EXPORT void NSSetZoneName(NSZone *zone, NSString *name); FOUNDATION_EXPORT NSString *NSZoneName(NSZone *zone); FOUNDATION_EXPORT NSZone *NSZoneFromPointer(void *pointer); FOUNDATION_EXPORT void *NSZoneCalloc(NSZone *zone, NSUInteger numElems, NSUInteger numBytes); FOUNDATION_EXPORT void NSZoneFree(NSZone *zone, void *pointer); FOUNDATION_EXPORT void *NSZoneMalloc(NSZone *zone, NSUInteger size); FOUNDATION_EXPORT void *NSZoneRealloc(NSZone *zone, void *pointer, NSUInteger size); FOUNDATION_EXPORT id NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone); FOUNDATION_EXPORT void NSDeallocateObject(id object); FOUNDATION_EXPORT id NSCopyObject(id object, NSUInteger extraBytes, NSZone *zone); FOUNDATION_EXPORT BOOL NSShouldRetainWithZone(id object, NSZone *zone); FOUNDATION_EXPORT void NSIncrementExtraRefCount(id object); FOUNDATION_EXPORT BOOL NSDecrementExtraRefCountWasZero(id object); FOUNDATION_EXPORT NSUInteger NSExtraRefCount(id object);
891
819
#define DR_WAV_IMPLEMENTATION #include "../../dr_wav.h" #include "../common/dr_common.c" int main(int argc, char** argv) { (void)argc; (void)argv; return 0; }
83
1,337
<reponame>zhoupan/cuba /* * Copyright (c) 2008-2016 Haulmont. * * 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.haulmont.cuba.gui.sys; import com.haulmont.cuba.core.global.UserSessionSource; import com.haulmont.cuba.gui.ComponentsHelper; import com.haulmont.cuba.gui.app.security.role.edit.UiPermissionDescriptor; import com.haulmont.cuba.gui.components.*; import com.haulmont.cuba.gui.components.security.ActionsPermissions; import com.haulmont.cuba.security.entity.Permission; import com.haulmont.cuba.security.entity.PermissionType; import com.haulmont.cuba.security.entity.ScreenComponentPermission; import com.haulmont.cuba.security.global.UserSession; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.inject.Inject; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Utility class used by the framework when it creates frames and windows. Not for use in application code. */ @org.springframework.stereotype.Component(WindowCreationHelper.NAME) public class WindowCreationHelper { public static final String NAME = "cuba_WindowCreationHelper"; private final Pattern INNER_COMPONENT_PATTERN = Pattern.compile("(.+?)\\[(.+?)]"); private final Pattern COMPONENT_ACTION_PATTERN = Pattern.compile("(.+?)<(.+?)>"); private final Logger log = LoggerFactory.getLogger(WindowCreationHelper.class); @Inject protected UserSessionSource sessionSource; private WindowCreationHelper() { } /** * Apply UI permissions to a frame. * * @param container frame */ public void applyUiPermissions(Frame container) { Window window = container instanceof Window ? (Window) container : ComponentsHelper.getWindow(container); if (window == null) { log.warn(String.format("Unable to find window for container %s with id '%s'", container.getClass(), container.getId())); return; } UserSession userSession = sessionSource.getUserSession(); String screenId = window.getId(); Map<String, Integer> uiPermissions = userSession.getPermissionsByType(PermissionType.UI); for (Map.Entry<String, Integer> permissionEntry : uiPermissions.entrySet()) { String target = permissionEntry.getKey(); String targetComponentId = getTargetComponentId(target, screenId); if (targetComponentId != null) { if (targetComponentId.contains("[")) { applyCompositeComponentPermission(window, screenId, permissionEntry.getValue(), targetComponentId); } else if (targetComponentId.contains(">")) { applyComponentActionPermission(window, screenId, permissionEntry.getValue(), targetComponentId); } else { applyComponentPermission(window, screenId, permissionEntry.getValue(), targetComponentId); } } } } @Nullable protected String getTargetComponentId(String target, String screenId) { if (StringUtils.isNotBlank(target)) { int delimiterIndex = target.indexOf(Permission.TARGET_PATH_DELIMETER); if (delimiterIndex >= 0) { String targetScreenId = target.substring(0, delimiterIndex); if (Objects.equals(screenId, targetScreenId)) { return target.substring(delimiterIndex + 1); } } } return null; } protected void applyComponentPermission(Window window, String screenId, Integer permissionValue, String targetComponentId) { Component component = window.getComponent(targetComponentId); if (component != null) { if (ScreenComponentPermission.DENY.getId().equals(permissionValue)) { component.setVisible(false); } else if (ScreenComponentPermission.VIEW.getId().equals(permissionValue)) { if (component instanceof Component.Editable) { ((Component.Editable) component).setEditable(false); } else { component.setEnabled(false); } } } else { log.info(String.format("Couldn't find component %s in window %s", targetComponentId, screenId)); } } protected void applyCompositeComponentPermission(Window window, String screenId, Integer permissionValue, String componentId) { final Matcher matcher = INNER_COMPONENT_PATTERN.matcher(componentId); if (matcher.find()) { final String customComponentId = matcher.group(1); final String subComponentId = matcher.group(2); final Component compositeComponent = window.getComponent(customComponentId); if (compositeComponent != null) { if (compositeComponent instanceof UiPermissionAware) { UiPermissionAware uiPermissionAwareComponent = (UiPermissionAware) compositeComponent; ScreenComponentPermission uiPermissionValue = ScreenComponentPermission.fromId(permissionValue); UiPermissionDescriptor permissionDescriptor; if (subComponentId.contains("<")) { final Matcher actionMatcher = COMPONENT_ACTION_PATTERN.matcher(subComponentId); if (actionMatcher.find()) { final String actionHolderComponentId = actionMatcher.group(1); final String actionId = actionMatcher.group(2); permissionDescriptor = new UiPermissionDescriptor(uiPermissionValue, screenId, actionHolderComponentId, actionId); } else { log.warn(String.format("Incorrect permission definition for component %s in window %s", subComponentId, screenId)); return; } } else { permissionDescriptor = new UiPermissionDescriptor(uiPermissionValue, screenId, subComponentId); } uiPermissionAwareComponent.applyPermission(permissionDescriptor); } } else { log.info(String.format("Couldn't find component %s in window %s", componentId, screenId)); } } } /** * Process permissions for actions in action holder * * @param window Window * @param screenId Screen Id * @param permissionValue Permission value * @param componentId Component Id */ protected void applyComponentActionPermission(Window window, String screenId, Integer permissionValue, String componentId) { Matcher matcher = COMPONENT_ACTION_PATTERN.matcher(componentId); if (matcher.find()) { final String customComponentId = matcher.group(1); final String actionId = matcher.group(2); final Component actionHolderComponent = window.getComponent(customComponentId); if (actionHolderComponent != null) { if (actionHolderComponent instanceof SecuredActionsHolder) { ActionsPermissions permissions = ((SecuredActionsHolder) actionHolderComponent).getActionsPermissions(); if (ScreenComponentPermission.DENY.getId().equals(permissionValue)) { permissions.addHiddenActionPermission(actionId); } else if (ScreenComponentPermission.VIEW.getId().equals(permissionValue)) { permissions.addDisabledActionPermission(actionId); } } else { log.warn(String.format("Couldn't apply permission on action %s for component %s in window %s", actionId, customComponentId, screenId)); } } else { log.info(String.format("Couldn't find component %s in window %s", componentId, screenId)); } } else { log.warn(String.format("Incorrect permission definition for component %s in window %s", componentId, screenId)); } } }
3,806
14,668
<reponame>chromium/chromium // Copyright 2021 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 CHROMECAST_CAST_CORE_RUNTIME_BROWSER_URL_REWRITE_URL_REQUEST_REWRITE_TYPE_CONVERTERS_H_ #define CHROMECAST_CAST_CORE_RUNTIME_BROWSER_URL_REWRITE_URL_REQUEST_REWRITE_TYPE_CONVERTERS_H_ #include "components/url_rewrite/mojom/url_request_rewrite.mojom.h" #include "mojo/public/cpp/bindings/type_converter.h" #include "third_party/cast_core/public/src/proto/v2/url_rewrite.pb.h" namespace mojo { // This conversion is done with a TypeCoverter rather than a typemap because // it is only done one way, from the gRPC type to the Mojo type. This conversion // is only done once, in the browser process. These rules are validated after // they have been converted into Mojo. // In Core Runtime, we have a one-way flow from the untrusted embedder into the // browser process, via a gRPC API. From there, the rules are converted into // Mojo and then validated before being sent to renderer processes. No further // conversion is performed, the Mojo types are used as is to apply the rewrites // on URL requests. // Converter returns |nullptr| if conversion is not possible. template <> struct TypeConverter<url_rewrite::mojom::UrlRequestRewriteRulesPtr, cast::v2::UrlRequestRewriteRules> { static url_rewrite::mojom::UrlRequestRewriteRulesPtr Convert( const cast::v2::UrlRequestRewriteRules& input); }; } // namespace mojo #endif // CHROMECAST_CAST_CORE_RUNTIME_BROWSER_URL_REWRITE_URL_REQUEST_REWRITE_TYPE_CONVERTERS_H_
559
1,059
/* * Copyright 2021 <NAME> <<EMAIL>> * Copyright 2021 <NAME> */ #include <array> #include <numeric> #include "SQLiteParser.h" #include "sqlcommon.h" #include "utilities/CommonOperations.h" #include "ExceptionHandling/BlazingThread.h" #include <arrow/io/file.h> #include <sqlite3.h> #include <parquet/column_writer.h> #include <parquet/file_writer.h> #include "Util/StringUtil.h" namespace ral { namespace io { namespace cudf_io = cudf::io; // TODO percy this is too naive ... improve this later // TEXT types: // - CHARACTER(20) // - VARCHAR(255) // - VARYING CHARACTER(255) // - NCHAR(55) // - NATIVE CHARACTER(70) // - NVARCHAR(100) // - TEXT // - CLOB static const std::array<const char *, 10> mysql_string_types_hints = { "character", "varchar", "char", "varying character", "nchar", "native character", "nvarchar", "text", "clob", "string" // TODO percy ??? }; bool sqlite_is_cudf_string(const std::string & t) { for (auto hint : mysql_string_types_hints) { if (StringUtil::beginsWith(t, std::string{hint})) return true; } return false; } cudf::type_id parse_sqlite_column_type(std::string t) { std::transform( t.cbegin(), t.cend(), t.begin(), [](const std::string::value_type c) { return std::tolower(c); }); if (sqlite_is_cudf_string(t)) return cudf::type_id::STRING; if (t == "tinyint") { return cudf::type_id::INT8; } if (t == "smallint") { return cudf::type_id::INT8; } if (t == "mediumint") { return cudf::type_id::INT16; } if (t == "int") { return cudf::type_id::INT32; } if (t == "integer") { return cudf::type_id::INT32; } if (t == "bigint") { return cudf::type_id::INT64; } if (t == "unsigned big int") { return cudf::type_id::UINT64; } if (t == "int2") { return cudf::type_id::INT16; } if (t == "int8") { return cudf::type_id::INT64; } if (t == "real") { return cudf::type_id::FLOAT32; } if (t == "double") { return cudf::type_id::FLOAT64; } if (t == "double precision") { return cudf::type_id::FLOAT64; } if (t == "float") { return cudf::type_id::FLOAT32; } if (t == "decimal") { return cudf::type_id::FLOAT64; } if (t == "boolean") { return cudf::type_id::UINT8; } if (t == "date") { return cudf::type_id::TIMESTAMP_MILLISECONDS; } if (t == "datetime") { return cudf::type_id::TIMESTAMP_MILLISECONDS; } } sqlite_parser::sqlite_parser() : abstractsql_parser{DataType::SQLITE} {} sqlite_parser::~sqlite_parser() = default; void sqlite_parser::read_sql_loop(void * src, const std::vector<cudf::type_id> & cudf_types, const std::vector<int> & column_indices, std::vector<void *> & host_cols, std::vector<std::vector<cudf::bitmask_type>> & null_masks) { int rowCounter = 0; sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); while (sqlite3_step(stmt) == SQLITE_ROW) { parse_sql( src, column_indices, cudf_types, rowCounter, host_cols, null_masks); ++rowCounter; } } cudf::type_id sqlite_parser::get_cudf_type_id( const std::string & sql_column_type) { return parse_sqlite_column_type(sql_column_type); } // To know about postgresql data type details // see https://www.postgresql.org/docs/current/datatype.html std::uint8_t sqlite_parser::parse_cudf_int8(void * src, std::size_t col, std::size_t row, std::vector<std::int8_t> * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { return 0; } const std::int8_t value = static_cast<std::int8_t>(sqlite3_column_int(stmt, col)); v->at(row) = value; return 1; } std::uint8_t sqlite_parser::parse_cudf_int16(void * src, std::size_t col, std::size_t row, std::vector<std::int16_t> * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { return 0; } const std::int16_t value = static_cast<std::int16_t>(sqlite3_column_int(stmt, col)); v->at(row) = value; return 1; } std::uint8_t sqlite_parser::parse_cudf_int32(void * src, std::size_t col, std::size_t row, std::vector<std::int32_t> * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { return 0; } const std::int32_t value = static_cast<std::int32_t>(sqlite3_column_int(stmt, col)); v->at(row) = value; return 1; } std::uint8_t sqlite_parser::parse_cudf_int64(void * src, std::size_t col, std::size_t row, std::vector<std::int64_t> * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { return 0; } const std::int64_t value = static_cast<std::int64_t>(sqlite3_column_int64(stmt, col)); v->at(row) = value; return 1; } std::uint8_t sqlite_parser::parse_cudf_uint8(void * src, std::size_t col, std::size_t row, std::vector<std::uint8_t> * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { return 0; } const std::uint8_t value = static_cast<std::uint8_t>(sqlite3_column_int(stmt, col)); v->at(row) = value; return 1; } std::uint8_t sqlite_parser::parse_cudf_uint16(void * src, std::size_t col, std::size_t row, std::vector<std::uint16_t> * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { return 0; } const std::uint16_t value = static_cast<std::uint16_t>(sqlite3_column_int(stmt, col)); v->at(row) = value; return 1; } std::uint8_t sqlite_parser::parse_cudf_uint32(void * src, std::size_t col, std::size_t row, std::vector<std::uint32_t> * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { return 0; } const std::uint32_t value = static_cast<std::uint32_t>(sqlite3_column_int(stmt, col)); v->at(row) = value; return 1; } std::uint8_t sqlite_parser::parse_cudf_uint64(void * src, std::size_t col, std::size_t row, std::vector<std::uint64_t> * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { return 0; } const std::uint64_t value = static_cast<std::uint64_t>(sqlite3_column_int64(stmt, col)); v->at(row) = value; return 1; } std::uint8_t sqlite_parser::parse_cudf_float32( void * src, std::size_t col, std::size_t row, std::vector<float> * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { return 0; } const float value = static_cast<float>(sqlite3_column_double(stmt, col)); v->at(row) = value; return 1; } std::uint8_t sqlite_parser::parse_cudf_float64( void * src, std::size_t col, std::size_t row, std::vector<double> * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { return 0; } const double value = sqlite3_column_double(stmt, col); v->at(row) = value; return 1; } std::uint8_t sqlite_parser::parse_cudf_bool8(void * src, std::size_t col, std::size_t row, std::vector<std::int8_t> * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { return 0; } const std::int8_t value = static_cast<std::int8_t>(sqlite3_column_int(stmt, col)); v->at(row) = value; return 1; } std::uint8_t sqlite_parser::parse_cudf_timestamp_days( void * src, std::size_t col, std::size_t row, cudf_string_col * v) { return parse_cudf_string(src, col, row, v); } std::uint8_t sqlite_parser::parse_cudf_timestamp_seconds( void * src, std::size_t col, std::size_t row, cudf_string_col * v) { return parse_cudf_string(src, col, row, v); } std::uint8_t sqlite_parser::parse_cudf_timestamp_milliseconds( void * src, std::size_t col, std::size_t row, cudf_string_col * v) { return parse_cudf_string(src, col, row, v); } std::uint8_t sqlite_parser::parse_cudf_timestamp_microseconds( void * src, std::size_t col, std::size_t row, cudf_string_col * v) { return parse_cudf_string(src, col, row, v); } std::uint8_t sqlite_parser::parse_cudf_timestamp_nanoseconds( void * src, std::size_t col, std::size_t row, cudf_string_col * v) { return parse_cudf_string(src, col, row, v); } std::uint8_t sqlite_parser::parse_cudf_string( void * src, std::size_t col, std::size_t row, cudf_string_col * v) { sqlite3_stmt * stmt = reinterpret_cast<sqlite3_stmt *>(src); std::string column_decltype = sqlite3_column_decltype(stmt, col); if (sqlite3_column_type(stmt, col) == SQLITE_NULL) { v->offsets.push_back(v->offsets.back()); return 0; } else { const unsigned char * text = sqlite3_column_text(stmt, col); const std::string value{reinterpret_cast<const char *>(text)}; v->chars.insert(v->chars.end(), value.cbegin(), value.cend()); v->offsets.push_back(v->offsets.back() + value.length()); return 1; } } } /* namespace io */ } /* namespace ral */
3,960
729
<reponame>probonopd/imagewriter<filename>dependencies/libarchive-3.4.2/libarchive/test/test_read_format_lha_filename_utf16.c /*- * Copyright (c) 2019 <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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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 AUTHOR(S) 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 "test.h" __FBSDID("$FreeBSD"); #include <locale.h> static void test_read_format_lha_filename_UTF16_UTF8(const char *refname) { struct archive *a; struct archive_entry *ae; /* * Read LHA filename in en_US.UTF-8. */ if (NULL == setlocale(LC_ALL, "en_US.UTF-8")) { skipping("en_US.UTF-8 locale not available on this system."); return; } /* * Create a read object only for a test that platform support * a character-set conversion because we can read a character-set * of filenames from the header of an lha archive file and so we * want to test that it works well. */ assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_all(a)); if (ARCHIVE_OK != archive_read_set_options(a, "hdrcharset=CP932")) { assertEqualInt(ARCHIVE_OK, archive_read_free(a)); skipping("This system cannot convert character-set" " from CP932 to UTF-8."); return; } if (ARCHIVE_OK != archive_read_set_options(a, "hdrcharset=UTF-16")) { assertEqualInt(ARCHIVE_OK, archive_read_free(a)); skipping("This system cannot convert character-set" " from UTF-16 to UTF-8."); return; } assertEqualInt(ARCHIVE_OK, archive_read_free(a)); assert((a = archive_read_new()) != NULL); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_filter_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_all(a)); assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, refname, 10240)); /* Note that usual Japanese filenames are tested in other cases */ #if defined(__APPLE__) /* NFD normalization */ /* U:O:A:u:o:a: */ #define UMLAUT_DIRNAME "\x55\xcc\x88\x4f\xcc\x88\x41\xcc\x88\x75\xcc\x88\x6f"\ "\xcc\x88\x61\xcc\x88/" /* a:o:u:A:O:U:.txt */ #define UMLAUT_FNAME "\x61\xcc\x88\x6f\xcc\x88\x75\xcc\x88\x41\xcc\x88"\ "\x4f\xcc\x88\x55\xcc\x88.txt" #else /* NFC normalization */ /* U:O:A:u:o:a: */ #define UMLAUT_DIRNAME "\xc3\x9c\xc3\x96\xc3\x84\xc3\xbc\xc3\xb6\xc3\xa4/" /* a:o:u:A:O:U:.txt */ #define UMLAUT_FNAME "\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x84\xc3\x96\xc3\x9c.txt" #endif /* "Test" in Japanese Katakana */ #define KATAKANA_FNAME "\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88.txt" #define KATAKANA_DIRNAME "\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88/" /* Verify regular file. U:O:A:u:o:a:/a:o:u:A:O:U:.txt */ assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString(UMLAUT_DIRNAME UMLAUT_FNAME, archive_entry_pathname(ae)); assertEqualInt(12, archive_entry_size(ae)); /* Verify directory. U:O:A:u:o:a:/ */ assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString(UMLAUT_DIRNAME, archive_entry_pathname(ae)); assertEqualInt(0, archive_entry_size(ae)); /* Verify regular file. U:O:A:u:o:a:/("Test" in Japanese).txt */ assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString(UMLAUT_DIRNAME KATAKANA_FNAME, archive_entry_pathname(ae)); assertEqualInt(25, archive_entry_size(ae)); /* Verify regular file. ("Test" in Japanese)/a:o:u:A:O:U:.txt */ assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString(KATAKANA_DIRNAME UMLAUT_FNAME, archive_entry_pathname(ae)); assertEqualInt(12, archive_entry_size(ae)); /* Verify directory. ("Test" in Japanese)/ */ assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString(KATAKANA_DIRNAME, archive_entry_pathname(ae)); assertEqualInt(0, archive_entry_size(ae)); /* Verify regular file. a:o:u:A:O:U:.txt */ assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae)); assertEqualString(UMLAUT_FNAME, archive_entry_pathname(ae)); assertEqualInt(12, archive_entry_size(ae)); /* End of archive. */ assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); /* Verify archive format. */ assertEqualIntA(a, ARCHIVE_FILTER_NONE, archive_filter_code(a, 0)); assertEqualIntA(a, ARCHIVE_FORMAT_LHA, archive_format(a)); /* Close the archive. */ assertEqualInt(ARCHIVE_OK, archive_read_close(a)); assertEqualInt(ARCHIVE_OK, archive_read_free(a)); } DEFINE_TEST(test_read_format_lha_filename_UTF16) { /* A sample file was created with Unlha32.dll. */ const char *refname = "test_read_format_lha_filename_utf16.lzh"; extract_reference_file(refname); test_read_format_lha_filename_UTF16_UTF8(refname); }
2,302
2,206
/* * * Copyright (c) 2006-2020, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.tool.core.util; import com.speedment.common.injector.Injector; import com.speedment.runtime.core.component.InfoComponent; import com.speedment.tool.core.brand.Brand; import com.speedment.tool.core.component.UserInterfaceComponent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; /** * * @author <NAME> * @since 2.3.0 */ public final class BrandUtil { private BrandUtil() {} public static void applyBrand(Injector injector, Stage stage) { applyBrand(injector, stage, stage.getScene()); } public static void applyBrand(Injector injector, Stage stage, Scene scene) { applyBrandToStage(injector, stage); final Brand brand = injector.getOrThrow(Brand.class); final InfoComponent info = injector.getOrThrow(InfoComponent.class); apply(brand, info, stage, scene); } public static void applyBrandToStage(Injector injector, Stage stage) { final InfoComponent info = injector.getOrThrow(InfoComponent.class); final Brand brand = injector.getOrThrow(Brand.class); stage.setTitle(info.getTitle()); brand.logoSmall() .map(Image::new) .ifPresent(stage.getIcons()::add); } public static void applyBrandToScene(Injector injector, Scene scene) { final Brand brand = injector.getOrThrow(Brand.class); final UserInterfaceComponent ui = injector.getOrThrow(UserInterfaceComponent.class); final InfoComponent info = injector.getOrThrow(InfoComponent.class); final Stage stage = scene.getWindow() == null ? ui.getStage() : (Stage) scene.getWindow(); apply(brand, info, stage, scene); } private static void apply(Brand brand, InfoComponent info, Stage stage, Scene scene) { if (stage != null) { stage.setTitle(info.getTitle()); } brand.logoSmall() .map(Image::new) .ifPresent(icon -> { if (stage != null) { stage.getIcons().add(icon); } @SuppressWarnings("unchecked") final Stage dialogStage = (Stage) scene.getWindow(); if (dialogStage != null) { dialogStage.getIcons().add(icon); } }); brand.stylesheets().forEachOrdered(scene.getStylesheets()::add); } }
1,286
649
<filename>serenity-model/src/main/java/net/thucydides/core/reports/adaptors/common/FilebasedOutcomeAdaptor.java<gh_stars>100-1000 package net.thucydides.core.reports.adaptors.common; import net.thucydides.core.model.TestOutcome; import net.thucydides.core.reports.adaptors.TestOutcomeAdaptor; import java.io.IOException; import java.util.List; public abstract class FilebasedOutcomeAdaptor implements TestOutcomeAdaptor { @Override public List<TestOutcome> loadOutcomes() throws IOException { throw new UnsupportedOperationException("File based adaptors need to be provided a directory"); } }
204
1,338
/* * Copyright 2013-2014, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #ifndef HEAP_CACHE_H #define HEAP_CACHE_H #include <package/hpkg/DataReader.h> #include <condition_variable.h> #include <util/DoublyLinkedList.h> #include <util/OpenHashTable.h> #include <vm/vm_types.h> using BPackageKit::BHPKG::BAbstractBufferedDataReader; using BPackageKit::BHPKG::BDataReader; class CachedDataReader : public BAbstractBufferedDataReader { public: CachedDataReader(); virtual ~CachedDataReader(); status_t Init(BAbstractBufferedDataReader* reader, off_t size); virtual status_t ReadDataToOutput(off_t offset, size_t size, BDataIO* output); private: class CacheLineLocker : public DoublyLinkedListLinkImpl<CacheLineLocker> { public: CacheLineLocker(CachedDataReader* reader, off_t cacheLineOffset) : fReader(reader), fOffset(cacheLineOffset) { fReader->_LockCacheLine(this); } ~CacheLineLocker() { fReader->_UnlockCacheLine(this); } off_t Offset() const { return fOffset; } CacheLineLocker*& HashNext() { return fHashNext; } DoublyLinkedList<CacheLineLocker>& Queue() { return fQueue; } void Wait(mutex& lock) { fWaitCondition.Init(this, "cached reader line locker"); ConditionVariableEntry waitEntry; fWaitCondition.Add(&waitEntry); mutex_unlock(&lock); waitEntry.Wait(); mutex_lock(&lock); } void WakeUp() { fWaitCondition.NotifyOne(); } private: CachedDataReader* fReader; off_t fOffset; CacheLineLocker* fHashNext; DoublyLinkedList<CacheLineLocker> fQueue; ConditionVariable fWaitCondition; }; friend class CacheLineLocker; struct LockerHashDefinition { typedef off_t KeyType; typedef CacheLineLocker ValueType; size_t HashKey(off_t key) const { return size_t(key / kCacheLineSize); } size_t Hash(const CacheLineLocker* value) const { return HashKey(value->Offset()); } bool Compare(off_t key, const CacheLineLocker* value) const { return value->Offset() == key; } CacheLineLocker*& GetLink(CacheLineLocker* value) const { return value->HashNext(); } }; typedef BOpenHashTable<LockerHashDefinition> LockerTable; struct PagesDataOutput; private: status_t _ReadCacheLine(off_t lineOffset, size_t lineSize, off_t requestOffset, size_t requestLength, BDataIO* output); void _DiscardPages(vm_page** pages, size_t firstPage, size_t pageCount); void _CachePages(vm_page** pages, size_t firstPage, size_t pageCount); status_t _WritePages(vm_page** pages, size_t pagesRelativeOffset, size_t requestLength, BDataIO* output); status_t _ReadIntoPages(vm_page** pages, size_t firstPage, size_t pageCount); void _LockCacheLine(CacheLineLocker* lineLocker); void _UnlockCacheLine(CacheLineLocker* lineLocker); private: static const size_t kCacheLineSize = 64 * 1024; static const size_t kPagesPerCacheLine = kCacheLineSize / B_PAGE_SIZE; private: mutex fLock; BAbstractBufferedDataReader* fReader; VMCache* fCache; LockerTable fCacheLineLockers; }; #endif // HEAP_CACHE_H
1,519
352
<reponame>swaroop0707/TinyWeb /* *Author:GeneralSandman *Code:https://github.com/GeneralSandman/TinyWeb *E-mail:<EMAIL> *Web:www.dissigil.cn */ /*---Configer Class--- * **************************************** * */ #ifndef CONFIGER_H #define CONFIGER_H #include <algorithm> #include <iostream> #include <list> #include <string> #include <unordered_map> #include <vector> class BasicConfig { public: int worker; std::string pid; bool sendfile; std::string mimetype; bool chunked; bool gzip; int gzip_level; int gzip_buffers_4k; int gzip_min_len; std::vector<int> gzip_http_version; std::vector<std::string> gzip_mime_type; }; class FcgiConfig { public: bool enable; bool keep_connect; unsigned int connect_timeout; unsigned int send_timeout; unsigned int read_timeout; }; typedef struct errorpage { unsigned int code; std::string path; std::string file; } errorpage; typedef struct fcgi_t { std::string pattern; std::string path; std::vector<std::string> indexpage; std::string listen; } fcgi_t; class ProxyConfig { public: std::string name; std::string server_address; bool enable; bool keep_connect; unsigned int connect_timeout; unsigned int send_timeout; unsigned int read_timeout; unsigned int buffers_4k; std::vector<std::pair<std::string, std::string>> set_header; }; class CacheConfig { public: std::string name; std::string server_address; std::string path; std::vector<int> file_grade; unsigned long long space_max_size; unsigned long long expires; }; class ServerConfig { public: int listen; std::string www; std::vector<std::string> servername; std::vector<std::string> indexpage; std::vector<errorpage> errorpages; std::vector<fcgi_t> fcgis; }; class LogConfig { public: std::string level; std::string path; std::string debugfile; std::string infofile; std::string warnfile; std::string errorfile; std::string fatalfile; }; void setConfigerFile(const std::string& file); int loadConfig(bool debug); class Configer { private: static std::string m_nFile; BasicConfig basicConf; FcgiConfig fcgiConf; std::vector<ProxyConfig> proxyConf; std::vector<CacheConfig> cacheConf; std::vector<ServerConfig> serverConf; LogConfig logConf; std::unordered_map<std::string, std::string> mimeTypes; Configer(); Configer(const Configer& c) {} bool haveProxyName(const ProxyConfig& conf, const std::string& proxyname) { return (conf.name == proxyname); } bool haveCacheName(const CacheConfig& conf, const std::string& cachename) { return (conf.name == cachename); // auto it = find(std::begin(conf.name), // std::end(conf.name), // cachename); // return (it != std::end(conf.name)); } bool haveServerName(const ServerConfig& conf, const std::string& servername) { auto it = find(std::begin(conf.servername), std::end(conf.servername), servername); return (it != std::end(conf.servername)); } public: static Configer& getConfigerInstance() { static Configer ConfigerInstance; return ConfigerInstance; } void setConfigerFile(const std::string& file); int checkConfigerFile(const std::string& file); int loadConfig(bool debug = false); const BasicConfig& getBasicConfig(); const FcgiConfig& getFcgiConfig(); const ProxyConfig& getProxyConfig(const std::string& proxyname); const std::vector<ProxyConfig>& getProxyConfig(); const CacheConfig& getCacheConfig(const std::string& cachename); const ServerConfig& getServerConfig(const std::string& servername); const std::vector<ServerConfig>& getServerConfig(); const LogConfig& getLogConfig(); std::string getMimeType(const std::string& file_type); ~Configer(); }; #endif //
1,520
777
<filename>net/base/network_interfaces_posix.h<gh_stars>100-1000 // Copyright (c) 2014 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 NET_BASE_NETWORK_INTERFACES_POSIX_H_ #define NET_BASE_NETWORK_INTERFACES_POSIX_H_ // This file is only used to expose some of the internals of // network_interfaces_posix.cc to network_interfaces_linux.cc and network_interfaces_mac.cc. #include <string> struct sockaddr; namespace net { namespace internal { #if !defined(OS_NACL) bool ShouldIgnoreInterface(const std::string& name, int policy); bool IsLoopbackOrUnspecifiedAddress(const sockaddr* addr); #endif // !OS_NACL } // namespace internal } // namespace net #endif // NET_BASE_NETWORK_INTERFACES_POSIX_H_
277
3,301
package com.alibaba.alink.operator.common.distance; import com.alibaba.alink.common.linalg.*; public class InnerProduct extends FastDistance { @Override public double calc(double[] array1, double[] array2) { return BLAS.dot(array1, array2); } @Override public double calc(Vector vec1, Vector vec2) { return MatVecOp.dot(vec1, vec2); } @Override public void updateLabel(FastDistanceData data) { } @Override double calc(FastDistanceVectorData left, FastDistanceVectorData right) { return MatVecOp.dot(left.vector, right.vector); } @Override void calc(FastDistanceVectorData leftVector, FastDistanceMatrixData rightVectors, double[] res) { CosineDistance.baseCalc(leftVector, rightVectors, res, 0, 1); } @Override void calc(FastDistanceMatrixData left, FastDistanceMatrixData right, DenseMatrix res) { CosineDistance.baseCalc(left, right, res, 0, 1); } @Override void calc(FastDistanceVectorData left, FastDistanceSparseData right, double[] res) { CosineDistance.baseCalc(left, right, res, 0, x -> x); } @Override void calc(FastDistanceSparseData left, FastDistanceSparseData right, double[] res) { CosineDistance.baseCalc(left, right, res, 0, x -> x); } }
488
3,631
<filename>drools/drools-core/src/main/java/org/drools/core/impl/StatefulSessionPool.java /* * Copyright 2018 JBoss 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.drools.core.impl; import java.util.function.Supplier; import org.drools.core.util.ScalablePool; public class StatefulSessionPool { private final KnowledgeBaseImpl kbase; private final ScalablePool<StatefulKnowledgeSessionImpl> pool; public StatefulSessionPool( KnowledgeBaseImpl kbase, int initialSize, Supplier<StatefulKnowledgeSessionImpl> supplier ) { this.kbase = kbase; this.pool = new ScalablePool<>(initialSize, supplier, s -> s.reset(), s -> s.fromPool(null).dispose()); } public KnowledgeBaseImpl getKieBase() { return kbase; } public StatefulKnowledgeSessionImpl get() { return pool.get().fromPool( this ); } public void release(StatefulKnowledgeSessionImpl session) { pool.release( session ); } public void shutdown() { pool.shutdown(); } }
496
3,755
<filename>frappe/patches/v13_0/remove_web_view.py import frappe def execute(): frappe.delete_doc_if_exists("DocType", "Web View") frappe.delete_doc_if_exists("DocType", "Web View Component") frappe.delete_doc_if_exists("DocType", "CSS Class")
98
463
<reponame>zanachka/parsedatetime # -*- coding: utf-8 -*- """ Test parsing of units """ import sys import time import datetime import unittest import parsedatetime as pdt from parsedatetime.context import pdtContext from . import utils class test(unittest.TestCase): @utils.assertEqualWithComparator def assertExpectedResult(self, result, check, **kwargs): return utils.compareResultByTimeTuplesAndFlags(result, check, **kwargs) def setUp(self): self.cal = pdt.Calendar() (self.yr, self.mth, self.dy, self.hr, self.mn, self.sec, self.wd, self.yd, self.isdst) = time.localtime() def testMinutes(self): s = datetime.datetime.now() t = s + datetime.timedelta(minutes=1) h = s - datetime.timedelta(minutes=1) start = s.timetuple() target = t.timetuple() history = h.timetuple() self.assertExpectedResult( self.cal.parse('1 minutes', start), (target, pdtContext(pdtContext.ACU_MIN))) self.assertExpectedResult( self.cal.parse('1 minute', start), (target, pdtContext(pdtContext.ACU_MIN))) self.assertExpectedResult( self.cal.parse('1 min', start), (target, pdtContext(pdtContext.ACU_MIN))) self.assertExpectedResult( self.cal.parse('1min', start), (target, pdtContext(pdtContext.ACU_MIN))) self.assertExpectedResult( self.cal.parse('1 m', start), (target, pdtContext(pdtContext.ACU_MIN))) self.assertExpectedResult( self.cal.parse('1m', start), (target, pdtContext(pdtContext.ACU_MIN))) self.assertExpectedResult( self.cal.parse('1 minutes ago', start), (history, pdtContext(pdtContext.ACU_MIN))) self.assertExpectedResult( self.cal.parse('1 minute ago', start), (history, pdtContext(pdtContext.ACU_MIN))) def testHours(self): s = datetime.datetime.now() t = s + datetime.timedelta(hours=1) h = s - datetime.timedelta(hours=1) start = s.timetuple() target = t.timetuple() history = h.timetuple() self.assertExpectedResult( self.cal.parse('1 hour', start), (target, pdtContext(pdtContext.ACU_HOUR))) self.assertExpectedResult( self.cal.parse('1 hours', start), (target, pdtContext(pdtContext.ACU_HOUR))) self.assertExpectedResult( self.cal.parse('1 hr', start), (target, pdtContext(pdtContext.ACU_HOUR))) self.assertExpectedResult( self.cal.parse('1 hour ago', start), (history, pdtContext(pdtContext.ACU_HOUR))) self.assertExpectedResult( self.cal.parse('1 hours ago', start), (history, pdtContext(pdtContext.ACU_HOUR))) def testDays(self): s = datetime.datetime.now() t = s + datetime.timedelta(days=1) start = s.timetuple() target = t.timetuple() self.assertExpectedResult( self.cal.parse('1 day', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('1 days', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('1days', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('1 dy', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('1 d', start), (target, pdtContext(pdtContext.ACU_DAY))) def testNegativeDays(self): s = datetime.datetime.now() t = s + datetime.timedelta(days=-1) start = s.timetuple() target = t.timetuple() self.assertExpectedResult( self.cal.parse('-1 day', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('-1 days', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('-1days', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('-1 dy', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('-1 d', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('- 1 day', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('- 1 days', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('- 1days', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('- 1 dy', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('- 1 d', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('1 day ago', start), (target, pdtContext(pdtContext.ACU_DAY))) self.assertExpectedResult( self.cal.parse('1 days ago', start), (target, pdtContext(pdtContext.ACU_DAY))) def testWeeks(self): s = datetime.datetime.now() t = s + datetime.timedelta(weeks=1) h = s - datetime.timedelta(weeks=1) start = s.timetuple() target = t.timetuple() history = h.timetuple() self.assertExpectedResult( self.cal.parse('1 week', start), (target, pdtContext(pdtContext.ACU_WEEK))) self.assertExpectedResult( self.cal.parse('1week', start), (target, pdtContext(pdtContext.ACU_WEEK))) self.assertExpectedResult( self.cal.parse('1 weeks', start), (target, pdtContext(pdtContext.ACU_WEEK))) self.assertExpectedResult( self.cal.parse('1 wk', start), (target, pdtContext(pdtContext.ACU_WEEK))) self.assertExpectedResult( self.cal.parse('1 w', start), (target, pdtContext(pdtContext.ACU_WEEK))) self.assertExpectedResult( self.cal.parse('1w', start), (target, pdtContext(pdtContext.ACU_WEEK))) self.assertExpectedResult( self.cal.parse('1 week ago', start), (history, pdtContext(pdtContext.ACU_WEEK))) self.assertExpectedResult( self.cal.parse('1 weeks ago', start), (history, pdtContext(pdtContext.ACU_WEEK))) def testMonths(self): s = datetime.datetime.now() t = self.cal.inc(s, month=1) h = self.cal.inc(s, month=-1) start = s.timetuple() target = t.timetuple() history = h.timetuple() self.assertExpectedResult( self.cal.parse('1 month', start), (target, pdtContext(pdtContext.ACU_MONTH))) self.assertExpectedResult( self.cal.parse('1 months', start), (target, pdtContext(pdtContext.ACU_MONTH))) self.assertExpectedResult( self.cal.parse('1month', start), (target, pdtContext(pdtContext.ACU_MONTH))) self.assertExpectedResult( self.cal.parse('1 month ago', start), (history, pdtContext(pdtContext.ACU_MONTH))) self.assertExpectedResult( self.cal.parse('1 months ago', start), (history, pdtContext(pdtContext.ACU_MONTH))) def testYears(self): s = datetime.datetime.now() t = self.cal.inc(s, year=1) start = s.timetuple() target = t.timetuple() self.assertExpectedResult( self.cal.parse('1 year', start), (target, pdtContext(pdtContext.ACU_YEAR))) self.assertExpectedResult( self.cal.parse('1 years', start), (target, pdtContext(pdtContext.ACU_YEAR))) self.assertExpectedResult( self.cal.parse('1 yr', start), (target, pdtContext(pdtContext.ACU_YEAR))) self.assertExpectedResult( self.cal.parse('1 y', start), (target, pdtContext(pdtContext.ACU_YEAR))) self.assertExpectedResult( self.cal.parse('1y', start), (target, pdtContext(pdtContext.ACU_YEAR))) if __name__ == "__main__": unittest.main()
4,220
517
<reponame>supakiad/wro4j package ro.isdc.wro.cache.factory; import javax.servlet.http.HttpServletRequest; import ro.isdc.wro.cache.CacheKey; import ro.isdc.wro.util.AbstractDecorator; /** * Decorator for {@link CacheKeyFactory} object. * * @author <NAME> * @since 1.6.0 * @created 19 Oct 2012 */ public class CacheKeyFactoryDecorator extends AbstractDecorator<CacheKeyFactory> implements CacheKeyFactory { public CacheKeyFactoryDecorator(final CacheKeyFactory decorated) { super(decorated); } /** * {@inheritDoc} */ public CacheKey create(final HttpServletRequest request) { return getDecoratedObject().create(request); } }
240
2,199
<gh_stars>1000+ /******************************************************************************* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. ******************************************************************************/ package the8472.utils.io; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.function.Consumer; public class FileIO { public static void writeAndAtomicMove(Path targetName, Consumer<PrintWriter> write) throws IOException { Path tempFile = Files.createTempFile(targetName.getParent(), targetName.getFileName().toString(), ".tmp"); try (PrintWriter statusWriter = new PrintWriter(Files.newBufferedWriter(tempFile, StandardCharsets.UTF_8))) { write.accept(statusWriter); statusWriter.close(); Files.move(tempFile, targetName, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } } }
345
3,040
<filename>novel-front/src/main/java/xyz/zinglizingli/common/utils/ExcutorUtils.java package xyz.zinglizingli.common.utils; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author XXY */ public class ExcutorUtils { private static ExecutorService fixedThreadPool; private static ExecutorService cachedThreadPool ; static{ fixedThreadPool = Executors.newFixedThreadPool(5); cachedThreadPool = Executors.newCachedThreadPool(); } public static void excuteFixedTask(Runnable task){ fixedThreadPool.execute(task); } public static void excuteCachedTask(Runnable task){ cachedThreadPool.execute(task); } }
256
1,021
<reponame>tolgaeren/FrameCapturer #pragma once struct fcVPXEncoderConfig { int width; int height; int target_framerate; fcBitrateMode bitrate_mode; int target_bitrate; }; fcIWebMVideoEncoder* fcCreateVPXVP8Encoder(const fcVPXEncoderConfig& conf); fcIWebMVideoEncoder* fcCreateVPXVP9Encoder(const fcVPXEncoderConfig& conf); fcIWebMVideoEncoder* fcCreateVPXVP9LossLessEncoder(const fcVPXEncoderConfig& conf);
192
471
import re from abc import abstractmethod, ABCMeta import sys from django.utils.html import format_html, escape from django.utils.safestring import mark_safe from memoized import memoized url_re = re.compile( r"""(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""" ) def _wrap_url(url): return format_html('<a href="{url}">{url}</a>', url=url) def _get_url_segments(text): for chunk in url_re.split(text): # The match pattern contains multiple capture groups; # Because only one will be populated, we need to ignore the Nones if not chunk: continue elif url_re.match(chunk): yield _wrap_url(chunk) else: yield escape(chunk) def mark_up_urls(text): """ Add HTML markup to any links within the text. I.e. 'Go to http://www.google.com' becomes 'Go to <a href="http://www.google.com">http://www.google.com</a>'. """ return mark_safe(''.join(_get_url_segments(text))) # nosec: all segments are sanitized def _shell_color_template(color_code): def inner(text): return "\033[%sm%s\033[0m" % (color_code, text) return inner shell_red = _shell_color_template('31') shell_green = _shell_color_template('32') class SimpleTableWriter(object): """Helper class for writing tables to the console """ def __init__(self, output=None, row_formatter=None): self.output = output or sys.stdout self.row_formatter = row_formatter or CSVRowFormatter() def write_table(self, headers, rows): self.write_headers(headers) self.write_rows(rows) def write_headers(self, headers): self.output.write(self.row_formatter.format_headers(headers)) def write_rows(self, rows): for row in rows: self.output.write(self.row_formatter.format_row(row)) class RowFormatter(metaclass=ABCMeta): @abstractmethod def get_template(self, num_cols): raise NotImplementedError def format_headers(self, headers): return self.format_row(headers) def format_row(self, row): return self.get_template(len(row)).format(*row) class CSVRowFormatter(RowFormatter): """Format rows as CSV""" def get_template(self, num_cols): return ','.join(['{}'] * num_cols) class TableRowFormatter(RowFormatter): """Format rows as a table with optional row highlighting""" def __init__(self, col_widths=None, row_color_getter=None): self.col_widths = col_widths self.row_color_getter = row_color_getter @memoized def get_template(self, num_cols): if self.col_widths: assert len(self.col_widths) == num_cols else: self.col_widths = [20] * num_cols return ' | '.join(['{{:<{}}}'.format(width) for width in self.col_widths]) def format_headers(self, headers): template = self.get_template(len(headers)) return '{}\n{}'.format( template.format(*headers), template.format(*['-' * width for width in self.col_widths]), ) def format_row(self, row): template = self.get_template(len(row)) color = self.row_color_getter(row) if self.row_color_getter else None return self._highlight(color, template).format(*row) def _highlight(self, color, template): if not color: return template if color == 'red': return shell_red(template) if color == 'green': return shell_green(template) raise Exception('Unknown color: {}'.format(color))
1,615
1,270
/* * Copyright 2013 <NAME> * Copyright 2014 <NAME> (@f2prateek) * * 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 dart.common; /** Base class of code generators. They generate java code. */ public abstract class BaseGenerator { /** * Create all Java code * * @return the javacode as string. */ public abstract String brewJava(); /** @return the Fully Qualified Class Name of the generated code. */ public abstract String getFqcn(); }
270
543
<reponame>CoenRijsdijk/Bytecoder /* * Copyright (c) 2000, 2001, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.awt.image; import java.awt.image.DataBuffer; import sun.java2d.SurfaceData; import java.awt.Rectangle; /** * This class extends {@code DataBuffer} and allows access to * native data via the DataBuffer methods. Note that, unlike other * DataBuffer classes, the data is not stored in this class but * has been created and stored elsewhere and this class is used * merely to access that data. Note also that this class subclasses * from DataBuffer and not from any of the standard subclasses * (e.g., DataBufferInt); those subclasses allow the user to * get a pointer to the data and manipulate it directly. That * operation may not be possible or wise with native data. * One important use of this DataBuffer class is in accessing the * data stored in an offscreen vram surface, such as that created * by the createVolatileImage() method. */ public class DataBufferNative extends DataBuffer { protected SurfaceData surfaceData; protected int width; /** * Constructor. The constructor of this object requires a * SurfaceData object; that surfaceData object will be used * to access the actual pixel data in native code. */ public DataBufferNative(SurfaceData sData, int type, int width, int height) { super(type, width*height); this.width = width; this.surfaceData = sData; } protected native int getElem(int x, int y, SurfaceData sData); /** * getElem returns the pixel value for a given index into the * dataBuffer array. The bank value is currently ignored (the * type of data accessed through this class is not stored in * separate banks). The x and y coordinates of a pixel are calculated * from the index value and the native getElem() method is * called with the internal surfaceData object. */ public int getElem(int bank, int i) { return getElem(i % width, i / width, surfaceData); } protected native void setElem(int x, int y, int val, SurfaceData sData); /** * setElem sets the pixel value of a given index into the * dataBuffer array. The bank value is currently ignored (the * type of data accessed through this class is not stored in * separate banks). The x and y coordinates of a pixel are calculated * from the index value and the native setElem() method is * called with the internal surfaceData object. */ public void setElem(int bank, int i, int val) { setElem(i % width, i / width, val, surfaceData); } }
1,099
416
package org.springframework.roo.addon.layers.repository.jpa.addon; import org.springframework.roo.addon.layers.repository.jpa.annotations.RooJpaRepositoryCustomImpl; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.details.annotations.populator.AbstractAnnotationValues; import org.springframework.roo.classpath.details.annotations.populator.AutoPopulate; import org.springframework.roo.classpath.details.annotations.populator.AutoPopulationUtils; import org.springframework.roo.model.JavaType; import org.springframework.roo.model.RooJavaType; /** * The values of a {@link RooJpaRepositoryCustomImpl} annotation. * * @author <NAME> * @since 2.0 */ public class RepositoryJpaCustomImplAnnotationValues extends AbstractAnnotationValues { @AutoPopulate private JavaType repository; /** * Constructor * * @param governorPhysicalTypeMetadata the metadata to parse (required) */ public RepositoryJpaCustomImplAnnotationValues( final PhysicalTypeMetadata governorPhysicalTypeMetadata) { super(governorPhysicalTypeMetadata, RooJavaType.ROO_REPOSITORY_JPA_CUSTOM_IMPL); AutoPopulationUtils.populate(this, annotationMetadata); } /** * Returns the repository type implemented by the annotated class * * @return a non-<code>null</code> type */ public JavaType getRepository() { return repository; } }
440
530
/* * Copyright (c) 2020, 2021 Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2020, 2021 Red Hat Inc. All rights reserved. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The contents of this file are subject to the terms of either the Universal Permissive License * v 1.0 as shown at http://oss.oracle.com/licenses/upl * * or the following license: * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openjdk.jmc.console.agent.messages.internal; import org.eclipse.osgi.util.NLS; public class Messages extends NLS { private static final String BUNDLE_NAME = "org.openjdk.jmc.console.agent.messages.internal.messages"; //$NON-NLS-1$ public static String AgentEditorOpener_JOB_NAME; public static String AgentEditorOpener_MESSAGE_COULD_NOT_CONNECT; public static String AgentEditorOpener_MESSAGE_STARTING_AGENT_ON_REMOTE_JVM_NOT_SUPPORTED; public static String AgentEditorOpener_MESSAGE_START_AGENT_MANUALLY; public static String AgentEditorOpener_MESSAGE_FAILED_TO_OPEN_AGENT_EDITOR; public static String AgentEditor_CONNECTION_LOST; public static String AgentEditor_AGENT_EDITOR_TITLE; public static String AgentEditorAction_MESSAGE_REFRESH; public static String AgentEditorAction_MESSAGE_LOAD_PRESET; public static String AgentEditorAction_MESSAGE_SAVE_AS_PRESET; public static String AgentEditorUI_MESSAGE_FAILED_TO_LOAD_PRESET; public static String AgentEditorUI_MESSAGE_EMPTY_PRESET; public static String AgentEditorUI_MESSAGE_EMPTY_PRESET_TITLE; public static String CapturedValue_ERROR_RELATION_KEY_HAS_INCORRECT_SYNTAX; public static String CapturedValue_ERROR_CONVERTER_HAS_INCORRECT_SYNTAX; public static String Event_ERROR_ID_CANNOT_BE_EMPTY_OR_NULL; public static String Event_ERROR_NAME_CANNOT_BE_EMPTY_OR_NULL; public static String Event_ERROR_CLASS_CANNOT_BE_EMPTY_OR_NULL; public static String Event_ERROR_METHOD_NAME_CANNOT_BE_EMPTY_OR_NULL; public static String Event_ERROR_METHOD_DESCRIPTOR_CANNOT_BE_EMPTY_OR_NULL; public static String Event_ERROR_METHOD_PARAMETER_CANNOT_BE_NULL; public static String Event_ERROR_FIELD_CANNOT_BE_NULL; public static String Event_ERROR_CLASS_HAS_INCORRECT_SYNTAX; public static String Event_ERROR_PATH_HAS_INCORRECT_SYNTAX; public static String Event_ERROR_METHOD_NAME_HAS_INCORRECT_SYNTAX; public static String Event_ERROR_METHOD_DESCRIPTOR_HAS_INCORRECT_SYNTAX; public static String Event_ERROR_INDEX_MUST_BE_UNIQUE; public static String Field_ERROR_NAME_CANNOT_BE_EMPTY_OR_NULL; public static String Field_ERROR_EXPRESSION_CANNOT_BE_EMPTY_OR_NULL; public static String Field_ERROR_EXPRESSION_HAS_INCORRECT_SYNTAX; public static String MethodParameter_ERROR_INDEX_CANNOT_BE_LESS_THAN_ZERO; public static String MethodParameter_ERROR_NAME_CANNOT_BE_EMPTY_OR_NULL; public static String Preset_ERROR_FILE_NAME_CANNOT_BE_EMPTY_OR_NULL; public static String Preset_ERROR_MUST_HAVE_UNIQUE_ID; public static String Preset_ERROR_MUST_HAVE_UNIQUE_EVENT_CLASS_NAME; public static String CapturedValueEditingPage_PAGE_NAME; public static String CapturedValueEditingPage_MESSAGE_PARAMETER_OR_RETURN_VALUE_EDITING_PAGE_TITLE; public static String CapturedValueEditingPage_MESSAGE_PARAMETER_OR_RETURN_VALUE_EDITING_PAGE_DESCRIPTION; public static String CapturedValueEditingPage_MESSAGE_FIELD_EDITING_PAGE_TITLE; public static String CapturedValueEditingPage_MESSAGE_FIELD_EDITING_PAGE_DESCRIPTION; public static String CapturedValueEditingPage_LABEL_NAME; public static String CapturedValueEditingPage_LABEL_INDEX; public static String CapturedValueEditingPage_LABEL_IS_RETURN_VALUE; public static String CapturedValueEditingPage_LABEL_EXPRESSION; public static String CapturedValueEditingPage_LABEL_DESCRIPTION; public static String CapturedValueEditingPage_LABEL_CONTENT_TYPE; public static String CapturedValueEditingPage_LABEL_CLEAR; public static String CapturedValueEditingPage_LABEL_RELATIONAL_KEY; public static String CapturedValueEditingPage_LABEL_CONVERTER; public static String CapturedValueEditingPage_MESSAGE_NAME_OF_THE_CAPTURING; public static String CapturedValueEditingPage_MESSAGE_JAVA_PRIMARY_EXPRESSION_TO_BE_EVALUATED; public static String CapturedValueEditingPage_MESSAGE_OPTIONAL_DESCRIPTION_OF_THIS_CAPTURING; public static String CapturedValueEditingPage_MESSAGE_RELATIONAL_KEY_DESCRIPTION; public static String CapturedValueEditingPage_MESSAGE_CONVERTER_DESCRIPTION; public static String EventEditingWizardConfigPage_PAGE_NAME; public static String EventEditingWizardConfigPage_MESSAGE_EVENT_EDITING_WIZARD_CONFIG_PAGE_TITLE; public static String EventEditingWizardConfigPage_MESSAGE_EVENT_EDITING_WIZARD_CONFIG_PAGE_DESCRIPTION; public static String EventEditingWizardConfigPage_LABEL_ID; public static String EventEditingWizardConfigPage_LABEL_NAME; public static String EventEditingWizardConfigPage_LABEL_DESCRIPTION; public static String EventEditingWizardConfigPage_LABEL_CLASS; public static String EventEditingWizardConfigPage_LABEL_METHOD; public static String EventEditingWizardConfigPage_LABEL_PATH; public static String EventEditingWizardConfigPage_LABEL_LOCATION; public static String EventEditingWizardConfigPage_LABEL_CLEAR; public static String EventEditingWizardConfigPage_LABEL_RECORD_EXCEPTIONS; public static String EventEditingWizardConfigPage_LABEL_RECORD_STACK_TRACE; public static String EventEditingWizardConfigPage_MESSAGE_EVENT_ID; public static String EventEditingWizardConfigPage_MESSAGE_NAME_OF_THE_EVENT; public static String EventEditingWizardConfigPage_MESSAGE_FULLY_QUALIFIED_CLASS_NAME; public static String EventEditingWizardConfigPage_MESSAGE_METHOD_NAME; public static String EventEditingWizardConfigPage_MESSAGE_METHOD_DESCRIPTOR; public static String EventEditingWizardConfigPage_MESSAGE_OPTIONAL_DESCRIPTION_OF_THIS_EVENT; public static String EventEditingWizardConfigPage_MESSAGE_PATH_TO_EVENT; public static String EventEditingWizardFieldPage_PAGE_NAME; public static String EventEditingWizardFieldPage_MESSAGE_EVENT_EDITING_WIZARD_FIELD_PAGE_TITLE; public static String EventEditingWizardFieldPage_MESSAGE_EVENT_EDITING_WIZARD_FIELD_PAGE_DESCRIPTION; public static String EventEditingWizardFieldPage_MESSAGE_UNABLE_TO_SAVE_THE_FIELD; public static String EventEditingWizardFieldPage_LABEL_NAME; public static String EventEditingWizardFieldPage_LABEL_EXPRESSION; public static String EventEditingWizardFieldPage_LABEL_DESCRIPTION; public static String EventEditingWizardFieldPage_ID_NAME; public static String EventEditingWizardFieldPage_ID_EXPRESSION; public static String EventEditingWizardFieldPage_ID_DESCRIPTION; public static String EventEditingWizardParameterPage_PAGE_NAME; public static String EventEditingWizardParameterPage_MESSAGE_EVENT_EDITING_WIZARD_PARAMETER_PAGE_TITLE; public static String EventEditingWizardParameterPage_MESSAGE_EVENT_EDITING_WIZARD_PARAMETER_PAGE_DESCRIPTION; public static String EventEditingWizardParameterPage_MESSAGE_RETURN_VALUE; public static String EventEditingWizardParameterPage_MESSAGE_UNABLE_TO_SAVE_THE_PARAMETER_OR_RETURN_VALUE; public static String EventEditingWizardParameterPage_LABEL_INDEX; public static String EventEditingWizardParameterPage_LABEL_NAME; public static String EventEditingWizardParameterPage_LABEL_DESCRIPTION; public static String EventEditingWizardParameterPage_ID_INDEX; public static String EventEditingWizardParameterPage_ID_NAME; public static String EventEditingWizardParameterPage_ID_DESCRIPTION; public static String PresetSelectorWizardPage_PAGE_NAME; public static String PresetSelectorWizardPage_MESSAGE_FAILED_TO_SAVE_PRESET; public static String PresetSelectorWizardPage_MESSAGE_PAGE_TITLE; public static String PresetSelectorWizardPage_MESSAGE_PAGE_DESCRIPTION; public static String PresetSelectorWizardPage_ID_PRESET; public static String PresetSelectorWizardPage_MESSAGE_EVENTS; public static String PresetSelectorWizardPage_ERROR_PAGE_TITLE; public static String PresetSelectorWizardPage_SAVE_PRESET_TITLE; public static String PresetSelectorWizardPage_SAVE_PRESET_MESSAGE; public static String PresetEditingWizardConfigPage_PAGE_NAME; public static String PresetEditingWizardConfigPage_MESSAGE_PRESET_EDITING_WIZARD_CONFIG_PAGE_TITLE; public static String PresetEditingWizardConfigPage_MESSAGE_PRESET_EDITING_WIZARD_CONFIG_PAGE_DESCRIPTION; public static String PresetEditingWizardConfigPage_LABEL_FILE_NAME; public static String PresetEditingWizardConfigPage_LABEL_CLASS_PREFIX; public static String PresetEditingWizardConfigPage_LABEL_ALLOW_TO_STRING; public static String PresetEditingWizardConfigPage_LABEL_ALLOW_CONVERTER; public static String PresetEditingWizardConfigPage_MESSAGE_NAME_OF_THE_SAVED_XML; public static String PresetEditingWizardConfigPage_MESSAGE_PREFIX_ADDED_TO_GENERATED_EVENT_CLASSES; public static String PresetEditingWizardEventPage_PAGE_NAME; public static String PresetEditingWizardEventPage_MESSAGE_PRESET_EDITING_WIZARD_EVENT_PAGE_TITLE; public static String PresetEditingWizardEventPage_MESSAGE_PRESET_EDITING_WIZARD_EVENT_PAGE_DESCRIPTION; public static String PresetEditingWizardEventPage_MESSAGE_UNABLE_TO_SAVE_THE_PRESET; public static String PresetEditingWizardEventPage_LABEL_ID_COLUMN; public static String PresetEditingWizardEventPage_LABEL_NAME_COLUMN; public static String PresetEditingWizardEventPage_ID_ID_COLUMN; public static String PresetEditingWizardEventPage_ID_NAME_COLUMN; public static String PresetEditingWizardPreviewPage_PAGE_NAME; public static String PresetEditingWizardPreviewPage_MESSAGE_PRESET_EDITING_WIZARD_PREVIEW_PAGE_TITLE; public static String PresetEditingWizardPreviewPage_MESSAGE_PRESET_EDITING_WIZARD_PREVIEW_PAGE_DESCRIPTION; public static String PresetManagerPage_PAGE_NAME; public static String PresetManagerPage_MESSAGE_PRESET_MANAGER_PAGE_TITLE; public static String PresetManagerPage_MESSAGE_PRESET_MANAGER_PAGE_DESCRIPTION; public static String PresetManagerPage_MESSAGE_PRESET_MANAGER_UNABLE_TO_SAVE_THE_PRESET; public static String PresetManagerPage_MESSAGE_PRESET_MANAGER_UNABLE_TO_IMPORT_THE_PRESET; public static String PresetManagerPage_MESSAGE_PRESET_MANAGER_UNABLE_TO_EXPORT_THE_PRESET; public static String PresetManagerPage_MESSAGE_IMPORT_EXTERNAL_PRESET_FILES; public static String PresetManagerPage_MESSAGE_EXPORT_PRESET_TO_A_FILE; public static String PresetManagerPage_MESSAGE_EVENTS; public static String ProbeCreationPage_MESSAGE_PROBE_CREATION_PAGE_TITLE; public static String ProbeCreationPage_MESSAGE_PROBE_CREATION_PAGE_DESCRIPTION; public static String ProbeCreationPage_MESSAGE_PROBE_CREATION_SET_NAME_MESSAGE; public static String ProbeCreationPage_MESSAGE_PROBE_CREATION_SET_NAME_DESCRIPTION; public static String EditorTab_TITLE; public static String ActionButtons_LABEL_SAVE_TO_PRESET_BUTTON; public static String ActionButtons_LABEL_SAVE_TO_FILE_BUTTON; public static String ActionButtons_LABEL_APPLY_PRESET_BUTTON; public static String ActionButtons_LABEL_APPLY_LOCAL_CONFIG_BUTTON; public static String ActionButtons_ERROR_PAGE_TITLE; public static String ActionButtons_MESSAGE_APPLY_LOCAL_CONFIG; public static String LiveConfigTab_TITLE; public static String OverviewTab_TITLE; public static String OverviewTab_MESSAGE_AGENT_LOADED; public static String EditAgentSection_MESSAGE_ENTER_PATH; public static String EditAgentSection_MESSAGE_AGENT_XML_PATH; public static String EditAgentSection_MESSAGE_BROWSE; public static String EditAgentSection_MESSAGE_EDIT; public static String EditAgentSection_MESSAGE_VALIDATE; public static String EditAgentSection_MESSAGE_APPLY; public static String EditAgentSection_MESSAGE_NO_WARNINGS_OR_ERRORS_FOUND; public static String PresetsTab_TITLE; public static String BaseWizardPage_MESSAGE_UNEXPECTED_ERROR_HAS_OCCURRED; public static String StartAgentWizard_MESSAGE_FAILED_TO_START_AGENT; public static String StartAgentWizard_MESSAGE_FAILED_TO_OPEN_AGENT_EDITOR; public static String StartAgentWizard_MESSAGE_UNEXPECTED_ERROR_HAS_OCCURRED; public static String StartAgentWizard_MESSAGE_INVALID_AGENT_CONFIG; public static String StartAgentWizard_MESSAGE_ACCESS_TO_UNSAFE_REQUIRED; public static String StartAgentWizard_WIZARD_FINISH_BUTTON_TEXT; public static String StartAgentWizard_MESSAGE_FAILED_TO_LOAD_AGENT; public static String StartAgentWizardPage_PAGE_NAME; public static String StartAgentWizardPage_MESSAGE_START_AGENT_WIZARD_PAGE_TITLE; public static String StartAgentWizardPage_MESSAGE_START_AGENT_WIZARD_PAGE_DESCRIPTION; public static String StartAgentWizardPage_MESSAGE_PATH_TO_AN_AGENT_JAR; public static String StartAgentWizardPage_MESSAGE_PATH_TO_AN_AGENT_CONFIG; public static String StartAgentWizardPage_LABEL_TARGET_JVM; public static String StartAgentWizardPage_LABEL_AGENT_JAR; public static String StartAgentWizardPage_LABEL_AGENT_XML; public static String StartAgentWizardPage_LABEL_BROWSE; public static String StartAgentWizardPage_DIALOG_BROWSER_FOR_AGENT_JAR; public static String StartAgentWizardPage_DIALOG_BROWSER_FOR_AGENT_CONFIG; static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); } private Messages() { } }
4,872
1,825
<gh_stars>1000+ package com.github.unidbg.ios.file; import com.github.unidbg.Emulator; import com.github.unidbg.arm.backend.Backend; import com.github.unidbg.file.FileIO; import com.github.unidbg.file.ios.BaseDarwinFileIO; import com.github.unidbg.file.ios.DarwinFileIO; import com.github.unidbg.file.ios.StatStructure; import com.github.unidbg.ios.struct.attr.AttrList; import com.github.unidbg.ios.struct.kernel.StatFS; import com.sun.jna.Pointer; import java.io.IOException; import java.util.Arrays; public class Stdin extends BaseDarwinFileIO implements DarwinFileIO { public Stdin(int oflags) { super(oflags); } @Override public void close() { } @Override public int write(byte[] data) { throw new AbstractMethodError(new String(data)); } @Override public int read(Backend backend, Pointer buffer, int count) { try { byte[] data = new byte[count]; int read = System.in.read(data, 0, count); if (read <= 0) { return read; } buffer.write(0, Arrays.copyOf(data, read), 0, read); return read; } catch (IOException e) { throw new IllegalStateException(e); } } @Override public FileIO dup2() { return this; } @Override public int ioctl(Emulator<?> emulator, long request, long argp) { return 0; } @Override public int fstat(Emulator<?> emulator, StatStructure stat) { throw new UnsupportedOperationException(); } @Override public int fstatfs(StatFS statFS) { throw new UnsupportedOperationException(); } @Override public String toString() { return "stdin"; } @Override public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) { throw new UnsupportedOperationException(); } @Override public int getdirentries64(Pointer buf, int bufSize) { throw new UnsupportedOperationException(); } }
850
903
<reponame>javanna/lucene /* * 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.lucene.util.automaton; import java.util.ArrayList; import java.util.Arrays; import java.util.List; // TODO // - do we really need the .bits...? if not we can make util in UnicodeUtil to convert 1 char // into a BytesRef /** * Converts UTF-32 automata to the equivalent UTF-8 representation. * * @lucene.internal */ public final class UTF32ToUTF8 { // Unicode boundaries for UTF8 bytes 1,2,3,4 private static final int[] startCodes = new int[] {0, 128, 2048, 65536}; private static final int[] endCodes = new int[] {127, 2047, 65535, 1114111}; static int[] MASKS = new int[32]; static { int v = 2; for (int i = 0; i < 32; i++) { MASKS[i] = v - 1; v *= 2; } } // Represents one of the N utf8 bytes that (in sequence) // define a code point. value is the byte value; bits is // how many bits are "used" by utf8 at that byte private static class UTF8Byte { int value; // TODO: change to byte byte bits; } // Holds a single code point, as a sequence of 1-4 utf8 bytes: // TODO: maybe move to UnicodeUtil? private static class UTF8Sequence { private final UTF8Byte[] bytes; private int len; public UTF8Sequence() { bytes = new UTF8Byte[4]; for (int i = 0; i < 4; i++) { bytes[i] = new UTF8Byte(); } } public int byteAt(int idx) { return bytes[idx].value; } public int numBits(int idx) { return bytes[idx].bits; } private void set(int code) { if (code < 128) { // 0xxxxxxx bytes[0].value = code; bytes[0].bits = 7; len = 1; } else if (code < 2048) { // 110yyyxx 10xxxxxx bytes[0].value = (6 << 5) | (code >> 6); bytes[0].bits = 5; setRest(code, 1); len = 2; } else if (code < 65536) { // 1110yyyy 10yyyyxx 10xxxxxx bytes[0].value = (14 << 4) | (code >> 12); bytes[0].bits = 4; setRest(code, 2); len = 3; } else { // 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx bytes[0].value = (30 << 3) | (code >> 18); bytes[0].bits = 3; setRest(code, 3); len = 4; } } private void setRest(int code, int numBytes) { for (int i = 0; i < numBytes; i++) { bytes[numBytes - i].value = 128 | (code & MASKS[5]); bytes[numBytes - i].bits = 6; code = code >> 6; } } @Override public String toString() { StringBuilder b = new StringBuilder(); for (int i = 0; i < len; i++) { if (i > 0) { b.append(' '); } b.append(Integer.toBinaryString(bytes[i].value)); } return b.toString(); } } /** Sole constructor. */ public UTF32ToUTF8() {} private final UTF8Sequence startUTF8 = new UTF8Sequence(); private final UTF8Sequence endUTF8 = new UTF8Sequence(); private final UTF8Sequence tmpUTF8a = new UTF8Sequence(); private final UTF8Sequence tmpUTF8b = new UTF8Sequence(); // Builds necessary utf8 edges between start & end void convertOneEdge(int start, int end, int startCodePoint, int endCodePoint) { startUTF8.set(startCodePoint); endUTF8.set(endCodePoint); build(start, end, startUTF8, endUTF8, 0); } private void build(int start, int end, UTF8Sequence startUTF8, UTF8Sequence endUTF8, int upto) { // Break into start, middle, end: if (startUTF8.byteAt(upto) == endUTF8.byteAt(upto)) { // Degen case: lead with the same byte: if (upto == startUTF8.len - 1 && upto == endUTF8.len - 1) { // Super degen: just single edge, one UTF8 byte: utf8.addTransition(start, end, startUTF8.byteAt(upto), endUTF8.byteAt(upto)); return; } else { assert startUTF8.len > upto + 1; assert endUTF8.len > upto + 1; int n = utf8.createState(); // Single value leading edge utf8.addTransition(start, n, startUTF8.byteAt(upto)); // start.addTransition(new Transition(startUTF8.byteAt(upto), n)); // type=single // Recurse for the rest build(n, end, startUTF8, endUTF8, 1 + upto); } } else if (startUTF8.len == endUTF8.len) { if (upto == startUTF8.len - 1) { // start.addTransition(new Transition(startUTF8.byteAt(upto), endUTF8.byteAt(upto), end)); // // type=startend utf8.addTransition(start, end, startUTF8.byteAt(upto), endUTF8.byteAt(upto)); } else { start(start, end, startUTF8, upto, false); if (endUTF8.byteAt(upto) - startUTF8.byteAt(upto) > 1) { // There is a middle all( start, end, startUTF8.byteAt(upto) + 1, endUTF8.byteAt(upto) - 1, startUTF8.len - upto - 1); } end(start, end, endUTF8, upto, false); } } else { // start start(start, end, startUTF8, upto, true); // possibly middle, spanning multiple num bytes int byteCount = 1 + startUTF8.len - upto; final int limit = endUTF8.len - upto; while (byteCount < limit) { // wasteful: we only need first byte, and, we should // statically encode this first byte: tmpUTF8a.set(startCodes[byteCount - 1]); tmpUTF8b.set(endCodes[byteCount - 1]); all(start, end, tmpUTF8a.byteAt(0), tmpUTF8b.byteAt(0), tmpUTF8a.len - 1); byteCount++; } // end end(start, end, endUTF8, upto, true); } } private void start(int start, int end, UTF8Sequence startUTF8, int upto, boolean doAll) { if (upto == startUTF8.len - 1) { // Done recursing utf8.addTransition( start, end, startUTF8.byteAt(upto), startUTF8.byteAt(upto) | MASKS[startUTF8.numBits(upto) - 1]); // type=start // start.addTransition(new Transition(startUTF8.byteAt(upto), startUTF8.byteAt(upto) | // MASKS[startUTF8.numBits(upto)-1], end)); // type=start } else { int n = utf8.createState(); utf8.addTransition(start, n, startUTF8.byteAt(upto)); // start.addTransition(new Transition(startUTF8.byteAt(upto), n)); // type=start start(n, end, startUTF8, 1 + upto, true); int endCode = startUTF8.byteAt(upto) | MASKS[startUTF8.numBits(upto) - 1]; if (doAll && startUTF8.byteAt(upto) != endCode) { all(start, end, startUTF8.byteAt(upto) + 1, endCode, startUTF8.len - upto - 1); } } } private void end(int start, int end, UTF8Sequence endUTF8, int upto, boolean doAll) { if (upto == endUTF8.len - 1) { // Done recursing // start.addTransition(new Transition(endUTF8.byteAt(upto) & // (~MASKS[endUTF8.numBits(upto)-1]), endUTF8.byteAt(upto), end)); // type=end utf8.addTransition( start, end, endUTF8.byteAt(upto) & (~MASKS[endUTF8.numBits(upto) - 1]), endUTF8.byteAt(upto)); } else { final int startCode; if (endUTF8.numBits(upto) == 5) { // special case -- avoid created unused edges (endUTF8 // doesn't accept certain byte sequences) -- there // are other cases we could optimize too: startCode = 194; } else { startCode = endUTF8.byteAt(upto) & (~MASKS[endUTF8.numBits(upto) - 1]); } if (doAll && endUTF8.byteAt(upto) != startCode) { all(start, end, startCode, endUTF8.byteAt(upto) - 1, endUTF8.len - upto - 1); } int n = utf8.createState(); // start.addTransition(new Transition(endUTF8.byteAt(upto), n)); // type=end utf8.addTransition(start, n, endUTF8.byteAt(upto)); end(n, end, endUTF8, 1 + upto, true); } } private void all(int start, int end, int startCode, int endCode, int left) { if (left == 0) { // start.addTransition(new Transition(startCode, endCode, end)); // type=all utf8.addTransition(start, end, startCode, endCode); } else { int lastN = utf8.createState(); // start.addTransition(new Transition(startCode, endCode, lastN)); // type=all utf8.addTransition(start, lastN, startCode, endCode); while (left > 1) { int n = utf8.createState(); // lastN.addTransition(new Transition(128, 191, n)); // type=all* utf8.addTransition(lastN, n, 128, 191); // type=all* left--; lastN = n; } // lastN.addTransition(new Transition(128, 191, end)); // type = all* utf8.addTransition(lastN, end, 128, 191); // type = all* } } Automaton.Builder utf8; /** * Converts an incoming utf32 automaton to an equivalent utf8 one. The incoming automaton need not * be deterministic. Note that the returned automaton will not in general be deterministic, so you * must determinize it if that's needed. */ public Automaton convert(Automaton utf32) { if (utf32.getNumStates() == 0) { return utf32; } int[] map = new int[utf32.getNumStates()]; Arrays.fill(map, -1); List<Integer> pending = new ArrayList<>(); int utf32State = 0; pending.add(utf32State); utf8 = new Automaton.Builder(); int utf8State = utf8.createState(); utf8.setAccept(utf8State, utf32.isAccept(utf32State)); map[utf32State] = utf8State; Transition scratch = new Transition(); while (pending.size() != 0) { utf32State = pending.remove(pending.size() - 1); utf8State = map[utf32State]; assert utf8State != -1; int numTransitions = utf32.getNumTransitions(utf32State); utf32.initTransition(utf32State, scratch); for (int i = 0; i < numTransitions; i++) { utf32.getNextTransition(scratch); int destUTF32 = scratch.dest; int destUTF8 = map[destUTF32]; if (destUTF8 == -1) { destUTF8 = utf8.createState(); utf8.setAccept(destUTF8, utf32.isAccept(destUTF32)); map[destUTF32] = destUTF8; pending.add(destUTF32); } // Writes new transitions into pendingTransitions: convertOneEdge(utf8State, destUTF8, scratch.min, scratch.max); } } return utf8.finish(); } }
4,702
880
class Foo: ... class Bar : ... class Old ( ) : gold : int class OO ( Foo ) : ... class OOP ( Foo , Bar, ) : pass class OOPS ( Foo , ) : pass class OOPSI ( Foo, * Bar , metaclass = foo , ): pass class OOPSIE ( list , *args, kw = arg , ** kwargs ) : what : does_this_even = mean def __init__(self) -> None: self.foo: Bar = Bar()
167
372
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.adexchangebuyer2.v2beta1.model; /** * A set of filters that is applied to a request for data. Within a filter set, an AND operation is * performed across the filters represented by each field. An OR operation is performed across the * filters represented by the multiple values of a repeated field, e.g., "format=VIDEO AND * deal_id=12 AND (seller_network_id=34 OR seller_network_id=56)". * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Ad Exchange Buyer API II. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class FilterSet extends com.google.api.client.json.GenericJson { /** * An absolute date range, defined by a start date and an end date. Interpreted relative to * Pacific time zone. * The value may be {@code null}. */ @com.google.api.client.util.Key private AbsoluteDateRange absoluteDateRange; /** * The set of dimensions along which to break down the response; may be empty. If multiple * dimensions are requested, the breakdown is along the Cartesian product of the requested * dimensions. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> breakdownDimensions; /** * The ID of the creative on which to filter; optional. This field may be set only for a filter * set that accesses account-level troubleshooting data, i.e., one whose name matches the * `bidders/accounts/filterSets` pattern. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String creativeId; /** * The ID of the deal on which to filter; optional. This field may be set only for a filter set * that accesses account-level troubleshooting data, i.e., one whose name matches the * `bidders/accounts/filterSets` pattern. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long dealId; /** * The environment on which to filter; optional. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String environment; /** * Creative format bidded on or allowed to bid on, can be empty. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String format; /** * Creative formats bidded on or allowed to bid on, can be empty. Although this field is a list, * it can only be populated with a single item. A HTTP 400 bad request error will be returned in * the response if you specify multiple items. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> formats; /** * A user-defined name of the filter set. Filter set names must be unique globally and match one * of the patterns: - `bidders/filterSets` (for accessing bidder-level troubleshooting data) - * `bidders/accounts/filterSets` (for accessing account-level troubleshooting data) This field is * required in create operations. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * The list of platforms on which to filter; may be empty. The filters represented by multiple * platforms are ORed together (i.e., if non-empty, results must match any one of the platforms). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> platforms; /** * For Open Bidding partners only. The list of publisher identifiers on which to filter; may be * empty. The filters represented by multiple publisher identifiers are ORed together. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> publisherIdentifiers; /** * An open-ended realtime time range, defined by the aggregation start timestamp. * The value may be {@code null}. */ @com.google.api.client.util.Key private RealtimeTimeRange realtimeTimeRange; /** * A relative date range, defined by an offset from today and a duration. Interpreted relative to * Pacific time zone. * The value may be {@code null}. */ @com.google.api.client.util.Key private RelativeDateRange relativeDateRange; /** * For Authorized Buyers only. The list of IDs of the seller (publisher) networks on which to * filter; may be empty. The filters represented by multiple seller network IDs are ORed together * (i.e., if non-empty, results must match any one of the publisher networks). See [seller- * network-ids](https://developers.google.com/authorized-buyers/rtb/downloads/seller-network-ids) * file for the set of existing seller network IDs. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.Integer> sellerNetworkIds; /** * The granularity of time intervals if a time series breakdown is desired; optional. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String timeSeriesGranularity; /** * An absolute date range, defined by a start date and an end date. Interpreted relative to * Pacific time zone. * @return value or {@code null} for none */ public AbsoluteDateRange getAbsoluteDateRange() { return absoluteDateRange; } /** * An absolute date range, defined by a start date and an end date. Interpreted relative to * Pacific time zone. * @param absoluteDateRange absoluteDateRange or {@code null} for none */ public FilterSet setAbsoluteDateRange(AbsoluteDateRange absoluteDateRange) { this.absoluteDateRange = absoluteDateRange; return this; } /** * The set of dimensions along which to break down the response; may be empty. If multiple * dimensions are requested, the breakdown is along the Cartesian product of the requested * dimensions. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getBreakdownDimensions() { return breakdownDimensions; } /** * The set of dimensions along which to break down the response; may be empty. If multiple * dimensions are requested, the breakdown is along the Cartesian product of the requested * dimensions. * @param breakdownDimensions breakdownDimensions or {@code null} for none */ public FilterSet setBreakdownDimensions(java.util.List<java.lang.String> breakdownDimensions) { this.breakdownDimensions = breakdownDimensions; return this; } /** * The ID of the creative on which to filter; optional. This field may be set only for a filter * set that accesses account-level troubleshooting data, i.e., one whose name matches the * `bidders/accounts/filterSets` pattern. * @return value or {@code null} for none */ public java.lang.String getCreativeId() { return creativeId; } /** * The ID of the creative on which to filter; optional. This field may be set only for a filter * set that accesses account-level troubleshooting data, i.e., one whose name matches the * `bidders/accounts/filterSets` pattern. * @param creativeId creativeId or {@code null} for none */ public FilterSet setCreativeId(java.lang.String creativeId) { this.creativeId = creativeId; return this; } /** * The ID of the deal on which to filter; optional. This field may be set only for a filter set * that accesses account-level troubleshooting data, i.e., one whose name matches the * `bidders/accounts/filterSets` pattern. * @return value or {@code null} for none */ public java.lang.Long getDealId() { return dealId; } /** * The ID of the deal on which to filter; optional. This field may be set only for a filter set * that accesses account-level troubleshooting data, i.e., one whose name matches the * `bidders/accounts/filterSets` pattern. * @param dealId dealId or {@code null} for none */ public FilterSet setDealId(java.lang.Long dealId) { this.dealId = dealId; return this; } /** * The environment on which to filter; optional. * @return value or {@code null} for none */ public java.lang.String getEnvironment() { return environment; } /** * The environment on which to filter; optional. * @param environment environment or {@code null} for none */ public FilterSet setEnvironment(java.lang.String environment) { this.environment = environment; return this; } /** * Creative format bidded on or allowed to bid on, can be empty. * @return value or {@code null} for none */ public java.lang.String getFormat() { return format; } /** * Creative format bidded on or allowed to bid on, can be empty. * @param format format or {@code null} for none */ public FilterSet setFormat(java.lang.String format) { this.format = format; return this; } /** * Creative formats bidded on or allowed to bid on, can be empty. Although this field is a list, * it can only be populated with a single item. A HTTP 400 bad request error will be returned in * the response if you specify multiple items. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getFormats() { return formats; } /** * Creative formats bidded on or allowed to bid on, can be empty. Although this field is a list, * it can only be populated with a single item. A HTTP 400 bad request error will be returned in * the response if you specify multiple items. * @param formats formats or {@code null} for none */ public FilterSet setFormats(java.util.List<java.lang.String> formats) { this.formats = formats; return this; } /** * A user-defined name of the filter set. Filter set names must be unique globally and match one * of the patterns: - `bidders/filterSets` (for accessing bidder-level troubleshooting data) - * `bidders/accounts/filterSets` (for accessing account-level troubleshooting data) This field is * required in create operations. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * A user-defined name of the filter set. Filter set names must be unique globally and match one * of the patterns: - `bidders/filterSets` (for accessing bidder-level troubleshooting data) - * `bidders/accounts/filterSets` (for accessing account-level troubleshooting data) This field is * required in create operations. * @param name name or {@code null} for none */ public FilterSet setName(java.lang.String name) { this.name = name; return this; } /** * The list of platforms on which to filter; may be empty. The filters represented by multiple * platforms are ORed together (i.e., if non-empty, results must match any one of the platforms). * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPlatforms() { return platforms; } /** * The list of platforms on which to filter; may be empty. The filters represented by multiple * platforms are ORed together (i.e., if non-empty, results must match any one of the platforms). * @param platforms platforms or {@code null} for none */ public FilterSet setPlatforms(java.util.List<java.lang.String> platforms) { this.platforms = platforms; return this; } /** * For Open Bidding partners only. The list of publisher identifiers on which to filter; may be * empty. The filters represented by multiple publisher identifiers are ORed together. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPublisherIdentifiers() { return publisherIdentifiers; } /** * For Open Bidding partners only. The list of publisher identifiers on which to filter; may be * empty. The filters represented by multiple publisher identifiers are ORed together. * @param publisherIdentifiers publisherIdentifiers or {@code null} for none */ public FilterSet setPublisherIdentifiers(java.util.List<java.lang.String> publisherIdentifiers) { this.publisherIdentifiers = publisherIdentifiers; return this; } /** * An open-ended realtime time range, defined by the aggregation start timestamp. * @return value or {@code null} for none */ public RealtimeTimeRange getRealtimeTimeRange() { return realtimeTimeRange; } /** * An open-ended realtime time range, defined by the aggregation start timestamp. * @param realtimeTimeRange realtimeTimeRange or {@code null} for none */ public FilterSet setRealtimeTimeRange(RealtimeTimeRange realtimeTimeRange) { this.realtimeTimeRange = realtimeTimeRange; return this; } /** * A relative date range, defined by an offset from today and a duration. Interpreted relative to * Pacific time zone. * @return value or {@code null} for none */ public RelativeDateRange getRelativeDateRange() { return relativeDateRange; } /** * A relative date range, defined by an offset from today and a duration. Interpreted relative to * Pacific time zone. * @param relativeDateRange relativeDateRange or {@code null} for none */ public FilterSet setRelativeDateRange(RelativeDateRange relativeDateRange) { this.relativeDateRange = relativeDateRange; return this; } /** * For Authorized Buyers only. The list of IDs of the seller (publisher) networks on which to * filter; may be empty. The filters represented by multiple seller network IDs are ORed together * (i.e., if non-empty, results must match any one of the publisher networks). See [seller- * network-ids](https://developers.google.com/authorized-buyers/rtb/downloads/seller-network-ids) * file for the set of existing seller network IDs. * @return value or {@code null} for none */ public java.util.List<java.lang.Integer> getSellerNetworkIds() { return sellerNetworkIds; } /** * For Authorized Buyers only. The list of IDs of the seller (publisher) networks on which to * filter; may be empty. The filters represented by multiple seller network IDs are ORed together * (i.e., if non-empty, results must match any one of the publisher networks). See [seller- * network-ids](https://developers.google.com/authorized-buyers/rtb/downloads/seller-network-ids) * file for the set of existing seller network IDs. * @param sellerNetworkIds sellerNetworkIds or {@code null} for none */ public FilterSet setSellerNetworkIds(java.util.List<java.lang.Integer> sellerNetworkIds) { this.sellerNetworkIds = sellerNetworkIds; return this; } /** * The granularity of time intervals if a time series breakdown is desired; optional. * @return value or {@code null} for none */ public java.lang.String getTimeSeriesGranularity() { return timeSeriesGranularity; } /** * The granularity of time intervals if a time series breakdown is desired; optional. * @param timeSeriesGranularity timeSeriesGranularity or {@code null} for none */ public FilterSet setTimeSeriesGranularity(java.lang.String timeSeriesGranularity) { this.timeSeriesGranularity = timeSeriesGranularity; return this; } @Override public FilterSet set(String fieldName, Object value) { return (FilterSet) super.set(fieldName, value); } @Override public FilterSet clone() { return (FilterSet) super.clone(); } }
4,947
1,104
<filename>trunk/adhoc-core/src/main/java/com/alipay/bluewhale/core/task/acker/AckObject.java package com.alipay.bluewhale.core.task.acker; public class AckObject { public Long val=null; public Object spout_task=null; public Boolean failed=false; }
104
358
<reponame>prisae/simpeg from __future__ import print_function # Functions to import and export MT EDI files. from SimPEG import mkvc from scipy.constants import mu_0 from numpy.lib import recfunctions as recFunc from .data_utils import rec_to_ndarr # Import modules import numpy as np import os, sys, re class EDIimporter: """ A class to import EDIfiles. """ # Define data converters # Convert Z[mV/km/nT] (as in EDI)to Z[V/A] SI unit _impUnitEDI2SI = 4 * np.pi * 1e-4 # ConvertZ[V/A] SI unit to Z[mV/km/nT] (as in EDI)_ _impUnitSI2EDI = 1.0 / _impUnitEDI2SI # Properties filesList = None comps = None # Hidden properties _outEPSG = None # Project info _2out = None # The projection operator def __init__(self, EDIfilesList, compList=None, outEPSG=None): # Set the fileList self.filesList = EDIfilesList # Set the components to import if compList is None: self.comps = [ "ZXXR", "ZXYR", "ZYXR", "ZYYR", "ZXXI", "ZXYI", "ZYXI", "ZYYI", "ZXX.VAR", "ZXY.VAR", "ZYX.VAR", "ZYY.VAR", ] else: self.comps = compList if outEPSG is not None: self._outEPSG = outEPSG def __call__(self, comps=None): if comps is None: return self._data return self._data[comps] def importFiles(self): """ Function to import EDI files into a object. """ # Constants that are needed for convertion of units # Temp lists tmpStaList = [] tmpCompList = ["freq", "x", "y", "z"] tmpCompList.extend(self.comps) # List of how to "rotate/shift" the data to comply with shift_list = [["xx", "yy"], ["xy", "yx"], ["yx", "xy"], ["yy", "xx"]] # Make the outarray dtRI = [(compS.lower().replace(".", ""), float) for compS in tmpCompList] # Loop through all the files for nrEDI, EDIfile in enumerate(self.filesList): # Read the file into a list of the lines with open(EDIfile, "r") as fid: EDIlines = fid.readlines() # Find the location latD, longD, elevM = _findLatLong(EDIlines) # Transfrom coordinates transCoord = self._transfromPoints(longD, latD) # Extract the name of the file (station) EDIname = EDIfile.split(os.sep)[-1].split(".")[0] # Arrange the data staList = [EDIname, EDIfile, transCoord[0], transCoord[1], elevM[0]] # Add to the station list tmpStaList.extend(staList) # Read the frequency data freq = _findEDIcomp(">FREQ", EDIlines) # Make the temporary rec array. tArrRec = (np.nan * np.ones((len(freq), len(dtRI)))).view(dtRI) tArrRec["freq"] = mkvc(freq, 2) tArrRec["x"] = mkvc(np.ones((len(freq), 1)) * transCoord[0], 2) tArrRec["y"] = mkvc(np.ones((len(freq), 1)) * transCoord[1], 2) tArrRec["z"] = mkvc(np.ones((len(freq), 1)) * elevM[0], 2) for comp in self.comps: # Deal with converting units of the impedance tensor if "Z" in comp: unitConvert = self._impUnitEDI2SI else: unitConvert = 1 # Rotate the data since EDI x is *north, y *east but Simpeg # uses x *east, y *north (* means internal reference frame) key = [ comp.lower().replace(".", "").replace(s, t) for s, t in shift_list if s in comp.lower() ][0] tArrRec[key] = mkvc(unitConvert * _findEDIcomp(">" + comp, EDIlines), 2) # Make a masked array mArrRec = np.ma.MaskedArray( rec_to_ndarr(tArrRec), mask=np.isnan(rec_to_ndarr(tArrRec)) ).view(dtype=tArrRec.dtype) try: outTemp = recFunc.stack_arrays((outTemp, mArrRec)) except NameError: outTemp = mArrRec # Assign the data self._data = outTemp # % Assign the data to the obj # nOutData=length(obj.data); # obj.data(nOutData+1:nOutData+length(TEMP.data),:) = TEMP.data; def _transfromPoints(self, longD, latD): # Import the coordinate projections try: import osr except ImportError as e: print( ( "Could not import osr, missing the gdal" + "package\nCan not project coordinates" ) ) raise e # Coordinates convertor if self._2out is None: src = osr.SpatialReference() src.ImportFromEPSG(4326) out = osr.SpatialReference() if self._outEPSG is None: # Find the UTM EPSG number Nnr = 700 if latD < 0.0 else 600 utmZ = int(1 + (longD + 180.0) / 6.0) self._outEPSG = 32000 + Nnr + utmZ out.ImportFromEPSG(self._outEPSG) self._2out = osr.CoordinateTransformation(src, out) # Return the transfrom return self._2out.TransformPoint(longD, latD) # Hidden functions def _findLatLong(fileLines): latDMS = np.array( fileLines[_findLine("LAT=", fileLines)[0]].split("=")[1].split()[0].split(":"), float, ) longDMS = np.array( fileLines[_findLine("LONG=", fileLines)[0]].split("=")[1].split()[0].split(":"), float, ) elevM = np.array( [fileLines[_findLine("ELEV=", fileLines)[0]].split("=")[1].split()[0]], float ) # Convert to D.ddddd values latS = np.sign(latDMS[0]) longS = np.sign(longDMS[0]) latD = latDMS[0] + latS * latDMS[1] / 60 + latS * latDMS[2] / 3600 longD = longDMS[0] + longS * longDMS[1] / 60 + longS * longDMS[2] / 3600 return latD, longD, elevM def _findLine(comp, fileLines): """ Find a line number in the file""" # Line counter c = 0 # List of indices for found lines found = [] # Loop through all the lines for line in fileLines: if comp in line: # Append if found found.append(c) # Increse the counter c += 1 # Return the found indices return found def _findEDIcomp(comp, fileLines, dt=float): """ Extract the data vector. Returns a list of the data. """ # Find the data headLine, indHead = [ (st, nr) for nr, st in enumerate(fileLines) if re.search(comp, st) ][0] # Extract the data nrVec = int(headLine.split("//")[-1]) c = 0 dataList = [] while c < nrVec: indHead += 1 dataList.extend(fileLines[indHead].split()) c = len(dataList) return np.array(dataList, dt)
3,646
2,023
<filename>recipes/Python/580702_Image_to_ASCII_Art_Converter/recipe-580702.py # ASCII Art Generator (Image to ASCII Art Converter) # FB - 20160925 import sys if len(sys.argv) != 3: print "USAGE:" print "[python] img2asciiart.py InputImageFileName OutputTextFileName" print "Use quotes if file paths/names contain spaces!" sys.exit() inputImageFileName = sys.argv[1] OutputTextFileName = sys.argv[2] from PIL import Image, ImageDraw, ImageFont font = ImageFont.load_default() # load default bitmap monospaced font (chrx, chry) = font.getsize(chr(32)) # calculate weights of ASCII chars weights = [] for i in range(32, 127): chrImage = font.getmask(chr(i)) ctr = 0 for y in range(chry): for x in range(chrx): if chrImage.getpixel((x, y)) > 0: ctr += 1 weights.append(float(ctr) / (chrx * chry)) image = Image.open(inputImageFileName) (imgx, imgy) = image.size imgx = int(imgx / chrx) imgy = int(imgy / chry) # NEAREST/BILINEAR/BICUBIC/ANTIALIAS image = image.resize((imgx, imgy), Image.BICUBIC) image = image.convert("L") # convert to grayscale pixels = image.load() output = open(OutputTextFileName, "w") for y in range(imgy): for x in range(imgx): w = float(pixels[x, y]) / 255 # find closest weight match wf = -1.0; k = -1 for i in range(len(weights)): if abs(weights[i] - w) <= abs(wf - w): wf = weights[i]; k = i output.write(chr(k + 32)) output.write("\n") output.close()
653
1,192
<filename>tools/clang/test/CoverageMapping/control-flow-macro.c // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only %s | FileCheck %s #define ifc if // CHECK: main // CHECK-NEXT: File 0, {{[0-9]+}}:40 -> [[END:[0-9]+]]:2 = #0 int main(int argc, const char *argv[]) { // CHECK: Expansion,File 0, [[@LINE+1]]:3 -> [[@LINE+1]]:6 = #0 ifc(1) return 0; // Expansion,File 0, [[@LINE+2]]:3 -> [[@LINE+2]]:6 = (#0 - #1) // File 0, [[@LINE+1]]:6 -> [[END]]:2 = (#0 - #1) ifc(1) return 0; return 0; }
254
407
package com.alibaba.smart.framework.engine.behavior; import com.alibaba.smart.framework.engine.context.ExecutionContext; import com.alibaba.smart.framework.engine.pvm.PvmActivity; /** * @author 高海军 帝奇 2016.11.11 * @author ettear 2016.04.13 */ public interface ActivityBehavior { boolean enter(ExecutionContext context, PvmActivity pvmActivity); void execute(ExecutionContext context, PvmActivity pvmActivity); void leave(ExecutionContext context, PvmActivity pvmActivity); }
161
428
/** * Copyright 2018 The Feign 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 reactivefeign.client; import org.reactivestreams.Publisher; import reactivefeign.client.statushandler.ReactiveStatusHandler; import reactivefeign.client.statushandler.ReactiveStatusHandlers; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * Uses statusHandlers to process status of http response * * @author <NAME> */ public class StatusHandlerPostProcessor<P extends Publisher<?>> implements ReactiveHttpResponseMapper<P> { private final ReactiveStatusHandler statusHandler; private static final ReactiveStatusHandler defaultStatusHandler = ReactiveStatusHandlers.defaultFeignErrorDecoder(); public static StatusHandlerPostProcessor handleStatus(ReactiveStatusHandler statusHandler) { return new StatusHandlerPostProcessor(statusHandler); } private StatusHandlerPostProcessor(ReactiveStatusHandler statusHandler) { this.statusHandler = statusHandler; } @Override public Mono<ReactiveHttpResponse<P>> apply(ReactiveHttpResponse<P> response) { String methodKey = response.request().methodKey(); ReactiveHttpResponse<P> errorResponse = response; if (statusHandler.shouldHandle(response.status())) { errorResponse = new ErrorReactiveHttpResponse<>(response, statusHandler.decode(methodKey, response)); } else if(defaultStatusHandler.shouldHandle(response.status())){ errorResponse = new ErrorReactiveHttpResponse<>(response, defaultStatusHandler.decode(methodKey, response)); } return Mono.just(errorResponse); } private static class ErrorReactiveHttpResponse<P extends Publisher<?>> extends DelegatingReactiveHttpResponse<P> { private final Mono<? extends Throwable> error; ErrorReactiveHttpResponse(ReactiveHttpResponse<P> response, Mono<? extends Throwable> error) { super(response); this.error = error; } @Override public P body() { if (getResponse().body() instanceof Mono) { return (P)error.flatMap(Mono::error); } else { return (P)error.flatMapMany(Flux::error); } } } }
768
6,457
#pragma once #include "Core.h" #include "Engine.h" DECLARE_LOG_CATEGORY_EXTERN(LogRealSenseDemo, Log, All);
55
389
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2017 Adobe ~ ~ 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.adobe.cq.wcm.core.components.testing; import org.apache.commons.lang3.StringUtils; import org.apache.sling.api.resource.Resource; import com.adobe.cq.xf.social.ExperienceFragmentSocialVariation; import com.day.cq.wcm.api.Page; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class MockXFFactory { private static final String IMAGE_RT = "wcm/foundation/components/image"; public static ExperienceFragmentSocialVariation getExperienceFragmentSocialVariation(Page page) { ExperienceFragmentSocialVariation socialVariation = mock(ExperienceFragmentSocialVariation.class); StringBuilder stringBuilder = new StringBuilder(); String image = null; for (Resource resource : page.getContentResource().getChild("root").getChildren()) { if (resource.isResourceType(IMAGE_RT) && StringUtils.isEmpty(image)) { image = resource.getValueMap().get("fileReference", String.class); } String text = resource.getValueMap().get("text", String.class); if (StringUtils.isNotEmpty(text)) { stringBuilder.append(text); } } when(socialVariation.getText()).thenReturn(stringBuilder.toString()); when(socialVariation.getImagePath()).thenReturn(image); return socialVariation; } }
683
1,056
<filename>ide/git/src/org/netbeans/modules/git/ui/menu/BranchMenu.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.netbeans.modules.git.ui.menu; import java.io.File; import java.util.List; import java.util.Set; import javax.swing.Action; import javax.swing.JMenu; import javax.swing.JMenuItem; import org.netbeans.libs.git.GitBranch; import org.netbeans.modules.git.Annotator; import org.netbeans.modules.git.ui.branch.CherryPickAction; import org.netbeans.modules.git.ui.branch.CreateBranchAction; import org.netbeans.modules.git.ui.branch.SetTrackingAction; import org.netbeans.modules.git.ui.checkout.AbstractCheckoutAction; import org.netbeans.modules.git.ui.checkout.SwitchBranchAction; import org.netbeans.modules.git.ui.merge.MergeRevisionAction; import org.netbeans.modules.git.ui.rebase.RebaseAction; import org.netbeans.modules.git.ui.repository.RepositoryInfo; import org.netbeans.modules.git.ui.tag.CreateTagAction; import org.netbeans.modules.git.ui.tag.ManageTagsAction; import org.netbeans.modules.git.utils.GitUtils; import org.netbeans.modules.versioning.spi.VCSAnnotator.ActionDestination; import org.netbeans.modules.versioning.spi.VCSContext; import org.netbeans.modules.versioning.util.SystemActionBridge; import org.netbeans.modules.versioning.util.Utils; import org.openide.awt.Actions; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.NbPreferences; import org.openide.util.actions.SystemAction; /** * Container menu for export actions. * * @author Ondra */ public final class BranchMenu extends DynamicMenu { private final ActionDestination dest; private final Lookup lkp; private final VCSContext ctx; @NbBundle.Messages({ "CTL_MenuItem_BranchMenu=&Branch/Tag", "CTL_MenuItem_BranchMenu.popup=Branch/Tag" }) public BranchMenu (ActionDestination dest, Lookup lkp, VCSContext ctx) { super(dest.equals(ActionDestination.MainMenu) ? Bundle.CTL_MenuItem_BranchMenu() : Bundle.CTL_MenuItem_BranchMenu_popup()); this.dest = dest; this.lkp = lkp; this.ctx = ctx; } @Override protected JMenu createMenu () { JMenu menu = new JMenu(this); JMenuItem item; if (dest.equals(ActionDestination.MainMenu)) { item = new JMenuItem(); Action action = (Action) SystemAction.get(CreateBranchAction.class); Utils.setAcceleratorBindings(Annotator.ACTIONS_PATH_PREFIX, action); Actions.connect(item, action, false); menu.add(item); item = new JMenuItem(); action = (Action) SystemAction.get(SwitchBranchAction.class); Utils.setAcceleratorBindings(Annotator.ACTIONS_PATH_PREFIX, action); Actions.connect(item, action, false); menu.add(item); item = new JMenuItem(); action = (Action) SystemAction.get(SetTrackingAction.class); Utils.setAcceleratorBindings(Annotator.ACTIONS_PATH_PREFIX, action); Actions.connect(item, action, false); menu.add(item); menu.addSeparator(); item = new JMenuItem(); action = (Action) SystemAction.get(CreateTagAction.class); Utils.setAcceleratorBindings(Annotator.ACTIONS_PATH_PREFIX, action); Actions.connect(item, action, false); menu.add(item); item = new JMenuItem(); action = (Action) SystemAction.get(ManageTagsAction.class); Utils.setAcceleratorBindings(Annotator.ACTIONS_PATH_PREFIX, action); Actions.connect(item, action, false); menu.add(item); menu.addSeparator(); item = new JMenuItem(); action = (Action) SystemAction.get(MergeRevisionAction.class); Utils.setAcceleratorBindings(Annotator.ACTIONS_PATH_PREFIX, action); Actions.connect(item, action, false); menu.add(item); item = new JMenuItem(); action = (Action) SystemAction.get(RebaseAction.class); Utils.setAcceleratorBindings(Annotator.ACTIONS_PATH_PREFIX, action); Actions.connect(item, action, false); menu.add(item); item = new JMenuItem(); action = (Action) SystemAction.get(CherryPickAction.class); Utils.setAcceleratorBindings(Annotator.ACTIONS_PATH_PREFIX, action); Actions.connect(item, action, false); menu.add(item); } else { item = menu.add(SystemActionBridge.createAction(SystemAction.get(CreateBranchAction.class), NbBundle.getMessage(CreateBranchAction.class, "LBL_CreateBranchAction_PopupName"), lkp)); //NOI18N org.openide.awt.Mnemonics.setLocalizedText(item, item.getText()); item = menu.add(SystemActionBridge.createAction(SystemAction.get(SwitchBranchAction.class), NbBundle.getMessage(SwitchBranchAction.class, "LBL_SwitchBranchAction_PopupName"), lkp)); //NOI18N org.openide.awt.Mnemonics.setLocalizedText(item, item.getText()); if (ctx != null) { File repositoryRoot = null; Set<File> repositoryRoots = GitUtils.getRepositoryRoots(ctx); if (repositoryRoots.size() == 1) { repositoryRoot = repositoryRoots.iterator().next(); } if (repositoryRoot != null) { RepositoryInfo info = RepositoryInfo.getInstance(repositoryRoot); GitBranch branch = info.getActiveBranch(); List<String> recentlySwitched = Utils.getStringList(NbPreferences.forModule(BranchMenu.class), AbstractCheckoutAction.PREF_KEY_RECENT_BRANCHES + repositoryRoot.getAbsolutePath()); int index = 0; for (String recentBranch : recentlySwitched) { if (recentBranch.equals(branch.getName())) { continue; } menu.add(new SwitchBranchAction.KnownBranchAction(recentBranch, ctx)); if (++index > 2) { break; } } } } item = menu.add(SystemActionBridge.createAction(SystemAction.get(SetTrackingAction.class), NbBundle.getMessage(SetTrackingAction.class, "LBL_SetTrackingAction_PopupName"), lkp)); //NOI18N org.openide.awt.Mnemonics.setLocalizedText(item, item.getText()); menu.addSeparator(); item = menu.add(SystemActionBridge.createAction(SystemAction.get(CreateTagAction.class), NbBundle.getMessage(CreateTagAction.class, "LBL_CreateTagAction_PopupName"), lkp)); //NOI18N org.openide.awt.Mnemonics.setLocalizedText(item, item.getText()); item = menu.add(SystemActionBridge.createAction(SystemAction.get(ManageTagsAction.class), NbBundle.getMessage(ManageTagsAction.class, "LBL_ManageTagsAction_PopupName"), lkp)); //NOI18N org.openide.awt.Mnemonics.setLocalizedText(item, item.getText()); menu.addSeparator(); item = menu.add(SystemActionBridge.createAction(SystemAction.get(MergeRevisionAction.class), NbBundle.getMessage(MergeRevisionAction.class, "LBL_MergeRevisionAction_PopupName"), lkp)); //NOI18N org.openide.awt.Mnemonics.setLocalizedText(item, item.getText()); item = menu.add(SystemActionBridge.createAction(SystemAction.get(RebaseAction.class), NbBundle.getMessage(RebaseAction.class, "LBL_RebaseAction_PopupName"), lkp)); //NOI18N org.openide.awt.Mnemonics.setLocalizedText(item, item.getText()); item = menu.add(SystemActionBridge.createAction(SystemAction.get(CherryPickAction.class), NbBundle.getMessage(CherryPickAction.class, "LBL_CherryPickAction_PopupName"), lkp)); //NOI18N org.openide.awt.Mnemonics.setLocalizedText(item, item.getText()); } return menu; } }
3,810
548
<reponame>neechadi/django-basic-apps from django.db.models import Q from django.utils import simplejson as json from django.http import HttpResponse def auto_complete(request, queryset, fields=None): """ Returns a JSON list to be used with the AutoCompleteWidget javascript. Example: url(r'^autocomplete/$', view='basic.tools.views.generic.auto_complete', kwargs={ 'queryset': Author.objects.all() 'fields': ('first_name__icontains', 'last_name__icontains') } ) """ object_list = [] limit = request.GET.get('limit', 10) query = request.GET.get('term', '') if fields: q_object = Q() for field in fields: q_object |= Q(**{field: query}) queryset = queryset.filter(q_object) for obj in queryset[:limit]: object_list.append({'text': obj.__unicode__(), 'id': obj.pk}) return HttpResponse(json.dumps(object_list), mimetype='application/json')
437
335
{ "word": "Grave", "definitions": [ "Engrave (an inscription or image) on a surface.", "Fix (something) indelibly in the mind." ], "parts-of-speech": "Verb" }
84
3,358
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 <NAME> This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <<EMAIL>>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ql/experimental/commodities/dateinterval.hpp> namespace QuantLib { std::ostream& operator<<(std::ostream& out, const DateInterval& di) { if (di.startDate_ == Date() || di.endDate_ == Date()) return out << "Null<DateInterval>()"; return out << di.startDate_ << " to " << di.endDate_; } }
350
307
<reponame>ConnectionMaster/qgis-earthengine-plugin import ee from ee_plugin import Map from ee_plugin.contrib import utils, palettes Map.setCenter(4.408241, 52.177595, 18) dem = ee.Image("AHN/AHN2_05M_RUW") \ .resample('bicubic') \ .convolve(ee.Kernel.gaussian(0.5, 0.25, 'meters')) # palette = palettes.crameri['lisbon'][50] palette = palettes.crameri['oleron'][50] # palette = palettes.crameri['roma'][50].slice(0).reverse() demRGB = dem.visualize(**{ 'min': -5, 'max': 15, 'palette': palette }) weight = 0.4 # wegith of Hillshade vs RGB intensity (0 - flat, 1 - HS) exaggeration = 5 # vertical exaggeration azimuth = 315 # Sun azimuth zenith = 20 # Sun elevation brightness = -0.05 # 0 - default contrast = 0.05 # 0 - default saturation = 0.8 # 1 - default castShadows = False # no shadows rgb = utils.hillshadeRGB(demRGB, dem, weight, exaggeration, azimuth, zenith, contrast, brightness, saturation, castShadows) Map.addLayer(rgb, {}, 'DEM (no shadows)', False) # with shadows castShadows = True rgb = utils.hillshadeRGB(demRGB, dem, weight, exaggeration, azimuth, zenith, contrast, brightness, saturation, castShadows) Map.addLayer(rgb, {}, 'DEM') Map.addLayer(dem, {}, 'DEM (raw)', false)
460
484
package com.kbeanie.multipicker.api.entity; import android.media.ExifInterface; import android.os.Parcel; /** * Contains details about the image that was chosen */ public class ChosenImage extends ChosenFile { private int orientation; private String thumbnailPath; private String thumbnailSmallPath; private int width; private int height; public ChosenImage(){ } protected ChosenImage(Parcel in) { super(in); this.orientation = in.readInt(); this.thumbnailPath = in.readString(); this.thumbnailSmallPath = in.readString(); this.width = in.readInt(); this.height = in.readInt(); } public static final Creator<ChosenImage> CREATOR = new Creator<ChosenImage>() { @Override public ChosenImage createFromParcel(Parcel in) { return new ChosenImage(in); } @Override public ChosenImage[] newArray(int size) { return new ChosenImage[size]; } }; /** * Get orientation of the actual image * * @return */ public int getOrientation() { return orientation; } public void setOrientation(int orientation) { this.orientation = orientation; } /** * Get the path to the thumbnail(big) of the image * * @return */ public String getThumbnailPath() { return thumbnailPath; } public void setThumbnailPath(String thumbnailPath) { this.thumbnailPath = thumbnailPath; } /** * Get the path to the thumbnail(small) of the image * * @return */ public String getThumbnailSmallPath() { return thumbnailSmallPath; } public void setThumbnailSmallPath(String thumbnailSmallPath) { this.thumbnailSmallPath = thumbnailSmallPath; } /** * Get the image width * * @return */ public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } /** * Get the image height; * * @return */ public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } private final static String STRING_FORMAT = "Height: %s, Width: %s, Orientation: %s"; @Override public String toString() { return super.toString() + " " + String.format(STRING_FORMAT, height, width, getOrientationName()); } /** * Get Orientation user friendly label * * @return */ public String getOrientationName() { String orientationName = "NORMAL"; switch (orientation) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: orientationName = "FLIP_HORIZONTAL"; break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: orientationName = "FLIP_VERTICAL"; break; case ExifInterface.ORIENTATION_ROTATE_90: orientationName = "ROTATE_90"; break; case ExifInterface.ORIENTATION_ROTATE_180: orientationName = "ROTATE_180"; break; case ExifInterface.ORIENTATION_ROTATE_270: orientationName = "ROTATE_270"; break; case ExifInterface.ORIENTATION_TRANSPOSE: orientationName = "TRANSPOSE"; break; case ExifInterface.ORIENTATION_TRANSVERSE: orientationName = "TRANSVERSE"; break; case ExifInterface.ORIENTATION_UNDEFINED: orientationName = "UNDEFINED"; break; } return orientationName; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(orientation); dest.writeString(thumbnailPath); dest.writeString(thumbnailSmallPath); dest.writeInt(width); dest.writeInt(height); } }
1,789
587
package org.lightadmin.test.model; import org.lightadmin.demo.model.AbstractEntity; import javax.persistence.Entity; import javax.persistence.ManyToMany; import javax.validation.constraints.NotNull; import java.util.Set; @Entity public class TestDiscountProgram extends AbstractEntity { @NotNull private String name; @ManyToMany( mappedBy = "discountPrograms" ) private Set<TestCustomer> customers; public String getName() { return name; } public void setName( final String name ) { this.name = name; } public Set<TestCustomer> getCustomers() { return customers; } public void setCustomers( final Set<TestCustomer> testCustomers ) { this.customers = testCustomers; } }
229
372
<reponame>yoshi-code-bot/google-api-java-client-services<gh_stars>100-1000 /* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.gmail.model; /** * Settings associated with a send-as alias, which can be either the primary login address * associated with the account or a custom "from" address. Send-as aliases correspond to the "Send * Mail As" feature in the web interface. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Gmail API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class SendAs extends com.google.api.client.json.GenericJson { /** * A name that appears in the "From:" header for mail sent using this alias. For custom "from" * addresses, when this is empty, Gmail will populate the "From:" header with the name that is * used for the primary address associated with the account. If the admin has disabled the ability * for users to update their name format, requests to update this field for the primary login will * silently fail. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String displayName; /** * Whether this address is selected as the default "From:" address in situations such as composing * a new message or sending a vacation auto-reply. Every Gmail account has exactly one default * send-as address, so the only legal value that clients may write to this field is `true`. * Changing this from `false` to `true` for an address will result in this field becoming `false` * for the other previous default address. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean isDefault; /** * Whether this address is the primary address used to login to the account. Every Gmail account * has exactly one primary address, and it cannot be deleted from the collection of send-as * aliases. This field is read-only. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean isPrimary; /** * An optional email address that is included in a "Reply-To:" header for mail sent using this * alias. If this is empty, Gmail will not generate a "Reply-To:" header. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String replyToAddress; /** * The email address that appears in the "From:" header for mail sent using this alias. This is * read-only for all operations except create. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String sendAsEmail; /** * An optional HTML signature that is included in messages composed with this alias in the Gmail * web UI. This signature is added to new emails only. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String signature; /** * An optional SMTP service that will be used as an outbound relay for mail sent using this alias. * If this is empty, outbound mail will be sent directly from Gmail's servers to the destination * SMTP service. This setting only applies to custom "from" aliases. * The value may be {@code null}. */ @com.google.api.client.util.Key private SmtpMsa smtpMsa; /** * Whether Gmail should treat this address as an alias for the user's primary email address. This * setting only applies to custom "from" aliases. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean treatAsAlias; /** * Indicates whether this address has been verified for use as a send-as alias. Read-only. This * setting only applies to custom "from" aliases. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String verificationStatus; /** * A name that appears in the "From:" header for mail sent using this alias. For custom "from" * addresses, when this is empty, Gmail will populate the "From:" header with the name that is * used for the primary address associated with the account. If the admin has disabled the ability * for users to update their name format, requests to update this field for the primary login will * silently fail. * @return value or {@code null} for none */ public java.lang.String getDisplayName() { return displayName; } /** * A name that appears in the "From:" header for mail sent using this alias. For custom "from" * addresses, when this is empty, Gmail will populate the "From:" header with the name that is * used for the primary address associated with the account. If the admin has disabled the ability * for users to update their name format, requests to update this field for the primary login will * silently fail. * @param displayName displayName or {@code null} for none */ public SendAs setDisplayName(java.lang.String displayName) { this.displayName = displayName; return this; } /** * Whether this address is selected as the default "From:" address in situations such as composing * a new message or sending a vacation auto-reply. Every Gmail account has exactly one default * send-as address, so the only legal value that clients may write to this field is `true`. * Changing this from `false` to `true` for an address will result in this field becoming `false` * for the other previous default address. * @return value or {@code null} for none */ public java.lang.Boolean getIsDefault() { return isDefault; } /** * Whether this address is selected as the default "From:" address in situations such as composing * a new message or sending a vacation auto-reply. Every Gmail account has exactly one default * send-as address, so the only legal value that clients may write to this field is `true`. * Changing this from `false` to `true` for an address will result in this field becoming `false` * for the other previous default address. * @param isDefault isDefault or {@code null} for none */ public SendAs setIsDefault(java.lang.Boolean isDefault) { this.isDefault = isDefault; return this; } /** * Whether this address is the primary address used to login to the account. Every Gmail account * has exactly one primary address, and it cannot be deleted from the collection of send-as * aliases. This field is read-only. * @return value or {@code null} for none */ public java.lang.Boolean getIsPrimary() { return isPrimary; } /** * Whether this address is the primary address used to login to the account. Every Gmail account * has exactly one primary address, and it cannot be deleted from the collection of send-as * aliases. This field is read-only. * @param isPrimary isPrimary or {@code null} for none */ public SendAs setIsPrimary(java.lang.Boolean isPrimary) { this.isPrimary = isPrimary; return this; } /** * An optional email address that is included in a "Reply-To:" header for mail sent using this * alias. If this is empty, Gmail will not generate a "Reply-To:" header. * @return value or {@code null} for none */ public java.lang.String getReplyToAddress() { return replyToAddress; } /** * An optional email address that is included in a "Reply-To:" header for mail sent using this * alias. If this is empty, Gmail will not generate a "Reply-To:" header. * @param replyToAddress replyToAddress or {@code null} for none */ public SendAs setReplyToAddress(java.lang.String replyToAddress) { this.replyToAddress = replyToAddress; return this; } /** * The email address that appears in the "From:" header for mail sent using this alias. This is * read-only for all operations except create. * @return value or {@code null} for none */ public java.lang.String getSendAsEmail() { return sendAsEmail; } /** * The email address that appears in the "From:" header for mail sent using this alias. This is * read-only for all operations except create. * @param sendAsEmail sendAsEmail or {@code null} for none */ public SendAs setSendAsEmail(java.lang.String sendAsEmail) { this.sendAsEmail = sendAsEmail; return this; } /** * An optional HTML signature that is included in messages composed with this alias in the Gmail * web UI. This signature is added to new emails only. * @return value or {@code null} for none */ public java.lang.String getSignature() { return signature; } /** * An optional HTML signature that is included in messages composed with this alias in the Gmail * web UI. This signature is added to new emails only. * @param signature signature or {@code null} for none */ public SendAs setSignature(java.lang.String signature) { this.signature = signature; return this; } /** * An optional SMTP service that will be used as an outbound relay for mail sent using this alias. * If this is empty, outbound mail will be sent directly from Gmail's servers to the destination * SMTP service. This setting only applies to custom "from" aliases. * @return value or {@code null} for none */ public SmtpMsa getSmtpMsa() { return smtpMsa; } /** * An optional SMTP service that will be used as an outbound relay for mail sent using this alias. * If this is empty, outbound mail will be sent directly from Gmail's servers to the destination * SMTP service. This setting only applies to custom "from" aliases. * @param smtpMsa smtpMsa or {@code null} for none */ public SendAs setSmtpMsa(SmtpMsa smtpMsa) { this.smtpMsa = smtpMsa; return this; } /** * Whether Gmail should treat this address as an alias for the user's primary email address. This * setting only applies to custom "from" aliases. * @return value or {@code null} for none */ public java.lang.Boolean getTreatAsAlias() { return treatAsAlias; } /** * Whether Gmail should treat this address as an alias for the user's primary email address. This * setting only applies to custom "from" aliases. * @param treatAsAlias treatAsAlias or {@code null} for none */ public SendAs setTreatAsAlias(java.lang.Boolean treatAsAlias) { this.treatAsAlias = treatAsAlias; return this; } /** * Indicates whether this address has been verified for use as a send-as alias. Read-only. This * setting only applies to custom "from" aliases. * @return value or {@code null} for none */ public java.lang.String getVerificationStatus() { return verificationStatus; } /** * Indicates whether this address has been verified for use as a send-as alias. Read-only. This * setting only applies to custom "from" aliases. * @param verificationStatus verificationStatus or {@code null} for none */ public SendAs setVerificationStatus(java.lang.String verificationStatus) { this.verificationStatus = verificationStatus; return this; } @Override public SendAs set(String fieldName, Object value) { return (SendAs) super.set(fieldName, value); } @Override public SendAs clone() { return (SendAs) super.clone(); } }
3,533
4,901
<gh_stars>1000+ /* * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * Defines buffers, which are containers for data, and provides an overview of the * other NIO packages. * * * <p> The central abstractions of the NIO APIs are: </p> * * <ul> * * <li><p> <a href="#buffers"><i>Buffers</i></a>, which are containers for data; * </p></li> * * <li><p> <a href="charset/package-summary.html"><i>Charsets</i></a> and their * associated <i>decoders</i> and <i>encoders</i>, <br> which translate between * bytes and Unicode characters; </p></li> * * <li><p> <a href="channels/package-summary.html"><i>Channels</i></a> of * various types, which represent connections <br> to entities capable of * performing I/O operations; and </p></li> * * <li><p> <i>Selectors</i> and <i>selection keys</i>, which together with <br> * <i>selectable channels</i> define a <a * href="channels/package-summary.html#multiplex">multiplexed, non-blocking <br> * I/O</a>&nbsp;facility. </p></li> * * </ul> * * <p> The <tt>java.nio</tt> package defines the buffer classes, which are used * throughout the NIO APIs. The charset API is defined in the {@link * java.nio.charset} package, and the channel and selector APIs are defined in the * {@link java.nio.channels} package. Each of these subpackages has its own * service-provider (SPI) subpackage, the contents of which can be used to extend * the platform's default implementations or to construct alternative * implementations. * * * <a name="buffers"> * * <blockquote><table cellspacing=1 cellpadding=0 summary="Description of the various buffers"> * <tr><th><p align="left">Buffers</p></th><th><p align="left">Description</p></th></tr> * <tr><td valign=top><tt>{@link java.nio.Buffer}</tt></td> * <td>Position, limit, and capacity; * <br>clear, flip, rewind, and mark/reset</td></tr> * <tr><td valign=top><tt>&nbsp;&nbsp;{@link java.nio.ByteBuffer}</tt></td> * <td>Get/put, compact, views; allocate,&nbsp;wrap</td></tr> * <tr><td valign=top><tt>&nbsp;&nbsp;&nbsp;&nbsp;{@link java.nio.MappedByteBuffer}&nbsp;&nbsp;</tt></td> * <td>A byte buffer mapped to a file</td></tr> * <tr><td valign=top><tt>&nbsp;&nbsp;{@link java.nio.CharBuffer}</tt></td> * <td>Get/put, compact; allocate,&nbsp;wrap</td></tr> * <tr><td valign=top><tt>&nbsp;&nbsp;{@link java.nio.DoubleBuffer}</tt></td> * <td>&nbsp;&nbsp;&nbsp;&nbsp;'&nbsp;'</td></tr> * <tr><td valign=top><tt>&nbsp;&nbsp;{@link java.nio.FloatBuffer}</tt></td> * <td>&nbsp;&nbsp;&nbsp;&nbsp;'&nbsp;'</td></tr> * <tr><td valign=top><tt>&nbsp;&nbsp;{@link java.nio.IntBuffer}</tt></td> * <td>&nbsp;&nbsp;&nbsp;&nbsp;'&nbsp;'</td></tr> * <tr><td valign=top><tt>&nbsp;&nbsp;{@link java.nio.LongBuffer}</tt></td> * <td>&nbsp;&nbsp;&nbsp;&nbsp;'&nbsp;'</td></tr> * <tr><td valign=top><tt>&nbsp;&nbsp;{@link java.nio.ShortBuffer}</tt></td> * <td>&nbsp;&nbsp;&nbsp;&nbsp;'&nbsp;'</td></tr> * <tr><td valign=top><tt>{@link java.nio.ByteOrder}</tt></td> * <td>Typesafe enumeration for&nbsp;byte&nbsp;orders</td></tr> * </table></blockquote> * * <p> A <i>buffer</i> is a container for a fixed amount of data of a specific * primitive type. In addition to its content a buffer has a <i>position</i>, * which is the index of the next element to be read or written, and a * <i>limit</i>, which is the index of the first element that should not be read * or written. The base {@link java.nio.Buffer} class defines these properties as * well as methods for <i>clearing</i>, <i>flipping</i>, and <i>rewinding</i>, for * <i>marking</i> the current position, and for <i>resetting</i> the position to * the previous mark. * * <p> There is a buffer class for each non-boolean primitive type. Each class * defines a family of <i>get</i> and <i>put</i> methods for moving data out of * and in to a buffer, methods for <i>compacting</i>, <i>duplicating</i>, and * <i>slicing</i> a buffer, and static methods for <i>allocating</i> a new buffer * as well as for <i>wrapping</i> an existing array into a buffer. * * <p> Byte buffers are distinguished in that they can be used as the sources and * targets of I/O operations. They also support several features not found in the * other buffer classes: * * <ul> * * <li><p> A byte buffer can be allocated as a <a href="ByteBuffer.html#direct"> * <i>direct</i></a> buffer, in which case the Java virtual machine will make a * best effort to perform native I/O operations directly upon it. </p></li> * * <li><p> A byte buffer can be created by {@link * java.nio.channels.FileChannel#map </code><i>mapping</i><code>} a region of a * file directly into memory, in which case a few additional file-related * operations defined in the {@link java.nio.MappedByteBuffer} class are * available. </p></li> * * <li><p> A byte buffer provides access to its content as either a heterogeneous * or homogeneous sequence of <a href="ByteBuffer.html#bin">binary data</i></a> * of any non-boolean primitive type, in either big-endian or little-endian <a * href="ByteOrder.html">byte order</a>. </p></li> * * </ul> * * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor * or method in any class or interface in this package will cause a {@link * java.lang.NullPointerException NullPointerException} to be thrown. * * @since 1.4 * @author <NAME> * @author JSR-51 Expert Group */ package java.nio;
2,376
3,012
<gh_stars>1000+ /** @file Capsule Architectural Protocol as defined in PI1.0a Specification VOLUME 2 DXE The DXE Driver that produces this protocol must be a runtime driver. The driver is responsible for initializing the CapsuleUpdate() and QueryCapsuleCapabilities() fields of the UEFI Runtime Services Table. After the two fields of the UEFI Runtime Services Table have been initialized, the driver must install the EFI_CAPSULE_ARCH_PROTOCOL_GUID on a new handle with a NULL interface pointer. The installation of this protocol informs the DXE Foundation that the Capsule related services are now available and that the DXE Foundation must update the 32-bit CRC of the UEFI Runtime Services Table. Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __ARCH_PROTOCOL_CAPSULE_ARCH_H__ #define __ARCH_PROTOCOL_CAPSULE_ARCH_H__ // // Global ID for the Capsule Architectural Protocol // #define EFI_CAPSULE_ARCH_PROTOCOL_GUID \ { 0x5053697e, 0x2cbc, 0x4819, {0x90, 0xd9, 0x05, 0x80, 0xde, 0xee, 0x57, 0x54 }} extern EFI_GUID gEfiCapsuleArchProtocolGuid; #endif
408
1,107
<gh_stars>1000+ /* * File : semaphore.h * This file is part of RT-Thread RTOS * COPYRIGHT (C) 2006 - 2010, RT-Thread Development Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Change Logs: * Date Author Notes * 2010-10-26 Bernard the first version */ #ifndef __POSIX_SEMAPHORE_H__ #define __POSIX_SEMAPHORE_H__ #include <rtthread.h> #include <pthread.h> struct posix_sem { /* reference count and unlinked */ rt_uint16_t refcount; rt_uint8_t unlinked; rt_uint8_t unamed; /* RT-Thread semaphore */ rt_sem_t sem; /* next posix semaphore */ struct posix_sem* next; }; typedef struct posix_sem sem_t; int sem_close(sem_t *sem); int sem_destroy(sem_t *sem); int sem_getvalue(sem_t *sem, int *sval); int sem_init(sem_t *sem, int pshared, unsigned int value); sem_t *sem_open(const char *name, int oflag, ...); int sem_post(sem_t *sem); int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout); int sem_trywait(sem_t *sem); int sem_unlink(const char *name); int sem_wait(sem_t *sem); #endif
626
923
package core.cli.server.handlers; import java.io.IOException; import java.util.logging.Logger; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.nio.protocol.HttpAsyncExchange; import org.apache.http.protocol.HttpContext; import argo.jdom.JsonNode; import core.cli.messages.TaskGroupMessage; import core.cli.messages.TaskIdentifier; import core.cli.server.CliRpcCodec; import core.userDefinedTask.TaskGroup; import core.userDefinedTask.UserDefinedAction; import core.webui.webcommon.HttpHandlerWithBackend; public abstract class TaskActionHandler extends HttpHandlerWithBackend { private static final Logger LOGGER = Logger.getLogger(TaskActionHandler.class.getName()); private static final String ACCEPTED_METHOD = "POST"; @Override protected void handleWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod(); if (!method.equalsIgnoreCase(ACCEPTED_METHOD)) { LOGGER.warning("Ignoring request with unknown method " + method); CliRpcCodec.prepareResponse(exchange, 400, "Method must be " + ACCEPTED_METHOD); return; } JsonNode requestData = CliRpcCodec.decodeRequest(getRequestBody(request)); if (requestData == null) { LOGGER.warning("Failed to parse request into JSON!"); CliRpcCodec.prepareResponse(exchange, 400, "Cannot parse request!"); return; } handleTaskActionWithBackend(exchange, requestData); } protected abstract Void handleTaskActionWithBackend(HttpAsyncExchange exchange, JsonNode request) throws IOException; protected UserDefinedAction getTask(TaskGroup group, TaskIdentifier taskIdentifier) { UserDefinedAction task = null; if (group != null) { task = group.getTask(taskIdentifier.getTask().getIndex()); if (task == null) { task = group.getTaskByName(taskIdentifier.getTask().getName()); } return task; } return backEndHolder.getTaskByName(taskIdentifier.getTask().getName()); } protected TaskGroup getGroup(TaskIdentifier taskIdentifier) { return getGroup(taskIdentifier.getGroup()); } protected TaskGroup getGroup(TaskGroupMessage taskGroup) { int index = taskGroup.getIndex(); String name = taskGroup.getName(); if (index == TaskGroupMessage.UNKNOWN_INDEX && name.isEmpty()) { index = 0; } TaskGroup group = null; if (taskGroup != null) { group = backEndHolder.getTaskGroup(index); if (group == null) { group = backEndHolder.getTaskGroupFromName(name); } } return group; } }
855
471
package org.plantuml.idea.grammar.psi; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFileFactory; import org.plantuml.idea.lang.PlantUmlFileImpl; import org.plantuml.idea.lang.PlantUmlFileType; public class PumlElementFactory { public static PumlItem createWord(Project project, String name) { final PlantUmlFileImpl file = createFile(project, name); return (PumlItem) file.getFirstChild(); } public static PlantUmlFileImpl createFile(Project project, String text) { String name = "dummy.puml"; return (PlantUmlFileImpl) PsiFileFactory.getInstance(project).createFileFromText(name, PlantUmlFileType.INSTANCE, text); } public static PsiElement createCRLF(Project project) { final PlantUmlFileImpl file = createFile(project, "\n"); return file.getFirstChild(); } }
338
335
{ "word": "Lap", "definitions": [ "The flat area between the waist and knees of a seated person.", "The part of an item of clothing, especially a skirt or dress, covering the lap.", "A hanging flap on a garment or a saddle." ], "parts-of-speech": "Noun" }
111