max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
405
{ "apiVersion": "v1", "kind": "Secret", "metadata": { "name": "onepanel", "namespace": "$(applicationDefaultNamespace)", "labels": { "app.kubernetes.io/component": "onepanel", "app.kubernetes.io/instance": "onepanel-v0.5.0", "app.kubernetes.io/managed-by": "onepanel-cli", "app.kubernetes.io/name": "onepanel", "app.kubernetes.io/part-of": "onepanel", "app.kubernetes.io/version": "v0.5.0" } }, "data": { "artifactRepositoryS3AccessKey": "$(artifactRepositoryS3AccessKey)", "artifactRepositoryS3SecretKey": "$(artifactRepositoryS3SecretKey)" }, "type": "Opaque" }
288
1,099
<gh_stars>1000+ package com.example.chat.mvp.commentdetail; import android.app.Activity; import android.content.Intent; import android.view.View; import com.example.chat.base.ChatApplication; import com.example.chat.R; import com.example.chat.adapter.CommentDetailAdapter; import com.example.chat.base.ChatBaseActivity; import com.example.chat.base.ConstantUtil; import com.example.chat.bean.post.PublicCommentBean; import com.example.chat.bean.post.ReplyDetailContent; import com.example.chat.dagger.commentdetail.CommentDetailModule; import com.example.chat.dagger.commentdetail.DaggerCommentDetailComponent; import com.example.chat.mvp.UserDetail.UserDetailActivity; import com.example.commonlibrary.baseadapter.SuperRecyclerView; import com.example.commonlibrary.baseadapter.empty.EmptyLayout; import com.example.commonlibrary.baseadapter.foot.OnLoadMoreListener; import com.example.commonlibrary.baseadapter.listener.OnSimpleItemChildClickListener; import com.example.commonlibrary.baseadapter.manager.WrappedLinearLayoutManager; import com.example.commonlibrary.customview.ToolBarOption; import com.example.commonlibrary.customview.swipe.CustomSwipeRefreshLayout; import java.util.List; import javax.inject.Inject; import androidx.core.app.ActivityOptionsCompat; import androidx.core.util.Pair; /** * 项目名称: NewFastFrame * 创建人: 陈锦军 * 创建时间: 2018/1/3 15:42 * QQ: 1981367757 */ public class CommentListDetailActivity extends ChatBaseActivity<List<ReplyDetailContent>, CommentDetailPresenter> implements CustomSwipeRefreshLayout.OnRefreshListener, OnLoadMoreListener { @Inject CommentDetailAdapter adapter; private CustomSwipeRefreshLayout refresh; private SuperRecyclerView display; private PublicCommentBean data; @Override public void updateData(List<ReplyDetailContent> listDetailBeans) { addOtherData(listDetailBeans); if (refresh.isRefreshing()) { adapter.refreshData(listDetailBeans); } else { adapter.addData(listDetailBeans); } } private void addOtherData(List<ReplyDetailContent> listDetailBeans) { if (listDetailBeans != null) { int size = listDetailBeans.size(); for (int i = 0; i < size; i++) { ReplyDetailContent item = listDetailBeans.get(i); if (i % 2 == 0) { item.setMsgType(ReplyDetailContent.TYPE_RIGHT); } else { item.setMsgType(ReplyDetailContent.TYPE_LEFT); } } } } @Override protected boolean isNeedHeadLayout() { return true; } @Override protected boolean isNeedEmptyLayout() { return true; } @Override protected int getContentLayout() { return R.layout.activity_comment_list_detail; } @Override protected void initView() { refresh = findViewById(R.id.refresh_activity_comment_list_detail_refresh); display = findViewById(R.id.srcv_activity_comment_list_detail_display); refresh.setOnRefreshListener(this); } @Override protected void initData() { DaggerCommentDetailComponent.builder().chatMainComponent(ChatApplication .getChatMainComponent()) .commentDetailModule(new CommentDetailModule(this)) .build().inject(this); data = (PublicCommentBean) getIntent().getSerializableExtra(ConstantUtil.DATA); display.setLayoutManager(new WrappedLinearLayoutManager(this)); display.setAdapter(adapter); adapter.setOnItemClickListener(new OnSimpleItemChildClickListener() { @Override public void onItemChildClick(int position, View view, int id) { if (id == R.id.riv_comment_detail_left_avatar || id == R.id.riv_comment_detail_right_avatar) { UserDetailActivity.start(CommentListDetailActivity.this , adapter .getData(position).getUid(), ActivityOptionsCompat.makeSceneTransitionAnimation(CommentListDetailActivity.this, Pair.create(view, "avatar"))); } } }); runOnUiThread(() -> presenter.getCommentListDetailData(data, true)); ToolBarOption toolBarOption = new ToolBarOption(); toolBarOption.setTitle("对话列表"); toolBarOption.setNeedNavigation(true); setToolBar(toolBarOption); } public static void start(Activity activity, PublicCommentBean data) { Intent intent = new Intent(activity, CommentListDetailActivity.class); intent.putExtra(ConstantUtil.DATA, data); activity.startActivity(intent); } @Override public void showLoading(String loadMessage) { refresh.setRefreshing(true); } @Override public void showError(String errorMsg, EmptyLayout.OnRetryListener listener) { if (refresh.isRefreshing()) { refresh.setRefreshing(false); super.showError(errorMsg, listener); } } @Override public void hideLoading() { super.hideLoading(); if (refresh.isRefreshing()) { refresh.setRefreshing(false); } } @Override public void onRefresh() { presenter.getCommentListDetailData(data, true); } @Override public void loadMore() { presenter.getCommentListDetailData(data, false); } }
2,254
374
<reponame>EMinsight/SARibbon<filename>src/SARibbonBar/SARibbonStackedWidget.cpp #include "SARibbonStackedWidget.h" #include <QEventLoop> #include <QMouseEvent> #include <QDebug> #include <QApplication> /** * @brief The SARibbonStackedWidgetPrivate class */ class SARibbonStackedWidgetPrivate { public: SARibbonStackedWidget *Parent; QEventLoop *eventLoop; bool isAutoResize; SARibbonStackedWidgetPrivate(SARibbonStackedWidget *p) : Parent(p) , eventLoop(nullptr) , isAutoResize(true) { } void init() { //Parent->setFocusPolicy(Qt::StrongFocus); } }; SARibbonStackedWidget::SARibbonStackedWidget(QWidget *parent) : QStackedWidget(parent) , m_d(new SARibbonStackedWidgetPrivate(this)) { m_d->init(); setNormalMode(); } SARibbonStackedWidget::~SARibbonStackedWidget() { if (m_d->eventLoop) { m_d->eventLoop->exit(); } delete m_d; } void SARibbonStackedWidget::setPopupMode() { setMouseTracking(true); setWindowFlags(Qt::Popup|Qt::FramelessWindowHint); setFrameShape(QFrame::Panel); } bool SARibbonStackedWidget::isPopupMode() const { return (windowFlags()&Qt::Popup); } void SARibbonStackedWidget::setNormalMode() { if (m_d->eventLoop) { m_d->eventLoop->exit(); m_d->eventLoop = nullptr; } setMouseTracking(false); setWindowFlags(Qt::Widget | Qt::FramelessWindowHint); setFrameShape(QFrame::NoFrame); } bool SARibbonStackedWidget::isNormalMode() const { return (!isPopupMode()); } void SARibbonStackedWidget::exec() { show(); if (!isPopupMode()) { m_d->eventLoop = nullptr; return; } QEventLoop event; m_d->eventLoop = &event; event.exec(); m_d->eventLoop = nullptr; } /** * @brief 设置stacked管理的窗口会随着stacked的大小变化而变化大小 * * 默认为true * @param autoresize */ void SARibbonStackedWidget::setAutoResize(bool autoresize) { m_d->isAutoResize = autoresize; } bool SARibbonStackedWidget::isAutoResize() const { return (m_d->isAutoResize); } /** * @brief 类似tabbar的moveTab函数,交换两个窗口的index * @param from * @param to * @note 此操作会触发widgetRemoved(int index)信号 */ void SARibbonStackedWidget::moveWidget(int from, int to) { QWidget *w = widget(from); removeWidget(w); insertWidget(to, w); } void SARibbonStackedWidget::hideEvent(QHideEvent *e) { if (isPopupMode()) { if (m_d->eventLoop) { m_d->eventLoop->exit(); } } setFocus(); emit hidWindow(); QStackedWidget::hideEvent(e); }
1,332
375
<reponame>chrissnell/HeaterMeter /* * Project: LevenbergMarquardtLeastSquaresFitting * * File: lmmin.c * * Contents: Public interface to the Levenberg-Marquardt core implementation. * * Author: <NAME> 2004-8 * * Homepage: www.messen-und-deuten.de/lmfit * * Licence: Public domain. */ #ifndef LMMIN_H #define LMMIN_H #ifdef __cplusplus extern "C" { #endif /** User-supplied subroutines. **/ /* Type of user-supplied subroutine that calculates fvec. */ typedef void (lm_evaluate_ftype) (double *par, int m_dat, double *fvec, void *data, int *info); /* Default implementation therof, provided by lm_eval.c. */ void lm_evaluate_default(double *par, int m_dat, double *fvec, void *data, int *info); /* Type of user-supplied subroutine that informs about fit progress. */ typedef void (lm_print_ftype) (int n_par, double *par, int m_dat, double *fvec, void *data, int iflag, int iter, int nfev); /* Default implementation therof, provided by lm_eval.c. */ void lm_print_default(int n_par, double *par, int m_dat, double *fvec, void *data, int iflag, int iter, int nfev); /** Compact high-level interface. **/ /* Collection of control parameters. */ typedef struct { double ftol; /* relative error desired in the sum of squares. */ double xtol; /* relative error between last two approximations. */ double gtol; /* orthogonality desired between fvec and its derivs. */ double epsilon; /* step used to calculate the jacobian. */ double stepbound; /* initial bound to steps in the outer loop. */ double fnorm; /* norm of the residue vector fvec. */ int maxcall; /* maximum number of iterations. */ int nfev; /* actual number of iterations. */ int info; /* status of minimization. */ } lm_control_type; /* Initialize control parameters with default values. */ void lm_initialize_control(lm_control_type * control); /* Refined calculation of Eucledian norm, typically used in printout routine. */ double lm_enorm(int, double *); /* The actual minimization. */ void lm_minimize(int m_dat, int n_par, double *par, lm_evaluate_ftype * evaluate, lm_print_ftype * printout, void *data, lm_control_type * control); /** Legacy low-level interface. **/ /* Alternative to lm_minimize, allowing full control, and read-out of auxiliary arrays. For usage, see implementation of lm_minimize. */ void lm_lmdif(int m, int n, double *x, double *fvec, double ftol, double xtol, double gtol, int maxfev, double epsfcn, double *diag, int mode, double factor, int *info, int *nfev, double *fjac, int *ipvt, double *qtf, double *wa1, double *wa2, double *wa3, double *wa4, lm_evaluate_ftype * evaluate, lm_print_ftype * printout, void *data); #ifndef _LMDIF extern const char *lm_infmsg[]; extern const char *lm_shortmsg[]; #endif #ifdef __cplusplus } #endif #endif /* LMMIN_H */
1,186
1,056
<filename>platform/o.n.bootstrap/src/org/netbeans/ProxyURLStreamHandlerFactory.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans; import java.lang.reflect.Field; import java.net.URL; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; /** * A stream handler factory that delegates to others in lookup. */ public class ProxyURLStreamHandlerFactory implements URLStreamHandlerFactory, LookupListener { private static final Logger LOG = Logger.getLogger(ProxyURLStreamHandlerFactory.class.getName()); private static boolean proxyFactoryInitialized; private static URLStreamHandler originalJarHandler; public static synchronized void register() { LOG.log(Level.FINE, "register: {0}", proxyFactoryInitialized); // NOI18N LOG.log(Level.FINER, null, new Exception("Initialized by")); // NOI18N if (!proxyFactoryInitialized) { if (!ProxyURLStreamHandlerFactory.class.getClassLoader().getClass().getName().equals("com.sun.jnlp.JNLPClassLoader")) { // #196970 try { List<Field> candidates = new ArrayList<Field>(); for (Field f : URL.class.getDeclaredFields()) { if (f.getType() == URLStreamHandler.class) { candidates.add(f); } } if (candidates.size() != 1) { throw new Exception("No, or multiple, URLStreamHandler-valued fields in URL: " + candidates); } Field f = candidates.get(0); f.setAccessible(true); originalJarHandler = (URLStreamHandler) f.get(new URL("jar:file:/sample.jar!/")); LOG.log(Level.FINE, "found originalJarHandler: {0}", originalJarHandler); } catch (Throwable t) { if (originalJarHandler == null) { LOG.log(Level.SEVERE, "No way to find original stream handler for jar protocol", t); // NOI18N } } } try { URL.setURLStreamHandlerFactory(new ProxyURLStreamHandlerFactory(null)); } catch (Error e) { LOG.log(Level.CONFIG, "Problems registering URLStreamHandlerFactory, trying reflection", e); // NOI18N try { URLStreamHandlerFactory prev = null; for (Field f : URL.class.getDeclaredFields()) { LOG.log(Level.FINEST, "Found field {0}", f); if (f.getType() == URLStreamHandlerFactory.class) { LOG.log(Level.FINEST, "Clearing field {0}"); f.setAccessible(true); prev = (URLStreamHandlerFactory) f.get(null); LOG.log(Level.CONFIG, "Previous value was {0}", prev); f.set(null, null); LOG.config("Field is supposed to be empty"); break; } } if (prev != null && prev.getClass().getName().equals(ProxyURLStreamHandlerFactory.class.getName())) { prev = null; } URL.setURLStreamHandlerFactory(new ProxyURLStreamHandlerFactory(prev)); } catch (Throwable t) { LOG.log(Level.SEVERE, "No way to register URLStreamHandlerFactory; NetBeans is unlikely to work", t); // NOI18N } } proxyFactoryInitialized = true; } } static URLStreamHandler originalJarHandler() { return originalJarHandler; } private final URLStreamHandlerFactory delegate; private Lookup.Result<URLStreamHandlerFactory> r; private URLStreamHandlerFactory[] handlers; private ProxyURLStreamHandlerFactory(URLStreamHandlerFactory delegate) { this.delegate = delegate; LOG.log(Level.FINE, "new ProxyURLStreamHandlerFactory. delegate={0} originalJarHandler={1}", new Object[]{delegate, originalJarHandler}); } @Override public URLStreamHandler createURLStreamHandler(String protocol) { if (protocol.equals("jar")) { return originalJarHandler != null ? new JarClassLoader.JarURLStreamHandler(originalJarHandler) : null; } else if (protocol.equals("file") || protocol.equals("http") || protocol.equals("https") || protocol.equals("resource")) { // NOI18N // Well-known handlers in JRE. Do not try to initialize lookup, etc. // (delegate already ignores these, but we cannot afford to look for URLSHFs in default lookup either.) return null; } else { if (delegate != null) { URLStreamHandler h = delegate.createURLStreamHandler(protocol); if (h != null) { return h; } } URLStreamHandlerFactory[] _handlers; synchronized (this) { if (handlers == null) { r = Lookup.getDefault().lookupResult(URLStreamHandlerFactory.class); r.addLookupListener(this); resultChanged(null); } _handlers = handlers; } for (URLStreamHandlerFactory f : _handlers) { URLStreamHandler h = f.createURLStreamHandler(protocol); if (h != null) { return h; } } return null; } } @Override public void resultChanged(LookupEvent ev) { Collection<? extends URLStreamHandlerFactory> c = r.allInstances(); synchronized (this) { handlers = c.toArray(new URLStreamHandlerFactory[c.size()]); } } }
2,963
836
<reponame>mooreandrew/zsign #pragma once #include "common/common.h" #include "common/json.h" #include "openssl.h" class ZAppBundle { public: ZAppBundle(); public: bool SignFolder(ZSignAsset *pSignAsset, const string &strFolder, const string &strBundleID, const string &strBundleVersion, const string &strDisplayName, const string &strDyLibFile, bool bForce, bool bWeakInject, bool bEnableCache); private: bool SignNode(JValue &jvNode); void GetNodeChangedFiles(JValue &jvNode); void GetChangedFiles(JValue &jvNode, vector<string> &arrChangedFiles); void GetPlugIns(const string &strFolder, vector<string> &arrPlugIns); private: bool FindAppFolder(const string &strFolder, string &strAppFolder); bool GetObjectsToSign(const string &strFolder, JValue &jvInfo); bool GetSignFolderInfo(const string &strFolder, JValue &jvNode, bool bGetName = false); private: bool GenerateCodeResources(const string &strFolder, JValue &jvCodeRes); void GetFolderFiles(const string &strFolder, const string &strBaseFolder, set<string> &setFiles); private: bool m_bForceSign; bool m_bWeakInject; string m_strDyLibPath; ZSignAsset *m_pSignAsset; public: string m_strAppFolder; };
403
460
<gh_stars>100-1000 /* # This file is part of the Astrometry.net suite. # Licensed under a 3-clause BSD style license - see LICENSE */ #include <stdlib.h> #include <math.h> #include <assert.h> #include "os-features.h" #include "index.h" #include "starutil.h" #include "log.h" #include "errors.h" #include "ioutils.h" #include "boilerplate.h" #include "tic.h" #include "fitstable.h" static const char* OPTIONS = "hvr:d:R:o:"; void printHelp(char* progname) { BOILERPLATE_HELP_HEADER(stdout); printf("\nUsage: %s [options] <index-files>\n" " -r <ra> (deg)\n" " -d <dec> (deg)\n" " -R <radius> (deg)\n" " [-o <filename>]: save results in FITS table; tag-along columns must be the same in all indices\n" " [-v]: +verbose\n" "\n", progname); } int main(int argc, char **argv) { int argchar; double ra=HUGE_VAL, dec=HUGE_VAL, radius=HUGE_VAL; int loglvl = LOG_MSG; char** myargs; int nmyargs; int i; char* outfn = NULL; fitstable_t* table = NULL; while ((argchar = getopt (argc, argv, OPTIONS)) != -1) switch (argchar) { case 'o': outfn = optarg; break; case 'r': ra = atof(optarg); break; case 'd': dec = atof(optarg); break; case 'R': radius = atof(optarg); break; case 'v': loglvl++; break; case '?': fprintf(stderr, "Unknown option `-%c'.\n", optopt); case 'h': default: printHelp(argv[0]); return -1; } log_init(loglvl); nmyargs = argc - optind; myargs = argv + optind; if (nmyargs < 1) { printHelp(argv[0]); exit(-1); } if (ra == HUGE_VAL || dec == HUGE_VAL || radius == HUGE_VAL) { printHelp(argv[0]); exit(-1); } if (outfn) { table = fitstable_open_for_writing(outfn); if (!table) { ERROR("Failed to open output table"); exit(-1); } if (fitstable_write_primary_header(table)) { ERROR("Failed to write primary header of output table"); exit(-1); } } for (i=0; i<nmyargs; i++) { char* indexfn = myargs[i]; index_t index; sl* cols; int* inds; double* radecs; int N; int j; fitstable_t* tagtable = NULL; logmsg("Reading index \"%s\"...\n", indexfn); if (!index_load(indexfn, 0, &index)) { ERROR("Failed to read index \"%s\"", indexfn); continue; } logmsg("Index %s: id %i, healpix %i (nside %i), %i stars, %i quads, dimquads=%i, scales %g to %g arcmin.\n", index.indexname, index.indexid, index.healpix, index.hpnside, index.nstars, index.nquads, index.dimquads, arcsec2arcmin(index.index_scale_lower), arcsec2arcmin(index.index_scale_upper)); cols = startree_get_tagalong_column_names(index.starkd, NULL); { char* colstr = sl_join(cols, ", "); logmsg("Tag-along columns: %s\n", colstr); free(colstr); } logmsg("Searching for stars around RA,Dec (%g, %g), radius %g deg.\n", ra, dec, radius); startree_search_for_radec(index.starkd, ra, dec, radius, NULL, &radecs, &inds, &N); logmsg("Found %i stars\n", N); if (table) { int tagsize; int rowsize; char* rowbuf = NULL; if (i > 0) { fitstable_next_extension(table); fitstable_clear_table(table); } tagtable = startree_get_tagalong(index.starkd); if (tagtable) { fitstable_add_fits_columns_as_struct(tagtable); logverb("Input tag-along table:\n"); if (log_get_level() >= LOG_VERB) fitstable_print_columns(tagtable); fitstable_copy_columns(tagtable, table); } tagsize = fitstable_get_struct_size(table); debug("tagsize=%i\n", tagsize); // Add RA,Dec at the end of the row... fitstable_add_write_column_struct(table, fitscolumn_double_type(), 1, tagsize, fitscolumn_double_type(), "RA", "degrees"); fitstable_add_write_column_struct(table, fitscolumn_double_type(), 1, tagsize + sizeof(double), fitscolumn_double_type(), "DEC", "degrees"); rowsize = fitstable_get_struct_size(table); assert(rowsize == tagsize + 2*sizeof(double)); debug("rowsize=%i\n", rowsize); rowbuf = malloc(rowsize); logverb("Output table:\n"); if (log_get_level() >= LOG_VERB) fitstable_print_columns(table); if (fitstable_write_header(table)) { ERROR("Failed to write header of output table"); exit(-1); } for (j=0; j<N; j++) { if (tagtable) { if (fitstable_read_struct(tagtable, inds[j], rowbuf)) { ERROR("Failed to read row %i of tag-along table", inds[j]); exit(-1); } } // Add RA,Dec to end of struct... memcpy(rowbuf + tagsize, radecs+2*j+0, sizeof(double)); memcpy(rowbuf + tagsize + sizeof(double), radecs+2*j+1, sizeof(double)); if (fitstable_write_struct(table, rowbuf)) { ERROR("Failed to write row %i of output", j); exit(-1); } } free(rowbuf); if (fitstable_fix_header(table)) { ERROR("Failed to fix header of output table"); exit(-1); } } sl_free2(cols); free(radecs); free(inds); index_close(&index); } if (table) { if (fitstable_close(table)) { ERROR("Failed to close output table"); exit(-1); } } return 0; }
3,351
838
import sx127x import config_lora # import LoRaDumpRegisters import LoRaSender import LoRaReceiver # import LoRaSetSpread # import LoRaSetSyncWord # import LoRaReceiverCallback # import LoRaReceiverCallback_dual_channels # import LoRaDuplex # import LoRaDuplexCallback # import LoRaPingPong PIN_ID_SS = 26 PIN_ID_FOR_LORA_DIO0 = 21 controller = config_lora.Controller() lora = controller.add_transceiver(sx127x.SX127x(name = 'LoRa'), pin_id_ss = PIN_ID_SS, pin_id_RxDone = PIN_ID_FOR_LORA_DIO0) LoRaSender.send(lora) def main(): # Controller(spi = spi, # pin_id_led = ON_BOARD_LED_PIN_NO, # on_board_led_high_is_on = ON_BOARD_LED_HIGH_IS_ON, # pin_id_reset = PIN_ID_FOR_LORA_RESET, # blink_on_start = (2, 0.5, 0.5)) controller = config_lora.Controller() # SX127x(name = 'SX127x', # parameters = {'frequency': 433E6, 'tx_power_level': 2, 'signal_bandwidth': 125E3, # 'spreading_factor': 8, 'coding_rate': 5, 'preamble_length': 8, # 'implicitHeader': False, 'sync_word': 0x12, 'enable_CRC': False}, # onReceive = None) # controller.add_transceiver(transceiver, # pin_id_ss = PIN_ID_FOR_LORA_SS, # pin_id_RxDone = PIN_ID_FOR_LORA_DIO0, # pin_id_RxTimeout = PIN_ID_FOR_LORA_DIO1, # pin_id_ValidHeader = PIN_ID_FOR_LORA_DIO2, # pin_id_CadDone = PIN_ID_FOR_LORA_DIO3, # pin_id_CadDetected = PIN_ID_FOR_LORA_DIO4, # pin_id_PayloadCrcError = PIN_ID_FOR_LORA_DIO5) lora = controller.add_transceiver(sx127x.SX127x(name = 'LoRa'), pin_id_ss = PIN_ID_SS, pin_id_RxDone = PIN_ID_FOR_LORA_DIO0) print('lora', lora) # LoRaDumpRegisters.dumpRegisters(lora) LoRaSender.send(lora) # LoRaReceiver.receive(lora) # LoRaSetSpread.setSpread(lora) # LoRaSetSyncWord.setSyncWord(lora) # LoRaReceiverCallback.receiveCallback(lora) # LoRaReceiverCallback_dual_channels.receiveCallback(lora1, lora2) # LoRaDuplex.duplex(lora) # LoRaDuplexCallback.duplexCallback(lora) # LoRaPingPong.ping_pong(lora)
1,210
14,668
<gh_stars>1000+ # Copyright (C) 2010 Google 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 Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import mimetypes import six.moves.urllib from blinkpy.common.net.network_transaction import NetworkTransaction def get_mime_type(filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream' # FIXME: Rather than taking tuples, this function should take more structured data. def _encode_multipart_form_data(fields, files): """Encode form fields for multipart/form-data. Args: fields: A sequence of (name, value) elements for regular form fields. files: A sequence of (name, filename, value) elements for data to be uploaded as files. Returns: (content_type, body) ready for httplib.HTTP instance. Source: https://github.com/rietveld-codereview/rietveld/blob/1be266f92fbd6e01732e1bde10589bc408d65633/upload.py#L964 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' lines = [] for key, value in fields: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"' % key) lines.append('') if isinstance(value, unicode): value = value.encode('utf-8') lines.append(value) for key, filename, value in files: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) lines.append('Content-Type: %s' % get_mime_type(filename)) lines.append('') if isinstance(value, unicode): value = value.encode('utf-8') lines.append(value) lines.append('--' + BOUNDARY + '--') lines.append('') body = CRLF.join(lines) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body class FileUploader(object): def __init__(self, url, timeout_seconds): self._url = url self._timeout_seconds = timeout_seconds def upload_single_text_file(self, filesystem, content_type, filename): return self._upload_data(content_type, filesystem.read_text_file(filename)) def upload_as_multipart_form_data(self, filesystem, files, attrs): file_objs = [] for filename, path in files: file_objs.append(('file', filename, filesystem.read_binary_file(path))) # FIXME: We should use the same variable names for the formal and actual parameters. content_type, data = _encode_multipart_form_data(attrs, file_objs) return self._upload_data(content_type, data) def _upload_data(self, content_type, data): def callback(): # FIXME: Setting a timeout, either globally using socket.setdefaulttimeout() # or in urlopen(), doesn't appear to work on Mac 10.5 with Python 2.7. # For now we will ignore the timeout value and hope for the best. request = urllib.Request(self._url, data, {'Content-Type': content_type}) return urllib.urlopen(request) return NetworkTransaction( timeout_seconds=self._timeout_seconds).run(callback)
1,767
854
<reponame>timxor/leetcode-journal __________________________________________________________________________________________________ class Solution { public: void duplicateZeros(vector<int>& A) { int n = A.size(), j = n + count(A.begin(), A.end(), 0); for (int i = n - 1; i >= 0; --i) { if (--j < n) A[j] = A[i]; if (A[i] == 0 && --j < n) A[j] = 0; } } }; __________________________________________________________________________________________________ __________________________________________________________________________________________________
217
1,561
<filename>endpoints/bookstore-grpc/server/src/main/java/com/google/endpoints/examples/bookstore/BookstoreData.java // Copyright 2016 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. // //////////////////////////////////////////////////////////////////////////////// package com.google.endpoints.examples.bookstore; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import io.grpc.Status; import io.grpc.StatusException; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; /** * The in-memory Bookstore database implementation. */ final class BookstoreData { private static final class ShelfInfo { private final Shelf shelf; private final Map<Long, Book> books; private long lastBookId; private ShelfInfo(Shelf shelf) { this.shelf = shelf; this.books = new HashMap<>(); this.lastBookId = 0; } } private final Object lock; private final Map<Long, ShelfInfo> shelves; private long lastShelfId; private final Function<ShelfInfo, Shelf> shelfInfoToShelf = new Function<ShelfInfo, Shelf>() { @Nullable @Override public Shelf apply(@Nullable ShelfInfo shelfInfo) { if (shelfInfo == null) { return null; } return shelfInfo.shelf; } }; BookstoreData() { lock = new Object(); shelves = new HashMap<>(); lastShelfId = 0; } public ShelfEntity createShelf(Shelf shelf) { synchronized (lock) { lastShelfId++; shelf = shelf.toBuilder() .setId(lastShelfId) .build(); shelves.put(lastShelfId, new ShelfInfo(shelf)); return ShelfEntity.create(lastShelfId, shelf); } } public Iterable<Shelf> listShelves() { synchronized (lock) { return Iterables.transform(ImmutableList.copyOf(shelves.values()), shelfInfoToShelf); } } public Shelf getShelf(long shelfId) throws StatusException { synchronized (lock) { @Nullable Shelf shelf = shelfInfoToShelf.apply(shelves.get(shelfId)); if (shelf == null) { throw Status.NOT_FOUND .withDescription("Unknown shelf ID") .asException(); } return shelf; } } public void deleteShelf(long shelfId) throws StatusException { synchronized (lock) { if (shelves.remove(shelfId) == null) { throw Status.NOT_FOUND .withDescription("Unknown shelf ID") .asException(); } } } public Iterable<Book> listBooks(long shelfId) throws StatusException { synchronized (lock) { @Nullable ShelfInfo shelfInfo = shelves.get(shelfId); if (shelfInfo == null) { throw Status.NOT_FOUND .withDescription("Unknown shelf ID") .asException(); } return ImmutableList.copyOf(shelfInfo.books.values()); } } public Book createBook(long shelfId, Book book) throws StatusException { synchronized (lock) { @Nullable ShelfInfo shelfInfo = shelves.get(shelfId); if (shelfInfo == null) { throw Status.NOT_FOUND .withDescription("Unknown shelf ID") .asException(); } shelfInfo.lastBookId++; book = book.toBuilder() .setId(shelfInfo.lastBookId) .build(); shelfInfo.books.put(shelfInfo.lastBookId, book); } return book; } public Book getBook(long shelfId, long bookId) throws StatusException { synchronized (lock) { @Nullable ShelfInfo shelfInfo = shelves.get(shelfId); if (shelfInfo == null) { throw Status.NOT_FOUND .withDescription("Unknown shelf ID") .asException(); } @Nullable Book book = shelfInfo.books.get(bookId); if (book == null) { throw Status.NOT_FOUND .withDescription("Unknown book ID") .asException(); } return book; } } public void deleteBook(long shelfId, long bookId) throws StatusException { synchronized (lock) { @Nullable ShelfInfo shelfInfo = shelves.get(shelfId); if (shelfInfo == null) { throw Status.NOT_FOUND .withDescription("Unknown shelf ID") .asException(); } if (shelfInfo.books.remove(bookId) == null) { throw Status.NOT_FOUND .withDescription("Unknown book ID") .asException(); } } } }
1,958
1,568
#!/usr/bin/env python3 """ module to operations with prime numbers """ def check_prime(number): """ it's not the best solution """ special_non_primes = [0,1,2] if number in special_non_primes[:2]: return 2 elif number == special_non_primes[-1]: return 3 return all([number % i for i in range(2, number)]) def next_prime(value, factor=1, **kwargs): value = factor * value first_value_val = value while not check_prime(value): value += 1 if not ("desc" in kwargs.keys() and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1, **kwargs) return value
334
4,603
from rockstar import RockStar eiffel_code = """class HELLO_WORLD create make feature make do print ("Hello, world!%N") end end """ rock_it_bro = RockStar(days=400, file_name='helloworld.e', code=eiffel_code) rock_it_bro.make_me_a_rockstar()
135
702
/* * Copyright ConsenSys AG. * * 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. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.consensus.ibft; import org.hyperledger.besu.consensus.common.BlockInterface; import org.hyperledger.besu.consensus.common.EpochManager; import org.hyperledger.besu.consensus.common.PoaContext; import org.hyperledger.besu.consensus.common.validator.ValidatorProvider; import org.hyperledger.besu.ethereum.ConsensusContext; /** Holds the BFT specific mutable state. */ public class IbftLegacyContext implements PoaContext { private final ValidatorProvider validatorProvider; private final EpochManager epochManager; private final BlockInterface blockInterface; public IbftLegacyContext( final ValidatorProvider validatorProvider, final EpochManager epochManager, final BlockInterface blockInterface) { this.validatorProvider = validatorProvider; this.epochManager = epochManager; this.blockInterface = blockInterface; } public ValidatorProvider getValidatorProvider() { return validatorProvider; } public EpochManager getEpochManager() { return epochManager; } @Override public BlockInterface getBlockInterface() { return blockInterface; } @Override public <C extends ConsensusContext> C as(final Class<C> klass) { return klass.cast(this); } }
543
1,430
<reponame>nko3/AtomOS #ifndef _SYSCALL_H #define _SYSCALL_H #include <_ansi.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <stdint.h> #include <string.h> /******************************************************************** SYSCALL FUNCTIONS ********************************************************************/ #define SYS_exit 1 #define SYS_fork 2 #define SYS_read 3 #define SYS_write 4 #define SYS_open 5 #define SYS_close 6 #define SYS_wait4 7 #define SYS_creat 8 #define SYS_link 9 #define SYS_unlink 10 #define SYS_execv 11 #define SYS_chdir 12 #define SYS_mknod 14 #define SYS_chmod 15 #define SYS_chown 16 #define SYS_lseek 19 #define SYS_getpid 20 #define SYS_isatty 21 #define SYS_fstat 22 #define SYS_time 23 #define SYS_ARG 24 #define SYS_kill 37 #define SYS_stat 38 #define SYS_pipe 42 #define SYS_brk 45 #define SYS_execve 59 #define SYS_gettimeofday 78 #define SYS_truncate 129 #define SYS_ftruncate 130 #define SYS_argc 172 #define SYS_argnlen 173 #define SYS_argn 174 #define SYS_utime 201 #define SYS_wait 202 /******************************************************************** HELPER FUNCTIONS ********************************************************************/ #define DEFINE_SYSCALL_0(fn, num) \ int fn() \ { \ int a; \ asm volatile("int $0x7f" : "=a" (a) : "0" (num)); \ return a; \ } #define DEFINE_SYSCALL_1(fn, num, P1) \ int fn(P1 p1) \ { \ int a; \ asm volatile("int $0x7f" : "=a" (a) : "0" (num), "b" ((int)p1)); \ return a; \ } #define DEFINE_SYSCALL_2(fn, num, P1, P2) \ int fn(P1 p1, P2 p2) \ { \ int a; \ asm volatile("int $0x7f" : "=a" (a) : "0" (num), "b" ((int)p1), "c" ((int)p2)); \ return a; \ } #define DEFINE_SYSCALL_3(fn, num, P1, P2, P3) \ int fn(P1 p1, P2 p2, P3 p3) \ { \ int a; \ asm volatile("int $0x7f" : "=a" (a) : "0" (num), "b" ((int)p1), "c" ((int)p2), "d" ((int)p3)); \ return a; \ } /******************************************************************** DECLARATION ********************************************************************/ int _exit(int code); int close(int file); int execve(char *name, char **argv, char **env); int fork(); int fstat(int file, struct stat *st); int getpid(); int isatty(int file); int kill(int pid, int sig); int link(char *old, char *new); int lseek(int file, int ptr, int dir); int open(const char *name, int flags, int mode); int read(int file, char *ptr, int len); int brk(int incr); int stat(const char *file, struct stat *st); int unlink(char *name); int wait(int *status); int write(int file, char *ptr, int len); //int gettimeofday(struct timeval *p, struct timezone *z); #endif
1,542
702
/* * Copyright ConsenSys AG. * * 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. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.ethereum.api.jsonrpc.internal; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcRequestException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; @JsonIgnoreProperties(ignoreUnknown = true) public class JsonRpcRequest { private final JsonRpcParameter parameterAccessor = new JsonRpcParameter(); private JsonRpcRequestId id; private final String method; private final Object[] params; private final String version; private boolean isNotification = true; @JsonCreator public JsonRpcRequest( @JsonProperty("jsonrpc") final String version, @JsonProperty("method") final String method, @JsonProperty("params") final Object[] params) { this.version = version; this.method = method; this.params = params; if (method == null) { throw new InvalidJsonRpcRequestException("Field 'method' is required"); } } @JsonGetter("id") public Object getId() { return id == null ? null : id.getValue(); } @JsonGetter("method") public String getMethod() { return method; } @JsonGetter("jsonrpc") public String getVersion() { return version; } @JsonInclude(Include.NON_NULL) @JsonGetter("params") public Object[] getParams() { return params; } @JsonIgnore public boolean isNotification() { return isNotification; } @JsonIgnore public int getParamLength() { return hasParams() ? params.length : 0; } @JsonIgnore public boolean hasParams() { // Null Object: "params":null if (params == null) { return false; } // Null Array: "params":[null] if (params.length == 0 || params[0] == null) { return false; } return true; } @JsonSetter("id") protected void setId(final JsonRpcRequestId id) { // If an id is explicitly set, it is not a notification isNotification = false; this.id = id; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final JsonRpcRequest that = (JsonRpcRequest) o; return isNotification == that.isNotification && Objects.equals(id, that.id) && Objects.equals(method, that.method) && Arrays.equals(params, that.params) && Objects.equals(version, that.version); } @Override public int hashCode() { return Objects.hash(id, method, Arrays.hashCode(params), version, isNotification); } public <T> T getRequiredParameter(final int index, final Class<T> paramClass) { return parameterAccessor.required(params, index, paramClass); } public <T> Optional<T> getOptionalParameter(final int index, final Class<T> paramClass) { return parameterAccessor.optional(params, index, paramClass); } }
1,376
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-hvp5-xq7g-8w42", "modified": "2022-05-13T01:36:18Z", "published": "2022-05-13T01:36:18Z", "aliases": [ "CVE-2017-7530" ], "details": "In CloudForms Management Engine (cfme) before 5.7.3 and 5.8.x before 5.8.1, it was found that privilege check is missing when invoking arbitrary methods via filtering on VMs that MiqExpression will execute that is triggerable by API users. An attacker could use this to execute actions they should not be allowed to (e.g. destroying VMs).", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2017-7530" }, { "type": "WEB", "url": "https://access.redhat.com/errata/RHSA-2017:1758" }, { "type": "WEB", "url": "https://bugzilla.redhat.com/show_bug.cgi?id=CVE-2017-7530" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/100151" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
570
852
<reponame>ckamtsikis/cmssw #ifndef AlphaTVarAnalyzer_h #define AlphaTVarAnalyzer_h #include "DQM/DataScouting/interface/ScoutingAnalyzerBase.h" class AlphaTVarAnalyzer : public ScoutingAnalyzerBase { public: explicit AlphaTVarAnalyzer(const edm::ParameterSet &); ~AlphaTVarAnalyzer() override; void bookHistograms(DQMStore::IBooker &, edm::Run const &, edm::EventSetup const &) override; void analyze(const edm::Event &, const edm::EventSetup &) override; private: edm::InputTag m_jetCollectionTag; edm::InputTag m_alphaTVarCollectionTag; // inclusive histograms by jet number MonitorElement *m_HTAlphaT; MonitorElement *m_HTAlphaTg0p55; MonitorElement *m_HTAlphaTg0p60; // define Token(-s) edm::EDGetTokenT<std::vector<double>> m_alphaTVarCollectionTagToken_; }; #endif
283
854
<reponame>timxor/leetcode-journal __________________________________________________________________________________________________ sample 4 ms submission class Solution { public: vector<int> singleNumber(vector<int>& nums) { std::ios::sync_with_stdio(false);std::cin.tie(NULL);std::cout.tie(NULL); if (nums.empty()) return {}; int x = 0; for (auto v: nums) x ^= v; int lsb = x&-x; int y = 0; for (auto v: nums) if (lsb & v) y^=v; return {y, x^y}; } }; __________________________________________________________________________________________________ sample 9652 kb submission class Solution { public: vector<int> singleNumber(vector<int>& nums) { int sum = 0; int n = nums.size(); int i; for (i = 0; i < n; ++i) { sum ^= nums[i]; } sum = sum & -sum; int n1 = 0; int n2 = 0; for (i = 0; i < n; ++i) { if (nums[i] & sum) { n1 ^= nums[i]; } else { n2 ^= nums[i]; } } vector<int> res; res.push_back(n1); res.push_back(n2); return res; } }; __________________________________________________________________________________________________
593
381
""" An interpreter for a strange word-based language: the program is a list of space-separated words. Most words push themselves on a stack; some words have another action. The result is the space-separated words from the stack. Hello World => 'Hello World' 6 7 ADD => '13' 'ADD' is a special word 7 * 5 = 7 5 MUL => '7 * 5 = 35' '*' and '=' are not special words Arithmetic on non-integers gives a 'symbolic' result: X 2 MUL => 'X*2' Input arguments can be passed on the command-line, and used as #1, #2, etc.: #1 1 ADD => one more than the argument on the command-line, or if it was not an integer, concatenates '+1' You can store back into an (existing) argument index with ->#N: #1 5 ADD ->#1 Braces { } delimitate a loop. Don't forget spaces around each one. The '}' pops an integer value off the stack and loops if it is not zero: { #1 #1 1 SUB ->#1 #1 } => when called with 5, gives '5 4 3 2 1' """ from rpython.rlib.jit import hint, promote, JitDriver # # See pypy/doc/jit.txt for a higher-level overview of the JIT techniques # detailed in the following comments. # class Box: # Although all words are in theory strings, we use two subclasses # to represent the strings differently from the words known to be integers. # This is an optimization that is essential for the JIT and merely # useful for the basic interpreter. pass class IntBox(Box): _immutable_ = True def __init__(self, intval): self.intval = intval def as_int(self): return self.intval def as_str(self): return str(self.intval) class StrBox(Box): _immutable_ = True def __init__(self, strval): self.strval = strval def as_int(self): return myint(self.strval) def as_str(self): return self.strval def func_add_int(ix, iy): return ix + iy def func_sub_int(ix, iy): return ix - iy def func_mul_int(ix, iy): return ix * iy def func_add_str(sx, sy): return sx + '+' + sy def func_sub_str(sx, sy): return sx + '-' + sy def func_mul_str(sx, sy): return sx + '*' + sy def op2(stack, func_int, func_str): # Operate on the top two stack items. The promotion hints force the # class of each arguments (IntBox or StrBox) to turn into a compile-time # constant if they weren't already. The effect we seek is to make the # calls to as_int() direct calls at compile-time, instead of indirect # ones. The JIT compiler cannot look into indirect calls, but it # can analyze and inline the code in directly-called functions. stack, y = stack.pop() promote(y.__class__) stack, x = stack.pop() promote(x.__class__) try: z = IntBox(func_int(x.as_int(), y.as_int())) except ValueError: z = StrBox(func_str(x.as_str(), y.as_str())) stack = Stack(z, stack) return stack class Stack(object): def __init__(self, value, next=None): self.next = next self.value = value def pop(self): return self.next, self.value def empty_stack(): return None class TinyJitDriver(JitDriver): reds = ['args', 'loops', 'stack'] greens = ['bytecode', 'pos'] def compute_invariants(self, reds, bytecode, pos): # Some of the information that we maintain only really depends on # bytecode and pos: the whole 'loops' list has this property. # By being a bit careful we could also put len(args) in the # invariants, but although it doesn't make much sense it is a # priori possible for the same bytecode to be run with # different len(args). return reds.loops def on_enter_jit(self, invariants, reds, bytecode, pos): # Now some strange code that makes a copy of the 'args' list in # a complicated way... this is a workaround forcing the whole 'args' # list to be virtual. It is a way to tell the JIT compiler that it # doesn't have to worry about the 'args' list being unpredictably # modified. oldloops = invariants oldargs = reds.args argcount = promote(len(oldargs)) args = [] n = 0 while n < argcount: hint(n, concrete=True) args.append(oldargs[n]) n += 1 reds.args = args # turn the green 'loops' from 'invariants' into a virtual list oldloops = hint(oldloops, deepfreeze=True) argcount = len(oldloops) loops = [] n = 0 while n < argcount: hint(n, concrete=True) loops.append(oldloops[n]) n += 1 reds.loops = loops tinyjitdriver = TinyJitDriver() def interpret(bytecode, args): """The interpreter's entry point and portal function. """ loops = [] stack = empty_stack() pos = 0 while True: tinyjitdriver.jit_merge_point(args=args, loops=loops, stack=stack, bytecode=bytecode, pos=pos) bytecode = hint(bytecode, deepfreeze=True) if pos >= len(bytecode): break opcode = bytecode[pos] hint(opcode, concrete=True) # same as in tiny1.py pos += 1 if opcode == 'ADD': stack = op2(stack, func_add_int, func_add_str) elif opcode == 'SUB': stack = op2(stack, func_sub_int, func_sub_str) elif opcode == 'MUL': stack = op2(stack, func_mul_int, func_mul_str) elif opcode[0] == '#': n = myint(opcode, start=1) stack = Stack(args[n-1], stack) elif opcode.startswith('->#'): n = myint(opcode, start=3) if n > len(args): raise IndexError stack, args[n-1] = stack.pop() elif opcode == '{': loops.append(pos) elif opcode == '}': stack, flag = stack.pop() if flag.as_int() == 0: loops.pop() else: pos = loops[-1] # A common problem when interpreting loops or jumps: the 'pos' # above is read out of a list, so the hint-annotator thinks # it must be red (not a compile-time constant). But the # hint(opcode, concrete=True) in the next iteration of the # loop requires all variables the 'opcode' depends on to be # green, including this 'pos'. We promote 'pos' to a green # here, as early as possible. Note that in practice the 'pos' # read out of the 'loops' list will be a compile-time constant # because it was pushed as a compile-time constant by the '{' # case above into 'loops', which is a virtual list, so the # promotion below is just a way to make the colors match. pos = promote(pos) tinyjitdriver.can_enter_jit(args=args, loops=loops, stack=stack, bytecode=bytecode, pos=pos) else: stack = Stack(StrBox(opcode), stack) return stack def repr(stack): # this bit moved out of the portal function because JIT'ing it is not # very useful, and the JIT generator is confused by the 'for' right now... lst = [] while stack: stack, x = stack.pop() lst.append(x.as_str()) lst.reverse() return ' '.join(lst) # ------------------------------ # Pure workaround code! It will eventually be unnecessary. # For now, myint(s, n) is a JIT-friendly way to spell int(s[n:]). # We don't support negative numbers, though. def myint_internal(s, start=0): if start >= len(s): return -1 res = 0 while start < len(s): c = s[start] n = ord(c) - ord('0') if not (0 <= n <= 9): return -1 res = res * 10 + n start += 1 return res def myint(s, start=0): n = myint_internal(s, start) if n < 0: raise ValueError return n # ------------------------------ def test_main(): main = """#1 5 ADD""".split() res = interpret(main, [IntBox(20)]) assert repr(res) == '25' res = interpret(main, [StrBox('foo')]) assert repr(res) == 'foo+5' FACTORIAL = """The factorial of #1 is 1 { #1 MUL #1 1 SUB ->#1 #1 }""".split() def test_factorial(): res = interpret(FACTORIAL, [IntBox(5)]) assert repr(res) == 'The factorial of 5 is 120' FIBONACCI = """Fibonacci numbers: { #1 #2 #1 #2 ADD ->#2 ->#1 #3 1 SUB ->#3 #3 }""".split() def test_fibonacci(): res = interpret(FIBONACCI, [IntBox(1), IntBox(1), IntBox(10)]) assert repr(res) == "Fibonacci numbers: 1 1 2 3 5 8 13 21 34 55" FIBONACCI_SINGLE = """#3 1 SUB ->#3 { #2 #1 #2 ADD ->#2 ->#1 #3 1 SUB ->#3 #3 } #1""".split() def test_fibonacci_single(): res = interpret(FIBONACCI_SINGLE, [IntBox(1), IntBox(1), IntBox(11)]) assert repr(res) == "89"
3,934
2,151
<filename>third_party/blink/renderer/platform/blob/testing/fake_blob.cc // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/blob/testing/fake_blob.h" #include "mojo/public/cpp/bindings/strong_binding.h" namespace blink { FakeBlob::FakeBlob(const String& uuid) : uuid_(uuid) {} void FakeBlob::Clone(mojom::blink::BlobRequest request) { mojo::MakeStrongBinding(std::make_unique<FakeBlob>(uuid_), std::move(request)); } void FakeBlob::AsDataPipeGetter( network::mojom::blink::DataPipeGetterRequest request) { NOTREACHED(); } void FakeBlob::ReadRange(uint64_t offset, uint64_t length, mojo::ScopedDataPipeProducerHandle, mojom::blink::BlobReaderClientPtr) { NOTREACHED(); } void FakeBlob::ReadAll(mojo::ScopedDataPipeProducerHandle, mojom::blink::BlobReaderClientPtr) { NOTREACHED(); } void FakeBlob::ReadSideData(ReadSideDataCallback callback) { NOTREACHED(); } void FakeBlob::GetInternalUUID(GetInternalUUIDCallback callback) { std::move(callback).Run(uuid_); } } // namespace blink
544
551
<reponame>pjm073/beeper-android-smsmms /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.telephony.TelephonyManager; import com.android.internal.util.Objects; import static android.net.ConnectivityManager.TYPE_WIFI; /** * Network definition that includes strong identity. Analogous to combining * {@link NetworkInfo} and an IMSI. * * @hide */ public class NetworkIdentity { /** * When enabled, combine all {@link #mSubType} together under * {@link #SUBTYPE_COMBINED}. */ public static final boolean COMBINE_SUBTYPE_ENABLED = true; public static final int SUBTYPE_COMBINED = -1; final int mType; final int mSubType; final String mSubscriberId; final String mNetworkId; final boolean mRoaming; public NetworkIdentity( int type, int subType, String subscriberId, String networkId, boolean roaming) { mType = type; mSubType = COMBINE_SUBTYPE_ENABLED ? SUBTYPE_COMBINED : subType; mSubscriberId = subscriberId; mNetworkId = networkId; mRoaming = roaming; } /** * {@hide} */ public static String getNetworkTypeName(int type) { switch (type) { case 0: return "MOBILE"; case TYPE_WIFI: return "WIFI"; case 2: return "MOBILE_MMS"; case 3: return "MOBILE_SUPL"; case 4: return "MOBILE_DUN"; case 5: return "MOBILE_HIPRI"; case 6: return "WIMAX"; case 7: return "BLUETOOTH"; case 8: return "DUMMY"; case 9: return "ETHERNET"; case 10: return "MOBILE_FOTA"; case 11: return "MOBILE_IMS"; case 12: return "MOBILE_CBS"; case 13: return "WIFI_P2P"; default: return Integer.toString(type); } } /** * {@hide} */ public static boolean isNetworkTypeMobile(int networkType) { switch (networkType) { case 0: case 2: case 3: case 4: case 5: case 10: case 11: case 12: return true; default: return false; } } @Override public int hashCode() { return Objects.hashCode(mType, mSubType, mSubscriberId, mNetworkId, mRoaming); } @Override public boolean equals(Object obj) { if (obj instanceof NetworkIdentity) { final NetworkIdentity ident = (NetworkIdentity) obj; return mType == ident.mType && mSubType == ident.mSubType && mRoaming == ident.mRoaming && Objects.equal(mSubscriberId, ident.mSubscriberId) && Objects.equal(mNetworkId, ident.mNetworkId); } return false; } @Override public String toString() { final StringBuilder builder = new StringBuilder("["); builder.append("type=").append(getNetworkTypeName(mType)); builder.append(", subType="); if (COMBINE_SUBTYPE_ENABLED) { builder.append("COMBINED"); } else if (isNetworkTypeMobile(mType)) { builder.append(getNetworkTypeName(mSubType)); } else { builder.append(mSubType); } if (mSubscriberId != null) { builder.append(", subscriberId=").append(scrubSubscriberId(mSubscriberId)); } if (mNetworkId != null) { builder.append(", networkId=").append(mNetworkId); } if (mRoaming) { builder.append(", ROAMING"); } return builder.append("]").toString(); } public int getType() { return mType; } public int getSubType() { return mSubType; } public String getSubscriberId() { return mSubscriberId; } public String getNetworkId() { return mNetworkId; } public boolean getRoaming() { return mRoaming; } /** * Scrub given IMSI on production builds. */ public static String scrubSubscriberId(String subscriberId) { if ("eng".equals(Build.TYPE)) { return subscriberId; } else if (subscriberId != null) { // TODO: parse this as MCC+MNC instead of hard-coding return subscriberId.substring(0, Math.min(6, subscriberId.length())) + "..."; } else { return "null"; } } /** * Build a {@link NetworkIdentity} from the given {@link NetworkState}, * assuming that any mobile networks are using the current IMSI. */ public static NetworkIdentity buildNetworkIdentity(Context context, NetworkState state) { final int type = state.networkInfo.getType(); final int subType = state.networkInfo.getSubtype(); // TODO: consider moving subscriberId over to LinkCapabilities, so it // comes from an authoritative source. String subscriberId = null; String networkId = null; boolean roaming = false; if (isNetworkTypeMobile(type)) { final TelephonyManager telephony = (TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE); roaming = telephony.isNetworkRoaming(); if (state.subscriberId != null) { subscriberId = state.subscriberId; } else { subscriberId = telephony.getSubscriberId(); } } else if (type == TYPE_WIFI) { if (state.networkId != null) { networkId = state.networkId; } else { final WifiManager wifi = (WifiManager) context.getSystemService( Context.WIFI_SERVICE); final WifiInfo info = wifi.getConnectionInfo(); networkId = info != null ? info.getSSID() : null; } } return new NetworkIdentity(type, subType, subscriberId, networkId, roaming); } }
3,151
848
<reponame>gilteunchoi/clstm #include "clstm_compute.h" #include <iomanip> #include <iostream> #include <memory> #include <unsupported/Eigen/CXX11/Tensor> // The NOINLINE attribute is used before all forward_/backward_ steps // to make execution profiles a little more readable (probably not // needed). #ifndef NOINLINE #define NOINLINE __attribute__((noinline)) #endif // The host/device directives are only meaningful with CUDACC #ifdef __CUDACC__ #define ONBOTH __host__ __device__ #define ONDEVICE __device__ #else #define ONBOTH #define ONDEVICE #endif namespace ocropus { inline void print2d(TensorRef2 t) { for (int i = 0; i < t.dimension(0); i++) { for (int j = 0; j < t.dimension(1); j++) { std::cerr << std::setw(8) << t(i, j); } std::cerr << "\n"; } } // We can generate code for different Eigen devices by defining // the DEVICE macro when compiling this compilation unit. // // When no DEVICE is given, we use the Eigen::DefaultDevice // and default to some of the Eigen::Matrix routines (which // are faster in some cases). // // When a DEVICE is given, we use all Tensor operations. #ifndef DEVICE typedef Eigen::DefaultDevice Device; Eigen::DefaultDevice default_device; #else #define CLSTM_ALL_TENSOR typedef DEVICE Device; #endif inline void device_notify(Device *dev, int gpu) { static int count = 0; if (count > 0) return; cerr << "using " << typeid(dev).name() << " gpu: " << gpu << "\n"; count++; } // When compiling with CUDA, we refer to GPUs by integer index outside // this code. That ensures that none of the rest of CLSTM has to know // about CUDA or nvcc. #if defined(CLSTM_CUDA) && defined(__CUDACC__) #define MAXGPUS 64 using std::unique_ptr; struct EigenGpu { unique_ptr<Eigen::CudaStreamDevice> stream; unique_ptr<Eigen::GpuDevice> dev; }; static EigenGpu devices[MAXGPUS]; Eigen::GpuDevice *gpu_device(int id) { using std::cerr; using std::endl; if (id < 0) return nullptr; assert(id < MAXGPUS); if (!devices[id].dev) { cerr << "initializing GPU " << id << endl; assert(id == 0 && "only GPU 0 tested / supported so far"); auto stream = new Eigen::CudaStreamDevice(/*id*/); devices[id].stream.reset(stream); devices[id].dev.reset(new Eigen::GpuDevice(stream)); } return devices[id].dev.get(); } #endif // Some utility functions for dealing with Eigen indexes and axes. typedef Eigen::IndexPair<int> IndexPair; typedef Eigen::array<IndexPair, 1> Axes1; typedef Eigen::array<ptrdiff_t, 1> Indexes1; typedef Eigen::array<ptrdiff_t, 2> Indexes2; typedef Eigen::array<ptrdiff_t, 3> Indexes3; typedef Eigen::array<ptrdiff_t, 4> Indexes4; ONBOTH inline Axes1 axispairs(int i, int j) { Axes1 result = {IndexPair(i, j)}; return result; } ONBOTH inline Indexes1 indexes(int i) { return Indexes1({i}); } ONBOTH inline Indexes2 indexes(int i, int j) { return Indexes2({i, j}); } // Non-linearities. These come in two versions: regular and in-place. // Note that the regular ones use additive backward-deltas, while the // in-place ones just modify the deltas in place. NOINLINE void forward_identity(Device *dev, Batch &y, Batch &x) { y.v().device(*dev) = x.v(); } NOINLINE void forward_sigmoid(Device *dev, Batch &y, Batch &x) { y.v().device(*dev) = x.v().sigmoid(); } NOINLINE void forward_tanh(Device *dev, Batch &y, Batch &x) { y.v().device(*dev) = x.v().tanh(); } NOINLINE void forward_relu(Device *dev, Batch &y, Batch &x) { y.v().device(*dev) = x.v().cwiseMax(Float(0)); } NOINLINE void forward_logmag(Device *dev, Batch &y, Batch &x) { y.v().device(*dev) = (x.v().abs() + Float(1)).log() * ((x.v() < Float(0)).cast<Float>() * Float(-2) + Float(1)); } NOINLINE void forward_nonlin(Device *dev, Batch &y, Batch &x, int nl) { switch (nl) { case LIN: forward_identity(dev, y, x); break; case SIG: forward_sigmoid(dev, y, x); break; case TANH: forward_tanh(dev, y, x); break; case RELU: forward_relu(dev, y, x); break; case LOGMAG: forward_logmag(dev, y, x); break; default: abort(); } } NOINLINE void backward_identity(Device *dev, Batch &y, Batch &x) { x.d().device(*dev) += y.d(); } NOINLINE void backward_sigmoid(Device *dev, Batch &y, Batch &x) { x.d().device(*dev) += y.v() * (-y.v() + Float(1)) * y.d(); } NOINLINE void backward_tanh(Device *dev, Batch &y, Batch &x) { x.d().device(*dev) += (-y.v() * y.v() + Float(1)) * y.d(); } NOINLINE void backward_relu(Device *dev, Batch &y, Batch &x) { Float zero = 0; x.d().device(*dev) += y.d() * (y.v() > zero).cast<Float>(); } NOINLINE void backward_logmag(Device *dev, Batch &y, Batch &x) { x.d().device(*dev) += y.d() * (-y.v().abs()).exp(); } NOINLINE void backward_nonlin(Device *dev, Batch &y, Batch &x, int nl) { switch (nl) { case LIN: backward_identity(dev, y, x); break; case SIG: backward_sigmoid(dev, y, x); break; case TANH: backward_tanh(dev, y, x); break; case RELU: backward_relu(dev, y, x); break; case LOGMAG: backward_logmag(dev, y, x); break; default: abort(); } } // Forward and backward non-linearities for in-place processing. NOINLINE void forward_identity0(Device *dev, Batch &y) { y.v().device(*dev) = y.v(); } NOINLINE void forward_sigmoid0(Device *dev, Batch &y) { y.v().device(*dev) = y.v().sigmoid(); } NOINLINE void forward_tanh0(Device *dev, Batch &y) { y.v().device(*dev) = y.v().tanh(); } NOINLINE void forward_relu0(Device *dev, Batch &y) { y.v().device(*dev) = y.v().cwiseMax(Float(0)); } NOINLINE void forward_logmag0(Device *dev, Batch &y) { y.v().device(*dev) = (y.v().abs() + Float(1)).log() * ((y.v() < Float(0)).cast<Float>() * Float(-2) + Float(1)); } NOINLINE void forward_nonlin0(Device *dev, Batch &y, int nl) { switch (nl) { case LIN: forward_identity0(dev, y); break; case SIG: forward_sigmoid0(dev, y); break; case TANH: forward_tanh0(dev, y); break; case RELU: forward_relu0(dev, y); break; case LOGMAG: forward_logmag0(dev, y); break; default: abort(); } } NOINLINE void backward_identity0(Device *dev, Batch &y) { y.d().device(*dev) = y.d(); } NOINLINE void backward_sigmoid0(Device *dev, Batch &y) { y.d().device(*dev) = y.v() * (-y.v() + Float(1)) * y.d(); } NOINLINE void backward_tanh0(Device *dev, Batch &y) { y.d().device(*dev) = (-y.v() * y.v() + Float(1)) * y.d(); } NOINLINE void backward_relu0(Device *dev, Batch &y) { Float zero = 0; y.d().device(*dev) = y.d() * (y.v() > zero).cast<Float>(); } NOINLINE void backward_logmag0(Device *dev, Batch &y) { y.d().device(*dev) = y.d() * (-y.v().abs()).exp(); } NOINLINE void backward_nonlin0(Device *dev, Batch &y, int nl) { switch (nl) { case LIN: backward_identity0(dev, y); break; case SIG: backward_sigmoid0(dev, y); break; case TANH: backward_tanh0(dev, y); break; case RELU: backward_relu0(dev, y); break; case LOGMAG: backward_logmag0(dev, y); break; default: abort(); } } // Full layers with constant offset #ifndef CLSTM_ALL_TENSOR #define CBUTFIRST(M) (M).block(0, 1, (M).rows(), (M).cols() - 1) #define CFIRST(M) (M).col(0) #endif NOINLINE void forward_lin1(Device *dev, Batch &y, Params &W1, Batch &x) { int n = W1.v.dimension(0); int m = W1.v.dimension(1); assert(y.rows() == n); assert(y.cols() == x.cols()); assert(x.rows() == m - 1); #ifdef CLSTM_ALL_TENSOR int bs = y.cols(); Indexes2 offsets{0, 1}; Indexes2 sizes{n, m - 1}; Axes1 axes01{IndexPair(1, 0)}; y.v().device(*dev) = W1.v.map1().contract(x.v(), axes01); Indexes2 shape{n, 1}; Indexes2 bcast{1, bs}; y.v().device(*dev) += W1.v.off1().reshape(shape).broadcast(bcast); #else y.v.mat() = (W1.v.mat1() * x.v.mat()).colwise() + W1.v.vec1(); #endif } NOINLINE void backward_lin1(Device *dev, Batch &y, Params &W1, Batch &x) { #ifdef CLSTM_ALL_TENSOR x.d().device(*dev) += W1.v.map1().contract(y.d(), axispairs(0, 0)); W1.d.map1().device(*dev) += y.d().contract(x.v(), axispairs(1, 1)); W1.d.off1().device(*dev) += y.d().sum(indexes(1)); #else x.d.mat() += W1.v.mat1().transpose() * y.d.mat(); W1.d.mat1() += y.d.mat() * x.v.mat().transpose(); W1.d.vec1() += y.d.mat().rowwise().sum(); #endif } // full layers with nonlinearities NOINLINE void forward_full1(Device *dev, Batch &y, Params &W1, Batch &x, int nl) { assert(y.getGpu() < 0 ? typeid(dev) == typeid(&default_device) : true); assert(y.getGpu() >= 0 ? typeid(dev) != typeid(&default_device) : true); forward_lin1(dev, y, W1, x); forward_nonlin0(dev, y, nl); } NOINLINE void backward_full1(Device *dev, Batch &y, Params &W1, Batch &x, int nl) { backward_nonlin0(dev, y, nl); backward_lin1(dev, y, W1, x); } // softmax NOINLINE void forward_softmax(Device *dev, Batch &z, Params &W1, Batch &x) { Float (*f)(Float) = limexp; int n = W1.v.dimension(0); assert(n == z.v.dimension(0)); assert(n >= 2); #ifdef CLSTM_ALL_TENSOR int bs = x.cols(); z.v().device(*dev) = W1.v.map1().contract(x.v(), axispairs(1, 0)); z.v().device(*dev) += W1.v.off1().reshape(indexes(n, 1)).broadcast(indexes(1, bs)); z.v().device(*dev) = z.v().unaryExpr(f); EigenTensor1 sums = z.v().sum(indexes(0)); z.v().device(*dev) = z.v() / sums.reshape(indexes(1, bs)).broadcast(indexes(n, 1)); ; #else z.v.mat() = (W1.v.mat1() * x.v.mat()).colwise() + W1.v.vec1(); z.v.mat() = z.v.mat().unaryExpr(f); EigenVector sums = z.v.mat().colwise().sum(); z.v.mat().array().rowwise() /= sums.transpose().array(); #endif } NOINLINE void backward_softmax(Device *dev, Batch &z, Params &W1, Batch &x) { #ifdef CLSTM_ALL_TENSOR x.d().device(*dev) = W1.v.map1().contract(z.d(), axispairs(0, 0)); W1.d.map1().device(*dev) += z.d().contract(x.v(), axispairs(1, 1)); W1.d.off1().device(*dev) += z.d().sum(indexes(1)); #else x.d.mat() = W1.v.mat1().transpose() * z.d.mat(); W1.d.mat1() += z.d.mat() * x.v.mat().transpose(); W1.d.vec1() += z.d.mat().rowwise().sum(); #endif } // stacking NOINLINE void forward_stack(Device *dev, Batch &z, Batch &x, Batch &y) { int nx = x.v.dimension(0), ny = y.v.dimension(0); int bs = x.v.dimension(1); assert(z.rows() == x.rows() + y.rows()); assert(z.cols() == x.cols() && z.cols() == y.cols()); z.v().slice(indexes(0, 0), indexes(nx, bs)).device(*dev) = x.v(); z.v().slice(indexes(nx, 0), indexes(ny, bs)).device(*dev) = y.v(); } NOINLINE void backward_stack(Device *dev, Batch &z, Batch &x, Batch &y) { int nx = x.v.dimension(0), ny = y.v.dimension(0); int bs = x.v.dimension(1); x.d().device(*dev) += z.d().slice(indexes(0, 0), indexes(nx, bs)); y.d().device(*dev) += z.d().slice(indexes(nx, 0), indexes(ny, bs)); } // stacking with delay NOINLINE void forward_stack_delay(Device *dev, Batch &z, Batch &x, Sequence &y, int last) { int nx = x.v.dimension(0), ny = y[0].v.dimension(0); int bs = x.v.dimension(1); assert(z.rows() == x.rows() + y.rows()); assert(z.cols() == x.cols() && z.cols() == y.cols()); #ifdef CLSTM_ALL_TENSOR z.v().slice(indexes(0, 0), indexes(nx, bs)).device(*dev) = x.v(); if (last >= 0) z.v().slice(indexes(nx, 0), indexes(ny, bs)).device(*dev) = y[last].v(); else z.v().slice(indexes(nx, 0), indexes(ny, bs)).device(*dev) = y[0].v().constant(0); #else z.v.mat().block(0, 0, nx, bs) = x.v.mat(); if (last >= 0) z.v.mat().block(nx, 0, ny, bs) = y[last].v.mat(); else z.v.mat().block(nx, 0, ny, bs).setZero(); #endif } NOINLINE void backward_stack_delay(Device *dev, Batch &z, Batch &x, Sequence &y, int last) { int nx = x.v.dimension(0), ny = y[0].v.dimension(0); int bs = x.v.dimension(1); #ifdef CLSTM_ALL_TENSOR x.d().device(*dev) += z.d().slice(indexes(0, 0), indexes(nx, bs)); if (last >= 0) y[last].d().device(*dev) += z.d().slice(indexes(nx, 0), indexes(ny, bs)); #else x.d.mat() += z.d.mat().block(0, 0, nx, bs); if (last >= 0) y[last].d.mat() += z.d.mat().block(nx, 0, ny, bs); #endif } // reverse sequences NOINLINE void forward_reverse(Device *dev, Sequence &y, Sequence &x) { int N = x.size(); for (int i = 0; i < N; i++) y[N - i - 1] = x[i]; } NOINLINE void backward_reverse(Device *dev, Sequence &y, Sequence &x) { int N = x.size(); for (int i = 0; i < N; i++) x[N - i - 1].d().device(*dev) += y[i].d(); } // switch time and batch NOINLINE void forward_btswitch(Device *dev, Sequence &y, Sequence &x) { TensorMap4 y4 = y.map4(); TensorMap4 x4 = x.map4(); // dimensions are: (feature, batch, 2, time) assert(y4.dimension(0) == x4.dimension(0)); assert(y4.dimension(1) == x4.dimension(3)); assert(y4.dimension(2) == 2); assert(y4.dimension(3) == x4.dimension(1)); Indexes3 axes{0, 2, 1}; y4.chip(0, 2).device(*dev) = x4.chip(0, 2).shuffle(axes); } NOINLINE void backward_btswitch(Device *dev, Sequence &y, Sequence &x) { TensorMap4 y4 = y.map4(); TensorMap4 x4 = x.map4(); assert(y4.dimension(0) == x4.dimension(0)); assert(y4.dimension(1) == x4.dimension(3)); assert(y4.dimension(2) == 2); assert(y4.dimension(3) == x4.dimension(1)); Indexes3 axes{0, 2, 1}; x4.chip(1, 2).device(*dev) += y4.chip(1, 2).shuffle(axes); } // stacking neighboring batches NOINLINE void forward_batchstack(Device *dev, Sequence &y, Sequence &x, int pre, int post) { TensorMap4 y4 = y.map4(); TensorMap4 x4 = x.map4(); // dimensions are: (feature, batch, 2, time) int d = x4.dimension(0); int bs = x4.dimension(1); int size = x4.dimension(3); int copies = pre + post + 1; assert(y4.dimension(0) == copies * d); assert(y4.dimension(1) == bs); assert(y4.dimension(2) == 2); assert(y4.dimension(3) == x4.dimension(3)); y4.device(*dev) = y4.constant(Float(0)); for (int k = -pre; k <= post; k++) { int source = max(k, 0); int dest = max(-k, 0); int crimp = abs(k); Indexes4 source_offsets{0, source, 0, 0}; Indexes4 dest_offsets{d * (pre + k), dest, 0, 0}; Indexes4 sizes{d, bs - crimp, 1, size}; y4.slice(dest_offsets, sizes).device(*dev) = x4.slice(source_offsets, sizes); } } NOINLINE void backward_batchstack(Device *dev, Sequence &y, Sequence &x, int pre, int post) { TensorMap4 y4 = y.map4(); TensorMap4 x4 = x.map4(); // dimensions are: (feature, batch, 2, time) int d = x4.dimension(0); int bs = x4.dimension(1); int size = x4.dimension(3); int copies = pre + post + 1; assert(y4.dimension(0) == copies * d); assert(y4.dimension(1) == bs); assert(y4.dimension(2) == 2); assert(y4.dimension(3) == x4.dimension(3)); // x4.chip(1,2).device(*dev) = x4.chip(1,2).constant(Float(0)); for (int k = -pre; k <= post; k++) { int source = max(k, 0); int dest = max(-k, 0); int crimp = abs(k); Indexes4 source_offsets{0, source, 1, 0}; Indexes4 dest_offsets{d * (pre + k), dest, 1, 0}; Indexes4 sizes{d, bs - crimp, 1, size}; x4.slice(source_offsets, sizes).device(*dev) += y4.slice(dest_offsets, sizes); } } // combine the delayed gated state with the gated input NOINLINE void forward_statemem(Device *dev, Batch &state, Batch &ci, Batch &gi, Sequence &states, int last, Batch &gf) { state.v().device(*dev) = ci.v() * gi.v(); if (last >= 0) state.v().device(*dev) += gf.v() * states[last].v(); } NOINLINE void backward_statemem(Device *dev, Batch &state, Batch &ci, Batch &gi, Sequence &states, int last, Batch &gf) { if (last >= 0) states[last].d().device(*dev) += state.d() * gf.v(); if (last >= 0) gf.d().device(*dev) += state.d() * states[last].v(); gi.d().device(*dev) += state.d() * ci.v(); ci.d().device(*dev) += state.d() * gi.v(); } // linear gated output NOINLINE void forward_gate(Device *dev, Batch &out, Batch &nlstate, Batch &go) { out.v().device(*dev) = nlstate.v() * go.v(); } NOINLINE void backward_gate(Device *dev, Batch &out, Batch &nlstate, Batch &go) { go.d().device(*dev) += nlstate.v() * out.d(); nlstate.d().device(*dev) += go.v() * out.d(); } // nonlinear gated output NOINLINE void forward_nonlingate(Device *dev, Batch &out, Batch &state, Batch &go, int nl) { BatchStorage temp; temp.setGpu(out.getGpu()); temp.resize(out.rows(), out.cols()); forward_nonlin(dev, (Batch &)temp, state, nl); forward_gate(dev, out, (Batch &)temp, go); } NOINLINE void backward_nonlingate(Device *dev, Batch &out, Batch &state, Batch &go, int nl) { BatchStorage temp; temp.setGpu(out.getGpu()); temp.resize(out.rows(), out.cols()); forward_nonlin(dev, (Batch &)temp, state, nl); backward_gate(dev, out, (Batch &)temp, go); backward_nonlin(dev, (Batch &)temp, state, nl); } NOINLINE void fill(Device *dev, TensorMap2 &a, Float value) { a.device(*dev) = a.constant(value); } NOINLINE void clip_gradient(Device *dev, Batch &x, Float clip) { if (clip >= 1e6) return; assert(clip > 0); x.d().device(*dev) = x.d().cwiseMin(clip); x.d().device(*dev) = x.d().cwiseMax(-clip); } NOINLINE void sgd_update(Device *dev, Params &params, Float lr, Float mom) { params.v().device(*dev) += params.d() * lr; params.d().device(*dev) = params.d() * mom; } }
7,838
706
#!/usr/bin/env python """ This script shows how to use shellpython directly from python without using the shellpy command """ import shellpython shellpython.init() # installs the shellpython import hook. Call uninit() to remove the hook if no longer needed import shared # imports shellpy module def main(): print(shared.shared_func()) # call to a function from shellpy module if __name__ == '__main__': main()
117
618
<gh_stars>100-1000 package hprose.example.promise; import hprose.util.concurrent.Promise; public class Exam11 { public static void main(String[] args) throws InterruptedException { Promise.forEach((Integer element) -> { System.out.println(element); }, 1, Promise.value(2), 3); Promise.forEach(new Object[] {1, Promise.value(2), 3}, (Integer element, int index) -> { System.out.println("a[" + index + "] = " + element); return null; } ); } }
263
337
<filename>idea/testData/copyPaste/conversion/FieldWithNoModifierAndNoSemicolon.java public class JavaClass { public <selection>volatile int field = 1</selection>; }
53
4,013
<gh_stars>1000+ from checkov.common.models.enums import CheckResult, CheckCategories from checkov.cloudformation.checks.resource.base_resource_value_check import BaseResourceValueCheck from checkov.common.models.consts import ANY_VALUE class CloudtrailEncryption(BaseResourceValueCheck): def __init__(self): name = "Ensure CloudTrail logs are encrypted at rest using KMS CMKs" id = "CKV_AWS_35" supported_resources = ['AWS::CloudTrail::Trail'] categories = [CheckCategories.LOGGING] super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources) def get_inspected_key(self): return 'Properties/KMSKeyId' def get_expected_value(self): return ANY_VALUE check = CloudtrailEncryption()
282
2,542
<gh_stars>1000+ // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace ServiceModel { class InternalDeletedApplicationsQueryObject : public Serialization::FabricSerializable , public Common::IFabricJsonSerializable { public: InternalDeletedApplicationsQueryObject(); InternalDeletedApplicationsQueryObject(std::vector<std::wstring> const & applicationIds); InternalDeletedApplicationsQueryObject(InternalDeletedApplicationsQueryObject && other); void WriteTo(Common::TextWriter&, Common::FormatOptions const &) const; __declspec(property(get=get_ApplicationIds)) std::vector<std::wstring> const &ApplicationIds; std::vector<std::wstring> const& get_ApplicationIds() const { return applicationIds_; } InternalDeletedApplicationsQueryObject const & operator= (InternalDeletedApplicationsQueryObject && other); FABRIC_FIELDS_01(applicationIds_) BEGIN_JSON_SERIALIZABLE_PROPERTIES() SERIALIZABLE_PROPERTY(Constants::ApplicationIds, applicationIds_) END_JSON_SERIALIZABLE_PROPERTIES() private: std::vector<std::wstring> applicationIds_; }; }
465
319
<reponame>Celebrate-future/openimaj /** * Copyright (c) 2011, The University of Southampton and the individual contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the University of Southampton nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openimaj.math.matrix; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Field; import java.util.Scanner; import org.openimaj.io.ReadWriteable; import Jama.Matrix; /** * A wrapper around a JAMA Matrix that is read-writeable by * OpenIMAJ IOUtils. * * @author <NAME> (<EMAIL>) * */ public class ReadWriteableMatrix extends Matrix implements ReadWriteable { private static final long serialVersionUID = 1L; /** * Construct a new matrix of zero size. Only for IOUtils use. */ protected ReadWriteableMatrix() { super(0, 0); } /** * Construct a matrix using the provided 2-D double array. * The array is assigned internally and is not copied. * * @param data the data */ public ReadWriteableMatrix(double[][] data) { super(data); } /** * Construct a new matrix of the given size * @param rows Number of rows * @param cols Number of columns */ public ReadWriteableMatrix(int rows, int cols) { super(rows, cols); } /** * Construct a matrix using the provided matrix. * The matrix data is assigned internally and is not copied. * * @param data the data */ public ReadWriteableMatrix(Matrix data) { this(data.getArray()); } @Override public void readASCII(Scanner in) throws IOException { final int rows = in.nextInt(); final int cols = in.nextInt(); double[][] data = new double[rows][cols]; for (int r=0; r<rows; r++) for (int c=0; c<cols; c++) data[r][c] = in.nextDouble(); setData(rows, cols, data); } @Override public String asciiHeader() { return this.getClass().getName() + " "; } @Override public void readBinary(DataInput in) throws IOException { final int rows = in.readInt(); final int cols = in.readInt(); double[][] data = new double[rows][cols]; for (int r=0; r<rows; r++) for (int c=0; c<cols; c++) data[r][c] = in.readDouble(); setData(rows, cols, data); } protected void setData(int m, int n, double[][] data) { Class<Matrix> clz = Matrix.class; try { Field mField = clz.getDeclaredField("m"); mField.setAccessible(true); mField.setInt(this, m); Field nField = clz.getDeclaredField("n"); nField.setAccessible(true); nField.setInt(this, n); Field AField = clz.getDeclaredField("A"); AField.setAccessible(true); AField.set(this, data); } catch (Exception e) { throw new RuntimeException(e); } } @Override public byte[] binaryHeader() { return "RWMAT".getBytes(); } @Override public void writeASCII(PrintWriter out) throws IOException { final int rows = this.getRowDimension(); final int cols = this.getColumnDimension(); final double[][] data = this.getArray(); out.print(rows + " " + cols); out.println(); for (int r=0; r<rows; r++) { for (int c=0; c<cols; c++) { out.print(data[r][c] + " "); } out.println(); } } @Override public void writeBinary(DataOutput out) throws IOException { final int rows = this.getRowDimension(); final int cols = this.getColumnDimension(); final double[][] data = this.getArray(); out.writeInt(rows); out.writeInt(cols); for (int r=0; r<rows; r++) for (int c=0; c<cols; c++) out.writeDouble(data[r][c]); } }
1,742
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Federation; using namespace Common; using namespace Transport; using namespace TestCommon; using namespace FederationTestCommon; StringLiteral TraceOutput("Output"); GlobalWString DeclareVotesCommand = make_global<wstring>(L"votes"); GlobalWString ListBehaviorsCommand = make_global<wstring>(L"listbehaviors"); GlobalWString AddUnreliableTransportBehaviorCommand = make_global<wstring>(L"addbehavior"); GlobalWString RemoveUnreliableTransportBehaviorCommand = make_global<wstring>(L"removebehavior"); CommonDispatcher::CommonDispatcher() { } bool CommonDispatcher::ExecuteCommand(wstring command) { StringCollection paramCollection; StringUtility::Split<wstring>(command, paramCollection, L" "); if (paramCollection.size() == 0) { return false; } command = *paramCollection.begin(); paramCollection.erase(paramCollection.begin()); paramCollection = CompactParameters(paramCollection); if (command == DeclareVotesCommand) { return DeclareVotes(paramCollection); } else if (command == ListBehaviorsCommand) { return ListBehaviors(); } else if (command == AddUnreliableTransportBehaviorCommand) { return AddUnreliableTransportBehavior(paramCollection); } else if (command == RemoveUnreliableTransportBehaviorCommand) { return RemoveUnreliableTransportBehavior(paramCollection); } return false; } bool CommonDispatcher::DeclareVotes(StringCollection const & params) { VoteConfig voteOverrides; map<wstring, wstring> connectionStringsToVoteIdsMap; //TestSession::FailTestIfNot(Federation.Count == 0, "Federation is not empty:{0}", Federation.Count); auto seedNodePorts = AddressHelper::GetAvailableSeedNodePorts(); TestSession::FailTestIf(seedNodePorts.size() < params.size(), "seed node port address range should be larger than {0}", params.size()); for (wstring const & nodeIdString : params) { StringCollection configuration; StringUtility::Split<wstring>(nodeIdString, configuration, L":"); wstring ringName; size_t index = configuration[0].find_first_of(L'@'); if (index != wstring::npos) { ringName = configuration[0].substr(index + 1); configuration[0] = configuration[0].substr(0, index); } NodeId nodeId; wstring voteType, voteConnectionString; if (configuration.size() == 1) { nodeId = ParseNodeId(configuration[0]); voteType = *Federation::Constants::SeedNodeVoteType; StringWriter writer(voteConnectionString); writer.Write(AddressHelper::GetLoopbackAddress()); writer.Write(":"); writer.Write(seedNodePorts.front()); seedNodePorts.pop(); } else if (configuration.size() == 2) { voteType = configuration[1]; if (voteType == Federation::Constants::SeedNodeVoteType) { nodeId = ParseNodeId(configuration[0]); StringWriter writer(voteConnectionString); writer.Write(AddressHelper::GetLoopbackAddress()); writer.Write(":"); writer.Write(seedNodePorts.front()); seedNodePorts.pop(); } else { ErrorCode errorCode = NodeIdGenerator::GenerateFromString(configuration[0], nodeId); TestSession::FailTestIfNot(errorCode.IsSuccess(), "NodeIdGenerator failed"); voteConnectionString = L"Driver={SQL Server};Server=(local);Database=master;Trusted_Connection=yes"; } } else if (configuration.size() == 3) { voteType = configuration[1]; if (voteType == Federation::Constants::SeedNodeVoteType) { nodeId = ParseNodeId(configuration[0]); voteConnectionString = AddressHelper::GetLoopbackAddress() + L":" + configuration[2]; } else { ErrorCode errorCode = NodeIdGenerator::GenerateFromString(configuration[0], nodeId); TestSession::FailTestIfNot(errorCode.IsSuccess(), "NodeIdGenerator failed"); voteConnectionString = configuration[2]; TestSession::FailTestIf( !connectionStringsToVoteIdsMap.empty() && connectionStringsToVoteIdsMap.find(voteConnectionString) != connectionStringsToVoteIdsMap.end(), "Connection string {0} specified for key {1} already", voteConnectionString, connectionStringsToVoteIdsMap[voteConnectionString]); connectionStringsToVoteIdsMap[voteConnectionString] = configuration[0]; } } else { TestSession::FailTest("Invalid vote configuration"); } TestSession::FailTestIf(voteOverrides.find(nodeId, ringName) != voteOverrides.end(), "Vote {0} for key {1} already present", nodeId, configuration[0]); voteOverrides.push_back(VoteEntryConfig(nodeId, voteType, voteConnectionString, ringName)); } FederationConfig::GetConfig().Votes = voteOverrides; return true; } bool CommonDispatcher::AddUnreliableTransportBehavior(Common::StringCollection const & params) { if (params.size() < 1) { PrintHelp(*AddUnreliableTransportBehaviorCommand); return true; } wstring name = params[0]; wstring data; for (size_t i = 1; i < params.size(); i++) { if (i > 1) { data += L" "; } data += params[i]; } if (!UnreliableTransportConfig::GetConfig().AddSpecification(name, data)) { TestSession::WriteError(TraceOutput, "Invalid unreliable transport specification."); } return true; } bool CommonDispatcher::RemoveUnreliableTransportBehavior(Common::StringCollection const & params) { if (params.size() != 1) { PrintHelp(*RemoveUnreliableTransportBehaviorCommand); return true; } UnreliableTransportConfig::GetConfig().RemoveSpecification(params[0]); return true; } bool CommonDispatcher::ListBehaviors() { TestSession::WriteInfo(TraceOutput, "{0}", UnreliableTransportConfig::GetConfig()); return true; } NodeId CommonDispatcher::ParseNodeId(wstring const & nodeIdString) { return NodeId(ParseLargeInteger(nodeIdString)); } LargeInteger CommonDispatcher::ParseLargeInteger(wstring const & value) { LargeInteger result; if (!LargeInteger::TryParse(value, result)) { TestSession::FailTest("Cannot parse a large integer {0}", value); } return result; }
2,719
3,428
<gh_stars>1000+ {"id":"00482","group":"easy-ham-2","checksum":{"type":"MD5","value":"dcb4dd7822137630e5659b86336082c3"},"text":"From <EMAIL> Wed Aug 21 12:41:30 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 518DE43C32\n\tfor <jm@localhost>; Wed, 21 Aug 2002 07:41:28 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 21 Aug 2002 12:41:28 +0100 (IST)\nReceived: from lugh.tuatha.org (<EMAIL> [172.16.58.35]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g7LBeZZ22390 for\n <<EMAIL>>; Wed, 21 Aug 2002 12:40:35 +0100\nReceived: from lugh (root@localhost [127.0.0.1]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id MAA26678; Wed, 21 Aug 2002 12:39:38 +0100\nX-Authentication-Warning: lugh.tuatha.org: Host root@localhost [127.0.0.1]\n claimed to be lugh\nReceived: from holly.csn.ul.ie (holly.csn.ul.ie [136.201.105.4]) by\n lugh.tuatha.org (8.9.3/8.9.3) with ESMTP id MAA26655 for <<EMAIL>>;\n Wed, 21 Aug 2002 12:39:32 +0100\nReceived: from skynet.csn.ul.ie (skynet [136.201.105.2]) by\n holly.csn.ul.ie (Postfix) with ESMTP id E051F2B7A3; Wed, 21 Aug 2002\n 12:38:57 +0100 (IST)\nReceived: by skynet.csn.ul.ie (Postfix, from userid 2665) id A4C81E7D4;\n Wed, 21 Aug 2002 12:38:57 +0100 (IST)\nDate: Wed, 21 Aug 2002 12:38:57 +0100\nFrom: <NAME> <<EMAIL>>\nTo: <NAME> <<EMAIL>>\nCc: [email protected]\nSubject: Re: [ILUG] URGENT: Cant get a skrew out... PLEASE HELP!\nMessage-Id: <<EMAIL>>\nMail-Followup-To: <NAME> <<EMAIL>>,\n\[email protected]\nReferences: <<EMAIL>>\nMIME-Version: 1.0\nContent-Type: text/plain; charset=us-ascii\nContent-Disposition: inline\nIn-Reply-To: <<EMAIL>>\nUser-Agent: Mutt/1.3.24i\nSender: [email protected]\nErrors-To: [email protected]\nX-Mailman-Version: 1.1\nPrecedence: bulk\nList-Id: Irish Linux Users' Group <ilug.linux.ie>\nX-Beenthere: [email protected]\n\nOn (21/08/02 12:42), <NAME> didst pronounce:\n> \n> Hi i have a phillips head skrew thats holding a circut board together i need\n> to take it out ASAP and nothing will work, the threads on the skrew are\n> almost completly gone, its is a very small skrew that i have to use a\n> percision skrewdriver set to remove the skrews any help would be\n> appreaciated...\n> \nTry a hammer -- great precision tool that!!\n\n-- \nChat ya later,\n\nJohn.\n--\nBOFH excuse #167: excessive collisions & not enough packet ambulances\n\n-- \nIrish Linux Users' Group: <EMAIL>\nhttp://www.linux.ie/mailman/listinfo/ilug for (un)subscription information.\nList maintainer: [email protected]\n\n"}
1,142
488
#ifndef H_SATIRE_DATAFLOW_ANALYSIS #define H_SATIRE_DATAFLOW_ANALYSIS #include "satire.h" #include <cstdarg> namespace SATIrE { class DataFlowAnalysis: public Analysis { public: virtual std::string identifier() const; virtual std::string description() const; // DataFlowAnalysis defines a common way to run data-flow analyzers by // providing implementations of these methods. The user need not override // these further. void run(Program *program); void processResults(Program *program); // The prefixFiles flag determines whether to prefix the generated files // (term, ICFG, etc.) with the analysis identifier. void processResultsWithPrefix(Program *program, bool prefixFiles = true); bool query(std::string query, ...); // The DataFlowAnalysis class provides a general framework for data-flow // analyzers generated by PAG; the details of a specific analysis are // encapsulated in an instance of this delegate class. This ensures that // the DataFlowAnalysis class is completely independent of function or // object names generated by PAG, and of the type of data flow information // computed by the analysis. // This class is abstract; it is made concrete by subclassing and defining // the methods and other details, for which SATIrE provides templates. class Implementation { public: virtual std::string identifier() const = 0; virtual std::string description() const = 0; // Methods for wrapping PAG's generated functions. virtual void analysisDoit(CFG *cfg) = 0; virtual void makePersistent() const = 0; // Methods for annotating the program and generating various annotated // representations. Note that these methods do not get the analysis // results as parameter; typically, this means that the subclass must // define a member to hold the analysis results computed by the // analysisDoit method. Note also that these are not const, since they // might have to pass their analysis info around. virtual void outputAnalysisVisualization( Program *program, bool prefixFiles = false) = 0; virtual void annotateProgram(Program *program) = 0; virtual void outputAnnotatedProgram( Program *program, bool prefixFiles = false) = 0; // Forwarded query method. virtual bool query(std::string query, va_list args) const = 0; // Methods for setting possibly prefixed PAG options. virtual void setDebugStat(int debugStat) const = 0; virtual void setGlobalRetfunc(int globalRetfunc) const = 0; }; // A pointer to an instance of the Implementation must be passed in to // construct a DataFlowAnalysis; the Implementation object must live as // long as the DataFlowAnalysis instance lives, but its ownership is not // transferred to the DataFlowAnalysis object. DataFlowAnalysis(Implementation *implementation); ~DataFlowAnalysis(); private: Implementation *p_impl; // Copying of DataFlowAnalysis objects is explicitly prohibited. DataFlowAnalysis(const DataFlowAnalysis &); DataFlowAnalysis &operator=(const DataFlowAnalysis &); #if HAVE_PAG // Helper methods for computing/printing call strings. void computeCallStrings(Program *program) const; void outputContextData(Program *program) const; #endif }; // Generated function that returns an instance of a provided data-flow // analyzer. DataFlowAnalysis *makeProvidedAnalyzer(const char *name); } #endif
1,000
648
{"resourceType":"DataElement","id":"Contract.term","meta":{"lastUpdated":"2015-10-24T07:41:03.495+11:00"},"url":"http://hl7.org/fhir/DataElement/Contract.term","name":"term","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/structuredefinition-explicit-type-name","valueString":"Term"}],"path":"Contract.term","name":"term","short":"Contract Term List","definition":"One or more Contract Provisions, which may be related and conveyed as a group, and may contain nested groups.","min":0,"max":"*","type":[{"code":"BackboneElement"}]}]}
174
335
<filename>T/Tiff_noun.json<gh_stars>100-1000 { "word": "Tiff", "definitions": [ "A petty quarrel, especially one between friends or lovers." ], "parts-of-speech": "Noun" }
84
402
/* * Copyright 2000-2021 <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. */ package com.vaadin.flow.data.binder; import java.util.Locale; import java.util.Objects; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.vaadin.flow.component.Text; import com.vaadin.flow.component.UI; import com.vaadin.flow.data.binder.testcomponents.TestDatePicker; import com.vaadin.flow.data.binder.testcomponents.TestTextField; import com.vaadin.flow.internal.CurrentInstance; import com.vaadin.flow.server.VaadinRequest; public class ValueContextTest extends UI { private static final Locale UI_LOCALE = Locale.GERMAN; private static final Locale COMPONENT_LOCALE = Locale.FRENCH; private TestTextField textField; @Test public void locale_from_component() { setLocale(COMPONENT_LOCALE); ValueContext fromComponent = new ValueContext(textField); Locale locale = fromComponent.getLocale().orElse(null); Objects.requireNonNull(locale); Assert.assertEquals("Unexpected locale from component", COMPONENT_LOCALE, locale); } @Test public void locale_from_ui() { ValueContext fromComponent = new ValueContext(textField); Locale locale = fromComponent.getLocale().orElse(null); Objects.requireNonNull(locale); Assert.assertEquals("Unexpected locale from component", UI_LOCALE, locale); } @Test public void default_locale() { setLocale(Locale.getDefault()); ValueContext fromComponent = new ValueContext(textField); Locale locale = fromComponent.getLocale().orElse(null); Objects.requireNonNull(locale); Assert.assertEquals("Unexpected locale from component", Locale.getDefault(), locale); } @Test public void testHasValue1() { setLocale(Locale.getDefault()); ValueContext fromComponent = new ValueContext(textField); Assert.assertEquals(textField, fromComponent.getHasValue().get()); } @Test public void testHasValue2() { setLocale(Locale.getDefault()); ValueContext fromComponent = new ValueContext(new TestDatePicker(), textField); Assert.assertEquals(textField, fromComponent.getHasValue().get()); } @Test public void testHasValue3() { setLocale(Locale.getDefault()); ValueContext fromComponent = new ValueContext(new TestDatePicker(), textField, Locale.CANADA); Assert.assertEquals(textField, fromComponent.getHasValue().get()); Assert.assertEquals(Locale.CANADA, fromComponent.getLocale().get()); } @Test public void getLocale_localeComesFromComponentUI() { UI.setCurrent(null); UI ui = new UI(); ui.setLocale(Locale.GERMAN); Text text = new Text(""); ui.add(text); ValueContext context = new ValueContext(text); Assert.assertEquals(Locale.GERMAN, context.getLocale().get()); } @Before public void setUp() { setLocale(UI_LOCALE); UI.setCurrent(this); textField = new TestTextField(); add(textField); } @After public void tearDown() { CurrentInstance.clearAll(); } @Override public void init(VaadinRequest request) { } }
1,461
335
{ "word": "Splendid", "definitions": [ "Magnificent; very impressive.", "Excellent; very good." ], "parts-of-speech": "Adjective" }
74
3,459
#ifndef _SHARED_H_ #define _SHARED_H_ #include <mednafen/mednafen.h> #include <mednafen/hw_cpu/z80-fuse/z80.h> using namespace Mednafen; #include "sms.h" #include "pio.h" #include "memz80.h" #include "vdp.h" #include "render.h" #include "sound.h" #include "system.h" #include "tms.h" #include "cart.h" using namespace MDFN_IEN_SMS; #endif /* _SHARED_H_ */
199
364
<filename>app/src/main/java/com/markzhai/lyrichere/ui/AboutActivity.java package com.markzhai.lyrichere.ui; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.widget.TextView; import com.markzhai.lyrichere.R; public class AboutActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); TextView versionTextView = (TextView) findViewById(R.id.about_version_name); try { PackageInfo pi = this.getPackageManager().getPackageInfo(this.getPackageName(), 0); versionTextView.setText(String.format("%s %s", getString(R.string.about_version), pi.versionName)); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
556
314
<reponame>syamasakigoodrx/astronomer from tests.helm_template_generator import render_chart import pytest from . import supported_k8s_versions import jmespath @pytest.mark.parametrize( "kube_version", supported_k8s_versions, ) def test_astronomer_commander_deployment(kube_version): """Test that helm renders a good deployment template for astronomer/commander.""" docs = render_chart( kube_version=kube_version, show_only=["charts/astronomer/templates/commander/commander-deployment.yaml"], ) assert len(docs) == 1 doc = docs[0] assert doc["kind"] == "Deployment" assert doc["apiVersion"] == "apps/v1" assert doc["metadata"]["name"] == "RELEASE-NAME-commander" assert any( image_name.startswith("quay.io/astronomer/ap-commander:") for image_name in jmespath.search("spec.template.spec.containers[*].image", doc) ) assert len(doc["spec"]["template"]["spec"]["containers"]) == 1 env_vars = { x["name"]: x["value"] for x in doc["spec"]["template"]["spec"]["containers"][0]["env"] } assert env_vars["COMMANDER_UPGRADE_TIMEOUT"] == "300" @pytest.mark.parametrize( "kube_version", supported_k8s_versions, ) def test_astronomer_commander_deployment_upgrade_timeout(kube_version): """Test that helm renders a good deployment template for astronomer/commander. when upgrade timeout is set""" docs = render_chart( kube_version=kube_version, values={"astronomer": {"commander": {"upgradeTimeout": 600}}}, show_only=["charts/astronomer/templates/commander/commander-deployment.yaml"], ) assert len(docs) == 1 doc = docs[0] assert doc["kind"] == "Deployment" assert doc["apiVersion"] == "apps/v1" assert doc["metadata"]["name"] == "RELEASE-NAME-commander" assert any( image_name.startswith("quay.io/astronomer/ap-commander:") for image_name in jmespath.search("spec.template.spec.containers[*].image", doc) ) assert len(doc["spec"]["template"]["spec"]["containers"]) == 1 env_vars = { x["name"]: x["value"] for x in doc["spec"]["template"]["spec"]["containers"][0]["env"] } assert env_vars["COMMANDER_UPGRADE_TIMEOUT"] == "600"
923
337
<filename>app/src/main/java/com/edotassi/amazmod/event/ResultDownloadFileChunk.java package com.edotassi.amazmod.event; import com.huami.watch.transport.DataBundle; import amazmod.com.transport.data.ResultDownloadFileChunkData; public class ResultDownloadFileChunk { private ResultDownloadFileChunkData resultDownloadFileChunkData; public ResultDownloadFileChunk(DataBundle dataBundle) { resultDownloadFileChunkData = ResultDownloadFileChunkData.fromDataBundle(dataBundle); } public ResultDownloadFileChunkData getResultDownloadFileChunkData() { return resultDownloadFileChunkData; } }
206
499
<reponame>ivasanpag/datasource-proxy package net.ttddyy.dsproxy.support; import net.ttddyy.dsproxy.proxy.ProxyConfig; import org.springframework.beans.factory.BeanNameAware; /** * Extending {@link ProxyDataSource} to use * spring bean name(id) as dataSourceName when it is not set. * * @author <NAME> */ public class BeanNameProxyDataSource extends ProxyDataSource implements BeanNameAware { public void setBeanName(String name) { final String dataSourceName = getProxyConfig().getDataSourceName(); if (dataSourceName == null || "".equals(dataSourceName)) { ProxyConfig proxyConfig = ProxyConfig.Builder.from(getProxyConfig()).dataSourceName(name).build(); setProxyConfig(proxyConfig); } } }
263
441
<reponame>mrdziuban/basex package org.basex.query.func.inspect; import java.util.*; import org.basex.query.*; import org.basex.query.func.*; import org.basex.query.value.*; import org.basex.query.value.item.*; import org.basex.query.value.type.*; import org.basex.util.*; import org.basex.util.options.*; /** * Function implementation. * * @author BaseX Team 2005-21, BSD License * @author <NAME> */ public final class InspectType extends StandardFunc { /** Inspection options. */ public static class InspectOptions extends Options { /** Mode. */ public static final EnumOption<Mode> MODE = new EnumOption<>("mode", Mode.COMPUTED); /** Item. */ public static final BooleanOption ITEM = new BooleanOption("item", false); } /** Inspection mode. */ public enum Mode { /** Combined. */ COMPUTED, /** Value. */ VALUE, /** Expression. */ EXPRESSION; @Override public String toString() { return name().toLowerCase(Locale.ENGLISH); } } @Override public Str item(final QueryContext qc, final InputInfo ii) throws QueryException { final Value value = exprs[0].value(qc); final InspectOptions opts = toOptions(1, new InspectOptions(), qc); final Mode mode = opts.get(InspectOptions.MODE); final boolean item = opts.get(InspectOptions.ITEM); SeqType st = null; switch(mode) { case EXPRESSION: st = exprs[0].seqType(); break; case VALUE: st = value.seqType(); break; default: // combine types of all items to get more specific type for(final Item it : value) { final SeqType st2 = it.seqType(); st = st == null ? st2 : st.union(st2); } if(st == null) st = SeqType.EMPTY_SEQUENCE_Z; st = st.with(value.seqType().occ); // compare with original type, which may be more specific (in particular for node types) final SeqType et = exprs[0].seqType(); if(et.instanceOf(st)) st = et; } return Str.get((item ? st.type : st).toString()); } }
799
1,006
<reponame>zhuyanlinzyl/incubator-nuttx<gh_stars>1000+ /**************************************************************************** * include/nuttx/sensors/hall3ph.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ #ifndef __INCLUDE_NUTTX_SENSORS_HALL3PH_H #define __INCLUDE_NUTTX_SENSORS_HALL3PH_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <nuttx/fs/ioctl.h> #include <nuttx/sensors/ioctl.h> /**************************************************************************** * Public Types ****************************************************************************/ /* 120-degree Hall effect sensors positions */ enum hall3_120deg_position_e { HALL3_120DEG_POS_1 = 0b001, HALL3_120DEG_POS_2 = 0b011, HALL3_120DEG_POS_3 = 0b010, HALL3_120DEG_POS_4 = 0b110, HALL3_120DEG_POS_5 = 0b100, HALL3_120DEG_POS_6 = 0b101 }; /* 60-degree Hall effect sensors postions */ enum hall3_60deg_position_e { HALL3_60DEG_POS_1 = 0b000, HALL3_60DEG_POS_2 = 0b001, HALL3_60DEG_POS_3 = 0b101, HALL3_60DEG_POS_4 = 0b111, HALL3_60DEG_POS_5 = 0b110, HALL3_60DEG_POS_6 = 0b010 }; /* This structure provides the "lower-half" driver operations available to * the "upper-half" driver. */ struct hall3_lowerhalf_s; struct hall3_ops_s { /* Configure the 3-phase Hall effect sensor device */ CODE int (*setup)(FAR struct hall3_lowerhalf_s *lower); /* Disable the 3-phase Hall effect sensor device */ CODE int (*shutdown)(FAR struct hall3_lowerhalf_s *lower); /* Return the current 3-phase Hall effect sensor position */ CODE int (*position)(FAR struct hall3_lowerhalf_s *lower, FAR uint8_t *pos); }; /* This structure provides the publicly visible representation of the * "lower-half" driver state structure. "lower half" drivers will have an * internal structure definition that will be cast-compatible with this * structure definitions. */ struct hall3_lowerhalf_s { FAR const struct hall3_ops_s *ops; }; /**************************************************************************** * Public Data ****************************************************************************/ #ifdef __cplusplus #define EXTERN extern "C" extern "C" { #else #define EXTERN extern #endif /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /**************************************************************************** * Name: hall3_register * * Description: * Register the 3-phase Hall effect sensor lower half device as 'devpath' * * Input Parameters: * devpath - The full path to the driver to register. E.g., "/dev/hall0" * lower - An instance of the lower half interface * * Returned Value: * Zero (OK) on success; a negated errno value on failure. The following * possible error values may be returned (most are returned by * register_driver()): * * EINVAL - 'path' is invalid for this operation * EEXIST - An inode already exists at 'path' * ENOMEM - Failed to allocate in-memory resources for the operation * ****************************************************************************/ int hall3_register(FAR const char *devpath, FAR struct hall3_lowerhalf_s *lower); #undef EXTERN #ifdef __cplusplus } #endif #endif /* __INCLUDE_NUTTX_SENSORS_HALL3PH_H */
1,265
405
#!/usr/bin/python3 import struct import sys import os import argparse def read_labels(filename): """ read labels from given file. """ contents = bytes() with open(filename, "rb") as f: f.seek(0, 2) # move the cursor to the end of the file num_points = int(f.tell() / 4) f.seek(0, 0) contents = f.read() arr = [struct.unpack('<I', contents[4 * i:4 * i + 4])[0] for i in range(num_points)] return arr def write_labels(filename, labels): """ write labels in given file. """ arr = [struct.pack('<I', label) for label in labels] with open(filename, "bw") as f: for a in arr: f.write(a) def get_labelfiles(directory): return {f: os.path.join(directory, f) for f in os.listdir(directory) if f.endswith(".label")} if __name__ == "__main__": parser = argparse.ArgumentParser(description='Merge multiple label files.') parser.add_argument('input', nargs=2, help='directories containing labels to merge.') parser.add_argument('--out', nargs=1, help='output directory', default=None) parser.add_argument( "--keep", nargs=1, help="keep labels from given directory. Otherwise always newer labels are keept.", default=None) args = parser.parse_args() if args.out is None: os.makedirs("./labels_merged", exist_ok=True) out = os.path.abspath("./labels_merged") if not os.path.exists(out): os.makedirs(out) print("-- Creating directory {}".format(out)) print("-- Writing merged labels to {}".format(out)) if len([f.endswith(".label") for f in os.listdir(out)]) > 0: print("-- Found label files in output directory. Delete? ", end="") answer = input("[y/N/c(ontinue)] ") if answer.lower() == "y": print("-- Deleting files in output directory.") files = [os.path.join(out, f) for f in os.listdir(out) if f.endswith(".label")] for f in files: os.remove(f) elif answer.lower() == "c": print("-- Continue.") else: print("Aborted.") sys.exit(1) labels1 = get_labelfiles(args.input[0]) labels2 = get_labelfiles(args.input[1]) already_merged = [f for f in os.listdir(out) if f.endswith(".label")] print(already_merged[:10]) if len(labels1) != len(labels2) or len(labels1) == 0: print("-- Error: Inconsistent number of labels. Aborting.") sys.exit(1) print("-- Merging: ", end="", flush=True) progress = 10 count = 0 for (f, f1) in labels1.items(): count += 1 if 100 * count / len(labels1) > progress: print(progress, end=" ", flush=True) progress += 10 if f in already_merged: continue f2 = labels2[f] labels = [read_labels(f1), read_labels(f2)] if len(labels[0]) != len(labels[1]): print("Inconsistent number of labels for {}: Expected {}, but got {} labels.".format(f, len(labels[0]), len(labels[1]))) sys.exit(1) keep_index = 0 if args.keep is None: if os.stat(f2).st_mtime > os.stat(f1).st_mtime: keep_index = 1 elif args.keep[0] == args.input[1]: keep_index = 1 merged = labels[keep_index] for i in range(len(merged)): if merged[i] == 0: merged[i] = labels[(keep_index + 1) % 2][i] write_labels(os.path.join(out, f), merged) while 100 * count / len(labels1) < 100: print(progress, end=" ") progress += 10 print("finished.") # print("{} labels in file".format(len(labels1))) # #print(labels1[0:100]) # # labels_test = read_labels("test.label") # labels_test == labels1
1,389
1,093
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.router; import java.lang.reflect.Method; import org.springframework.integration.annotation.Router; import org.springframework.integration.handler.MessageProcessor; import org.springframework.integration.handler.MethodInvokingMessageProcessor; /** * A Message Router that invokes the specified method on the given object. The * method's return value may be a single MessageChannel instance, a single * String to be interpreted as a channel name, or a Collection (or Array) of * either type. If the method returns channel names, then a * {@link org.springframework.messaging.core.DestinationResolver} is required. * * @author <NAME> * @author <NAME> */ public class MethodInvokingRouter extends AbstractMessageProcessingRouter { public MethodInvokingRouter(Object object, Method method) { super(new MethodInvokingMessageProcessor<Object>(object, method)); } public MethodInvokingRouter(Object object, String methodName) { super(new MethodInvokingMessageProcessor<Object>(object, methodName)); } public MethodInvokingRouter(Object object) { super(object instanceof MessageProcessor<?> ? (MessageProcessor<?>) object : new MethodInvokingMessageProcessor<Object>(object, Router.class)); } }
502
30,023
<reponame>liangleslie/core<gh_stars>1000+ """Representation of a sensorMultilevel.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from zwave_me_ws import ZWaveMeData from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ELECTRIC_CURRENT_AMPERE, ELECTRIC_POTENTIAL_VOLT, ENERGY_KILO_WATT_HOUR, LIGHT_LUX, PERCENTAGE, POWER_WATT, PRESSURE_KPA, TEMP_CELSIUS, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddEntitiesCallback from . import ZWaveMeController, ZWaveMeEntity from .const import DOMAIN, ZWaveMePlatform @dataclass class ZWaveMeSensorEntityDescription(SensorEntityDescription): """Class describing ZWaveMeSensor sensor entities.""" value: Callable = lambda value: value SENSORS_MAP: dict[str, ZWaveMeSensorEntityDescription] = { "barometer": ZWaveMeSensorEntityDescription( key="barometer", device_class=SensorDeviceClass.PRESSURE, native_unit_of_measurement=PRESSURE_KPA, state_class=SensorStateClass.MEASUREMENT, ), "co": ZWaveMeSensorEntityDescription( key="co", device_class=SensorDeviceClass.CO, native_unit_of_measurement="ppm", state_class=SensorStateClass.MEASUREMENT, ), "co2": ZWaveMeSensorEntityDescription( key="co2", device_class=SensorDeviceClass.CO2, native_unit_of_measurement="ppm", state_class=SensorStateClass.MEASUREMENT, ), "humidity": ZWaveMeSensorEntityDescription( key="humidity", device_class=SensorDeviceClass.HUMIDITY, native_unit_of_measurement=PERCENTAGE, state_class=SensorStateClass.MEASUREMENT, ), "luminosity": ZWaveMeSensorEntityDescription( key="luminosity", device_class=SensorDeviceClass.ILLUMINANCE, native_unit_of_measurement=LIGHT_LUX, state_class=SensorStateClass.MEASUREMENT, ), "meterElectric_ampere": ZWaveMeSensorEntityDescription( key="meterElectric_ampere", device_class=SensorDeviceClass.CURRENT, native_unit_of_measurement=ELECTRIC_CURRENT_AMPERE, state_class=SensorStateClass.MEASUREMENT, ), "meterElectric_kilowatt_hour": ZWaveMeSensorEntityDescription( key="meterElectric_kilowatt_hour", device_class=SensorDeviceClass.ENERGY, native_unit_of_measurement=ENERGY_KILO_WATT_HOUR, state_class=SensorStateClass.TOTAL_INCREASING, ), "meterElectric_power_factor": ZWaveMeSensorEntityDescription( key="meterElectric_power_factor", device_class=SensorDeviceClass.POWER_FACTOR, native_unit_of_measurement=PERCENTAGE, state_class=SensorStateClass.MEASUREMENT, value=lambda value: float(value) * 100, ), "meterElectric_voltage": ZWaveMeSensorEntityDescription( key="meterElectric_voltage", device_class=SensorDeviceClass.VOLTAGE, native_unit_of_measurement=ELECTRIC_POTENTIAL_VOLT, state_class=SensorStateClass.MEASUREMENT, ), "meterElectric_watt": ZWaveMeSensorEntityDescription( key="meterElectric_watt", device_class=SensorDeviceClass.POWER, native_unit_of_measurement=POWER_WATT, state_class=SensorStateClass.MEASUREMENT, ), "temperature": ZWaveMeSensorEntityDescription( key="temperature", device_class=SensorDeviceClass.TEMPERATURE, native_unit_of_measurement=TEMP_CELSIUS, state_class=SensorStateClass.MEASUREMENT, ), "generic": ZWaveMeSensorEntityDescription( key="generic", ), } DEVICE_NAME = ZWaveMePlatform.SENSOR async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the sensor platform.""" @callback def add_new_device(new_device: ZWaveMeData) -> None: controller: ZWaveMeController = hass.data[DOMAIN][config_entry.entry_id] description = SENSORS_MAP.get(new_device.probeType, SENSORS_MAP["generic"]) sensor = ZWaveMeSensor(controller, new_device, description) async_add_entities( [ sensor, ] ) config_entry.async_on_unload( async_dispatcher_connect( hass, f"ZWAVE_ME_NEW_{DEVICE_NAME.upper()}", add_new_device ) ) class ZWaveMeSensor(ZWaveMeEntity, SensorEntity): """Representation of a ZWaveMe sensor.""" entity_description: ZWaveMeSensorEntityDescription def __init__( self, controller: ZWaveMeController, device: ZWaveMeData, description: ZWaveMeSensorEntityDescription, ) -> None: """Initialize the device.""" super().__init__(controller=controller, device=device) self.entity_description = description @property def native_value(self) -> str: """Return the state of the sensor.""" return self.entity_description.value(self.device.level)
2,143
2,460
package io.fabric8.openshift.api.model; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.IntOrString; import io.fabric8.kubernetes.api.model.KubernetesResource; import io.fabric8.kubernetes.api.model.LabelSelector; import io.fabric8.kubernetes.api.model.LocalObjectReference; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.ObjectReference; import io.fabric8.kubernetes.api.model.PersistentVolumeClaim; import io.fabric8.kubernetes.api.model.PodTemplateSpec; import io.fabric8.kubernetes.api.model.ResourceRequirements; import io.sundr.builder.annotations.Buildable; import io.sundr.builder.annotations.BuildableReference; import lombok.EqualsAndHashCode; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; @JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "apiVersion", "kind", "metadata", "bitbucketWebHook", "genericWebHook", "githubWebHook", "gitlabWebHook", "imageChangeBuild", "message" }) @ToString @EqualsAndHashCode @Setter @Accessors(prefix = { "_", "" }) @Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder", refs = { @BuildableReference(ObjectMeta.class), @BuildableReference(LabelSelector.class), @BuildableReference(Container.class), @BuildableReference(PodTemplateSpec.class), @BuildableReference(ResourceRequirements.class), @BuildableReference(IntOrString.class), @BuildableReference(ObjectReference.class), @BuildableReference(LocalObjectReference.class), @BuildableReference(PersistentVolumeClaim.class) }) public class BuildTriggerCause implements KubernetesResource { @JsonProperty("bitbucketWebHook") private BitbucketWebHookCause bitbucketWebHook; @JsonProperty("genericWebHook") private GenericWebHookCause genericWebHook; @JsonProperty("githubWebHook") private GitHubWebHookCause githubWebHook; @JsonProperty("gitlabWebHook") private GitLabWebHookCause gitlabWebHook; @JsonProperty("imageChangeBuild") private ImageChangeCause imageChangeBuild; @JsonProperty("message") private String message; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * No args constructor for use in serialization * */ public BuildTriggerCause() { } /** * * @param githubWebHook * @param genericWebHook * @param bitbucketWebHook * @param imageChangeBuild * @param message * @param gitlabWebHook */ public BuildTriggerCause(BitbucketWebHookCause bitbucketWebHook, GenericWebHookCause genericWebHook, GitHubWebHookCause githubWebHook, GitLabWebHookCause gitlabWebHook, ImageChangeCause imageChangeBuild, String message) { super(); this.bitbucketWebHook = bitbucketWebHook; this.genericWebHook = genericWebHook; this.githubWebHook = githubWebHook; this.gitlabWebHook = gitlabWebHook; this.imageChangeBuild = imageChangeBuild; this.message = message; } @JsonProperty("bitbucketWebHook") public BitbucketWebHookCause getBitbucketWebHook() { return bitbucketWebHook; } @JsonProperty("bitbucketWebHook") public void setBitbucketWebHook(BitbucketWebHookCause bitbucketWebHook) { this.bitbucketWebHook = bitbucketWebHook; } @JsonProperty("genericWebHook") public GenericWebHookCause getGenericWebHook() { return genericWebHook; } @JsonProperty("genericWebHook") public void setGenericWebHook(GenericWebHookCause genericWebHook) { this.genericWebHook = genericWebHook; } @JsonProperty("githubWebHook") public GitHubWebHookCause getGithubWebHook() { return githubWebHook; } @JsonProperty("githubWebHook") public void setGithubWebHook(GitHubWebHookCause githubWebHook) { this.githubWebHook = githubWebHook; } @JsonProperty("gitlabWebHook") public GitLabWebHookCause getGitlabWebHook() { return gitlabWebHook; } @JsonProperty("gitlabWebHook") public void setGitlabWebHook(GitLabWebHookCause gitlabWebHook) { this.gitlabWebHook = gitlabWebHook; } @JsonProperty("imageChangeBuild") public ImageChangeCause getImageChangeBuild() { return imageChangeBuild; } @JsonProperty("imageChangeBuild") public void setImageChangeBuild(ImageChangeCause imageChangeBuild) { this.imageChangeBuild = imageChangeBuild; } @JsonProperty("message") public String getMessage() { return message; } @JsonProperty("message") public void setMessage(String message) { this.message = message; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
2,141
478
<reponame>undeadinu/minko /* Copyright (c) 2014 Aerys 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 "minko/Common.hpp" #include "minko/material/PhongMaterial.hpp" namespace minko { namespace material { class WaterMaterial : public PhongMaterial { public: typedef std::shared_ptr<WaterMaterial> Ptr; private: uint _numWaves; std::vector<float> _amplitudes; std::vector<float> _waveLength; std::vector<math::vec2> _origins; std::vector<float> _speeds; std::vector<float> _sharpness; std::vector<int> _waveType; public: inline static Ptr create(uint numWaves, const std::string& name = "WaterMaterial") { return std::shared_ptr<WaterMaterial>(new WaterMaterial(numWaves, name)); } Ptr setDirection(int waveId, const math::vec2& direction); Ptr setCenter(int waveId, const math::vec2& origin); Ptr setAmplitude(int waveId, float amplitude); Ptr setWaveLength(int waveId, float waveLength); Ptr setSharpness(int waveId, float sharpness); Ptr setSpeed(int waveId, float speed); // Ptr // dudvMap(AbsTexturePtr); // // TexturePtr // dudvMap() const; // // Ptr // dudvFactor(float); // // float // dudvFactor() const; // // Ptr // dudvSpeed(float); // // float // dudvSpeed() const; // Ptr // depthMap(AbsTexturePtr); // // TexturePtr // depthMap() const; // // Ptr // reflectionMap(AbsTexturePtr); // // TexturePtr // reflectionMap() const; // // Ptr // flowMap(AbsTexturePtr); // // TexturePtr // flowMap() const; // // Ptr // flowMapScale(float); // // float // flowMapScale() const; // // Ptr // flowMapCycle(float); // // float // flowMapCycle() const; // // Ptr // flowMapOffset1(float); // // float // flowMapOffset1() const; // // Ptr // flowMapOffset2(float); // // float // flowMapOffset2() const; // // Ptr // noiseMap(AbsTexturePtr); // // TexturePtr // noiseMap() const; // // Ptr // reflectivity(float); // // float // reflectivity() const; private: WaterMaterial(uint numWaves, const std::string& name); template <typename T> void setWaveProperty(const std::string& propertyName, int waveId, T value) { std::vector<T>& values = *data()->getUnsafePointer<std::vector<T>>(propertyName); values[waveId] = value; } }; } }
2,305
19,438
/* * Copyright (c) 2018-2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/MACAddress.h> #include <Kernel/Bus/PCI/API.h> #include <Kernel/Bus/PCI/IDs.h> #include <Kernel/Debug.h> #include <Kernel/Net/Intel/E1000NetworkAdapter.h> #include <Kernel/Net/NetworkingManagement.h> #include <Kernel/Sections.h> namespace Kernel { #define REG_CTRL 0x0000 #define REG_STATUS 0x0008 #define REG_EEPROM 0x0014 #define REG_CTRL_EXT 0x0018 #define REG_INTERRUPT_CAUSE_READ 0x00C0 #define REG_INTERRUPT_RATE 0x00C4 #define REG_INTERRUPT_MASK_SET 0x00D0 #define REG_INTERRUPT_MASK_CLEAR 0x00D8 #define REG_RCTRL 0x0100 #define REG_RXDESCLO 0x2800 #define REG_RXDESCHI 0x2804 #define REG_RXDESCLEN 0x2808 #define REG_RXDESCHEAD 0x2810 #define REG_RXDESCTAIL 0x2818 #define REG_TCTRL 0x0400 #define REG_TXDESCLO 0x3800 #define REG_TXDESCHI 0x3804 #define REG_TXDESCLEN 0x3808 #define REG_TXDESCHEAD 0x3810 #define REG_TXDESCTAIL 0x3818 #define REG_RDTR 0x2820 // RX Delay Timer Register #define REG_RXDCTL 0x3828 // RX Descriptor Control #define REG_RADV 0x282C // RX Int. Absolute Delay Timer #define REG_RSRPD 0x2C00 // RX Small Packet Detect Interrupt #define REG_TIPG 0x0410 // Transmit Inter Packet Gap #define ECTRL_SLU 0x40 // set link up #define RCTL_EN (1 << 1) // Receiver Enable #define RCTL_SBP (1 << 2) // Store Bad Packets #define RCTL_UPE (1 << 3) // Unicast Promiscuous Enabled #define RCTL_MPE (1 << 4) // Multicast Promiscuous Enabled #define RCTL_LPE (1 << 5) // Long Packet Reception Enable #define RCTL_LBM_NONE (0 << 6) // No Loopback #define RCTL_LBM_PHY (3 << 6) // PHY or external SerDesc loopback #define RTCL_RDMTS_HALF (0 << 8) // Free Buffer Threshold is 1/2 of RDLEN #define RTCL_RDMTS_QUARTER (1 << 8) // Free Buffer Threshold is 1/4 of RDLEN #define RTCL_RDMTS_EIGHTH (2 << 8) // Free Buffer Threshold is 1/8 of RDLEN #define RCTL_MO_36 (0 << 12) // Multicast Offset - bits 47:36 #define RCTL_MO_35 (1 << 12) // Multicast Offset - bits 46:35 #define RCTL_MO_34 (2 << 12) // Multicast Offset - bits 45:34 #define RCTL_MO_32 (3 << 12) // Multicast Offset - bits 43:32 #define RCTL_BAM (1 << 15) // Broadcast Accept Mode #define RCTL_VFE (1 << 18) // VLAN Filter Enable #define RCTL_CFIEN (1 << 19) // Canonical Form Indicator Enable #define RCTL_CFI (1 << 20) // Canonical Form Indicator Bit Value #define RCTL_DPF (1 << 22) // Discard Pause Frames #define RCTL_PMCF (1 << 23) // Pass MAC Control Frames #define RCTL_SECRC (1 << 26) // Strip Ethernet CRC // Buffer Sizes #define RCTL_BSIZE_256 (3 << 16) #define RCTL_BSIZE_512 (2 << 16) #define RCTL_BSIZE_1024 (1 << 16) #define RCTL_BSIZE_2048 (0 << 16) #define RCTL_BSIZE_4096 ((3 << 16) | (1 << 25)) #define RCTL_BSIZE_8192 ((2 << 16) | (1 << 25)) #define RCTL_BSIZE_16384 ((1 << 16) | (1 << 25)) // Transmit Command #define CMD_EOP (1 << 0) // End of Packet #define CMD_IFCS (1 << 1) // Insert FCS #define CMD_IC (1 << 2) // Insert Checksum #define CMD_RS (1 << 3) // Report Status #define CMD_RPS (1 << 4) // Report Packet Sent #define CMD_VLE (1 << 6) // VLAN Packet Enable #define CMD_IDE (1 << 7) // Interrupt Delay Enable // TCTL Register #define TCTL_EN (1 << 1) // Transmit Enable #define TCTL_PSP (1 << 3) // Pad Short Packets #define TCTL_CT_SHIFT 4 // Collision Threshold #define TCTL_COLD_SHIFT 12 // Collision Distance #define TCTL_SWXOFF (1 << 22) // Software XOFF Transmission #define TCTL_RTLC (1 << 24) // Re-transmit on Late Collision #define TSTA_DD (1 << 0) // Descriptor Done #define TSTA_EC (1 << 1) // Excess Collisions #define TSTA_LC (1 << 2) // Late Collision #define LSTA_TU (1 << 3) // Transmit Underrun // STATUS Register #define STATUS_FD 0x01 #define STATUS_LU 0x02 #define STATUS_TXOFF 0x08 #define STATUS_SPEED 0xC0 #define STATUS_SPEED_10MB 0x00 #define STATUS_SPEED_100MB 0x40 #define STATUS_SPEED_1000MB1 0x80 #define STATUS_SPEED_1000MB2 0xC0 // Interrupt Masks #define INTERRUPT_TXDW (1 << 0) #define INTERRUPT_TXQE (1 << 1) #define INTERRUPT_LSC (1 << 2) #define INTERRUPT_RXSEQ (1 << 3) #define INTERRUPT_RXDMT0 (1 << 4) #define INTERRUPT_RXO (1 << 6) #define INTERRUPT_RXT0 (1 << 7) #define INTERRUPT_MDAC (1 << 9) #define INTERRUPT_RXCFG (1 << 10) #define INTERRUPT_PHYINT (1 << 12) #define INTERRUPT_TXD_LOW (1 << 15) #define INTERRUPT_SRPD (1 << 16) // https://www.intel.com/content/dam/doc/manual/pci-pci-x-family-gbe-controllers-software-dev-manual.pdf Section 5.2 UNMAP_AFTER_INIT static bool is_valid_device_id(u16 device_id) { // FIXME: It would be nice to distinguish which particular device it is. // Especially since it's needed to determine which registers we can access. // The reason I haven't done it now is because there's some IDs with multiple devices // and some devices with multiple IDs. switch (device_id) { case 0x1019: // 82547EI-A0, 82547EI-A1, 82547EI-B0, 82547GI-B0 case 0x101A: // 82547EI-B0 case 0x1010: // 82546EB-A1 case 0x1012: // 82546EB-A1 case 0x101D: // 82546EB-A1 case 0x1079: // 82546GB-B0 case 0x107A: // 82546GB-B0 case 0x107B: // 82546GB-B0 case 0x100F: // 82545EM-A case 0x1011: // 82545EM-A case 0x1026: // 82545GM-B case 0x1027: // 82545GM-B case 0x1028: // 82545GM-B case 0x1107: // 82544EI-A4 case 0x1112: // 82544GC-A4 case 0x1013: // 82541EI-A0, 82541EI-B0 case 0x1018: // 82541EI-B0 case 0x1076: // 82541GI-B1, 82541PI-C0 case 0x1077: // 82541GI-B1 case 0x1078: // 82541ER-C0 case 0x1017: // 82540EP-A case 0x1016: // 82540EP-A case 0x100E: // 82540EM-A case 0x1015: // 82540EM-A return true; default: return false; } } UNMAP_AFTER_INIT RefPtr<E1000NetworkAdapter> E1000NetworkAdapter::try_to_initialize(PCI::DeviceIdentifier const& pci_device_identifier) { if (pci_device_identifier.hardware_id().vendor_id != PCI::VendorID::Intel) return {}; if (!is_valid_device_id(pci_device_identifier.hardware_id().device_id)) return {}; u8 irq = pci_device_identifier.interrupt_line().value(); // FIXME: Better propagate errors here auto interface_name_or_error = NetworkingManagement::generate_interface_name_from_pci_address(pci_device_identifier); if (interface_name_or_error.is_error()) return {}; auto adapter = adopt_ref_if_nonnull(new (nothrow) E1000NetworkAdapter(pci_device_identifier.address(), irq, interface_name_or_error.release_value())); if (!adapter) return {}; if (adapter->initialize()) return adapter; return {}; } UNMAP_AFTER_INIT void E1000NetworkAdapter::setup_link() { u32 flags = in32(REG_CTRL); out32(REG_CTRL, flags | ECTRL_SLU); } UNMAP_AFTER_INIT void E1000NetworkAdapter::setup_interrupts() { out32(REG_INTERRUPT_RATE, 6000); // Interrupt rate of 1.536 milliseconds out32(REG_INTERRUPT_MASK_SET, INTERRUPT_LSC | INTERRUPT_RXT0 | INTERRUPT_RXO); in32(REG_INTERRUPT_CAUSE_READ); enable_irq(); } UNMAP_AFTER_INIT bool E1000NetworkAdapter::initialize() { dmesgln("E1000: Found @ {}", pci_address()); enable_bus_mastering(pci_address()); m_io_base = IOAddress(PCI::get_BAR1(pci_address()) & ~1); size_t mmio_base_size = PCI::get_BAR_space_size(pci_address(), 0); auto region_or_error = MM.allocate_kernel_region(PhysicalAddress(page_base_of(PCI::get_BAR0(pci_address()))), Memory::page_round_up(mmio_base_size).release_value_but_fixme_should_propagate_errors(), "E1000 MMIO", Memory::Region::Access::ReadWrite, Memory::Region::Cacheable::No); if (region_or_error.is_error()) return false; m_mmio_region = region_or_error.release_value(); m_mmio_base = m_mmio_region->vaddr(); m_use_mmio = true; dmesgln("E1000: port base: {}", m_io_base); dmesgln("E1000: MMIO base: {}", PhysicalAddress(PCI::get_BAR0(pci_address()) & 0xfffffffc)); dmesgln("E1000: MMIO base size: {} bytes", mmio_base_size); dmesgln("E1000: Interrupt line: {}", interrupt_number()); detect_eeprom(); dmesgln("E1000: Has EEPROM? {}", m_has_eeprom); read_mac_address(); const auto& mac = mac_address(); dmesgln("E1000: MAC address: {}", mac.to_string()); initialize_rx_descriptors(); initialize_tx_descriptors(); setup_link(); setup_interrupts(); return true; } UNMAP_AFTER_INIT E1000NetworkAdapter::E1000NetworkAdapter(PCI::Address address, u8 irq, NonnullOwnPtr<KString> interface_name) : NetworkAdapter(move(interface_name)) , PCI::Device(address) , IRQHandler(irq) , m_rx_descriptors_region(MM.allocate_contiguous_kernel_region(Memory::page_round_up(sizeof(e1000_rx_desc) * number_of_rx_descriptors + 16).release_value_but_fixme_should_propagate_errors(), "E1000 RX Descriptors", Memory::Region::Access::ReadWrite).release_value()) , m_tx_descriptors_region(MM.allocate_contiguous_kernel_region(Memory::page_round_up(sizeof(e1000_tx_desc) * number_of_tx_descriptors + 16).release_value_but_fixme_should_propagate_errors(), "E1000 TX Descriptors", Memory::Region::Access::ReadWrite).release_value()) { } UNMAP_AFTER_INIT E1000NetworkAdapter::~E1000NetworkAdapter() { } bool E1000NetworkAdapter::handle_irq(const RegisterState&) { u32 status = in32(REG_INTERRUPT_CAUSE_READ); m_entropy_source.add_random_event(status); if (status == 0) return false; if (status & INTERRUPT_LSC) { u32 flags = in32(REG_CTRL); out32(REG_CTRL, flags | ECTRL_SLU); } if (status & INTERRUPT_RXDMT0) { // Threshold OK? } if (status & INTERRUPT_RXO) { dbgln_if(E1000_DEBUG, "E1000: RX buffer overrun"); } if (status & INTERRUPT_RXT0) { receive(); } m_wait_queue.wake_all(); out32(REG_INTERRUPT_CAUSE_READ, 0xffffffff); return true; } UNMAP_AFTER_INIT void E1000NetworkAdapter::detect_eeprom() { out32(REG_EEPROM, 0x1); for (int i = 0; i < 999; ++i) { u32 data = in32(REG_EEPROM); if (data & 0x10) { m_has_eeprom = true; return; } } m_has_eeprom = false; } UNMAP_AFTER_INIT u32 E1000NetworkAdapter::read_eeprom(u8 address) { u16 data = 0; u32 tmp = 0; if (m_has_eeprom) { out32(REG_EEPROM, ((u32)address << 8) | 1); while (!((tmp = in32(REG_EEPROM)) & (1 << 4))) ; } else { out32(REG_EEPROM, ((u32)address << 2) | 1); while (!((tmp = in32(REG_EEPROM)) & (1 << 1))) ; } data = (tmp >> 16) & 0xffff; return data; } UNMAP_AFTER_INIT void E1000NetworkAdapter::read_mac_address() { if (m_has_eeprom) { MACAddress mac {}; u32 tmp = read_eeprom(0); mac[0] = tmp & 0xff; mac[1] = tmp >> 8; tmp = read_eeprom(1); mac[2] = tmp & 0xff; mac[3] = tmp >> 8; tmp = read_eeprom(2); mac[4] = tmp & 0xff; mac[5] = tmp >> 8; set_mac_address(mac); } else { VERIFY_NOT_REACHED(); } } bool E1000NetworkAdapter::link_up() { return (in32(REG_STATUS) & STATUS_LU); } UNMAP_AFTER_INIT void E1000NetworkAdapter::initialize_rx_descriptors() { auto* rx_descriptors = (e1000_tx_desc*)m_rx_descriptors_region->vaddr().as_ptr(); constexpr auto rx_buffer_size = 8192; constexpr auto rx_buffer_page_count = rx_buffer_size / PAGE_SIZE; m_rx_buffer_region = MM.allocate_contiguous_kernel_region(rx_buffer_size * number_of_rx_descriptors, "E1000 RX buffers", Memory::Region::Access::ReadWrite).release_value(); for (size_t i = 0; i < number_of_rx_descriptors; ++i) { auto& descriptor = rx_descriptors[i]; m_rx_buffers[i] = m_rx_buffer_region->vaddr().as_ptr() + rx_buffer_size * i; descriptor.addr = m_rx_buffer_region->physical_page(rx_buffer_page_count * i)->paddr().get(); descriptor.status = 0; } out32(REG_RXDESCLO, m_rx_descriptors_region->physical_page(0)->paddr().get()); out32(REG_RXDESCHI, 0); out32(REG_RXDESCLEN, number_of_rx_descriptors * sizeof(e1000_rx_desc)); out32(REG_RXDESCHEAD, 0); out32(REG_RXDESCTAIL, number_of_rx_descriptors - 1); out32(REG_RCTRL, RCTL_EN | RCTL_SBP | RCTL_UPE | RCTL_MPE | RCTL_LBM_NONE | RTCL_RDMTS_HALF | RCTL_BAM | RCTL_SECRC | RCTL_BSIZE_8192); } UNMAP_AFTER_INIT void E1000NetworkAdapter::initialize_tx_descriptors() { auto* tx_descriptors = (e1000_tx_desc*)m_tx_descriptors_region->vaddr().as_ptr(); constexpr auto tx_buffer_size = 8192; constexpr auto tx_buffer_page_count = tx_buffer_size / PAGE_SIZE; m_tx_buffer_region = MM.allocate_contiguous_kernel_region(tx_buffer_size * number_of_tx_descriptors, "E1000 TX buffers", Memory::Region::Access::ReadWrite).release_value(); for (size_t i = 0; i < number_of_tx_descriptors; ++i) { auto& descriptor = tx_descriptors[i]; m_tx_buffers[i] = m_tx_buffer_region->vaddr().as_ptr() + tx_buffer_size * i; descriptor.addr = m_tx_buffer_region->physical_page(tx_buffer_page_count * i)->paddr().get(); descriptor.cmd = 0; } out32(REG_TXDESCLO, m_tx_descriptors_region->physical_page(0)->paddr().get()); out32(REG_TXDESCHI, 0); out32(REG_TXDESCLEN, number_of_tx_descriptors * sizeof(e1000_tx_desc)); out32(REG_TXDESCHEAD, 0); out32(REG_TXDESCTAIL, 0); out32(REG_TCTRL, in32(REG_TCTRL) | TCTL_EN | TCTL_PSP); out32(REG_TIPG, 0x0060200A); } void E1000NetworkAdapter::out8(u16 address, u8 data) { dbgln_if(E1000_DEBUG, "E1000: OUT8 {:#02x} @ {:#04x}", data, address); if (m_use_mmio) { auto* ptr = (volatile u8*)(m_mmio_base.get() + address); *ptr = data; return; } m_io_base.offset(address).out(data); } void E1000NetworkAdapter::out16(u16 address, u16 data) { dbgln_if(E1000_DEBUG, "E1000: OUT16 {:#04x} @ {:#04x}", data, address); if (m_use_mmio) { auto* ptr = (volatile u16*)(m_mmio_base.get() + address); *ptr = data; return; } m_io_base.offset(address).out(data); } void E1000NetworkAdapter::out32(u16 address, u32 data) { dbgln_if(E1000_DEBUG, "E1000: OUT32 {:#08x} @ {:#04x}", data, address); if (m_use_mmio) { auto* ptr = (volatile u32*)(m_mmio_base.get() + address); *ptr = data; return; } m_io_base.offset(address).out(data); } u8 E1000NetworkAdapter::in8(u16 address) { dbgln_if(E1000_DEBUG, "E1000: IN8 @ {:#04x}", address); if (m_use_mmio) return *(volatile u8*)(m_mmio_base.get() + address); return m_io_base.offset(address).in<u8>(); } u16 E1000NetworkAdapter::in16(u16 address) { dbgln_if(E1000_DEBUG, "E1000: IN16 @ {:#04x}", address); if (m_use_mmio) return *(volatile u16*)(m_mmio_base.get() + address); return m_io_base.offset(address).in<u16>(); } u32 E1000NetworkAdapter::in32(u16 address) { dbgln_if(E1000_DEBUG, "E1000: IN32 @ {:#04x}", address); if (m_use_mmio) return *(volatile u32*)(m_mmio_base.get() + address); return m_io_base.offset(address).in<u32>(); } void E1000NetworkAdapter::send_raw(ReadonlyBytes payload) { disable_irq(); size_t tx_current = in32(REG_TXDESCTAIL) % number_of_tx_descriptors; dbgln_if(E1000_DEBUG, "E1000: Sending packet ({} bytes)", payload.size()); auto* tx_descriptors = (e1000_tx_desc*)m_tx_descriptors_region->vaddr().as_ptr(); auto& descriptor = tx_descriptors[tx_current]; VERIFY(payload.size() <= 8192); auto* vptr = (void*)m_tx_buffers[tx_current]; memcpy(vptr, payload.data(), payload.size()); descriptor.length = payload.size(); descriptor.status = 0; descriptor.cmd = CMD_EOP | CMD_IFCS | CMD_RS; dbgln_if(E1000_DEBUG, "E1000: Using tx descriptor {} (head is at {})", tx_current, in32(REG_TXDESCHEAD)); tx_current = (tx_current + 1) % number_of_tx_descriptors; cli(); enable_irq(); out32(REG_TXDESCTAIL, tx_current); for (;;) { if (descriptor.status) { sti(); break; } m_wait_queue.wait_forever("E1000NetworkAdapter"); } dbgln_if(E1000_DEBUG, "E1000: Sent packet, status is now {:#02x}!", (u8)descriptor.status); } void E1000NetworkAdapter::receive() { auto* rx_descriptors = (e1000_tx_desc*)m_rx_descriptors_region->vaddr().as_ptr(); u32 rx_current; for (;;) { rx_current = in32(REG_RXDESCTAIL) % number_of_rx_descriptors; rx_current = (rx_current + 1) % number_of_rx_descriptors; if (!(rx_descriptors[rx_current].status & 1)) break; auto* buffer = m_rx_buffers[rx_current]; u16 length = rx_descriptors[rx_current].length; VERIFY(length <= 8192); dbgln_if(E1000_DEBUG, "E1000: Received 1 packet @ {:p} ({} bytes)", buffer, length); did_receive({ buffer, length }); rx_descriptors[rx_current].status = 0; out32(REG_RXDESCTAIL, rx_current); } } i32 E1000NetworkAdapter::link_speed() { if (!link_up()) return NetworkAdapter::LINKSPEED_INVALID; u32 speed = in32(REG_STATUS) & STATUS_SPEED; switch (speed) { case STATUS_SPEED_10MB: return 10; case STATUS_SPEED_100MB: return 100; case STATUS_SPEED_1000MB1: case STATUS_SPEED_1000MB2: return 1000; default: return NetworkAdapter::LINKSPEED_INVALID; } } bool E1000NetworkAdapter::link_full_duplex() { u32 status = in32(REG_STATUS); return !!(status & STATUS_FD); } }
8,059
3,269
// Time: O(m * n) // Space: O(n) class Solution { public: int smallestCommonElement(vector<vector<int>>& mat) { // values could be duplicated in each row unordered_set<int> intersections(mat[0].cbegin(), mat[0].cend()); for (int i = 1; i < mat.size(); ++i) { const auto a = move(intersections); const unordered_set<int> b(mat[i].cbegin(), mat[i].cend()); copy_if(a.cbegin(), a.cend(), inserter(intersections, intersections.begin()), [&b](const int x){ return b.count(x); }); if (intersections.empty()) { return -1; } } return *min_element(intersections.cbegin(), intersections.cend()); } }; // Time: O(m * n) // Space: O(n) class Solution2 { public: int smallestCommonElement(vector<vector<int>>& mat) { // assumed value is unique in each row unordered_map<int, int> counter; for (const auto& row : mat) { for (const auto& c : row) { ++counter[c]; if (counter[c] == mat.size()) { return c; } } } return -1; } };
611
571
<reponame>ManiLikhdhari/camelinaction2 package camelinaction; import java.util.ArrayList; import java.util.List; import org.apache.camel.test.spring.CamelSpringTestSupport; import org.junit.Test; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class OrderRouterTest extends CamelSpringTestSupport { private static final String ORDER = "<order name=\"motor\" amount=\"1\" customer=\"honda\"/>"; @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("META-INF/spring/camel-context.xml"); } @Test public void testSendToFtpAndWebService() throws Exception { template.sendBody("ftp://rider@localhost:21000/order?password=<PASSWORD>", ORDER); List<Object> params = new ArrayList<Object>(); params.add("motor"); params.add(1); params.add("honda"); String reply = template.requestBody("cxf:bean:orderEndpoint", params, String.class); assertEquals("OK", reply); Thread.sleep(2000); // should see output on console now } }
455
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/Message.framework/MailServices/IMAP.framework/IMAP */ #import <IMAP/IMAP-Structs.h> #import <IMAP/XXUnknownSuperclass.h> @class NSString, MFIMAPFetchResult, NSDictionary, NSArray; @interface MFIMAPResponse : XXUnknownSuperclass { unsigned _responseType : 8; // 4 = 0x4 NSString *_tag; // 8 = 0x8 NSDictionary *_keyValuePairs; // 12 = 0xc IMAPResponseData _data; // 16 = 0x10 } @property(assign) int responseType; // G=0x14df5; S=0x14e05; converted property @property(retain) NSString *tag; // G=0x14e75; S=0x17925; converted property @property(retain) id capabilities; // G=0x1a8ad; S=0x1a7bd; converted property @property(retain) id serverInfo; // G=0x1a701; S=0x1a60d; converted property @property(assign) unsigned long number; // G=0x1a529; S=0x1a449; converted property @property(retain) id flags; // G=0x1a391; S=0x1a2ad; converted property @property(retain) id searchResults; // G=0x19e7d; S=0x19d99; converted property @property(retain) id fetchResults; // G=0x199ed; S=0x19905; converted property @property(assign) int uidFlagsChange; // G=0x193dd; S=0x19311; converted property @property(retain) id uids; // G=0x19259; S=0x19169; converted property @property(retain) id flagsFetchResult; // G=0x190ad; S=0x18fb9; converted property @property(readonly, retain) NSDictionary *keyValuePairs; // G=0x17b1d; converted property // converted property getter: - (int)responseType; // 0x14df5 // converted property setter: - (void)setResponseType:(int)type; // 0x14e05 - (BOOL)isUntagged; // 0x14e15 - (BOOL)isAlertResponse; // 0x1790d - (BOOL)isResponseWithCode:(int)code; // 0x14e45 // converted property getter: - (id)tag; // 0x14e75 // converted property setter: - (void)setTag:(id)tag; // 0x17925 - (void)dealloc; // 0x186b5 - (int)responseCode; // 0x1adfd - (id)responseInfo; // 0x1acd5 - (id)userData; // 0x1abad - (id)userString; // 0x1ab2d - (void)setUserData:(id)data responseCode:(int)code responseInfo:(id)info; // 0x1a965 // converted property getter: - (id)capabilities; // 0x1a8ad // converted property setter: - (void)setCapabilities:(id)capabilities; // 0x1a7bd // converted property getter: - (id)serverInfo; // 0x1a701 // converted property setter: - (void)setServerInfo:(id)info; // 0x1a60d // converted property getter: - (unsigned long)number; // 0x1a529 // converted property setter: - (void)setNumber:(unsigned long)number; // 0x1a449 // converted property getter: - (id)flags; // 0x1a391 // converted property setter: - (void)setFlags:(id)flags; // 0x1a2ad - (id)mailboxName; // 0x1a159 - (id)statusEntries; // 0x1a09d - (void)setMailboxName:(id)name statusEntries:(id)entries; // 0x19f35 // converted property getter: - (id)searchResults; // 0x19e7d // converted property setter: - (void)setSearchResults:(id)results; // 0x19d99 - (unsigned long)mailboxAttributes; // 0x19cdd - (id)separator; // 0x19bc5 - (void)setMailboxAttributes:(unsigned long)attributes separator:(id)separator mailboxName:(id)name extraAttributes:(id)attributes4; // 0x19a61 - (id)extraAttributes; // 0x14e85 - (id)permanentTag; // 0x179d1 - (id)fetchResultWithType:(int)type; // 0x17a2d // converted property getter: - (id)fetchResults; // 0x199ed // converted property setter: - (void)setFetchResults:(id)results; // 0x19905 - (id)quotaRootNames; // 0x19849 - (void)setMailboxName:(id)name quotaRootNames:(id)names; // 0x1972d - (id)quotaRootName; // 0x19675 - (id)quotas; // 0x195b9 - (void)setQuotaRootName:(id)name quotas:(id)quotas; // 0x1949d // converted property getter: - (int)uidFlagsChange; // 0x193dd // converted property setter: - (void)setUidFlagsChange:(int)change; // 0x19311 // converted property getter: - (id)uids; // 0x19259 // converted property setter: - (void)setUids:(id)uids; // 0x19169 // converted property getter: - (id)flagsFetchResult; // 0x190ad // converted property setter: - (void)setFlagsFetchResult:(id)result; // 0x18fb9 - (id)responseName; // 0x18f01 - (id)parameters; // 0x18e45 - (void)setValue:(id)value forKey:(id)key; // 0x17aa5 // converted property getter: - (id)keyValuePairs; // 0x17b1d - (void)setResponseName:(id)name parameters:(id)parameters; // 0x18d1d - (id)description; // 0x17b55 - (id)initWithConnection:(id)connection; // 0x18a81 - (id)initWithString:(id)string; // 0x18809 @end
1,697
528
<reponame>egorodet/MethaneK<filename>Modules/Graphics/Core/Sources/Methane/Graphics/Vulkan/BufferVK.h /****************************************************************************** Copyright 2019-2020 <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. ******************************************************************************* FILE: Methane/Graphics/Vulkan/BufferVK.h Vulkan implementation of the buffer interface. ******************************************************************************/ #pragma once #include "ResourceVK.hpp" #include <Methane/Graphics/BufferBase.h> #include <Methane/Graphics/Types.h> #include <vulkan/vulkan.hpp> namespace Methane::Graphics { class BufferVK final : public ResourceVK<BufferBase, vk::Buffer> { public: BufferVK(const ContextBase& context, const Settings& settings, const DescriptorByUsage& descriptor_by_usage = DescriptorByUsage()); // Resource interface void SetData(const SubResources& sub_resources, CommandQueue* sync_cmd_queue) override; private: vk::UniqueBuffer m_vk_unique_staging_buffer; vk::UniqueDeviceMemory m_vk_unique_staging_memory; std::vector<vk::BufferCopy> m_vk_copy_regions; }; class BufferSetVK final : public BufferSetBase { public: BufferSetVK(Buffer::Type buffers_type, const Refs<Buffer>& buffer_refs); const std::vector<vk::Buffer>& GetNativeBuffers() const noexcept { return m_vk_buffers; } const std::vector<vk::DeviceSize>& GetNativeOffsets() const noexcept { return m_vk_offsets; } private: std::vector<vk::Buffer> m_vk_buffers; std::vector<vk::DeviceSize> m_vk_offsets; }; } // namespace Methane::Graphics
661
3,212
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.reporting.sql.util; import org.apache.nifi.controller.status.ConnectionStatus; import org.apache.nifi.controller.status.ProcessGroupStatus; import org.apache.nifi.reporting.ReportingContext; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; public class ConnectionStatusRecursiveIterator implements Iterator<ConnectionStatus> { private final ReportingContext context; private Deque<Iterator<ProcessGroupStatus>> iteratorBreadcrumb; private Iterator<ConnectionStatus> connectionStatusIterator; private ConnectionStatus currentRow; public ConnectionStatusRecursiveIterator(final ReportingContext context) { this.context = context; iteratorBreadcrumb = new LinkedList<>(); } @Override public boolean hasNext() { if (iteratorBreadcrumb.isEmpty()) { // Start the breadcrumb trail to follow recursively into process groups looking for connections ProcessGroupStatus rootStatus = context.getEventAccess().getControllerStatus(); iteratorBreadcrumb.push(rootStatus.getProcessGroupStatus().iterator()); connectionStatusIterator = rootStatus.getConnectionStatus().iterator(); } currentRow = getNextConnectionStatus(); return (currentRow != null); } @Override public ConnectionStatus next() { if (currentRow != null) { final ConnectionStatus result = currentRow; currentRow = null; return result; } if (hasNext()) { ConnectionStatus result = currentRow; currentRow = null; return result; } else { return null; } } private ConnectionStatus getNextConnectionStatus() { if (connectionStatusIterator != null && connectionStatusIterator.hasNext()) { return connectionStatusIterator.next(); } // No more connections in this PG, so move to the next connectionStatusIterator = null; Iterator<ProcessGroupStatus> i = iteratorBreadcrumb.peek(); if (i == null) { return null; } if (i.hasNext()) { ProcessGroupStatus nextPG = i.next(); iteratorBreadcrumb.push(nextPG.getProcessGroupStatus().iterator()); connectionStatusIterator = nextPG.getConnectionStatus().iterator(); return getNextConnectionStatus(); } else { // No more child PGs, remove it from the breadcrumb trail and try again iteratorBreadcrumb.pop(); return getNextConnectionStatus(); } } }
1,175
2,151
<filename>third_party/angle/third_party/glmark2/src/src/gl-state.h /* * Copyright © 2013 Canonical Ltd * * This file is part of the glmark2 OpenGL (ES) 2.0 benchmark. * * glmark2 is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * glmark2 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 * glmark2. If not, see <http://www.gnu.org/licenses/>. * * Authors: * <NAME> */ #ifndef GLMARK2_GL_STATE_H_ #define GLMARK2_GL_STATE_H_ class GLVisualConfig; class GLState { public: virtual ~GLState() {} virtual bool init_display(void *native_display, GLVisualConfig& config_pref) = 0; virtual bool init_surface(void *native_window) = 0; virtual bool init_gl_extensions() = 0; virtual bool valid() = 0; virtual bool reset() = 0; virtual void swap() = 0; virtual bool gotNativeConfig(int& vid) = 0; virtual void getVisualConfig(GLVisualConfig& vc) = 0; }; #endif /* GLMARK2_GL_STATE_H_ */
449
1,008
<reponame>Mshuu/Pizzly { "name": "Microsoft Teams", "image": "https://upload.wikimedia.org/wikipedia/commons/c/c9/Microsoft_Office_Teams_%282018%E2%80%93present%29.svg", "auth": { "authorizationURL": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", "tokenURL": "https://login.microsoftonline.com/common/oauth2/v2.0/token", "authType": "OAUTH2" }, "request": { "baseURL": "https://graph.microsoft.com/v1.0/", "headers": { "Accept": "application/json", "Authorization": "Bearer ${auth.accessToken}", "User-Agent": "Pizzly" } } }
256
461
<gh_stars>100-1000 #include "socketthread.h" #include "config.h" SocketThread::SocketThread():QThread () { } void SocketThread::run(){ tcpServer=new TCPServer(Config::port,Config::ip,5); tcpServer->loop(); } void SocketThread::endThread(){ tcpServer->close_socket(); } SocketThread::~SocketThread(){ delete this->tcpServer; }
127
789
/*- * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SRC_LIBUTIL_SQLITE_UTILS_H_ #define SRC_LIBUTIL_SQLITE_UTILS_H_ #include "config.h" #include "mem_pool.h" #include "sqlite3.h" #define RSPAMD_SQLITE3_STMT_MULTIPLE (1 << 0) #ifdef __cplusplus extern "C" { #endif struct rspamd_sqlite3_prstmt { gint idx; const gchar *sql; const gchar *args; sqlite3_stmt *stmt; gint result; const gchar *ret; gint flags; }; /** * Create prepared statements for specified database from init statements * @param db * @param max_idx * @param err * @return new prepared statements array or NULL */ GArray *rspamd_sqlite3_init_prstmt (sqlite3 *db, struct rspamd_sqlite3_prstmt *init_stmt, gint max_idx, GError **err); /** * Run prepared statements by its index getting parameters and setting results from * varargs structure * @param db * @param stmts * @param idx * @return */ gint rspamd_sqlite3_run_prstmt (rspamd_mempool_t *pool, sqlite3 *db, GArray *stmts, gint idx, ...); /** * Close and free prepared statements * @param db * @param stmts */ void rspamd_sqlite3_close_prstmt (sqlite3 *db, GArray *stmts); /** * Creates or opens sqlite database trying to share it between processes * @param path * @param create_sql * @return */ sqlite3 *rspamd_sqlite3_open_or_create (rspamd_mempool_t *pool, const gchar *path, const gchar *create_sql, guint32 version, GError **err); /** * Sync sqlite3 db ensuring that all wal things are done * @param db */ gboolean rspamd_sqlite3_sync (sqlite3 *db, gint *wal_frames, gint *wal_checkpoints); #ifdef __cplusplus } #endif #endif /* SRC_LIBUTIL_SQLITE_UTILS_H_ */
827
3,263
/* * Copyright 2020 Immutables Authors and Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.immutables.criteria.backend; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import org.immutables.criteria.expression.Expression; import org.immutables.criteria.expression.Path; import java.lang.reflect.Member; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; /** * Various implementations supporting {@link KeyExtractor} interface. Hides all * implementations in package-private class. */ final class KeyExtractors { /** * Extractor based on generic {@link Function}. Does not contain any key expression metadata */ static class Generic implements KeyExtractor { private final Class<?> entityType; private final Function<Object, Object> extractor; Generic(Class<?> entityType, Function<Object, Object> extractor) { this.entityType = entityType; this.extractor = Objects.requireNonNull(extractor, "extractor"); } @Override public Object extract(Object instance) { return extractor.apply(instance); } @Override public KeyMetadata metadata() { return new KeyMetadata() { @Override public boolean isExpression() { return false; } @Override public List<Expression> keys() { throw new UnsupportedOperationException("This extractor is defined for generic java function. " + "Key AST (as Expression) is unknown for " + entityType.getName() + " by current " + Generic.class.getSimpleName() + " extractor. Did you check isExpression() ?"); } @Override public boolean isKeyDefined() { return true; } }; } } /** * Empty extractor which always throws exceptions */ static class NoKey implements KeyExtractor { private final Class<?> entityType; NoKey(Class<?> entityType) { this.entityType = Objects.requireNonNull(entityType, "entityType"); } @Override public Object extract(Object instance) { throw new UnsupportedOperationException(String.format("Entity %s does not have a key defined. " + " extract() method is not supposed to be called on %s using this class (%s). " + "Did you check for metadata().isKeyDefined() ?", entityType.getName(), NoKey.class.getSimpleName(), instance == null ? null : instance.getClass().getSimpleName())); } @Override public KeyMetadata metadata() { return new KeyMetadata() { @Override public boolean isKeyDefined() { return false; } @Override public boolean isExpression() { return false; } @Override public List<Expression> keys() { return Collections.emptyList(); } }; } } /** * Extractor based on a single member (field or method) */ static class SingleMember implements KeyExtractor { private final Member member; private final List<Expression> keys; private final org.immutables.criteria.reflect.MemberExtractor extractor; SingleMember(Class<?> entityType, Member member) { this.member = Objects.requireNonNull(member, "member"); this.keys = Collections.singletonList(Path.ofMember(member)); this.extractor = org.immutables.criteria.reflect.MemberExtractor.ofReflection(); } @Override public Object extract(Object instance) { return extractor.extract(member, instance); } @Override public KeyMetadata metadata() { return new KeyMetadata() { @Override public boolean isExpression() { return true; } @Override public List<Expression> keys() { return keys; } }; } } static class MultipleMembers implements KeyExtractor { private final Class<?> entityType; private final List<Member> members; private final List<Expression> keys; private final org.immutables.criteria.reflect.MemberExtractor extractor; MultipleMembers(Class<?> entityType, List<Member> members) { this.entityType = Objects.requireNonNull(entityType, "entityType"); Preconditions.checkArgument(!members.isEmpty(), "No keys defined for %s", entityType); this.members = ImmutableList.copyOf(members); this.keys = ImmutableList.copyOf(members.stream().map(Path::ofMember).collect(Collectors.toList())); this.extractor = org.immutables.criteria.reflect.MemberExtractor.ofReflection(); } @Override public Object extract(Object instance) { return members.stream() .map(m -> extractor.extract(m, instance)) .collect(Collectors.toList()); } @Override public KeyMetadata metadata() { return new KeyMetadata() { @Override public boolean isExpression() { return true; } @Override public List<Expression> keys() { return keys; } }; } } private KeyExtractors() {} }
2,062
2,487
<reponame>lichongbing/lswagger /* * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD. * All rights reserved. * Official Web Site: http://www.xiaominfo.com. * Developer Web Site: http://open.xiaominfo.com. */ package com.github.xiaoymin.knife4j.aggre.nacos; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.StrUtil; import com.github.xiaoymin.knife4j.aggre.core.ext.PoolingConnectionManager; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.Callable; /** * @author <a href="mailto:<EMAIL>"><EMAIL></a> * 2020/11/18 9:36 * @since:knife4j-aggregation-spring-boot-starter 2.0.8 */ public class NacosService extends PoolingConnectionManager implements Callable<Optional<NacosInstance>> { Logger logger= LoggerFactory.getLogger(NacosService.class); /** * Nacos获取实例列表OpenAPI接口,详情参考:https://nacos.io/zh-cn/docs/open-api.html */ private static final String NACOS_INSTANCE_LIST_API="/v1/ns/instance/list"; /** * 登录接口 */ public static final String NACOS_LOGIN="/v1/auth/login"; /** * 服务名称 */ private final String serviceUrl; /** * nacos密钥 */ private final String accessToken; /** * Nacos配置 */ private final NacosRoute nacosRoute; public NacosService(String serviceUrl, String accessToken, NacosRoute nacosRoute) { this.serviceUrl = serviceUrl; this.accessToken = accessToken; this.nacosRoute = nacosRoute; } @Override public Optional<NacosInstance> call() throws Exception { List<String> params=new ArrayList<>(); params.add("serviceName="+nacosRoute.getServiceName()); //默认聚合时只返回健康实例 params.add("healthyOnly=true"); if (StrUtil.isNotBlank(nacosRoute.getGroupName())){ params.add("groupName="+nacosRoute.getGroupName()); } if (StrUtil.isNotBlank(nacosRoute.getNamespaceId())){ params.add("namespaceId="+nacosRoute.getNamespaceId()); } if (StrUtil.isNotBlank(nacosRoute.getClusters())){ params.add("clusters="+nacosRoute.getClusters()); } //是否需要登录token if (StrUtil.isNotBlank(this.accessToken)){ params.add("accessToken="+this.accessToken); } String parameter=CollectionUtil.join(params,"&"); String api=serviceUrl+NACOS_INSTANCE_LIST_API+"?"+parameter; HttpGet get=new HttpGet(api); CloseableHttpResponse response=getClient().execute(get); if (response!=null){ int statusCode=response.getStatusLine().getStatusCode(); logger.info("Nacos Response Status:{}",statusCode); if (statusCode== HttpStatus.SC_OK){ String content= EntityUtils.toString(response.getEntity(),"UTF-8"); if (StrUtil.isNotBlank(content)){ JsonElement jsonElement=JsonParser.parseString(content); if (jsonElement!=null&&jsonElement.isJsonObject()){ JsonElement instances=jsonElement.getAsJsonObject().get("hosts"); if (instances!=null&&instances.isJsonArray()){ Type type=new TypeToken<List<NacosInstance>>(){}.getType(); List<NacosInstance> nacosInstances=new Gson().fromJson(instances,type); if (CollectionUtil.isNotEmpty(nacosInstances)){ NacosInstance nacosInstance=nacosInstances.stream().findAny().get(); nacosInstance.setServiceName(nacosRoute.getServiceName()); return Optional.of(nacosInstance); } } } } }else{ get.abort(); } } IoUtil.close(response); return Optional.empty(); } }
2,112
375
/* Copyright (c) 2014, Intel Corporation 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "device/cpu/core/layer_convolution_avx2_batch24n.h" #include "device/cpu/core/layer_convolution_avx2_forward.h" #include "device/cpu/api_internal/data_helper.h" #include "tester/g_ult/unit_tests/cpu/naive_implementations.h" #include "cpu/test_helpers.h" #include <cfloat> #include <iostream> #include <gtest/gtest.h> const uint32_t C_simd_width = sizeof(__m256)/sizeof(float); const uint32_t C_slice_size = 2 * C_simd_width; namespace { using namespace convolution; struct TestStride : Stride { TestStride(Value<Rows, uint64_t> rows = make<Rows>(0), Value<Cols, uint64_t> cols = make<Cols>(0)) : Stride({rows, cols}) {} }; struct DataPair { std::vector<float> naive; std::unique_ptr<nn::workload_data<nn::layout_f32>> impl; }; std::shared_ptr<DataPair> make_output(uint32_t batch, uint32_t width, uint32_t height, uint32_t feats) { auto ret = std::make_shared<DataPair>(); ret->impl = decltype(ret->impl)( nn::data_helper<NN_WORKLOAD_DATA_TAG_NBLOCKZXYN, nn::layout_f32>::create( (batch + BATCH_ACCEPTED_BLOCK - 1) / BATCH_ACCEPTED_BLOCK * BATCH_ACCEPTED_BLOCK, width, height, feats, BATCH_ACCEPTED_BLOCK)); memset(ret->impl->parent->data_buffer, 0, sizeof(float) * ret->impl->parent->lengths.size()); ret->naive = decltype(ret->naive)(batch * width * height * feats, 0); return ret; } std::shared_ptr<DataPair> make_input(uint32_t batch, uint32_t width, uint32_t height, uint32_t feats) { auto batch_block_size = BATCH_ACCEPTED_BLOCK; auto ret = make_output(batch, width, height, feats); std::vector<float> aux(ret->naive.size()); randomizeWithAny(aux.begin(), aux.end(), -10.0, 10.0, batch * width * height * feats); auto it = aux.begin(); for (uint32_t b = 0; b < batch; ++b) for (uint32_t y = 0; y < height; ++y) for (uint32_t x = 0; x < width; ++x) for (uint32_t f = 0; f < feats; ++f) { ult_nn_naive_convolve_set_input_value( &ret->naive.front(), width, height, feats, b, x, y, f, *it); auto batch_block = b / batch_block_size; auto pic_in_block = b % batch_block_size; ret->impl->at(batch_block, x, y, f, pic_in_block, 0) = *it; ++it; } return ret; } std::shared_ptr<DataPair> make_bias(uint32_t feats) { auto ret = std::make_shared<DataPair>(); ret->impl = decltype(ret->impl)( nn::data_helper<NN_WORKLOAD_DATA_TAG_O, nn::layout_f32>::create(nullptr, feats, false)); ret->naive = decltype(ret->naive)(feats, 0); randomizeWithAny(ret->naive.begin(), ret->naive.end(), -10.0, 10.0, feats); for (uint32_t x = 0; x < feats; ++x) ret->impl->at(0, x, 0, 0, 0, 0) = ret->naive[x]; return ret; } std::shared_ptr<DataPair> make_kernel(uint32_t width, uint32_t height, uint32_t in_feats, uint32_t out_feats) { auto outfeats_block_size = OUTPUT_ACCEPTED_MOD; auto ret = std::make_shared<DataPair>(); ret->impl = decltype(ret->impl)( nn::data_helper<NN_WORKLOAD_DATA_TAG_OBLOCKIOXY, nn::layout_f32>::create( width, height, in_feats, out_feats, OUTPUT_ACCEPTED_MOD)); ret->naive = decltype(ret->naive)(width * height * in_feats * out_feats, 0); std::vector<float> aux(ret->naive.size()); randomizeWithAny(aux.begin(), aux.end(), -10.0, 10.0, width * height * in_feats * out_feats); auto it = aux.begin(); for (uint32_t p = 0; p < out_feats; ++p) for (uint32_t y = 0; y < height; ++y) for (uint32_t x = 0; x < width; ++x) for (uint32_t z = 0; z < in_feats; ++z) { ult_nn_naive_convolve_set_kernel_value( &ret->naive.front(), width, height, in_feats, x, y, z, p, *it); ret->impl->at(0, x, y, z, p % outfeats_block_size, p / outfeats_block_size) = *it; ++it; } return ret; } struct InitializedConv { nn_device_internal internal_device; std::shared_ptr<layer::convolution_f32_batch24n> primitive; InitializedConv(const nn_workload_data_coords_t& kernel_coords, const uint_least32_t& calculated_in_feats, const nn_workload_data_coords_t& output_coords, Stride stride, uint_least32_t batch_size, NN_ACTIVATION_FUNCTION activation) : internal_device() { uint32_t center_offset_x = (kernel_coords.t[NN_DATA_COORD_x]) / 2; uint32_t center_offset_y = (kernel_coords.t[NN_DATA_COORD_y]) / 2; primitive = decltype(primitive)(new layer::convolution_f32_batch24n( make<Batch>(batch_size), OutputDimensions{make<OutputHeight>(output_coords.t[NN_DATA_COORD_y]), make<OutputWidth>(output_coords.t[NN_DATA_COORD_x]), make<OutputFeats>(output_coords.t[NN_DATA_COORD_z])}, KernelInfo{KernelDimensions{make<KernelHeight>(kernel_coords.t[NN_DATA_COORD_y]), make<KernelWidth>(kernel_coords.t[NN_DATA_COORD_x]), make<KernelFeats>(calculated_in_feats)}, make<OutputFeats>(output_coords.t[NN_DATA_COORD_z]), KernelCenter{make<Rows>(center_offset_y), make<Cols>(center_offset_x)}, stride}, {activation}, &internal_device)); } }; void ult_nn_convolution_check_outputs( nn_workload_data_t* output, float* output_ref, uint_least32_t feats, uint_least32_t width, uint_least32_t height, uint_least32_t batch_size) { for (uint_least32_t pic = 0; pic < batch_size; pic++) { for (uint_least32_t outmapa = 0; outmapa < feats; outmapa++) { for (uint_least32_t row = 0; row < height; row++) { for (uint_least32_t column = 0; column < width; column++) { float ref_value = ult_nn_naive_convolve_get_output_value( output_ref, width, height, feats, pic, column, row, outmapa); auto batch_block = pic / BATCH_ACCEPTED_BLOCK; auto pic_in_block = pic % BATCH_ACCEPTED_BLOCK; float value = nn_workload_data_get<float>( output, batch_block, column, row, outmapa, pic_in_block, 0); ASSERT_FLOAT_CHECK(ref_value, value) << " pic: " << pic << " outmapa: " << outmapa << " row: " << row << " column: " << column; } } } } } void ult_perform_test( uint_least32_t batch_size, uint_least32_t out_feats, uint_least32_t in_feats, uint_least32_t input_width, uint_least32_t input_height, uint_least32_t kernel_width, uint_least32_t kernel_height, Stride stride, NN_ACTIVATION_FUNCTION activation ) { uint32_t out_width = (input_width + stride.cols - 1) / stride.cols; uint32_t out_height = (input_height + stride.rows - 1) / stride.rows; auto input = make_input(batch_size, input_width, input_height, in_feats); auto output = make_output(batch_size, out_width, out_height, out_feats); auto kernel = make_kernel(kernel_width, kernel_height, in_feats, out_feats); auto bias = make_bias(out_feats); ult_nn_naive_convolve_all_pics( &input->naive.front(), &output->naive.front(), &kernel->naive.front(), &bias->naive.front(), batch_size, out_feats, in_feats, out_width, out_height, input_width, input_height, kernel_width, kernel_height, stride.cols, stride.rows, kernel_width / 2, kernel_height / 2); if (activation == NN_ACTIVATION_FUNCTION_RELU) for (auto& val: output->naive) val = std::max(0.0f, val); InitializedConv conv(kernel->impl->parent->lengths, in_feats, output->impl->parent->lengths, stride, (batch_size + BATCH_ACCEPTED_BLOCK - 1) / BATCH_ACCEPTED_BLOCK * BATCH_ACCEPTED_BLOCK, activation); conv.primitive->prepare_forward({input->impl.get()}, {kernel->impl.get(), bias->impl.get()}, {output->impl.get()}); conv.primitive->forward({input->impl.get()}, {kernel->impl.get(), bias->impl.get()}, {output->impl.get()}); ASSERT_NO_FATAL_FAILURE(ult_nn_convolution_check_outputs( output->impl.get(), &output->naive.front(), out_feats, out_width, out_height, batch_size)) << " batch: " << batch_size << ", " << " out_feats: " << out_feats << ", " << " in_feats: " << in_feats << ", " << " in_width: " << input_width << ", " << " in_height: " << input_height << ", " << " kernel_width: " << kernel_width << ", " << " kernel_height: " << kernel_height << ", " << " col_stride: " << stride.cols << ", " << " row_stride: " << stride.rows << ", " << " activation: " << activation; } struct Padding { uint_least32_t top; uint_least32_t bottom; uint_least32_t left; uint_least32_t right; uint_least32_t in_depth_start; uint_least32_t in_depth_end; uint_least32_t out_depth_start; uint_least32_t out_depth_end; }; void ult_perform_padding_test( uint_least32_t out_size, uint_least32_t kernel_size, Stride stride, Padding padding) { uint_least32_t truncated_out_feats = 19; uint_least32_t out_feats = truncated_out_feats + padding.out_depth_start + padding.out_depth_end; uint_least32_t truncated_in_feats = 4; uint_least32_t in_feats = padding.in_depth_start + padding.in_depth_end + truncated_in_feats; uint_least32_t batch_size = 24u; uint_least32_t input_height = padding.top + padding.bottom + stride.rows * out_size; uint_least32_t input_width = padding.left + padding.right + stride.cols * out_size; auto input = make_input(batch_size, input_width, input_height, in_feats); auto output_naive = make_output(batch_size, input_width, input_height, truncated_out_feats); auto output_fast = make_output(batch_size, out_size, out_size, out_feats); auto kernel_naive = make_kernel(kernel_size, kernel_size, in_feats, truncated_out_feats); auto kernel_fast = make_kernel(kernel_size, kernel_size, truncated_in_feats, truncated_out_feats); auto bias = make_bias(truncated_out_feats); auto outfeats_block_size = OUTPUT_ACCEPTED_MOD; for (auto y = 0u; y < kernel_size; ++y) for (auto x = 0u; x < kernel_size; ++x) for (auto z = 0u; z < truncated_in_feats; ++z) for (auto o = 0u; o < truncated_out_feats; ++o) kernel_fast->impl->at(0, x, y, z, o % outfeats_block_size, o / outfeats_block_size) = kernel_naive->impl->at(0, x, y, z + padding.in_depth_start, o % outfeats_block_size, o / outfeats_block_size); for (uint32_t b = 0; b < batch_size; ++b) for (uint32_t y = 0; y < input_height; ++y) for (uint32_t x = 0; x < input_width; ++x) for (uint32_t f = 0; f < in_feats; ++f) if ((f < padding.in_depth_start) or (f > in_feats - padding.in_depth_end - 1)) ult_nn_naive_convolve_set_input_value( &input->naive.front(), input_width, input_height, in_feats, b, x, y, f, 0); ult_nn_naive_convolve_all_pics( &input->naive.front(), &output_naive->naive.front(), &kernel_naive->naive.front(), &bias->naive.front(), batch_size, truncated_out_feats, in_feats, input_width, input_height, input_width, input_height, kernel_size, kernel_size, 1, 1, kernel_size / 2, kernel_size / 2); auto input_view = std::make_shared<nn::workload_data<nn::layout_f32>>( *input->impl, nn_workload_data_coords_t(0, padding.left, padding.top, padding.in_depth_start, 0, 0), nn_workload_data_coords_t(input->impl->get_length(NN_DATA_COORD_n) - 1, input_width - padding.right - 1, input_height - padding.bottom - 1, in_feats - padding.in_depth_end - 1, input->impl->get_length(NN_DATA_COORD_p) - 1, input->impl->get_length(NN_DATA_COORD_q) - 1)); auto output_view = std::make_shared<nn::workload_data<nn::layout_f32>>( *output_fast->impl, nn_workload_data_coords_t(0, 0, 0, padding.out_depth_start, 0, 0), nn_workload_data_coords_t(output_fast->impl->get_length(NN_DATA_COORD_n) - 1, output_fast->impl->get_length(NN_DATA_COORD_x) - 1, output_fast->impl->get_length(NN_DATA_COORD_y) - 1, out_feats - padding.out_depth_end - 1, output_fast->impl->get_length(NN_DATA_COORD_p) - 1, output_fast->impl->get_length(NN_DATA_COORD_q) - 1)); ASSERT_EQ(stride.rows * out_size, input_view->get_length(NN_DATA_COORD_y)); ASSERT_EQ(stride.cols * out_size, input_view->get_length(NN_DATA_COORD_x)); ASSERT_EQ(in_feats - padding.in_depth_start - padding.in_depth_end, input_view->get_length(NN_DATA_COORD_z)); InitializedConv conv(kernel_fast->impl->parent->lengths, in_feats - padding.in_depth_start - padding.in_depth_end, output_view->get_length(), stride, batch_size, NN_ACTIVATION_FUNCTION_NONE); conv.primitive->prepare_forward({input_view.get()}, {kernel_fast->impl.get(), bias->impl.get()}, {output_view.get()}); conv.primitive->forward({input_view.get()}, {kernel_fast->impl.get(), bias->impl.get()}, {output_view.get()}); for (uint_least32_t pic = 0; pic < batch_size; pic++) { for (uint_least32_t outmapa = 0; outmapa < truncated_out_feats; outmapa++) { for (uint_least32_t row = 0; row < out_size; row++) { for (uint_least32_t column = 0; column < out_size; column++) { float ref_value = ult_nn_naive_convolve_get_output_value( &output_naive->naive.front(), input_width, input_height, truncated_out_feats, pic, column * stride.cols + padding.left, row * stride.rows + padding.top, outmapa); auto batch_block = pic / BATCH_ACCEPTED_BLOCK; auto pic_in_block = pic % BATCH_ACCEPTED_BLOCK; float value = nn_workload_data_get<float>( output_view.get(), batch_block, column, row, outmapa, pic_in_block, 0); ASSERT_FLOAT_CHECK(ref_value, value) << " pic: " << pic << " outmapa: " << outmapa << " row: " << row << " column: " << column; } } } } } struct InputSize { uint_least32_t width; uint_least32_t height; }; struct KernelSize { uint_least32_t width; uint_least32_t height; }; typedef std::tuple< uint_least32_t, //out_feats uint_least32_t, //in_feats uint_least32_t, //batch NN_ACTIVATION_FUNCTION, InputSize, KernelSize, TestStride > ArtificialConvStrideParams; struct CpuConvolutionArtificial : ::testing::TestWithParam<ArtificialConvStrideParams> { }; TEST(CpuConvolutionArtificial, cpu_convolution_stride_example) { ult_perform_test(1, 8, 1, 3, 3, 2, 2, {make<Rows>(1), make<Cols>(1)}, NN_ACTIVATION_FUNCTION_NONE); } TEST_P(CpuConvolutionArtificial, cpu_convolution_stride) { ult_perform_test( std::get<2>(GetParam()), //batch std::get<0>(GetParam()), //ofeats std::get<1>(GetParam()), //infeats std::get<4>(GetParam()).width, //input std::get<4>(GetParam()).height, //input std::get<5>(GetParam()).width, //kernel std::get<5>(GetParam()).height, //kernel std::get<6>(GetParam()), //stride std::get<3>(GetParam()) //activation ); } INSTANTIATE_TEST_CASE_P(CpuConvolutionArtificialInst, CpuConvolutionArtificial, ::testing::Combine( ::testing::Values(8u, 16u), //ofeats ::testing::Values(4u), //ifeats ::testing::Values(1u, 8u), //batch ::testing::Values(NN_ACTIVATION_FUNCTION_NONE, NN_ACTIVATION_FUNCTION_RELU), ::testing::Values(InputSize{3, 3}, InputSize{8, 8}, InputSize{16, 16}, InputSize{32, 32}), ::testing::Values(KernelSize{1, 1}, KernelSize{2, 2}, KernelSize{3, 2}, KernelSize{2, 3}, KernelSize{1, 1}, KernelSize{1, 2}, KernelSize{2, 1}, KernelSize{3, 1}, KernelSize{3, 3}), ::testing::Values(TestStride(make<Rows>(1), make<Cols>(1)), TestStride(make<Rows>(2), make<Cols>(2)), TestStride(make<Rows>(3), make<Cols>(3)), TestStride(make<Rows>(4), make<Cols>(4)), TestStride(make<Rows>(2), make<Cols>(3)), TestStride(make<Rows>(4), make<Cols>(3))))); TEST(cpu_convolution_real, cpu_convolution_LeNet5) { ult_perform_test(1, 8, 1, 32, 32, 5, 5, {make<Rows>(1), make<Cols>(1)}, NN_ACTIVATION_FUNCTION_NONE); ult_perform_test(1, 16, 8, 14, 14, 5, 5, {make<Rows>(1), make<Cols>(1)}, NN_ACTIVATION_FUNCTION_NONE); ult_perform_test(1, 120, 16, 5, 5, 5, 5, {make<Rows>(1), make<Cols>(1)}, NN_ACTIVATION_FUNCTION_NONE); ult_perform_test(8, 8, 1, 32, 32, 5, 5, {make<Rows>(1), make<Cols>(1)}, NN_ACTIVATION_FUNCTION_NONE); ult_perform_test(8, 16, 8, 14, 14, 5, 5, {make<Rows>(1), make<Cols>(1)}, NN_ACTIVATION_FUNCTION_NONE); ult_perform_test(8, 120, 16, 5, 5, 5, 5, {make<Rows>(1), make<Cols>(1)}, NN_ACTIVATION_FUNCTION_NONE); } typedef std::tuple<uint_least32_t, //out_size uint_least32_t, //kernel_size TestStride, Padding> ConvolutionPaddingParams; struct CpuConvolutionPadding : ::testing::TestWithParam<ConvolutionPaddingParams> { }; TEST_P(CpuConvolutionPadding, cpu_convolution_padding_stride) { ult_perform_padding_test( std::get<0>(GetParam()), //out size std::get<1>(GetParam()), //kernel size std::get<2>(GetParam()), //stride std::get<3>(GetParam())); } INSTANTIATE_TEST_CASE_P(CpuConvolutionPaddingInst, CpuConvolutionPadding, ::testing::Combine( ::testing::Values(1u, 2u, 3u), //out size ::testing::Values(1u, 2u, 3u), //kernel size ::testing::Values(TestStride(make<Rows>(1), make<Cols>(1)), TestStride(make<Rows>(3), make<Cols>(3)), TestStride(make<Rows>(4), make<Cols>(3))), ::testing::Values(Padding{2, 3, 2, 3, 0, 0, 0, 0}, Padding{1, 2, 2, 1, 2, 1, 1, 2}, Padding{0, 0, 3, 3, 0, 3, 0, 0}, Padding{3, 3, 0, 0, 1, 0, 0, 0}, Padding{1, 0, 0, 0, 0, 1, 1, 0}, Padding{0, 1, 0, 0, 2, 2, 0, 1}, Padding{0, 0, 1, 0, 3, 3, 3, 4}, Padding{0, 0, 0, 1, 1, 3, 2, 2}, Padding{1, 0, 2, 0, 3, 1, 2, 1}, Padding{0, 2, 0, 1, 1, 1, 1, 1}, Padding{4, 3, 2, 1, 5, 7, 7, 5}))); } //namespace
11,884
11,548
<reponame>UStarGao/mall-learning package com.macro.mall.tiny.service; import com.macro.mall.tiny.domain.AdminUserDetails; /** * 后台用于管理Service * Created by macro on 2020/10/15. */ public interface UmsAdminService { /** * 根据用户名获取用户信息 */ AdminUserDetails getAdminByUsername(String username); /** * 用户名密码登录 */ String login(String username, String password); }
198
785
<gh_stars>100-1000 #ifdef __OpenBSD__ #include <stdlib.h> #else #include <alloca.h> #endif #include <string.h> #include <stdio.h> static int foo(int n, const char *str) { char *data = alloca(n); memcpy(data, str, n); return printf("%s\n", data); } static const char hello[] = "Hello world!"; int main(void) { return foo(sizeof(hello), hello); }
145
2,978
<reponame>nonomal/CommonDevKnowledge package com.lzw.part1_creation_mode.builder.chainsaw; /** * 测试类 */ public class Test { public static void main(String[] args) { HardwareStoreBoss hardwareStoreBoss = new HardwareStoreBoss(); Chainsaws chainsaws = hardwareStoreBoss.notify(new ChainsawBuilderImpl()); System.out.println(chainsaws.toString()); // 新链锯 Chainsaws chainsaws2 = hardwareStoreBoss.notify(new ChainsawBuilderImpl2()); System.out.println(chainsaws2.toString()); } }
209
435
{ "description": "Tytu\u0142/Topic: PyCon PL 2014 \"Projekty sprz\u0119towe \u2013 bo nie tylko webem cz\u0142owiek \u017cyje\" [PL}\nPrelegent/Speaker: <NAME>\u0144ski \n\nRozw\u00f3j mobilnych urz\u0105dze\u0144 i post\u0119puj\u0105ca cyfryzacja \u017cycia, popularyzacja bezprzewodowego dost\u0119pu dost\u0119pu do internetu tworz\u0105 nowe rynki, na kt\u00f3rych startupy odnosz\u0105 sukcesy oferuj\u0105c nowe urz\u0105dzenia i us\u0142ugi oparte o istniej\u0105ce urz\u0105dzenia. Sama aplikacja internetowa, czy mobilna staje si\u0119 niewystarczaj\u0105ca by zaistnie\u0107 i zarobi\u0107. Czasami te\u017c mamy po prostu do\u015b\u0107 rutyny i chcemy zrobi\u0107 co\u015b nowego ;)\n\nhttp://pl.pycon.org/2014/pl/agenda", "duration": 2528, "language": "pol", "recorded": "2014-10-17", "speakers": [ "<NAME>\u0144ski" ], "thumbnail_url": "https://i.ytimg.com/vi/bZYyKGC8mC8/hqdefault.jpg", "title": "Projekty sprz\u0119towe \u2013 bo nie tylko webem cz\u0142owiek \u017cyje", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=bZYyKGC8mC8" } ] }
561
14,668
<reponame>zealoussnow/chromium // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/zucchini/rel32_finder.h" #include <algorithm> #include "base/numerics/safe_conversions.h" namespace zucchini { /******** Abs32GapFinder ********/ Abs32GapFinder::Abs32GapFinder(ConstBufferView image, ConstBufferView region, const std::vector<offset_t>& abs32_locations, size_t abs32_width) : base_(image.begin()), region_end_(region.end()), abs32_end_(abs32_locations.end()), abs32_width_(abs32_width) { DCHECK_GT(abs32_width, size_t(0)); DCHECK_GE(region.begin(), image.begin()); DCHECK_LE(region.end(), image.end()); const offset_t begin_offset = base::checked_cast<offset_t>(region.begin() - image.begin()); // Find the first |abs32_cur_| with |*abs32_cur_ >= begin_offset|. abs32_cur_ = std::lower_bound(abs32_locations.begin(), abs32_locations.end(), begin_offset); // Find lower boundary, accounting for the possibility that |abs32_cur_[-1]| // may straddle across |region.begin()|. cur_lo_ = region.begin(); if (abs32_cur_ > abs32_locations.begin()) cur_lo_ = std::max(cur_lo_, image.begin() + abs32_cur_[-1] + abs32_width_); } Abs32GapFinder::~Abs32GapFinder() = default; bool Abs32GapFinder::FindNext() { // Iterate over |[abs32_cur_, abs32_end_)| and emit segments. while (abs32_cur_ != abs32_end_ && base_ + *abs32_cur_ < region_end_) { ConstBufferView::const_iterator hi = base_ + *abs32_cur_; gap_ = ConstBufferView::FromRange(cur_lo_, hi); cur_lo_ = hi + abs32_width_; ++abs32_cur_; if (!gap_.empty()) return true; } // Emit final segment. if (cur_lo_ < region_end_) { gap_ = ConstBufferView::FromRange(cur_lo_, region_end_); cur_lo_ = region_end_; return true; } return false; } /******** Rel32Finder ********/ Rel32Finder::Rel32Finder(ConstBufferView image, const AddressTranslator& translator) : image_(image), offset_to_rva_(translator) {} Rel32Finder::~Rel32Finder() = default; void Rel32Finder::SetRegion(ConstBufferView region) { region_ = region; accept_it_ = region.begin(); } bool Rel32Finder::FindNext() { NextIterators next_iters = Scan(region_); if (next_iters.reject == nullptr) { region_.seek(region_.end()); return false; } region_.seek(next_iters.reject); accept_it_ = next_iters.accept; DCHECK_GE(accept_it_, region_.begin()); DCHECK_LE(accept_it_, region_.end()); return true; } void Rel32Finder::Accept() { region_.seek(accept_it_); } /******** Rel32FinderIntel ********/ Rel32Finder::NextIterators Rel32FinderIntel::SetResult( ConstBufferView::const_iterator cursor, uint32_t opcode_size, bool can_point_outside_section) { offset_t location = base::checked_cast<offset_t>((cursor + opcode_size) - image_.begin()); rva_t location_rva = offset_to_rva_.Convert(location); DCHECK_NE(location_rva, kInvalidRva); rva_t target_rva = location_rva + 4 + image_.read<uint32_t>(location); rel32_ = {location, target_rva, can_point_outside_section}; return {cursor + 1, cursor + (opcode_size + 4)}; } /******** Rel32FinderX86 ********/ Rel32Finder::NextIterators Rel32FinderX86::Scan(ConstBufferView region) { ConstBufferView::const_iterator cursor = region.begin(); while (cursor < region.end()) { // Heuristic rel32 detection by looking for opcodes that use them. if (cursor + 5 <= region.end()) { if (cursor[0] == 0xE8 || cursor[0] == 0xE9) // JMP rel32; CALL rel32 return SetResult(cursor, 1, false); } if (cursor + 6 <= region.end()) { if (cursor[0] == 0x0F && (cursor[1] & 0xF0) == 0x80) // Jcc long form return SetResult(cursor, 2, false); } ++cursor; } return {nullptr, nullptr}; } /******** Rel32FinderX64 ********/ Rel32Finder::NextIterators Rel32FinderX64::Scan(ConstBufferView region) { ConstBufferView::const_iterator cursor = region.begin(); while (cursor < region.end()) { // Heuristic rel32 detection by looking for opcodes that use them. if (cursor + 5 <= region.end()) { if (cursor[0] == 0xE8 || cursor[0] == 0xE9) // JMP rel32; CALL rel32 return SetResult(cursor, 1, false); } if (cursor + 6 <= region.end()) { if (cursor[0] == 0x0F && (cursor[1] & 0xF0) == 0x80) { // Jcc long form return SetResult(cursor, 2, false); } else if ((cursor[0] == 0xFF && (cursor[1] == 0x15 || cursor[1] == 0x25)) || ((cursor[0] == 0x89 || cursor[0] == 0x8B || cursor[0] == 0x8D) && (cursor[1] & 0xC7) == 0x05)) { // 6-byte instructions: // [2-byte opcode] [disp32]: // Opcode // FF 15: CALL QWORD PTR [rip+disp32] // FF 25: JMP QWORD PTR [rip+disp32] // // [1-byte opcode] [ModR/M] [disp32]: // Opcode // 89: MOV DWORD PTR [rip+disp32],reg // 8B: MOV reg,DWORD PTR [rip+disp32] // 8D: LEA reg,[rip+disp32] // ModR/M : MMRRRMMM // MM = 00 & MMM = 101 => rip+disp32 // RRR: selects reg operand from [eax|ecx|...|edi] return SetResult(cursor, 2, true); } } ++cursor; } return {nullptr, nullptr}; } /******** Rel32FinderArm ********/ template <typename ADDR_TYPE> Rel32FinderArm<ADDR_TYPE>::Rel32FinderArm(ConstBufferView image, const AddressTranslator& translator) : Rel32Finder(image, translator) {} template <typename ADDR_TYPE> Rel32FinderArm<ADDR_TYPE>::~Rel32FinderArm() = default; template <typename ADDR_TYPE> Rel32Finder::NextIterators Rel32FinderArm<ADDR_TYPE>::SetResult( Result&& result, ConstBufferView::const_iterator cursor, int instr_size) { rel32_ = result; return {cursor + instr_size, cursor + instr_size}; } // SetResult() for end of scan. template <typename ADDR_TYPE> Rel32Finder::NextIterators Rel32FinderArm<ADDR_TYPE>::SetEmptyResult() { rel32_ = {kInvalidOffset, kInvalidOffset, ADDR_TYPE::ADDR_NONE}; return {nullptr, nullptr}; } /******** Rel32FinderAArch32 ********/ Rel32FinderAArch32::Rel32FinderAArch32(ConstBufferView image, const AddressTranslator& translator, bool is_thumb2) : Rel32FinderArm(image, translator), is_thumb2_(is_thumb2) {} Rel32FinderAArch32::~Rel32FinderAArch32() = default; Rel32Finder::NextIterators Rel32FinderAArch32::ScanA32(ConstBufferView region) { // Guard against alignment potentially causing |cursor > region.end()|. if (region.size() < 4) return SetEmptyResult(); ConstBufferView::const_iterator cursor = region.begin(); cursor += IncrementForAlignCeil4(cursor - image_.begin()); for (; region.end() - cursor >= 4; cursor += 4) { offset_t offset = base::checked_cast<offset_t>(cursor - image_.begin()); AArch32Rel32Translator translator; rva_t instr_rva = offset_to_rva_.Convert(offset); uint32_t code32 = translator.FetchArmCode32(image_, offset); rva_t target_rva = kInvalidRva; if (translator.ReadA24(instr_rva, code32, &target_rva)) { return SetResult({offset, target_rva, AArch32Rel32Translator::ADDR_A24}, cursor, 4); } } return SetEmptyResult(); } Rel32Finder::NextIterators Rel32FinderAArch32::ScanT32(ConstBufferView region) { // Guard against alignment potentially causing |cursor > region.end()|. if (region.size() < 2) return SetEmptyResult(); ConstBufferView::const_iterator cursor = region.begin(); cursor += IncrementForAlignCeil2(cursor - image_.begin()); while (region.end() - cursor >= 2) { offset_t offset = base::checked_cast<offset_t>(cursor - image_.begin()); AArch32Rel32Translator translator; AArch32Rel32Translator::AddrType type = AArch32Rel32Translator::ADDR_NONE; rva_t instr_rva = offset_to_rva_.Convert(offset); uint16_t code16 = translator.FetchThumb2Code16(image_, offset); int instr_size = GetThumb2InstructionSize(code16); rva_t target_rva = kInvalidRva; if (instr_size == 2) { // 16-bit THUMB2 instruction. if (translator.ReadT8(instr_rva, code16, &target_rva)) type = AArch32Rel32Translator::ADDR_T8; else if (translator.ReadT11(instr_rva, code16, &target_rva)) type = AArch32Rel32Translator::ADDR_T11; } else { // |instr_size == 4|: 32-bit THUMB2 instruction. if (region.end() - cursor >= 4) { uint32_t code32 = translator.FetchThumb2Code32(image_, offset); if (translator.ReadT20(instr_rva, code32, &target_rva)) type = AArch32Rel32Translator::ADDR_T20; else if (translator.ReadT24(instr_rva, code32, &target_rva)) type = AArch32Rel32Translator::ADDR_T24; } } if (type != AArch32Rel32Translator::ADDR_NONE) return SetResult({offset, target_rva, type}, cursor, instr_size); cursor += instr_size; } return SetEmptyResult(); } Rel32Finder::NextIterators Rel32FinderAArch32::Scan(ConstBufferView region) { return is_thumb2_ ? ScanT32(region) : ScanA32(region); } /******** Rel32FinderAArch64 ********/ Rel32FinderAArch64::Rel32FinderAArch64(ConstBufferView image, const AddressTranslator& translator) : Rel32FinderArm(image, translator) {} Rel32FinderAArch64::~Rel32FinderAArch64() = default; Rel32Finder::NextIterators Rel32FinderAArch64::Scan(ConstBufferView region) { // Guard against alignment potentially causing |cursor > region.end()|. if (region.size() < 4) return SetEmptyResult(); ConstBufferView::const_iterator cursor = region.begin(); cursor += IncrementForAlignCeil4(cursor - image_.begin()); for (; region.end() - cursor >= 4; cursor += 4) { offset_t offset = base::checked_cast<offset_t>(cursor - image_.begin()); // For simplicity we assume RVA fits within 32-bits. AArch64Rel32Translator translator; AArch64Rel32Translator::AddrType type = AArch64Rel32Translator::ADDR_NONE; rva_t instr_rva = offset_to_rva_.Convert(offset); uint32_t code32 = translator.FetchCode32(image_, offset); rva_t target_rva = kInvalidRva; if (translator.ReadImmd14(instr_rva, code32, &target_rva)) { type = AArch64Rel32Translator::ADDR_IMMD14; } else if (translator.ReadImmd19(instr_rva, code32, &target_rva)) { type = AArch64Rel32Translator::ADDR_IMMD19; } else if (translator.ReadImmd26(instr_rva, code32, &target_rva)) { type = AArch64Rel32Translator::ADDR_IMMD26; } if (type != AArch64Rel32Translator::ADDR_NONE) return SetResult({offset, target_rva, type}, cursor, 4); } return SetEmptyResult(); } } // namespace zucchini
4,608
565
<filename>quantities/elementary_functions_test.cpp  #include <functional> #include <string> #include "google/protobuf/stubs/common.h" #include "glog/logging.h" #include "gtest/gtest.h" #include "quantities/astronomy.hpp" #include "quantities/bipm.hpp" #include "quantities/constants.hpp" #include "quantities/elementary_functions.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" #include "quantities/uk.hpp" #include "testing_utilities/almost_equals.hpp" #include "testing_utilities/numerics.hpp" #include "testing_utilities/vanishes_before.hpp" namespace principia { namespace quantities { using astronomy::AstronomicalUnit; using astronomy::JulianYear; using astronomy::LightYear; using astronomy::Parsec; using astronomy::JovianGravitationalParameter; using astronomy::SolarGravitationalParameter; using astronomy::TerrestrialGravitationalParameter; using base::CPUFeatureFlags; using base::HasCPUFeatures; using constants::GravitationalConstant; using constants::SpeedOfLight; using constants::StandardGravity; using constants::VacuumPermeability; using constants::VacuumPermittivity; using numerics::CanEmitFMAInstructions; using si::Ampere; using si::Coulomb; using si::Day; using si::Degree; using si::Kilo; using si::Kilogram; using si::Mega; using si::Metre; using si::Mole; using si::Radian; using si::Second; using testing_utilities::AlmostEquals; using testing_utilities::RelativeError; using testing_utilities::VanishesBefore; using uk::Foot; using uk::Gallon; using uk::Rood; using ::testing::Eq; using ::testing::Lt; class ElementaryFunctionsTest : public testing::Test {}; TEST_F(ElementaryFunctionsTest, FMA) { if (!CanEmitFMAInstructions || !HasCPUFeatures(CPUFeatureFlags::FMA)) { GTEST_SKIP() << "Cannot test FMA on a machine without FMA"; } EXPECT_EQ(11 * Coulomb, FusedMultiplyAdd(2 * Ampere, 3 * Second, 5 * Coulomb)); EXPECT_EQ(11 * Radian, FusedMultiplyAdd(2.0, 3 * Radian, 5 * Radian)); EXPECT_EQ(11.0, FusedMultiplyAdd(2.0, 3.0, 5.0)); } TEST_F(ElementaryFunctionsTest, AbsoluteValue) { EXPECT_EQ(Abs(-1729), 1729); EXPECT_EQ(Abs(1729), 1729); EXPECT_EQ(Abs(-1729 * Metre), 1729 * Metre); } TEST_F(ElementaryFunctionsTest, DimensionlessExponentiation) { double const number = π - 42; double positivePower = 1; double negativePower = 1; EXPECT_EQ(positivePower, Pow<0>(number)); positivePower *= number; negativePower /= number; EXPECT_EQ(positivePower, Pow<1>(number)); EXPECT_EQ(negativePower, Pow<-1>(number)); positivePower *= number; negativePower /= number; EXPECT_EQ(positivePower, Pow<2>(number)); EXPECT_EQ(negativePower, Pow<-2>(number)); positivePower *= number; negativePower /= number; EXPECT_EQ(positivePower, Pow<3>(number)); EXPECT_EQ(negativePower, Pow<-3>(number)); positivePower *= number; negativePower /= number; // This one calls |std::pow|. EXPECT_THAT(positivePower, AlmostEquals(Pow<4>(number), 0, 1)); EXPECT_THAT(negativePower, AlmostEquals(Pow<-4>(number), 0, 1)); } // The Greek letters cause a warning when stringified by the macros, because // apparently Visual Studio doesn't encode strings in UTF-8 by default. #pragma warning(disable: 4566) TEST_F(ElementaryFunctionsTest, PhysicalConstants) { Length const lunar_distance = 384402 * Kilo(Metre); // By definition. EXPECT_THAT(1 / Pow<2>(SpeedOfLight), AlmostEquals(VacuumPermittivity * VacuumPermeability, 1)); // The Keplerian approximation for the mass of the Sun // is fairly accurate. EXPECT_THAT(RelativeError( 4 * Pow<2>(π) * Pow<3>(AstronomicalUnit) / Pow<2>(JulianYear), SolarGravitationalParameter), Lt(4e-5)); EXPECT_THAT(RelativeError(1 * Parsec, 3.26156 * LightYear), Lt(2e-6)); // The Keplerian approximation for the mass of the Earth // is pretty bad, but the error is still only 1%. EXPECT_THAT(RelativeError(4 * Pow<2>(π) * Pow<3>(lunar_distance) / Pow<2>(27.321582 * Day), TerrestrialGravitationalParameter), Lt(1e-2)); EXPECT_THAT(RelativeError(1 * SolarGravitationalParameter, 1047 * JovianGravitationalParameter), Lt(6e-4)); // Delambre & Méchain. EXPECT_THAT(RelativeError(TerrestrialGravitationalParameter / Pow<2>(40 * Mega(Metre) / (2 * π)), StandardGravity), Lt(4e-3)); // Talleyrand. EXPECT_THAT(RelativeError(π * Sqrt(1 * Metre / StandardGravity), 1 * Second), Lt(4e-3)); } #pragma warning(default: 4566) TEST_F(ElementaryFunctionsTest, TrigonometricFunctions) { EXPECT_EQ(Cos(0 * Degree), 1); EXPECT_EQ(Sin(0 * Degree), 0); EXPECT_THAT(Cos(90 * Degree), VanishesBefore(1.0, 0)); EXPECT_EQ(Sin(90 * Degree), 1); EXPECT_EQ(Cos(180 * Degree), -1); EXPECT_THAT(Sin(180 * Degree), VanishesBefore(1.0, 1)); EXPECT_THAT(Cos(-90 * Degree), VanishesBefore(1.0, 0)); EXPECT_EQ(Sin(-90 * Degree), -1); for (int k = 1; k < 360; ++k) { // Don't test for multiples of 90 degrees as zeros lead to horrible // conditioning. if (k % 90 != 0) { EXPECT_THAT(Cos((90 - k) * Degree), AlmostEquals(Sin(k * Degree), 0, 47)); EXPECT_THAT(Sin(k * Degree) / Cos(k * Degree), AlmostEquals(Tan(k * Degree), 0, 2)); EXPECT_THAT(((k + 179) % 360 - 179) * Degree, AlmostEquals(ArcTan(Sin(k * Degree), Cos(k * Degree)), 0, 77)); EXPECT_THAT(((k + 179) % 360 - 179) * Degree, AlmostEquals(ArcTan(Sin(k * Degree) * AstronomicalUnit, Cos(k * Degree) * AstronomicalUnit), 0, 77)); EXPECT_THAT(Cos(ArcCos(Cos(k * Degree))), AlmostEquals(Cos(k * Degree), 0, 7)); EXPECT_THAT(Sin(ArcSin(Sin(k * Degree))), AlmostEquals(Sin(k * Degree), 0, 1)); } } // Horribly conditioned near 0, so not in the loop above. EXPECT_EQ(Tan(ArcTan(Tan(-42 * Degree))), Tan(-42 * Degree)); } TEST_F(ElementaryFunctionsTest, HyperbolicFunctions) { EXPECT_EQ(Sinh(0 * Radian), 0); EXPECT_EQ(Cosh(0 * Radian), 1); EXPECT_EQ(Tanh(0 * Radian), 0); // Limits: EXPECT_EQ(Sinh(20 * Radian), Cosh(20 * Radian)); EXPECT_EQ(Tanh(20 * Radian), 1); EXPECT_EQ(Sinh(-20 * Radian), -Cosh(-20 * Radian)); EXPECT_EQ(Tanh(-20 * Radian), -1); EXPECT_THAT(Sinh(2 * Radian) / Cosh(2 * Radian), AlmostEquals(Tanh(2 * Radian), 0, 1)); EXPECT_THAT(ArcSinh(Sinh(-10 * Degree)), AlmostEquals(-10 * Degree, 0, 1)); EXPECT_THAT(ArcCosh(Cosh(-10 * Degree)), AlmostEquals(10 * Degree, 19, 20)); EXPECT_THAT(ArcTanh(Tanh(-10 * Degree)), AlmostEquals(-10 * Degree, 0, 1)); } TEST_F(ElementaryFunctionsTest, ExpLogAndRoots) { // The ULP distance is 1 if everything is correctly rounded. EXPECT_THAT(std::exp(std::log(2) / 2), AlmostEquals(Sqrt(2), 1)); // The ULP distance is 0 if everything is correctly rounded. EXPECT_THAT(std::exp(std::log(2) / 3), AlmostEquals(Cbrt(2), 0)); EXPECT_THAT( Sqrt(Rood), AlmostEquals(std::exp(std::log(Rood / Pow<2>(Foot)) / 2) * Foot, 0)); EXPECT_THAT( Cbrt(Gallon), AlmostEquals(std::exp(std::log(Gallon / Pow<3>(Foot)) / 3) * Foot, 0, 1)); } } // namespace quantities } // namespace principia
3,184
591
<filename>client/src/main/java/com/github/yeecode/objectlogger/client/richText/Html2Text.java package com.github.yeecode.objectlogger.client.richText; import javax.swing.text.MutableAttributeSet; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.parser.ParserDelegator; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class Html2Text extends HTMLEditorKit.ParserCallback { private String lineBreak = "\n"; private StringBuilder stringBuilder = new StringBuilder(); public static String simpleHtml(String html) { try { if (html.isEmpty()) { return ""; } Html2Text parser = new Html2Text(); parser.parse(html); return parser.getText() != null ? parser.getText() : ""; } catch (Exception e) { e.printStackTrace(); } return null; } private void parse(String html) throws IOException { Reader reader = new StringReader(html); ParserDelegator parsers = new ParserDelegator(); parsers.parse(reader, this, Boolean.TRUE); } @Override public void handleText(char[] text, int pos) { stringBuilder.append(text); } @Override public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) { if (stringBuilder.length() != 0 && t.isBlock() && !stringBuilder.toString().endsWith(lineBreak)) { stringBuilder.append(lineBreak); } } @Override public void handleEndTag(HTML.Tag t, int pos) { if (stringBuilder.length() != 0 && t.isBlock() && !stringBuilder.toString().endsWith(lineBreak)) { stringBuilder.append(lineBreak); } } @Override public void handleEndOfLineString(String eol) { if (stringBuilder.length() - lineBreak.length() > 0) { stringBuilder.delete(stringBuilder.length() - lineBreak.length(), stringBuilder.length()); } } @Override public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) { // deal with <img> if (HTML.Tag.IMG.equals(t)) { stringBuilder.append(Constant.imgLeftPlaceholder).append(a.toString()).append(Constant.imgRightPlaceholder); } } private String getText() { return stringBuilder.toString(); } }
1,044
1,975
// Copyright 2013 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. // ======================================================================== // // CUP-ECDSA public keys consist of a byte array, 66 bytes long, containing: // * The key ID (one byte) // * The public key in X9.62 uncompressed encoding (65 bytes): // * Uncompressed header byte (0x04) // * Gx coordinate (256-bit integer, big-endian) // * Gy coordinate (256-bit integer, big-endian) {0x03, 0x04, 0x19, 0x3e, 0x1b, 0xa3, 0x6b, 0xfd, 0x7c, 0x4a, 0x30, 0xec, 0x5d, 0xf3, 0x75, 0x2a, 0xf8, 0x77, 0x39, 0x45, 0x23, 0x1e, 0x9e, 0xb6, 0x8e, 0x44, 0x1c, 0x74, 0xc2, 0x9a, 0xce, 0xb8, 0x5c, 0x87, 0x43, 0x87, 0xa5, 0x25, 0x47, 0x07, 0xc0, 0x08, 0xaa, 0x10, 0x97, 0xc5, 0x79, 0x27, 0x83, 0x87, 0x37, 0x37, 0x4f, 0x13, 0x7e, 0x63, 0xfd, 0x80, 0x70, 0x23, 0x08, 0xa1, 0xa7, 0x7f, 0xae, 0x49};
555
2,071
/* * Copyright 2019 WeBank * 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.webank.wedatasphere.dss.framework.project.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; @TableName(value = "dss_project") public class DSSProjectDO implements Serializable { private static final long serialVersionUID=1L; @TableId(value = "id", type = IdType.AUTO) private Long id; private String name; /** * Source of the dss_project */ private String source; private String description; private Long userId; private String username; private Long workspaceId; private Date createTime; private String createBy; private Date updateTime; private String updateBy; /** * Organization ID */ private Long orgId; private Boolean visibility; /** * Reserved word */ private Boolean isTransfer; private Long initialOrgId; /** * If it is archived */ @TableField("isArchive") private Boolean isArchive; private String pic; private Integer starNum; private String product; private Integer applicationArea; private String business; private Integer isPersonal; private String createByStr; private String updateByStr; /** * 开发流程,多个以英文逗号分隔,取得的值是dss_dictionary中的dic_key(parent_key=p_develop_process),首尾以英文逗号结束 */ private String devProcess; /** * 编码模式,多个以英文逗号分隔,取得的值是dss_dictionary中的dic_key(parent_key=p_arrangement_mode或下面一级),首尾以英文逗号结束 */ private String orchestratorMode; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Long getWorkspaceId() { return workspaceId; } public void setWorkspaceId(Long workspaceId) { this.workspaceId = workspaceId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Long getOrgId() { return orgId; } public void setOrgId(Long orgId) { this.orgId = orgId; } public Boolean getVisibility() { return visibility; } public void setVisibility(Boolean visibility) { this.visibility = visibility; } public Boolean getTransfer() { return isTransfer; } public void setTransfer(Boolean transfer) { isTransfer = transfer; } public Long getInitialOrgId() { return initialOrgId; } public void setInitialOrgId(Long initialOrgId) { this.initialOrgId = initialOrgId; } public Boolean getArchive() { return isArchive; } public void setArchive(Boolean archive) { isArchive = archive; } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } public Integer getStarNum() { return starNum; } public void setStarNum(Integer starNum) { this.starNum = starNum; } public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } public Integer getApplicationArea() { return applicationArea; } public void setApplicationArea(Integer applicationArea) { this.applicationArea = applicationArea; } public String getBusiness() { return business; } public void setBusiness(String business) { this.business = business; } public Integer getIsPersonal() { return isPersonal; } public void setIsPersonal(Integer isPersonal) { this.isPersonal = isPersonal; } public String getCreateByStr() { return createByStr; } public void setCreateByStr(String createByStr) { this.createByStr = createByStr; } public String getUpdateByStr() { return updateByStr; } public void setUpdateByStr(String updateByStr) { this.updateByStr = updateByStr; } public String getDevProcess() { return devProcess; } public void setDevProcess(String devProcess) { this.devProcess = devProcess; } public String getOrchestratorMode() { return orchestratorMode; } public void setOrchestratorMode(String orchestratorMode) { this.orchestratorMode = orchestratorMode; } @Override public String toString() { return "DSSProject{" + "id=" + id + ", name='" + name + '\'' + ", source='" + source + '\'' + ", description='" + description + '\'' + ", userId=" + userId + ", username='" + username + '\'' + ", workspaceId=" + workspaceId + ", createTime=" + createTime + ", createBy='" + createBy + '\'' + ", updateTime=" + updateTime + ", updateBy='" + updateBy + '\'' + ", orgId=" + orgId + ", visibility=" + visibility + ", isTransfer=" + isTransfer + ", initialOrgId=" + initialOrgId + ", isArchive=" + isArchive + ", pic='" + pic + '\'' + ", starNum=" + starNum + ", product='" + product + '\'' + ", applicationArea=" + applicationArea + ", business='" + business + '\'' + ", isPersonal=" + isPersonal + ", createByStr='" + createByStr + '\'' + ", updateByStr='" + updateByStr + '\'' + ", devProcess='" + devProcess + '\'' + ", orchestratorMode='" + orchestratorMode + '\'' + '}'; } }
3,265
403
<gh_stars>100-1000 package io.craft.atom.redis; import io.craft.atom.redis.api.MasterSlaveRedis; import io.craft.atom.redis.api.Redis; import io.craft.atom.redis.api.RedisException; import io.craft.atom.redis.api.RedisPubSub; import io.craft.atom.redis.api.RedisTransaction; import io.craft.atom.redis.api.ScanResult; import io.craft.atom.redis.api.Slowlog; import io.craft.atom.redis.api.handler.RedisMonitorHandler; import io.craft.atom.redis.api.handler.RedisPsubscribeHandler; import io.craft.atom.redis.api.handler.RedisSubscribeHandler; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import lombok.ToString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author mindwind * @version 1.0, Jun 26, 2013 */ @ToString public class DefaultMasterSlaveRedis implements MasterSlaveRedis { private static final Logger LOG = LoggerFactory.getLogger(DefaultMasterSlaveRedis.class); private List<Redis> chain ; private volatile int index ; private volatile boolean readSlave; // ~ --------------------------------------------------------------------------------------------------------- public DefaultMasterSlaveRedis(List<Redis> chain) { this(chain, 0); } public DefaultMasterSlaveRedis(List<Redis> chain, int index) { if (chain == null) { throw new IllegalArgumentException("Master-slave chain list is null."); } int size = chain.size(); if (size < 2) { throw new IllegalArgumentException("Master-slave chain list must have 2 redis node at lease."); } Set<Redis> set = new HashSet<Redis>(); set.addAll(chain); if (set.size() != size) { throw new IllegalArgumentException("Invalid master-slave chain, because repeated redis node, chain=" + chain); } check(index, size); this.chain = chain; this.index = index; rebuild(); } private void check(int index, int size) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Master index should be in [0," + (size - 1) + "]"); } } // ~ --------------------------------------------------------------------------------------------------------- @Override public void master(int index) { master(index, true); } private void master(int index, boolean rebuild) { check(index, chain.size()); this.index = index; if (rebuild) { rebuild(); } } @Override public Redis master() { return chain.get(index); } @Override public int index() { return index; } @Override public List<Redis> chain() { List<Redis> l = new ArrayList<Redis>(chain.size()); int c = index; for (int i = 0; i < chain.size(); i++) { l.add(chain.get(c)); c++; if (c == chain.size()) { c = 0; } } return l; } private void rebuild() { Redis master = chain.get(index); master.slaveofnoone(); // after master for (int i = index + 1; i < chain.size(); i++) { Redis m = chain.get(i - 1); Redis s = chain.get(i); link(m, s); } // before master except index 0 for (int i = 1; i < index; i++) { Redis m = chain.get(i - 1); Redis s = chain.get(i); link(m, s); } // index 0 if (index != 0) { Redis m = chain.get(chain.size() - 1); Redis s = chain.get(0); link(m, s); } } @Override public void reset() { index = 0; rebuild(); } private void link(Redis m, Redis s) { try { s.slaveof(m.host(), m.port()); } catch (RedisException e) { LOG.warn("[CRAFT-ATOM-REDIS] {} slaveof {} failed", s.toString(), m.toString()); } } private Redis firstSlave() { int slaveIndex = (index + 1) % chain.size(); return chain.get(slaveIndex); } @Override public void enableReadSlave() { this.readSlave = true; } @Override public void disableReadSlave() { this.readSlave = false; } // ~ --------------------------------------------------------------------------------------------------------- Keys @Override public Long del(String... keys) { return master().del(keys); } @Override public byte[] dump(String key) { return master().dump(key); } @Override public Boolean exists(String key) { return readSlave ? firstSlave().exists(key) : master().exists(key); } @Override public Long expire(String key, int seconds) { return master().expire(key, seconds); } @Override public Long expireat(String key, long timestamp) { return master().expireat(key, timestamp); } @Override public Set<String> keys(String pattern) { return readSlave ? firstSlave().keys(pattern) : master().keys(pattern); } @Override public String migrate(String host, int port, String key, int destinationdb, int timeout) { return master().migrate(host, port, key, destinationdb, timeout); } @Override public Long move(String key, int db) { return master().move(key, db); } @Override public Long objectrefcount(String key) { return readSlave ? firstSlave().objectrefcount(key) : master().objectrefcount(key); } @Override public String objectencoding(String key) { return readSlave ? firstSlave().objectencoding(key) : master().objectencoding(key); } @Override public Long objectidletime(String key) { return readSlave ? firstSlave().objectidletime(key) : master().objectidletime(key); } @Override public Long persist(String key) { return master().persist(key); } @Override public Long pexpire(String key, long milliseconds) { return master().pexpire(key, milliseconds); } @Override public Long pexpireat(String key, long millisecondstimestamp) { return master().pexpireat(key, millisecondstimestamp); } @Override public Long pttl(String key) { return readSlave ? firstSlave().pttl(key) : master().pttl(key); } @Override public String randomkey() { return readSlave ? firstSlave().randomkey() : master().randomkey(); } @Override public String rename(String key, String newkey) { return master().rename(key, newkey); } @Override public Long renamenx(String key, String newkey) { return master().renamenx(key, newkey); } @Override public String restore(String key, int ttl, byte[] serializedvalue) { return master().restore(key, ttl, serializedvalue); } @Override public List<String> sort(String key) { return readSlave ? firstSlave().sort(key) : master().sort(key); } @Override public List<String> sort(String key, boolean desc) { return readSlave ? firstSlave().sort(key, desc) : master().sort(key, desc); } @Override public List<String> sort(String key, boolean alpha, boolean desc) { return readSlave ? firstSlave().sort(key, alpha, desc) : master().sort(key, alpha, desc); } @Override public List<String> sort(String key, int offset, int count) { return readSlave ? firstSlave().sort(key, offset, count) : master().sort(key, offset, count); } @Override public List<String> sort(String key, int offset, int count, boolean alpha, boolean desc) { return readSlave ? firstSlave().sort(key, offset, count, alpha, desc) : master().sort(key, offset, count, alpha, desc); } @Override public List<String> sort(String key, String bypattern, String... getpatterns) { return readSlave ? firstSlave().sort(key, bypattern, getpatterns) : master().sort(key, bypattern, getpatterns); } @Override public List<String> sort(String key, String bypattern, boolean desc, String... getpatterns) { return readSlave ? firstSlave().sort(key, bypattern, desc, getpatterns) : master().sort(key, bypattern, desc, getpatterns); } @Override public List<String> sort(String key, String bypattern, boolean alpha, boolean desc, String... getpatterns) { return readSlave ? firstSlave().sort(key, bypattern, alpha, desc, getpatterns) : master().sort(key, bypattern, alpha, desc, getpatterns); } @Override public List<String> sort(String key, String bypattern, int offset, int count, String... getpatterns) { return readSlave ? firstSlave().sort(key, bypattern, offset, count, getpatterns) : master().sort(key, bypattern, offset, count, getpatterns); } @Override public List<String> sort(String key, String bypattern, int offset, int count, boolean alpha, boolean desc, String... getpatterns) { return readSlave ? firstSlave().sort(key, bypattern, offset, count, alpha, desc, getpatterns) : master().sort(key, bypattern, offset, count, alpha, desc, getpatterns); } @Override public Long sort(String key, String destination) { return readSlave ? firstSlave().sort(key, destination) : master().sort(key, destination); } @Override public Long sort(String key, boolean desc, String destination) { return readSlave ? firstSlave().sort(key, desc, destination) : master().sort(key, desc, destination); } @Override public Long sort(String key, boolean alpha, boolean desc, String destination) { return readSlave ? firstSlave().sort(key, alpha, desc, destination) : master().sort(key, alpha, desc, destination); } @Override public Long sort(String key, int offset, int count, String destination) { return readSlave ? firstSlave().sort(key, offset, count, destination) : master().sort(key, offset, count, destination); } @Override public Long sort(String key, int offset, int count, boolean alpha, boolean desc, String destination) { return readSlave ? firstSlave().sort(key, offset, count, alpha, desc, destination) : master().sort(key, offset, count, alpha, desc, destination); } @Override public Long sort(String key, String bypattern, String destination, String... getpatterns) { return readSlave ? firstSlave().sort(key, bypattern, destination, getpatterns) : master().sort(key, bypattern, destination, getpatterns); } @Override public Long sort(String key, String bypattern, boolean desc, String destination, String... getpatterns) { return readSlave ? firstSlave().sort(key, bypattern, desc, destination, getpatterns) : master().sort(key, bypattern, desc, destination, getpatterns); } @Override public Long sort(String key, String bypattern, boolean alpha, boolean desc, String destination, String... getpatterns) { return readSlave ? firstSlave().sort(key, bypattern, alpha, desc, destination, getpatterns) : master().sort(key, bypattern, alpha, desc, destination, getpatterns); } @Override public Long sort(String key, String bypattern, int offset, int count, String destination, String... getpatterns) { return readSlave ? firstSlave().sort(key, bypattern, offset, count, destination, getpatterns) : master().sort(key, bypattern, offset, count, destination, getpatterns); } @Override public Long sort(String key, String bypattern, int offset, int count, boolean alpha, boolean desc, String destination, String... getpatterns) { return readSlave ? firstSlave().sort(key, bypattern, offset, count, alpha, desc, destination, getpatterns) : master().sort(key, bypattern, offset, count, alpha, desc, destination, getpatterns); } @Override public Long ttl(String key) { return readSlave ? firstSlave().ttl(key) : master().ttl(key); } @Override public String type(String key) { return readSlave ? firstSlave().type(key) : master().type(key); } @Override public ScanResult<String> scan(String cursor) { return readSlave ? firstSlave().scan(cursor) : master().scan(cursor); } @Override public ScanResult<String> scan(String cursor, int count) { return readSlave ? firstSlave().scan(cursor, count) : master().scan(cursor, count); } @Override public ScanResult<String> scan(String cursor, String pattern) { return readSlave ? firstSlave().scan(cursor, pattern) : master().scan(cursor, pattern); } @Override public ScanResult<String> scan(String cursor, String pattern, int count) { return readSlave ? firstSlave().scan(cursor, pattern, count) : master().scan(cursor, pattern, count); } // ~ ------------------------------------------------------------------------------------------------------ Strings @Override public Long append(String key, String value) { return master().append(key, value); } @Override public Long bitcount(String key) { return readSlave ? firstSlave().bitcount(key) : master().bitcount(key); } @Override public Long bitcount(String key, long start, long end) { return readSlave ? firstSlave().bitcount(key) : master().bitcount(key, start, end); } @Override public Long bitnot(String destkey, String key) { return master().bitnot(destkey, key); } @Override public Long bitand(String destkey, String... keys) { return master().bitand(destkey, keys); } @Override public Long bitor(String destkey, String... keys) { return master().bitor(destkey, keys); } @Override public Long bitxor(String destkey, String... keys) { return master().bitxor(destkey, keys); } @Override public Long bitpos(String key, boolean value) { return readSlave ? firstSlave().bitpos(key, value) : master().bitpos(key, value); } @Override public Long bitpos(String key, boolean value, long start) { return readSlave ? firstSlave().bitpos(key, value, start) : master().bitpos(key, value, start); } @Override public Long bitpos(String key, boolean value, long start, long end) { return readSlave ? firstSlave().bitpos(key, value, start, end) : master().bitpos(key, value, start, end); } @Override public Long decr(String key) { return master().decr(key); } @Override public Long decrby(String key, long decrement) { return master().decrby(key, decrement); } @Override public String get(String key) { return readSlave ? firstSlave().get(key) : master().get(key); } @Override public Boolean getbit(String key, long offset) { return readSlave ? firstSlave().getbit(key, offset) : master().getbit(key, offset); } @Override public String getrange(String key, long start, long end) { return readSlave ? firstSlave().getrange(key, start, end) : master().getrange(key, start, end); } @Override public String getset(String key, String value) { return master().getset(key, value); } @Override public Long incr(String key) { return master().incr(key); } @Override public Long incrby(String key, long increment) { return master().incrby(key, increment); } @Override public Double incrbyfloat(String key, double increment) { return master().incrbyfloat(key, increment); } @Override public List<String> mget(String... keys) { return readSlave ? firstSlave().mget(keys) : master().mget(keys); } @Override public String mset(String... keysvalues) { return master().mset(keysvalues); } @Override public Long msetnx(String... keysvalues) { return master().msetnx(keysvalues); } @Override public String psetex(String key, int milliseconds, String value) { return master().psetex(key, milliseconds, value); } @Override public String set(String key, String value) { return master().set(key, value); } @Override public String setxx(String key, String value) { return master().setxx(key, value); } @Override public String setnxex(String key, String value, int seconds) { return master().setnxex(key, value, seconds); } @Override public String setnxpx(String key, String value, int milliseconds) { return master().setnxpx(key, value, milliseconds); } @Override public String setxxex(String key, String value, int seconds) { return master().setxxex(key, value, seconds); } @Override public String setxxpx(String key, String value, int milliseconds) { return master().setxxpx(key, value, milliseconds); } @Override public Boolean setbit(String key, long offset, boolean value) { return master().setbit(key, offset, value); } @Override public String setex(String key, int seconds, String value) { return master().setex(key, seconds, value); } @Override public Long setnx(String key, String value) { return master().setnx(key, value); } @Override public Long setrange(String key, long offset, String value) { return master().setrange(key, offset, value); } @Override public Long strlen(String key) { return readSlave ? firstSlave().strlen(key) : master().strlen(key); } // ~ ------------------------------------------------------------------------------------------------------ Hashes @Override public Long hdel(String key, String... fields) { return master().hdel(key, fields); } @Override public Boolean hexists(String key, String field) { return readSlave ? firstSlave().hexists(key, field) : master().hexists(key, field); } @Override public String hget(String key, String field) { return readSlave ? firstSlave().hget(key, field) : master().hget(key, field); } @Override public Map<String, String> hgetall(String key) { return readSlave ? firstSlave().hgetall(key) : master().hgetall(key); } @Override public Long hincrby(String key, String field, long increment) { return master().hincrby(key, field, increment); } @Override public Double hincrbyfloat(String key, String field, double increment) { return master().hincrbyfloat(key, field, increment); } @Override public Set<String> hkeys(String key) { return readSlave ? firstSlave().hkeys(key) : master().hkeys(key); } @Override public Long hlen(String key) { return readSlave ? firstSlave().hlen(key) : master().hlen(key); } @Override public List<String> hmget(String key, String... fields) { return readSlave ? firstSlave().hmget(key, fields) : master().hmget(key, fields); } @Override public String hmset(String key, Map<String, String> fieldvalues) { return master().hmset(key, fieldvalues); } @Override public Long hset(String key, String field, String value) { return master().hset(key, field, value); } @Override public Long hsetnx(String key, String field, String value) { return master().hsetnx(key, field, value); } @Override public List<String> hvals(String key) { return readSlave ? firstSlave().hvals(key) : master().hvals(key); } @Override public ScanResult<Entry<String, String>> hscan(String key, String cursor) { return readSlave ? firstSlave().hscan(key, cursor) : master().hscan(key, cursor); } @Override public ScanResult<Entry<String, String>> hscan(String key, String cursor, int count) { return readSlave ? firstSlave().hscan(key, cursor, count) : master().hscan(key, cursor, count); } @Override public ScanResult<Entry<String, String>> hscan(String key, String cursor, String pattern) { return readSlave ? firstSlave().hscan(key, cursor, pattern) : master().hscan(key, cursor, pattern); } @Override public ScanResult<Entry<String, String>> hscan(String key, String cursor, String pattern, int count) { return readSlave ? firstSlave().hscan(key, cursor, pattern, count) : master().hscan(key, cursor, pattern, count); } // ~ ------------------------------------------------------------------------------------------------------- Lists @Override public String blpop(String key) { return master().blpop(key); } @Override public String blpop(String key, int timeout) { return master().blpop(key, timeout); } @Override public Map<String, String> blpop(String... keys) { return master().blpop(keys); } @Override public Map<String, String> blpop(int timeout, String... keys) { return master().blpop(timeout, keys); } @Override public String brpop(String key) { return master().brpop(key); } @Override public String brpop(String key, int timeout) { return master().brpop(key, timeout); } @Override public Map<String, String> brpop(String... keys) { return master().brpop(keys); } @Override public Map<String, String> brpop(int timeout, String... keys) { return master().brpop(timeout, keys); } @Override public String brpoplpush(String source, String destination, int timeout) { return master().brpoplpush(source, destination, timeout); } @Override public String lindex(String key, long index) { return readSlave ? firstSlave().lindex(key, index) : master().lindex(key, index); } @Override public Long linsertbefore(String key, String pivot, String value) { return master().linsertbefore(key, pivot, value); } @Override public Long linsertafter(String key, String pivot, String value) { return master().linsertafter(key, pivot, value); } @Override public Long llen(String key) { return readSlave ? firstSlave().llen(key) : master().llen(key); } @Override public String lpop(String key) { return master().lpop(key); } @Override public Long lpush(String key, String... values) { return master().lpush(key, values); } @Override public Long lpushx(String key, String value) { return master().lpushx(key, value); } @Override public List<String> lrange(String key, long start, long stop) { return readSlave ? firstSlave().lrange(key, start, stop) : master().lrange(key, start, stop); } @Override public Long lrem(String key, long count, String value) { return master().lrem(key, count, value); } @Override public String lset(String key, long index, String value) { return master().lset(key, index, value); } @Override public String ltrim(String key, long start, long stop) { return master().ltrim(key, start, stop); } @Override public String rpop(String key) { return master().rpop(key); } @Override public String rpoplpush(String source, String destination) { return master().rpoplpush(source, destination); } @Override public Long rpush(String key, String... values) { return master().rpush(key, values); } @Override public Long rpushx(String key, String value) { return master().rpushx(key, value); } // ~ ------------------------------------------------------------------------------------------------------- Sets @Override public Long sadd(String key, String... members) { return master().sadd(key, members); } @Override public Long scard(String key) { return readSlave ? firstSlave().scard(key) : master().scard(key); } @Override public Set<String> sdiff(String... keys) { return readSlave ? firstSlave().sdiff(keys) : master().sdiff(keys); } @Override public Long sdiffstore(String destination, String... keys) { return master().sdiffstore(destination, keys); } @Override public Set<String> sinter(String... keys) { return readSlave ? firstSlave().sinter(keys) : master().sinter(keys); } @Override public Long sinterstore(String destination, String... keys) { return master().sinterstore(destination, keys); } @Override public Boolean sismember(String key, String member) { return readSlave ? firstSlave().sismember(key, member) : master().sismember(key, member); } @Override public Set<String> smembers(String key) { return readSlave ? firstSlave().smembers(key) : master().smembers(key); } @Override public Long smove(String source, String destination, String member) { return master().smove(source, destination, member); } @Override public String spop(String key) { return readSlave ? firstSlave().spop(key) : master().spop(key); } @Override public List<String> srandmember(String key, int count) { return readSlave ? firstSlave().srandmember(key, count) : master().srandmember(key, count); } @Override public String srandmember(String key) { return readSlave ? firstSlave().srandmember(key) : master().srandmember(key); } @Override public Long srem(String key, String... members) { return master().srem(key, members); } @Override public Set<String> sunion(String... keys) { return readSlave ? firstSlave().sunion(keys) : master().sunion(keys); } @Override public Long sunionstore(String destination, String... keys) { return master().sunionstore(destination, keys); } @Override public ScanResult<String> sscan(String key, String cursor) { return readSlave ? firstSlave().sscan(key, cursor) : master().sscan(key, cursor); } @Override public ScanResult<String> sscan(String key, String cursor, int count) { return readSlave ? firstSlave().sscan(key, cursor, count) : master().sscan(key, cursor, count); } @Override public ScanResult<String> sscan(String key, String cursor, String pattern) { return readSlave ? firstSlave().sscan(key, cursor, pattern) : master().sscan(key, cursor, pattern); } @Override public ScanResult<String> sscan(String key, String cursor, String pattern, int count) { return readSlave ? firstSlave().sscan(key, cursor, pattern, count) : master().sscan(key, cursor, pattern, count); } // ~ ------------------------------------------------------------------------------------------------- Sorted Sets @Override public Long zadd(String key, double score, String member) { return master().zadd(key, score, member); } @Override public Long zadd(String key, Map<String, Double> scoremembers) { return master().zadd(key, scoremembers); } @Override public Long zcard(String key) { return readSlave ? firstSlave().zcard(key) : master().zcard(key); } @Override public Long zcount(String key, double min, double max) { return readSlave ? firstSlave().zcount(key, min, max) : master().zcount(key, min, max); } @Override public Long zcount(String key, String min, String max) { return readSlave ? firstSlave().zcount(key, min, max) : master().zcount(key, min, max); } @Override public Double zincrby(String key, double score, String member) { return master().zincrby(key, score, member); } @Override public Long zinterstore(String destination, String... keys) { return master().zinterstore(destination, keys); } @Override public Long zinterstoremax(String destination, String... keys) { return master().zinterstoremax(destination, keys); } @Override public Long zinterstoremin(String destination, String... keys) { return master().zinterstoremin(destination, keys); } @Override public Long zinterstore(String destination, Map<String, Integer> weightkeys) { return master().zinterstore(destination, weightkeys); } @Override public Long zinterstoremax(String destination, Map<String, Integer> weightkeys) { return master().zinterstoremax(destination, weightkeys); } @Override public Long zinterstoremin(String destination, Map<String, Integer> weightkeys) { return master().zinterstoremin(destination, weightkeys); } @Override public Long zlexcount(String key, String min, String max) { return readSlave ? firstSlave().zlexcount(key, min, max) : master().zlexcount(key, min, max); } @Override public Set<String> zrange(String key, long start, long stop) { return readSlave ? firstSlave().zrange(key, start, stop) : master().zrange(key, start, stop); } @Override public Map<String, Double> zrangewithscores(String key, long start, long stop) { return readSlave ? firstSlave().zrangewithscores(key, start, stop) : master().zrangewithscores(key, start, stop); } @Override public Set<String> zrangebyscore(String key, double min, double max) { return readSlave ? firstSlave().zrangebyscore(key, min, max) : master().zrangebyscore(key, min, max); } @Override public Set<String> zrangebyscore(String key, String min, String max) { return readSlave ? firstSlave().zrangebyscore(key, min, max) : master().zrangebyscore(key, min, max); } @Override public Set<String> zrangebyscore(String key, double min, double max, int offset, int count) { return readSlave ? firstSlave().zrangebyscore(key, min, max, offset, count) : master().zrangebyscore(key, min, max, offset, count); } @Override public Set<String> zrangebyscore(String key, String min, String max, int offset, int count) { return readSlave ? firstSlave().zrangebyscore(key, min, max, offset, count) : master().zrangebyscore(key, min, max, offset, count); } @Override public Map<String, Double> zrangebyscorewithscores(String key, double min, double max) { return readSlave ? firstSlave().zrangebyscorewithscores(key, min, max) : master().zrangebyscorewithscores(key, min, max); } @Override public Map<String, Double> zrangebyscorewithscores(String key, String min, String max) { return readSlave ? firstSlave().zrangebyscorewithscores(key, min, max) : master().zrangebyscorewithscores(key, min, max); } @Override public Map<String, Double> zrangebyscorewithscores(String key, double min, double max, int offset, int count) { return readSlave ? firstSlave().zrangebyscorewithscores(key, min, max, offset, count) : master().zrangebyscorewithscores(key, min, max, offset, count); } @Override public Map<String, Double> zrangebyscorewithscores(String key, String min, String max, int offset, int count) { return readSlave ? firstSlave().zrangebyscorewithscores(key, min, max, offset, count) : master().zrangebyscorewithscores(key, min, max, offset, count); } @Override public Set<String> zrangebylex(String key, String min, String max) { return readSlave ? firstSlave().zrangebylex(key, min, max) : master().zrangebylex(key, min, max); } @Override public Set<String> zrangebylex(String key, String min, String max, int offset, int count) { return readSlave ? firstSlave().zrangebylex(key, min, max, offset, count) : master().zrangebylex(key, min, max, offset, count); } @Override public Long zrank(String key, String member) { return readSlave ? firstSlave().zrank(key, member) : master().zrank(key, member); } @Override public Long zrem(String key, String... members) { return master().zrem(key, members); } @Override public Long zremrangebylex(String key, String min, String max) { return master().zremrangebylex(key, min, max); } @Override public Long zremrangebyrank(String key, long start, long stop) { return master().zremrangebyrank(key, start, stop); } @Override public Long zremrangebyscore(String key, double min, double max) { return master().zremrangebyscore(key, min, max); } @Override public Long zremrangebyscore(String key, String min, String max) { return master().zremrangebyscore(key, min, max); } @Override public Set<String> zrevrange(String key, long start, long stop) { return readSlave ? firstSlave().zrevrange(key, start, stop) : master().zrevrange(key, start, stop); } @Override public Map<String, Double> zrevrangewithscores(String key, long start, long stop) { return readSlave ? firstSlave().zrevrangewithscores(key, start, stop) : master().zrevrangewithscores(key, start, stop); } @Override public Set<String> zrevrangebyscore(String key, double max, double min) { return readSlave ? firstSlave().zrevrangebyscore(key, max, min) : master().zrevrangebyscore(key, max, min); } @Override public Set<String> zrevrangebyscore(String key, String max, String min) { return readSlave ? firstSlave().zrevrangebyscore(key, max, min) : master().zrevrangebyscore(key, max, min); } @Override public Set<String> zrevrangebyscore(String key, double max, double min, int offset, int count) { return readSlave ? firstSlave().zrevrangebyscore(key, max, min, offset, count) : master().zrevrangebyscore(key, max, min, offset, count); } @Override public Set<String> zrevrangebyscore(String key, String max, String min, int offset, int count) { return readSlave ? firstSlave().zrevrangebyscore(key, max, min, offset, count) : master().zrevrangebyscore(key, max, min, offset, count); } @Override public Map<String, Double> zrevrangebyscorewithscores(String key, double max, double min) { return readSlave ? firstSlave().zrevrangebyscorewithscores(key, max, min) : master().zrevrangebyscorewithscores(key, max, min); } @Override public Map<String, Double> zrevrangebyscorewithscores(String key, String max, String min) { return readSlave ? firstSlave().zrevrangebyscorewithscores(key, max, min) : master().zrevrangebyscorewithscores(key, max, min); } @Override public Map<String, Double> zrevrangebyscorewithscores(String key, double max, double min, int offset, int count) { return readSlave ? firstSlave().zrevrangebyscorewithscores(key, max, min, offset, count) : master().zrevrangebyscorewithscores(key, max, min, offset, count); } @Override public Map<String, Double> zrevrangebyscorewithscores(String key, String max, String min, int offset, int count) { return readSlave ? firstSlave().zrevrangebyscorewithscores(key, max, min, offset, count) : master().zrevrangebyscorewithscores(key, max, min, offset, count); } @Override public Long zrevrank(String key, String member) { return readSlave ? firstSlave().zrevrank(key, member) : master().zrevrank(key, member); } @Override public Double zscore(String key, String member) { return readSlave ? firstSlave().zscore(key, member) : master().zscore(key, member); } @Override public Long zunionstore(String destination, String... keys) { return master().zunionstore(destination, keys); } @Override public Long zunionstoremax(String destination, String... keys) { return master().zunionstoremax(destination, keys); } @Override public Long zunionstoremin(String destination, String... keys) { return master().zunionstoremin(destination, keys); } @Override public Long zunionstore(String destination, Map<String, Integer> weightkeys) { return master().zunionstore(destination, weightkeys); } @Override public Long zunionstoremax(String destination, Map<String, Integer> weightkeys) { return master().zunionstoremax(destination, weightkeys); } @Override public Long zunionstoremin(String destination, Map<String, Integer> weightkeys) { return master().zunionstoremin(destination, weightkeys); } @Override public ScanResult<Entry<String, Double>> zscan(String key, String cursor) { return readSlave ? firstSlave().zscan(key, cursor) : master().zscan(key, cursor); } @Override public ScanResult<Entry<String, Double>> zscan(String key, String cursor, int count) { return readSlave ? firstSlave().zscan(key, cursor, count) : master().zscan(key, cursor, count); } @Override public ScanResult<Entry<String, Double>> zscan(String key, String cursor, String pattern) { return readSlave ? firstSlave().zscan(key, cursor, pattern) : master().zscan(key, cursor, pattern); } @Override public ScanResult<Entry<String, Double>> zscan(String key, String cursor, String pattern, int count) { return readSlave ? firstSlave().zscan(key, cursor, pattern, count) : master().zscan(key, cursor, pattern, count); } // ~ -------------------------------------------------------------------------------------------------- HyperLogLog @Override public Long pfadd(String key, String... elements) { return master().pfadd(key, elements); } @Override public Long pfcount(String... keys) { return master().pfcount(keys); } @Override public String pfmerge(String destkey, String... sourcekeys) { return master().pfmerge(destkey, sourcekeys); } // ~ ----------------------------------------------------------------------------------------------------- Pub/Sub @Override public RedisPubSub psubscribe(RedisPsubscribeHandler handler, String... patterns) { return readSlave ? firstSlave().psubscribe(handler, patterns) : master().psubscribe(handler, patterns); } @Override public Long publish(String channel, String message) { return master().publish(channel, message); } @Override public void punsubscribe(RedisPubSub pubsub, String... patterns) { if (readSlave) firstSlave().punsubscribe(pubsub, patterns); else master().punsubscribe(pubsub, patterns); } @Override public RedisPubSub subscribe(RedisSubscribeHandler handler, String... channels) { return readSlave ? firstSlave().subscribe(handler, channels) : master().subscribe(handler, channels); } @Override public void unsubscribe(RedisPubSub pubsub, String... channels) { if (readSlave) firstSlave().unsubscribe(pubsub, channels); else master().unsubscribe(pubsub, channels); } @Override public List<String> pubsubchannels(String pattern) { return readSlave ? firstSlave().pubsubchannels(pattern) : master().pubsubchannels(pattern); } @Override public Long pubsubnumpat() { return readSlave ? firstSlave().pubsubnumpat() : master().pubsubnumpat(); } @Override public Map<String, String> pubsubnumsub(String... channels) { return readSlave ? firstSlave().pubsubnumsub(channels) : master().pubsubnumsub(channels); } // ~ ------------------------------------------------------------------------------------------------ Transactions @Override public String discard(RedisTransaction t) { return master().discard(t); } @Override public List<Object> exec(RedisTransaction t) { return master().exec(t); } @Override public RedisTransaction multi() { return master().multi(); } @Override public String unwatch() { return master().unwatch(); } @Override public String watch(String... keys) { return master().watch(keys); } // ~ --------------------------------------------------------------------------------------------------- Scripting @Override public Object eval(String script) { return master().eval(script); } @Override public Object eval(String script, List<String> keys) { return master().eval(script, keys); } @Override public Object eval(String script, List<String> keys, List<String> args) { return master().eval(script, keys, args); } @Override public Object evalsha(String sha1) { return master().evalsha(sha1); } @Override public Object evalsha(String sha1, List<String> keys) { return master().evalsha(sha1, keys); } @Override public Object evalsha(String sha1, List<String> keys, List<String> args) { return master().evalsha(sha1); } @Override public Boolean scriptexists(String sha1) { return readSlave ? firstSlave().scriptexists(sha1) : master().scriptexists(sha1); } @Override public Boolean[] scriptexists(String... sha1s) { return readSlave ? firstSlave().scriptexists(sha1s) : master().scriptexists(sha1s); } @Override public String scriptflush() { return master().scriptflush(); } @Override public String scriptkill() { return master().scriptkill(); } @Override public String scriptload(String script) { return master().scriptload(script); } // ~ ------------------------------------------------------------------------------------------------- Connection @Override public String auth(String password) { return master().auth(password); } @Override public String echo(String message) { return master().echo(message); } @Override public String ping() { return master().ping(); } @Override public String quit() { return master().quit(); } @Override public String select(int index) { return master().select(index); } // ~ ------------------------------------------------------------------------------------------------------ Server @Override public String bgrewriteaof() { return master().bgrewriteaof(); } @Override public String bgsave() { return master().bgsave(); } @Override public String clientgetname() { return master().clientgetname(); } @Override public String clientkill(String ip, int port) { return master().clientkill(ip, port); } @Override public String clientkill(String client) { return master().clientkill(client); } @Override public List<String> clientlist() { return master().clientlist(); } @Override public String clientsetname(String connectionname) { return master().clientsetname(connectionname); } @Override public Map<String, String> configget(String parameter) { return master().configget(parameter); } @Override public String configset(String parameter, String value) { return master().configset(parameter, value); } @Override public String configresetstat() { return master().configresetstat(); } @Override public Long dbsize() { return master().dbsize(); } @Override public String debugobject(String key) { return master().debugobject(key); } @Override public String debugsegfault() { return master().debugsegfault(); } @Override public String flushall() { return master().flushall(); } @Override public String flushdb() { return master().flushdb(); } @Override public String info() { return master().info(); } @Override public String info(String section) { return master().info(section); } @Override public Long lastsave() { return master().lastsave(); } @Override public void monitor(RedisMonitorHandler handler) { master().monitor(handler); } @Override public String save() { return master().save(); } @Override public String shutdown(boolean save) { return master().shutdown(save); } @Override public String slaveof(String host, int port) { return master().slaveof(host, port); } @Override public String slaveofnoone() { return master().slaveofnoone(); } @Override public List<Slowlog> slowlogget() { return master().slowlogget(); } @Override public List<Slowlog> slowlogget(long len) { return master().slowlogget(len); } @Override public String slowlogreset() { return master().slowlogreset(); } @Override public Long slowloglen() { return master().slowloglen(); } @Override public void sync() { master().sync(); } @Override public Long time() { return master().time(); } @Override public Long microtime() { return master().microtime(); } }
13,300
348
{"nom":"Candor","circ":"6ème circonscription","dpt":"Oise","inscrits":230,"abs":131,"votants":99,"blancs":5,"nuls":2,"exp":92,"res":[{"nuance":"FN","nom":"M. <NAME>","voix":61},{"nuance":"REM","nom":"<NAME>","voix":31}]}
89
841
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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.jbpm.services.task.audit.impl.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import org.kie.internal.task.api.AuditTask; @Entity @Table(name = "AuditTaskImpl", indexes = { @Index(name = "IDX_AuditTaskImpl_taskId", columnList = "taskId"), @Index(name = "IDX_AuditTaskImpl_pInstId", columnList = "processInstanceId"), @Index(name = "IDX_AuditTaskImpl_workItemId", columnList = "workItemId"), @Index(name = "IDX_AuditTaskImpl_name", columnList = "name"), @Index(name = "IDX_AuditTaskImpl_processId", columnList = "processId"), @Index(name = "IDX_AuditTaskImpl_status", columnList = "status") }) @SequenceGenerator(name = "auditIdSeq", sequenceName = "AUDIT_ID_SEQ", allocationSize = 1) public class AuditTaskImpl implements Serializable, AuditTask { private static final long serialVersionUID = 5388016330549830043L; @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "auditIdSeq") private Long id; private Long taskId; private String status; @Temporal(javax.persistence.TemporalType.TIMESTAMP) private Date activationTime; private String name; private String description; private int priority; private String createdBy; private String actualOwner; @Temporal(javax.persistence.TemporalType.TIMESTAMP) private Date createdOn; @Temporal(javax.persistence.TemporalType.TIMESTAMP) private Date dueDate; private long processInstanceId; private String processId; private long processSessionId; private long parentId; private String deploymentId; private Long workItemId; @Temporal(javax.persistence.TemporalType.TIMESTAMP) private Date lastModificationDate; public AuditTaskImpl() { } public AuditTaskImpl(long taskId, String name, String status, Date activationTime, String actualOwner, String description, int priority, String createdBy, Date createdOn, Date dueDate, long processInstanceId, String processId, long processSessionId, String deploymentId, long parentId, long workItemId) { this.taskId = taskId; this.status = status; this.activationTime = activationTime; this.name = name; this.description = description; this.priority = priority; this.createdBy = createdBy; this.createdOn = createdOn; this.actualOwner = actualOwner; this.dueDate = dueDate; this.processInstanceId = processInstanceId; this.processId = processId; this.processSessionId = processSessionId; this.deploymentId = deploymentId; this.parentId = parentId; this.workItemId = workItemId; this.lastModificationDate = new Date(); } public AuditTaskImpl(long taskId, String name, String status, Date activationTime, String actualOwner, String description, int priority, String createdBy, Date createdOn, Date dueDate, long processInstanceId, String processId, long processSessionId, String deploymentId, long parentId, long workItemId, Date lastModificationDate) { this.taskId = taskId; this.status = status; this.activationTime = activationTime; this.name = name; this.description = description; this.priority = priority; this.createdBy = createdBy; this.createdOn = createdOn; this.actualOwner = actualOwner; this.dueDate = dueDate; this.processInstanceId = processInstanceId; this.processId = processId; this.processSessionId = processSessionId; this.deploymentId = deploymentId; this.parentId = parentId; this.workItemId = workItemId; this.lastModificationDate = lastModificationDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public long getTaskId() { return taskId; } @Override public void setTaskId(long taskId) { this.taskId = taskId; } @Override public String getStatus() { return status; } @Override public void setStatus(String status) { this.status = status; } @Override public Date getActivationTime() { return activationTime; } @Override public void setActivationTime(Date activationTime) { this.activationTime = activationTime; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override public int getPriority() { return priority; } @Override public void setPriority(int priority) { this.priority = priority; } @Override public String getCreatedBy() { return createdBy; } @Override public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } @Override public Date getCreatedOn() { return createdOn; } @Override public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } @Override public Date getDueDate() { return dueDate; } @Override public void setDueDate(Date dueDate) { this.dueDate = dueDate; } @Override public long getProcessInstanceId() { return processInstanceId; } @Override public void setProcessInstanceId(long processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getProcessId() { return processId; } @Override public void setProcessId(String processId) { this.processId = processId; } @Override public long getProcessSessionId() { return processSessionId; } @Override public void setProcessSessionId(long processSessionId) { this.processSessionId = processSessionId; } @Override public long getParentId() { return parentId; } @Override public void setParentId(long parentId) { this.parentId = parentId; } public String getActualOwner() { return actualOwner; } public void setActualOwner(String actualOwner) { this.actualOwner = actualOwner; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public long getWorkItemId() { return workItemId; } @Override public void setWorkItemId(long workItemId) { this.workItemId = workItemId; } public Date getLastModificationDate() { return lastModificationDate; } public void setLastModificationDate(Date lastModificationDate) { this.lastModificationDate = lastModificationDate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((activationTime == null) ? 0 : activationTime.hashCode()); result = prime * result + ((actualOwner == null) ? 0 : actualOwner.hashCode()); result = prime * result + ((createdBy == null) ? 0 : createdBy.hashCode()); result = prime * result + ((createdOn == null) ? 0 : createdOn.hashCode()); result = prime * result + ((deploymentId == null) ? 0 : deploymentId.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((dueDate == null) ? 0 : dueDate.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((lastModificationDate == null) ? 0 : lastModificationDate.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + (int) (parentId ^ (parentId >>> 32)); result = prime * result + priority; result = prime * result + ((processId == null) ? 0 : processId.hashCode()); result = prime * result + (int) (processInstanceId ^ (processInstanceId >>> 32)); result = prime * result + (int) (processSessionId ^ (processSessionId >>> 32)); result = prime * result + ((status == null) ? 0 : status.hashCode()); result = prime * result + ((taskId == null) ? 0 : taskId.hashCode()); result = prime * result + ((workItemId == null) ? 0 : workItemId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AuditTaskImpl other = (AuditTaskImpl) obj; if (activationTime == null) { if (other.activationTime != null) return false; } else if (!activationTime.equals(other.activationTime)) return false; if (actualOwner == null) { if (other.actualOwner != null) return false; } else if (!actualOwner.equals(other.actualOwner)) return false; if (createdBy == null) { if (other.createdBy != null) return false; } else if (!createdBy.equals(other.createdBy)) return false; if (createdOn == null) { if (other.createdOn != null) return false; } else if (!createdOn.equals(other.createdOn)) return false; if (deploymentId == null) { if (other.deploymentId != null) return false; } else if (!deploymentId.equals(other.deploymentId)) return false; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (dueDate == null) { if (other.dueDate != null) return false; } else if (!dueDate.equals(other.dueDate)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (lastModificationDate == null) { if (other.lastModificationDate != null) return false; } else if (!lastModificationDate.equals(other.lastModificationDate)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (parentId != other.parentId) return false; if (priority != other.priority) return false; if (processId == null) { if (other.processId != null) return false; } else if (!processId.equals(other.processId)) return false; if (processInstanceId != other.processInstanceId) return false; if (processSessionId != other.processSessionId) return false; if (status == null) { if (other.status != null) return false; } else if (!status.equals(other.status)) return false; if (taskId == null) { if (other.taskId != null) return false; } else if (!taskId.equals(other.taskId)) return false; if (workItemId == null) { if (other.workItemId != null) return false; } else if (!workItemId.equals(other.workItemId)) return false; return true; } @Override public String toString() { return "AuditTaskImpl [id=" + id + ", taskId=" + taskId + ", status=" + status + ", activationTime=" + activationTime + ", name=" + name + ", description=" + description + ", priority=" + priority + ", createdBy=" + createdBy + ", actualOwner=" + actualOwner + ", createdOn=" + createdOn + ", dueDate=" + dueDate + ", processInstanceId=" + processInstanceId + ", processId=" + processId + ", processSessionId=" + processSessionId + ", parentId=" + parentId + ", deploymentId=" + deploymentId + ", workItemId=" + workItemId + ", lastModificationDate=" + lastModificationDate + "]"; } }
6,182
457
package denominator.route53; import com.squareup.okhttp.mockwebserver.MockResponse; import org.junit.Rule; import org.junit.Test; import denominator.DNSApiManager; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class HostedZonesReadableMockTest { @Rule public MockRoute53Server server = new MockRoute53Server(); @Test public void singleRequestOnSuccess() throws Exception { server.enqueue(new MockResponse().setBody("<ListHostedZonesResponse />")); DNSApiManager api = server.connect(); assertTrue(api.checkConnection()); server.assertRequest() .hasMethod("GET") .hasPath("/2012-12-12/hostedzone"); } @Test public void singleRequestOnFailure() throws Exception { server.enqueue(new MockResponse().setResponseCode(403).setBody( "<ErrorResponse xmlns=\"https:route53.amazonaws.com/doc/2012-12-12/\">\n" + " <Error>\n" + " <Type>Sender</Type>\n" + " <Code>InvalidClientTokenId</Code>\n" + " <Message>The security token included in the request is invalid</Message>\n" + " </Error>\n" + " <RequestId>d3801bc8-f70d-11e2-8a6e-435ba83aa63f</RequestId>\n" + "</ErrorResponse>")); DNSApiManager api = server.connect(); assertFalse(api.checkConnection()); server.assertRequest() .hasMethod("GET") .hasPath("/2012-12-12/hostedzone"); } }
567
435
<reponame>amaajemyfren/data<filename>pydata-indy-2018/videos/sparkflow-utilizing-pyspark-for-training-tensorflow-models-on-large-datasets-by-derek-miller.json { "copyright_text": "Creative Commons Attribution license (reuse allowed)", "description": "As more public, large datasets are becoming available, distributed data processing tools such as Apache Spark are vital for data scientists. While SparkML provides many machine learning algorithms, standard pipelines, and a basic linear algebra library, it does not support training deep learning models. Due to the rise of Tensorflow in the last two years, Lifeomic built the Sparkflow library to combine the power of the Pipeline api from Spark with training Deep Learning models in Tensorflow. Sparkflow uses the Hogwild algorithm to train deep learning models in a distributed manor, which underneath leverages the driver/executor architecture in Spark to manage copied networks and gradients. In this session, we describe some of the lessons learned in building Sparkflow, the pros and cons of asynchronous distributed deep learning, how to use Spark Pipelines with Tensorflow with very few lines of code, and where we are headed with the library in the near future.", "duration": 1420, "language": "eng", "recorded": "2018-10-12", "related_urls": [ { "label": "schedule", "url": "https://www.meetup.com/fr-FR/indypy/events/252203530/" } ], "speakers": [ "<NAME>" ], "tags": [ "Pyspark", "Tensorflow" ], "thumbnail_url": "https://i.ytimg.com/vi/nNrdv45O3pE/maxresdefault.jpg", "title": "Sparkflow: Utilizing Pyspark for Training Tensorflow Models on Large Datasets", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=nNrdv45O3pE" } ] }
549
14,668
<reponame>zealoussnow/chromium // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/renderer/feature_manager.h" #include <iostream> #include <map> #include <string> #include <vector> #include "base/check.h" #include "base/logging.h" #include "base/values.h" #include "chromecast/base/cast_features.h" #include "chromecast/common/feature_constants.h" #include "chromecast/renderer/assistant_bindings.h" #include "chromecast/renderer/cast_accessibility_bindings.h" #include "chromecast/renderer/cast_demo_bindings.h" #include "chromecast/renderer/cast_window_manager_bindings.h" #include "chromecast/renderer/settings_ui_bindings.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_frame_media_playback_options.h" #include "services/network/public/cpp/is_potentially_trustworthy.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" #include "third_party/blink/public/platform/web_runtime_features.h" #include "third_party/blink/public/platform/web_security_origin.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/web/web_local_frame.h" #include "third_party/blink/public/web/web_security_policy.h" namespace chromecast { FeatureManager::FeatureManager(content::RenderFrame* render_frame) : content::RenderFrameObserver(render_frame), configured_(false), can_install_bindings_(false), dev_origin_(GURL::EmptyGURL()), secure_origin_set_(false) { registry_.AddInterface(base::BindRepeating( &FeatureManager::OnFeatureManagerRequest, base::Unretained(this))); } FeatureManager::~FeatureManager() {} void FeatureManager::OnInterfaceRequestForFrame( const std::string& interface_name, mojo::ScopedMessagePipeHandle* interface_pipe) { registry_.TryBindInterface(interface_name, interface_pipe); } void FeatureManager::OnDestruct() { delete this; } void FeatureManager::DidClearWindowObject() { can_install_bindings_ = true; if (!configured_) return; EnableBindings(); } void FeatureManager::ConfigureFeatures( std::vector<chromecast::shell::mojom::FeaturePtr> features) { if (configured_) return; configured_ = true; for (auto& feature : features) { // If we want to add enabled/disabled status to FeaturePtr, we can overlap // previous setting via [] operator features_map_[feature->name] = std::move(feature); } ConfigureFeaturesInternal(); if (!can_install_bindings_) return; EnableBindings(); } void FeatureManager::ConfigureFeaturesInternal() { if (FeatureEnabled(feature::kEnableDevMode)) { base::Value& dev_mode_config = (features_map_.find(feature::kEnableDevMode)->second)->config; base::Value* dev_mode_origin = dev_mode_config.FindKey(feature::kDevModeOrigin); DCHECK(dev_mode_origin); dev_origin_ = GURL(dev_mode_origin->GetString()); DCHECK(dev_origin_.is_valid()); } if (FeatureEnabled(feature::kDisableBackgroundSuspend)) { auto options = render_frame()->GetRenderFrameMediaPlaybackOptions(); options.is_background_suspend_enabled = false; render_frame()->SetRenderFrameMediaPlaybackOptions(options); } // Call feature-specific functions. SetupAdditionalSecureOrigin(); // Disable timer throttling for background tabs before the frame is painted. if (FeatureEnabled(feature::kDisableBackgroundTabTimerThrottle)) { blink::WebRuntimeFeatures::EnableTimerThrottlingForBackgroundTabs(false); } if (FeatureEnabled(feature::kEnableSettingsUiMojo)) { v8_bindings_.insert(new shell::SettingsUiBindings(render_frame())); } // Window manager bindings will install themselves depending on the specific // feature flags enabled, so we pass the feature manager through to let it // decide. v8_bindings_.insert( new shell::CastWindowManagerBindings(render_frame(), this)); // Accessibility bindings will install themselves depending on the specific // feature flags enabled, so we pass the feature manager through to let it // decide. v8_bindings_.insert( new shell::CastAccessibilityBindings(render_frame(), this)); if (FeatureEnabled(feature::kEnableDemoStandaloneMode)) { v8_bindings_.insert(new shell::CastDemoBindings(render_frame())); } if (FeatureEnabled(feature::kEnableAssistantMessagePipe)) { auto& feature = GetFeature(feature::kEnableAssistantMessagePipe); v8_bindings_.insert( new shell::AssistantBindings(render_frame(), feature->config)); } } void FeatureManager::EnableBindings() { LOG(INFO) << "Enabling bindings: " << *this; for (auto* binding : v8_bindings_) { binding->TryInstall(); } } void FeatureManager::OnFeatureManagerRequest( mojo::PendingReceiver<shell::mojom::FeatureManager> request) { bindings_.Add(this, std::move(request)); } bool FeatureManager::FeatureEnabled(const std::string& feature) const { return features_map_.find(feature) != features_map_.end(); } const chromecast::shell::mojom::FeaturePtr& FeatureManager::GetFeature( const std::string& feature) const { auto itor = features_map_.find(feature); DCHECK(itor != features_map_.end()); return itor->second; } void FeatureManager::SetupAdditionalSecureOrigin() { if (!dev_origin_.is_valid()) { return; } // Secure origin should be only set once, otherwise it will cause CHECK // failure when race between origin safelist changing and thread creation // happens (b/63583734). if (secure_origin_set_) { return; } secure_origin_set_ = true; LOG(INFO) << "Treat origin " << dev_origin_ << " as secure origin"; blink::WebSecurityPolicy::AddSchemeToSecureContextSafelist( blink::WebString::FromASCII(dev_origin_.scheme())); network::SecureOriginAllowlist::GetInstance().SetAuxiliaryAllowlist( dev_origin_.spec(), nullptr); } std::ostream& operator<<(std::ostream& os, const FeatureManager& features) { for (auto& feature : features.features_map_) { os << feature.first << " "; } return os; } } // namespace chromecast
2,003
1,083
//===--- Syntax.cpp - Swift Syntax Implementation -------------------------===// // // 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 // //===----------------------------------------------------------------------===// // This source file is part of the polarphp.org open source project // // Copyright (c) 2017 - 2019 polarphp software foundation // Copyright (c) 2017 - 2019 zzu_softboy <<EMAIL>> // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://polarphp.org/LICENSE.txt for license information // See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors // // Created by polarboy on 2019/05/11. #include "polarphp/syntax/Syntax.h" #include "polarphp/syntax/SyntaxData.h" #include "polarphp/syntax/SyntaxNodeVisitor.h" #include <optional> namespace polar::syntax { Syntax::~Syntax() {} RefCountPtr<RawSyntax> Syntax::getRaw() const { return m_data->getRaw(); } SyntaxKind Syntax::getKind() const { return getRaw()->getKind(); } void Syntax::print(utils::raw_ostream &outStream, SyntaxPrintOptions opts) const { if (auto raw = getRaw()) { raw->print(outStream, opts); } } void Syntax::dump() const { return getRaw()->dump(); } void Syntax::dump(utils::raw_ostream &outStream, [[maybe_unused]] unsigned indent) const { return getRaw()->dump(outStream, 0); } bool Syntax::isDecl() const { return m_data->isDecl(); } bool Syntax::isStmt() const { return m_data->isStmt(); } bool Syntax::isExpr() const { return m_data->isExpr(); } bool Syntax::isToken() const { return getRaw()->isToken(); } bool Syntax::isUnknown() const { return m_data->isUnknown(); } bool Syntax::isPresent() const { return getRaw()->isPresent(); } bool Syntax::isMissing() const { return getRaw()->isMissing(); } std::optional<Syntax> Syntax::getParent() const { auto parentData = getData().getParent(); if (!parentData) { return std::nullopt; } return std::optional<Syntax> { Syntax { m_root, parentData } }; } Syntax Syntax::getRoot() const { return { m_root, m_root.get() }; } size_t Syntax::getNumChildren() const { return m_data->getNumChildren(); } std::optional<Syntax> Syntax::getChild(const size_t index) const { auto childData = m_data->getChild(index); if (!childData) { return std::nullopt; } return Syntax {m_root, childData.get()}; } } // polar::syntax
917
852
#ifndef TkDetLayers_TIBLayer_h #define TkDetLayers_TIBLayer_h #include "TBLayer.h" #include "TIBRing.h" #include "TrackingTools/DetLayers/interface/GeneralBinFinderInZforGeometricSearchDet.h" /** A concrete implementation for TIB layer * built out of TIBRings */ #pragma GCC visibility push(hidden) class TIBLayer final : public TBLayer { public: TIBLayer(std::vector<const TIBRing*>& innerRings, std::vector<const TIBRing*>& outerRings) __attribute__((cold)); ~TIBLayer() override __attribute__((cold)); private: // private methods for the implementation of groupedCompatibleDets() std::tuple<bool, int, int> computeIndexes(GlobalPoint gInnerPoint, GlobalPoint gOuterPoint) const override __attribute__((hot)); void searchNeighbors(const TrajectoryStateOnSurface& tsos, const Propagator& prop, const MeasurementEstimator& est, const SubLayerCrossing& crossing, float window, std::vector<DetGroup>& result, bool checkClosest) const override __attribute__((hot)); float computeWindowSize(const GeomDet* det, const TrajectoryStateOnSurface& tsos, const MeasurementEstimator& est) const override __attribute__((hot)); static bool overlap(const GlobalPoint& gpos, const GeometricSearchDet& ring, float window) __attribute__((hot)); GeneralBinFinderInZforGeometricSearchDet<float> theInnerBinFinder; GeneralBinFinderInZforGeometricSearchDet<float> theOuterBinFinder; BoundCylinder* cylinder(const std::vector<const GeometricSearchDet*>& rings) __attribute__((cold)); }; #pragma GCC visibility pop #endif
677
412
<filename>scripts/redact_cli_py/tests/test_helpers/redact_policy_helper.py # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project # root for license information. import re class RedactPolicyHelper: @staticmethod def is_first_char(text: str) -> bool: # There is no alphanumeric char except Aa0. return re.match("^[b-zB-Z1-9]*$", text) is None
154
432
#include <common.h> int main(void) { struct stat sb; sem_t *id; int error; id = sem_open(TEST_PATH, O_CREAT, 0777, 0); if (id == SEM_FAILED) { perror("sem_open"); return 1; } error = stat("/var/run/sem", &sb); if (error) { perror("stat"); return 1; } if ((sb.st_mode & ALLPERMS) != (S_IRWXU|S_IRWXG|S_IRWXO|S_ISTXT)) { fprintf(stderr, "semaphore dir has incorrect mode: 0%o\n", (sb.st_mode & ALLPERMS)); return 1; } sem_close(id); return 0; }
239
1,766
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // TODO(pbos): Move Config from common.h to here. #ifndef WEBRTC_CONFIG_H_ #define WEBRTC_CONFIG_H_ #include <string> #include <vector> #include "webrtc/base/basictypes.h" #include "webrtc/base/optional.h" #include "webrtc/base/refcount.h" #include "webrtc/base/scoped_ref_ptr.h" #include "webrtc/common_types.h" #include "webrtc/typedefs.h" namespace webrtc { // Settings for NACK, see RFC 4585 for details. struct NackConfig { NackConfig() : rtp_history_ms(0) {} std::string ToString() const; // Send side: the time RTP packets are stored for retransmissions. // Receive side: the time the receiver is prepared to wait for // retransmissions. // Set to '0' to disable. int rtp_history_ms; }; // Settings for ULPFEC forward error correction. // Set the payload types to '-1' to disable. struct UlpfecConfig { UlpfecConfig() : ulpfec_payload_type(-1), red_payload_type(-1), red_rtx_payload_type(-1) {} std::string ToString() const; bool operator==(const UlpfecConfig& other) const; // Payload type used for ULPFEC packets. int ulpfec_payload_type; // Payload type used for RED packets. int red_payload_type; // RTX payload type for RED payload. int red_rtx_payload_type; }; // Settings for FlexFEC forward error correction. // Set the payload type to '-1' to disable. struct FlexfecConfig { FlexfecConfig(); ~FlexfecConfig(); std::string ToString() const; bool IsCompleteAndEnabled() const; bool operator==(const FlexfecConfig& other) const; // Payload type of FlexFEC. int flexfec_payload_type; // SSRC of FlexFEC stream. uint32_t flexfec_ssrc; // Vector containing a single element, corresponding to the SSRC of the media // stream being protected by this FlexFEC stream. The vector MUST have size 1. // // TODO(brandtr): Update comment above when we support multistream protection. std::vector<uint32_t> protected_media_ssrcs; }; // RTP header extension, see RFC 5285. struct RtpExtension { RtpExtension() : id(0) {} RtpExtension(const std::string& uri, int id) : uri(uri), id(id) {} std::string ToString() const; bool operator==(const RtpExtension& rhs) const { return uri == rhs.uri && id == rhs.id; } static bool IsSupportedForAudio(const std::string& uri); static bool IsSupportedForVideo(const std::string& uri); // Header extension for audio levels, as defined in: // http://tools.ietf.org/html/draft-ietf-avtext-client-to-mixer-audio-level-03 static const char* kAudioLevelUri; static const int kAudioLevelDefaultId; // Header extension for RTP timestamp offset, see RFC 5450 for details: // http://tools.ietf.org/html/rfc5450 static const char* kTimestampOffsetUri; static const int kTimestampOffsetDefaultId; // Header extension for absolute send time, see url for details: // http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time static const char* kAbsSendTimeUri; static const int kAbsSendTimeDefaultId; // Header extension for coordination of video orientation, see url for // details: // http://www.etsi.org/deliver/etsi_ts/126100_126199/126114/12.07.00_60/ts_126114v120700p.pdf static const char* kVideoRotationUri; static const int kVideoRotationDefaultId; // Header extension for transport sequence number, see url for details: // http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions static const char* kTransportSequenceNumberUri; static const int kTransportSequenceNumberDefaultId; static const char* kPlayoutDelayUri; static const int kPlayoutDelayDefaultId; std::string uri; int id; }; struct VideoStream { VideoStream(); ~VideoStream(); std::string ToString() const; size_t width; size_t height; int max_framerate; int min_bitrate_bps; int target_bitrate_bps; int max_bitrate_bps; int max_qp; // Bitrate thresholds for enabling additional temporal layers. Since these are // thresholds in between layers, we have one additional layer. One threshold // gives two temporal layers, one below the threshold and one above, two give // three, and so on. // The VideoEncoder may redistribute bitrates over the temporal layers so a // bitrate threshold of 100k and an estimate of 105k does not imply that we // get 100k in one temporal layer and 5k in the other, just that the bitrate // in the first temporal layer should not exceed 100k. // TODO(kthelgason): Apart from a special case for two-layer screencast these // thresholds are not propagated to the VideoEncoder. To be implemented. std::vector<int> temporal_layer_thresholds_bps; }; class VideoEncoderConfig { public: // These are reference counted to permit copying VideoEncoderConfig and be // kept alive until all encoder_specific_settings go out of scope. // TODO(kthelgason): Consider removing the need for copying VideoEncoderConfig // and use rtc::Optional for encoder_specific_settings instead. class EncoderSpecificSettings : public rtc::RefCountInterface { public: // TODO(pbos): Remove FillEncoderSpecificSettings as soon as VideoCodec is // not in use and encoder implementations ask for codec-specific structs // directly. void FillEncoderSpecificSettings(VideoCodec* codec_struct) const; virtual void FillVideoCodecVp8(VideoCodecVP8* vp8_settings) const; virtual void FillVideoCodecVp9(VideoCodecVP9* vp9_settings) const; virtual void FillVideoCodecH264(VideoCodecH264* h264_settings) const; private: ~EncoderSpecificSettings() override {} friend class VideoEncoderConfig; }; class H264EncoderSpecificSettings : public EncoderSpecificSettings { public: explicit H264EncoderSpecificSettings(const VideoCodecH264& specifics); void FillVideoCodecH264(VideoCodecH264* h264_settings) const override; private: VideoCodecH264 specifics_; }; class Vp8EncoderSpecificSettings : public EncoderSpecificSettings { public: explicit Vp8EncoderSpecificSettings(const VideoCodecVP8& specifics); void FillVideoCodecVp8(VideoCodecVP8* vp8_settings) const override; private: VideoCodecVP8 specifics_; }; class Vp9EncoderSpecificSettings : public EncoderSpecificSettings { public: explicit Vp9EncoderSpecificSettings(const VideoCodecVP9& specifics); void FillVideoCodecVp9(VideoCodecVP9* vp9_settings) const override; private: VideoCodecVP9 specifics_; }; enum class ContentType { kRealtimeVideo, kScreen, }; class VideoStreamFactoryInterface : public rtc::RefCountInterface { public: // An implementation should return a std::vector<VideoStream> with the // wanted VideoStream settings for the given video resolution. // The size of the vector may not be larger than // |encoder_config.number_of_streams|. virtual std::vector<VideoStream> CreateEncoderStreams( int width, int height, const VideoEncoderConfig& encoder_config) = 0; protected: ~VideoStreamFactoryInterface() override {} }; VideoEncoderConfig& operator=(VideoEncoderConfig&&) = default; VideoEncoderConfig& operator=(const VideoEncoderConfig&) = delete; // Mostly used by tests. Avoid creating copies if you can. VideoEncoderConfig Copy() const { return VideoEncoderConfig(*this); } VideoEncoderConfig(); VideoEncoderConfig(VideoEncoderConfig&&); ~VideoEncoderConfig(); std::string ToString() const; rtc::scoped_refptr<VideoStreamFactoryInterface> video_stream_factory; std::vector<SpatialLayer> spatial_layers; ContentType content_type; rtc::scoped_refptr<const EncoderSpecificSettings> encoder_specific_settings; // Padding will be used up to this bitrate regardless of the bitrate produced // by the encoder. Padding above what's actually produced by the encoder helps // maintaining a higher bitrate estimate. Padding will however not be sent // unless the estimated bandwidth indicates that the link can handle it. int min_transmit_bitrate_bps; int max_bitrate_bps; // Max number of encoded VideoStreams to produce. size_t number_of_streams; private: // Access to the copy constructor is private to force use of the Copy() // method for those exceptional cases where we do use it. VideoEncoderConfig(const VideoEncoderConfig&); }; } // namespace webrtc #endif // WEBRTC_CONFIG_H_
2,757
5,169
{ "name": "incelerPod", "version": "0.0.1", "summary": "Her projeye extension yazmaya bıktıysanız size bir haberimiz var!", "description": "Bu pod tamamen eğitim amaçlıdır.", "homepage": "https://github.com/Egemenclr/incelerPod", "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "11.0" }, "source": { "git": "https://github.com/Egemenclr/incelerPod.git", "commit": "<PASSWORD>" }, "source_files": "incelerPod/**/*.{h,m, swift}" }
214
60,067
<gh_stars>1000+ // Intentionally blank so I get a compile_commands.json entry for the header
28
1,838
''' Main module to launch an example hyperopt search on EC2. Launch this from outside the rllab main dir. Otherwise, rllab will try to ship the logfiles being written by this process, which will fail because tar doesn't want to tar files that are being written to. Alternatively, disable the packaging of log files by rllab, but I couldn't quickly find how to do this. You can use Jupyter notebook visualize_hyperopt_results.ipynb to inspect results. ''' from hyperopt import hp from contrib.rllab_hyperopt.core import launch_hyperopt_search # the functions to run the task and process result do not need to be in separate files. They do need to be separate from # the main file though. Also, anything you import in the module that contains run_task needs to be on the Rllab AMI. # Therefore, since I use pandas to process results, I have put them in separate files here. from contrib.rllab_hyperopt.example.score import process_result from contrib.rllab_hyperopt.example.task import run_task # define a search space. See https://github.com/hyperopt/hyperopt/wiki/FMin, sect 2 for more detail param_space = {'step_size': hp.uniform('step_size', 0.01, 0.1), 'seed': hp.choice('seed',[0, 1, 2])} # just by way of example, pass a different config to run_experiment_lite run_experiment_kwargs = dict( n_parallel=16, aws_config=dict(instance_type="c4.4xlarge",spot_price='0.7') ) launch_hyperopt_search( run_task, # the task to run process_result, # the function that will process results and return a score param_space, # param search space hyperopt_experiment_key='test12', # key for hyperopt DB, and also exp_prefix for run_experiment_lite n_hyperopt_workers=3, # nr of local workers AND nr of EC2 instances that will be started in parallel hyperopt_max_evals=5, # nr of parameter values to eval result_timeout=600, # wait this long for results from S3 before timing out run_experiment_kwargs=run_experiment_kwargs) # additional kwargs to pass to run_experiment_lite
775
1,118
{"deu":{"common":"Amerikanisch-Samoa","official":"Amerikanisch-Samoa"},"fin":{"common":"Amerikan Samoa","official":"Amerikan Samoa"},"fra":{"common":"Samoa américaines","official":"Samoa américaines"},"hrv":{"common":"Američka Samoa","official":"američka Samoa"},"ita":{"common":"Samoa Americane","official":"Samoa americane"},"jpn":{"common":"アメリカ領サモア","official":"米サモア"},"nld":{"common":"Amerikaans Samoa","official":"Amerikaans Samoa"},"por":{"common":"Samoa Americana","official":"Samoa americana"},"rus":{"common":"Американское Самоа","official":"американское Самоа"},"spa":{"common":"Samoa Americana","official":"Samoa Americana"}}
223
1,538
<filename>examples/ex_threads.c /* * Example program for the Allegro library, by <NAME>. * * In this example, each thread handles its own window and event queue. */ #include <math.h> #include <allegro5/allegro.h> #include <allegro5/allegro_primitives.h> #include "common.c" #define MAX_THREADS 100 #define MAX_BACKGROUNDS 10 #define MAX_SQUARES 25 typedef struct Background { double rmax; double gmax; double bmax; } Background; typedef struct Square { float cx, cy; float dx, dy; float size, dsize; float rot, drot; float life, dlife; } Square; static float rand01(void) { return (rand() % 10000) / 10000.0; } static float rand11(void) { return (-10000 + (rand() % 20000)) / 20000.0; } static void gen_square(Square *sq, int w, int h) { sq->cx = rand() % w; sq->cy = rand() % h; sq->dx = 3.0 * rand11(); sq->dy = 3.0 * rand11(); sq->size = 10 + (rand() % 10); sq->dsize = rand11(); sq->rot = ALLEGRO_PI * rand01(); sq->drot = rand11() / 3.0; sq->life = 0.0; sq->dlife = (ALLEGRO_PI / 100.0) + (ALLEGRO_PI / 30.0) * rand01(); } static void animate_square(Square *sq) { sq->cx += sq->dx; sq->cy += sq->dy; sq->size += sq->dsize; sq->rot += sq->drot; sq->life += sq->dlife; if (sq->size < 1.0 || sq->life > ALLEGRO_PI) { ALLEGRO_BITMAP *bmp = al_get_target_bitmap(); gen_square(sq, al_get_bitmap_width(bmp), al_get_bitmap_height(bmp)); } } static void draw_square(Square *sq) { ALLEGRO_TRANSFORM trans; float alpha; float size; ALLEGRO_COLOR tint; al_build_transform(&trans, sq->cx, sq->cy, 1.0, 1.0, sq->rot); al_use_transform(&trans); alpha = sin(sq->life); al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_ONE); tint = al_map_rgba_f(0.5, 0.3, 0, alpha); size = sq->size; al_draw_filled_rounded_rectangle(-size, -size, size, size, 3, 3, tint); size *= 1.1; al_draw_rounded_rectangle(-size, -size, size, size, 3, 3, tint, 2); } static void *thread_func(ALLEGRO_THREAD *thr, void *arg) { const int INITIAL_WIDTH = 300; const int INITIAL_HEIGHT = 300; const Background *background = (Background *) arg; ALLEGRO_DISPLAY *display; ALLEGRO_EVENT_QUEUE *queue = NULL; ALLEGRO_TIMER *timer = NULL; ALLEGRO_EVENT event; ALLEGRO_STATE state; Square squares[MAX_SQUARES]; double theta = 0.0; bool redraw = true; int i; (void)thr; al_set_new_display_flags(ALLEGRO_RESIZABLE); display = al_create_display(INITIAL_WIDTH, INITIAL_HEIGHT); if (!display) { goto Quit; } queue = al_create_event_queue(); if (!queue) { goto Quit; } timer = al_create_timer(0.1); if (!timer) { goto Quit; } al_register_event_source(queue, al_get_display_event_source(display)); al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_timer_event_source(timer)); for (i = 0; i < MAX_SQUARES; i++) { gen_square(&squares[i], INITIAL_WIDTH, INITIAL_HEIGHT); } al_start_timer(timer); while (true) { if (al_is_event_queue_empty(queue) && redraw) { double r = 0.7 + 0.3 * (sin(theta) + 1.0) / 2.0; ALLEGRO_COLOR c = al_map_rgb_f( background->rmax * r, background->gmax * r, background->bmax * r ); al_clear_to_color(c); al_store_state(&state, ALLEGRO_STATE_BLENDER | ALLEGRO_STATE_TRANSFORM); for (i = 0; i < MAX_SQUARES; i++) { draw_square(&squares[i]); } al_restore_state(&state); al_flip_display(); redraw = false; } al_wait_for_event(queue, &event); if (event.type == ALLEGRO_EVENT_TIMER) { for (i = 0; i < MAX_SQUARES; i++) { animate_square(&squares[i]); } theta += 0.1; redraw = true; } else if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } else if (event.type == ALLEGRO_EVENT_KEY_DOWN && event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) { break; } else if (event.type == ALLEGRO_EVENT_DISPLAY_RESIZE) { al_acknowledge_resize(event.display.source); } } Quit: if (timer) { al_destroy_timer(timer); } if (queue) { al_destroy_event_queue(queue); } if (display) { al_destroy_display(display); } return NULL; } int main(int argc, char **argv) { ALLEGRO_THREAD *thread[MAX_THREADS]; Background background[MAX_BACKGROUNDS] = { { 1.0, 0.5, 0.5 }, { 0.5, 1.0, 0.5 }, { 0.5, 0.5, 1.0 }, { 1.0, 1.0, 0.5 }, { 0.5, 1.0, 1.0 }, { 1.0, 0.7, 0.5 }, { 0.5, 1.0, 0.7 }, { 0.7, 0.5, 1.0 }, { 1.0, 0.7, 0.5 }, { 0.5, 0.7, 1.0 } }; int num_threads; int i; if (argc > 1) { num_threads = strtol(argv[1], NULL, 10); if (num_threads > MAX_THREADS) num_threads = MAX_THREADS; else if (num_threads < 1) num_threads = 1; } else { num_threads = 3; } if (!al_init()) { abort_example("Could not init Allegro.\n"); } al_init_primitives_addon(); al_install_keyboard(); al_install_mouse(); for (i = 0; i < num_threads; i++) { thread[i] = al_create_thread(thread_func, &background[i % MAX_BACKGROUNDS]); } for (i = 0; i < num_threads; i++) { al_start_thread(thread[i]); } for (i = 0; i < num_threads; i++) { al_join_thread(thread[i], NULL); al_destroy_thread(thread[i]); } return 0; } /* vim: set sts=3 sw=3 et: */
2,739
424
package com.twitter.elephantbird.pig.store; import java.io.IOException; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.pig.data.Tuple; import com.google.protobuf.Message; import com.google.protobuf.Message.Builder; import com.twitter.elephantbird.mapreduce.io.ProtobufWritable; import com.twitter.elephantbird.mapreduce.output.RCFileProtobufOutputFormat; import com.twitter.elephantbird.pig.util.PigToProtobuf; import com.twitter.elephantbird.util.Protobufs; import com.twitter.elephantbird.util.TypeRef; /** * StoreFunc for storing Protobuf messages in RCFiles. <p> * * @see {@link RCFileProtobufOutputFormat} */ public class RCFileProtobufPigStorage extends BaseStoreFunc { // add stats? private TypeRef<? extends Message> typeRef; private Builder msgBuilder; private ProtobufWritable<Message> writable; public RCFileProtobufPigStorage(String protoClassName) { typeRef = Protobufs.getTypeRef(protoClassName); msgBuilder = Protobufs.getMessageBuilder(typeRef.getRawClass()); writable = ProtobufWritable.newInstance(Message.class); } @Override @SuppressWarnings("unchecked") public OutputFormat getOutputFormat() throws IOException { return new RCFileProtobufOutputFormat(typeRef); } public void putNext(Tuple t) throws IOException { Message msg = PigToProtobuf.tupleToMessage(msgBuilder.clone(), t); writable.set(msg); writeRecord(null, writable); } }
480
647
<gh_stars>100-1000 #ifndef TEST_VIEW_HH #define TEST_VIEW_HH #include <sstream> #include "string.h" #include "DPV/DPV_view.hh" #include "DPC/DPC_product.hh" class Test_view: public DPV_view { public: Test_view() {}; ~Test_view() {}; DPV_pointer render_product( DPC_product* product); DPV_pointer render_page( DPV_pointer parent_data, DPC_page* page); DPV_pointer render_plot( DPV_pointer parent_data, DPC_plot* plot); DPV_pointer render_table( DPV_pointer parent_data, DPC_table* table); DPV_pointer render_curve( DPV_pointer parent_data, DPC_curve* curve); void finalize_product_view( DPV_pointer product_view ); void finalize_page_view( DPV_pointer page_view ); void finalize_plot_view( DPV_pointer plot_view ); void finalize_table_view( DPV_pointer table_view ); /** * The following functions are unused from abstract class DPV_view */ void notify_product( DPV_pointer, DPV_message) {}; void notify_page( DPV_pointer, DPV_message) {}; void notify_table( DPV_pointer, DPV_message) {}; void notify_plot( DPV_pointer, DPV_message) {}; void notify_curve( DPV_pointer, DPV_message) {}; std::string getOutput(); private: std::stringstream s; }; #endif
478
764
<gh_stars>100-1000 {"symbol": "ALPHR","address": "0xaa99199d1e9644b588796F3215089878440D58e0","overview":{"en": ""},"email": "","website": "https://www.alphr.finance/","state": "NORMAL","links": {"blog": "https://medium.com/alphr-finance","twitter": "https://twitter.com/alphrfinance","telegram": "","github": ""}}
117
309
// Copyright 2019 the deepx authors. // Author: <NAME> (<EMAIL>) // #include <deepx_core/common/array_view_io.h> #include <deepx_core/ps/dist_message.h> namespace deepx_core { /************************************************************************/ /* DistMessage */ /************************************************************************/ bool DistMessage::HasResponse() const noexcept { return HasResponse(type_); } bool DistMessage::HasResponse(int type) noexcept { switch (type) { case DIST_MESSAGE_TYPE_ECHO_REQUEST: case DIST_MESSAGE_TYPE_FILE_REQUEST: case DIST_MESSAGE_TYPE_PULL_REQUEST: case DIST_MESSAGE_TYPE_MODEL_SAVE_REQUEST: case DIST_MESSAGE_TYPE_USER_REQUEST: return true; default: return false; } } OutputStringStream& operator<<(OutputStringStream& os, const DistMessage& message) { os.BeginMessage(); os << message.type(); switch (message.type()) { case DIST_MESSAGE_TYPE_ECHO_REQUEST: os << message.echo_request().buf; break; case DIST_MESSAGE_TYPE_ECHO_RESPONSE: os << message.echo_response().buf; break; case DIST_MESSAGE_TYPE_HEART_BEAT_NOTIFY: break; case DIST_MESSAGE_TYPE_FILE_REQUEST: break; case DIST_MESSAGE_TYPE_FILE_RESPONSE: os << message.file_response().epoch; os << message.file_response().file; break; case DIST_MESSAGE_TYPE_FILE_FINISH_NOTIFY: os << message.file_finish_notify().file; os << message.file_finish_notify().loss; os << message.file_finish_notify().loss_weight; break; case DIST_MESSAGE_TYPE_PULL_REQUEST: os << message.pull_request().buf; break; case DIST_MESSAGE_TYPE_PULL_RESPONSE: os << message.pull_response().buf; break; case DIST_MESSAGE_TYPE_PUSH_NOTIFY: os << message.push_notify().buf; break; case DIST_MESSAGE_TYPE_MODEL_SAVE_REQUEST: os << message.model_save_request().epoch; os << message.model_save_request().timestamp; os << message.model_save_request().feature_kv_protocol_version; break; case DIST_MESSAGE_TYPE_MODEL_SAVE_RESPONSE: break; case DIST_MESSAGE_TYPE_TERMINATION_NOTIFY: break; case DIST_MESSAGE_TYPE_USER_REQUEST: os << message.user_request().buf; break; case DIST_MESSAGE_TYPE_USER_RESPONSE: os << message.user_response().buf; break; case DIST_MESSAGE_TYPE_USER_NOTIFY: os << message.user_notify().buf; break; } os.EndMessage(); return os; } /************************************************************************/ /* DistMessageView */ /************************************************************************/ bool DistMessageView::HasResponse() const noexcept { return HasResponse(type_); } bool DistMessageView::HasResponse(int type) noexcept { switch (type) { case DIST_MESSAGE_TYPE_ECHO_REQUEST: case DIST_MESSAGE_TYPE_FILE_REQUEST: case DIST_MESSAGE_TYPE_PULL_REQUEST: case DIST_MESSAGE_TYPE_MODEL_SAVE_REQUEST: case DIST_MESSAGE_TYPE_USER_REQUEST: return true; default: return false; } } InputStringStream& ReadView(InputStringStream& is, DistMessageView& message) { int place_holder, type; ReadView(is, place_holder); ReadView(is, type); if (!is) { return is; } message.set_type(type); switch (type) { case DIST_MESSAGE_TYPE_ECHO_REQUEST: ReadView(is, message.mutable_echo_request()->buf); break; case DIST_MESSAGE_TYPE_ECHO_RESPONSE: ReadView(is, message.mutable_echo_response()->buf); break; case DIST_MESSAGE_TYPE_HEART_BEAT_NOTIFY: break; case DIST_MESSAGE_TYPE_FILE_REQUEST: break; case DIST_MESSAGE_TYPE_FILE_RESPONSE: ReadView(is, message.mutable_file_response()->epoch); ReadView(is, message.mutable_file_response()->file); break; case DIST_MESSAGE_TYPE_FILE_FINISH_NOTIFY: ReadView(is, message.mutable_file_finish_notify()->file); ReadView(is, message.mutable_file_finish_notify()->loss); ReadView(is, message.mutable_file_finish_notify()->loss_weight); break; case DIST_MESSAGE_TYPE_PULL_REQUEST: ReadView(is, message.mutable_pull_request()->buf); break; case DIST_MESSAGE_TYPE_PULL_RESPONSE: ReadView(is, message.mutable_pull_response()->buf); break; case DIST_MESSAGE_TYPE_PUSH_NOTIFY: ReadView(is, message.mutable_push_notify()->buf); break; case DIST_MESSAGE_TYPE_MODEL_SAVE_REQUEST: ReadView(is, message.mutable_model_save_request()->epoch); ReadView(is, message.mutable_model_save_request()->timestamp); ReadView( is, message.mutable_model_save_request()->feature_kv_protocol_version); break; case DIST_MESSAGE_TYPE_MODEL_SAVE_RESPONSE: break; case DIST_MESSAGE_TYPE_TERMINATION_NOTIFY: break; case DIST_MESSAGE_TYPE_USER_REQUEST: ReadView(is, message.mutable_user_request()->buf); break; case DIST_MESSAGE_TYPE_USER_RESPONSE: ReadView(is, message.mutable_user_response()->buf); break; case DIST_MESSAGE_TYPE_USER_NOTIFY: ReadView(is, message.mutable_user_notify()->buf); break; } return is; } } // namespace deepx_core
2,287
462
#include <gb/gb.h> #include <stdint.h> int var_0; /* In external RAM bank 0 */
34
8,633
from prefect.agent.ecs.agent import ECSAgent
15
318
<filename>Gep/Source/dc/main.cpp #include <kos.h> #include <string.h> #include "types.h" #include "main.h" #include "console.h" #include "mainloop.h" /* You can safely remove this line if you don't use a ROMDISK */ //extern uint8 romdisk[]; /* Your program's main entry point */ int main(int argc, char **argv) { int i; /* Initialize KOS. This initializes everything in KOS so it's ready go to after this line. You can set individual things to initialize here, or you can enable sets of things with the following special macros: ALL_ENABLE -- enables EVERYTHING BASIC_ENABLE -- enables basic kernel services, no platform specific goodies like 3D NONE_ENABLE -- don't do anything Also you may replace "romdisk" with ROMDISK_NONE if you don't want to use a ROMDISK image. */ // kos_init_all(ALL_ENABLE & (~PVR_ENABLE) & (~TA_ENABLE), ROMDISK_NONE); kos_init_all(ALL_ENABLE & (~PVR_ENABLE) & (~TA_ENABLE) & (~THD_ENABLE), ROMDISK_NONE); ConInit(); if (MainLoopInit()) { // do stuff here while (MainLoopProcess()) { } MainLoopShutdown(); } ConShutdown(); /* Shut everything down: not technically required, but a good idea to do this... */ kos_shutdown_all(); return 0; }
518
14,668
<reponame>zealoussnow/chromium // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_BUFFERING_BYTES_CONSUMER_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_BUFFERING_BYTES_CONSUMER_H_ #include "base/memory/scoped_refptr.h" #include "base/types/pass_key.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/loader/fetch/bytes_consumer.h" #include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/blink/renderer/platform/timer.h" #include "third_party/blink/renderer/platform/wtf/deque.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { // BufferingBytesConsumer is a BytesConsumer. It takes a BytesConsumer // ("the original BytesConsumer") as a constructor parameter, and results read // from the BufferingBytesConsumer are as same as results which would be read // from the original BytesConsumer. // BufferingBytesConsumer buffers reads chunks from the original BytesConsumer // and store it until they are read, before read requests are issued from the // client. class PLATFORM_EXPORT BufferingBytesConsumer final : public BytesConsumer, private BytesConsumer::Client { public: // Creates a BufferingBytesConsumer that waits some delay before beginning // to buffer data from the underlying consumer. This delay provides an // opportunity for the data to be drained before buffering begins. The // |bytes_consumer| is the original BytesConsumer. |bytes_consumer| must // not have a client. static BufferingBytesConsumer* CreateWithDelay( BytesConsumer* bytes_consumer, scoped_refptr<base::SingleThreadTaskRunner> timer_task_runner); // Creates a BufferingBytesConsumer that buffers immediately without any // delay. |bytes_consumer| is the original BytesConsumer. |bytes_consumer| // must not have a client. static BufferingBytesConsumer* Create(BytesConsumer* bytes_consumer); // Use the Create*() factory methods instead of direct instantiation. BufferingBytesConsumer( base::PassKey<BufferingBytesConsumer> key, BytesConsumer* bytes_consumer, scoped_refptr<base::SingleThreadTaskRunner> timer_task_runner, base::TimeDelta buffering_start_delay); ~BufferingBytesConsumer() override; // Attempt to start buffering data from the underlying consumer. This will // only have an effect if we're currently in the kDelayed state. If // buffering has already started or been explicitly stopped then this method // has no effect. void MaybeStartBuffering(); // After this function is called, |this| will not do buffering. Already // buffered data still waits to be consumed, but after all the buffered data // is consumed, BeginRead and EndRead will result in BeginRead and EndRead // calls to the original BytesConsumer. void StopBuffering(); // BufferingBytesConsumer Result BeginRead(const char** buffer, size_t* available) override; Result EndRead(size_t read_size) override; scoped_refptr<BlobDataHandle> DrainAsBlobDataHandle(BlobSizePolicy) override; scoped_refptr<EncodedFormData> DrainAsFormData() override; mojo::ScopedDataPipeConsumerHandle DrainAsDataPipe() override; void SetClient(BytesConsumer::Client*) override; void ClearClient() override; void Cancel() override; PublicState GetPublicState() const override; Error GetError() const override; String DebugName() const override { return "BufferingBytesConsumer"; } void Trace(Visitor*) const override; private: void OnTimerFired(TimerBase*); // BufferingBytesConsumer::Client void OnStateChange() override; void BufferData(); const Member<BytesConsumer> bytes_consumer_; HeapTaskRunnerTimer<BufferingBytesConsumer> timer_; Deque<Vector<char>> buffer_; size_t offset_for_first_chunk_ = 0; enum class BufferingState { kDelayed, kStarted, kStopped, }; BufferingState buffering_state_ = BufferingState::kDelayed; bool has_seen_end_of_data_ = false; bool has_seen_error_ = false; Member<BytesConsumer::Client> client_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_BUFFERING_BYTES_CONSUMER_H_
1,354
1,166
// Copyright (c) 2021 Ximalaya Speech Team (<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. #include "grpc/grpc_client.h" #include "utils/log.h" namespace wenet { using grpc::Channel; using grpc::ClientContext; using grpc::ClientReaderWriter; using grpc::Status; using wenet::Request; using wenet::Response; GrpcClient::GrpcClient(const std::string& host, int port, int nbest, bool continuous_decoding) : host_(host), port_(port), nbest_(nbest), continuous_decoding_(continuous_decoding) { Connect(); t_.reset(new std::thread(&GrpcClient::ReadLoopFunc, this)); } void GrpcClient::Connect() { channel_ = grpc::CreateChannel(host_ + ":" + std::to_string(port_), grpc::InsecureChannelCredentials()); stub_ = ASR::NewStub(channel_); context_ = std::make_shared<ClientContext>(); stream_ = stub_->Recognize(context_.get()); request_ = std::make_shared<Request>(); response_ = std::make_shared<Response>(); request_->mutable_decode_config()->set_nbest_config(nbest_); request_->mutable_decode_config()->set_continuous_decoding_config( continuous_decoding_); stream_->Write(*request_); } void GrpcClient::SendBinaryData(const void* data, size_t size) { const int16_t* pdata = reinterpret_cast<const int16_t*>(data); request_->set_audio_data(pdata, size); stream_->Write(*request_); } void GrpcClient::ReadLoopFunc() { try { while (stream_->Read(response_.get())) { for (int i = 0; i < response_->nbest_size(); i++) { // you can also traverse wordpieces like demonstrated above LOG(INFO) << i + 1 << "best " << response_->nbest(i).sentence(); } if (response_->status() != Response_Status_ok) { break; } if (response_->type() == Response_Type_speech_end) { done_ = true; break; } } } catch (std::exception const& e) { LOG(ERROR) << e.what(); } } void GrpcClient::Join() { stream_->WritesDone(); t_->join(); Status status = stream_->Finish(); if (!status.ok()) { LOG(INFO) << "Recognize rpc failed."; } } } // namespace wenet
989
3,212
<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.nifi.components.validation; import org.apache.nifi.controller.ComponentNode; import org.apache.nifi.controller.flow.FlowManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TriggerValidationTask implements Runnable { private static final Logger logger = LoggerFactory.getLogger(TriggerValidationTask.class); private final FlowManager flowManager; private final ValidationTrigger validationTrigger; public TriggerValidationTask(final FlowManager flowManager, final ValidationTrigger validationTrigger) { this.flowManager = flowManager; this.validationTrigger = validationTrigger; } @Override public void run() { try { logger.debug("Triggering validation of all components"); for (final ComponentNode node : flowManager.getAllControllerServices()) { validationTrigger.trigger(node); } for (final ComponentNode node : flowManager.getAllReportingTasks()) { validationTrigger.trigger(node); } for (final ComponentNode node : flowManager.getRootGroup().findAllProcessors()) { validationTrigger.trigger(node); } } catch (final Throwable t) { logger.error("Encountered unexpected error when attempting to validate components", t); } } }
703
2,805
<gh_stars>1000+ # encoding: utf-8 """057 Tracking Revision ID: 660a5aae527e Revises: <PASSWORD> Create Date: 2018-09-04 18:49:08.573692 """ from alembic import op import sqlalchemy as sa from ckan.migration import skip_based_on_legacy_engine_version # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade(): if skip_based_on_legacy_engine_version(op, __name__): return op.create_table( 'tracking_raw', sa.Column('user_key', sa.String(100), nullable=False), sa.Column('url', sa.UnicodeText, nullable=False), sa.Column('tracking_type', sa.String(10), nullable=False), sa.Column( 'access_timestamp', sa.TIMESTAMP, server_default=sa.func.current_timestamp() ) ) op.create_index('tracking_raw_url', 'tracking_raw', ['url']) op.create_index('tracking_raw_user_key', 'tracking_raw', ['user_key']) op.create_index( 'tracking_raw_access_timestamp', 'tracking_raw', ['access_timestamp'] ) op.create_table( 'tracking_summary', sa.Column('url', sa.UnicodeText, nullable=False), sa.Column('package_id', sa.UnicodeText), sa.Column('tracking_type', sa.String(10), nullable=False), sa.Column('count', sa.Integer, nullable=False), sa.Column( 'running_total', sa.Integer, nullable=False, server_default='0' ), sa.Column( 'recent_views', sa.Integer, nullable=False, server_default='0' ), sa.Column('tracking_date', sa.Date) ) op.create_index('tracking_summary_url', 'tracking_summary', ['url']) op.create_index( 'tracking_summary_package_id', 'tracking_summary', ['package_id'] ) op.create_index( 'tracking_summary_date', 'tracking_summary', ['tracking_date'] ) def downgrade(): op.drop_table('tracking_summary') op.drop_table('tracking_raw')
842
2,151
// Copyright 2017 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 COMPONENTS_ARC_CONNECTION_NOTIFIER_H_ #define COMPONENTS_ARC_CONNECTION_NOTIFIER_H_ #include "base/macros.h" #include "base/observer_list.h" #include "base/threading/thread_checker.h" namespace arc { namespace internal { class ConnectionObserverBase; // Manages events related to connection. Designed to be used only by // ConnectionHolder. class ConnectionNotifier { public: ConnectionNotifier(); ~ConnectionNotifier(); void AddObserver(ConnectionObserverBase* observer); void RemoveObserver(ConnectionObserverBase* observer); // Notifies observers that connection gets ready. void NotifyConnectionReady(); // Notifies observers that connection is closed. void NotifyConnectionClosed(); private: THREAD_CHECKER(thread_checker_); base::ObserverList<ConnectionObserverBase> observer_list_; DISALLOW_COPY_AND_ASSIGN(ConnectionNotifier); }; } // namespace internal } // namespace arc #endif // COMPONENTS_ARC_CONNECTION_NOTIFIER_H_
344
1,323
{ "stages": [ { "services": {}, "stageName": "quality-gate-test" } ], "creationDate": "1629211070179837245", "gitRemoteURI": "https://github.com/carpe-github/claus-tenant-dev.git", "gitUser": "carpe-github", "projectName": "testproject", "shipyard": "apiVersion: \"spec.keptn.sh/0.2.0\" kind: \"Shipyard\" metadata: name: \"shipyard-quality-gates\" spec: stages: - name: \"quality-gate-test\"", "shipyardVersion": "spec.keptn.sh/0.2.0" }
198
5,169
{ "name": "QueueITLibrary", "version": "3.0.1", "summary": "Library for integrating Queue-it into an iOS app using web uI", "homepage": "https://github.com/queueit/ios-webui-sdk", "license": "MIT", "authors": { "Queue-It": "https://queue-it.com" }, "platforms": { "ios": "9.3" }, "source": { "git": "https://github.com/queueit/ios-webui-sdk.git", "tag": "3.0.1" }, "requires_arc": true, "source_files": "QueueITLib/*.{h,m}" }
206