max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
310
<filename>alpha-zero/const.py import torch # GOMOKU SPACE = 0. BLACK = 1. WHITE = 2. SIZE = 8 # MCTS CPUCT = 5 MCTSSIMNUM = 400 HISTORY = 3 TEMPTRIG = 8 # Dirichlet DLEPS = .25 DLALPHA = .03 # Net params IND = HISTORY * 2 + 2 OUTD = SIZE**2 BLOCKS = 10 RES_BLOCK_FILLTERS = 128 # Train params USECUDA = torch.cuda.is_available() EPOCHS = 5 GAMETIMES = 3000 CHECKOUT = 50 EVALNUMS = 20 MINIBATCH = 512 WINRATE = .55 TRAINLEN = 10000 # Optim LR = 0.03 L2 = 0.0001
221
384
from argparse import Namespace import math import time import os import dill as pickle from tqdm import tqdm import torch import torch.nn.functional as F import torch.optim as optim from torchbenchmark.util.torchtext_legacy.field import Field from torchbenchmark.util.torchtext_legacy.data import Dataset from torchbenchmark.util.torchtext_legacy.iterator import BucketIterator from torchbenchmark.util.torchtext_legacy.translation import TranslationDataset from .transformer import Constants from .transformer.Models import Transformer from .transformer.Optim import ScheduledOptim from .train import prepare_dataloaders, cal_performance, patch_src, patch_trg import random import numpy as np from pathlib import Path from ...util.model import BenchmarkModel from torchbenchmark.tasks import NLP torch.manual_seed(1337) random.seed(1337) np.random.seed(1337) torch.backends.cudnn.deterministic = False torch.backends.cudnn.benchmark = False class Model(BenchmarkModel): task = NLP.TRANSLATION optimized_for_inference = True def _create_transformer(self): transformer = Transformer( self.opt.src_vocab_size, self.opt.trg_vocab_size, src_pad_idx=self.opt.src_pad_idx, trg_pad_idx=self.opt.trg_pad_idx, trg_emb_prj_weight_sharing=self.opt.proj_share_weight, emb_src_trg_weight_sharing=self.opt.embs_share_weight, d_k=self.opt.d_k, d_v=self.opt.d_v, d_model=self.opt.d_model, d_word_vec=self.opt.d_word_vec, d_inner=self.opt.d_inner_hid, n_layers=self.opt.n_layers, n_head=self.opt.n_head, dropout=self.opt.dropout).to(self.device) return transformer def _preprocess(self, data_iter): preloaded_data = [] for d in data_iter: src_seq = patch_src(d.src, self.opt.src_pad_idx).to(self.device) trg_seq, gold = map(lambda x: x.to(self.device), patch_trg(d.trg, self.opt.trg_pad_idx)) preloaded_data.append((src_seq, trg_seq, gold)) return preloaded_data # Original batch size 256, hardware platform unknown # Source: https://github.com/jadore801120/attention-is-all-you-need-pytorch/blob/132907dd272e2cc92e3c10e6c4e783a87ff8893d/README.md?plain=1#L83 def __init__(self, device=None, jit=False, train_bs=256, eval_bs=32): super().__init__() self.device = device self.jit = jit root = os.path.join(str(Path(__file__).parent), ".data") self.opt = Namespace(**{ 'batch_size': train_bs, 'eval_batch_size': eval_bs, 'd_inner_hid': 2048, 'd_k': 64, 'd_model': 512, 'd_word_vec': 512, 'd_v': 64, 'data_pkl': f'{root}/m30k_deen_shr.pkl', 'debug': '', 'dropout': 0.1, 'embs_share_weight': False, 'epoch': 1, 'label_smoothing': False, 'log': None, 'n_head': 8, 'n_layers': 6, 'n_warmup_steps': 128, 'cuda': True, 'proj_share_weight': False, 'save_mode': 'best', 'save_model': None, 'script': False, 'train_path': None, 'val_path': None, }) train_data, test_data = prepare_dataloaders(self.opt, self.device) transformer = self._create_transformer() self.eval_model = self._create_transformer() self.eval_model.eval() self.train_data_loader = self._preprocess(train_data) self.eval_data_loader = self._preprocess(test_data) src_seq, trg_seq, gold = self.train_data_loader[0] example_inputs = (src_seq, trg_seq) if self.jit: if hasattr(torch.jit, '_script_pdt'): transformer = torch.jit._script_pdt(transformer, example_inputs = [example_inputs, ]) self.eval_model = torch.jit._script_pdt(self.eval_model, example_inputs = [example_inputs, ]) else: transformer = torch.jit.script(transformer, example_inputs = [example_inputs, ]) self.eval_model = torch.jit.script(self.eval_model, example_inputs = [example_inputs, ]) self.eval_model = torch.jit.optimize_for_inference(self.eval_model) self.module = transformer self.optimizer = ScheduledOptim( optim.Adam(self.module.parameters(), betas=(0.9, 0.98), eps=1e-09), 2.0, self.opt.d_model, self.opt.n_warmup_steps) def get_module(self): for (src_seq, trg_seq, gold) in self.train_data_loader: return self.module, (*(src_seq, trg_seq), ) def eval(self, niter=1): self.module.eval() for _, (src_seq, trg_seq, gold) in zip(range(niter), self.eval_data_loader): self.eval_model(*(src_seq, trg_seq)) def train(self, niter=1): self.module.train() for _, (src_seq, trg_seq, gold) in zip(range(niter), self.train_data_loader): self.optimizer.zero_grad() example_inputs = (src_seq, trg_seq) pred = self.module(*example_inputs) loss, n_correct, n_word = cal_performance( pred, gold, self.opt.trg_pad_idx, smoothing=self.opt.label_smoothing) loss.backward() self.optimizer.step_and_update_lr() if __name__ == '__main__': m = Model(device='cuda', jit=False) module, example_inputs = m.get_module() module(*example_inputs) m.train(niter=1) m.eval(niter=1)
2,694
903
#include "../../../src/corelib/animation/qpropertyanimation_p.h"
25
381
import imp import os try: import cpyext except ImportError: raise ImportError("No module named '_testcapi'") import _pypy_testcapi cfile = '_testcapimodule.c' thisdir = os.path.dirname(__file__) output_dir = _pypy_testcapi.get_hashed_dir(os.path.join(thisdir, cfile)) try: fp, filename, description = imp.find_module('_testcapi', path=[output_dir]) with fp: imp.load_module('_testcapi', fp, filename, description) except ImportError: if os.name == 'nt': # hack around finding compilers on win32 try: import setuptools except ImportError: pass _pypy_testcapi.compile_shared(cfile, '_testcapi', output_dir)
296
515
<filename>Libs/PluginFramework/Testing/org.commontk.eventadmintest/ctkEAScenario3TestSuite.cpp /*============================================================================= Library: CTK Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "ctkEAScenario3TestSuite_p.h" #include <ctkPluginContext.h> #include <service/event/ctkEventConstants.h> #include <service/event/ctkEventAdmin.h> #include <QTest> //---------------------------------------------------------------------------- ctkEAScenario3EventConsumer::ctkEAScenario3EventConsumer( ctkPluginContext* pluginContext, const QStringList topics, int numSyncMsg, int numAsyncMsg) : context(pluginContext), topicsToConsume(topics), asynchMessages(0), synchMessages(0), numSyncMessages(numSyncMsg), numAsyncMessages(numAsyncMsg), error(false), exc("") { } //---------------------------------------------------------------------------- void ctkEAScenario3EventConsumer::runTest() { asynchMessages = 0; synchMessages = 0; /* create the hashtable to put properties in */ ctkDictionary props; /* put service.pid property in hashtable */ props.insert(ctkEventConstants::EVENT_TOPIC, topicsToConsume); /* register the service */ serviceRegistration = context->registerService<ctkEventHandler>(this, props); QVERIFY2(serviceRegistration, "service registration should not be null"); } //---------------------------------------------------------------------------- void ctkEAScenario3EventConsumer::cleanup() { QMutexLocker l(&mutex); try { serviceRegistration.unregister(); } catch (const ctkIllegalStateException&) {} if (error) { throw exc; } QCOMPARE(synchMessages, numSyncMessages); // "Not all synch messages recieved" QCOMPARE(asynchMessages, numAsyncMessages); // "Not all asynch messages recieved" } //---------------------------------------------------------------------------- void ctkEAScenario3EventConsumer::handleEvent(const ctkEvent& event) { QMutexLocker l(&mutex); try { /* try to get the message */ QString message = event.getProperty("Synchronous message").toString(); if (!message.isNull()) { /* its an asyncronous message */ synchMessages++; qDebug() << "received a Synchronous event with message:" << message; } else { message = event.getProperty("Asynchronous message").toString(); if (!message.isNull()) { asynchMessages++; qDebug() << "received an Asynchronus event with message:" << message; } } /* assert that the messages property is not null */ QVERIFY2(!message.isNull(), "Message should not be null in handleEvent()"); /* assert that the messages of syncronous type are not too many */ QVERIFY2(synchMessages < numSyncMessages + 1, "too many synchronous messages"); /* assert that the messsage of the asyncronous type are not too many */ QVERIFY2(asynchMessages < numAsyncMessages + 1, "too many asynchronous messages"); } catch (const ctkRuntimeException& e) { error = true; exc = e; throw e; } catch (...) { error = true; } } //---------------------------------------------------------------------------- void ctkEAScenario3EventPublisher::sendEvents() { for (int i = 0; i < messageTosend; i++) { /* a Hash table to store message in */ ctkDictionary message; /* put some properties into the messages */ message.insert("Synchronous message", i); /* send the message */ qDebug() << "sending a synchronous event with message:" << message << "and the topic:" << topicToSend; eventAdmin->sendEvent(ctkEvent(topicToSend, message)); } thread.quit(); } //---------------------------------------------------------------------------- void ctkEAScenario3EventPublisher::postEvents() { for (int i = 0; i < messageTosend; i++) { /* create the hasht table */ ctkDictionary message; /* create the message */ message.insert("Asynchronous message", i); /* Sends a asynchronous event to the admin */ qDebug() << "sending an Asynchronous event with message:" << message << "and the topic:" << topicToSend; eventAdmin->postEvent(ctkEvent(topicToSend, message)); } thread.quit(); } //---------------------------------------------------------------------------- ctkEAScenario3EventPublisher::ctkEAScenario3EventPublisher(ctkPluginContext* context, const QString& name, int id, int numOfMessage, const QString& topic) : eventAdmin(0), context(context), messageTosend(numOfMessage), topicToSend(topic) { thread.setObjectName(QString("%1-%2").arg(name).arg(id)); moveToThread(&thread); } //---------------------------------------------------------------------------- void ctkEAScenario3EventPublisher::runTest() { /* Claims the reference of the EventAdmin Service */ serviceReference = context->getServiceReference<ctkEventAdmin>(); /* assert that a reference is aquired */ QVERIFY2(serviceReference, "Should be able to get reference to ctkEventAdmin service"); eventAdmin = context->getService<ctkEventAdmin>(serviceReference); QVERIFY2(eventAdmin, "Should be able to get instance to ctkEventAdmin object"); connect(&thread, SIGNAL(started()), SLOT(sendEvents())); thread.start(); /* wait until thread is dead */ thread.wait(); disconnect(&thread, SIGNAL(started()), this, SLOT(sendEvents())); connect(&thread, SIGNAL(started()), SLOT(postEvents())); thread.start(); /* wait until thread is dead */ thread.wait(); QTest::qWait(1000); // allow for delivery } //---------------------------------------------------------------------------- ctkEAScenario3TestSuite::ctkEAScenario3TestSuite(ctkPluginContext* context, long eventPluginId) : pluginContext(context), eventPluginId(eventPluginId) { } //---------------------------------------------------------------------------- void ctkEAScenario3TestSuite::initTestCase() { pluginContext->getPlugin(eventPluginId)->start(); /* create a topic string */ QStringList scenario3_topics1; scenario3_topics1 << "com/acme/timer"; scenario3_topics1 << "com/acme/log"; /* add the event consumer with the correct topics to the test suite */ eventConsumers.push_back(new ctkEAScenario3EventConsumer(pluginContext, scenario3_topics1, 8, 8)); eventPublishers.push_back(new ctkEAScenario3EventPublisher( pluginContext, "Scenario 3 EventPublisher1", 3, 4, "com/acme/timer")); eventPublishers.push_back(new ctkEAScenario3EventPublisher( pluginContext, "Scenario 3 EventPublisher2", 3, 4, "com/acme/log")); } //---------------------------------------------------------------------------- void ctkEAScenario3TestSuite::cleanupTestCase() { foreach(ctkEAScenario3EventConsumer* eventConsumer, eventConsumers) { eventConsumer->cleanup(); } qDeleteAll(eventPublishers); qDeleteAll(eventConsumers); pluginContext->getPlugin(eventPluginId)->stop(); } //---------------------------------------------------------------------------- void ctkEAScenario3TestSuite::testRegisterConsumer() { foreach(ctkEAScenario3EventConsumer* consumer, eventConsumers) { consumer->runTest(); } } //---------------------------------------------------------------------------- void ctkEAScenario3TestSuite::testPublishEvents() { foreach(ctkEAScenario3EventPublisher* publisher, eventPublishers) { publisher->runTest(); } }
2,526
787
<gh_stars>100-1000 // OJ: https://leetcode.com/problems/friend-circles/ // Author: github.com/lzl124631x // Time: O(N^2 * a(N)), where `a` is the inverse function of Ackermann function. O(a(N)) is faster than O(log(N)). // Space: O(N) class UnionFind { private: vector<int> rank; vector<int> id; int count; int find (int i) { if (id[i] == i) return i; return id[i] = find(id[i]); } public: UnionFind(int n) : rank(n, 0), id(n), count(n) { for (int i = 0; i < n; ++i) id[i] = i; } void connect(int i, int j) { int p = find(i), q = find(j); if (p == q) return; if (rank[p] > rank[q]) id[p] = q; else { id[q] = p; if (rank[p] == rank[q]) rank[p]++; } --count; } int getCount() { return count; } }; class Solution { public: int findCircleNum(vector<vector<int>>& M) { int N = M.size(); UnionFind uf(N); for (int i = 0; i < N; ++i) for (int j = i + 1; j < N; ++j) if (M[i][j]) uf.connect(i, j); return uf.getCount(); } };
585
480
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.polardbx.druid.bvt.sql.mysql.create_function; import com.alibaba.polardbx.druid.sql.MysqlTest; import com.alibaba.polardbx.druid.sql.SQLUtils; import com.alibaba.polardbx.druid.sql.ast.SQLStatement; import com.alibaba.polardbx.druid.sql.visitor.SchemaStatVisitor; import com.alibaba.polardbx.druid.util.JdbcConstants; import java.util.List; public class MySql_Create_Function_2 extends MysqlTest { public void test_0() throws Exception { String sql = "CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR\n" + "BEGIN\n" + " DECLARE NAME_FOUND VARCHAR DEFAULT \"\";\n" + "\n" + " SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;\n" + " RETURN NAME_FOUND;\n" + "END;//"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL); SQLStatement stmt = statementList.get(0); assertEquals(1, statementList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.MYSQL); stmt.accept(visitor); assertEquals("CREATE FUNCTION F_TEST (\n" + "\tPID INT\n" + ")\n" + "RETURNS VARCHAR\n" + "BEGIN\n" + "\tDECLARE NAME_FOUND VARCHAR DEFAULT '';\n" + "\tSELECT EMPLOYEE_NAME\n" + "\tINTO NAME_FOUND\n" + "\tFROM TABLE_NAME\n" + "\tWHERE ID = PID;\n" + "\tRETURN NAME_FOUND;\n" + "END;", // SQLUtils.toMySqlString(stmt)); assertEquals("create function F_TEST (\n" + "\tPID INT\n" + ")\n" + "returns VARCHAR\n" + "begin\n" + "\tdeclare NAME_FOUND VARCHAR default '';\n" + "\tselect EMPLOYEE_NAME\n" + "\tinto NAME_FOUND\n" + "\tfrom TABLE_NAME\n" + "\twhere ID = PID;\n" + "\treturn NAME_FOUND;\n" + "end;", // SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(3, visitor.getColumns().size()); assertEquals(2, visitor.getConditions().size()); // Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("City"))); // Assert.assertTrue(visitor.getTables().containsKey(new TableStat.Name("t2"))); // Assert.assertTrue(visitor.getColumns().contains(new Column("t2", "id"))); } }
1,910
443
<filename>migrations/versions/5844fbc9d9e4_add_flakyteststat_double_reruns.py """Add flakyteststat.double_reruns Revision ID: 5844fbc9d9e4 Revises: 18c15<PASSWORD>2a21 Create Date: 2015-06-04 14:20:02.697048 """ # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '18c150792a21' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('flakyteststat', sa.Column('double_reruns', sa.Integer(), nullable=False, server_default='0')) def downgrade(): op.drop_column('flakyteststat', 'double_reruns')
217
1,062
<filename>MailHeaders/Catalina/IMAP/IMAPDownload.h<gh_stars>1000+ // // Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @class NSData, NSError, NSMutableArray, NSProgress; @interface IMAPDownload : NSObject { NSMutableArray *_pendingFetchResults; // 8 = 0x8 unsigned int _uid; // 16 = 0x10 NSProgress *_downloadProgress; // 24 = 0x18 } @property(retain) NSProgress *downloadProgress; // @synthesize downloadProgress=_downloadProgress; @property(readonly, nonatomic) unsigned int uid; // @synthesize uid=_uid; - (void).cxx_destruct; // IMP=0x0000000000010da8 - (void)sortPendingFetchResultsUsingFunction:(CDUnknownFunctionPointerType)arg1 context:(void *)arg2; // IMP=0x0000000000013d36 - (void)removeObjectFromPendingFetchResultsAtIndex:(unsigned long long)arg1; // IMP=0x000000000001347b - (void)addPendingFetchResultsObject:(id)arg1; // IMP=0x0000000000011e4b - (id)objectInPendingFetchResultsAtIndex:(unsigned long long)arg1; // IMP=0x00000000000133eb @property(readonly) unsigned long long countOfPendingFetchResults; - (id)description; // IMP=0x000000000002c79e - (void)addCommandsToPipeline:(id)arg1 withCache:(id)arg2; // IMP=0x000000000002c798 - (void)processResults; // IMP=0x000000000002c792 - (BOOL)handleFetchResult:(id)arg1; // IMP=0x000000000002c78a @property(copy) NSError *error; @property(readonly, copy) NSData *data; @property(readonly, nonatomic) unsigned int bytesFetched; - (id)createCopy; // IMP=0x000000000002c71c - (id)init; // IMP=0x000000000002c64d - (id)initWithUid:(unsigned int)arg1; // IMP=0x0000000000010168 @end
622
1,020
<gh_stars>1000+ package io.spring.core.article; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.util.Arrays; import org.junit.Test; public class ArticleTest { @Test public void should_get_right_slug() { Article article = new Article("a new title", "desc", "body", Arrays.asList("java"), "123"); assertThat(article.getSlug(), is("a-new-title")); } @Test public void should_get_right_slug_with_number_in_title() { Article article = new Article("a new title 2", "desc", "body", Arrays.asList("java"), "123"); assertThat(article.getSlug(), is("a-new-title-2")); } @Test public void should_get_lower_case_slug() { Article article = new Article("A NEW TITLE", "desc", "body", Arrays.asList("java"), "123"); assertThat(article.getSlug(), is("a-new-title")); } @Test public void should_handle_other_language() { Article article = new Article("中文:标题", "desc", "body", Arrays.asList("java"), "123"); assertThat(article.getSlug(), is("中文-标题")); } @Test public void should_handle_commas() { Article article = new Article("what?the.hell,w", "desc", "body", Arrays.asList("java"), "123"); assertThat(article.getSlug(), is("what-the-hell-w")); } }
480
403
package org.camunda.bpm.demo.orderconfirmation.model; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Version; @Entity public class DiscountRuleEntry implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @SuppressWarnings("unused") @Version private Long version; private String name; private int amountMin; private int amountMax; private int discount; public DiscountRuleEntry() { } public DiscountRuleEntry(String name, int amountMin, int amountMax, int discount) { this.name = name; this.amountMin = amountMin; this.amountMax = amountMax; this.discount = discount; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAmountMin() { return amountMin; } public void setAmountMin(int amountMin) { this.amountMin = amountMin; } public int getAmountMax() { return amountMax; } public void setAmountMax(int amountMax) { this.amountMax = amountMax; } public int getDiscount() { return discount; } public void setDiscount(int discount) { this.discount = discount; } @Override public String toString() { return "DiscountRuleEntry [id=" + id + ", name=" + name + ", amountMin=" + amountMin + ", amountMax=" + amountMax + ", discount=" + discount + "]"; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
566
2,288
<reponame>michaelfolkson/lnhw<gh_stars>1000+ /* MIT (BSD) license - see LICENSE file for details */ #include <ccan/crypto/hmac_sha256/hmac_sha256.h> #include <string.h> #define IPAD 0x3636363636363636ULL #define OPAD 0x5C5C5C5C5C5C5C5CULL #define BLOCK_U64S (HMAC_SHA256_BLOCKSIZE / sizeof(uint64_t)) static inline void xor_block(uint64_t block[BLOCK_U64S], uint64_t pad) { size_t i; for (i = 0; i < BLOCK_U64S; i++) block[i] ^= pad; } void hmac_sha256_init(struct hmac_sha256_ctx *ctx, const void *k, size_t ksize) { struct sha256 hashed_key; /* We use k_opad as k_ipad temporarily. */ uint64_t *k_ipad = ctx->k_opad; /* (keys longer than B bytes are first hashed using H) */ if (ksize > HMAC_SHA256_BLOCKSIZE) { sha256(&hashed_key, k, ksize); k = &hashed_key; ksize = sizeof(hashed_key); } /* From RFC2104: * * (1) append zeros to the end of K to create a B byte string * (e.g., if K is of length 20 bytes and B=64, then K will be * appended with 44 zero bytes 0x00) */ memcpy(k_ipad, k, ksize); memset((char *)k_ipad + ksize, 0, HMAC_SHA256_BLOCKSIZE - ksize); /* * (2) XOR (bitwise exclusive-OR) the B byte string computed * in step (1) with ipad */ xor_block(k_ipad, IPAD); /* * We start (4) here, appending text later: * * (3) append the stream of data 'text' to the B byte string resulting * from step (2) * (4) apply H to the stream generated in step (3) */ sha256_init(&ctx->sha); sha256_update(&ctx->sha, k_ipad, HMAC_SHA256_BLOCKSIZE); /* * (5) XOR (bitwise exclusive-OR) the B byte string computed in * step (1) with opad */ xor_block(ctx->k_opad, IPAD^OPAD); } void hmac_sha256_update(struct hmac_sha256_ctx *ctx, const void *p, size_t size) { /* This is the appending-text part of this: * * (3) append the stream of data 'text' to the B byte string resulting * from step (2) * (4) apply H to the stream generated in step (3) */ sha256_update(&ctx->sha, p, size); } void hmac_sha256_done(struct hmac_sha256_ctx *ctx, struct hmac_sha256 *hmac) { /* (4) apply H to the stream generated in step (3) */ sha256_done(&ctx->sha, &hmac->sha); /* * (6) append the H result from step (4) to the B byte string * resulting from step (5) * (7) apply H to the stream generated in step (6) and output * the result */ sha256_init(&ctx->sha); sha256_update(&ctx->sha, ctx->k_opad, sizeof(ctx->k_opad)); sha256_update(&ctx->sha, &hmac->sha, sizeof(hmac->sha)); sha256_done(&ctx->sha, &hmac->sha); } #if 1 void hmac_sha256(struct hmac_sha256 *hmac, const void *k, size_t ksize, const void *d, size_t dsize) { struct hmac_sha256_ctx ctx; hmac_sha256_init(&ctx, k, ksize); hmac_sha256_update(&ctx, d, dsize); hmac_sha256_done(&ctx, hmac); } #else /* Direct mapping from MD5 example in RFC2104 */ void hmac_sha256(struct hmac_sha256 *hmac, const void *key, size_t key_len, const void *text, size_t text_len) { struct sha256_ctx context; unsigned char k_ipad[65]; /* inner padding - * key XORd with ipad */ unsigned char k_opad[65]; /* outer padding - * key XORd with opad *//* start out by storing key in pads */ unsigned char tk[32]; int i; /* if key is longer than 64 bytes reset it to key=MD5(key) */ if (key_len > 64) { struct sha256_ctx tctx; sha256_init(&tctx); sha256_update(&tctx, key, key_len); sha256_done(&tctx, tk); key = tk; key_len = 32; } bzero( k_ipad, sizeof k_ipad); bzero( k_opad, sizeof k_opad); bcopy( key, k_ipad, key_len); bcopy( key, k_opad, key_len); /* XOR key with ipad and opad values */ for (i=0; i<64; i++) { k_ipad[i] ^= 0x36; k_opad[i] ^= 0x5c; } /* * perform inner MD5 */ sha256_init(&context); /* init context for 1st * pass */ sha256_update(&context, k_ipad, 64); /* start with inner pad */ sha256_update(&context, text, text_len); /* then text of datagram */ sha256_done(&context, &hmac->sha); /* finish up 1st pass */ /* * perform outer MD5 */ sha256_init(&context); /* init context for 2nd * pass */ sha256_update(&context, k_opad, 64); /* start with outer pad */ sha256_update(&context, &hmac->sha, 32); /* then results of 1st * hash */ sha256_done(&context, &hmac->sha); /* finish up 2nd pass */ } #endif
2,398
6,098
<filename>h2o-docs/src/booklets/v2_2015/source/Python_Vignette_code_examples/python_descriptive_stats_single_column.py df4["A"].mean() # [nan] df4["A"].mean(na_rm=True) # [2.0]
82
660
/* * Copyright (c) 2018-2019, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ //! //! \file cm_command_buffer.cpp //! \brief Contains Class CmCommandBuffer definitions //! #include "cm_command_buffer.h" #include "cm_ish.h" #include "cm_ssh.h" #include "cm_media_state.h" #include "cm_thread_space_rt.h" #include "cm_mem.h" #include "cm_kernel_ex.h" #include "cm_group_space.h" #include "mhw_render_g12_X.h" #include "mhw_render_g11_X.h" #include "mhw_mi_g12_X.h" #include "mhw_state_heap_hwcmd_g9_X.h" #include "mos_solo_generic.h" #include "mhw_mmio_g9.h" #include "cm_hal_g12.h" CmCommandBuffer::CmCommandBuffer(CM_HAL_STATE *cmhal): m_cmhal(cmhal), m_osInterface(nullptr), m_miInterface(nullptr), m_hwRender(nullptr), m_ssh(nullptr), m_origRemain(0) { MOS_ZeroMemory(&m_cmdBuf, sizeof(m_cmdBuf)); MOS_ZeroMemory(m_masks, sizeof(m_masks)); } CmCommandBuffer::~CmCommandBuffer() { if (m_ssh) { MOS_Delete(m_ssh); } } MOS_STATUS CmCommandBuffer::Initialize() { if (m_cmhal == nullptr) { return MOS_STATUS_NULL_POINTER; } m_osInterface = m_cmhal->osInterface; m_miInterface = m_cmhal->renderHal->pMhwMiInterface; m_hwRender = m_cmhal->renderHal->pMhwRenderInterface; if (m_osInterface == nullptr) { return MOS_STATUS_NULL_POINTER; } CM_CHK_MOSSTATUS_RETURN(m_osInterface->pfnGetCommandBuffer(m_osInterface, &m_cmdBuf, 0)); m_cmdBuf.Attributes.bIsMdfLoad = true; m_origRemain = m_cmdBuf.iRemaining; return MOS_STATUS_SUCCESS; } CmSSH* CmCommandBuffer::GetSSH() { if (m_ssh != nullptr) { return m_ssh; } m_ssh = MOS_New(CmSSH, m_cmhal, &m_cmdBuf); return m_ssh; } MOS_STATUS CmCommandBuffer::AddFlushCacheAndSyncTask(bool isRead, bool rtCache, MOS_RESOURCE *syncBuffer) { MHW_PIPE_CONTROL_PARAMS pipeCtlParams; MOS_ZeroMemory(&pipeCtlParams, sizeof(pipeCtlParams)); pipeCtlParams.presDest = syncBuffer; pipeCtlParams.bFlushRenderTargetCache = rtCache; pipeCtlParams.dwFlushMode = isRead ? MHW_FLUSH_READ_CACHE : MHW_FLUSH_WRITE_CACHE; pipeCtlParams.dwPostSyncOp = MHW_FLUSH_NOWRITE; return m_miInterface->AddPipeControl(&m_cmdBuf, nullptr, &pipeCtlParams); } MOS_STATUS CmCommandBuffer::AddReadTimeStamp(MOS_RESOURCE *resource, uint32_t offset, bool isRead) { MHW_PIPE_CONTROL_PARAMS pipeCtlParams; MOS_ZeroMemory(&pipeCtlParams, sizeof(pipeCtlParams)); pipeCtlParams.bFlushRenderTargetCache = true; pipeCtlParams.presDest = resource; pipeCtlParams.dwResourceOffset = offset; pipeCtlParams.dwPostSyncOp = MHW_FLUSH_WRITE_TIMESTAMP_REG; pipeCtlParams.dwFlushMode = isRead ? MHW_FLUSH_READ_CACHE : MHW_FLUSH_WRITE_CACHE; return m_miInterface->AddPipeControl(&m_cmdBuf, nullptr, &pipeCtlParams); } MOS_STATUS CmCommandBuffer::AddL3CacheConfig(L3ConfigRegisterValues *l3Values) { if (m_cmhal->platform.eRenderCoreFamily <= IGFX_GEN10_CORE) //gen10- { MHW_RENDER_ENGINE_L3_CACHE_SETTINGS l3CacheSettting = {}; if (l3Values->config_register3) { l3CacheSettting.dwCntlReg = l3Values->config_register3; } else { l3CacheSettting.dwCntlReg = 0x60000060; } CM_CHK_MOSSTATUS_RETURN(m_hwRender->EnableL3Caching(&l3CacheSettting)); return m_hwRender->SetL3Cache(&m_cmdBuf); } else if (m_cmhal->platform.eRenderCoreFamily == IGFX_GEN11_CORE) { MHW_RENDER_ENGINE_L3_CACHE_SETTINGS_G11 l3CacheSettting = {}; l3CacheSettting.dwTcCntlReg = l3Values->config_register1; l3CacheSettting.dwCntlReg = (l3Values->config_register0 == 0)?0xA0000420:l3Values->config_register0; CM_CHK_MOSSTATUS_RETURN(m_hwRender->EnableL3Caching(&l3CacheSettting)); return m_hwRender->SetL3Cache(&m_cmdBuf); } else //gen12 { MHW_RENDER_ENGINE_L3_CACHE_SETTINGS_G12 l3CacheSettting = {}; l3CacheSettting.dwAllocReg = (l3Values->config_register0 == 0)? m_cmhal->cmHalInterface->m_l3Plane[0].config_register0 :l3Values->config_register0; l3CacheSettting.dwTcCntlReg = (l3Values->config_register1 == 0)? m_cmhal->cmHalInterface->m_l3Plane[0].config_register1 :l3Values->config_register1; CM_CHK_MOSSTATUS_RETURN(m_hwRender->EnableL3Caching(&l3CacheSettting)); return m_hwRender->SetL3Cache(&m_cmdBuf); } } MOS_STATUS CmCommandBuffer::AddPipelineSelect(bool gpgpu) { return m_hwRender->AddPipelineSelectCmd(&m_cmdBuf, gpgpu); } MOS_STATUS CmCommandBuffer::AddStateBaseAddress(CmISH *ish, CmMediaState *mediaState) { MHW_STATE_BASE_ADDR_PARAMS stateBaseAddressParams; MOS_ZeroMemory(&stateBaseAddressParams, sizeof(stateBaseAddressParams)); MOS_RESOURCE *gshResource = mediaState->GetHeapResource(); uint32_t gshSize = mediaState->GetHeapSize(); MOS_RESOURCE *ishResource = ish->GetResource(); uint32_t ishSize = ish->GetSize(); stateBaseAddressParams.presGeneralState = gshResource; stateBaseAddressParams.dwGeneralStateSize = gshSize; stateBaseAddressParams.presDynamicState = gshResource; stateBaseAddressParams.dwDynamicStateSize = gshSize; stateBaseAddressParams.bDynamicStateRenderTarget = false; stateBaseAddressParams.presIndirectObjectBuffer = gshResource; stateBaseAddressParams.dwIndirectObjectBufferSize = gshSize; stateBaseAddressParams.presInstructionBuffer = ishResource; stateBaseAddressParams.dwInstructionBufferSize = ishSize; uint32_t heapMocs = m_osInterface->pfnCachePolicyGetMemoryObject(MOS_CM_RESOURCE_USAGE_SurfaceState, m_osInterface->pfnGetGmmClientContext(m_osInterface)).DwordValue; stateBaseAddressParams.mocs4DynamicState = heapMocs; stateBaseAddressParams.mocs4GeneralState = heapMocs; stateBaseAddressParams.mocs4InstructionCache = heapMocs; stateBaseAddressParams.mocs4SurfaceState = heapMocs; stateBaseAddressParams.mocs4IndirectObjectBuffer = heapMocs; stateBaseAddressParams.mocs4StatelessDataport = heapMocs; return m_hwRender->AddStateBaseAddrCmd(&m_cmdBuf, &stateBaseAddressParams); } MOS_STATUS CmCommandBuffer::AddMediaVFE(CmMediaState *mediaState, bool fusedEuDispatch, CMRT_UMD::CmThreadSpaceRT **threadSpaces, uint32_t count) { MHW_VFE_PARAMS vfeParams = {}; MHW_VFE_PARAMS_G12 vfeParamsG12 = {}; MHW_VFE_PARAMS *param = nullptr; if (m_cmhal->platform.eRenderCoreFamily <= IGFX_GEN11_CORE) { param = &vfeParams; } else { param = &vfeParamsG12; vfeParamsG12.bFusedEuDispatch = fusedEuDispatch; } MHW_RENDER_ENGINE_CAPS *hwCaps = m_hwRender->GetHwCaps(); param->dwDebugCounterControl = MEDIASTATE_DEBUG_COUNTER_FREE_RUNNING; param->dwNumberofURBEntries = 32; param->dwMaximumNumberofThreads = hwCaps->dwMaxThreads; param->dwCURBEAllocationSize = MOS_ROUNDUP_SHIFT(mediaState->GetCurbeSize(), 5) << 5; param->dwURBEntryAllocationSize = 1; param->dwPerThreadScratchSpace = 0; param->dwScratchSpaceBasePointer = mediaState->GetScratchSpaceOffset(); uint32_t scratchSizePerThread = mediaState->GetScratchSizePerThread(); if (scratchSizePerThread > 0) { scratchSizePerThread = scratchSizePerThread >> 9; int remain = scratchSizePerThread % 2; scratchSizePerThread = scratchSizePerThread / 2; int sizeParam = 0; while ((scratchSizePerThread / 2) && !remain) { sizeParam++; remain = scratchSizePerThread % 2; scratchSizePerThread = scratchSizePerThread / 2; } param->dwPerThreadScratchSpace = sizeParam; } if (threadSpaces != nullptr && m_cmhal->cmHalInterface->IsScoreboardParamNeeded()) { bool globalSpace = (count == 0); uint32_t spaceCount = globalSpace ? 1 : count; uint8_t map[256] = {0}; // x*4+y as index, order in the global dependency vector as value (starting from 1) uint8_t index = 1; for (uint32_t i = 0; i < spaceCount; i ++) { if (threadSpaces[i] == nullptr) { continue; } CM_HAL_DEPENDENCY *dependency; threadSpaces[i]->GetDependency(dependency); for (uint32_t j = 0; j < dependency->count; j ++) { uint8_t depVec = (uint8_t)(dependency->deltaX[j]) * 16 + (uint8_t)(dependency->deltaY[j]); if (map[depVec] == 0) { param->Scoreboard.ScoreboardDelta[index - 1].x = (uint8_t)(dependency->deltaX[j]); param->Scoreboard.ScoreboardDelta[index - 1].y = (uint8_t)(dependency->deltaY[j]); map[depVec] = index ++; } m_masks[i] |= 1 << (map[depVec] - 1); } } if (globalSpace) { CmSafeMemSet(m_masks, m_masks[0], sizeof(m_masks)); } param->Scoreboard.ScoreboardEnable = 1; param->Scoreboard.ScoreboardMask = (1 << (index-1)) - 1; param->Scoreboard.ScoreboardType = (param->Scoreboard.ScoreboardMask != 0); } else { param->Scoreboard.ScoreboardEnable = 1; } return m_hwRender->AddMediaVfeCmd(&m_cmdBuf, param); } MOS_STATUS CmCommandBuffer::AddCurbeLoad(CmMediaState *mediaState) { MHW_CURBE_LOAD_PARAMS curbeLoadParams; MOS_ZeroMemory(&curbeLoadParams, sizeof(curbeLoadParams)); uint32_t curbeSize = mediaState->GetCurbeSize(); if (curbeSize > 0) { curbeLoadParams.pKernelState = nullptr; curbeLoadParams.bOldInterface = false; curbeLoadParams.dwCURBETotalDataLength = curbeSize; curbeLoadParams.dwCURBEDataStartAddress = mediaState->GetCurbeOffset(); return m_hwRender->AddMediaCurbeLoadCmd(&m_cmdBuf, &curbeLoadParams); } return MOS_STATUS_SUCCESS; } MOS_STATUS CmCommandBuffer::AddMediaIDLoad(CmMediaState *mediaState) { MHW_ID_LOAD_PARAMS idLoadParams; MOS_ZeroMemory(&idLoadParams, sizeof(idLoadParams)); idLoadParams.dwInterfaceDescriptorStartOffset = mediaState->GetMediaIDOffset(); idLoadParams.dwInterfaceDescriptorLength = mediaState->GetMediaIDSize(); return m_hwRender->AddMediaIDLoadCmd(&m_cmdBuf, &idLoadParams); } MOS_STATUS CmCommandBuffer::AddSyncBetweenKernels() { MHW_PIPE_CONTROL_PARAMS pipeCtlParams; MOS_ZeroMemory(&pipeCtlParams, sizeof(pipeCtlParams)); pipeCtlParams.bInvalidateTextureCache = true; pipeCtlParams.bFlushRenderTargetCache = true; pipeCtlParams.dwFlushMode = MHW_FLUSH_CUSTOM; pipeCtlParams.dwPostSyncOp = MHW_FLUSH_NOWRITE; return m_miInterface->AddPipeControl(&m_cmdBuf, nullptr, &pipeCtlParams); } MOS_STATUS CmCommandBuffer::AddMediaObjectWalker(CMRT_UMD::CmThreadSpaceRT *threadSpace, uint32_t mediaID) { MHW_WALKER_PARAMS mediaWalkerParams; MOS_ZeroMemory(&mediaWalkerParams, sizeof(mediaWalkerParams)); mediaWalkerParams.CmWalkerEnable = true; mediaWalkerParams.InterfaceDescriptorOffset = mediaID; mediaWalkerParams.InlineDataLength = 0; mediaWalkerParams.pInlineData = nullptr; uint32_t colorCountM1 = 0; CM_MW_GROUP_SELECT groupSelect = CM_MW_GROUP_NONE; CM_WALKING_PATTERN walkPattern = CM_WALK_DEFAULT; CM_DEPENDENCY_PATTERN dependencyPattern = CM_NONE_DEPENDENCY; uint32_t threadSpaceWidth = 1; uint32_t threadSpaceHeight = 1; if (threadSpace != nullptr) { threadSpace->GetColorCountMinusOne(colorCountM1); threadSpace->GetMediaWalkerGroupSelect(groupSelect); threadSpace->GetWalkingPattern(walkPattern); threadSpace->GetDependencyPatternType(dependencyPattern); threadSpace->GetThreadSpaceSize(threadSpaceWidth, threadSpaceHeight); } mediaWalkerParams.ColorCountMinusOne = colorCountM1; mediaWalkerParams.GroupIdLoopSelect = (uint32_t)groupSelect; uint32_t threadCount = threadSpaceWidth * threadSpaceHeight; switch (dependencyPattern) { case CM_NONE_DEPENDENCY: break; case CM_HORIZONTAL_WAVE: walkPattern = CM_WALK_HORIZONTAL; break; case CM_VERTICAL_WAVE: walkPattern = CM_WALK_VERTICAL; break; case CM_WAVEFRONT: walkPattern = CM_WALK_WAVEFRONT; break; case CM_WAVEFRONT26: walkPattern = CM_WALK_WAVEFRONT26; break; case CM_WAVEFRONT26X: if (threadSpaceWidth > 1) { walkPattern = CM_WALK_WAVEFRONT26X; } else { walkPattern = CM_WALK_DEFAULT; } break; case CM_WAVEFRONT26ZIG: if (threadSpaceWidth > 2) { walkPattern = CM_WALK_WAVEFRONT26ZIG; } else { walkPattern = CM_WALK_DEFAULT; } break; default: CM_ASSERTMESSAGE("Error: Invalid walking pattern."); walkPattern = CM_WALK_DEFAULT; break; } mediaWalkerParams.BlockResolution.x = threadSpaceWidth; mediaWalkerParams.BlockResolution.y = threadSpaceHeight; mediaWalkerParams.LocalStart.x = 0; mediaWalkerParams.LocalStart.y = 0; mediaWalkerParams.LocalEnd.x = 0; mediaWalkerParams.LocalEnd.y = 0; mediaWalkerParams.dwGlobalLoopExecCount = 1; mediaWalkerParams.MidLoopUnitX = 0; mediaWalkerParams.MidLoopUnitY = 0; mediaWalkerParams.MiddleLoopExtraSteps = 0; uint32_t adjHeight = ((threadSpaceHeight + 1) >> 1) << 1; uint32_t adjWidth = ((threadSpaceWidth + 1) >> 1) << 1; uint32_t maxThreadWidth = m_cmhal->cmHalInterface->GetMediaWalkerMaxThreadWidth(); switch (walkPattern) { case CM_WALK_DEFAULT: case CM_WALK_HORIZONTAL: if (threadSpaceWidth == threadCount && threadSpaceHeight == 1) { mediaWalkerParams.BlockResolution.x = MOS_MIN(threadCount, maxThreadWidth); mediaWalkerParams.BlockResolution.y = 1 + threadCount / maxThreadWidth; } mediaWalkerParams.dwLocalLoopExecCount = mediaWalkerParams.BlockResolution.y - 1; mediaWalkerParams.LocalOutLoopStride.x = 0; mediaWalkerParams.LocalOutLoopStride.y = 1; mediaWalkerParams.LocalInnerLoopUnit.x = 1; mediaWalkerParams.LocalInnerLoopUnit.y = 0; mediaWalkerParams.LocalEnd.x = mediaWalkerParams.BlockResolution.x - 1; break; case CM_WALK_WAVEFRONT: mediaWalkerParams.dwLocalLoopExecCount = threadSpaceWidth + (threadSpaceHeight - 1) * 1 - 1; mediaWalkerParams.LocalOutLoopStride.x = 1; mediaWalkerParams.LocalOutLoopStride.y = 0; mediaWalkerParams.LocalInnerLoopUnit.x = 0xFFFF; // -1 in uint32_t:16 mediaWalkerParams.LocalInnerLoopUnit.y = 1; break; case CM_WALK_WAVEFRONT26: mediaWalkerParams.dwLocalLoopExecCount = threadSpaceWidth + (threadSpaceHeight - 1) * 2 - 1; mediaWalkerParams.LocalOutLoopStride.x = 1; mediaWalkerParams.LocalOutLoopStride.y = 0; mediaWalkerParams.LocalInnerLoopUnit.x = 0xFFFE; // -2 in uint32_t:16 mediaWalkerParams.LocalInnerLoopUnit.y = 1; break; case CM_WALK_WAVEFRONT26X: case CM_WALK_WAVEFRONT26XALT: mediaWalkerParams.dwLocalLoopExecCount = 0x7ff; mediaWalkerParams.dwGlobalLoopExecCount = 0; mediaWalkerParams.LocalOutLoopStride.x = 1; mediaWalkerParams.LocalOutLoopStride.y = 0; mediaWalkerParams.LocalInnerLoopUnit.x = 0xFFFE; // -2 in uint32_t:16 mediaWalkerParams.LocalInnerLoopUnit.y = 2; mediaWalkerParams.MiddleLoopExtraSteps = 1; mediaWalkerParams.MidLoopUnitX = 0; mediaWalkerParams.MidLoopUnitY = 1; break; case CM_WALK_WAVEFRONT26ZIG: mediaWalkerParams.dwLocalLoopExecCount = 1; mediaWalkerParams.dwGlobalLoopExecCount = (adjHeight / 2 - 1) * 2 + (adjWidth / 2) - 1; mediaWalkerParams.LocalOutLoopStride.x = 0; mediaWalkerParams.LocalOutLoopStride.y = 1; mediaWalkerParams.LocalInnerLoopUnit.x = 1; mediaWalkerParams.LocalInnerLoopUnit.y = 0; mediaWalkerParams.BlockResolution.x = 2; mediaWalkerParams.BlockResolution.y = 2; mediaWalkerParams.LocalEnd.x = mediaWalkerParams.BlockResolution.x - 1; break; case CM_WALK_VERTICAL: mediaWalkerParams.dwLocalLoopExecCount = mediaWalkerParams.BlockResolution.x - 1; mediaWalkerParams.LocalOutLoopStride.x = 1; mediaWalkerParams.LocalOutLoopStride.y = 0; mediaWalkerParams.LocalInnerLoopUnit.x = 0; mediaWalkerParams.LocalInnerLoopUnit.y = 1; mediaWalkerParams.LocalEnd.y = mediaWalkerParams.BlockResolution.y - 1; break; case CM_WALK_WAVEFRONT45D: mediaWalkerParams.dwLocalLoopExecCount = 0x7ff; mediaWalkerParams.dwGlobalLoopExecCount = 0x7ff; mediaWalkerParams.LocalStart.x = threadSpaceWidth; mediaWalkerParams.LocalOutLoopStride.x = 1; mediaWalkerParams.LocalOutLoopStride.y = 0; mediaWalkerParams.LocalInnerLoopUnit.x = 0xFFFF; // -1 in uint32_t:16 mediaWalkerParams.LocalInnerLoopUnit.y = 1; break; case CM_WALK_WAVEFRONT45XD_2: mediaWalkerParams.dwLocalLoopExecCount = 0x7ff; mediaWalkerParams.dwGlobalLoopExecCount = 0x7ff; // Local mediaWalkerParams.LocalStart.x = threadSpaceWidth; mediaWalkerParams.LocalOutLoopStride.x = 1; mediaWalkerParams.LocalOutLoopStride.y = 0; mediaWalkerParams.LocalInnerLoopUnit.x = 0xFFFF; // -1 in uint32_t:16 mediaWalkerParams.LocalInnerLoopUnit.y = 2; // Mid mediaWalkerParams.MiddleLoopExtraSteps = 1; mediaWalkerParams.MidLoopUnitX = 0; mediaWalkerParams.MidLoopUnitY = 1; break; case CM_WALK_WAVEFRONT26D: mediaWalkerParams.dwLocalLoopExecCount = 0x7ff; mediaWalkerParams.dwGlobalLoopExecCount = 0x7ff; mediaWalkerParams.LocalStart.x = threadSpaceWidth; mediaWalkerParams.LocalOutLoopStride.x = 1; mediaWalkerParams.LocalOutLoopStride.y = 0; mediaWalkerParams.LocalInnerLoopUnit.x = 0xFFFE; // -2 in uint32_t:16 mediaWalkerParams.LocalInnerLoopUnit.y = 1; break; case CM_WALK_WAVEFRONT26XD: mediaWalkerParams.dwLocalLoopExecCount = 0x7ff; mediaWalkerParams.dwGlobalLoopExecCount = 0x7ff; // Local mediaWalkerParams.LocalStart.x = threadSpaceWidth; mediaWalkerParams.LocalOutLoopStride.x = 1; mediaWalkerParams.LocalOutLoopStride.y = 0; mediaWalkerParams.LocalInnerLoopUnit.x = 0xFFFE; // -2 in uint32_t:16 mediaWalkerParams.LocalInnerLoopUnit.y = 2; // Mid mediaWalkerParams.MiddleLoopExtraSteps = 1; mediaWalkerParams.MidLoopUnitX = 0; mediaWalkerParams.MidLoopUnitY = 1; break; default: mediaWalkerParams.dwLocalLoopExecCount = MOS_MIN(threadCount, 0x3FF); mediaWalkerParams.LocalOutLoopStride.x = 0; mediaWalkerParams.LocalOutLoopStride.y = 1; mediaWalkerParams.LocalInnerLoopUnit.x = 1; mediaWalkerParams.LocalInnerLoopUnit.y = 0; break; } //Global loop parameters: execution count, resolution and strides //Since no global loop, global resolution equals block resolution. mediaWalkerParams.GlobalStart.x = 0; mediaWalkerParams.GlobalStart.y = 0; mediaWalkerParams.GlobalOutlerLoopStride.y = 0; if (walkPattern == CM_WALK_WAVEFRONT26ZIG) { mediaWalkerParams.GlobalResolution.x = threadSpaceWidth; mediaWalkerParams.GlobalResolution.y = threadSpaceHeight; mediaWalkerParams.GlobalOutlerLoopStride.x = 2; mediaWalkerParams.GlobalInnerLoopUnit.x = 0xFFFC; mediaWalkerParams.GlobalInnerLoopUnit.y = 2; } else { mediaWalkerParams.GlobalResolution.x = mediaWalkerParams.BlockResolution.x; mediaWalkerParams.GlobalResolution.y = mediaWalkerParams.BlockResolution.y; mediaWalkerParams.GlobalOutlerLoopStride.x = mediaWalkerParams.GlobalResolution.x; mediaWalkerParams.GlobalInnerLoopUnit.x = 0; mediaWalkerParams.GlobalInnerLoopUnit.y = mediaWalkerParams.GlobalResolution.y; } mediaWalkerParams.UseScoreboard = 1; mediaWalkerParams.ScoreboardMask = m_masks[mediaID]; return m_hwRender->AddMediaObjectWalkerCmd(&m_cmdBuf, &mediaWalkerParams); } MOS_STATUS CmCommandBuffer::AddDummyVFE() { // Add PipeControl to invalidate ISP and MediaState to avoid PageFault issue MHW_PIPE_CONTROL_PARAMS pipeControlParams; MOS_ZeroMemory(&pipeControlParams, sizeof(pipeControlParams)); pipeControlParams.dwFlushMode = MHW_FLUSH_WRITE_CACHE; pipeControlParams.bGenericMediaStateClear = true; pipeControlParams.bIndirectStatePointersDisable = true; pipeControlParams.bDisableCSStall = false; CM_CHK_MOSSTATUS_RETURN(m_miInterface->AddPipeControl(&m_cmdBuf, nullptr, &pipeControlParams)); if (MEDIA_IS_WA(m_cmhal->renderHal->pWaTable, WaSendDummyVFEafterPipelineSelect)) { MHW_VFE_PARAMS vfeStateParams; MOS_ZeroMemory(&vfeStateParams, sizeof(vfeStateParams)); vfeStateParams.dwNumberofURBEntries = 1; CM_CHK_MOSSTATUS_RETURN(m_hwRender->AddMediaVfeCmd(&m_cmdBuf, &vfeStateParams)); } return MOS_STATUS_SUCCESS; } MOS_STATUS CmCommandBuffer::AddBatchBufferEnd() { return m_miInterface->AddMiBatchBufferEnd(&m_cmdBuf, nullptr); } MOS_STATUS CmCommandBuffer::AddMMCProlog() { uint64_t auxTableBaseAddr = 0; auxTableBaseAddr = m_cmhal->osInterface->pfnGetAuxTableBaseAddr(m_cmhal->osInterface); if (auxTableBaseAddr) { MHW_MI_LOAD_REGISTER_IMM_PARAMS lriParams; MOS_ZeroMemory(&lriParams, sizeof(MHW_MI_LOAD_REGISTER_IMM_PARAMS)); lriParams.dwRegister = MhwMiInterfaceG12::m_mmioRcsAuxTableBaseLow; lriParams.dwData = (auxTableBaseAddr & 0xffffffff); CM_CHK_MOSSTATUS_RETURN(m_miInterface->AddMiLoadRegisterImmCmd(&m_cmdBuf, &lriParams)); lriParams.dwRegister = MhwMiInterfaceG12::m_mmioRcsAuxTableBaseHigh; lriParams.dwData = ((auxTableBaseAddr >> 32) & 0xffffffff); CM_CHK_MOSSTATUS_RETURN(m_miInterface->AddMiLoadRegisterImmCmd(&m_cmdBuf, &lriParams)); } return MOS_STATUS_SUCCESS; } MOS_STATUS CmCommandBuffer::AddProtectedProlog() { return m_miInterface->AddProtectedProlog(&m_cmdBuf); } void CmCommandBuffer::ReturnUnusedBuffer() { m_osInterface->pfnReturnCommandBuffer(m_osInterface, &m_cmdBuf, 0); } void CmCommandBuffer::ReturnWholeBuffer() { int tmp = m_origRemain - m_cmdBuf.iRemaining; m_cmdBuf.iRemaining = m_origRemain; m_cmdBuf.iOffset -= tmp; m_cmdBuf.pCmdPtr = m_cmdBuf.pCmdBase + m_cmdBuf.iOffset/sizeof(uint32_t); m_osInterface->pfnReturnCommandBuffer(m_osInterface, &m_cmdBuf, 0); } MOS_STATUS CmCommandBuffer::Submit() { return m_osInterface->pfnSubmitCommandBuffer(m_osInterface, &m_cmdBuf, m_cmhal->nullHwRenderCm); } MOS_STATUS CmCommandBuffer::AddPreemptionConfig(bool isGpgpu) { bool csrEnable = !m_cmhal->midThreadPreemptionDisabled; if (MEDIA_IS_SKU(m_cmhal->skuTable, FtrPerCtxtPreemptionGranularityControl)) { MHW_MI_LOAD_REGISTER_IMM_PARAMS loadRegImm; MOS_ZeroMemory(&loadRegImm, sizeof(MHW_MI_LOAD_REGISTER_IMM_PARAMS)); loadRegImm.dwRegister = MHW_RENDER_ENGINE_PREEMPTION_CONTROL_OFFSET; // Same reg offset and value for gpgpu pipe and media pipe if (isGpgpu) { if (MEDIA_IS_SKU(m_cmhal->skuTable, FtrGpGpuMidThreadLevelPreempt)) { if (csrEnable) { loadRegImm.dwData = MHW_RENDER_ENGINE_MID_THREAD_PREEMPT_VALUE; } else { loadRegImm.dwData = MHW_RENDER_ENGINE_THREAD_GROUP_PREEMPT_VALUE; } } else if (MEDIA_IS_SKU(m_cmhal->skuTable, FtrGpGpuThreadGroupLevelPreempt)) { loadRegImm.dwData = MHW_RENDER_ENGINE_THREAD_GROUP_PREEMPT_VALUE; } else if (MEDIA_IS_SKU(m_cmhal->skuTable, FtrGpGpuMidBatchPreempt)) { loadRegImm.dwData = MHW_RENDER_ENGINE_MID_BATCH_PREEMPT_VALUE; } else { // if hit this branch then platform does not support any media preemption in render engine. Still program the register to avoid GPU hang loadRegImm.dwData = MHW_RENDER_ENGINE_MID_BATCH_PREEMPT_VALUE; } } else { if ( MEDIA_IS_SKU(m_cmhal->skuTable, FtrMediaMidThreadLevelPreempt)) { loadRegImm.dwData = MHW_RENDER_ENGINE_MID_THREAD_PREEMPT_VALUE; } else if ( MEDIA_IS_SKU(m_cmhal->skuTable, FtrMediaThreadGroupLevelPreempt) ) { loadRegImm.dwData = MHW_RENDER_ENGINE_THREAD_GROUP_PREEMPT_VALUE; } else if ( MEDIA_IS_SKU(m_cmhal->skuTable, FtrMediaMidBatchPreempt)) { loadRegImm.dwData = MHW_RENDER_ENGINE_MID_BATCH_PREEMPT_VALUE; } else { // if hit this branch then platform does not support any media preemption in render engine. Still program the register to avoid GPU hang loadRegImm.dwData = MHW_RENDER_ENGINE_MID_BATCH_PREEMPT_VALUE; } } m_cmdBuf.Attributes.bMediaPreemptionEnabled = m_hwRender->IsPreemptionEnabled(); CM_CHK_MOSSTATUS_RETURN(m_miInterface->AddMiLoadRegisterImmCmd(&m_cmdBuf, &loadRegImm)); } return MOS_STATUS_SUCCESS; } MOS_STATUS CmCommandBuffer::AddSipState(uint32_t sipKernelOffset) { if (m_cmhal->midThreadPreemptionDisabled) { return MOS_STATUS_SUCCESS; } // Send CS_STALL pipe control //Insert a pipe control as synchronization MHW_PIPE_CONTROL_PARAMS pipeCtlParams; MOS_ZeroMemory(&pipeCtlParams, sizeof(MHW_PIPE_CONTROL_PARAMS)); pipeCtlParams.presDest = &m_cmhal->renderTimeStampResource.osResource; pipeCtlParams.dwPostSyncOp = MHW_FLUSH_NOWRITE; pipeCtlParams.dwFlushMode = MHW_FLUSH_WRITE_CACHE; pipeCtlParams.bDisableCSStall = 0; pipeCtlParams.bFlushRenderTargetCache = true; CM_CHK_MOSSTATUS_RETURN(m_miInterface->AddPipeControl(&m_cmdBuf, nullptr, &pipeCtlParams)); MHW_SIP_STATE_PARAMS sipStateParams; MOS_ZeroMemory(&sipStateParams, sizeof(MHW_SIP_STATE_PARAMS)); sipStateParams.bSipKernel = true; sipStateParams.dwSipBase = sipKernelOffset; CM_CHK_MOSSTATUS_RETURN(m_hwRender->AddSipStateCmd(&m_cmdBuf, &sipStateParams)); return MOS_STATUS_SUCCESS; } MOS_STATUS CmCommandBuffer::AddCsrBaseAddress(MOS_RESOURCE *resource) { if (m_cmhal->midThreadPreemptionDisabled) { return MOS_STATUS_SUCCESS; } // Send csr base addr command CM_CHK_MOSSTATUS_RETURN(m_hwRender->AddGpgpuCsrBaseAddrCmd(&m_cmdBuf, resource)); return MOS_STATUS_SUCCESS; } MOS_STATUS CmCommandBuffer::AddConditionalBatchBufferEnd(CM_HAL_CONDITIONAL_BB_END_INFO *cbbInfo) { MHW_MI_CONDITIONAL_BATCH_BUFFER_END_PARAMS cbbParams; MOS_ZeroMemory(&cbbParams, sizeof(MHW_MI_CONDITIONAL_BATCH_BUFFER_END_PARAMS)); cbbParams.presSemaphoreBuffer = &(m_cmhal->bufferTable[cbbInfo->bufferTableIndex].osResource); cbbParams.dwValue = cbbInfo->compareValue; cbbParams.bDisableCompareMask = cbbInfo->disableCompareMask; cbbParams.dwOffset = cbbInfo->offset; CM_CHK_MOSSTATUS_RETURN(m_miInterface->AddMiConditionalBatchBufferEndCmd(&m_cmdBuf, &cbbParams)); return MOS_STATUS_SUCCESS; } MOS_STATUS CmCommandBuffer::AddPowerOption(CM_POWER_OPTION *option) { if (option == nullptr) { return MOS_STATUS_SUCCESS; } if (m_cmhal->cmHalInterface->IsOverridePowerOptionPerGpuContext()) { return MOS_STATUS_SUCCESS; } MEDIA_FEATURE_TABLE *skuTable = m_cmhal->renderHal->pSkuTable; MEDIA_SYSTEM_INFO *gtSystemInfo = m_osInterface->pfnGetGtSystemInfo(m_osInterface); // set command buffer attributes if (skuTable && (MEDIA_IS_SKU(skuTable, FtrSSEUPowerGating)|| MEDIA_IS_SKU(skuTable, FtrSSEUPowerGatingControlByUMD))) { if ((option->nSlice || option->nSubSlice || option->nEU) && (gtSystemInfo != nullptr && gtSystemInfo->SliceCount && gtSystemInfo->SubSliceCount)) { m_cmdBuf.Attributes.dwNumRequestedEUSlices = NonZeroMin(option->nSlice, gtSystemInfo->SliceCount); m_cmdBuf.Attributes.dwNumRequestedSubSlices = NonZeroMin(option->nSubSlice, (gtSystemInfo->SubSliceCount / gtSystemInfo->SliceCount)); m_cmdBuf.Attributes.dwNumRequestedEUs = NonZeroMin(option->nEU, (gtSystemInfo->EUCount / gtSystemInfo->SubSliceCount)); m_cmdBuf.Attributes.bValidPowerGatingRequest = true; if (m_cmhal->platform.eRenderCoreFamily == IGFX_GEN12_CORE) { m_cmdBuf.Attributes.bUmdSSEUEnable = true; } } if (m_cmhal->requestSingleSlice) { m_cmdBuf.Attributes.dwNumRequestedEUSlices = 1; } if (GFX_IS_PRODUCT(m_cmhal->platform, IGFX_SKYLAKE) && m_osInterface->pfnSetSliceCount) { uint32_t sliceCount = m_cmdBuf.Attributes.dwNumRequestedEUSlices; m_osInterface->pfnSetSliceCount(m_osInterface, &sliceCount); } } // Add Load register command if(m_cmdBuf.Attributes.bUmdSSEUEnable) { MHW_MI_LOAD_REGISTER_IMM_PARAMS MiLoadRegImmParams; MHW_RENDER_PWR_CLK_STATE_PARAMS params; MOS_ZeroMemory(&params, sizeof(params)); params.PowerClkStateEn = true; params.SCountEn = true; params.SSCountEn = true; params.SliceCount = m_cmdBuf.Attributes.dwNumRequestedEUSlices; params.SubSliceCount = m_cmdBuf.Attributes.dwNumRequestedSubSlices; params.EUmax = m_cmdBuf.Attributes.dwNumRequestedEUs; params.EUmin = m_cmdBuf.Attributes.dwNumRequestedEUs; MOS_ZeroMemory(&MiLoadRegImmParams, sizeof(MiLoadRegImmParams)); MiLoadRegImmParams.dwRegister = MHW__PWR_CLK_STATE_REG; MiLoadRegImmParams.dwData = params.Data; CM_CHK_MOSSTATUS_RETURN(m_miInterface->AddMiLoadRegisterImmCmd( &m_cmdBuf, &MiLoadRegImmParams)); } return MOS_STATUS_SUCCESS; } MOS_STATUS CmCommandBuffer::AddUmdProfilerStart() { if (m_cmhal->perfProfiler != nullptr) { CM_CHK_MOSSTATUS_RETURN(m_cmhal->perfProfiler->AddPerfCollectStartCmd((void *)m_cmhal, m_osInterface, m_miInterface, &m_cmdBuf)); } return MOS_STATUS_SUCCESS; } MOS_STATUS CmCommandBuffer::AddUmdProfilerEnd() { if (m_cmhal->perfProfiler != nullptr) { CM_CHK_MOSSTATUS_RETURN(m_cmhal->perfProfiler->AddPerfCollectEndCmd((void *)m_cmhal, m_osInterface, m_miInterface, &m_cmdBuf)); } return MOS_STATUS_SUCCESS; } MOS_STATUS CmCommandBuffer::AddGpgpuWalker(CMRT_UMD::CmThreadGroupSpace *threadGroupSpace, CmKernelEx *kernel, uint32_t mediaID) { MHW_GPGPU_WALKER_PARAMS gpGpuWalkerParams; MOS_ZeroMemory(&gpGpuWalkerParams, sizeof(MHW_GPGPU_WALKER_PARAMS)); gpGpuWalkerParams.InterfaceDescriptorOffset = mediaID; gpGpuWalkerParams.GpGpuEnable = true; threadGroupSpace->GetThreadGroupSpaceSize(gpGpuWalkerParams.ThreadWidth, gpGpuWalkerParams.ThreadHeight, gpGpuWalkerParams.ThreadDepth, gpGpuWalkerParams.GroupWidth, gpGpuWalkerParams.GroupHeight, gpGpuWalkerParams.GroupDepth); gpGpuWalkerParams.SLMSize = kernel->GetSLMSize(); CM_CHK_MOSSTATUS_RETURN(m_hwRender->AddGpGpuWalkerStateCmd(&m_cmdBuf, &gpGpuWalkerParams)); return MOS_STATUS_SUCCESS; } struct PACKET_SURFACE_STATE { SURFACE_STATE_TOKEN_COMMON token; union { mhw_state_heap_g9_X::RENDER_SURFACE_STATE_CMD cmdSurfaceState; mhw_state_heap_g9_X::MEDIA_SURFACE_STATE_CMD cmdSurfaceStateAdv; }; }; void CmCommandBuffer::Dump() { #if MDF_COMMAND_BUFFER_DUMP if (m_cmhal->dumpCommandBuffer) { m_cmhal->pfnDumpCommadBuffer( m_cmhal, &m_cmdBuf, offsetof(PACKET_SURFACE_STATE, cmdSurfaceState), mhw_state_heap_g9_X::RENDER_SURFACE_STATE_CMD::byteSize); } #endif }
16,516
1,127
<reponame>ryanloney/openvino-1 // Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "mvn_kernel_bfyx_opt.h" #include "kernel_selector_utils.h" #include <algorithm> #include <vector> #include <string> namespace kernel_selector { ParamsKey MVNKernelBfyxOpt::GetSupportedKey() const { ParamsKey k; k.EnableInputDataType(Datatype::F16); k.EnableInputDataType(Datatype::F32); k.EnableInputDataType(Datatype::INT8); k.EnableInputDataType(Datatype::UINT8); k.EnableOutputDataType(Datatype::F16); k.EnableOutputDataType(Datatype::F32); k.EnableOutputDataType(Datatype::INT8); k.EnableOutputDataType(Datatype::UINT8); k.EnableInputLayout(DataLayout::bfyx); k.EnableOutputLayout(DataLayout::bfyx); k.EnableInputLayout(DataLayout::bfzyx); k.EnableOutputLayout(DataLayout::bfzyx); k.EnableBatching(); k.EnableDifferentTypes(); k.EnableMVNMode(MVNMode::WITHIN_CHANNELS); k.EnableMVNMode(MVNMode::ACROSS_CHANNELS); k.EnableMVNNormalizeVariance(); return k; } MVNKernelBfyxOpt::Parent::DispatchData MVNKernelBfyxOpt::SetDefault(const mvn_params& params) const { DispatchData dispatchData; const auto& input = params.inputs[0]; if (params.mvnMode == MVNMode::WITHIN_CHANNELS) { dispatchData.dataSetSize = input.X().v * input.Y().v * input.Z().v; dispatchData.dataSetsCount = input.Batch().v * input.Feature().v; } else { dispatchData.dataSetSize = input.X().v * input.Y().v * input.Z().v * input.Feature().v; dispatchData.dataSetsCount = input.Batch().v; } // start with 1 thread per data set dispatchData.gws[0] = 1; dispatchData.gws[1] = dispatchData.dataSetsCount; dispatchData.gws[2] = 1; dispatchData.itemsNum = dispatchData.dataSetSize; // We have two units of data per work item in current implementation. auto local_mem_per_wi = 2 * BytesPerElement(params.inputs[0].GetDType()); // Combining device execution and local memory restrictions to compute maximum possible LWS. auto max_lws = std::min(params.engineInfo.maxWorkGroupSize, params.engineInfo.maxLocalMemSize / local_mem_per_wi); dispatchData.lws[0] = 1; dispatchData.lws[1] = 1; dispatchData.lws[2] = 1; // Compute maximum possible LWS that does not exceed device capabilities and optimizes number of global memory // reads. while ((dispatchData.itemsNum > 32 || dispatchData.lws[0] < dispatchData.itemsNum) && (2 * dispatchData.lws[0] <= max_lws)) { dispatchData.lws[0] *= 2; dispatchData.itemsNum /= 2; } dispatchData.gws[0] = dispatchData.lws[0]; dispatchData.leftovers = dispatchData.dataSetSize % dispatchData.lws[0]; return dispatchData; } JitConstants MVNKernelBfyxOpt::GetJitConstants(const mvn_params& params, MVNKernelBase::DispatchData dispatchData) const { auto jit = MVNKernelBase::GetJitConstants(params, dispatchData); jit.AddConstants({ MakeJitConstant("ITEMS_NUM", dispatchData.itemsNum), MakeJitConstant("LWS", dispatchData.lws[0]), MakeJitConstant("GWS", dispatchData.gws[0]), MakeJitConstant("DATA_SETS_COUNT", dispatchData.dataSetsCount), MakeJitConstant("DATA_SET_SIZE", dispatchData.dataSetSize), MakeJitConstant("LEFTOVERS", dispatchData.leftovers), }); auto activation_dt = GetActivationType(params); jit.Merge(MakeTypeJitConstants(activation_dt, "ACTIVATION")); if (!params.fused_ops.empty()) { std::vector<std::string> idx_order; if (params.inputs[0].GetDims().size() <= 4) { if (params.mvnMode == MVNMode::WITHIN_CHANNELS) { idx_order = { "(data_set_idx / OUTPUT_FEATURE_NUM)", "(data_set_idx % OUTPUT_FEATURE_NUM)", "((in_data_set_idx + iteration_in_data_set_offset) / OUTPUT_SIZE_X)", "((in_data_set_idx + iteration_in_data_set_offset) % OUTPUT_SIZE_X)" }; } else if (params.mvnMode == MVNMode::ACROSS_CHANNELS) { idx_order = { "data_set_idx", "((in_data_set_idx + iteration_in_data_set_offset) / (OUTPUT_SIZE_X * OUTPUT_SIZE_Y))", "((in_data_set_idx + iteration_in_data_set_offset) / OUTPUT_SIZE_X % OUTPUT_SIZE_Y)", "((in_data_set_idx + iteration_in_data_set_offset) % OUTPUT_SIZE_X)" }; } } else if (params.inputs[0].GetDims().size() == 5) { if (params.mvnMode == MVNMode::WITHIN_CHANNELS) { idx_order = { "(data_set_idx / OUTPUT_FEATURE_NUM)", "(data_set_idx % OUTPUT_FEATURE_NUM)", "((in_data_set_idx + iteration_in_data_set_offset) / (OUTPUT_SIZE_X * OUTPUT_SIZE_Y))", "((in_data_set_idx + iteration_in_data_set_offset) / OUTPUT_SIZE_X % OUTPUT_SIZE_Y)", "((in_data_set_idx + iteration_in_data_set_offset) % OUTPUT_SIZE_X)" }; } else if (params.mvnMode == MVNMode::ACROSS_CHANNELS) { idx_order = { "data_set_idx", "((in_data_set_idx + iteration_in_data_set_offset) / (OUTPUT_SIZE_X * OUTPUT_SIZE_Y * OUTPUT_SIZE_Z))", "((in_data_set_idx + iteration_in_data_set_offset) / (OUTPUT_SIZE_X * OUTPUT_SIZE_Y) % OUTPUT_SIZE_Z)", "((in_data_set_idx + iteration_in_data_set_offset) / OUTPUT_SIZE_X % OUTPUT_SIZE_Y)", "((in_data_set_idx + iteration_in_data_set_offset) % OUTPUT_SIZE_X)" }; } } auto conf = FusedOpsConfiguration("", idx_order, "result", activation_dt, 1, LoadType::LT_UNALIGNED, BoundaryCheck::DISABLED); jit.Merge(MakeFusedOpsJitConstants(params, { conf })); } return jit; } KernelsData MVNKernelBfyxOpt::GetKernelsData(const Params& params, const optional_params& optParams) const { return GetCommonKernelsData(params, optParams); } KernelsPriority MVNKernelBfyxOpt::GetKernelsPriority(const Params& /*params*/, const optional_params& /*options*/) const { return FORCE_PRIORITY_7; } } // namespace kernel_selector
2,853
2,197
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "eventpipeeventprinter.h" using std::vector; using std::shared_ptr; EventPipeEventPrinter::EventPipeEventPrinter() { } LPCWCH EventPipeEventPrinter::TypeCodeToString(EventPipeTypeCode typeCode) { switch (typeCode) { case EventPipeTypeCode::Object: return WCHAR("Object"); case EventPipeTypeCode::Boolean: return WCHAR("Boolean"); case EventPipeTypeCode::Char: return WCHAR("Char"); case EventPipeTypeCode::Sbyte: return WCHAR("Sbyte"); case EventPipeTypeCode::Byte: return WCHAR("Byte"); case EventPipeTypeCode::Int16: return WCHAR("Int16"); case EventPipeTypeCode::Uint16: return WCHAR("Uint16"); case EventPipeTypeCode::Int32: return WCHAR("Int32"); case EventPipeTypeCode::Uint32: return WCHAR("Uint32"); case EventPipeTypeCode::Int64: return WCHAR("Int64"); case EventPipeTypeCode::Uint64: return WCHAR("Uint64"); case EventPipeTypeCode::Single: return WCHAR("Single"); case EventPipeTypeCode::Double: return WCHAR("Double"); case EventPipeTypeCode::Decimal: return WCHAR("Decimal"); case EventPipeTypeCode::Datetime: return WCHAR("Datetime"); case EventPipeTypeCode::Guid: return WCHAR("Guid"); case EventPipeTypeCode::String: return WCHAR("String"); case EventPipeTypeCode::ArrayType: return WCHAR("ArrayType"); default: return WCHAR("Unknown Type"); } } void EventPipeEventPrinter::PrintIndentLevel(ULONG level) { for (ULONG i = 0; i < level; ++i) { printf(" "); } } // typedef struct _GUID { // unsigned long Data1; // unsigned short Data2; // unsigned short Data3; // unsigned char Data4[8]; // } GUID; void EventPipeEventPrinter::PrintGuid(LPCGUID guid) { if (guid == NULL) { printf("{NULL Guid}"); } else { printf("{%8.8lu-%4.4u-%4.4u-%2.2u%2.2u-%2.2u%2.2u%2.2u%2.2u%2.2u%2.2u}", guid->Data1, guid->Data2, guid->Data3, guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3], guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]); } } void EventPipeEventPrinter::PrintEvent(LPCWSTR providerName, EventPipeMetadataInstance metadata, LPCBYTE eventData, ULONG cbEventData, LPCGUID pActivityId, LPCGUID pRelatedActivityId, ThreadID eventThread, UINT_PTR stackFrames[], ULONG numStackFrames) { wprintf(L"Saw EventPipe event from provider %s\n", providerName); PrintIndentLevel(1); wprintf(L"name: %s\n", metadata.name); PrintIndentLevel(1); printf("eventId: %d\n", metadata.id); PrintIndentLevel(1); printf("eventLevel: %d\n", metadata.level); PrintIndentLevel(1); printf("eventKeywords: %lld\n", metadata.keywords); PrintIndentLevel(1); printf("eventVersion: %d\n", metadata.version); PrintIndentLevel(1); printf("eventOpcode: %d\n", metadata.opcode); PrintIndentLevel(1); printf("activityID: "); PrintGuid(pActivityId); printf("\n"); PrintIndentLevel(1); printf("relatedActivityID: "); PrintGuid(pActivityId); printf("\n"); PrintIndentLevel(1); printf("event ThreadID: %p\n", (void *)eventThread); PrintIndentLevel(1); printf("numStackFrames: %lu\n", numStackFrames); PrintIndentLevel(1); printf("stackFrames %p\n", (void *)stackFrames); PrintIndentLevel(1); printf("number of event params: %d\n", (int)metadata.parameters.size()); PrintIndentLevel(1); printf("event params:\n"); ULONG offset = 0; for (auto &&descriptor : metadata.parameters) { if (!PrintParam(descriptor, 2, eventData, cbEventData, &offset)) { return; } } } bool EventPipeEventPrinter::PrintType(EventPipeDataDescriptor type, ULONG indentLevel, // number of tabs to put include LPCBYTE eventData, ULONG cbEventData, ULONG *offset) { switch (type.type) { case EventPipeTypeCode::Boolean: { // Bools are encoded as 4 bytes UINT32 data = ReadFromBuffer<UINT32>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Boolean value=%s\n", data != 0 ? "true" : "false"); } break; case EventPipeTypeCode::Char: { WCHAR data = ReadFromBuffer<WCHAR>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Char value=%c\n", data); } break; case EventPipeTypeCode::Sbyte: { INT8 data = ReadFromBuffer<INT8>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Sbyte value=%d\n", data); } break; case EventPipeTypeCode::Byte: { BYTE data = ReadFromBuffer<BYTE>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Byte value=%d\n", data); } break; case EventPipeTypeCode::Int16: { INT16 data = ReadFromBuffer<INT16>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Int16 value=%d\n", data); } break; case EventPipeTypeCode::Uint16: { UINT16 data = ReadFromBuffer<UINT16>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Uint16 value=%d\n", data); } break; case EventPipeTypeCode::Int32: { INT32 data = ReadFromBuffer<INT32>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Int32 value=%d\n", data); } break; case EventPipeTypeCode::Uint32: { UINT32 data = ReadFromBuffer<UINT32>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Uint32 value=%d\n", data); } break; case EventPipeTypeCode::Int64: { INT64 data = ReadFromBuffer<INT64>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Int64 value=%lld\n", data); } break; case EventPipeTypeCode::Uint64: { UINT64 data = ReadFromBuffer<UINT64>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Uint64 value=%llu\n", data); } break; case EventPipeTypeCode::Single: { float data = ReadFromBuffer<float>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Single value=%f\n", data); } break; case EventPipeTypeCode::Double: { double data = ReadFromBuffer<double>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); printf("type Double value=%f\n", data); } break; case EventPipeTypeCode::String: { WCHAR *data = ReadWideStringFromBuffer(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); wprintf(L"type String value=\"%s\"\n", data); } break; case EventPipeTypeCode::ArrayType: { UINT16 arrayLength = ReadFromBuffer<UINT16>(eventData, cbEventData, offset); PrintIndentLevel(indentLevel); wprintf(L"Array length=%d param type=%s values:\n", arrayLength, TypeCodeToString(type.elementType->type)); for (int i = 0; i < arrayLength; ++i) { if (!PrintType(*(type.elementType), indentLevel + 1, eventData, cbEventData, offset)) { return false; } } PrintIndentLevel(indentLevel); printf("End of array values\n"); } break; case EventPipeTypeCode::Object: { PrintIndentLevel(indentLevel); printf("Self describing object param fields:\n"); for (auto &&fieldDescriptor : type.fields) { if (!PrintType(fieldDescriptor, indentLevel + 1, eventData, cbEventData, offset)) { return false; } } } break; case EventPipeTypeCode::Decimal: case EventPipeTypeCode::Datetime: case EventPipeTypeCode::Guid: default: { PrintIndentLevel(indentLevel); wprintf(L"Unsupported param type code %s\n", TypeCodeToString(type.type)); return false; } } return true; } bool EventPipeEventPrinter::PrintParam(EventPipeDataDescriptor descriptor, ULONG indentLevel, // number of tabs to put in LPCBYTE eventData, ULONG cbEventData, ULONG *offset) { PrintIndentLevel(indentLevel); wprintf(L"Param name: %s\n", descriptor.name); return PrintType(descriptor, indentLevel + 1, eventData, cbEventData, offset); }
5,523
2,434
<reponame>SergKhram/swagger2markup package io.github.swagger2markup.adoc.ast.impl; import org.asciidoctor.ast.Block; import org.asciidoctor.ast.StructuralNode; import java.util.*; public class BlockImpl extends StructuralNodeImpl implements Block { private List<String> lines; public BlockImpl(StructuralNode parent, String context) { this(parent, context, ""); } public BlockImpl(StructuralNode parent, String context, Object content) { this(parent, context, new HashMap<>(), content); } public BlockImpl(StructuralNode parent, String context, Map<String, Object> attributes) { this(parent, context, attributes, ""); } public BlockImpl(StructuralNode parent, String context, Map<String, Object> attributes, Object content) { this(parent, context, attributes, new ArrayList<>(), content, new ArrayList<>(), "", new ArrayList<>()); } public BlockImpl(StructuralNode parent, String context, Map<String, Object> attributes, List<String> roles, Object content, List<StructuralNode> blocks, String contentModel, List<String> subs) { this(parent, context, attributes, roles, content, blocks, calculateLevel(parent), contentModel, subs); } public BlockImpl(StructuralNode parent, String context, Map<String, Object> attributes, List<String> roles, Object content, List<StructuralNode> blocks, Integer level, String contentModel, List<String> subs) { super(parent, context, attributes, roles, content, blocks, level, contentModel, subs); this.lines = new ArrayList<>(); } @Override @Deprecated public List<String> lines() { return getLines(); } @Override public List<String> getLines() { return lines; } @Override public void setLines(List<String> lines) { this.lines = lines; } @Override @Deprecated public String source() { return getSource(); } @Override public String getSource() { return String.join("\n", lines); } @Override public void setSource(String source) { setLines(Arrays.asList(source.split("\n"))); } }
793
2,583
<reponame>onelsonic/armory import bpy from bpy.props import * class TLM_LuxCoreSceneProperties(bpy.types.PropertyGroup): #Luxcore specific here tlm_luxcore_dir : StringProperty( name="Luxcore Directory", description="Standalone path to your LuxCoreRender binary.", default="", subtype="FILE_PATH")
136
2,002
#pragma once struct NotificationsLongRunningProcessFactory WrlFinal : public Microsoft::WRL::ClassFactory<> { HRESULT RuntimeClassInitialize() noexcept; IFACEMETHODIMP CreateInstance( _In_opt_ IUnknown* outer, _In_ REFIID riid, _COM_Outptr_ void** ppvObject) override; private: winrt::com_ptr<NotificationsLongRunningPlatformImpl> m_platform; };
163
5,079
from setuptools import setup import textwrap setup(name='MarkupPy', version='1.14', description='An HTML/XML generator', url='https://github.com/tylerbakke/MarkupPy', author='<NAME>', author_email="<EMAIL>", long_description=textwrap.dedent("""\ This is MarkupPy - a Python module that attempts to make it easier to generate HTML/XML from a Python program in an intuitive, lightweight, customizable and pythonic way. It works with both python 2 and 3. The code is in the public domain. Version: 1.14 as of August 1, 2017. Please send bug reports, feature requests, enhancement ideas or questions to <EMAIL>. Installation: Run 'pip install MarkupPy" from the terminal. Documentation and further info is at https://tylerbakke.github.io/MarkupPy/ (Migrated from markup.py) """), license="MIT", packages=['MarkupPy'], classifiers=[ 'Environment :: Console', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3' ], zip_safe=False)
437
370
/* * Copyright (c) 2015-2019 Dubalu LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include "soundex.h" #include <string> // for std::string #include <unordered_map> // for std::unordered_map #include <utility> // for std::forward #include "strings.hh" // for strings::inplace_upper static const std::unordered_map<std::string, std::string> german_accents({ { "Ä", "A" }, { "ä", "A" }, { "Ö" , "O" }, { "ö", "O" }, { "Ü", "U" }, { "ü", "U" }, { "ß", "S" } }); static const std::unordered_map<std::string, std::string> german_composed({ { "PH", "3" }, { "CA", "4" }, { "CH", "4" }, { "CK", "4" }, { "CO", "4" }, { "CQ", "4" }, { "CU", "4" }, { "CX", "4" }, { "DC", "8" }, { "DS", "8" }, { "DZ", "8" }, { "TC", "8" }, { "TS", "8" }, { "TZ", "8" }, { "KX", "8" }, { "QX", "8" }, { "SC", "8" }, { "ZC", "8" } }); /* * Soundex for German based in Kölner Phonetik: * https://de.wikipedia.org/wiki/Kölner_Phonetik * * Length of the result is not truncated, so the code does not have a fixed length. */ class SoundexGerman : public Soundex<SoundexGerman> { friend class Soundex<SoundexGerman>; std::string _encode(std::string str) const { if (str.empty()) { return str; } // 1. Replace accents. replace(str, 0, german_accents); // 2. Pass to upper case. strings::inplace_upper(str); // 3. Remove all non alphabetic characters at the begin. auto it = str.begin(); while (it != str.end()) { if (*it >= 'A' && *it <= 'Z') { break; } else { it = str.erase(it); } } if (str.empty()) { return str; } // 4. Replace prefix. if (str.length() > 1 && *it == 'C') { switch (*(it + 1)) { case 'A': case 'H': case 'K': case 'L': case 'O': case 'Q': case 'R': case 'U': case 'X': it = str.erase(it); *it = '4'; break; } } // 5. Replace "composed letters". replace(str, 0, german_composed); // 6. Starts the calculation of Soundex. it = str.begin(); while (it != str.end()) { switch (*it) { case 'A': case 'E': case 'I': case 'J': case 'O': case 'U': case 'Y': if (it == str.begin() || *(it - 1) != '0') { *it++ = '0'; } else { it = str.erase(it); } break; case 'B': case 'P': if (it == str.begin() || *(it - 1) != '1') { *it++ = '1'; } else { it = str.erase(it); } break; case 'D': case 'T': if (it == str.begin() || *(it - 1) != '2') { *it++ = '2'; } else { it = str.erase(it); } break; case 'F': case 'V': case 'W': if (it == str.begin() || *(it - 1) != '3') { *it++ = '3'; } else { it = str.erase(it); } break; case 'G': case 'K': case 'Q': if (it == str.begin() || *(it - 1) != '4') { *it++ = '4'; } else { it = str.erase(it); } break; case 'L': if (it == str.begin() || *(it - 1) != '5') { *it++ = '5'; } else { it = str.erase(it); } break; case 'M': case 'N': if (it == str.begin() || *(it - 1) != '6') { *it++ = '6'; } else { it = str.erase(it); } break; case 'R': if (it == str.begin() || *(it - 1) != '7') { *it++ = '7'; } else { it = str.erase(it); } break; case 'C': case 'S': case 'Z': if (it == str.begin() || *(it - 1) != '8') { *it++ = '8'; } else { it = str.erase(it); } break; case 'X': if (it == str.begin() || *(it - 1) != '4') { *it++ = '4'; it = ++str.insert(it, '8'); } else { *it++ = '8'; } break; case '3': case '4': case '8': ++it; break; default: it = str.erase(it); break; } } return str; } std::string_view _name() const noexcept { return "SoundexGerman"; } std::string _description() const noexcept { return "Soundex for German Language"; } public: public: SoundexGerman() = default; template <typename T> SoundexGerman(T&& str) : Soundex<SoundexGerman>(_encode(std::string(std::forward<T>(str)))) { } };
2,479
5,169
{ "name": "SBUnits", "version": "0.1.0", "summary": "Dimensions, Units and Quantities", "description": "A number without its unit of measure is meaningless at best and dangerous at worst. The unit\nprovides the context within which to interpret the value...", "homepage": "http://github.com/EBGToo/SBUnits", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/EBGToo/SBUnits.git", "tag": "0.1.0" }, "source_files": "Sources/*.swift", "platforms": { "osx": "10.9" } }
212
309
<filename>src/Cxx/DataStructures/OBBTreeExtractCells.cxx #include <vtkSmartPointer.h> #include <vtkSphereSource.h> #include <vtkPoints.h> #include <vtkIdList.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkLine.h> #include <vtkLineSource.h> #include <vtkExtractCells.h> #include <vtkOBBTree.h> #include <vtkPolyDataMapper.h> #include <vtkDataSetMapper.h> #include <vtkActor.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkRenderWindowInteractor.h> int main(int, char *[]) { vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New(); sphereSource->SetPhiResolution(7); sphereSource->SetThetaResolution(15); sphereSource->Update(); // Create the locator vtkSmartPointer<vtkOBBTree> tree = vtkSmartPointer<vtkOBBTree>::New(); tree->SetDataSet(sphereSource->GetOutput()); tree->BuildLocator(); // Intersect the locator with the line double lineP0[3] = {-0.6, -0.6, -0.6}; double lineP1[3] = {.6, .6, .6}; vtkSmartPointer<vtkPoints> intersectPoints = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkIdList> intersectCells = vtkSmartPointer<vtkIdList>::New(); double tol = 1.e-8; tree->SetTolerance(tol); tree->IntersectWithLine(lineP0, lineP1, intersectPoints, intersectCells); std::cout << "NumPoints: " << intersectPoints->GetNumberOfPoints() << std::endl; // Display list of intersections double intersection[3]; for(int i = 0; i < intersectPoints->GetNumberOfPoints(); i++ ) { intersectPoints->GetPoint(i, intersection); std::cout << "\tPoint Intersection " << i << ": " << intersection[0] << ", " << intersection[1] << ", " << intersection[2] << std::endl; } std::cout << "NumCells: " << intersectCells->GetNumberOfIds() << std::endl; vtkIdType cellId; for(int i = 0; i < intersectCells->GetNumberOfIds(); i++ ) { cellId = intersectCells->GetId(i); std::cout << "\tCellId " << i << ": " << cellId << std::endl; } // Render the line, sphere and intersected cells vtkSmartPointer<vtkLineSource> lineSource = vtkSmartPointer<vtkLineSource>::New(); lineSource->SetPoint1(lineP0); lineSource->SetPoint2(lineP1); vtkSmartPointer<vtkPolyDataMapper> lineMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); lineMapper->SetInputConnection(lineSource->GetOutputPort()); vtkSmartPointer<vtkActor> lineActor = vtkSmartPointer<vtkActor>::New(); lineActor->SetMapper(lineMapper); vtkSmartPointer<vtkPolyDataMapper> sphereMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); sphereMapper->SetInputConnection(sphereSource->GetOutputPort()); vtkSmartPointer<vtkActor> sphereActor = vtkSmartPointer<vtkActor>::New(); sphereActor->SetMapper(sphereMapper); sphereActor->GetProperty()->SetRepresentationToWireframe(); sphereActor->GetProperty()->SetColor(0.89,0.81,0.34); vtkSmartPointer<vtkExtractCells> cellSource = vtkSmartPointer<vtkExtractCells>::New(); cellSource->SetInputConnection(sphereSource->GetOutputPort()); cellSource->SetCellList(intersectCells); vtkSmartPointer<vtkDataSetMapper> cellMapper = vtkSmartPointer<vtkDataSetMapper>::New(); cellMapper->SetInputConnection(cellSource->GetOutputPort()); vtkSmartPointer<vtkActor> cellActor = vtkSmartPointer<vtkActor>::New(); cellActor->SetMapper(cellMapper); cellActor->GetProperty()->SetColor(1.0, 0.3882, 0.2784); vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); renderer->AddActor(lineActor); renderer->AddActor(sphereActor); renderer->AddActor(cellActor); renderer->SetBackground(.4, .5, .6); renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; }
1,639
622
//===================================================================== // Copyright 2016 (c), Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //===================================================================== #include "cpimageview.h" #include "acimageview.h" void cpImageView::oncpImageViewVirtualMousePosition(QPointF* scenePos, QPointF* localPos, int onID) { oncpImageViewMousePosition(scenePos, localPos, onID); } void cpImageView::showToobarButton(bool show) { if (custTitleBar) custTitleBar->setButtonToolBarShow(show); } void cpImageView::oncpImageViewMousePosition(QPointF* scenePos, QPointF* localPos, int onID) { Q_UNUSED(scenePos); Q_UNUSED(onID); if (!m_acImageView) return; // is mouse inside image view if (localPos) { m_localPos = *localPos; // Rounds up pixel co-ordinates // if in debugMode: blocks at 0,0 will start at 1,1 int x = qRound(localPos->rx() + 0.5); int y = qRound(localPos->ry() + 0.5); if (x < 0) x = 0; if (y < 0) y = 0; QColor color; QString Txt = ""; switch (m_ImageViewState) { case eImageViewState::isOriginal: { //m_labelTxtView->setText("Original"); if (m_acImageView->m_imageItem_Original) { color = m_acImageView->m_imageItem_Original->pixmap().toImage().pixel(localPos->rx(), localPos->ry()); } else { // original image is a root on project explorer if (m_acImageView->m_imageItem_Processed) color = m_acImageView->m_imageItem_Processed->pixmap().toImage().pixel(localPos->rx(), localPos->ry()); } bool dispDefault = true; // New feature for debugging code that uses alpha channel if (m_OriginalMipImages && m_CMips) { if (m_OriginalMipImages->mipset) { MipLevel* mipLevel = m_CMips->GetMipLevel(m_OriginalMipImages->mipset, m_acImageView->m_currentMiplevel,m_DepthLevel); if (mipLevel) { if (m_OriginalMipImages->mipset->m_format == CMP_FORMAT_RGBA_8888_S) { CMP_SBYTE* pData = mipLevel->m_psbData; if (pData) { if ((y <= mipLevel->m_nHeight) && (x <= mipLevel->m_nWidth)) { // For Channel data RGBA 8:8:8:8 in mipset if (m_OriginalMipImages->mipset->m_ChannelFormat == CF_8bit) { CMP_DWORD pixoffset = 0; if ((x > 0) && (y > 0)) pixoffset = (y - 1) * mipLevel->m_nWidth * 4 + (x - 1) * 4; if ((mipLevel->m_dwLinearSize > 3) && (pixoffset < mipLevel->m_dwLinearSize - 3)) { dispDefault = false; Txt.sprintf("RGBA_S Source (%3d,%3d,%3d,%3d) Rendered (%3d,%3d,%3d,%3d)", pData[pixoffset], pData[pixoffset + 1], pData[pixoffset + 2], pData[pixoffset + 3], color.red(), color.green(), color.blue(), color.alpha()); } } } } } else { CMP_BYTE* pData = mipLevel->m_pbData; if (pData) { if ((y <= mipLevel->m_nHeight) && (x <= mipLevel->m_nWidth)) { // For Channel data RGBA 8:8:8:8 in mipset if (m_OriginalMipImages->mipset->m_ChannelFormat == CF_8bit) { CMP_DWORD pixoffset = 0; if ((x > 0) && (y > 0)) pixoffset = (y - 1) * mipLevel->m_nWidth * 4 + (x - 1) * 4; if ((mipLevel->m_dwLinearSize > 3) && (pixoffset < mipLevel->m_dwLinearSize - 3)) { dispDefault = false; Txt.sprintf("RGBA Source (%3d,%3d,%3d,%3d) ", pData[pixoffset], pData[pixoffset + 1], pData[pixoffset + 2], pData[pixoffset + 3]); // Rendered (%3d,%3d,%3d,%3d) ", //color.red(), color.green(), color.blue(), color.alpha()); } } } } } } } } if (dispDefault) Txt.sprintf(" RGBA Rendered (%3d,%3d,%3d,%3d)", color.red(), color.green(), color.blue(), color.alpha()); } break; case eImageViewState::isDiff: m_labelTxtView->setText(TXT_IMAGE_DIFF); if (m_acImageView->m_imageItem_Processed) { color = m_acImageView->m_imageItem_Processed->pixmap().toImage().pixel(localPos->rx(), localPos->ry()); // normalize color back prior to any brightness or contrast adjustments for the user view int r = color.red(); int g = color.green(); int b = color.blue(); if (g_Application_Options.m_imagediff_contrast != 0) { r = (r / g_Application_Options.m_imagediff_contrast); g = (g / g_Application_Options.m_imagediff_contrast); b = (b / g_Application_Options.m_imagediff_contrast); } color.setRed(r); color.setGreen(g); color.setBlue(b); Txt.sprintf("RGB Diff [%3d,%3d,%3d]", color.red(), color.green(), color.blue()); } break; case eImageViewState::isProcessed: m_labelTxtView->setText(TXT_IMAGE_PROCESSED); if (m_acImageView->m_imageItem_Processed) { bool dispDefault = true; if (m_acImageView->m_MipImages) { color = m_acImageView->m_imageItem_Processed->pixmap().toImage().pixel(localPos->rx(), localPos->ry()); if (m_acImageView->m_MipImages->decompressedMipSet) { MipLevel* mipLevel = m_CMips->GetMipLevel(m_acImageView->m_MipImages->decompressedMipSet, m_acImageView->m_currentMiplevel, m_DepthLevel); if (mipLevel) { if (m_acImageView->m_MipImages->decompressedMipSet->m_format == CMP_FORMAT_RGBA_8888_S) { CMP_SBYTE* pData = mipLevel->m_psbData; if (pData) { if ((y <= mipLevel->m_nHeight) && (x <= mipLevel->m_nWidth)) { // For Channel data RGBA 8:8:8:8 in mipset if (m_acImageView->m_MipImages->decompressedMipSet->m_ChannelFormat == CF_8bit) { CMP_DWORD pixoffset = 0; if ((x > 0) && (y > 0)) pixoffset = (y - 1) * mipLevel->m_nWidth * 4 + (x - 1) * 4; if ((mipLevel->m_dwLinearSize > 3) && (pixoffset < mipLevel->m_dwLinearSize - 3)) { dispDefault = false; Txt.sprintf("RGBA_S Source (%3d,%3d,%3d,%3d) Rendered (%3d,%3d,%3d,%3d)", pData[pixoffset], pData[pixoffset + 1], pData[pixoffset + 2], pData[pixoffset + 3], color.red(), color.green(), color.blue(), color.alpha()); } } } } } else { CMP_BYTE* pData = mipLevel->m_pbData; if (pData) { if ((y <= mipLevel->m_nHeight) && (x <= mipLevel->m_nWidth)) { // For Channel data RGBA 8:8:8:8 in mipset if (m_acImageView->m_MipImages->decompressedMipSet->m_ChannelFormat == CF_8bit) { CMP_DWORD pixoffset = 0; if ((x > 0) && (y > 0)) pixoffset = (y - 1) * mipLevel->m_nWidth * 4 + (x - 1) * 4; if ((mipLevel->m_dwLinearSize > 3) && (pixoffset < mipLevel->m_dwLinearSize - 3)) { dispDefault = false; Txt.sprintf("RGBA Source (%3d,%3d,%3d,%3d)", pData[pixoffset], pData[pixoffset + 1], pData[pixoffset + 2], pData[pixoffset + 3]); } } } } } } } } if (dispDefault) Txt.sprintf(" RGBA Rendered (%3d,%3d,%3d,%3d)", color.red(), color.green(), color.blue(), color.alpha()); } break; default: m_labelTxtView->setText("?"); break; } m_labelColorTxt->setText(Txt); QString Txt2; #ifdef USE_BCN_IMAGE_DEBUG #ifdef _DEBUG if (m_acImageView->m_debugMode) { m_labelColorTxt->setText(""); XBlockNum = x; YBlockNum = y; Txt2 = QString::number(x) + "," + QString::number(y) + " Block"; } #endif #endif Txt2 = QString::number(x) + "," + QString::number(y) + " px"; m_labelPos->setText(Txt2); if (x == 0) x = 1; if (y == 0) y = 1; m_source_BlockXPos = (x - 1) / 4; m_source_BlockYPos = (y - 1) / 4; Txt2 = QString::number(m_source_BlockXPos) + "," + QString::number(m_source_BlockYPos) + " (4x4)"; m_labelBlockPos->setText(Txt2); QPalette palette; palette.setColor(QPalette::Background, color); palette.setColor(QPalette::WindowText, color); m_labelColorRGBA->setPalette(palette); } else { m_labelPos->setText(""); m_labelBlockPos->setText(""); m_labelColorTxt->setText(""); QPalette palette; palette.setColor(QPalette::Background, Qt::black); palette.setColor(QPalette::WindowText, Qt::black); m_labelColorRGBA->setPalette(palette); } } #include "cexr.h" #include "ImfArray.h" #include "ImfRgba.h" void cpImageView::onImageDiff() { if (!m_CBimageview_Toggle) return; if (qApp) qApp->setOverrideCursor(Qt::BusyCursor); imageview_ImageDiff->setDisabled(true); if (m_ImageViewState == eImageViewState::isDiff) { m_ImageViewState = eImageViewState::isProcessed; m_CBimageview_Toggle->setItemText(0, TXT_IMAGE_PROCESSED); } else { m_ImageViewState = eImageViewState::isDiff; m_CBimageview_Toggle->setItemText(0, TXT_IMAGE_DIFF); } activeview = 0; m_CBimageview_Toggle->setCurrentIndex(0); if (m_acImageView) { m_acImageView->onToggleImageViews(0); m_acImageView->onSetPixelDiffView(m_ImageViewState == eImageViewState::isDiff); } oncpImageViewMousePosition(0, &m_localPos, 0); if (qApp) qApp->restoreOverrideCursor(); imageview_ImageDiff->setDisabled(false); setActionForImageViewStateChange(); } void cpImageView::keyPressEvent(QKeyEvent* event) { if (m_acImageView == NULL) return; #ifndef __linux__ //------------------------------------------------------------------------------------ // Feature enabled to allow user to copy an image view onto window system clipboard // This is only available through keyboard entry using: // Ctrl+C to copy the viewed image (Scaled accroding to zoom setting) // Alt+C to copy using the original image size // in both cases aspect ratio is maintained. //------------------------------------------------------------------------------------ if (event->key() == Qt::Key_C) { bool CTRL_key = event->modifiers() & Qt::ControlModifier; bool ALT_key = event->modifiers() & Qt::AltModifier; if (CTRL_key || ALT_key) { if (!m_acImageView->m_imageItem_Processed) return; // Copy Scaled image size if (CTRL_key) { int w = m_acImageView->m_imageItem_Processed->pixmap().width(); int h = m_acImageView->m_imageItem_Processed->pixmap().height(); qreal scale = m_acImageView->m_imageItem_Processed->scale(); // same value as m_ZoomLevel->value() / 100.0f w = int(w * scale); h = int(h * scale); QPixmap pixmap = m_acImageView->m_imageItem_Processed->pixmap().scaled(w, h, Qt::KeepAspectRatio); QApplication::clipboard()->setPixmap(pixmap, QClipboard::Clipboard); } else { // Copy Original Size QPixmap pixmap = m_acImageView->m_imageItem_Processed->pixmap(); QApplication::clipboard()->setPixmap(pixmap, QClipboard::Clipboard); } } } #endif if (m_OriginalMipImages->mipset == NULL) return; if (!m_CBimageview_Toggle) return; // Checks if we are viewing a processed image view (child node in project explorer) if (m_CBimageview_Toggle) { if (event->key() == Qt::Key_D) { // Set View to Processed Image (Index 0) and Enable Diff if applicable onImageDiff(); } else if (event->key() == Qt::Key_P) { // View Processed Image (Index 0) activeview = 0; m_CBimageview_Toggle->setCurrentIndex(0); // switch to a processed image view if (m_acImageView) m_acImageView->onToggleImageViews(0); oncpImageViewMousePosition(0, &m_localPos, 0); if (m_ImageViewState == eImageViewState::isDiff) { // the current processed view is an image diff to reset the view back to processed with no diff onImageDiff(); } m_ImageViewState = eImageViewState::isProcessed; } else if (event->key() == Qt::Key_O) { // View Original Image (Index 1) activeview = 1; m_CBimageview_Toggle->setCurrentIndex(1); // switch to a original image view if (m_acImageView) m_acImageView->onToggleImageViews(1); oncpImageViewMousePosition(0, &m_localPos, 0); m_ImageViewState = eImageViewState::isOriginal; } else if (event->key() == Qt::Key_Space || event->key() == Qt::Key_S) { if (activeview == 0) { activeview = 1; // Original m_ImageViewState = eImageViewState::isOriginal; } else { activeview = 0; // Processed or "Processed Diff" view if (m_DiffOnOff) m_ImageViewState = eImageViewState::isDiff; else m_ImageViewState = eImageViewState::isProcessed; } m_CBimageview_Toggle->setCurrentIndex(activeview); if (m_acImageView) m_acImageView->onToggleImageViews(activeview); oncpImageViewMousePosition(0, &m_localPos, 0); } } // This feature can be enabled in Debug Mode and allows users to breakpoint into various // codecs at the lowest block level of encoding. #ifdef USE_BCN_IMAGE_DEBUG #ifdef _DEBUG if (event->key() == Qt::Key_F1) { if (m_acImageView->m_debugMode) { MipLevel* mipLevel = m_CMips->GetMipLevel(m_OriginalMipImages->mipset, m_DepthLevel); if (!mipLevel) return; // Check the block size matches what we expect for BC6H or BC7 if (m_acImageView->m_graphicsScene->cursorBlockX != 4) return; if (m_acImageView->m_graphicsScene->cursorBlockY != 4) return; // Flag to indicate we have data to process bool hasData = false; // Calc data stride for each row index = width * num channels int row_stride = m_OriginalMipImages->mipset->m_nWidth * 4; // (BC6 Block Width * BC6 Block Height * Num Channels) * (Image Width / BC6 Block Width) // (4*4*4) * (Width / 4) = 4*4*Width int block_offset = 4 * 4 * m_OriginalMipImages->mipset->m_nWidth; // Get the block position we need to fill from // 16 = BC6 Block Width * Num Channels int start_index = (((XBlockNum - 1) * 16)) + ((YBlockNum - 1) * block_offset); int index; // napatel check format before getting data! // we have two sets Float16 (2 Bytes alligned) and Float32 (4 Bytes alligned) if (m_acImageView->m_debugFormat == "BC6H" || m_acImageView->m_debugFormat == "BC6H_SF") { // Encoder input to fill with data CMP_FLOAT in[16][4]; float dec_out[16][4]; BYTE cmp_in[16]; if (m_OriginalMipImages->mipset->m_ChannelFormat == CF_Float16) { // Get origin data pointer CMP_HALFSHORT* data = mipLevel->m_phfsData; CMP_HALF* temp = (CMP_HALF*)data; Array2D<Rgba> pixels(4, 4); pixels.resizeErase(4, 4); int d = 0; for (int row = 0; row < 4; row++) { index = (row * row_stride) + start_index; for (int col = 0; col < 4; col++) { in[d][0] = (float)temp[index]; pixels[row][col].r.setBits(data[index]); in[d][1] = (float)temp[index + 1]; pixels[row][col].g.setBits(data[index + 1]); in[d][2] = (float)temp[index + 2]; pixels[row][col].b.setBits(data[index + 2]); in[d][3] = (float)temp[index + 3]; pixels[row][col].a.setBits(data[index + 3]); d++; index += 4; } } hasData = true; if (event->key() == Qt::Key_S) { string filename = "exr16f_srcblock_x" + to_string(XBlockNum) + "_y" + to_string(YBlockNum) + ".exr"; Exr::writeRgba(filename, pixels, 4, 4); } } else if (m_OriginalMipImages->mipset->m_ChannelFormat == CF_Float32) { // Get origin data pointer float* data = mipLevel->m_pfData; Array2D<Rgba> pixels(4, 4); pixels.resizeErase(4, 4); int d = 0; for (int row = 0; row < 4; row++) { index = (row * row_stride) + start_index; for (int col = 0; col < 4; col++) { in[d][0] = data[index]; pixels[row][col].r = data[index]; in[d][1] = data[index + 1]; pixels[row][col].g = data[index + 1]; in[d][2] = data[index + 2]; pixels[row][col].b = data[index + 1]; in[d][3] = data[index + 3]; pixels[row][col].a = data[index + 1]; d++; index += 4; } } hasData = true; if (event->key() == Qt::Key_S) { string filename = "exr32f_srcblock_" + to_string(XBlockNum) + "_y" + to_string(YBlockNum) + ".exr"; Exr::writeRgba(filename, pixels, 4, 4); } } else if (m_OriginalMipImages->mipset->m_ChannelFormat == CF_Compressed) { // Get origin data pointer BYTE* data = mipLevel->m_pbData; // set the data offset to the compressed block row,col which is in 16 byte incriments // Note : 16 bytes per block * (Width in pixels / width of block which is 4 ) = 4 * width int cmp_block_offset = 4 * m_OriginalMipImages->mipset->m_nWidth; int offset = (((XBlockNum - 1) * 16)) + ((YBlockNum - 1) * cmp_block_offset); data = data + offset; for (int d = 0; d < 16; d++) { cmp_in[d] = data[d]; } hasData = true; } if (hasData) { // Use SDK interface to Encode a Block for debugging with BC6HBlockEncoder* blockEncode; BYTE output[16]; if (CMP_InitializeBCLibrary() == BC_ERROR_NONE) { CMP_BC6H_BLOCK_PARAMETERS user_settings; user_settings.fQuality = 1.0; user_settings.bUsePatternRec = false; if (m_acImageView->m_debugFormat == "BC6H") user_settings.bIsSigned = false; else user_settings.bIsSigned = true; user_settings.fExposure = 1.00; if (CMP_CreateBC6HEncoder(user_settings, &blockEncode) == BC_ERROR_NONE) { if (m_OriginalMipImages->mipset->m_ChannelFormat != CF_Compressed) { CMP_EncodeBC6HBlock(blockEncode, in, output); // Feed compressed output to be decoded into dec_out CMP_DecodeBC6HBlock(output, dec_out); } else { CMP_DecodeBC6HBlock(cmp_in, dec_out); } CMP_DestroyBC6HEncoder(blockEncode); } CMP_ShutdownBCLibrary(); } } } else if (m_acImageView->m_debugFormat == "BC7") { // Encoder input to fill with data double in[16][4]; double dec_out[16][4]; // Get origin data pointer BYTE* data = mipLevel->m_pbData; int d = 0; for (int row = 0; row < 4; row++) { index = (row * row_stride) + start_index; for (int col = 0; col < 4; col++) { in[d][0] = data[index]; in[d][1] = data[index + 1]; in[d][2] = data[index + 2]; in[d][3] = data[index + 3]; d++; index += 4; } } hasData = true; if (hasData) { // Use SDK interface to Encode a Block for debugging with BC7BlockEncoder* blockEncode; BYTE output[16]; if (CMP_InitializeBCLibrary() == BC_ERROR_NONE) { CMP_BC6H_BLOCK_PARAMETERS user_settings; user_settings.fQuality = 1.0; user_settings.bUsePatternRec = false; user_settings.bIsSigned = false; user_settings.fExposure = 1.00; if (CMP_CreateBC7Encoder(0.05, false, false, 0xCF, 1.0, &blockEncode) == BC_ERROR_NONE) { CMP_EncodeBC7Block(blockEncode, in, output); // Feed compressed output to be decoded into dec_out CMP_DecodeBC7Block(output, dec_out); CMP_DestroyBC7Encoder(blockEncode); } CMP_ShutdownBCLibrary(); } } } } else return; } #endif #endif setActionForImageViewStateChange(); return; } void cpImageView::GetSourceBlock(int BlockX, int BlockY, string filename) { if (!m_CMips) return; if (!m_OriginalMipImages) return; // Compressed source files not supported. if (m_OriginalMipImages->mipset->m_ChannelFormat == CF_Compressed) return; MipLevel* mipLevel = m_CMips->GetMipLevel(m_OriginalMipImages->mipset, m_DepthLevel); if (!mipLevel) return; if (m_acImageView->m_graphicsScene->cursorBlockX != 4) return; if (m_acImageView->m_graphicsScene->cursorBlockY != 4) return; #define CHANNEL_SIZE 4 // 4 channels RGBA #define XBLOCK_SIZE 4 // 4 pixels #define YBLOCK_SIZE 4 // 4 pixels // Calc data stride for each row index = width * num channels int row_stride = m_OriginalMipImages->mipset->m_nWidth * CHANNEL_SIZE; // Start position of the first pixel to save in the 4x4 block int start_index = (BlockX * XBLOCK_SIZE * CHANNEL_SIZE) + (BlockY * row_stride * YBLOCK_SIZE); // Incrimental start pixel index from (row,col = 0) position of each 4x4 block int index; if (m_OriginalMipImages->mipset->m_ChannelFormat == CF_Float16) { // Encoder input to fill with data CMP_FLOAT in[16][4]; // Get origin data pointer CMP_HALFSHORT* data = mipLevel->m_phfsData; CMP_HALF* temp = (CMP_HALF*)data; Array2D<Rgba> pixels(4, 4); pixels.resizeErase(4, 4); int d = 0; for (int row = 0; row < 4; row++) { index = (row * row_stride) + start_index; for (int col = 0; col < 4; col++) { in[d][0] = (float)temp[index]; pixels[row][col].r.setBits(data[index]); in[d][1] = (float)temp[index + 1]; pixels[row][col].g.setBits(data[index + 1]); in[d][2] = (float)temp[index + 2]; pixels[row][col].b.setBits(data[index + 2]); in[d][3] = (float)temp[index + 3]; pixels[row][col].a.setBits(data[index + 3]); d++; index += 4; } } Exr::writeRgba(filename, pixels, 4, 4); } else if (m_OriginalMipImages->mipset->m_ChannelFormat == CF_Float32) { // Encoder input to fill with data CMP_FLOAT in[16][4]; // Get origin data pointer float* data = mipLevel->m_pfData; Array2D<Rgba> pixels(4, 4); pixels.resizeErase(4, 4); int d = 0; for (int row = 0; row < 4; row++) { index = (row * row_stride) + start_index; for (int col = 0; col < 4; col++) { in[d][0] = data[index]; pixels[row][col].r = data[index]; in[d][1] = data[index + 1]; pixels[row][col].g = data[index + 1]; in[d][2] = data[index + 2]; pixels[row][col].b = data[index + 1]; in[d][3] = data[index + 3]; pixels[row][col].a = data[index + 1]; d++; index += 4; } } Exr::writeRgba(filename, pixels, 4, 4); } // else CF_Float3 else { QColor color; QPixmap pixmap(4, 4); QImage image = pixmap.toImage(); CMP_BYTE* data = mipLevel->m_pbData; int d = 0; for (int h = 0; h < 4; h++) { index = (h * row_stride) + start_index; for (int w = 0; w < 4; w++) { color.setRed(data[index]); color.setGreen(data[index + 1]); color.setBlue(data[index + 2]); color.setAlpha(data[index + 3]); image.setPixel(w, h, color.rgba()); d++; index += 4; } } image.save(filename.c_str()); } } void cpImageView::EnableMipLevelDisplay(int level) { if (level <= 1) return; for (int num = 0; num < level; num++) { m_CBimageview_MipLevel->addItem("MipLevel : " + QString::number(num)); } m_CBimageview_MipLevel->setEnabled(true); m_MipLevels = level; } void cpImageView::EnableDepthLevelDisplay(int level) { if (level < 0) return; for (int num = 0; num < level; num++) { m_CBimageview_DepthLevel->addItem("Frames : " + QString::number(num)); } m_CBimageview_DepthLevel->setEnabled(true); m_DepthLevel = level; } cpImageView::~cpImageView() { if (m_ExrProperties) { delete m_ExrProperties; } if (m_localMipImages) { if (m_processedMipImages) m_imageLoader->clearMipImages(&m_processedMipImages); delete m_imageLoader; m_imageLoader = NULL; } if (m_imageLoader) { delete m_imageLoader; m_imageLoader = NULL; } if (m_CMips) { delete m_CMips; m_CMips = NULL; } if (Plastique_style) { delete Plastique_style; Plastique_style = NULL; } } void cpImageView::setActionForImageViewStateChange() { switch (m_ImageViewState) { case eImageViewState::isOriginal: case eImageViewState::isDiff: if (imageview_ResetImageView) imageview_ResetImageView->setEnabled(false); if (imageview_ToggleChannelR) imageview_ToggleChannelR->setEnabled(false); if (imageview_ToggleChannelG) imageview_ToggleChannelG->setEnabled(false); if (imageview_ToggleChannelB) imageview_ToggleChannelB->setEnabled(false); if (imageview_ToggleChannelA) imageview_ToggleChannelA->setEnabled(false); if (imageview_ToggleGrayScale) imageview_ToggleGrayScale->setEnabled(false); if (imageview_InvertImage) imageview_InvertImage->setEnabled(false); if (imageview_MirrorHorizontal) imageview_MirrorHorizontal->setEnabled(false); if (imageview_MirrorVirtical) imageview_MirrorVirtical->setEnabled(false); if (imageview_RotateRight) imageview_RotateRight->setEnabled(false); if (imageview_RotateLeft) imageview_RotateLeft->setEnabled(false); if (m_BrightnessLevel) m_BrightnessLevel->setEnabled(false); if (m_CBimageview_ToolList) m_CBimageview_ToolList->setEnabled(false); if (m_ExrProperties) { if (m_ExrProperties->isVisible()) m_ExrProperties->hide(); } break; case eImageViewState::isProcessed: if (imageview_ResetImageView) imageview_ResetImageView->setEnabled(true); if (imageview_ToggleChannelR) imageview_ToggleChannelR->setEnabled(true); if (imageview_ToggleChannelG) imageview_ToggleChannelG->setEnabled(true); if (imageview_ToggleChannelB) imageview_ToggleChannelB->setEnabled(true); if (imageview_ToggleChannelA) imageview_ToggleChannelA->setEnabled(true); if (imageview_ToggleGrayScale) imageview_ToggleGrayScale->setEnabled(true); if (imageview_InvertImage) imageview_InvertImage->setEnabled(true); if (imageview_MirrorHorizontal) imageview_MirrorHorizontal->setEnabled(true); if (imageview_MirrorVirtical) imageview_MirrorVirtical->setEnabled(true); if (imageview_RotateRight) imageview_RotateRight->setEnabled(true); if (imageview_RotateLeft) imageview_RotateLeft->setEnabled(true); if (m_BrightnessLevel) m_BrightnessLevel->setEnabled(true); if (m_CBimageview_ToolList) m_CBimageview_ToolList->setEnabled(true); break; } } void cpImageView::InitData() { m_imageSize = {0, 0}; ID = 0; m_localMipImages = false; m_MipLevels = 0; m_DepthLevel = 0; m_MaxDepthLevel = 1; m_FitOnShow = true; m_imageLoader = NULL; m_acImageView = NULL; m_processedMipImages = NULL; m_newWidget = NULL; m_layout = NULL; m_parent = NULL; m_button2 = NULL; m_button = NULL; m_toolBar = NULL; m_statusBar = NULL; m_buttonNavigate = NULL; m_labelColorTxt = NULL; m_labelColorRGBA = NULL; m_labelPos = NULL; m_labelBlockPos = NULL; m_pMyWidget = NULL; m_pixmap = NULL; imageview_ResetImageView = NULL; imageview_ToggleChannelR = NULL; imageview_ToggleChannelG = NULL; imageview_ToggleChannelB = NULL; imageview_ToggleChannelA = NULL; imageview_ToggleGrayScale = NULL; imageview_InvertImage = NULL; imageview_MirrorHorizontal = NULL; imageview_MirrorVirtical = NULL; imageview_RotateRight = NULL; imageview_RotateLeft = NULL; imageview_ZoomIn = NULL; imageview_ZoomOut = NULL; imageview_ViewImageOriginalSize = NULL; imageview_FitInWindow = NULL; imageview_ImageDiff = NULL; m_CBimageview_GridBackground = NULL; m_CBimageview_ToolList = NULL; m_CBimageview_MipLevel = NULL; m_CBimageview_DepthLevel = NULL; m_CBimage_DecompressUsing = NULL; m_ExrProperties = NULL; m_OriginalMipImages = NULL; m_bOnacScaleChange = false; m_useOriginalImageCursor = false; XBlockNum = 1; YBlockNum = 1; m_source_BlockXPos = 1; m_source_BlockYPos = 1; m_DiffOnOff = false; m_ImageViewState = eImageViewState::isProcessed; } cpImageView::cpImageView(const QString filePathName, const QString Title, QWidget* parent, CMipImages* MipImages, Setting* setting, CMipImages* CompressedMipImages) : acCustomDockWidget(filePathName, parent) { if (!setting) return; InitData(); m_parent = parent; m_fileName = filePathName; m_setting = *setting; m_localMipImages = false; // Flags if we used our own MipImage and not from parameter m_CBimageview_MipLevel = NULL; m_CBimageview_DepthLevel = NULL; m_CMips = new CMIPS(); Plastique_style = QStyleFactory::create("Plastique"); getSupportedImageFormats(); if (MipImages) { if (setting->reloadImage && !setting->generateDiff && !setting->generateMips) { m_imageLoader = new CImageLoader(); if (m_imageLoader) { m_processedMipImages = m_imageLoader->LoadPluginImage(filePathName.toStdString()); } } else m_processedMipImages = MipImages; } else { m_imageLoader = new CImageLoader(); if (m_imageLoader) { m_processedMipImages = m_imageLoader->LoadPluginImage(filePathName.toStdString()); m_localMipImages = true; } else m_processedMipImages = NULL; } // if our current image is compressed, Are we suppiled with a pointer to its uncomprssed source image miplevels // else we just use the current miplevels, this pointer can be either compressed or uncompressed data // check its MIPIMAGE_FORMAT property to determine which one it is if (CompressedMipImages) { if (CompressedMipImages->mipset) { m_CompressedMipImages = CompressedMipImages->mipset->m_compressed; } else { m_CompressedMipImages = true; } m_OriginalMipImages = CompressedMipImages; m_ImageViewState = eImageViewState::isProcessed; } else { m_CompressedMipImages = false; m_OriginalMipImages = m_processedMipImages; m_ImageViewState = eImageViewState::isOriginal; } QFile f(filePathName); QFileInfo fileInfo(f.fileName()); m_tabName = fileInfo.fileName(); setWindowTitle(m_tabName); this->m_CustomTitle = Title; custTitleBar->setTitle(m_CustomTitle); custTitleBar->setToolTip(filePathName); //=============== // Center Widget //=============== m_newWidget = new QWidget(parent); if (!m_newWidget) { // ToDo::Need to process error! return; } //=================== // Get MipLevels //=================== if (m_processedMipImages) { if (m_processedMipImages->mipset) { m_MipLevels = m_processedMipImages->mipset->m_nMipLevels; m_MaxDepthLevel = m_processedMipImages->mipset->m_nDepth; // check levels with number of images to view //if (m_processedMipImages->m_MipImageFormat == MIPIMAGE_FORMAT::Format_QImage) //{ int count = (int)m_processedMipImages->QImage_list[0].size(); if (count <= 1) { m_MipLevels = 0; } //} } } else { m_MipLevels = 0; m_DepthLevel = 0; } //================================ // Image/Texture Viewer Component //================================ if (m_CompressedMipImages) m_acImageView = new acImageView(filePathName, this, NULL, m_processedMipImages); else m_acImageView = new acImageView(filePathName, this, m_OriginalMipImages, m_processedMipImages); m_viewContextMenu = new QMenu(m_acImageView); // Image View Context Menu Item m_acImageView->setContextMenuPolicy(Qt::CustomContextMenu); connect(m_acImageView, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(onViewCustomContextMenu(const QPoint&))); actSaveView = new QAction("Save View as...", this); connect(actSaveView, SIGNAL(triggered()), this, SLOT(onSaveViewAs())); m_viewContextMenu->addAction(actSaveView); actSaveBlockView = new QAction(" ", this); // Text for this action item is auto set prior to context menu view connect(actSaveBlockView, SIGNAL(triggered()), this, SLOT(onSaveBlockView())); m_viewContextMenu->addAction(actSaveBlockView); if (Title.contains("File#")) { custTitleBar->setTitle(Title + ": " + filePathName); } else { // Need to check if MipImages is valid here!! if (m_processedMipImages) { QString gpuView = ""; bool useGPUView = false; switch (m_processedMipImages->m_DecompressedFormat) { case MIPIMAGE_FORMAT_DECOMPRESSED::Format_CPU: custTitleBar->setTitle("Compressed Image: CPU View"); break; case MIPIMAGE_FORMAT_DECOMPRESSED::Format_GPU: useGPUView = true; gpuView = "Compressed Image: GPU View "; break; default: case MIPIMAGE_FORMAT_DECOMPRESSED::Format_NONE: break; } if (useGPUView) { switch (m_processedMipImages->m_MipImageFormat) { case MIPIMAGE_FORMAT::Format_OpenGL: gpuView += "using OpenGL"; custTitleBar->setTitle(gpuView); break; case MIPIMAGE_FORMAT::Format_DirectX: gpuView += "using DirectX"; custTitleBar->setTitle(gpuView); break; case MIPIMAGE_FORMAT::Format_Vulkan: gpuView += "using Vulkan"; custTitleBar->setTitle(gpuView); break; default: custTitleBar->setTitle(gpuView); break; } } } } if (m_acImageView->m_graphicsScene) { ID = m_acImageView->m_graphicsScene->ID; m_imageSize = m_acImageView->m_MipImages->QImage_list[0].front()->size(); m_acImageView->enableNavigation(true); connect(m_acImageView, SIGNAL(acImageViewMousePosition(QPointF*, QPointF*, int)), this, SLOT(oncpImageViewMousePosition(QPointF*, QPointF*, int))); connect(m_acImageView, SIGNAL(acImageViewVirtualMousePosition(QPointF*, QPointF*, int)), this, SLOT(oncpImageViewVirtualMousePosition(QPointF*, QPointF*, int))); connect(custTitleBar, SIGNAL(ToolBarCliked()), this, SLOT(OnToolBarClicked())); } // //=============== // // Virtual mouse with block // //=============== // connect(this->m_acImageView, SIGNAL(acImageViewMousePosition(QPointF *, QPointF *, int)), &m_customMouse, SLOT(onVirtualMouseMoveEvent(QPointF *, QPointF *, int))); // connect(&m_customMouse, SIGNAL(VirtialMousePosition(QPointF*, QPointF*, int)), this->m_acImageView, SLOT(onVirtualMouseMoveEvent(QPointF*, QPointF*, int))); //=============== // Tool Bar //=============== m_toolBar = new QToolBar("Tools"); m_toolBar->setStyleSheet("QToolBar{spacing: 0px;} QToolButton {width:15px;} "); m_toolBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); // Grid Background QLabel* GridLabel = new QLabel(this); GridLabel->setText("Grid:"); //GridLabel->setMinimumWidth(15); //GridLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); m_toolBar->addWidget(GridLabel); m_CBimageview_GridBackground = new QComboBox(this); m_CBimageview_GridBackground->addItem(tr("ChkBox")); m_CBimageview_GridBackground->addItem(tr("Black")); m_CBimageview_GridBackground->addItem(tr("Lines")); m_CBimageview_GridBackground->addItem(tr("Points")); m_CBimageview_GridBackground->setStyle(Plastique_style); //m_CBimageview_GridBackground->setMinimumWidth(15); //m_CBimageview_GridBackground->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); // http://blog.qt.io/blog/2012/10/30/cleaning-up-styles-in-qt5-and-adding-fusion/ //m_CBimageview_GridBackground->setStyleSheet("QComboBox { border: 1px solid gray; border - radius: 3px; padding: 1px 18px 1px 3px; min - width: 6em; }"); //m_CBimageview_GridBackground->setStyleSheet("QComboBox::drop-down {subcontrol-origin: padding; subcontrol-position: top right; width: 15px; border-left-width: 1px; border-left-color: darkgray; border-left-style: solid; border-top-right-radius: 3px; border-bottom-right-radius: 3px; }"); connect(m_CBimageview_GridBackground, SIGNAL(currentIndexChanged(int)), m_acImageView, SLOT(onGridBackground(int))); int i = m_CBimageview_GridBackground->findText("ChkBox"); m_CBimageview_GridBackground->setCurrentIndex(i); m_toolBar->addWidget(m_CBimageview_GridBackground); m_toolBar->addSeparator(); // Zoom level m_ZoomLevel = new QSpinBox(this); if (m_ZoomLevel) { QLabel* ZoomLabel = new QLabel(this); ZoomLabel->setText("Zoom:"); m_toolBar->addWidget(ZoomLabel); connect(m_ZoomLevel, SIGNAL(valueChanged(int)), this, SLOT(onZoomLevelChanged(int))); connect(this, SIGNAL(OnSetScale(int)), m_acImageView, SLOT(onSetScale(int))); connect(m_acImageView, SIGNAL(acScaleChanged(int)), this, SLOT(onacScaleChange(int))); connect(m_acImageView, SIGNAL(acPSNRUpdated(double)), this, SLOT(onacPSNRUpdated(double))); m_ZoomLevel->setRange(AC_IMAGE_MIN_ZOOM, AC_IMAGE_MAX_ZOOM); m_ZoomLevel->setSingleStep(10); m_ZoomLevel->setValue(100); m_toolBar->addWidget(m_ZoomLevel); } //always enable brightness icons in gui and cursor indicates original RGBA data this->m_useOriginalImageCursor = true; setting->onBrightness = true; m_BrightnessLevel = new QSpinBox(this); if (m_BrightnessLevel) { QLabel* ZoomLabel = new QLabel(this); ZoomLabel->setText(" Brightness:"); m_toolBar->addWidget(ZoomLabel); connect(m_BrightnessLevel, SIGNAL(valueChanged(int)), this, SLOT(onBrightnessLevelChanged(int))); m_BrightnessLevel->setRange(-100, 100); m_BrightnessLevel->setSingleStep(1); m_BrightnessLevel->setValue(0); m_toolBar->addWidget(m_BrightnessLevel); } imageview_ViewImageOriginalSize = new QAction(QIcon(":/compressonatorgui/images/cx100.png"), tr("Original Size"), this); if (imageview_ViewImageOriginalSize) { m_toolBar->addAction(imageview_ViewImageOriginalSize); connect(imageview_ViewImageOriginalSize, SIGNAL(triggered()), m_acImageView, SLOT(onViewImageOriginalSize())); } imageview_FitInWindow = new QAction(QIcon(":/compressonatorgui/images/cxfit.png"), tr("&Fit in Window"), this); if (imageview_FitInWindow) { m_toolBar->addAction(imageview_FitInWindow); connect(imageview_FitInWindow, SIGNAL(triggered()), m_acImageView, SLOT(onFitInWindow())); } imageview_ResetImageView = new QAction(QIcon(":/compressonatorgui/images/originalimage.png"), tr("Reset Image View"), this); if (imageview_ResetImageView) { m_toolBar->addAction(imageview_ResetImageView); connect(imageview_ResetImageView, SIGNAL(triggered()), m_acImageView, SLOT(onResetImageView())); connect(imageview_ResetImageView, SIGNAL(triggered()), this, SLOT(oncpResetImageView())); } m_toolBar->addSeparator(); imageview_ToggleChannelR = new QAction(QIcon(":/compressonatorgui/images/cxred.png"), tr("Show or Hide Red channel"), this); if (imageview_ToggleChannelR) { imageview_ToggleChannelR->setCheckable(true); m_toolBar->addAction(imageview_ToggleChannelR); connect(imageview_ToggleChannelR, SIGNAL(triggered()), m_acImageView, SLOT(onToggleChannelR())); } imageview_ToggleChannelG = new QAction(QIcon(":/compressonatorgui/images/cxgreen.png"), tr("Show or Hide Green channel"), this); if (imageview_ToggleChannelG) { imageview_ToggleChannelG->setCheckable(true); m_toolBar->addAction(imageview_ToggleChannelG); connect(imageview_ToggleChannelG, SIGNAL(triggered()), m_acImageView, SLOT(onToggleChannelG())); } imageview_ToggleChannelB = new QAction(QIcon(":/compressonatorgui/images/cxblue.png"), tr("Show or Hide Blue channel"), this); if (imageview_ToggleChannelB) { imageview_ToggleChannelB->setCheckable(true); m_toolBar->addAction(imageview_ToggleChannelB); connect(imageview_ToggleChannelB, SIGNAL(triggered()), m_acImageView, SLOT(onToggleChannelB())); } imageview_ToggleChannelA = new QAction(QIcon(":/compressonatorgui/images/cxalpha.png"), tr("Show or Hide Alpha channel"), this); if (imageview_ToggleChannelA) { imageview_ToggleChannelA->setCheckable(true); m_toolBar->addAction(imageview_ToggleChannelA); connect(imageview_ToggleChannelA, SIGNAL(triggered()), m_acImageView, SLOT(onToggleChannelA())); } m_toolBar->addSeparator(); imageview_ToggleGrayScale = new QAction(QIcon(":/compressonatorgui/images/cxgrayscale.png"), tr("Gray Scale"), this); if (imageview_ToggleGrayScale) { imageview_ToggleGrayScale->setCheckable(true); m_toolBar->addAction(imageview_ToggleGrayScale); connect(imageview_ToggleGrayScale, SIGNAL(triggered()), m_acImageView, SLOT(onToggleGrayScale())); } imageview_InvertImage = new QAction(QIcon(":/compressonatorgui/images/cxinvert.png"), tr("Invert Image"), this); if (imageview_InvertImage) { m_toolBar->addAction(imageview_InvertImage); connect(imageview_InvertImage, SIGNAL(triggered()), m_acImageView, SLOT(onInvertImage())); } imageview_MirrorHorizontal = new QAction(QIcon(":/compressonatorgui/images/mirrorhorizonal.png"), tr("Mirror Image Horizontally"), this); if (imageview_MirrorHorizontal) { m_toolBar->addAction(imageview_MirrorHorizontal); connect(imageview_MirrorHorizontal, SIGNAL(triggered()), m_acImageView, SLOT(onMirrorHorizontal())); } imageview_MirrorVirtical = new QAction(QIcon(":/compressonatorgui/images/mirrorvertical.png"), tr("Mirror Image Vertically"), this); if (imageview_MirrorVirtical) { m_toolBar->addAction(imageview_MirrorVirtical); connect(imageview_MirrorVirtical, SIGNAL(triggered()), m_acImageView, SLOT(onMirrorVirtical())); } imageview_RotateRight = new QAction(QIcon(":/compressonatorgui/images/cxrotationr.png"), tr("Rotate Image 90 Degrees"), this); if (imageview_RotateRight) { m_toolBar->addAction(imageview_RotateRight); connect(imageview_RotateRight, SIGNAL(triggered()), m_acImageView, SLOT(onRotateRight())); } imageview_RotateLeft = new QAction(QIcon(":/compressonatorgui/images/cxrotationl.png"), tr("Rotate Image -90 Degrees"), this); if (imageview_RotateLeft) { m_toolBar->addAction(imageview_RotateLeft); connect(imageview_RotateLeft, SIGNAL(triggered()), m_acImageView, SLOT(onRotateLeft())); } if (m_MaxDepthLevel > 1) { m_toolBar->addSeparator(); QLabel* MDepthLevelLabel = new QLabel(this); MDepthLevelLabel->setText("Frame:"); m_toolBar->addWidget(MDepthLevelLabel); m_CBimageview_DepthLevel = new QComboBox(this); for (int num = 0; num < m_MaxDepthLevel; num++) { QString depthLevelList = QString::number(num + 1); m_CBimageview_DepthLevel->addItem(depthLevelList); } connect(m_CBimageview_DepthLevel, SIGNAL(currentIndexChanged(int)), m_acImageView, SLOT(onImageDepthChanged(int))); m_toolBar->addWidget(m_CBimageview_DepthLevel); } if (m_MipLevels > 0) { m_toolBar->addSeparator(); QLabel* MipLevelLabel = new QLabel(this); MipLevelLabel->setText("MipLevel:"); m_toolBar->addWidget(MipLevelLabel); m_CBimageview_MipLevel = new QComboBox(this); int processedImage_miplevel_max = (int)m_processedMipImages->QImage_list[0].size(); // check if we have miplevels in Original Image if its available match its level with the processed if (m_OriginalMipImages && (setting->input_image == eImageViewState::isProcessed)) { if (m_OriginalMipImages->QImage_list[0].size() < processedImage_miplevel_max) { // Remove this // QMessageBox msgBox; // QMessageBox::warning(this, // "MipLevel", // "Original image MipMap Levels do not match the Processed image levels.\nLevels will be limited, retry by regenerating " // "original image mip levels", // QMessageBox::Ok); processedImage_miplevel_max = (int)m_OriginalMipImages->QImage_list[0].size(); } } for (int num = 0; num < m_MipLevels; num++) { if (m_processedMipImages) { if (processedImage_miplevel_max > num) { QString mipLevelList = QString::number(num + 1); QImage* image = m_processedMipImages->QImage_list[0][num]; mipLevelList.append(QString(" (")); mipLevelList.append(QString::number(image->width())); mipLevelList.append(QString("x")); mipLevelList.append(QString::number(image->height())); mipLevelList.append(QString(")")); m_CBimageview_MipLevel->addItem(mipLevelList); } } } //m_CBimageview_MipLevel->setStyleSheet("QComboBox { border: 1px solid gray; border - radius: 3px; padding: 1px 18px 1px 3px; min - width: 6em; }"); connect(m_CBimageview_MipLevel, SIGNAL(currentIndexChanged(int)), m_acImageView, SLOT(onImageMipLevelChanged(int))); connect(m_CBimageview_MipLevel, SIGNAL(currentIndexChanged(int)), this, SLOT(onResetHDRandDiff(int))); m_toolBar->addWidget(m_CBimageview_MipLevel); } m_toolBar->addSeparator(); if (setting->input_image == eImageViewState::isProcessed) { // This combo box is used as one of two methods to changes image view states, the other is user keypress m_CBimageview_Toggle = new QComboBox(this); if (m_CBimageview_Toggle) { m_CBimageview_Toggle->addItem(tr(TXT_IMAGE_PROCESSED)); m_CBimageview_Toggle->addItem(tr(TXT_IMAGE_ORIGINAL)); connect(m_CBimageview_Toggle, SIGNAL(currentIndexChanged(int)), this, SLOT(onToggleViewChanged(int))); m_CBimageview_Toggle->setToolTip(tr("Switch views to 'Processed' or 'Original' Image [can use 'p','o' or 'space bar' to toggles views")); m_toolBar->addWidget(m_CBimageview_Toggle); } imageview_ImageDiff = new QAction(QIcon(":/compressonatorgui/images/imagediff.png"), tr("&View Image Diff [can use 'd' key to toggle on or off]"), this); if (imageview_ImageDiff) { m_toolBar->addAction(imageview_ImageDiff); connect(imageview_ImageDiff, SIGNAL(triggered()), this, SLOT(onImageDiff())); } m_toolBar->addSeparator(); } else m_CBimageview_Toggle = NULL; #ifdef USE_BCN_IMAGE_DEBUG #ifdef _DEBUG // Debug Checkbox m_CBimageview_Debug = new QComboBox(this); m_CBimageview_Debug->addItem(tr("Debug...")); m_CBimageview_Debug->addItem(tr("BC6H")); m_CBimageview_Debug->addItem(tr("BC6H_SF")); m_CBimageview_Debug->addItem(tr("BC7")); m_toolBar->addWidget(m_CBimageview_Debug); connect(m_CBimageview_Debug, SIGNAL(activated(int)), m_acImageView, SLOT(onToggleDebugChanged(int))); m_toolBar->addSeparator(); #endif #endif if (m_processedMipImages && (m_processedMipImages->mipset != NULL)) { if (m_processedMipImages->mipset->m_format == CMP_FORMAT_ARGB_32F || (m_processedMipImages->mipset->m_format == CMP_FORMAT_ARGB_16F) || (m_processedMipImages->mipset->m_format == CMP_FORMAT_RGBE_32F) || (m_processedMipImages->mipset->m_format == CMP_FORMAT_BC6H) || (m_processedMipImages->mipset->m_format == CMP_FORMAT_BC6H_SF)) { m_ExrProperties = new acEXRTool(); // Tool list QLabel* GridLabel = new QLabel(this); GridLabel->setText(""); m_toolBar->addWidget(GridLabel); m_CBimageview_ToolList = new QComboBox(this); m_CBimageview_ToolList->addItem(tr("View...")); m_CBimageview_ToolList->addItem(tr("HDR Properties")); m_CBimageview_ToolList->setStyle(Plastique_style); m_toolBar->addWidget(m_CBimageview_ToolList); connect(m_CBimageview_ToolList, SIGNAL(activated(int)), this, SLOT(onToolListChanged(int))); if (m_ExrProperties) { connect(m_ExrProperties->exrExposureBox, SIGNAL(valueChanged(double)), m_acImageView, SLOT(onExrExposureChanged(double))); connect(m_ExrProperties->exrDefogBox, SIGNAL(valueChanged(double)), m_acImageView, SLOT(onExrDefogChanged(double))); connect(m_ExrProperties->exrKneeLowBox, SIGNAL(valueChanged(double)), m_acImageView, SLOT(onExrKneeLowChanged(double))); connect(m_ExrProperties->exrKneeHighBox, SIGNAL(valueChanged(double)), m_acImageView, SLOT(onExrKneeHighChanged(double))); connect(m_ExrProperties->exrGammaBox, SIGNAL(valueChanged(double)), m_acImageView, SLOT(onExrGammaChanged(double))); } } } #ifdef USE_INTERNAL_DECOMPRESS // This code may not be usable as decompression can be done // outside of this class, The decompressed images are also // used to calculate the statistics of image diff m_CBimage_DecompressUsing = new QComboBox(this); m_CBimage_DecompressUsing->addItem("View: CPU"); m_CBimage_DecompressUsing->addItem("View: OpenGL"); m_CBimage_DecompressUsing->setStyleSheet("QComboBox { border: 1px solid gray; border - radius: 3px; padding: 1px 18px 1px 3px; min - width: 6em; }"); connect(m_CBimage_DecompressUsing, SIGNAL(currentIndexChanged(int)), this, SLOT(onDecompressUsing(int))); m_toolBar->addWidget(m_CBimageview_MipLevel); #endif // IF we have processed images then enable PSNR view to user if (m_processedMipImages->decompressedMipSet != NULL) { m_PSNRLabel = new QLabel(this); if (m_PSNRLabel) { m_PSNRLabel->setText("PSNR: Not Available"); m_toolBar->addWidget(m_PSNRLabel); } } else m_PSNRLabel = NULL; m_toolBar->setMaximumHeight(25); m_toolBar->hide(); QHBoxLayout* hlayout2 = new QHBoxLayout; hlayout2->setSpacing(0); hlayout2->setMargin(0); hlayout2->setContentsMargins(0, 0, 0, 0); hlayout2->addWidget(m_toolBar, 0); QString Navigation = QStringLiteral(":/compressonatorgui/images/navigate.png"); m_statusBar = new QStatusBar(this); m_statusBar->setStyleSheet("QStatusBar{border-top: 1px outset grey; border-bottom: 1px outset grey;}"); m_labelColorRGBA = new QLabel(this); m_labelColorRGBA->setAlignment(Qt::AlignLeft); m_labelColorRGBA->setAutoFillBackground(true); QPalette sample_palette; sample_palette.setColor(QPalette::Window, Qt::black); sample_palette.setColor(QPalette::WindowText, Qt::black); m_labelColorRGBA->setPalette(sample_palette); m_labelColorRGBA->setText("RGBA"); m_labelColorTxt = new QLabel(this); m_labelColorTxt->setText("0,0,0,0"); m_labelColorTxt->setAlignment(Qt::AlignLeft); m_labelPos = new QLabel(this); m_labelPos->setText(""); m_labelPos->setAlignment(Qt::AlignLeft); m_labelBlockPos = new QLabel(this); m_labelBlockPos->setText(""); m_labelBlockPos->setAlignment(Qt::AlignLeft); m_labelTxtView = new QLabel(this); switch (setting->input_image) { case eImageViewState::isOriginal: m_ImageViewState = eImageViewState::isOriginal; m_labelTxtView->setText(TXT_IMAGE_ORIGINAL); break; case eImageViewState::isDiff: m_ImageViewState = eImageViewState::isDiff; // Set a default Contrast for image diff views if (m_acImageView) { if (m_acImageView->m_imageItem_Processed) { m_acImageView->m_imageItem_Processed->m_fContrast = g_Application_Options.m_imagediff_contrast; m_acImageView->setBrightnessLevel(0); } } m_labelTxtView->setText(TXT_IMAGE_DIFF); setActionForImageViewStateChange(); break; case eImageViewState::isProcessed: m_ImageViewState = eImageViewState::isProcessed; m_labelTxtView->setText(TXT_IMAGE_PROCESSED); break; } m_labelTxtView->setAlignment(Qt::AlignLeft); m_statusBar->addPermanentWidget(m_labelColorRGBA); m_statusBar->addPermanentWidget(m_labelTxtView, 10); m_statusBar->addPermanentWidget(m_labelColorTxt, 40); m_statusBar->addPermanentWidget(m_labelPos, 40); m_statusBar->addPermanentWidget(m_labelBlockPos, 20); m_layout = new QGridLayout(m_newWidget); m_layout->setSpacing(0); m_layout->setMargin(0); m_layout->setContentsMargins(0, 0, 0, 0); m_layout->addLayout(hlayout2, 0, 0); m_layout->addWidget(m_acImageView, 1, 0); m_layout->addWidget(m_statusBar, 2, 0); m_newWidget->setLayout(m_layout); setWidget(m_newWidget); // Process any quality stats m_acImageView->processPSNR(); } // User selected a view from drop down combo box or called from a key event void cpImageView::onToggleViewChanged(int view) { if (!m_CBimageview_Toggle) return; QString itemView = m_CBimageview_Toggle->itemText(view); if (itemView.compare(TXT_IMAGE_PROCESSED) == 0) { m_ImageViewState = eImageViewState::isProcessed; m_labelTxtView->setText(TXT_IMAGE_PROCESSED); } else if (itemView.compare(TXT_IMAGE_DIFF) == 0) { m_ImageViewState = eImageViewState::isDiff; m_labelTxtView->setText(TXT_IMAGE_DIFF); } else if (itemView.compare(TXT_IMAGE_ORIGINAL) == 0) { m_ImageViewState = eImageViewState::isOriginal; m_labelTxtView->setText(TXT_IMAGE_ORIGINAL); } else { // send an error message ... return; } setActionForImageViewStateChange(); // acImage view has two states 0 = Processed and 1 = Original if (m_acImageView) m_acImageView->onToggleImageViews(view); } void cpImageView::oncpResetImageView() { imageview_ToggleChannelR->setChecked(false); imageview_ToggleChannelG->setChecked(false); imageview_ToggleChannelB->setChecked(false); imageview_ToggleChannelA->setChecked(false); imageview_ToggleGrayScale->setCheckable(false); onResetHDRandDiff(0); m_BrightnessLevel->setValue(0); } void cpImageView::onDecompressUsing(int useDecomp) { Q_UNUSED(useDecomp); } void cpImageView::onResetHDRandDiff(int MipLevel) { // on a MipLevel Change Diff views are reset back to processed views // Makesure the text in the image view ComboBox lable is "Processed" if (MipLevel > 0) { if (m_CBimageview_Toggle) { if (m_ImageViewState == eImageViewState::isDiff) { onImageDiff(); } } } if (m_ExrProperties) { if (m_ExrProperties->isVisible()) m_ExrProperties->hide(); m_ExrProperties->exrExposureBox->setValue(DEFAULT_EXPOSURE); m_ExrProperties->exrDefogBox->setValue(DEFAULT_DEFOG); m_ExrProperties->exrKneeLowBox->setValue(DEFAULT_KNEELOW); m_ExrProperties->exrKneeHighBox->setValue(DEFAULT_KNEEHIGH); m_ExrProperties->exrGammaBox->setValue(DEFAULT_GAMMA); } } void cpImageView::onToolListChanged(int index) { switch (index) { case 1: //EXR if (m_ExrProperties) { if (m_ExrProperties->isVisible()) m_ExrProperties->raise(); else m_ExrProperties->show(); } break; default: if (m_ExrProperties) m_ExrProperties->hide(); break; } } void cpImageView::onViewCustomContextMenu(const QPoint& point) { if (actSaveBlockView) { QString strSaveBlock; strSaveBlock.sprintf("Save Source Block (%d,%d) as", m_source_BlockXPos, m_source_BlockYPos); actSaveBlockView->setText(strSaveBlock); } m_viewContextMenu->exec(m_acImageView->mapToGlobal(point)); } void cpImageView::onSaveViewAs() { if (m_acImageView && actSaveBlockView) { QString ImageFilter; ImageFilter = m_QtImageFilter; bool hasFloatData = false; // Add EXR if source is HDR if (m_processedMipImages) { if ((m_processedMipImages->mipset->m_ChannelFormat == CF_Float16) || (m_processedMipImages->mipset->m_ChannelFormat == CF_Float32)) { ImageFilter.insert(ImageFilter.length() - 1, "*.exr;"); } } if (!hasFloatData) ImageFilter.insert(ImageFilter.length() - 1, "*.bmp;"); QFileInfo fileInfo(m_fileName); QDir dir(fileInfo.absoluteDir()); QString SuggetedFileNamePath; SuggetedFileNamePath = dir.absolutePath(); SuggetedFileNamePath.append("/"); SuggetedFileNamePath.append(fileInfo.baseName()); // Set suggested file target type if (hasFloatData) { SuggetedFileNamePath.append("_view.dds"); } else SuggetedFileNamePath.append("_view.bmp"); std::string ext; QString filePathName; bool done = false; do { filePathName = QFileDialog::getSaveFileName(this, tr("Save Image View as"), SuggetedFileNamePath, ImageFilter); if (filePathName.length() == 0) return; ext = CMP_GetFilePathExtension(filePathName.toStdString()); transform(ext.begin(), ext.end(), ext.begin(), ::tolower); string supported_ExtListings = ImageFilter.toStdString(); if (supported_ExtListings.find(ext) != std::string::npos) { done = true; } else { if (QMessageBox::question(this, "Save Image View", "File extension is not supported try again?", QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) return; } } while (!done); // get file extension to choose for Qt file or Compressonator File save using .dds,.ktx or .exr plugins if ((ext.compare("exr") == 0) || (ext.compare("dds") == 0) || (ext.compare("ktx") == 0) || (ext.compare("ktx2") == 0)) { int mipLevel = 0; if (m_CBimageview_MipLevel) { mipLevel = m_CBimageview_MipLevel->currentIndex(); } int depthLevel = 0; if (m_CBimageview_DepthLevel) { depthLevel = m_CBimageview_DepthLevel->currentIndex(); } if (m_processedMipImages && hasFloatData) { if (mipLevel > 0) { MipLevel* pInMipLevel = m_CMips->GetMipLevel(m_processedMipImages->mipset, mipLevel, depthLevel); if (pInMipLevel == NULL) { PrintInfo("Error: MipLevel Data failed to retrieved."); return; } // Create a temporary mipset for saving the miplevel data MipSet* pMipLevelMipSet; pMipLevelMipSet = new MipSet(); if (pMipLevelMipSet == NULL) { PrintInfo("Error: Failed to allocate mipset for saving."); return; } memset(pMipLevelMipSet, 0, sizeof(MipSet)); // Set the channel formats and mip levels pMipLevelMipSet->m_ChannelFormat = m_processedMipImages->mipset->m_ChannelFormat; pMipLevelMipSet->m_TextureDataType = m_processedMipImages->mipset->m_TextureDataType; pMipLevelMipSet->m_dwFourCC = m_processedMipImages->mipset->m_dwFourCC; pMipLevelMipSet->m_dwFourCC2 = m_processedMipImages->mipset->m_dwFourCC2; pMipLevelMipSet->m_TextureType = m_processedMipImages->mipset->m_TextureType; pMipLevelMipSet->m_nWidth = m_processedMipImages->QImage_list[0][mipLevel]->width(); pMipLevelMipSet->m_nHeight = m_processedMipImages->QImage_list[0][mipLevel]->height(); pMipLevelMipSet->m_nDepth = m_processedMipImages->mipset->m_nDepth; // depthsupport if (pMipLevelMipSet->m_nDepth == 0) pMipLevelMipSet->m_nDepth = 1; // Allocate default MipSet header m_CMips->AllocateMipSet(pMipLevelMipSet, pMipLevelMipSet->m_ChannelFormat, pMipLevelMipSet->m_TextureDataType, pMipLevelMipSet->m_TextureType, m_processedMipImages->QImage_list[0][mipLevel]->width(), m_processedMipImages->QImage_list[0][mipLevel]->height(), pMipLevelMipSet->m_nDepth); // Determin buffer size and set Mip Set Levels we want to use for now MipLevel* mipLevelInfo = m_CMips->GetMipLevel(pMipLevelMipSet, mipLevel, depthLevel); pMipLevelMipSet->m_nMipLevels = 1; m_CMips->AllocateMipLevelData(mipLevelInfo, pMipLevelMipSet->m_nWidth, pMipLevelMipSet->m_nHeight, pMipLevelMipSet->m_ChannelFormat, pMipLevelMipSet->m_TextureDataType); // We have allocated a data buffer to fill get its referance mipLevelInfo->m_pbData = pInMipLevel->m_pbData; AMDSaveMIPSTextureImage(filePathName.toStdString().c_str(), pMipLevelMipSet, false, g_CmdPrams.CompressOptions); // delete the temporary mipset used for saving delete pMipLevelMipSet; } else AMDSaveMIPSTextureImage(filePathName.toStdString().c_str(), m_processedMipImages->mipset, false, g_CmdPrams.CompressOptions); } else { if (m_OriginalMipImages) { AMDSaveMIPSTextureImage(filePathName.toStdString().c_str(), m_OriginalMipImages->mipset, false, g_CmdPrams.CompressOptions); } } } else { QPixmap pixmap = m_acImageView->m_imageItem_Processed->pixmap(); QImage img = pixmap.toImage(); img.save(filePathName); } } } void cpImageView::getSupportedImageFormats() { m_QtImageFilter = "Images ("; #ifdef USE_SaveViewAs_ALL_FILE_FORMATS // Get a list of all Supported file formats from Qt Plugins QList<QByteArray> QtFormats = QImageReader::supportedImageFormats(); // Upppercase List QList<QByteArray>::Iterator i; for (i = QtFormats.begin(); i != QtFormats.end(); ++i) { QByteArray fformat = (*i); fformat = fformat.toUpper(); m_QtImageFilter.append("*."); m_QtImageFilter.append(fformat); m_QtImageFilter.append(";"); } // Add DDS and KTX m_QtImageFilter.append("*.dds;*.ktx;"); #else m_QtImageFilter.append("*.dds;"); #endif m_QtImageFilter.append(")"); } void cpImageView::onSaveBlockView() { if (m_acImageView && m_OriginalMipImages) { QString ImageFilter; if ((m_OriginalMipImages->mipset->m_ChannelFormat == CF_Float16) || (m_OriginalMipImages->mipset->m_ChannelFormat == CF_Float32)) ImageFilter = "Image files (*.exr)"; else ImageFilter = "Image files (*.bmp)"; ; QFileInfo fileInfo(m_fileName); QDir dir(fileInfo.absoluteDir()); QString SuggetedFileNamePath; SuggetedFileNamePath = dir.absolutePath(); SuggetedFileNamePath.append("/"); SuggetedFileNamePath.append(fileInfo.baseName()); SuggetedFileNamePath.append("_" + QString::number(m_source_BlockXPos) + "_" + QString::number(m_source_BlockYPos)); std::string ext; QString filePathName; bool done = false; do { filePathName = QFileDialog::getSaveFileName(this, tr("Save Block Image as"), SuggetedFileNamePath, ImageFilter); if (filePathName.length() == 0) return; ext = CMP_GetFilePathExtension(filePathName.toStdString()); transform(ext.begin(), ext.end(), ext.begin(), ::tolower); string supported_ExtListings = ImageFilter.toStdString(); if (supported_ExtListings.find(ext) != std::string::npos) { done = true; } else { if (QMessageBox::question(this, "Save Block Image", "File extension is not supported try again?", QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) return; } } while (!done); // Create the 4x4 image block from MipSet data and save to file GetSourceBlock(m_source_BlockXPos, m_source_BlockYPos, filePathName.toStdString()); } } void cpImageView::showToobar(bool show) { if (show) m_toolBar->show(); else m_toolBar->hide(); } void cpImageView::OnToolBarClicked() { if (m_toolBar->isVisible()) m_toolBar->hide(); else m_toolBar->show(); } void cpImageView::paintEvent(QPaintEvent* event) { Q_UNUSED(event); if (m_FitOnShow) { imageview_FitInWindow->trigger(); m_FitOnShow = false; } if (m_CBimageview_MipLevel) { if ((m_processedMipImages) && (m_CBimageview_MipLevel->isEnabled() == false)) { // need to find root cause of 0xFEEEFEEE if ((m_processedMipImages->mipset) && (m_processedMipImages->mipset != (void*)0xFEEEFEEE)) { if (m_MipLevels != m_processedMipImages->mipset->m_nMipLevels) { EnableMipLevelDisplay(m_processedMipImages->mipset->m_nMipLevels); } } } } if (m_CBimageview_DepthLevel) { if ((m_processedMipImages) && (m_CBimageview_DepthLevel->isEnabled() == false)) { // need to find root cause of 0xFEEEFEEE if ((m_processedMipImages->mipset) && (m_processedMipImages->mipset != (void*)0xFEEEFEEE)) { if (m_MaxDepthLevel != m_processedMipImages->mipset->m_nDepth) { EnableDepthLevelDisplay(m_processedMipImages->mipset->m_nDepth); } } } } } void cpImageView::showEvent(QShowEvent*) { } void cpImageView::closeEvent(QCloseEvent*) { if (m_ExrProperties) { if (m_ExrProperties->isVisible()) m_ExrProperties->hide(); } } // This slot is received when user changes zoom using tool bar zoom void cpImageView::onZoomLevelChanged(int value) { if (!m_bOnacScaleChange) emit OnSetScale(value); } // This slot is received when user changes zoom using mouse wheel event in acImageView void cpImageView::onacScaleChange(int value) { m_bOnacScaleChange = true; m_ZoomLevel->setValue(value); m_bOnacScaleChange = false; } void cpImageView::onacPSNRUpdated(double value) { if (m_PSNRLabel && value > 0) { char buff[16]; snprintf(buff, sizeof(buff), "PSNR: %3.2f dB", value); m_PSNRLabel->setText(buff); } } // This slot is received when user changes brightness level using tool bar zoom void cpImageView::onBrightnessLevelChanged(int value) { if (m_acImageView->m_imageItem_Processed) { m_acImageView->setBrightnessLevel(value); } }
42,785
892
{ "schema_version": "1.2.0", "id": "GHSA-qqfm-8ggf-xpch", "modified": "2022-05-17T00:00:53Z", "published": "2022-05-07T00:00:36Z", "aliases": [ "CVE-2021-27751" ], "details": "HCL Commerce is affected by an Insufficient Session Expiration vulnerability. After the session expires, in some circumstances, parts of the application are still accessible.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-27751" }, { "type": "WEB", "url": "https://support.hcltechsw.com/csm?id=kb_article&sysparm_article=KB0097650" } ], "database_specific": { "cwe_ids": [ "CWE-613" ], "severity": "LOW", "github_reviewed": false } }
424
1,695
<filename>plugin/trino-hive/src/test/java/io/trino/plugin/hive/TestRecordingMetastoreConfig.java<gh_stars>1000+ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.hive; import com.google.common.collect.ImmutableMap; import io.airlift.units.Duration; import org.testng.annotations.Test; import java.util.Map; import java.util.concurrent.TimeUnit; import static io.airlift.configuration.testing.ConfigAssertions.assertFullMapping; import static io.airlift.configuration.testing.ConfigAssertions.assertRecordedDefaults; import static io.airlift.configuration.testing.ConfigAssertions.recordDefaults; public class TestRecordingMetastoreConfig { @Test public void testDefaults() { assertRecordedDefaults(recordDefaults(RecordingMetastoreConfig.class) .setRecordingPath(null) .setRecordingDuration(new Duration(10, TimeUnit.MINUTES)) .setReplay(false)); } @Test public void testExplicitPropertyMappings() { Map<String, String> properties = ImmutableMap.<String, String>builder() .put("hive.metastore-recording-path", "/foo/bar") .put("hive.metastore-recording-duration", "42s") .put("hive.replay-metastore-recording", "true") .buildOrThrow(); RecordingMetastoreConfig expected = new RecordingMetastoreConfig() .setRecordingPath("/foo/bar") .setRecordingDuration(new Duration(42, TimeUnit.SECONDS)) .setReplay(true); assertFullMapping(properties, expected); } }
783
360
/* ------------------------------------------------------------------------ * * geqo_copy.cpp * * Portions Copyright (c) 2020 Huawei Technologies Co.,Ltd. * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/gausskernel/optimizer/geqo/geqo_copy.cpp * * ------------------------------------------------------------------------- */ /* contributed by: =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*= * <NAME> * Institute of Automatic Control * = = University of Mining and Technology = * <EMAIL> * Freiberg, Germany * =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*= */ /* this is adopted from D. Whitley's Genitor algorithm */ /*************************************************************/ /* */ /* Copyright (c) 1990 */ /* <NAME> */ /* Computer Science Department */ /* Colorado State University */ /* */ /* Permission is hereby granted to copy all or any part of */ /* this program for free distribution. The author's name */ /* and this copyright notice must be included in any copy. */ /* */ /*************************************************************/ #include "postgres.h" #include "knl/knl_variable.h" #include "optimizer/geqo_copy.h" /* geqo_copy * * copies one gene to another * */ void geqo_copy(PlannerInfo* root, Chromosome* chromo1, Chromosome* chromo2, int string_length) { int i; for (i = 0; i < string_length; i++) chromo1->string[i] = chromo2->string[i]; chromo1->worth = chromo2->worth; }
685
502
<filename>core/src/main/java/org/apache/iceberg/avro/MissingIds.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.iceberg.avro; import java.util.List; import java.util.function.Supplier; import org.apache.avro.Schema; import org.apache.iceberg.relocated.com.google.common.collect.Iterables; /** * Returns true once the first node is found with ID property missing. Reverse of {@link HasIds} * <p> * Note: To use {@link AvroSchemaUtil#toIceberg(Schema)} on an avro schema, the avro schema need to be either * have IDs on every node or not have IDs at all. Invoke {@link AvroSchemaUtil#hasIds(Schema)} only proves * that the schema has at least one ID, and not sufficient condition for invoking * {@link AvroSchemaUtil#toIceberg(Schema)} on the schema. */ class MissingIds extends AvroCustomOrderSchemaVisitor<Boolean, Boolean> { @Override public Boolean record(Schema record, List<String> names, Iterable<Boolean> fields) { return Iterables.any(fields, Boolean.TRUE::equals); } @Override public Boolean field(Schema.Field field, Supplier<Boolean> fieldResult) { // either this field is missing ID, or the subtree is missing ID somewhere return !AvroSchemaUtil.hasFieldId(field) || fieldResult.get(); } @Override public Boolean map(Schema map, Supplier<Boolean> value) { // either this map node is missing (key/value) ID, or the subtree is missing ID somewhere return !AvroSchemaUtil.hasProperty(map, AvroSchemaUtil.KEY_ID_PROP) || !AvroSchemaUtil.hasProperty(map, AvroSchemaUtil.VALUE_ID_PROP) || value.get(); } @Override public Boolean array(Schema array, Supplier<Boolean> element) { // either this list node is missing (elem) ID, or the subtree is missing ID somewhere return !AvroSchemaUtil.hasProperty(array, AvroSchemaUtil.ELEMENT_ID_PROP) || element.get(); } @Override public Boolean union(Schema union, Iterable<Boolean> options) { return Iterables.any(options, Boolean.TRUE::equals); } @Override public Boolean primitive(Schema primitive) { // primitive node cannot be missing ID as Iceberg do not assign primitive node IDs in the first place return false; } }
904
666
#!/usr/bin/env python # -*- coding: utf-8 -*- # # gui.py # # Copyright 2017 <NAME> <<EMAIL>> # # 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. # # import sys sys.path.append("../../") import gettext import uuid import traceback import appJar #import hs602 # Setup gettext. gettext.install('Hs602util') class Gui(appJar.gui): """Simple HS602 utility using appJar.""" def __init__(self): super().__init__() # Some defaults. # Window title. self.setTitle(self.lang('default_title')) # Default widget padding. self.padx = 5 self.pady = 5 # Widget sticky setting. self.sticky = 'nesw' # The default window. self.manual_win() def lang(self, key): """Return string value of the requested key in values. :param key: key of the value you want. """ value = None values = { 'default_title': _('HS602 Utility'), 'error_title': _('Something Went Wrong!'), 'error_msg': _('Sorry, there\'s a problem. If it continues ' 'please report it.'), 'error_retry': _('\u2753 Try again'), 'error_quit': _('\u274C Quit'), 'scan_info': _('\u231B Scanning, please wait..'), 'scan_failed_title': _('No Devices Found!'), 'scan_failed_msg': _('No devices found!\nTry with an ' 'increased timeout (Yes)? Or connect ' 'manually (No)?'), 'manual_title': _('HS602 Utility - Connect'), 'manual_frm': _('Connect to Device'), 'manual_info': _('The address is required, leave the rest ' 'blank to use defaults.'), 'manual_addr': _('Address'), 'manual_tcp_lbl': _('TCP port'), 'manual_udp_lbl': _('UDP port'), 'manual_timeout_lbl': _('Timeout (in seconds)'), 'manual_scan_again': _('\u2753 Scan'), 'manual_connect': _('\u2713 Connect'), 'device_addr_invalid': _('Address must be set!'), } try: value = values[key] except KeyError: pass return str(value or uuid.uuid4()) def widget_defaults(self, inside_padding=False): """Set widget defaults. :param inside_padding: Set the padding inside the widget. """ # Padding. func = self.setPadding if inside_padding: func = self.setInPadding func(self.padx, self.pady) # Sticky. self.setSticky(self.sticky) def error_win(self, exc, callback=None): """There was a problem, display the traceback. :param exc: Exception or error message. :param callback: Function to call if the user would like to try again. """ # Window settings. self.removeAllWidgets() self.widget_defaults() # Widgets. self.addLabel('error_msg', self.lang('error_msg')) # If possible, get the backtrace. backtrace = '' try: backtrace = ''.join(traceback.format_tb(exc.__traceback__)) except AttributeError: pass # Add a text area so the user can copy the error. self.addScrolledTextArea('backtrace') self.setTextArea('backtrace', "{}\n\n{}".format(exc, backtrace)) if callable(callback): self.addButton(self.lang('error_retry'), callback) else: self.addButton(self.lang('error_quit'), self.stop) def scan_win(self, btn=None, timeout=5): """The scan window. :param: Button that triggered this method. :param: Timeout to pass to the scan thread. """ # Window settings. self.removeAllWidgets() self.widget_defaults() self.addLabel('scan_info', self.lang('scan_info')) # Queue the scan! self.after(100, self.thread, self.scan_thread, timeout) def scan_thread(self, timeout=5): """The scan thread - must be ran in the background. :param timeout: The socket timeout (in seconds 5-120). """ # Make sure the timeout is sane. try: timeout = int(timeout) if timeout not in range(4, 121): timeout = 5 except ValueError: timeout = 5 # OK try to probe! try: devices = hs602.Controller(timeout=timeout).discover() except OSError as exc: return self.queueFunction(self.error_win, exc) self.queueFunction(self.scan_finished_win, devices) def scan_again_win(self): """Ask the user to scan again or connect manually. This will in future allow the user to enter a timeout. """ prompt = self.questionBox(self.lang('scan_failed_title'), self.lang('scan_failed_msg')) if prompt == 'yes': return self.scan_win(None, 60) self.manual_win() def scan_finished_win(self, devices): """The scan has finished, ask the user to select a device - usually called by scan_thread. :param devices: list of devices found. """ if not isinstance(devices, list) or not len(devices) > 0: return self.scan_again_win() self.scan_again_win() def manual_win(self, btn=None): """Display manual connection form. :param btn: The button that called this method (not used). """ # Window settings. self.removeAllWidgets() self.widget_defaults() def connect(btn=None): """Connect button method. This basically calls device_connect with the form values as keyword args. :param btn: Button that called the method (not used). """ values = self.getAllEntries() self.queueFunction(self.device_connect, **values) # Connection input frame - this is before the above buttons. with self.labelFrame(self.lang('manual_frm'), 0, 0, 2): self.widget_defaults() # Frame widgets. self.addEntry('addr', 0, 1) self.addNumericEntry('tcp', 1, 1) self.addNumericEntry('timeout', 2, 1) self.addLabel('addr_lbl', self.lang('manual_addr'), 0, 0, 1) self.addLabel('tcp_lbl', self.lang('manual_tcp_lbl'), 1, 0) self.addLabel('to_lbl', self.lang('manual_timeout_lbl'), 2, 0) self.addLabel('info_lbl', self.lang('manual_info'), 3, 0, 2) self.setEntryMaxLength('tcp', 5) self.setEntryMaxLength('timeout', 3) self.setLabelAlign('info_lbl', 'center') self.setLabelAlign('addr_lbl', 'center') self.setLabelAlign('tcp_lbl', 'center') self.setLabelAlign('to_lbl', 'center') # Widgets. self.addButton(self.lang('manual_scan_again'), self.scan_win, 1, 0) self.addButton(self.lang('manual_connect'), connect, 1, 1) self.resize() def device_connect(self, **kwargs): """Try to connect using the values provided - this must be called in the background. :param kwargs: Connection info list - addr is required. """ # Check addr, port and timeout. try: kwargs['tcp'] = int(kwargs.get('tcp') or -1) kwargs['timeout'] = int(kwargs.get('timeout') or 0) kwargs['addr'] = str(kwargs.get('addr') or '').strip() # Port and timeout if not kwargs['tcp'] >= 1: kwargs.pop('tcp') if not kwargs['timeout'] > 0: kwargs.pop('timeout') if not len(kwargs['addr']) > 0: raise ValueError(self.lang('device_addr_invalid')) except ValueError as exc: return self.queueFunction(self.error_win, exc, self.manual_win) print(kwargs) def main(args): app = Gui() app.go() if __name__ == '__main__': import sys sys.exit(main(sys.argv))
4,121
2,859
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB (<EMAIL>). * See LICENSE for details. */ package com.almasb.fxgl.physics; import com.almasb.fxgl.entity.Entity; /** * Handler for a collision that occurred between two entities. * Subclasses should override only those callbacks they are * interested in. * * @author <NAME> (AlmasB) (<EMAIL>) */ public abstract class CollisionHandler extends Pair<Object> { /** * The order of types determines the order of entities in callbacks. * * @param a entity type of the first entity * @param b entity type of the second entity */ public CollisionHandler(Object a, Object b) { super(a, b); } /** * Called once per collision during the same tick when collision occurred. * Only the first hit box in the collision is passed. * * @param a first entity * @param b second entity * @param boxA hit box of first entity * @param boxB hit box of second entity */ protected void onHitBoxTrigger(Entity a, Entity b, HitBox boxA, HitBox boxB) { // no default implementation } /** * Called when entities A and B have just collided and weren't colliding in the last tick. * * @param a first entity * @param b second entity */ protected void onCollisionBegin(Entity a, Entity b) { // no default implementation } /** * Called if entities A and B are currently colliding. * * @param a first entity * @param b second entity */ protected void onCollision(Entity a, Entity b) { // no default implementation } /** * Called when entities A and B have just stopped colliding and were colliding in the last tick. * * @param a first entity * @param b second entity */ protected void onCollisionEnd(Entity a, Entity b) { // no default implementation } /** * Returns a copy of the collision handler with different entity types. * This allows convenient use of the same handler code for * multiple entity types. * * @param a entity type A * @param b entity type B * @return copy of collision handler */ public final CollisionHandler copyFor(Object a, Object b) { CollisionHandler copy = this; return new CollisionHandler(a, b) { @Override protected void onHitBoxTrigger(Entity a, Entity b, HitBox boxA, HitBox boxB) { copy.onHitBoxTrigger(a, b, boxA, boxB); } @Override protected void onCollisionBegin(Entity a, Entity b) { copy.onCollisionBegin(a, b); } @Override protected void onCollision(Entity a, Entity b) { copy.onCollision(a, b); } @Override protected void onCollisionEnd(Entity a, Entity b) { copy.onCollisionEnd(a, b); } }; } }
1,176
459
package com.example.pocketknife; import android.os.Parcel; import android.os.Parcelable; public class MyParcelable implements Parcelable { public static final Creator<MyParcelable> CREATOR = new Creator<MyParcelable>() { @Override public MyParcelable createFromParcel(Parcel in) { return new MyParcelable(in); } @Override public MyParcelable[] newArray(int size) { return new MyParcelable[size]; } }; private int data; public MyParcelable(int data) { this.data = data; } private MyParcelable(Parcel in) { data = in.readInt(); } @Override public int hashCode() { return Integer.valueOf(data).hashCode(); } @Override public boolean equals(Object obj) { return obj instanceof MyParcelable && ((MyParcelable) obj).data == this.data; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeInt(data); } public int getData() { return data; } public void setData(int data) { this.data = data; } }
505
377
import requests from .attacktemplate import AttackTemplate from .base import Base class NewBeeAttackDataset(Base): """ Data Source: https://github.com/NewBee119/Attack-Technique-Dataset Author: NewBee119 This class is a wrapper for the above data set """ URL = 'https://raw.githubusercontent.com/NewBee119/Attack-Technique-Dataset/master/tech_refer.json' def __get_data(self): return requests.get(self.URL).json() def get(self): return_dict = {} for key,val in self.__get_data().items(): for item in val: if item not in return_dict: return_dict[item] = [] return_dict[item].append(key) return_list = [] template = AttackTemplate() for key,val in return_dict.items(): template.id = key for item in val: template.add_external_reference(item) return_list.append(template.get()) return return_list
436
581
<filename>test/llvm_test_code/taint_analysis/taint_11.c<gh_stars>100-1000 #include <stdio.h> int quk(int i) { return i; } int baz(int i) { return quk(i); } int bar(int i) { return baz(i); } int foo(int i) { return bar(i); } int main(int argc, char **argv) { int y = foo(argc); int a = 42; int z = foo(a); printf("%d\n", y); printf("%d\n", z); }
171
369
// Copyright (c) 2017-2021, Mudit<NAME>. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include <UrcCreg.hpp> #include <magic_enum.hpp> using namespace at::urc; auto Creg::isValid() const noexcept -> bool { return isExtended() || isShort(); } auto Creg::isExtended() const noexcept -> bool { return tokens.size() == magic_enum::enum_count<Tokens>(); } auto Creg::isShort() const noexcept -> bool { return tokens.size() == NumOfShortTokens; } auto Creg::getStatus() const noexcept -> Store::Network::Status { if (isValid()) { int statusInt; try { statusInt = std::stoi(tokens[Tokens::Stat]); } catch (const std::exception &e) { return Store::Network::Status::Unknown; } auto status = magic_enum::enum_cast<Store::Network::Status>(statusInt); if (status.has_value()) { return status.value(); } } return Store::Network::Status::Unknown; } auto Creg::getLocation() const noexcept -> std::optional<std::string> { if (isValid() && isExtended()) { auto location = tokens[Tokens::Lac]; utils::findAndReplaceAll(location, "\"", ""); return location; } return std::nullopt; } auto Creg::getCellId() const noexcept -> std::optional<std::string> { if (isValid() && isExtended()) { auto cellId = tokens[Tokens::Ci]; utils::findAndReplaceAll(cellId, "\"", ""); return cellId; } return std::nullopt; } auto Creg::getAccessTechnology() const noexcept -> Store::Network::AccessTechnology { if (isValid() && isExtended()) { int accessTechnologyInt; try { accessTechnologyInt = std::stoi(tokens[Tokens::Act]); } catch (const std::exception &e) { return Store::Network::AccessTechnology::Unknown; } auto accessTechnology = magic_enum::enum_cast<Store::Network::AccessTechnology>(accessTechnologyInt); if (accessTechnology.has_value()) { return accessTechnology.value(); } } return Store::Network::AccessTechnology::Unknown; }
876
496
<reponame>dubadub/vas3k.club<filename>club/exceptions.py class ClubException(Exception): default_code = "error" default_title = "Что-то пошло не так" default_message = "Никто не знает что произошло :(" def __init__(self, code=None, title=None, message=None, data=None): self.code = code or self.default_code self.title = title or self.default_title self.message = message or self.default_message self.data = data or {} class BadRequest(ClubException): default_code = "bad-request" default_title = "Неправильный параметр запроса" default_message = "Что-то сломалось" class NotFound(ClubException): default_code = "not-found" default_title = "Не найдено" default_message = "" class AccessDenied(ClubException): default_code = "access-forbidden" default_title = "Вам сюда нельзя" default_message = "Атата" class RateLimitException(ClubException): default_code = "rate-limit" default_title = "Вы создали слишком много постов или комментов сегодня" default_message = "Пожалуйста, остановитесь" class ContentDuplicated(ClubException): default_code = "duplicated-content" default_title = "Обнаружен дубликат!" default_message = "Кажется, вы пытаетесь опубликовать то же самое повторно. " \ "Проверьте всё ли в порядке." class InsufficientFunds(ClubException): default_code = "insufficient-funds" default_title = "Недостаточно средств" class URLParsingException(ClubException): default_code = "url-parser-exception" default_title = "Не удалось распарсить URL" default_message = "" class InvalidCode(ClubException): default_code = "invalid-code" default_title = "Вы ввели неправильный код" default_message = "Введите или запросите его еще раз. Через несколько неправильных попыток коды удаляются" class ApiInsufficientFunds(ClubException): default_code = "api-insufficient-funds" default_title = "Недостаточно средств" class ApiException(ClubException): default_message = None class ApiAuthRequired(ApiException): default_code = "api-auth-required" default_title = "Auth Required" class ApiAccessDenied(ApiException): default_code = "api-access-denied" default_title = "Access Denied"
1,192
2,743
from __future__ import unicode_literals default_app_config = 'rest_api.apps.RESTAPIApp'
32
575
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_IMPORT_MAP_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_IMPORT_MAP_H_ #include "base/macros.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/weborigin/kurl_hash.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" namespace blink { class ConsoleLogger; class JSONObject; class Modulator; class ParsedSpecifier; class ScriptValue; // Import maps. // https://wicg.github.io/import-maps/ // https://github.com/WICG/import-maps/blob/master/spec.md class CORE_EXPORT ImportMap final : public GarbageCollected<ImportMap> { public: static ImportMap* Parse(const Modulator&, const String& text, const KURL& base_url, ConsoleLogger& logger, ScriptValue* error_to_rethrow); // <spec href="https://wicg.github.io/import-maps/#specifier-map">A specifier // map is an ordered map from strings to resolution results.</spec> // // An invalid KURL corresponds to a null resolution result in the spec. // // In Blink, we actually use an unordered map here, and related algorithms // are implemented differently from the spec. using SpecifierMap = HashMap<String, KURL>; // <spec href="https://wicg.github.io/import-maps/#import-map-scopes">an // ordered map of URLs to specifier maps.</spec> using ScopeEntryType = std::pair<String, SpecifierMap>; using ScopeType = Vector<ScopeEntryType>; // Empty import map. ImportMap(); ImportMap(SpecifierMap&& imports, ScopeType&& scopes); // Return values of Resolve(), ResolveImportsMatch() and // ResolveImportsMatchInternal(): // - base::nullopt: corresponds to returning a null in the spec, // i.e. allowing fallback to a less specific scope etc. // - An invalid KURL: corresponds to throwing an error in the spec. // - A valid KURL: corresponds to returning a valid URL in the spec. base::Optional<KURL> Resolve(const ParsedSpecifier&, const KURL& base_url, String* debug_message) const; String ToString() const; void Trace(Visitor*) const {} private: using MatchResult = SpecifierMap::const_iterator; // https://wicg.github.io/import-maps/#resolve-an-imports-match base::Optional<KURL> ResolveImportsMatch(const ParsedSpecifier&, const SpecifierMap&, String* debug_message) const; base::Optional<MatchResult> MatchPrefix(const ParsedSpecifier&, const SpecifierMap&) const; static SpecifierMap SortAndNormalizeSpecifierMap(const JSONObject* imports, const KURL& base_url, ConsoleLogger&); KURL ResolveImportsMatchInternal(const String& normalizedSpecifier, const MatchResult&, String* debug_message) const; // https://wicg.github.io/import-maps/#import-map-imports SpecifierMap imports_; // https://wicg.github.io/import-maps/#import-map-scopes. ScopeType scopes_; }; } // namespace blink #endif
1,463
4,036
<gh_stars>1000+ // Generated automatically from org.apache.commons.collections4.OrderedMapIterator for testing purposes package org.apache.commons.collections4; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.OrderedIterator; public interface OrderedMapIterator<K, V> extends MapIterator<K, V>, OrderedIterator<K> { K previous(); boolean hasPrevious(); }
126
4,140
<reponame>FANsZL/hive<filename>ql/src/java/org/apache/hadoop/hive/ql/parse/WindowingComponentizer.java<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.parse; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.parse.PTFInvocationSpec.PartitioningSpec; import org.apache.hadoop.hive.ql.parse.WindowingSpec.WindowExpressionSpec; import org.apache.hadoop.hive.ql.parse.WindowingSpec.WindowFunctionSpec; /* * breakup the original WindowingSpec into a set of WindowingSpecs. * Each WindowingSpec is executed in an instance of PTFOperator, * preceded by ReduceSink and Extract. * The logic to componentize is straightforward: * - distribute Window Fn. Specs from original Window Spec into a set of WindowSpecs, * based on their Partitioning. * - A Group of WindowSpecs, is a subset of the Window Fn Invocations in the QueryBlock that * have the same Partitioning(Partition + Order spec). * - Each Group is put in a new WindowingSpec and is evaluated in its own PTFOperator instance. * - the order of computation is then inferred based on the dependency between Groups. * If 2 groups have the same dependency, then the Group with the function that is * earliest in the SelectList is executed first. */ public class WindowingComponentizer { WindowingSpec originalSpec; LinkedHashMap<PartitioningSpec, WindowingSpec> groups; public WindowingComponentizer(WindowingSpec originalSpec) throws SemanticException { super(); this.originalSpec = originalSpec; groups = new LinkedHashMap<PartitioningSpec, WindowingSpec>(); groupFunctions(); } private void groupFunctions() throws SemanticException { for (WindowExpressionSpec expr : originalSpec.getWindowExpressions()) { WindowFunctionSpec wFn = (WindowFunctionSpec) expr; PartitioningSpec wFnGrp = wFn.getWindowSpec().getPartitioning(); WindowingSpec wSpec = groups.get(wFnGrp); if (wSpec == null) { wSpec = new WindowingSpec(); groups.put(wFnGrp, wSpec); } wSpec.addWindowFunction(wFn); } } public boolean hasNext() { return !groups.isEmpty(); } public WindowingSpec next(HiveConf hCfg, SemanticAnalyzer semAly, UnparseTranslator unparseT, RowResolver inputRR) throws SemanticException { SemanticException originalException = null; Iterator<Map.Entry<PartitioningSpec, WindowingSpec>> grpIt = groups.entrySet().iterator(); while (grpIt.hasNext()) { Map.Entry<PartitioningSpec, WindowingSpec> entry = grpIt.next(); WindowingSpec wSpec = entry.getValue(); try { PTFTranslator t = new PTFTranslator(); t.translate(wSpec, semAly, hCfg, inputRR, unparseT); groups.remove(entry.getKey()); return wSpec; } catch (SemanticException se) { originalException = se; } } throw new SemanticException("Failed to breakup Windowing invocations into Groups. " + "At least 1 group must only depend on input columns. " + "Also check for circular dependencies.\n" + "Underlying error: " + originalException.getMessage()); } }
1,292
5,821
<filename>metaflow/plugins/aws/batch/batch.py import atexit import json import os import select import shlex import time from metaflow import util from metaflow.datatools.s3tail import S3Tail from metaflow.exception import MetaflowException, MetaflowInternalError from metaflow.metaflow_config import ( BATCH_METADATA_SERVICE_URL, DATATOOLS_S3ROOT, DATASTORE_LOCAL_DIR, DATASTORE_SYSROOT_S3, DEFAULT_METADATA, BATCH_METADATA_SERVICE_HEADERS, BATCH_EMIT_TAGS ) from metaflow.mflog.mflog import refine, set_should_persist from metaflow.mflog import ( export_mflog_env_vars, bash_capture_logs, update_delay, BASH_SAVE_LOGS, ) from .batch_client import BatchClient # Redirect structured logs to /logs/ LOGS_DIR = "/logs" STDOUT_FILE = "mflog_stdout" STDERR_FILE = "mflog_stderr" STDOUT_PATH = os.path.join(LOGS_DIR, STDOUT_FILE) STDERR_PATH = os.path.join(LOGS_DIR, STDERR_FILE) class BatchException(MetaflowException): headline = "AWS Batch error" class BatchKilledException(MetaflowException): headline = "AWS Batch task killed" class Batch(object): def __init__(self, metadata, environment): self.metadata = metadata self.environment = environment self._client = BatchClient() atexit.register( lambda: self.job.kill() if hasattr(self, "job") else None ) def _command( self, environment, code_package_url, step_name, step_cmds, task_spec ): mflog_expr = export_mflog_env_vars( datastore_type="s3", stdout_path=STDOUT_PATH, stderr_path=STDERR_PATH, **task_spec ) init_cmds = environment.get_package_commands(code_package_url) init_expr = " && ".join(init_cmds) step_expr = bash_capture_logs( " && ".join(environment.bootstrap_commands(step_name) + step_cmds) ) # construct an entry point that # 1) initializes the mflog environment (mflog_expr) # 2) bootstraps a metaflow environment (init_expr) # 3) executes a task (step_expr) # the `true` command is to make sure that the generated command # plays well with docker containers which have entrypoint set as # eval $@ cmd_str = "true && mkdir -p /logs && %s && %s && %s; " % ( mflog_expr, init_expr, step_expr, ) # after the task has finished, we save its exit code (fail/success) # and persist the final logs. The whole entrypoint should exit # with the exit code (c) of the task. # # Note that if step_expr OOMs, this tail expression is never executed. # We lose the last logs in this scenario (although they are visible # still through AWS CloudWatch console). cmd_str += "c=$?; %s; exit $c" % BASH_SAVE_LOGS return shlex.split('bash -c "%s"' % cmd_str) def _search_jobs(self, flow_name, run_id, user): if user is None: regex = "-{flow_name}-".format(flow_name=flow_name) else: regex = "{user}-{flow_name}-".format(user=user, flow_name=flow_name) jobs = [] for job in self._client.unfinished_jobs(): if regex in job["jobName"]: jobs.append(job["jobId"]) if run_id is not None: run_id = run_id[run_id.startswith("sfn-") and len("sfn-") :] for job in self._client.describe_jobs(jobs): parameters = job["parameters"] match = ( (user is None or parameters["metaflow.user"] == user) and (parameters["metaflow.flow_name"] == flow_name) and (run_id is None or parameters["metaflow.run_id"] == run_id) ) if match: yield job def _job_name( self, user, flow_name, run_id, step_name, task_id, retry_count ): return "{user}-{flow_name}-{run_id}-{step_name}-{task_id}-{retry_count}".format( user=user, flow_name=flow_name, run_id=str(run_id) if run_id is not None else "", step_name=step_name, task_id=str(task_id) if task_id is not None else "", retry_count=str(retry_count) if retry_count is not None else "", ) def list_jobs(self, flow_name, run_id, user, echo): jobs = self._search_jobs(flow_name, run_id, user) found = False for job in jobs: found = True echo( "{name} [{id}] ({status})".format( name=job["jobName"], id=job["jobId"], status=job["status"] ) ) if not found: echo("No running AWS Batch jobs found.") def kill_jobs(self, flow_name, run_id, user, echo): jobs = self._search_jobs(flow_name, run_id, user) found = False for job in jobs: found = True try: self._client.attach_job(job["jobId"]).kill() echo( "Killing AWS Batch job: {name} [{id}] ({status})".format( name=job["jobName"], id=job["jobId"], status=job["status"], ) ) except Exception as e: echo( "Failed to terminate AWS Batch job %s [%s]" % (job["jobId"], repr(e)) ) if not found: echo("No running AWS Batch jobs found.") def create_job( self, step_name, step_cli, task_spec, code_package_sha, code_package_url, code_package_ds, image, queue, iam_role=None, execution_role=None, cpu=None, gpu=None, memory=None, run_time_limit=None, shared_memory=None, max_swap=None, swappiness=None, env={}, attrs={}, host_volumes=None, ): job_name = self._job_name( attrs.get("metaflow.user"), attrs.get("metaflow.flow_name"), attrs.get("metaflow.run_id"), attrs.get("metaflow.step_name"), attrs.get("metaflow.task_id"), attrs.get("metaflow.retry_count"), ) job = ( self._client.job() .job_name(job_name) .job_queue(queue) .command( self._command(self.environment, code_package_url, step_name, [step_cli], task_spec)) \ .image(image) \ .iam_role(iam_role) \ .execution_role(execution_role) \ .job_def(image, iam_role, queue, execution_role, shared_memory, max_swap, swappiness, host_volumes=host_volumes) \ .cpu(cpu) \ .gpu(gpu) \ .memory(memory) \ .shared_memory(shared_memory) \ .max_swap(max_swap) \ .swappiness(swappiness) \ .timeout_in_secs(run_time_limit) \ .environment_variable('AWS_DEFAULT_REGION', self._client.region()) \ .environment_variable('METAFLOW_CODE_SHA', code_package_sha) \ .environment_variable('METAFLOW_CODE_URL', code_package_url) \ .environment_variable('METAFLOW_CODE_DS', code_package_ds) \ .environment_variable('METAFLOW_USER', attrs['metaflow.user']) \ .environment_variable('METAFLOW_SERVICE_URL', BATCH_METADATA_SERVICE_URL) \ .environment_variable('METAFLOW_SERVICE_HEADERS', json.dumps(BATCH_METADATA_SERVICE_HEADERS)) \ .environment_variable('METAFLOW_DATASTORE_SYSROOT_S3', DATASTORE_SYSROOT_S3) \ .environment_variable('METAFLOW_DATATOOLS_S3ROOT', DATATOOLS_S3ROOT) \ .environment_variable('METAFLOW_DEFAULT_DATASTORE', 's3') \ .environment_variable('METAFLOW_DEFAULT_METADATA', DEFAULT_METADATA)) # Skip setting METAFLOW_DATASTORE_SYSROOT_LOCAL because metadata sync between the local user # instance and the remote AWS Batch instance assumes metadata is stored in DATASTORE_LOCAL_DIR # on the remote AWS Batch instance; this happens when METAFLOW_DATASTORE_SYSROOT_LOCAL # is NOT set (see get_datastore_root_from_config in datastore/local.py). for name, value in env.items(): job.environment_variable(name, value) if attrs: for key, value in attrs.items(): job.parameter(key, value) # Tags for AWS Batch job (for say cost attribution) if BATCH_EMIT_TAGS: for key in ['metaflow.flow_name', 'metaflow.run_id', 'metaflow.step_name', 'metaflow.version', 'metaflow.run_id.$', 'metaflow.user', 'metaflow.owner', 'metaflow.production_token']: if key in attrs: job.tag(key, attrs.get(key)) return job def launch_job( self, step_name, step_cli, task_spec, code_package_sha, code_package_url, code_package_ds, image, queue, iam_role=None, execution_role=None, # for FARGATE compatibility cpu=None, gpu=None, memory=None, run_time_limit=None, shared_memory=None, max_swap=None, swappiness=None, host_volumes=None, env={}, attrs={}, ): if queue is None: queue = next(self._client.active_job_queues(), None) if queue is None: raise BatchException( "Unable to launch AWS Batch job. No job queue " " specified and no valid & enabled queue found." ) job = self.create_job( step_name, step_cli, task_spec, code_package_sha, code_package_url, code_package_ds, image, queue, iam_role, execution_role, cpu, gpu, memory, run_time_limit, shared_memory, max_swap, swappiness, env=env, attrs=attrs, host_volumes=host_volumes ) self.job = job.execute() def wait(self, stdout_location, stderr_location, echo=None): def wait_for_launch(job): status = job.status echo( "Task is starting (status %s)..." % status, "stderr", batch_id=job.id, ) t = time.time() while True: if status != job.status or (time.time() - t) > 30: status = job.status echo( "Task is starting (status %s)..." % status, "stderr", batch_id=job.id, ) t = time.time() if job.is_running or job.is_done or job.is_crashed: break select.poll().poll(200) prefix = b"[%s] " % util.to_bytes(self.job.id) def _print_available(tail, stream, should_persist=False): # print the latest batch of lines from S3Tail try: for line in tail: if should_persist: line = set_should_persist(line) else: line = refine(line, prefix=prefix) echo(line.strip().decode("utf-8", errors="replace"), stream) except Exception as ex: echo( "[ temporary error in fetching logs: %s ]" % ex, "stderr", batch_id=self.job.id, ) stdout_tail = S3Tail(stdout_location) stderr_tail = S3Tail(stderr_location) # 1) Loop until the job has started wait_for_launch(self.job) # 2) Loop until the job has finished start_time = time.time() is_running = True next_log_update = start_time log_update_delay = 1 while is_running: if time.time() > next_log_update: _print_available(stdout_tail, "stdout") _print_available(stderr_tail, "stderr") now = time.time() log_update_delay = update_delay(now - start_time) next_log_update = now + log_update_delay is_running = self.job.is_running # This sleep should never delay log updates. On the other hand, # we should exit this loop when the task has finished without # a long delay, regardless of the log tailing schedule d = min(log_update_delay, 5.0) select.poll().poll(d * 1000) # 3) Fetch remaining logs # # It is possible that we exit the loop above before all logs have been # shown. # # TODO if we notice AWS Batch failing to upload logs to S3, we can add a # HEAD request here to ensure that the file exists prior to calling # S3Tail and note the user about truncated logs if it doesn't _print_available(stdout_tail, "stdout") _print_available(stderr_tail, "stderr") # In case of hard crashes (OOM), the final save_logs won't happen. # We fetch the remaining logs from AWS CloudWatch and persist them to # Amazon S3. if self.job.is_crashed: msg = next( msg for msg in [ self.job.reason, self.job.status_reason, "Task crashed.", ] if msg is not None ) raise BatchException( "%s " "This could be a transient error. " "Use @retry to retry." % msg ) else: if self.job.is_running: # Kill the job if it is still running by throwing an exception. raise BatchException("Task failed!") echo( "Task finished with exit code %s." % self.job.status_code, "stderr", batch_id=self.job.id, )
7,753
814
<filename>torchrec/distributed/utils.py<gh_stars>100-1000 #!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and 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 collections import OrderedDict from typing import Any, Dict, List, Optional, Set, Union import torch from torchrec.distributed.types import ShardedModule def append_prefix(prefix: str, name: str) -> str: """ Appends provided prefix to provided name. """ if prefix != "" and name != "": return prefix + "." + name else: return prefix + name def filter_state_dict( state_dict: "OrderedDict[str, torch.Tensor]", name: str ) -> "OrderedDict[str, torch.Tensor]": """ Filters state dict for keys that start with provided name. Strips provided name from beginning of key in the resulting state dict. Args: state_dict (OrderedDict[str, torch.Tensor]): input state dict to filter. name (str): name to filter from state dict keys. Returns: OrderedDict[str, torch.Tensor]: filtered state dict. """ filtered_state_dict = OrderedDict() for key, value in state_dict.items(): if key.startswith(name): # + 1 to length is to remove the '.' after the key filtered_state_dict[key[len(name) + 1 :]] = value return filtered_state_dict def add_prefix_to_state_dict(state_dict: Dict[str, Any], prefix: str) -> None: """ Adds prefix to all keys in state dict, in place. Args: state_dict (Dict[str, Any]): input state dict to update. prefix (str): name to filter from state dict keys. Returns: None. """ keys = sorted(state_dict.keys()) for key in keys: state_dict[prefix + key] = state_dict.pop(key) if "_metadata" in state_dict: metadata = state_dict["_metadata"] for key in list(metadata.keys()): if len(key) == 0: continue metadata[prefix + key] = metadata.pop(key) def _get_unsharded_module_names_helper( model: torch.nn.Module, path: str, unsharded_module_names: Set[str], ) -> bool: sharded_children = set() for name, child in model.named_children(): curr_path = path + name if isinstance(child, ShardedModule): sharded_children.add(name) else: child_sharded = _get_unsharded_module_names_helper( child, curr_path + ".", unsharded_module_names, ) if child_sharded: sharded_children.add(name) if len(sharded_children) > 0: for name, _ in model.named_children(): if name not in sharded_children: unsharded_module_names.add(path + name) return len(sharded_children) > 0 def get_unsharded_module_names(model: torch.nn.Module) -> List[str]: """ Retrieves names of top level modules that do not contain any sharded sub-modules. Args: model (torch.nn.Module): model to retrieve unsharded module names from. Returns: List[str]: list of names of modules that don't have sharded sub-modules. """ unsharded_module_names: Set[str] = set() _get_unsharded_module_names_helper( model, "", unsharded_module_names, ) return list(unsharded_module_names) class sharded_model_copy: """ Allows copying of DistributedModelParallel module to a target device. Example:: # Copying model to CPU. m = DistributedModelParallel(m) with sharded_model_copy("cpu"): m_cpu = copy.deepcopy(m) """ def __init__(self, device: Optional[Union[str, int, torch.device]]) -> None: self.device = device def __enter__(self) -> None: # pyre-ignore [16] self.t_copy_save_ = torch.Tensor.__deepcopy__ # pyre-ignore [16] self.p_copy_save_ = torch.nn.Parameter.__deepcopy__ device = self.device # pyre-ignore [2, 3, 53] def _tensor_copy(tensor, memo): if tensor.device != device: return tensor.detach().to(device) else: return tensor.detach().clone() # pyre-ignore [2, 3] def _no_copy(obj, memo): return obj _copy_or_not = _tensor_copy if self.device is not None else _no_copy # pyre-ignore [2, 3, 53] def _param_copy(param, memo): return torch.nn.Parameter( _copy_or_not(param, memo), requires_grad=param.requires_grad ) # pyre-ignore [16] torch.Tensor.__deepcopy__ = _copy_or_not torch.nn.Parameter.__deepcopy__ = _param_copy torch._C._distributed_c10d.ProcessGroupNCCL.__deepcopy__ = _no_copy torch._C._distributed_c10d.ProcessGroupGloo.__deepcopy__ = _no_copy torch._C._distributed_c10d.Work.__deepcopy__ = _no_copy # pyre-ignore [16] torch.cuda.streams.Stream.__deepcopy__ = _no_copy # pyre-ignore [2] def __exit__(self, exc_type, exc_val, exc_tb) -> None: # pyre-ignore [16] torch.Tensor.__deepcopy__ = self.t_copy_save_ # pyre-ignore [16] torch.nn.Parameter.__deepcopy__ = self.p_copy_save_ torch._C._distributed_c10d.ProcessGroupNCCL.__deepcopy__ = None torch._C._distributed_c10d.ProcessGroupGloo.__deepcopy__ = None torch._C._distributed_c10d.Work.__deepcopy__ = None # pyre-ignore [16] torch.cuda.streams.Stream.__deepcopy__ = None
2,455
1,125
<reponame>chefmramos85/monster-mash // This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2020 <NAME> <<EMAIL>> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #ifndef IGL_FILE_UTILS_H #define IGL_FILE_UTILS_H #include "igl_inline.h" #include <streambuf> #include <istream> #include <string> #include <vector> namespace igl { IGL_INLINE void read_file_binary(FILE *fp, std::vector<uint8_t> &fileBufferBytes); struct file_memory_buffer : public std::streambuf { char *p_start{nullptr}; char *p_end{nullptr}; size_t size; file_memory_buffer(char const *first_elem, size_t size) : p_start(const_cast<char *>(first_elem)), p_end(p_start + size), size(size) { setg(p_start, p_start, p_end); } pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) override { if (dir == std::ios_base::cur) { gbump(static_cast<int>(off)); } else { setg(p_start, (dir == std::ios_base::beg ? p_start : p_end) + off, p_end); } return gptr() - p_start; } pos_type seekpos(pos_type pos, std::ios_base::openmode which) override { return seekoff(pos, std::ios_base::beg, which); } }; struct file_memory_stream : virtual file_memory_buffer, public std::istream { file_memory_stream(char const *first_elem, size_t size) : file_memory_buffer(first_elem, size), std::istream( static_cast<std::streambuf *>( this)) {} }; } // namespace igl #ifndef IGL_STATIC_LIBRARY #include "file_utils.cpp" #endif #endif
814
32,544
<filename>quarkus/src/test/java/com/baeldung/quarkus/utils/CustomTestProfile.java<gh_stars>1000+ package com.baeldung.quarkus.utils; import io.quarkus.test.junit.QuarkusTestProfile; import java.util.Collections; import java.util.Map; import java.util.Set; public class CustomTestProfile implements QuarkusTestProfile { @Override public Map<String, String> getConfigOverrides() { return Collections.singletonMap("quarkus.resteasy.path", "/custom"); } @Override public Set<Class<?>> getEnabledAlternatives() { return Collections.singleton(TestBookRepository.class); } @Override public String getConfigProfile() { return "custom-profile"; } }
257
335
<filename>src/datagen/generated/assets/projecte/models/block/collector_mk2.json { "parent": "projecte:block/collector_mk1", "textures": { "top": "projecte:block/collectors/top_2" } }
77
971
#!/usr/bin/python # Copyright (C) 2017 Google 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. import builtins import json import tempfile import time import os import os.path import pytest import subprocess import uuid # Propagation delays for Device Registration API resource creation. DEVICE_MODEL_PROPAGATION_DELAY_S = 30 DEVICE_INSTANCE_PROPAGATION_DELAY_S = 60 PROJECT_ID = os.environ.get('PROJECT_ID', 'dummy-project-id') @pytest.fixture(scope='session') def device_model(): device_model_id = 'assistant-sdk-test-model-%s' % str(uuid.uuid1()) subprocess.check_call(['python', '-m', 'googlesamples.assistant.grpc.devicetool', '--project-id', PROJECT_ID, 'register-model', '--model', device_model_id, '--type', 'LIGHT', '--trait', 'action.devices.traits.OnOff', '--manufacturer', 'assistant-sdk-test', '--product-name', 'assistant-sdk-test']) # Wait for model registration to be consistent # on the Device Registration API. time.sleep(DEVICE_MODEL_PROPAGATION_DELAY_S) yield device_model_id subprocess.check_call(['python', '-m', 'googlesamples.assistant.grpc.devicetool', '--project-id', PROJECT_ID, 'delete', '--model', device_model_id]) @pytest.fixture(scope='session') def device_instance(device_model): device_instance_id = 'assistant-sdk-test-device-%s' % str(uuid.uuid1()) subprocess.check_call(['python', '-m', 'googlesamples.assistant.grpc.devicetool', '--project-id', PROJECT_ID, 'register-device', '--model', device_model, '--client-type', 'SERVICE', '--device', device_instance_id]) # Wait for device registration to be consistent # on the Device Registration API. time.sleep(DEVICE_INSTANCE_PROPAGATION_DELAY_S) yield device_instance_id subprocess.check_call(['python', '-m', 'googlesamples.assistant.grpc.devicetool', '--project-id', PROJECT_ID, 'delete', '--device', device_instance_id]) def test_endtoend_pushtotalk(): temp_dir = tempfile.mkdtemp() audio_out_file = os.path.join(temp_dir, 'out.raw') out = subprocess.check_output(['python', '-m', 'googlesamples.assistant.grpc.pushtotalk', '--verbose', '--device-model-id', 'test-device-model', '--device-id', 'test-device', '-i', 'tests/data/whattimeisit.riff', '-o', audio_out_file], stderr=subprocess.STDOUT) print(out) assert 'what time is it' in builtins.str(out).lower() assert os.path.getsize(audio_out_file) > 0 def test_endtoend_pushtotalk_htmloutput(device_model, device_instance): temp_dir = tempfile.mkdtemp() audio_out_file = os.path.join(temp_dir, 'out.raw') env = os.environ.copy() env['TMPDIR'] = temp_dir out = subprocess.check_output(['python', '-m', 'googlesamples.assistant.grpc.pushtotalk', '--verbose', '--device-model-id', device_model, '--device-id', device_instance, '-i', 'tests/data/grapefruit.riff', '--display', '-o', audio_out_file], stderr=subprocess.STDOUT, env=env) print(out) assert 'grapefruit' in builtins.str(out).lower() assert os.path.getsize(audio_out_file) > 0 files = [os.path.join(path, f) for path, _, fs in os.walk(temp_dir) for f in fs] assert len(files) > 0 screen_out = None for f in files: if os.path.basename(f) == 'google-assistant-sdk-screen-out.html': screen_out = f assert screen_out is not None with open(screen_out, 'r') as f: assert 'pamplemousse' in f.read() def test_registration_pushtotalk(device_model): temp_dir = tempfile.mkdtemp() audio_out_file = os.path.join(temp_dir, 'out.raw') # Use an non-existing device config file intentionally # to force device registration. device_config = os.path.join(temp_dir, 'device_config.json') out = subprocess.check_output(['python', '-m', 'googlesamples.assistant.grpc.pushtotalk', '--verbose', '--project-id', PROJECT_ID, '--device-model-id', device_model, '--device-config', device_config, '-i', 'tests/data/whattimeisit.riff', '-o', audio_out_file], stderr=subprocess.STDOUT) assert 'what time is it' in builtins.str(out).lower() assert os.path.getsize(audio_out_file) > 0 with open(device_config) as f: config = json.load(f) assert ('device registered: %s' % config['id'] in builtins.str(out).lower()) out = subprocess.check_output( ['python', '-m', 'googlesamples.assistant.grpc.devicetool', '--project-id', PROJECT_ID, 'get', '--device', config['id']], stderr=subprocess.STDOUT ) print(out) assert ('device instance id: %s' % config['id'] in builtins.str(out).lower()) subprocess.check_call(['python', '-m', 'googlesamples.assistant.grpc.devicetool', '--project-id', PROJECT_ID, 'delete', '--device', config['id']]) def test_endtoend_textinput(device_model, device_instance): p = subprocess.Popen(['python', '-m', 'googlesamples.assistant.grpc.textinput', '--verbose', '--device-model-id', device_model, '--device-id', device_instance], stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate(b'how do you say grapefruit in French?') print(out) out = builtins.str(out).lower() assert err is None assert 'grapefruit' in out assert 'pamplemousse' in out def test_endtoend_textinput_htmloutput(device_model, device_instance): temp_dir = tempfile.mkdtemp() env = os.environ.copy() env['TMPDIR'] = temp_dir p = subprocess.Popen(['python', '-m', 'googlesamples.assistant.grpc.textinput', '--verbose', '--device-model-id', device_model, '--device-id', device_instance, '--display'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env) out, err = p.communicate(b'how do you say grapefruit in French?') print(out) out = builtins.str(out).lower() assert err is None assert 'grapefruit' in out files = [os.path.join(path, f) for path, _, fs in os.walk(temp_dir) for f in fs] assert len(files) == 1 assert os.path.basename(files[0]) == 'google-assistant-sdk-screen-out.html' with open(files[0], 'r') as f: assert 'pamplemousse' in f.read() def test_endtoend_audiofileinput(device_model, device_instance): temp_dir = tempfile.mkdtemp() audio_out_file = os.path.join(temp_dir, 'out.raw') out = subprocess.check_output( ['python', '-m', 'googlesamples.assistant.grpc.audiofileinput', '--verbose', '--device-model-id', device_model, '--device-id', device_instance, '-i', 'tests/data/whattimeisit.riff', '-o', audio_out_file], stderr=subprocess.STDOUT) print(out) assert 'what time is it' in builtins.str(out).lower() assert os.path.getsize(audio_out_file) > 0
4,603
5,169
<filename>Specs/4/2/b/FSnapChatLoading/1.0.5/FSnapChatLoading.podspec.json { "name": "FSnapChatLoading", "version": "1.0.5", "summary": "A loading tool similar to that in Snap Chat", "description": "Loading tool similar to that in Snap Chat (framework)", "homepage": "https://github.com/faisalbz/FSnapChatLoading", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "9.0" }, "source": { "git": "https://github.com/faisalbz/FSnapChatLoading.git", "tag": "1.0.5" }, "source_files": "FSnapChatLoading/**/*", "exclude_files": "FSnapChatLoading/*.plist", "swift_version": "4.2" }
269
335
{ "word": "Pharmacognosy", "definitions": [ "The branch of knowledge concerned with medicinal drugs obtained from plants or other natural sources." ], "parts-of-speech": "Noun" }
71
984
// // corecrt_memcpy_s.h // // Copyright (c) Microsoft Corporation. All rights reserved. // // Inline definitions of memcpy_s and memmove_s // #pragma once #include <corecrt.h> #include <errno.h> #include <vcruntime_string.h> #pragma warning(push) #pragma warning(disable: _UCRT_DISABLED_WARNINGS) _UCRT_DISABLE_CLANG_WARNINGS _CRT_BEGIN_C_HEADER #ifndef _CRT_MEMCPY_S_INLINE #define _CRT_MEMCPY_S_INLINE static __inline #endif #define _CRT_MEMCPY_S_VALIDATE_RETURN_ERRCODE(expr, errorcode) \ { \ int _Expr_val=!!(expr); \ if (!(_Expr_val)) \ { \ errno = errorcode; \ _invalid_parameter_noinfo(); \ return errorcode; \ } \ } #if !defined RC_INVOKED && !defined __midl && __STDC_WANT_SECURE_LIB__ _Success_(return == 0) _Check_return_opt_ _CRT_MEMCPY_S_INLINE errno_t __CRTDECL memcpy_s( _Out_writes_bytes_to_opt_(_DestinationSize, _SourceSize) void* const _Destination, _In_ rsize_t const _DestinationSize, _In_reads_bytes_opt_(_SourceSize) void const* const _Source, _In_ rsize_t const _SourceSize ) { if (_SourceSize == 0) { return 0; } _CRT_MEMCPY_S_VALIDATE_RETURN_ERRCODE(_Destination != NULL, EINVAL); if (_Source == NULL || _DestinationSize < _SourceSize) { memset(_Destination, 0, _DestinationSize); _CRT_MEMCPY_S_VALIDATE_RETURN_ERRCODE(_Source != NULL, EINVAL); _CRT_MEMCPY_S_VALIDATE_RETURN_ERRCODE(_DestinationSize >= _SourceSize, ERANGE); // Unreachable, but required to suppress /analyze warnings: return EINVAL; } memcpy(_Destination, _Source, _SourceSize); return 0; } _Check_return_wat_ _CRT_MEMCPY_S_INLINE errno_t __CRTDECL memmove_s( _Out_writes_bytes_to_opt_(_DestinationSize, _SourceSize) void* const _Destination, _In_ rsize_t const _DestinationSize, _In_reads_bytes_opt_(_SourceSize) void const* const _Source, _In_ rsize_t const _SourceSize ) { if (_SourceSize == 0) { return 0; } _CRT_MEMCPY_S_VALIDATE_RETURN_ERRCODE(_Destination != NULL, EINVAL); _CRT_MEMCPY_S_VALIDATE_RETURN_ERRCODE(_Source != NULL, EINVAL); _CRT_MEMCPY_S_VALIDATE_RETURN_ERRCODE(_DestinationSize >= _SourceSize, ERANGE); memmove(_Destination, _Source, _SourceSize); return 0; } #endif #undef _CRT_MEMCPY_S_VALIDATE_RETURN_ERRCODE _UCRT_RESTORE_CLANG_WARNINGS #pragma warning(pop) // _UCRT_DISABLED_WARNINGS _CRT_END_C_HEADER
2,105
834
// Copyright 2004-present Facebook. All Rights Reserved. #pragma once extern "C" { #include <bcm/mpls.h> } #include "fboss/agent/state/LabelForwardingAction.h" #include "fboss/agent/state/LabelForwardingEntry.h" namespace facebook::fboss::utility { bcm_mpls_switch_action_t getLabelSwitchAction( LabelNextHopEntry::Action action, LabelForwardingAction::LabelForwardingType type); bool isValidLabeledNextHopSet( uint32_t maxLabelStackDepth, const LabelNextHopSet& nexthops); bool isValidLabeledNextHop(uint32_t maxLabelStackDepth, const NextHop& nexthop); RouteNextHopEntry::NextHopSet stripLabelForwarding( RouteNextHopEntry::NextHopSet nexthops); } // namespace facebook::fboss::utility
248
451
// File Automatically generated by eLiSe #include "StdAfx.h" #include "cREgDistDx_Four11x2.h" cREgDistDx_Four11x2::cREgDistDx_Four11x2(): cElCompiledFonc(2) { AddIntRef (cIncIntervale("Intr",0,16)); Close(false); } void cREgDistDx_Four11x2::ComputeVal() { double tmp0_ = mLocRegDistu1_x - mLocFour11x2_State_1_0; double tmp1_ = (tmp0_) / mLocFour11x2_State_0_0; double tmp2_ = mLocRegDistu1_y - mLocFour11x2_State_2_0; double tmp3_ = (tmp2_) / mLocFour11x2_State_0_0; double tmp4_ = mCompCoord[9]; double tmp5_ = tmp1_ - tmp4_; double tmp6_ = mCompCoord[10]; double tmp7_ = tmp3_ - tmp6_; double tmp8_ = (tmp5_) * (tmp5_); double tmp9_ = (tmp7_) * (tmp7_); double tmp10_ = tmp8_ + tmp9_; double tmp11_ = (tmp10_) * (tmp10_); double tmp12_ = tmp11_ * (tmp10_); double tmp13_ = tmp12_ * (tmp10_); double tmp14_ = mCompCoord[3]; double tmp15_ = 1 + tmp14_; double tmp16_ = mCompCoord[4]; double tmp17_ = mCompCoord[5]; double tmp18_ = tmp17_ * 2; double tmp19_ = mLocRegDistu2_x - mLocFour11x2_State_1_0; double tmp20_ = (tmp19_) / mLocFour11x2_State_0_0; double tmp21_ = mCompCoord[6]; double tmp22_ = mLocRegDistu2_y - mLocFour11x2_State_2_0; double tmp23_ = (tmp22_) / mLocFour11x2_State_0_0; double tmp24_ = mCompCoord[7]; double tmp25_ = mCompCoord[11]; double tmp26_ = tmp20_ - tmp4_; double tmp27_ = tmp23_ - tmp6_; double tmp28_ = mCompCoord[12]; double tmp29_ = (tmp26_) * (tmp26_); double tmp30_ = (tmp27_) * (tmp27_); double tmp31_ = tmp29_ + tmp30_; double tmp32_ = mCompCoord[13]; double tmp33_ = (tmp31_) * (tmp31_); double tmp34_ = mCompCoord[14]; double tmp35_ = tmp33_ * (tmp31_); double tmp36_ = mCompCoord[15]; double tmp37_ = tmp35_ * (tmp31_); double tmp38_ = (tmp1_) * (tmp3_); double tmp39_ = (tmp3_) * (tmp3_); double tmp40_ = (tmp1_) * (tmp1_); double tmp41_ = tmp25_ * (tmp10_); double tmp42_ = tmp28_ * tmp11_; double tmp43_ = tmp41_ + tmp42_; double tmp44_ = tmp32_ * tmp12_; double tmp45_ = tmp43_ + tmp44_; double tmp46_ = tmp34_ * tmp13_; double tmp47_ = tmp45_ + tmp46_; double tmp48_ = tmp13_ * (tmp10_); double tmp49_ = tmp36_ * tmp48_; double tmp50_ = tmp47_ + tmp49_; double tmp51_ = 1 - tmp14_; double tmp52_ = (tmp20_) * (tmp23_); double tmp53_ = tmp21_ * 2; double tmp54_ = (tmp23_) * (tmp23_); double tmp55_ = mCompCoord[8]; double tmp56_ = (tmp20_) * (tmp20_); double tmp57_ = tmp25_ * (tmp31_); double tmp58_ = tmp28_ * tmp33_; double tmp59_ = tmp57_ + tmp58_; double tmp60_ = tmp32_ * tmp35_; double tmp61_ = tmp59_ + tmp60_; double tmp62_ = tmp34_ * tmp37_; double tmp63_ = tmp61_ + tmp62_; double tmp64_ = tmp37_ * (tmp31_); double tmp65_ = tmp36_ * tmp64_; double tmp66_ = tmp63_ + tmp65_; mVal[0] = (mLocFour11x2_State_1_0 + (((tmp15_) * (tmp1_) + tmp16_ * (tmp3_)) - tmp18_ * tmp40_ + tmp21_ * tmp38_ + tmp24_ * tmp39_ + (tmp5_) * (tmp50_)) * mLocFour11x2_State_0_0) - (mLocFour11x2_State_1_0 + (((tmp15_) * (tmp20_) + tmp16_ * (tmp23_)) - tmp18_ * tmp56_ + tmp21_ * tmp52_ + tmp24_ * tmp54_ + (tmp26_) * (tmp66_)) * mLocFour11x2_State_0_0) - mLocRegDistu3_x; mVal[1] = (mLocFour11x2_State_2_0 + (((tmp51_) * (tmp3_) + tmp16_ * (tmp1_) + tmp17_ * tmp38_) - tmp53_ * tmp39_ + tmp55_ * tmp40_ + (tmp7_) * (tmp50_)) * mLocFour11x2_State_0_0) - (mLocFour11x2_State_2_0 + (((tmp51_) * (tmp23_) + tmp16_ * (tmp20_) + tmp17_ * tmp52_) - tmp53_ * tmp54_ + tmp55_ * tmp56_ + (tmp27_) * (tmp66_)) * mLocFour11x2_State_0_0) - mLocRegDistu3_y; } void cREgDistDx_Four11x2::ComputeValDeriv() { double tmp0_ = mLocRegDistu1_x - mLocFour11x2_State_1_0; double tmp1_ = (tmp0_) / mLocFour11x2_State_0_0; double tmp2_ = mLocRegDistu1_y - mLocFour11x2_State_2_0; double tmp3_ = (tmp2_) / mLocFour11x2_State_0_0; double tmp4_ = mCompCoord[9]; double tmp5_ = tmp1_ - tmp4_; double tmp6_ = mCompCoord[10]; double tmp7_ = tmp3_ - tmp6_; double tmp8_ = (tmp5_) * (tmp5_); double tmp9_ = (tmp7_) * (tmp7_); double tmp10_ = tmp8_ + tmp9_; double tmp11_ = (tmp10_) * (tmp10_); double tmp12_ = tmp11_ * (tmp10_); double tmp13_ = tmp12_ * (tmp10_); double tmp14_ = mCompCoord[3]; double tmp15_ = 1 + tmp14_; double tmp16_ = mCompCoord[4]; double tmp17_ = mCompCoord[5]; double tmp18_ = tmp17_ * 2; double tmp19_ = mLocRegDistu2_x - mLocFour11x2_State_1_0; double tmp20_ = (tmp19_) / mLocFour11x2_State_0_0; double tmp21_ = mCompCoord[6]; double tmp22_ = mLocRegDistu2_y - mLocFour11x2_State_2_0; double tmp23_ = (tmp22_) / mLocFour11x2_State_0_0; double tmp24_ = mCompCoord[7]; double tmp25_ = mCompCoord[11]; double tmp26_ = tmp20_ - tmp4_; double tmp27_ = tmp23_ - tmp6_; double tmp28_ = mCompCoord[12]; double tmp29_ = (tmp26_) * (tmp26_); double tmp30_ = (tmp27_) * (tmp27_); double tmp31_ = tmp29_ + tmp30_; double tmp32_ = mCompCoord[13]; double tmp33_ = (tmp31_) * (tmp31_); double tmp34_ = mCompCoord[14]; double tmp35_ = tmp33_ * (tmp31_); double tmp36_ = mCompCoord[15]; double tmp37_ = tmp35_ * (tmp31_); double tmp38_ = (tmp1_) * (tmp1_); double tmp39_ = (tmp20_) * (tmp20_); double tmp40_ = (tmp1_) * (tmp3_); double tmp41_ = (tmp20_) * (tmp23_); double tmp42_ = (tmp3_) * (tmp3_); double tmp43_ = (tmp23_) * (tmp23_); double tmp44_ = tmp25_ * (tmp10_); double tmp45_ = tmp28_ * tmp11_; double tmp46_ = tmp44_ + tmp45_; double tmp47_ = tmp32_ * tmp12_; double tmp48_ = tmp46_ + tmp47_; double tmp49_ = tmp34_ * tmp13_; double tmp50_ = tmp48_ + tmp49_; double tmp51_ = tmp13_ * (tmp10_); double tmp52_ = tmp36_ * tmp51_; double tmp53_ = tmp50_ + tmp52_; double tmp54_ = -(1); double tmp55_ = tmp54_ * (tmp5_); double tmp56_ = tmp55_ + tmp55_; double tmp57_ = (tmp56_) * (tmp10_); double tmp58_ = tmp57_ + tmp57_; double tmp59_ = (tmp58_) * (tmp10_); double tmp60_ = (tmp56_) * tmp11_; double tmp61_ = tmp59_ + tmp60_; double tmp62_ = (tmp61_) * (tmp10_); double tmp63_ = (tmp56_) * tmp12_; double tmp64_ = tmp62_ + tmp63_; double tmp65_ = tmp25_ * (tmp31_); double tmp66_ = tmp28_ * tmp33_; double tmp67_ = tmp65_ + tmp66_; double tmp68_ = tmp32_ * tmp35_; double tmp69_ = tmp67_ + tmp68_; double tmp70_ = tmp34_ * tmp37_; double tmp71_ = tmp69_ + tmp70_; double tmp72_ = tmp37_ * (tmp31_); double tmp73_ = tmp36_ * tmp72_; double tmp74_ = tmp71_ + tmp73_; double tmp75_ = tmp54_ * (tmp26_); double tmp76_ = tmp75_ + tmp75_; double tmp77_ = (tmp76_) * (tmp31_); double tmp78_ = tmp77_ + tmp77_; double tmp79_ = (tmp78_) * (tmp31_); double tmp80_ = (tmp76_) * tmp33_; double tmp81_ = tmp79_ + tmp80_; double tmp82_ = (tmp81_) * (tmp31_); double tmp83_ = (tmp76_) * tmp35_; double tmp84_ = tmp82_ + tmp83_; double tmp85_ = tmp54_ * (tmp7_); double tmp86_ = tmp85_ + tmp85_; double tmp87_ = (tmp86_) * (tmp10_); double tmp88_ = tmp87_ + tmp87_; double tmp89_ = (tmp88_) * (tmp10_); double tmp90_ = (tmp86_) * tmp11_; double tmp91_ = tmp89_ + tmp90_; double tmp92_ = (tmp91_) * (tmp10_); double tmp93_ = (tmp86_) * tmp12_; double tmp94_ = tmp92_ + tmp93_; double tmp95_ = tmp54_ * (tmp27_); double tmp96_ = tmp95_ + tmp95_; double tmp97_ = (tmp96_) * (tmp31_); double tmp98_ = tmp97_ + tmp97_; double tmp99_ = (tmp98_) * (tmp31_); double tmp100_ = (tmp96_) * tmp33_; double tmp101_ = tmp99_ + tmp100_; double tmp102_ = (tmp101_) * (tmp31_); double tmp103_ = (tmp96_) * tmp35_; double tmp104_ = tmp102_ + tmp103_; double tmp105_ = 1 - tmp14_; double tmp106_ = tmp21_ * 2; double tmp107_ = mCompCoord[8]; double tmp108_ = (tmp1_) * mLocFour11x2_State_0_0; double tmp109_ = (tmp20_) * mLocFour11x2_State_0_0; double tmp110_ = tmp108_ - tmp109_; double tmp111_ = tmp40_ * mLocFour11x2_State_0_0; double tmp112_ = tmp41_ * mLocFour11x2_State_0_0; double tmp113_ = tmp111_ - tmp112_; double tmp114_ = (tmp56_) * tmp25_; double tmp115_ = (tmp58_) * tmp28_; double tmp116_ = tmp114_ + tmp115_; double tmp117_ = (tmp61_) * tmp32_; double tmp118_ = tmp116_ + tmp117_; double tmp119_ = (tmp64_) * tmp34_; double tmp120_ = tmp118_ + tmp119_; double tmp121_ = (tmp64_) * (tmp10_); double tmp122_ = (tmp56_) * tmp13_; double tmp123_ = tmp121_ + tmp122_; double tmp124_ = (tmp123_) * tmp36_; double tmp125_ = tmp120_ + tmp124_; double tmp126_ = (tmp76_) * tmp25_; double tmp127_ = (tmp78_) * tmp28_; double tmp128_ = tmp126_ + tmp127_; double tmp129_ = (tmp81_) * tmp32_; double tmp130_ = tmp128_ + tmp129_; double tmp131_ = (tmp84_) * tmp34_; double tmp132_ = tmp130_ + tmp131_; double tmp133_ = (tmp84_) * (tmp31_); double tmp134_ = (tmp76_) * tmp37_; double tmp135_ = tmp133_ + tmp134_; double tmp136_ = (tmp135_) * tmp36_; double tmp137_ = tmp132_ + tmp136_; double tmp138_ = tmp54_ * (tmp53_); double tmp139_ = (tmp86_) * tmp25_; double tmp140_ = (tmp88_) * tmp28_; double tmp141_ = tmp139_ + tmp140_; double tmp142_ = (tmp91_) * tmp32_; double tmp143_ = tmp141_ + tmp142_; double tmp144_ = (tmp94_) * tmp34_; double tmp145_ = tmp143_ + tmp144_; double tmp146_ = (tmp94_) * (tmp10_); double tmp147_ = (tmp86_) * tmp13_; double tmp148_ = tmp146_ + tmp147_; double tmp149_ = (tmp148_) * tmp36_; double tmp150_ = tmp145_ + tmp149_; double tmp151_ = tmp54_ * (tmp74_); double tmp152_ = (tmp96_) * tmp25_; double tmp153_ = (tmp98_) * tmp28_; double tmp154_ = tmp152_ + tmp153_; double tmp155_ = (tmp101_) * tmp32_; double tmp156_ = tmp154_ + tmp155_; double tmp157_ = (tmp104_) * tmp34_; double tmp158_ = tmp156_ + tmp157_; double tmp159_ = (tmp104_) * (tmp31_); double tmp160_ = (tmp96_) * tmp37_; double tmp161_ = tmp159_ + tmp160_; double tmp162_ = (tmp161_) * tmp36_; double tmp163_ = tmp158_ + tmp162_; mVal[0] = (mLocFour11x2_State_1_0 + (((tmp15_) * (tmp1_) + tmp16_ * (tmp3_)) - tmp18_ * tmp38_ + tmp21_ * tmp40_ + tmp24_ * tmp42_ + (tmp5_) * (tmp53_)) * mLocFour11x2_State_0_0) - (mLocFour11x2_State_1_0 + (((tmp15_) * (tmp20_) + tmp16_ * (tmp23_)) - tmp18_ * tmp39_ + tmp21_ * tmp41_ + tmp24_ * tmp43_ + (tmp26_) * (tmp74_)) * mLocFour11x2_State_0_0) - mLocRegDistu3_x; mCompDer[0][0] = 0; mCompDer[0][1] = 0; mCompDer[0][2] = 0; mCompDer[0][3] = tmp110_; mCompDer[0][4] = (tmp3_) * mLocFour11x2_State_0_0 - (tmp23_) * mLocFour11x2_State_0_0; mCompDer[0][5] = -(2 * tmp38_) * mLocFour11x2_State_0_0 - -(2 * tmp39_) * mLocFour11x2_State_0_0; mCompDer[0][6] = tmp113_; mCompDer[0][7] = tmp42_ * mLocFour11x2_State_0_0 - tmp43_ * mLocFour11x2_State_0_0; mCompDer[0][8] = 0; mCompDer[0][9] = (tmp138_ + (tmp125_) * (tmp5_)) * mLocFour11x2_State_0_0 - (tmp151_ + (tmp137_) * (tmp26_)) * mLocFour11x2_State_0_0; mCompDer[0][10] = (tmp150_) * (tmp5_) * mLocFour11x2_State_0_0 - (tmp163_) * (tmp26_) * mLocFour11x2_State_0_0; mCompDer[0][11] = (tmp10_) * (tmp5_) * mLocFour11x2_State_0_0 - (tmp31_) * (tmp26_) * mLocFour11x2_State_0_0; mCompDer[0][12] = tmp11_ * (tmp5_) * mLocFour11x2_State_0_0 - tmp33_ * (tmp26_) * mLocFour11x2_State_0_0; mCompDer[0][13] = tmp12_ * (tmp5_) * mLocFour11x2_State_0_0 - tmp35_ * (tmp26_) * mLocFour11x2_State_0_0; mCompDer[0][14] = tmp13_ * (tmp5_) * mLocFour11x2_State_0_0 - tmp37_ * (tmp26_) * mLocFour11x2_State_0_0; mCompDer[0][15] = tmp51_ * (tmp5_) * mLocFour11x2_State_0_0 - tmp72_ * (tmp26_) * mLocFour11x2_State_0_0; mVal[1] = (mLocFour11x2_State_2_0 + (((tmp105_) * (tmp3_) + tmp16_ * (tmp1_) + tmp17_ * tmp40_) - tmp106_ * tmp42_ + tmp107_ * tmp38_ + (tmp7_) * (tmp53_)) * mLocFour11x2_State_0_0) - (mLocFour11x2_State_2_0 + (((tmp105_) * (tmp23_) + tmp16_ * (tmp20_) + tmp17_ * tmp41_) - tmp106_ * tmp43_ + tmp107_ * tmp39_ + (tmp27_) * (tmp74_)) * mLocFour11x2_State_0_0) - mLocRegDistu3_y; mCompDer[1][0] = 0; mCompDer[1][1] = 0; mCompDer[1][2] = 0; mCompDer[1][3] = tmp54_ * (tmp3_) * mLocFour11x2_State_0_0 - tmp54_ * (tmp23_) * mLocFour11x2_State_0_0; mCompDer[1][4] = tmp110_; mCompDer[1][5] = tmp113_; mCompDer[1][6] = -(2 * tmp42_) * mLocFour11x2_State_0_0 - -(2 * tmp43_) * mLocFour11x2_State_0_0; mCompDer[1][7] = 0; mCompDer[1][8] = tmp38_ * mLocFour11x2_State_0_0 - tmp39_ * mLocFour11x2_State_0_0; mCompDer[1][9] = (tmp125_) * (tmp7_) * mLocFour11x2_State_0_0 - (tmp137_) * (tmp27_) * mLocFour11x2_State_0_0; mCompDer[1][10] = (tmp138_ + (tmp150_) * (tmp7_)) * mLocFour11x2_State_0_0 - (tmp151_ + (tmp163_) * (tmp27_)) * mLocFour11x2_State_0_0; mCompDer[1][11] = (tmp10_) * (tmp7_) * mLocFour11x2_State_0_0 - (tmp31_) * (tmp27_) * mLocFour11x2_State_0_0; mCompDer[1][12] = tmp11_ * (tmp7_) * mLocFour11x2_State_0_0 - tmp33_ * (tmp27_) * mLocFour11x2_State_0_0; mCompDer[1][13] = tmp12_ * (tmp7_) * mLocFour11x2_State_0_0 - tmp35_ * (tmp27_) * mLocFour11x2_State_0_0; mCompDer[1][14] = tmp13_ * (tmp7_) * mLocFour11x2_State_0_0 - tmp37_ * (tmp27_) * mLocFour11x2_State_0_0; mCompDer[1][15] = tmp51_ * (tmp7_) * mLocFour11x2_State_0_0 - tmp72_ * (tmp27_) * mLocFour11x2_State_0_0; } void cREgDistDx_Four11x2::ComputeValDerivHessian() { ELISE_ASSERT(false,"Foncteur cREgDistDx_Four11x2 Has no Der Sec"); } void cREgDistDx_Four11x2::SetFour11x2_State_0_0(double aVal){ mLocFour11x2_State_0_0 = aVal;} void cREgDistDx_Four11x2::SetFour11x2_State_1_0(double aVal){ mLocFour11x2_State_1_0 = aVal;} void cREgDistDx_Four11x2::SetFour11x2_State_2_0(double aVal){ mLocFour11x2_State_2_0 = aVal;} void cREgDistDx_Four11x2::SetRegDistu1_x(double aVal){ mLocRegDistu1_x = aVal;} void cREgDistDx_Four11x2::SetRegDistu1_y(double aVal){ mLocRegDistu1_y = aVal;} void cREgDistDx_Four11x2::SetRegDistu2_x(double aVal){ mLocRegDistu2_x = aVal;} void cREgDistDx_Four11x2::SetRegDistu2_y(double aVal){ mLocRegDistu2_y = aVal;} void cREgDistDx_Four11x2::SetRegDistu3_x(double aVal){ mLocRegDistu3_x = aVal;} void cREgDistDx_Four11x2::SetRegDistu3_y(double aVal){ mLocRegDistu3_y = aVal;} double * cREgDistDx_Four11x2::AdrVarLocFromString(const std::string & aName) { if (aName == "Four11x2_State_0_0") return & mLocFour11x2_State_0_0; if (aName == "Four11x2_State_1_0") return & mLocFour11x2_State_1_0; if (aName == "Four11x2_State_2_0") return & mLocFour11x2_State_2_0; if (aName == "RegDistu1_x") return & mLocRegDistu1_x; if (aName == "RegDistu1_y") return & mLocRegDistu1_y; if (aName == "RegDistu2_x") return & mLocRegDistu2_x; if (aName == "RegDistu2_y") return & mLocRegDistu2_y; if (aName == "RegDistu3_x") return & mLocRegDistu3_x; if (aName == "RegDistu3_y") return & mLocRegDistu3_y; return 0; } cElCompiledFonc::cAutoAddEntry cREgDistDx_Four11x2::mTheAuto("cREgDistDx_Four11x2",cREgDistDx_Four11x2::Alloc); cElCompiledFonc * cREgDistDx_Four11x2::Alloc() { return new cREgDistDx_Four11x2(); }
7,172
743
<filename>hermes-common/src/main/java/pl/allegro/tech/hermes/domain/filtering/header/HeaderPredicate.java package pl.allegro.tech.hermes.domain.filtering.header; import pl.allegro.tech.hermes.domain.filtering.FilterableMessage; import java.util.function.Predicate; import java.util.regex.Pattern; class HeaderPredicate implements Predicate<FilterableMessage> { private final String name; private final Pattern valuePattern; HeaderPredicate(String name, Pattern valuePattern) { this.name = name; this.valuePattern = valuePattern; } @Override public boolean test(FilterableMessage message) { return message.getExternalMetadata() .entrySet().stream() .filter(h -> h.getKey().equals(name)) .findFirst() .filter(h -> valuePattern.matcher(h.getValue()).matches()) .isPresent(); } }
361
849
<gh_stars>100-1000 #ifndef PROFILER_H #define PROFILER_H #include "rdtsc.h" struct name_mapper { int number; const char* name; }; extern name_mapper name_map[]; class profiling_checker { public: profiling_checker(int number); ~profiling_checker(); private: int number_; uint64_t start_time_; }; inline profiling_checker::profiling_checker(int number) : number_(number) { start_time_ = rdtsc(); } #ifdef NDEBUG #define PROFILE_CHECK(func_number) (void)0 #else #define PROFILE_CHECK(func_number) profiling_checker _checker(func_number) #endif #endif // PROFILER_H
248
473
<gh_stars>100-1000 /* * Copyright (C) <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "libcgc.h" #include "cgc_common.h" const char *CB_NAME = " TAP"; #define PIPE_RECV_CBS PIPE_TAP_B #define PIPE_RECV_CRS STDIN #define PIPE_SEND_CRS STDOUT #define PIPE_SEND_CB1 PIPE_CB1_A #define PIPE_SEND_CB2 PIPE_CB2_A /** * Called when the CRS issues a shutdown command. This function propagates the * shutdown to all CBs in the set then cgc__terminate(0)s itself. * * @return void */ void cgc_do_exit(msg *exit_msg); /** * Implement a simple blocking router to mediate between the CB set and the CRS. * Messages are routed based on their desintation field, allowing the CRS to * address any particular CB. * * @return An int indicating SUCCESS (0) or an error condition (!=0). */ int main(int cgc_argc, char *cgc_argv[]);
589
364
<reponame>spring-operator/reactive-streams-commons package rsc.publisher; import java.util.Objects; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.function.BooleanSupplier; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import rsc.subscriber.MultiSubscriptionSubscriber; import rsc.util.ExceptionHelper; /** * Repeatedly subscribes to the source if the predicate returns true after * completion of the previous subscription. * * @param <T> the value type */ public final class PublisherRepeatPredicate<T> extends PublisherSource<T, T> { final BooleanSupplier predicate; public PublisherRepeatPredicate(Publisher<? extends T> source, BooleanSupplier predicate) { super(source); this.predicate = Objects.requireNonNull(predicate, "predicate"); } @Override public void subscribe(Subscriber<? super T> s) { PublisherRepeatPredicateSubscriber<T> parent = new PublisherRepeatPredicateSubscriber<>(source, s, predicate); s.onSubscribe(parent); if (!parent.isCancelled()) { parent.resubscribe(); } } static final class PublisherRepeatPredicateSubscriber<T> extends MultiSubscriptionSubscriber<T, T> { final Publisher<? extends T> source; final BooleanSupplier predicate; volatile int wip; @SuppressWarnings("rawtypes") static final AtomicIntegerFieldUpdater<PublisherRepeatPredicateSubscriber> WIP = AtomicIntegerFieldUpdater.newUpdater(PublisherRepeatPredicateSubscriber.class, "wip"); long produced; public PublisherRepeatPredicateSubscriber(Publisher<? extends T> source, Subscriber<? super T> actual, BooleanSupplier predicate) { super(actual); this.source = source; this.predicate = predicate; } @Override public void onNext(T t) { produced++; subscriber.onNext(t); } @Override public void onComplete() { boolean b; try { b = predicate.getAsBoolean(); } catch (Throwable e) { ExceptionHelper.throwIfFatal(e); subscriber.onError(ExceptionHelper.unwrap(e)); return; } if (b) { resubscribe(); } else { subscriber.onComplete(); } } void resubscribe() { if (WIP.getAndIncrement(this) == 0) { do { if (isCancelled()) { return; } long c = produced; if (c != 0L) { produced = 0L; produced(c); } source.subscribe(this); } while (WIP.decrementAndGet(this) != 0); } } } }
1,407
403
package io.craft.atom.util.schedule; import io.craft.atom.test.CaseCounter; import io.craft.atom.util.schedule.ExpirationListener; import io.craft.atom.util.schedule.TimingWheel; import java.util.Date; import java.util.Set; import java.util.concurrent.TimeUnit; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author mindwind * @version 1.0, Sep 21, 2012 */ public class TestTimingWheel { private static final Logger LOG = LoggerFactory.getLogger(TestTimingWheel.class); private TimingWheel<String> wheel ; private volatile long startTime; private volatile long endTime ; @Before public void before() { wheel = new TimingWheel<String>(1, 500, TimeUnit.MILLISECONDS); wheel.addExpirationListener(new TestExpirationListener()); wheel.start(); } @After public void after() { wheel.stop(); } @Test public void testAdd() throws InterruptedException { startTime = System.currentTimeMillis(); long ttl = wheel.add("test-0"); LOG.debug("[CRAFT-ATOM-UTIL] Add object test-0 to timing wheel, will timeout after {} ms, start time={}", ttl, new Date(startTime)); for (int i = 1; i <= 30; i++) { Thread.sleep(10); wheel.add("test-" + i); } Assert.assertEquals(31, wheel.size()); System.out.println(String.format("[CRAFT-ATOM-UTIL] (^_^) <%s> Case -> test timing wheel add. ", CaseCounter.incr(1))); } @Test public void testRemove() throws InterruptedException { for (int i = 1; i <= 10; i++) { Thread.sleep(10); wheel.add("test-" + i); } Assert.assertEquals(10, wheel.size()); wheel.remove("test-3"); wheel.remove("test-4"); wheel.remove("test-5"); Assert.assertEquals(7, wheel.size()); Set<String> set = wheel.elements(); Assert.assertEquals(7, set.size()); System.out.println(String.format("[CRAFT-ATOM-UTIL] (^_^) <%s> Case -> test timing wheel remove. ", CaseCounter.incr(3))); } @Test public void testAddTwice() throws InterruptedException { startTime = System.currentTimeMillis(); long ttl = wheel.add("test-1"); LOG.debug("[CRAFT-ATOM-UTIL] Add object test-1 to timing wheel, will timeout after {} ms, start time={}", ttl, new Date(startTime)); Thread.sleep(20); ttl = wheel.add("test-1"); LOG.debug("[CRAFT-ATOM-UTIL] Add object test-1 second to timing wheel, will timeout after {} ms, start time={}", ttl, new Date(startTime)); Assert.assertEquals(1, wheel.size()); System.out.println(String.format("[CRAFT-ATOM-UTIL] (^_^) <%s> Case -> test timing wheel add twice. ", CaseCounter.incr(1))); } @Test public void testExpire() throws InterruptedException { startTime = System.currentTimeMillis(); long ttl = wheel.add("test-1"); while(endTime == 0); long deviation = (endTime - startTime) - ttl; LOG.debug("[CRAFT-ATOM-UTIL] Timing wheel deviation={}", deviation); Assert.assertTrue(deviation <= 2); Assert.assertTrue(deviation >= -2); System.out.println(String.format("[CRAFT-ATOM-UTIL] (^_^) <%s> Case -> test timing wheel expire. ", CaseCounter.incr(2))); } private class TestExpirationListener implements ExpirationListener<String> { @Override public void expired(String expiredObject) { endTime = System.currentTimeMillis(); LOG.debug("[CRAFT-ATOM-UTIL] Expired object={} end time={}", expiredObject, new Date(endTime)); } } }
1,313
361
<gh_stars>100-1000 # -*- coding: utf-8 -*- # # Copyright (c) 2019-2020 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2-Clause """ Execute cve-bin-tool https://github.com/intel/cve-bin-tool This plugin does not support installation of cve-bin-tool The assumption is that cve-bin-tool is globally executable """ import logging from tern.analyze import passthrough from tern.extensions.executor import Executor from tern.utils import constants logger = logging.getLogger(constants.logger_name) class CveBinTool(Executor): '''Execute cve-bin-tool''' def execute(self, image_obj, redo=False): '''Execution should be: cve-bin-tool -x -u now /path/to/directory ''' command = 'cve-bin-tool -x -u now' for layer in image_obj.layers: # execute the command for each layer logger.debug("Analyzing layer %s", layer.layer_index) passthrough.execute_and_pass(layer, command, True) # for now we just print the results for each layer print(layer.analyzed_output) def execute_layer(self, image_layer, redo=False): command = 'cve-bin-tool -x -u now' logger.debug("Analyzing layer %s", image_layer.layer_index) passthrough.execute_and_pass(image_layer, command, True) # for now we just print the results for each image_layer print(image_layer.analyzed_output)
567
401
// // TOPasscodeCircleImage.h // // Copyright 2017 <NAME>. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** A subclass of `UIImage` that can procedurally generate both hollow and full circle graphics at any size. These are used for the 'normal' and 'tapped' states of the passcode circle buttons. */ @interface TOPasscodeCircleImage : UIImage /** Generates and returns a `UIImage` of a filled circle at the specified size. @param size The diameter of the final circle image @param inset An inset value that will shrink the size of the circle. This is so it can be overlaid on a hollow circle without interfering with the anti-aliasing on the outer border. @param padding External padding around the circle to ensure it won't be clipped by the edge of the layer. Setting this value will increase the dimensions of the final `UIImage`. @param antialias Whether the circle boundary will be antialiased (Since antialiasing is unnecessary if this circle will overlay another.) */ + (UIImage *)circleImageOfSize:(CGFloat)size inset:(CGFloat)inset padding:(CGFloat)padding antialias:(BOOL)antialias; /** Generates and returns a `UIImage` of a hollow circle at the specified size. @param size The diameter of the final circle image @param strokeWidth The thickness, in points, of the stroke making up the circle image. @param padding External padding around the circle to ensure it won't be clipped by the edge of the layer. Setting this value will increase the dimensions of the final `UIImage`. */ + (UIImage *)hollowCircleImageOfSize:(CGFloat)size strokeWidth:(CGFloat)strokeWidth padding:(CGFloat)padding; @end NS_ASSUME_NONNULL_END
819
546
<filename>include/Msnhnet/robot/MsnhSegment.h #ifndef SEGMENT_H #define SEGMENT_H #include "Msnhnet/robot/MsnhFrame.h" #include "Msnhnet/robot/MsnhJoint.h" namespace Msnhnet { class MsnhNet_API Segment { public: Segment(const std::string &name, const Joint &joint=Joint(Joint::JOINT_FIXED), const Frame& endToTip=Frame(), const double jointMin = -DBL_MAX, const double jointMax = DBL_MAX); Segment(const Joint &joint=Joint(Joint::JOINT_FIXED), const Frame& endToTip=Frame(), const double jointMin = -DBL_MAX, const double jointMax = DBL_MAX); Segment(const Segment& in); Segment& operator=(const Segment& in); std::string getName() const; Joint getJoint() const; Frame getEndToTip() const; Frame getPos(const double &q) const; Twist getTwist(const double &q, const double &qdot) const; double getJointMin() const; double getJointMax() const; Joint::MoveType getMoveType() const; private: std::string _name; Joint _joint; Frame _endToTip; double _jointMin = -DBL_MAX; double _jointMax = DBL_MAX; Joint::MoveType _moveType; }; } #endif
504
72,551
//===--- MigratorOptions.h - Swift Migrator ---------------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // A container for Swift Migrator options pulled in through the driver/frontend. // //===----------------------------------------------------------------------===// #ifndef SWIFT_MIGRATOR_MIGRATOROPTIONS_H #define SWIFT_MIGRATOR_MIGRATOROPTIONS_H namespace swift { struct MigratorOptions { /// Add `@objc` to declarations that would've been implicitly /// visible to the Objective-C runtime in Swift 3. bool KeepObjcVisibility = false; /// Skip the migration phase that repeatedly asks for fix-its from the /// compiler and applies them. This is generally for debugging. bool EnableMigratorFixits = true; /// Whether to print each USR we query the api change data store about. bool DumpUsr = false; /// If non-empty, print a replacement map describing changes to get from /// the first MigrationState's output text to the last MigrationState's /// output text. std::string EmitRemapFilePath = ""; /// If non-empty, print the last MigrationState's output text to the given /// file path. std::string EmitMigratedFilePath = ""; /// If non-empty, dump all Migrator::States to this directory. std::string DumpMigrationStatesDir = ""; /// If non-empty, use the api change data serialized to this path. std::vector<std::string> APIDigesterDataStorePaths; bool shouldRunMigrator() const { return !(EmitRemapFilePath.empty() && EmitMigratedFilePath.empty() && DumpMigrationStatesDir.empty()); } }; } // end namespace swift #endif // SWIFT_MIGRATOR_MIGRATOROPTIONS_H
584
988
<filename>src/yvalve/perf.cpp /* * PROGRAM: JRD Access Method * MODULE: perf.cpp * DESCRIPTION: Performance monitoring routines * * The contents of this file are subject to the Interbase Public * License Version 1.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.Inprise.com/IPL.html * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code was created by Inprise Corporation * and its predecessors. Portions created by Inprise Corporation are * Copyright (C) Inprise Corporation. * * All Rights Reserved. * Contributor(s): ______________________________________. * * 2002.02.15 <NAME> - Code Cleanup, removed obsolete "DELTA" port * 2002.02.15 <NAME> - Code Cleanup, removed obsolete "IMP" port * * 2002.10.30 <NAME> - Removed support for obsolete "PC_PLATFORM" define * */ #include "firebird.h" #include <stdio.h> #include <limits.h> #include "ibase.h" #include "../yvalve/perf.h" #include "../yvalve/gds_proto.h" #include "../yvalve/perf_proto.h" #include "../yvalve/utl_proto.h" #include "../yvalve/YObjects.h" #include "../common/gdsassert.h" #include "../common/classes/fb_string.h" #if defined(TIME_WITH_SYS_TIME) #include <sys/time.h> #include <time.h> #elif defined(HAVE_SYS_TIME_H) #include <sys/time.h> #else #include <time.h> #endif #ifdef HAVE_SYS_TIMEB_H #include <sys/timeb.h> #endif template <typename T> static SINT64 get_parameter(const T** ptr) { /************************************** * * g e t _ p a r a m e t e r * ************************************** * * Functional description * Get a parameter (length is encoded), convert to internal form, * and return. * **************************************/ SSHORT l = *(*ptr)++; l += (*(*ptr)++) << 8; const SINT64 parameter = isc_portable_integer(reinterpret_cast<const ISC_UCHAR*>(*ptr), l); *ptr += l; return parameter; } #ifndef HAVE_TIMES static void times(struct tms*); #endif static const SCHAR items[] = { isc_info_reads, isc_info_writes, isc_info_fetches, isc_info_marks, isc_info_page_size, isc_info_num_buffers, isc_info_current_memory, isc_info_max_memory }; static const SCHAR* report = "elapsed = !e cpu = !u reads = !r writes = !w fetches = !f marks = !m$"; #if defined(WIN_NT) && !defined(CLOCKS_PER_SEC) #define TICK 100 #endif // EKU: TICK (sys/param.h) and CLOCKS_PER_SEC (time.h) may both be defined #if !defined(TICK) && defined(CLOCKS_PER_SEC) #define TICK ((SLONG)CLOCKS_PER_SEC) #endif #ifndef TICK #define TICK ((SLONG)CLK_TCK) #endif template<typename P> static int perf_format(const P* before, const P* after, const SCHAR* string, SCHAR* buffer, SSHORT* buf_len) { /************************************** * * P E R F _ f o r m a t * ************************************** * * Functional description * Format a buffer with statistical stuff under control of formatting * string. Substitute in appropriate stuff. Return the length of the * formatting output. * **************************************/ SCHAR c; SLONG buffer_length = buf_len ? *buf_len : 0; SCHAR* p = buffer; if (buffer_length < 0) { buffer_length = 0; } while ((c = *string++) && c != '$') { if (c != '!') *p++ = c; else { SINT64 delta; switch (c = *string++) { case 'r': delta = after->perf_reads - before->perf_reads; break; case 'w': delta = after->perf_writes - before->perf_writes; break; case 'f': delta = after->perf_fetches - before->perf_fetches; break; case 'm': delta = after->perf_marks - before->perf_marks; break; case 'd': delta = after->perf_current_memory - before->perf_current_memory; break; case 'p': delta = after->perf_page_size; break; case 'b': delta = after->perf_buffers; break; case 'c': delta = after->perf_current_memory; break; case 'x': delta = after->perf_max_memory; break; case 'e': delta = after->perf_elapsed - before->perf_elapsed; break; case 'u': delta = after->perf_times.tms_utime - before->perf_times.tms_utime; break; case 's': delta = after->perf_times.tms_stime - before->perf_times.tms_stime; break; default: sprintf(p, "?%c?", c); while (*p) p++; } switch (c) { case 'r': case 'w': case 'f': case 'm': case 'd': case 'p': case 'b': case 'c': case 'x': sprintf(p, "%" SQUADFORMAT, delta); while (*p) p++; break; case 'u': case 's': sprintf(p, "%" SQUADFORMAT".%.2" SQUADFORMAT, delta / TICK, (delta % TICK) * 100 / TICK); while (*p) p++; break; case 'e': sprintf(p, "%" SQUADFORMAT".%.2" SQUADFORMAT, delta / 100, delta % 100); while (*p) p++; break; } } } *p = 0; const int length = static_cast<int>(p - buffer); if (buffer_length && (buffer_length -= length) >= 0) { memset(p, ' ', static_cast<size_t>(buffer_length)); } return length; } template<typename P> static void perf_get_info(FB_API_HANDLE* handle, P* perf) { /************************************** * * P E R F _ g e t _ i n f o * ************************************** * * Functional description * Acquire timing and performance information. Some info comes * from the system and some from the database. * **************************************/ SSHORT buffer_length, item_length; ISC_STATUS_ARRAY jrd_status; #ifdef HAVE_GETTIMEOFDAY struct timeval tp; #else struct timeb time_buffer; #define LARGE_NUMBER 696600000 // to avoid overflow, get rid of decades) #endif // If there isn't a database, zero everything out if (!*handle) { memset(perf, 0, sizeof(PERF)); } // Get system time times(&perf->perf_times); #ifdef HAVE_GETTIMEOFDAY GETTIMEOFDAY(&tp); perf->perf_elapsed = tp.tv_sec * 100 + tp.tv_usec / 10000; #else ftime(&time_buffer); perf->perf_elapsed = (time_buffer.time - LARGE_NUMBER) * 100 + (time_buffer.millitm / 10); #endif if (!*handle) return; SCHAR buffer[256]; buffer_length = sizeof(buffer); item_length = sizeof(items); isc_database_info(jrd_status, handle, item_length, items, buffer_length, buffer); const char* p = buffer; while (true) switch (*p++) { case isc_info_reads: perf->perf_reads = get_parameter(&p); break; case isc_info_writes: perf->perf_writes = get_parameter(&p); break; case isc_info_marks: perf->perf_marks = get_parameter(&p); break; case isc_info_fetches: perf->perf_fetches = get_parameter(&p); break; case isc_info_num_buffers: perf->perf_buffers = get_parameter(&p); break; case isc_info_page_size: perf->perf_page_size = get_parameter(&p); break; case isc_info_current_memory: perf->perf_current_memory = get_parameter(&p); break; case isc_info_max_memory: perf->perf_max_memory = get_parameter(&p); break; case isc_info_end: return; case isc_info_error: switch (p[2]) { case isc_info_marks: perf->perf_marks = 0; break; case isc_info_current_memory: perf->perf_current_memory = 0; break; case isc_info_max_memory: perf->perf_max_memory = 0; break; } { const SLONG temp = isc_vax_integer(p, 2); fb_assert(temp <= MAX_SSHORT); p += temp + 2; } perf->perf_marks = 0; break; default: return; } } template<typename P> static void perf_report(const P* before, const P* after, SCHAR* buffer, SSHORT* buf_len) { /************************************** * * p e r f _ r e p o r t * ************************************** * * Functional description * Report a common set of parameters. * **************************************/ perf_format<P>(before, after, report, buffer, buf_len); } #ifndef HAVE_TIMES static void times(struct tms* buffer) { /************************************** * * t i m e s * ************************************** * * Functional description * Emulate the good old unix call "times". Only both with user time. * **************************************/ buffer->tms_utime = clock(); } #endif int API_ROUTINE perf_format(const PERF* before, const PERF* after, const SCHAR* string, SCHAR* buffer, SSHORT* buf_len) { return perf_format<PERF>(before, after, string, buffer, buf_len); } int API_ROUTINE perf64_format(const PERF64* before, const PERF64* after, const SCHAR* string, SCHAR* buffer, SSHORT* buf_len) { return perf_format<PERF64>(before, after, string, buffer, buf_len); } void API_ROUTINE perf_get_info(FB_API_HANDLE* handle, PERF* perf) { perf_get_info<PERF>(handle, perf); } void API_ROUTINE perf64_get_info(FB_API_HANDLE* handle, PERF64* perf) { perf_get_info<PERF64>(handle, perf); } void API_ROUTINE perf_report(const PERF* before, const PERF* after, SCHAR* buffer, SSHORT* buf_len) { perf_report<PERF>(before, after, buffer, buf_len); } void API_ROUTINE perf64_report(const PERF64* before, const PERF64* after, SCHAR* buffer, SSHORT* buf_len) { perf_report<PERF64>(before, after, buffer, buf_len); } namespace { static const unsigned CNT_DB_INFO = 1; static const unsigned CNT_TIMER = 2; enum CntTimer {CNT_TIME_REAL, CNT_TIME_USER, CNT_TIME_SYSTEM}; struct KnownCounters { const char* name; unsigned type; unsigned code; }; #define TOTAL_COUNTERS 11 // we use case-insensitive names, here they are written with capital letters for human readability KnownCounters knownCounters[TOTAL_COUNTERS] = { {"RealTime", CNT_TIMER, CNT_TIME_REAL}, {"UserTime", CNT_TIMER, CNT_TIME_USER}, {"SystemTime", CNT_TIMER, CNT_TIME_SYSTEM}, {"Fetches", CNT_DB_INFO, isc_info_fetches}, {"Marks", CNT_DB_INFO, isc_info_marks}, {"Reads", CNT_DB_INFO, isc_info_reads}, {"Writes", CNT_DB_INFO, isc_info_writes}, {"CurrentMemory", CNT_DB_INFO, isc_info_current_memory}, {"MaxMemory", CNT_DB_INFO, isc_info_max_memory}, {"Buffers", CNT_DB_INFO, isc_info_num_buffers}, {"PageSize", CNT_DB_INFO, isc_info_page_size} }; } // anonymous namespace void Why::UtilInterface::getPerfCounters(Firebird::CheckStatusWrapper* status, Firebird::IAttachment* att, const char* countersSet, ISC_INT64* counters) { try { // Parse countersSet unsigned cntLink[TOTAL_COUNTERS]; memset(cntLink, 0xFF, sizeof cntLink); Firebird::string dupSet(countersSet); char* set = dupSet.begin(); char* save = NULL; const char* delim = " \t,;"; unsigned typeMask = 0; unsigned n = 0; UCHAR info[TOTAL_COUNTERS]; // will never use all, but do not care about few bytes UCHAR* pinfo = info; #ifdef WIN_NT #define strtok_r strtok_s #endif for (char* nm = strtok_r(set, delim, &save); nm; nm = strtok_r(NULL, delim, &save)) { Firebird::NoCaseString name(nm); for (unsigned i = 0; i < TOTAL_COUNTERS; ++i) { if (name == knownCounters[i].name) { if (cntLink[i] != ~0u) (Firebird::Arg::Gds(isc_random) << "Duplicated name").raise(); //report name & position cntLink[i] = n++; typeMask |= knownCounters[i].type; if (knownCounters[i].type == CNT_DB_INFO) *pinfo++ = knownCounters[i].code; goto found; } } (Firebird::Arg::Gds(isc_random) << "Unknown name").raise(); //report name & position found: ; } #ifdef WIN_NT #undef strtok_r #endif // Force reset counters memset(counters, 0, n * sizeof(ISC_INT64)); // Fill time counters if (typeMask & CNT_TIMER) { SINT64 tr = fb_utils::query_performance_counter() * 1000 / fb_utils::query_performance_frequency(); SINT64 uTime, sTime; fb_utils::get_process_times(uTime, sTime); for (unsigned i = 0; i < TOTAL_COUNTERS; ++i) { if (cntLink[i] == ~0u) continue; if (knownCounters[i].type == CNT_TIMER) { clock_t v = 0; switch(knownCounters[i].code) { case CNT_TIME_REAL: v = tr; break; case CNT_TIME_USER: v = uTime; break; case CNT_TIME_SYSTEM: v = sTime; break; default: fb_assert(false); break; } counters[cntLink[i]] = v; } } } // Fill DB counters if (typeMask & CNT_DB_INFO) { UCHAR buffer[BUFFER_LARGE]; att->getInfo(status, pinfo - info, info, sizeof(buffer), buffer); if (status->getState() & Firebird::IStatus::STATE_ERRORS) return; const UCHAR* p = buffer; while (true) { SINT64 v = 0; UCHAR ipb = *p++; switch (ipb) { case isc_info_reads: case isc_info_writes: case isc_info_marks: case isc_info_fetches: case isc_info_num_buffers: case isc_info_page_size: case isc_info_current_memory: case isc_info_max_memory: v = get_parameter(&p); break; case isc_info_end: goto parsed; case isc_info_error: { const SINT64 temp = isc_portable_integer(p, 2); fb_assert(temp <= MAX_SSHORT); p += temp + 2; continue; } default: (Firebird::Arg::Gds(isc_random) << "Unknown info code").raise(); //report char code } for (unsigned i = 0; i < TOTAL_COUNTERS; ++i) { if (knownCounters[i].type == CNT_DB_INFO && knownCounters[i].code == ipb) { if (cntLink[i] != ~0u) counters[cntLink[i]] = v; break; } } } parsed: ; } } catch (const Firebird::Exception& ex) { ex.stuffException(status); } }
5,679
1,880
# built-in import re from typing import Optional # external import attr REX_AUTHOR = re.compile(r'^\s*(?P<name>.+?) \<(?P<mail>.+?)\>\s*$') @attr.s() class Author: name = attr.ib(type=str) mail = attr.ib(type=Optional[str], default=None) @classmethod def parse(cls, text: str) -> 'Author': match = REX_AUTHOR.match(text) if match is not None: return cls(**match.groupdict()) return cls(name=text) def __str__(self) -> str: if not self.mail: return self.name return '{name} <{mail}>'.format(name=self.name, mail=self.mail)
288
376
/************************************************************************** Copyright 2015 <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 "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. ****************************************************************************/ #pragma once namespace Kvasir { namespace Io{ namespace Action{ struct Input{}; struct Output{}; struct Set{}; struct Clear{}; struct Toggle{}; struct Read{}; template<int I> struct PinFunction{ static constexpr int value = I;}; constexpr Input input{}; constexpr Output output{}; constexpr Set set{}; constexpr Clear clear{}; constexpr Toggle toggle{}; constexpr PinFunction<0> pinFunction0{}; constexpr PinFunction<1> pinFunction1{}; constexpr PinFunction<2> pinFunction2{}; constexpr PinFunction<3> pinFunction3{}; constexpr PinFunction<4> pinFunction4{}; } template<int I> struct HwPort{ static constexpr int value = I; using Type = HwPort<I>; }; template<int I> struct Pin{ static constexpr int value = I; using Type = Pin<I>; }; enum class PortAccess{ defaultMode, setClear, toggle, exclusiveMask, sharedMask, readModifyWrite }; template<PortAccess Access, typename... Ts> struct Port{ using Type = Port<Access, Ts...>; }; namespace Access{ constexpr MPL::Value<PortAccess,PortAccess::defaultMode> defaultMode{}; //this will try to select the best mode for the chip used constexpr MPL::Value<PortAccess,PortAccess::setClear> setClear{}; constexpr MPL::Value<PortAccess,PortAccess::toggle> toggle{}; constexpr MPL::Value<PortAccess,PortAccess::exclusiveMask> exclusiveMask{}; constexpr MPL::Value<PortAccess,PortAccess::sharedMask> sharedMask{}; constexpr MPL::Value<PortAccess,PortAccess::readModifyWrite> readModifyWrite{}; } } //Pin location needs to live in Register in order for the factory functions to be found by ADL namespace Register { template<int Port, int Pin> struct PinLocation { using Type = PinLocation<Port, Pin>; }; } }
727
335
<filename>V/Vasopressor_noun.json { "word": "Vasopressor", "definitions": [ "A drug or other agent which causes the constriction of blood vessels." ], "parts-of-speech": "Noun" }
83
2,338
<reponame>mkinsner/llvm<gh_stars>1000+ // Run lines are sensitive to line numbers and come below the code. #ifndef HEADER #define HEADER // Not a Doxygen comment. notdoxy1 NOT_DOXYGEN void notdoxy1(void); /* Not a Doxygen comment. notdoxy2 NOT_DOXYGEN */ void notdoxy2(void); /*/ Not a Doxygen comment. notdoxy3 NOT_DOXYGEN */ void notdoxy3(void); /** Doxygen comment. isdoxy4 IS_DOXYGEN_SINGLE */ void isdoxy4(void); /*! Doxygen comment. isdoxy5 IS_DOXYGEN_SINGLE */ void isdoxy5(void); /// Doxygen comment. isdoxy6 IS_DOXYGEN_SINGLE void isdoxy6(void); /* BLOCK_ORDINARY_COMMENT */ // ORDINARY COMMENT /// This is a BCPL comment. IS_DOXYGEN_START /// It has only two lines. /** But there are other blocks that are part of the comment, too. IS_DOXYGEN_END */ void multi_line_comment_plus_ordinary(int); // MULTILINE COMMENT // // WITH EMPTY LINE void multi_line_comment_empty_line(int); int notdoxy7; // Not a Doxygen juxtaposed comment. notdoxy7 NOT_DOXYGEN int notdoxy8; // Not a Doxygen juxtaposed comment. notdoxy8 NOT_DOXYGEN int trdoxy9; /// A Doxygen non-trailing comment. trdoxyA IS_DOXYGEN_SINGLE int trdoxyA; int trdoxyB; // Not a Doxygen trailing comment. PART_ONE // It's a multiline one too. trdoxyB NOT_DOXYGEN int trdoxyC; int trdoxyD; // Not a Doxygen trailing comment. trdoxyD NOT_DOXYGEN /// This comment doesn't get merged. trdoxyE IS_DOXYGEN int trdoxyE; int trdoxyF; /// A Doxygen non-trailing comment that gets dropped on the floor. // This comment will also be dropped. int trdoxyG; // This one won't. trdoxyG NOT_DOXYGEN int trdoxyH; ///< A Doxygen trailing comment. PART_ONE // This one gets merged with it. trdoxyH SOME_DOXYGEN int trdoxyI; // This one doesn't. trdoxyI NOT_DOXYGEN int trdoxyJ; // Not a Doxygen trailing comment. PART_ONE ///< This one gets merged with it. trdoxyJ SOME_DOXYGEN int trdoxyK; // This one doesn't. trdoxyK NOT_DOXYGEN int trdoxyL; // Not a Doxygen trailing comment. trdoxyL NOT_DOXYGEN // This one shouldn't get merged. trdoxyM NOT_DOXYGEN int trdoxyM; int trdoxyN; ///< A Doxygen trailing comment. trdoxyN IS_DOXYGEN // This one shouldn't get merged. trdoxyO NOT_DOXYGEN int trdoxyO; #endif // RUN: rm -rf %t // RUN: mkdir %t // RUN: c-index-test -write-pch %t/out.pch -fparse-all-comments -x c++ -std=c++11 %s // RUN: c-index-test -test-load-source all -comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng -x c++ -std=c++11 %s -fparse-all-comments > %t/out.c-index-direct // RUN: c-index-test -test-load-tu %t/out.pch all > %t/out.c-index-pch // RUN: FileCheck %s -check-prefix=WRONG < %t/out.c-index-direct // RUN: FileCheck %s -check-prefix=WRONG < %t/out.c-index-pch // Ensure that XML is not invalid // WRONG-NOT: CommentXMLInvalid // RUN: FileCheck %s < %t/out.c-index-direct // RUN: FileCheck %s < %t/out.c-index-pch // CHECK: parse-all-comments.c:7:6: FunctionDecl=notdoxy1:{{.*}} notdoxy1 NOT_DOXYGEN // CHECK: parse-all-comments.c:10:6: FunctionDecl=notdoxy2:{{.*}} notdoxy2 NOT_DOXYGEN // CHECK: parse-all-comments.c:13:6: FunctionDecl=notdoxy3:{{.*}} notdoxy3 NOT_DOXYGEN // CHECK: parse-all-comments.c:16:6: FunctionDecl=isdoxy4:{{.*}} isdoxy4 IS_DOXYGEN_SINGLE // CHECK: parse-all-comments.c:19:6: FunctionDecl=isdoxy5:{{.*}} isdoxy5 IS_DOXYGEN_SINGLE // CHECK: parse-all-comments.c:22:6: FunctionDecl=isdoxy6:{{.*}} isdoxy6 IS_DOXYGEN_SINGLE // CHECK: parse-all-comments.c:29:6: FunctionDecl=multi_line_comment_plus_ordinary:{{.*}} BLOCK_ORDINARY_COMMENT {{.*}} ORDINARY COMMENT {{.*}} IS_DOXYGEN_START {{.*}} IS_DOXYGEN_END // CHECK: parse-all-comments.c:34:6: FunctionDecl=multi_line_comment_empty_line:{{.*}} MULTILINE COMMENT{{.*}}\n{{.*}}\n{{.*}} WITH EMPTY LINE // CHECK: parse-all-comments.c:36:5: VarDecl=notdoxy7:{{.*}} notdoxy7 NOT_DOXYGEN // CHECK: parse-all-comments.c:37:5: VarDecl=notdoxy8:{{.*}} notdoxy8 NOT_DOXYGEN // CHECK-NOT: parse-all-comments.c:39:5: VarDecl=trdoxy9:{{.*}} trdoxyA IS_DOXYGEN_SINGLE // CHECK: parse-all-comments.c:40:5: VarDecl=trdoxyA:{{.*}} trdoxyA IS_DOXYGEN_SINGLE // CHECK: parse-all-comments.c:42:5: VarDecl=trdoxyB:{{.*}} PART_ONE {{.*}} trdoxyB NOT_DOXYGEN // CHECK-NOT: parse-all-comments.c:44:5: VarDecl=trdoxyC:{{.*}} trdoxyB NOT_DOXYGEN // CHECK: parse-all-comments.c:46:5: VarDecl=trdoxyD:{{.*}} trdoxyD NOT_DOXYGEN // CHECK: parse-all-comments.c:48:5: VarDecl=trdoxyE:{{.*}} trdoxyE IS_DOXYGEN // CHECK-NOT: parse-all-comments.c:50:5: VarDecl=trdoxyF:{{.*}} RawComment // CHECK: parse-all-comments.c:52:5: VarDecl=trdoxyG:{{.*}} trdoxyG NOT_DOXYGEN // CHECK: parse-all-comments.c:54:5: VarDecl=trdoxyH:{{.*}} PART_ONE {{.*}} trdoxyH SOME_DOXYGEN // CHECK: parse-all-comments.c:56:5: VarDecl=trdoxyI:{{.*}} trdoxyI NOT_DOXYGEN // CHECK: parse-all-comments.c:58:5: VarDecl=trdoxyJ:{{.*}} PART_ONE {{.*}} trdoxyJ SOME_DOXYGEN // CHECK: parse-all-comments.c:60:5: VarDecl=trdoxyK:{{.*}} trdoxyK NOT_DOXYGEN // CHECK: parse-all-comments.c:62:5: VarDecl=trdoxyL:{{.*}} trdoxyL NOT_DOXYGEN // CHECK: parse-all-comments.c:64:5: VarDecl=trdoxyM:{{.*}} trdoxyM NOT_DOXYGEN // CHECK: parse-all-comments.c:66:5: VarDecl=trdoxyN:{{.*}} trdoxyN IS_DOXYGEN // CHECK: parse-all-comments.c:68:5: VarDecl=trdoxyO:{{.*}} trdoxyO NOT_DOXYGEN
2,252
190,993
<filename>tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/multi_arguments_results_v1.py # Copyright 2019 The TensorFlow 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. # ============================================================================== # RUN: %p/multi_arguments_results_v1 | FileCheck %s # pylint: disable=missing-docstring,line-too-long import tensorflow.compat.v1 as tf from tensorflow.compiler.mlir.tensorflow.tests.tf_saved_model import common_v1 from tensorflow.python.ops import array_ops # Tests multiple inputs and outputs with index paths. # CHECK-LABEL: func @key( # CHECK-SAME: %[[ARG0:.*]]: tensor<3x5xf32> {tf_saved_model.index_path = ["y"]} # CHECK-SAME: %[[ARG1:.*]]: tensor<5x3xf32> {tf_saved_model.index_path = ["x"]} # CHECK-SAME: tensor<3x3xf32> {tf_saved_model.index_path = ["t"]} # CHECK-SAME: tensor<5x5xf32> {tf_saved_model.index_path = ["s"]} # CHECK-SAME: attributes {{.*}} tf_saved_model.exported_names = ["key"] # CHECK-DAG: %[[MUL0:.*]] = "tf.MatMul"(%[[ARG1]], %[[ARG0]]) # CHECK-DAG: %[[MUL1:.*]] = "tf.MatMul"(%[[ARG0]], %[[ARG1]]) # CHECK: %[[IDENTITY:.*]]:2 = "tf.IdentityN"(%[[MUL1]], %[[MUL0]]) # CHECK: return %[[IDENTITY]]#0, %[[IDENTITY]]#1 # CHECK-LABEL: func @key2( # CHECK-SAME: %[[ARG1:.*]]: tensor<5x3xf32> {tf_saved_model.index_path = ["b"]} # CHECK-SAME: %[[ARG0:.*]]: tensor<3x5xf32> {tf_saved_model.index_path = ["a"]} # CHECK-SAME: tensor<5x5xf32> {tf_saved_model.index_path = ["d"]} # CHECK-SAME: tensor<3x3xf32> {tf_saved_model.index_path = ["c"]} # CHECK-SAME: attributes {{.*}} tf_saved_model.exported_names = ["key2"] # CHECK-DAG: %[[MUL1:.*]] = "tf.MatMul"(%[[ARG0]], %[[ARG1]]) # CHECK-DAG: %[[MUL2:.*]] = "tf.MatMul"(%[[ARG1]], %[[ARG0]]) # CHECK: %[[IDENTITY:.*]]:2 = "tf.IdentityN"(%[[MUL1]], %[[MUL2]]) # CHECK: return %[[IDENTITY]]#1, %[[IDENTITY]]#0 def Test(): x = tf.constant(1.0, shape=(5, 3)) y = tf.constant(1.0, shape=(3, 5)) s = tf.matmul(x, y) t = tf.matmul(y, x) [t, s] = array_ops.identity_n([t, s]) tensor_info_x = tf.compat.v1.saved_model.utils.build_tensor_info(x) tensor_info_y = tf.compat.v1.saved_model.utils.build_tensor_info(y) tensor_info_s = tf.compat.v1.saved_model.utils.build_tensor_info(s) tensor_info_t = tf.compat.v1.saved_model.utils.build_tensor_info(t) return { 'key': (tf.compat.v1.saved_model.signature_def_utils.build_signature_def( inputs={ 'x': tensor_info_x, 'y': tensor_info_y }, outputs={ 's': tensor_info_s, 't': tensor_info_t }, method_name='some_function')), 'key2': (tf.compat.v1.saved_model.signature_def_utils.build_signature_def( inputs={ 'a': tensor_info_y, 'b': tensor_info_x, }, outputs={ 'c': tensor_info_t, 'd': tensor_info_s, }, method_name='reverse_arguments')) }, None, None if __name__ == '__main__': common_v1.set_tf_options() common_v1.do_test(Test)
1,711
377
<reponame>rcorcs/llvm-mctoll //===- ARMCreateJumpTable.cpp - Binary raiser utility llvm-mctoll ---------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains the implementation of ARMCreateJumpTable class // for use by llvm-mctoll. // //===----------------------------------------------------------------------===// #include "ARMCreateJumpTable.h" #include "ARMBaseInstrInfo.h" #include "ARMMachineFunctionInfo.h" #include "ARMSubtarget.h" #include "llvm/CodeGen/ISDOpcodes.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineJumpTableInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/TargetRegisterInfo.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Support/Debug.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #define DEBUG_TYPE "mctoll" using namespace llvm; char ARMCreateJumpTable::ID = 0; ARMCreateJumpTable::ARMCreateJumpTable(ARMModuleRaiser &mr) : ARMRaiserBase(ID, mr) {} ARMCreateJumpTable::~ARMCreateJumpTable() {} void ARMCreateJumpTable::init(MachineFunction *mf, Function *rf) { ARMRaiserBase::init(mf, rf); } void ARMCreateJumpTable::setMCInstRaiser(MCInstRaiser *PMCIR) { MCIR = PMCIR; } /// Get the MachineBasicBlock to add the jumptable instruction. MachineBasicBlock *ARMCreateJumpTable::checkJumptableBB(MachineFunction &MF) { MachineBasicBlock *jumptableBB = nullptr; for (MachineBasicBlock &MBB : MF) { for (MachineBasicBlock::iterator backMBBIter = MBB.begin(); backMBBIter != MBB.end(); backMBBIter++) { MachineInstr &curMachInstr = (*backMBBIter); // Find the MI: %r0 = ADDri %pc if (curMachInstr.getOpcode() == ARM::ADDri && curMachInstr.getOperand(1).getReg() == ARM::PC) { jumptableBB = curMachInstr.getParent(); } } } // Remove the machine instructions which are no sense after building the // machine jump table. std::vector<MachineInstr *> Instrs; if (jumptableBB && jumptableBB->pred_size() == 1) { MachineBasicBlock *mbb = jumptableBB->pred_begin()[0]; for (MachineBasicBlock::iterator MIIter = mbb->begin(); MIIter != mbb->end(); MIIter++) { MachineInstr &curMI = (*MIIter); if (curMI.getOpcode() == ARM::CMPri && curMI.getNextNode()->getOpcode() == ARM::STRi12) { Instrs.push_back(curMI.getNextNode()); } if (curMI.getOpcode() == ARM::STRi12 && curMI.getNextNode()->getOpcode() == ARM::Bcc) { Instrs.push_back(curMI.getNextNode()); } } for (unsigned int i = 0; i < Instrs.size(); i++) { mbb->erase(Instrs[i]); } } return jumptableBB; } bool ARMCreateJumpTable::UpdatetheBranchInst(MachineBasicBlock &MBB) { MachineFunction *MF = MBB.getParent(); const ARMSubtarget &STI = MF->getSubtarget<ARMSubtarget>(); const ARMBaseInstrInfo *TII = STI.getInstrInfo(); std::vector<MachineInstr *> Instrs; for (MachineBasicBlock::iterator MIIter = MBB.begin(); MIIter != MBB.end(); MIIter++) { MachineInstr &curMI = (*MIIter); if (curMI.getOpcode() == ARM::Bcc) { for (unsigned int i = 0; i < curMI.getNumOperands(); i++) { LLVM_DEBUG(curMI.getOperand(i).dump()); } BuildMI(&MBB, DebugLoc(), TII->get(ARM::B)).add(curMI.getOperand(0)); Instrs.push_back(&curMI); } } for (unsigned int i = 0; i < Instrs.size(); i++) { MBB.erase(Instrs[i]); } return true; } /// Raise the machine jumptable according to the CFG. bool ARMCreateJumpTable::raiseMaichineJumpTable(MachineFunction &MF) { // A vector to record MBBs that need to be erased upon jump table creation. std::vector<MachineBasicBlock *> MBBsToBeErased; std::map<uint64_t, MCInstOrData> mcInstMapData; MCInstRaiser::const_mcinst_iter iter_in; // Save the ADDri and Calculate the start address of data. for (MachineBasicBlock &JmpTblBaseCalcMBB : MF) { for (MachineBasicBlock::iterator CurMBBIter = JmpTblBaseCalcMBB.begin(); CurMBBIter != JmpTblBaseCalcMBB.end(); CurMBBIter++) { MachineInstr &JmpTblOffsetCalcMI = *CurMBBIter; // Find the MI: %r0 = ADDri %pc, #8 // add r0, pc, #8 // ldr r1, [sp] // ldr r2, [r0, r1, lsl #2] // add pc, r0, r2 if (JmpTblOffsetCalcMI.getOpcode() == ARM::ADDri && JmpTblOffsetCalcMI.getOperand(1).getReg() == ARM::PC && JmpTblOffsetCalcMI.getOperand(2).getImm() == 8) { // If the fourth instruction in swith block is "add pc, rm, rn", // this library should be built with "-fPIC". bool IsFPIC = false; MachineBasicBlock::iterator FourthInstr = CurMBBIter; std::advance(FourthInstr, 3); if (FourthInstr != JmpTblBaseCalcMBB.end()) { MachineInstr &JGPC = *FourthInstr; if (JGPC.getOpcode() == ARM::ADDrr && JGPC.getOperand(0).getReg() == ARM::PC) { IsFPIC = true; } } // A vector of switch target MBBs std::vector<MachineBasicBlock *> JmpTgtMBBvec; assert( MCIR != nullptr && "Current function machine instruction raiser wasn't initialized!"); for (iter_in = MCIR->const_mcinstr_begin(); iter_in != MCIR->const_mcinstr_end(); iter_in++) { MCInstOrData mcInstorData = iter_in->second; if (mcInstorData.isData() && mcInstorData.getData() > 0) { // The 16 is 8 + 8. The first 8 is the PC offset, the second 8 is // the immediate of current instruction. // If the current library is position-independent, the offset should // be CASE VALUE + PC + 8. // If the current library is not position-independent, the offset // should be CASE VALUE - text section address. uint64_t Offset = IsFPIC ? (mcInstorData.getData() + MCIR->getMCInstIndex(JmpTblOffsetCalcMI) + 16) : (mcInstorData.getData() - MR->getTextSectionAddress()); auto MBBNo = MCIR->getMBBNumberOfMCInstOffset(Offset, MF); if (MBBNo != -1) { MachineBasicBlock *MBB = MF.getBlockNumbered(MBBNo); JmpTgtMBBvec.push_back(MBB); } } } // If no potential jump target addresses were found the current // instruction does not compute jump table base. if (JmpTgtMBBvec.size() == 0) { continue; } // Construct jump table. Current block is the block which would // potentially contain the start of jump targets. If current block has // multiple predecessors this may not be a jump table. For now assert // this to discover potential situations in binaries. Change the assert // to and continue if the assumption is correct. assert((JmpTblBaseCalcMBB.pred_size() == 1) && "Expect a single predecessor during jump table discovery"); MachineBasicBlock *JmpTblPredMBB = *(JmpTblBaseCalcMBB.pred_begin()); // Predecessor block of current block (MBB) - which is jump table block // - is expected to have exactly two successors; one the current block // and the other which should become the default MBB for the switch. assert((JmpTblPredMBB->succ_size() == 2) && "Unexpected number of successors of switch block"); JumpTableInfo JmpTblInfo; // Set predecessor of current block as condition block of jump table // info JmpTblInfo.conditionMBB = JmpTblPredMBB; // Set default basic block in jump table info for (auto Succ : JmpTblPredMBB->successors()) { if (Succ != &JmpTblBaseCalcMBB) { JmpTblInfo.df_MBB = Succ; break; } } MachineJumpTableInfo *JTI = MF.getOrCreateJumpTableInfo(llvm::MachineJumpTableInfo::EK_Inline); JmpTblInfo.jtIdx = JTI->createJumpTableIndex(JmpTgtMBBvec); // Verify the branch instruction of JmpTblPredMBB is a conditional jmp // that uses eflags. Go to the most recent instruction that defines // eflags. Remove that instruction as well as any subsequent instruction // that uses the register defined by that instruction. MachineInstr &BranchInstr = JmpTblPredMBB->instr_back(); std::vector<MachineInstr *> MBBInstrsToErase; if (BranchInstr.isConditionalBranch()) { // Walk the basic block backwards to find the most recent instruction // that implicitly defines eflags. bool EflagsModifierFound = false; MachineBasicBlock::reverse_instr_iterator CurInstrIter = JmpTblPredMBB->instr_rbegin(); for (auto LastInstIter = JmpTblPredMBB->instr_rend(); ((CurInstrIter != LastInstIter) && (!EflagsModifierFound)); ++CurInstrIter) { MachineInstr &curInst = *CurInstrIter; if (curInst.getDesc().hasImplicitDefOfPhysReg(ARM::CPSR)) { EflagsModifierFound = true; } } assert(EflagsModifierFound && "Failed to find eflags defining instruction during jump table " "extraction."); // Note: decrement CurInstrIter to point to the eflags modifying // instruction. CurInstrIter--; // Find the registers that the eflags modifying instruction defines. // Delete all instructions that uses them since we will be deleting // the eflags modifying instruction. MachineInstr &EflagsModInstr = *CurInstrIter; std::set<unsigned int> EflagsDefRegs; for (auto MO : EflagsModInstr.defs()) { // Create a set of all physical registers this instruction defines. if (MO.isReg()) { unsigned int DefReg = MO.getReg(); if (Register::isPhysicalRegister(DefReg)) { EflagsDefRegs.insert(getARMCPSR(DefReg)); } } } // Add EflagsModInstr to the list of instructions to delete MBBInstrsToErase.push_back(&EflagsModInstr); MachineBasicBlock::iterator InstrEndIter = JmpTblPredMBB->instr_end(); // Start walking the block instructions forward to identify // instructions that need be deleted. MachineBasicBlock::iterator InstrFwdIter = MachineBasicBlock::instr_iterator(CurInstrIter); // Find instructions that use any of the register in the set // EflagsDefRegs. Add it to a list of instructions that can be // deleted. while (InstrFwdIter != InstrEndIter) { MachineInstr &CurInstr = *InstrFwdIter; for (auto MO : CurInstr.uses()) { // Check if this use register is defined by EflagsModInstr if (MO.isReg()) { unsigned int UseReg = MO.getReg(); if (Register::isPhysicalRegister(UseReg)) { if (EflagsDefRegs.find(getARMCPSR(UseReg)) != EflagsDefRegs.end()) { MBBInstrsToErase.push_back(&CurInstr); // No need to look for other register uses. break; } } } } // If this instruction redefines any of the registers, remove that // register from EflagsDefRegs. Any instruction that uses this // redefined register and follows the current instruction, should // not be deleted. for (auto MO : CurInstr.defs()) { if (MO.isReg()) { unsigned int DefReg = MO.getReg(); if (Register::isPhysicalRegister(DefReg)) { if (EflagsDefRegs.find(getARMCPSR(DefReg)) != EflagsDefRegs.end()) { EflagsDefRegs.erase(DefReg); } } } } InstrFwdIter++; } // Finally add BranchInstr to the list of instructions to be // deleted MBBInstrsToErase.push_back(&BranchInstr); // BranchInstr.dump(); // Now delete the instructions for (auto MI : MBBInstrsToErase) { JmpTblPredMBB->erase(MI); } } const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>(); const ARMBaseInstrInfo *TII = STI.getInstrInfo(); MBBsToBeErased.push_back(&JmpTblBaseCalcMBB); MachineInstrBuilder MIB = BuildMI(JmpTblPredMBB, DebugLoc(), TII->get(ARM::BR_JTr)) .addJumpTableIndex(JmpTblInfo.jtIdx); // The new machine instrucion should contain the metadata. // Create the metadata and add it to the machine instrucion. LLVMContext *CTX = &M->getContext(); ConstantAsMetadata *CAM = ConstantAsMetadata::get( ConstantInt::get(*CTX, llvm::APInt(64, 0, false))); MDNode *MDnode = MDNode::get(*CTX, CAM); MIB.addMetadata(MDnode); jtList.push_back(JmpTblInfo); } } } // Delete MBBs for (auto MBB : MBBsToBeErased) { MBB->eraseFromParent(); } return true; } unsigned int ARMCreateJumpTable::getARMCPSR(unsigned int PhysReg) { // Get the ARM CPSR. if (PhysReg == ARM::CPSR) { return PhysReg; } return -1; } bool ARMCreateJumpTable::getJTlist(std::vector<JumpTableInfo> &List) { List = jtList; return true; } bool ARMCreateJumpTable::create() { LLVM_DEBUG(dbgs() << "ARMCreateJumpTable start.\n"); raiseMaichineJumpTable(*MF); // For debugging. LLVM_DEBUG(MF->dump()); LLVM_DEBUG(getCRF()->dump()); LLVM_DEBUG(dbgs() << "ARMCreateJumpTable end.\n"); return false; } bool ARMCreateJumpTable::runOnMachineFunction(MachineFunction &mf) { bool rtn = false; init(); rtn = create(); return rtn; } #undef DEBUG_TYPE #ifdef __cplusplus extern "C" { #endif FunctionPass *InitializeARMCreateJumpTable(ARMModuleRaiser &mr) { return new ARMCreateJumpTable(mr); } #ifdef __cplusplus } #endif
6,384
3,167
<filename>open_spiel/algorithms/corr_dist/cce.cc // Copyright 2019 DeepMind Technologies Ltd. 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. #include "open_spiel/algorithms/corr_dist/cce.h" #include "open_spiel/abseil-cpp/absl/strings/str_format.h" #include "open_spiel/algorithms/corr_dist/efcce.h" #include "open_spiel/spiel_globals.h" namespace open_spiel { namespace algorithms { CCEState::CCEState(std::shared_ptr<const Game> game, std::unique_ptr<State> state, CorrDistConfig config, const CorrelationDevice& mu) : WrappedState(game, std::move(state)), config_(config), mu_(mu), rec_index_(-1) {} Player CCEState::CurrentPlayer() const { // Only override this in the first chance actions. if (rec_index_ < 0) { return kChancePlayerId; } else { return state_->CurrentPlayer(); } } ActionsAndProbs CCEState::ChanceOutcomes() const { if (rec_index_ < 0) { ActionsAndProbs outcomes; for (int i = 0; i < mu_.size(); ++i) { outcomes.push_back({i, mu_[i].first}); } return outcomes; } else { return state_->ChanceOutcomes(); } } std::vector<Action> CCEState::LegalActions() const { SPIEL_CHECK_FALSE(IsSimultaneousNode()); if (IsTerminal()) { return {}; } else if (IsChanceNode()) { return LegalChanceOutcomes(); } else { return state_->LegalActions(); } } std::string CCEState::InformationStateString(Player player) const { return state_->InformationStateString(player); } std::string CCEState::ToString() const { std::string state_str = absl::StrFormat("%s\nCur player: %i\nRec index %i", state_->ToString(), CurrentPlayer(), rec_index_); return state_str; } void CCEState::DoApplyAction(Action action_id) { if (rec_index_ < 0) { // Pick the joint policy which will provide recommendations. rec_index_ = action_id; SPIEL_CHECK_LT(rec_index_, mu_.size()); } else if (state_->IsChanceNode()) { // Regular chance node state_->ApplyAction(action_id); } else { // Regular decision node state_->ApplyAction(action_id); } } ActionsAndProbs CCEState::CurrentRecommendedStatePolicy() const { SPIEL_CHECK_GE(rec_index_, 0); return mu_[rec_index_].second.GetStatePolicy( InformationStateString(CurrentPlayer())); } ActionsAndProbs CCETabularPolicy::GetStatePolicy(const State& state) const { const auto* cce_state = dynamic_cast<const CCEState*>(&state); SPIEL_CHECK_TRUE(cce_state != nullptr); return cce_state->CurrentRecommendedStatePolicy(); } } // namespace algorithms } // namespace open_spiel
1,127
1,088
<reponame>amznero/graph-learn # Copyright 2020 Alibaba Group Holding Limited. 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. # ============================================================================= from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from graphlearn.python.nn.tf.data.feature_handler import FeatureHandler class EgoGraph(object): """ `EgoGraph` is a basic data structure used to describe a sampled graph. It constists of src `Data` and src's neighbors(nodes and edges) `Data`. The `EgoGraph` is mainly used to represent subgraphs generated by fixed-size neighbor sampling, in which the data can be efficiently organized in dense format and the model can be computed using the dense operators. Args: src: A `Data`/Tensor object used to describe the centric nodes. nbr_nodes: A list of `Data`/Tensor instance to describe neighborhood nodes. node_schema: A list of tuple to describe the FeatureSpec of src and neighbor nodes. Each tuple is formatted with (name, spec), in which `name` is node's type, and `spec` is a FeatureSpec object. Be sure that `len(node_schema) == len(neighbors) + 1`. nbr_nums: A list of number of neighbor per hop. nbr_edges: A list of `Data`/Tensor instance to describe neighborhood edges. edge_schema: A list of tuple to describe the `FeatureSpec` of neighbor edges. """ def __init__(self, src, nbr_nodes, node_schema, nbr_nums, nbr_edges=None, edge_schema=None, **kwargs): self._src = src self._nbr_nodes = nbr_nodes self._node_schema = node_schema self._nbr_edges = nbr_edges self._edge_schema = edge_schema if self._node_schema is not None: assert len(self._node_schema) == len(nbr_nums) + 1 self._nbr_nums = np.array(nbr_nums) @property def src(self): return self._src @property def node_schema(self): return self._node_schema @property def nbr_nodes(self): return self._nbr_nodes @property def nbr_nums(self): return self._nbr_nums @property def edge_schema(self): return self._edge_schema @property def nbr_edges(self): return self._nbr_nodes def hop_node(self, i): """ Get the hop ith neighbors nodes of centric src, where i starts from zero. The return value is a tensor with shape [batch_size * k_1 *...* k_i, dim], where k_i is the expand neighbor count at hop i and dim is the sum of all feature dimensions, which may be different due to kinds of vertex types. """ return self._nbr_nodes[i] def hop_edge(self, i): if self._nbr_edges is not None: return self._nbr_edges[i] else: raise ValueError("No edge data.") def transform(self, transform_func=None): """transforms `EgoGraph`. Default transformation is encoding nodes feature to embedding. Args: transform_func: A function that takes in an `EgoGraph` object and returns a transformed version. """ if self.node_schema is None: return self assert len(self.node_schema) == (len(self.nbr_nodes) + 1) s = self.node_schema[0] vertex_handler = FeatureHandler(s[0], s[1]) vertex_tensor = vertex_handler.forward(self.src) neighbors = [] for i, nbr in enumerate(self.nbr_nodes): s = self.node_schema[i + 1] neighbor_handler = FeatureHandler(s[0], s[1]) neighbor_tensor = neighbor_handler.forward(self.nbr_nodes[i]) neighbors.append(neighbor_tensor) return EgoGraph(vertex_tensor, neighbors, None, self.nbr_nums) def __getitem__(self, key): return getattr(self, key, None) def __setitem__(self, key, value): setattr(self, key, value)
1,571
352
/* *Author:GeneralSandman *Code:https://github.com/GeneralSandman/TinyWeb *E-mail:<EMAIL> *Web:www.generalsandman.cn */ /*---XXX--- * **************************************** * */ #include <tiny_base/log.h> #include <tiny_base/exception.h> #include <tiny_core/defer.h> #include <iostream> #include <deque> #include <boost/function.hpp> #include <boost/bind.hpp> void succ1() { std::cout << "succ1():no throwing exception\n"; } void fail1(Exception &exc) { std::cout << "fail1():no throwing exception\n"; } void succ2() { std::cout << "succ2():throw exception[error3]\n"; Exception e("error3"); throw e; } void fail2(Exception &exc) { std::cout << "fail2():catch exceptrion and no throwing exception\n"; std::cout << exc.what() << std::endl; } void succ3() { std::cout << "succ3():throw exception\n"; Exception e("error4"); throw e; } void fail3(Exception &exc) { std::cout << "fail3():catch exceptrion and throw exception\n"; std::cout << exc.what() << std::endl; Exception e("error5"); throw e; } void doneSucc() { std::cout << "chains done\n"; } void doneFail(Exception &exc) { std::cout << "chains done with error\n"; } int main() { Defer defer; defer.addCallBack(succ1); defer.addErrorBack(fail1); defer.addCallBack(succ2); defer.addErrorBack(fail2); defer.addCallBack(succ3); defer.addErrorBack(fail3); defer.addErrorBack(doneFail); defer.callback(); return 0; }
613
617
#pragma once #include "CoreMinimal.h" #include "RTSOrderType.generated.h" UENUM(BlueprintType) enum class ERTSOrderType : uint8 { /** Idle. */ ORDER_None, /** Move to a destination in the world. */ ORDER_Move, /** Attack another actor. */ ORDER_Attack, /** Create a new construction site. */ ORDER_BeginConstruction, /** Finish a building construction. */ ORDER_ContinueConstruction, /** Gather resources. */ ORDER_Gather, /** Return carried resources. */ ORDER_ReturnResources };
168
613
<gh_stars>100-1000 package mezz.jei.plugins.vanilla.cooking.fuel; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import net.minecraft.world.item.ItemStack; import com.google.common.base.Preconditions; import mezz.jei.api.gui.drawable.IDrawableAnimated; import mezz.jei.api.helpers.IGuiHelper; import mezz.jei.config.Constants; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; public class FuelRecipe { private final List<ItemStack> inputs; private final Component smeltCountText; private final IDrawableAnimated flame; public FuelRecipe(IGuiHelper guiHelper, Collection<ItemStack> input, int burnTime) { Preconditions.checkArgument(burnTime > 0, "burn time must be greater than 0"); this.inputs = new ArrayList<>(input); this.smeltCountText = createSmeltCountText(burnTime); this.flame = guiHelper.drawableBuilder(Constants.RECIPE_GUI_VANILLA, 82, 114, 14, 14) .buildAnimated(burnTime, IDrawableAnimated.StartDirection.TOP, true); } public List<ItemStack> getInputs() { return inputs; } public Component getSmeltCountText() { return smeltCountText; } public IDrawableAnimated getFlame() { return flame; } public static Component createSmeltCountText(int burnTime) { if (burnTime == 200) { return new TranslatableComponent("gui.jei.category.fuel.smeltCount.single"); } else { NumberFormat numberInstance = NumberFormat.getNumberInstance(); numberInstance.setMaximumFractionDigits(2); String smeltCount = numberInstance.format(burnTime / 200f); return new TranslatableComponent("gui.jei.category.fuel.smeltCount", smeltCount); } } }
568
518
package com.paypal.api.payments; import com.paypal.base.rest.PayPalModel; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import java.util.List; @Getter @Setter @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) public class TemplateData extends PayPalModel { /** * Information about the merchant who is sending the invoice. */ private MerchantInfo merchantInfo; /** * The required invoice recipient email address and any optional billing information. One recipient is supported. */ private List<BillingInfo> billingInfo; /** * For invoices sent by email, one or more email addresses to which to send a Cc: copy of the notification. Supports only email addresses under participant. */ private List<String> ccInfo; /** * The shipping information for entities to whom items are being shipped. */ private ShippingInfo shippingInfo; /** * The list of items to include in the invoice. Maximum value is 100 items per invoice. */ private List<InvoiceItem> items; /** * Optional. The payment deadline for the invoice. Value is either `term_type` or `due_date` but not both. */ private PaymentTerm paymentTerm; /** * Reference data, such as PO number, to add to the invoice. Maximum length is 60 characters. */ private String reference; /** * The invoice level discount, as a percent or an amount value. */ private Cost discount; /** * The shipping cost, as a percent or an amount value. */ private ShippingCost shippingCost; /** * The custom amount to apply on an invoice. If you include a label, the amount cannot be empty. */ private CustomAmount custom; /** * Indicates whether the invoice allows a partial payment. If set to `false`, invoice must be paid in full. If set to `true`, the invoice allows partial payments. Default is `false`. */ private Boolean allowPartialPayment; /** * If `allow_partial_payment` is set to `true`, the minimum amount allowed for a partial payment. */ private Currency minimumAmountDue; /** * Indicates whether tax is calculated before or after a discount. If set to `false`, the tax is calculated before a discount. If set to `true`, the tax is calculated after a discount. Default is `false`. */ private Boolean taxCalculatedAfterDiscount; /** * Indicates whether the unit price includes tax. Default is `false`. */ private Boolean taxInclusive; /** * General terms of the invoice. 4000 characters max. */ private String terms; /** * Note to the payer. 4000 characters max. */ private String note; /** * A private bookkeeping memo for the merchant. Maximum length is 150 characters. */ private String merchantMemo; /** * Full URL of an external image to use as the logo. Maximum length is 4000 characters. */ private String logoUrl; /** * The total amount of the invoice. */ private Currency totalAmount; /** * List of files attached to the invoice. */ private List<FileAttachment> attachments; /** * Default Constructor */ public TemplateData() { } /** * Parameterized Constructor */ public TemplateData(MerchantInfo merchantInfo) { this.merchantInfo = merchantInfo; } }
903
4,268
<reponame>wenq1/duktape /* * Illustrate corner case string intern side effect behavior: when a finalizer * is triggered during string interning it can potentially invalidate the * string data pointer/length provided before the data has been copied. * * This would be quite difficult to trigger in practice. This tests case * relies on voluntary mark-and-sweep to trigger when the new duk_hstring * is allocated. To achieve that a lot of tries are needed. * * https://github.com/svaarala/duktape/pull/884 * * Run with valgrind to catch memory unsafe behavior. */ /* When testing manually, increase to e.g. 100. */ #define TEST_COUNT 4 /*=== *** test_side_effect (duk_safe_call) ...0 finalizer resized ...1 finalizer resized ...2 finalizer resized ...3 finalizer resized final top: 0 ==> rc=0, result='undefined' ===*/ static int finalizer_ran = 0; static duk_ret_t my_finalizer(duk_context *ctx) { finalizer_ran = 1; #if 1 printf("finalizer\n"); fflush(stdout); #endif duk_get_global_string(ctx, "currentBuffer"); duk_resize_buffer(ctx, -1, 0); #if 1 printf("resized\n"); fflush(stdout); #endif return 0; } static duk_ret_t test_side_effect(duk_context *ctx, void *udata) { int i, count_intern; void *ptr; (void) udata; for (i = 0; i < TEST_COUNT; i++) { printf("...%d\n", i); fflush(stdout); /* Create a dynamic buffer we tweak in the side effect. * Buffer is not yet registered to global.currentBuffer * so any previous finalizers (which might still exist) * can't reach it. */ ptr = duk_push_dynamic_buffer(ctx, 1024 * 1024); /* Create cyclical garbage which won't get collected by * refcounting. This is essential so that there can be * something with a finalizer when mark-and-sweep gets * triggered. */ duk_push_object(ctx); duk_push_object(ctx); duk_dup(ctx, -2); duk_put_prop_string(ctx, -2, "ref"); duk_dup(ctx, -1); duk_put_prop_string(ctx, -3, "ref"); duk_push_c_function(ctx, my_finalizer, 0); duk_set_finalizer(ctx, -2); /* Fill the buffer and make it reachable for the finalizer. */ finalizer_ran = 0; memset(ptr, 0, 1024 * 1024); *((int *) ptr) = i; /* Create a new string on each round. */ duk_dup(ctx, -3); duk_put_global_string(ctx, "currentBuffer"); duk_remove(ctx, -3); /* We're now ready: cause the two objects to become not yet * collected garbage. The buffer may be resized before we * reach the string test, so don't reference 'ptr' anymore. */ duk_pop_2(ctx); /* Finally, push a new string and hope we trigger the * finalizer. Repeat the operation until the finalizer * runs (it may already have run), and hope it gets triggered * in the right spot. */ count_intern = 0; while (!finalizer_ran) { count_intern++; duk_push_lstring(ctx, ptr, 1024 * 1024); duk_pop(ctx); /* Because the fix in https://github.com/svaarala/duktape/pull/884 * prevent side effects in string interning, we need to trigger * them explicitly at some pointer to avoid looping forever. * The limit here allows a failure to be detected in e.g. 1.5.0. */ if (count_intern >= 100000) { duk_gc(ctx, 0); } } #if 0 printf("Finalizer run took %d tries \n", count_intern); fflush(stdout); #endif } duk_gc(ctx, 0); duk_gc(ctx, 0); printf("final top: %ld\n", (long) duk_get_top(ctx)); return 0; } void test(duk_context *ctx) { TEST_SAFE_CALL(test_side_effect); }
1,284
3,227
<gh_stars>1000+ #include <CGAL/Exact_integer.h> #include <CGAL/Homogeneous.h> #include <CGAL/Nef_polyhedron_3.h> #include <CGAL/IO/Nef_polyhedron_iostream_3.h> typedef CGAL::Homogeneous<CGAL::Exact_integer> Kernel; typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron; typedef Nef_polyhedron::Vertex_const_handle Vertex_const_handle; typedef Nef_polyhedron::Halfedge_const_handle Halfedge_const_handle; typedef Nef_polyhedron::Halffacet_const_handle Halffacet_const_handle; typedef Nef_polyhedron::SHalfedge_const_handle SHalfedge_const_handle; typedef Nef_polyhedron::SHalfloop_const_handle SHalfloop_const_handle; typedef Nef_polyhedron::SFace_const_handle SFace_const_handle; typedef Nef_polyhedron::Volume_const_iterator Volume_const_iterator; typedef Nef_polyhedron::Shell_entry_const_iterator Shell_entry_const_iterator; typedef Kernel::Point_3 Point_3; class Shell_explorer { bool first; Vertex_const_handle v_min; public: Shell_explorer() : first(true) {} void visit(Vertex_const_handle v) { if(first || CGAL::lexicographically_xyz_smaller(v->point(),v_min->point())) { v_min = v; first=false; } } void visit(Halfedge_const_handle ) {} void visit(Halffacet_const_handle ) {} void visit(SHalfedge_const_handle ) {} void visit(SHalfloop_const_handle ) {} void visit(SFace_const_handle ) {} Vertex_const_handle& minimal_vertex() { return v_min; } void reset_minimal_vertex() { first = true; } }; int main() { Nef_polyhedron N; std::cin >> N; int ic = 0; Volume_const_iterator c; Shell_explorer SE; CGAL_forall_volumes(c,N) { std::cout << "Volume " << ic++ << std::endl; int is = 0; Shell_entry_const_iterator it; CGAL_forall_shells_of(it,c) { SE.reset_minimal_vertex(); N.visit_shell_objects(SFace_const_handle(it),SE); Point_3 p(SE.minimal_vertex()->point()); std::cout << " minimal vertex of shell " << is++ << " is at " << p << std::endl; } } }
816
8,805
// Boost.Geometry Index // // Copyright (c) 2011-2014 <NAME>, <NAME>. // // Use, modification and distribution is subject to 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) #ifndef BOOST_GEOMETRY_INDEX_DETAIL_EXCEPTION_HPP #define BOOST_GEOMETRY_INDEX_DETAIL_EXCEPTION_HPP #include <boost/core/no_exceptions_support.hpp> #ifndef BOOST_NO_EXCEPTIONS #include <stdexcept> #include <boost/throw_exception.hpp> #else #include <cstdlib> #include <boost/geometry/index/detail/assert.hpp> #endif namespace boost { namespace geometry { namespace index { namespace detail { #ifndef BOOST_NO_EXCEPTIONS inline void throw_runtime_error(const char * str) { BOOST_THROW_EXCEPTION(std::runtime_error(str)); } inline void throw_logic_error(const char * str) { BOOST_THROW_EXCEPTION(std::logic_error(str)); } inline void throw_invalid_argument(const char * str) { BOOST_THROW_EXCEPTION(std::invalid_argument(str)); } inline void throw_length_error(const char * str) { BOOST_THROW_EXCEPTION(std::length_error(str)); } inline void throw_out_of_range(const char * str) { BOOST_THROW_EXCEPTION(std::out_of_range(str)); } #else inline void throw_runtime_error(const char * str) { BOOST_GEOMETRY_INDEX_ASSERT(!"runtime_error thrown", str); std::abort(); } inline void throw_logic_error(const char * str) { BOOST_GEOMETRY_INDEX_ASSERT(!"logic_error thrown", str); std::abort(); } inline void throw_invalid_argument(const char * str) { BOOST_GEOMETRY_INDEX_ASSERT(!"invalid_argument thrown", str); std::abort(); } inline void throw_length_error(const char * str) { BOOST_GEOMETRY_INDEX_ASSERT(!"length_error thrown", str); std::abort(); } inline void throw_out_of_range(const char * str) { BOOST_GEOMETRY_INDEX_ASSERT(!"out_of_range thrown", str); std::abort(); } #endif }}}} // namespace boost::geometry::index::detail #endif // BOOST_GEOMETRY_INDEX_DETAIL_EXCEPTION_HPP
895
492
#!/usr/bin/env python # -*- coding: utf-8 -*- import warnings import logging import sys, os import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import options, parse_command_line, add_parse_callback, OptionParser from tornado.log import define_logging_options, LogFormatter from tornado.util import import_object from exception import ConfigError, ArgumentError, UrlError from application import Application from settings_manager import settings from logger import enable_pretty_logging, ProcessLogTimedFileHandler reload(sys) sys.setdefaultencoding('utf-8') class Server(object): def __init__(self, ioloop=None): self.urls = [] self.application = None self.httpserver = None self.ioloop = ioloop def _patch_httpserver(self): """ 重写httpserver的xheader配置,让gunicorn可以加载xheaders设置 :return: """ httpserver = sys.modules["tornado.httpserver"] try: xhs = settings.XHEADERS except: xhs = True class TorngasHTTPServer(httpserver.HTTPServer): def __init__(self, request_callback, xheaders=xhs, **kwargs): super(TorngasHTTPServer, self).__init__(request_callback, xheaders=xheaders, **kwargs) httpserver.HTTPServer = TorngasHTTPServer sys.modules["tornado.httpserver"] = httpserver def load_application(self, application=None): """ :type application: torngas.application.Application subclass or instance :return: """ self._patch_httpserver() if settings.TRANSLATIONS: try: from tornado import locale locale.load_translations(settings.TRANSLATIONS_CONF.translations_dir) except: warnings.warn('locale dir load failure,maybe your config file is not set correctly.') if not application: self._install_application(application) elif isinstance(application, Application): self.application = application elif issubclass(application, Application): self._install_application(application) else: raise ArgumentError('need torngas.application.Application instance object or subclass.') tmpl = settings.TEMPLATE_CONFIG.template_engine self.application.tmpl = import_object(tmpl) if tmpl else None return self.application def _install_application(self, application): if not self.urls: raise UrlError("urls not found.") if application: app_class = application else: app_class = Application tornado_conf = settings.TORNADO_CONF if 'default_handler_class' in tornado_conf and \ isinstance(tornado_conf['default_handler_class'], basestring): tornado_conf['default_handler_class'] = import_object(tornado_conf['default_handler_class']) else: tornado_conf['default_handler_class'] = import_object('torngas.handler.ErrorHandler') tornado_conf['debug'] = settings.DEBUG self.application = app_class(handlers=self.urls, default_host='', transforms=None, wsgi=False, middlewares=settings.MIDDLEWARE_CLASSES, **tornado_conf) def load_urls(self): urls = [] if settings.INSTALLED_APPS: for app_name in settings.INSTALLED_APPS: app_urls = import_object(app_name + '.urls.urls') urls.extend(app_urls) else: raise ConfigError('load urls error,INSTALLED_APPS not found!') self.urls = urls return self.urls def load_httpserver(self, sockets=None, **kwargs): if not sockets: from tornado.netutil import bind_sockets if settings.IPV4_ONLY: import socket sockets = bind_sockets(options.port, options.address, family=socket.AF_INET) else: sockets = bind_sockets(options.port, options.address) http_server = tornado.httpserver.HTTPServer(self.application, **kwargs) http_server.add_sockets(sockets) self.httpserver = http_server return self.httpserver def server_start(self, sockets=None, **kwargs): if not self.httpserver: self.load_httpserver(sockets, **kwargs) self.start() def load_all(self, application=None, sockets=None, **kwargs): self.parse_command() self.load_urls() self.load_application(application) if not self.httpserver: self.load_httpserver(sockets, **kwargs) def start(self): self.print_settings_info() if not self.ioloop: self.ioloop = tornado.ioloop.IOLoop.instance() self.ioloop.start() def print_settings_info(self): if settings.DEBUG: print('tornado version: %s' % tornado.version) print('locale support: %s' % settings.TRANSLATIONS) print('load apps:') for app in settings.INSTALLED_APPS: print(' - %s' % str(app)) print('template engine: %s' % (settings.TEMPLATE_CONFIG.template_engine or 'default')) print('server started. development server at http://%s:%s/' % (options.address, options.port)) def parse_command(self, args=None, final=False): """ 解析命令行参数,解析logger配置 :return: """ self.define() add_parse_callback(self.parse_logger_callback) parse_command_line(args, final) options.run_parse_callbacks() def parse_logger_callback(self): if options.disable_log: options.logging = None if options.log_file_prefix and options.log_port_prefix: options.log_file_prefix += ".%s" % options.port if options.log_patch: logging.handlers.TimedRotatingFileHandler = ProcessLogTimedFileHandler tornado_logger = logging.getLogger('tornado') enable_pretty_logging(logger=tornado_logger) logdir = options.logging_dir or settings.LOGGING_DIR for log in settings.LOGGING: opt = OptionParser() define_logging_options(opt) self.define(opt) opt.log_rotate_when = log.get('when', 'midnight') opt.log_to_stderr = log.get('log_to_stderr', False) if options.log_to_stderr is None else options.log_to_stderr opt.logging = log.get('level', 'INFO') opt.log_file_prefix = os.path.join(logdir, log['filename']) if log.get('backups'): opt.log_file_num_backups = log.get('backups') if opt.log_port_prefix: opt.log_file_prefix += ".%s" % options.port opt.log_rotate_interval = log.get('interval', 1) opt.log_rotate_mode = 'time' logger = logging.getLogger(log['name']) logger.propagate = 0 enable_pretty_logging(options=opt, logger=logger) map(lambda h: h.setFormatter(LogFormatter(fmt=log.get("formatter", LogFormatter.DEFAULT_FORMAT), color=settings.DEBUG)), logger.handlers) def define(self, options=options): """ 定义命令行参数,你可以自定义很多自己的命令行参数,或重写此方法覆盖默认参数 :return: """ try: # 增加timerotating日志配置 options.define("log_rotate_when", type=str, default='midnight', help=("specify the type of TimedRotatingFileHandler interval " "other options:('S', 'M', 'H', 'D', 'W0'-'W6')")) options.define("log_rotate_interval", type=int, default=1, help="The interval value of timed rotating") options.define("log_rotate_mode", type=str, default='time', help="The mode of rotating files(time or size)") except: pass options.define("port", default=8000, help="run server on it", type=int) options.define("settings", default='', help="setting module name", type=str) options.define("address", default='0.0.0.0', help='listen host,default:0.0.0.0', type=str) options.define("log_patch", default=True, help='Use ProcessTimedRotatingFileHandler instead of the default TimedRotatingFileHandler.', type=bool) options.define("log_port_prefix", default=None, help='add port to log file prefix.', type=bool) options.define("logging_dir", default='', help='custom log dir.') options.define("disable_log", default=True, help='disable tornado log function.') def run(application=None, sockets=None, **kwargs): server = Server() server.load_all(application, sockets, **kwargs) server.start()
4,282
423
import pathlib from typing import Optional, Sequence from pysen import ComponentBase def build(components: Sequence[ComponentBase], src_path: Optional[pathlib.Path]) -> int: return 42
53
489
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2021 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #ifndef __OPENSPACE_MODULE_GLOBEBROWSING___ASYNC_TILE_DATAPROVIDER___H__ #define __OPENSPACE_MODULE_GLOBEBROWSING___ASYNC_TILE_DATAPROVIDER___H__ #include <modules/globebrowsing/src/prioritizingconcurrentjobmanager.h> #include <modules/globebrowsing/src/rawtiledatareader.h> #include <modules/globebrowsing/src/tileindex.h> #include <ghoul/misc/boolean.h> #include <map> #include <optional> #include <set> namespace openspace::globebrowsing { struct RawTile; /** * The responsibility of this class is to enqueue tile requests and fetching finished * <code>RawTile</code>s that has been asynchronously loaded. */ class AsyncTileDataProvider { public: /** * \param rawTileDataReader is the reader that will be used for the asynchronous * tile loading. */ AsyncTileDataProvider(std::string name, std::unique_ptr<RawTileDataReader> rawTileDataReader); ~AsyncTileDataProvider(); /** * Creates a job which asynchronously loads a raw tile. This job is enqueued. */ bool enqueueTileIO(const TileIndex& tileIndex); /** * Get one finished job. */ std::optional<RawTile> popFinishedRawTile(); void update(); void reset(); void prepareToBeDeleted(); bool shouldBeDeleted(); const RawTileDataReader& rawTileDataReader() const; float noDataValueAsFloat() const; protected: BooleanType(ResetRawTileDataReader); enum class ResetMode { ShouldResetAll, ShouldResetAllButRawTileDataReader, ShouldBeDeleted, ShouldNotReset }; /** * \returns true if tile of index <code>tileIndex</code> is not already enqueued. */ bool satisfiesEnqueueCriteria(const TileIndex& tileIndex); /** * An unfinished job is a load tile job that has been popped from the thread pool due * to its low priority. Once it has been popped, it is marked as unfinished and needs * to be explicitly ended. */ void endUnfinishedJobs(); void clearTiles(); void endEnqueuedJobs(); void performReset(ResetRawTileDataReader resetRawTileDataReader); private: const std::string _name; /// The reader used for asynchronous reading std::unique_ptr<RawTileDataReader> _rawTileDataReader; PrioritizingConcurrentJobManager<RawTile, TileIndex::TileHashKey> _concurrentJobManager; std::set<TileIndex::TileHashKey> _enqueuedTileRequests; ResetMode _resetMode = ResetMode::ShouldResetAllButRawTileDataReader; bool _shouldBeDeleted = false; }; } // namespace openspace::globebrowsing #endif // __OPENSPACE_MODULE_GLOBEBROWSING___ASYNC_TILE_DATAPROVIDER___H__
2,025
370
package com.vitco.app.util.components.progressbar; import javax.swing.*; /** * A worker thread that encapsulates a task handled by a ProgressDialog. */ public abstract class ProgressWorker extends SwingWorker<Object, Object> { @Override protected abstract Object doInBackground() throws Exception; }
89
381
<reponame>wslblb/TestChat package chen.testchat.bean; import java.io.Serializable; /** * 项目名称: TestChat * 创建人: 陈锦军 * 创建时间: 2016/10/15 23:29 * QQ: 1981367757 */ public class RecentMsg implements Serializable { private static final long serialVersionUID = 1L; /** * 单聊:最近会话界面显示的用户ID * 群聊:群ID */ private String belongId; /** * 单聊:最近会话界面显示的用户头像 * 群聊:群头像 */ private String avatar; /** * 单聊:最近会话界面显示的用户昵称 * 群聊:群昵称 */ private String nick; /** * 单聊:最近会话界面显示的用户用户名 * 群聊:群名 */ private String name; /** * 单聊、群聊:最近会话消息创建时间 */ private String time; /** * 消息类型 */ private Integer msgType; /** * 消息内容 */ private String lastMsgContent; public String getBelongId() { return belongId; } public void setBelongId(String belongId) { this.belongId = belongId; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getNick() { return nick; } public void setNick(String nick) { this.nick = nick; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public Integer getMsgType() { return msgType; } public void setMsgType(Integer msgType) { this.msgType = msgType; } public String getLastMsgContent() { return lastMsgContent; } public void setLastMsgContent(String lastMsgContent) { this.lastMsgContent = lastMsgContent; } @Override public boolean equals(Object obj) { if (obj instanceof RecentMsg) { RecentMsg recentMsg = (RecentMsg) obj; return recentMsg.getBelongId().equals(getBelongId()); } return false; } }
1,591
732
/* * Copyright 2014 Google 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 org.inferred.freebuilder.processor.property; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.google.common.collect.Lists; import com.google.common.primitives.Primitives; import com.google.common.testing.EqualsTester; import org.inferred.freebuilder.FreeBuilder; import org.inferred.freebuilder.processor.FeatureSets; import org.inferred.freebuilder.processor.NamingConvention; import org.inferred.freebuilder.processor.Processor; import org.inferred.freebuilder.processor.source.SourceBuilder; import org.inferred.freebuilder.processor.source.feature.FeatureSet; import org.inferred.freebuilder.processor.source.testing.BehaviorTester; import org.inferred.freebuilder.processor.source.testing.ParameterizedBehaviorTestFactory; import org.inferred.freebuilder.processor.source.testing.ParameterizedBehaviorTestFactory.Shared; import org.inferred.freebuilder.processor.source.testing.TestBuilder; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Parameterized.UseParametersRunnerFactory; import java.util.Arrays; import java.util.List; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.function.IntFunction; /** Behavioral tests for primitive optional properties. */ @RunWith(Parameterized.class) @UseParametersRunnerFactory(ParameterizedBehaviorTestFactory.class) public class PrimitiveOptionalPropertyTest { enum OptionalFactory { INTS(OptionalInt.class, int.class, v -> v * (v + 1) / 2), LONGS(OptionalLong.class, long.class, v -> (long) v * (v + 1) / 2), DOUBLE(OptionalDouble.class, double.class, v -> 1.0 / (v + 1)); private final Class<?> type; private final Class<? extends Number> primitiveType; private final Class<?> boxedType; private final IntFunction<? extends Number> examples; <T, P extends Number> OptionalFactory( Class<T> type, Class<P> primitiveType, IntFunction<P> examples) { this.type = type; this.primitiveType = primitiveType; this.boxedType = Primitives.wrap(primitiveType); this.examples = examples; } Number example(int i) { return examples.apply(i); } @Override public String toString() { return type.getSimpleName(); } } private static final String INVALID_MESSAGE = "item must be non-negative"; @SuppressWarnings("unchecked") @Parameters(name = "{0}, {1}, {2}") public static Iterable<Object[]> parameters() { List<OptionalFactory> optionals = Arrays.asList(OptionalFactory.values()); List<NamingConvention> conventions = Arrays.asList(NamingConvention.values()); List<FeatureSet> features = FeatureSets.ALL; return () -> Lists .cartesianProduct(optionals, conventions, features) .stream() .map(List::toArray) .iterator(); } @Rule public final ExpectedException thrown = ExpectedException.none(); @Shared public BehaviorTester behaviorTester; private final OptionalFactory optional; private final NamingConvention convention; private final FeatureSet features; private final SourceBuilder datatype; public PrimitiveOptionalPropertyTest( OptionalFactory optional, NamingConvention convention, FeatureSet features) { this.optional = optional; this.convention = convention; this.features = features; datatype = SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("@%s(builder = DataType.Builder.class)", JsonDeserialize.class) .addLine("public interface DataType {") .addLine(" %s %s;", optional.type, convention.get("item")) .addLine("") .addLine(" Builder toBuilder();") .addLine(" class Builder extends DataType_Builder {") .addLine(" @Override public Builder %s(%s item) {", convention.set("item"), optional.primitiveType) .addLine(" if (item < 0) {") .addLine(" throw new IllegalArgumentException(\"%s\");", INVALID_MESSAGE) .addLine(" }") .addLine(" return super.%s(item);", convention.set("item")) .addLine(" }") .addLine(" }") .addLine("") .addLine(" public static Builder builder() {") .addLine(" return new Builder();") .addLine(" }") .addLine("}"); } @Test public void testConstructor_defaultEmpty() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = new DataType.Builder().build();") .addLine("assertEquals(%s.empty(), value.%s);", optional.type, convention.get("item")) .build()) .runTest(); } @Test public void testBuilderGetter_defaultValue() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType.Builder builder = new DataType.Builder();") .addLine("assertEquals(%s.empty(), builder.%s);", optional.type, convention.get("item")) .build()) .runTest(); } @Test public void testBuilderGetter_nonDefaultValue() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType.Builder builder = new DataType.Builder()") .addLine(" .%s(%s);", convention.set("item"), optional.example(0)) .addLine("assertEquals(%s.of(%s), builder.%s);", optional.type, optional.example(0), convention.get("item")) .build()) .runTest(); } @Test public void testSet_primitive() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .build();") .addLine("assertEquals(%s.of(%s), value.%s);", optional.type, optional.example(0), convention.get("item")) .build()) .runTest(); } @Test public void testSet_optional() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .%s(%s.of(%s))", convention.set("item"), optional.type, optional.example(0)) .addLine(" .build();") .addLine("assertEquals(%s.of(%s), value.%s);", optional.type, optional.example(0), convention.get("item")) .build()) .runTest(); } @Test public void testSet_optionalDelegatesToPrimitiveSetterForValidation() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(INVALID_MESSAGE); behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType.Builder template = DataType.builder()") .addLine(" .%s(%s.of(-1));", convention.set("item"), optional.type) .build()) .runTest(); } @Test public void testSet_empty() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .%s(%s.empty())", convention.set("item"), optional.type) .addLine(" .build();") .addLine("assertEquals(%s.empty(), value.%s);", optional.type, convention.get("item")) .build()) .runTest(); } @Test public void testSet_nullOptional() { thrown.expect(NullPointerException.class); behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("new DataType.Builder().%s((%s) null);", convention.set("item"), optional.type) .build()) .runTest(); } @Test public void testMap_modifiesValue() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(1)) .addLine(" .mapItem(a -> a + %s)", optional.example(2)) .addLine(" .build();") .addLine("assertEquals(%s.of(%s + %s), value.%s);", optional.type, optional.example(1), optional.example(2), convention.get("item")) .build()) .runTest(); } @Test public void testMap_delegatesToSetterForValidation() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(INVALID_MESSAGE); behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("new DataType.Builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .mapItem(a -> -1);") .build()) .runTest(); } @Test public void testMap_throwsNpeIfMapperIsNull() { thrown.expect(NullPointerException.class); behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("new DataType.Builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .mapItem(null);") .build()) .runTest(); } @Test public void testMap_throwsNpeIfMapperIsNullAndPropertyIsEmpty() { thrown.expect(NullPointerException.class); behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("new DataType.Builder()") .addLine(" .mapItem(null);") .build()) .runTest(); } @Test public void testMap_skipsMapperIfPropertyIsEmpty() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .mapItem(a -> { fail(\"mapper called\"); return -1; })") .addLine(" .build();") .addLine("assertFalse(value.%s.isPresent());", convention.get("item")) .build()) .runTest(); } @Test public void testMap_canUseCustomBoxedFunctionalInterface() { SourceBuilder customMutatorType = SourceBuilder.forTesting(); for (String line : datatype.toString().split("\n")) { if (line.contains("extends DataType_Builder")) { int insertOffset = line.indexOf('{') + 1; customMutatorType .addLine("%s", line.substring(0, insertOffset)) .addLine(" public interface Mapper {") .addLine(" %1$s map(%1$s value);", optional.boxedType) .addLine(" }") .addLine(" @Override public Builder mapItem(Mapper mapper) {") .addLine(" return super.mapItem(mapper);") .addLine(" }") .addLine("%s", line.substring(insertOffset)); } else { customMutatorType.addLine("%s", line); } } behaviorTester .with(new Processor(features)) .with(customMutatorType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .mapItem(a -> null)") .addLine(" .build();") .addLine("assertEquals(%s.empty(), value.%s);", optional.type, convention.get("item")) .build()) .runTest(); } @Test public void testMap_canUseCustomUnboxedFunctionalInterface() { SourceBuilder customMutatorType = SourceBuilder.forTesting(); for (String line : datatype.toString().split("\n")) { if (line.contains("extends DataType_Builder")) { int insertOffset = line.indexOf('{') + 1; customMutatorType .addLine("%s", line.substring(0, insertOffset)) .addLine(" public interface Mapper {") .addLine(" %1$s map(%1$s value);", optional.primitiveType) .addLine(" }") .addLine(" @Override public Builder mapItem(Mapper mapper) {") .addLine(" return super.mapItem(mapper);") .addLine(" }") .addLine("%s", line.substring(insertOffset)); } else { customMutatorType.addLine("%s", line); } } behaviorTester .with(new Processor(features)) .with(customMutatorType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .mapItem(a -> %s)", optional.example(1)) .addLine(" .build();") .addLine("assertEquals(%s.of(%s), value.%s);", optional.type, optional.example(1), convention.get("item")) .build()) .runTest(); } @Test public void testMap_canUseCustomOptionalFunctionalInterface() { SourceBuilder customMutatorType = SourceBuilder.forTesting(); for (String line : datatype.toString().split("\n")) { if (line.contains("extends DataType_Builder")) { int insertOffset = line.indexOf('{') + 1; customMutatorType .addLine("%s", line.substring(0, insertOffset)) .addLine(" public interface Mapper {") .addLine(" %1$s map(%1$s value);", optional.type) .addLine(" }") .addLine(" @Override public Builder mapItem(Mapper mapper) {") .addLine(" return super.mapItem(mapper);") .addLine(" }") .addLine("%s", line.substring(insertOffset)); } else { customMutatorType.addLine("%s", line); } } behaviorTester .with(new Processor(features)) .with(customMutatorType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .mapItem(a -> %s.empty())", optional.type) .addLine(" .build();") .addLine("assertEquals(%s.empty(), value.%s);", optional.type, convention.get("item")) .build()) .runTest(); } @Test public void testClear() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .clearItem()") .addLine(" .build();") .addLine("assertEquals(%s.empty(), value.%s);", optional.type, convention.get("item")) .build()) .runTest(); } @Test public void testMergeFrom_valueInstance() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = DataType.builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .build();") .addLine("DataType.Builder builder = DataType.builder()") .addLine(" .mergeFrom(value);") .addLine("assertEquals(%s.of(%s), builder.%s);", optional.type, optional.example(0), convention.get("item")) .build()) .runTest(); } @Test public void testMergeFrom_builder() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType.Builder template = DataType.builder()") .addLine(" .%s(%s);", convention.set("item"), optional.example(0)) .addLine("DataType.Builder builder = DataType.builder()") .addLine(" .mergeFrom(template);") .addLine("assertEquals(%s.of(%s), builder.%s);", optional.type, optional.example(0), convention.get("item")) .build()) .runTest(); } @Test public void testMergeFrom_valueInstance_emptyOptional() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = DataType.builder()") .addLine(" .build();") .addLine("DataType.Builder builder = DataType.builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .mergeFrom(value);") .addLine("assertEquals(%s.of(%s), builder.%s);", optional.type, optional.example(0), convention.get("item")) .build()) .runTest(); } @Test public void testMergeFrom_builder_emptyOptional() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType.Builder template = DataType.builder();") .addLine("DataType.Builder builder = DataType.builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .mergeFrom(template);") .addLine("assertEquals(%s.of(%s), builder.%s);", optional.type, optional.example(0), convention.get("item")) .build()) .runTest(); } @Test public void testBuilderClear() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .clear()") .addLine(" .build();") .addLine("assertEquals(%s.empty(), value.%s);", optional.type, convention.get("item")) .build()) .runTest(); } @Test public void testBuilderClear_customDefault() { behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %s %s;", optional.type, convention.get("item")) .addLine("") .addLine(" public static class Builder extends DataType_Builder {}") .addLine(" public static Builder builder() {") .addLine(" return new Builder().%s(%s);", convention.set("item"), optional.example(1)) .addLine(" }") .addLine("}")) .with(testBuilder() .addLine("DataType value = DataType.builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .clear()") .addLine(" .build();") .addLine("assertEquals(%s.of(%s), value.%s);", optional.type, optional.example(1), convention.get("item")) .build()) .runTest(); } @Test public void testBuilderClear_noBuilderFactory() { behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %s %s;", optional.type, convention.get("item")) .addLine("") .addLine(" public static class Builder extends DataType_Builder {") .addLine(" public Builder(%s s) {", optional.primitiveType) .addLine(" %s(s);", convention.set("item")) .addLine(" }") .addLine(" }") .addLine("}")) .with(testBuilder() .addLine("DataType value = new DataType.Builder(%s)", optional.example(0)) .addLine(" .clear()") .addLine(" .build();") .addLine("assertEquals(%s.empty(), value.%s);", optional.type, convention.get("item")) .build()) .runTest(); } @Test public void testToBuilder() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = DataType.builder().%s(%s).build();", convention.set("item"), optional.example(0)) .addLine("DataType copy = value.toBuilder().build();") .addLine("assertEquals(value, copy);") .build()) .runTest(); } @Test public void testEquality() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("new %s()", EqualsTester.class) .addLine(" .addEqualityGroup(") .addLine(" DataType.builder().build(),") .addLine(" DataType.builder()") .addLine(" .%s(%s.empty())", convention.set("item"), optional.type) .addLine(" .build(),") .addLine(" DataType.builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .clearItem()") .addLine(" .build())") .addLine(" .addEqualityGroup(") .addLine(" DataType.builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .build(),") .addLine(" DataType.builder()") .addLine(" .%s(%s.of(%s))", convention.set("item"), optional.type, optional.example(0)) .addLine(" .build())") .addLine(" .testEquals();") .build()) .runTest(); } @Test public void testValueToString() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType empty = DataType.builder()") .addLine(" .build();") .addLine("DataType present = DataType.builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .build();") .addLine("assertEquals(\"DataType{}\", empty.toString());") .addLine("assertEquals(\"DataType{item=\" + %s + \"}\", present.toString());", optional.example(0)) .build()) .runTest(); } @Test public void testPartialToString() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType empty = DataType.builder()") .addLine(" .buildPartial();") .addLine("DataType present = DataType.builder()") .addLine(" .%s(%s)", convention.set("item"), optional.example(0)) .addLine(" .buildPartial();") .addLine("assertEquals(\"partial DataType{}\", empty.toString());") .addLine("assertEquals(\"partial DataType{item=\" + %s + \"}\", present.toString());", optional.example(0)) .build()) .runTest(); } @Test public void testJacksonInteroperability() { behaviorTester .with(new Processor(features)) .with(datatype) .with(testBuilder() .addLine("DataType value = new DataType.Builder().%s(%s).build();", convention.set("item"), optional.example(0)) .addLine("%1$s mapper = new %1$s()", ObjectMapper.class) .addLine(" .registerModule(new %s());", Jdk8Module.class) .addLine("String json = mapper.writeValueAsString(value);") .addLine("assertEquals(\"{\\\"item\\\":%s}\", json);", optional.example(0)) .addLine("DataType clone = mapper.readValue(json, DataType.class);") .addLine("assertEquals(%s.of(%s), clone.%s);", optional.type, optional.example(0), convention.get("item")) .build()) .runTest(); } @Test public void testUpgradeMishapCaughtInCompiler() { // Users upgrading from older FreeBuilder versions may have implemented their own primitive // setter delegating to the OptionalP-accepting setter. We need to turn this runtime stack // overflow into a compile-time error. behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting(features) .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("@%s(builder = DataType.Builder.class)", JsonDeserialize.class) .addLine("public interface DataType {") .addLine(" %s %s;", optional.type, convention.get("item")) .addLine("") .addLine(" class Builder extends DataType_Builder {") .addLine(" public Builder %s(%s item) {", convention.set("item"), optional.primitiveType) .addLine(" return %s(%s.of(item));", convention.set("item"), optional.type) .addLine(" }") .addLine(" }") .addLine("") .addLine(" public static Builder builder() {") .addLine(" return new Builder();") .addLine(" }") .addLine("}")) .failsToCompile() .withErrorThat(error -> error .hasMessage("Infinite recursive loop detected") .inFile("/com/example/DataType.java") .onLine(14)); } private static TestBuilder testBuilder() { return new TestBuilder() .addImport("com.example.DataType"); } }
11,929
628
from enum import Flag import json import struct import sys from json_config_parse import parse_json if (len(sys.argv) < 3): sys.exit() output_file = sys.argv[2] asm_file = open(sys.argv[1], "r") asm_text = asm_file.read() asm_file.close() json_text = asm_text.split(";%ifdef CONFIG") if (len(json_text) > 1): json_text = json_text[1].split(";%endif") if (len(json_text) > 1): json_text = json_text[0].strip() # We need to walk each line of text and remove the comment line json_text = json_text.splitlines(False) parsed_lines = "" for line in json_text: line = line.strip() if (line[0] != ';'): sys.exit("Config line needs to start with a comment character ;") line = line.lstrip(";") parsed_lines = parsed_lines + line + '\n' parsed_lines = parsed_lines.strip() parse_json(parsed_lines, output_file)
468
1,150
#pragma once #include <esp_err.h> #ifdef __cplusplus extern "C" { #endif #include <esp_http_server.h> typedef struct { httpd_handle_t hd; int fd; } async_resp_arg_t; typedef void (*blinker_websocket_data_cb_t)(httpd_req_t *req, const char *payload); esp_err_t blinker_websocket_async_print(async_resp_arg_t *arg, const char *payload); esp_err_t blinker_websocket_print(httpd_req_t *req, const char *payload); esp_err_t blinker_websocket_server_init(blinker_websocket_data_cb_t cb); #ifdef __cplusplus } #endif
237
495
<reponame>cz3pearl/database-rider<gh_stars>100-1000 package com.github.database.rider.examples.cucumber.withoutcdi; import com.github.database.rider.core.api.dataset.DataSetExecutor; import com.github.database.rider.core.configuration.DataSetConfig; import com.github.database.rider.core.connection.ConnectionHolderImpl; import com.github.database.rider.core.util.EntityManagerProvider; import com.github.database.rider.core.dataset.DataSetExecutorImpl; import cucumber.api.java.Before; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.example.jpadomain.Contact; import org.junit.Assert; import javax.persistence.Query; import static com.github.database.rider.core.util.EntityManagerProvider.em; import static com.github.database.rider.core.util.EntityManagerProvider.tx; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class ContactStepsWithoutCDI { EntityManagerProvider entityManagerProvider = EntityManagerProvider.newInstance("customerTestDB"); DataSetExecutor dbunitExecutor; Long count; @Before public void setUp() { dbunitExecutor = DataSetExecutorImpl.instance(new ConnectionHolderImpl(entityManagerProvider.connection())); EntityManagerProvider.em().clear();//important to clear JPA first level cache between scenarios } @Given("^we have a list of contacts2$") public void given() { dbunitExecutor.createDataSet(new DataSetConfig("contacts.yml")); Assert.assertEquals(EntityManagerProvider.em().createQuery("select count(c.id) from Contact c").getSingleResult(), new Long(3)); } @When("^^we search contacts by name \"([^\"]*)\"2$") public void we_search_contacts_by_name_(String name) throws Throwable { Contact contact = new Contact(); contact.setName(name); Query query = EntityManagerProvider.em().createQuery("select count(c.id) from Contact c where UPPER(c.name) like :name"); query.setParameter("name", "%" + name.toUpperCase() + "%"); count = (Long) query.getSingleResult(); } @Then("^we should find (\\d+) contacts2$") public void we_should_find_result_contacts(Long result) throws Throwable { assertEquals(result, count); } @When("^we delete contact by id (\\d+) 2$") public void we_delete_contact_by_id(long id) throws Throwable { EntityManagerProvider.tx().begin(); EntityManagerProvider.em().remove(EntityManagerProvider.em().find(Contact.class, id)); EntityManagerProvider.tx().commit(); } @Then("^we should not find contact (\\d+) 2$") public void we_should_not_find_contacts_in_database(long id) throws Throwable { assertNull(EntityManagerProvider.em().find(Contact.class, id)); } }
973
2,114
package io.searchbox.core.search.aggregation; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static io.searchbox.core.search.aggregation.AggregationField.VALUES; /** * @author cfstout */ public class PercentileRanksAggregation extends MetricAggregation { public static final String TYPE = "percentile_ranks"; private Map<String, Double> percentileRanks = new HashMap<String, Double>(); public PercentileRanksAggregation(String name, JsonObject percentilesAggregation) { super(name, percentilesAggregation); parseSource(percentilesAggregation.getAsJsonObject(String.valueOf(VALUES))); } private void parseSource(JsonObject source) { for (Map.Entry<String, JsonElement> entry : source.entrySet()) { if (!(Double.isNaN(entry.getValue().getAsDouble()))) { percentileRanks.put(entry.getKey(), entry.getValue().getAsDouble()); } } } public Map<String, Double> getPercentileRanks() { return percentileRanks; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } PercentileRanksAggregation rhs = (PercentileRanksAggregation) obj; return super.equals(obj) && Objects.equals(percentileRanks, rhs.percentileRanks); } @Override public int hashCode() { return Objects.hash(super.hashCode(), percentileRanks); } }
663
1,909
package org.knowm.xchange.deribit.v2.dto; public enum GrantType { /** using email and and password as when logging on to the website */ password, /** using the access key and access secret that can be found on the API page on the website */ client_credentials, /** * using the access key that can be found on the API page on the website and user generated * signature. The signature is calculated using some fields provided in the request, using formula * described here https://docs.deribit.com/v2/#authentication */ client_signature, /** using a refresh token that was received from an earlier invocation */ refresh_token; }
177
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.billing.models; import com.azure.core.annotation.Immutable; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; /** The details about a participant. */ @Immutable public final class Participants { @JsonIgnore private final ClientLogger logger = new ClientLogger(Participants.class); /* * The acceptance status of the participant. */ @JsonProperty(value = "status", access = JsonProperty.Access.WRITE_ONLY) private String status; /* * The date when the status got changed. */ @JsonProperty(value = "statusDate", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime statusDate; /* * The email address of the participant. */ @JsonProperty(value = "email", access = JsonProperty.Access.WRITE_ONLY) private String email; /** * Get the status property: The acceptance status of the participant. * * @return the status value. */ public String status() { return this.status; } /** * Get the statusDate property: The date when the status got changed. * * @return the statusDate value. */ public OffsetDateTime statusDate() { return this.statusDate; } /** * Get the email property: The email address of the participant. * * @return the email value. */ public String email() { return this.email; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
667
480
/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #include "ble_rpc_event_encoder_gap.h" #include "ble_rpc_defines.h" #include "app_util.h" #include "ble_gap.h" /**@brief Function for encoding a peer address. * * @param[out] p_buffer Pointer to the buffer used for the encoded ble_gap_addr_t. * @param[in] p_peer_address Pointer to the structure to be encoded. * * @return Number of bytes encoded. */ static uint32_t peer_address_encode(uint8_t * const p_buffer, const ble_gap_addr_t * const p_peer_address) { uint32_t i; uint32_t index = 0; p_buffer[index++] = p_peer_address->addr_type; for (i = 0; i < BLE_GAP_ADDR_LEN; i++) { p_buffer[index++] = p_peer_address->addr[i]; } return index; } /** @brief Function for encoding the BLE_GAP_EVT_CONNECTED event. * * @param[in] p_ble_evt Input BLE event. * @param[out] p_buffer Pointer to a buffer for the encoded event. * * @return Number of bytes encoded. */ static uint32_t gap_connected_evt_encode(const ble_evt_t * const p_ble_evt, uint8_t * const p_buffer) { uint32_t index = 0; index += peer_address_encode(&p_buffer[index], &(p_ble_evt->evt.gap_evt.params.connected.peer_addr)); p_buffer[index] = (p_ble_evt->evt.gap_evt.params.connected.irk_match_idx << 1) & 0xFE; p_buffer[index] |= p_ble_evt->evt.gap_evt.params.connected.irk_match; index++; const ble_gap_conn_params_t * p_conn_params; p_conn_params = &(p_ble_evt->evt.gap_evt.params.connected.conn_params); index += uint16_encode(p_conn_params->min_conn_interval, &p_buffer[index]); index += uint16_encode(p_conn_params->max_conn_interval, &p_buffer[index]); index += uint16_encode(p_conn_params->slave_latency, &p_buffer[index]); index += uint16_encode(p_conn_params->conn_sup_timeout, &p_buffer[index]); return index; } /** @brief Function for encoding the BLE_GAP_EVT_DISCONNECTED event. * * @param[in] p_ble_evt Input BLE event. * @param[out] p_buffer Pointer to a buffer for the encoded event. * * @return Number of bytes encoded. */ static uint32_t gap_disconnected_evt_encode(const ble_evt_t * const p_ble_evt, uint8_t * const p_buffer) { uint32_t index = 0; index += peer_address_encode(&p_buffer[index], &(p_ble_evt->evt.gap_evt.params.disconnected.peer_addr)); p_buffer[index++] = p_ble_evt->evt.gap_evt.params.disconnected.reason; return index; } /** @brief Function for encoding the BLE_GAP_EVT_TIMEOUT event. * * @param[in] p_ble_evt Input BLE event. * @param[out] p_buffer Pointer to a buffer for the encoded event. * * @return Number of bytes encoded. */ static uint32_t gap_timeout_evt_encode(const ble_evt_t * const p_ble_evt, uint8_t * const p_buffer) { uint32_t index = 0; p_buffer[index++] = p_ble_evt->evt.gap_evt.params.timeout.src; return index; } /** @brief Function for encoding the BLE_GAP_EVT_CONN_PARAM_UPDATE event. * * @param[in] p_ble_evt Input BLE event. * @param[out] p_buffer Pointer to a buffer for the encoded event. * * @return Number of bytes encoded. */ static uint32_t gap_conn_param_upd_evt_encode(const ble_evt_t * const p_ble_evt, uint8_t * const p_buffer) { uint32_t index = 0; const ble_gap_conn_params_t * p_conn_params; p_conn_params = &(p_ble_evt->evt.gap_evt.params.conn_param_update.conn_params); index += uint16_encode(p_conn_params->min_conn_interval, &p_buffer[index]); index += uint16_encode(p_conn_params->max_conn_interval, &p_buffer[index]); index += uint16_encode(p_conn_params->slave_latency, &p_buffer[index]); index += uint16_encode(p_conn_params->conn_sup_timeout, &p_buffer[index]); return index; } /** @brief Function for encoding the BLE_GAP_EVT_SEC_PARAMS_REQUEST event. * * @param[in] p_ble_evt Input BLE event. * @param[out] p_buffer Pointer to a buffer for the encoded event. * * @return Number of bytes encoded. */ static uint32_t gap_sec_param_req_evt_encode(const ble_evt_t * const p_ble_evt, uint8_t * const p_buffer) { uint32_t index = 0; const ble_gap_evt_sec_params_request_t * p_sec_params_request; p_sec_params_request = &(p_ble_evt->evt.gap_evt.params.sec_params_request); index += uint16_encode(p_sec_params_request->peer_params.timeout, &p_buffer[index]); p_buffer[index++] = (p_sec_params_request->peer_params.oob << 5) | (p_sec_params_request->peer_params.io_caps << 2) | (p_sec_params_request->peer_params.mitm << 1) | (p_sec_params_request->peer_params.bond); p_buffer[index++] = p_sec_params_request->peer_params.min_key_size; p_buffer[index++] = p_sec_params_request->peer_params.max_key_size; return index; } /** @brief Function for encoding the BLE_GAP_EVT_SEC_INFO_REQUEST event. * * @param[in] p_ble_evt Input BLE event. * @param[out] p_buffer Pointer to a buffer for the encoded event. * * @return Number of bytes encoded. */ static uint32_t gap_sec_info_req_evt_encode(const ble_evt_t * const p_ble_evt, uint8_t * const p_buffer) { uint32_t index = 0; const ble_gap_evt_sec_info_request_t * p_sec_info_request; p_sec_info_request = &(p_ble_evt->evt.gap_evt.params.sec_info_request); index += peer_address_encode(&p_buffer[index], &(p_sec_info_request->peer_addr)); index += uint16_encode(p_sec_info_request->div, &p_buffer[index]); p_buffer[index++] = (p_sec_info_request->sign_info << 2 ) | (p_sec_info_request->id_info << 1 ) | (p_sec_info_request->enc_info); return index; } /** @brief Function for encoding the BLE_GAP_EVT_AUTH_STATUS event. * * @param[in] p_ble_evt Input BLE event. * @param[out] p_buffer Pointer to a buffer for the encoded event. * * @return Number of bytes encoded. */ static uint32_t gap_auth_status_evt_encode(const ble_evt_t * const p_ble_evt, uint8_t * const p_buffer) { uint32_t index = 0; const ble_gap_evt_auth_status_t * p_auth_status; p_auth_status = &(p_ble_evt->evt.gap_evt.params.auth_status); p_buffer[index++] = p_auth_status->auth_status; p_buffer[index++] = p_auth_status->error_src; p_buffer[index++] = (p_auth_status->sm1_levels.lv3 << 5) | (p_auth_status->sm1_levels.lv2 << 4) | (p_auth_status->sm1_levels.lv1 << 3) | (p_auth_status->sm2_levels.lv3 << 2) | (p_auth_status->sm2_levels.lv2 << 1) | (p_auth_status->sm2_levels.lv1); p_buffer[index++] = (p_auth_status->periph_kex.csrk << 4) | (p_auth_status->periph_kex.address << 3) | (p_auth_status->periph_kex.irk << 2) | (p_auth_status->periph_kex.ediv_rand << 1) | (p_auth_status->periph_kex.ltk); p_buffer[index++] = (p_auth_status->central_kex.csrk << 4) | (p_auth_status->central_kex.address << 3) | (p_auth_status->central_kex.irk << 2) | (p_auth_status->central_kex.ediv_rand << 1) | (p_auth_status->central_kex.ltk); index += uint16_encode(p_auth_status->periph_keys.enc_info.div, &p_buffer[index]); uint32_t i; for (i = 0; i < BLE_GAP_SEC_KEY_LEN; i++) { p_buffer[index++] = p_auth_status->periph_keys.enc_info.ltk[i]; } p_buffer[index++] = (p_auth_status->periph_keys.enc_info.ltk_len << 1) | (p_auth_status->periph_keys.enc_info.auth); for (i = 0; i < BLE_GAP_SEC_KEY_LEN; i++) { p_buffer[index++] = (p_auth_status->central_keys.irk.irk[i]); } index += peer_address_encode(&p_buffer[index], &(p_auth_status->central_keys.id_info)); return index; } /** @brief Function for encoding the BLE_GAP_EVT_CONN_SEC_UPDATE event. * * @param[in] p_ble_evt Input BLE event. * @param[out] p_buffer Pointer to a buffer for the encoded event. * * @return Number of bytes encoded. */ static uint32_t gap_con_sec_upd_evt_encode(const ble_evt_t * const p_ble_evt, uint8_t * const p_buffer) { uint32_t index = 0; const ble_gap_evt_conn_sec_update_t * p_conn_sec_update; p_conn_sec_update = &(p_ble_evt->evt.gap_evt.params.conn_sec_update); p_buffer[index++] = p_conn_sec_update->conn_sec.sec_mode.sm | (p_conn_sec_update->conn_sec.sec_mode.lv << 4); p_buffer[index++] = p_conn_sec_update->conn_sec.encr_key_size; return index; } uint32_t ble_rpc_evt_gap_encode(ble_evt_t * p_ble_evt, uint8_t * p_buffer) { uint32_t index = 0; // Encode packet type. p_buffer[index++] = BLE_RPC_PKT_EVT; // Encode header. index += uint16_encode(p_ble_evt->header.evt_id, &p_buffer[index]); // Encode common part of the event. index += uint16_encode(p_ble_evt->evt.gap_evt.conn_handle, &p_buffer[index]); // Encode events. switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: index += gap_connected_evt_encode(p_ble_evt, &p_buffer[index]); break; case BLE_GAP_EVT_DISCONNECTED: index += gap_disconnected_evt_encode(p_ble_evt, &p_buffer[index]); break; case BLE_GAP_EVT_TIMEOUT: index += gap_timeout_evt_encode(p_ble_evt, &p_buffer[index]); break; case BLE_GAP_EVT_CONN_PARAM_UPDATE: index += gap_conn_param_upd_evt_encode(p_ble_evt, &p_buffer[index]); break; case BLE_GAP_EVT_SEC_PARAMS_REQUEST: index += gap_sec_param_req_evt_encode(p_ble_evt, &p_buffer[index]); break; case BLE_GAP_EVT_SEC_INFO_REQUEST: index += gap_sec_info_req_evt_encode(p_ble_evt, &p_buffer[index]); break; case BLE_GAP_EVT_AUTH_STATUS: index += gap_auth_status_evt_encode(p_ble_evt, &p_buffer[index]); break; case BLE_GAP_EVT_CONN_SEC_UPDATE: index += gap_con_sec_upd_evt_encode(p_ble_evt, &p_buffer[index]); break; default: break; } return index; }
5,675
892
{ "schema_version": "1.2.0", "id": "GHSA-j6px-jwvv-vpwq", "modified": "2021-02-01T15:00:53Z", "published": "2021-02-01T15:01:26Z", "aliases": [ "CVE-2021-21277" ], "summary": "Angular Expressions - Remote Code Execution", "details": "### Impact\n\nThe vulnerability, reported by GoSecure Inc, allows Remote Code Execution, if you call `expressions.compile(userControlledInput)` where `userControlledInput` is text that comes from user input.\n\nThis time, the security of the package could be bypassed by using a more complex payload, using a `.constructor.constructor` technique.\n\n* If running angular-expressions in the browser, an attacker could run any browser script when the application code calls expressions.compile(userControlledInput).\n* If running angular-expressions on the server, an attacker could run any Javascript expression, thus gaining Remote Code Execution.\n\n### Patches\n\nUsers should upgrade to version 1.1.2 of angular-expressions\n\n### Workarounds\n\nA temporary workaround might be either to : \n\n* disable user-controlled input that will be fed into angular-expressions in your application\n\nOR\n\n* allow only following characters in the userControlledInput : \n\n```js\nif (/^[|a-zA-Z.0-9 :\"'+-?]+$/.test(userControlledInput)) {\n var result = expressions.compile(userControlledInput);\n}\nelse {\n result = undefined;\n}\n```\n\n### References\n\n[Removal of angular-expression sandbox](http://blog.angularjs.org/2016/09/angular-16-expression-sandbox-removal.html)\n\n### For more information\n\nIf you have any questions or comments about this advisory:\n* Open an issue in [angular-expressions](https://github.com/peerigon/angular-expressions/issues)\n* [Email us](mailto:<EMAIL>)\n\n### Credits \n\nThe issue was reported by <NAME> from GoSecure, Inc.", "severity": [ ], "affected": [ { "package": { "ecosystem": "npm", "name": "angular-expressions" }, "ranges": [ { "type": "ECOSYSTEM", "events": [ { "introduced": "0" }, { "fixed": "1.1.2" } ] } ] } ], "references": [ { "type": "WEB", "url": "https://github.com/peerigon/angular-expressions/security/advisories/GHSA-j6px-jwvv-vpwq" }, { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-21277" }, { "type": "WEB", "url": "https://github.com/peerigon/angular-expressions/commit/07edb62902b1f6127b3dcc013da61c6316dd0bf1" }, { "type": "WEB", "url": "https://www.npmjs.com/package/angular-expressions" }, { "type": "WEB", "url": "http://blog.angularjs.org/2016/09/angular-16-expression-sandbox-removal.html" } ], "database_specific": { "cwe_ids": [ "CWE-74" ], "severity": "LOW", "github_reviewed": true } }
1,214
471
<reponame>madanagopaltcomcast/pxCore<filename>examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/src/os2/dir.cpp ///////////////////////////////////////////////////////////////////////////// // Name: src/os2/dir.cpp // Purpose: wxDir implementation for OS/2 // Author: <NAME> // Modified by: <NAME> // Created: 08.12.99 // Copyright: (c) 1999 <NAME> <<EMAIL>> // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/os2/private.h" #include "wx/intl.h" #include "wx/log.h" #endif // PCH #include "wx/dir.h" #include "wx/filefn.h" // for wxMatchWild #include <sys/types.h> #define INCL_DOSFILEMGR #define INCL_DOSERRORS #include <os2.h> #ifdef __EMX__ #include <dirent.h> #endif // ---------------------------------------------------------------------------- // define the types and functions used for file searching // ---------------------------------------------------------------------------- typedef FILEFINDBUF3 FIND_STRUCT; typedef HDIR FIND_DATA; typedef ULONG FIND_ATTR; static inline FIND_DATA InitFindData() { return ERROR_INVALID_HANDLE; } static inline bool IsFindDataOk( FIND_DATA vFd ) { return vFd != ERROR_INVALID_HANDLE; } static inline void FreeFindData( FIND_DATA vFd ) { if (!::DosFindClose(vFd)) { wxLogLastError(wxT("DosFindClose")); } } static inline FIND_DATA FindFirst( const wxString& rsSpec , FIND_STRUCT* pFinddata ) { ULONG ulFindCount = 1; FIND_DATA hDir = HDIR_CREATE; FIND_ATTR rc; rc = ::DosFindFirst( rsSpec.c_str() ,&hDir ,0x37 // was: FILE_NORMAL ,pFinddata ,sizeof(FILEFINDBUF3) ,&ulFindCount ,FIL_STANDARD ); if (rc != 0) return InitFindData(); return hDir; } static inline bool FindNext( FIND_DATA vFd , FIND_STRUCT* pFinddata ) { ULONG ulFindCount = 1; return ::DosFindNext( vFd ,pFinddata ,sizeof(FILEFINDBUF3) ,&ulFindCount ) == 0; } static const wxChar* GetNameFromFindData( FIND_STRUCT* pFinddata ) { return (wxChar*)pFinddata->achName; } static const FIND_ATTR GetAttrFromFindData( FIND_STRUCT* pFinddata ) { return pFinddata->attrFile; } static inline bool IsDir( FIND_ATTR vAttr ) { return (vAttr & FILE_DIRECTORY) != 0; } static inline bool IsHidden( FIND_ATTR vAttr ) { return (vAttr & (FILE_HIDDEN | FILE_SYSTEM)) != 0; } // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- #ifndef MAX_PATH #define MAX_PATH 260 // from PM++ headers #endif // ---------------------------------------------------------------------------- // macros // ---------------------------------------------------------------------------- #define M_DIR ((wxDirData *)m_data) // ---------------------------------------------------------------------------- // private classes // ---------------------------------------------------------------------------- // this class stores everything we need to enumerate the files class wxDirData { public: wxDirData(const wxString& rsDirname); ~wxDirData(); void SetFileSpec(const wxString& rsFilespec) { m_sFilespec = rsFilespec; } void SetFlags(int nFlags) { m_nFlags = nFlags; } const wxString& GetName() const { return m_sDirname; } void Close(); void Rewind(); bool Read(wxString* rsFilename); private: FIND_DATA m_vFinddata; wxString m_sDirname; wxString m_sFilespec; int m_nFlags; }; // end of CLASS wxDirData // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // wxDirData // ---------------------------------------------------------------------------- wxDirData::wxDirData( const wxString& rsDirname ) : m_sDirname(rsDirname) { m_vFinddata = InitFindData(); } // end of wxDirData::wxDirData wxDirData::~wxDirData() { Close(); } // end of wxDirData::~wxDirData void wxDirData::Close() { if ( IsFindDataOk(m_vFinddata) ) { FreeFindData(m_vFinddata); m_vFinddata = InitFindData(); } } // end of wxDirData::Close void wxDirData::Rewind() { Close(); } // end of wxDirData::Rewind bool wxDirData::Read( wxString* psFilename ) { bool bFirst = false; FILEFINDBUF3 vFinddata; #define PTR_TO_FINDDATA (&vFinddata) if (!IsFindDataOk(m_vFinddata)) { // // Open first // wxString sFilespec = m_sDirname; if ( !wxEndsWithPathSeparator(sFilespec) ) { sFilespec += wxT('\\'); } sFilespec += (!m_sFilespec ? wxT("*.*") : m_sFilespec.c_str()); m_vFinddata = FindFirst( sFilespec ,PTR_TO_FINDDATA ); bFirst = true; } if ( !IsFindDataOk(m_vFinddata) ) { return false; } const wxChar* zName; FIND_ATTR vAttr; for ( ;; ) { if (bFirst) { bFirst = false; } else { if (!FindNext( m_vFinddata ,PTR_TO_FINDDATA )) { return false; } } zName = GetNameFromFindData(PTR_TO_FINDDATA); vAttr = GetAttrFromFindData(PTR_TO_FINDDATA); // // Don't return "." and ".." unless asked for // if ( zName[0] == wxT('.') && ((zName[1] == wxT('.') && zName[2] == wxT('\0')) || (zName[1] == wxT('\0'))) ) { if (!(m_nFlags & wxDIR_DOTDOT)) continue; } // // Check the type now // if (!(m_nFlags & wxDIR_FILES) && !IsDir(vAttr)) { // // It's a file, but we don't want them // continue; } else if (!(m_nFlags & wxDIR_DIRS) && IsDir(vAttr) ) { // // It's a dir, and we don't want it // continue; } // // Finally, check whether it's a hidden file // if (!(m_nFlags & wxDIR_HIDDEN)) { if (IsHidden(vAttr)) { // // It's a hidden file, skip it // continue; } } *psFilename = zName; break; } return true; } // end of wxDirData::Read // ---------------------------------------------------------------------------- // wxDir construction/destruction // ---------------------------------------------------------------------------- wxDir::wxDir( const wxString& rsDirname ) { m_data = NULL; (void)Open(rsDirname); } // end of wxDir::wxDir bool wxDir::Open( const wxString& rsDirname ) { delete M_DIR; m_data = new wxDirData(rsDirname); return true; } // end of wxDir::Open bool wxDir::IsOpened() const { return m_data != NULL; } // end of wxDir::IsOpen wxString wxDir::GetName() const { wxString name; if ( m_data ) { name = M_DIR->GetName(); if ( !name.empty() ) { // bring to canonical Windows form name.Replace(wxT("/"), wxT("\\")); if ( name.Last() == wxT('\\') ) { // chop off the last (back)slash name.Truncate(name.length() - 1); } } } return name; } wxDir::~wxDir() { delete M_DIR; } // end of wxDir::~wxDir // ---------------------------------------------------------------------------- // wxDir enumerating // ---------------------------------------------------------------------------- bool wxDir::GetFirst( wxString* psFilename , const wxString& rsFilespec , int nFlags ) const { wxCHECK_MSG( IsOpened(), false, wxT("must wxDir::Open() first") ); M_DIR->Rewind(); M_DIR->SetFileSpec(rsFilespec); M_DIR->SetFlags(nFlags); return GetNext(psFilename); } // end of wxDir::GetFirst bool wxDir::GetNext( wxString* psFilename ) const { wxCHECK_MSG( IsOpened(), false, wxT("must wxDir::Open() first") ); wxCHECK_MSG( psFilename, false, wxT("bad pointer in wxDir::GetNext()") ); return M_DIR->Read(psFilename); } // end of wxDir::GetNext
4,672
386
<filename>src/IECoreHoudini/plugin/Plugin.cpp ////////////////////////////////////////////////////////////////////////// // // Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios), // its affiliates and/or its licensors. // // Copyright (c) 2010-2015, Image Engine Design Inc. 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECoreHoudini/GEO_CobIOTranslator.h" #include "IECoreHoudini/GEO_CortexPrimitive.h" #include "IECoreHoudini/GU_CortexPrimitive.h" #include "IECoreHoudini/OBJ_SceneCacheGeometry.h" #include "IECoreHoudini/OBJ_SceneCacheTransform.h" #include "IECoreHoudini/ROP_SceneCacheWriter.h" #include "IECoreHoudini/SOP_CortexConverter.h" #include "IECoreHoudini/SOP_OpHolder.h" #include "IECoreHoudini/SOP_ParameterisedHolder.h" #include "IECoreHoudini/SOP_SceneCacheSource.h" #include "IECoreHoudini/SOP_SceneCacheTransform.h" #include "DM/DM_RenderTable.h" #include "OP/OP_OperatorTable.h" #include "UT/UT_DSOVersion.h" #include "UT/UT_IOTable.h" #include "UT/UT_Version.h" #if UT_MAJOR_VERSION_INT >= 14 typedef IECoreHoudini::GEO_CortexPrimitive CortexPrimitive; #else #include "IECoreHoudini/GU_CortexPrimitive.h" typedef IECoreHoudini::GU_CortexPrimitive CortexPrimitive; #endif using namespace IECoreHoudini; /// Tell Houdini that this plugin should be loaded with RTLD_GLOBAL extern "C" { SYS_VISIBILITY_EXPORT void HoudiniDSOInit( UT_DSOInfo &dsoinfo ) { const char *forceGlobals = std::getenv( "IECORE_RTLD_GLOBAL" ); if( !forceGlobals || !strcmp( forceGlobals, "1" ) ) { dsoinfo.loadGlobal = true; } } } /// Declare our new SOPs void newSopOperator(OP_OperatorTable *table) { OP_Operator *opHolder = new OP_Operator( "ieOpHolder", "Cortex Op", SOP_OpHolder::create, SOP_ParameterisedHolder::parameters, 0, 4, SOP_ParameterisedHolder::variables, OP_FLAG_GENERATOR ); opHolder->setIconName( "CortexLogoMini" ); OP_Operator *converter = new OP_Operator( SOP_CortexConverter::typeName, "Cortex Convert", SOP_CortexConverter::create, SOP_CortexConverter::parameters, 1, 1, SOP_CortexConverter::variables, OP_FLAG_GENERATOR ); converter->setIconName( "CortexLogoMini" ); OP_Operator *sceneCacheSource = new OP_Operator( SOP_SceneCacheSource::typeName, "SceneCache Source", SOP_SceneCacheSource::create, SOP_SceneCacheSource::buildParameters(), 0, 0, NULL, OP_FLAG_GENERATOR ); /// \todo: get a new icon sceneCacheSource->setIconName( "SOP_ieCortexConverter" ); OP_Operator *sceneCacheTransform = new OP_Operator( SOP_SceneCacheTransform::typeName, "SceneCache Xform", SOP_SceneCacheTransform::create, SOP_SceneCacheTransform::buildParameters(), 1, 1, NULL ); /// \todo: get a new icon sceneCacheTransform->setIconName( "SOP_xform" ); table->addOperator( opHolder ); table->addOperator( converter ); table->addOperator( sceneCacheSource ); table->addOperator( sceneCacheTransform ); table->addOpHidden( opHolder->getName() ); table->addOpHidden( converter->getName() ); table->addOpHidden( sceneCacheSource->getName() ); table->addOpHidden( sceneCacheTransform->getName() ); } void newObjectOperator( OP_OperatorTable *table ) { OP_Operator *sceneCacheTransform = new OP_Operator( OBJ_SceneCacheTransform::typeName, "SceneCache Xform", OBJ_SceneCacheTransform::create, OBJ_SceneCacheTransform::buildParameters(), #if UT_MAJOR_VERSION_INT >= 16 OBJ_SceneCacheTransform::theChildTableName, #endif 0, 1 ); /// \todo: get a new icon sceneCacheTransform->setIconName( "SOP_ieCortexConverter" ); OP_Operator *sceneCacheGeometry = new OP_Operator( OBJ_SceneCacheGeometry::typeName, "SceneCache GEO", OBJ_SceneCacheGeometry::create, OBJ_SceneCacheGeometry::buildParameters(), #if UT_MAJOR_VERSION_INT >= 16 OBJ_SceneCacheGeometry::theChildTableName, #endif 0, 1, NULL ); /// \todo: get a new icon sceneCacheGeometry->setIconName( "SOP_ieProceduralHolder" ); table->addOperator( sceneCacheTransform ); table->addOperator( sceneCacheGeometry ); table->addOpHidden( sceneCacheTransform->getName() ); table->addOpHidden( sceneCacheGeometry->getName() ); } void newDriverOperator( OP_OperatorTable *table ) { OP_Operator *sceneCacheWriter = new OP_Operator( ROP_SceneCacheWriter::typeName, "SceneCache Writer", ROP_SceneCacheWriter::create, ROP_SceneCacheWriter::buildParameters(), #if UT_MAJOR_VERSION_INT >= 16 ROP_SceneCacheWriter::theChildTableName, #endif 0, 999, NULL, OP_FLAG_GENERATOR ); sceneCacheWriter->setIconName( "CortexLogoMini" ); table->addOperator( sceneCacheWriter ); table->addOpHidden( sceneCacheWriter->getName() ); } /// Declare our new Render Hooks for Houdini 12.0 and 12.1 only #if UT_MAJOR_VERSION_INT == 12 && UT_MINOR_VERSION_INT <= 1 void newRenderHook( GR_RenderTable *table ) { GR_Cortex *hook = new GR_Cortex; table->addHook( hook, GR_RENDER_HOOK_VERSION ); } #endif extern "C"{ void newGeometryPrim( GA_PrimitiveFactory *factory ) { CortexPrimitive::registerDefinition(factory); } } /// Declare our new IO Translators void newGeometryIO( void * ) { GU_Detail::registerIOTranslator( new GEO_CobIOTranslator() ); UT_ExtensionList *geoextension = UTgetGeoExtensions(); if ( !geoextension->findExtension( "cob" ) ) { geoextension->addExtension( "cob" ); } if ( !geoextension->findExtension( "pdc" ) ) { geoextension->addExtension( "pdc" ); } }
2,492
575
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/prefetch/no_state_prefetch/no_state_prefetch_tab_helper.h" #include "chrome/browser/prefetch/no_state_prefetch/no_state_prefetch_manager_factory.h" #include "components/no_state_prefetch/browser/no_state_prefetch_manager.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" using content::WebContents; namespace prerender { NoStatePrefetchTabHelper::NoStatePrefetchTabHelper( content::WebContents* web_contents) : content::WebContentsObserver(web_contents) {} NoStatePrefetchTabHelper::~NoStatePrefetchTabHelper() = default; void NoStatePrefetchTabHelper::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame() || !navigation_handle->HasCommitted() || navigation_handle->IsErrorPage()) { return; } NoStatePrefetchManager* no_state_prefetch_manager = NoStatePrefetchManagerFactory::GetForBrowserContext( web_contents()->GetBrowserContext()); if (!no_state_prefetch_manager) return; if (no_state_prefetch_manager->IsWebContentsPrerendering(web_contents())) return; no_state_prefetch_manager->RecordNavigation(navigation_handle->GetURL()); } WEB_CONTENTS_USER_DATA_KEY_IMPL(NoStatePrefetchTabHelper) } // namespace prerender
509
746
// 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.impala.analysis; import org.apache.impala.testutil.TestUtils; import org.junit.Test; public class AnalyzeUpsertStmtTest extends AnalyzerTest { @Test public void TestUpsert() { // VALUES clause AnalyzesOk("upsert into table functional_kudu.testtbl values(1, 'a', 1)"); AnalyzesOk("upsert into table functional_kudu.testtbl(id) values(1)"); AnalyzesOk("upsert into table functional_kudu.testtbl values(1, 'a', 1), " + "(2, 'b', 2), (3, 'c', 3)"); // SELECT clause AnalyzesOk("upsert into functional_kudu.testtbl select bigint_col, string_col, " + "int_col from functional.alltypes"); // Permutation lists AnalyzesOk("upsert into table functional_kudu.testtbl(id) select bigint_col " + "from functional.alltypes"); AnalyzesOk("upsert into table functional_kudu.testtbl(id, name) select bigint_col, " + "string_col from functional.alltypes"); AnalyzesOk("upsert into table functional_kudu.testtbl(name, zip, id) select " + "string_col, int_col, bigint_col from functional.alltypes"); // WITH clause AnalyzesOk("with t1 as (select 1, 'a', 2) upsert into functional_kudu.testtbl " + "select * from t1"); AnalyzesOk("with t1 as (select * from functional.alltypes) upsert into " + "functional_kudu.testtbl select bigint_col, string_col, int_col from t1"); // WITH belonging to the select clause AnalyzesOk("upsert into functional_kudu.testtbl with t1 as (select * from " + "functional.alltypes) select bigint_col, string_col, int_col from t1"); AnalyzesOk("upsert into functional_kudu.testtbl(id) with t1 as (select * from " + "functional.alltypes) select bigint_col from t1"); // Multiple WITH clauses AnalyzesOk("with t1 as (select * from functional.alltypestiny) " + "upsert into functional_kudu.testtbl with t2 as (select * from " + "functional.alltypessmall) select bigint_col, string_col, int_col from t1"); // Correlated inline view AnalyzesOk("upsert into table functional_kudu.testtbl " + "select a.id, string_col, b.month " + "from functional.alltypes a, functional.allcomplextypes b, " + "(select item from b.int_array_col) v1 " + "where a.id = b.id"); // Hint AnalyzesOk("upsert into table functional_kudu.testtbl [clustered] select * from " + "functional_kudu.testtbl"); // Mixed column name case on both primary key and non-primary key cols. AnalyzesOk("upsert into functional_kudu.testtbl (ID, ZIP) values (0, 0)"); // Key columns missing from permutation AnalysisError("upsert into functional_kudu.testtbl(zip) values(1)", "All primary key columns must be specified for UPSERTing into Kudu tables. " + "Missing columns are: id"); // SELECT clause with wrong number of columns AnalysisError("upsert into functional_kudu.testtbl select * from functional.alltypes", "Target table 'functional_kudu.testtbl' has fewer columns (3) than the SELECT " + "/ VALUES clause returns (13)"); // VALUES clause with wrong number of columns AnalysisError("upsert into functional_kudu.testtbl values(1)", "Target table " + "'functional_kudu.testtbl' has more columns (3) than the SELECT / VALUES " + "clause returns (1)"); // Permutation with wrong number of columns AnalysisError("upsert into functional_kudu.testtbl(id, name, zip) values(1)", "Column permutation mentions more columns (3) than the SELECT / VALUES " + "clause returns (1)"); // Type mismatch AnalysisError("upsert into functional_kudu.testtbl values(1, 1, 1)", "Target table 'functional_kudu.testtbl' is incompatible with source " + "expressions.\nExpression '1' (type: TINYINT) is not compatible with column " + "'name' (type: STRING)"); // Permutation with type mismatch AnalysisError("upsert into functional_kudu.testtbl(zip, id, name) " + "values('a', 'a', 'a')", "Target table 'functional_kudu.testtbl' is " + "incompatible with source expressions.\nExpression ''a'' (type: STRING) is not " + "compatible with column 'zip' (type: INT)"); // Permutation with invalid column name AnalysisError("upsert into functional_kudu.testtbl (id, name, invalid) values " + "(1, 'a', 1)", "Unknown column 'invalid' in column permutation"); // Permutation with repeated column AnalysisError("upsert into functional_kudu.testtbl (id, name, zip, id) values " + "(1, 'a', 1, 1)", "Duplicate column 'id' in column permutation"); // UPSERT into non-Kudu table AnalysisError("upsert into functional.alltypes select * from functional.alltypes", "UPSERT is only supported for Kudu tables"); // Unknown target DB AnalysisError("upsert into UNKNOWNDB.testtbl select * " + "from functional.alltypesnopart", "Database does not exist: UNKNOWNDB"); // WITH-clause tables cannot be upserted into AnalysisError("with t1 as (select 'a' x) upsert into t1 values('b' x)", "Table does not exist: default.t1"); // Cannot upsert into a view AnalysisError("upsert into functional.alltypes_view select * from " + "functional.alltypes", "Impala does not support UPSERTing into views: functional.alltypes_view"); // Upsert with uncorrelated inline view AnalysisError("upsert into table functional_kudu.testtbl " + "select a.id, a.string_col, b.month " + "from functional.alltypes a, functional.allcomplextypes b, " + "(select item from b.int_array_col, functional.alltypestiny) v1 " + "where a.id = b.id", "Nested query is illegal because it contains a table reference " + "'b.int_array_col' correlated with an outer block as well as an " + "uncorrelated one 'functional.alltypestiny':\n" + "SELECT item FROM b.int_array_col, functional.alltypestiny"); // Illegal complex-typed expr AnalysisError("upsert into functional_kudu.testtbl " + "select int_array_col from functional.allcomplextypes", "Expr 'int_array_col' in select list returns a collection type 'ARRAY<INT>'.\n" + "Collection types are not allowed in the select list."); } }
2,533
435
<reponame>allen91wu/data<gh_stars>100-1000 { "description": "During this talk, I will share my experience gathered during the\ndevelopment of Allegro's visual search engine. I will present our entire\njourney from the plain idea through different modelling approaches up to\nits current solution. Finally, I will provide some tips and tricks that\nwe have learned along the way and show a lot of images - after all,\nthat's what you're looking for!\n\nHow can one effectively find a recently seen t-shirt on an e-commerce\nplatform such as Allegro? Or maybe an unusual set of cups, that is used\nby the coffee shop downstairs? One could try to describe them, but a\npicture is worth a thousand words - what if that one picture or actually\na photo was enough? With over 100 million offers and with multiple\nphotos for every product, this seems nearly impossible. Especially given\nhow similar some products are. During this talk, I will share how we\nmake it possible by introducing a visual search model. I will focus on\nour machine learning model and its evolution over time but also cover\nsome technical aspects of our approach.\n", "duration": 1675, "language": "eng", "published_at": "2020-01-02T16:37:14.000Z", "recorded": "2019-12-13", "speakers": [ "<NAME>\u0144ski" ], "thumbnail_url": "https://i.ytimg.com/vi/89tVbSIqwFA/hqdefault.jpg", "title": "Visual Search @ allegro.pl", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=89tVbSIqwFA" } ] }
462
2,406
<filename>inference-engine/src/low_precision_transformations/include/low_precision/lpt_visibility.hpp // Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "ngraph/visibility.hpp" /** * @file lpt_visibility.hpp * @brief Defines visibility settings for Inference Engine LP Transformations library */ #ifdef inference_engine_lp_transformations_EXPORTS #define LP_TRANSFORMATIONS_API NGRAPH_HELPER_DLL_EXPORT #else #define LP_TRANSFORMATIONS_API NGRAPH_HELPER_DLL_IMPORT #endif
188
359
<reponame>shubham-goel/idr import os import torch import numpy as np import utils.general as utils from utils import rend_util class SceneDataset(torch.utils.data.Dataset): """Dataset for a class of objects, where each datapoint is a SceneInstanceDataset.""" def __init__(self, train_cameras, data_dir, img_res, scan_id=0, cam_file=None ): self.instance_dir = os.path.join('../data', data_dir, 'scan{0}'.format(scan_id)) self.total_pixels = img_res[0] * img_res[1] self.img_res = img_res assert os.path.exists(self.instance_dir), "Data directory is empty" self.sampling_idx = None self.train_cameras = train_cameras image_dir = '{0}/image'.format(self.instance_dir) image_paths = sorted(utils.glob_imgs(image_dir)) mask_dir = '{0}/mask'.format(self.instance_dir) mask_paths = sorted(utils.glob_imgs(mask_dir)) self.n_images = len(image_paths) self.cam_file = '{0}/cameras.npz'.format(self.instance_dir) if cam_file is not None: self.cam_file = '{0}/{1}'.format(self.instance_dir, cam_file) camera_dict = np.load(self.cam_file) scale_mats = [camera_dict['scale_mat_%d' % idx].astype(np.float32) for idx in range(self.n_images)] world_mats = [camera_dict['world_mat_%d' % idx].astype(np.float32) for idx in range(self.n_images)] self.intrinsics_all = [] self.pose_all = [] for scale_mat, world_mat in zip(scale_mats, world_mats): P = world_mat @ scale_mat P = P[:3, :4] intrinsics, pose = rend_util.load_K_Rt_from_P(None, P) self.intrinsics_all.append(torch.from_numpy(intrinsics).float()) self.pose_all.append(torch.from_numpy(pose).float()) self.rgb_images = [] for path in image_paths: rgb = rend_util.load_rgb(path) rgb = rgb.reshape(3, -1).transpose(1, 0) self.rgb_images.append(torch.from_numpy(rgb).float()) self.object_masks = [] for path in mask_paths: object_mask = rend_util.load_mask(path) object_mask = object_mask.reshape(-1) self.object_masks.append(torch.from_numpy(object_mask).bool()) def __len__(self): return self.n_images def __getitem__(self, idx): uv = np.mgrid[0:self.img_res[0], 0:self.img_res[1]].astype(np.int32) uv = torch.from_numpy(np.flip(uv, axis=0).copy()).float() uv = uv.reshape(2, -1).transpose(1, 0) sample = { "object_mask": self.object_masks[idx], "uv": uv, "intrinsics": self.intrinsics_all[idx], } ground_truth = { "rgb": self.rgb_images[idx] } if self.sampling_idx is not None: ground_truth["rgb"] = self.rgb_images[idx][self.sampling_idx, :] sample["object_mask"] = self.object_masks[idx][self.sampling_idx] sample["uv"] = uv[self.sampling_idx, :] if not self.train_cameras: sample["pose"] = self.pose_all[idx] return idx, sample, ground_truth def collate_fn(self, batch_list): # get list of dictionaries and returns input, ground_true as dictionary for all batch instances batch_list = zip(*batch_list) all_parsed = [] for entry in batch_list: if type(entry[0]) is dict: # make them all into a new dict ret = {} for k in entry[0].keys(): ret[k] = torch.stack([obj[k] for obj in entry]) all_parsed.append(ret) else: all_parsed.append(torch.LongTensor(entry)) return tuple(all_parsed) def change_sampling_idx(self, sampling_size): if sampling_size == -1: self.sampling_idx = None else: self.sampling_idx = torch.randperm(self.total_pixels)[:sampling_size] def get_scale_mat(self): return np.load(self.cam_file)['scale_mat_0'] def get_gt_pose(self, scaled=False): # Load gt pose without normalization to unit sphere camera_dict = np.load(self.cam_file) world_mats = [camera_dict['world_mat_%d' % idx].astype(np.float32) for idx in range(self.n_images)] scale_mats = [camera_dict['scale_mat_%d' % idx].astype(np.float32) for idx in range(self.n_images)] pose_all = [] for scale_mat, world_mat in zip(scale_mats, world_mats): P = world_mat if scaled: P = world_mat @ scale_mat P = P[:3, :4] _, pose = rend_util.load_K_Rt_from_P(None, P) pose_all.append(torch.from_numpy(pose).float()) return torch.cat([p.float().unsqueeze(0) for p in pose_all], 0) def get_pose_init(self): # get noisy initializations obtained with the linear method cam_file = '{0}/cameras_linear_init.npz'.format(self.instance_dir) camera_dict = np.load(cam_file) scale_mats = [camera_dict['scale_mat_%d' % idx].astype(np.float32) for idx in range(self.n_images)] world_mats = [camera_dict['world_mat_%d' % idx].astype(np.float32) for idx in range(self.n_images)] init_pose = [] for scale_mat, world_mat in zip(scale_mats, world_mats): P = world_mat @ scale_mat P = P[:3, :4] _, pose = rend_util.load_K_Rt_from_P(None, P) init_pose.append(pose) init_pose = torch.cat([torch.Tensor(pose).float().unsqueeze(0) for pose in init_pose], 0).cuda() init_quat = rend_util.rot_to_quat(init_pose[:, :3, :3]) init_quat = torch.cat([init_quat, init_pose[:, :3, 3]], 1) return init_quat
2,929
582
/******************************************************************************* * Copyright 2005, CHISEL Group, University of Victoria, Victoria, BC, Canada. * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: The Chisel Group, University of Victoria *******************************************************************************/ package org.eclipse.zest.layouts.dataStructures; import java.util.HashMap; import org.eclipse.zest.layouts.LayoutEntity; import org.eclipse.zest.layouts.constraints.BasicEntityConstraint; import org.eclipse.zest.layouts.constraints.LayoutConstraint; /** * @author <NAME> */ @SuppressWarnings({"rawtypes", "unchecked"}) public class InternalNode implements Comparable, LayoutEntity { private LayoutEntity entity = null; private HashMap attributeMap = new HashMap(); BasicEntityConstraint basicEntityConstraint = new BasicEntityConstraint(); public InternalNode(LayoutEntity entity) { this.entity = entity; this.entity.setLayoutInformation(this); this.layoutWidth = entity.getWidthInLayout(); this.layoutHeight = entity.getHeightInLayout(); entity.populateLayoutConstraint(basicEntityConstraint); } public LayoutEntity getLayoutEntity() { return this.entity; } public double getPreferredX() { return basicEntityConstraint.preferredX; } public double getPreferredY() { return basicEntityConstraint.preferredY; } public boolean hasPreferredLocation() { return basicEntityConstraint.hasPreferredLocation; } double dx, dy; public void setDx(double x) { this.dx = x; } public void setDy(double y) { this.dy = y; } public double getDx() { return this.dx; } public double getDy() { return this.dy; } public double getCurrentX() { return entity.getXInLayout(); } public double getCurrentY() { return entity.getYInLayout(); } public void setLocation(double x, double y) { entity.setLocationInLayout(x, y); } public void setSize(double width, double height) { entity.setSizeInLayout(width, height); } double normalizedX = 0.0; double normalizedY = 0.0; double normalizedWidth = 0.0; double normalizedHeight = 0.0; public void setInternalLocation(double x, double y) { //entity.setLocationInLayout(x,y); normalizedX = x; normalizedY = y; } public DisplayIndependentPoint getInternalLocation() { return new DisplayIndependentPoint(getInternalX(), getInternalY()); } public void setInternalSize(double width, double height) { normalizedWidth = width; normalizedHeight = height; } public double getInternalX() { //return entity.getXInLayout(); return normalizedX; } public double getInternalY() { //return entity.getYInLayout(); return normalizedY; } public double getInternalWidth() { return normalizedWidth; } public double getInternalHeight() { return normalizedHeight; } /** * An algorithm may require a place to store information. Use this structure for that purpose. */ public void setAttributeInLayout(Object attribute, Object value) { attributeMap.put(attribute, value); } /** * An algorithm may require a place to store information. Use this structure for that purpose. */ public Object getAttributeInLayout(Object attribute) { return attributeMap.get(attribute); } //TODO: Fix all these preferred stuff!!!!! NOW! public boolean hasPreferredWidth() { return false; //return enity.getAttributeInLayout(LayoutEntity.ATTR_PREFERRED_WIDTH) != null; } public double getPreferredWidth() { return 0.0; // if (hasPreferredWidth()) { // return ((Double)entity.getAttributeInLayout(LayoutEntity.ATTR_PREFERRED_WIDTH)).doubleValue(); // } else { // return 10.0; // } } public boolean hasPreferredHeight() { return false; // return entity.getAttributeInLayout(LayoutEntity.ATTR_PREFERRED_HEIGHT) != null; } public double getPreferredHeight() { return 0.0; // if (hasPreferredHeight()) { // return ((Double)entity.getAttributeInLayout(LayoutEntity.ATTR_PREFERRED_HEIGHT)).doubleValue(); // } else { // return 10.0; // } } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(Object arg0) { return 0; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return (entity != null ? entity.toString() : ""); //$NON-NLS-1$ } double layoutHeight; double layoutWidth; double layoutX; double layoutY; Object layoutInfo; @Override public double getHeightInLayout() { // TODO Auto-generated method stub return layoutHeight; } @Override public Object getLayoutInformation() { // TODO Auto-generated method stub return this.layoutInfo; } @Override public double getWidthInLayout() { // TODO Auto-generated method stub return layoutWidth; } @Override public double getXInLayout() { // TODO Auto-generated method stub return layoutX; } @Override public double getYInLayout() { // TODO Auto-generated method stub return layoutY; } @Override public void populateLayoutConstraint(LayoutConstraint constraint) { // TODO Auto-generated method stub } @Override public void setLayoutInformation(Object internalEntity) { this.layoutInfo = internalEntity; } @Override public void setLocationInLayout(double x, double y) { // TODO Auto-generated method stub this.layoutX = x; this.layoutY = y; } @Override public void setSizeInLayout(double width, double height) { this.layoutWidth = width; this.layoutHeight = height; } @Override public Object getGraphData() { return null; } @Override public void setGraphData(Object o) { // TODO Auto-generated method stub } }
2,473
353
package org.nutz.mock.servlet; import javax.servlet.ServletInputStream; public abstract class MockInputStream extends ServletInputStream { public abstract void init(); public abstract void append(String name, String value); }
69
4,758
#!/usr/bin/env python """ Copyright (c) 2014-2021 Maltrail developers (https://github.com/stamparm/maltrail/) See the file 'LICENSE' for copying permission """ from __future__ import print_function # simple ignore rule mechanism configured by file 'misc/ignore_event.txt' and/or user defined `USER_IGNORELIST` import re from core.settings import config from core.settings import IGNORE_EVENTS def ignore_event(event_tuple): retval = False _, _, src_ip, src_port, dst_ip, dst_port, _, _, _, _, _ = event_tuple if config.IGNORE_EVENTS_REGEX and re.search(config.IGNORE_EVENTS_REGEX, repr(event_tuple), re.I): retval = True for ignore_src_ip, ignore_src_port, ignore_dst_ip, ignore_dst_port in IGNORE_EVENTS: if ignore_src_ip != '*' and ignore_src_ip != src_ip: continue if ignore_src_port != '*' and ignore_src_port != str(src_port): continue if ignore_dst_ip != '*' and ignore_dst_ip != dst_ip: continue if ignore_dst_port != '*' and ignore_dst_port != str(dst_port): continue retval = True break if retval and config.SHOW_DEBUG: print("[i] ignore_event src_ip=%s, src_port=%s, dst_ip=%s, dst_port=%s" % (src_ip, src_port, dst_ip, dst_port)) return retval
548
1,105
<filename>testsuite/blackbody-reg/run.py<gh_stars>1000+ #!/usr/bin/env python # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github.com/AcademySoftwareFoundation/OpenShadingLanguage command += testshade("-g 200 200 blackbody_v_temperature -od uint8 -o Cout v_blackbody.tif -o mCout m_v_blackbody.tif") outputs.append ("v_blackbody.tif") outputs.append ("m_v_blackbody.tif") command += testshade("-g 200 200 blackbody_u_temperature -od uint8 -o Cout u_blackbody.tif -o mCout m_u_blackbody.tif") outputs.append ("u_blackbody.tif") outputs.append ("m_u_blackbody.tif") # expect a few LSB failures failthresh = 0.008 failpercent = 3
252