max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
335
<filename>C/Cinematograph_noun.json { "word": "Cinematograph", "definitions": [ "An apparatus for showing motion-picture films." ], "parts-of-speech": "Noun" }
78
4,339
<filename>modules/core/src/main/java/org/apache/ignite/client/ClientCluster.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.client; import org.apache.ignite.cluster.ClusterState; /** * Thin client cluster facade. Represents whole cluster (all available nodes). */ public interface ClientCluster extends ClientClusterGroup { /** * Gets current cluster state. * * @return Current cluster state. */ public ClusterState state(); /** * Changes current cluster state to given {@code newState} cluster state. * <p> * <b>NOTE:</b> * Deactivation clears in-memory caches (without persistence) including the system caches. * * @param newState New cluster state. * @throws ClientException If change state operation failed. */ public void state(ClusterState newState) throws ClientException; /** * Disables write-ahead logging for specified cache. When WAL is disabled, changes are not logged to disk. * This significantly improves cache update speed. The drawback is absence of local crash-recovery guarantees. * If node is crashed, local content of WAL-disabled cache will be cleared on restart to avoid data corruption. * <p> * Internally this method will wait for all current cache operations to finish and prevent new cache operations * from being executed. Then checkpoint is initiated to flush all data to disk. Control is returned to the callee * when all dirty pages are prepared for checkpoint, but not necessarily flushed to disk. * <p> * WAL state can be changed only for persistent caches. * * @param cacheName Cache name. * @return Whether WAL disabled by this call. * @throws ClientException If error occurs. * @see #enableWal(String) * @see #isWalEnabled(String) */ public boolean disableWal(String cacheName) throws ClientException; /** * Enables write-ahead logging for specified cache. Restoring crash-recovery guarantees of a previous call to * {@link #disableWal(String)}. * <p> * Internally this method will wait for all current cache operations to finish and prevent new cache operations * from being executed. Then checkpoint is initiated to flush all data to disk. Control is returned to the callee * when all data is persisted to disk. * <p> * WAL state can be changed only for persistent caches. * * @param cacheName Cache name. * @return Whether WAL enabled by this call. * @throws ClientException If error occurs. * @see #disableWal(String) * @see #isWalEnabled(String) */ public boolean enableWal(String cacheName) throws ClientException; /** * Checks if write-ahead logging is enabled for specified cache. * * @param cacheName Cache name. * @return {@code True} if WAL is enabled for cache. * @see #disableWal(String) * @see #enableWal(String) */ public boolean isWalEnabled(String cacheName); }
1,130
642
<reponame>remaininlight/axiom #pragma once #include <QtWidgets/QDialog> namespace AxiomGui { class AboutWindow : public QDialog { Q_OBJECT public: AboutWindow(); }; }
87
1,767
package com.annimon.stream.streamtests; import com.annimon.stream.Functions; import com.annimon.stream.Stream; import com.annimon.stream.function.Predicate; import com.annimon.stream.test.hamcrest.StreamMatcher; import org.junit.Test; import static com.annimon.stream.test.hamcrest.StreamMatcher.assertElements; import static org.hamcrest.Matchers.contains; public final class TakeUntilTest { @Test public void testTakeUntil() { Stream.of(2, 4, 6, 7, 8, 10, 11) .takeUntil(Predicate.Util.negate(Functions.remainder(2))) .custom(assertElements(contains( 2, 4, 6, 7 ))); } @Test public void testTakeUntilOnEmptyStream() { Stream.<Integer>empty() .takeUntil(Functions.remainder(2)) .custom(StreamMatcher.<Integer>assertIsEmpty()); } }
391
2,757
/** @file Definitions for memory allocation routines: calloc, malloc, realloc, free. The order and contiguity of storage allocated by successive calls to the calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer of any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly freed or reallocated). Each such allocation shall yield a pointer to an object disjoint from any other object. The pointer returned points to the start (lowest byte address) of the allocated space. If the space can not be allocated, a null pointer is returned. If the size of the space requested is zero, the behavior is implementation-defined; the value returned shall be either a null pointer or a unique pointer. The value of a pointer that refers to freed space is indeterminate. Copyright (c) 2010 - 2014, 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. */ #include <Uefi.h> #include <Library/MemoryAllocationLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/BaseLib.h> #include <Library/BaseMemoryLib.h> #include <Library/DebugLib.h> #include <LibConfig.h> #include <assert.h> #include <stdlib.h> #include <errno.h> #define CPOOL_HEAD_SIGNATURE SIGNATURE_32('C','p','h','d') /** The UEFI functions do not provide a way to determine the size of an allocated region of memory given just a pointer to the start of that region. Since this is required for the implementation of realloc, the memory head structure, CPOOL_HEAD, containing the necessary information is prepended to the requested space. The order of members is important. This structure is 8-byte aligned, as per the UEFI specification for memory allocation functions. By specifying Size as a 64-bit value and placing it immediately before Data, it ensures that Data will always be 8-byte aligned. On IA32 systems, this structure is 24 bytes long, excluding Data. On X64 systems, this structure is 32 bytes long, excluding Data. **/ typedef struct { LIST_ENTRY List; UINT32 Signature; UINT64 Size; CHAR8 Data[1]; } CPOOL_HEAD; // List of memory allocated by malloc/calloc/etc. static LIST_ENTRY MemPoolHead = INITIALIZE_LIST_HEAD_VARIABLE(MemPoolHead); /****************************/ /** The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate. This implementation uses the UEFI memory allocation boot services to get a region of memory that is 8-byte aligned and of the specified size. The region is allocated with type EfiLoaderData. @param size Size, in bytes, of the region to allocate. @return NULL is returned if the space could not be allocated and errno contains the cause. Otherwise, a pointer to an 8-byte aligned region of the requested size is returned.<BR> If NULL is returned, errno may contain: - EINVAL: Requested Size is zero. - ENOMEM: Memory could not be allocated. **/ void * malloc(size_t Size) { CPOOL_HEAD *Head; void *RetVal; EFI_STATUS Status; UINTN NodeSize; if( Size == 0) { errno = EINVAL; // Make errno diffenent, just in case of a lingering ENOMEM. DEBUG((DEBUG_ERROR, "ERROR malloc: Zero Size\n")); return NULL; } NodeSize = (UINTN)(Size + sizeof(CPOOL_HEAD)); DEBUG((DEBUG_POOL, "malloc(%d): NodeSz: %d", Size, NodeSize)); Status = gBS->AllocatePool( EfiLoaderData, NodeSize, (void**)&Head); if( Status != EFI_SUCCESS) { RetVal = NULL; errno = ENOMEM; DEBUG((DEBUG_ERROR, "\nERROR malloc: AllocatePool returned %r\n", Status)); } else { assert(Head != NULL); // Fill out the pool header Head->Signature = CPOOL_HEAD_SIGNATURE; Head->Size = NodeSize; // Add this node to the list (void)InsertTailList(&MemPoolHead, (LIST_ENTRY *)Head); // Return a pointer to the data RetVal = (void*)Head->Data; DEBUG((DEBUG_POOL, " Head: %p, Returns %p\n", Head, RetVal)); } return RetVal; } /** The calloc function allocates space for an array of Num objects, each of whose size is Size. The space is initialized to all bits zero. This implementation uses the UEFI memory allocation boot services to get a region of memory that is 8-byte aligned and of the specified size. The region is allocated with type EfiLoaderData. @param Num Number of objects to allocate. @param Size Size, in bytes, of the objects to allocate space for. @return NULL is returned if the space could not be allocated and errno contains the cause. Otherwise, a pointer to an 8-byte aligned region of the requested size is returned. **/ void * calloc(size_t Num, size_t Size) { void *RetVal; size_t NumSize; NumSize = Num * Size; RetVal = NULL; if (NumSize != 0) { RetVal = malloc(NumSize); if( RetVal != NULL) { (VOID)ZeroMem( RetVal, NumSize); } } DEBUG((DEBUG_POOL, "0x%p = calloc(%d, %d)\n", RetVal, Num, Size)); return RetVal; } /** The free function causes the space pointed to by Ptr to be deallocated, that is, made available for further allocation. If Ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined. @param Ptr Pointer to a previously allocated region of memory to be freed. **/ void free(void *Ptr) { CPOOL_HEAD *Head; Head = BASE_CR(Ptr, CPOOL_HEAD, Data); assert(Head != NULL); DEBUG((DEBUG_POOL, "free(%p): Head: %p\n", Ptr, Head)); if(Ptr != NULL) { if (Head->Signature == CPOOL_HEAD_SIGNATURE) { (void) RemoveEntryList((LIST_ENTRY *)Head); // Remove this node from the malloc pool (void) gBS->FreePool (Head); // Now free the associated memory } else { errno = EFAULT; DEBUG((DEBUG_ERROR, "ERROR free(0x%p): Signature is 0x%8X, expected 0x%8X\n", Ptr, Head->Signature, CPOOL_HEAD_SIGNATURE)); } } DEBUG((DEBUG_POOL, "free Done\n")); } /** The realloc function changes the size of the object pointed to by Ptr to the size specified by NewSize. The contents of the object are unchanged up to the lesser of the new and old sizes. If the new size is larger, the value of the newly allocated portion of the object is indeterminate. If Ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. If Ptr does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If the space cannot be allocated, the object pointed to by Ptr is unchanged. If NewSize is zero and Ptr is not a null pointer, the object it points to is freed. This implementation uses the UEFI memory allocation boot services to get a region of memory that is 8-byte aligned and of the specified size. The region is allocated with type EfiLoaderData. The following combinations of Ptr and NewSize can occur:<BR> Ptr NewSize<BR> -------- -------------------<BR> - NULL 0 Returns NULL; - NULL > 0 Same as malloc(NewSize) - invalid X Returns NULL; - valid NewSize >= OldSize Returns malloc(NewSize) with Oldsize bytes copied from Ptr - valid NewSize < OldSize Returns new buffer with Oldsize bytes copied from Ptr - valid 0 Return NULL. Frees Ptr. @param Ptr Pointer to a previously allocated region of memory to be resized. @param NewSize Size, in bytes, of the new object to allocate space for. @return NULL is returned if the space could not be allocated and errno contains the cause. Otherwise, a pointer to an 8-byte aligned region of the requested size is returned. If NewSize is zero, NULL is returned and errno will be unchanged. **/ void * realloc(void *Ptr, size_t ReqSize) { void *RetVal = NULL; CPOOL_HEAD *Head = NULL; size_t OldSize = 0; size_t NewSize; size_t NumCpy; // Find out the size of the OLD memory region if( Ptr != NULL) { Head = BASE_CR (Ptr, CPOOL_HEAD, Data); assert(Head != NULL); if (Head->Signature != CPOOL_HEAD_SIGNATURE) { errno = EFAULT; DEBUG((DEBUG_ERROR, "ERROR realloc(0x%p): Signature is 0x%8X, expected 0x%8X\n", Ptr, Head->Signature, CPOOL_HEAD_SIGNATURE)); return NULL; } OldSize = (size_t)Head->Size; } // At this point, Ptr is either NULL or a valid pointer to an allocated space NewSize = (size_t)(ReqSize + (sizeof(CPOOL_HEAD))); if( ReqSize > 0) { RetVal = malloc(NewSize); // Get the NEW memory region if( Ptr != NULL) { // If there is an OLD region... if( RetVal != NULL) { // and the NEW region was successfully allocated NumCpy = OldSize; if( OldSize > NewSize) { NumCpy = NewSize; } (VOID)CopyMem( RetVal, Ptr, NumCpy); // Copy old data to the new region. free( Ptr); // and reclaim the old region. } else { errno = ENOMEM; } } } else { free( Ptr); // Reclaim the old region. } DEBUG((DEBUG_POOL, "0x%p = realloc(%p, %d): Head: %p NewSz: %d\n", RetVal, Ptr, ReqSize, Head, NewSize)); return RetVal; }
4,047
2,453
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12). // // Copyright (C) 1997-2019 <NAME>. // #import <swiftCore/_TtCs12_SwiftObject.h> @class MISSING_TYPE; @interface _TtC12SourceEditor22SourceEditorDataSource : _TtCs12_SwiftObject { MISSING_TYPE *lineData; MISSING_TYPE *utf8RangeData; MISSING_TYPE *contents; MISSING_TYPE *transactionNesting; MISSING_TYPE *editedRange; MISSING_TYPE *invalidatedRange; MISSING_TYPE *lockedDocument; MISSING_TYPE *name; MISSING_TYPE *language; MISSING_TYPE *$__lazy_storage_$_languageService; MISSING_TYPE *formattingOptions; MISSING_TYPE *observerTokens; MISSING_TYPE *journalObserverTokens; MISSING_TYPE *documentSettings; MISSING_TYPE *delegate; MISSING_TYPE *$__lazy_storage_$_undoManager; MISSING_TYPE *isPermanentlyClosed; MISSING_TYPE *newObserverTokens; MISSING_TYPE *diagnosticProviderToken; MISSING_TYPE *diagnosticManager; } @end
389
3,651
/** * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>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. * * <p>For more information: http://www.orientdb.com */ package com.orientechnologies.spatial.shape.legacy; import com.orientechnologies.orient.core.index.OCompositeKey; import java.util.ArrayList; import java.util.List; import org.locationtech.spatial4j.context.SpatialContext; import org.locationtech.spatial4j.shape.Shape; /** Created by <NAME> on 23/10/15. */ public class OShapeBuilderLegacyImpl implements OShapeBuilderLegacy<Shape> { public static final OShapeBuilderLegacyImpl INSTANCE = new OShapeBuilderLegacyImpl(); private List<OShapeBuilderLegacy> builders = new ArrayList<OShapeBuilderLegacy>(); protected OShapeBuilderLegacyImpl() { builders.add(new OPointLegecyBuilder()); builders.add(new ORectangleLegacyBuilder()); } @Override public Shape makeShape(OCompositeKey key, SpatialContext ctx) { for (OShapeBuilderLegacy f : builders) { if (f.canHandle(key)) { return f.makeShape(key, ctx); } } return null; } @Override public boolean canHandle(OCompositeKey key) { return false; } }
530
72,551
<reponame>gandhi56/swift void fromClangLibrarySubmodule();
22
994
/*++ Copyright (c) Microsoft Corporation Module Name: FxWmiIrpHandlerUm.cpp Abstract: This module implements the wmi irp handler for the driver frameworks. Author: Environment: User mode only Revision History: --*/ #include "fxmin.hpp" #include "FxWmiIrpHandler.hpp" class FxWmiIrpHandler; _Must_inspect_result_ NTSTATUS FxWmiIrpHandler::PostCreateDeviceInitialize( VOID ) { ASSERTMSG("Not implemented for UMDF\n", FALSE); return STATUS_NOT_IMPLEMENTED; } VOID FxWmiIrpHandler::Deregister( VOID ) { ASSERTMSG("Not implemented for UMDF\n", FALSE); } _Must_inspect_result_ NTSTATUS FxWmiIrpHandler::AddPowerPolicyProviderAndInstance( __in PWDF_WMI_PROVIDER_CONFIG /* ProviderConfig */, __in FxWmiInstanceInternalCallbacks* /* InstanceCallbacks */, __inout FxWmiInstanceInternal** /* Instance */ ) { ASSERTMSG("Not implemented for UMDF\n", FALSE); return STATUS_NOT_IMPLEMENTED; } _Must_inspect_result_ NTSTATUS FxWmiIrpHandler::Register( VOID ) { ASSERTMSG("Not implemented for UMDF\n", FALSE); return STATUS_NOT_IMPLEMENTED; } VOID FxWmiIrpHandler::Cleanup( VOID ) { ASSERTMSG("Not implemented for UMDF\n", FALSE); } VOID FxWmiIrpHandler::ResetStateForPdoRestart( VOID ) { ASSERTMSG("Not implemented for UMDF\n", FALSE); }
568
358
<gh_stars>100-1000 #!/usr/bin/env python from datetime import datetime import sys print("Hello from cx_Freeze") print( "The current date is %s\n" % datetime.today().strftime("%B %d, %Y %H:%M:%S") ) print(f"Executable: {sys.executable!r}\n") import BUILD_CONSTANTS excludedVars = [ "__builtins__", "__cached__", "__doc__", "__loader__", "__package__", "__spec__", ] print("== variables in BUILD_CONSTANTS ==\n") for var in dir(BUILD_CONSTANTS): if var in excludedVars: continue attr = BUILD_CONSTANTS.__getattribute__(var) print(f"{var} = {attr!r}")
275
363
<gh_stars>100-1000 /* Copyright 2013 predic8 GmbH, www.predic8.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.predic8.membrane.servlet.test; import static com.predic8.membrane.test.AssertUtils.getAndAssert200; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import org.apache.http.ParseException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Request; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.predic8.membrane.core.exchange.Exchange; import com.predic8.membrane.core.http.Header; import com.predic8.membrane.core.http.MimeType; import com.predic8.membrane.core.http.Response; import com.predic8.membrane.core.interceptor.AbstractInterceptor; import com.predic8.membrane.core.interceptor.Outcome; import com.predic8.membrane.core.resolver.SchemaResolver; public class ResolverTestTriggerTest extends AbstractInterceptor { private static final Logger LOG = LoggerFactory.getLogger(ResolverTestTriggerTest.class); private static final String MAGIC = "MAGIC463634623\n"; @Override public Outcome handleRequest(Exchange exc) { try { Class<?> clazz = Class.forName("com.predic8.membrane.core.resolver.ResolverTest"); clazz.getField("deployment").set(null, "J2EE"); Object value = router.getResolverMap().getFileSchemaResolver(); Object resolverMap = clazz.getField("resolverMap").get(null); resolverMap.getClass().getMethod("addSchemaResolver", SchemaResolver.class).invoke(resolverMap, value); Parameterized p = new Parameterized(clazz); JUnitCore c = new JUnitCore(); Result run = c.run(Request.runner(p)); StringBuilder sb = new StringBuilder(); sb.append(MAGIC); for (Failure f : run.getFailures()) { sb.append(f.toString()); StringWriter stringWriter = new StringWriter(); f.getException().printStackTrace(new PrintWriter(stringWriter)); sb.append(stringWriter.toString()); sb.append("\n"); sb.append("\n"); } exc.setResponse(Response.ok().header(Header.CONTENT_TYPE, MimeType.TEXT_PLAIN_UTF8).body(sb.toString()).build()); } catch (Throwable t) { LOG.error(t.getMessage(), t); } return Outcome.RETURN; } @Test public void run() throws ParseException, IOException { Assert.assertEquals(MAGIC, getAndAssert200("http://localhost:3021/test/")); } }
1,039
454
<reponame>zwkjhx/vertx-zero /* * This file is generated by jOOQ. */ package cn.vertxup.ambient.domain.tables; import cn.vertxup.ambient.domain.Db; import cn.vertxup.ambient.domain.Indexes; import cn.vertxup.ambient.domain.Keys; import cn.vertxup.ambient.domain.tables.records.XMenuRecord; import org.jooq.*; import org.jooq.impl.DSL; import org.jooq.impl.SQLDataType; import org.jooq.impl.TableImpl; import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; /** * This class is generated by jOOQ. */ @SuppressWarnings({"all", "unchecked", "rawtypes"}) public class XMenu extends TableImpl<XMenuRecord> { /** * The reference instance of <code>DB_ETERNAL.X_MENU</code> */ public static final XMenu X_MENU = new XMenu(); private static final long serialVersionUID = 1L; /** * The column <code>DB_ETERNAL.X_MENU.KEY</code>. 「key」- 菜单主键 */ public final TableField<XMenuRecord, String> KEY = createField(DSL.name("KEY"), SQLDataType.VARCHAR(36).nullable(false), this, "「key」- 菜单主键"); /** * The column <code>DB_ETERNAL.X_MENU.NAME</code>. 「name」- 菜单名称 */ public final TableField<XMenuRecord, String> NAME = createField(DSL.name("NAME"), SQLDataType.VARCHAR(255), this, "「name」- 菜单名称"); /** * The column <code>DB_ETERNAL.X_MENU.ICON</code>. 「icon」- 菜单使用的icon */ public final TableField<XMenuRecord, String> ICON = createField(DSL.name("ICON"), SQLDataType.VARCHAR(255), this, "「icon」- 菜单使用的icon"); /** * The column <code>DB_ETERNAL.X_MENU.TEXT</code>. 「text」- 菜单显示文字 */ public final TableField<XMenuRecord, String> TEXT = createField(DSL.name("TEXT"), SQLDataType.VARCHAR(255), this, "「text」- 菜单显示文字"); /** * The column <code>DB_ETERNAL.X_MENU.URI</code>. 「uri」- 菜单地址(不包含应用的path) */ public final TableField<XMenuRecord, String> URI = createField(DSL.name("URI"), SQLDataType.VARCHAR(255), this, "「uri」- 菜单地址(不包含应用的path)"); /** * The column <code>DB_ETERNAL.X_MENU.TYPE</code>. 「type」- 菜单类型 */ public final TableField<XMenuRecord, String> TYPE = createField(DSL.name("TYPE"), SQLDataType.VARCHAR(255), this, "「type」- 菜单类型"); /** * The column <code>DB_ETERNAL.X_MENU.ORDER</code>. 「order」- 菜单排序 */ public final TableField<XMenuRecord, Long> ORDER = createField(DSL.name("ORDER"), SQLDataType.BIGINT, this, "「order」- 菜单排序"); /** * The column <code>DB_ETERNAL.X_MENU.LEVEL</code>. 「level」- 菜单层级 */ public final TableField<XMenuRecord, Long> LEVEL = createField(DSL.name("LEVEL"), SQLDataType.BIGINT, this, "「level」- 菜单层级"); /** * The column <code>DB_ETERNAL.X_MENU.PARENT_ID</code>. 「parentId」- 菜单父ID */ public final TableField<XMenuRecord, String> PARENT_ID = createField(DSL.name("PARENT_ID"), SQLDataType.VARCHAR(36), this, "「parentId」- 菜单父ID"); /** * The column <code>DB_ETERNAL.X_MENU.APP_ID</code>. 「appId」- 应用程序ID */ public final TableField<XMenuRecord, String> APP_ID = createField(DSL.name("APP_ID"), SQLDataType.VARCHAR(36), this, "「appId」- 应用程序ID"); /** * The column <code>DB_ETERNAL.X_MENU.ACTIVE</code>. 「active」- 是否启用 */ public final TableField<XMenuRecord, Boolean> ACTIVE = createField(DSL.name("ACTIVE"), SQLDataType.BIT, this, "「active」- 是否启用"); /** * The column <code>DB_ETERNAL.X_MENU.SIGMA</code>. 「sigma」- 统一标识 */ public final TableField<XMenuRecord, String> SIGMA = createField(DSL.name("SIGMA"), SQLDataType.VARCHAR(32), this, "「sigma」- 统一标识"); /** * The column <code>DB_ETERNAL.X_MENU.METADATA</code>. 「metadata」- 附加配置 */ public final TableField<XMenuRecord, String> METADATA = createField(DSL.name("METADATA"), SQLDataType.CLOB, this, "「metadata」- 附加配置"); /** * The column <code>DB_ETERNAL.X_MENU.LANGUAGE</code>. 「language」- 使用的语言 */ public final TableField<XMenuRecord, String> LANGUAGE = createField(DSL.name("LANGUAGE"), SQLDataType.VARCHAR(8), this, "「language」- 使用的语言"); /** * The column <code>DB_ETERNAL.X_MENU.CREATED_AT</code>. 「createdAt」- 创建时间 */ public final TableField<XMenuRecord, LocalDateTime> CREATED_AT = createField(DSL.name("CREATED_AT"), SQLDataType.LOCALDATETIME(0), this, "「createdAt」- 创建时间"); /** * The column <code>DB_ETERNAL.X_MENU.CREATED_BY</code>. 「createdBy」- 创建人 */ public final TableField<XMenuRecord, String> CREATED_BY = createField(DSL.name("CREATED_BY"), SQLDataType.VARCHAR(36), this, "「createdBy」- 创建人"); /** * The column <code>DB_ETERNAL.X_MENU.UPDATED_AT</code>. 「updatedAt」- 更新时间 */ public final TableField<XMenuRecord, LocalDateTime> UPDATED_AT = createField(DSL.name("UPDATED_AT"), SQLDataType.LOCALDATETIME(0), this, "「updatedAt」- 更新时间"); /** * The column <code>DB_ETERNAL.X_MENU.UPDATED_BY</code>. 「updatedBy」- 更新人 */ public final TableField<XMenuRecord, String> UPDATED_BY = createField(DSL.name("UPDATED_BY"), SQLDataType.VARCHAR(36), this, "「updatedBy」- 更新人"); private XMenu(Name alias, Table<XMenuRecord> aliased) { this(alias, aliased, null); } private XMenu(Name alias, Table<XMenuRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table()); } /** * Create an aliased <code>DB_ETERNAL.X_MENU</code> table reference */ public XMenu(String alias) { this(DSL.name(alias), X_MENU); } /** * Create an aliased <code>DB_ETERNAL.X_MENU</code> table reference */ public XMenu(Name alias) { this(alias, X_MENU); } /** * Create a <code>DB_ETERNAL.X_MENU</code> table reference */ public XMenu() { this(DSL.name("X_MENU"), null); } public <O extends Record> XMenu(Table<O> child, ForeignKey<O, XMenuRecord> key) { super(child, key, X_MENU); } /** * The class holding records for this type */ @Override public Class<XMenuRecord> getRecordType() { return XMenuRecord.class; } @Override public Schema getSchema() { return aliased() ? null : Db.DB_ETERNAL; } @Override public List<Index> getIndexes() { return Arrays.asList(Indexes.X_MENU_IDX_X_MENU_APP_ID); } @Override public UniqueKey<XMenuRecord> getPrimaryKey() { return Keys.KEY_X_MENU_PRIMARY; } @Override public List<UniqueKey<XMenuRecord>> getUniqueKeys() { return Arrays.asList(Keys.KEY_X_MENU_NAME); } @Override public XMenu as(String alias) { return new XMenu(DSL.name(alias), this); } @Override public XMenu as(Name alias) { return new XMenu(alias, this); } /** * Rename this table */ @Override public XMenu rename(String name) { return new XMenu(DSL.name(name), null); } /** * Rename this table */ @Override public XMenu rename(Name name) { return new XMenu(name, null); } // ------------------------------------------------------------------------- // Row18 type methods // ------------------------------------------------------------------------- @Override public Row18<String, String, String, String, String, String, Long, Long, String, String, Boolean, String, String, String, LocalDateTime, String, LocalDateTime, String> fieldsRow() { return (Row18) super.fieldsRow(); } }
3,334
337
package com.edotassi.amazmod.event; import com.huami.watch.transport.DataBundle; public class NextMusic { public NextMusic(DataBundle dataBundle) {} }
55
5,169
{ "name": "InAppPurchaseButton", "version": "1.0.5", "license": "MIT", "summary": "In-App Purchase Button written in Swift", "homepage": "https://github.com/PGSSoft/InAppPurchaseButton", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/PGSSoft/InAppPurchaseButton.git", "tag": "1.0.5" }, "platforms": { "ios": "8.4" }, "source_files": "Sources/{*.swift}" }
178
2,151
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Make sure pdb is named as expected (shared between .cc files). """ import TestGyp import sys if sys.platform == 'win32': test = TestGyp.TestGyp() CHDIR = 'compiler-flags' test.run_gyp('pdbname-override.gyp', chdir=CHDIR) test.build('pdbname-override.gyp', test.ALL, chdir=CHDIR) # Confirm that the pdb generated by the compiler was renamed (and we also # have the linker generated one). test.built_file_must_exist('compiler_generated.pdb', chdir=CHDIR) test.built_file_must_exist('linker_generated.pdb', chdir=CHDIR) test.pass_test()
257
443
<reponame>simoll/sleef<gh_stars>100-1000 #include <stdio.h> #if defined(_MSC_VER) #include <intrin.h> #else #include <x86intrin.h> #endif #include <sleef.h> int main(int argc, char **argv) { double a[] = {2, 10}; double b[] = {3, 20}; __m128d va, vb, vc; va = _mm_loadu_pd(a); vb = _mm_loadu_pd(b); vc = Sleef_powd2_u10(va, vb); double c[2]; _mm_storeu_pd(c, vc); printf("pow(%g, %g) = %g\n", a[0], b[0], c[0]); printf("pow(%g, %g) = %g\n", a[1], b[1], c[1]); }
263
1,483
<reponame>lealone/Lealone /* * Copyright Lealone Database Group. * Licensed under the Server Side Public License, v 1. * Initial Developer: zhh */ package org.lealone.sql.query; import org.lealone.db.result.LocalResult; import org.lealone.db.result.ResultTarget; import org.lealone.db.session.ServerSession; import org.lealone.db.value.Value; import org.lealone.sql.expression.Expression; import org.lealone.sql.expression.ValueExpression; import org.lealone.sql.expression.evaluator.AlwaysTrueEvaluator; import org.lealone.sql.expression.evaluator.ExpressionEvaluator; import org.lealone.sql.expression.evaluator.ExpressionInterpreter; import org.lealone.sql.operator.Operator; // 由子类实现具体的查询操作 abstract class QOperator implements Operator { protected final Select select; protected final ServerSession session; protected final ExpressionEvaluator conditionEvaluator; int columnCount; ResultTarget target; ResultTarget result; LocalResult localResult; int maxRows; // 实际返回的最大行数 long limitRows; // 有可能超过maxRows int sampleSize; int rowCount; // 满足条件的记录数 int loopCount; // 循环次数,有可能大于rowCount boolean loopEnd; YieldableSelect yieldableSelect; QOperator(Select select) { this.select = select; session = select.getSession(); Expression c = select.condition; // 没有查询条件或者查询条件是常量时看看是否能演算为true,false在IndexCursor.isAlwaysFalse()中已经处理了 if (c == null || (c instanceof ValueExpression && c.getValue(session).getBoolean())) { conditionEvaluator = new AlwaysTrueEvaluator(); } else { conditionEvaluator = new ExpressionInterpreter(session, c); } } boolean yieldIfNeeded(int rowNumber) { return yieldableSelect.yieldIfNeeded(rowNumber); } boolean canBreakLoop() { // 不需要排序时,如果超过行数限制了可以退出循环 if ((select.sort == null || select.sortUsingIndex) && limitRows > 0 && rowCount >= limitRows) { return true; } // 超过采样数也可以退出循环 if (sampleSize > 0 && rowCount >= sampleSize) { return true; } return false; } @Override public void start() { limitRows = maxRows; // 并不会按offset先跳过前面的行数,而是limitRows加上offset,读够limitRows+offset行,然后再从result中跳 // 因为可能需要排序,offset是相对于最后的结果来说的,而不是排序前的结果 // limitRows must be long, otherwise we get an int overflow // if limitRows is at or near Integer.MAX_VALUE // limitRows is never 0 here if (limitRows > 0 && select.offsetExpr != null) { int offset = select.offsetExpr.getValue(session).getInt(); if (offset > 0) { limitRows += offset; } if (limitRows < 0) { // Overflow limitRows = Long.MAX_VALUE; } } rowCount = 0; select.setCurrentRowNumber(0); sampleSize = select.getSampleSizeValue(session); } @Override public void run() { } @Override public void stop() { if (select.offsetExpr != null) { localResult.setOffset(select.offsetExpr.getValue(session).getInt()); } if (maxRows >= 0) { localResult.setLimit(maxRows); } if (localResult != null) { localResult.done(); if (target != null) { while (localResult.next()) { target.addRow(localResult.currentRow()); } localResult.close(); } } } @Override public boolean isStopped() { return loopEnd; } @Override public LocalResult getLocalResult() { return localResult; } Value[] createRow() { Value[] row = new Value[columnCount]; for (int i = 0; i < columnCount; i++) { Expression expr = select.expressions.get(i); row[i] = expr.getValue(session); } return row; } }
1,995
16,989
<gh_stars>1000+ // Copyright 2021 The Bazel Authors. 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.google.devtools.build.lib.remote.common; import build.bazel.remote.execution.v2.Digest; import com.google.devtools.build.lib.vfs.Path; import java.io.IOException; /** An exception to indicate the digest of downloaded output does not match the expected value. */ public class OutputDigestMismatchException extends IOException { private final Digest expected; private final Digest actual; private Path localPath; private String outputPath; public OutputDigestMismatchException(Digest expected, Digest actual) { this.expected = expected; this.actual = actual; } public void setOutputPath(String outputPath) { this.outputPath = outputPath; } public String getOutputPath() { return outputPath; } public Path getLocalPath() { return localPath; } public void setLocalPath(Path localPath) { this.localPath = localPath; } @Override public String getMessage() { return String.format( "Output %s download failed: Expected digest '%s/%d' does not match " + "received digest '%s/%d'.", outputPath, expected.getHash(), expected.getSizeBytes(), actual.getHash(), actual.getSizeBytes()); } }
569
4,283
<gh_stars>1000+ /* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.map.impl.operation; import com.hazelcast.core.OperationTimeoutException; import com.hazelcast.internal.locksupport.LockWaitNotifyKey; import com.hazelcast.internal.serialization.Data; import com.hazelcast.map.impl.MapDataSerializerHook; import com.hazelcast.spi.impl.operationservice.BlockingOperation; import com.hazelcast.spi.impl.operationservice.WaitNotifyKey; public final class GetOperation extends ReadonlyKeyBasedMapOperation implements BlockingOperation { private Data result; public GetOperation() { } public GetOperation(String name, Data dataKey) { super(name, dataKey); this.dataKey = dataKey; } @Override protected void runInternal() { Object currentValue = recordStore.get(dataKey, false, getCallerAddress()); if (noCopyReadAllowed(currentValue)) { // in case of a 'remote' call (e.g a client call) we prevent making // an on-heap copy of the off-heap data result = (Data) currentValue; } else { // in case of a local call, we do make a copy, so we can safely share // it with e.g. near cache invalidation result = mapService.getMapServiceContext().toData(currentValue); } } private boolean noCopyReadAllowed(Object currentValue) { return currentValue instanceof Data && (!getNodeEngine().getLocalMember().getUuid().equals(getCallerUuid()) || !super.executedLocally()); } @Override protected void afterRunInternal() { mapServiceContext.interceptAfterGet(mapContainer.getInterceptorRegistry(), result); } @Override public WaitNotifyKey getWaitKey() { return new LockWaitNotifyKey(getServiceNamespace(), dataKey); } @Override public boolean shouldWait() { if (recordStore.isTransactionallyLocked(dataKey)) { return !recordStore.canAcquireLock(dataKey, getCallerUuid(), getThreadId()); } return false; } @Override public void onWaitExpire() { sendResponse(new OperationTimeoutException("Cannot read transactionally locked entry!")); } @Override public Data getResponse() { return result; } @Override public int getClassId() { return MapDataSerializerHook.GET; } }
1,060
14,668
<reponame>zealoussnow/chromium<filename>components/crash/core/browser/crashes_ui_util.cc // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/crash/core/browser/crashes_ui_util.h" #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/i18n/time_formatting.h" #include "base/notreached.h" #include "base/values.h" #include "components/strings/grit/components_chromium_strings.h" #include "components/strings/grit/components_strings.h" #include "components/upload_list/upload_list.h" namespace crash_reporter { const CrashesUILocalizedString kCrashesUILocalizedStrings[] = { {"bugLinkText", IDS_CRASH_BUG_LINK_LABEL}, {"crashCaptureTimeFormat", IDS_CRASH_CAPTURE_TIME_FORMAT}, {"crashCountFormat", IDS_CRASH_CRASH_COUNT_BANNER_FORMAT}, {"crashStatus", IDS_CRASH_REPORT_STATUS}, {"crashStatusNotUploaded", IDS_CRASH_REPORT_STATUS_NOT_UPLOADED}, {"crashStatusPending", IDS_CRASH_REPORT_STATUS_PENDING}, {"crashStatusPendingUserRequested", IDS_CRASH_REPORT_STATUS_PENDING_USER_REQUESTED}, {"crashStatusUploaded", IDS_CRASH_REPORT_STATUS_UPLOADED}, {"crashesTitle", IDS_CRASH_TITLE}, {"disabledHeader", IDS_CRASH_DISABLED_HEADER}, {"disabledMessage", IDS_CRASH_DISABLED_MESSAGE}, {"fileSize", IDS_CRASH_REPORT_FILE_SIZE}, {"localId", IDS_CRASH_REPORT_LOCAL_ID}, {"noCrashesMessage", IDS_CRASH_NO_CRASHES_MESSAGE}, {"showDeveloperDetails", IDS_CRASH_SHOW_DEVELOPER_DETAILS}, {"uploadCrashesLinkText", IDS_CRASH_UPLOAD_MESSAGE}, {"uploadId", IDS_CRASH_REPORT_UPLOADED_ID}, {"uploadNowLinkText", IDS_CRASH_UPLOAD_NOW_LINK_TEXT}, {"uploadTime", IDS_CRASH_REPORT_UPLOADED_TIME}, }; const size_t kCrashesUILocalizedStringsCount = base::size(kCrashesUILocalizedStrings); const char kCrashesUICrashesJS[] = "crashes.js"; const char kCrashesUICrashesCSS[] = "crashes.css"; const char kCrashesUISadTabSVG[] = "sadtab.svg"; const char kCrashesUIRequestCrashList[] = "requestCrashList"; const char kCrashesUIRequestCrashUpload[] = "requestCrashUpload"; const char kCrashesUIShortProductName[] = "shortProductName"; const char kCrashesUIUpdateCrashList[] = "update-crash-list"; const char kCrashesUIRequestSingleCrashUpload[] = "requestSingleCrashUpload"; std::string UploadInfoStateAsString(UploadList::UploadInfo::State state) { switch (state) { case UploadList::UploadInfo::State::NotUploaded: return "not_uploaded"; case UploadList::UploadInfo::State::Pending: return "pending"; case UploadList::UploadInfo::State::Pending_UserRequested: return "pending_user_requested"; case UploadList::UploadInfo::State::Uploaded: return "uploaded"; } NOTREACHED(); return ""; } void UploadListToValue(UploadList* upload_list, base::ListValue* out_value) { std::vector<UploadList::UploadInfo> crashes; upload_list->GetUploads(50, &crashes); for (const auto& info : crashes) { std::unique_ptr<base::DictionaryValue> crash(new base::DictionaryValue()); crash->SetString("id", info.upload_id); if (info.state == UploadList::UploadInfo::State::Uploaded) { crash->SetString("upload_time", base::TimeFormatFriendlyDateAndTime(info.upload_time)); } if (!info.capture_time.is_null()) { crash->SetString("capture_time", base::TimeFormatFriendlyDateAndTime(info.capture_time)); } crash->SetString("local_id", info.local_id); crash->SetString("state", UploadInfoStateAsString(info.state)); crash->SetString("file_size", info.file_size); out_value->Append(std::move(crash)); } } } // namespace crash_reporter
1,464
507
# tests/test_provider_hetznercloud_hcloud.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:18:06 UTC) def test_provider_import(): import terrascript.provider.hetznercloud.hcloud def test_resource_import(): from terrascript.resource.hetznercloud.hcloud import hcloud_certificate from terrascript.resource.hetznercloud.hcloud import hcloud_firewall from terrascript.resource.hetznercloud.hcloud import hcloud_floating_ip from terrascript.resource.hetznercloud.hcloud import hcloud_floating_ip_assignment from terrascript.resource.hetznercloud.hcloud import hcloud_load_balancer from terrascript.resource.hetznercloud.hcloud import hcloud_load_balancer_network from terrascript.resource.hetznercloud.hcloud import hcloud_load_balancer_service from terrascript.resource.hetznercloud.hcloud import hcloud_load_balancer_target from terrascript.resource.hetznercloud.hcloud import hcloud_managed_certificate from terrascript.resource.hetznercloud.hcloud import hcloud_network from terrascript.resource.hetznercloud.hcloud import hcloud_network_route from terrascript.resource.hetznercloud.hcloud import hcloud_network_subnet from terrascript.resource.hetznercloud.hcloud import hcloud_placement_group from terrascript.resource.hetznercloud.hcloud import hcloud_rdns from terrascript.resource.hetznercloud.hcloud import hcloud_server from terrascript.resource.hetznercloud.hcloud import hcloud_server_network from terrascript.resource.hetznercloud.hcloud import hcloud_snapshot from terrascript.resource.hetznercloud.hcloud import hcloud_ssh_key from terrascript.resource.hetznercloud.hcloud import hcloud_uploaded_certificate from terrascript.resource.hetznercloud.hcloud import hcloud_volume from terrascript.resource.hetznercloud.hcloud import hcloud_volume_attachment def test_datasource_import(): from terrascript.data.hetznercloud.hcloud import hcloud_certificate from terrascript.data.hetznercloud.hcloud import hcloud_certificates from terrascript.data.hetznercloud.hcloud import hcloud_datacenter from terrascript.data.hetznercloud.hcloud import hcloud_datacenters from terrascript.data.hetznercloud.hcloud import hcloud_firewall from terrascript.data.hetznercloud.hcloud import hcloud_firewalls from terrascript.data.hetznercloud.hcloud import hcloud_floating_ip from terrascript.data.hetznercloud.hcloud import hcloud_floating_ips from terrascript.data.hetznercloud.hcloud import hcloud_image from terrascript.data.hetznercloud.hcloud import hcloud_images from terrascript.data.hetznercloud.hcloud import hcloud_load_balancer from terrascript.data.hetznercloud.hcloud import hcloud_load_balancers from terrascript.data.hetznercloud.hcloud import hcloud_location from terrascript.data.hetznercloud.hcloud import hcloud_locations from terrascript.data.hetznercloud.hcloud import hcloud_network from terrascript.data.hetznercloud.hcloud import hcloud_networks from terrascript.data.hetznercloud.hcloud import hcloud_placement_group from terrascript.data.hetznercloud.hcloud import hcloud_placement_groups from terrascript.data.hetznercloud.hcloud import hcloud_server from terrascript.data.hetznercloud.hcloud import hcloud_server_type from terrascript.data.hetznercloud.hcloud import hcloud_server_types from terrascript.data.hetznercloud.hcloud import hcloud_servers from terrascript.data.hetznercloud.hcloud import hcloud_ssh_key from terrascript.data.hetznercloud.hcloud import hcloud_ssh_keys from terrascript.data.hetznercloud.hcloud import hcloud_volume from terrascript.data.hetznercloud.hcloud import hcloud_volumes # TODO: Shortcut imports without namespace for official and supported providers. # TODO: This has to be moved into a required_providers block. # def test_version_source(): # # import terrascript.provider.hetznercloud.hcloud # # t = terrascript.provider.hetznercloud.hcloud.hcloud() # s = str(t) # # assert 'https://github.com/hetznercloud/terraform-provider-hcloud' in s # assert '1.31.1' in s
1,379
2,577
<reponame>mlehotsky13/camunda-bpm-platform /* * 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. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.model.bpmn.impl.instance.camunda; import org.camunda.bpm.model.bpmn.impl.instance.BpmnModelElementInstanceImpl; import org.camunda.bpm.model.bpmn.instance.camunda.CamundaOut; import org.camunda.bpm.model.xml.ModelBuilder; import org.camunda.bpm.model.xml.impl.instance.ModelTypeInstanceContext; import org.camunda.bpm.model.xml.type.ModelElementTypeBuilder; import org.camunda.bpm.model.xml.type.attribute.Attribute; import static org.camunda.bpm.model.bpmn.impl.BpmnModelConstants.*; import static org.camunda.bpm.model.xml.type.ModelElementTypeBuilder.ModelTypeInstanceProvider; /** * The BPMN out camunda extension element * * @author <NAME> */ public class CamundaOutImpl extends BpmnModelElementInstanceImpl implements CamundaOut { protected static Attribute<String> camundaSourceAttribute; protected static Attribute<String> camundaSourceExpressionAttribute; protected static Attribute<String> camundaVariablesAttribute; protected static Attribute<String> camundaTargetAttribute; protected static Attribute<Boolean> camundaLocalAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaOut.class, CAMUNDA_ELEMENT_OUT) .namespaceUri(CAMUNDA_NS) .instanceProvider(new ModelTypeInstanceProvider<CamundaOut>() { public CamundaOut newInstance(ModelTypeInstanceContext instanceContext) { return new CamundaOutImpl(instanceContext); } }); camundaSourceAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_SOURCE) .namespace(CAMUNDA_NS) .build(); camundaSourceExpressionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_SOURCE_EXPRESSION) .namespace(CAMUNDA_NS) .build(); camundaVariablesAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_VARIABLES) .namespace(CAMUNDA_NS) .build(); camundaTargetAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_TARGET) .namespace(CAMUNDA_NS) .build(); camundaLocalAttribute = typeBuilder.booleanAttribute(CAMUNDA_ATTRIBUTE_LOCAL) .namespace(CAMUNDA_NS) .build(); typeBuilder.build(); } public CamundaOutImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getCamundaSource() { return camundaSourceAttribute.getValue(this); } public void setCamundaSource(String camundaSource) { camundaSourceAttribute.setValue(this, camundaSource); } public String getCamundaSourceExpression() { return camundaSourceExpressionAttribute.getValue(this); } public void setCamundaSourceExpression(String camundaSourceExpression) { camundaSourceExpressionAttribute.setValue(this, camundaSourceExpression); } public String getCamundaVariables() { return camundaVariablesAttribute.getValue(this); } public void setCamundaVariables(String camundaVariables) { camundaVariablesAttribute.setValue(this, camundaVariables); } public String getCamundaTarget() { return camundaTargetAttribute.getValue(this); } public void setCamundaTarget(String camundaTarget) { camundaTargetAttribute.setValue(this, camundaTarget); } public boolean getCamundaLocal() { return camundaLocalAttribute.getValue(this); } public void setCamundaLocal(boolean camundaLocal) { camundaLocalAttribute.setValue(this, camundaLocal); } }
1,352
16,761
<filename>spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ApolloDataSourceFactoryBean.java<gh_stars>1000+ /* * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.cloud.sentinel.datasource.factorybean; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.datasource.apollo.ApolloDataSource; import org.springframework.beans.factory.FactoryBean; /** * A {@link FactoryBean} for creating {@link ApolloDataSource} instance. * * @author <a href="mailto:<EMAIL>">Jim</a> * @see ApolloDataSource */ public class ApolloDataSourceFactoryBean implements FactoryBean<ApolloDataSource> { private String namespaceName; private String flowRulesKey; private String defaultFlowRuleValue; private Converter converter; @Override public ApolloDataSource getObject() throws Exception { return new ApolloDataSource(namespaceName, flowRulesKey, defaultFlowRuleValue, converter); } @Override public Class<?> getObjectType() { return ApolloDataSource.class; } public String getNamespaceName() { return namespaceName; } public void setNamespaceName(String namespaceName) { this.namespaceName = namespaceName; } public String getFlowRulesKey() { return flowRulesKey; } public void setFlowRulesKey(String flowRulesKey) { this.flowRulesKey = flowRulesKey; } public String getDefaultFlowRuleValue() { return defaultFlowRuleValue; } public void setDefaultFlowRuleValue(String defaultFlowRuleValue) { this.defaultFlowRuleValue = defaultFlowRuleValue; } public Converter getConverter() { return converter; } public void setConverter(Converter converter) { this.converter = converter; } }
707
2,847
<gh_stars>1000+ from tests import testmodels from tortoise.contrib import test from tortoise.exceptions import ConfigurationError, IntegrityError from tortoise.fields import TextField class TestTextFields(test.TestCase): async def test_empty(self): with self.assertRaises(IntegrityError): await testmodels.TextFields.create() async def test_create(self): obj0 = await testmodels.TextFields.create(text="baaa" * 32000) obj = await testmodels.TextFields.get(id=obj0.id) self.assertEqual(obj.text, "baaa" * 32000) self.assertEqual(obj.text_null, None) await obj.save() obj2 = await testmodels.TextFields.get(id=obj.id) self.assertEqual(obj, obj2) async def test_values(self): obj0 = await testmodels.TextFields.create(text="baa") values = await testmodels.TextFields.get(id=obj0.id).values("text") self.assertEqual(values["text"], "baa") async def test_values_list(self): obj0 = await testmodels.TextFields.create(text="baa") values = await testmodels.TextFields.get(id=obj0.id).values_list("text", flat=True) self.assertEqual(values, "baa") def test_unique_fail(self): with self.assertRaisesRegex( ConfigurationError, "TextField doesn't support unique indexes, consider CharField" ): TextField(unique=True) def test_index_fail(self): with self.assertRaisesRegex(ConfigurationError, "can't be indexed, consider CharField"): TextField(index=True) def test_pk_deprecated(self): with self.assertWarnsRegex( DeprecationWarning, "TextField as a PrimaryKey is Deprecated, use CharField" ): TextField(pk=True)
718
1,082
<reponame>dingxing123/game-server<gh_stars>1000+ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jjy.game.dbtool.util; import java.io.File; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.jzy.game.tool.util.FileUtil; /** * * @author JiangZhiYong * @QQ 359135103 */ public class FileUtilTest { @Test public void testGetFile() { List<File> sourceFileList = new ArrayList<>(); FileUtil.getFiles("E:\\arts\\策划文档\\翻牌机\\翻牌机数值", sourceFileList, "xlsx", null); } }
300
1,371
{ "dependencies": { "github.com/aws/aws-sdk-go-v2": "v1.4.0", "github.com/aws/smithy-go": "v1.4.0" }, "files": [ "api_client.go", "api_op_AddApplicationCloudWatchLoggingOption.go", "api_op_AddApplicationInput.go", "api_op_AddApplicationInputProcessingConfiguration.go", "api_op_AddApplicationOutput.go", "api_op_AddApplicationReferenceDataSource.go", "api_op_AddApplicationVpcConfiguration.go", "api_op_CreateApplication.go", "api_op_CreateApplicationPresignedUrl.go", "api_op_CreateApplicationSnapshot.go", "api_op_DeleteApplication.go", "api_op_DeleteApplicationCloudWatchLoggingOption.go", "api_op_DeleteApplicationInputProcessingConfiguration.go", "api_op_DeleteApplicationOutput.go", "api_op_DeleteApplicationReferenceDataSource.go", "api_op_DeleteApplicationSnapshot.go", "api_op_DeleteApplicationVpcConfiguration.go", "api_op_DescribeApplication.go", "api_op_DescribeApplicationSnapshot.go", "api_op_DescribeApplicationVersion.go", "api_op_DiscoverInputSchema.go", "api_op_ListApplicationSnapshots.go", "api_op_ListApplicationVersions.go", "api_op_ListApplications.go", "api_op_ListTagsForResource.go", "api_op_RollbackApplication.go", "api_op_StartApplication.go", "api_op_StopApplication.go", "api_op_TagResource.go", "api_op_UntagResource.go", "api_op_UpdateApplication.go", "api_op_UpdateApplicationMaintenanceConfiguration.go", "deserializers.go", "doc.go", "endpoints.go", "generated.json", "internal/endpoints/endpoints.go", "internal/endpoints/endpoints_test.go", "protocol_test.go", "serializers.go", "types/enums.go", "types/errors.go", "types/types.go", "validators.go" ], "go": "1.15", "module": "github.com/aws/aws-sdk-go-v2/service/kinesisanalyticsv2", "unstable": false }
963
348
<filename>docs/data/leg-t2/017/01703344.json {"nom":"Saint-Hilaire-de-Villefranche","circ":"3ème circonscription","dpt":"Charente-Maritime","inscrits":910,"abs":522,"votants":388,"blancs":41,"nuls":31,"exp":316,"res":[{"nuance":"REM","nom":"<NAME>","voix":193},{"nuance":"LR","nom":"M. <NAME>","voix":123}]}
124
1,155
// // Copyright 2005-2007 Adobe Systems Incorporated // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // #include <boost/gil.hpp> #include <boost/gil/extension/io/jpeg.hpp> #include <algorithm> #include <fstream> // Example file to demonstrate a way to compute histogram using namespace boost::gil; template <typename GrayView, typename R> void gray_image_hist(const GrayView& img_view, R& hist) { // for_each_pixel(img_view,++lambda::var(hist)[lambda::_1]); for (typename GrayView::iterator it=img_view.begin(); it!=img_view.end(); ++it) ++hist[*it]; } template <typename V, typename R> void get_hist(const V& img_view, R& hist) { gray_image_hist(color_converted_view<gray8_pixel_t>(img_view), hist); } int main() { rgb8_image_t img; read_image("test.jpg", img, jpeg_tag()); int histogram[256]; std::fill(histogram,histogram + 256, 0); get_hist(const_view(img), histogram); std::fstream histo_file("out-histogram.txt", std::ios::out); for(std::size_t ii = 0; ii < 256; ++ii) histo_file << histogram[ii] << std::endl; histo_file.close(); return 0; }
479
1,194
package ca.uhn.fhir.model.dstu2; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.dstu2.resource.Observation; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.util.TestUtil; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class CompartmentDstu2Test { private static FhirContext ourCtx = FhirContext.forDstu2(); @AfterAll public static void afterClassClearContext() { TestUtil.randomizeLocaleAndTimezone(); } @Test public void testMembership() { Observation o = new Observation(); o.getSubject().setReference("Patient/PID1"); assertTrue(ourCtx.newTerser().isSourceInCompartmentForTarget("Patient", o, new IdDt("Patient/PID1"))); assertFalse(ourCtx.newTerser().isSourceInCompartmentForTarget("Patient", o, new IdDt("Patient/PID2"))); } @Test public void testBadArguments() { try { Observation o = new Observation(); o.getSubject().setReference("Patient/PID1"); ourCtx.newTerser().isSourceInCompartmentForTarget("Patient", o, new IdDt("123")); fail(); } catch (IllegalArgumentException e) { assertEquals("theTarget must have a populated resource type (theTarget.getResourceType() does not return a value)", e.getMessage()); } } }
563
1,056
/* * 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.editor.lib2.view; import java.awt.Rectangle; import java.util.Set; import java.util.logging.Level; import javax.swing.JComponent; import javax.swing.RepaintManager; import javax.swing.SwingUtilities; import org.openide.util.WeakSet; /** * Repaint manager showing repaints in a particular component. * * @author <NAME> */ final class DebugRepaintManager extends RepaintManager { private static final DebugRepaintManager INSTANCE = new DebugRepaintManager(); public static void register(JComponent component) { if (RepaintManager.currentManager(component) != INSTANCE) { RepaintManager.setCurrentManager(INSTANCE); } INSTANCE.addLogComponent(component); } private final Set<JComponent> logComponents = new WeakSet<JComponent>(); private DebugRepaintManager() { } public void addLogComponent(JComponent component) { logComponents.add(component); } @Override public void addDirtyRegion(JComponent c, int x, int y, int w, int h) { for (JComponent dc : logComponents) { if (SwingUtilities.isDescendingFrom(dc, c)) { String boundsMsg = ViewUtils.toString(new Rectangle(x, y, w, h)); ViewHierarchyImpl.REPAINT_LOG.log(Level.FINER, "Component-REPAINT: " + boundsMsg + // NOI18N " c:" + ViewUtils.toString(c), // NOI18N new Exception("Component-Repaint of " + boundsMsg + " cause:")); // NOI18N break; } } super.addDirtyRegion(c, x, y, w, h); } }
887
911
<filename>app/src/com/linchaolong/apktoolplus/core/Jad.java<gh_stars>100-1000 package com.linchaolong.apktoolplus.core; import com.linchaolong.apktoolplus.utils.*; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; /** * Jad,java反编译工具 * * Created by linchaolong on 2015/11/15. */ public class Jad { public static final String TAG = Jad.class.getSimpleName(); public static File jad; private Jad() { } /** * 反编译java字节码 * * @param target 类路径或jar * @param out 源码输出路径(注意:jad不支持包含中文的路径) * @return 是否反编译成功 */ public static boolean decompileByCmd(File target, File out){ if(target == null || !target.exists() || out == null){ return false; } // clean FileHelper.delete(out); File classes = new File(AppManager.getTempDir(), "jad_classes"); if(!target.equals(classes)){ FileHelper.delete(classes); if (target.isFile()){ // 解压文件到缓存目录 boolean result = ZipUtils.unzip(target, classes); if(!result){ return false; } }else{ if(!FileHelper.copyDir(target,classes)){ return false; } } } // 检查jad checkJad(); //jad -r -ff -d src -s java classes/**/*.class StringBuilder cmdBuilder = new StringBuilder(); cmdBuilder.append(jad.getPath()).append(" ") .append("-r -ff -s java ") .append("-d ").append(out.getPath()).append(" ") .append(classes.getPath()).append("/**/*.class"); // CmdUtils.exec(cmdBuilder.toString()); //问题:通过Runtime.exec启动jad,反编译大文件是反编译并不完整(比如8M的jar),会卡在某个地方,但没报错。 //解决方案:动态生成批处理,通过Desktop.browser打开该批处理。 String cmdSuffix = ".bat"; if(!OSUtils.isWindows()){ cmdSuffix = ".sh"; } File cmdFile = new File(AppManager.getTempDir(),"jad_cmd"+cmdSuffix); cmdFile.delete(); OutputStreamWriter output = null; try { output = new OutputStreamWriter(new FileOutputStream(cmdFile), OSUtils.getCharset()); output.write(cmdBuilder.toString()); } catch (Exception e) { e.printStackTrace(); }finally{ IOUtils.close(output); } AppManager.browser(cmdFile); return true; } /** * 反编译java字节码 * * @param target 类路径或jar * @param out 源码输出路径 * @param isOutZip 是否输出为zip文件,输出的zip文件在out同级目录下,命名与out相同,格式为zip * @return 是否反编译成功 */ public static boolean decompile(File target, File out, boolean isOutZip){ if(target == null || !target.exists() || out == null){ return false; } File classes = new File(AppManager.getTempDir(), "jad_classes"); if(!target.equals(classes)){ FileHelper.delete(classes); if (target.isFile()){ // 解压文件到缓存目录 boolean result = ZipUtils.unzip(target, classes); if(!result){ return false; } }else{ if(!FileHelper.copyDir(target,classes)){ return false; } } } // 检查jad checkJad(); File src = new File(classes.getParentFile(),"jad_src"); FileHelper.delete(src); //jad -r -ff -d src -s java classes/**/*.class StringBuilder cmdBuilder = new StringBuilder(); cmdBuilder.append(jad.getPath()).append(" ") .append("-r -ff -s java ") .append("-d ").append(src.getPath()).append(" ") .append(classes.getPath()).append("/**/*.class"); CmdUtils.exec(cmdBuilder.toString(), jad.getParentFile(), true); // clean if(!src.equals(out)){ FileHelper.delete(out); src.renameTo(out); } File finalOut = out; // 输出zip文件 if(isOutZip){ finalOut = new File(out.getParentFile(),out.getName()+".zip"); finalOut.delete(); ZipUtils.zip(out.listFiles(), finalOut); } return finalOut.exists(); } private static void checkJad(){ if(jad == null || !jad.exists()){ String filePath; if(OSUtils.isWindows()){ filePath = "jad/bin/windows/jad.exe"; }else if(OSUtils.isMacOSX()){ filePath = "jad/bin/macosx/jad"; }else if(OSUtils.isUnix()){ filePath = "jad/bin/linux/jad"; }else{ throw new RuntimeException("jad not support this system."); } String fileName = filePath.substring(filePath.lastIndexOf('/') + 1); jad = new File(AppManager.getTempDir(),fileName); ClassUtils.releaseResourceToFile(filePath,jad); } } }
2,895
903
package org.develnext.jphp.ext.mail.classes; import org.apache.commons.mail.EmailAttachment; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.develnext.jphp.ext.mail.MailExtension; import php.runtime.Memory; import php.runtime.annotation.Reflection; import php.runtime.annotation.Reflection.Nullable; import php.runtime.annotation.Reflection.Signature; import php.runtime.env.Environment; import php.runtime.ext.core.classes.stream.Stream; import php.runtime.lang.BaseObject; import php.runtime.reflection.ClassEntity; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.util.ByteArrayDataSource; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; @Reflection.Name("Email") @Reflection.Namespace(MailExtension.NS) public class PHtmlEmail extends BaseObject { private HtmlEmail htmlEmail; public PHtmlEmail(Environment env) { super(env); } public PHtmlEmail(Environment env, ClassEntity clazz) { super(env, clazz); } @Signature public void __construct() { htmlEmail = new HtmlEmail(); } @Signature public PHtmlEmail setHtmlMessage(String value) throws EmailException { htmlEmail.setHtmlMsg(value); return this; } @Signature public PHtmlEmail setTextMessage(String value) throws EmailException { htmlEmail.setTextMsg(value); return this; } @Signature public PHtmlEmail setMessage(String value) throws EmailException { htmlEmail.setMsg(value); return this; } @Signature public PHtmlEmail setFrom(String email, String name, String charset) throws EmailException { htmlEmail.setFrom(email, name, charset); return this; } @Signature public PHtmlEmail setFrom(String email, String name) throws EmailException { htmlEmail.setFrom(email, name); return this; } @Signature public PHtmlEmail setFrom(String email) throws EmailException { htmlEmail.setFrom(email); return this; } @Signature public PHtmlEmail setCharset(String charset) { htmlEmail.setCharset(charset); return this; } @Signature public PHtmlEmail setSubject(String subject) { htmlEmail.setSubject(subject); return this; } @Signature public PHtmlEmail setTo(List<InternetAddress> addresses) throws AddressException, EmailException { htmlEmail.setTo(addresses); return this; } @Signature public PHtmlEmail setCc(List<InternetAddress> addresses) throws EmailException { htmlEmail.setCc(addresses); return this; } @Signature public PHtmlEmail setBcc(List<InternetAddress> addresses) throws EmailException { htmlEmail.setBcc(addresses); return this; } @Signature public PHtmlEmail setBounceAddress(@Nullable String email) throws EmailException { htmlEmail.setBounceAddress(email); return this; } @Signature public PHtmlEmail setHeaders(Map<String, String> map) { htmlEmail.setHeaders(map); return this; } @Signature public PHtmlEmail attach(Environment env, Memory content, String type, String name, String description) throws EmailException, MessagingException, IOException { InputStream is = Stream.getInputStream(env, content); try { htmlEmail.attach(new ByteArrayDataSource(is, type), name, description, EmailAttachment.ATTACHMENT); return this; } finally { Stream.closeStream(env, is); } } @Signature public PHtmlEmail attach(Environment env, Memory content, String type, String name) throws EmailException, MessagingException, IOException { return attach(env, content, type, name, ""); } @Signature public String send(PEmailBackend backend) throws EmailException { backend._apply(htmlEmail); return htmlEmail.send(); } }
1,543
4,224
/**************************************************************************** * * Copyright (c) 2018-2021 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #pragma once #include <stdint.h> #include <px4_defines.h> #include <px4_platform_common/module.h> #include <px4_platform_common/tasks.h> #include <px4_platform_common/getopt.h> #include <px4_platform_common/posix.h> #include <px4_platform_common/module_params.h> #include <px4_platform_common/px4_config.h> #include <px4_platform_common/getopt.h> #include <errno.h> #include <math.h> // NAN #include <cstring> #include <lib/drivers/device/device.h> #include <lib/mixer_module/mixer_module.hpp> #include <lib/mathlib/mathlib.h> #include <lib/cdev/CDev.hpp> #include <lib/led/led.h> #include <lib/tunes/tunes.h> #include <uORB/PublicationMulti.hpp> #include <uORB/Subscription.hpp> #include <uORB/topics/esc_status.h> #include <uORB/topics/led_control.h> #include <drivers/drv_hrt.h> #include <drivers/drv_mixer.h> #include "tap_esc_common.h" #include "drv_tap_esc.h" #if !defined(BOARD_TAP_ESC_MODE) # define BOARD_TAP_ESC_MODE 0 #endif #if !defined(DEVICE_ARGUMENT_MAX_LENGTH) # define DEVICE_ARGUMENT_MAX_LENGTH 32 #endif using namespace time_literals; /* * This driver connects to TAP ESCs via serial. */ class TAP_ESC : public cdev::CDev, public ModuleBase<TAP_ESC>, public OutputModuleInterface { public: TAP_ESC(const char *device, uint8_t channels_count); virtual ~TAP_ESC(); /** @see ModuleBase */ static int task_spawn(int argc, char *argv[]); /** @see ModuleBase */ static int custom_command(int argc, char *argv[]); /** @see ModuleBase */ static int print_usage(const char *reason = nullptr); /** @see ModuleBase::print_status() */ int print_status() override; int init() override; int ioctl(device::file_t *filp, int cmd, unsigned long arg) override; bool updateOutputs(bool stop_motors, uint16_t outputs[MAX_ACTUATORS], unsigned num_outputs, unsigned num_control_groups_updated) override; private: void Run() override; inline void send_esc_outputs(const uint16_t *pwm, const uint8_t motor_cnt); inline void send_tune_packet(EscbusTunePacket &tune_packet); MixingOutput _mixing_output; uORB::SubscriptionInterval _parameter_update_sub{ORB_ID(parameter_update), 1_s}; bool _initialized{false}; char _device[DEVICE_ARGUMENT_MAX_LENGTH] {}; int _uart_fd{-1}; const uint8_t _device_mux_map[TAP_ESC_MAX_MOTOR_NUM] = ESC_POS; const uint8_t _device_dir_map[TAP_ESC_MAX_MOTOR_NUM] = ESC_DIR; uORB::PublicationMulti<esc_status_s> _esc_feedback_pub{ORB_ID(esc_status)}; esc_status_s _esc_feedback{}; uint8_t _channels_count{0}; ///< number of ESC channels uint8_t _responding_esc{0}; ESC_UART_BUF _uartbuf{}; EscPacket _packet{}; Tunes _tunes{}; uORB::Subscription _tune_control_sub{ORB_ID(tune_control)}; hrt_abstime _interval_timestamp{0}; unsigned int _silence_length{0}; ///< If nonzero, silence before next note. unsigned int _frequency{0}; unsigned int _duration{0}; LedControlData _led_control_data{}; LedController _led_controller{}; perf_counter_t _cycle_perf{perf_alloc(PC_ELAPSED, MODULE_NAME": cycle")}; perf_counter_t _interval_perf{perf_alloc(PC_INTERVAL, MODULE_NAME": interval")}; };
1,714
12,651
import argparse import torch import torch.nn.functional as F from torch.nn import Linear as Lin from torch_geometric.nn import SplineConv, radius_graph, fps, global_mean_pool from points.datasets import get_dataset from points.train_eval import run parser = argparse.ArgumentParser() parser.add_argument('--epochs', type=int, default=200) parser.add_argument('--batch_size', type=int, default=8) parser.add_argument('--lr', type=float, default=0.001) parser.add_argument('--lr_decay_factor', type=float, default=0.5) parser.add_argument('--lr_decay_step_size', type=int, default=50) parser.add_argument('--weight_decay', type=float, default=0) args = parser.parse_args() class Net(torch.nn.Module): def __init__(self, num_classes): super(Net, self).__init__() self.conv1 = SplineConv(1, 64, dim=3, kernel_size=5) self.conv2 = SplineConv(64, 64, dim=3, kernel_size=5) self.conv3 = SplineConv(64, 128, dim=3, kernel_size=5) self.lin1 = Lin(128, 256) self.lin2 = Lin(256, 256) self.lin3 = Lin(256, num_classes) def forward(self, pos, batch): x = pos.new_ones((pos.size(0), 1)) radius = 0.2 edge_index = radius_graph(pos, r=radius, batch=batch) pseudo = (pos[edge_index[1]] - pos[edge_index[0]]) / (2 * radius) + 0.5 pseudo = pseudo.clamp(min=0, max=1) x = F.elu(self.conv1(x, edge_index, pseudo)) idx = fps(pos, batch, ratio=0.5) x, pos, batch = x[idx], pos[idx], batch[idx] radius = 0.4 edge_index = radius_graph(pos, r=radius, batch=batch) pseudo = (pos[edge_index[1]] - pos[edge_index[0]]) / (2 * radius) + 0.5 pseudo = pseudo.clamp(min=0, max=1) x = F.elu(self.conv2(x, edge_index, pseudo)) idx = fps(pos, batch, ratio=0.25) x, pos, batch = x[idx], pos[idx], batch[idx] radius = 1 edge_index = radius_graph(pos, r=radius, batch=batch) pseudo = (pos[edge_index[1]] - pos[edge_index[0]]) / (2 * radius) + 0.5 pseudo = pseudo.clamp(min=0, max=1) x = F.elu(self.conv3(x, edge_index, pseudo)) x = global_mean_pool(x, batch) x = F.elu(self.lin1(x)) x = F.elu(self.lin2(x)) x = F.dropout(x, p=0.5, training=self.training) x = self.lin3(x) return F.log_softmax(x, dim=-1) train_dataset, test_dataset = get_dataset(num_points=1024) model = Net(train_dataset.num_classes) run(train_dataset, test_dataset, model, args.epochs, args.batch_size, args.lr, args.lr_decay_factor, args.lr_decay_step_size, args.weight_decay)
1,187
1,176
// Copyright (c) 2014 <NAME>. All rights reserved. // Copyright (c) 2012 The Chromium Authors. // See the LICENSE file. #ifndef THRUST_SHELL_NET_NET_LOG_H_ #define THRUST_SHELL_NET_NET_LOG_H_ #include <string> #include "base/memory/scoped_ptr.h" #include "net/base/net_log_logger.h" namespace thrust_shell { class ThrustShellNetLog : public net::NetLog { public: ThrustShellNetLog(); virtual ~ThrustShellNetLog(); private: scoped_ptr<net::NetLogLogger> net_log_logger_; DISALLOW_COPY_AND_ASSIGN(ThrustShellNetLog); }; } // namespace thrust_shell #endif // THRUST_SHELL_NET_NET_LOG_H_
228
479
<gh_stars>100-1000 package com.crashinvaders.texturepackergui.lml.tags; import com.badlogic.gdx.scenes.scene2d.Actor; import com.crashinvaders.common.scene2d.ShrinkContainer; import com.github.czyzby.lml.parser.LmlParser; import com.github.czyzby.lml.parser.impl.tag.actor.ContainerLmlTag; import com.github.czyzby.lml.parser.tag.LmlActorBuilder; import com.github.czyzby.lml.parser.tag.LmlTag; import com.github.czyzby.lml.parser.tag.LmlTagProvider; /** @see ShrinkContainer */ public class ShrinkContainerLmlTag extends ContainerLmlTag { public ShrinkContainerLmlTag(LmlParser parser, LmlTag parentTag, StringBuilder rawTagData) { super(parser, parentTag, rawTagData); } @Override protected Actor getNewInstanceOfActor(final LmlActorBuilder builder) { return new ShrinkContainer<Actor>(); } public static class TagProvider implements LmlTagProvider { @Override public LmlTag create(final LmlParser parser, final LmlTag parentTag, final StringBuilder rawTagData) { return new ShrinkContainerLmlTag(parser, parentTag, rawTagData); } } }
420
8,232
<reponame>isra-fel/STL // Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include <assert.h> #include <exception> #include <stddef.h> using namespace std; struct BasicLifetimeTracker { static size_t allAlive; }; size_t BasicLifetimeTracker::allAlive = 0; template <class T> struct LifetimeTracker : BasicLifetimeTracker { static size_t thisAlive; static void AssertAlive(const size_t expected) { assert(thisAlive == expected); } LifetimeTracker() { ++thisAlive; ++allAlive; } LifetimeTracker(const LifetimeTracker&) { ++thisAlive; ++allAlive; } LifetimeTracker& operator=(const LifetimeTracker&) = default; ~LifetimeTracker() { --thisAlive; --allAlive; } }; template <class T> size_t LifetimeTracker<T>::thisAlive = 0; template <size_t NestLevel> struct EvilException : LifetimeTracker<EvilException<NestLevel>> { EvilException() = default; EvilException(const EvilException&) { throw EvilException<NestLevel - 1>(); } }; template <> struct EvilException<0> : LifetimeTracker<EvilException<0>> {}; // The asserts about number of exceptions alive in this test are MSVC ABI assumptions: // We copy the exception object in throw (as mandated by the standard), current_exception (allowed by the standard), // and rethrow_exception (unclear compliance with the standard; P1675 looks to make it allowed) int main() { try { throw EvilException<0>(); // copy 1 } catch (...) { try { rethrow_exception( // copy 3 current_exception() // copy 2 ); } catch (const EvilException<0>&) { // unwind destroys copy 2 LifetimeTracker<EvilException<0>>::AssertAlive(2); } } assert(BasicLifetimeTracker::allAlive == 0); { exception_ptr ptr; try { throw EvilException<0>(); // copy 1 } catch (...) { try { ptr = current_exception(); // copy 2 rethrow_exception(ptr); // copy 3 } catch (const EvilException<0>&) { LifetimeTracker<EvilException<0>>::AssertAlive(3); } } LifetimeTracker<EvilException<0>>::AssertAlive(1); // *ptr } assert(BasicLifetimeTracker::allAlive == 0); try { throw EvilException<1>(); // copy 1 } catch (...) { try { rethrow_exception( // EvilException<0> copy 2 current_exception() // attempt copy 2, fails, making EvilException<0> copy 1 ); } catch (const EvilException<0>&) { // unwind destroys EvilException<0> copy 2 LifetimeTracker<EvilException<0>>::AssertAlive(1); LifetimeTracker<EvilException<1>>::AssertAlive(1); } } assert(BasicLifetimeTracker::allAlive == 0); try { throw EvilException<2>(); // copy 1 } catch (...) { try { rethrow_exception(current_exception() // attempt copy 2, fails, // making EvilException<1> copy 1, // copying that fails, making bad_exception ); } catch (const bad_exception&) { LifetimeTracker<EvilException<0>>::AssertAlive(0); LifetimeTracker<EvilException<1>>::AssertAlive(0); LifetimeTracker<EvilException<2>>::AssertAlive(1); } } assert(BasicLifetimeTracker::allAlive == 0); }
1,681
360
<reponame>PiaCuk/KD_Lib from .dynamic import Dynamic_Quantizer from .static import Static_Quantizer from .qat import QAT_Quantizer
45
831
/* * Copyright (C) 2013 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. */ package com.android.tools.idea.rendering; import static com.android.SdkConstants.CLASS_COMPOSE_INSPECTABLE; import static com.android.SdkConstants.CLASS_COMPOSE_VIEW_ADAPTER; import static com.intellij.lang.annotation.HighlightSeverity.ERROR; import com.android.SdkConstants; import com.android.ide.common.rendering.HardwareConfigHelper; import com.android.ide.common.rendering.api.DrawableParams; import com.android.ide.common.rendering.api.HardwareConfig; import com.android.ide.common.rendering.api.IImageFactory; import com.android.ide.common.rendering.api.ILayoutPullParser; import com.android.ide.common.rendering.api.RenderResources; import com.android.ide.common.rendering.api.RenderSession; import com.android.ide.common.rendering.api.ResourceNamespace; import com.android.ide.common.rendering.api.ResourceValue; import com.android.ide.common.rendering.api.ResourceValueImpl; import com.android.ide.common.rendering.api.Result; import com.android.ide.common.rendering.api.SessionParams; import com.android.ide.common.rendering.api.SessionParams.RenderingMode; import com.android.ide.common.rendering.api.ViewInfo; import com.android.ide.common.resources.ResourceResolver; import com.android.ide.common.resources.configuration.LayoutDirectionQualifier; import com.android.ide.common.util.PathString; import com.android.resources.LayoutDirection; import com.android.resources.ResourceFolderType; import com.android.resources.ResourceType; import com.android.resources.ScreenOrientation; import com.android.sdklib.IAndroidTarget; import com.android.sdklib.devices.Device; import com.android.tools.analytics.crash.CrashReporter; import com.android.tools.idea.AndroidPsiUtils; import com.android.tools.idea.configurations.Configuration; import com.android.tools.idea.diagnostics.crash.StudioExceptionReport; import com.android.tools.idea.layoutlib.LayoutLibrary; import com.android.tools.idea.layoutlib.RenderParamsFlags; import com.android.tools.idea.model.ActivityAttributesSnapshot; import com.android.tools.idea.model.AndroidModuleInfo; import com.android.tools.idea.model.MergedManifestSnapshot; import com.android.tools.idea.projectsystem.GoogleMavenArtifactId; import com.android.tools.idea.rendering.imagepool.ImagePool; import com.android.tools.idea.rendering.multi.CompatibilityRenderTarget; import com.android.tools.idea.rendering.parsers.ILayoutPullParserFactory; import com.android.tools.idea.rendering.parsers.LayoutFilePullParser; import com.android.tools.idea.rendering.parsers.LayoutPsiPullParser; import com.android.tools.idea.rendering.parsers.LayoutPullParsers; import com.android.tools.idea.res.AssetRepositoryImpl; import com.android.tools.idea.res.IdeResourcesUtil; import com.android.tools.idea.res.LocalResourceRepository; import com.android.tools.idea.res.ResourceIdManager; import com.android.tools.idea.res.ResourceRepositoryManager; import com.android.tools.idea.util.DependencyManagementUtil; import com.android.utils.SdkUtils; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.Futures; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.util.concurrency.AppExecutorUtil; import java.awt.image.BufferedImage; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.function.Supplier; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.android.uipreview.ModuleClassLoader; import org.jetbrains.android.uipreview.ModuleClassLoaderManager; import org.jetbrains.android.util.AndroidUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * The {@link RenderTask} provides rendering and layout information for * Android layouts. This is a wrapper around the layout library. */ public class RenderTask { private static final Logger LOG = Logger.getInstance(RenderTask.class); /** * When an element in Layoutlib does not take any space, it will ask for a 0px X 0px image. This will throw an exception so we limit the * min size of the returned bitmap to 1x1. */ private static final int MIN_BITMAP_SIZE_PX = 1; /** * {@link IImageFactory} that returns a new image exactly of the requested size. It does not do caching or resizing. */ private static final IImageFactory SIMPLE_IMAGE_FACTORY = new IImageFactory() { @NotNull @Override public BufferedImage getImage(int width, int height) { @SuppressWarnings("UndesirableClassUsage") BufferedImage image = new BufferedImage(Math.max(MIN_BITMAP_SIZE_PX, width), Math.max(MIN_BITMAP_SIZE_PX, height), BufferedImage.TYPE_INT_ARGB); image.setAccelerationPriority(1f); return image; } }; /** * Minimum downscaling factor used. The quality can go from [0, 1] but that setting is actually mapped into [MIN_DOWNSCALING_FACTOR, 1] * since below MIN_DOWNSCALING_FACTOR the quality is not good enough. */ private static final float MIN_DOWNSCALING_FACTOR = .5f; /** * When quality < 1.0, the max allowed size for the rendering is DOWNSCALED_IMAGE_MAX_BYTES * downscalingFactor */ private static final int DOWNSCALED_IMAGE_MAX_BYTES = 2_500_000; // 2.5MB /** * Executor to run the dispose tasks. The thread will run them sequentially. */ @VisibleForTesting static final ExecutorService ourDisposeService = AppExecutorUtil.createBoundedApplicationPoolExecutor("RenderTask Dispose Thread", 1); public static final String GAP_WORKER_CLASS_NAME = "androidx.recyclerview.widget.GapWorker"; @NotNull private final ImagePool myImagePool; @NotNull private final RenderTaskContext myContext; @NotNull private final RenderLogger myLogger; @NotNull private final LayoutlibCallbackImpl myLayoutlibCallback; @NotNull private final LayoutLibrary myLayoutLib; @NotNull private final HardwareConfigHelper myHardwareConfigHelper; private final float myDefaultQuality; @Nullable private IncludeReference myIncludedWithin; @NotNull private RenderingMode myRenderingMode = RenderingMode.NORMAL; private boolean mySetTransparentBackground = false; private boolean myShowDecorations = true; private boolean myShadowEnabled = true; private boolean myHighQualityShadow = true; private boolean myEnableLayoutValidator = false; private boolean myShowWithToolsVisibilityAndPosition = true; private AssetRepositoryImpl myAssetRepository; private long myTimeout; @NotNull private final Locale myLocale; @NotNull private final Object myCredential; private boolean myProvideCookiesForIncludedViews = false; @Nullable private RenderSession myRenderSession; @NotNull private IImageFactory myCachingImageFactory = SIMPLE_IMAGE_FACTORY; @Nullable private IImageFactory myImageFactoryDelegate; private final boolean isSecurityManagerEnabled; @NotNull private CrashReporter myCrashReporter; private final List<CompletableFuture<?>> myRunningFutures = new LinkedList<>(); @NotNull private final AtomicBoolean isDisposed = new AtomicBoolean(false); @Nullable private XmlFile myXmlFile; @NotNull private final Function<Module, MergedManifestSnapshot> myManifestProvider; /** * Don't create this task directly; obtain via {@link RenderService} * * @param quality Factor from 0 to 1 used to downscale the rendered image. A lower value means smaller images used * during rendering at the expense of quality. 1 means that downscaling is disabled. * @param privateClassLoader if true, this task should have its own ModuleClassLoader, if false it can use a shared one for the module */ RenderTask(@NotNull AndroidFacet facet, @NotNull RenderService renderService, @NotNull Configuration configuration, @NotNull RenderLogger logger, @NotNull LayoutLibrary layoutLib, @NotNull Device device, @NotNull Object credential, @NotNull CrashReporter crashReporter, @NotNull ImagePool imagePool, @Nullable ILayoutPullParserFactory parserFactory, boolean isSecurityManagerEnabled, float quality, @NotNull StackTraceCapture stackTraceCaptureElement, @NotNull Function<Module, MergedManifestSnapshot> manifestProvider, boolean privateClassLoader) { this.isSecurityManagerEnabled = isSecurityManagerEnabled; if (!isSecurityManagerEnabled) { LOG.debug("Security manager was disabled"); } myLogger = logger; myCredential = credential; myCrashReporter = crashReporter; myImagePool = imagePool; myAssetRepository = new AssetRepositoryImpl(facet); myHardwareConfigHelper = new HardwareConfigHelper(device); ScreenOrientation orientation = configuration.getFullConfig().getScreenOrientationQualifier() != null ? configuration.getFullConfig().getScreenOrientationQualifier().getValue() : ScreenOrientation.PORTRAIT; myHardwareConfigHelper.setOrientation(orientation); myLayoutLib = layoutLib; LocalResourceRepository appResources = ResourceRepositoryManager.getAppResources(facet); ActionBarHandler actionBarHandler = new ActionBarHandler(this, myCredential); Module module = facet.getModule(); myLayoutlibCallback = new LayoutlibCallbackImpl( this, myLayoutLib, appResources, module, facet, myLogger, myCredential, actionBarHandler, parserFactory, privateClassLoader); if (ResourceIdManager.get(module).finalIdsUsed()) { myLayoutlibCallback.loadAndParseRClass(); } AndroidModuleInfo moduleInfo = AndroidModuleInfo.getInstance(facet); myLocale = configuration.getLocale(); myContext = new RenderTaskContext(module.getProject(), module, configuration, moduleInfo, renderService.getPlatform(facet)); myDefaultQuality = quality; restoreDefaultQuality(); myManifestProvider = manifestProvider; stackTraceCaptureElement.bind(this); } public void setQuality(float quality) { if (quality >= 1.f) { myCachingImageFactory = SIMPLE_IMAGE_FACTORY; return; } float actualSamplingFactor = MIN_DOWNSCALING_FACTOR + Math.max(Math.min(quality, 1f), 0f) * (1f - MIN_DOWNSCALING_FACTOR); long maxSize = (long)((float)DOWNSCALED_IMAGE_MAX_BYTES * actualSamplingFactor); myCachingImageFactory = new CachingImageFactory(((width, height) -> { int downscaleWidth = width; int downscaleHeight = height; int size = width * height; if (size > maxSize) { double scale = maxSize / (double)size; downscaleWidth *= scale; downscaleHeight *= scale; } return SIMPLE_IMAGE_FACTORY.getImage(downscaleWidth, downscaleHeight); })); } public void restoreDefaultQuality() { setQuality(myDefaultQuality); } public void setXmlFile(@NotNull XmlFile file) { myXmlFile = file; ReadAction.run(() -> getContext().setFolderType(IdeResourcesUtil.getFolderType(file))); } @Nullable public XmlFile getXmlFile() { return myXmlFile; } @NotNull public IRenderLogger getLogger() { return myLogger; } @NotNull public HardwareConfigHelper getHardwareConfigHelper() { return myHardwareConfigHelper; } public boolean getShowDecorations() { return myShowDecorations; } public boolean getShowWithToolsVisibilityAndPosition() { return myShowWithToolsVisibilityAndPosition; } public boolean isDisposed() { return isDisposed.get(); } private void clearGapWorkerCache() { if (!myLayoutlibCallback.hasLoadedClass(SdkConstants.RECYCLER_VIEW.newName()) && !myLayoutlibCallback.hasLoadedClass(SdkConstants.RECYCLER_VIEW.oldName())) { // If RecyclerView has not been loaded, we do not need to care about the GapWorker cache return; } try { Class<?> gapWorkerClass = myLayoutlibCallback.findClass(GAP_WORKER_CLASS_NAME); Field gapWorkerField = gapWorkerClass.getDeclaredField("sGapWorker"); gapWorkerField.setAccessible(true); // Because we are clearing-up a ThreadLocal, the code must run on the Layoutlib Thread RenderService.runAsyncRenderAction(() -> { try { ThreadLocal<?> gapWorkerFieldValue = (ThreadLocal<?>)gapWorkerField.get(null); gapWorkerFieldValue.set(null); LOG.debug("GapWorker was cleared"); } catch (IllegalAccessException e) { LOG.debug(e); } }); } catch(Throwable t) { LOG.debug(t); } } private void clearHandlerCallbacks() { try { Class<?> handlerDelegateClass = myLayoutlibCallback.findClass("android.os.Handler_Delegate"); Field runnableQueueField = handlerDelegateClass.getDeclaredField("sRunnablesQueues"); runnableQueueField.setAccessible(true); WeakHashMap<?, ?> runnablesQueue = (WeakHashMap<?, ?>)runnableQueueField.get(null); runnablesQueue.clear(); } catch (NoSuchFieldException e) { // layoutlib-standard may have no sRunnablesQueues. ignore exception. if (LayoutLibrary.isNative()) { LOG.warn(e); } } catch (Throwable t) { LOG.warn(t); } } // Workaround for http://b/155861985 private void clearComposeTables() { if (!myLayoutlibCallback.hasLoadedClass(CLASS_COMPOSE_VIEW_ADAPTER)) { // If Compose has not been loaded, we do not need to care about disposing it return; } try { Class<?> inspectableKt = myLayoutlibCallback.findClass(CLASS_COMPOSE_INSPECTABLE); Field tablesField = inspectableKt.getDeclaredField("tables"); tablesField.setAccessible(true); Set<?> tables = (Set<?>)tablesField.get(null); tables.clear(); } catch (Throwable e) { // The tables field does not exist anymore in dev11 } } // Workaround for http://b/143378087 private void clearCompose() { if (!myLayoutlibCallback.hasLoadedClass(CLASS_COMPOSE_VIEW_ADAPTER)) { // If Compose has not been loaded, we do not need to care about disposing it return; } try { Class<?> adapterClass = myLayoutlibCallback.findClass(CLASS_COMPOSE_VIEW_ADAPTER); ClassLoader adapterClassClassLoader = adapterClass.getClassLoader(); if (!(adapterClassClassLoader instanceof ModuleClassLoader)) { LOG.warn("Unexpected ClassLoader for " + CLASS_COMPOSE_VIEW_ADAPTER + ": " + adapterClassClassLoader); return; } // Let ModuleClassLoaderManager know we are no longer using this ClassLoader ModuleClassLoaderManager.get().release((ModuleClassLoader)adapterClassClassLoader); } catch (Throwable t) { LOG.warn(t); // Failure detected here will most probably cause a memory leak } } /** * Disposes the RenderTask and releases the allocated resources. The execution of the dispose operation will run asynchronously. * The returned {@link Future} can be used to wait for the dispose operation to complete. */ public Future<?> dispose() { if (isDisposed.getAndSet(true)) { assert false : "RenderTask was already disposed"; return Futures.immediateFailedFuture(new IllegalStateException("RenderTask was already disposed")); } RenderTaskAllocationTrackerKt.captureDisposeStackTrace().bind(this); return ourDisposeService.submit(() -> { try { CompletableFuture<?>[] currentRunningFutures; synchronized (myRunningFutures) { currentRunningFutures = myRunningFutures.toArray(new CompletableFuture<?>[0]); myRunningFutures.clear(); } // Wait for all current running operations to complete CompletableFuture.allOf(currentRunningFutures).get(5, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException e) { // We do not care about these exceptions since we are disposing the task anyway LOG.debug(e); } myLayoutlibCallback.setLogger(IRenderLogger.NULL_LOGGER); if (myRenderSession != null) { try { disposeRenderSession(myRenderSession); myRenderSession = null; } catch (Exception ignored) { } } myImageFactoryDelegate = null; myAssetRepository = null; clearCompose(); return null; }); } /** * Overrides the width and height to be used during rendering (which might be adjusted if * the {@link #setRenderingMode(RenderingMode)} is {@link RenderingMode#FULL_EXPAND}. * <p/> * A value of -1 will make the rendering use the normal width and height coming from the * {@link Configuration#getDevice()} object. * * @param overrideRenderWidth the width in pixels of the layout to be rendered * @param overrideRenderHeight the height in pixels of the layout to be rendered * @return this (such that chains of setters can be stringed together) */ @SuppressWarnings("UnusedReturnValue") @NotNull public RenderTask setOverrideRenderSize(int overrideRenderWidth, int overrideRenderHeight) { myHardwareConfigHelper.setOverrideRenderSize(overrideRenderWidth, overrideRenderHeight); return this; } /** * Sets the max width and height to be used during rendering (which might be adjusted if * the {@link #setRenderingMode(RenderingMode)} is {@link RenderingMode#FULL_EXPAND}. * <p/> * A value of -1 will make the rendering use the normal width and height coming from the * {@link Configuration#getDevice()} object. * * @param maxRenderWidth the max width in pixels of the layout to be rendered * @param maxRenderHeight the max height in pixels of the layout to be rendered * @return this (such that chains of setters can be stringed together) */ @SuppressWarnings("UnusedReturnValue") @NotNull public RenderTask setMaxRenderSize(int maxRenderWidth, int maxRenderHeight) { myHardwareConfigHelper.setMaxRenderSize(maxRenderWidth, maxRenderHeight); return this; } /** * Sets the {@link RenderingMode} to be used during rendering. If none is specified, the default is * {@link RenderingMode#NORMAL}. * * @param renderingMode the rendering mode to be used * @return this (such that chains of setters can be stringed together) */ @SuppressWarnings("UnusedReturnValue") @NotNull public RenderTask setRenderingMode(@NotNull RenderingMode renderingMode) { myRenderingMode = renderingMode; return this; } @SuppressWarnings("UnusedReturnValue") @NotNull public RenderTask setTimeout(long timeout) { myTimeout = timeout; return this; } /** * Sets the transparent background to be used. * * @return this (such that chains of setters can be stringed together) */ @SuppressWarnings("UnusedReturnValue") @NotNull public RenderTask setTransparentBackground() { mySetTransparentBackground = true; return this; } /** * Sets whether the rendering should include decorations such as a system bar, an * application bar etc depending on the SDK target and theme. The default is true. * * @param showDecorations true if the rendering should include system bars etc. * @return this (such that chains of setters can be stringed together) */ @SuppressWarnings("UnusedReturnValue") @NotNull public RenderTask setDecorations(boolean showDecorations) { myShowDecorations = showDecorations; return this; } /** * Sets the value of the {@link com.android.layoutlib.bridge.android.RenderParamsFlags#FLAG_ENABLE_SHADOW} * which dictates if shadows will be rendered or not by layout lib. * <p> * Default is {@code true}. */ public RenderTask setShadowEnabled(boolean shadowEnabled) { myShadowEnabled = shadowEnabled; return this; } /** * Sets the value of the {@link com.android.layoutlib.bridge.android.RenderParamsFlags#FLAG_RENDER_HIGH_QUALITY_SHADOW} * which dictates if shadows will be rendered using the high quality algorithm by layout lib. * <p> * Default is {@code true}. */ public RenderTask setHighQualityShadows(boolean highQualityShadows) { myHighQualityShadow = highQualityShadows; return this; } /** * Sets the value of the {@link com.android.layoutlib.bridge.android.RenderParamsFlags#FLAG_KEY_ENABLE_LAYOUT_VALIDATOR} * which enables layout validation during the render process. The validation includes accessibility checks (whether the layout properly * support accessibilty cases), and various other layout sanity checks. */ public RenderTask setEnableLayoutValidator(boolean enableLayoutValidator) { myEnableLayoutValidator = enableLayoutValidator; return this; } /** * Sets whether the rendering should use 'tools' namespaced 'visibility' and 'layout_editor_absoluteX/Y' attributes. * <p> * Default is {@code true}. */ @NotNull public RenderTask setShowWithToolsVisibilityAndPosition(boolean showWithToolsVisibilityAndPosition) { myShowWithToolsVisibilityAndPosition = showWithToolsVisibilityAndPosition; return this; } /** Returns whether this parser will provide view cookies for included views. */ public boolean getProvideCookiesForIncludedViews() { return myProvideCookiesForIncludedViews; } /** * Renders the model and returns the result as a {@link RenderSession}. * * @param factory Factory for images which would be used to render layouts to. * @return the {@link RenderResult resulting from rendering the current model */ @Nullable private RenderResult createRenderSession(@NotNull IImageFactory factory) { RenderTaskContext context = getContext(); Module module = context.getModule(); if (module.isDisposed()) { return null; } PsiFile psiFile = getXmlFile(); if (psiFile == null) { throw new IllegalStateException("createRenderSession shouldn't be called on RenderTask without PsiFile"); } if (isDisposed.get()) { return null; } Configuration configuration = context.getConfiguration(); ResourceResolver resolver = ResourceResolver.copy(configuration.getResourceResolver()); if (resolver == null) { // Abort the rendering if the resources are not found. return null; } ILayoutPullParser modelParser = LayoutPullParsers.create(this); if (modelParser == null) { return null; } myLayoutlibCallback.reset(); if (modelParser instanceof LayoutPsiPullParser) { // For regular layouts, if we use appcompat, we have to emulat the app:srcCompat attribute behaviour. boolean useSrcCompat = DependencyManagementUtil.dependsOn(module, GoogleMavenArtifactId.APP_COMPAT_V7) || DependencyManagementUtil.dependsOn(module, GoogleMavenArtifactId.ANDROIDX_APP_COMPAT_V7); ((LayoutPsiPullParser)modelParser).setUseSrcCompat(useSrcCompat); myLayoutlibCallback.setAaptDeclaredResources(((LayoutPsiPullParser)modelParser).getAaptDeclaredAttrs()); } ILayoutPullParser includingParser = getIncludingLayoutParser(resolver, modelParser); if (includingParser != null) { modelParser = includingParser; } IAndroidTarget target = configuration.getTarget(); int simulatedPlatform = target instanceof CompatibilityRenderTarget ? target.getVersion().getApiLevel() : 0; HardwareConfig hardwareConfig = myHardwareConfigHelper.getConfig(); SessionParams params = new SessionParams(modelParser, myRenderingMode, module /* projectKey */, hardwareConfig, resolver, myLayoutlibCallback, context.getMinSdkVersion().getApiLevel(), context.getTargetSdkVersion().getApiLevel(), myLogger, simulatedPlatform); params.setAssetRepository(myAssetRepository); params.setFlag(RenderParamsFlags.FLAG_KEY_ROOT_TAG, AndroidUtils.getRootTagName(psiFile)); params.setFlag(RenderParamsFlags.FLAG_KEY_RECYCLER_VIEW_SUPPORT, true); params.setFlag(RenderParamsFlags.FLAG_KEY_DISABLE_BITMAP_CACHING, true); params.setFlag(RenderParamsFlags.FLAG_DO_NOT_RENDER_ON_CREATE, true); params.setFlag(RenderParamsFlags.FLAG_KEY_RESULT_IMAGE_AUTO_SCALE, true); params.setFlag(RenderParamsFlags.FLAG_KEY_ENABLE_SHADOW, myShadowEnabled); params.setFlag(RenderParamsFlags.FLAG_KEY_RENDER_HIGH_QUALITY_SHADOW, myHighQualityShadow); params.setFlag(RenderParamsFlags.FLAG_KEY_ENABLE_LAYOUT_VALIDATOR, myEnableLayoutValidator); // Request margin and baseline information. // TODO: Be smarter about setting this; start without it, and on the first request // for an extended view info, re-render in the same session, and then set a flag // which will cause this to create extended view info each time from then on in the // same session. params.setExtendedViewInfoMode(true); LayoutDirectionQualifier qualifier = configuration.getFullConfig().getLayoutDirectionQualifier(); if (qualifier != null && qualifier.getValue() == LayoutDirection.RTL && !getLayoutLib().isRtl(myLocale.toLocaleId())) { // We don't have a flag to force RTL regardless of locale, so just pick a RTL locale (note that // this is decoupled from resource lookup) params.setLocale("ur"); } else { params.setLocale(myLocale.toLocaleId()); } try { @Nullable MergedManifestSnapshot manifestInfo = myManifestProvider.apply(module); params.setRtlSupport(manifestInfo != null && manifestInfo.isRtlSupported()); } catch (Exception e) { // ignore. } // Don't show navigation buttons on older platforms. Device device = configuration.getDevice(); if (!myShowDecorations || HardwareConfigHelper.isWear(device)) { params.setForceNoDecor(); } else { try { @Nullable MergedManifestSnapshot manifestInfo = myManifestProvider.apply(module); ResourceValue appLabel = manifestInfo != null ? manifestInfo.getApplicationLabel() : new ResourceValueImpl(ResourceNamespace.RES_AUTO, ResourceType.STRING, "appName", ""); if (manifestInfo != null) { params.setAppIcon(manifestInfo.getApplicationIcon()); } String activity = configuration.getActivity(); if (activity != null) { params.setActivityName(activity); ActivityAttributesSnapshot attributes = manifestInfo != null ? manifestInfo.getActivityAttributes(activity) : null; if (attributes != null) { if (attributes.getLabel() != null) { appLabel = attributes.getLabel(); } if (attributes.getIcon() != null) { params.setAppIcon(attributes.getIcon()); } } } ResourceValue resource = params.getResources().resolveResValue(appLabel); if (resource != null) { params.setAppLabel(resource.getValue()); } } catch (Exception ignored) { } } if (mySetTransparentBackground || requiresTransparency()) { params.setTransparentBackground(); } params.setImageFactory(factory); if (myTimeout > 0) { params.setTimeout(myTimeout); } params.setFontScale(configuration.getFontScale()); try { myLayoutlibCallback.setLogger(myLogger); RenderSecurityManager securityManager = isSecurityManagerEnabled ? RenderSecurityManagerFactory.create(module, context.getPlatform()) : null; if (securityManager != null) { securityManager.setActive(true, myCredential); } try { RenderSession session = myLayoutLib.createSession(params); if (session.getResult().isSuccess()) { long now = System.nanoTime(); session.setSystemBootTimeNanos(now); session.setSystemTimeNanos(now); // Advance the frame time to display the material progress bars session.setElapsedFrameTimeNanos(TimeUnit.MILLISECONDS.toNanos(500)); } RenderResult result = RenderResult.create(this, session, psiFile, myLogger, myImagePool.copyOf(session.getImage())); myRenderSession = session; addDiagnostics(result.getRenderResult()); return result; } finally { if (securityManager != null) { securityManager.dispose(myCredential); } } } catch (RuntimeException t) { // Exceptions from the bridge myLogger.error(null, t.getLocalizedMessage(), t, null, null); throw t; } } @Nullable private ILayoutPullParser getIncludingLayoutParser(RenderResources resolver, ILayoutPullParser modelParser) { XmlFile xmlFile = getXmlFile(); if (xmlFile == null) { throw new IllegalStateException("getIncludingLayoutParser shouldn't be called on RenderTask without PsiFile"); } if (!myShowWithToolsVisibilityAndPosition) { // Don't support 'showIn' when 'tools' attributes are ignored for rendering. return null; } // Code to support editing included layout. if (myIncludedWithin == null) { String layout = IncludeReference.getIncludingLayout(xmlFile); Module module = getContext().getModule(); myIncludedWithin = layout != null ? IncludeReference.get(module, xmlFile, resolver) : IncludeReference.NONE; } ILayoutPullParser topParser = null; if (myIncludedWithin != IncludeReference.NONE) { assert Comparing.equal(myIncludedWithin.getToFile(), xmlFile.getVirtualFile()); // TODO: Validate that we're really including the same layout here! //ResourceValue contextLayout = resolver.findResValue(myIncludedWithin.getFromResourceUrl(), false /* forceFrameworkOnly*/); //if (contextLayout != null) { // File layoutFile = new File(contextLayout.getValue()); // if (layoutFile.isFile()) { // VirtualFile layoutVirtualFile = myIncludedWithin.getFromFile(); // Get the name of the layout actually being edited, without the extension // as it's what IXmlPullParser.getParser(String) will receive. String queryLayoutName = SdkUtils.fileNameToResourceName(xmlFile.getName()); myLayoutlibCallback.setLayoutParser(queryLayoutName, modelParser); // Attempt to read from PSI. PsiFile psiFile = AndroidPsiUtils.getPsiFileSafely(getContext().getProject(), layoutVirtualFile); if (psiFile instanceof XmlFile) { LayoutPsiPullParser parser = LayoutPsiPullParser.create((XmlFile)psiFile, myLogger); // For included layouts, we don't normally see view cookies; we want the leaf to point back to the include tag parser.setProvideViewCookies(myProvideCookiesForIncludedViews); topParser = parser; } else { // TODO(namespaces, b/74003372): figure out where to get the namespace from. topParser = LayoutFilePullParser.create(new PathString(myIncludedWithin.getFromPath()), ResourceNamespace.TODO()); if (topParser == null) { myLogger.error(null, String.format("Could not read layout file %1$s", myIncludedWithin.getFromPath()), null, null, null); } } } return topParser; } private static <T> CompletableFuture<T> immediateFailedFuture(Throwable exception) { CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(exception); return future; } /** * Executes the passed {@link Callable} as an async render action and keeps track of it. If {@link #dispose()} is called, the call will * wait until all the async actions have finished running. * See {@link RenderService#runAsyncRenderAction(Supplier)}. */ @VisibleForTesting @NotNull <V> CompletableFuture<V> runAsyncRenderAction(@NotNull Supplier<V> callable) { if (isDisposed.get()) { return immediateFailedFuture(new IllegalStateException("RenderTask was already disposed")); } synchronized (myRunningFutures) { CompletableFuture<V> newFuture = RenderService.runAsyncRenderAction(callable); myRunningFutures.add(newFuture); newFuture .whenCompleteAsync((result, ex) -> { synchronized (myRunningFutures) { myRunningFutures.remove(newFuture); } }); return newFuture; } } /** * Inflates the layout but does not render it. * @return A {@link RenderResult} with the result of inflating the inflate call. The result might not contain a result bitmap. */ @NotNull public CompletableFuture<RenderResult> inflate() { // During development only: //assert !ApplicationManager.getApplication().isReadAccessAllowed() : "Do not hold read lock during inflate!"; XmlFile xmlFile = getXmlFile(); if (xmlFile == null) { return immediateFailedFuture(new IllegalStateException("inflate shouldn't be called on RenderTask without PsiFile")); } if (xmlFile.getProject().isDisposed()) { return CompletableFuture.completedFuture(null); } try { return runAsyncRenderAction(() -> createRenderSession((width, height) -> { if (myImageFactoryDelegate != null) { return myImageFactoryDelegate.getImage(width, height); } return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); })); } catch (Exception e) { String message = e.getMessage(); if (message == null) { message = e.toString(); } myLogger.addMessage(RenderProblem.createPlain(ERROR, message, myLogger.getProject(), myLogger.getLinkManager(), e)); return CompletableFuture.completedFuture(RenderResult.createSessionInitializationError(this, xmlFile, myLogger, e)); } } /** * Only do a measure pass using the current render session. */ @NotNull public CompletableFuture<RenderResult> layout() { if (myRenderSession == null) { return CompletableFuture.completedFuture(null); } assert getXmlFile() != null; try { // runAsyncRenderAction might not run immediately so we need to capture the current myRenderSession and myPsiFile values RenderSession renderSession = myRenderSession; PsiFile psiFile = getXmlFile(); return runAsyncRenderAction(() -> { myRenderSession.measure(); return RenderResult.create(this, renderSession, psiFile, myLogger, ImagePool.NULL_POOLED_IMAGE); }); } catch (Exception e) { // nothing } return CompletableFuture.completedFuture(null); } /** * Triggers execution of the Handler and frame callbacks in layoutlib * @return a boolean future that is completed when callbacks are executed that is true if there are more callbacks to execute */ @NotNull public CompletableFuture<Boolean> executeCallbacks() { if (myRenderSession == null) { return CompletableFuture.completedFuture(false); } return runAsyncRenderAction(() -> { myRenderSession.setSystemTimeNanos(System.nanoTime()); return myRenderSession.executeCallbacks(System.nanoTime()); }); } /** * Sets layoutlib system time (needed for the correct touch event handling) and informs layoutlib that there was a (mouse) touch event * detected of a particular type at a particular point. * @param touchEventType type of a touch event * @param x horizontal android coordinate of the detected touch event * @param y vertical android coordinate of the detected touch event * @return a future that is completed when layoutlib handled the touch event */ @NotNull public CompletableFuture<Void> triggerTouchEvent(@NotNull RenderSession.TouchEventType touchEventType, int x, int y) { if (myRenderSession == null) { return CompletableFuture.completedFuture(null); } return runAsyncRenderAction(() -> { myRenderSession.setSystemTimeNanos(System.nanoTime()); myRenderSession.triggerTouchEvent(touchEventType, x, y); return null; }); } /** * Method used to report unhandled layoutlib exceptions to the crash reporter */ private void reportException(@NotNull Throwable e) { // This in an unhandled layoutlib exception, pass it to the crash reporter myCrashReporter.submit(new StudioExceptionReport.Builder().setThrowable(e, false).build()); } /** * Renders the layout to the current {@link IImageFactory} set in {@link #myImageFactoryDelegate} */ @NotNull private CompletableFuture<RenderResult> renderInner() { // During development only: //assert !ApplicationManager.getApplication().isReadAccessAllowed() : "Do not hold read lock during render!"; PsiFile psiFile = getXmlFile(); assert psiFile != null; CompletableFuture<RenderResult> inflateCompletableResult; if (myRenderSession == null) { inflateCompletableResult = inflate() .whenComplete((renderResult, exception) -> { Result result = renderResult != null ? renderResult.getRenderResult() : null; if (result == null || !result.isSuccess()) { Throwable e = result != null ? result.getException() : exception; if (e != null) { reportException(e); } if (result != null) { myLogger.error(null, result.getErrorMessage(), e, null, null); } } }); } else { inflateCompletableResult = CompletableFuture.completedFuture(null); } return inflateCompletableResult.thenCompose(ignored -> { try { return runAsyncRenderAction(() -> { myRenderSession.render(); RenderResult result = RenderResult.create(this, myRenderSession, psiFile, myLogger, myImagePool.copyOf(myRenderSession.getImage())); Result renderResult = result.getRenderResult(); if (renderResult.getException() != null) { reportException(renderResult.getException()); myLogger.error(null, renderResult.getErrorMessage(), renderResult.getException(), null, null); } return result; }).whenComplete((result, ex) -> { clearComposeTables(); // After render clean-up. Dispose the GapWorker cache. clearGapWorkerCache(); clearHandlerCallbacks(); }); } catch (Exception e) { reportException(e); String message = e.getMessage(); if (message == null) { message = e.toString(); } myLogger.addMessage(RenderProblem.createPlain(ERROR, message, myLogger.getProject(), myLogger.getLinkManager(), e)); return CompletableFuture.completedFuture(RenderResult.createSessionInitializationError(this, psiFile, myLogger, e)); } }); } /** * Method that renders the layout to a bitmap using the given {@link IImageFactory}. This render call will render the image to a * bitmap that can be accessed via the returned {@link RenderResult}. * <p/> * If {@link #inflate()} hasn't been called before, this method will implicitly call it. */ @NotNull CompletableFuture<RenderResult> render(@NotNull IImageFactory factory) { myImageFactoryDelegate = factory; return renderInner(); } /** * Run rendering with default IImageFactory implementation provided by RenderTask. This render call will render the image to a bitmap * that can be accessed via the returned {@link RenderResult} * <p/> * If {@link #inflate()} hasn't been called before, this method will implicitly call it. */ @NotNull public CompletableFuture<RenderResult> render() { return render(myCachingImageFactory); } /** * Sets the time for which the next frame will be selected. The time is the elapsed time from * the current system nanos time. */ public void setElapsedFrameTimeNanos(long nanos) { if (myRenderSession != null) { myRenderSession.setElapsedFrameTimeNanos(nanos); } } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") private void addDiagnostics(@NotNull Result result) { if (!myLogger.hasProblems() && !result.isSuccess()) { if (result.getException() != null || result.getErrorMessage() != null) { myLogger.error(null, result.getErrorMessage(), result.getException(), null, null); } else if (result.getStatus() == Result.Status.ERROR_TIMEOUT) { myLogger.error(null, "Rendering timed out.", null, null, null); } else { myLogger.error(null, "Unknown render problem: " + result.getStatus(), null, null, null); } } else if (myIncludedWithin != null && myIncludedWithin != IncludeReference.NONE) { ILayoutPullParser layoutEmbeddedParser = myLayoutlibCallback.getLayoutEmbeddedParser(); if (layoutEmbeddedParser != null) { // Should have been nulled out if used myLogger.error(null, String.format("The surrounding layout (%1$s) did not actually include this layout. " + "Remove tools:" + SdkConstants.ATTR_SHOW_IN + "=... from the root tag.", myIncludedWithin.getFromResourceUrl()), null, null, null); } } } /** * Asynchronously renders the given resource value (which should refer to a drawable) * and returns it as an image. * * @param drawableResourceValue the drawable resource value to be rendered * @return a {@link CompletableFuture} with the BufferedImage of the passed drawable. */ @NotNull public CompletableFuture<BufferedImage> renderDrawable(@NotNull ResourceValue drawableResourceValue) { HardwareConfig hardwareConfig = myHardwareConfigHelper.getConfig(); RenderTaskContext context = getContext(); Module module = getContext().getModule(); DrawableParams params = new DrawableParams(drawableResourceValue, module, hardwareConfig, context.getConfiguration().getResourceResolver(), myLayoutlibCallback, context.getMinSdkVersion().getApiLevel(), context.getTargetSdkVersion().getApiLevel(), myLogger); params.setForceNoDecor(); params.setAssetRepository(myAssetRepository); return runAsyncRenderAction(() -> myLayoutLib.renderDrawable(params)) .thenCompose(result -> { if (result != null && result.isSuccess()) { Object data = result.getData(); if (!(data instanceof BufferedImage)) { data = null; } return CompletableFuture.completedFuture((BufferedImage)data); } else { if (result.getStatus() == Result.Status.ERROR_NOT_A_DRAWABLE) { LOG.debug("renderDrawable called with a non-drawable resource" + drawableResourceValue); return CompletableFuture.completedFuture(null); } Throwable exception = result == null ? new RuntimeException("Rendering failed - null result") : result.getException(); if (exception == null) { String message = result.getErrorMessage(); exception = new RuntimeException(message == null ? "Rendering failed" : "Rendering failed - " + message); } reportException(exception); return immediateFailedFuture(exception); } }); } /** * Renders the given resource value (which should refer to a drawable) and returns it * as an image * * @param drawableResourceValue the drawable resource value to be rendered, or null * @return the image, or null if something went wrong */ @NotNull @SuppressWarnings("unchecked") public List<BufferedImage> renderDrawableAllStates(@Nullable ResourceValue drawableResourceValue) { if (drawableResourceValue == null) { return Collections.emptyList(); } HardwareConfig hardwareConfig = myHardwareConfigHelper.getConfig(); RenderTaskContext context = getContext(); Module module = context.getModule(); DrawableParams params = new DrawableParams(drawableResourceValue, module, hardwareConfig, context.getConfiguration().getResourceResolver(), myLayoutlibCallback, context.getMinSdkVersion().getApiLevel(), context.getTargetSdkVersion().getApiLevel(), myLogger); params.setForceNoDecor(); params.setAssetRepository(myAssetRepository); params.setFlag(RenderParamsFlags.FLAG_KEY_RENDER_ALL_DRAWABLE_STATES, Boolean.TRUE); try { Result result = RenderService.runRenderAction(() -> myLayoutLib.renderDrawable(params)); if (result != null && result.isSuccess()) { Object data = result.getData(); if (data instanceof List) { return (List<BufferedImage>)data; } } } catch (Exception e) { // ignore } return Collections.emptyList(); } @NotNull private LayoutLibrary getLayoutLib() { return myLayoutLib; } @NotNull public LayoutlibCallbackImpl getLayoutlibCallback() { return myLayoutlibCallback; } /** Returns true if this service can render a non-rectangular shape */ private boolean isNonRectangular() { ResourceFolderType folderType = getContext().getFolderType(); // Drawable images can have non-rectangular shapes; we need to ensure that we blank out the // background with full alpha return folderType == ResourceFolderType.DRAWABLE || folderType == ResourceFolderType.MIPMAP; } /** Returns true if this service requires rendering into a transparent/alpha channel image */ private boolean requiresTransparency() { // Drawable images can have non-rectangular shapes; we need to ensure that we blank out the // background with full alpha return isNonRectangular(); } /** * Measure the children of the given parent tag, applying the given filter to the pull parser's * attribute values. * * @param parent the parent tag to measure children for * @param filter the filter to apply to the attribute values * @return a map from the children of the parent to new bounds of the children */ @NotNull public CompletableFuture<Map<XmlTag, ViewInfo>> measureChildren(@NotNull XmlTag parent, @Nullable AttributeFilter filter) { ILayoutPullParser modelParser = LayoutPsiPullParser.create(filter, parent, myLogger); Map<XmlTag, ViewInfo> map = new HashMap<>(); return RenderService.runAsyncRenderAction(() -> measure(modelParser)) .thenComposeAsync(session -> { if (session != null) { try { Result result = session.getResult(); if (result != null && result.isSuccess()) { assert session.getRootViews().size() == 1; ViewInfo root = session.getRootViews().get(0); List<ViewInfo> children = root.getChildren(); for (ViewInfo info : children) { XmlTag tag = RenderService.getXmlTag(info); if (tag != null) { map.put(tag, info); } } } return CompletableFuture.completedFuture(map); } finally { disposeRenderSession(session); } } return CompletableFuture.completedFuture(Collections.emptyMap()); }, AppExecutorUtil.getAppExecutorService()); } /** * Measure the given child in context, applying the given filter to the * pull parser's attribute values. * * @param tag the child to measure * @param filter the filter to apply to the attribute values * @return a {@link CompletableFuture} that will return the {@link ViewInfo} if found. */ @NotNull public CompletableFuture<ViewInfo> measureChild(@NotNull XmlTag tag, @Nullable AttributeFilter filter) { XmlTag parent = tag.getParentTag(); if (parent == null) { return CompletableFuture.completedFuture(null); } return measureChildren(parent, filter) .thenApply(map -> { for (Map.Entry<XmlTag, ViewInfo> entry : map.entrySet()) { if (entry.getKey() == tag) { return entry.getValue(); } } return null; }); } @Nullable private RenderSession measure(ILayoutPullParser parser) { RenderTaskContext context = getContext(); ResourceResolver resolver = context.getConfiguration().getResourceResolver(); myLayoutlibCallback.reset(); HardwareConfig hardwareConfig = myHardwareConfigHelper.getConfig(); Module module = getContext().getModule(); SessionParams params = new SessionParams(parser, RenderingMode.NORMAL, module /* projectKey */, hardwareConfig, resolver, myLayoutlibCallback, context.getMinSdkVersion().getApiLevel(), context.getTargetSdkVersion().getApiLevel(), myLogger); //noinspection deprecation We want to measure while creating the session. RenderSession.measure would require a second call. params.setLayoutOnly(); params.setForceNoDecor(); params.setExtendedViewInfoMode(true); params.setLocale(myLocale.toLocaleId()); params.setAssetRepository(myAssetRepository); params.setFlag(RenderParamsFlags.FLAG_KEY_RECYCLER_VIEW_SUPPORT, true); @Nullable MergedManifestSnapshot manifestInfo = myManifestProvider.apply(module); params.setRtlSupport(manifestInfo != null && manifestInfo.isRtlSupported()); try { myLayoutlibCallback.setLogger(myLogger); return myLayoutLib.createSession(params); } catch (RuntimeException t) { // Exceptions from the bridge. myLogger.error(null, t.getLocalizedMessage(), t, null, null); throw t; } } @VisibleForTesting void setCrashReporter(@NotNull CrashReporter crashReporter) { myCrashReporter = crashReporter; } /** * Returns the context used in this render task. The context includes things like platform information, file or module. */ @NotNull public RenderTaskContext getContext() { return myContext; } /** * The {@link AttributeFilter} allows a client of {@link #measureChildren} to modify the actual * XML values of the nodes being rendered, for example to force width and height values to * wrap_content when measuring preferred size. */ public interface AttributeFilter { /** * Returns the attribute value for the given node and attribute name. This filter * allows a client to adjust the attribute values that a node presents to the * layout library. * <p/> * Returns "" to unset an attribute. Returns null to return the unfiltered value. * * @param node the node for which the attribute value should be returned * @param namespace the attribute namespace * @param localName the attribute local name * @return an override value, or null to return the unfiltered value */ @Nullable String getAttribute(@NotNull XmlTag node, @Nullable String namespace, @NotNull String localName); } /** * Properly disposes {@link RenderSession} as a single {@link RenderService} call. * @param renderSession a session to be disposed of */ private void disposeRenderSession(@NotNull RenderSession renderSession) { Optional<Method> disposeMethod = Optional.empty(); try { if (myLayoutlibCallback.hasLoadedClass(CLASS_COMPOSE_VIEW_ADAPTER)) { Class<?> composeViewAdapter = myLayoutlibCallback.findClass(CLASS_COMPOSE_VIEW_ADAPTER); // Kotlin bytecode generation converts dispose() method into dispose$ui_tooling() therefore we have to perform this filtering disposeMethod = Arrays.stream(composeViewAdapter.getMethods()).filter(m -> m.getName().contains("dispose")).findFirst(); } } catch (ClassNotFoundException ex) { LOG.warn(CLASS_COMPOSE_VIEW_ADAPTER + " class not found", ex); } disposeMethod.ifPresent(m -> m.setAccessible(true)); Optional<Method> finalDisposeMethod = disposeMethod; RenderService.runAsyncRenderAction(() -> { finalDisposeMethod.ifPresent(m -> renderSession.getRootViews().forEach(v -> disposeIfCompose(v, m))); renderSession.dispose(); }); } /** * Performs dispose() call against View object associated with {@link ViewInfo} if that object is an instance of ComposeViewAdapter * @param viewInfo a {@link ViewInfo} associated with the View object to be potentially disposed of * @param disposeMethod a dispose method to be executed against View object */ private static void disposeIfCompose(@NotNull ViewInfo viewInfo, @NotNull Method disposeMethod) { Object viewObject = viewInfo.getViewObject(); if (viewObject == null || !viewObject.getClass().getName().equals(CLASS_COMPOSE_VIEW_ADAPTER)) { return; } try { disposeMethod.invoke(viewObject); } catch (IllegalAccessException | InvocationTargetException ex) { LOG.warn( "Unexpected error while disposing compose view", ex); } } }
19,182
666
<reponame>elina8013/android_demo package com.renyu.showcaselibrary; /** * Created by Administrator on 2017/7/3. */ public class CalculatorBean { FocusShape mFocusShape; int mCircleCenterX; int mCircleCenterY; int mCircleRadius; // 圆角矩形专用 int mFocusWidth; int mFocusHeight; public FocusShape getmFocusShape() { return mFocusShape; } public void setmFocusShape(FocusShape mFocusShape) { this.mFocusShape = mFocusShape; } public int getmCircleCenterX() { return mCircleCenterX; } public void setmCircleCenterX(int mCircleCenterX) { this.mCircleCenterX = mCircleCenterX; } public int getmCircleCenterY() { return mCircleCenterY; } public void setmCircleCenterY(int mCircleCenterY) { this.mCircleCenterY = mCircleCenterY; } public int getmFocusWidth() { return mFocusWidth; } public void setmFocusWidth(int mFocusWidth) { this.mFocusWidth = mFocusWidth; } public int getmFocusHeight() { return mFocusHeight; } public void setmFocusHeight(int mFocusHeight) { this.mFocusHeight = mFocusHeight; } public int getmCircleRadius() { return mCircleRadius; } public void setmCircleRadius(int mCircleRadius) { this.mCircleRadius = mCircleRadius; } }
593
377
<reponame>gburd/Kundera /******************************************************************************* * * Copyright 2015 Impetus Infotech. * * * * 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.impetus.client.spark.entities; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import com.impetus.kundera.index.Index; import com.impetus.kundera.index.IndexCollection; /** * The Class Person. * * @author: karthikp.manchala */ @Entity @Table(name = "spark_person") @IndexCollection(columns = { @Index(name = "personName"), @Index(name = "age"), @Index(name = "salary") }) public class Person implements Serializable { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The person id. */ @Id private String personId; /** The person name. */ private String personName; /** The age. */ private long age; /** The salary. */ private Double salary; /** * Gets the person id. * * @return the person id */ public String getPersonId() { return personId; } /** * Sets the person id. * * @param personId * the new person id */ public void setPersonId(String personId) { this.personId = personId; } /** * Gets the person name. * * @return the person name */ public String getPersonName() { return personName; } /** * Sets the person name. * * @param personName * the new person name */ public void setPersonName(String personName) { this.personName = personName; } /** * Gets the age. * * @return the age */ public long getAge() { return age; } /** * Sets the age. * * @param age * the new age */ public void setAge(long age) { this.age = age; } /** * Gets the salary. * * @return the salary */ public Double getSalary() { return salary; } /** * Sets the salary. * * @param salary * the new salary */ public void setSalary(Double salary) { this.salary = salary; } }
1,161
1,909
<reponame>grmkris/XChange package info.bitrich.xchangestream.btcmarkets; import info.bitrich.xchangestream.core.StreamingExchange; import info.bitrich.xchangestream.core.StreamingExchangeFactory; import io.reactivex.disposables.Disposable; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.currency.CurrencyPair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BTCMarketsManualExample { private static final Logger logger = LoggerFactory.getLogger(BTCMarketsManualExample.class); public static void main(String[] args) { ExchangeSpecification defaultExchangeSpecification = new ExchangeSpecification(BTCMarketsStreamingExchange.class); StreamingExchange exchange = StreamingExchangeFactory.INSTANCE.createExchange(defaultExchangeSpecification); exchange.connect().blockingAwait(); Disposable btcOrderBookDisposable = exchange .getStreamingMarketDataService() .getOrderBook(CurrencyPair.BTC_AUD) .forEach( orderBook -> { logger.info("First btc ask: {}", orderBook.getAsks().get(0)); logger.info("First btc bid: {}", orderBook.getBids().get(0)); }); Disposable ethOrderBookDisposable = exchange .getStreamingMarketDataService() .getOrderBook(CurrencyPair.ETH_AUD) .forEach( orderBook -> { logger.info("First eth ask: {}", orderBook.getAsks().get(0)); logger.info("First eth bid: {}", orderBook.getBids().get(0)); }); Disposable btcTickerDisposable = exchange .getStreamingMarketDataService() .getTicker(CurrencyPair.BTC_AUD) .forEach( ticker -> { logger.info("BTC: First ask: {}", ticker.getAsk()); logger.info("BTC: First bid: {}", ticker.getBid()); logger.info("BTC: last price: {}", ticker.getLast()); logger.info("BTC: 24h volume {}", ticker.getVolume()); logger.info("BTC: timestamp {}", ticker.getVolume()); }); try { Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); } btcOrderBookDisposable.dispose(); ethOrderBookDisposable.dispose(); btcTickerDisposable.dispose(); exchange.disconnect().subscribe(() -> logger.info("Disconnected from the Exchange")); } }
1,102
5,964
<gh_stars>1000+ {% extends 'interface_base.cpp' %} {##############################################################################} {% block prepare_prototype_object %} {% from 'interface.cpp' import install_unscopeables with context %} {% from 'interface.cpp' import install_conditionally_enabled_attributes_on_prototype with context %} {% from 'methods.cpp' import install_conditionally_enabled_methods with context %} void {{v8_class_or_partial}}::preparePrototypeObject(v8::Isolate* isolate, v8::Local<v8::Object> prototypeObject, v8::Local<v8::FunctionTemplate> interfaceTemplate) { {{v8_class}}::preparePrototypeObject(isolate, prototypeObject, interfaceTemplate); {% if unscopeables %} {{install_unscopeables() | indent}} {% endif %} {% if has_conditional_attributes_on_prototype %} {{install_conditionally_enabled_attributes_on_prototype() | indent}} {% endif %} {% if conditionally_enabled_methods %} {{install_conditionally_enabled_methods() | indent}} {% endif %} } {% endblock %} {##############################################################################} {% block partial_interface %} void {{v8_class_or_partial}}::initialize() { // Should be invoked from initModules. {{v8_class}}::updateWrapperTypeInfo( &{{v8_class_or_partial}}::install{{v8_class}}Template, &{{v8_class_or_partial}}::preparePrototypeObject); {% for method in methods %} {% if method.overloads and method.overloads.has_partial_overloads %} {{v8_class}}::register{{method.name | blink_capitalize}}MethodForPartialInterface(&{{cpp_class_or_partial}}V8Internal::{{method.name}}Method); {% endif %} {% endfor %} } {% endblock %}
557
480
/* * Copyright [2013-2021], Alibaba Group Holding Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.polardbx.rule.enumerator; import static org.junit.Assert.assertEquals; import java.util.Set; import com.alibaba.polardbx.rule.TestUtils; import org.junit.Test; import com.alibaba.polardbx.common.model.sqljep.Comparative; public class LongPartDiscontinousRangeEnumeratorUnitTest { /* * T:测试在有自增和没有自增的情况下 对于close interval的处理, 在有自增和range的情况下测试 x = ? or (x > ? * and x < ?) 测试开区间 ,测试x>5 and x>10,测试x >= 3 and x < 5取值是否正确 测试x>3 and * x<5取值是否正确。 测试x >=3 and x=3的时候返回是否正确。 */ Comparative btc = null; Enumerator e = new RuleEnumeratorImpl(); boolean needMergeValueInCloseRange = true; @Test public void test_没有自增的closeinterval() throws Exception { btc = TestUtils.gand(TestUtils.gcomp(3, TestUtils.GreaterThan), TestUtils.gcomp(5, TestUtils.LessThanOrEqual)); try { e.getEnumeratedValue(btc, null, null, needMergeValueInCloseRange); } catch (IllegalArgumentException e) { assertEquals("当原子增参数或叠加参数为空时,不支持在sql中使用范围选择,如id>? and id<?", e.getMessage()); } } @Test public void test_带有自增的closeInterval() throws Exception { btc = TestUtils.gand(TestUtils.gcomp(3l, TestUtils.GreaterThan), TestUtils.gcomp(5l, TestUtils.LessThanOrEqual)); Set<Object> s = e.getEnumeratedValue(btc, 16, 64, needMergeValueInCloseRange); TestUtils.testSet(new Object[] { 4l, 5l }, s); } // --------------------------------------------------以下是一些对两个and节点上挂两个参数一些情况的单元测试。 // 因为从公共逻辑测试中已经测试了> 在处理中会转变为>= 而< 在处理中会转为<= 因此只需要测试> = < // 在and,两个节点的情况下的可能性即可。 @Test public void test_带有自增的closeInterval_1() throws Exception { btc = TestUtils.gand(TestUtils.gcomp(3l, TestUtils.GreaterThan), TestUtils.gcomp(5l, TestUtils.LessThanOrEqual)); Set<Object> s = e.getEnumeratedValue(btc, 64, 1, needMergeValueInCloseRange); TestUtils.testSet(new Object[] { 4l, 5l }, s); } @Test public void test_开区间() throws Exception { btc = TestUtils.gand(TestUtils.gcomp(3, TestUtils.LessThanOrEqual), TestUtils.gcomp(5, TestUtils.GreaterThan)); Set<Object> s = e.getEnumeratedValue(btc, 5, 1, needMergeValueInCloseRange); TestUtils.testSet(new Object[] {}, s); } @Test public void test_一个大于一个null在一个and中() throws Exception { btc = TestUtils.gand(TestUtils.gcomp(3, TestUtils.LessThanOrEqual), null); try { e.getEnumeratedValue(btc, 64, 1, needMergeValueInCloseRange); } catch (IllegalArgumentException e) { assertEquals("input value is not a comparative: null", e.getMessage()); } } @Test public void test_一个小于() throws Exception { btc = TestUtils.gcomp(3l, TestUtils.LessThanOrEqual); Set<Object> s = e.getEnumeratedValue(btc, 5, 1, needMergeValueInCloseRange); // TestUtils.testSet(new Object[]{3l,2l,1l,0l,-1l},s );//默认忽略负数 TestUtils.testSet(new Object[] { 3l, 2l, 1l, 0l, }, s); } @Test public void test_两个小于等于() throws Exception { btc = TestUtils .gand(TestUtils.gcomp(3l, TestUtils.LessThanOrEqual), TestUtils.gcomp(5l, TestUtils.LessThanOrEqual)); Set<Object> s = e.getEnumeratedValue(btc, 5, 1, needMergeValueInCloseRange); // TestUtils.testSet(new Object[]{3l,2l,1l,0l,-1l},s );//默认忽略负数 TestUtils.testSet(new Object[] { 3l, 2l, 1l, 0l }, s); } @Test public void test_一个小于一个等于() throws Exception { btc = TestUtils.gand(TestUtils.gcomp(3, TestUtils.LessThanOrEqual), TestUtils.gcomp(5, TestUtils.Equivalent)); Set<Object> s = e.getEnumeratedValue(btc, 5, 1, needMergeValueInCloseRange); TestUtils.testSet(new Object[] {}, s); } @Test public void test_一个等于一个小于() throws Exception { btc = TestUtils.gand(TestUtils.gcomp(3, TestUtils.Equivalent), TestUtils.gcomp(5, TestUtils.LessThan)); Set<Object> s = e.getEnumeratedValue(btc, 5, 1, needMergeValueInCloseRange); TestUtils.testSet(new Object[] { 3 }, s); } @Test public void test_一个等于一个大于() throws Exception { btc = TestUtils.gand(TestUtils.gcomp(3, TestUtils.Equivalent), TestUtils.gcomp(5, TestUtils.GreaterThan)); Set<Object> s = e.getEnumeratedValue(btc, 5, 1, needMergeValueInCloseRange); TestUtils.testSet(new Object[] {}, s); } @Test public void test_一个大于一个等于() throws Exception { btc = TestUtils.gand(TestUtils.gcomp(3, TestUtils.GreaterThan), TestUtils.gcomp(5, TestUtils.Equivalent)); Set<Object> s = e.getEnumeratedValue(btc, 5, 1, needMergeValueInCloseRange); TestUtils.testSet(new Object[] { 5 }, s); } @Test public void test_两个等于() throws Exception { btc = TestUtils.gand(TestUtils.gcomp(3, TestUtils.LessThanOrEqual), TestUtils.gcomp(5, TestUtils.Equivalent)); Set<Object> s = e.getEnumeratedValue(btc, 5, 1, needMergeValueInCloseRange); TestUtils.testSet(new Object[] {}, s); } @Test public void test_两个大于不是大于等于() throws Exception { btc = TestUtils.gand(TestUtils.gcomp(3l, TestUtils.GreaterThan), TestUtils.gcomp(5l, TestUtils.GreaterThan)); Set<Object> s = e.getEnumeratedValue(btc, 5, 1, needMergeValueInCloseRange); TestUtils.testSet(new Object[] { 6l, 7l, 8l, 9l, 10l }, s); } }
3,179
721
<filename>nucleus/io/tfrecord_reader.h /* * Copyright 2019 Google LLC. * * 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 THIRD_PARTY_NUCLEUS_IO_TFRECORD_READER_H_ #define THIRD_PARTY_NUCLEUS_IO_TFRECORD_READER_H_ #include <memory> #include <string> #include "nucleus/platform/types.h" #include "tensorflow/core/platform/tstring.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { class RandomAccessFile; namespace io { class RecordReader; } // namespace io } // namespace tensorflow namespace nucleus { // A class for reading TFRecord files, designed for easy CLIF-wrapping // for Python. Loosely based on tensorflow/python/lib/io/py_record_reader.h // An instance of this class is NOT safe for concurrent access by multiple // threads. class TFRecordReader { public: // Create a TFRecordReader. // Valid compression_types are "ZLIB", "GZIP", or "" (for none). // Returns nullptr on failure. static std::unique_ptr<TFRecordReader> New( const std::string& filename, const std::string& compression_type); ~TFRecordReader(); // Returns true on success, false on error. bool GetNext(); // Return the current record contents. Only valid after GetNext() // has returned true. tensorflow::tstring record() const { return record_; } // Close the file and release its resources. void Close(); // Disallow copy and assignment operations. TFRecordReader(const TFRecordReader& other) = delete; TFRecordReader& operator=(const TFRecordReader&) = delete; private: TFRecordReader(); tensorflow::uint64 offset_; // |reader_| has a non-owning pointer on |file_|, so destruct it first. std::unique_ptr<tensorflow::RandomAccessFile> file_; std::unique_ptr<tensorflow::io::RecordReader> reader_; tensorflow::tstring record_; }; } // namespace nucleus #endif // THIRD_PARTY_NUCLEUS_IO_TFRECORD_READER_H_
738
14,668
// Copyright 2018 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 CHROME_BROWSER_ANDROID_VR_TEST_AR_TEST_SUITE_H_ #define CHROME_BROWSER_ANDROID_VR_TEST_AR_TEST_SUITE_H_ #include "base/test/test_suite.h" namespace base { namespace test { class TaskEnvironment; } // namespace test } // namespace base namespace vr { class ArTestSuite : public base::TestSuite { public: ArTestSuite(int argc, char** argv); ArTestSuite(const ArTestSuite&) = delete; ArTestSuite& operator=(const ArTestSuite&) = delete; ~ArTestSuite() override; protected: void Initialize() override; void Shutdown() override; private: std::unique_ptr<base::test::TaskEnvironment> task_environment_; }; } // namespace vr #endif // CHROME_BROWSER_ANDROID_VR_TEST_AR_TEST_SUITE_H_
316
1,433
<reponame>gerald-yang/ubuntu-iotivity-demo<filename>iotivity-1.0.1/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Utility.java<gh_stars>1000+ /* * Copyright 2015 Samsung Electronics 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 oic.simulator.serviceprovider.utils; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; /** * This class has common utility methods. */ public class Utility { public static String uriToDisplayName(String uri) { String result = null; if (null != uri) { String tokens[] = uri.split(Constants.FORWARD_SLASH); if (null != tokens && tokens.length > 2) { result = tokens[tokens.length - 3] + Constants.UNDERSCORE + tokens[tokens.length - 1]; } } return result; } public static String fileNameToDisplay(String fileName) { if (null == fileName || fileName.length() < 1) { return null; } // Remove the RAML file standard prefix int len = Constants.RAML_FILE_PREFIX.length(); if (len > 0) { if (fileName.startsWith(Constants.RAML_FILE_PREFIX)) { fileName = fileName.substring(len); } } // Removing the file extension int index = fileName.lastIndexOf('.'); fileName = fileName.substring(0, index); return fileName; } public static String displayToFileName(String displayName) { if (null == displayName || displayName.length() < 1) { return null; } String fileName; // Adding the prefix fileName = Constants.RAML_FILE_PREFIX + displayName; // Adding the file extension fileName = fileName + Constants.RAML_FILE_EXTENSION; return fileName; } public static String getAutomationStatus(boolean status) { if (status) { return Constants.ENABLED; } else { return Constants.DISABLED; } } public static String getAutomationString(boolean status) { if (status) { return Constants.ENABLE; } else { return Constants.DISABLE; } } public static boolean getAutomationBoolean(String status) { if (null != status) { if (status.equals(Constants.ENABLE)) { return true; } } return false; } public static int getUpdateIntervalFromString(String value) { int result = Constants.DEFAULT_AUTOMATION_INTERVAL; if (null != value) { try { result = Integer.parseInt(value); } catch (NumberFormatException nfe) { System.out .println("Getting UpdateInterval from string failed!"); } } return result; } public static List<String> convertSetToList(Set<String> typeSet) { if (null == typeSet) { return null; } List<String> list = new ArrayList<String>(); Iterator<String> typeItr = typeSet.iterator(); while (typeItr.hasNext()) { list.add(typeItr.next()); } return list; } }
1,640
423
# Copyright (c) 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. from torch.utils._pytree import tree_flatten, tree_unflatten def tree_map_(fn_, pytree): flat_args, _ = tree_flatten(pytree) [fn_(arg) for arg in flat_args] return pytree class PlaceHolder(): def __repr__(self): return '*' def treespec_pprint(spec): leafs = [PlaceHolder() for _ in range(spec.num_leaves)] result = tree_unflatten(leafs, spec) return repr(result)
219
315
<reponame>FredrikBlomgren/aff3ct #include "Factory/Module/Encoder/RSC/Encoder_RSC.hpp" #include "Factory/Module/Decoder/RSC/Decoder_RSC.hpp" #include "Factory/Tools/Codec/RSC/Codec_RSC.hpp" using namespace aff3ct; using namespace aff3ct::factory; const std::string aff3ct::factory::Codec_RSC_name = "Codec RSC"; const std::string aff3ct::factory::Codec_RSC_prefix = "cdc"; Codec_RSC ::Codec_RSC(const std::string &prefix) : Codec_SISO(Codec_RSC_name, prefix) { Codec::set_enc(new Encoder_RSC("enc")); Codec::set_dec(new Decoder_RSC("dec")); } Codec_RSC* Codec_RSC ::clone() const { return new Codec_RSC(*this); } void Codec_RSC ::get_description(cli::Argument_map_info &args) const { Codec_SISO::get_description(args); enc->get_description(args); dec->get_description(args); auto pdec = dec->get_prefix(); args.erase({pdec+"-cw-size", "N"}); args.erase({pdec+"-info-bits", "K"}); args.erase({pdec+"-no-buff" }); args.erase({pdec+"-poly" }); args.erase({pdec+"-std" }); } void Codec_RSC ::store(const cli::Argument_map_value &vals) { Codec_SISO::store(vals); auto enc_rsc = dynamic_cast<Encoder_RSC*>(enc.get()); auto dec_rsc = dynamic_cast<Decoder_RSC*>(dec.get()); enc->store(vals); dec_rsc->K = enc_rsc->K; dec_rsc->N_cw = enc_rsc->N_cw; dec_rsc->buffered = enc_rsc->buffered; dec_rsc->poly = enc_rsc->poly; dec_rsc->standard = enc_rsc->standard; dec->store(vals); K = enc->K; N_cw = enc->N_cw; N = enc->N_cw; tail_length = enc->tail_length; } void Codec_RSC ::get_headers(std::map<std::string,tools::header_list>& headers, const bool full) const { Codec_SISO::get_headers(headers, full); enc->get_headers(headers, full); dec->get_headers(headers, full); } template <typename B, typename Q> tools::Codec_RSC<B,Q>* Codec_RSC ::build(const module::CRC<B>* crc) const { return new tools::Codec_RSC<B,Q>(dynamic_cast<const Encoder_RSC&>(*enc), dynamic_cast<const Decoder_RSC&>(*dec)); } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef AFF3CT_MULTI_PREC template aff3ct::tools::Codec_RSC<B_8 ,Q_8 >* aff3ct::factory::Codec_RSC::build<B_8 ,Q_8 >(const aff3ct::module::CRC<B_8 >*) const; template aff3ct::tools::Codec_RSC<B_16,Q_16>* aff3ct::factory::Codec_RSC::build<B_16,Q_16>(const aff3ct::module::CRC<B_16>*) const; template aff3ct::tools::Codec_RSC<B_32,Q_32>* aff3ct::factory::Codec_RSC::build<B_32,Q_32>(const aff3ct::module::CRC<B_32>*) const; template aff3ct::tools::Codec_RSC<B_64,Q_64>* aff3ct::factory::Codec_RSC::build<B_64,Q_64>(const aff3ct::module::CRC<B_64>*) const; #else template aff3ct::tools::Codec_RSC<B,Q>* aff3ct::factory::Codec_RSC::build<B,Q>(const aff3ct::module::CRC<B>*) const; #endif // ==================================================================================== explicit template instantiation
1,296
357
/* * Copyright (c) 2012-2015 VMware, 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.vmware.identity.util; import java.util.Date; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.Validate; /** * This class represents a period of time. The time interval can be restricted * [startTime, endTime), even from one side like [startTime, +Inf) or (-Inf, * endTime) or not restricted (-Inf,+Inf). */ public final class TimePeriod { private final Date startTime; private final Date endTime; /** * Creates time interval [startTime, endTime) if times are not null. Creates * time interval (-Inf, endTime) if start time is null. Creates time interval * [startTime, +Inf) if end time is null. Creates time interval (-Inf, +Inf) * if both times are null. * * @param startTime * as UTC milliseconds from the epoch. Can be null. * @param endTime * as UTC milliseconds from the epoch. Should be after start time, * if it is not null. Can be null. * @throws IllegalArgumentException * when start and end times are not null and the end time is not * greater than start time */ public TimePeriod(Date startTime, Date endTime) { if (startTime != null && endTime != null && !endTime.after(startTime)) { throw new IllegalArgumentException("EndTime: " + endTime + " is not after startTime: " + startTime); } this.startTime = startTime; this.endTime = endTime; } /** * Creates time interval [startTime, startTime + duration). * * @param startTime * cannot be null. * @param duration * time period length in milliseconds. Should be positive. * @throws IllegalArgumentException * when the start time is null or duration is not positive number */ public TimePeriod(Date startTime, long duration) { Validate.notNull(startTime); Validate.isTrue(duration > 0); this.startTime = startTime; this.endTime = new Date(startTime.getTime() + duration); } /** * @return period start time. Can be null, which means -Inf. */ public Date getStartTime() { return startTime; } /** * @return period end time. Can be null, which means +Inf. */ public Date getEndTime() { return endTime; } /** * * @param pointOfTime * cannot be null * @return if given pointOfTime is in this time period. If this period has * start and end times this point of time can match with start time * but not with end time, meaning if start and end times are not null * the point of time is compared to this interval inclusive the start * time, exclusive the end time. */ public boolean contains(Date pointOfTime) { Validate.notNull(pointOfTime); boolean result = true; if (startTime != null) { result &= (pointOfTime.compareTo(startTime) >= 0); } if (endTime != null) { result &= pointOfTime.before(endTime); } return result; } /** * @param period * of time for expansion. Cannot be null. * @param tolerance * in milliseconds. Non-negative. * @return left and right expanded interval with given time. If interval is * opened expansion is applied only on closed side of interval. */ public static TimePeriod expand(TimePeriod period, long tolerance) { Validate.notNull(period); Validate.isTrue(tolerance >= 0); if (tolerance == 0) { return period; } Date startTime = period.getStartTime(); startTime = (startTime != null) ? new Date(startTime.getTime() - tolerance) : null; Date endTime = period.getEndTime(); endTime = (endTime != null) ? new Date(endTime.getTime() + tolerance) : null; return new TimePeriod(startTime, endTime); } @Override public String toString() { return "TimePeriod [startTime=" + (startTime == null ? "-Inf" : startTime) + ", endTime=" + (endTime == null ? "+Inf" : endTime) + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ObjectUtils.hashCode(endTime); result = prime * result + ObjectUtils.hashCode(startTime); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } TimePeriod other = (TimePeriod) obj; return ObjectUtils.equals(startTime, other.startTime) && ObjectUtils.equals(endTime, other.endTime); } }
2,003
2,123
<gh_stars>1000+ require_extension('M'); require_rv64; WRITE_RD(sext32(RS1 * RS2));
39
14,668
// 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. #ifndef CHROME_BROWSER_ASH_LOGIN_SCREENS_TPM_ERROR_SCREEN_H_ #define CHROME_BROWSER_ASH_LOGIN_SCREENS_TPM_ERROR_SCREEN_H_ #include <string> #include "chrome/browser/ash/login/screens/base_screen.h" // TODO(https://crbug.com/1164001): move to forward declaration #include "chrome/browser/ui/webui/chromeos/login/tpm_error_screen_handler.h" namespace ash { // Controller for the tpm error screen. class TpmErrorScreen : public BaseScreen { public: explicit TpmErrorScreen(TpmErrorView* view); TpmErrorScreen(const TpmErrorScreen&) = delete; TpmErrorScreen& operator=(const TpmErrorScreen&) = delete; ~TpmErrorScreen() override; // Called when the screen is being destroyed. This should call Unbind() on the // associated View if this class is destroyed before that. void OnViewDestroyed(TpmErrorView* view); private: // BaseScreen: void ShowImpl() override; void HideImpl() override; void OnUserAction(const std::string& action_id) override; TpmErrorView* view_ = nullptr; }; } // namespace ash // TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos // source migration is finished. namespace chromeos { using ::ash::TpmErrorScreen; } #endif // CHROME_BROWSER_ASH_LOGIN_SCREENS_TPM_ERROR_SCREEN_H_
471
624
<filename>examples/plot_compute_emd.py<gh_stars>100-1000 # -*- coding: utf-8 -*- """ ================== OT distances in 1D ================== Shows how to compute multiple Wassersein and Sinkhorn with two different ground metrics and plot their values for different distributions. """ # Author: <NAME> <<EMAIL>> # # License: MIT License # sphinx_gallery_thumbnail_number = 2 import numpy as np import matplotlib.pylab as pl import ot from ot.datasets import make_1D_gauss as gauss ############################################################################## # Generate data # ------------- #%% parameters n = 100 # nb bins n_target = 20 # nb target distributions # bin positions x = np.arange(n, dtype=np.float64) lst_m = np.linspace(20, 90, n_target) # Gaussian distributions a = gauss(n, m=20, s=5) # m= mean, s= std B = np.zeros((n, n_target)) for i, m in enumerate(lst_m): B[:, i] = gauss(n, m=m, s=5) # loss matrix and normalization M = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)), 'euclidean') M /= M.max() * 0.1 M2 = ot.dist(x.reshape((n, 1)), x.reshape((n, 1)), 'sqeuclidean') M2 /= M2.max() * 0.1 ############################################################################## # Plot data # --------- #%% plot the distributions pl.figure(1) pl.subplot(2, 1, 1) pl.plot(x, a, 'r', label='Source distribution') pl.title('Source distribution') pl.subplot(2, 1, 2) for i in range(n_target): pl.plot(x, B[:, i], 'b', alpha=i / n_target) pl.plot(x, B[:, -1], 'b', label='Target distributions') pl.title('Target distributions') pl.tight_layout() ############################################################################## # Compute EMD for the different losses # ------------------------------------ #%% Compute and plot distributions and loss matrix d_emd = ot.emd2(a, B, M) # direct computation of OT loss d_emd2 = ot.emd2(a, B, M2) # direct computation of OT loss with metrixc M2 d_tv = [np.sum(abs(a - B[:, i])) for i in range(n_target)] pl.figure(2) pl.subplot(2, 1, 1) pl.plot(x, a, 'r', label='Source distribution') pl.title('Distributions') for i in range(n_target): pl.plot(x, B[:, i], 'b', alpha=i / n_target) pl.plot(x, B[:, -1], 'b', label='Target distributions') pl.ylim((-.01, 0.13)) pl.xticks(()) pl.legend() pl.subplot(2, 1, 2) pl.plot(d_emd, label='Euclidean OT') pl.plot(d_emd2, label='Squared Euclidean OT') pl.plot(d_tv, label='Total Variation (TV)') #pl.xlim((-7,23)) pl.xlabel('Displacement') pl.title('Divergences') pl.legend() ############################################################################## # Compute Sinkhorn for the different losses # ----------------------------------------- #%% reg = 1e-1 d_sinkhorn = ot.sinkhorn2(a, B, M, reg) d_sinkhorn2 = ot.sinkhorn2(a, B, M2, reg) pl.figure(3) pl.clf() pl.subplot(2, 1, 1) pl.plot(x, a, 'r', label='Source distribution') pl.title('Distributions') for i in range(n_target): pl.plot(x, B[:, i], 'b', alpha=i / n_target) pl.plot(x, B[:, -1], 'b', label='Target distributions') pl.ylim((-.01, 0.13)) pl.xticks(()) pl.legend() pl.subplot(2, 1, 2) pl.plot(d_emd, label='Euclidean OT') pl.plot(d_emd2, label='Squared Euclidean OT') pl.plot(d_sinkhorn, '+', label='Euclidean Sinkhorn') pl.plot(d_sinkhorn2, '+', label='Squared Euclidean Sinkhorn') pl.plot(d_tv, label='Total Variation (TV)') #pl.xlim((-7,23)) pl.xlabel('Displacement') pl.title('Divergences') pl.legend() pl.show()
1,308
837
<filename>app/src/main/java/me/saket/dank/utils/itemanimators/SubmissionCommentsItemAnimator.java package me.saket.dank.utils.itemanimators; import android.view.View; public class SubmissionCommentsItemAnimator extends SlideAlphaAnimator<SubmissionCommentsItemAnimator> { public SubmissionCommentsItemAnimator(int itemViewElevation) { super(itemViewElevation); } @Override protected float getAnimationTranslationX(View itemView) { return 0; } protected float getAnimationTranslationY(View itemView) { return -dpToPx(32, itemView.getContext()); } }
184
360
#ifndef TZW_GLFW_BACKEND_H #define TZW_GLFW_BACKEND_H #include "../WindowBackEnd.h" #define NOMINMAX class GLFWwindow; namespace tzw { class GLFW_BackEnd : public WindowBackEnd { public: void prepare(int width, int height, bool isFullScreen) override; void run() override; GLFW_BackEnd(); void setUnlimitedCursor(bool enable) override; void getMousePos(double* posX, double* posY) override; int getMouseButton(int buttonMode) override; void setWinSize(int width, int height) override; void setIsFullScreen(bool isFullScreen) override; void changeScreenSetting(int w, int h, bool isFullScreen) override; private: GLFWwindow * m_window; bool glfwSetWindowCenter( GLFWwindow * window ); float m_w,m_h; }; } // namespace tzw #endif // TZW_GLFW_BACKEND_H
283
897
#include <iostream> using namespace std; //Recursion+Memoization int fib(int n,int dp[]){ //base case if(n == 0 || n == 1) return n; //Recursive //Look Up if(dp[n] != 0) return dp[n]; int ans; ans = fib(n-1,dp)+fib(n-2,dp); return dp[n] = ans; } int main() { int n; cin>>n; int dp[n+1]={0}; cout<<"output :"<<fib(n,dp)<<endl; return 0; } /* sample input output input: 10 output: 55 */ /* Space O(n) Time O(n) */
209
311
<reponame>witquicked/fetlife-android package com.bitlove.fetlife.event; import com.bitlove.fetlife.model.service.FetLifeApiIntentService; public class VideoChunkUploadFinishedEvent extends ServiceCallFinishedEvent { private final int chunk; private final int chunkCount; private String videoId; public VideoChunkUploadFinishedEvent(String videoId, int chunk, int chunkCount) { super(FetLifeApiIntentService.ACTION_APICALL_UPLOAD_VIDEO_CHUNK, chunkCount); this.videoId = videoId; this.chunk = chunk; this.chunkCount = chunkCount; } public String getVideoId() { return videoId; } public int getChunk() { return chunk; } public int getChunkCount() { return chunkCount; } }
298
688
<reponame>NielsRogge/scenic """Tests for model.py.""" import functools from absl.testing import absltest from absl.testing import parameterized from jax import random import jax.numpy as jnp from scenic.projects.token_learner import model class TokenLearnerTest(parameterized.TestCase): """Tests for modules in token-learner model.py.""" @parameterized.named_parameters( ('32_tokens', 32), ('111_tokens', 111), ) def test_dynamic_tokenizer(self, num_tokens): """Tests TokenLearner module.""" rng = random.PRNGKey(0) x = jnp.ones((4, 224, 224, 64)) tokenizer = functools.partial(model.TokenLearnerModule, num_tokens=num_tokens) tokenizer_vars = tokenizer().init(rng, x) y = tokenizer().apply(tokenizer_vars, x) # Test outputs shape. self.assertEqual(y.shape, (x.shape[0], num_tokens, x.shape[-1])) @parameterized.named_parameters( ('encoder_image', (2, 16, 192), 'dynamic', 1, 8, model.EncoderMod), ('encoder_video_temporal_dims_1', (2, 16, 192), 'video', 1, 8, model.EncoderMod), ('encoder_video_temporal_dims_2', (2, 32, 192), 'video', 2, 8, model.EncoderMod), ('encoder_video_temporal_dims_4', (2, 64, 192), 'video', 4, 8, model.EncoderMod), ('encoder_fusion_image', (2, 16, 192), 'dynamic', 1, 8, model.EncoderModFuser), ('encoder_fusion_video_temporal_dims_1', (2, 16, 192), 'video', 1, 8, model.EncoderModFuser), ('encoder_fusion_video_temporal_dims_2', (2, 32, 192), 'video', 2, 8, model.EncoderModFuser), ('encoder_fusion_video_temporal_dims_4', (2, 64, 192), 'video', 4, 8, model.EncoderModFuser), ) def test_encoder(self, input_shape, tokenizer_type, temporal_dimensions, num_tokens, encoder_function): """Tests shapes of TokenLearner Encoder (with and without TokenFuser).""" rng = random.PRNGKey(0) dummy_input = jnp.ones(input_shape) encoder = functools.partial( encoder_function, num_layers=3, mlp_dim=192, num_heads=3, tokenizer_type=tokenizer_type, temporal_dimensions=temporal_dimensions, num_tokens=num_tokens, tokenlearner_loc=2) encoder_vars = encoder().init(rng, dummy_input) y = encoder().apply(encoder_vars, dummy_input) if encoder_function == model.EncoderMod: if tokenizer_type == 'dynamic': expected_shape = (input_shape[0], num_tokens, input_shape[2]) elif tokenizer_type == 'video': expected_shape = ( input_shape[0], num_tokens * temporal_dimensions, input_shape[2]) else: raise ValueError('Unknown tokenizer type.') elif encoder_function == model.EncoderModFuser: expected_shape = input_shape else: raise ValueError('Unknown encoder function.') self.assertEqual(y.shape, expected_shape) if __name__ == '__main__': absltest.main()
1,298
389
#pragma once #include "ligra.h" #include "histogram.h" // edgeMapInduced // Version of edgeMapSparse that maps over the one-hop frontier and returns it as // a sparse array, without filtering. template <class E, class vertex, class VS, class F> inline vertexSubsetData<E> edgeMapInduced(graph<vertex>& GA, VS& V, F& f) { vertex *G = GA.V; uintT m = V.size(); V.toSparse(); auto degrees = array_imap<uintT>(m); granular_for(i, 0, m, (m > 2000), { vertex v = G[V.vtx(i)]; uintE degree = v.getOutDegree(); degrees[i] = degree; }); long outEdgeCount = pbbs::scan_add(degrees, degrees); if (outEdgeCount == 0) { return vertexSubsetData<E>(GA.n); } typedef tuple<uintE, E> VE; VE* outEdges = pbbs::new_array_no_init<VE>(outEdgeCount); auto gen = [&] (const uintE& ngh, const uintE& offset, const Maybe<E>& val = Maybe<E>()) { outEdges[offset] = make_tuple(ngh, val.t); }; parallel_for (size_t i = 0; i < m; i++) { uintT o = degrees[i]; auto v = V.vtx(i); G[v].template copyOutNgh<E>(v, o, f, gen); } auto vs = vertexSubsetData<E>(GA.n, outEdgeCount, outEdges); return vs; } template <class V, class vertex> struct EdgeMap { using K = uintE; // keys are always uintE's (vertex-identifiers) using KV = tuple<K, V>; graph<vertex>& G; pbbs::hist_table<K, V> ht; EdgeMap(graph<vertex>& _G, KV _empty, size_t ht_size=numeric_limits<size_t>::max()) : G(_G) { if (ht_size == numeric_limits<size_t>::max()) { ht_size = 1L << pbbs::log2_up(G.m/20); } else { ht_size = 1L << pbbs::log2_up(ht_size); } ht = pbbs::hist_table<K, V>(_empty, ht_size); } // map_f: (uintE v, uintE ngh) -> E // reduce_f: (E, tuple(uintE ngh, E ngh_val)) -> E // apply_f: (uintE ngh, E reduced_val) -> O template <class O, class M, class Map, class Reduce, class Apply, class VS> inline vertexSubsetData<O> edgeMapReduce(VS& vs, Map& map_f, Reduce& reduce_f, Apply& apply_f) { size_t m = vs.size(); if (m == 0) { return vertexSubsetData<O>(vs.numNonzeros()); } auto oneHop = edgeMapInduced<M, vertex, VS, Map>(G, vs, map_f); oneHop.toSparse(); auto get_elm = make_in_imap<tuple<K, M> >(oneHop.size(), [&] (size_t i) { return oneHop.vtxAndData(i); }); auto get_key = make_in_imap<uintE>(oneHop.size(), [&] (size_t i) -> uintE { return oneHop.vtx(i); }); auto q = [&] (sequentialHT<K, V>& S, tuple<K, M> v) -> void { S.template insertF<M>(v, reduce_f); }; auto res = pbbs::histogram_reduce<tuple<K, M>, tuple<K, O> >(get_elm, get_key, oneHop.size(), q, apply_f, ht); oneHop.del(); return vertexSubsetData<O>(vs.numNonzeros(), res.first, res.second); } template <class O, class Apply, class VS> inline vertexSubsetData<O> edgeMapCount(VS& vs, Apply& apply_f) { auto map_f = [] (const uintE& i, const uintE& j) { return pbbs::empty(); }; auto reduce_f = [&] (const uintE& cur, const tuple<uintE, pbbs::empty>& r) { return cur + 1; }; return edgeMapReduce<O, pbbs::empty>(vs, map_f, reduce_f, apply_f); } ~EdgeMap() { ht.del(); } };
1,323
619
/* * Copyright 2016 <NAME> * * 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 &quot;AS IS&quot; 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 de.javakaffee.web.msm.serializer.kryo; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.serializers.CollectionSerializer; import com.esotericsoftware.kryo.util.DefaultClassResolver; import com.esotericsoftware.kryo.util.DefaultStreamFactory; import com.esotericsoftware.kryo.util.MapReferenceResolver; import org.objenesis.strategy.InstantiatorStrategy; import org.objenesis.strategy.StdInstantiatorStrategy; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.Collection; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; public class KryoBuilderTest { @DataProvider public static Object[][] buildKryoProvider() { return new Object[][] { { new BuildKryo("customizationsFirst") { @Override Kryo build(DefaultClassResolver classResolver, MapReferenceResolver referenceResolver, DefaultStreamFactory streamFactory, InstantiatorStrategy instantiatorStrategy, KryoCustomization enableAsm, KryoCustomization registerMyCollectionSerializer) { return new KryoBuilder() .withKryoCustomization(enableAsm) .withKryoCustomization(registerMyCollectionSerializer) .withClassResolver(classResolver) .withReferenceResolver(referenceResolver) .withStreamFactory(streamFactory) .withInstantiatorStrategy(instantiatorStrategy) .withRegistrationRequired(true) // Kryo default is false .withReferences(false) // Kryo default is true .withOptimizedGenerics(false) .build(); } } }, { new BuildKryo("customizationsLast") { @Override Kryo build(DefaultClassResolver classResolver, MapReferenceResolver referenceResolver, DefaultStreamFactory streamFactory, InstantiatorStrategy instantiatorStrategy, KryoCustomization enableAsm, KryoCustomization registerMyCollectionSerializer) { return new KryoBuilder() .withClassResolver(classResolver) .withReferenceResolver(referenceResolver) .withStreamFactory(streamFactory) .withInstantiatorStrategy(instantiatorStrategy) .withRegistrationRequired(true) // Kryo default is false .withReferences(false) // Kryo default is true .withOptimizedGenerics(false) .withKryoCustomization(enableAsm) .withKryoCustomization(registerMyCollectionSerializer) .build(); } } } }; } @Test(dataProvider = "buildKryoProvider") public void testKryoBuilder(BuildKryo buildKryo) { DefaultClassResolver classResolver = new DefaultClassResolver(); MapReferenceResolver referenceResolver = new MapReferenceResolver(); DefaultStreamFactory streamFactory = new DefaultStreamFactory(); InstantiatorStrategy instantiatorStrategy = new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()); KryoCustomization enableAsm = new KryoCustomization() { @Override public void customize(Kryo kryo) { kryo.getFieldSerializerConfig().setUseAsm(true); // Kryo default false } }; final CollectionSerializer collectionSerializer = new CollectionSerializer(); KryoCustomization registerMyCollectionSerializer = new KryoCustomization() { @Override public void customize(Kryo kryo) { kryo.addDefaultSerializer(Collection.class, collectionSerializer); } }; Kryo kryo = buildKryo.build(classResolver, referenceResolver, streamFactory, instantiatorStrategy, enableAsm, registerMyCollectionSerializer); assertSame(kryo.getClassResolver(), classResolver); assertSame(kryo.getReferenceResolver(), referenceResolver); assertSame(kryo.getStreamFactory(), streamFactory); assertSame(kryo.getInstantiatorStrategy(), instantiatorStrategy); assertTrue(kryo.isRegistrationRequired()); assertFalse(kryo.getReferences()); assertTrue(kryo.getFieldSerializerConfig().isUseAsm()); assertSame(kryo.getDefaultSerializer(Collection.class), collectionSerializer); assertFalse(kryo.getFieldSerializerConfig().isOptimizedGenerics()); } static abstract class BuildKryo { private final String description; BuildKryo(String description) { this.description = description; } abstract Kryo build(DefaultClassResolver classResolver, MapReferenceResolver referenceResolver, DefaultStreamFactory streamFactory, InstantiatorStrategy instantiatorStrategy, KryoCustomization enableAsm, KryoCustomization registerMyCollectionSerializer); @Override public String toString() { return getClass().getSimpleName() + "(" + description + ")"; } } }
1,833
567
import sys import os def get_env(name): if name not in os.environ: sys.exit(name + " env var not set") return os.environ[name] def batch(iterable, n=1): current_batch = [] for item in iterable: if item is not None : current_batch.append(item) if len(current_batch) >= n: yield current_batch current_batch = [] if current_batch: yield current_batch
185
344
<gh_stars>100-1000 /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "dup": "Il comando `{0}` è presente più volte nella sezione `commands`.", "dupe.command": "La voce di menu fa riferimento allo stesso comando come comando predefinito e come comando alternativo", "menuId.invalid": "`{0}` non è un identificatore di menu valido", "menus.editorContext": "Menu di scelta rapida dell'editor", "menus.editorTitle": "Menu del titolo dell'editor", "menus.explorerContext": "Menu di scelta rapida Esplora file", "missing.altCommand": "La voce di menu fa riferimento a un comando alternativo `{0}` che non è definito nella sezione 'commands'.", "missing.command": "La voce di menu fa riferimento a un comando `{0}` che non è definito nella sezione 'commands'.", "nonempty": "è previsto un valore non vuoto.", "nosupport.altCommand": "I comandi alternativi sono attualmente supportati solo nel gruppo 'navigation' del menu 'editor/title'", "opticon": "la proprietà `icon` può essere omessa o deve essere una stringa o un valore letterale come `{dark, light}`", "optstring": "la proprietà `{0}` può essere omessa o deve essere di tipo `string`", "requirearry": "le voci di menu devono essere una matrice", "requirestring": "la proprietà `{0}` è obbligatoria e deve essere di tipo `string`", "vscode.extension.contributes.commandType.category": "(Facoltativo) Stringa di categoria in base a cui è raggruppato il comando nell'interfaccia utente", "vscode.extension.contributes.commandType.command": "Identificatore del comando da eseguire", "vscode.extension.contributes.commandType.icon": "(Facoltativa) Icona usata per rappresentare il comando nell'interfaccia utente. Percorso di file o configurazione che supporta i temi", "vscode.extension.contributes.commandType.icon.dark": "Percorso dell'icona quando viene usato un tema scuro", "vscode.extension.contributes.commandType.icon.light": "Percorso dell'icona quando viene usato un tema chiaro", "vscode.extension.contributes.commandType.title": "Titolo con cui è rappresentato il comando nell'interfaccia utente", "vscode.extension.contributes.commands": "Comandi di contributes per il riquadro comandi.", "vscode.extension.contributes.menuItem.alt": "Identificatore di un comando alternativo da eseguire. Il comando deve essere dichiarato nella sezione 'commands'", "vscode.extension.contributes.menuItem.command": "Identificatore del comando da eseguire. Il comando deve essere dichiarato nella sezione 'commands'", "vscode.extension.contributes.menuItem.group": "Gruppo a cui appartiene questo comando", "vscode.extension.contributes.menuItem.when": "Condizione che deve essere vera per mostrare questo elemento", "vscode.extension.contributes.menus": "Aggiunge voci del menu all'editor come contributo" }
1,047
1,020
<reponame>icse18-refactorings/RoboBinding package org.robobinding.codegen.viewbinding; import org.apache.commons.lang3.StringUtils; import org.robobinding.codegen.apt.element.SetterElement; import org.robobinding.codegen.apt.type.WrappedPrimitiveType; import org.robobinding.codegen.apt.type.WrappedTypeMirror; import org.robobinding.util.Objects; import com.helger.jcodemodel.JDefinedClass; /** * @since 1.0 * @author <NAME> * */ public class SimpleOneWayPropertyInfo { private final SetterElement setter; private JDefinedClass bindingType; public SimpleOneWayPropertyInfo(SetterElement setter) { this.setter = setter; } public String propertySetter() { return setter.methodName(); } public String propertyType() { WrappedTypeMirror parameterType = setter.parameterType(); if(parameterType.isPrimitive()) { return ((WrappedPrimitiveType)parameterType).boxedClassName(); } else { return parameterType.className(); } } public String propertyName() { return setter.propertyName(); } public JDefinedClass getBindingClass() { return bindingType; } public JDefinedClass defineBindingClass(ClassDefinitionCallback callback) { bindingType = callback.define(bindingTypeName()); return bindingType; } String bindingTypeName() { return StringUtils.capitalize(propertyName())+"Attribute"; } @Override public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof SimpleOneWayPropertyInfo)) return false; final SimpleOneWayPropertyInfo that = (SimpleOneWayPropertyInfo) other; return Objects.equal(setter, that.setter) && Objects.equal(bindingType, that.bindingType); } @Override public int hashCode() { return Objects.hashCode(setter) + Objects.hashCode(bindingType); } }
685
1,467
<reponame>Deluxe123123/aws-sdk-java-v2<gh_stars>1000+ package software.amazon.awssdk.services.json.model.eventstream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.json.model.EventOne; import software.amazon.awssdk.services.json.model.EventStream; import software.amazon.awssdk.services.json.model.EventStreamOperationResponseHandler; import software.amazon.awssdk.services.json.model.EventStreamOperationWithOnlyOutputResponseHandler; /** * A specialization of {@code software.amazon.awssdk.services.json.model.EventOne} that represents the * {@code EventStream$secondEventOne} event. Do not use this class directly. Instead, use the static builder methods on * {@link software.amazon.awssdk.services.json.model.EventStream}. */ @SdkInternalApi @Generated("software.amazon.awssdk:codegen") public final class DefaultSecondEventOne extends EventOne { private static final long serialVersionUID = 1L; DefaultSecondEventOne(BuilderImpl builderImpl) { super(builderImpl); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } @Override public void accept(EventStreamOperationResponseHandler.Visitor visitor) { visitor.visitSecondEventOne(this); } @Override public void accept(EventStreamOperationWithOnlyOutputResponseHandler.Visitor visitor) { visitor.visitSecondEventOne(this); } @Override public EventStream.EventType sdkEventType() { return EventStream.EventType.SECOND_EVENT_ONE; } public interface Builder extends EventOne.Builder { @Override DefaultSecondEventOne build(); } private static final class BuilderImpl extends EventOne.BuilderImpl implements Builder { private BuilderImpl() { } private BuilderImpl(DefaultSecondEventOne event) { super(event); } @Override public DefaultSecondEventOne build() { return new DefaultSecondEventOne(this); } } }
737
675
/* * Copyright 2018 The Bazel Authors. 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.google.idea.blaze.cpp; import com.google.common.collect.ImmutableMap; import com.google.idea.blaze.base.logging.EventLoggingService; import com.google.idea.blaze.base.settings.Blaze; import com.intellij.ide.actions.ShowFilePathAction; import com.intellij.notification.Notification; import com.intellij.notification.NotificationDisplayType; import com.intellij.notification.NotificationGroup; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ModuleRootModificationUtil; import com.intellij.openapi.roots.impl.storage.ClassPathStorageUtil; import com.intellij.openapi.roots.impl.storage.ClasspathStorage; import com.intellij.openapi.roots.libraries.LibraryTable; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import javax.swing.event.HyperlinkEvent; /** * Notify users to convert old CMake+Blaze projects into pure Blaze projects, and avoid scanning * overly broad roots. * * <p>If CMake claims a module before Blaze is able to claim it with {@link * com.google.idea.blaze.clwb.BlazeCppModuleType} (old projects), then it may make modifications to * (1) the "classpath", and (2) content entries + libraries. The libraries may be okay, but the * content entries are likely too broad: b/79884939 and cause "Scanning files" to run ~forever. * * <p>#api181: After enough modules are migrated to BlazeCppModuleType, perhaps this will become * unnecessary. See EventLoggingService data to see how often this comes up. */ class CMakeWorkspaceOverride { static void undoCMakeModifications(Project project) { if (!Blaze.isBlazeProject(project)) { return; } boolean notified = false; for (Module module : getCMakeModules(project)) { clearClasspath(module); clearContentRootsAndLibrariesIfModifiedForCMake(module); if (!notified) { suggestRemedies(project); notified = true; } } } /** Get any modules marked with the CMake classpath */ private static List<Module> getCMakeModules(Project project) { // We could check for old CPP_MODULE type, but some modules are already partially migrated to // the new BLAZE_CPP_MODULE type. Instead, check for the CMake "classpath". return Arrays.stream(ModuleManager.getInstance(project).getModules()) .filter(module -> "CMake".equals(ClassPathStorageUtil.getStorageType(module))) .collect(Collectors.toList()); } private static void clearClasspath(Module module) { ClasspathStorage.setStorageType( ModuleRootManager.getInstance(module), ClassPathStorageUtil.DEFAULT_STORAGE); Logger.getInstance(CMakeWorkspaceOverride.class).warn("Had to clear CMake classpath"); EventLoggingService.getInstance() .logEvent(CMakeWorkspaceOverride.class, "cleared-cmake-classpath", ImmutableMap.of()); } private static void clearContentRootsAndLibrariesIfModifiedForCMake(Module module) { ModuleRootModificationUtil.updateModel( module, modifiableModel -> { if (areLibrariesAndRootsModifiedByCMake(modifiableModel)) { // Nuke the roots from orbit. modifiableModel.clear(); } }); } private static boolean areLibrariesAndRootsModifiedByCMake(ModifiableRootModel modifiableModel) { LibraryTable table = modifiableModel.getModuleLibraryTable(); return table.getLibraryByName("Header Search Paths") != null; } private static void suggestRemedies(Project project) { Logger.getInstance(CMakeWorkspaceOverride.class) .warn("Need to migrate hybrid CMake+Blaze project"); EventLoggingService.getInstance() .logEvent( CMakeWorkspaceOverride.class, "must-migrate-hybrid-cmake-blaze-project", ImmutableMap.of()); String projectFilePath = project.getProjectFilePath(); if (projectFilePath == null) { return; } File projectFile = new File(projectFilePath); NotificationGroup notificationGroup = new NotificationGroup("Migrate CMake Module", NotificationDisplayType.STICKY_BALLOON, true); NotificationListener notificationListener = new NotificationListener.Adapter() { @Override protected void hyperlinkActivated(Notification notification, HyperlinkEvent event) { notification.expire(); ShowFilePathAction.openFile(projectFile); EventLoggingService.getInstance() .logEvent( CMakeWorkspaceOverride.class, "must-migrate-hybrid-cmake-blaze-opened-xml", ImmutableMap.of()); } }; Notification notification = new Notification( notificationGroup.getDisplayId(), "CMake -> Blaze C++ Conversion Required", "Detected old CMake/Blaze project.<br>" + "Please reimport the project. Or, try these manual steps:<br>" + "<ul>" + " <li>Open <a href=\"open_project_xml\">" + projectFile.getName() + "</a>" + " <li>Close project" + " <li>Remove &lt;component name=\"CMakeWorkspace\" " + "PROJECT_DIR=\"$PROJECT_DIR$\" /&gt;" + " <li>Reopen project." + " <li>Re-run blaze sync." + "</ul>", NotificationType.WARNING, notificationListener); notification.setImportant(true); notification.notify(project); } }
2,361
488
<gh_stars>100-1000 [ "../../protos/google/cloud/vision/v1p3beta1/geometry.proto", "../../protos/google/cloud/vision/v1p3beta1/image_annotator.proto", "../../protos/google/cloud/vision/v1p3beta1/product_search.proto", "../../protos/google/cloud/vision/v1p3beta1/product_search_service.proto", "../../protos/google/cloud/vision/v1p3beta1/text_annotation.proto", "../../protos/google/cloud/vision/v1p3beta1/web_detection.proto" ]
185
5,355
package graphql.schema; import graphql.PublicApi; import java.util.concurrent.CompletionStage; import java.util.function.BiFunction; /** * A helper for {@link graphql.schema.DataFetcherFactory} */ @PublicApi public class DataFetcherFactories { /** * Creates a {@link graphql.schema.DataFetcherFactory} that always returns the provided {@link graphql.schema.DataFetcher} * * @param dataFetcher the data fetcher to always return * @param <T> the type of the data fetcher * * @return a data fetcher factory that always returns the provided data fetcher */ public static <T> DataFetcherFactory<T> useDataFetcher(DataFetcher<T> dataFetcher) { return fieldDefinition -> dataFetcher; } /** * This helper function allows you to wrap an existing data fetcher and map the value once it completes. It helps you handle * values that might be {@link java.util.concurrent.CompletionStage} returned values as well as plain old objects. * * @param delegateDataFetcher the original data fetcher that is present on a {@link graphql.schema.GraphQLFieldDefinition} say * @param mapFunction the bi function to apply to the original value * * @return a new data fetcher that wraps the provided data fetcher */ public static DataFetcher wrapDataFetcher(DataFetcher delegateDataFetcher, BiFunction<DataFetchingEnvironment, Object, Object> mapFunction) { return environment -> { Object value = delegateDataFetcher.get(environment); if (value instanceof CompletionStage) { //noinspection unchecked return ((CompletionStage<Object>) value).thenApply(v -> mapFunction.apply(environment, v)); } else { return mapFunction.apply(environment, value); } }; } }
680
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"<NAME>","circ":"2ème circonscription","dpt":"Haute-Loire","inscrits":490,"abs":229,"votants":261,"blancs":12,"nuls":4,"exp":245,"res":[{"nuance":"REM","nom":"<NAME>","voix":132},{"nuance":"LR","nom":"<NAME>","voix":113}]}
110
625
<reponame>renesugar/jtransc /* * 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 java.nio.channels; import java.io.IOException; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketOption; import java.nio.ByteBuffer; import java.nio.channels.spi.AbstractSelectableChannel; import java.nio.channels.spi.SelectorProvider; public abstract class SocketChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel { /** * Initializes a new instance of this class. * * @param provider * The provider that created this channel */ protected SocketChannel(SelectorProvider provider) { super(provider); } /** * Opens a socket channel. * * <p> The new channel is created by invoking the {@link * java.nio.channels.spi.SelectorProvider#openSocketChannel * openSocketChannel} method of the system-wide default {@link * java.nio.channels.spi.SelectorProvider} object. </p> * * @return A new socket channel * * @throws IOException * If an I/O error occurs */ public static SocketChannel open() throws IOException { return SelectorProvider.provider().openSocketChannel(); } /** * Opens a socket channel and connects it to a remote address. * * <p> This convenience method works as if by invoking the {@link #open()} * method, invoking the {@link #connect(SocketAddress) connect} method upon * the resulting socket channel, passing it <tt>remote</tt>, and then * returning that channel. </p> * * @param remote * The remote address to which the new channel is to be connected * * @return A new, and connected, socket channel * * @throws AsynchronousCloseException * If another thread closes this channel * while the connect operation is in progress * * @throws ClosedByInterruptException * If another thread interrupts the current thread * while the connect operation is in progress, thereby * closing the channel and setting the current thread's * interrupt status * * @throws UnresolvedAddressException * If the given remote address is not fully resolved * * @throws UnsupportedAddressTypeException * If the type of the given remote address is not supported * * @throws SecurityException * If a security manager has been installed * and it does not permit access to the given remote endpoint * * @throws IOException * If some other I/O error occurs */ public static SocketChannel open(SocketAddress remote) throws IOException { SocketChannel sc = open(); try { sc.connect(remote); } catch (Throwable x) { try { sc.close(); } catch (Throwable suppressed) { x.addSuppressed(suppressed); } throw x; } assert sc.isConnected(); return sc; } public final int validOps() { return SelectionKey.OP_READ | SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT; } @Override public abstract SocketChannel bind(SocketAddress local) throws IOException; @Override public abstract <T> SocketChannel setOption(SocketOption<T> name, T value) throws IOException; public abstract SocketChannel shutdownInput() throws IOException; public abstract SocketChannel shutdownOutput() throws IOException; public abstract Socket socket(); public abstract boolean isConnected(); public abstract boolean isConnectionPending(); public abstract boolean connect(SocketAddress remote) throws IOException; public abstract boolean finishConnect() throws IOException; public abstract SocketAddress getRemoteAddress() throws IOException; public abstract int read(ByteBuffer dst) throws IOException; public abstract long read(ByteBuffer[] dsts, int offset, int length) throws IOException; public final long read(ByteBuffer[] dsts) throws IOException { return read(dsts, 0, dsts.length); } public abstract int write(ByteBuffer src) throws IOException; public abstract long write(ByteBuffer[] srcs, int offset, int length) throws IOException; public final long write(ByteBuffer[] srcs) throws IOException { return write(srcs, 0, srcs.length); } @Override public abstract SocketAddress getLocalAddress() throws IOException; }
1,521
395
<gh_stars>100-1000 package timely.netty.websocket.subscription; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import timely.api.request.subscription.CreateSubscription; import timely.configuration.Configuration; import timely.store.DataStore; import timely.store.cache.DataStoreCache; import timely.subscription.Subscription; import timely.subscription.SubscriptionRegistry; public class WSCreateSubscriptionRequestHandler extends SimpleChannelInboundHandler<CreateSubscription> { private static final Logger LOG = LoggerFactory.getLogger(WSCreateSubscriptionRequestHandler.class); private final DataStore store; private final DataStoreCache cache; private final Configuration conf; public WSCreateSubscriptionRequestHandler(DataStore store, DataStoreCache cache, Configuration conf) { this.store = store; this.cache = cache; this.conf = conf; } @Override protected void channelRead0(ChannelHandlerContext ctx, CreateSubscription create) throws Exception { final String subscriptionId = create.getSubscriptionId(); SubscriptionRegistry.get().put(subscriptionId, new Subscription(subscriptionId, create.getSessionId(), store, cache, ctx, this.conf)); // Store the session id as an attribute on the context. ctx.channel().attr(SubscriptionRegistry.SUBSCRIPTION_ID_ATTR).set(subscriptionId); LOG.info("[{}] Created subscription on channel {}", subscriptionId, ctx); ctx.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { Subscription s = SubscriptionRegistry.get().remove(subscriptionId); if (null != s) { LOG.info("[{}] Channel closed, closing subscriptions", subscriptionId); s.close(); } } }); } }
749
716
<filename>src/OrbitGl/AccessibleTrack.h // Copyright (c) 2020 The Orbit 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 ORBIT_GL_ACCESSIBLE_TRACK_H_ #define ORBIT_GL_ACCESSIBLE_TRACK_H_ #include <string> #include "AccessibleCaptureViewElement.h" #include "OrbitAccessibility/AccessibleInterface.h" #include "TimeGraphLayout.h" class Track; namespace orbit_gl { /* * Accessibility information for the track. * This will return a "virtual" control for the timers in addition to the actual children of the * track. The timers pane is the last child. * * TODO (b/185854980): Remove the fake elements. */ class AccessibleTrack : public AccessibleCaptureViewElement { public: AccessibleTrack(Track* track, const TimeGraphLayout* layout); [[nodiscard]] int AccessibleChildCount() const override; [[nodiscard]] const AccessibleInterface* AccessibleChild(int index) const override; [[nodiscard]] orbit_accessibility::AccessibilityState AccessibleState() const override; private: Track* track_; std::unique_ptr<CaptureViewElement> fake_timers_pane_; }; } // namespace orbit_gl #endif
360
1,893
""" Similarity module """ import numpy as np from .labels import Labels class Similarity(Labels): """ Computes similarity between query and list of text using a text classifier. """ # pylint: disable=W0222 def __call__(self, query, texts, multilabel=True): """ Computes the similarity between query and list of text. Returns a list of (id, score) sorted by highest score, where id is the index in texts. This method supports query as a string or a list. If the input is a string, the return type is a 1D list of (id, score). If text is a list, a 2D list of (id, score) is returned with a row per string. Args: query: query text|list texts: list of text Returns: list of (id, score) """ # Call Labels pipeline for texts using input query as the candidate label scores = super().__call__(texts, [query] if isinstance(query, str) else query, multilabel) # Sort on query index id scores = [[score for _, score in sorted(row)] for row in scores] # Transpose axes to get a list of text scores for each query scores = np.array(scores).T.tolist() # Build list of (id, score) per query sorted by highest score scores = [sorted(enumerate(row), key=lambda x: x[1], reverse=True) for row in scores] return scores[0] if isinstance(query, str) else scores
547
973
/*_########################################################################## _## _## Copyright (C) 2016 Pcap4J.org _## _########################################################################## */ package org.pcap4j.packet; import org.pcap4j.packet.LlcPacket.LlcControl; import org.pcap4j.packet.namednumber.LlcControlModifierFunction; import org.pcap4j.util.ByteArrays; /** * The Control field of an LLC header in U-format. * * <pre>{@code * 0 1 2 3 4 5 6 7 * +-----+-----+-----+-----+-----+-----+-----+-----+ * | modifier | P/F | modifier | 1 | 1 | * | func bits | | func bits | | | * +-----+-----+-----+-----+-----+-----+-----+-----+ * }</pre> * * @see <a href="http://standards.ieee.org/about/get/802/802.2.html">IEEE 802.2</a> * @author <NAME> * @since pcap4j 1.6.5 */ public final class LlcControlUnnumbered implements LlcControl { /** */ private static final long serialVersionUID = 8688698899763120721L; private final LlcControlModifierFunction modifierFunction; private final boolean pfBit; /** * @param value value * @return a new LlcControlSupervisory object. * @throws IllegalRawDataException if parsing the value fails. */ public static LlcControlUnnumbered newInstance(byte value) throws IllegalRawDataException { return new LlcControlUnnumbered(value); } private LlcControlUnnumbered(byte value) throws IllegalRawDataException { if ((value & 0x03) != 0x03) { StringBuilder sb = new StringBuilder(50); sb.append("Both the lsb and the second lsb of the value must be 1. value: ") .append(ByteArrays.toHexString(value, " ")); throw new IllegalRawDataException(sb.toString()); } this.modifierFunction = LlcControlModifierFunction.getInstance((byte) ((value >> 2) & 0x3B)); if ((value & 0x10) == 0) { this.pfBit = false; } else { this.pfBit = true; } } private LlcControlUnnumbered(Builder builder) { if (builder == null || builder.modifierFunction == null) { StringBuilder sb = new StringBuilder(); sb.append("builder: ") .append(builder) .append(" builder.modifierFunction: ") .append(builder.modifierFunction); throw new NullPointerException(sb.toString()); } this.modifierFunction = builder.modifierFunction; this.pfBit = builder.pfBit; } /** @return modifierFunction */ public LlcControlModifierFunction getModifierFunction() { return modifierFunction; } /** @return true if the P/F bit is set to 1; otherwise false. */ public boolean getPfBit() { return pfBit; } @Override public int length() { return 1; } @Override public byte[] getRawData() { byte[] data = new byte[1]; data[0] = (byte) (0x03 | (modifierFunction.value() << 2)); if (pfBit) { data[0] |= 0x10; } return data; } /** @return a new Builder object populated with this object's fields. */ public Builder getBuilder() { return new Builder(this); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[modifier function: ") .append(modifierFunction) .append("] [P/F bit: ") .append(pfBit ? 1 : 0) .append("]"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + modifierFunction.hashCode(); result = prime * result + (pfBit ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!this.getClass().isInstance(obj)) { return false; } LlcControlUnnumbered other = (LlcControlUnnumbered) obj; return modifierFunction.equals(other.modifierFunction) && pfBit == other.pfBit; } /** * @author <NAME> * @since pcap4j 1.6.5 */ public static final class Builder { private LlcControlModifierFunction modifierFunction; private boolean pfBit; /** */ public Builder() {} private Builder(LlcControlUnnumbered ctrl) { this.modifierFunction = ctrl.modifierFunction; this.pfBit = ctrl.pfBit; } /** * @param modifierFunction modifierFunction * @return this Builder object for method chaining. */ public Builder modifierFunction(LlcControlModifierFunction modifierFunction) { this.modifierFunction = modifierFunction; return this; } /** * @param pfBit pfBit * @return this Builder object for method chaining. */ public Builder pfBit(boolean pfBit) { this.pfBit = pfBit; return this; } /** @return a new LlcControlSupervisory object. */ public LlcControlUnnumbered build() { return new LlcControlUnnumbered(this); } } }
1,811
353
<reponame>lihongwu19921215/nutzmore package org.nutz.integration.spring; import org.nutz.dao.DaoException; import org.nutz.dao.DaoInterceptor; import org.nutz.dao.DaoInterceptorChain; import org.nutz.log.Log; import org.nutz.log.Logs; public class SimpleDaoInterceptor implements DaoInterceptor { private static final Log log = Logs.get(); public void filter(DaoInterceptorChain chain) throws DaoException { log.debug("before >>> " + chain.getDaoStatement().toPreparedStatement()); chain.doChain(); log.debug("after <<< " + chain.getDaoStatement().toPreparedStatement()); } }
232
3,203
package github.javaguide.springbootfilter.filter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @WebFilter(filterName = "MyFilterWithAnnotation", urlPatterns = "/api/annotation/*") public class MyFilterWithAnnotation implements Filter { private static final Logger logger = LoggerFactory.getLogger(MyFilterWithAnnotation.class); @Override public void init(FilterConfig filterConfig) { logger.info("初始化过滤器"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //对请求进行预处理 logger.info("过滤器开始对请求进行预处理:"); HttpServletRequest request = (HttpServletRequest) servletRequest; String requestUri = request.getRequestURI(); System.out.println("请求的接口为:" + requestUri); long startTime = System.currentTimeMillis(); //通过 doFilter 方法实现过滤功能 filterChain.doFilter(servletRequest, servletResponse); // 上面的 doFilter 方法执行结束后用户的请求已经返回 long endTime = System.currentTimeMillis(); System.out.println("该用户的请求已经处理完毕,请求花费的时间为:" + (endTime - startTime)); } @Override public void destroy() { logger.info("销毁过滤器"); } }
740
407
<reponame>emsec/HAL #include "gui/user_action/action_create_object.h" #include "gui/user_action/action_delete_object.h" #include "gui/gui_globals.h" #include "hal_core/netlist/grouping.h" #include "gui/grouping/grouping_manager_widget.h" #include "gui/graph_widget/contexts/graph_context.h" namespace hal { ActionCreateObjectFactory::ActionCreateObjectFactory() : UserActionFactory("CreateObject") {;} ActionCreateObjectFactory* ActionCreateObjectFactory::sFactory = new ActionCreateObjectFactory; UserAction* ActionCreateObjectFactory::newAction() const { return new ActionCreateObject; } QString ActionCreateObject::tagname() const { return ActionCreateObjectFactory::sFactory->tagname(); } ActionCreateObject::ActionCreateObject(UserActionObjectType::ObjectType type, const QString &objName) : mObjectName(objName), mParentId(0) { setObject(UserActionObject(0,type)); } void ActionCreateObject::addToHash(QCryptographicHash &cryptoHash) const { cryptoHash.addData(mObjectName.toUtf8()); cryptoHash.addData((char*)(&mParentId),sizeof(mParentId)); } void ActionCreateObject::writeToXml(QXmlStreamWriter& xmlOut) const { xmlOut.writeTextElement("objectname", mObjectName); xmlOut.writeTextElement("parentid", QString::number(mParentId)); } void ActionCreateObject::readFromXml(QXmlStreamReader& xmlIn) { while (xmlIn.readNextStartElement()) { if (xmlIn.name() == "objectname") mObjectName = xmlIn.readElementText(); if (xmlIn.name() == "parentid") mParentId = xmlIn.readElementText().toInt(); } } bool ActionCreateObject::exec() { bool standardUndo = false; switch (mObject.type()) { case UserActionObjectType::Module: { Module* parentModule = gNetlist->get_module_by_id(mParentId); if (parentModule) { Module* m = gNetlist->create_module(gNetlist->get_unique_module_id(), mObjectName.toStdString(), parentModule); setObject(UserActionObject(m->get_id(),UserActionObjectType::Module)); standardUndo = true; } } break; /* case UserActionObjectType::Gate: { Gate* g = gNetlist->create_gate(mGroupingName.toStdString()); setObject(UserActionObject(g->get_id(),UserActionObjectType::Gate)); } break; */ case UserActionObjectType::Net: { Net* n = gNetlist->create_net(mObjectName.toStdString()); setObject(UserActionObject(n->get_id(),UserActionObjectType::Net)); standardUndo = true; } break; case UserActionObjectType::Grouping: { GroupingTableModel* grpModel = gContentManager->getGroupingManagerWidget()->getModel(); if (!grpModel) return false; Grouping* grp = grpModel->addDefaultEntry(); if (!mObjectName.isEmpty()) grpModel->renameGrouping(grp->get_id(),mObjectName); setObject(UserActionObject(grp->get_id(),UserActionObjectType::Grouping)); standardUndo = true; } break; case UserActionObjectType::Context: { QString contextName = mObjectName.isEmpty() ? gGraphContextManager->nextDefaultName() : mObjectName; GraphContext* ctx = gGraphContextManager->createNewContext(contextName); if (mObject.id() > 0) gGraphContextManager->setContextId(ctx,mObject.id()); setObject(UserActionObject(ctx->id(),UserActionObjectType::Context)); standardUndo = true; } break; default: return false; // don't know how to create } if (standardUndo) { mUndoAction = new ActionDeleteObject; mUndoAction->setObject(mObject); } return UserAction::exec(); } }
1,948
517
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tensorflow/core/framework/types.proto package org.tensorflow.proto.framework; /** * <pre> * (== suppress_warning documentation-presence ==) * LINT.IfChange * </pre> * * Protobuf enum {@code tensorflow.DataType} */ public enum DataType implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Not a legal value for DataType. Used to indicate a DataType field * has not been set. * </pre> * * <code>DT_INVALID = 0;</code> */ DT_INVALID(0), /** * <pre> * Data types that all computation devices are expected to be * capable to support. * </pre> * * <code>DT_FLOAT = 1;</code> */ DT_FLOAT(1), /** * <code>DT_DOUBLE = 2;</code> */ DT_DOUBLE(2), /** * <code>DT_INT32 = 3;</code> */ DT_INT32(3), /** * <code>DT_UINT8 = 4;</code> */ DT_UINT8(4), /** * <code>DT_INT16 = 5;</code> */ DT_INT16(5), /** * <code>DT_INT8 = 6;</code> */ DT_INT8(6), /** * <code>DT_STRING = 7;</code> */ DT_STRING(7), /** * <pre> * Single-precision complex * </pre> * * <code>DT_COMPLEX64 = 8;</code> */ DT_COMPLEX64(8), /** * <code>DT_INT64 = 9;</code> */ DT_INT64(9), /** * <code>DT_BOOL = 10;</code> */ DT_BOOL(10), /** * <pre> * Quantized int8 * </pre> * * <code>DT_QINT8 = 11;</code> */ DT_QINT8(11), /** * <pre> * Quantized uint8 * </pre> * * <code>DT_QUINT8 = 12;</code> */ DT_QUINT8(12), /** * <pre> * Quantized int32 * </pre> * * <code>DT_QINT32 = 13;</code> */ DT_QINT32(13), /** * <pre> * Float32 truncated to 16 bits. Only for cast ops. * </pre> * * <code>DT_BFLOAT16 = 14;</code> */ DT_BFLOAT16(14), /** * <pre> * Quantized int16 * </pre> * * <code>DT_QINT16 = 15;</code> */ DT_QINT16(15), /** * <pre> * Quantized uint16 * </pre> * * <code>DT_QUINT16 = 16;</code> */ DT_QUINT16(16), /** * <code>DT_UINT16 = 17;</code> */ DT_UINT16(17), /** * <pre> * Double-precision complex * </pre> * * <code>DT_COMPLEX128 = 18;</code> */ DT_COMPLEX128(18), /** * <code>DT_HALF = 19;</code> */ DT_HALF(19), /** * <code>DT_RESOURCE = 20;</code> */ DT_RESOURCE(20), /** * <pre> * Arbitrary C++ data types * </pre> * * <code>DT_VARIANT = 21;</code> */ DT_VARIANT(21), /** * <code>DT_UINT32 = 22;</code> */ DT_UINT32(22), /** * <code>DT_UINT64 = 23;</code> */ DT_UINT64(23), /** * <pre> * Do not use! These are only for parameters. Every enum above * should have a corresponding value below (verified by types_test). * </pre> * * <code>DT_FLOAT_REF = 101;</code> */ DT_FLOAT_REF(101), /** * <code>DT_DOUBLE_REF = 102;</code> */ DT_DOUBLE_REF(102), /** * <code>DT_INT32_REF = 103;</code> */ DT_INT32_REF(103), /** * <code>DT_UINT8_REF = 104;</code> */ DT_UINT8_REF(104), /** * <code>DT_INT16_REF = 105;</code> */ DT_INT16_REF(105), /** * <code>DT_INT8_REF = 106;</code> */ DT_INT8_REF(106), /** * <code>DT_STRING_REF = 107;</code> */ DT_STRING_REF(107), /** * <code>DT_COMPLEX64_REF = 108;</code> */ DT_COMPLEX64_REF(108), /** * <code>DT_INT64_REF = 109;</code> */ DT_INT64_REF(109), /** * <code>DT_BOOL_REF = 110;</code> */ DT_BOOL_REF(110), /** * <code>DT_QINT8_REF = 111;</code> */ DT_QINT8_REF(111), /** * <code>DT_QUINT8_REF = 112;</code> */ DT_QUINT8_REF(112), /** * <code>DT_QINT32_REF = 113;</code> */ DT_QINT32_REF(113), /** * <code>DT_BFLOAT16_REF = 114;</code> */ DT_BFLOAT16_REF(114), /** * <code>DT_QINT16_REF = 115;</code> */ DT_QINT16_REF(115), /** * <code>DT_QUINT16_REF = 116;</code> */ DT_QUINT16_REF(116), /** * <code>DT_UINT16_REF = 117;</code> */ DT_UINT16_REF(117), /** * <code>DT_COMPLEX128_REF = 118;</code> */ DT_COMPLEX128_REF(118), /** * <code>DT_HALF_REF = 119;</code> */ DT_HALF_REF(119), /** * <code>DT_RESOURCE_REF = 120;</code> */ DT_RESOURCE_REF(120), /** * <code>DT_VARIANT_REF = 121;</code> */ DT_VARIANT_REF(121), /** * <code>DT_UINT32_REF = 122;</code> */ DT_UINT32_REF(122), /** * <code>DT_UINT64_REF = 123;</code> */ DT_UINT64_REF(123), UNRECOGNIZED(-1), ; /** * <pre> * Not a legal value for DataType. Used to indicate a DataType field * has not been set. * </pre> * * <code>DT_INVALID = 0;</code> */ public static final int DT_INVALID_VALUE = 0; /** * <pre> * Data types that all computation devices are expected to be * capable to support. * </pre> * * <code>DT_FLOAT = 1;</code> */ public static final int DT_FLOAT_VALUE = 1; /** * <code>DT_DOUBLE = 2;</code> */ public static final int DT_DOUBLE_VALUE = 2; /** * <code>DT_INT32 = 3;</code> */ public static final int DT_INT32_VALUE = 3; /** * <code>DT_UINT8 = 4;</code> */ public static final int DT_UINT8_VALUE = 4; /** * <code>DT_INT16 = 5;</code> */ public static final int DT_INT16_VALUE = 5; /** * <code>DT_INT8 = 6;</code> */ public static final int DT_INT8_VALUE = 6; /** * <code>DT_STRING = 7;</code> */ public static final int DT_STRING_VALUE = 7; /** * <pre> * Single-precision complex * </pre> * * <code>DT_COMPLEX64 = 8;</code> */ public static final int DT_COMPLEX64_VALUE = 8; /** * <code>DT_INT64 = 9;</code> */ public static final int DT_INT64_VALUE = 9; /** * <code>DT_BOOL = 10;</code> */ public static final int DT_BOOL_VALUE = 10; /** * <pre> * Quantized int8 * </pre> * * <code>DT_QINT8 = 11;</code> */ public static final int DT_QINT8_VALUE = 11; /** * <pre> * Quantized uint8 * </pre> * * <code>DT_QUINT8 = 12;</code> */ public static final int DT_QUINT8_VALUE = 12; /** * <pre> * Quantized int32 * </pre> * * <code>DT_QINT32 = 13;</code> */ public static final int DT_QINT32_VALUE = 13; /** * <pre> * Float32 truncated to 16 bits. Only for cast ops. * </pre> * * <code>DT_BFLOAT16 = 14;</code> */ public static final int DT_BFLOAT16_VALUE = 14; /** * <pre> * Quantized int16 * </pre> * * <code>DT_QINT16 = 15;</code> */ public static final int DT_QINT16_VALUE = 15; /** * <pre> * Quantized uint16 * </pre> * * <code>DT_QUINT16 = 16;</code> */ public static final int DT_QUINT16_VALUE = 16; /** * <code>DT_UINT16 = 17;</code> */ public static final int DT_UINT16_VALUE = 17; /** * <pre> * Double-precision complex * </pre> * * <code>DT_COMPLEX128 = 18;</code> */ public static final int DT_COMPLEX128_VALUE = 18; /** * <code>DT_HALF = 19;</code> */ public static final int DT_HALF_VALUE = 19; /** * <code>DT_RESOURCE = 20;</code> */ public static final int DT_RESOURCE_VALUE = 20; /** * <pre> * Arbitrary C++ data types * </pre> * * <code>DT_VARIANT = 21;</code> */ public static final int DT_VARIANT_VALUE = 21; /** * <code>DT_UINT32 = 22;</code> */ public static final int DT_UINT32_VALUE = 22; /** * <code>DT_UINT64 = 23;</code> */ public static final int DT_UINT64_VALUE = 23; /** * <pre> * Do not use! These are only for parameters. Every enum above * should have a corresponding value below (verified by types_test). * </pre> * * <code>DT_FLOAT_REF = 101;</code> */ public static final int DT_FLOAT_REF_VALUE = 101; /** * <code>DT_DOUBLE_REF = 102;</code> */ public static final int DT_DOUBLE_REF_VALUE = 102; /** * <code>DT_INT32_REF = 103;</code> */ public static final int DT_INT32_REF_VALUE = 103; /** * <code>DT_UINT8_REF = 104;</code> */ public static final int DT_UINT8_REF_VALUE = 104; /** * <code>DT_INT16_REF = 105;</code> */ public static final int DT_INT16_REF_VALUE = 105; /** * <code>DT_INT8_REF = 106;</code> */ public static final int DT_INT8_REF_VALUE = 106; /** * <code>DT_STRING_REF = 107;</code> */ public static final int DT_STRING_REF_VALUE = 107; /** * <code>DT_COMPLEX64_REF = 108;</code> */ public static final int DT_COMPLEX64_REF_VALUE = 108; /** * <code>DT_INT64_REF = 109;</code> */ public static final int DT_INT64_REF_VALUE = 109; /** * <code>DT_BOOL_REF = 110;</code> */ public static final int DT_BOOL_REF_VALUE = 110; /** * <code>DT_QINT8_REF = 111;</code> */ public static final int DT_QINT8_REF_VALUE = 111; /** * <code>DT_QUINT8_REF = 112;</code> */ public static final int DT_QUINT8_REF_VALUE = 112; /** * <code>DT_QINT32_REF = 113;</code> */ public static final int DT_QINT32_REF_VALUE = 113; /** * <code>DT_BFLOAT16_REF = 114;</code> */ public static final int DT_BFLOAT16_REF_VALUE = 114; /** * <code>DT_QINT16_REF = 115;</code> */ public static final int DT_QINT16_REF_VALUE = 115; /** * <code>DT_QUINT16_REF = 116;</code> */ public static final int DT_QUINT16_REF_VALUE = 116; /** * <code>DT_UINT16_REF = 117;</code> */ public static final int DT_UINT16_REF_VALUE = 117; /** * <code>DT_COMPLEX128_REF = 118;</code> */ public static final int DT_COMPLEX128_REF_VALUE = 118; /** * <code>DT_HALF_REF = 119;</code> */ public static final int DT_HALF_REF_VALUE = 119; /** * <code>DT_RESOURCE_REF = 120;</code> */ public static final int DT_RESOURCE_REF_VALUE = 120; /** * <code>DT_VARIANT_REF = 121;</code> */ public static final int DT_VARIANT_REF_VALUE = 121; /** * <code>DT_UINT32_REF = 122;</code> */ public static final int DT_UINT32_REF_VALUE = 122; /** * <code>DT_UINT64_REF = 123;</code> */ public static final int DT_UINT64_REF_VALUE = 123; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static DataType valueOf(int value) { return forNumber(value); } public static DataType forNumber(int value) { switch (value) { case 0: return DT_INVALID; case 1: return DT_FLOAT; case 2: return DT_DOUBLE; case 3: return DT_INT32; case 4: return DT_UINT8; case 5: return DT_INT16; case 6: return DT_INT8; case 7: return DT_STRING; case 8: return DT_COMPLEX64; case 9: return DT_INT64; case 10: return DT_BOOL; case 11: return DT_QINT8; case 12: return DT_QUINT8; case 13: return DT_QINT32; case 14: return DT_BFLOAT16; case 15: return DT_QINT16; case 16: return DT_QUINT16; case 17: return DT_UINT16; case 18: return DT_COMPLEX128; case 19: return DT_HALF; case 20: return DT_RESOURCE; case 21: return DT_VARIANT; case 22: return DT_UINT32; case 23: return DT_UINT64; case 101: return DT_FLOAT_REF; case 102: return DT_DOUBLE_REF; case 103: return DT_INT32_REF; case 104: return DT_UINT8_REF; case 105: return DT_INT16_REF; case 106: return DT_INT8_REF; case 107: return DT_STRING_REF; case 108: return DT_COMPLEX64_REF; case 109: return DT_INT64_REF; case 110: return DT_BOOL_REF; case 111: return DT_QINT8_REF; case 112: return DT_QUINT8_REF; case 113: return DT_QINT32_REF; case 114: return DT_BFLOAT16_REF; case 115: return DT_QINT16_REF; case 116: return DT_QUINT16_REF; case 117: return DT_UINT16_REF; case 118: return DT_COMPLEX128_REF; case 119: return DT_HALF_REF; case 120: return DT_RESOURCE_REF; case 121: return DT_VARIANT_REF; case 122: return DT_UINT32_REF; case 123: return DT_UINT64_REF; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<DataType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< DataType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<DataType>() { public DataType findValueByNumber(int number) { return DataType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return org.tensorflow.proto.framework.TypesProtos.getDescriptor().getEnumTypes().get(0); } private static final DataType[] VALUES = values(); public static DataType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private DataType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:tensorflow.DataType) }
6,170
1,315
#include "SoloFeature.h" #include "streamFuns.h" #include "TimeFunctions.h" #include "serviceFuns.cpp" #include <unordered_map> #include "SoloCommon.h" inline int funCompareSolo1 (const void *a, const void *b); //defined below inline int funCompare_uint32_1_2_0 (const void *a, const void *b); void SoloFeature::collapseUMIall(uint32 iCB, uint32 *umiArray) { uint32 *rGU=rCBp[iCB]; uint32 rN=nReadPerCB[iCB]; //with multimappers, this is the number of all aligns, not reads qsort(rGU,rN,rguStride*sizeof(uint32),funCompareNumbers<uint32>); //sort by gene index uint32 gid1 = -1;//current gID uint32 nGenes = 0, nGenesMult = 0; //number of genes uint32 *gID = new uint32[min(featuresNumber,rN)+1]; //gene IDs uint32 *gReadS = new uint32[min(featuresNumber,rN)+1]; //start of gene reads TODO: allocate this array in the 2nd half of rGU for (uint32 iR=0; iR<rN*rguStride; iR+=rguStride) { if (rGU[iR+rguG]!=gid1) {//record gene boundary gReadS[nGenes]=iR; gid1=rGU[iR+rguG]; gID[nGenes]=gid1; ++nGenes; if (gid1>=geneMultMark) ++nGenesMult; }; }; gReadS[nGenes]=rguStride*rN;//so that gReadS[nGenes]-gReadS[nGenes-1] is the number of reads for nGenes, see below in qsort nGenes -= nGenesMult;//unique only gene nReadPerCBunique[iCB] = gReadS[nGenes]/rguStride; //number of unique reads for this CB nReadPerCBtotal[iCB] = nReadPerCBunique[iCB]; //unordered_map <uintUMI, unordered_set<uint32>> umiGeneMap; unordered_map <uintUMI, unordered_map<uint32,uint32>> umiGeneMapCount, umiGeneMapCount0; //UMI //Gene //Count if (pSolo.umiFiltering.MultiGeneUMI) { for (uint32 iR=0; iR<gReadS[nGenes]; iR+=rguStride) { umiGeneMapCount[rGU[iR+1]][rGU[iR]]++; }; for (auto &iu : umiGeneMapCount) {//loop over all UMIs if (iu.second.size()==1) continue; uint32 maxu=0; for (const auto &ig : iu.second) {//loop over genes for a given UMI if (maxu<ig.second) maxu=ig.second; //find gene with maximum count }; if (maxu==1) maxu=2;//to kill UMIs with 1 read to one gene, 1 read to another gene for (auto &ig : iu.second) { if (maxu>ig.second) ig.second=0; //kills Gene with read count *strictly* < maximum count }; }; }; if (pSolo.umiFiltering.MultiGeneUMI_All) { for (uint32 iR=0; iR<gReadS[nGenes]; iR+=rguStride) { umiGeneMapCount[rGU[iR+1]][rGU[iR]]++; }; for (auto &iu : umiGeneMapCount) {//loop over all UMIs if (iu.second.size()>1) { for (auto &ig : iu.second) ig.second=0; //kill all genes for this UMI }; }; }; vector<unordered_map <uintUMI,uintUMI>> umiCorrected(nGenes); if (countCellGeneUMI.size() < countCellGeneUMIindex[iCB] + nGenes*countMatStride) countCellGeneUMI.resize((countCellGeneUMI.size() + nGenes*countMatStride )*2);//allocated vector too small nGenePerCB[iCB]=0; nUMIperCB[iCB]=0; countCellGeneUMIindex[iCB+1]=countCellGeneUMIindex[iCB]; ///////////////////////////////////////////// /////////// main cycle over genes with unique-gene-mappers for (uint32 iG=0; iG<nGenes; iG++) {//collapse UMIs for each gene uint32 *rGU1=rGU+gReadS[iG]; uint32 nR0 = (gReadS[iG+1]-gReadS[iG])/rguStride; //total number of reads if (nR0==0) continue; //no reads - this should not happen? qsort(rGU1, nR0, rguStride*sizeof(uint32), funCompareTypeShift<uint32,rguU>); //exact collapse uint32 iR1=-umiArrayStride; //number of distinct UMIs for this gene uint32 u1=-1; for (uint32 iR=rguU; iR<gReadS[iG+1]-gReadS[iG]; iR+=rguStride) {//count and collapse identical UMIs if (pSolo.umiFiltering.MultiGeneUMI && umiGeneMapCount[rGU1[iR]][gID[iG]]==0) {//multigene UMI is not recorded if ( pSolo.umiDedup.typeMain != UMIdedup::typeI::NoDedup ) //for NoDedup, the UMI filtering is not done rGU1[iR] = (uintUMI) -1; //mark multigene UMI, so that UB tag will be set to - continue; }; if (rGU1[iR]!=u1) { iR1 += umiArrayStride; u1=rGU1[iR]; umiArray[iR1]=u1; umiArray[iR1+1]=0; }; umiArray[iR1+1]++; //if ( umiArray[iR1+1]>nRumiMax) nRumiMax=umiArray[iR1+1]; }; uint32 nU0 = (iR1+umiArrayStride)/umiArrayStride;//number of UMIs after simple exact collapse if (pSolo.umiFiltering.MultiGeneUMI_CR) { if (nU0==0) continue; //nothing to count for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) { umiGeneMapCount0[umiArray[iu+0]][iG]+=umiArray[iu+1];//this sums read counts over UMIs that were collapsed }; umiArrayCorrect_CR(nU0, umiArray, readInfo.size()>0, false, umiCorrected[iG]); for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) {//just fill the umiGeneMapCount - will calculate UMI counts later umiGeneMapCount[umiArray[iu+2]][iG]+=umiArray[iu+1];//this sums read counts over UMIs that were collapsed }; continue; //done with MultiGeneUMI_CR, readInfo will be filled later }; if (pSolo.umiDedup.yes.NoDedup) countCellGeneUMI[countCellGeneUMIindex[iCB+1] + pSolo.umiDedup.countInd.NoDedup] = nR0; if (nU0>0) {//otherwise no need to count if (pSolo.umiDedup.yes.Exact) countCellGeneUMI[countCellGeneUMIindex[iCB+1] + pSolo.umiDedup.countInd.Exact] = nU0; if (pSolo.umiDedup.yes.CR) countCellGeneUMI[countCellGeneUMIindex[iCB+1] + pSolo.umiDedup.countInd.CR] = umiArrayCorrect_CR(nU0, umiArray, readInfo.size()>0 && pSolo.umiDedup.typeMain==UMIdedup::typeI::CR, true, umiCorrected[iG]); if (pSolo.umiDedup.yes.Directional) countCellGeneUMI[countCellGeneUMIindex[iCB+1] + pSolo.umiDedup.countInd.Directional] = umiArrayCorrect_Directional(nU0, umiArray, readInfo.size()>0 && pSolo.umiDedup.typeMain==UMIdedup::typeI::Directional, true, umiCorrected[iG], 0); if (pSolo.umiDedup.yes.Directional_UMItools) countCellGeneUMI[countCellGeneUMIindex[iCB+1] + pSolo.umiDedup.countInd.Directional_UMItools] = umiArrayCorrect_Directional(nU0, umiArray, readInfo.size()>0 && pSolo.umiDedup.typeMain==UMIdedup::typeI::Directional_UMItools, true, umiCorrected[iG], -1); //this changes umiArray, so it should be last call if (pSolo.umiDedup.yes.All) countCellGeneUMI[countCellGeneUMIindex[iCB+1] + pSolo.umiDedup.countInd.All] = umiArrayCorrect_Graph(nU0, umiArray, readInfo.size()>0 && pSolo.umiDedup.typeMain==UMIdedup::typeI::All, true, umiCorrected[iG]); };//if (nU0>0) {//check any count>0 and finalize record for this gene uint32 totcount=0; for (uint32 ii=countCellGeneUMIindex[iCB+1]+1; ii<countCellGeneUMIindex[iCB+1]+countMatStride; ii++) { totcount += countCellGeneUMI[ii]; }; if (totcount>0) {//at least one umiDedup type is non-0 countCellGeneUMI[countCellGeneUMIindex[iCB+1] + 0] = gID[iG]; nGenePerCB[iCB]++; nUMIperCB[iCB] += countCellGeneUMI[countCellGeneUMIindex[iCB+1] + pSolo.umiDedup.countInd.main]; countCellGeneUMIindex[iCB+1] = countCellGeneUMIindex[iCB+1] + countMatStride;//iCB+1 accumulates the index }; }; if (readInfo.size()>0) {//record cb/umi for each read for (uint32 iR=0; iR<gReadS[iG+1]-gReadS[iG]; iR+=rguStride) {//cycle over reads uint64 iread1 = rGU1[iR+rguR]; readInfo[iread1].cb = indCB[iCB] ; uint32 umi=rGU1[iR+rguU]; if (umiCorrected[iG].count(umi)>0) umi=umiCorrected[iG][umi]; //correct UMI readInfo[iread1].umi=umi; }; }; }; if (pSolo.umiFiltering.MultiGeneUMI_CR) { vector<uint32> geneCounts(nGenes,0); vector<unordered_set<uintUMI>> geneUmiHash; if (readInfo.size()>0) geneUmiHash.resize(nGenes); for (const auto &iu: umiGeneMapCount) {//loop over UMIs for all genes uint32 maxu=0, maxg=-1; for (const auto &ig : iu.second) { if (ig.second>maxu) { maxu=ig.second; maxg=ig.first; } else if (ig.second==maxu) { maxg=-1; }; }; if ( maxg+1==0 ) continue; //this umi is not counted for any gene, because two genes have the same read count for this UMI for (const auto &ig : umiGeneMapCount0[iu.first]) {//check that this umi/gene had also top count for uncorrected umis if (ig.second>umiGeneMapCount0[iu.first][maxg]) { maxg=-1; break; }; }; if ( maxg+1!=0 ) {//this UMI is counted geneCounts[maxg]++; if (readInfo.size()>0) geneUmiHash[maxg].insert(iu.first); }; }; for (uint32 ig=0; ig<nGenes; ig++) { if (geneCounts[ig] == 0) continue; //no counts for this gene nGenePerCB[iCB]++; nUMIperCB[iCB] += geneCounts[ig]; countCellGeneUMI[countCellGeneUMIindex[iCB+1] + 0] = gID[ig]; countCellGeneUMI[countCellGeneUMIindex[iCB+1] + pSolo.umiDedup.countInd.CR] = geneCounts[ig]; countCellGeneUMIindex[iCB+1] = countCellGeneUMIindex[iCB+1] + countMatStride;//iCB+1 accumulates the index }; if (readInfo.size()>0) {//record cb/umi for each read for (uint32 iG=0; iG<nGenes; iG++) {//cycle over genes uint32 *rGU1=rGU+gReadS[iG]; for (uint32 iR=0; iR<gReadS[iG+1]-gReadS[iG]; iR+=rguStride) {//cycle over reads uint64 iread1 = rGU1[iR+rguR]; readInfo[iread1].cb = indCB[iCB]; uint32 umi=rGU1[iR+rguU]; if (umiCorrected[iG].count(umi)>0) umi=umiCorrected[iG][umi]; //correct UMI //cout << iG << "-" << iR << " " <<flush ; if (geneUmiHash[iG].count(umi)>0) { readInfo[iread1].umi=umi; } else { readInfo[iread1].umi=(uintUMI) -1; }; }; }; }; }; //////////////////////////////////////////multi-gene reads ////////////////////////////////////////// if (pSolo.multiMap.yes.multi) countMatMult.i[iCB+1] = countMatMult.i[iCB]; if (nGenesMult>0) {//process multigene reads if (readInfo.size()>0) { for (uint32 iR=gReadS[nGenes]; iR<gReadS[nGenes+nGenesMult]; iR+=rguStride) {//cycle over multi-gene reads to record their CB and UMI, no corrections uint64 iread1 = rGU[iR+rguR]; readInfo[iread1].cb = indCB[iCB]; readInfo[iread1].umi = rGU[iR+rguU]; }; }; std::vector<vector<uint32>> umiGenes; umiGenes.reserve(256); {//for each umi, count number of reads per gene. //Output umiGenes: only genes with nReads = nReads-for-this-UMI will be kept for this UMI uint32 *rGUm = rGU + gReadS[nGenes]; uint32 nRm=( gReadS[nGenes+nGenesMult] - gReadS[nGenes] ) / rguStride; //sort by UMI, then by read, then by gene qsort(rGUm, nRm, rguStride*sizeof(uint32), funCompare_uint32_1_2_0);//there is no need to sort by read or gene actually std::unordered_map<uint32, uint32> geneReadCount; //number of reads per gene uint32 nRumi=0; bool skipUMI=false; uintUMI umiPrev = (uintUMI)-1; uintRead readPrev = (uintRead)-1; for (uint32 iR=0; iR<nRm*rguStride; iR+=rguStride) {//for each umi, find intersection of genes from each read uintUMI umi1 = rGUm[iR+1]; if (umi1!=umiPrev) {//starting new UMI umiPrev = umi1; if (umiGeneMapCount.count(umi1)>0) { skipUMI = true;//this UMI is skipped because it was among uniquely mapped } else { skipUMI = false;//new good umi geneReadCount.clear(); nRumi=0; readPrev = (uintRead)-1; }; }; if (skipUMI) continue; //this UMI is skipped because it was among uniquely mapped uintRead read1 = rGUm[iR+2]; if (read1 != readPrev) { ++nRumi; readPrev = read1; nReadPerCBtotal[iCB]++; }; uint32 g1 = rGUm[iR+0] ^ geneMultMark; //XOR to unset the geneMultMark bit geneReadCount[g1]++; if (iR == nRm*rguStride-rguStride || umi1 != rGUm[iR+1+rguStride]) {//record this umi uint32 ng=0; for (const auto &gg: geneReadCount) { if (gg.second == nRumi) ++ng; }; vector<uint32> vg; vg.reserve(ng);//this and above is to construct vector of precise size, for efficiency? for (const auto &gg: geneReadCount) { if (gg.second == nRumi) vg.push_back(gg.first); }; umiGenes.push_back(vg); }; }; }; std::map<uint32,uint32> genesM; //genes to quantify {//collect all genes, replace geneID with index in umiGenes uint32 ng = 0; for (auto &uu: umiGenes) { for (auto &gg: uu) { if (genesM.count(gg) == 0) {//new gene genesM[gg]=ng; ++ng; }; gg = genesM[gg]; }; }; }; vector<double> gEuniform(genesM.size(), 0); {//gEuniform=uniformly distribute multigene UMIs for (auto &ug: umiGenes) { for (auto &gg: ug) { gEuniform[gg] += 1.0 / double(ug.size()); // 1/n_genes_umi }; }; }; vector<vector<double>> gErescue(pSolo.umiDedup.yes.N); if (pSolo.multiMap.yes.Rescue) { for (uint32 indDedup=0; indDedup < pSolo.umiDedup.yes.N; indDedup++) { vector<double> gEu(genesM.size(), 0); {//collect unique gene counts for (uint32 igm=countCellGeneUMIindex[iCB]; igm<countCellGeneUMIindex[iCB+1]; igm+=countMatStride) { uint32 g1 = countCellGeneUMI[igm]; if (genesM.count(g1)>0) gEu[genesM[g1]]=(double)countCellGeneUMI[igm+1+indDedup]; }; }; gErescue[indDedup].resize(genesM.size(), 0); {//gErescue=distribute UMI proportionally to gEuniform+gEu for (auto &ug: umiGenes) { double norm1 = 0.0; for (auto &gg: ug) norm1 += gEuniform[gg]+gEu[gg]; if (norm1==0.0) continue; //this should not happen since gEuniform is non-zero for all genes involved norm1 = 1.0 / norm1; for (auto &gg: ug) { gErescue[indDedup][gg] += (gEuniform[gg]+gEu[gg])*norm1; }; }; }; }; }; vector<vector<double>> gEpropUnique(pSolo.umiDedup.yes.N); if (pSolo.multiMap.yes.PropUnique) { for (uint32 indDedup=0; indDedup < pSolo.umiDedup.yes.N; indDedup++) { vector<double> gEu(genesM.size(), 0); {//collect unique gene counts for (uint32 igm=countCellGeneUMIindex[iCB]; igm<countCellGeneUMIindex[iCB+1]; igm+=countMatStride) { uint32 g1 = countCellGeneUMI[igm]; if (genesM.count(g1)>0) gEu[genesM[g1]]=(double)countCellGeneUMI[igm+1+indDedup]; }; }; gEpropUnique[indDedup].resize(genesM.size(), 0); {//gErescue=distribute UMI proportionally to gEuniform+gEu for (auto &ug: umiGenes) { double norm1 = 0.0; for (auto &gg: ug) norm1 += gEu[gg]; if (norm1==0.0) {//this UMI has no genes with unique mappers - distribute it uniformly for (auto &gg: ug) gEpropUnique[indDedup][gg] += 1.0 / double(ug.size()); } else {//this UMI has genes with unique mappers - distribute it proportionally to unique mappers norm1 = 1.0 / norm1; for (auto &gg: ug) gEpropUnique[indDedup][gg] += gEu[gg]*norm1; }; }; }; }; }; vector<vector<double>> gEem(pSolo.umiDedup.yes.N); if (pSolo.multiMap.yes.EM) { for (uint32 indDedup=0; indDedup < pSolo.umiDedup.yes.N; indDedup++) { vector<double> gEu(genesM.size(), 0); {//collect unique gene counts for (uint32 igm=countCellGeneUMIindex[iCB]; igm<countCellGeneUMIindex[iCB+1]; igm+=countMatStride) { uint32 g1 = countCellGeneUMI[igm]; if (genesM.count(g1)>0) gEu[genesM[g1]]=(double)countCellGeneUMI[igm+1+indDedup]; }; }; {//gEem = EM vector<double> gEM1 = gEuniform; for (uint32 ii=0; ii<gEM1.size(); ii++) gEM1[ii] += gEu[ii]; //start with sum of unique and uniform vector<double> gEM2(genesM.size(), 0); auto *gEM1p=&gEM1; auto *gEM2p=&gEM2; double maxAbsChange=1; uint32 iterI=0; while(true) { ++iterI; auto &gEMold=*gEM1p; //for convenience - to use instead of pointer auto &gEMnew=*gEM2p; std::copy(gEu.begin(), gEu.end(), gEMnew.begin());//gEMnew is initialized with unique counts for (auto &gg: gEMold) {//zero-out very small counts if (gg<0.01) //hardcoded gg=0; }; for (auto &ug: umiGenes) { double norm1 = 0.0; for (auto &gg: ug) //cycle over genes for this umi norm1 += gEMold[gg]; norm1 = 1.0 / norm1; for (auto &gg: ug) { gEMnew[gg] += gEMold[gg]*norm1; }; }; maxAbsChange=0.0; for (uint32 ii=0; ii<gEMnew.size(); ii++) { double change1 = abs(gEMnew[ii]-gEMold[ii]); if (change1 > maxAbsChange) maxAbsChange = change1; }; if (maxAbsChange < 0.01 || iterI>100) {//hardcoded gEem[indDedup] = gEMnew; break; }; swap(gEM1p, gEM2p); //swap new and old for the next interation of EM }; for (uint32 ii=0; ii<gEM1.size(); ii++) gEem[indDedup][ii] -= gEu[ii]; //gEem contains only multimapper counts }; }; }; {//write to countMatMult for (const auto &gm: genesM) { countMatMult.m[countMatMult.i[iCB+1] + 0] = gm.first; for (uint32 indDedup=0; indDedup < pSolo.umiDedup.yes.N; indDedup++) { uint32 ind1 = countMatMult.i[iCB+1] + indDedup; if (pSolo.multiMap.yes.Uniform) countMatMult.m[ind1 + pSolo.multiMap.countInd.Uniform] = gEuniform[gm.second]; if (pSolo.multiMap.yes.Rescue) countMatMult.m[ind1 + pSolo.multiMap.countInd.Rescue] = gErescue[indDedup][gm.second]; if (pSolo.multiMap.yes.PropUnique) countMatMult.m[ind1 + pSolo.multiMap.countInd.PropUnique] = gEpropUnique[indDedup][gm.second]; if (pSolo.multiMap.yes.EM) countMatMult.m[ind1 + pSolo.multiMap.countInd.EM] = gEem[indDedup][gm.second]; countMatMult.i[iCB+1] += countMatMult.s; }; }; }; }; }; ////////////////////////////////////////////////////////////////////////////// sorting functions inline int funCompareSolo1 (const void *a, const void *b) { uint32 *va= (uint32*) a; uint32 *vb= (uint32*) b; if (va[1]>vb[1]) { return 1; } else if (va[1]<vb[1]) { return -1; } else if (va[0]>vb[0]){ return 1; } else if (va[0]<vb[0]){ return -1; } else { return 0; }; }; inline int funCompare_uint32_1_2_0 (const void *a, const void *b) { uint32 *va= (uint32*) a; uint32 *vb= (uint32*) b; if (va[1]>vb[1]) { return 1; } else if (va[1]<vb[1]) { return -1; } else if (va[2]>vb[2]){ return 1; } else if (va[2]<vb[2]){ return -1; } else if (va[0]>vb[0]){ return 1; } else if (va[0]<vb[0]){ return -1; } else { return 0; }; }; //////////////////////////////////////////////////////////////////////////////////////////////// uint32 SoloFeature::umiArrayCorrect_CR(const uint32 nU0, uintUMI *umiArr, const bool readInfoRec, const bool nUMIyes, unordered_map <uintUMI,uintUMI> &umiCorr) { qsort(umiArr, nU0, umiArrayStride*sizeof(uint32), funCompareSolo1); for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) { umiArr[iu+2] = umiArr[iu+0]; //stores corrected UMI for 1MM_CR and 1MM_Directional for (uint64 iuu=(nU0-1)*umiArrayStride; iuu>iu; iuu-=umiArrayStride) { uint32 uuXor = umiArr[iu+0] ^ umiArr[iuu+0]; if ( (uuXor >> (__builtin_ctz(uuXor)/2)*2) <= 3 ) {//1MM umiArr[iu+2]=umiArr[iuu+0];//replace iu with iuu break; }; }; }; if (readInfoRec) {//record corrections for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) { if (umiArr[iu+0] != umiArr[iu+2]) umiCorr[umiArr[iu+0]]=umiArr[iu+2]; }; }; if (!nUMIyes) { return 0; } else { unordered_set<uintUMI> umiC; for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) { umiC.insert(umiArr[iu+2]); }; return umiC.size(); }; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////// uint32 SoloFeature::umiArrayCorrect_Directional(const uint32 nU0, uintUMI *umiArr, const bool readInfoRec, const bool nUMIyes, unordered_map <uintUMI,uintUMI> &umiCorr, const int32 dirCountAdd) { qsort(umiArr, nU0, umiArrayStride*sizeof(uint32), funCompareNumbersReverseShift<uint32, 1>);//TODO no need to sort by sequence here, only by count. for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) umiArr[iu+2] = umiArr[iu+0]; //initialized - it will store corrected UMI for 1MM_CR and 1MM_Directional uint32 nU1 = nU0; for (uint64 iu=umiArrayStride; iu<nU0*umiArrayStride; iu+=umiArrayStride) { for (uint64 iuu=0; iuu<iu; iuu+=umiArrayStride) { uint32 uuXor = umiArr[iu+0] ^ umiArr[iuu+0]; if ( (uuXor >> (__builtin_ctz(uuXor)/2)*2) <= 3 && umiArr[iuu+1] >= (2*umiArr[iu+1]+dirCountAdd) ) {//1MM && directional condition umiArr[iu+2]=umiArr[iuu+2];//replace iuu with iu-corrected nU1--; break; }; }; }; if (readInfoRec) {//record corrections for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) { if (umiArr[iu+0] != umiArr[iu+2]) umiCorr[umiArr[iu+0]]=umiArr[iu+2]; }; }; if (!nUMIyes) { return 0; } else { unordered_set<uintUMI> umiC; for (uint64 iu=0; iu<nU0*umiArrayStride; iu+=umiArrayStride) { umiC.insert(umiArr[iu+2]); }; if (umiC.size()!=nU1) cout << nU1 <<" "<< umiC.size()<<endl; return umiC.size(); }; };
16,238
648
{"resourceType":"DataElement","id":"DiagnosticReport.performer.role","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/DiagnosticReport.performer.role","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"DiagnosticReport.performer.role","path":"DiagnosticReport.performer.role","short":"Type of performer","definition":"Describes the type of participation (e.g. a responsible party, author, or verifier).","min":0,"max":"1","type":[{"code":"CodeableConcept"}],"isSummary":true,"binding":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName","valueString":"Role"}],"strength":"example","description":"Indicate a role of diagnostic report performer","valueSetReference":{"reference":"http://hl7.org/fhir/ValueSet/performer-role"}},"mapping":[{"identity":"workflow","map":"Event.performer.role"},{"identity":"v2","map":"PRT-8 (where this PRT-4-Participation = \"PO\")"},{"identity":"rim","map":".functionCode"}]}]}
296
373
/** @file Device IDs for PCH Serial IO Controllers for PCH Conventions: - Register definition format: Prefix_[GenerationName]_[ComponentName]_SubsystemName_RegisterSpace_RegisterName - Prefix: Definitions beginning with "R_" are registers Definitions beginning with "B_" are bits within registers Definitions beginning with "V_" are meaningful values within the bits Definitions beginning with "S_" are register size Definitions beginning with "N_" are the bit position - [GenerationName]: Three letter acronym of the generation is used . Register name without GenerationName applies to all generations. - [ComponentName]: This field indicates the component name that the register belongs to (e.g. PCH, SA etc.) Register name without ComponentName applies to all components. Register that is specific to -H denoted by "_PCH_H_" in component name. Register that is specific to -LP denoted by "_PCH_LP_" in component name. - SubsystemName: This field indicates the subsystem name of the component that the register belongs to (e.g. PCIE, USB, SATA, GPIO, PMC etc.). - RegisterSpace: MEM - MMIO space register of subsystem. IO - IO space register of subsystem. PCR - Private configuration register of subsystem. CFG - PCI configuration space register of subsystem. - RegisterName: Full register name. Copyright (c) 2019 Intel Corporation. All rights reserved. <BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef _PCH_REGS_SERIAL_IO_CNL_ #define _PCH_REGS_SERIAL_IO_CNL_ // // Serial IO I2C0 Controller Registers // #define PCI_DEVICE_NUMBER_PCH_SERIAL_IO_I2C0 21 #define PCI_FUNCTION_NUMBER_PCH_SERIAL_IO_I2C0 0 #define V_CNL_PCH_LP_SERIAL_IO_CFG_I2C0_DEVICE_ID 0x9DE8 #define V_CNL_PCH_H_SERIAL_IO_CFG_I2C0_DEVICE_ID 0xA368 // // Serial IO I2C1 Controller Registers // #define PCI_DEVICE_NUMBER_PCH_SERIAL_IO_I2C1 21 #define PCI_FUNCTION_NUMBER_PCH_SERIAL_IO_I2C1 1 #define V_CNL_PCH_LP_SERIAL_IO_CFG_I2C1_DEVICE_ID 0x9DE9 #define V_CNL_PCH_H_SERIAL_IO_CFG_I2C1_DEVICE_ID 0xA369 // // Serial IO I2C2 Controller Registers // #define PCI_DEVICE_NUMBER_PCH_SERIAL_IO_I2C2 21 #define PCI_FUNCTION_NUMBER_PCH_SERIAL_IO_I2C2 2 #define V_CNL_PCH_LP_SERIAL_IO_CFG_I2C2_DEVICE_ID 0x9DEA #define V_CNL_PCH_H_SERIAL_IO_CFG_I2C2_DEVICE_ID 0xA36A // // Serial IO I2C3 Controller Registers // #define PCI_DEVICE_NUMBER_PCH_SERIAL_IO_I2C3 21 #define PCI_FUNCTION_NUMBER_PCH_SERIAL_IO_I2C3 3 #define V_CNL_PCH_LP_SERIAL_IO_CFG_I2C3_DEVICE_ID 0x9DEB #define V_CNL_PCH_H_SERIAL_IO_CFG_I2C3_DEVICE_ID 0xA36B // // Serial IO I2C4 Controller Registers // #define PCI_DEVICE_NUMBER_PCH_SERIAL_IO_I2C4 25 #define PCI_FUNCTION_NUMBER_PCH_SERIAL_IO_I2C4 0 #define V_CNL_PCH_LP_SERIAL_IO_CFG_I2C4_DEVICE_ID 0x9DC5 // // Serial IO I2C5 Controller Registers // #define PCI_DEVICE_NUMBER_PCH_SERIAL_IO_I2C5 25 #define PCI_FUNCTION_NUMBER_PCH_SERIAL_IO_I2C5 1 #define V_CNL_PCH_LP_SERIAL_IO_CFG_I2C5_DEVICE_ID 0x9DC6 // // Serial IO SPI0 Controller Registers // #define PCI_DEVICE_NUMBER_PCH_SERIAL_IO_SPI0 30 #define PCI_FUNCTION_NUMBER_PCH_SERIAL_IO_SPI0 2 #define V_CNL_PCH_LP_SERIAL_IO_CFG_SPI0_DEVICE_ID 0x9DAA #define V_CNL_PCH_H_SERIAL_IO_CFG_SPI0_DEVICE_ID 0xA32A // // Serial IO SPI1 Controller Registers // #define PCI_DEVICE_NUMBER_PCH_SERIAL_IO_SPI1 30 #define PCI_FUNCTION_NUMBER_PCH_SERIAL_IO_SPI1 3 #define V_CNL_PCH_LP_SERIAL_IO_CFG_SPI1_DEVICE_ID 0x9DAB #define V_CNL_PCH_H_SERIAL_IO_CFG_SPI1_DEVICE_ID 0xA32B // // Serial IO UART0 Controller Registers // #define PCI_DEVICE_NUMBER_PCH_SERIAL_IO_UART0 30 #define PCI_FUNCTION_NUMBER_PCH_SERIAL_IO_UART0 0 #define V_CNL_PCH_LP_SERIAL_IO_CFG_UART0_DEVICE_ID 0x9DA8 #define V_CNL_PCH_H_SERIAL_IO_CFG_UART0_DEVICE_ID 0xA328 // // Serial IO UART1 Controller Registers // #define PCI_DEVICE_NUMBER_PCH_SERIAL_IO_UART1 30 #define PCI_FUNCTION_NUMBER_PCH_SERIAL_IO_UART1 1 #define V_CNL_PCH_LP_SERIAL_IO_CFG_UART1_DEVICE_ID 0x9DA9 #define V_CNL_PCH_H_SERIAL_IO_CFG_UART1_DEVICE_ID 0xA329 // // Serial IO UART2 Controller Registers // #define PCI_DEVICE_NUMBER_PCH_SERIAL_IO_UART2 25 #define PCI_FUNCTION_NUMBER_PCH_SERIAL_IO_UART2 2 #define V_CNL_PCH_LP_SERIAL_IO_CFG_UART2_DEVICE_ID 0x9DC7 #define V_CNL_PCH_H_SERIAL_IO_CFG_UART2_DEVICE_ID 0xA347 #endif
2,356
5,607
<filename>inject-java/src/main/java/io/micronaut/annotation/processing/visitor/JavaWildcardElement.java /* * Copyright 2017-2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micronaut.annotation.processing.visitor; import io.micronaut.core.annotation.Internal; import io.micronaut.core.annotation.NonNull; import io.micronaut.inject.ast.ArrayableClassElement; import io.micronaut.inject.ast.ClassElement; import io.micronaut.inject.ast.WildcardElement; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; /** * Implementation of {@link io.micronaut.inject.ast.WildcardElement} for Java. * * @author <NAME> * @since 3.1.0 */ @Internal final class JavaWildcardElement extends JavaClassElement implements WildcardElement { private final List<JavaClassElement> upperBounds; private final List<JavaClassElement> lowerBounds; JavaWildcardElement(@NonNull List<JavaClassElement> upperBounds, @NonNull List<JavaClassElement> lowerBounds) { super( upperBounds.get(0).classElement, upperBounds.get(0).getAnnotationMetadata(), upperBounds.get(0).visitorContext, upperBounds.get(0).typeArguments, upperBounds.get(0).getGenericTypeInfo() ); this.upperBounds = upperBounds; this.lowerBounds = lowerBounds; } @NonNull @Override public List<? extends ClassElement> getUpperBounds() { return upperBounds; } @NonNull @Override public List<? extends ClassElement> getLowerBounds() { return lowerBounds; } @Override public ClassElement withArrayDimensions(int arrayDimensions) { if (arrayDimensions != 0) { throw new UnsupportedOperationException("Can't create array of wildcard"); } return this; } @Override public ClassElement foldBoundGenericTypes(@NonNull Function<ClassElement, ClassElement> fold) { List<JavaClassElement> upperBounds = this.upperBounds.stream().map(ele -> toJavaClassElement(ele.foldBoundGenericTypes(fold))).collect(Collectors.toList()); List<JavaClassElement> lowerBounds = this.lowerBounds.stream().map(ele -> toJavaClassElement(ele.foldBoundGenericTypes(fold))).collect(Collectors.toList()); return fold.apply(upperBounds.contains(null) || lowerBounds.contains(null) ? null : new JavaWildcardElement(upperBounds, lowerBounds)); } private JavaClassElement toJavaClassElement(ClassElement element) { if (element == null || element instanceof JavaClassElement) { return (JavaClassElement) element; } else { if (element.isWildcard() || element.isGenericPlaceholder()) { throw new UnsupportedOperationException("Cannot convert wildcard / free type variable to JavaClassElement"); } else { return (JavaClassElement) ((ArrayableClassElement) visitorContext.getClassElement(element.getName()) .orElseThrow(() -> new UnsupportedOperationException("Cannot convert ClassElement to JavaClassElement, class was not found on the visitor context"))) .withArrayDimensions(element.getArrayDimensions()) .withBoundGenericTypes(element.getBoundGenericTypes()); } } } }
1,386
777
<filename>chrome/browser/ui/cocoa/autofill/autofill_layout.h // Copyright 2013 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 CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_LAYOUT_H_ #define CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_LAYOUT_H_ #import <Cocoa/Cocoa.h> // Defines a protocol that allows resizing a view hierarchy based on the size // requirements of the subviews. Is implemented by either views or view // controllers. // The way this works together is: // * Subview indicates by calling -requestRelayout on the window controller. // * Window controller queries subviews for preferredSize to determine the // total size of the contentView, adjusts subview origins appropriately, // and calls performLayout on each subview. // * Subviews then recursively do the same thing. @protocol AutofillLayout // Query the preferred size, without actually layouting. // Akin to -intrinsicContentSize on 10.7 - (NSSize)preferredSize; // Layout the content according to the preferred size. Will not touch // frameOrigin. If all objects in the hierarchy were custom views (and not // view controllers), this could be replaced by overriding // -resizeSubviewsWithOldSize:. - (void)performLayout; @end #endif // CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_LAYOUT_H_
414
3,212
<reponame>YolandaMDavis/nifi /* * 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.nifi.hbase; import org.apache.nifi.hbase.util.VisibilityUtil; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.util.MockFlowFile; import org.apache.nifi.util.TestRunner; import org.apache.nifi.util.TestRunners; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.HashMap; public class TestVisibilityUtil { private TestRunner runner; @Before public void setup() throws Exception { runner = TestRunners.newTestRunner(PutHBaseCell.class); final MockHBaseClientService hBaseClient = new MockHBaseClientService(); runner.addControllerService("hbaseClient", hBaseClient); runner.enableControllerService(hBaseClient); runner.setProperty(PutHBaseCell.HBASE_CLIENT_SERVICE, "hbaseClient"); runner.setProperty(PutHBaseCell.TABLE_NAME, "test"); runner.setProperty(PutHBaseCell.COLUMN_QUALIFIER, "test"); runner.setProperty(PutHBaseCell.COLUMN_FAMILY, "test"); runner.assertValid(); } @Test public void testAllPresentOnFlowfile() { runner.setProperty("visibility.test.test", "U&PII"); MockFlowFile ff = new MockFlowFile(System.currentTimeMillis()); ff.putAttributes(new HashMap<String, String>(){{ put("visibility.test.test", "U&PII&PHI"); }}); ProcessContext context = runner.getProcessContext(); String label = VisibilityUtil.pickVisibilityString("test", "test", ff, context); Assert.assertNotNull(label); Assert.assertEquals("U&PII&PHI", label); } @Test public void testOnlyColumnFamilyOnFlowfile() { runner.setProperty("visibility.test", "U&PII"); MockFlowFile ff = new MockFlowFile(System.currentTimeMillis()); ff.putAttributes(new HashMap<String, String>(){{ put("visibility.test", "U&PII&PHI"); }}); ProcessContext context = runner.getProcessContext(); String label = VisibilityUtil.pickVisibilityString("test", "test", ff, context); Assert.assertNotNull(label); Assert.assertEquals("U&PII&PHI", label); } @Test public void testInvalidAttributes() { runner.setProperty("visibility.test", "U&PII"); MockFlowFile ff = new MockFlowFile(System.currentTimeMillis()); ff.putAttributes(new HashMap<String, String>(){{ put("visibility..test", "U&PII&PHI"); }}); ProcessContext context = runner.getProcessContext(); String label = VisibilityUtil.pickVisibilityString("test", "test", ff, context); Assert.assertNotNull(label); Assert.assertEquals("U&PII", label); } @Test public void testColumnFamilyAttributeOnly() { MockFlowFile ff = new MockFlowFile(System.currentTimeMillis()); ff.putAttributes(new HashMap<String, String>(){{ put("visibility.test", "U&PII"); }}); ProcessContext context = runner.getProcessContext(); String label = VisibilityUtil.pickVisibilityString("test", "test", ff, context); Assert.assertNotNull(label); Assert.assertEquals("U&PII", label); } @Test public void testNoAttributes() { runner.setProperty("visibility.test", "U&PII"); MockFlowFile ff = new MockFlowFile(System.currentTimeMillis()); ProcessContext context = runner.getProcessContext(); String label = VisibilityUtil.pickVisibilityString("test", "test", ff, context); Assert.assertNotNull(label); Assert.assertEquals("U&PII", label); runner.setProperty("visibility.test.test", "U&PII&PHI"); label = VisibilityUtil.pickVisibilityString("test", "test", ff, context); Assert.assertNotNull(label); Assert.assertEquals("U&PII&PHI", label); } }
1,723
892
<reponame>westonsteimel/advisory-database-github { "schema_version": "1.2.0", "id": "GHSA-9cp3-fh5x-xfcj", "modified": "2020-08-31T18:26:23Z", "published": "2018-08-09T20:55:46Z", "aliases": [ "CVE-2017-16098" ], "summary": "Regular Expression Denial of Service in charset", "details": "Affected versions of `charset` are susceptible to a regular expression denial of service.\n\nThe amplification on this vulnerability is relatively low - it takes around 2 seconds for the engine to execute on a malicious input which is 50,000 characters in length.\n\n\nIf node was compiled using the `-DHTTP_MAX_HEADER_SIZE` however, the impact of the vulnerability can be significant, as the primary limitation for the vulnerability is the default max HTTP header length in node.\n\n\n## Recommendation\n\nUpdate to version 1.0.1 or later.", "severity": [ ], "affected": [ { "package": { "ecosystem": "npm", "name": "charset" }, "ranges": [ { "type": "ECOSYSTEM", "events": [ { "introduced": "0" }, { "fixed": "1.0.1" } ] } ] } ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2017-16098" }, { "type": "WEB", "url": "https://github.com/node-modules/charset/issues/10" }, { "type": "ADVISORY", "url": "https://github.com/advisories/GHSA-9cp3-fh5x-xfcj" }, { "type": "WEB", "url": "https://nodesecurity.io/advisories/524" }, { "type": "WEB", "url": "https://www.npmjs.com/advisories/524" } ], "database_specific": { "cwe_ids": [ "CWE-400" ], "severity": "MODERATE", "github_reviewed": true } }
867
2,550
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (C) 2010-2012 <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the author nor other contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /** * @defgroup ctrl Video capture and processing control */ #include "libuvc/libuvc.h" #include "libuvc/libuvc_internal.h" static const int REQ_TYPE_SET = 0x21; static const int REQ_TYPE_GET = 0xa1; uvc_error_t uvc_get_power_mode(uvc_device_handle_t *devh, enum uvc_device_power_mode *mode, enum uvc_req_code req_code) { uint8_t mode_char; uvc_error_t ret; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_GET, req_code, UVC_VC_VIDEO_POWER_MODE_CONTROL << 8, 0, &mode_char, sizeof(mode_char), 0); if (ret == 1) { *mode = mode_char; return UVC_SUCCESS; } else { return ret; } } uvc_error_t uvc_set_power_mode(uvc_device_handle_t *devh, enum uvc_device_power_mode mode) { uint8_t mode_char = mode; uvc_error_t ret; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_SET, UVC_SET_CUR, UVC_VC_VIDEO_POWER_MODE_CONTROL << 8, 0, &mode_char, sizeof(mode_char), 0); if (ret == 1) return UVC_SUCCESS; else return ret; } /***** CAMERA TERMINAL CONTROLS *****/ uvc_error_t uvc_get_ae_mode(uvc_device_handle_t *devh, int *mode, enum uvc_req_code req_code) { uint8_t data[1]; uvc_error_t ret; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_GET, req_code, UVC_CT_AE_MODE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) { *mode = data[0]; return UVC_SUCCESS; } else { return ret; } } uvc_error_t uvc_set_ae_mode(uvc_device_handle_t *devh, int mode) { uint8_t data[1]; uvc_error_t ret; data[0] = mode; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_SET, UVC_SET_CUR, UVC_CT_AE_MODE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) return UVC_SUCCESS; else return ret; } uvc_error_t uvc_get_ae_priority(uvc_device_handle_t *devh, uint8_t *priority, enum uvc_req_code req_code) { uint8_t data[1]; uvc_error_t ret; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_GET, req_code, UVC_CT_AE_PRIORITY_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) { *priority = data[0]; return UVC_SUCCESS; } else { return ret; } } uvc_error_t uvc_set_ae_priority(uvc_device_handle_t *devh, uint8_t priority) { uint8_t data[1]; uvc_error_t ret; data[0] = priority; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_SET, UVC_SET_CUR, UVC_CT_AE_PRIORITY_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) return UVC_SUCCESS; else return ret; } uvc_error_t uvc_get_exposure_abs(uvc_device_handle_t *devh, int *time, enum uvc_req_code req_code) { uint8_t data[4]; uvc_error_t ret; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_GET, req_code, UVC_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) { *time = DW_TO_INT(data); return UVC_SUCCESS; } else { return ret; } } uvc_error_t uvc_set_exposure_abs(uvc_device_handle_t *devh, int time) { uint8_t data[4]; uvc_error_t ret; INT_TO_DW(time, data); ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_SET, UVC_SET_CUR, UVC_CT_EXPOSURE_TIME_ABSOLUTE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) return UVC_SUCCESS; else return ret; } uvc_error_t uvc_get_exposure_rel(uvc_device_handle_t *devh, int *step, enum uvc_req_code req_code) { uint8_t data[1]; uvc_error_t ret; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_GET, req_code, UVC_CT_EXPOSURE_TIME_RELATIVE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) { *step = data[0]; return UVC_SUCCESS; } else { return ret; } } uvc_error_t uvc_set_exposure_rel(uvc_device_handle_t *devh, int step) { uint8_t data[1]; uvc_error_t ret; data[0] = step; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_SET, UVC_SET_CUR, UVC_CT_EXPOSURE_TIME_RELATIVE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) return UVC_SUCCESS; else return ret; } uvc_error_t uvc_get_scanning_mode(uvc_device_handle_t *devh, int *step, enum uvc_req_code req_code) { uint8_t data[1]; uvc_error_t ret; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_GET, req_code, UVC_CT_SCANNING_MODE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) { *step = data[0]; return UVC_SUCCESS; } else { return ret; } } uvc_error_t uvc_set_scanning_mode(uvc_device_handle_t *devh, int mode) { uint8_t data[1]; uvc_error_t ret; data[0] = mode; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_SET, UVC_SET_CUR, UVC_CT_SCANNING_MODE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) return UVC_SUCCESS; else return ret; } uvc_error_t uvc_get_focus_abs(uvc_device_handle_t *devh, short *focus, enum uvc_req_code req_code) { uint8_t data[2]; uvc_error_t ret; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_GET, req_code, UVC_CT_FOCUS_ABSOLUTE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) { *focus = SW_TO_SHORT(data); return UVC_SUCCESS; } else { return ret; } } uvc_error_t uvc_set_focus_abs(uvc_device_handle_t *devh, short focus) { uint8_t data[2]; uvc_error_t ret; SHORT_TO_SW(focus, data); ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_SET, UVC_SET_CUR, UVC_CT_FOCUS_ABSOLUTE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) return UVC_SUCCESS; else return ret; } /** @todo focus_rel, focus_auto_control */ /** @todo iris_abs_ctrl, iris_rel_ctrl */ /** @todo zoom_abs, zoom_rel */ uvc_error_t uvc_get_pantilt_abs(uvc_device_handle_t *devh, int *pan, int *tilt, enum uvc_req_code req_code) { uint8_t data[8]; uvc_error_t ret; ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_GET, req_code, UVC_CT_PANTILT_ABSOLUTE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) { *pan = DW_TO_INT(data); *tilt = DW_TO_INT(data + 4); return UVC_SUCCESS; } else { return ret; } } uvc_error_t uvc_set_pantilt_abs(uvc_device_handle_t *devh, int pan, int tilt) { uint8_t data[8]; uvc_error_t ret; INT_TO_DW(pan, data); INT_TO_DW(tilt, data + 4); ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_SET, UVC_SET_CUR, UVC_CT_PANTILT_ABSOLUTE_CONTROL << 8, 1 << 8, data, sizeof(data), 0); if (ret == sizeof(data)) return UVC_SUCCESS; else return ret; } /** @todo pantilt_rel */ /** @todo roll_abs, roll_rel */ /** @todo privacy */ /***** SELECTOR UNIT CONTROLS *****/ /** @todo input_select */ /***** PROCESSING UNIT CONTROLS *****/ /***** GENERIC CONTROLS *****/ /** * @brief Get the length of a control on a terminal or unit. * * @param devh UVC device handle * @param unit Unit or Terminal ID; obtain this from the uvc_extension_unit_t describing the extension unit * @param ctrl Vendor-specific control number to query * @return On success, the length of the control as reported by the device. Otherwise, * a uvc_error_t error describing the error encountered. */ int uvc_get_ctrl_len(uvc_device_handle_t *devh, uint8_t unit, uint8_t ctrl) { unsigned char buf[2]; int ret = libusb_control_transfer( devh->usb_devh, REQ_TYPE_GET, UVC_GET_LEN, ctrl << 8, unit << 8, buf, 2, 0 /* timeout */); if (ret < 0) return ret; else return (unsigned short)SW_TO_SHORT(buf); } /** * @brief Perform a GET_* request from an extension unit. * * @param devh UVC device handle * @param unit Unit ID; obtain this from the uvc_extension_unit_t describing the extension unit * @param ctrl Control number to query * @param data Data buffer to be filled by the device * @param len Size of data buffer * @param req_code GET_* request to execute * @return On success, the number of bytes actually transferred. Otherwise, * a uvc_error_t error describing the error encountered. */ int uvc_get_ctrl(uvc_device_handle_t *devh, uint8_t unit, uint8_t ctrl, void *data, int len, enum uvc_req_code req_code) { return libusb_control_transfer( devh->usb_devh, REQ_TYPE_GET, req_code, ctrl << 8, unit << 8, data, len, 0 /* timeout */); } /** * @brief Perform a SET_CUR request to a terminal or unit. * * @param devh UVC device handle * @param unit Unit or Terminal ID * @param ctrl Control number to set * @param data Data buffer to be sent to the device * @param len Size of data buffer * @return On success, the number of bytes actually transferred. Otherwise, * a uvc_error_t error describing the error encountered. */ int uvc_set_ctrl(uvc_device_handle_t *devh, uint8_t unit, uint8_t ctrl, void *data, int len) { return libusb_control_transfer( devh->usb_devh, REQ_TYPE_SET, UVC_SET_CUR, ctrl << 8, unit << 8, data, len, 0 /* timeout */); }
4,715
583
package lumenghz.com.pulllaunchrocket.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import lumenghz.com.pulllaunchrocket.R; import lumenghz.com.pullrefresh.PullToRefreshView; /** * @author lumeng on 2016-06-17. * <EMAIL> */ public class RecyclerViewFragment extends BaseFragment { @BindView(R.id.pull_to_refresh) PullToRefreshView mPullToRefresh; @BindView(R.id.recycler_view) RecyclerView recyclerView; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_recyclerview, container, false); ButterKnife.bind(this, view); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initRecylerView(); initRefreshView(); } private void initRecylerView() { recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setAdapter(new SampleAdaper()); } private void initRefreshView() { mPullToRefresh.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() { @Override public void onRefresh() { mPullToRefresh.postDelayed(new Runnable() { @Override public void run() { mPullToRefresh.setRefreshing(false); } }, REFRESH_DELAY); } }); } class SampleAdaper extends RecyclerView.Adapter<SampleHolder> { @Override public SampleHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); return new SampleHolder(view); } @Override public void onBindViewHolder(SampleHolder holder, int position) { Map<String, Integer> data = mSampleDatas.get(position); holder.bindData(data); } @Override public int getItemCount() { return mSampleDatas.size(); } } class SampleHolder extends RecyclerView.ViewHolder { private View mRootView; private ImageView iconView; private Map<String, Integer> mData; public SampleHolder(View itemView) { super(itemView); mRootView = itemView; iconView = (ImageView) itemView.findViewById(R.id.image_view_icon); } public void bindData(Map<String, Integer> data) { mData = data; mRootView.setBackgroundResource(mData.get(COLOR)); iconView.setImageResource(mData.get(ICON)); } } }
1,359
599
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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. """ from typing import List from unittest import mock import pytest from backend.iam.permissions.apply_url import ApplyURLGenerator from backend.iam.permissions.request import ActionResourcesRequest from backend.iam.permissions.resources.cluster import ClusterPermission from backend.iam.permissions.resources.namespace import NamespacePermission from backend.iam.permissions.resources.project import ProjectPermission from .fake_iam import FakeClusterPermission, FakeNamespacePermission, FakeProjectPermission def generate_apply_url(username: str, action_request_list: List[ActionResourcesRequest]) -> List[str]: expect = [] for req in action_request_list: resources = '' if req.resources: resources = ''.join(req.resources) parent_chain = '' if req.parent_chain: parent_chain = ''.join([f'{item.resource_type}/{item.resource_id}' for item in req.parent_chain]) expect.append(f'{req.resource_type}:{req.action_id}:{resources}:{parent_chain}') return expect @pytest.fixture(autouse=True) def patch_generate_apply_url(): with mock.patch.object(ApplyURLGenerator, 'generate_apply_url', new=generate_apply_url): yield @pytest.fixture def project_permission_obj(): patcher = mock.patch.object(ProjectPermission, '__bases__', (FakeProjectPermission,)) with patcher: patcher.is_local = True # 标注为本地属性,__exit__ 的时候恢复成 patcher.temp_original yield ProjectPermission() @pytest.fixture def namespace_permission_obj(): cluster_patcher = mock.patch.object(ClusterPermission, '__bases__', (FakeClusterPermission,)) project_patcher = mock.patch.object(ProjectPermission, '__bases__', (FakeProjectPermission,)) namespace_patcher = mock.patch.object(NamespacePermission, '__bases__', (FakeNamespacePermission,)) with cluster_patcher, project_patcher, namespace_patcher: cluster_patcher.is_local = True # 标注为本地属性,__exit__ 的时候恢复成 patcher.temp_original project_patcher.is_local = True namespace_patcher.is_local = True yield NamespacePermission()
988
14,668
// 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. #include "services/network/public/cpp/self_deleting_url_loader_factory.h" #include <utility> namespace network { SelfDeletingURLLoaderFactory::SelfDeletingURLLoaderFactory( mojo::PendingReceiver<mojom::URLLoaderFactory> factory_receiver) { receivers_.set_disconnect_handler(base::BindRepeating( &SelfDeletingURLLoaderFactory::OnDisconnect, base::Unretained(this))); receivers_.Add(this, std::move(factory_receiver)); } SelfDeletingURLLoaderFactory::~SelfDeletingURLLoaderFactory() = default; void SelfDeletingURLLoaderFactory::DisconnectReceiversAndDestroy() { // Clear |receivers_| to explicitly make sure that no further method // invocations or disconnection notifications will happen. (per the // comment of mojo::ReceiverSet::Clear) receivers_.Clear(); // Similarly to OnDisconnect, if there are no more |receivers_|, then no // instance methods of |this| can be called in the future (mojo methods Clone // and CreateLoaderAndStart should be the only public entrypoints). // Therefore, it is safe to delete |this| at this point. delete this; } void SelfDeletingURLLoaderFactory::Clone( mojo::PendingReceiver<mojom::URLLoaderFactory> loader) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); receivers_.Add(this, std::move(loader)); } void SelfDeletingURLLoaderFactory::OnDisconnect() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (receivers_.empty()) { // If there are no more |receivers_|, then no instance methods of |this| can // be called in the future (mojo methods Clone and CreateLoaderAndStart // should be the only public entrypoints). Therefore, it is safe to delete // |this| at this point. delete this; } } } // namespace network
615
1,418
<reponame>amenic-hub/aima-java<gh_stars>1000+ package aima.core.search.framework.problem; import aima.core.search.framework.Node; import java.util.List; /** * Artificial Intelligence A Modern Approach (3rd Edition): page 66.<br> * <br> * A problem can be defined formally by five components: <br> * <ul> * <li>The <b>initial state</b> that the agent starts in.</li> * <li>A description of the possible <b>actions</b> available to the agent. * Given a particular state s, ACTIONS(s) returns the set of actions that can be * executed in s.</li> * <li>A description of what each action does; the formal name for this is the * <b>transition model, specified by a function RESULT(s, a) that returns the * state that results from doing action a in state s.</b></li> * <li>The <b>goal test</b>, which determines whether a given state is a goal * state.</li> * <li>A <b>path cost</b> function that assigns a numeric cost to each path. The * problem-solving agent chooses a cost function that reflects its own * performance measure. The <b>step cost</b> of taking action a in state s to * reach state s' is denoted by c(s,a,s')</li> * </ul> * * This implementation provides an additional solution test. It can be used to * compute more than one solution or to formulate acceptance criteria for the * sequence of actions. * * @param <S> The type used to represent states * @param <A> The type of the actions to be used to navigate through the state space * * @author <NAME> * @author <NAME> */ public interface Problem<S, A> extends OnlineSearchProblem<S, A> { /** * Returns the initial state of the agent. */ S getInitialState(); /** * Returns the set of actions that can be executed in the given state. * We say that each of these actions is <b>applicable</b> in the state. */ List<A> getActions(S state); /** * Returns the description of what each action does. */ S getResult(S state, A action); /** * Determines whether a given state is a goal state. */ boolean testGoal(S state); /** * Returns the <b>step cost</b> of taking action <code>action</code> in state <code>state</code> to reach state * <code>stateDelta</code> denoted by c(s, a, s'). */ double getStepCosts(S state, A action, S stateDelta); /** * Tests whether a node represents an acceptable solution. The default implementation * delegates the check to the goal test. Other implementations could make use of the additional * information given by the node (e.g. the sequence of actions leading to the node). To compute * all or the five best solutions (not just the best), tester implementations could return false * and internally collect the paths of all nodes whose state passes the goal test until enough * solutions have been collected. * Search implementations should always access the goal test via this method to support * solution acceptance testing. */ default boolean testSolution(Node<S, A> node) { return testGoal(node.getState()); } }
1,034
313
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.runtime.store.v3.memory; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancer; import com.netflix.titus.api.loadbalancer.model.JobLoadBalancerState; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTarget; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTarget.State; import com.netflix.titus.api.loadbalancer.model.LoadBalancerTargetState; import com.netflix.titus.api.loadbalancer.store.LoadBalancerStore; import com.netflix.titus.runtime.loadbalancer.LoadBalancerCursors; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import rx.Completable; import rx.Observable; /** * Operations are not being indexed yet for simplicity. */ public class InMemoryLoadBalancerStore implements LoadBalancerStore { private final ConcurrentMap<JobLoadBalancer, JobLoadBalancer.State> associations = new ConcurrentHashMap<>(); private final ConcurrentMap<LoadBalancerTarget, State> targets = new ConcurrentHashMap<>(); @Override public Observable<JobLoadBalancer> getAssociatedLoadBalancersForJob(String jobId) { return Observable.defer(() -> Observable.from(getAssociatedLoadBalancersSetForJob(jobId))); } // Note: This implementation is not optimized for constant time lookup and should only // be used for non-performance critical scenarios, like testing. @Override public Set<JobLoadBalancer> getAssociatedLoadBalancersSetForJob(String jobId) { return associations.entrySet().stream() .filter(pair -> pair.getKey().getJobId().equals(jobId) && (pair.getValue() == JobLoadBalancer.State.ASSOCIATED)) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } @Override public Completable addOrUpdateLoadBalancer(JobLoadBalancer jobLoadBalancer, JobLoadBalancer.State state) { return Completable.fromAction(() -> associations.put(jobLoadBalancer, state)); } @Override public Completable removeLoadBalancer(JobLoadBalancer jobLoadBalancer) { return Completable.fromAction(() -> associations.remove(jobLoadBalancer)); } @Override public int getNumLoadBalancersForJob(String jobId) { int loadBalancerCount = 0; for (Map.Entry<JobLoadBalancer, JobLoadBalancer.State> entry : associations.entrySet()) { if (entry.getKey().getJobId().equals(jobId)) { loadBalancerCount++; } } return loadBalancerCount; } @Override public List<JobLoadBalancerState> getAssociations() { return associations.entrySet().stream() .map(JobLoadBalancerState::from) .collect(Collectors.toList()); } @Override public List<JobLoadBalancer> getAssociationsPage(int offset, int limit) { return associations.keySet().stream() .sorted(LoadBalancerCursors.loadBalancerComparator()) .skip(offset) .limit(limit) .collect(Collectors.toList()); } @Override public Mono<Void> addOrUpdateTargets(Collection<LoadBalancerTargetState> toAdd) { return Mono.fromRunnable(() -> toAdd.forEach(t -> targets.put(t.getLoadBalancerTarget(), t.getState()))); } @Override public Mono<Void> removeDeregisteredTargets(Collection<LoadBalancerTarget> toRemove) { return Mono.fromRunnable(() -> toRemove.forEach(target -> targets.remove(target, State.DEREGISTERED))); } @Override public Flux<LoadBalancerTargetState> getLoadBalancerTargets(String loadBalancerId) { return Flux.fromStream( targets.entrySet().stream() .filter(entry -> entry.getKey().getLoadBalancerId().equals(loadBalancerId)) .map(LoadBalancerTargetState::from) ); } }
1,692
1,604
package org.bouncycastle.jcajce.provider.asymmetric.util; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.GOST3410Parameters; import org.bouncycastle.crypto.params.GOST3410PrivateKeyParameters; import org.bouncycastle.crypto.params.GOST3410PublicKeyParameters; import org.bouncycastle.jce.interfaces.GOST3410PrivateKey; import org.bouncycastle.jce.interfaces.GOST3410PublicKey; import org.bouncycastle.jce.spec.GOST3410PublicKeyParameterSetSpec; /** * utility class for converting jce/jca GOST3410-94 objects * objects into their org.bouncycastle.crypto counterparts. */ public class GOST3410Util { static public AsymmetricKeyParameter generatePublicKeyParameter( PublicKey key) throws InvalidKeyException { if (key instanceof GOST3410PublicKey) { GOST3410PublicKey k = (GOST3410PublicKey)key; GOST3410PublicKeyParameterSetSpec p = k.getParameters().getPublicKeyParameters(); return new GOST3410PublicKeyParameters(k.getY(), new GOST3410Parameters(p.getP(), p.getQ(), p.getA())); } throw new InvalidKeyException("can't identify GOST3410 public key: " + key.getClass().getName()); } static public AsymmetricKeyParameter generatePrivateKeyParameter( PrivateKey key) throws InvalidKeyException { if (key instanceof GOST3410PrivateKey) { GOST3410PrivateKey k = (GOST3410PrivateKey)key; GOST3410PublicKeyParameterSetSpec p = k.getParameters().getPublicKeyParameters(); return new GOST3410PrivateKeyParameters(k.getX(), new GOST3410Parameters(p.getP(), p.getQ(), p.getA())); } throw new InvalidKeyException("can't identify GOST3410 private key."); } }
798
1,420
<gh_stars>1000+ /* * * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.genie.agent.execution.statemachine.stages; import com.netflix.genie.agent.cli.logging.ConsoleLog; import com.netflix.genie.agent.execution.exceptions.SetUpJobException; import com.netflix.genie.agent.execution.services.JobSetupService; import com.netflix.genie.agent.execution.statemachine.ExecutionContext; import com.netflix.genie.agent.execution.statemachine.ExecutionStage; import com.netflix.genie.agent.execution.statemachine.FatalJobExecutionException; import com.netflix.genie.agent.execution.statemachine.RetryableJobExecutionException; import com.netflix.genie.agent.execution.statemachine.States; import com.netflix.genie.common.external.dtos.v4.JobSpecification; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.util.Set; /** * Download dependencies such as binaries and configurations attached to the job and its dependent entities. * * @author mprimi * @since 4.0.0 */ @Slf4j public class DownloadDependenciesStage extends ExecutionStage { private final JobSetupService jobSetupService; /** * Constructor. * * @param jobSetupService job setup service */ public DownloadDependenciesStage(final JobSetupService jobSetupService) { super(States.DOWNLOAD_DEPENDENCIES); this.jobSetupService = jobSetupService; } @Override protected void attemptStageAction( final ExecutionContext executionContext ) throws RetryableJobExecutionException, FatalJobExecutionException { final JobSpecification jobSpecification = executionContext.getJobSpecification(); final File jobDirectory = executionContext.getJobDirectory(); assert jobSpecification != null; assert jobDirectory != null; log.info("Downloading job dependencies"); final Set<File> downloaded; try { downloaded = this.jobSetupService.downloadJobResources(jobSpecification, jobDirectory); } catch (SetUpJobException e) { throw createFatalException(e); } ConsoleLog.getLogger().info("Downloaded dependencies ({} files)", downloaded.size()); } }
912
3,071
<filename>.devcontainer/devcontainer.json { "name": "Bats core development environment", "dockerFile": "Dockerfile", "build": {"args": {"bashver": "4.3"}} }
61
1,334
package org.mockserver.memory; import org.mockserver.model.ObjectWithJsonToString; public class Detail extends ObjectWithJsonToString { private long init; private long used; private long committed; private long max; public Detail plus(Detail detail) { return new Detail() .setInit(init + detail.init) .setUsed(used + detail.used) .setCommitted(committed + detail.committed) .setMax(max + detail.max); } public long getInit() { return init; } public Detail setInit(long init) { this.init = init; return this; } public long getUsed() { return used; } public Detail setUsed(long used) { this.used = used; return this; } public long getCommitted() { return committed; } public Detail setCommitted(long committed) { this.committed = committed; return this; } public long getMax() { return max; } public Detail setMax(long max) { this.max = max; return this; } }
474
2,415
{ "headers": { "expires": "Sun, 04 Nov 2018 13:10:05 GMT", "date": "Sun, 04 Nov 2018 13:10:05 GMT", "cache-control": "private, max-age=0, must-revalidate, no-transform", "etag": "\"MVck1nZK1y2Nk_4y5UoypDlO31c=/6UeW4kpHSUM2gc7z0bIbcg4Ych0=\"", "vary": "Origin, X-Origin", "content-type": "application/json; charset=UTF-8", "x-content-type-options": "nosniff", "x-frame-options": "SAMEORIGIN", "x-xss-protection": "1; mode=block", "server": "GSE", "alt-svc": "quic=\":443\"; ma=2592000; v=\"44,43,39,35\"", "transfer-encoding": "chunked", "status": "200", "content-length": "620", "-content-encoding": "gzip", "content-location": "https://www.googleapis.com/compute/v1/projects/cloud-custodian/global/firewalls/allow-inbound-xyz?alt=json" }, "body": { "kind": "compute#firewall", "id": "4746899906201084445", "creationTimestamp": "2018-11-04T03:50:10.647-08:00", "name": "allow-inbound-xyz", "description": "", "network": "https://www.googleapis.com/compute/v1/projects/cloud-custodian/global/networks/default", "priority": 1000, "sourceRanges": [ "0.0.0.0/0" ], "targetServiceAccounts": [ "604150802624-<EMAIL>@developer.gserviceaccount.com" ], "allowed": [ { "IPProtocol": "all" } ], "direction": "INGRESS", "disabled": false, "selfLink": "https://www.googleapis.com/compute/v1/projects/cloud-custodian/global/firewalls/allow-inbound-xyz" } }
711
305
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/aecm/echo_control_mobile.h" #ifdef AEC_DEBUG #include <stdio.h> #endif #include <stdlib.h> #include <string.h> extern "C" { #include "common_audio/ring_buffer.h" #include "common_audio/signal_processing/include/signal_processing_library.h" #include "modules/audio_processing/aecm/aecm_defines.h" } #include "modules/audio_processing/aecm/aecm_core.h" #define BUF_SIZE_FRAMES 50 // buffer size (frames) // Maximum length of resampled signal. Must be an integer multiple of frames // (ceil(1/(1 + MIN_SKEW)*2) + 1)*FRAME_LEN // The factor of 2 handles wb, and the + 1 is as a safety margin #define MAX_RESAMP_LEN (5 * FRAME_LEN) static const size_t kBufSizeSamp = BUF_SIZE_FRAMES * FRAME_LEN; // buffer size (samples) static const int kSampMsNb = 8; // samples per ms in nb // Target suppression levels for nlp modes // log{0.001, 0.00001, 0.00000001} static const int kInitCheck = 42; typedef struct { int sampFreq; int scSampFreq; short bufSizeStart; int knownDelay; // Stores the last frame added to the farend buffer short farendOld[2][FRAME_LEN]; short initFlag; // indicates if AEC has been initialized // Variables used for averaging far end buffer size short counter; short sum; short firstVal; short checkBufSizeCtr; // Variables used for delay shifts short msInSndCardBuf; short filtDelay; int timeForDelayChange; int ECstartup; int checkBuffSize; int delayChange; short lastDelayDiff; int16_t echoMode; #ifdef AEC_DEBUG FILE* bufFile; FILE* delayFile; FILE* preCompFile; FILE* postCompFile; #endif // AEC_DEBUG // Structures RingBuffer* farendBuf; AecmCore* aecmCore; } AecMobile; // Estimates delay to set the position of the farend buffer read pointer // (controlled by knownDelay) static int WebRtcAecm_EstBufDelay(AecMobile* aecm, short msInSndCardBuf); // Stuffs the farend buffer if the estimated delay is too large static int WebRtcAecm_DelayComp(AecMobile* aecm); void* WebRtcAecm_Create() { AecMobile* aecm = static_cast<AecMobile*>(malloc(sizeof(AecMobile))); aecm->aecmCore = WebRtcAecm_CreateCore(); if (!aecm->aecmCore) { WebRtcAecm_Free(aecm); return NULL; } aecm->farendBuf = WebRtc_CreateBuffer(kBufSizeSamp, sizeof(int16_t)); if (!aecm->farendBuf) { WebRtcAecm_Free(aecm); return NULL; } aecm->initFlag = 0; #ifdef AEC_DEBUG aecm->aecmCore->farFile = fopen("aecFar.pcm", "wb"); aecm->aecmCore->nearFile = fopen("aecNear.pcm", "wb"); aecm->aecmCore->outFile = fopen("aecOut.pcm", "wb"); // aecm->aecmCore->outLpFile = fopen("aecOutLp.pcm","wb"); aecm->bufFile = fopen("aecBuf.dat", "wb"); aecm->delayFile = fopen("aecDelay.dat", "wb"); aecm->preCompFile = fopen("preComp.pcm", "wb"); aecm->postCompFile = fopen("postComp.pcm", "wb"); #endif // AEC_DEBUG return aecm; } void WebRtcAecm_Free(void* aecmInst) { AecMobile* aecm = static_cast<AecMobile*>(aecmInst); if (aecm == NULL) { return; } #ifdef AEC_DEBUG fclose(aecm->aecmCore->farFile); fclose(aecm->aecmCore->nearFile); fclose(aecm->aecmCore->outFile); // fclose(aecm->aecmCore->outLpFile); fclose(aecm->bufFile); fclose(aecm->delayFile); fclose(aecm->preCompFile); fclose(aecm->postCompFile); #endif // AEC_DEBUG WebRtcAecm_FreeCore(aecm->aecmCore); WebRtc_FreeBuffer(aecm->farendBuf); free(aecm); } int32_t WebRtcAecm_Init(void* aecmInst, int32_t sampFreq) { AecMobile* aecm = static_cast<AecMobile*>(aecmInst); AecmConfig aecConfig; if (aecm == NULL) { return -1; } if (sampFreq != 8000 && sampFreq != 16000) { return AECM_BAD_PARAMETER_ERROR; } aecm->sampFreq = sampFreq; // Initialize AECM core if (WebRtcAecm_InitCore(aecm->aecmCore, aecm->sampFreq) == -1) { return AECM_UNSPECIFIED_ERROR; } // Initialize farend buffer WebRtc_InitBuffer(aecm->farendBuf); aecm->initFlag = kInitCheck; // indicates that initialization has been done aecm->delayChange = 1; aecm->sum = 0; aecm->counter = 0; aecm->checkBuffSize = 1; aecm->firstVal = 0; aecm->ECstartup = 1; aecm->bufSizeStart = 0; aecm->checkBufSizeCtr = 0; aecm->filtDelay = 0; aecm->timeForDelayChange = 0; aecm->knownDelay = 0; aecm->lastDelayDiff = 0; memset(&aecm->farendOld, 0, sizeof(aecm->farendOld)); // Default settings. aecConfig.cngMode = AecmTrue; aecConfig.echoMode = 3; if (WebRtcAecm_set_config(aecm, aecConfig) == -1) { return AECM_UNSPECIFIED_ERROR; } return 0; } // Returns any error that is caused when buffering the // farend signal. int32_t WebRtcAecm_GetBufferFarendError(void* aecmInst, const int16_t* farend, size_t nrOfSamples) { AecMobile* aecm = static_cast<AecMobile*>(aecmInst); if (aecm == NULL) return -1; if (farend == NULL) return AECM_NULL_POINTER_ERROR; if (aecm->initFlag != kInitCheck) return AECM_UNINITIALIZED_ERROR; if (nrOfSamples != 80 && nrOfSamples != 160) return AECM_BAD_PARAMETER_ERROR; return 0; } int32_t WebRtcAecm_BufferFarend(void* aecmInst, const int16_t* farend, size_t nrOfSamples) { AecMobile* aecm = static_cast<AecMobile*>(aecmInst); const int32_t err = WebRtcAecm_GetBufferFarendError(aecmInst, farend, nrOfSamples); if (err != 0) return err; // TODO(unknown): Is this really a good idea? if (!aecm->ECstartup) { WebRtcAecm_DelayComp(aecm); } WebRtc_WriteBuffer(aecm->farendBuf, farend, nrOfSamples); return 0; } int32_t WebRtcAecm_Process(void* aecmInst, const int16_t* nearendNoisy, const int16_t* nearendClean, int16_t* out, size_t nrOfSamples, int16_t msInSndCardBuf) { AecMobile* aecm = static_cast<AecMobile*>(aecmInst); int32_t retVal = 0; size_t i; short nmbrOfFilledBuffers; size_t nBlocks10ms; size_t nFrames; #ifdef AEC_DEBUG short msInAECBuf; #endif if (aecm == NULL) { return -1; } if (nearendNoisy == NULL) { return AECM_NULL_POINTER_ERROR; } if (out == NULL) { return AECM_NULL_POINTER_ERROR; } if (aecm->initFlag != kInitCheck) { return AECM_UNINITIALIZED_ERROR; } if (nrOfSamples != 80 && nrOfSamples != 160) { return AECM_BAD_PARAMETER_ERROR; } if (msInSndCardBuf < 0) { msInSndCardBuf = 0; retVal = AECM_BAD_PARAMETER_WARNING; } else if (msInSndCardBuf > 500) { msInSndCardBuf = 500; retVal = AECM_BAD_PARAMETER_WARNING; } msInSndCardBuf += 10; aecm->msInSndCardBuf = msInSndCardBuf; nFrames = nrOfSamples / FRAME_LEN; nBlocks10ms = nFrames / aecm->aecmCore->mult; if (aecm->ECstartup) { if (nearendClean == NULL) { if (out != nearendNoisy) { memcpy(out, nearendNoisy, sizeof(short) * nrOfSamples); } } else if (out != nearendClean) { memcpy(out, nearendClean, sizeof(short) * nrOfSamples); } nmbrOfFilledBuffers = (short)WebRtc_available_read(aecm->farendBuf) / FRAME_LEN; // The AECM is in the start up mode // AECM is disabled until the soundcard buffer and farend buffers are OK // Mechanism to ensure that the soundcard buffer is reasonably stable. if (aecm->checkBuffSize) { aecm->checkBufSizeCtr++; // Before we fill up the far end buffer we require the amount of data on // the sound card to be stable (+/-8 ms) compared to the first value. This // comparison is made during the following 4 consecutive frames. If it // seems to be stable then we start to fill up the far end buffer. if (aecm->counter == 0) { aecm->firstVal = aecm->msInSndCardBuf; aecm->sum = 0; } if (abs(aecm->firstVal - aecm->msInSndCardBuf) < WEBRTC_SPL_MAX(0.2 * aecm->msInSndCardBuf, kSampMsNb)) { aecm->sum += aecm->msInSndCardBuf; aecm->counter++; } else { aecm->counter = 0; } if (aecm->counter * nBlocks10ms >= 6) { // The farend buffer size is determined in blocks of 80 samples // Use 75% of the average value of the soundcard buffer aecm->bufSizeStart = WEBRTC_SPL_MIN( (3 * aecm->sum * aecm->aecmCore->mult) / (aecm->counter * 40), BUF_SIZE_FRAMES); // buffersize has now been determined aecm->checkBuffSize = 0; } if (aecm->checkBufSizeCtr * nBlocks10ms > 50) { // for really bad sound cards, don't disable echocanceller for more than // 0.5 sec aecm->bufSizeStart = WEBRTC_SPL_MIN( (3 * aecm->msInSndCardBuf * aecm->aecmCore->mult) / 40, BUF_SIZE_FRAMES); aecm->checkBuffSize = 0; } } // if checkBuffSize changed in the if-statement above if (!aecm->checkBuffSize) { // soundcard buffer is now reasonably stable // When the far end buffer is filled with approximately the same amount of // data as the amount on the sound card we end the start up phase and // start to cancel echoes. if (nmbrOfFilledBuffers == aecm->bufSizeStart) { aecm->ECstartup = 0; // Enable the AECM } else if (nmbrOfFilledBuffers > aecm->bufSizeStart) { WebRtc_MoveReadPtr(aecm->farendBuf, (int)WebRtc_available_read(aecm->farendBuf) - (int)aecm->bufSizeStart * FRAME_LEN); aecm->ECstartup = 0; } } } else { // AECM is enabled // Note only 1 block supported for nb and 2 blocks for wb for (i = 0; i < nFrames; i++) { int16_t farend[FRAME_LEN]; const int16_t* farend_ptr = NULL; nmbrOfFilledBuffers = (short)WebRtc_available_read(aecm->farendBuf) / FRAME_LEN; // Check that there is data in the far end buffer if (nmbrOfFilledBuffers > 0) { // Get the next 80 samples from the farend buffer WebRtc_ReadBuffer(aecm->farendBuf, (void**)&farend_ptr, farend, FRAME_LEN); // Always store the last frame for use when we run out of data memcpy(&(aecm->farendOld[i][0]), farend_ptr, FRAME_LEN * sizeof(short)); } else { // We have no data so we use the last played frame memcpy(farend, &(aecm->farendOld[i][0]), FRAME_LEN * sizeof(short)); farend_ptr = farend; } // Call buffer delay estimator when all data is extracted, // i,e. i = 0 for NB and i = 1 for WB if ((i == 0 && aecm->sampFreq == 8000) || (i == 1 && aecm->sampFreq == 16000)) { WebRtcAecm_EstBufDelay(aecm, aecm->msInSndCardBuf); } // Call the AECM /*WebRtcAecm_ProcessFrame(aecm->aecmCore, farend, &nearend[FRAME_LEN * i], &out[FRAME_LEN * i], aecm->knownDelay);*/ if (WebRtcAecm_ProcessFrame( aecm->aecmCore, farend_ptr, &nearendNoisy[FRAME_LEN * i], (nearendClean ? &nearendClean[FRAME_LEN * i] : NULL), &out[FRAME_LEN * i]) == -1) return -1; } } #ifdef AEC_DEBUG msInAECBuf = (short)WebRtc_available_read(aecm->farendBuf) / (kSampMsNb * aecm->aecmCore->mult); fwrite(&msInAECBuf, 2, 1, aecm->bufFile); fwrite(&(aecm->knownDelay), sizeof(aecm->knownDelay), 1, aecm->delayFile); #endif return retVal; } int32_t WebRtcAecm_set_config(void* aecmInst, AecmConfig config) { AecMobile* aecm = static_cast<AecMobile*>(aecmInst); if (aecm == NULL) { return -1; } if (aecm->initFlag != kInitCheck) { return AECM_UNINITIALIZED_ERROR; } if (config.cngMode != AecmFalse && config.cngMode != AecmTrue) { return AECM_BAD_PARAMETER_ERROR; } aecm->aecmCore->cngMode = config.cngMode; if (config.echoMode < 0 || config.echoMode > 4) { return AECM_BAD_PARAMETER_ERROR; } aecm->echoMode = config.echoMode; if (aecm->echoMode == 0) { aecm->aecmCore->supGain = SUPGAIN_DEFAULT >> 3; aecm->aecmCore->supGainOld = SUPGAIN_DEFAULT >> 3; aecm->aecmCore->supGainErrParamA = SUPGAIN_ERROR_PARAM_A >> 3; aecm->aecmCore->supGainErrParamD = SUPGAIN_ERROR_PARAM_D >> 3; aecm->aecmCore->supGainErrParamDiffAB = (SUPGAIN_ERROR_PARAM_A >> 3) - (SUPGAIN_ERROR_PARAM_B >> 3); aecm->aecmCore->supGainErrParamDiffBD = (SUPGAIN_ERROR_PARAM_B >> 3) - (SUPGAIN_ERROR_PARAM_D >> 3); } else if (aecm->echoMode == 1) { aecm->aecmCore->supGain = SUPGAIN_DEFAULT >> 2; aecm->aecmCore->supGainOld = SUPGAIN_DEFAULT >> 2; aecm->aecmCore->supGainErrParamA = SUPGAIN_ERROR_PARAM_A >> 2; aecm->aecmCore->supGainErrParamD = SUPGAIN_ERROR_PARAM_D >> 2; aecm->aecmCore->supGainErrParamDiffAB = (SUPGAIN_ERROR_PARAM_A >> 2) - (SUPGAIN_ERROR_PARAM_B >> 2); aecm->aecmCore->supGainErrParamDiffBD = (SUPGAIN_ERROR_PARAM_B >> 2) - (SUPGAIN_ERROR_PARAM_D >> 2); } else if (aecm->echoMode == 2) { aecm->aecmCore->supGain = SUPGAIN_DEFAULT >> 1; aecm->aecmCore->supGainOld = SUPGAIN_DEFAULT >> 1; aecm->aecmCore->supGainErrParamA = SUPGAIN_ERROR_PARAM_A >> 1; aecm->aecmCore->supGainErrParamD = SUPGAIN_ERROR_PARAM_D >> 1; aecm->aecmCore->supGainErrParamDiffAB = (SUPGAIN_ERROR_PARAM_A >> 1) - (SUPGAIN_ERROR_PARAM_B >> 1); aecm->aecmCore->supGainErrParamDiffBD = (SUPGAIN_ERROR_PARAM_B >> 1) - (SUPGAIN_ERROR_PARAM_D >> 1); } else if (aecm->echoMode == 3) { aecm->aecmCore->supGain = SUPGAIN_DEFAULT; aecm->aecmCore->supGainOld = SUPGAIN_DEFAULT; aecm->aecmCore->supGainErrParamA = SUPGAIN_ERROR_PARAM_A; aecm->aecmCore->supGainErrParamD = SUPGAIN_ERROR_PARAM_D; aecm->aecmCore->supGainErrParamDiffAB = SUPGAIN_ERROR_PARAM_A - SUPGAIN_ERROR_PARAM_B; aecm->aecmCore->supGainErrParamDiffBD = SUPGAIN_ERROR_PARAM_B - SUPGAIN_ERROR_PARAM_D; } else if (aecm->echoMode == 4) { aecm->aecmCore->supGain = SUPGAIN_DEFAULT << 1; aecm->aecmCore->supGainOld = SUPGAIN_DEFAULT << 1; aecm->aecmCore->supGainErrParamA = SUPGAIN_ERROR_PARAM_A << 1; aecm->aecmCore->supGainErrParamD = SUPGAIN_ERROR_PARAM_D << 1; aecm->aecmCore->supGainErrParamDiffAB = (SUPGAIN_ERROR_PARAM_A << 1) - (SUPGAIN_ERROR_PARAM_B << 1); aecm->aecmCore->supGainErrParamDiffBD = (SUPGAIN_ERROR_PARAM_B << 1) - (SUPGAIN_ERROR_PARAM_D << 1); } return 0; } int32_t WebRtcAecm_InitEchoPath(void* aecmInst, const void* echo_path, size_t size_bytes) { AecMobile* aecm = static_cast<AecMobile*>(aecmInst); const int16_t* echo_path_ptr = static_cast<const int16_t*>(echo_path); if (aecmInst == NULL) { return -1; } if (echo_path == NULL) { return AECM_NULL_POINTER_ERROR; } if (size_bytes != WebRtcAecm_echo_path_size_bytes()) { // Input channel size does not match the size of AECM return AECM_BAD_PARAMETER_ERROR; } if (aecm->initFlag != kInitCheck) { return AECM_UNINITIALIZED_ERROR; } WebRtcAecm_InitEchoPathCore(aecm->aecmCore, echo_path_ptr); return 0; } int32_t WebRtcAecm_GetEchoPath(void* aecmInst, void* echo_path, size_t size_bytes) { AecMobile* aecm = static_cast<AecMobile*>(aecmInst); int16_t* echo_path_ptr = static_cast<int16_t*>(echo_path); if (aecmInst == NULL) { return -1; } if (echo_path == NULL) { return AECM_NULL_POINTER_ERROR; } if (size_bytes != WebRtcAecm_echo_path_size_bytes()) { // Input channel size does not match the size of AECM return AECM_BAD_PARAMETER_ERROR; } if (aecm->initFlag != kInitCheck) { return AECM_UNINITIALIZED_ERROR; } memcpy(echo_path_ptr, aecm->aecmCore->channelStored, size_bytes); return 0; } size_t WebRtcAecm_echo_path_size_bytes() { return (PART_LEN1 * sizeof(int16_t)); } static int WebRtcAecm_EstBufDelay(AecMobile* aecm, short msInSndCardBuf) { short delayNew, nSampSndCard; short nSampFar = (short)WebRtc_available_read(aecm->farendBuf); short diff; nSampSndCard = msInSndCardBuf * kSampMsNb * aecm->aecmCore->mult; delayNew = nSampSndCard - nSampFar; if (delayNew < FRAME_LEN) { WebRtc_MoveReadPtr(aecm->farendBuf, FRAME_LEN); delayNew += FRAME_LEN; } aecm->filtDelay = WEBRTC_SPL_MAX(0, (8 * aecm->filtDelay + 2 * delayNew) / 10); diff = aecm->filtDelay - aecm->knownDelay; if (diff > 224) { if (aecm->lastDelayDiff < 96) { aecm->timeForDelayChange = 0; } else { aecm->timeForDelayChange++; } } else if (diff < 96 && aecm->knownDelay > 0) { if (aecm->lastDelayDiff > 224) { aecm->timeForDelayChange = 0; } else { aecm->timeForDelayChange++; } } else { aecm->timeForDelayChange = 0; } aecm->lastDelayDiff = diff; if (aecm->timeForDelayChange > 25) { aecm->knownDelay = WEBRTC_SPL_MAX((int)aecm->filtDelay - 160, 0); } return 0; } static int WebRtcAecm_DelayComp(AecMobile* aecm) { int nSampFar = (int)WebRtc_available_read(aecm->farendBuf); int nSampSndCard, delayNew, nSampAdd; const int maxStuffSamp = 10 * FRAME_LEN; nSampSndCard = aecm->msInSndCardBuf * kSampMsNb * aecm->aecmCore->mult; delayNew = nSampSndCard - nSampFar; if (delayNew > FAR_BUF_LEN - FRAME_LEN * aecm->aecmCore->mult) { // The difference of the buffer sizes is larger than the maximum // allowed known delay. Compensate by stuffing the buffer. nSampAdd = (int)(WEBRTC_SPL_MAX(((nSampSndCard >> 1) - nSampFar), FRAME_LEN)); nSampAdd = WEBRTC_SPL_MIN(nSampAdd, maxStuffSamp); WebRtc_MoveReadPtr(aecm->farendBuf, -nSampAdd); aecm->delayChange = 1; // the delay needs to be updated } return 0; }
8,490
1,602
<filename>modoboa/limits/urls_api.py """Limits API urls.""" from rest_framework import routers from . import viewsets router = routers.SimpleRouter() router.register( r"resources", viewsets.ResourcesViewSet, basename="resources") urlpatterns = router.urls
87
410
#ifndef CARYLL_FONTOPS_OTL_GSUB_MULTI_H #define CARYLL_FONTOPS_OTL_GSUB_MULTI_H #include "common.h" bool consolidate_gsub_multi(otfcc_Font *font, table_OTL *table, otl_Subtable *_subtable, const otfcc_Options *options); bool consolidate_gsub_alternative(otfcc_Font *font, table_OTL *table, otl_Subtable *_subtable, const otfcc_Options *options); #endif
208
777
<gh_stars>100-1000 // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/css/resolver/SharedStyleFinder.h" #include "core/css/RuleFeature.h" #include "core/css/RuleSet.h" #include "core/css/parser/CSSParser.h" #include "core/css/parser/CSSParserContext.h" #include "core/dom/Document.h" #include "core/dom/shadow/ShadowRoot.h" #include "core/dom/shadow/ShadowRootInit.h" #include "core/frame/FrameView.h" #include "core/html/HTMLElement.h" #include "core/testing/DummyPageHolder.h" #include "testing/gtest/include/gtest/gtest.h" #include <memory> namespace blink { class SharedStyleFinderTest : public ::testing::Test { protected: SharedStyleFinderTest() = default; ~SharedStyleFinderTest() override = default; Document& document() { return m_dummyPageHolder->document(); } void setBodyContent(const String& html) { document().body()->setInnerHTML(html); document().view()->updateAllLifecyclePhases(); } ShadowRoot& attachShadow(Element& host) { ShadowRootInit init; init.setMode("open"); ShadowRoot* shadowRoot = host.attachShadow(ScriptState::forMainWorld(document().frame()), init, ASSERT_NO_EXCEPTION); EXPECT_TRUE(shadowRoot); return *shadowRoot; } void addSelector(const String& selector) { StyleRuleBase* newRule = CSSParser::parseRule(CSSParserContext::create(HTMLStandardMode), nullptr, selector + "{color:pink}"); m_ruleSet->addStyleRule(static_cast<StyleRule*>(newRule), RuleHasNoSpecialState); } void finishAddingSelectors() { m_siblingRuleSet = makeRuleSet(m_ruleSet->features().siblingRules()); m_uncommonAttributeRuleSet = makeRuleSet(m_ruleSet->features().uncommonAttributeRules()); } bool matchesUncommonAttributeRuleSet(Element& element) { return matchesRuleSet(element, m_uncommonAttributeRuleSet); } private: void SetUp() override { m_dummyPageHolder = DummyPageHolder::create(IntSize(800, 600)); m_ruleSet = RuleSet::create(); } static RuleSet* makeRuleSet(const HeapVector<RuleFeature>& ruleFeatures) { if (ruleFeatures.isEmpty()) return nullptr; RuleSet* ruleSet = RuleSet::create(); for (auto ruleFeature : ruleFeatures) ruleSet->addRule(ruleFeature.rule, ruleFeature.selectorIndex, RuleHasNoSpecialState); return ruleSet; } bool matchesRuleSet(Element& element, RuleSet* ruleSet) { if (!ruleSet) return false; ElementResolveContext context(element); SharedStyleFinder finder(context, m_ruleSet->features(), m_siblingRuleSet, m_uncommonAttributeRuleSet, document().ensureStyleResolver()); return finder.matchesRuleSet(ruleSet); } std::unique_ptr<DummyPageHolder> m_dummyPageHolder; Persistent<RuleSet> m_ruleSet; Persistent<RuleSet> m_siblingRuleSet; Persistent<RuleSet> m_uncommonAttributeRuleSet; }; // Selectors which only fail matching :hover/:focus/:active/:-webkit-drag are // considered as matching for matchesRuleSet because affectedBy bits need to be // set correctly on ComputedStyle objects, hence ComputedStyle may not be shared // with elements which would not have reached the pseudo classes during // matching. TEST_F(SharedStyleFinderTest, AttributeAffectedByHover) { setBodyContent("<div id=a attr></div><div id=b></div>"); addSelector("[attr]:hover"); finishAddingSelectors(); Element* a = document().getElementById("a"); Element* b = document().getElementById("b"); ASSERT_TRUE(a); ASSERT_TRUE(b); EXPECT_FALSE(a->isHovered()); EXPECT_FALSE(b->isHovered()); EXPECT_TRUE(matchesUncommonAttributeRuleSet(*a)); EXPECT_FALSE(matchesUncommonAttributeRuleSet(*b)); } TEST_F(SharedStyleFinderTest, AttributeAffectedByHoverNegated) { setBodyContent("<div id=a attr></div><div id=b></div>"); addSelector("[attr]:not(:hover)"); finishAddingSelectors(); Element* a = document().getElementById("a"); Element* b = document().getElementById("b"); ASSERT_TRUE(a); ASSERT_TRUE(b); EXPECT_FALSE(a->isHovered()); EXPECT_FALSE(b->isHovered()); EXPECT_TRUE(matchesUncommonAttributeRuleSet(*a)); EXPECT_FALSE(matchesUncommonAttributeRuleSet(*b)); } TEST_F(SharedStyleFinderTest, AttributeAffectedByFocus) { setBodyContent("<div id=a attr></div><div id=b></div>"); addSelector("[attr]:focus"); finishAddingSelectors(); Element* a = document().getElementById("a"); Element* b = document().getElementById("b"); ASSERT_TRUE(a); ASSERT_TRUE(b); EXPECT_FALSE(a->isFocused()); EXPECT_FALSE(b->isFocused()); EXPECT_TRUE(matchesUncommonAttributeRuleSet(*a)); EXPECT_FALSE(matchesUncommonAttributeRuleSet(*b)); } TEST_F(SharedStyleFinderTest, AttributeAffectedByActive) { setBodyContent("<div id=a attr></div><div id=b></div>"); addSelector("[attr]:active"); finishAddingSelectors(); Element* a = document().getElementById("a"); Element* b = document().getElementById("b"); ASSERT_TRUE(a); ASSERT_TRUE(b); EXPECT_FALSE(a->isActive()); EXPECT_FALSE(b->isActive()); EXPECT_TRUE(matchesUncommonAttributeRuleSet(*a)); EXPECT_FALSE(matchesUncommonAttributeRuleSet(*b)); } TEST_F(SharedStyleFinderTest, AttributeAffectedByDrag) { setBodyContent("<div id=a attr></div><div id=b></div>"); addSelector("[attr]:-webkit-drag"); finishAddingSelectors(); Element* a = document().getElementById("a"); Element* b = document().getElementById("b"); ASSERT_TRUE(a); ASSERT_TRUE(b); EXPECT_FALSE(a->isDragged()); EXPECT_FALSE(b->isDragged()); EXPECT_TRUE(matchesUncommonAttributeRuleSet(*a)); EXPECT_FALSE(matchesUncommonAttributeRuleSet(*b)); } TEST_F(SharedStyleFinderTest, SlottedPseudoWithAttribute) { setBodyContent("<div id=host><div id=a></div><div id=b attr></div></div>"); Element* host = document().getElementById("host"); ShadowRoot& root = attachShadow(*host); root.setInnerHTML("<slot></slot>"); document().updateDistribution(); addSelector("::slotted([attr])"); finishAddingSelectors(); Element* a = document().getElementById("a"); Element* b = document().getElementById("b"); EXPECT_TRUE(a->assignedSlot()); EXPECT_TRUE(b->assignedSlot()); EXPECT_FALSE(matchesUncommonAttributeRuleSet(*a)); EXPECT_TRUE(matchesUncommonAttributeRuleSet(*b)); } } // namespace blink
2,372
3,459
/* FCE Ultra - NES/Famicom Emulator * * Copyright notice for this file: * Copyright (C) 2006 CaH4e3 * * 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 * * 700in1 and 400in1 carts * */ #include "mapinc.h" static uint16 cmd, bank; static SFORMAT StateRegs[] = { { &cmd, 2, "CMD" }, { &bank, 2, "BANK" }, { 0 } }; static void Sync(void) { setmirror((cmd & 1) ^ 1); setchr8(0); if (cmd & 2) { if (cmd & 0x100) { setprg16(0x8000, ((cmd & 0xfc) >> 2) | bank); setprg16(0xC000, ((cmd & 0xfc) >> 2) | 7); } else { setprg16(0x8000, ((cmd & 0xfc) >> 2) | (bank & 6)); setprg16(0xC000, ((cmd & 0xfc) >> 2) | ((bank & 6) | 1)); } } else { setprg16(0x8000, ((cmd & 0xfc) >> 2) | bank); setprg16(0xC000, ((cmd & 0xfc) >> 2) | bank); } } static uint16 ass = 0; static DECLFW(UNLN625092WriteCommand) { cmd = A; if (A == 0x80F8) { setprg16(0x8000, ass); setprg16(0xC000, ass); } else { Sync(); } } static DECLFW(UNLN625092WriteBank) { bank = A & 7; Sync(); } static void UNLN625092Power(void) { cmd = 0; bank = 0; Sync(); SetReadHandler(0x8000, 0xFFFF, CartBR); SetWriteHandler(0x8000, 0xBFFF, UNLN625092WriteCommand); SetWriteHandler(0xC000, 0xFFFF, UNLN625092WriteBank); } static void UNLN625092Reset(void) { cmd = 0; bank = 0; ass++; FCEU_printf("%04x\n", ass); } static void StateRestore(int version) { Sync(); } void UNLN625092_Init(CartInfo *info) { info->Reset = UNLN625092Reset; info->Power = UNLN625092Power; GameStateRestore = StateRestore; AddExState(&StateRegs, ~0, 0, 0); }
993