max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
535 | /*
* 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.
*/
//
// Fetch the resources asynchronously using envoy. The fetcher is called in
// the rewrite thread.
//
#pragma once
#include <vector>
#include "envoy_cluster_manager.h"
#include "envoy_fetch.h"
#include "envoy_logger.h"
#include "net/instaweb/http/public/url_async_fetcher.h"
#include "pagespeed/kernel/base/basictypes.h"
#include "pagespeed/kernel/base/pool.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/thread_system.h"
namespace net_instaweb {
class AsyncFetch;
class MessageHandler;
class Statistics;
class Variable;
class EnvoyFetch;
struct EnvoyStats {
static const char kEnvoyFetchRequestCount[];
static const char kEnvoyFetchByteCount[];
static const char kEnvoyFetchTimeDurationMs[];
static const char kEnvoyFetchCancelCount[];
static const char kEnvoyFetchActiveCount[];
static const char kEnvoyFetchTimeoutCount[];
static const char kEnvoyFetchFailureCount[];
static const char kEnvoyFetchCertErrors[];
static const char kEnvoyFetchReadCalls[];
// A fetch that finished with a 2xx or a 3xx code --- and not just a
// mechanically successful one that's a 4xx or such.
static const char kEnvoyFetchUltimateSuccess[];
// A failure or an error status. Doesn't include fetches dropped due to
// process exit and the like.
static const char kEnvoyFetchUltimateFailure[];
// When we last checked the ultimate failure/success numbers for a
// possible concern.
static const char kEnvoyFetchLastCheckTimestampMs[];
};
class EnvoyUrlAsyncFetcher : public UrlAsyncFetcher {
public:
EnvoyUrlAsyncFetcher(const char* proxy, ThreadSystem* thread_system,
Statistics* statistics, Timer* timer, int64 timeout_ms,
MessageHandler* handler);
~EnvoyUrlAsyncFetcher() override;
static void InitStats(Statistics* statistics);
// It should be called in the module init_process callback function. Do some
// intializations which can't be done in the master process
bool Init();
// shutdown all the fetches.
void ShutDown() override;
bool SupportsHttps() const override { return false; }
void Fetch(const GoogleString& url, MessageHandler* message_handler,
AsyncFetch* callback) override;
// Remove the completed fetch from the active fetch set, and put it into a
// completed fetch list to be cleaned up.
void FetchComplete(EnvoyFetch* fetch);
void PrintActiveFetches(MessageHandler* handler) const;
// Indicates that it should track the original content length for
// fetched resources.
bool track_original_content_length() {
return track_original_content_length_;
}
void set_track_original_content_length(bool x) {
track_original_content_length_ = x;
}
// AnyPendingFetches is accurate only at the time of call; this is
// used conservatively during shutdown. It counts fetches that have been
// requested by some thread, and can include fetches for which no action
// has yet been taken (ie fetches that are not active).
virtual bool AnyPendingFetches() { return !active_fetches_.empty(); }
// ApproximateNumActiveFetches can under- or over-count and is used only for
// error reporting.
int ApproximateNumActiveFetches() { return active_fetches_.size(); }
void CancelActiveFetches();
// These must be accessed with mutex_ held.
bool shutdown() const { return shutdown_; }
void set_shutdown(bool s) { shutdown_ = s; }
protected:
typedef Pool<EnvoyFetch> EnvoyFetchPool;
private:
void FetchWithEnvoy();
static void TimeoutHandler();
static bool ParseUrl();
friend class EnvoyFetch;
EnvoyFetchPool active_fetches_;
std::unique_ptr<EnvoyClusterManager> cluster_manager_ptr_;
std::unique_ptr<PagespeedLogSink> envoy_log_sink_;
EnvoyFetchPool pending_fetches_;
EnvoyFetchPool completed_fetches_;
char* proxy_;
int fetchers_count_;
bool shutdown_;
bool track_original_content_length_;
int64 byte_count_;
ThreadSystem* thread_system_;
MessageHandler* message_handler_;
// Protect the member variable in this class
// active_fetches, pending_fetches
ThreadSystem::CondvarCapableMutex* mutex_;
int64 resolver_timeout_;
int64 fetch_timeout_;
DISALLOW_COPY_AND_ASSIGN(EnvoyUrlAsyncFetcher);
};
} // namespace net_instaweb | 1,550 |
1,096 | <reponame>mostafa-yasen/evillimiter
import os
import subprocess
from evillimiter.console.io import IO
DEVNULL = open(os.devnull, 'w')
def execute(command, root=True):
return subprocess.call('sudo ' + command if root else command, shell=True)
def execute_suppressed(command, root=True):
return subprocess.call('sudo ' + command if root else command, shell=True, stdout=DEVNULL, stderr=DEVNULL)
def output(command, root=True):
return subprocess.check_output('sudo ' + command if root else command, shell=True).decode('utf-8')
def output_suppressed(command, root=True):
return subprocess.check_output('sudo ' + command if root else command, shell=True, stderr=DEVNULL).decode('utf-8')
def locate_bin(name):
try:
return output_suppressed('which {}'.format(name)).replace('\n', '')
except subprocess.CalledProcessError:
IO.error('missing util: {}, check your PATH'.format(name)) | 311 |
1,743 | <filename>tests/resources/apiritif/test_nfc.py
# coding=utf-8
import logging
import random
import string
import sys
import unittest
from time import time, sleep
import apiritif
log = logging.getLogger('apiritif.http')
log.addHandler(logging.StreamHandler(sys.stdout))
log.setLevel(logging.DEBUG)
class TestSc1(unittest.TestCase):
def setUp(self):
self.vars = {}
timeout = 2.0
apiritif.put_into_thread_store(timeout=timeout, func_mode=False, scenario_name='sc1')
def _1_httpsblazedemocomsetup1(self):
with apiritif.smart_transaction('https://blazedemo.com/setup1'):
response = apiritif.http.get('https://blazedemo.com/setup1', timeout=2.0)
def _2_httpsblazedemocomsetup2(self):
with apiritif.smart_transaction('https://blazedemo.com/setup2'):
response = apiritif.http.get('https://blazedemo.com/setup2', timeout=2.0)
def _3_httpsblazedemocommain1(self):
with apiritif.smart_transaction('https://blazedemo.com/main1'):
response = apiritif.http.get('https://blazedemo.com/main1', timeout=2.0)
def _4_httpsblazedemocommain2(self):
with apiritif.smart_transaction('https://blazedemo.com/main2'):
response = apiritif.http.get('https://blazedemo.com/main2', timeout=2.0)
def _5_httpsblazedemocommain3(self):
with apiritif.smart_transaction('https://blazedemo.com/main3'):
response = apiritif.http.get('https://blazedemo.com/main3', timeout=2.0)
def _6_httpsblazedemocomteardown1(self):
with apiritif.smart_transaction('https://blazedemo.com/teardown1'):
response = apiritif.http.get('https://blazedemo.com/teardown1', timeout=2.0)
def _7_httpsblazedemocomteardown2(self):
with apiritif.smart_transaction('https://blazedemo.com/teardown2'):
response = apiritif.http.get('https://blazedemo.com/teardown2', timeout=2.0)
def test_sc1(self):
try:
self._1_httpsblazedemocomsetup1()
self._2_httpsblazedemocomsetup2()
self._3_httpsblazedemocommain1()
self._4_httpsblazedemocommain2()
self._5_httpsblazedemocommain3()
finally:
apiritif.set_stage("teardown") # can't be interrupted
self._6_httpsblazedemocomteardown1()
self._7_httpsblazedemocomteardown2()
| 1,051 |
3,799 | <reponame>chris-horner/androidx
/*
* Copyright 2020 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 androidx.mediarouter.media;
import static androidx.annotation.RestrictTo.Scope.LIBRARY;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* MediaRouterParams are used in {@link MediaRouter} to denote routing functionality and UI types.
*/
public class MediaRouterParams {
/**
* A dialog type used for default if not set.
* {@link androidx.mediarouter.app.MediaRouteChooserDialog} and
* {@link androidx.mediarouter.app.MediaRouteControllerDialog} will be shown
*/
public static final int DIALOG_TYPE_DEFAULT = 1;
/**
* A dialog type supporting dynamic group.
* Users can dynamically group and ungroup route devices via this type of route dialog when the
* selected routes are from a {@link MediaRouteProvider} that supports dynamic group.
*/
public static final int DIALOG_TYPE_DYNAMIC_GROUP = 2;
/**
* @hide
*/
@RestrictTo(LIBRARY)
@IntDef({DIALOG_TYPE_DEFAULT, DIALOG_TYPE_DYNAMIC_GROUP})
@Retention(RetentionPolicy.SOURCE)
public @interface DialogType {}
/**
* Bundle key used for enabling group volume UX. The default value is {@code true}.
* To disable the group volume UX, set the value {@code false}.
*
* <p>TYPE: boolean
*/
public static final String ENABLE_GROUP_VOLUME_UX =
"androidx.mediarouter.media.MediaRouterParams.ENABLE_GROUP_VOLUME_UX";
/**
* Bundle key used for setting the cast icon fixed regardless of its connection state.
*
* <p>TYPE: boolean
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
public static final String EXTRAS_KEY_FIXED_CAST_ICON =
"androidx.mediarouter.media.MediaRouterParams.FIXED_CAST_ICON";
@DialogType
final int mDialogType;
final boolean mOutputSwitcherEnabled;
final boolean mTransferToLocalEnabled;
final Bundle mExtras;
MediaRouterParams(@NonNull Builder builder) {
mDialogType = builder.mDialogType;
mOutputSwitcherEnabled = builder.mOutputSwitcherEnabled;
mTransferToLocalEnabled = builder.mTransferToLocalEnabled;
Bundle extras = builder.mExtras;
mExtras = extras == null ? Bundle.EMPTY : new Bundle(extras);
}
/**
* Gets the media route controller dialog type.
*
* @see Builder#setDialogType(int)
*/
public @DialogType int getDialogType() {
return mDialogType;
}
/**
* Gets whether the output switcher dialog is enabled.
* <p>
* Note that it always returns {@code false} for Android versions earlier than Android R.
*
* @see Builder#setOutputSwitcherEnabled(boolean)
*/
public boolean isOutputSwitcherEnabled() {
return mOutputSwitcherEnabled;
}
/**
* Returns whether transferring media from remote to local is enabled.
* <p>
* Note that it always returns {@code false} for Android versions earlier than Android R.
*
* @see Builder#setTransferToLocalEnabled(boolean)
*/
public boolean isTransferToLocalEnabled() {
return mTransferToLocalEnabled;
}
/**
* @hide
*/
@NonNull
@RestrictTo(RestrictTo.Scope.LIBRARY)
public Bundle getExtras() {
return mExtras;
}
/**
* Builder class for {@link MediaRouterParams}.
*/
public static final class Builder {
@DialogType
int mDialogType = DIALOG_TYPE_DEFAULT;
boolean mOutputSwitcherEnabled;
boolean mTransferToLocalEnabled;
Bundle mExtras;
/**
* Constructor for builder to create {@link MediaRouterParams}.
*/
public Builder() {}
/**
* Constructor for builder to create {@link MediaRouterParams} with existing
* {@link MediaRouterParams} instance.
*
* @param params the existing instance to copy data from.
*/
public Builder(@NonNull MediaRouterParams params) {
if (params == null) {
throw new NullPointerException("params should not be null!");
}
mDialogType = params.mDialogType;
mOutputSwitcherEnabled = params.mOutputSwitcherEnabled;
mTransferToLocalEnabled = params.mTransferToLocalEnabled;
mExtras = params.mExtras == null ? null : new Bundle(params.mExtras);
}
/**
* Sets the media route controller dialog type. Default value is
* {@link #DIALOG_TYPE_DEFAULT}.
* <p>
* Note that from Android R, output switcher will be used rather than the dialog type set by
* this method if both {@link #setOutputSwitcherEnabled(boolean)} output switcher} and
* {@link MediaTransferReceiver media transfer feature} are enabled.
*
* @param dialogType the dialog type
* @see #setOutputSwitcherEnabled(boolean)
* @see #DIALOG_TYPE_DEFAULT
* @see #DIALOG_TYPE_DYNAMIC_GROUP
*/
@NonNull
public Builder setDialogType(@DialogType int dialogType) {
mDialogType = dialogType;
return this;
}
/**
* Sets whether output switcher dialogs are enabled. This method will be no-op for Android
* versions earlier than Android R. Default value is {@code false}.
* <p>
* If set to {@code true}, and when {@link MediaTransferReceiver media transfer is enabled},
* {@link androidx.mediarouter.app.MediaRouteButton MediaRouteButton} will show output
* switcher when clicked, no matter what type of dialog is set by
* {@link #setDialogType(int)}.
* <p>
* If set to {@code false}, {@link androidx.mediarouter.app.MediaRouteButton
* MediaRouteButton} will show the dialog type which is set by {@link #setDialogType(int)}.
*/
@NonNull
public Builder setOutputSwitcherEnabled(boolean enabled) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
mOutputSwitcherEnabled = enabled;
}
return this;
}
/**
* Enables media can be transferred from remote (e.g. TV) to local (e.g. phone, Bluetooth).
* Apps that enabling this feature should handle the case in their {@link
* MediaRouter.Callback#onRouteSelected(MediaRouter, MediaRouter.RouteInfo, int) callback}
* properly. Default value is {@code false}.
* <p>
* When this is enabled, {@link MediaRouter.Callback#onRouteSelected(MediaRouter,
* MediaRouter.RouteInfo, int, MediaRouter.RouteInfo)} will be called whenever the
* 'remote to local' transfer happens, regardless of the selector provided in
* {@link MediaRouter#addCallback(MediaRouteSelector, MediaRouter.Callback)}.
* <p>
* Note: This method will be no-op for Android versions earlier than Android R. It has
* effect only when {@link MediaTransferReceiver media transfer is enabled}.
*/
@NonNull
public Builder setTransferToLocalEnabled(boolean enabled) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
mTransferToLocalEnabled = enabled;
}
return this;
}
/**
* Set extras. Default value is {@link Bundle#EMPTY} if not set.
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY)
@NonNull
public Builder setExtras(@Nullable Bundle extras) {
mExtras = (extras == null) ? null : new Bundle(extras);
return this;
}
/**
* Builds the {@link MediaRouterParams} instance.
*/
@NonNull
public MediaRouterParams build() {
return new MediaRouterParams(this);
}
}
}
| 3,398 |
488 | <filename>tests/roseTests/astInterfaceTests/typeEquivalenceTests/inputFiles/types_016.cpp<gh_stars>100-1000
//0
// array types equal
const int v = 10;
int a[v];
int b[10];
| 65 |
636 | package cn.org.atool.fluent.mybatis.segment;
import cn.org.atool.fluent.mybatis.base.crud.IQuery;
import cn.org.atool.fluent.mybatis.base.model.ISqlOp;
import cn.org.atool.fluent.mybatis.functions.IAggregate;
import cn.org.atool.fluent.mybatis.segment.fragment.BracketFrag;
import cn.org.atool.fluent.mybatis.segment.fragment.CachedFrag;
import cn.org.atool.fluent.mybatis.segment.fragment.IFragment;
import cn.org.atool.fluent.mybatis.segment.model.IOperator;
import static cn.org.atool.fluent.mybatis.utility.MybatisUtil.assertNotNull;
/**
* HavingOperator: having聚合操作
*
* @param <H> Having操作器
* @author wudarui
*/
@SuppressWarnings({"rawtypes"})
public class HavingOperator<H extends HavingBase<H, ?>>
implements IOperator<H> {
/**
* 表达式
*/
private IFragment expression;
private final H having;
HavingOperator(H having) {
this.having = having;
}
@Override
public H apply(ISqlOp op, Object... args) {
assertNotNull("expression", expression);
return this.having.aggregate(expression, op, args);
}
/**
* having aggregate(column) op (select ...)
*
* @param op 比较符
* @param query 子查询
* @return H
*/
public H apply(ISqlOp op, IQuery query) {
assertNotNull("query", query);
query.data().sharedParameter(this.having.data());
return this.having.apply(expression, op, BracketFrag.set(query));
}
/**
* having aggregate(column) op func(args)
*
* @param op 比较符
* @param func 函数
* @param args 参数
* @return H
*/
public H applyFunc(ISqlOp op, String func, Object... args) {
assertNotNull("func", func);
return this.having.apply(expression, op, CachedFrag.set(func), args);
}
/**
* 设置聚合函数表达式
*
* @param column 聚合字段
* @param aggregate 聚合函数
* @return 操作器
*/
HavingOperator<H> aggregate(IFragment column, IAggregate aggregate) {
this.expression = aggregate.aggregate(column);
return this;
}
} | 955 |
6,989 | <reponame>henrytien/tcmalloc
// Copyright 2019 The TCMalloc 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.
#ifndef TCMALLOC_PEAK_HEAP_TRACKER_H_
#define TCMALLOC_PEAK_HEAP_TRACKER_H_
#include "absl/base/thread_annotations.h"
#include "tcmalloc/common.h"
#include "tcmalloc/internal/atomic_stats_counter.h"
#include "tcmalloc/internal/logging.h"
#include "tcmalloc/malloc_extension.h"
GOOGLE_MALLOC_SECTION_BEGIN
namespace tcmalloc {
namespace tcmalloc_internal {
class PeakHeapTracker {
public:
constexpr PeakHeapTracker() : peak_sampled_span_stacks_(nullptr) {}
// Possibly save high-water-mark allocation stack traces for peak-heap
// profile. Should be called immediately after sampling an allocation. If
// the heap has grown by a sufficient amount since the last high-water-mark,
// it will save a copy of the sample profile.
void MaybeSaveSample() ABSL_LOCKS_EXCLUDED(pageheap_lock);
// Return the saved high-water-mark heap profile, if any.
std::unique_ptr<ProfileBase> DumpSample() const
ABSL_LOCKS_EXCLUDED(pageheap_lock);
size_t CurrentPeakSize() const { return peak_sampled_heap_size_.value(); }
private:
// Linked list of stack traces from sampled allocations saved (from
// sampled_objects_ above) when we allocate memory from the system. The
// linked list pointer is stored in StackTrace::stack[kMaxStackDepth-1].
StackTrace* peak_sampled_span_stacks_;
// Sampled heap size last time peak_sampled_span_stacks_ was saved. Only
// written under pageheap_lock; may be read without it.
StatsCounter peak_sampled_heap_size_;
bool IsNewPeak();
};
} // namespace tcmalloc_internal
} // namespace tcmalloc
GOOGLE_MALLOC_SECTION_END
#endif // TCMALLOC_PEAK_HEAP_TRACKER_H_
| 719 |
617 | <filename>oceanus-all/oceanus-core/src/main/java/com/bj58/oceanus/core/timetracker/Tracker.java<gh_stars>100-1000
/*
* Copyright Beijing 58 Information Technology Co.,Ltd.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.bj58.oceanus.core.timetracker;
import java.util.HashMap;
import java.util.Map;
import com.bj58.oceanus.core.exception.ConfigurationException;
import com.bj58.oceanus.core.timetracker.handler.TrackResult;
import com.google.common.collect.Maps;
/**
* 耗时监控点以及处理器的持有者,也是监控器的基类
* 子类实现 {@link #doTrack()} 方法并加入配置,即可实现自定义监控
*
* @author Service Platform Architecture Team (<EMAIL>)
*/
public abstract class Tracker {
private static final Map<TrackPoint, TrackerHodler> generalTrackerMap = Maps.newHashMap();
private static final Map<String, Map<TrackPoint, TrackerHodler>> tableTrackerMap = Maps.newHashMap();
/**
* 添加全局Tracker
* @param trackerHodler
*/
static synchronized void addTracker(TrackerHodler trackerHodler) {
if(generalTrackerMap.containsKey(trackerHodler.getTrackPoint()))
throw new ConfigurationException("TrackPoint ["+ trackerHodler.getTrackPoint() +
"] already exsit!");
generalTrackerMap.put(trackerHodler.getTrackPoint(), trackerHodler);
}
/**
* 为指定table添加Tracker
* @param tableName
* @param trackerHodler
*/
static synchronized void addTracker(String tableName, TrackerHodler trackerHodler) {
if(!tableTrackerMap.containsKey(tableName))
tableTrackerMap.put(tableName, new HashMap<TrackPoint, TrackerHodler>());
if(tableTrackerMap.get(tableName).containsKey(trackerHodler.getTrackPoint()))
throw new ConfigurationException("TrackPoint [" + trackerHodler.getTrackPoint() +
"] for table [" + tableName + "] already exsit!");
tableTrackerMap.get(tableName).put(trackerHodler.getTrackPoint(), trackerHodler);
}
/**
* 获取全局指定类型的 tracker
* @param trackPoint
* @return
*/
static TrackerHodler getTracker(TrackPoint trackPoint) {
return generalTrackerMap.get(trackPoint);
}
/**
* 获取指定表、指定类型的 tracker
* @param tableName
* @param trackPoint
* @return
*/
static TrackerHodler getTableTracker(String tableName, TrackPoint trackPoint) {
if(!tableTrackerMap.containsKey(tableName))
return null;
return tableTrackerMap.get(tableName).get(trackPoint);
}
/**
* 当对应的 TrackPoint 执行时间大于 getThreshold() 时的回调方法
* @param TrackResult
* - tableName 对应的表
* - sql 对应的sql
* - costTime 执行耗时
*/
public abstract void doTrack(TrackResult trackResult);
}
| 1,345 |
326 | from typing import Dict
from typing import List
import numpy as np
import pandas as pd
from ruptures.base import BaseEstimator
from ruptures.costs import CostLinear
from etna.datasets import TSDataset
def _prepare_signal(series: pd.Series, model: BaseEstimator) -> np.ndarray:
"""Prepare series for change point model."""
signal = series.to_numpy()
if isinstance(model.cost, CostLinear):
signal = signal.reshape((-1, 1))
return signal
def _find_change_points_segment(
series: pd.Series, change_point_model: BaseEstimator, **model_predict_params
) -> List[pd.Timestamp]:
"""Find trend change points within one segment."""
signal = _prepare_signal(series=series, model=change_point_model)
timestamp = series.index
change_point_model.fit(signal=signal)
# last point in change points is the first index after the series
change_points_indices = change_point_model.predict(**model_predict_params)[:-1]
change_points = [timestamp[idx] for idx in change_points_indices]
return change_points
def find_change_points(
ts: TSDataset, in_column: str, change_point_model: BaseEstimator, **model_predict_params
) -> Dict[str, List[pd.Timestamp]]:
"""Find trend change points using ruptures models.
Parameters
----------
ts:
dataset to work with
in_column:
name of column to work with
change_point_model:
ruptures model to get trend change points
model_predict_params:
params for ``change_point_model`` predict method
Returns
-------
Dict[str, List[pd.Timestamp]]
dictionary with list of trend change points for each segment
"""
result: Dict[str, List[pd.Timestamp]] = {}
df = ts.to_pandas()
for segment in ts.segments:
df_segment = df[segment]
raw_series = df_segment[in_column]
series = raw_series.loc[raw_series.first_valid_index() : raw_series.last_valid_index()]
result[segment] = _find_change_points_segment(
series=series, change_point_model=change_point_model, **model_predict_params
)
return result
| 789 |
14,668 | {
"name": "chrome.runtime.sendMessage test",
"version": "0.1",
"manifest_version": 3,
"description": "end-to-end browser test for chrome.runtime.sendMessage API",
"background": {
"service_worker": "worker.js"
}
}
| 83 |
3,269 | <reponame>Akhil-Kashyap/LeetCode-Solutions
// Time: O(logn)
// Space: O(1)
class Solution {
public:
int getIndex(ArrayReader &reader) {
int left = 0, right = reader.length() - 1;
while (left < right) {
const auto& mid = left + (right - left) / 2;
if (reader.compareSub(left, mid, (right - left + 1) % 2 ? mid : mid + 1, right) >= 0) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};
| 269 |
320 | package com.jme3.gde.textureeditor.filters;
import java.awt.image.BufferedImage;
public interface BufferedImageFilter {
BufferedImage filter(BufferedImage source, Object... args);
}
| 60 |
1,602 | /*
* Copyright (c) 2014-2019, Cisco Systems, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* BSD license below:
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include "rdma/fi_errno.h"
#include "ofi_enosys.h"
#include "ofi.h"
#include "usnic_direct.h"
#include "usnic_ip_utils.h"
#include "libnl_utils.h"
#include "usd.h"
#include "usd_queue.h"
#include "usdf.h"
#include "usdf_av.h"
#include "usdf_cm.h"
#include "usdf_timer.h"
#include "fi_ext_usnic.h"
static int usdf_av_alloc_dest(struct usdf_dest **dest_o)
{
struct usdf_dest *dest;
dest = calloc(1, sizeof(**dest_o));
if (dest == NULL)
return -errno;
*dest_o = dest;
return 0;
}
static void usdf_av_free_dest(struct usdf_dest *dest)
{
LIST_REMOVE(dest, ds_addresses_entry);
free(dest);
}
static int usdf_av_close_(struct usdf_av *av)
{
struct usdf_dest *entry;
USDF_TRACE_SYS(AV, "\n");
pthread_spin_lock(&av->av_lock);
if (av->av_eq)
ofi_atomic_dec32(&av->av_eq->eq_refcnt);
ofi_atomic_dec32(&av->av_domain->dom_refcnt);
while (!LIST_EMPTY(&av->av_addresses)) {
entry = LIST_FIRST(&av->av_addresses);
usdf_av_free_dest(entry);
}
pthread_spin_destroy(&av->av_lock);
free(av);
USDF_DBG_SYS(AV, "AV successfully destroyed\n");
return 0;
}
static int usdf_av_close(struct fid *fid)
{
struct usdf_av *av;
int pending;
USDF_TRACE_SYS(AV, "\n");
av = container_of(fid, struct usdf_av, av_fid.fid);
if (ofi_atomic_get32(&av->av_refcnt) > 0)
return -FI_EBUSY;
pending = ofi_atomic_get32(&av->av_active_inserts);
assert(pending >= 0);
if (pending) {
USDF_DBG_SYS(AV, "%d pending inserts, defer closing\n",
pending);
ofi_atomic_set32(&av->av_closing, 1);
} else {
usdf_av_close_(av);
}
return 0;
}
static void
usdf_av_insert_async_complete(struct usdf_av_insert *insert)
{
struct fi_eq_entry entry;
struct usdf_av *av;
int pending;
int closing;
av = insert->avi_av;
entry.fid = &av->av_fid.fid;
entry.context = insert->avi_context;
entry.data = insert->avi_successes;
usdf_eq_write_internal(av->av_eq,
FI_AV_COMPLETE, &entry, sizeof(entry), 0);
usdf_timer_free(av->av_domain->dom_fabric, insert->avi_timer);
pending = ofi_atomic_dec32(&av->av_active_inserts);
USDF_DBG_SYS(AV, "new active insert value: %d\n", pending);
assert(pending >= 0);
closing = ofi_atomic_get32(&av->av_closing);
if (!pending && closing)
usdf_av_close_(av);
free(insert);
}
/*
* A request failed, post an error event to the EQ
*/
static void
usdf_post_insert_request_error(struct usdf_av_insert *insert,
struct usdf_av_req *req)
{
struct fi_eq_err_entry err_entry;
struct usdf_av *av;
av = insert->avi_av;
*req->avr_fi_addr = FI_ADDR_NOTAVAIL;
free(req->avr_dest);
err_entry.fid = &av->av_fid.fid;
err_entry.context = insert->avi_context;
err_entry.data = req - (struct usdf_av_req *)(insert + 1);
err_entry.err = -req->avr_status;
err_entry.err_data = NULL;
err_entry.err_data_size = 0;
usdf_eq_write_internal(av->av_eq, 0,
&err_entry, sizeof(err_entry),
USDF_EVENT_FLAG_ERROR);
}
/*
* Called by progression thread to look for AV completions on this domain
*/
static void
usdf_av_insert_progress(void *v)
{
int ret;
struct usdf_av_insert *insert;
struct usdf_fabric *fp;
struct usdf_dest *dest;
struct usdf_av_req *req;
struct usdf_av_req *tmpreq;
struct usd_device_attrs *dap;
uint64_t now;
uint8_t *eth;
insert = v;
fp = insert->avi_av->av_domain->dom_fabric;
dap = fp->fab_dev_attrs;
TAILQ_FOREACH_SAFE(req, tmpreq, &insert->avi_req_list, avr_link) {
dest = req->avr_dest;
eth = &dest->ds_dest.ds_dest.ds_udp.u_hdr.uh_eth.ether_dhost[0];
ret = usnic_arp_lookup(dap->uda_ifname,
req->avr_daddr_be, fp->fab_arp_sockfd, eth);
/* anything besides EAGAIN means request is completed */
if (ret != EAGAIN) {
TAILQ_REMOVE(&insert->avi_req_list, req, avr_link);
req->avr_status = -ret;
if (ret == 0) {
++insert->avi_successes;
*(struct usdf_dest **)req->avr_fi_addr = dest;
LIST_INSERT_HEAD(&insert->avi_av->av_addresses,
dest, ds_addresses_entry);
} else {
usdf_post_insert_request_error(insert, req);
}
}
}
/* Time for a new ARP? */
now = usdf_get_ms();
if (now - insert->avi_last_arp_time > USDF_AV_ARP_INTERVAL) {
/* If no more ARP requests left, fail all remaining requests */
if (insert->avi_arps_left == 0) {
TAILQ_FOREACH(req, &insert->avi_req_list, avr_link) {
req->avr_status = -FI_EHOSTUNREACH;
usdf_post_insert_request_error(insert, req);
}
TAILQ_INIT(&insert->avi_req_list);
/* Trigger an ARP request for all pending requests */
} else {
TAILQ_FOREACH_SAFE(req, tmpreq,
&insert->avi_req_list, avr_link) {
ret = usnic_arp_request(req->avr_daddr_be,
fp->fab_arp_sockfd);
if (ret != 0) {
req->avr_status = -ret;
TAILQ_REMOVE(&insert->avi_req_list,
req, avr_link);
usdf_post_insert_request_error(insert,
req);
}
}
insert->avi_last_arp_time = now;
--insert->avi_arps_left;
}
}
/* If no more pending requests, all done! */
if (TAILQ_EMPTY(&insert->avi_req_list)) {
usdf_av_insert_async_complete(insert);
} else {
/* retry in 1 ms */
usdf_timer_set(fp, insert->avi_timer, 1);
}
}
static int
usdf_am_insert_async(struct fid_av *fav, const void *addr, size_t count,
fi_addr_t *fi_addr, uint64_t flags, void *context)
{
const struct sockaddr_in *sin;
const char **addr_str;
struct sockaddr_in *cur_sin;
struct usd_device_attrs *dap;
struct usdf_av_insert *insert;
struct usdf_av_req *req;
struct usdf_av *av;
struct usdf_fabric *fp;
struct usd_dest *u_dest;
struct fi_info *info;
int ret;
size_t i;
bool addr_format_str;
USDF_TRACE_SYS(AV, "\n");
if ((flags & ~(FI_MORE)) != 0)
return -FI_EBADFLAGS;
av = av_ftou(fav);
fp = av->av_domain->dom_fabric;
dap = fp->fab_dev_attrs;
info = av->av_domain->dom_info;
addr_format_str = (info->addr_format == FI_ADDR_STR);
if (av->av_eq == NULL) {
return -FI_ENOEQ;
}
sin = addr;
addr_str = (const char **)addr;
/* allocate an insert record and N requests */
insert = calloc(1, sizeof(*insert) + count * sizeof(*req));
if (insert == NULL) {
return -errno;
}
insert->avi_av = av;
insert->avi_context = context;
ret = usdf_timer_alloc(usdf_av_insert_progress, insert,
&insert->avi_timer);
if (ret != 0) {
goto fail;
}
TAILQ_INIT(&insert->avi_req_list);
insert->avi_arps_left = USDF_AV_MAX_ARPS;
ret = ofi_atomic_inc32(&av->av_active_inserts);
USDF_DBG_SYS(AV, "new active insert value: %d\n", ret);
/* If no addresses, complete now */
if (count == 0) {
usdf_av_insert_async_complete(insert);
return 0;
}
req = (struct usdf_av_req *)(insert + 1);
for (i = 0; i < count; i++) {
req->avr_fi_addr = &fi_addr[i];
if (addr_format_str) {
usdf_str_toaddr(addr_str[i], &cur_sin);
if (NULL == cur_sin) {
ret = -FI_ENOMEM;
goto fail;
}
sin = cur_sin;
}
/* find the address we actually need to look up */
ret = usnic_nl_rt_lookup(dap->uda_ipaddr_be,
sin->sin_addr.s_addr, dap->uda_ifindex,
&req->avr_daddr_be);
if (ret != 0) {
if (ret == EHOSTUNREACH) {
req->avr_status = -FI_EHOSTUNREACH;
usdf_post_insert_request_error(insert, req);
} else {
ret = -ret;
goto fail;
}
} else {
if (req->avr_daddr_be == 0) {
req->avr_daddr_be = sin->sin_addr.s_addr;
}
req->avr_dest = calloc(1, sizeof(*req->avr_dest));
if (req->avr_dest == NULL) {
ret = -FI_ENOMEM;
goto fail;
}
u_dest = &req->avr_dest->ds_dest;
usd_fill_udp_dest(u_dest, dap,
sin->sin_addr.s_addr, sin->sin_port);
u_dest->ds_dest.ds_udp.u_hdr.uh_ip.frag_off |=
htons(IP_DF);
TAILQ_INSERT_TAIL(&insert->avi_req_list, req, avr_link);
}
if (addr_format_str) {
free(cur_sin);
cur_sin = NULL;
} else {
++sin;
}
++req;
}
/* resolve all addresses we can */
usdf_av_insert_progress(insert);
return 0;
fail:
if (insert != NULL) {
if (insert->avi_timer != NULL) {
usdf_timer_free(fp, insert->avi_timer);
}
free(insert);
}
return ret;
}
static int
usdf_am_insert_sync(struct fid_av *fav, const void *addr, size_t count,
fi_addr_t *fi_addr, uint64_t flags, void *context)
{
const struct sockaddr_in *sin;
const char **addr_str;
struct sockaddr_in *cur_sin;
struct usdf_av *av;
struct usd_dest *u_dest;
struct usdf_dest *dest;
struct fi_info *info;
int ret_count;
int ret;
int *errors;
uint32_t api_version;
size_t i;
bool addr_format_str;
USDF_TRACE_SYS(AV, "\n");
ret_count = 0;
av = av_ftou(fav);
api_version = av->av_domain->dom_fabric->fab_attr.fabric->api_version;
info = av->av_domain->dom_info;
addr_format_str = (info->addr_format == FI_ADDR_STR);
errors = context;
/* Screen out unsupported flags. */
if ((flags & ~(FI_MORE|FI_SYNC_ERR)) != 0)
return -FI_EBADFLAGS;
/* If user set FI_SYNC_ERR, we have to report back to user's buffer. */
if (flags & FI_SYNC_ERR) {
if (FI_VERSION_LT(api_version, FI_VERSION(1, 5)))
return -FI_EBADFLAGS;
memset(errors, 0, sizeof(int) * count);
}
sin = addr;
addr_str = (const char **)addr;
/* XXX parallelize, this will also eliminate u_dest silliness */
for (i = 0; i < count; i++) {
if (addr_format_str) {
usdf_str_toaddr(addr_str[i], &cur_sin);
if (NULL == cur_sin) {
if (flags & FI_SYNC_ERR)
errors[i] = -ENOMEM;
return ret_count;
}
sin = cur_sin;
}
dest = NULL;
u_dest = NULL;
ret = usdf_av_alloc_dest(&dest);
if (ret == 0) {
USDF_DBG_SYS(AV, "usd_create_dest(addr=0x%x, port=0x%x)\n",
ntohl(sin->sin_addr.s_addr), ntohs(sin->sin_port));
ret = usd_create_dest(av->av_domain->dom_dev,
sin->sin_addr.s_addr, sin->sin_port,
&u_dest);
}
if (ret == 0) {
u_dest->ds_dest.ds_udp.u_hdr.uh_ip.frag_off |=
htons(IP_DF);
dest->ds_dest = *u_dest;
fi_addr[i] = (fi_addr_t)dest;
LIST_INSERT_HEAD(&av->av_addresses, dest,
ds_addresses_entry);
++ret_count;
} else {
if (flags & FI_SYNC_ERR)
errors[i] = -ret;
fi_addr[i] = FI_ADDR_NOTAVAIL;
free(dest);
}
free(u_dest);
if (addr_format_str) {
free(cur_sin);
cur_sin = NULL;
} else {
++sin;
}
}
return ret_count;
}
static int usdf_resolve_addr(const char *node, const char *service,
struct sockaddr_in *in)
{
struct addrinfo *ai;
int ret;
struct addrinfo hints = {
.ai_family = AF_INET,
};
if (!node || !service || !in)
return -FI_EINVAL;
ret = getaddrinfo(node, service, &hints, &ai);
if (ret) {
USDF_DBG("getaddrinfo: %s\n", gai_strerror(ret));
return -FI_EINVAL;
}
*in = *(struct sockaddr_in *) ai->ai_addr;
assert(ai->ai_family == AF_INET);
assert(in->sin_family == AF_INET);
freeaddrinfo(ai);
return ret;
}
static int usdf_av_insertsvc(struct fid_av *fav, const char *node,
const char *service, fi_addr_t *fi_addr, uint64_t flags,
void *context)
{
struct sockaddr_in addr;
struct usdf_av *av;
struct fi_info *info;
int ret;
bool addr_format_str;
USDF_TRACE_SYS(AV, "\n");
av = av_ftou(fav);
info = av->av_domain->dom_info;
addr_format_str = (info->addr_format == FI_ADDR_STR);
if (!fav)
return -FI_EINVAL;
if (addr_format_str) {
/* string format should not come with service param. */
if (service)
return -FI_EINVAL;
ret = fav->ops->insert(fav, &node, 1, fi_addr, flags, context);
} else {
ret = usdf_resolve_addr(node, service, &addr);
if (ret)
goto fail;
ret = fav->ops->insert(fav, &addr, 1, fi_addr, flags, context);
}
fail:
return ret;
}
static int
usdf_am_remove(struct fid_av *fav, fi_addr_t *fi_addr, size_t count,
uint64_t flags)
{
struct usdf_dest *dest;
size_t i;
USDF_TRACE_SYS(AV, "\n");
for (i = 0; i < count; ++i) {
if (fi_addr[i] != FI_ADDR_NOTAVAIL) {
dest = (struct usdf_dest *)(uintptr_t)fi_addr[i];
usdf_av_free_dest(dest);
/* Mark invalid by setting to FI_ADDR_NOTAVAIL*/
fi_addr[i] = FI_ADDR_NOTAVAIL;
}
}
return 0;
}
static int
usdf_am_lookup(struct fid_av *fav, fi_addr_t fi_addr, void *addr,
size_t *addrlen)
{
struct usdf_dest *dest;
struct usdf_av *av;
struct fi_info *info;
struct sockaddr_in sin = { 0 };
size_t copylen;
bool addr_format_str;
USDF_TRACE_SYS(AV, "\n");
av = av_ftou(fav);
info = av->av_domain->dom_info;
addr_format_str = (info->addr_format == FI_ADDR_STR);
if (fi_addr == FI_ADDR_NOTAVAIL) {
USDF_WARN_SYS(AV, "invalid address, can't lookup\n");
return -FI_EINVAL;
}
dest = (struct usdf_dest *)(uintptr_t)fi_addr;
if (*addrlen < sizeof(sin)) {
copylen = *addrlen;
} else {
copylen = sizeof(sin);
}
sin.sin_family = AF_INET;
usd_expand_dest(&dest->ds_dest, &sin.sin_addr.s_addr, &sin.sin_port);
if (addr_format_str)
usdf_addr_tostr(&sin, addr, addrlen);
else {
memcpy(addr, &sin, copylen);
*addrlen = sizeof(sin);
}
return 0;
}
static const char *
usdf_av_straddr(struct fid_av *fav, const void *addr,
char *buf, size_t *len)
{
struct fi_info *info;
struct usdf_av *av;
if (!len || !addr || !buf)
return NULL;
av = av_fidtou(fav);
info = av->av_domain->dom_info;
return ofi_straddr(buf, len, info->addr_format, addr);
}
static int
usdf_av_bind(struct fid *fid, struct fid *bfid, uint64_t flags)
{
struct usdf_av *av;
USDF_TRACE_SYS(AV, "\n");
av = av_fidtou(fid);
switch (bfid->fclass) {
case FI_CLASS_EQ:
if (av->av_eq != NULL) {
return -FI_EINVAL;
}
av->av_eq = eq_fidtou(bfid);
ofi_atomic_inc32(&av->av_eq->eq_refcnt);
break;
default:
return -FI_EINVAL;
}
return 0;
}
static struct fi_ops usdf_av_fi_ops = {
.size = sizeof(struct fi_ops),
.close = usdf_av_close,
.bind = usdf_av_bind,
.control = fi_no_control,
.ops_open = usdf_av_ops_open,
};
static struct fi_ops_av usdf_am_ops_async = {
.size = sizeof(struct fi_ops_av),
.insert = usdf_am_insert_async,
.insertsvc = usdf_av_insertsvc,
.insertsym = fi_no_av_insertsym,
.remove = usdf_am_remove,
.lookup = usdf_am_lookup,
.straddr = usdf_av_straddr
};
static struct fi_ops_av usdf_am_ops_sync = {
.size = sizeof(struct fi_ops_av),
.insert = usdf_am_insert_sync,
.insertsvc = usdf_av_insertsvc,
.insertsym = fi_no_av_insertsym,
.remove = usdf_am_remove,
.lookup = usdf_am_lookup,
.straddr = usdf_av_straddr
};
static int usdf_av_process_attr(struct fi_av_attr *attr)
{
USDF_TRACE_SYS(AV, "\n");
if (attr == NULL) {
USDF_WARN_SYS(AV, "NULL AV attribute structure is invalid\n");
return -FI_EINVAL;
}
if (attr->name || attr->map_addr || (attr->flags & FI_READ)) {
USDF_WARN_SYS(AV, "named AVs are not supported\n");
return -FI_ENOSYS;
}
if (attr->flags & ~FI_EVENT) {
USDF_WARN_SYS(AV, "invalid flag, only FI_EVENT is supported\n");
return -FI_EINVAL;
}
if (attr->rx_ctx_bits) {
USDF_WARN_SYS(AV, "scalable endpoints not supported\n");
return -FI_EINVAL;
}
if (attr->ep_per_node > 1)
USDF_WARN_SYS(AV, "ep_per_node not supported, ignoring\n");
switch (attr->type) {
case FI_AV_UNSPEC:
USDF_DBG_SYS(AV, "no AV type specified, using FI_AV_MAP\n");
case FI_AV_MAP:
break;
case FI_AV_TABLE:
USDF_DBG_SYS(AV, "FI_AV_TABLE is unsupported\n");
return -FI_ENOSYS;
default:
USDF_WARN_SYS(AV, "unknown AV type %d, not supported",
attr->type);
return -FI_EINVAL;
}
return FI_SUCCESS;
}
int
usdf_av_open(struct fid_domain *domain, struct fi_av_attr *attr,
struct fid_av **av_o, void *context)
{
struct usdf_domain *udp;
struct usdf_av *av;
int ret;
USDF_TRACE_SYS(AV, "\n");
if (!av_o) {
USDF_WARN_SYS(AV, "provided AV pointer can not be NULL\n");
return -FI_EINVAL;
}
ret = usdf_av_process_attr(attr);
if (ret)
return ret;
udp = dom_ftou(domain);
av = calloc(1, sizeof(*av));
if (av == NULL) {
return -FI_ENOMEM;
}
if (attr->flags & FI_EVENT) {
av->av_fid.ops = &usdf_am_ops_async;
} else {
av->av_fid.ops = &usdf_am_ops_sync;
}
LIST_INIT(&av->av_addresses);
av->av_fid.fid.fclass = FI_CLASS_AV;
av->av_fid.fid.context = context;
av->av_fid.fid.ops = &usdf_av_fi_ops;
av->av_flags = attr->flags;
pthread_spin_init(&av->av_lock, PTHREAD_PROCESS_PRIVATE);
ofi_atomic_initialize32(&av->av_active_inserts, 0);
ofi_atomic_initialize32(&av->av_closing, 0);
ofi_atomic_initialize32(&av->av_refcnt, 0);
ofi_atomic_inc32(&udp->dom_refcnt);
av->av_domain = udp;
*av_o = av_utof(av);
return 0;
}
/* Look up if the sin address has been already inserted.
* if match, return the address of the dest pointer. otherwise,
* returns FI_ADDR_NOTAVAIL.
*/
fi_addr_t usdf_av_lookup_addr(struct usdf_av *av,
const struct sockaddr_in *sin)
{
struct usdf_dest *cur;
struct usd_udp_hdr u_hdr;
for (cur = av->av_addresses.lh_first; cur;
cur = cur->ds_addresses_entry.le_next) {
u_hdr = cur->ds_dest.ds_dest.ds_udp.u_hdr;
if (sin->sin_addr.s_addr == u_hdr.uh_ip.daddr &&
sin->sin_port == u_hdr.uh_udp.dest)
return (fi_addr_t)(uintptr_t)cur;
}
return FI_ADDR_NOTAVAIL;
}
/* Return sockaddr_in pointer. Must be used with usdf_free_sin_if_needed()
* to cleanup properly.
*/
struct sockaddr_in *usdf_format_to_sin(const struct fi_info *info, const void *addr)
{
struct sockaddr_in *sin;
if (!info)
return (struct sockaddr_in *)addr;
switch (info->addr_format) {
case FI_FORMAT_UNSPEC:
case FI_SOCKADDR:
case FI_SOCKADDR_IN:
return (struct sockaddr_in *)addr;
case FI_ADDR_STR:
usdf_str_toaddr(addr, &sin);
return sin;
default:
return NULL;
}
}
/* Utility function to free the sockaddr_in allocated from usdf_format_to_sin()
*/
void usdf_free_sin_if_needed(const struct fi_info *info, struct sockaddr_in *sin)
{
if (info && info->addr_format == FI_ADDR_STR)
free(sin);
}
/* Convert sockaddr_in pointer to appropriate format.
* If conversion happens, destroy the origin. (to minimize cleaning up code)
*/
void *usdf_sin_to_format(const struct fi_info *info, void *addr, size_t *len)
{
size_t addr_strlen;
char *addrstr;
if (!info)
return addr;
switch (info->addr_format) {
case FI_FORMAT_UNSPEC:
case FI_SOCKADDR:
case FI_SOCKADDR_IN:
if (len)
*len = sizeof(struct sockaddr_in);
return addr;
case FI_ADDR_STR:
addrstr = calloc(1, USDF_ADDR_STR_LEN);
if (addrstr == NULL) {
USDF_DBG_SYS(AV, "memory allocation failed\n");
return NULL;
}
addr_strlen = USDF_ADDR_STR_LEN;
usdf_addr_tostr(addr, addrstr, &addr_strlen);
if (len)
*len = addr_strlen;
free(addr);
return addrstr;
default:
return NULL;
}
}
| 8,997 |
596 | <reponame>RomeroLaura/Axelrod<gh_stars>100-1000
import inspect
import re
from typing import Callable, Set, Text, Type, Union
from axelrod.player import Player
def method_makes_use_of(method: Callable) -> Set[Text]:
result = set()
method_code = inspect.getsource(method)
attr_string = r".match_attributes\[\"(\w+)\"\]"
all_attrs = re.findall(attr_string, method_code)
for attr in all_attrs:
result.add(attr)
return result
def class_makes_use_of(cls) -> Set[Text]:
try:
result = cls.classifier["makes_use_of"]
except (AttributeError, KeyError):
result = set()
for method in inspect.getmembers(cls, inspect.ismethod):
if method[0] == "__init__":
continue
result.update(method_makes_use_of(method[1]))
return result
def makes_use_of(player: Type[Player]) -> Set[Text]:
if not isinstance(player, Player): # pragma: no cover
player = player()
return class_makes_use_of(player)
def makes_use_of_variant(
player_or_method: Union[Callable, Type[Player]]
) -> Set[Text]:
"""A version of makes_use_of that works on functions or player classes."""
try:
return method_makes_use_of(player_or_method)
# OSError catches the case of a transformed player, which has a dynamically
# created class.
# TypeError is the case in which we have a class rather than a method
except (OSError, TypeError):
return class_makes_use_of(player_or_method)
| 569 |
2,112 | <reponame>laohubuzaijia/fbthrift<gh_stars>1000+
/*
* Copyright (c) Facebook, Inc. and 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.
*/
#include <thrift/lib/cpp2/CloneableIOBuf.h>
#include <folly/portability/GTest.h>
using namespace folly;
using namespace apache::thrift;
TEST(CloneableIOBufTest, UniquePtrCompatibility) {
CloneableIOBuf ptr(IOBuf::copyBuffer("Test string"));
EXPECT_NE(nullptr, ptr.get());
CloneableIOBuf ptr2(std::move(ptr));
EXPECT_EQ(nullptr, ptr.get());
EXPECT_NE(nullptr, ptr2.get());
swap(ptr, ptr2);
EXPECT_NE(nullptr, ptr.get());
EXPECT_EQ(nullptr, ptr2.get());
}
TEST(CloneableIOBufTest, CopyConstructorAndAssignment) {
const std::string s = "Test string";
const std::string s2 = "Foo bar";
CloneableIOBuf ptr(IOBuf::wrapBuffer(s.data(), s.size()));
CloneableIOBuf ptr2(ptr);
CloneableIOBuf ptr3(IOBuf::wrapBuffer(s2.data(), s2.size()));
EXPECT_NE(nullptr, ptr.get());
EXPECT_NE(nullptr, ptr2.get());
EXPECT_NE(nullptr, ptr3.get());
EXPECT_NE(ptr.get(), ptr2.get());
EXPECT_TRUE(ptr->isShared());
EXPECT_EQ(ptr->buffer(), ptr2->buffer());
EXPECT_NE(ptr->buffer(), ptr3->buffer());
ptr2 = ptr3;
EXPECT_NE(nullptr, ptr.get());
EXPECT_NE(nullptr, ptr2.get());
EXPECT_NE(nullptr, ptr3.get());
EXPECT_NE(ptr.get(), ptr2.get());
EXPECT_NE(ptr2.get(), ptr3.get());
EXPECT_NE(ptr->buffer(), ptr2->buffer());
EXPECT_EQ(ptr2->buffer(), ptr3->buffer());
}
TEST(CloneableIOBufTest, Swap) {
const std::string s = "Test string";
const std::string s2 = "Foo bar";
CloneableIOBuf ptr(IOBuf::wrapBuffer(s.data(), s.size()));
CloneableIOBuf ptr2(IOBuf::wrapBuffer(s2.data(), s2.size()));
EXPECT_NE(nullptr, ptr.get());
EXPECT_NE(nullptr, ptr2.get());
EXPECT_NE(ptr.get(), ptr2.get());
EXPECT_NE(ptr->buffer(), ptr2->buffer());
EXPECT_STREQ(s.c_str(), (const char*)ptr->data());
EXPECT_STREQ(s2.c_str(), (const char*)ptr2->data());
swap(ptr, ptr2);
EXPECT_NE(nullptr, ptr.get());
EXPECT_NE(nullptr, ptr2.get());
EXPECT_NE(ptr.get(), ptr2.get());
EXPECT_NE(ptr->buffer(), ptr2->buffer());
EXPECT_STREQ(s2.c_str(), (const char*)ptr->data());
EXPECT_STREQ(s.c_str(), (const char*)ptr2->data());
}
TEST(CloneableIOBufTest, NullPtr) {
const std::string s = "Test string";
CloneableIOBuf ptr(IOBuf::wrapBuffer(s.data(), s.size()));
CloneableIOBuf ptr2;
EXPECT_NE(nullptr, ptr.get());
EXPECT_EQ(nullptr, ptr2.get());
CloneableIOBuf ptr3(ptr2);
EXPECT_EQ(nullptr, ptr3.get());
ptr = ptr2;
EXPECT_EQ(nullptr, ptr.get());
}
| 1,188 |
571 | <reponame>ufora/ufora
/***************************************************************************
Copyright 2015 Ufora 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.
****************************************************************************/
#include "CallSite.hpp"
using std::string;
CallSite::CallSite() : callerName(), siteId(), calleeName() { }
CallSite::CallSite(const string& caller, uint64_t id, const string& callee)
: callerName(caller), siteId(id), calleeName(callee) { }
bool operator==(const CallSite& a, const CallSite& b) {
return a.siteId == b.siteId &&
a.callerName == b.callerName &&
a.calleeName == b.calleeName;
}
bool operator<(const CallSite& a, const CallSite& b) {
return
a.siteId < b.siteId || (
a.siteId == b.siteId && (
a.callerName < b.callerName || (
a.callerName == b.callerName &&
a.calleeName < b.calleeName)));
}
| 449 |
852 | /*******************************************************************************
* *
* <NAME> *
* Warsaw University 2004 *
* *
*******************************************************************************/
#include "L1Trigger/RPCTrigger/interface/RPCTBGhostBuster.h"
//#include <set>
#include <algorithm>
using namespace std;
//---------------------------------------------------------------------------
L1RpcTBMuonsVec RPCTBGhostBuster::run(L1RpcTBMuonsVec2 &pacMuonsVec2) const {
L1RpcTBMuonsVec2 gbPhiMuonsVec2;
for (unsigned int iTow = 0; iTow < pacMuonsVec2.size(); iTow++) {
gbPhiMuonsVec2.push_back(gBPhi(pacMuonsVec2[iTow]));
}
return gBEta(gbPhiMuonsVec2);
}
/* version wyit imlemented condition "last but one"
NOT USED IN VHDL
bool prevKillByBigger = false;
for(int iMu = 0; iMu < m_SEGMENTS_IN_SECTOR_CNT; iMu++) {
if(pacMuonsVec[iMu].getCode() < pacMuonsVec[iPrevMu].getCode())
prevKillByBigger = true;
else if(pacMuonsVec[iMu].getCode() > pacMuonsVec[iPrevMu].getCode())
prevKillByBigger = false;
if(pacMuonsVec[iMu].getCode() == 0);
else if(pacMuonsVec[iMu].getCode() > pacMuonsVec[iPrevMu].getCode() && //local maximum
pacMuonsVec[iMu].getCode() > pacMuonsVec[iMu + 1].getCode() )
;
else if(pacMuonsVec[iMu].getCode() >= pacMuonsVec[iPrevMu].getCode() && //last-but-one
pacMuonsVec[iMu].getCode() == pacMuonsVec[iMu + 1].getCode() &&
pacMuonsVec[iMu + 1].getCode() > pacMuonsVec[iMu + 2].getCode()) {
if(prevKillByBigger)
pacMuonsVec[iMu].kill();
}
else {
pacMuonsVec[iMu].kill();
}
iPrevMu = iMu;
}
*/
L1RpcTBMuonsVec RPCTBGhostBuster::gBPhi(L1RpcTBMuonsVec &pacMuonsVec) const {
if (pacMuonsVec.empty())
return L1RpcTBMuonsVec(); //empty vector;
//--------- killing ghosts ---------------------------------------
pacMuonsVec.push_back(RPCTBMuon()); //adding empty muon to the end,
for (unsigned int iMu = 0; iMu < RPCConst::m_SEGMENTS_IN_SECTOR_CNT; iMu++) {
if (pacMuonsVec[iMu].getCode() == 0)
;
else if (pacMuonsVec[iMu].getCode() < pacMuonsVec[iMu + 1].getCode())
pacMuonsVec[iMu].kill();
else if (pacMuonsVec[iMu].getCode() == pacMuonsVec[iMu + 1].getCode()) {
if (pacMuonsVec[iMu].wasKilled())
pacMuonsVec[iMu + 1].kill();
else
pacMuonsVec[iMu].kill();
} else //>
pacMuonsVec[iMu + 1].kill();
}
pacMuonsVec.pop_back(); //removing empty muon from the end,
//-------setting the m_GBData ----------------------------------
if (pacMuonsVec[0].isLive())
pacMuonsVec[0].setGBDataKilledFirst();
else if (pacMuonsVec[0].wasKilled())
for (unsigned int iMu = 0; iMu < RPCConst::m_SEGMENTS_IN_SECTOR_CNT; iMu++) {
if (pacMuonsVec[iMu].isLive()) {
pacMuonsVec[iMu].setGBDataKilledFirst();
break;
}
}
if (pacMuonsVec[RPCConst::m_SEGMENTS_IN_SECTOR_CNT - 1].isLive())
pacMuonsVec[RPCConst::m_SEGMENTS_IN_SECTOR_CNT - 1].setGBDataKilledLast();
else if (pacMuonsVec[RPCConst::m_SEGMENTS_IN_SECTOR_CNT - 1].wasKilled())
for (int iMu = RPCConst::m_SEGMENTS_IN_SECTOR_CNT - 1; iMu >= 0; iMu--) {
if (pacMuonsVec[iMu].isLive()) {
pacMuonsVec[iMu].setGBDataKilledLast();
break;
}
}
//-------------sorting ------------------------------------------
/*
multiset<RPCTBMuon, RPCTBMuon::TMuonMore> liveMuonsSet;
for(int iMu = 0; iMu < m_SEGMENTS_IN_SECTOR_CNT; iMu++) {
if(pacMuonsVec[iMu].isLive()) {
pacMuonsVec[iMu].setPhiAddr(iMu);
liveMuonsSet.insert(pacMuonsVec[iMu]);
}
}
L1RpcTBMuonsVec outputMuons(liveMuonsSet.begin(), liveMuonsSet.end());*/
L1RpcTBMuonsVec outputMuons;
for (unsigned int iMu = 0; iMu < RPCConst::m_SEGMENTS_IN_SECTOR_CNT; iMu++) {
if (pacMuonsVec[iMu].isLive()) {
pacMuonsVec[iMu].setPhiAddr(iMu);
outputMuons.push_back(pacMuonsVec[iMu]);
}
}
sort(outputMuons.begin(), outputMuons.end(), RPCTBMuon::TMuonMore());
//-------setting size to m_GBPHI_OUT_MUONS_CNT----------------
while (outputMuons.size() < RPCConst::m_GBPHI_OUT_MUONS_CNT)
outputMuons.push_back(RPCTBMuon());
while (outputMuons.size() > RPCConst::m_GBPHI_OUT_MUONS_CNT)
outputMuons.pop_back();
return outputMuons;
}
////////////////////////////////////////////////////////////////////////////////
L1RpcTBMuonsVec RPCTBGhostBuster::gBEta(L1RpcTBMuonsVec2 &gbPhiMuonsVec2) const {
//----- killing ghosts ---------------------------------------
for (unsigned int iMuVec = 0; iMuVec < gbPhiMuonsVec2.size() - 1; iMuVec++) {
for (unsigned int iMu = 0; iMu < gbPhiMuonsVec2[iMuVec].size(); iMu++) {
if (gbPhiMuonsVec2[iMuVec][iMu].getCode() == 0)
break; //because muons are sorted
for (unsigned int iMuNext = 0; iMuNext < gbPhiMuonsVec2[iMuVec + 1].size(); iMuNext++) {
if (abs(gbPhiMuonsVec2[iMuVec][iMu].getPhiAddr() - gbPhiMuonsVec2[iMuVec + 1][iMuNext].getPhiAddr()) <= 1) {
//comparing with next:
if (gbPhiMuonsVec2[iMuVec][iMu].getCode() < gbPhiMuonsVec2[iMuVec + 1][iMuNext].getCode()) {
gbPhiMuonsVec2[iMuVec][iMu].kill();
} else {
gbPhiMuonsVec2[iMuVec + 1][iMuNext].kill();
}
}
}
}
}
//---------sorting-----------------------------------------
/* multiset<RPCTBMuon, RPCTBMuon::TMuonMore> liveMuonsSet;
for(unsigned int iMuVec = 0; iMuVec < gbPhiMuonsVec2.size(); iMuVec++)
for(unsigned int iMu = 0; iMu < gbPhiMuonsVec2[iMuVec].size(); iMu++)
if(gbPhiMuonsVec2[iMuVec][iMu].isLive()) {
gbPhiMuonsVec2[iMuVec][iMu].setEtaAddr(iMuVec);
liveMuonsSet.insert(gbPhiMuonsVec2[iMuVec][iMu]);
}
L1RpcTBMuonsVec outputMuons(liveMuonsSet.begin(), liveMuonsSet.end()); */
L1RpcTBMuonsVec outputMuons;
for (unsigned int iMuVec = 0; iMuVec < gbPhiMuonsVec2.size(); iMuVec++)
for (unsigned int iMu = 0; iMu < gbPhiMuonsVec2[iMuVec].size(); iMu++)
if (gbPhiMuonsVec2[iMuVec][iMu].isLive()) {
gbPhiMuonsVec2[iMuVec][iMu].setEtaAddr(iMuVec);
outputMuons.push_back(gbPhiMuonsVec2[iMuVec][iMu]);
}
sort(outputMuons.begin(), outputMuons.end(), RPCTBMuon::TMuonMore());
//-------setting size to m_GBETA_OUT_MUONS_CNT----------------
while (outputMuons.size() < RPCConst::m_GBETA_OUT_MUONS_CNT)
outputMuons.push_back(RPCTBMuon());
while (outputMuons.size() > RPCConst::m_GBETA_OUT_MUONS_CNT)
outputMuons.pop_back();
return outputMuons;
}
| 3,291 |
3,181 | <reponame>Doomsdayrs/android_packages_apps_GmsCore
/*
* SPDX-FileCopyrightText: 2020, microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package com.google.firebase.auth.api.internal;
import org.microg.safeparcel.AutoSafeParcelable;
public class ProviderUserInfo extends AutoSafeParcelable {
@Field(2)
public String federatedId;
@Field(3)
public String displayName;
@Field(4)
public String photoUrl;
@Field(5)
public String providerId;
@Field(6)
public String rawUserInfo;
@Field(7)
public String phoneNumber;
@Field(8)
public String email;
public static final Creator<ProviderUserInfo> CREATOR = new AutoCreator<>(ProviderUserInfo.class);
}
| 259 |
711 | <filename>examples/http/PlatformHttpsServer.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.
*/
// Self signed certificate generation:
//
// openssl genrsa -out server.key 2048
// openssl req -new -key server.key -out server.csr
// openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
// Storing certificate and keys in a secret
// kubectl create secret generic my-self-signed-ssl --from-file=server.key --from-file=server.crt
// Integration execution
//
// kamel run PlatformHttpsServer.java -p quarkus.http.ssl.certificate.file=/etc/ssl/my-self-signed-ssl/server.crt \
// -p quarkus.http.ssl.certificate.key-file=/etc/ssl/my-self-signed-ssl/server.key \
// --resource secret:my-self-signed-ssl@/etc/ssl/my-self-signed-ssl \
// -t container.port=8443 --dev
// Test
//
// recover the service location. If you're running on minikube, minikube service platform-https-server --url=true
// curl -H "name:World" -k https://<service-location>/hello
//
import org.apache.camel.builder.RouteBuilder;
public class PlatformHttpsServer extends RouteBuilder {
@Override
public void configure() throws Exception {
from("platform-http:/hello?httpMethodRestrict=GET").setBody(simple("Hello ${header.name}"));
}
} | 689 |
1,993 | /*
* Copyright 2013-2019 The OpenZipkin Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package brave.messaging.features;
import brave.Tracing;
import brave.messaging.MessagingRuleSampler;
import brave.messaging.MessagingTracing;
import brave.sampler.RateLimitingSampler;
import brave.sampler.Sampler;
import brave.sampler.SamplerFunctions;
import org.junit.Test;
import static brave.messaging.MessagingRequestMatchers.channelNameEquals;
import static brave.messaging.MessagingRequestMatchers.operationEquals;
import static org.mockito.Mockito.mock;
public class ExampleTest {
Tracing tracing = mock(Tracing.class);
MessagingTracing messagingTracing;
// This mainly shows that we don't accidentally rely on package-private access
@Test public void showConstruction() {
messagingTracing = MessagingTracing.newBuilder(tracing)
.consumerSampler(MessagingRuleSampler.newBuilder()
.putRule(channelNameEquals("alerts"), Sampler.NEVER_SAMPLE)
.putRule(operationEquals("receive"), RateLimitingSampler.create(100))
.build())
.producerSampler(SamplerFunctions.neverSample())
.build();
}
}
| 488 |
373 | <reponame>vusec/revanc<gh_stars>100-1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#define min(x, y) (((x) < (y)) ? (x) : (y))
#define max(x, y) (((x) > (y)) ? (x) : (y))
#define KIB ((size_t)1024)
#define MIB (1024 * KIB)
#define GIB (1024 * MIB)
#if SIZE_MAX == UINT64_MAX
#define TIB (1024 * GIB)
#endif
/* Used to extract a bit field. */
#define BIT(n) (1 << (n))
#define EXTRACT(x, k, n) ((x) >> (k) & ((1 << (n)) - 1))
/* Represents a register that is accessible using 8-bit, 16-bit and 32-bit
* granularity.
*/
union reg {
uint32_t u32;
uint16_t u16[2];
uint8_t u8[4];
};
#define dperror() dperror_ext(__FILE__, __LINE__)
#define dprintf(...) \
do { \
fprintf(stderr, "%s:%d: error: ", __FILE__, __LINE__); \
fprintf(stderr, __VA_ARGS__); \
} while(0)
void dperror_ext(const char *fname, int line_no);
| 458 |
778 | // KRATOS___
// // ) )
// // ___ ___
// // ____ //___) ) // ) )
// // / / // // / /
// ((____/ / ((____ ((___/ / MECHANICS
//
// License: geo_mechanics_application/license.txt
//
// Main authors: <NAME>
//
#if !defined(KRATOS_GEO_U_PW_SMALL_STRAIN_AXISYMMETRIC_ELEMENT_H_INCLUDED )
#define KRATOS_GEO_U_PW_SMALL_STRAIN_AXISYMMETRIC_ELEMENT_H_INCLUDED
// Project includes
#include "includes/serializer.h"
// Application includes
#include "custom_utilities/comparison_utilities.hpp"
#include "custom_elements/U_Pw_small_strain_element.hpp"
#include "custom_utilities/element_utilities.hpp"
#include "geo_mechanics_application_variables.h"
namespace Kratos
{
template< unsigned int TDim, unsigned int TNumNodes >
class KRATOS_API(GEO_MECHANICS_APPLICATION) UPwSmallStrainAxisymmetricElement :
public UPwSmallStrainElement<TDim,TNumNodes>
{
public:
KRATOS_CLASS_INTRUSIVE_POINTER_DEFINITION( UPwSmallStrainAxisymmetricElement );
typedef std::size_t IndexType;
typedef Properties PropertiesType;
typedef Node <3> NodeType;
typedef Geometry<NodeType> GeometryType;
typedef Geometry<NodeType>::PointsArrayType NodesArrayType;
typedef Vector VectorType;
typedef Matrix MatrixType;
/// The definition of the sizetype
typedef std::size_t SizeType;
using UPwBaseElement<TDim,TNumNodes>::mConstitutiveLawVector;
///----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/// Default Constructor
UPwSmallStrainAxisymmetricElement(IndexType NewId = 0) :
UPwSmallStrainElement<TDim,TNumNodes>( NewId ) {}
/// Constructor using an array of nodes
UPwSmallStrainAxisymmetricElement(IndexType NewId,
const NodesArrayType& ThisNodes) :
UPwSmallStrainElement<TDim,TNumNodes>(NewId, ThisNodes) {}
/// Constructor using Geometry
UPwSmallStrainAxisymmetricElement(IndexType NewId,
GeometryType::Pointer pGeometry) :
UPwSmallStrainElement<TDim,TNumNodes>(NewId, pGeometry) {}
/// Constructor using Properties
UPwSmallStrainAxisymmetricElement(IndexType NewId,
GeometryType::Pointer pGeometry,
PropertiesType::Pointer pProperties) :
UPwSmallStrainElement<TDim,TNumNodes>( NewId, pGeometry, pProperties ) {}
/// Destructor
~UPwSmallStrainAxisymmetricElement() override {}
///----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Element::Pointer Create( IndexType NewId,
NodesArrayType const& ThisNodes,
PropertiesType::Pointer pProperties ) const override;
Element::Pointer Create( IndexType NewId,
GeometryType::Pointer pGeom,
PropertiesType::Pointer pProperties ) const override;
///----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Turn back information as a string.
std::string Info() const override
{
std::stringstream buffer;
buffer << "U-Pw small strain axial symmetric Element #" << this->Id() << "\nConstitutive law: " << mConstitutiveLawVector[0]->Info();
return buffer.str();
}
// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override
{
rOStream << "U-Pw small strain axial symmetric Element #" << this->Id() << "\nConstitutive law: " << mConstitutiveLawVector[0]->Info();
}
///----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
protected:
/// Member Variables
///----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void CalculateBMatrix( Matrix &rB,
const Matrix &GradNpT,
const Vector &Np ) override;
double CalculateIntegrationCoefficient( const GeometryType::IntegrationPointsArrayType& IntegrationPoints,
const IndexType& PointNumber,
const double& detJ) override;
///----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
private:
/// Member Variables
///----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/// Serialization
friend class Serializer;
void save(Serializer& rSerializer) const override
{
KRATOS_SERIALIZE_SAVE_BASE_CLASS( rSerializer, Element )
}
void load(Serializer& rSerializer) override
{
KRATOS_SERIALIZE_LOAD_BASE_CLASS( rSerializer, Element )
}
// Assignment operator.
UPwSmallStrainAxisymmetricElement & operator=(UPwSmallStrainAxisymmetricElement const& rOther);
// Copy constructor.
UPwSmallStrainAxisymmetricElement(UPwSmallStrainAxisymmetricElement const& rOther);
// Private Operations
}; // Class UPwSmallStrainAxisymmetricElement
} // namespace Kratos
#endif // KRATOS_GEO_U_PW_SMALL_STRAIN_AXISYMMETRIC_ELEMENT_H_INCLUDED defined
| 2,026 |
5,169 | <gh_stars>1000+
{
"name": "ContentProviders",
"summary": "A collection of useful content providers used for accessing and modifying iOS applications data.",
"version": "1.2.0",
"platforms": {
"ios": "9.0"
},
"swift_version": "4.0",
"cocoapods_version": ">= 1.4.0",
"static_framework": true,
"homepage": "https://github.com/roxiemobile/content-providers.ios",
"authors": {
"Roxie Mobile Ltd.": "<EMAIL>",
"<NAME>": "<EMAIL>"
},
"license": "BSD-4-Clause",
"source": {
"git": "https://github.com/roxiemobile/content-providers.ios.git",
"tag": "1.2.0"
},
"subspecs": [
{
"name": "SQLite",
"dependencies": {
"ContentProvidersSQLite": [
"1.2.0"
]
}
}
]
}
| 337 |
514 | /****************************************************************************
**
** Copyright (c) 2008-2020 <NAME>. All rights reserved.
** $Id: //main/2019/qhull/src/libqhullcpp/QhullFacet.h#4 $$Change: 2963 $
** $DateTime: 2020/06/03 19:31:01 $$Author: bbarber $
**
****************************************************************************/
#ifndef QHULLFACET_H
#define QHULLFACET_H
#include "libqhull_r/qhull_ra.h"
#include "libqhullcpp/QhullHyperplane.h"
#include "libqhullcpp/QhullPoint.h"
#include "libqhullcpp/QhullSet.h"
#include "libqhullcpp/QhullPointSet.h"
#include <ostream>
namespace orgQhull {
#//!\name Used here
class Coordinates;
class Qhull;
class QhullFacetSet;
class QhullRidge;
class QhullVertex;
class QhullVertexSet;
#//!\name Defined here
class QhullFacet;
typedef QhullSet<QhullRidge> QhullRidgeSet;
//! A QhullFacet is the C++ equivalent to Qhull's facetT*
class QhullFacet {
#//!\name Defined here
public:
typedef facetT * base_type; // for QhullVertexSet
private:
#//!\name Fields -- no additions (QhullFacetSet of facetT*)
facetT * qh_facet; //!< Corresponding facetT, may be 0 for corner cases (e.g., *facetSet.end()==0) and tricoplanarOwner()
QhullQh * qh_qh; //!< QhullQh/qhT for facetT, may be 0
#//!\name Class objects
static facetT s_empty_facet; // needed for shallow copy
public:
#//!\name Constructors
QhullFacet() : qh_facet(&s_empty_facet), qh_qh(0) {}
explicit QhullFacet(const Qhull &q);
QhullFacet(const Qhull &q, facetT *f);
explicit QhullFacet(QhullQh *qqh) : qh_facet(&s_empty_facet), qh_qh(qqh) {}
QhullFacet(QhullQh *qqh, facetT *f) : qh_facet(f ? f : &s_empty_facet), qh_qh(qqh) {}
// Creates an alias. Does not copy QhullFacet. Needed for return by value and parameter passing
QhullFacet(const QhullFacet &other) : qh_facet(other.qh_facet ? other.qh_facet : &s_empty_facet), qh_qh(other.qh_qh) {}
// Creates an alias. Does not copy QhullFacet. Needed for vector<QhullFacet>
QhullFacet & operator=(const QhullFacet &other) { qh_facet= other.qh_facet ? other.qh_facet : &s_empty_facet; qh_qh= other.qh_qh; return *this; }
~QhullFacet() {}
#//!\name GetSet
int dimension() const { return (qh_qh ? qh_qh->hull_dim : 0); }
QhullPoint getCenter() { return getCenter(qh_PRINTpoints); }
QhullPoint getCenter(qh_PRINT printFormat);
facetT * getBaseT() const { return getFacetT(); } //!< For QhullSet<QhullFacet>
// Do not define facetT(). It conflicts with return type facetT*
facetT * getFacetT() const { return qh_facet; }
bool hasNext() const { return (qh_facet->next != NULL && qh_facet->next != qh_qh->facet_tail); }
bool hasPrevious() const { return (qh_facet->previous != NULL); }
QhullHyperplane hyperplane() const { return QhullHyperplane(qh_qh, dimension(), qh_facet->normal, qh_facet->offset); }
countT id() const { return (qh_facet ? qh_facet->id : static_cast<countT>(qh_IDunknown)); }
QhullHyperplane innerplane() const;
bool isValid() const { return qh_qh && qh_facet && qh_facet != &s_empty_facet; }
bool isGood() const { return qh_facet && qh_facet->good; }
bool isSimplicial() const { return qh_facet && qh_facet->simplicial; }
bool isTopOrient() const { return qh_facet && qh_facet->toporient; }
bool isTriCoplanar() const { return qh_facet && qh_facet->tricoplanar; }
bool isUpperDelaunay() const { return qh_facet && qh_facet->upperdelaunay; }
QhullFacet next() const { return QhullFacet(qh_qh, qh_facet->next); }
QhullFacet nextFacet2d(QhullVertex *nextVertex) const;
bool operator==(const QhullFacet &other) const { return qh_facet==other.qh_facet; }
bool operator!=(const QhullFacet &other) const { return !operator==(other); }
QhullHyperplane outerplane() const;
QhullFacet previous() const { return QhullFacet(qh_qh, qh_facet->previous); }
QhullQh * qh() const { return qh_qh; }
void setFacetT(QhullQh *qqh, facetT *facet) { qh_qh= qqh; qh_facet= facet; }
QhullFacet tricoplanarOwner() const;
int visitId() const { return (qh_facet ? qh_facet->visitid : -1); }
QhullPoint voronoiVertex();
#//!\name value
//! Undefined if c.size() != dimension()
double distance(const Coordinates &c) const { return distance(c.data()); }
double distance(const pointT *p) const { return distance(QhullPoint(qh_qh, const_cast<coordT *>(p))); }
double distance(const QhullPoint &p) const { return hyperplane().distance(p); }
double facetArea();
#//!\name foreach
// Can not inline. Otherwise circular reference
QhullPointSet coplanarPoints() const;
QhullFacetSet neighborFacets() const;
QhullPointSet outsidePoints() const;
QhullRidgeSet ridges() const;
QhullVertexSet vertices() const;
#//!\name IO
struct PrintCenter{
QhullFacet * facet; // non-const due to facet.center()
const char * message;
qh_PRINT print_format;
PrintCenter(QhullFacet &f, qh_PRINT printFormat, const char * s) : facet(&f), message(s), print_format(printFormat){}
};//PrintCenter
PrintCenter printCenter(qh_PRINT printFormat, const char *message) { return PrintCenter(*this, printFormat, message); }
struct PrintFacet{
QhullFacet * facet; // non-const due to f->center()
const char * message;
explicit PrintFacet(QhullFacet &f, const char * s) : facet(&f), message(s) {}
};//PrintFacet
PrintFacet print(const char *message) { return PrintFacet(*this, message); }
struct PrintFlags{
const QhullFacet *facet;
const char * message;
PrintFlags(const QhullFacet &f, const char *s) : facet(&f), message(s) {}
};//PrintFlags
PrintFlags printFlags(const char *message) const { return PrintFlags(*this, message); }
struct PrintHeader{
QhullFacet * facet; // non-const due to f->center()
PrintHeader(QhullFacet &f) : facet(&f) {}
};//PrintHeader
PrintHeader printHeader() { return PrintHeader(*this); }
struct PrintRidges{
const QhullFacet *facet;
PrintRidges(QhullFacet &f) : facet(&f) {}
};//PrintRidges
PrintRidges printRidges() { return PrintRidges(*this); }
};//class QhullFacet
}//namespace orgQhull
#//!\name Global
std::ostream &operator<<(std::ostream &os, const orgQhull::QhullFacet::PrintFacet &pr);
std::ostream &operator<<(std::ostream &os, const orgQhull::QhullFacet::PrintCenter &pr);
std::ostream &operator<<(std::ostream &os, const orgQhull::QhullFacet::PrintFlags &pr);
std::ostream &operator<<(std::ostream &os, const orgQhull::QhullFacet::PrintHeader &pr);
std::ostream &operator<<(std::ostream &os, const orgQhull::QhullFacet::PrintRidges &pr);
std::ostream &operator<<(std::ostream &os, orgQhull::QhullFacet &f); // non-const due to qh_getcenter()
#endif // QHULLFACET_H
| 3,542 |
2,939 | #ifndef LUMEN_EIR_CONVERSION_BUILTIN_OP_CONVERSION
#define LUMEN_EIR_CONVERSION_BUILTIN_OP_CONVERSION
#include "lumen/EIR/Conversion/ConversionSupport.h"
namespace lumen {
namespace eir {
class IncrementReductionsOpConversion;
class IsTypeOpConversion;
class IsTupleOpConversion;
class IsFunctionOpConversion;
class PrintOpConversion;
class TraceCaptureOpConversion;
class TraceConstructOpConversion;
class TracePrintOpConversion;
void populateBuiltinOpConversionPatterns(OwningRewritePatternList &patterns,
MLIRContext *context,
EirTypeConverter &converter,
TargetInfo &targetInfo);
} // namespace eir
} // namespace lumen
#endif // LUMEN_EIR_CONVERSION_BUILTIN_OP_CONVERSION
| 352 |
3,200 | <reponame>GuoSuiming/mindspore
/**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_IRPASS_ACCUMULATEN_ELIMINATE_H_
#define MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_IRPASS_ACCUMULATEN_ELIMINATE_H_
#include <vector>
#include <algorithm>
#include <memory>
#include "frontend/optimizer/irpass.h"
#include "frontend/optimizer/optimizer.h"
#include "frontend/optimizer/anf_visitor.h"
#include "frontend/operator/ops.h"
namespace mindspore {
namespace opt {
namespace irpass {
// {PrimAccumulateNV2, {kPrimMakeTuple, inputs}}
class AccumulateNV2Eliminater : public AnfVisitor {
public:
AnfNodePtr operator()(const OptimizerPtr &, const AnfNodePtr &node) override {
Reset();
AnfVisitor::Match(prim::kPrimAccumulateNV2, {IsCNode})(node);
if (inputs_.empty() || node->func_graph() == nullptr) {
return nullptr;
}
// If only two filtered inputs nodes, as {make_tuple, x}, return x.
if (inputs_.size() == 2) {
return inputs_[1];
}
// If only one filtered node, all inputs nodes are zerolike, return one of the input.
if (inputs_.size() == 1 && args_.size() > 0) {
return args_[0];
}
if (!has_zero_like_) {
return nullptr;
}
auto cnode = node->cast<CNodePtr>();
auto accumulaten = NewValueNode(GetValueNode(cnode->input(0)));
auto fg = node->func_graph();
auto make_tuple = fg->NewCNode(inputs_);
return fg->NewCNode({accumulaten, make_tuple});
}
void Visit(const CNodePtr &cnode) override {
if (!IsPrimitiveCNode(cnode, prim::kPrimMakeTuple)) {
return;
}
auto &inputs = cnode->inputs();
(void)std::copy(inputs.begin() + 1, inputs.end(), std::back_inserter(args_));
// {kPrimMakeTuple, X1, X2, ...}
inputs_.push_back(NewValueNode(prim::kPrimMakeTuple));
for (auto &x : args_) {
if (!IsPrimitiveCNode(x, prim::kPrimZerosLike)) {
inputs_.push_back(x);
} else {
has_zero_like_ = true;
}
}
}
void Reset() {
args_.clear();
inputs_.clear();
has_zero_like_ = false;
}
private:
std::vector<AnfNodePtr> inputs_{}, args_{};
bool has_zero_like_{false};
};
} // namespace irpass
} // namespace opt
} // namespace mindspore
#endif // MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_IRPASS_ACCUMULATEN_ELIMINATE_H_
| 1,107 |
6,989 | <filename>contrib/tools/python/src/Lib/plat-irix5/ERRNO.py
# Generated by h2py from /usr/include/errno.h
from warnings import warnpy3k
warnpy3k("the ERRNO module has been removed in Python 3.0", stacklevel=2)
del warnpy3k
# Included from sys/errno.h
__KBASE = 1000
__IRIXBASE = 1000
EPERM = 1
ENOENT = 2
ESRCH = 3
EINTR = 4
EIO = 5
ENXIO = 6
E2BIG = 7
ENOEXEC = 8
EBADF = 9
ECHILD = 10
EAGAIN = 11
ENOMEM = 12
EACCES = 13
EFAULT = 14
ENOTBLK = 15
EBUSY = 16
EEXIST = 17
EXDEV = 18
ENODEV = 19
ENOTDIR = 20
EISDIR = 21
EINVAL = 22
ENFILE = 23
EMFILE = 24
ENOTTY = 25
ETXTBSY = 26
EFBIG = 27
ENOSPC = 28
ESPIPE = 29
EROFS = 30
EMLINK = 31
EPIPE = 32
EDOM = 33
ERANGE = 34
ENOMSG = 35
EIDRM = 36
ECHRNG = 37
EL2NSYNC = 38
EL3HLT = 39
EL3RST = 40
ELNRNG = 41
EUNATCH = 42
ENOCSI = 43
EL2HLT = 44
EDEADLK = 45
ENOLCK = 46
EBADE = 50
EBADR = 51
EXFULL = 52
ENOANO = 53
EBADRQC = 54
EBADSLT = 55
EDEADLOCK = 56
EBFONT = 57
ENOSTR = 60
ENODATA = 61
ETIME = 62
ENOSR = 63
ENONET = 64
ENOPKG = 65
EREMOTE = 66
ENOLINK = 67
EADV = 68
ESRMNT = 69
ECOMM = 70
EPROTO = 71
EMULTIHOP = 74
EBADMSG = 77
ENAMETOOLONG = 78
EOVERFLOW = 79
ENOTUNIQ = 80
EBADFD = 81
EREMCHG = 82
ELIBACC = 83
ELIBBAD = 84
ELIBSCN = 85
ELIBMAX = 86
ELIBEXEC = 87
EILSEQ = 88
ENOSYS = 89
ELOOP = 90
ERESTART = 91
ESTRPIPE = 92
ENOTEMPTY = 93
EUSERS = 94
ENOTSOCK = 95
EDESTADDRREQ = 96
EMSGSIZE = 97
EPROTOTYPE = 98
ENOPROTOOPT = 99
EPROTONOSUPPORT = 120
ESOCKTNOSUPPORT = 121
EOPNOTSUPP = 122
EPFNOSUPPORT = 123
EAFNOSUPPORT = 124
EADDRINUSE = 125
EADDRNOTAVAIL = 126
ENETDOWN = 127
ENETUNREACH = 128
ENETRESET = 129
ECONNABORTED = 130
ECONNRESET = 131
ENOBUFS = 132
EISCONN = 133
ENOTCONN = 134
ESHUTDOWN = 143
ETOOMANYREFS = 144
ETIMEDOUT = 145
ECONNREFUSED = 146
EHOSTDOWN = 147
EHOSTUNREACH = 148
EWOULDBLOCK = __KBASE+101
EWOULDBLOCK = EAGAIN
EALREADY = 149
EINPROGRESS = 150
ESTALE = 151
EIORESID = 500
EUCLEAN = 135
ENOTNAM = 137
ENAVAIL = 138
EISNAM = 139
EREMOTEIO = 140
EINIT = 141
EREMDEV = 142
ECANCELED = 158
ECANCELED = 1000
EDQUOT = 1133
ENFSREMOTE = 1135
ETCP_EBASE = 100
ETCP_ELIMIT = 129
ENAMI_EBASE = 129
ENAMI_ELIMIT = 131
ENFS_EBASE = 131
ENFS_ELIMIT = 135
ELASTERRNO = 135
TCP_EBASE = ETCP_EBASE
TCP_ELIMIT = ETCP_ELIMIT
NAMI_EBASE = ENAMI_EBASE
NAMI_ELIMIT = ENAMI_ELIMIT
NFS_EBASE = ENFS_EBASE
NFS_ELIMIT = ENFS_ELIMIT
LASTERRNO = ELASTERRNO
| 1,119 |
646 | {
Identifier: "tutorial-navigation"
Name: "Orbital navigation tutorial"
Description: "Learn how to navigate between orbital sectors"
Ended Description: ""
Category: TUTORIAL
Resettable: true
Triggers: [
{
Type: QUEST_SUCCESFUL
}
]
Steps: [
{
Identifier: "travel"
Step Description: "Start travel to Surface Touch"
End Conditions: [
{
Type: SECTOR_VISITED
Identifier 1: "surface-touch"
}
]
Init Actions: [
{
Type: DISCOVER_SECTOR
Identifier 1: "surface-touch"
}
{
Type: PRINT_MESSAGE
Messages Parameters : [
"To start a travel, return to the orbital menu then select the destination sector : Surface touch. Then click on the Travel button.<br>Wait the travel to end."
]
}
]
}
{
Identifier: "activate"
Step Description: "Fly at Surface Touch"
End Conditions: [
{
Type: SECTOR_ACTIVE
Identifier 1: "surface-touch"
}
]
Init Actions: [
{
Type: PRINT_MESSAGE
Messages Parameters : [
"Now you can open the sector menu for Surface touch : the ship arrived at destination. Fly it now."
]
}
]
End Actions: [
{
Type: PRINT_MESSAGE
Messages Parameters : [
"You now kwow how to travel between sectors."
]
}
]
}
]
}
| 586 |
882 | <filename>vendor/pyexcel/plugins/sources/__init__.py
"""
pyexcel.plugins.sources
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A list of built-in sources
:copyright: (c) 2015-2017 by Onni Software Ltd.
:license: New BSD License
"""
from pyexcel.internal import PARSER, RENDERER
from pyexcel.plugins import PyexcelPluginChain
PyexcelPluginChain(__name__).add_a_source(
relative_plugin_class_path='http.HttpSource',
fields=['url'],
targets=['sheet', 'book'],
actions=['read'],
attributes=['url'],
key='url'
).add_an_input_source(
relative_plugin_class_path='file_input.ReadExcelFromFile',
fields=['file_name'],
targets=['sheet', 'book'],
attributes=[],
actions=['read'],
).add_an_input_source(
relative_plugin_class_path='memory_input.ReadExcelFileMemory',
fields=['file_type'],
targets=['sheet', 'book'],
actions=['read'],
key='file_type',
attributes=PARSER.get_all_file_types
).add_a_output_source(
relative_plugin_class_path='file_output.WriteSheetToFile',
fields=['file_name'],
targets=['sheet'],
attributes=[],
actions=['write'],
).add_a_output_source(
relative_plugin_class_path='file_output.WriteBookToFile',
fields=['file_name'],
targets=['book'],
attributes=[],
actions=['write'],
).add_a_output_source(
relative_plugin_class_path='output_to_memory.WriteSheetToMemory',
fields=['file_type'],
targets=['sheet'],
actions=['write'],
key='file_type',
attributes=RENDERER.get_all_file_types,
).add_a_output_source(
relative_plugin_class_path='output_to_memory.WriteBookToMemory',
fields=['file_type'],
targets=['book'],
actions=['write'],
key='file_type',
attributes=RENDERER.get_all_file_types,
).add_a_source(
relative_plugin_class_path='pydata.bookdict.BookDictSource',
fields=['bookdict'],
targets=['sheet', 'book'],
actions=['write', 'read'],
key='bookdict',
attributes=['bookdict']
).add_a_source(
relative_plugin_class_path='pydata.dictsource.DictSource',
fields=['adict'],
targets=['sheet', 'book'],
actions=['write', 'read'],
key='adict',
attributes=['dict'],
).add_a_source(
relative_plugin_class_path='pydata.arraysource.ArraySource',
fields=['array'],
targets=['sheet', 'book'],
actions=['write', 'read'],
key='array',
attributes=['array'],
).add_a_source(
relative_plugin_class_path='pydata.records.RecordsSource',
fields=['records'],
targets=['sheet', 'book'],
actions=['write', 'read'],
key='records',
attributes=['records'],
).add_a_source(
relative_plugin_class_path='django.SheetDjangoSource',
fields=['model'],
targets=['sheet'],
actions=['write', 'read'],
).add_a_source(
relative_plugin_class_path='django.BookDjangoSource',
fields=['models'],
targets=['book'],
actions=['write', 'read'],
).add_a_source(
relative_plugin_class_path='sqlalchemy.SheetSQLAlchemySource',
fields=['session', 'table'],
targets=['sheet'],
actions=['write', 'read'],
).add_a_source(
relative_plugin_class_path='sqlalchemy.BookSQLSource',
fields=['session', 'tables'],
targets=['book'],
actions=['write', 'read'],
).add_a_source(
relative_plugin_class_path='querysets.SheetQuerySetSource',
fields=['column_names', 'query_sets'],
targets=['sheet'],
actions=['read'],
)
| 1,376 |
892 | <gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-qv83-77rj-635j",
"modified": "2022-05-13T01:19:10Z",
"published": "2022-05-13T01:19:10Z",
"aliases": [
"CVE-2018-15471"
],
"details": "An issue was discovered in xenvif_set_hash_mapping in drivers/net/xen-netback/hash.c in the Linux kernel through 4.18.1, as used in Xen through 4.11.x and other products. The Linux netback driver allows frontends to control mapping of requests to request queues. When processing a request to set or change this mapping, some input validation (e.g., for an integer overflow) was missing or flawed, leading to OOB access in hash handling. A malicious or buggy frontend may cause the (usually privileged) backend to make out of bounds memory accesses, potentially resulting in one or more of privilege escalation, Denial of Service (DoS), or information leaks.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:L/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-2018-15471"
},
{
"type": "WEB",
"url": "https://bugs.chromium.org/p/project-zero/issues/detail?id=1607"
},
{
"type": "WEB",
"url": "https://lists.debian.org/debian-lts-announce/2019/03/msg00017.html"
},
{
"type": "WEB",
"url": "https://usn.ubuntu.com/3819-1/"
},
{
"type": "WEB",
"url": "https://usn.ubuntu.com/3820-1/"
},
{
"type": "WEB",
"url": "https://usn.ubuntu.com/3820-2/"
},
{
"type": "WEB",
"url": "https://usn.ubuntu.com/3820-3/"
},
{
"type": "WEB",
"url": "https://www.debian.org/security/2018/dsa-4313"
},
{
"type": "WEB",
"url": "http://xenbits.xen.org/xsa/advisory-270.html"
}
],
"database_specific": {
"cwe_ids": [
"CWE-125"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 898 |
338 | #ifndef HADOUKEN_VERSION_HPP
#define HADOUKEN_VERSION_HPP
#include <string>
namespace hadouken
{
struct version
{
static std::string GIT_BRANCH();
static std::string GIT_COMMIT_HASH();
static std::string VERSION();
};
}
#endif
| 135 |
6,449 | <filename>motan-extension/filter-extension/filter-opentracing/src/test/java/com/weibo/api/motan/filter/opentracing/zipkin/demo/HelloServer.java
/*
* Copyright 2009-2016 Weibo, 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.weibo.api.motan.filter.opentracing.zipkin.demo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloServer {
public static void main(String[] args) {
//set tracer implementation by spring config. see motan_server.xml
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:motan_server.xml");
System.out.println("server start...");
}
}
| 407 |
488 | <gh_stars>100-1000
template < class charT > struct basic_string {
basic_string (const charT * s) {}
};
typedef basic_string <char> string;
struct Geometry {
//ERROR(1): Geometry (std::string geometry_);
void f();
};
void Geometry::f() {
const char *geometry;
// this line used to cause a segfault; now it properly
// causes an error message
//ERROR(2): *this = std::string (geometry);
}
| 141 |
7,158 | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef _OPENCV_SLIC_HPP_
#define _OPENCV_SLIC_HPP_
#include "../or_utils/or_types.hpp"
#include "opencv2/core.hpp"
//------------------------------------------------------
//
// Compile time GPU Settings
//
//------------------------------------------------------
#ifndef HFS_BLOCK_DIM
#define HFS_BLOCK_DIM 16
#endif
namespace cv { namespace hfs { namespace slic {
struct slicSettings
{
Vector2i img_size;
int spixel_size;
int num_iters;
float coh_weight;
};
struct cSpixelInfo
{
Vec2f center;
Vec3f color_info;
int id;
int num_pixels;
};
class cSLIC {
private:
cv::Mat image;
cv::Mat lab;
std::vector<int> idx_img;
cv::Vec2i map_size;
std::vector<cSpixelInfo> spixel_list;
int spixel_size;
float spatial_weight;
float max_xy_dist, max_color_dist;
float compute_dist(cv::Point pix, cSpixelInfo center_info);
void init_data(cv::Mat image_);
cv::Mat cvt_img_space();
void find_association();
void update_cluster_center();
void enforce_connect(int padding, int diff_threshold);
public:
cSLIC() {}
~cSLIC() {}
std::vector<int> generate_superpixels(cv::Mat image, int spixel_size_, float spatial_weight_);
};
#ifdef _HFS_CUDA_ON_
// utils used only by GPU version of slic
struct gSpixelInfo
{
Vector2f center;
Vector4f color_info;
int id;
int num_pixels;
};
typedef orutils::Image<gSpixelInfo> gSpixelMap;
namespace engines
{
class SegEngine
{
protected:
float max_color_dist;
float max_xy_dist;
cv::Ptr<UChar4Image> source_img;
cv::Ptr<Float4Image> cvt_img;
cv::Ptr<IntImage> idx_img;
cv::Ptr<gSpixelMap> spixel_map;
int spixel_size;
Vector2i img_size;
Vector2i map_size;
slicSettings slic_settings;
virtual void cvtImgSpace(cv::Ptr<UChar4Image> inimg,
cv::Ptr<Float4Image> outimg) = 0;
virtual void initClusterCenters() = 0;
virtual void findCenterAssociation() = 0;
virtual void updateClusterCenter() = 0;
virtual void enforceConnectivity() = 0;
public:
SegEngine(const slicSettings& in_settings);
virtual ~SegEngine();
const cv::Ptr<IntImage> getSegMask() const
{
idx_img->updateHostFromDevice();
return idx_img;
};
void setImageSize( int x, int y )
{
img_size.x = x;
img_size.y = y;
map_size.x = (int)ceil((float)x / (float)spixel_size);
map_size.y = (int)ceil((float)y / (float)spixel_size);
};
Vector2i getImageSize()
{
return img_size;
};
void performSegmentation(cv::Ptr<UChar4Image> in_img);
};
class SegEngineGPU : public SegEngine
{
private:
int no_grid_per_center;
cv::Ptr<gSpixelMap> accum_map;
cv::Ptr<IntImage> tmp_idx_img;
protected:
void cvtImgSpace(cv::Ptr<UChar4Image> inimg,
cv::Ptr<Float4Image> outimg);
void initClusterCenters();
void findCenterAssociation();
void updateClusterCenter();
void enforceConnectivity();
public:
SegEngineGPU(const slicSettings& in_settings);
~SegEngineGPU();
};
class CoreEngine
{
private:
cv::Ptr<SegEngine> slic_seg_engine;
public:
CoreEngine(const slicSettings& in_settings);
~CoreEngine();
void setImageSize(int x, int y);
void processFrame(cv::Ptr<UChar4Image> in_img);
const cv::Ptr<IntImage> getSegRes();
};
} // end namespace engine
__host__ __device__ __forceinline__ void rgb2CIELab( const Vector4u& pix_in,
Vector4f& pix_out )
{
float _b = (float)pix_in.x / 255;
float _g = (float)pix_in.y / 255;
float _r = (float)pix_in.z / 255;
if (_b <= 0.04045f) _b = _b / 12.92f;
else _b = pow( (_b + 0.055f) / 1.055f, 2.4f );
if (_g <= 0.04045f) _g = _g / 12.92f;
else _g = pow( (_g + 0.055f) / 1.055f, 2.4f );
if (_r <= 0.04045f) _r = _r / 12.92f;
else _r = pow( (_r + 0.055f) / 1.055f, 2.4f );
float x = _r*0.4124564f + _g*0.3575761f + _b*0.1804375f;
float y = _r*0.2126729f + _g*0.7151522f + _b*0.0721750f;
float z = _r*0.0193339f + _g*0.1191920f + _b*0.9503041f;
float epsilon = 0.008856f;
float kappa = 903.3f;
float Xr = 0.950456f;
float Yr = 1.0f;
float Zr = 1.088754f;
float xr = x / Xr;
float yr = y / Yr;
float zr = z / Zr;
float fx, fy, fz;
if ( xr > epsilon ) fx = pow( xr, 1.0f / 3.0f );
else fx = ( kappa*xr + 16.0f ) / 116.0f;
if ( yr > epsilon ) fy = pow( yr, 1.0f / 3.0f );
else fy = ( kappa*yr + 16.0f ) / 116.0f;
if ( zr > epsilon ) fz = pow( zr, 1.0f / 3.0f );
else fz = ( kappa*zr + 16.0f ) / 116.0f;
pix_out.x = 116.0f*fy - 16.0f;
pix_out.y = 500.0f*(fx - fy);
pix_out.z = 200.0f*(fy - fz);
}
__host__ __device__ __forceinline__ void initClusterCentersShared(
const Vector4f* inimg, Vector2i map_size, Vector2i img_size,
int spixel_size, int x, int y, cv::hfs::slic::gSpixelInfo* out_spixel)
{
int cluster_idx = y * map_size.x + x;
int img_x = x * spixel_size + spixel_size / 2;
int img_y = y * spixel_size + spixel_size / 2;
img_x = img_x >= img_size.x ? (x * spixel_size + img_size.x) / 2 : img_x;
img_y = img_y >= img_size.y ? (y * spixel_size + img_size.y) / 2 : img_y;
out_spixel[cluster_idx].id = cluster_idx;
out_spixel[cluster_idx].center = Vector2f((float)img_x, (float)img_y);
out_spixel[cluster_idx].color_info = inimg[img_y*img_size.x + img_x];
out_spixel[cluster_idx].num_pixels = 0;
}
__host__ __device__ __forceinline__ float computeSlicDistance(
const Vector4f& pix, int x, int y,
const cv::hfs::slic::gSpixelInfo& center_info,
float weight, float normalizer_xy, float normalizer_color)
{
float dcolor =
(pix.x - center_info.color_info.x)*(pix.x - center_info.color_info.x)
+ (pix.y - center_info.color_info.y)*(pix.y - center_info.color_info.y)
+ (pix.z - center_info.color_info.z)*(pix.z - center_info.color_info.z);
float dxy =
(x - center_info.center.x) * (x - center_info.center.x)
+ (y - center_info.center.y) * (y - center_info.center.y);
float retval =
dcolor * normalizer_color + weight * dxy * normalizer_xy;
return sqrtf(retval);
}
__host__ __device__ __forceinline__ void findCenterAssociationShared(
const Vector4f* inimg,
const cv::hfs::slic::gSpixelInfo* in_spixel_map,
Vector2i map_size, Vector2i img_size,
int spixel_size, float weight, int x, int y,
float max_xy_dist, float max_color_dist, int* out_idx_img)
{
int idx_img = y * img_size.x + x;
int ctr_x = x / spixel_size;
int ctr_y = y / spixel_size;
int minidx = -1;
float dist = 999999.9999f;
for ( int i = -1; i <= 1; i++ )
for ( int j = -1; j <= 1; j++ )
{
int ctr_x_check = ctr_x + j;
int ctr_y_check = ctr_y + i;
if (ctr_x_check >= 0 && ctr_y_check >= 0 &&
ctr_x_check < map_size.x && ctr_y_check < map_size.y)
{
int ctr_idx = ctr_y_check*map_size.x + ctr_x_check;
float cdist =
computeSlicDistance(inimg[idx_img], x, y,
in_spixel_map[ctr_idx], weight,
max_xy_dist, max_color_dist);
if (cdist < dist)
{
dist = cdist;
minidx = in_spixel_map[ctr_idx].id;
}
}
}
if (minidx >= 0)
out_idx_img[idx_img] = minidx;
}
__host__ __device__ __forceinline__ void finalizeReductionResultShared(
const cv::hfs::slic::gSpixelInfo* accum_map,
Vector2i map_size, int num_blocks_per_spixel, int x, int y,
cv::hfs::slic::gSpixelInfo* spixel_list)
{
int spixel_idx = y * map_size.x + x;
spixel_list[spixel_idx].center = Vector2f(0, 0);
spixel_list[spixel_idx].color_info = Vector4f(0, 0, 0, 0);
spixel_list[spixel_idx].num_pixels = 0;
for (int i = 0; i < num_blocks_per_spixel; i++)
{
int accum_list_idx = spixel_idx * num_blocks_per_spixel + i;
spixel_list[spixel_idx].center +=
accum_map[accum_list_idx].center;
spixel_list[spixel_idx].color_info +=
accum_map[accum_list_idx].color_info;
spixel_list[spixel_idx].num_pixels +=
accum_map[accum_list_idx].num_pixels;
}
if (spixel_list[spixel_idx].num_pixels != 0)
{
spixel_list[spixel_idx].center /=
(float)spixel_list[spixel_idx].num_pixels;
spixel_list[spixel_idx].color_info /=
(float)spixel_list[spixel_idx].num_pixels;
}
else
{
spixel_list[spixel_idx].center =
Vector2f(-100, -100);
spixel_list[spixel_idx].color_info =
Vector4f(-100, -100, -100, -100);
}
}
__host__ __device__ __forceinline__ void supressLocalLable(
const int* in_idx_img, Vector2i img_size,
int x, int y, int* out_idx_img)
{
int clable = in_idx_img[y*img_size.x + x];
if (x < 2 || y < 2 || x >= img_size.x - 2 || y >= img_size.y - 2)
{
out_idx_img[y*img_size.x + x] = clable;
return;
}
int diff_count = 0;
int diff_lable = -1;
for ( int j = -2; j <= 2; j++ )
for ( int i = -2; i <= 2; i++ )
{
int nlable = in_idx_img[(y + j)*img_size.x + (x + i)];
if (nlable != clable)
{
diff_lable = nlable;
diff_count++;
}
}
if (diff_count > 16)
out_idx_img[y*img_size.x + x] = diff_lable;
else
out_idx_img[y*img_size.x + x] = clable;
}
__host__ __device__ __forceinline__ void supressLocalLable2(const int* in_idx_img,
Vector2i img_size, int x, int y, int* out_idx_img)
{
int pixel_idx = y*img_size.x + x;
int clable = in_idx_img[pixel_idx];
if (x < 1 || y < 1 || x >= img_size.x - 1 || y >= img_size.y - 1)
{
out_idx_img[y*img_size.x + x] = clable;
return;
}
int diff_count = 0;
int diff_lable = -1;
for (int j = -1; j <= 1; j++)
for (int i = -1; i <= 1; i++)
{
int nlable = in_idx_img[(y + j)*img_size.x + (x + i)];
if (nlable != clable)
{
diff_lable = nlable;
diff_count++;
}
}
if (diff_count >= 6)
out_idx_img[pixel_idx] = diff_lable;
else
out_idx_img[pixel_idx] = clable;
}
__host__ __device__ __forceinline__ dim3 getGridSize( Vector2i dataSz, dim3 blockSz )
{
return dim3((dataSz.x + blockSz.x - 1) / blockSz.x,
(dataSz.y + blockSz.y - 1) / blockSz.y);
}
struct Float4_
{
__host__ __device__ Float4_() {}
__host__ __device__ Float4_( float x_, float y_, float z_, float w_ ) {
x = x_, y = y_, z = z_, w = w_;
}
volatile float x, y, z, w;
};
struct Float2_
{
__host__ __device__ Float2_() {}
__host__ __device__ Float2_( float x_, float y_ ) {
x = x_, y = y_;
}
volatile float x, y;
};
__host__ __device__ __forceinline__ Float4_ operator+= ( Float4_ &a, Float4_ b )
{
a.x += b.x;
a.y += b.y;
a.z += b.z;
a.w += b.w;
return a;
}
__host__ __device__ __forceinline__ Float2_ operator+= ( Float2_ &a, Float2_ b )
{
a.x += b.x;
a.y += b.y;
return a;
}
#endif
}}}
#endif
| 5,937 |
640 | <filename>libsrc/_DEVELOPMENT/EXAMPLES/sms/SpaceHawks/screens/_screen_basic.c
#include <stdbool.h> //for true/false
#include <stddef.h> //for null
#include <arch/sms/SMSlib.h>
#include "../s8/joy.h"
#include "../s8/vdp.h"
#include "../resource.h"
#include "screenManager.h"
#define FONT_TILE 0
static bool paused = false;
static bool done = false;
static void joyPressed(unsigned char joy, unsigned int pressed, unsigned int state)
{
if (state == (PORT_A_KEY_UP|PORT_A_KEY_1))
{
done = true;
return;
}
}
static void joyReleased(unsigned char joy, unsigned int released, unsigned int state)
{
}
static void spritesInit( )
{
SMS_displayOff();
paused = false;
done = false;
SMS_loadTiles(font_lib_bin, FONT_TILE, font_lib_bin_size);
SMS_loadBGPalette(shawks_pal_bin);
SMS_loadSpritePalette(shawks_pal_bin);
JOY_init();
JOY_setPressedCallback(&joyPressed);
JOY_setReleasedCallback(&joyReleased);
SMS_displayOn();
}
static void spritesUpdate( )
{
if (done)
{
setCurrentScreen(TITLE_SCREEN);
return;
}
if (SMS_queryPauseRequested()) {
paused = !paused;
SMS_resetPauseRequest();
}
if (!paused)
{
JOY_update();
//sprite update
}
SMS_initSprites();
//addMetaSprite(&hawk);
SMS_finalizeSprites();
SMS_copySpritestoSAT( );
}
gameScreen spritesScreen =
{
// SPRITES_SCREEN,
SPRITESMIND_SCREEN,
&spritesInit,
&spritesUpdate,
NULL,
NULL,
NULL
};
| 604 |
316 | #pragma once
#include "../probe.h"
#include "../tga.h"
void TestMaterials(Scene* scene, Camera* camera, Options* options)
{
// add primitives
const int rowSize = 6;
float r = 0.5f;
float y = r;
float dx = r*2.2f;
float x = (rowSize-1)*r*2.2f*0.5f;
for (int i=0; i < rowSize; ++i)
{
Primitive sphere;
sphere.type = eSphere;
sphere.sphere.radius = r;
sphere.startTransform = Transform(Vec3(-x + i*dx, y, 0.0f));
sphere.endTransform = Transform(Vec3(-x + i*dx, y, 0.0f));
sphere.material.color = Vec3(.82f, .67f, .16f);
sphere.material.metallic = float(i)/(rowSize-1);
sphere.material.roughness = 0.25f;
scene->AddPrimitive(sphere);
}
y += r*2.2f;
for (int i=0; i < rowSize; ++i)
{
Primitive sphere;
sphere.type = eSphere;
sphere.sphere.radius = r;
sphere.startTransform = Transform(Vec3(-x + i*dx, y, 0.0f));
sphere.endTransform = Transform(Vec3(-x + i*dx, y, 0.0f));
sphere.material.color = Vec3(SrgbToLinear(Color(.05f, .57f, .36f)));
sphere.material.metallic = 0.0f;
float shiny = Max(0.0f, Sqr(1.0f-float(i)/(rowSize-1)));
sphere.material.specular = 0.75f;
sphere.material.roughness = shiny;
scene->AddPrimitive(sphere);
}
y += r*2.2f;
for (int i=0; i < rowSize; ++i)
{
Primitive sphere;
sphere.type = eSphere;
sphere.sphere.radius = r;
sphere.startTransform = Transform(Vec3(-x + i*dx, y, 0.0f));
sphere.endTransform = Transform(Vec3(-x + i*dx, y, 0.0f));
sphere.material.color = Vec3(SrgbToLinear(Color(0.9)));
sphere.material.metallic = 0.0f;
sphere.material.transmission = float(i)/(rowSize-1);
sphere.material.roughness = 0.01f;
scene->AddPrimitive(sphere);
}
y += r*2.2f;
/*
for (int i=0; i < rowSize; ++i)
{
Primitive sphere;
sphere.type = eSphere;
sphere.sphere.radius = r;
sphere.startTransform = Transform(Vec3(-x + i*dx, y, 0.0f));
sphere.endTransform = Transform(Vec3(-x + i*dx, y, 0.0f));
sphere.material.subsurface = float(i)/(rowSize-1);
sphere.material.color = SrgbToLinear(Color(0.7f));
sphere.material.specular = 0.0f;
scene->AddPrimitive(sphere);
}
y += r*2.2f;
*/
Material gold;
gold.color = Vec3(1.0f, 0.71f, 0.29f);
gold.roughness = 0.2f;
gold.metallic = 1.0f;
Material silver;
silver.color = Vec3(0.95f, 0.93f, 0.88f);
silver.roughness = 0.2f;
silver.metallic = 1.0f;
Material copper;
copper.color = Vec3(0.95f, 0.64f, 0.54f);
copper.roughness = 0.2f;
copper.metallic = 1.0f;
Material iron;
iron.color = Vec3(0.56f, 0.57f, 0.58f);
iron.roughness = 0.2f;
iron.metallic = 1.0f;
Material aluminum;
aluminum.color = Vec3(0.91f, 0.92f, 0.92f);
aluminum.roughness = 0.2f;
aluminum.metallic = 1.0f;
Material plaster;
plaster.color = Vec3(0.94f, 0.94f, 0.94f);
plaster.roughness = 0.5;
plaster.specular = 0.1;
Material mats[6] = { gold, silver, copper, iron, aluminum, plaster };
for (int i=0; i < 6; ++i)
{
Primitive sphere;
sphere.type = eSphere;
sphere.sphere.radius = r;
sphere.startTransform = Transform(Vec3(-x + i*dx, y, 0.0f));
sphere.endTransform = Transform(Vec3(-x+ i*dx, y, 0.0f));
sphere.material = mats[i];
scene->AddPrimitive(sphere);
}
Primitive plane;
plane.type = ePlane;
plane.plane.plane[0] = 0.0f;
plane.plane.plane[1] = 1.0f;
plane.plane.plane[2] = 0.0f;
plane.plane.plane[3] = 0.0f;
plane.material.color = Vec3(0.5);
Primitive back;
back.type = ePlane;
back.plane.plane[0] = 0.0f;
back.plane.plane[1] = 0.0f;
back.plane.plane[2] = 1.0f;
back.plane.plane[3] = 5.0f;
back.material.color = Vec3(0.1);
Primitive light;
light.type = eSphere;
light.sphere.radius = 1.0f;
light.startTransform = Transform(Vec3(0.0f, 6.0f, 6.0f));
light.endTransform = light.startTransform;
light.material.color = Vec3(0.0f);
light.material.emission = Vec3(15.0f);
light.lightSamples = 1;
scene->AddPrimitive(plane);
scene->AddPrimitive(back);
//scene->AddPrimitive(light);
//scene->sky.horizon = Color(0.1f, 0.3f, 0.6f)*2.0f;
//scene->sky.zenith = scene->sky.horizon;
scene->sky.probe = ProbeLoadFromFile("data/probes/vankleef.hdr");
// set up camera
camera->position = Vec3(0.0f, 2.0f, 20.0f);
camera->fov = DegToRad(15.0f);
}
void TestPaniq(Scene* scene, Camera* camera, Options* options)
{
#if 0
Vec3 colors[16] =
{
Vec3(1.0f, 0.254f, 0.287f), // light pink
Vec3(1.0f, 0.823f, 0.036f), // yellow
Vec3(0.209f, 1.0f, 0.521f), // light blue
Vec3(0.371f, 0.027f, 0.456f), // purple
Vec3(1.0f, 0.019f, 0.051f), // bright pink
Vec3(0.0f, 0.708f, 0.072f), // bright green
Vec3(0.0f, 0.275f, 0.730f), // mid blue
Vec3(1.0f, 0.305f, 0.026f), // orange
Vec3(0.168f, 0.0f, 0.01f), // dark red
Vec3(0.0f, 0.178f, 0.018f), // dark green
Vec3(0.015f, 0.016f, 0.178f), // dark blue
Vec3(0.546f, 0.082f, 0.041f), // dark orange
Vec3(0.0f, 0.0f, 0.0f), // black
Vec3(0.06f, 0.091f, 0.130f), // dark grey
Vec3(0.491f, 0.491f, 0.491f), // light grey
Vec3(1.0f, 1.0f, 1.0f) // white
};
float radius = 1.0f;
float spacing = 2.5f;
Mesh* obj = ImportMeshFromObj("data/brain.obj");
obj->Normalize(1.f);
MeshGeometry mesh = GeometryFromMesh(obj);
for (int y=0; y < 4; ++y)
{
for (int x=0; x < 4; ++x)
{
Primitive sphere;
//sphere.type = eSphere;
//sphere.sphere.radius = radius;
sphere.type = eMesh;
sphere.mesh = mesh;
sphere.startTransform = Transform(Vec3(x*spacing, y*spacing, 0.0f));
sphere.endTransform = Transform(Vec3(x*spacing, y*spacing, 0.0f));
sphere.material.color = colors[y*4 + x];
sphere.material.metallic = 0.0f;
sphere.material.roughness = 0.01f;
//sphere.material.clearcoat = 1.0f;
//sphere.material.transmission = 0.0f;
//sphere.material.absorption = Max(0.0f, Vec3(0.75f)-sphere.material.color);//Vec3(sqrtf(sphere.material.color.x), sqrtf(sphere.material.color.y), sqrtf(sphere.material.color.z))*0.5f;
scene->AddPrimitive(sphere);
}
}
float center = 3.0f*spacing*0.5f;
#else
TgaImage img;
TgaLoad("data/palette.tga", img);
float radius = 1.0f;
float spacing = 2.5f;
Mesh* obj = ImportMeshFromObj("data/meshes/brain.obj");
obj->Normalize(2.f);
obj->Transform(TranslationMatrix(Vec3(-1.0f)));
obj->RebuildBVH();
//MeshGeometry mesh = GeometryFromMesh(obj);
for (int y=0; y < img.m_height; ++y)
{
for (int x=0; x < img.m_width; ++x)
{
Primitive sphere;
//sphere.type = eSphere;
//sphere.sphere.radius = radius;
sphere.type = eMesh;
sphere.mesh = GeometryFromMesh(obj);
sphere.startTransform = Transform(Vec3(x*spacing, y*spacing, 0.0f));
sphere.endTransform = Transform(Vec3(x*spacing, y*spacing, 0.0f));
unsigned int c = img.m_data[y*img.m_width + x];
float r = (c>>0)&0xff;
float g = (c>>8)&0xff;
float b = (c>>16)&0xff;
printf("%f %f %f\n", r, g, b);
Color col(r/255.0f, g/255.0f, b/255.0f);
col = SrgbToLinear(col);
sphere.material.color = Vec3(col);
//sphere.material.specular = 0.0f;
//sphere.material.emission = Vec3(col)*0.25f;
sphere.material.metallic = 0.0f;
sphere.material.roughness = 0.01f;
sphere.material.clearcoat = 0.0f;
sphere.material.clearcoatGloss = 1.0f;
sphere.material.subsurface = 0.0f;
//sphere.material.transmission = 1.0f;
//sphere.material.absorption = Max(0.0f, Vec3(0.75f)-sphere.material.color);//Vec3(sqrtf(sphere.material.color.x), sqrtf(sphere.material.color.y), sqrtf(sphere.material.color.z))*0.5f;
scene->AddPrimitive(sphere);
}
}
TgaFree(img);
float center = (img.m_width-1)*spacing*0.5f;
#endif
Primitive plane;
plane.type = ePlane;
plane.plane.plane[0] = 0.0f;
plane.plane.plane[1] = 1.0f;
plane.plane.plane[2] = 0.0f;
plane.plane.plane[3] = 1.0f;
plane.material.color = Vec3(0.8);
Primitive back;
back.type = ePlane;
back.plane.plane[0] = 0.0f;
back.plane.plane[1] = 0.0f;
back.plane.plane[2] = 1.0f;
back.plane.plane[3] = 1.5f;
back.material.color = Vec3(0.8);
Primitive light;
light.type = eSphere;
light.sphere.radius = 1.0f;
light.startTransform = Transform(Vec3(10.f, 15.0f, 15.0f));
light.endTransform = light.startTransform;
light.material.color = Vec3(0.0f);
light.material.emission = Vec3(150.0f);
light.lightSamples = 1;
//scene->AddPrimitive(plane);
scene->AddPrimitive(back);
//scene->AddPrimitive(light);
//scene->sky.horizon = Color(0.1f, 0.3f, 0.6f)*2.0f;
//scene->sky.zenith = scene->sky.horizon;
scene->sky.probe = ProbeLoadFromFile("data/probes/nature.hdr");
options->width = 1920;
options->height = options->width/2;
//options->clamp = 2.0f;
// set up camera
camera->position = Vec3(center, 3.75f, 40.0f);
camera->rotation = Quat();
camera->fov = DegToRad(15.0f);
}
| 4,416 |
14,425 | <reponame>bzhaoopenstack/hadoop
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.blockmanagement;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.TestBlockStoragePolicy;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.net.NetworkTopology;
import org.apache.hadoop.test.GenericTestUtils.DelayAnswer;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.apache.hadoop.fs.contract.hdfs.HDFSContract.BLOCK_SIZE;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
/**
* This class tests RedundancyMonitor in BlockManager.
*/
public class TestRedundancyMonitor {
private static final String FILENAME = "/dummyfile.txt";
/**
* RedundancyMonitor invoke choose target out of global lock when
* #computeDatanodeWork. However it may result in NN terminate when choose
* target meet runtime exception(ArithmeticException) since we stop all
* DataNodes during that time.
* Verify that NN should not terminate even stop all datanodes.
*/
@Test
public void testChooseTargetWhenAllDataNodesStop() throws Throwable {
HdfsConfiguration conf = new HdfsConfiguration();
String[] hosts = new String[]{"host1", "host2"};
String[] racks = new String[]{"/d1/r1", "/d1/r1"};
try (MiniDFSCluster miniCluster = new MiniDFSCluster.Builder(conf)
.racks(racks).hosts(hosts).numDataNodes(hosts.length).build()) {
miniCluster.waitActive();
FSNamesystem fsn = miniCluster.getNamesystem();
BlockManager blockManager = fsn.getBlockManager();
BlockPlacementPolicyDefault replicator
= (BlockPlacementPolicyDefault) blockManager
.getBlockPlacementPolicy();
Set<DatanodeDescriptor> dns = blockManager.getDatanodeManager()
.getDatanodes();
DelayAnswer delayer = new DelayAnswer(BlockPlacementPolicyDefault.LOG);
NetworkTopology clusterMap = replicator.clusterMap;
NetworkTopology spyClusterMap = spy(clusterMap);
replicator.clusterMap = spyClusterMap;
doAnswer(delayer).when(spyClusterMap).getNumOfRacks();
ExecutorService pool = Executors.newFixedThreadPool(2);
// Trigger chooseTarget
Future<Void> chooseTargetFuture = pool.submit(() -> {
replicator.chooseTarget(FILENAME, 2, dns.iterator().next(),
new ArrayList<DatanodeStorageInfo>(), false, null, BLOCK_SIZE,
TestBlockStoragePolicy.DEFAULT_STORAGE_POLICY, null);
return null;
});
// Wait until chooseTarget calls NetworkTopology#getNumOfRacks
delayer.waitForCall();
// Remove all DataNodes
Future<Void> stopDatanodesFuture = pool.submit(() -> {
for (DatanodeDescriptor dn : dns) {
spyClusterMap.remove(dn);
}
return null;
});
// Wait stopDatanodesFuture run finish
stopDatanodesFuture.get();
// Allow chooseTarget to proceed
delayer.proceed();
try {
chooseTargetFuture.get();
} catch (ExecutionException ee) {
throw ee.getCause();
}
}
}
}
| 1,447 |
428 | package org.loon.framework.javase.game.action.sprite.j2me;
import java.util.Vector;
import org.loon.framework.javase.game.core.graphics.device.LGraphics;
/**
* Copyright 2008 - 2009
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @project loonframework
* @author chenpeng
* @email:<EMAIL>
* @version 0.1
*/
public class LayerManager {
private Vector<Layer> layers;
private int viewX, viewY, viewW, viewH;
public LayerManager() {
layers = new Vector<Layer>();
viewX = viewY = 0;
viewW = viewH = Integer.MAX_VALUE;
}
public void append(Layer layer) {
synchronized (this) {
if (layer == null)
throw new NullPointerException();
layers.add(layer);
}
}
public Layer getLayerAt(int i) {
return (Layer) layers.get(i);
}
public int getSize() {
return layers.size();
}
public void insert(Layer layer, int i) {
synchronized (this) {
if (layer == null)
throw new NullPointerException();
layers.insertElementAt(layer, i);
}
}
public void remove(Layer layer) {
synchronized (this) {
if (layer == null)
throw new NullPointerException();
layers.remove(layer);
}
}
public void setViewWindow(int x, int y, int width, int height) {
synchronized (this) {
if (width < 0 || height < 0)
throw new IllegalArgumentException();
viewX = x;
viewY = y;
viewW = width;
viewH = height;
}
}
public void paint(LGraphics g, int x, int y) {
synchronized (this) {
if (g == null){
throw new NullPointerException();
}
int clipX = g.getClipX();
int clipY = g.getClipY();
int clipW = g.getClipWidth();
int clipH = g.getClipHeight();
g.translate(x - viewX, y - viewY);
g.clipRect(viewX, viewY, viewW, viewH);
for (int i = getSize(); --i >= 0;) {
Layer comp = getLayerAt(i);
if (comp.isVisible()) {
comp.paint(g);
}
}
g.translate(-x + viewX, -y + viewY);
g.setClip(clipX, clipY, clipW, clipH);
}
}
}
| 939 |
371 | #!/usr/bin/env python3
# encoding: utf-8
from typing import Dict, List
import numpy as np
import torch as th
import torch.distributions as td
from rls.algorithms.base.sarl_on_policy import SarlOnPolicy
from rls.common.data import Data
from rls.common.decorator import iton
from rls.nn.models import (ActorCriticValueCts, ActorCriticValueDct, ActorDct,
ActorMuLogstd, CriticValue)
from rls.nn.utils import OPLR
from rls.utils.np_utils import calculate_td_error, discounted_sum
class PPO(SarlOnPolicy):
"""
Proximal Policy Optimization, https://arxiv.org/abs/1707.06347
Emergence of Locomotion Behaviours in Rich Environments, http://arxiv.org/abs/1707.02286, DPPO
"""
policy_mode = 'on-policy'
def __init__(self,
agent_spec,
ent_coef: float = 1.0e-2,
vf_coef: float = 0.5,
lr: float = 5.0e-4,
lambda_: float = 0.95,
epsilon: float = 0.2,
use_duel_clip: bool = False,
duel_epsilon: float = 0.,
use_vclip: bool = False,
value_epsilon: float = 0.2,
share_net: bool = True,
actor_lr: float = 3e-4,
critic_lr: float = 1e-3,
kl_reverse: bool = False,
kl_target: float = 0.02,
kl_target_cutoff: float = 2,
kl_target_earlystop: float = 4,
kl_beta: List[float] = [0.7, 1.3],
kl_alpha: float = 1.5,
kl_coef: float = 1.0,
extra_coef: float = 1000.0,
use_kl_loss: bool = False,
use_extra_loss: bool = False,
use_early_stop: bool = False,
network_settings: Dict = {
'share': {
'continuous': {
'condition_sigma': False,
'log_std_bound': [-20, 2],
'share': [32, 32],
'mu': [32, 32],
'v': [32, 32]
},
'discrete': {
'share': [32, 32],
'logits': [32, 32],
'v': [32, 32]
}
},
'actor_continuous': {
'hidden_units': [64, 64],
'condition_sigma': False,
'log_std_bound': [-20, 2]
},
'actor_discrete': [32, 32],
'critic': [32, 32]
},
**kwargs):
super().__init__(agent_spec=agent_spec, **kwargs)
self._ent_coef = ent_coef
self.lambda_ = lambda_
assert 0.0 <= lambda_ <= 1.0, "GAE lambda should be in [0, 1]."
self._epsilon = epsilon
self._use_vclip = use_vclip
self._value_epsilon = value_epsilon
self._share_net = share_net
self._kl_reverse = kl_reverse
self._kl_target = kl_target
self._kl_alpha = kl_alpha
self._kl_coef = kl_coef
self._extra_coef = extra_coef
self._vf_coef = vf_coef
self._use_duel_clip = use_duel_clip
self._duel_epsilon = duel_epsilon
if self._use_duel_clip:
assert - \
self._epsilon < self._duel_epsilon < self._epsilon, "duel_epsilon should be set in the range of (-epsilon, epsilon)."
self._kl_cutoff = kl_target * kl_target_cutoff
self._kl_stop = kl_target * kl_target_earlystop
self._kl_low = kl_target * kl_beta[0]
self._kl_high = kl_target * kl_beta[-1]
self._use_kl_loss = use_kl_loss
self._use_extra_loss = use_extra_loss
self._use_early_stop = use_early_stop
if self._share_net:
if self.is_continuous:
self.net = ActorCriticValueCts(self.obs_spec,
rep_net_params=self._rep_net_params,
output_shape=self.a_dim,
network_settings=network_settings['share']['continuous']).to(self.device)
else:
self.net = ActorCriticValueDct(self.obs_spec,
rep_net_params=self._rep_net_params,
output_shape=self.a_dim,
network_settings=network_settings['share']['discrete']).to(self.device)
self.oplr = OPLR(self.net, lr, **self._oplr_params)
self._trainer_modules.update(model=self.net,
oplr=self.oplr)
else:
if self.is_continuous:
self.actor = ActorMuLogstd(self.obs_spec,
rep_net_params=self._rep_net_params,
output_shape=self.a_dim,
network_settings=network_settings['actor_continuous']).to(self.device)
else:
self.actor = ActorDct(self.obs_spec,
rep_net_params=self._rep_net_params,
output_shape=self.a_dim,
network_settings=network_settings['actor_discrete']).to(self.device)
self.critic = CriticValue(self.obs_spec,
rep_net_params=self._rep_net_params,
network_settings=network_settings['critic']).to(self.device)
self.actor_oplr = OPLR(self.actor, actor_lr, **self._oplr_params)
self.critic_oplr = OPLR(self.critic, critic_lr, **self._oplr_params)
self._trainer_modules.update(actor=self.actor,
critic=self.critic,
actor_oplr=self.actor_oplr,
critic_oplr=self.critic_oplr)
@iton
def select_action(self, obs):
if self.is_continuous:
if self._share_net:
mu, log_std, value = self.net(obs, rnncs=self.rnncs) # [B, A]
self.rnncs_ = self.net.get_rnncs()
else:
mu, log_std = self.actor(obs, rnncs=self.rnncs) # [B, A]
self.rnncs_ = self.actor.get_rnncs()
value = self.critic(obs, rnncs=self.rnncs) # [B, 1]
dist = td.Independent(td.Normal(mu, log_std.exp()), 1)
action = dist.sample().clamp(-1, 1) # [B, A]
log_prob = dist.log_prob(action).unsqueeze(-1) # [B, 1]
else:
if self._share_net:
logits, value = self.net(obs, rnncs=self.rnncs) # [B, A], [B, 1]
self.rnncs_ = self.net.get_rnncs()
else:
logits = self.actor(obs, rnncs=self.rnncs) # [B, A]
self.rnncs_ = self.actor.get_rnncs()
value = self.critic(obs, rnncs=self.rnncs) # [B, 1]
norm_dist = td.Categorical(logits=logits)
action = norm_dist.sample() # [B,]
log_prob = norm_dist.log_prob(action).unsqueeze(-1) # [B, 1]
acts_info = Data(action=action,
value=value,
log_prob=log_prob + th.finfo().eps)
if self.use_rnn:
acts_info.update(rnncs=self.rnncs)
return action, acts_info
@iton
def _get_value(self, obs, rnncs=None):
if self._share_net:
if self.is_continuous:
_, _, value = self.net(obs, rnncs=rnncs) # [B, 1]
else:
_, value = self.net(obs, rnncs=rnncs) # [B, 1]
else:
value = self.critic(obs, rnncs=rnncs) # [B, 1]
return value
def _preprocess_BATCH(self, BATCH): # [T, B, *]
BATCH = super()._preprocess_BATCH(BATCH)
value = self._get_value(BATCH.obs_[-1], rnncs=self.rnncs)
BATCH.discounted_reward = discounted_sum(BATCH.reward,
self.gamma,
BATCH.done,
BATCH.begin_mask,
init_value=value)
td_error = calculate_td_error(BATCH.reward,
self.gamma,
BATCH.done,
value=BATCH.value,
next_value=np.concatenate((BATCH.value[1:], value[np.newaxis, :]), 0))
BATCH.gae_adv = discounted_sum(td_error,
self.lambda_ * self.gamma,
BATCH.done,
BATCH.begin_mask,
init_value=0.,
normalize=True)
return BATCH
def learn(self, BATCH: Data):
BATCH = self._preprocess_BATCH(BATCH) # [T, B, *]
for _ in range(self._epochs):
kls = []
for _BATCH in BATCH.sample(self._chunk_length, self.batch_size, repeat=self._sample_allow_repeat):
_BATCH = self._before_train(_BATCH)
summaries, kl = self._train(_BATCH)
kls.append(kl)
self.summaries.update(summaries)
self._after_train()
if self._use_early_stop and sum(kls) / len(kls) > self._kl_stop:
break
def _train(self, BATCH):
if self._share_net:
summaries, kl = self.train_share(BATCH)
else:
summaries = dict()
actor_summaries, kl = self.train_actor(BATCH)
critic_summaries = self.train_critic(BATCH)
summaries.update(actor_summaries)
summaries.update(critic_summaries)
if self._use_kl_loss:
# ref: https://github.com/joschu/modular_rl/blob/6970cde3da265cf2a98537250fea5e0c0d9a7639/modular_rl/ppo.py#L93
if kl > self._kl_high:
self._kl_coef *= self._kl_alpha
elif kl < self._kl_low:
self._kl_coef /= self._kl_alpha
summaries.update({
'Statistics/kl_coef': self._kl_coef
})
return summaries, kl
@iton
def train_share(self, BATCH):
if self.is_continuous:
# [T, B, A], [T, B, A], [T, B, 1]
mu, log_std, value = self.net(BATCH.obs, begin_mask=BATCH.begin_mask)
dist = td.Independent(td.Normal(mu, log_std.exp()), 1)
new_log_prob = dist.log_prob(BATCH.action).unsqueeze(-1) # [T, B, 1]
entropy = dist.entropy().unsqueeze(-1) # [T, B, 1]
else:
# [T, B, A], [T, B, 1]
logits, value = self.net(BATCH.obs, begin_mask=BATCH.begin_mask)
logp_all = logits.log_softmax(-1) # [T, B, 1]
new_log_prob = (BATCH.action * logp_all).sum(-1, keepdim=True) # [T, B, 1]
entropy = -(logp_all.exp() * logp_all).sum(-1, keepdim=True) # [T, B, 1]
ratio = (new_log_prob - BATCH.log_prob).exp() # [T, B, 1]
surrogate = ratio * BATCH.gae_adv # [T, B, 1]
clipped_surrogate = th.minimum(
surrogate,
ratio.clamp(1.0 - self._epsilon, 1.0 + self._epsilon) * BATCH.gae_adv
) # [T, B, 1]
# ref: https://github.com/thu-ml/tianshou/blob/c97aa4065ee8464bd5897bb86f1f81abd8e2cff9/tianshou/policy/modelfree/ppo.py#L159
if self._use_duel_clip:
clipped_surrogate2 = th.maximum(
clipped_surrogate,
(1.0 + self._duel_epsilon) * BATCH.gae_adv
) # [T, B, 1]
clipped_surrogate = th.where(BATCH.gae_adv < 0, clipped_surrogate2, clipped_surrogate) # [T, B, 1]
actor_loss = -(clipped_surrogate + self._ent_coef * entropy).mean() # 1
# ref: https://github.com/joschu/modular_rl/blob/6970cde3da265cf2a98537250fea5e0c0d9a7639/modular_rl/ppo.py#L40
# ref: https://github.com/hill-a/stable-baselines/blob/b3f414f4f2900403107357a2206f80868af16da3/stable_baselines/ppo2/ppo2.py#L185
if self._kl_reverse: # TODO:
kl = .5 * (new_log_prob - BATCH.log_prob).square().mean() # 1
else:
# a sample estimate for KL-divergence, easy to compute
kl = .5 * (BATCH.log_prob - new_log_prob).square().mean()
if self._use_kl_loss:
kl_loss = self._kl_coef * kl # 1
actor_loss += kl_loss
if self._use_extra_loss:
extra_loss = self._extra_coef * th.maximum(th.zeros_like(kl), kl - self._kl_cutoff).square().mean() # 1
actor_loss += extra_loss
td_error = BATCH.discounted_reward - value # [T, B, 1]
if self._use_vclip:
# ref: https://github.com/llSourcell/OpenAI_Five_vs_Dota2_Explained/blob/c5def7e57aa70785c2394ea2eeb3e5f66ad59a53/train.py#L154
# ref: https://github.com/hill-a/stable-baselines/blob/b3f414f4f2900403107357a2206f80868af16da3/stable_baselines/ppo2/ppo2.py#L172
value_clip = BATCH.value + (value - BATCH.value).clamp(-self._value_epsilon,
self._value_epsilon) # [T, B, 1]
td_error_clip = BATCH.discounted_reward - value_clip # [T, B, 1]
td_square = th.maximum(td_error.square(), td_error_clip.square()) # [T, B, 1]
else:
td_square = td_error.square() # [T, B, 1]
critic_loss = 0.5 * td_square.mean() # 1
loss = actor_loss + self._vf_coef * critic_loss # 1
self.oplr.optimize(loss)
return {
'LOSS/actor_loss': actor_loss,
'LOSS/critic_loss': critic_loss,
'Statistics/kl': kl,
'Statistics/entropy': entropy.mean(),
'LEARNING_RATE/lr': self.oplr.lr
}, kl
@iton
def train_actor(self, BATCH):
if self.is_continuous:
# [T, B, A], [T, B, A]
mu, log_std = self.actor(BATCH.obs, begin_mask=BATCH.begin_mask)
dist = td.Independent(td.Normal(mu, log_std.exp()), 1)
new_log_prob = dist.log_prob(BATCH.action).unsqueeze(-1) # [T, B, 1]
entropy = dist.entropy().unsqueeze(-1) # [T, B, 1]
else:
logits = self.actor(BATCH.obs, begin_mask=BATCH.begin_mask) # [T, B, A]
logp_all = logits.log_softmax(-1) # [T, B, A]
new_log_prob = (BATCH.action * logp_all).sum(-1, keepdim=True) # [T, B, 1]
entropy = -(logp_all.exp() * logp_all).sum(-1, keepdim=True) # [T, B, 1]
ratio = (new_log_prob - BATCH.log_prob).exp() # [T, B, 1]
kl = (BATCH.log_prob - new_log_prob).square().mean() # 1
surrogate = ratio * BATCH.gae_adv # [T, B, 1]
clipped_surrogate = th.minimum(
surrogate,
th.where(BATCH.gae_adv > 0, (1 + self._epsilon) *
BATCH.gae_adv, (1 - self._epsilon) * BATCH.gae_adv)
) # [T, B, 1]
if self._use_duel_clip:
clipped_surrogate = th.maximum(
clipped_surrogate,
(1.0 + self._duel_epsilon) * BATCH.gae_adv
) # [T, B, 1]
actor_loss = -(clipped_surrogate + self._ent_coef * entropy).mean() # 1
if self._use_kl_loss:
kl_loss = self._kl_coef * kl # 1
actor_loss += kl_loss
if self._use_extra_loss:
extra_loss = self._extra_coef * th.maximum(th.zeros_like(kl), kl - self._kl_cutoff).square().mean() # 1
actor_loss += extra_loss
self.actor_oplr.optimize(actor_loss)
return {
'LOSS/actor_loss': actor_loss,
'Statistics/kl': kl,
'Statistics/entropy': entropy.mean(),
'LEARNING_RATE/actor_lr': self.actor_oplr.lr
}, kl
@iton
def train_critic(self, BATCH):
value = self.critic(BATCH.obs, begin_mask=BATCH.begin_mask) # [T, B, 1]
td_error = BATCH.discounted_reward - value # [T, B, 1]
if self._use_vclip:
value_clip = BATCH.value + (value - BATCH.value).clamp(-self._value_epsilon,
self._value_epsilon) # [T, B, 1]
td_error_clip = BATCH.discounted_reward - value_clip # [T, B, 1]
td_square = th.maximum(td_error.square(), td_error_clip.square()) # [T, B, 1]
else:
td_square = td_error.square() # [T, B, 1]
critic_loss = 0.5 * td_square.mean() # 1
self.critic_oplr.optimize(critic_loss)
return {
'LOSS/critic_loss': critic_loss,
'LEARNING_RATE/critic_lr': self.critic_oplr.lr
}
| 10,370 |
361 | <reponame>khotyn/sofa-registry
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.sofa.registry.log;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.AppenderBase;
import java.util.ArrayList;
import java.util.List;
/**
* @author xuanbei
* @since 2018/12/29
*/
public class TestAppender extends AppenderBase<LoggingEvent> {
public static List<LoggingEvent> events = new ArrayList<>();
@Override
protected void append(LoggingEvent e) {
events.add(e);
}
public static boolean containsMessage(String message) {
for (LoggingEvent loggingEvent : events) {
if (loggingEvent.getFormattedMessage().contains(message)) {
return true;
}
}
return false;
}
public static boolean containsMessageAndThrowable(String message, Throwable throwable) {
for (LoggingEvent loggingEvent : events) {
if (loggingEvent.getFormattedMessage().contains(message)
&& loggingEvent.getThrowableProxy().getMessage().equals(throwable.getMessage())) {
return true;
}
}
return false;
}
} | 659 |
393 | <filename>OtrosLogViewer-app/src/main/java/pl/otros/logview/exceptionshandler/errrorreport/ExceptionERDC.java
package pl.otros.logview.exceptionshandler.errrorreport;
import com.google.common.base.Throwables;
import java.util.HashMap;
import java.util.Map;
public class ExceptionERDC implements ErrorReportDataCollector {
public static final String EXCEPTION = "EXCEPTION:exception";
public static final String MESSAGE = "EXCEPTION:message";
public static final String THREAD = "EXCEPTION:thread";
public static final String MESSAGE_LOCALIZED = "EXCEPTION:message.localized";
public static final String STACKTRACE = "EXCEPTION:stacktrace";
@Override
public Map<String, String> collect(ErrorReportCollectingContext context) {
HashMap<String, String> r = new HashMap<>();
Throwable throwable = context.getThrowable();
r.put(EXCEPTION, throwable.getClass().getName());
r.put(MESSAGE, throwable.getMessage());
r.put(THREAD, context.getThread().getName());
r.put(MESSAGE_LOCALIZED, throwable.getLocalizedMessage());
r.put(STACKTRACE, Throwables.getStackTraceAsString(throwable));
return r;
}
}
| 414 |
5,169 | {
"name": "GSKStretchyHeaderView",
"version": "0.12.2",
"summary": "A generic, easy to use stretchy header view for UITableView and UICollectionView",
"description": "GSKStretchyHeaderView allows you to add a stretchy header view (like Twitter's or Spotify's) to any existing UITableView and UICollectionView. There is no need inherit from custom view controllers, just create your custom header view and add it to your UITableView or UICollectionView. Creating a custom stretchy header view is as easy as inheriting from the base class or using Interface Builder.",
"homepage": "https://github.com/gskbyte/GSKStretchyHeaderView",
"screenshots": [
"https://raw.githubusercontent.com/gskbyte/GSKStretchyHeaderView/master/screenshots/spoty_default.jpg",
"https://raw.githubusercontent.com/gskbyte/GSKStretchyHeaderView/master/screenshots/gradient.jpg"
],
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/gskbyte/GSKStretchyHeaderView.git",
"tag": "0.12.2"
},
"social_media_url": "https://twitter.com/gskbyte",
"platforms": {
"ios": "7.0"
},
"requires_arc": true,
"source_files": "GSKStretchyHeaderView/Classes/**/*",
"private_header_files": "GSKStretchyHeaderView/Classes/Private/*.h"
}
| 434 |
7,409 | <reponame>FarazPatankar/posthog<filename>posthog/migrations/0114_fix_team_event_names.py
# Generated by Django 3.0.11 on 2021-01-12 19:18
from django.db import migrations
def fix_team_event_names(apps, schema_editor):
Team = apps.get_model("posthog", "Team")
for team in Team.objects.all():
old_event_names = team.event_names
team.event_names = list(event for event in old_event_names if isinstance(event, str))
if len(team.event_names) != len(old_event_names):
from posthog.tasks.calculate_event_property_usage import calculate_event_property_usage_for_team
team.save()
calculate_event_property_usage_for_team(team.pk)
def backwards(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
("posthog", "0113_cohort_is_static"),
]
operations = [
migrations.RunPython(fix_team_event_names, backwards),
]
| 377 |
1,285 | <filename>src/main/java/net/minestom/server/entity/metadata/animal/tameable/ParrotMeta.java
package net.minestom.server.entity.metadata.animal.tameable;
import net.minestom.server.entity.Entity;
import net.minestom.server.entity.Metadata;
import org.jetbrains.annotations.NotNull;
public class ParrotMeta extends TameableAnimalMeta {
public static final byte OFFSET = TameableAnimalMeta.MAX_OFFSET;
public static final byte MAX_OFFSET = OFFSET + 1;
public ParrotMeta(@NotNull Entity entity, @NotNull Metadata metadata) {
super(entity, metadata);
}
@NotNull
public Color getColor() {
return Color.VALUES[super.metadata.getIndex(OFFSET, 0)];
}
public void setColor(@NotNull Color value) {
super.metadata.setIndex(OFFSET, Metadata.VarInt(value.ordinal()));
}
public enum Color {
RED_BLUE,
BLUE,
GREEN,
YELLOW_BLUE,
GREY;
private final static Color[] VALUES = values();
}
}
| 389 |
369 | // Copyright (c) 2017-2022, Mudit<NAME>.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "EditQuotesWindow.hpp"
#include <application-settings/windows/WindowNames.hpp>
#include <OptionSetting.hpp>
namespace gui
{
EditQuotesWindow::EditQuotesWindow(app::ApplicationCommon *app) : BaseSettingsWindow(app, window::name::edit_quotes)
{
setTitle(utils::translate("app_settings_display_wallpaper_edit_quotes"));
}
auto EditQuotesWindow::buildOptionsList() -> std::list<gui::Option>
{
std::list<gui::Option> optionsList;
optionsList.emplace_back(std::make_unique<gui::option::OptionSettings>(
utils::translate("app_settings_display_wallpaper_quotes_categories"),
[=](gui::Item &item) {
application->switchWindow(gui::window::name::quote_categories, nullptr);
return true;
},
[=](gui::Item &item) {
if (item.focus) {
this->setNavBarText(utils::translate(style::strings::common::select), nav_bar::Side::Center);
}
return true;
},
this,
gui::option::SettingRightItem::ArrowWhite));
optionsList.emplace_back(std::make_unique<gui::option::OptionSettings>(
utils::translate("app_settings_display_wallpaper_edit_custom_quotes"),
[=](gui::Item &item) {
application->switchWindow(gui::window::name::quotes, nullptr);
return true;
},
[=](gui::Item &item) {
if (item.focus) {
this->setNavBarText(utils::translate(style::strings::common::select), nav_bar::Side::Center);
}
return true;
},
this,
gui::option::SettingRightItem::ArrowWhite));
return optionsList;
}
} // namespace gui
| 902 |
338 | <filename>ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyMessageController.java
package com.tvd12.ezyfoxserver.controller;
import com.tvd12.ezyfox.util.EzyEntityBuilders;
public class EzyMessageController extends EzyEntityBuilders {
}
| 90 |
423 | {
"culture": "cs-CZ",
"translations": {
"Choose file": "Vyberte soubor",
"Choose files": "Vyberte soubory"
}
}
| 65 |
1,172 | // Copyright (C) 2012 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.caja.parser.html;
import com.google.caja.lexer.ParseException;
import com.google.caja.reporting.MarkupRenderMode;
import com.google.caja.util.CajaTestCase;
import com.google.caja.util.FailureIsAnOption;
import com.google.caja.util.Strings;
import com.google.common.collect.ImmutableSet;
import java.util.Set;
import junit.framework.AssertionFailedError;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* This class tests safety and fidelity of {@link Nodes#render}.
* <p>
* Caja's security depends on faithful interpretation of Caja's output.
* Ideally Caja's XML output will always be interpreted as XML rather than
* HTML (and vice-versa), but this type of misinterpretation is an easy
* mistake to make.
* <p>
* So what we're trying to do here is guarantee that Caja's XML and HTML
* outputs are always "safe", whether they're subsequently interpreted or
* misinterpreted as XML or HTML.
* <p>
* There are a couple types of tests here:
*
* <ul>
* <li>"precise" - Most DOM trees can be rendered in a way that will be
* interpreted the same way by XML and HTML parsers.</li>
*
* <li>"robust" - Some DOM trees cannot be rendered precisely, but we can
* ensure that the only difference between XML and HTML interpretation is
* the values of inert text content. This is basically a guarantee that it's
* impossible for inert text to become misinterpreted as script.</li>
*
* <li>"htmlOnly" - Some DOM trees can be rendered safely as HTML (and
* misinterpretation as XML is harmless), but can't be rendered safely
* as XML</li>
*
* <li>"xmlOnly" - Some DOM trees can be rendered safely as XML (and
* misinterpretation as HTML is harmless), but can't be rendered safely
* as HTML</li>
*
* <li>"unsafe" - Some DOM trees are unsafe to render as HTML or XML.</li>
* </ul>
*
* @author <EMAIL>
*/
@SuppressWarnings("static-method")
public class NodesRenderTest extends CajaTestCase {
public final void testEmpty() {
precise("");
assertRender("", "");
}
public final void testDiv1() {
precise("<div></div><div></div></div>");
assertRender(
"<div></div><div></div></div>",
"<div></div><div></div></div>");
}
// <![CDATA[]]> has meaning in XML but not in HTML. These next few tests
// verify a couple properties:
// - If a dom tree was parsed as XML and has a CDATASection node, the
// node doesn't get rendered with "<![CDATA[...]]>", which would
// screw up HTML interpretation.</li>
// - If a dom tree has a text node containing "<![CDATA[", it doesn't
// get rendered as "<![CDATA[", which would screw up XML interpretation.
public final void testCdata1() {
precise("1<<![CDATA[2<]]><![CDATA[3<]]>4>5");
assertRender(
"1<2&lt;3<4>5",
"1<<![CDATA[2<]]><![CDATA[3<]]>4>5");
assertRender(
"1<<![CDATA[2<]]><![CDATA[3<]]>4>5",
"1<<![CDATA[2<]]><![CDATA[3<]]>4>5");
}
public final void testCdata2() {
precise("<div>1<<![CDATA[2<]><![CDATA[3<]]>4>5</div>");
assertRender(
"<div>1<2&lt;3<4>5</div>",
"<div>1<<![CDATA[2<]]><![CDATA[3<]]>4>5</div>");
assertRender(
"<div>1<<![CDATA[2<]]><![CDATA[3<]]>4>5</div>",
"<div>1<<![CDATA[2<]]><![CDATA[3<]]>4>5</div>");
}
public final void testCdata3() {
// <title> is RCDATA so this should be possible
precise("<title>1<<![CDATA[2<]><![CDATA[3<]]>4>5</title>");
assertRender(
"<title>1<2&lt;3<4>5</title>",
"<title>1<<![CDATA[2<]]><![CDATA[3<]]>4>5</title>");
assertRender(
"<title>1<<![CDATA[2<]]><![CDATA[3<]]>4>5</title>",
"<title>1<<![CDATA[2<]]><![CDATA[3<]]>4>5</title>");
}
/*TODO(felix8a)*/ @FailureIsAnOption
public final void testCdata4() {
// <xmp> is RAWTEXT, no entity decoding, so precise is impossible
robust("<xmp>1<<![CDATA[2<]><![CDATA[3<]]>4>5</xmp>");
}
public final void testXmp1() {
// xmp can never contain "</xmp>", and there's no way to escape it.
xmlOnly(xml("<xmp>1</xmp>2</xmp>"));
}
public final void testXmp2() {
// non-ascii characters are not renderable safely in xmp
xmlOnly(xml("<xmp>\u0000\u0080\u0131</xmp>"));
assertRenderXml(
"<xmp>�€ı</xmp>",
"<xmp>\u0000\u0080\u0131</xmp>");
}
/*TODO(felix8a)*/ @FailureIsAnOption
public final void testXmp3() {
robust(html("<xmp> a<b </xmp>"));
}
public final void testScript1() {
precise("<script> a </script>");
assertRender(
"<script> a </script>",
"<script> a </script>");
}
/*TODO(felix8a)*/ @FailureIsAnOption
public final void testScript2() {
precise(html(
"<script>//!<[CDATA[\n"
+ "a<b;\n"
+ "//]]></script>"));
}
/*TODO(felix8a)*/ @FailureIsAnOption
public final void testScript3() {
htmlOnly(html(
"<script> a<b; </script>"));
}
/*TODO(felix8a)*/ @FailureIsAnOption
public final void testScript4() {
unsafe(xml("<script> '</script>' </script>"));
}
// --------
@SuppressWarnings("unused")
private void assertRenderHtml(String expected, String test) {
assertEquals(expected, renderHtml(xml(test)));
}
private void assertRenderXml(String expected, String test) {
assertEquals(expected, renderXml(xml(test)));
}
private void assertRender(String expected, String test) {
Node tree = xml(test);
assertEquals(expected, renderHtml(tree));
assertEquals(expected, renderXml(tree));
}
/**
* Check that an output string has the same meaning, whether it's parsed
* as HTML or as XML.
*/
private void preciseOutput(String output) {
// TODO(felix8a): parser warnings here should be fatal?
Node asHtml = html(output);
Node asXml = xml(output);
assertIdenticalRender(asHtml, asXml);
assertIdenticalStructure(asHtml, asXml);
}
/**
* Check that our rendering of a DOM tree has the same meaning, whether
* the rendering is parsed as HTML or as XML.
*/
private void precise(Node tree) {
preciseOutput(Nodes.render(tree));
preciseOutput(Nodes.render(tree, MarkupRenderMode.HTML));
preciseOutput(Nodes.render(tree, MarkupRenderMode.XML));
// We're only making this guarantee for the common render options.
}
private void precise(String input) {
// Note, parser warnings here are unimportant. TODO(felix8a): really?
precise(html(input));
precise(xml(input));
}
// --------
/**
* Check that our rendering of a DOM tree has the same structure, whether
* the rendering is parsed as HTML or as XML.
* <p>
* Differences in text content are ignored, but differences in attributes
* and attribute values are significant.
* <p>
* Basically, we want to make sure that when an HTML output string is
* interpreted as XML or vice versa, that the misinterpretation does not
* turn inactive text into active script.
*/
private void robust(Node tree) {
String asHtml = renderHtml(tree);
assertIdenticalStructure(tree, html(asHtml));
assertIdenticalStructure(tree, xml(asHtml));
String asXml = renderXml(tree);
assertIdenticalStructure(tree, html(asXml));
assertIdenticalStructure(tree, xml(asXml));
}
private void robust(String source) {
robust(html(source));
robust(xml(source));
}
// --------
/**
* Check that when we refuse to render a DOM tree as XML, we can
* render it as HTML, and the HTML rendering is safe when misinterpreted
* as XML.
*/
private void htmlOnly(Node tree) {
try {
String result = renderXml(tree);
throw new AssertionFailedError(
"Unexpected renderXmlsuccess: " + result);
} catch (UncheckedUnrenderableException e) {}
String result = renderHtml(tree);
assertIdenticalStructure(html(result), xml(result));
}
/**
* Check that when we refuse to render a DOM tree as HTML, we can
* render it as XML, and the XML rendering is safe when misinterpreted
* as HTML.
*/
private void xmlOnly(Node tree) {
try {
String result = renderHtml(tree);
throw new AssertionFailedError(
"Unexpected renderHtml success: " + result);
} catch (UncheckedUnrenderableException e) {}
String result = renderXml(tree);
assertIdenticalStructure(html(result), xml(result));
}
/**
* Check that when we refuse to render a DOM tree as HTML or as XML
*/
private void unsafe(Node tree) {
try {
String result = renderHtml(tree);
throw new AssertionFailedError(
"Unexpected renderHtml success: " + result);
} catch (UncheckedUnrenderableException e) {}
try {
String result = renderXml(tree);
throw new AssertionFailedError(
"Unexpected renderXmlsuccess: " + result);
} catch (UncheckedUnrenderableException e) {}
}
// --------
private void assertIdenticalRender(Node n1, Node n2) {
String s1 = renderXml(n1);
String s2 = renderXml(n2);
assertEquals(s1, s2);
}
private void assertIdenticalStructure(Node n1, Node n2) {
assertEquals(n1.getNodeType(), n2.getNodeType());
switch (n1.getNodeType()) {
case Node.ELEMENT_NODE:
assertIdenticalStructure((Element) n1, (Element) n2);
break;
case Node.DOCUMENT_FRAGMENT_NODE:
assertIdenticalStructure(n1.getChildNodes(), n2.getChildNodes());
break;
default:
throw new IllegalStateException("Unexpected node type");
}
}
// These are HTML tags whose contents have security implications.
private static final Set<String> RISKY_ELEMENTS = ImmutableSet.of(
"noembed", "noframes", "noscript", "script", "style");
private void assertIdenticalStructure(Element e1, Element e2) {
assertEquals(e1.getTagName(), e2.getTagName());
// For RISKY_ELEMENTS, text equivalence is important.
String tagName = Strings.lower(e1.getTagName());
if (RISKY_ELEMENTS.contains(tagName)) {
assertIdenticalRender(e1, e2);
return;
}
// Check that attributes are identical
NamedNodeMap a1 = e1.getAttributes();
NamedNodeMap a2 = e2.getAttributes();
assertEquals(a1.getLength(), a2.getLength());
for (int i = 0; i < a1.getLength(); i++) {
Node attr = a1.item(i);
assertEquals(attr.getNodeValue(), a2.getNamedItem(attr.getNodeName()));
}
// Check that children are identical, ignoring unimportant text.
assertIdenticalStructure(e1.getChildNodes(), e2.getChildNodes());
}
private void assertIdenticalStructure(NodeList nl1, NodeList nl2) {
int p1 = nextElement(nl1, 0);
int p2 = nextElement(nl2, 0);
while (p1 < nl1.getLength() && p2 < nl2.getLength()) {
assertIdenticalStructure((Element) nl1.item(p1), (Element) nl2.item(p2));
p1 = nextElement(nl1, p1 + 1);
p2 = nextElement(nl2, p2 + 1);
}
assertTrue(nl1.getLength() <= nextElement(nl1, p1));
assertTrue(nl2.getLength() <= nextElement(nl2, p2));
}
// Return the next element node at or after pos
private int nextElement(NodeList nl, int pos) {
while (pos < nl.getLength()) {
switch (nl.item(pos).getNodeType()) {
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
pos++;
break;
case Node.ELEMENT_NODE:
return pos;
default:
throw new IllegalStateException("Unexpected node type");
}
}
return nl.getLength();
}
private DocumentFragment html(String source) {
try {
return htmlFragment(fromString(source));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
private DocumentFragment xml(String source) {
try {
return xmlFragment(fromString(source));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
private String renderXml(Node node) {
return Nodes.render(node, MarkupRenderMode.XML);
}
private String renderHtml(Node node) {
return Nodes.render(node, MarkupRenderMode.HTML);
}
}
| 4,959 |
445 | /////////////////////////////////////////////////////////////////////////
// $Id: soundwin.cc,v 1.22 2008/08/24 17:28:42 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.com/
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
/////////////////////////////////////////////////////////////////////////
// This file (SOUNDWIN.CC) written and donated by <NAME>
// Define BX_PLUGGABLE in files that can be compiled into plugins. For
// platforms that require a special tag on exported symbols, BX_PLUGGABLE
// is used to know when we are exporting symbols and when we are importing.
#define BX_PLUGGABLE
#define NO_DEVICE_INCLUDES
#include "iodev.h"
#define BX_SOUNDLOW
#include "sb16.h"
#if defined(WIN32) && BX_SUPPORT_SB16
#include "soundwin.h"
#define LOG_THIS sb16->
bx_sound_windows_c::bx_sound_windows_c(bx_sb16_c *sb16)
:bx_sound_output_c(sb16)
{
this->sb16 = sb16;
MidiOpen = 0;
WaveOpen = 0;
ismidiready = 1;
iswaveready = 1;
// size is the total size of the midi header and buffer and the
// BX_SOUND_WINDOWS_NBUF wave header and buffers, all aligned
// on a 16-byte boundary
#define ALIGN(size) ((size + 15) & ~15)
#define size ALIGN(sizeof(MIDIHDR)) \
+ ALIGN(sizeof(WAVEHDR)) \
+ ALIGN(BX_SOUND_WINDOWS_MAXSYSEXLEN) * BX_SOUND_WINDOWS_NBUF \
+ ALIGN(BX_SOUND_OUTPUT_WAVEPACKETSIZE) * BX_SOUND_WINDOWS_NBUF
DataHandle = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, size);
DataPointer = (Bit8u*) GlobalLock(DataHandle);
if (DataPointer == NULL)
BX_PANIC(("GlobalLock returned NULL-pointer"));
#define NEWBUFFER(size) &(DataPointer[offset]); offset += ALIGN(size)
unsigned offset = 0;
MidiHeader = (LPMIDIHDR) NEWBUFFER(sizeof(MIDIHDR));
MidiData = (LPSTR) NEWBUFFER(BX_SOUND_WINDOWS_MAXSYSEXLEN);
for (int bufnum=0; bufnum<BX_SOUND_WINDOWS_NBUF; bufnum++)
{
WaveHeader[bufnum] = (LPWAVEHDR) NEWBUFFER(sizeof(WAVEHDR));
WaveData[bufnum] = (LPSTR) NEWBUFFER(BX_SOUND_OUTPUT_WAVEPACKETSIZE+64);
}
if (offset > size)
BX_PANIC(("Allocated memory was too small!"));
#undef size
#undef ALIGN
#undef NEWBUFFER
}
bx_sound_windows_c::~bx_sound_windows_c()
{
GlobalUnlock(DataHandle);
GlobalFree(DataHandle);
}
int bx_sound_windows_c::waveready()
{
if (iswaveready == 0)
checkwaveready();
if (iswaveready == 1)
return BX_SOUND_OUTPUT_OK;
else
return BX_SOUND_OUTPUT_ERR;
}
int bx_sound_windows_c::midiready()
{
if (ismidiready == 0)
checkmidiready();
if (ismidiready == 1)
return BX_SOUND_OUTPUT_OK;
else
return BX_SOUND_OUTPUT_ERR;
}
int bx_sound_windows_c::openmidioutput(char *device)
{
// could make the output device selectable,
// but currently only the midi mapper is supported
UNUSED(device);
UINT deviceid = (UINT) MIDIMAPPER;
MidiOpen = 0;
UINT ret = midiOutOpen(&MidiOut, deviceid, 0, 0, CALLBACK_NULL);
if (ret == 0)
MidiOpen = 1;
WRITELOG(MIDILOG(4), "midiOutOpen() = %d, MidiOpen: %d", ret, MidiOpen);
return (MidiOpen == 1) ? BX_SOUND_OUTPUT_OK : BX_SOUND_OUTPUT_ERR;
}
int bx_sound_windows_c::sendmidicommand(int delta, int command, int length, Bit8u data[])
{
UINT ret;
if (MidiOpen != 1)
return BX_SOUND_OUTPUT_ERR;
if ((command == 0xf0) || (command == 0xf7) || (length > 3))
{
WRITELOG(WAVELOG(5), "SYSEX started, length %d", length);
ismidiready = 0; // until the buffer is done
memcpy(MidiData, data, length);
MidiHeader->lpData = MidiData;
MidiHeader->dwBufferLength = BX_SOUND_WINDOWS_MAXSYSEXLEN;
MidiHeader->dwBytesRecorded = 0;
MidiHeader->dwUser = 0;
MidiHeader->dwFlags = 0;
ret = midiOutPrepareHeader(MidiOut, MidiHeader, sizeof(*MidiHeader));
if (ret != 0)
WRITELOG(MIDILOG(2), "midiOutPrepareHeader() = %d", ret);
ret = midiOutLongMsg(MidiOut, MidiHeader, sizeof(*MidiHeader));
if (ret != 0)
WRITELOG(MIDILOG(2), "midiOutLongMsg() = %d", ret);
}
else
{
DWORD msg = command;
for (int i = 0; i<length; i++)
msg |= (data[i] << (8 * (i + 1)));
ret = midiOutShortMsg(MidiOut, msg);
WRITELOG(MIDILOG(4), "midiOutShortMsg(%x) = %d", msg, ret);
}
return (ret == 0) ? BX_SOUND_OUTPUT_OK : BX_SOUND_OUTPUT_ERR;
}
int bx_sound_windows_c::closemidioutput()
{
UINT ret;
if (MidiOpen != 1)
return BX_SOUND_OUTPUT_ERR;
ret = midiOutReset(MidiOut);
if (ismidiready == 0)
checkmidiready(); // to clear any pending SYSEX
ret = midiOutClose(MidiOut);
WRITELOG(MIDILOG(4), "midiOutClose() = %d", ret);
MidiOpen = 0;
return (ret == 0) ? BX_SOUND_OUTPUT_OK : BX_SOUND_OUTPUT_ERR;
}
int bx_sound_windows_c::openwaveoutput(char *device)
{
// could make the output device selectable,
// but currently only the midi mapper is supported
UNUSED(device);
WRITELOG(WAVELOG(4), "openwaveoutput(%s)", device);
#ifdef usewaveOut
WaveDevice = (UINT) WAVEMAPPER;
for (int i=0; i<BX_SOUND_WINDOWS_NBUF; i++)
WaveHeader[i]->dwFlags = WHDR_DONE;
head = 0;
tailfull = 0;
tailplay = 0;
needreopen = 0;
#endif
return BX_SOUND_OUTPUT_OK;
}
int bx_sound_windows_c::playnextbuffer()
{
UINT ret;
PCMWAVEFORMAT waveformat;
int bufnum;
// if the format is different, we have to reopen the device,
// so reset it first
if (needreopen != 0)
if (WaveOpen != 0)
ret = waveOutReset(WaveOut);
// clean up the buffers and mark if output is ready
checkwaveready();
// do we have to play anything?
if (tailplay == head)
return BX_SOUND_OUTPUT_OK;
// if the format is different, we have to close and reopen the device
// or, just open the device if it's not open yet
if ((needreopen != 0) || (WaveOpen == 0))
{
if (WaveOpen != 0)
{
ret = waveOutClose(WaveOut);
WaveOpen = 0;
}
// try three times to find a suitable format
for (int tries = 0; tries < 3; tries++)
{
int frequency = WaveInfo.frequency;
int stereo = WaveInfo.stereo;
int bits = WaveInfo.bits;
// int format = WaveInfo.format;
int bps = (bits / 8) * (stereo + 1);
waveformat.wf.wFormatTag = WAVE_FORMAT_PCM;
waveformat.wf.nChannels = stereo + 1;
waveformat.wf.nSamplesPerSec = frequency;
waveformat.wf.nAvgBytesPerSec = frequency * bps;
waveformat.wf.nBlockAlign = bps;
waveformat.wBitsPerSample = bits;
ret = waveOutOpen(&(WaveOut), WaveDevice, (LPWAVEFORMATEX)&(waveformat.wf), 0, 0, CALLBACK_NULL);
if (ret != 0)
{
char errormsg[4*MAXERRORLENGTH+1];
waveOutGetErrorTextA(ret, errormsg, 4*MAXERRORLENGTH+1);
WRITELOG(WAVELOG(5), "waveOutOpen: %s", errormsg);
switch (tries) {
case 0: // maybe try a different frequency
if (frequency < 15600)
frequency = 11025;
else if (frequency < 31200)
frequency = 22050;
else
frequency = 44100;
WRITELOG(WAVELOG(4), "Couldn't open wave device (error %d), trying frequency %d", ret, frequency);
break;
case 1: // or something else
frequency = 11025;
stereo = 0;
bits = 8;
bps = 1;
WRITELOG(WAVELOG(4), "Couldn't open wave device again (error %d), trying 11KHz, mono, 8bit", ret);
break;
case 2: // nope, doesn't work
WRITELOG(WAVELOG(2), "Couldn't open wave device (error %d)!", ret);
return BX_SOUND_OUTPUT_ERR;
}
WRITELOG(WAVELOG(5), "The format was: wFormatTag=%d, nChannels=%d, nSamplesPerSec=%d,",
waveformat.wf.wFormatTag, waveformat.wf.nChannels, waveformat.wf.nSamplesPerSec);
WRITELOG(WAVELOG(5), " nAvgBytesPerSec=%d, nBlockAlign=%d, wBitsPerSample=%d",
waveformat.wf.nAvgBytesPerSec, waveformat.wf.nBlockAlign, waveformat.wBitsPerSample);
}
else
{
WaveOpen = 1;
needreopen = 0;
break;
}
}
}
for (bufnum=tailplay; bufnum != head;
bufnum++, bufnum &= BX_SOUND_WINDOWS_NMASK, tailplay=bufnum)
{
WRITELOG(WAVELOG(5), "Playing buffer %d", bufnum);
// prepare the wave header
WaveHeader[bufnum]->lpData = WaveData[bufnum];
WaveHeader[bufnum]->dwBufferLength = length[bufnum];
WaveHeader[bufnum]->dwBytesRecorded = length[bufnum];
WaveHeader[bufnum]->dwUser = 0;
WaveHeader[bufnum]->dwFlags = 0;
WaveHeader[bufnum]->dwLoops = 1;
ret = waveOutPrepareHeader(WaveOut, WaveHeader[bufnum], sizeof(*WaveHeader[bufnum]));
if (ret != 0)
{
WRITELOG(WAVELOG(2), "waveOutPrepareHeader = %d", ret);
return BX_SOUND_OUTPUT_ERR;
}
ret = waveOutWrite(WaveOut, WaveHeader[bufnum], sizeof(*WaveHeader[bufnum]));
if (ret != 0)
{
char errormsg[4*MAXERRORLENGTH+1];
waveOutGetErrorTextA(ret, errormsg, 4*MAXERRORLENGTH+1);
WRITELOG(WAVELOG(5), "waveOutWrite: %s", errormsg);
}
}
return BX_SOUND_OUTPUT_OK;
}
int bx_sound_windows_c::startwaveplayback(int frequency, int bits, int stereo, int format)
{
WRITELOG(WAVELOG(4), "startwaveplayback(%d, %d, %d, %x)", frequency, bits, stereo, format);
#ifdef usewaveOut
// check if any of the properties have changed
if ((WaveInfo.frequency != frequency) ||
(WaveInfo.bits != bits) ||
(WaveInfo.stereo != stereo) ||
(WaveInfo.format != format))
{
needreopen = 1;
// store the current settings to be used by sendwavepacket()
WaveInfo.frequency = frequency;
WaveInfo.bits = bits;
WaveInfo.stereo = stereo;
WaveInfo.format = format;
}
#endif
#ifdef usesndPlaySnd
int bps = (bits / 8) * (stereo + 1);
LPWAVEFILEHEADER header = (LPWAVEFILEHEADER) WaveData[0];
memcpy(header->RIFF, "RIFF", 4);
memcpy(header->TYPE, "WAVE", 4);
memcpy(header->chnk, "fmt ", 4);
header->chnklen = 16;
header->waveformat.wf.wFormatTag = WAVE_FORMAT_PCM;
header->waveformat.wf.nChannels = stereo + 1;
header->waveformat.wf.nSamplesPerSec = frequency;
header->waveformat.wf.nAvgBytesPerSec = frequency * bps;
header->waveformat.wf.nBlockAlign = bps;
header->waveformat.wBitsPerSample = bits;
memcpy(header->chnk2, "data", 4);
#endif
return BX_SOUND_OUTPUT_OK;
}
int bx_sound_windows_c::sendwavepacket(int length, Bit8u data[])
{
#ifdef usewaveOut
int bufnum;
#endif
#ifdef usesndPlaySnd
UINT ret;
#endif
WRITELOG(WAVELOG(4), "sendwavepacket(%d, %p)", length, data);
#ifdef usewaveOut
bufnum = head;
memcpy(WaveData[bufnum], data, length);
this->length[bufnum] = length;
// select next buffer to write to
bufnum++;
bufnum &= BX_SOUND_WINDOWS_NMASK;
if (((bufnum + 1) & BX_SOUND_WINDOWS_NMASK) == tailfull)
{ // this should not actually happen!
WRITELOG(WAVELOG(2), "Output buffer overflow! Not played. Iswaveready was %d", iswaveready);
iswaveready = 0; // stop the output for a while
return BX_SOUND_OUTPUT_ERR;
}
head = bufnum;
// check if more buffers are available, otherwise stall the emulator
if (((bufnum + 2) & BX_SOUND_WINDOWS_NMASK) == tailfull)
{
WRITELOG(WAVELOG(5), "Buffer status: Head %d, TailFull %d, TailPlay %d. Stall.",
head, tailfull, tailplay);
iswaveready = 0;
}
playnextbuffer();
#endif
#ifdef usesndPlaySnd
LPWAVEFILEHEADER header = (LPWAVEFILEHEADER) WaveData[0];
header->length = length + 36;
header->chnk2len = length;
memcpy(&(header->data), data, length);
ret = sndPlaySoundA((LPCSTR) header, SND_SYNC | SND_MEMORY);
if (ret != 0)
{
WRITELOG(WAVELOG(3), "sndPlaySoundA: %d", ret);
}
#endif
return BX_SOUND_OUTPUT_OK;
}
int bx_sound_windows_c::stopwaveplayback()
{
WRITELOG(WAVELOG(4), "stopwaveplayback()");
#ifdef usewaveOut
// this is handled by checkwaveready() when closing
#endif
#ifdef usesndPlaySnd
sndPlaySoundA(NULL, SND_ASYNC | SND_MEMORY);
WaveOpen = 0;
#endif
return BX_SOUND_OUTPUT_OK;
}
int bx_sound_windows_c::closewaveoutput()
{
WRITELOG(WAVELOG(4), "closewaveoutput");
#ifdef usewaveOut
if (WaveOpen == 1)
{
waveOutReset(WaveOut);
// let checkwaveready() clean up the buffers
checkwaveready();
waveOutClose(WaveOut);
head = 0;
tailfull = 0;
tailplay = 0;
needreopen = 0;
}
#endif
return BX_SOUND_OUTPUT_OK;
}
void bx_sound_windows_c::checkmidiready()
{
UINT ret;
if ((MidiHeader->dwFlags & WHDR_DONE) != 0)
{
WRITELOG(MIDILOG(5), "SYSEX message done, midi ready again.");
ret = midiOutUnprepareHeader(MidiOut, MidiHeader, sizeof(*MidiHeader));
ismidiready = 1;
}
}
void bx_sound_windows_c::checkwaveready()
{
int bufnum;
UINT ret;
// clean up all finished buffers and mark them as available
for (bufnum=tailfull; (bufnum != tailplay) &&
((WaveHeader[bufnum]->dwFlags & WHDR_DONE) != 0);
bufnum++, bufnum &= BX_SOUND_WINDOWS_NMASK)
{
WRITELOG(WAVELOG(5), "Buffer %d done.", bufnum);
ret = waveOutUnprepareHeader(WaveOut, WaveHeader[bufnum], sizeof(*WaveHeader[bufnum]));
}
tailfull = bufnum;
// enable gathering data if a buffer is available
if (((head + 2) & BX_SOUND_WINDOWS_NMASK) != tailfull)
{
WRITELOG(WAVELOG(5), "Buffer status: Head %d, TailFull %d, TailPlay %d. Ready.",
head, tailfull, tailplay);
iswaveready = 1;
}
}
#endif // defined(WIN32)
| 6,007 |
419 | #include "WorldSystem_AIManager.h"
#include "Game/Core/AI/Components/Component_AISpawn.h"
#include "Game/Core/AI/Components/Component_AI.h"
#include "Engine/Core/Entity/Entity.h"
#include "Engine/Core/Entity/EntityWorldUpdateContext.h"
#include "Engine/Core/Entity/EntityMap.h"
#include "System/TypeSystem/TypeRegistry.h"
#include "System/Core/Threading/TaskSystem.h"
//-------------------------------------------------------------------------
namespace KRG::AI
{
void AIManager::ShutdownSystem()
{
KRG_ASSERT( m_spawnPoints.empty() );
}
void AIManager::RegisterComponent( Entity const* pEntity, EntityComponent* pComponent )
{
if ( auto pSpawnComponent = TryCast<AISpawnComponent>( pComponent ) )
{
m_spawnPoints.emplace_back( pSpawnComponent );
}
if ( auto pAIComponent = TryCast<AIComponent>( pComponent ) )
{
m_AIs.emplace_back( pAIComponent );
}
}
void AIManager::UnregisterComponent( Entity const* pEntity, EntityComponent* pComponent )
{
if ( auto pSpawnComponent = TryCast<AISpawnComponent>( pComponent ) )
{
m_spawnPoints.erase_first_unsorted( pSpawnComponent );
}
if ( auto pAIComponent = TryCast<AIComponent>( pComponent ) )
{
m_AIs.erase_first( pAIComponent );
}
}
//-------------------------------------------------------------------------
void AIManager::UpdateSystem( EntityWorldUpdateContext const& ctx )
{
if ( ctx.IsGameWorld() && !m_hasSpawnedAI )
{
m_hasSpawnedAI = TrySpawnAI( ctx );
}
}
bool AIManager::TrySpawnAI( EntityWorldUpdateContext const& ctx )
{
if ( m_spawnPoints.empty() )
{
return false;
}
auto pTypeRegistry = ctx.GetSystem<TypeSystem::TypeRegistry>();
auto pTaskSystem = ctx.GetSystem<TaskSystem>();
auto pPersistentMap = ctx.GetPersistentMap();
//-------------------------------------------------------------------------
for ( auto pSpawnPoint : m_spawnPoints )
{
pPersistentMap->AddEntityCollection( pTaskSystem, *pTypeRegistry, *pSpawnPoint->GetEntityCollectionDesc(), pSpawnPoint->GetWorldTransform() );
}
return true;
}
} | 938 |
1,217 | <reponame>473867143/Prometheus<filename>Modules/common/include/message_utils.h
/***************************************************************************************************************************
* message_utils.h
*
* Author: Jario
*
* Update Time: 2020.4.29
***************************************************************************************************************************/
#ifndef PROMETHEUS_MESSAGE_UTILS_H
#define PROMETHEUS_MESSAGE_UTILS_H
#include <string>
#include <prometheus_msgs/Message.h>
using namespace std;
// 消息发布函数
inline void pub_message(ros::Publisher& puber, int msg_type, std::string source_node, std::string msg_content)
{
prometheus_msgs::Message exect_msg;
exect_msg.header.stamp = ros::Time::now();
exect_msg.message_type = msg_type;
exect_msg.source_node = source_node;
exect_msg.content = msg_content;
puber.publish(exect_msg);
}
// 消息打印函数
inline void printf_message(const prometheus_msgs::Message& message)
{
//cout <<">>>>>>>>>>>>>>>>>>>>>>>> Message <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" <<endl;
if(message.message_type == prometheus_msgs::Message::NORMAL)
{
cout << "[NORMAL]" << "["<< message.source_node << "]:" << message.content <<endl;
}else if(message.message_type == prometheus_msgs::Message::WARN)
{
cout << "[WARN]" << "["<< message.source_node << "]:" <<message.content <<endl;
}else if(message.message_type == prometheus_msgs::Message::ERROR)
{
cout << "[ERROR]" << "["<< message.source_node << "]:" << message.content <<endl;
}
}
#endif
| 565 |
429 | /*
* Copyright (c) 2009-2017, <NAME>. All Rights Reserved.
*
* This file is part of Efficient Java Matrix Library (EJML).
*
* 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.ejml.sparse.triplet;
import org.ejml.data.DMatrixSparseTriplet;
import java.util.Random;
/**
* @author <NAME>
*/
public class RandomMatrices_DSTL {
/**
* Randomly generates matrix with the specified number of matrix elements filled with values from min to max.
*
* @param numRows Number of rows
* @param numCols Number of columns
* @param nz_total Total number of non-zero elements in the matrix
* @param min Minimum value
* @param max maximum value
* @param rand Random number generated
* @return Randomly generated matrix
*/
public static DMatrixSparseTriplet uniform(int numRows , int numCols , int nz_total ,
double min , double max , Random rand ) {
// Create a list of all the possible element values
int N = numCols*numRows;
if( N < 0 )
throw new IllegalArgumentException("matrix size is too large");
nz_total = Math.min(N,nz_total);
int selected[] = new int[N];
for (int i = 0; i < N; i++) {
selected[i] = i;
}
for (int i = 0; i < nz_total; i++) {
int s = rand.nextInt(N);
int tmp = selected[s];
selected[s] = selected[i];
selected[i] = tmp;
}
// Create a sparse matrix
DMatrixSparseTriplet ret = new DMatrixSparseTriplet(numRows,numCols,nz_total);
for (int i = 0; i < nz_total; i++) {
int row = selected[i]/numCols;
int col = selected[i]%numCols;
double value = rand.nextDouble()*(max-min)+min;
ret.addItem(row,col, value);
}
return ret;
}
}
| 955 |
1,515 | <reponame>zyl409214686/Qigsaw<filename>qigsaw-android/playcorelibrary/src/main/java/com/google/android/play/core/remote/UnbindServiceTask.java<gh_stars>1000+
package com.google.android.play.core.remote;
final class UnbindServiceTask extends RemoteTask {
private final RemoteManager mRemoteManager;
UnbindServiceTask(RemoteManager remoteManager) {
this.mRemoteManager = remoteManager;
}
@Override
protected void execute() {
if (this.mRemoteManager.mIInterface != null) {
this.mRemoteManager.mContext.unbindService(this.mRemoteManager.mServiceConnection);
this.mRemoteManager.mBindingService = false;
this.mRemoteManager.mIInterface = null;
this.mRemoteManager.mServiceConnection = null;
}
}
}
| 295 |
4,020 | package me.coley.recaf.ui.controls.text.selection;
import java.util.Map;
/**
* Wrapper for selected switch instruction.
*
* @author Matt
*/
public class SwitchSelection {
public final Map<String, String> mappings;
public final String dflt;
/**
* @param mappings
* Map of destinations and their key values.
* @param dflt
* Default destination.
*/
public SwitchSelection(Map<String, String> mappings, String dflt) {
this.mappings = mappings;
this.dflt = dflt;
}
} | 167 |
777 | <reponame>google-ar/chromium<filename>chrome/android/junit/src/org/chromium/chrome/browser/ChromeBackupAgentTest.java
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import android.app.backup.BackupDataInput;
import android.app.backup.BackupDataOutput;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.ParcelFileDescriptor;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.chromium.base.BaseChromiumApplication;
import org.chromium.base.ContextUtils;
import org.chromium.base.library_loader.ProcessInitException;
import org.chromium.chrome.browser.firstrun.FirstRunSignInProcessor;
import org.chromium.chrome.browser.firstrun.FirstRunStatus;
import org.chromium.components.signin.ChromeSigninController;
import org.chromium.testing.local.LocalRobolectricTestRunner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Unit tests for {@link org.chromium.chrome.browser.ChromeBackupAgent}.
*/
@RunWith(LocalRobolectricTestRunner.class)
@Config(manifest = Config.NONE, application = BaseChromiumApplication.class)
public class ChromeBackupAgentTest {
private Context mContext;
private ChromeBackupAgent mAgent;
private void setUpTestPrefs(SharedPreferences prefs) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(FirstRunStatus.FIRST_RUN_FLOW_COMPLETE, true);
editor.putBoolean(FirstRunSignInProcessor.FIRST_RUN_FLOW_SIGNIN_SETUP, false);
editor.putString(ChromeSigninController.SIGNED_IN_ACCOUNT_KEY, "user1");
editor.apply();
}
@Before
public void setUp() throws ProcessInitException {
// Set up the context.
mContext = RuntimeEnvironment.application.getApplicationContext();
ContextUtils.initApplicationContextForTests(mContext);
// Override the native calls.
mAgent = spy(new ChromeBackupAgent());
doReturn(new String[] {"pref1"}).when(mAgent).nativeGetBoolBackupNames();
doReturn(new boolean[] {true}).when(mAgent).nativeGetBoolBackupValues();
doNothing().when(mAgent).nativeSetBoolBackupPrefs(
any(String[].class), any(boolean[].class));
// Mock initializing the browser
doReturn(true).when(mAgent).initializeBrowser(any(Context.class));
}
/**
* Test method for {@link ChromeBackupAgent#onBackup} testing first backup
*
* @throws ProcessInitException
*/
@Test
@SuppressWarnings("unchecked")
public void testOnBackup_firstBackup() throws FileNotFoundException, IOException,
ClassNotFoundException, ProcessInitException {
// Mock the backup data.
BackupDataOutput backupData = mock(BackupDataOutput.class);
// Create a state file.
File stateFile1 = File.createTempFile("Test", "");
ParcelFileDescriptor newState =
ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.parseMode("w"));
// Set up some preferences to back up.
SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
setUpTestPrefs(prefs);
// Run the test function.
mAgent.onBackup(null, backupData, newState);
// Check that the right things were written to the backup
verify(backupData).writeEntityHeader("native.pref1", 1);
verify(backupData)
.writeEntityHeader("AndroidDefault." + FirstRunStatus.FIRST_RUN_FLOW_COMPLETE, 1);
verify(backupData, times(2)).writeEntityData(new byte[] {1}, 1);
verify(backupData)
.writeEntityHeader(
"AndroidDefault." + FirstRunSignInProcessor.FIRST_RUN_FLOW_SIGNIN_SETUP, 1);
verify(backupData).writeEntityData(new byte[] {0}, 1);
byte[] unameBytes = "user1".getBytes();
verify(backupData)
.writeEntityHeader("AndroidDefault." + ChromeSigninController.SIGNED_IN_ACCOUNT_KEY,
unameBytes.length);
verify(backupData).writeEntityData(unameBytes, unameBytes.length);
newState.close();
// Check that the state was saved correctly
ObjectInputStream newStateStream = new ObjectInputStream(new FileInputStream(stateFile1));
ArrayList<String> names = (ArrayList<String>) newStateStream.readObject();
assertThat(names.size(), equalTo(4));
assertThat(names, hasItem("native.pref1"));
assertThat(names, hasItem("AndroidDefault." + FirstRunStatus.FIRST_RUN_FLOW_COMPLETE));
assertThat(names,
hasItem("AndroidDefault." + FirstRunSignInProcessor.FIRST_RUN_FLOW_SIGNIN_SETUP));
assertThat(
names, hasItem("AndroidDefault." + ChromeSigninController.SIGNED_IN_ACCOUNT_KEY));
ArrayList<byte[]> values = (ArrayList<byte[]>) newStateStream.readObject();
assertThat(values.size(), equalTo(4));
assertThat(values, hasItem(unameBytes));
assertThat(values, hasItem(new byte[] {0}));
assertThat(values, hasItem(new byte[] {1}));
// Make sure that there are no extra objects.
assertThat(newStateStream.available(), equalTo(0));
// Tidy up.
newStateStream.close();
stateFile1.delete();
}
/**
* Test method for {@link ChromeBackupAgent#onBackup} a second backup with the same data
*/
@Test
@SuppressWarnings("unchecked")
public void testOnBackup_duplicateBackup()
throws FileNotFoundException, IOException, ClassNotFoundException {
// Mock the backup data.
BackupDataOutput backupData = mock(BackupDataOutput.class);
// Create a state file.
File stateFile1 = File.createTempFile("Test", "");
ParcelFileDescriptor newState =
ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.parseMode("w"));
// Set up some preferences to back up.
SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
setUpTestPrefs(prefs);
// Do a first backup.
mAgent.onBackup(null, backupData, newState);
// Minimal check on first backup, this isn't the test here.
verify(backupData, times(4)).writeEntityHeader(anyString(), anyInt());
verify(backupData, times(4)).writeEntityData(any(byte[].class), anyInt());
newState.close();
ParcelFileDescriptor oldState =
ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.parseMode("r"));
File stateFile2 = File.createTempFile("Test", "");
newState = ParcelFileDescriptor.open(stateFile2, ParcelFileDescriptor.parseMode("w"));
// Try a second backup without changing any data
mAgent.onBackup(oldState, backupData, newState);
// Check that the second backup didn't write anything.
verifyNoMoreInteractions(backupData);
oldState.close();
newState.close();
// The two state files should contain identical data.
ObjectInputStream oldStateStream = new ObjectInputStream(new FileInputStream(stateFile1));
ArrayList<String> oldNames = (ArrayList<String>) oldStateStream.readObject();
ArrayList<byte[]> oldValues = (ArrayList<byte[]>) oldStateStream.readObject();
ObjectInputStream newStateStream = new ObjectInputStream(new FileInputStream(stateFile2));
ArrayList<String> newNames = (ArrayList<String>) newStateStream.readObject();
ArrayList<byte[]> newValues = (ArrayList<byte[]>) newStateStream.readObject();
assertThat(newNames, equalTo(oldNames));
assertTrue(Arrays.deepEquals(newValues.toArray(), oldValues.toArray()));
assertThat(newStateStream.available(), equalTo(0));
// Tidy up.
oldStateStream.close();
newStateStream.close();
stateFile1.delete();
stateFile2.delete();
}
/**
* Test method for {@link ChromeBackupAgent#onBackup} a second backup with different data
*/
@Test
@SuppressWarnings("unchecked")
public void testOnBackup_dataChanged()
throws FileNotFoundException, IOException, ClassNotFoundException {
// Mock the backup data.
BackupDataOutput backupData = mock(BackupDataOutput.class);
// Create a state file.
File stateFile1 = File.createTempFile("Test", "");
ParcelFileDescriptor newState =
ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.parseMode("w"));
// Set up some preferences to back up.
SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
setUpTestPrefs(prefs);
// Do a first backup.
mAgent.onBackup(null, backupData, newState);
// Minimal check on first backup, this isn't the test here.
verify(backupData, times(4)).writeEntityHeader(anyString(), anyInt());
verify(backupData, times(4)).writeEntityData(any(byte[].class), anyInt());
newState.close();
ParcelFileDescriptor oldState =
ParcelFileDescriptor.open(stateFile1, ParcelFileDescriptor.parseMode("r"));
File stateFile2 = File.createTempFile("Test", "");
newState = ParcelFileDescriptor.open(stateFile2, ParcelFileDescriptor.parseMode("w"));
// Change some data.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(FirstRunSignInProcessor.FIRST_RUN_FLOW_SIGNIN_SETUP, true);
editor.apply();
// Do a second backup.
mAgent.onBackup(oldState, backupData, newState);
// Check that the second backup wrote something.
verify(backupData, times(8)).writeEntityHeader(anyString(), anyInt());
verify(backupData, times(8)).writeEntityData(any(byte[].class), anyInt());
oldState.close();
newState.close();
// the two state files should contain different data (although the names are unchanged).
ObjectInputStream oldStateStream = new ObjectInputStream(new FileInputStream(stateFile1));
ArrayList<String> oldNames = (ArrayList<String>) oldStateStream.readObject();
ArrayList<byte[]> oldValues = (ArrayList<byte[]>) oldStateStream.readObject();
ObjectInputStream newStateStream = new ObjectInputStream(new FileInputStream(stateFile2));
ArrayList<String> newNames = (ArrayList<String>) newStateStream.readObject();
ArrayList<byte[]> newValues = (ArrayList<byte[]>) newStateStream.readObject();
assertThat(newNames, equalTo(oldNames));
assertFalse(Arrays.deepEquals(newValues.toArray(), oldValues.toArray()));
assertThat(newStateStream.available(), equalTo(0));
// Tidy up.
oldStateStream.close();
newStateStream.close();
stateFile1.delete();
stateFile2.delete();
}
private BackupDataInput createMockBackupData() throws IOException {
// Mock the backup data
BackupDataInput backupData = mock(BackupDataInput.class);
final String[] keys = {"native.pref1", "native.pref2",
"AndroidDefault." + FirstRunStatus.FIRST_RUN_FLOW_COMPLETE, "AndroidDefault.junk",
"AndroidDefault." + ChromeSigninController.SIGNED_IN_ACCOUNT_KEY};
byte[] unameBytes = "user1".getBytes();
final byte[][] values = {{0}, {1}, {1}, {23, 42}, unameBytes};
when(backupData.getKey()).thenAnswer(new Answer<String>() {
private int mPos = 0;
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return keys[mPos++];
}
});
when(backupData.getDataSize()).thenAnswer(new Answer<Integer>() {
private int mPos = 0;
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
return values[mPos++].length;
}
});
when(backupData.readEntityData(any(byte[].class), anyInt(), anyInt()))
.thenAnswer(new Answer<Integer>() {
private int mPos = 0;
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
// TODO(aberent): Auto-generated method stub
byte[] buffer = invocation.getArgument(0);
for (int i = 0; i < values[mPos].length; i++) {
buffer[i] = values[mPos][i];
}
return values[mPos++].length;
}
});
when(backupData.readNextHeader()).thenAnswer(new Answer<Boolean>() {
private int mPos = 0;
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
return mPos++ < 5;
}
});
return backupData;
}
/**
* Test method for {@link ChromeBackupAgent#onRestore}.
*
* @throws IOException
* @throws ClassNotFoundException
*/
@Test
public void testOnRestore_normal() throws IOException, ClassNotFoundException {
BackupDataInput backupData = createMockBackupData();
doReturn(true).when(mAgent).accountExistsOnDevice(any(String.class));
// Create a state file.
File stateFile = File.createTempFile("Test", "");
ParcelFileDescriptor newState =
ParcelFileDescriptor.open(stateFile, ParcelFileDescriptor.parseMode("w"));
// Do a restore.
mAgent.onRestore(backupData, 0, newState);
SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
assertTrue(prefs.getBoolean(FirstRunStatus.FIRST_RUN_FLOW_COMPLETE, false));
assertFalse(prefs.contains("junk"));
verify(mAgent).nativeSetBoolBackupPrefs(
new String[] {"pref1", "pref2"}, new boolean[] {false, true});
}
/**
* Test method for {@link ChromeBackupAgent#onRestore} for a user that doesn't exist on the
* device
*
* @throws IOException
* @throws ClassNotFoundException
*/
@Test
public void testOnRestore_badUser() throws IOException, ClassNotFoundException {
BackupDataInput backupData = createMockBackupData();
doReturn(false).when(mAgent).accountExistsOnDevice(any(String.class));
// Create a state file.
File stateFile = File.createTempFile("Test", "");
ParcelFileDescriptor newState =
ParcelFileDescriptor.open(stateFile, ParcelFileDescriptor.parseMode("w"));
// Do a restore.
mAgent.onRestore(backupData, 0, newState);
SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
assertFalse(prefs.contains(FirstRunStatus.FIRST_RUN_FLOW_COMPLETE));
verify(mAgent, never()).nativeSetBoolBackupPrefs(any(String[].class), any(boolean[].class));
}
}
| 6,426 |
611 | """Keras layer types for padding ops."""
import tensorflow as tf
from tensorflow_gnn.graph import padding_ops
from tensorflow_gnn.graph import preprocessing_common
@tf.keras.utils.register_keras_serializable(package="GNN")
class PadToTotalSizes(tf.keras.layers.Layer):
"""Applies tfgnn.pad_to_total_sizes() to a GraphTensor.
This Keras layer maps a GraphTensor to a GraphTensor by calling
`tfgnn.pad_to_total_sizes()` with the additional arguments, notably
`sizes_constraints`, passed at initialization time. See that function
for detailed documentation.
Serialization to a Keras model config requires the `sizes_constraints` to
contain Python integers or eager Tensors, not symbolic Tensors.
"""
def __init__(self,
sizes_constraints: preprocessing_common.SizeConstraints,
*,
validate: bool = True,
**kwargs):
super().__init__(**kwargs)
self._sizes_constraints = sizes_constraints
self._validate = validate
def get_config(self):
try:
int_constraints = tf.nest.map_structure(int, self._sizes_constraints)
except TypeError as e:
raise NotImplementedError( # Let SavedModel export skip this gracefully.
"get_config() requires sizes_constraints convertible to int.") from e
return dict(
sizes_constraints=int_constraints._asdict(),
validate=self._validate,
**super().get_config())
@classmethod
def from_config(cls, config):
sizes_constraints = preprocessing_common.SizeConstraints(
**config.pop("sizes_constraints"))
return cls(sizes_constraints=sizes_constraints, **config)
def call(self, graph):
return padding_ops.pad_to_total_sizes(
graph, self._sizes_constraints, validate=self._validate)
| 663 |
583 | <filename>resources/sublimetext/flower/env.py<gh_stars>100-1000
import os
from collections import ChainMap
from sublime import expand_variables
import flower
# -----------------------------------------------
# ENV
# -----------------------------------------------
def expandStr(value):
"""Expand ${name}s and $NAMEs. Empty string if key not found"""
return expand_variables(os.path.expandvars(value), flower.ENV)
def expandEnv(*items):
"""[do, $things] -> (do, env.things)"""
res = tuple(filter(bool, map(expandStr, items)))
return res
def expandPath(path):
return os.path.normpath(os.path.expanduser(expandStr(path)))
def _recExpand(envdict):
expanded = {key : expand_variables(val, envdict) for key, val in envdict.items()}
return expanded if expanded == envdict else _recExpand(expanded)
def _getOSEnv():
"""Get variables dict for OS Envvars mentioned in config"""
envlist = set(flower.SETTINGS.get('osenv', []))
envdict = {}
for key in envlist:
value = os.getenv(key)
if value is None:
continue
envdict[key.lower()] = value
return envdict
def getEnv():
get = lambda val, default: default if val == "auto" else val
vitals = {k : get(flower.SETTINGS.get(k, "auto"), v) for k, v in flower.VITALS.items()}
custom = flower.SETTINGS.get('vars', {}) # override os env
return _recExpand(ChainMap(vitals, custom, _getOSEnv()))
| 516 |
323 | package com.li.springbootasync.test;
import com.li.springbootasync.task.Task;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @ClassName TaskTest
* @Author lihaodong
* @Date 2019/2/26 17:49
* @Mail <EMAIL>
* @Description
* @Version 1.0
**/
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class TaskTest {
@Autowired
private Task task;
@Test
public void test01() throws Exception {
task.doTaskOne();
task.doTaskTwo();
task.doTaskThree();
}
@Test
public void test02() throws Exception {
long start = System.currentTimeMillis();
Future<String> task1 = task.doTaskOne();
Future<String> task2 = task.doTaskTwo();
Future<String> task3 = task.doTaskThree();
while(true) {
if(task1.isDone() && task2.isDone() && task3.isDone()) {
// 三个任务都调用完成,退出循环等待
break;
}
Thread.sleep(1000);
}
long end = System.currentTimeMillis();
System.out.println("任务全部完成,总耗时:" + (end - start) + "毫秒");
}
@Test
public void test03() throws Exception {
task.doTaskOne();
task.doTaskTwo();
task.doTaskThree();
Thread.currentThread().join();
}
@Test
@SneakyThrows
public void test() {
for (int i = 0; i < 10000; i++) {
task.doTaskOne();
task.doTaskTwo();
task.doTaskThree();
if (i == 9999) {
System.exit(0);
}
}
}
@Test
public void test04() throws Exception {
Future<String> futureResult = task.run();
String result = futureResult.get(5, TimeUnit.SECONDS);
log.info(result);
}
}
| 995 |
737 | <reponame>etnrlz/rtbkit
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <string>
#include <boost/test/unit_test.hpp>
#include "soa/service/http_header.h"
using namespace std;
/* Ensure that long long/int64 header content-length are supported */
BOOST_AUTO_TEST_CASE(test_http_header_long_long)
{
Datacratic::HttpHeader header;
string response = ("HTTP/1.1 200 OK\r\n"
"x-amz-id-2: a4KTwfjQazJISfG4fout1ZGxh8zT9okHNw+x0IK9yeOf13sfBCPWaTU9NVX9UYDe\r\n"
"x-amz-request-id: 5C7BFD14CC6988A3\r\n"
"Date: Tue, 03 Jun 2014 12:19:58 GMT\r\n"
"Last-Modified: Tue, 03 Jun 2014 02:55:25 GMT\r\n"
"ETag: \"0d24e1a5d399439dcf60907de62101e8-173\"\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Type: binary/octet-stream\r\n"
"Content-Length: 10893368309\r\n"
"Server: AmazonS3\r\n"
"\r\n");
header.parse(response, false);
BOOST_CHECK_EQUAL(header.contentLength, 10893368309);
}
/* query parsing */
BOOST_AUTO_TEST_CASE(test_http_header_query_parser_no_query)
{
const std::string query = "GET /bid? HTTP/1.1\r\n"
"\r\n";
Datacratic::HttpHeader header;
header.parse(query);
}
BOOST_AUTO_TEST_CASE(test_http_header_query_parser_no_var)
{
const std::string query = "GET /bid?& HTTP/1.1\r\n"
"\r\n";
Datacratic::HttpHeader header;
header.parse(query);
}
namespace {
Datacratic::HttpHeader generateParser(const std::string& q)
{
const std::string query = "GET " + q + " HTTP/1.1\r\n\r\n";
Datacratic::HttpHeader parser;
parser.parse(query);
return std::move(parser);
}
void testQueryParam(const Datacratic::HttpHeader& header,
const std::string& var,
const std::string& expectedValue)
{
auto const& val = header.queryParams.getValue(var);
BOOST_CHECK_EQUAL(val, expectedValue);
}
} // namespace
// From Google url
BOOST_AUTO_TEST_CASE(test_http_header_query_parser_g1)
{
auto header = generateParser("/?arg1=1&arg2=2&bar");
testQueryParam(header, "arg1", "1");
testQueryParam(header, "arg2", "2");
testQueryParam(header, "bar", "");
}
BOOST_AUTO_TEST_CASE(test_http_header_query_parser_g2)
{
// Empty param at the end.
auto parser = generateParser("/?foo=bar&");
testQueryParam(parser, "foo", "bar");
}
BOOST_AUTO_TEST_CASE(test_http_header_query_parser_g3)
{
// Empty param at the beginning.
auto parser = generateParser("/?&foo=bar");
testQueryParam(parser, "", "");
testQueryParam(parser, "foo", "bar");
}
BOOST_AUTO_TEST_CASE(test_http_header_query_parser_g4)
{
// Empty key with value.
auto parser = generateParser("http://www.google.com?=foo");
testQueryParam(parser, "", "foo");
}
BOOST_AUTO_TEST_CASE(test_http_header_query_parser_g5)
{
// Empty value with key.
auto parser = generateParser("/?foo=");
testQueryParam(parser, "foo", "");
}
BOOST_AUTO_TEST_CASE(test_http_header_query_parser_g6)
{
// Empty key and values.
auto parser = generateParser("/?&&==&=");
BOOST_CHECK_EQUAL(parser.queryParams[0].second, "");
BOOST_CHECK_EQUAL(parser.queryParams[1].second, "");
BOOST_CHECK_EQUAL(parser.queryParams[2].second, "=");
BOOST_CHECK_EQUAL(parser.queryParams[3].second, "");
}
BOOST_AUTO_TEST_CASE(test_http_header_space_as_plus)
{
auto header = generateParser("/?arg1=1+2");
testQueryParam(header, "arg1", "1 2");
}
| 1,756 |
621 | <reponame>haohaoxiao/Deep-Reinforcement-Learning-Hands-On-Second-Edition
from ._env import CubeEnv, get, names
from . import cube3x3
from . import cube2x2
__all__ = ('CubeEnv', 'get', 'names')
| 73 |
2,151 | <reponame>zipated/src
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_VIZ_COMMON_GL_HELPER_H_
#define COMPONENTS_VIZ_COMMON_GL_HELPER_H_
#include <memory>
#include "base/atomicops.h"
#include "base/callback.h"
#include "base/macros.h"
#include "components/viz/common/viz_common_export.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "gpu/command_buffer/common/mailbox_holder.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/geometry/size.h"
namespace gfx {
class Point;
class Rect;
class Vector2d;
class Vector2dF;
} // namespace gfx
namespace gpu {
class ContextSupport;
struct Mailbox;
} // namespace gpu
class SkRegion;
namespace viz {
class GLHelperScaling;
class ScopedGLuint {
public:
typedef void (gpu::gles2::GLES2Interface::*GenFunc)(GLsizei n, GLuint* ids);
typedef void (gpu::gles2::GLES2Interface::*DeleteFunc)(GLsizei n,
const GLuint* ids);
ScopedGLuint(gpu::gles2::GLES2Interface* gl,
GenFunc gen_func,
DeleteFunc delete_func)
: gl_(gl), id_(0u), delete_func_(delete_func) {
(gl_->*gen_func)(1, &id_);
}
operator GLuint() const { return id_; }
GLuint id() const { return id_; }
~ScopedGLuint() {
if (id_ != 0) {
(gl_->*delete_func_)(1, &id_);
}
}
private:
gpu::gles2::GLES2Interface* gl_;
GLuint id_;
DeleteFunc delete_func_;
DISALLOW_COPY_AND_ASSIGN(ScopedGLuint);
};
class ScopedBuffer : public ScopedGLuint {
public:
explicit ScopedBuffer(gpu::gles2::GLES2Interface* gl)
: ScopedGLuint(gl,
&gpu::gles2::GLES2Interface::GenBuffers,
&gpu::gles2::GLES2Interface::DeleteBuffers) {}
};
class ScopedFramebuffer : public ScopedGLuint {
public:
explicit ScopedFramebuffer(gpu::gles2::GLES2Interface* gl)
: ScopedGLuint(gl,
&gpu::gles2::GLES2Interface::GenFramebuffers,
&gpu::gles2::GLES2Interface::DeleteFramebuffers) {}
};
class ScopedTexture : public ScopedGLuint {
public:
explicit ScopedTexture(gpu::gles2::GLES2Interface* gl)
: ScopedGLuint(gl,
&gpu::gles2::GLES2Interface::GenTextures,
&gpu::gles2::GLES2Interface::DeleteTextures) {}
};
template <GLenum Target>
class ScopedBinder {
public:
typedef void (gpu::gles2::GLES2Interface::*BindFunc)(GLenum target,
GLuint id);
ScopedBinder(gpu::gles2::GLES2Interface* gl, GLuint id, BindFunc bind_func)
: gl_(gl), bind_func_(bind_func) {
(gl_->*bind_func_)(Target, id);
}
virtual ~ScopedBinder() { (gl_->*bind_func_)(Target, 0); }
private:
gpu::gles2::GLES2Interface* gl_;
BindFunc bind_func_;
DISALLOW_COPY_AND_ASSIGN(ScopedBinder);
};
template <GLenum Target>
class ScopedBufferBinder : ScopedBinder<Target> {
public:
ScopedBufferBinder(gpu::gles2::GLES2Interface* gl, GLuint id)
: ScopedBinder<Target>(gl, id, &gpu::gles2::GLES2Interface::BindBuffer) {}
};
template <GLenum Target>
class ScopedFramebufferBinder : ScopedBinder<Target> {
public:
ScopedFramebufferBinder(gpu::gles2::GLES2Interface* gl, GLuint id)
: ScopedBinder<Target>(gl,
id,
&gpu::gles2::GLES2Interface::BindFramebuffer) {}
};
template <GLenum Target>
class ScopedTextureBinder : ScopedBinder<Target> {
public:
ScopedTextureBinder(gpu::gles2::GLES2Interface* gl, GLuint id)
: ScopedBinder<Target>(gl, id, &gpu::gles2::GLES2Interface::BindTexture) {
}
};
class GLHelperReadbackSupport;
class I420Converter;
class ReadbackYUVInterface;
// Provides higher level operations on top of the gpu::gles2::GLES2Interface
// interfaces.
class VIZ_COMMON_EXPORT GLHelper {
public:
GLHelper(gpu::gles2::GLES2Interface* gl,
gpu::ContextSupport* context_support);
~GLHelper();
enum ScalerQuality {
// Bilinear single pass, fastest possible.
SCALER_QUALITY_FAST = 1,
// Bilinear upscale + N * 50% bilinear downscales.
// This is still fast enough for most purposes and
// Image quality is nearly as good as the BEST option.
SCALER_QUALITY_GOOD = 2,
// Bicubic upscale + N * 50% bicubic downscales.
// Produces very good quality scaled images, but it's
// 2-8x slower than the "GOOD" quality, so it's not always
// worth it.
SCALER_QUALITY_BEST = 3,
};
// Copies the block of pixels specified with |src_subrect| from |src_texture|,
// scales it to |dst_size|, and writes it into |out|.
// |src_size| is the size of |src_texture|. The result is in |out_color_type|
// format and is potentially flipped vertically to make it a correct image
// representation. |callback| is invoked with the copy result when the copy
// operation has completed.
// Note that the src_texture will have the min/mag filter set to GL_LINEAR
// and wrap_s/t set to CLAMP_TO_EDGE in this call.
void CropScaleReadbackAndCleanTexture(
GLuint src_texture,
const gfx::Size& src_size,
const gfx::Size& dst_size,
unsigned char* out,
const SkColorType out_color_type,
const base::Callback<void(bool)>& callback,
GLHelper::ScalerQuality quality);
// Copies the all pixels from the texture in |src_mailbox| of |src_size|,
// scales it to |dst_size|, and writes it into |out|. The result is in
// |out_color_type| format and is potentially flipped vertically to make it a
// correct image representation. |callback| is invoked with the copy result
// when the copy operation has completed.
// Note that the texture bound to src_mailbox will have the min/mag filter set
// to GL_LINEAR and wrap_s/t set to CLAMP_TO_EDGE in this call. src_mailbox is
// assumed to be GL_TEXTURE_2D.
void CropScaleReadbackAndCleanMailbox(
const gpu::Mailbox& src_mailbox,
const gpu::SyncToken& sync_token,
const gfx::Size& src_size,
const gfx::Size& dst_size,
unsigned char* out,
const SkColorType out_color_type,
const base::Callback<void(bool)>& callback,
GLHelper::ScalerQuality quality);
// Copies the texture data out of |texture| into |out|. |size| is the
// size of the texture. No post processing is applied to the pixels. The
// texture is assumed to have a format of GL_RGBA with a pixel type of
// GL_UNSIGNED_BYTE. This is a blocking call that calls glReadPixels on the
// current OpenGL context.
void ReadbackTextureSync(GLuint texture,
const gfx::Rect& src_rect,
unsigned char* out,
SkColorType format);
void ReadbackTextureAsync(GLuint texture,
const gfx::Size& dst_size,
unsigned char* out,
SkColorType color_type,
const base::Callback<void(bool)>& callback);
// Creates a scaled copy of the specified texture. |src_size| is the size of
// the texture and |dst_size| is the size of the resulting copy.
// Note that the |texture| will have the min/mag filter set to GL_LINEAR
// and wrap_s/t set to CLAMP_TO_EDGE in this call. Returns 0 on invalid
// arguments.
GLuint CopyAndScaleTexture(GLuint texture,
const gfx::Size& src_size,
const gfx::Size& dst_size,
bool vertically_flip_texture,
ScalerQuality quality);
// Returns the shader compiled from the source.
GLuint CompileShaderFromSource(const GLchar* source, GLenum type);
// Copies all pixels from |previous_texture| into |texture| that are
// inside the region covered by |old_damage| but not part of |new_damage|.
void CopySubBufferDamage(GLenum target,
GLuint texture,
GLuint previous_texture,
const SkRegion& new_damage,
const SkRegion& old_damage);
// Simply creates a texture.
GLuint CreateTexture();
// Deletes a texture.
void DeleteTexture(GLuint texture_id);
// Inserts a fence sync, flushes, and generates a sync token.
void GenerateSyncToken(gpu::SyncToken* sync_token);
// Wait for the sync token before executing further GL commands.
void WaitSyncToken(const gpu::SyncToken& sync_token);
// Creates a mailbox holder that is attached to the given texture id, with a
// sync point to wait on before using the mailbox. Returns a holder with an
// empty mailbox on failure.
// Note the texture is assumed to be GL_TEXTURE_2D.
gpu::MailboxHolder ProduceMailboxHolderFromTexture(GLuint texture_id);
// Creates a texture and consumes a mailbox into it. Returns 0 on failure.
// Note the mailbox is assumed to be GL_TEXTURE_2D.
GLuint ConsumeMailboxToTexture(const gpu::Mailbox& mailbox,
const gpu::SyncToken& sync_token);
// Resizes the texture's size to |size|.
void ResizeTexture(GLuint texture, const gfx::Size& size);
// Copies the framebuffer data given in |rect| to |texture|.
void CopyTextureSubImage(GLuint texture, const gfx::Rect& rect);
// Copies the all framebuffer data to |texture|. |size| specifies the
// size of the framebuffer.
void CopyTextureFullImage(GLuint texture, const gfx::Size& size);
// Flushes GL commands.
void Flush();
// Force commands in the current command buffer to be executed before commands
// in other command buffers from the same process (ie channel to the GPU
// process).
void InsertOrderingBarrier();
// Caches all intermediate textures and programs needed to scale any subset of
// a source texture at a fixed scaling ratio.
class ScalerInterface {
public:
virtual ~ScalerInterface() {}
// Scales a portion of |src_texture| and draws the result into
// |dest_texture| at offset (0, 0).
//
// |src_texture_size| is the full, allocated size of the |src_texture|. This
// is required for computing texture coordinate transforms (and only because
// the OpenGL ES 2.0 API lacks the ability to query this info).
//
// |src_offset| is the offset in the source texture corresponding to point
// (0,0) in the source/output coordinate spaces. This prevents the need for
// extra texture copies just to re-position the source coordinate system.
// TODO(crbug.com/775740): This must be set to whole-numbered values for
// now, until the implementation is modified to handle fractional offsets.
//
// |output_rect| selects the region to draw (in the scaled, not the source,
// coordinate space). This is used to save work in cases where only a
// portion needs to be re-scaled. The implementation will back-compute,
// internally, to determine the region of the |src_texture| to sample.
//
// WARNING: The output will always be placed at (0, 0) in the
// |dest_texture|, and not at |output_rect.origin()|.
//
// Note that the src_texture will have the min/mag filter set to GL_LINEAR
// and wrap_s/t set to CLAMP_TO_EDGE in this call.
void Scale(GLuint src_texture,
const gfx::Size& src_texture_size,
const gfx::Vector2dF& src_offset,
GLuint dest_texture,
const gfx::Rect& output_rect) {
ScaleToMultipleOutputs(src_texture, src_texture_size, src_offset,
dest_texture, 0, output_rect);
}
// Same as above, but for shaders that output to two textures at once.
virtual void ScaleToMultipleOutputs(GLuint src_texture,
const gfx::Size& src_texture_size,
const gfx::Vector2dF& src_offset,
GLuint dest_texture_0,
GLuint dest_texture_1,
const gfx::Rect& output_rect) = 0;
// Given the |src_texture_size|, |src_offset| and |output_rect| arguments
// that would be passed to Scale(), compute the region of pixels in the
// source texture that would be sampled to produce a scaled result. The
// result is stored in |sampling_rect|, along with the |offset| to the (0,0)
// point relative to |sampling_rect|'s origin.
//
// This is used by clients that need to know the minimal portion of a source
// buffer that must be copied without affecting Scale()'s results. This
// method also accounts for vertical flipping.
virtual void ComputeRegionOfInfluence(const gfx::Size& src_texture_size,
const gfx::Vector2dF& src_offset,
const gfx::Rect& output_rect,
gfx::Rect* sampling_rect,
gfx::Vector2dF* offset) const = 0;
// Returns true if from:to represent the same scale ratio as that provided
// by this scaler.
virtual bool IsSameScaleRatio(const gfx::Vector2d& from,
const gfx::Vector2d& to) const = 0;
// Returns true if the scaler is assuming the source texture's content is
// vertically flipped.
virtual bool IsSamplingFlippedSource() const = 0;
// Returns true if the scaler will vertically-flip the output. Note that if
// both this method and IsSamplingFlippedSource() return true, then the
// scaler output will be right-side up.
virtual bool IsFlippingOutput() const = 0;
// Returns the format to use when calling glReadPixels() to read-back the
// output texture(s). This indicates whether the 0th and 2nd bytes in each
// RGBA quad have been swapped. If no swapping has occurred, this will
// return GL_RGBA. Otherwise, it will return GL_BGRA_EXT.
virtual GLenum GetReadbackFormat() const = 0;
protected:
ScalerInterface() {}
private:
DISALLOW_COPY_AND_ASSIGN(ScalerInterface);
};
// Create a scaler that upscales or downscales at the given ratio
// (scale_from:scale_to). Returns null on invalid arguments.
//
// If |flipped_source| is true, then the scaler will assume the content of the
// source texture is vertically-flipped. This is required so that the scaler
// can correctly compute the sampling region.
//
// If |flip_output| is true, then the scaler will vertically-flip its output
// result. This is used when the output texture will be read-back into system
// memory, so that the rows do not have to be copied in reverse.
//
// If |swizzle| is true, the 0th and 2nd elements in each RGBA quad will be
// swapped. This is beneficial for optimizing read-back into system memory.
//
// WARNING: The returned scaler assumes both this GLHelper and its
// GLES2Interface/ContextSupport will outlive it!
std::unique_ptr<ScalerInterface> CreateScaler(ScalerQuality quality,
const gfx::Vector2d& scale_from,
const gfx::Vector2d& scale_to,
bool flipped_source,
bool flip_output,
bool swizzle);
// Create a pipeline that will (optionally) scale a source texture, and then
// convert it to I420 (YUV) planar form, delivering results in three separate
// output textures (one for each plane; see I420Converter::Convert()).
//
// Due to limitations in the OpenGL ES 2.0 API, the output textures will have
// a format of GL_RGBA. However, each RGBA "pixel" in these textures actually
// carries 4 consecutive pixels for the single-color-channel result plane.
// Therefore, when using the OpenGL APIs to read-back the image into system
// memory, note that a width 1/4 the actual |output_rect.width()| must be
// used.
//
// |flipped_source|, |flip_output|, and |swizzle| have the same meaning as
// that explained in the method comments for CreateScaler().
//
// If |use_mrt| is true, the pipeline will try to optimize the YUV conversion
// using the multi-render-target extension, if the platform is capable.
// |use_mrt| should only be set to false for testing.
//
// The benefit of using this pipeline is seen when these output textures are
// read back from GPU to CPU memory: The I420 format reduces the amount of
// data read back by a factor of ~2.6 (32bpp → 12bpp) which can greatly
// improve performance, for things like video screen capture, on platforms
// with slow GPU read-back performance.
//
// WARNING: The returned I420Converter instance assumes both this GLHelper and
// its GLES2Interface/ContextSupport will outlive it!
std::unique_ptr<I420Converter> CreateI420Converter(bool flipped_source,
bool flip_output,
bool swizzle,
bool use_mrt);
// Create a readback pipeline that will (optionally) scale a source texture,
// then convert it to YUV420 planar form, and finally read back that. This
// reduces the amount of memory read from GPU to CPU memory by a factor of 2.6
// (32bpp → 12bpp), which can be quite handy since readbacks have very limited
// speed on some platforms.
//
// If |use_mrt| is true, the pipeline will try to optimize the YUV conversion
// using the multi-render-target extension, if the platform is capable.
// |use_mrt| should only be set to false for testing.
//
// WARNING: The returned ReadbackYUVInterface instance assumes both this
// GLHelper and its GLES2Interface/ContextSupport will outlive it!
//
// TODO(crbug/754872): DEPRECATED. This will be removed soon, in favor of
// CreateI420Converter().
std::unique_ptr<ReadbackYUVInterface> CreateReadbackPipelineYUV(
bool vertically_flip_texture,
bool use_mrt);
// Returns a ReadbackYUVInterface instance that is lazily created and owned by
// this class. |use_mrt| is always true for these instances.
ReadbackYUVInterface* GetReadbackPipelineYUV(bool vertically_flip_texture);
// Returns the maximum number of draw buffers available,
// 0 if GL_EXT_draw_buffers is not available.
GLint MaxDrawBuffers();
// Checks whether the readbback is supported for texture with the
// matching config. This doesnt check for cross format readbacks.
bool IsReadbackConfigSupported(SkColorType texture_format);
// Returns a GLHelperReadbackSupport instance, for querying platform readback
// capabilities and to determine the more-performant configurations.
GLHelperReadbackSupport* GetReadbackSupport();
protected:
class CopyTextureToImpl;
// Creates |copy_texture_to_impl_| if NULL.
void InitCopyTextToImpl();
// Creates |scaler_impl_| if NULL.
void InitScalerImpl();
// Creates |readback_support_| if NULL.
void LazyInitReadbackSupportImpl();
enum ReadbackSwizzle { kSwizzleNone = 0, kSwizzleBGRA };
gpu::gles2::GLES2Interface* gl_;
gpu::ContextSupport* context_support_;
std::unique_ptr<CopyTextureToImpl> copy_texture_to_impl_;
std::unique_ptr<GLHelperScaling> scaler_impl_;
std::unique_ptr<GLHelperReadbackSupport> readback_support_;
std::unique_ptr<ReadbackYUVInterface> shared_readback_yuv_flip_;
std::unique_ptr<ReadbackYUVInterface> shared_readback_yuv_noflip_;
private:
DISALLOW_COPY_AND_ASSIGN(GLHelper);
};
// Splits an RGBA source texture's image into separate Y, U, and V planes. The U
// and V planes are half-width and half-height, according to the I420 standard.
class VIZ_COMMON_EXPORT I420Converter {
public:
I420Converter();
virtual ~I420Converter();
// Transforms a RGBA |src_texture| into three textures, each containing bytes
// in I420 planar form. See the GLHelper::ScalerInterface::Scale() method
// comments for the meaning/semantics of |src_texture_size|, |src_offset| and
// |output_rect|. If |optional_scaler| is not null, it will first be used to
// scale the source texture into an intermediate texture before generating the
// Y+U+V planes.
//
// See notes for CreateI420Converter() regarding the semantics of the output
// textures.
virtual void Convert(GLuint src_texture,
const gfx::Size& src_texture_size,
const gfx::Vector2dF& src_offset,
GLHelper::ScalerInterface* optional_scaler,
const gfx::Rect& output_rect,
GLuint y_plane_texture,
GLuint u_plane_texture,
GLuint v_plane_texture) = 0;
// Returns true if the converter is assuming the source texture's content is
// vertically flipped.
virtual bool IsSamplingFlippedSource() const = 0;
// Returns true if the converter will vertically-flip the output.
virtual bool IsFlippingOutput() const = 0;
// Returns the format to use when calling glReadPixels() to read-back the
// output textures. This indicates whether the 0th and 2nd bytes in each RGBA
// quad have been swapped. If no swapping has occurred, this will return
// GL_RGBA. Otherwise, it will return GL_BGRA_EXT.
virtual GLenum GetReadbackFormat() const = 0;
// Returns the texture size of the Y plane texture, based on the size of the
// |output_rect| that was given to Convert(). This will have a width of
// CEIL(output_rect_size.width() / 4), and the same height.
static gfx::Size GetYPlaneTextureSize(const gfx::Size& output_rect_size);
// Like GetYPlaneTextureSize(), except the returned size will have a width of
// CEIL(output_rect_size.width() / 8), and a height of
// CEIL(output_rect_size.height() / 2); because the chroma planes are half-
// length in both dimensions in the I420 format.
static gfx::Size GetChromaPlaneTextureSize(const gfx::Size& output_rect_size);
private:
DISALLOW_COPY_AND_ASSIGN(I420Converter);
};
// Similar to a ScalerInterface, a YUV readback pipeline will cache a scaler and
// all intermediate textures and frame buffers needed to scale, crop, letterbox
// and read back a texture from the GPU into CPU-accessible RAM. A single
// readback pipeline can handle multiple outstanding readbacks at the same time.
//
// TODO(crbug/754872): DEPRECATED. This will be removed soon, in favor of
// I420Converter and readback implementation in GLRendererCopier.
class VIZ_COMMON_EXPORT ReadbackYUVInterface {
public:
ReadbackYUVInterface() {}
virtual ~ReadbackYUVInterface() {}
// Optional behavior: This sets a scaler to use to scale the inputs before
// planarizing. If null (or never called), then no scaling is performed.
virtual void SetScaler(std::unique_ptr<GLHelper::ScalerInterface> scaler) = 0;
// Returns the currently-set scaler, or null.
virtual GLHelper::ScalerInterface* scaler() const = 0;
// Returns true if the converter will vertically-flip the output.
virtual bool IsFlippingOutput() const = 0;
// Transforms a RGBA texture into I420 planar form, and then reads it back
// from the GPU into system memory. See the GLHelper::ScalerInterface::Scale()
// method comments for the meaning/semantics of |src_texture_size| and
// |output_rect|. The process is:
//
// 1. Sync-wait and then consume and take ownership of the source texture
// provided by |mailbox|.
// 2. Scale the source texture to an intermediate texture.
// 3. Planarize, producing textures containing the Y, U, and V planes.
// 4. Read-back the planar data, copying it into the given output
// destination. |paste_location| specifies the where to place the output
// pixels: Rect(paste_location.origin(), output_rect.size()).
// 5. Run |callback| with true on success, false on failure (with no output
// modified).
virtual void ReadbackYUV(const gpu::Mailbox& mailbox,
const gpu::SyncToken& sync_token,
const gfx::Size& src_texture_size,
const gfx::Rect& output_rect,
int y_plane_row_stride_bytes,
unsigned char* y_plane_data,
int u_plane_row_stride_bytes,
unsigned char* u_plane_data,
int v_plane_row_stride_bytes,
unsigned char* v_plane_data,
const gfx::Point& paste_location,
const base::Callback<void(bool)>& callback) = 0;
};
} // namespace viz
#endif // COMPONENTS_VIZ_COMMON_GL_HELPER_H_
| 9,309 |
5,169 | {
"name": "NSString_stripHtml",
"version": "0.1.0",
"summary": "A NSString category that adds a `stripHtml` method to all NSStrings.",
"description": " A podified version of Leigh McCulloch's NSString_stripHtml category.\n",
"homepage": "http://www.codeilove.com/2011/09/ios-dev-strip-html-tags-from-nsstring.html",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/imkmf/NSString_stripHtml.git",
"tag": "0.1.0"
},
"platforms": {
"ios": null
},
"requires_arc": false,
"source_files": "Classes/ios"
}
| 260 |
16,461 | // Copyright 2019-present 650 Industries. All rights reserved.
#import <ABI42_0_0UMCore/ABI42_0_0UMModuleRegistry.h>
#import <ABI42_0_0UMCore/ABI42_0_0UMModuleRegistryConsumer.h>
#import <UIKit/UIKit.h>
@interface ABI42_0_0EXAdsAdMob : ABI42_0_0UMExportedModule <ABI42_0_0UMModuleRegistryConsumer>
@end
| 130 |
1,511 | <gh_stars>1000+
*
* Basic Linux Telephony Interface
*
* (c) Copyright 1999-2001 Quicknet Technologies, Inc.
*
* This program is free software; you can redistribute it and/or | 57 |
1,909 | package org.knowm.xchange.ftx.service;
import java.nio.charset.StandardCharsets;
import javax.crypto.Mac;
import javax.ws.rs.HeaderParam;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.service.BaseParamsDigest;
import org.knowm.xchange.utils.DigestUtils;
import si.mazi.rescu.RestInvocation;
public class FtxDigest extends BaseParamsDigest {
private FtxDigest(byte[] secretKey) {
super(secretKey, HMAC_SHA_256);
}
public static FtxDigest createInstance(String secretKey) {
if (secretKey != null) {
return new FtxDigest(secretKey.getBytes());
} else return null;
}
@Override
public String digestParams(RestInvocation restInvocation) {
String message =
restInvocation.getParamValue(HeaderParam.class, "FTX-TS").toString()
+ restInvocation.getHttpMethod().toUpperCase()
+ restInvocation.getPath();
if (!restInvocation.getQueryString().isEmpty()) {
message += "?" + restInvocation.getQueryString();
}
if (restInvocation.getHttpMethod().equals("POST")
|| (restInvocation.getPath().contains("/orders")
&& restInvocation.getHttpMethod().equals("DELETE"))
&& restInvocation.getRequestBody() != null) {
message += restInvocation.getRequestBody();
}
Mac mac256 = getMac();
try {
mac256.update(message.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new ExchangeException("Digest encoding exception", e);
}
return DigestUtils.bytesToHex(mac256.doFinal()).toLowerCase();
}
}
| 600 |
348 | <reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000
{"nom":"Boinville-en-Woëvre","dpt":"Meuse","inscrits":60,"abs":16,"votants":44,"blancs":1,"nuls":0,"exp":43,"res":[{"panneau":"2","voix":22},{"panneau":"1","voix":21}]} | 100 |
480 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.executor.ddl.job.task.basic;
import com.alibaba.fastjson.annotation.JSONCreator;
import com.alibaba.polardbx.executor.ddl.job.meta.TableMetaChanger;
import com.alibaba.polardbx.executor.ddl.job.task.BaseGmsTask;
import com.alibaba.polardbx.executor.ddl.job.task.util.TaskName;
import com.alibaba.polardbx.executor.sync.SyncManagerHelper;
import com.alibaba.polardbx.executor.sync.TableMetaChangeSyncAction;
import com.alibaba.polardbx.executor.utils.failpoint.FailPoint;
import com.alibaba.polardbx.gms.metadb.table.TablesExtRecord;
import com.alibaba.polardbx.optimizer.context.ExecutionContext;
import lombok.Getter;
import java.sql.Connection;
@Getter
@TaskName(name = "CreateTableAddTablesExtMetaTask")
public class CreateTableAddTablesExtMetaTask extends BaseGmsTask {
private final boolean autoPartition;
private boolean temporary;
private TablesExtRecord tablesExtRecord;
@JSONCreator
public CreateTableAddTablesExtMetaTask(String schemaName, String logicalTableName, boolean temporary,
TablesExtRecord tablesExtRecord, boolean autoPartition) {
super(schemaName, logicalTableName);
this.autoPartition = autoPartition;
this.temporary = temporary;
this.tablesExtRecord = tablesExtRecord;
onExceptionTryRecoveryThenRollback();
}
@Override
public void executeImpl(Connection metaDbConnection, ExecutionContext executionContext) {
if (!isCreateTableSupported(executionContext)) {
return;
}
if (autoPartition) {
tablesExtRecord.setAutoPartition();
}
TableMetaChanger.addTableExt(metaDbConnection, tablesExtRecord);
FailPoint.injectRandomExceptionFromHint(executionContext);
FailPoint.injectRandomSuspendFromHint(executionContext);
}
@Override
public void rollbackImpl(Connection metaDbConnection, ExecutionContext executionContext) {
if (!isCreateTableSupported(executionContext)) {
return;
}
TableMetaChanger.removeTableExt(metaDbConnection, schemaName, logicalTableName);
FailPoint.injectRandomExceptionFromHint(executionContext);
FailPoint.injectRandomSuspendFromHint(executionContext);
SyncManagerHelper.sync(new TableMetaChangeSyncAction(schemaName, logicalTableName));
}
private boolean isCreateTableSupported(ExecutionContext executionContext) {
return !(temporary || executionContext.isUseHint());
}
@Override
public String remark() {
String partitionStr = "";
if (this.autoPartition) {
partitionStr = ",auto-partition by " + this.tablesExtRecord.dbPartitionKey;
}
return String.format("|table=%s%s", tablesExtRecord.tableName, partitionStr);
}
}
| 1,211 |
852 | <reponame>ckamtsikis/cmssw
#include "FWCore/PluginManager/interface/ModuleDef.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "SimG4Core/Watcher/interface/SimWatcherFactory.h"
#include "SimG4Core/Physics/interface/PhysicsListFactory.h"
#include "SimG4Core/CustomPhysics/interface/CustomPhysics.h"
#include "SimG4Core/CustomPhysics/interface/RHStopDump.h"
#include "SimG4Core/CustomPhysics/interface/RHStopTracer.h"
DEFINE_PHYSICSLIST(CustomPhysics);
DEFINE_FWK_MODULE(RHStopDump);
DEFINE_SIMWATCHER(RHStopTracer);
| 202 |
4,054 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
* \class storage::VisitorMessageSession
*/
#pragma once
#include <vespa/messagebus/result.h>
namespace documentapi {
class DocumentMessage;
}
namespace storage {
struct VisitorMessageSession {
typedef std::unique_ptr<VisitorMessageSession> UP;
virtual ~VisitorMessageSession() {}
virtual mbus::Result send(std::unique_ptr<documentapi::DocumentMessage>) = 0;
/** @return Returns the number of pending messages this session has. */
virtual uint32_t pending() = 0;
};
} // storage
| 188 |
5,852 | //
// ScrollZoomViewController.h
// JXCategoryView
//
// Created by jiaxin on 2019/2/14.
// Copyright © 2019 jiaxin. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface ScrollZoomViewController : UIViewController
@end
NS_ASSUME_NONNULL_END
| 110 |
1,085 | <reponame>weltam/dremio-oss
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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.dremio.exec.store;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexInputRef;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexShuttle;
/**
* Rewrite inputs in expression to handle any RowType change during expansion
*/
public class ExpressionInputRewriter extends RexShuttle {
private final RexBuilder builder;
private final List<String> fieldNames;
private final RelNode input;
private final Map<Integer, Integer> fieldMap;
private final String suffix;
public ExpressionInputRewriter(RexBuilder builder, RelDataType rowType, RelNode input, String suffix) {
this.builder = builder;
this.input = input;
this.fieldNames = rowType.getFieldNames();
this.fieldMap = new HashMap<>();
this.suffix = suffix;
final List<String> inputFields = input.getRowType().getFieldNames();
for(int i = 0 ; i < fieldNames.size() ; i++) {
String fieldName = fieldNames.get(i);
fieldMap.put(i, inputFields.indexOf(fieldName + suffix));
}
}
@Override
public RexNode visitInputRef(RexInputRef inputRef) {
int originalIndex = inputRef.getIndex();
int newIndex = fieldMap.get(inputRef.getIndex());
if (newIndex == -1) {
throw new IllegalArgumentException(String.format("Could not find field, %s, from, %s", fieldNames.get(originalIndex) + suffix, input.getRowType()));
}
return builder.makeInputRef(input, newIndex);
}
}
| 710 |
310 | <filename>integration-test-java/src/test/java/org/seasar/doma/it/domain/WeightTest.java
/*
* Copyright 2004-2010 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.doma.it.domain;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.seasar.doma.internal.jdbc.scalar.Scalar;
import org.seasar.doma.it.IntegrationTestEnvironment;
import org.seasar.doma.jdbc.ClassHelper;
import org.seasar.doma.jdbc.Config;
import org.seasar.doma.jdbc.domain.DomainType;
import org.seasar.doma.jdbc.domain.DomainTypeFactory;
@ExtendWith(IntegrationTestEnvironment.class)
public class WeightTest {
@Test
public void testDefaultValue(Config config) throws Exception {
DomainType<Integer, Weight> domainType =
DomainTypeFactory.getDomainType(Weight.class, new ClassHelper() {});
Scalar<Integer, Weight> scalar = domainType.createScalar();
Weight domain = scalar.get();
assertNotNull(domain);
assertNull(domain.getValue());
}
@Test
public void testDefaultValue_Optional(Config config) throws Exception {
DomainType<Integer, Weight> domainType = DomainTypeFactory.getDomainType(Weight.class);
Scalar<Integer, Optional<Weight>> scalar = domainType.createOptionalScalar();
Optional<Weight> optional = scalar.get();
assertNotNull(optional);
assertFalse(optional.isPresent());
}
}
| 674 |
1,602 | <gh_stars>1000+
//#include "../../hadoop-1.1.2/src/c++/libhdfs/hdfs.h"
//#include "hdfs.h"
#include <stdlib.h>
#include <stdio.h>
#include <hdfs.h>
#include <assert.h>
#define IS_NULL_TRUE 1
#define IS_NULL_FALSE 0
//typedef struct __hdfsString {
// int length;
// const char* buffer;
//} _hdfsString, *hdfsString;
typedef struct _chadoopFileInfo {
// const char* mKind; /* file or directory */
// const char *mName; /* the name of the file */
tTime mLastMod; /* the last modification time for the file in seconds */
tOffset mSize; /* the size of the file in bytes */
short mReplication; /* the count of replicas */
tOffset mBlockSize; /* the block size for the file */
// const char *mOwner; /* the owner of the file */
// const char *mGroup; /* the group associated with the file */
short mPermissions; /* the permissions associated with the file */
tTime mLastAccess; /* the last access time for the file in seconds */
} chadoopFileInfo;
int IS_NULL(void* ptr);
int printBlockHosts_C(char*** hostBlocks, char* locId);
void chadoopFree(void* ptr);
void chadoopFreeString(const char* str);
chadoopFileInfo chadoopGetFileInfo(hdfsFS fs, const char* path);
int chadoopGetBlockCount(char*** hostBlocks);
int chadoopGetHostCount(char*** hostBlocks, int block);
const char* chadoopGetHost(char*** hostBlocks, int block, int host);
const char* chadoopReadFile(hdfsFS fs, hdfsFile file, tSize length);
const char* chadoopReadFilePositional(hdfsFS fs, hdfsFile file, tOffset position, tSize length);
| 590 |
589 | #!/usr/bin/env python
"""
* *******************************************************
* Copyright (c) VMware, Inc. 2020. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware, Inc.'
__vcenter_version__ = '7.0+'
from samples.vsphere.common.sample_cli import build_arg_parser
"""
Builds a standard argument parser with required and optional argument groups
Most of the Vsphere Stats samples require these three standard required
arguments.
--expiration
--interval
"""
parser = build_arg_parser()
required_args = parser.add_argument_group(
'required arguments for creating acquisition spec')
required_args.add_argument(
'--expiration',
required=True,
help='Create an Acquisition Specification with expiration time.' +
' Example: 10000000000')
required_args.add_argument(
'--interval',
required=True,
help='Create an Acquisition Specification with interval. Example: 10')
| 413 |
777 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CC_DEBUG_UNITTEST_ONLY_BENCHMARK_IMPL_H_
#define CC_DEBUG_UNITTEST_ONLY_BENCHMARK_IMPL_H_
#include "base/memory/weak_ptr.h"
#include "cc/debug/micro_benchmark_impl.h"
namespace base {
class SingleThreadTaskRunner;
class Value;
}
namespace cc {
class LayerTreeHostImpl;
class CC_EXPORT UnittestOnlyBenchmarkImpl : public MicroBenchmarkImpl {
public:
UnittestOnlyBenchmarkImpl(
scoped_refptr<base::SingleThreadTaskRunner> origin_task_runner,
base::Value* settings,
const DoneCallback& callback);
~UnittestOnlyBenchmarkImpl() override;
void DidCompleteCommit(LayerTreeHostImpl* host) override;
};
} // namespace cc
#endif // CC_DEBUG_UNITTEST_ONLY_BENCHMARK_IMPL_H_
| 308 |
32,544 | <reponame>DBatOWL/tutorials
package com.baeldung.mockito;
import com.baeldung.mockito.repository.UserRepository;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class MockAnnotationUnitTest {
@Mock
UserRepository mockRepository;
@Test
public void givenCountMethodMocked_WhenCountInvoked_ThenMockValueReturned() {
Mockito.when(mockRepository.count()).thenReturn(123L);
long userCount = mockRepository.count();
Assert.assertEquals(123L, userCount);
Mockito.verify(mockRepository).count();
}
@Test
public void givenCountMethodMocked_WhenCountInvoked_ThenMockedValueReturned() {
UserRepository localMockRepository = Mockito.mock(UserRepository.class);
Mockito.when(localMockRepository.count()).thenReturn(111L);
long userCount = localMockRepository.count();
Assert.assertEquals(111L, userCount);
Mockito.verify(localMockRepository).count();
}
}
| 454 |
777 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SparseHeapBitmap_h
#define SparseHeapBitmap_h
#include "platform/heap/BlinkGC.h"
#include "platform/heap/HeapPage.h"
#include "wtf/Alignment.h"
#include "wtf/PtrUtil.h"
#include <bitset>
#include <memory>
namespace blink {
// A sparse bitmap of heap addresses where the (very few) addresses that are
// set are likely to be in small clusters. The abstraction is tailored to
// support heap compaction, assuming the following:
//
// - Addresses will be bitmap-marked from lower to higher addresses.
// - Bitmap lookups are performed for each object that is compacted
// and moved to some new location, supplying the (base, size)
// pair of the object's heap allocation.
// - If the sparse bitmap has any marked addresses in that range, it
// returns a sub-bitmap that can be quickly iterated over to check which
// addresses within the range are actually set.
// - The bitmap is needed to support something that is very rarely done
// by the current Blink codebase, which is to have nested collection
// part objects. Consequently, it is safe to assume sparseness.
//
// Support the above by having a sparse bitmap organized as a binary
// tree with nodes covering fixed size ranges via a simple bitmap/set.
// That is, each SparseHeapBitmap node will contain a bitmap/set for
// some fixed size range, along with pointers to SparseHeapBitmaps
// for addresses on each side its range.
//
// This bitmap tree isn't kept balanced across the Address additions
// made.
//
class PLATFORM_EXPORT SparseHeapBitmap {
public:
static std::unique_ptr<SparseHeapBitmap> create(Address base) {
return WTF::wrapUnique(new SparseHeapBitmap(base));
}
~SparseHeapBitmap() {}
// Return the sparse bitmap subtree that at least covers the
// [address, address + size) range, or nullptr if none.
//
// The returned SparseHeapBitmap can be used to quickly lookup what
// addresses in that range are set or not; see |isSet()|. Its
// |isSet()| behavior outside that range is not defined.
SparseHeapBitmap* hasRange(Address, size_t);
// True iff |address| is set for this SparseHeapBitmap tree.
bool isSet(Address);
// Mark |address| as present/set.
void add(Address);
// The assumed minimum alignment of the pointers being added. Cannot
// exceed |log2(allocationGranularity)|; having it be equal to
// the platform pointer alignment is what's wanted.
static const int s_pointerAlignmentInBits = WTF_ALIGN_OF(void*) == 8 ? 3 : 2;
static const size_t s_pointerAlignmentMask =
(0x1u << s_pointerAlignmentInBits) - 1;
// Represent ranges in 0x100 bitset chunks; bit I is set iff Address
// |m_base + I * (0x1 << s_pointerAlignmentInBits)| has been added to the
// |SparseHeapBitmap|.
static const size_t s_bitmapChunkSize = 0x100;
// A SparseHeapBitmap either contains a single Address or a bitmap
// recording the mapping for [m_base, m_base + s_bitmapChunkRange)
static const size_t s_bitmapChunkRange = s_bitmapChunkSize
<< s_pointerAlignmentInBits;
// Return the number of nodes; for debug stats.
size_t intervalCount() const;
private:
explicit SparseHeapBitmap(Address base) : m_base(base), m_size(1) {
DCHECK(!(reinterpret_cast<uintptr_t>(m_base) & s_pointerAlignmentMask));
static_assert(s_pointerAlignmentMask <= allocationMask,
"address shift exceeds heap pointer alignment");
// For now, only recognize 8 and 4.
static_assert(WTF_ALIGN_OF(void*) == 8 || WTF_ALIGN_OF(void*) == 4,
"unsupported pointer alignment");
}
Address base() const { return m_base; }
size_t size() const { return m_size; }
Address end() const { return base() + (m_size - 1); }
Address maxEnd() const { return base() + s_bitmapChunkRange; }
Address minStart() const {
// If this bitmap node represents the sparse [m_base, s_bitmapChunkRange)
// range, do not allow it to be "left extended" as that would entail
// having to shift down the contents of the std::bitset somehow.
//
// This shouldn't be a real problem as any clusters of set addresses
// will be marked while iterating from lower to higher addresses, hence
// "left extension" are unlikely to be common.
if (m_bitmap)
return base();
return (m_base > reinterpret_cast<Address>(s_bitmapChunkRange))
? (base() - s_bitmapChunkRange + 1)
: nullptr;
}
Address swapBase(Address address) {
DCHECK(!(reinterpret_cast<uintptr_t>(address) & s_pointerAlignmentMask));
Address oldBase = m_base;
m_base = address;
return oldBase;
}
void createBitmap();
Address m_base;
// Either 1 or |s_bitmapChunkRange|.
size_t m_size;
// If non-null, contains a bitmap for addresses within [m_base, m_size)
std::unique_ptr<std::bitset<s_bitmapChunkSize>> m_bitmap;
std::unique_ptr<SparseHeapBitmap> m_left;
std::unique_ptr<SparseHeapBitmap> m_right;
};
} // namespace blink
#endif // SparseHeapBitmap_h
| 1,740 |
407 | <filename>packages/benchmarks/merge-styles/package.json
{
"name": "table-merge-styles-table",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "devServer --package merge-styles",
"build": "devBuild --package merge-styles"
},
"license": "MIT",
"dependencies": {
"benchmarks-utils": "1.0.0",
"@uifabric/merge-styles": "5.12.2"
},
"devDependencies": {
"dev-tasks": "1.0.0"
},
"benchmarks": {
"name": "merge-styles",
"useCSS": true,
"link": "https://github.com/OfficeDev/office-ui-fabric-react/packages/merge-styles"
}
}
| 248 |
7,737 |
extern zend_class_entry *phalcon_mvc_model_transaction_exception_ce;
ZEPHIR_INIT_CLASS(Phalcon_Mvc_Model_Transaction_Exception);
| 52 |
3,084 | <gh_stars>1000+
/*
Copyright (c) Microsoft Corporation All Rights Reserved
Contoso voice activation driver definitions
Hardware manufacturers define identifiers and data structures specific to
their detection technology to pass voice models, keyword data, speaker
data, or any other data relevant to their technology.
*/
//
// Identifier for Contoso keyword configuration data.
//
// {6F7DBCC1-202E-498D-99C5-61C36C4EB2DC}
DEFINE_GUID(CONTOSO_KEYWORDCONFIGURATION_IDENTIFIER, 0x6f7dbcc1, 0x202e, 0x498d, 0x99, 0xc5, 0x61, 0xc3, 0x6c, 0x4e, 0xb2, 0xdc);
// {207F3D0C-5C79-496F-A94C-D3D2934DBFA9}
DEFINE_GUID(CONTOSO_KEYWORDCONFIGURATION_IDENTIFIER2, 0x207f3d0c, 0x5c79, 0x496f, 0xa9, 0x4c, 0xd3, 0xd2, 0x93, 0x4d, 0xbf, 0xa9);
// {A537F559-2D67-463B-B10E-BEB750A21F31}
DEFINE_GUID(CONTOSO_KEYWORD1, 0xa537f559, 0x2d67, 0x463b, 0xb1, 0xe, 0xbe, 0xb7, 0x50, 0xa2, 0x1f, 0x31);
// {655E417A-80A5-4A77-B3F1-512EAF67ABCF}
DEFINE_GUID(CONTOSO_KEYWORD2, 0x655e417a, 0x80a5, 0x4a77, 0xb3, 0xf1, 0x51, 0x2e, 0xaf, 0x67, 0xab, 0xcf);
//
// The format of the Contoso keyword pattern matching data.
//
typedef struct
{
SOUNDDETECTOR_PATTERNHEADER Header;
LONGLONG ContosoDetectorConfigurationData;
} CONTOSO_KEYWORDCONFIGURATION;
//
// The format of the Contoso match result data.
//
typedef struct
{
SOUNDDETECTOR_PATTERNHEADER Header;
LONGLONG ContosoDetectorResultData;
ULONGLONG KeywordStartTimestamp;
ULONGLONG KeywordStopTimestamp;
GUID EventId;
} CONTOSO_KEYWORDDETECTIONRESULT;
| 825 |
376 | <reponame>gogo2464/NazaraEngine
// Copyright (C) 2020 <NAME>
// This file is part of the "Nazara Engine - Vulkan Renderer"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/VulkanRenderer/VulkanUploadPool.hpp>
#include <Nazara/VulkanRenderer/Debug.hpp>
namespace Nz
{
inline VulkanUploadPool::VulkanUploadPool(Vk::Device& device, UInt64 blockSize) :
m_blockSize(blockSize),
m_device(device),
m_nextAllocationIndex(0)
{
}
}
#include <Nazara/VulkanRenderer/DebugOff.hpp>
| 189 |
841 | /*
* Copyright 2021 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.process.workitem.core.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.jbpm.process.workitem.core.util.WorkItemHeaderInfo.Builder;
import org.kie.api.runtime.process.WorkItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WorkItemHeaderUtils {
private WorkItemHeaderUtils() {}
private static final String CONTENT_PREFIX = "HEADER_";
private static final String PARAM_PREFIX = "HEADER_PARAM_";
static final String SEPARATOR_PROP = "org.kie.workitem.ws.header.separator";
private static final Logger logger = LoggerFactory.getLogger(WorkItemHeaderUtils.class);
public static Collection<WorkItemHeaderInfo> getHeaderInfo(WorkItem workItem) {
final String separator = System.getProperty(SEPARATOR_PROP, "_");
Map<String, WorkItemHeaderInfo.Builder> map = new HashMap<>();
for (Entry<String, Object> param : workItem.getParameters().entrySet()) {
String key = param.getKey().toUpperCase();
if (key.startsWith(PARAM_PREFIX)) {
key = param.getKey().substring(PARAM_PREFIX.length());
int indexOf = key.indexOf(separator);
if (indexOf != -1) {
map.computeIfAbsent(key.substring(indexOf + separator.length()), Builder::of)
.withParam(key.substring(0, indexOf), param.getValue());
} else {
logger.warn("Wrong parameter name {}. It expects at least one {} in {}", param.getKey(), separator,
key);
}
} else if (key.startsWith(CONTENT_PREFIX)) {
map.computeIfAbsent(param.getKey().substring(CONTENT_PREFIX.length()), Builder::of)
.withContent(param.getValue());
}
}
return map.values().stream().map(Builder::build).collect(Collectors.toList());
}
}
| 1,025 |
325 |
"""
This package contains implementations of initialization methods for matrix factorization.
"""
from .nndsvd import *
from .random import *
from .fixed import *
from .random_c import *
from .random_vcol import *
methods = {"random": Random,
"fixed": Fixed,
"nndsvd": Nndsvd,
"random_c": Random_c,
"random_vcol": Random_vcol,
"none": None}
| 170 |
521 | <reponame>Fimbure/icebox-1
/* xf86DDC.h
*
* This file contains all information to interpret a standard EDIC block
* transmitted by a display device via DDC (Display Data Channel). So far
* there is no information to deal with optional EDID blocks.
* DDC is a Trademark of VESA (Video Electronics Standard Association).
*
* Copyright 1998 by <NAME> <<EMAIL>>
*/
#ifndef XF86_DDC_H
# define XF86_DDC_H
#include "edid.h"
#include "xf86i2c.h"
#include "xf86str.h"
/* speed up / slow down */
typedef enum {
DDC_SLOW,
DDC_FAST
} xf86ddcSpeed;
typedef void (* DDC1SetSpeedProc)(ScrnInfoPtr, xf86ddcSpeed);
extern xf86MonPtr xf86DoEDID_DDC1(
int scrnIndex,
DDC1SetSpeedProc DDC1SetSpeed,
unsigned int (*DDC1Read)(ScrnInfoPtr)
);
extern xf86MonPtr xf86DoEDID_DDC2(
int scrnIndex,
I2CBusPtr pBus
);
extern xf86MonPtr xf86DoEEDID(int scrnIndex, I2CBusPtr pBus, Bool);
extern xf86MonPtr xf86PrintEDID(
xf86MonPtr monPtr
);
extern xf86MonPtr xf86InterpretEDID(
int screenIndex, Uchar *block
);
extern xf86MonPtr xf86InterpretEEDID(
int screenIndex, Uchar *block
);
extern void
xf86DDCMonitorSet(int scrnIndex, MonPtr Monitor, xf86MonPtr DDC);
extern Bool xf86SetDDCproperties(
ScrnInfoPtr pScreen,
xf86MonPtr DDC
);
DisplayModePtr xf86DDCGetModes(int scrnIndex, xf86MonPtr DDC);
extern Bool
xf86MonitorIsHDMI(xf86MonPtr mon);
#endif
| 580 |
4,054 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
* This conformance test class has been created in order to run the same tests
* on multiple implementations of the persistence SPI.
*
* To run conformance tests on a given implementation, just add a little wrapper
* such as the dummy persistence implementation does. (See dummyimpltest.cpp)
*/
#pragma once
#include <vespa/persistence/spi/persistenceprovider.h>
#include <gtest/gtest.h>
namespace document
{
class DocumentTypeRepo;
class TestDocMan;
}
namespace document::internal { class InternalDocumenttypesType; }
namespace storage::spi {
class ConformanceTest : public ::testing::Test {
public:
using PersistenceProviderUP = std::unique_ptr<PersistenceProvider>;
struct PersistenceFactory {
typedef std::unique_ptr<PersistenceFactory> UP;
using DocumenttypesConfig = const document::internal::InternalDocumenttypesType;
virtual ~PersistenceFactory() = default;
virtual PersistenceProviderUP getPersistenceImplementation(
const std::shared_ptr<const document::DocumentTypeRepo> &repo,
const DocumenttypesConfig &typesCfg) = 0;
virtual void
clear(void)
{
// clear persistent state, i.e. remove files/directories
}
virtual bool
hasPersistence(void) const
{
return false;
}
virtual bool
supportsActiveState() const
{
return false;
}
virtual bool
supportsRemoveEntry() const
{
return false;
}
// If bucket spaces are supported then testdoctype2 is in bucket space 1
virtual bool supportsBucketSpaces() const { return false; }
};
// Set by test runner.
static std::unique_ptr<PersistenceFactory>(*_factoryFactory)(const std::string &docType);
protected:
PersistenceFactory::UP _factory;
void populateBucket(const Bucket& b,
PersistenceProvider& spi,
Context& context,
uint32_t from,
uint32_t to,
document::TestDocMan& testDocMan);
void
testDeleteBucketPostCondition(const PersistenceProvider &spi,
const Bucket &bucket,
const Document &doc1);
void
testSplitNormalCasePostCondition(const PersistenceProvider &spi,
const Bucket &bucketA,
const Bucket &bucketB,
const Bucket &bucketC,
document::TestDocMan &testDocMan);
void
testSplitTargetExistsPostCondition(const PersistenceProvider &spi,
const Bucket &bucketA,
const Bucket &bucketB,
const Bucket &bucketC,
document::TestDocMan &testDocMan);
void
testSplitSingleDocumentInSourcePostCondition(
const PersistenceProvider& spi,
const Bucket& source,
const Bucket& target1,
const Bucket& target2,
document::TestDocMan& testDocMan);
void
createAndPopulateJoinSourceBuckets(
PersistenceProvider& spi,
const Bucket& source1,
const Bucket& source2,
document::TestDocMan& testDocMan);
void
doTestJoinNormalCase(const Bucket& source1,
const Bucket& source2,
const Bucket& target);
void
testJoinNormalCasePostCondition(const PersistenceProvider &spi,
const Bucket &bucketA,
const Bucket &bucketB,
const Bucket &bucketC,
document::TestDocMan &testDocMan);
void
testJoinTargetExistsPostCondition(const PersistenceProvider &spi,
const Bucket &bucketA,
const Bucket &bucketB,
const Bucket &bucketC,
document::TestDocMan &testDocMan);
void
testJoinOneBucketPostCondition(const PersistenceProvider &spi,
const Bucket &bucketA,
const Bucket &bucketC,
document::TestDocMan &testDocMan);
void
doTestJoinSameSourceBuckets(const Bucket& source,
const Bucket& target);
void
testJoinSameSourceBucketsPostCondition(
const PersistenceProvider& spi,
const Bucket& source,
const Bucket& target,
document::TestDocMan& testDocMan);
void
testJoinSameSourceBucketsTargetExistsPostCondition(
const PersistenceProvider& spi,
const Bucket& source,
const Bucket& target,
document::TestDocMan& testDocMan);
ConformanceTest();
ConformanceTest(const std::string &docType);
};
class SingleDocTypeConformanceTest : public ConformanceTest
{
protected:
SingleDocTypeConformanceTest();
};
}
| 2,567 |
421 | <filename>samples/snippets/cpp/VS_Snippets_CLR_Classic/classic Debug.Listeners Example/CPP/source.cpp
#using <System.dll>
using namespace System;
using namespace System::Diagnostics;
int main( void )
{
//<Snippet1>
// Create a listener that outputs to the console screen
// and add it to the debug listeners.
#if defined(DEBUG)
TextWriterTraceListener^ myWriter =
gcnew TextWriterTraceListener( System::Console::Out );
Debug::Listeners->Add( myWriter );
#endif
//</Snippet1>
}
| 198 |
892 | <reponame>westonsteimel/advisory-database-github
{
"schema_version": "1.2.0",
"id": "GHSA-5fq8-p5p9-5g3g",
"modified": "2022-04-10T00:01:13Z",
"published": "2022-04-02T00:00:16Z",
"aliases": [
"CVE-2021-35103"
],
"details": "Possible out of bound write due to improper validation of number of timer values received from firmware while syncing timers in Snapdragon Auto, Snapdragon Compute, Snapdragon Connectivity, Snapdragon Industrial IOT, Snapdragon Mobile, Snapdragon Wearables, Snapdragon Wired Infrastructure and Networking",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:L/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-2021-35103"
},
{
"type": "WEB",
"url": "https://www.qualcomm.com/company/product-security/bulletins/march-2022-bulletin"
}
],
"database_specific": {
"cwe_ids": [
"CWE-787"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 467 |
528 | /******************************************************************************
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/FpsCounter.h
FPS counter calculates frame time duration with moving average window algorithm.
******************************************************************************/
#pragma once
#include <Methane/Timer.hpp>
#include <cmath>
#include <queue>
namespace Methane::Graphics
{
class FpsCounter
{
public:
class FrameTiming
{
public:
FrameTiming() = default;
FrameTiming(const FrameTiming&) noexcept = default;
FrameTiming(double total_time_sec, double present_time_sec, double gpu_wait_time_sec) noexcept;
[[nodiscard]] double GetTotalTimeSec() const noexcept { return m_total_time_sec; }
[[nodiscard]] double GetPresentTimeSec() const noexcept { return m_present_time_sec; }
[[nodiscard]] double GetGpuWaitTimeSec() const noexcept { return m_gpu_wait_time_sec; }
[[nodiscard]] double GetCpuTimeSec() const noexcept { return m_total_time_sec - m_present_time_sec - m_gpu_wait_time_sec; }
[[nodiscard]] double GetTotalTimeMSec() const noexcept { return m_total_time_sec * 1000.0; }
[[nodiscard]] double GetPresentTimeMSec() const noexcept{ return m_present_time_sec * 1000.0; }
[[nodiscard]] double GetGpuWaitTimeMSec() const noexcept{ return m_gpu_wait_time_sec * 1000.0; }
[[nodiscard]] double GetCpuTimeMSec() const noexcept { return GetCpuTimeSec() * 1000.0; }
[[nodiscard]] double GetCpuTimePercent() const noexcept { return 100.0 * GetCpuTimeSec() / GetTotalTimeSec(); }
FrameTiming& operator=(const FrameTiming& other) noexcept = default;
FrameTiming& operator+=(const FrameTiming& other) noexcept;
FrameTiming& operator-=(const FrameTiming& other) noexcept;
FrameTiming operator/(double divisor) const noexcept;
FrameTiming operator*(double multiplier) const noexcept;
private:
double m_total_time_sec = 0.0;
double m_present_time_sec = 0.0;
double m_gpu_wait_time_sec = 0.0;
};
FpsCounter() = default;
explicit FpsCounter(uint32_t averaged_timings_count) noexcept : m_averaged_timings_count(averaged_timings_count) { }
void Reset(uint32_t averaged_timings_count) noexcept;
void OnGpuFramePresentWait() noexcept { m_present_timer.Reset(); }
void OnCpuFrameReadyToPresent() noexcept { m_present_timer.Reset(); }
void OnGpuFramePresented() noexcept { m_present_on_gpu_wait_time_sec = m_present_timer.GetElapsedSecondsD(); }
void OnCpuFramePresented() noexcept;
[[nodiscard]] uint32_t GetAveragedTimingsCount() const noexcept { return static_cast<uint32_t>(m_frame_timings.size()); }
[[nodiscard]] FrameTiming GetAverageFrameTiming() const noexcept;
[[nodiscard]] uint32_t GetFramesPerSecond() const noexcept;
private:
void ResetPresentTimer() noexcept;
Timer m_frame_timer;
Timer m_present_timer;
double m_present_on_gpu_wait_time_sec = 0.0;
uint32_t m_averaged_timings_count = 100;
FrameTiming m_frame_timings_sum;
std::queue<FrameTiming> m_frame_timings;
};
} // namespace Methane::Graphics
| 1,413 |
577 | <reponame>sgycup/aparapi
/**
* Copyright (c) 2016 - 2018 Syncleus, 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.
*/
/*
Copyright (c) 2010-2011, Advanced Micro Devices, 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 the copyright holder nor the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
If you use the software (in whole or in part), you shall adhere to all applicable U.S., European, and other export
laws, including but not limited to the U.S. Export Administration Regulations ("EAR"), (15 C.F.R. Sections 730 through
774), and E.U. Council Regulation (EC) No 1334/2000 of 22 June 2000. Further, pursuant to Section 740.6 of the EAR,
you hereby certify that, except pursuant to a license granted by the United States Department of Commerce Bureau of
Industry and Security or as otherwise permitted pursuant to a License Exception under the U.S. Export Administration
Regulations ("EAR"), you will not (1) export, re-export or release to a national of a country in Country Groups D:1,
E:1 or E:2 any restricted technology, software, or source code you receive hereunder, or (2) export to Country Groups
D:1, E:1 or E:2 the direct product of such technology or software, if such foreign produced direct product is subject
to national security controls as identified on the Commerce Control List (currently found in Supplement 1 to Part 774
of EAR). For the most current Country Group listings, or for additional information about the EAR or your obligations
under those regulations, please refer to the U.S. Bureau of Industry and Security's website at http://www.bis.doc.gov/.
*/
package com.aparapi.codegen;
import org.junit.Ignore;
import org.junit.Test;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class CreateJUnitTest {
@Ignore("We will probably never use this, it just generates test. We probably want to do this by hand.")
@Test
public void test() throws ClassNotFoundException, FileNotFoundException, IOException {
File rootDir = new File(System.getProperty("root", "."));
String rootPackageName = CreateJUnitTest.class.getPackage().getName();
String testPackageName = rootPackageName + ".test";
File sourceDir = new File(rootDir, "src/test/java");
System.out.println(sourceDir.getCanonicalPath());
File testDir = new File(sourceDir, testPackageName.replace(".", "/"));
System.out.println(testDir.getCanonicalPath());
List<String> classNames = new ArrayList<String>();
for (File sourceFile : testDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return (name.endsWith(".java"));
}
})) {
String fileName = sourceFile.getName();
String className = fileName.substring(0, fileName.length() - ".java".length());
classNames.add(className);
}
File genSourceDir = new File(rootDir, "src/genjava");
File codeGenDir = new File(genSourceDir, rootPackageName.replace(".", "/") + "/test/junit/codegen/");
codeGenDir.mkdirs();
for (String className : classNames) {
Source source = new Source(Class.forName(testPackageName + "." + className), sourceDir);
final String testName = className + "Test";
StringBuilder sb = new StringBuilder();
sb.append("package com.codegen.test.junit.codegen;\n");
sb.append("import org.junit.Test;\n");
String doc = source.getDocString();
if (doc.length() > 0) {
sb.append("/**\n");
sb.append(doc);
sb.append("\n */\n");
}
sb.append("public class " + testName + " extends com.codegen.CodeGenJUnitBase{\n");
appendExpectedOpenCL(source, sb);
appendExpectedExceptions(source, sb);
appendTest(testPackageName, testName, "", sb);
appendTest(testPackageName, testName, "WorksWithCaching", sb);
sb.append("}\n");
// System.out.println(sb.toString());
File generatedFile = new File(codeGenDir, testName + ".java");
PrintStream out = new PrintStream(generatedFile);
out.append(sb.toString());
out.close();
}
}
private static void appendTest(String testPackageName, String className, String suffix, StringBuilder sb) {
sb.append(" @Test public void " + className + suffix + "(){\n");
sb.append(" test(" + testPackageName + "." + className + ".class, expectedException, expectedOpenCL);\n");
sb.append(" }\n");
}
private static void appendExpectedExceptions(Source source, StringBuilder sb) {
String exceptions = source.getExceptionsString();
if (exceptions.length() > 0) {
sb.append(" private static final Class<? extends com.codegen.internal.exception.AparapiException> expectedException = ");
sb.append("com.codegen.internal.exception." + exceptions + ".class");
sb.append(";\n");
} else {
sb.append(" private static final Class<? extends com.codegen.internal.exception.AparapiException> expectedException = null;\n");
}
}
private static void appendExpectedOpenCL(Source source, StringBuilder sb) {
if (source.getOpenCLSectionCount() > 0) {
sb.append(" private static final String[] expectedOpenCL = new String[]{\n");
for (List<String> opencl : source.getOpenCL()) {
sb.append(" \"\"\n");
for (String line : opencl) {
sb.append(" +\"" + line + "\\n\"\n");
}
sb.append(" ,\n");
}
sb.append(" };\n");
} else {
sb.append(" private static final String[] expectedOpenCL = null;\n");
}
}
}
| 2,760 |
452 | /*-------------------------------------------------------------------------
*
* pg_replication_origin_d.h
* Macro definitions for pg_replication_origin
*
* Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* NOTES
* ******************************
* *** DO NOT EDIT THIS FILE! ***
* ******************************
*
* It has been GENERATED by src/backend/catalog/genbki.pl
*
*-------------------------------------------------------------------------
*/
#ifndef PG_REPLICATION_ORIGIN_D_H
#define PG_REPLICATION_ORIGIN_D_H
#define ReplicationOriginRelationId 6000
#define Anum_pg_replication_origin_roident 1
#define Anum_pg_replication_origin_roname 2
#define Natts_pg_replication_origin 2
#endif /* PG_REPLICATION_ORIGIN_D_H */
| 250 |
66,985 | <gh_stars>1000+
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.metrics.annotation;
import java.lang.reflect.Method;
import java.util.Set;
import io.micrometer.core.annotation.Timed;
import org.junit.jupiter.api.Test;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link TimedAnnotations}.
*
* @author <NAME>
*/
class TimedAnnotationsTests {
@Test
void getWhenNoneReturnsEmptySet() {
Object bean = new None();
Method method = ReflectionUtils.findMethod(bean.getClass(), "handle");
Set<Timed> annotations = TimedAnnotations.get(method, bean.getClass());
assertThat(annotations).isEmpty();
}
@Test
void getWhenOnMethodReturnsMethodAnnotations() {
Object bean = new OnMethod();
Method method = ReflectionUtils.findMethod(bean.getClass(), "handle");
Set<Timed> annotations = TimedAnnotations.get(method, bean.getClass());
assertThat(annotations).extracting(Timed::value).containsOnly("y", "z");
}
@Test
void getWhenNonOnMethodReturnsBeanAnnotations() {
Object bean = new OnBean();
Method method = ReflectionUtils.findMethod(bean.getClass(), "handle");
Set<Timed> annotations = TimedAnnotations.get(method, bean.getClass());
assertThat(annotations).extracting(Timed::value).containsOnly("y", "z");
}
static class None {
void handle() {
}
}
@Timed("x")
static class OnMethod {
@Timed("y")
@Timed("z")
void handle() {
}
}
@Timed("y")
@Timed("z")
static class OnBean {
void handle() {
}
}
}
| 709 |
1,587 | /**
*
*/
package io.pratik.dynamodbspring.models;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
/**
* @author pratikdas
*
*/
@DynamoDBTable(tableName = "Customer")
public class Customer {
private String customerID;
private String name;
private String email;
// Partition key
@DynamoDBHashKey(attributeName = "CustomerID")
public String getCustomerID() {
return customerID;
}
public void setCustomerID(String customerID) {
this.customerID = customerID;
}
@DynamoDBAttribute(attributeName = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@DynamoDBAttribute(attributeName = "Email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| 361 |
32,544 | <filename>spring-cloud/spring-cloud-bootstrap/customer-service/src/main/java/com/baeldung/customerservice/CustomerService.java
package com.baeldung.customerservice;
import com.baeldung.orderservice.client.OrderClient;
import com.baeldung.orderservice.client.OrderDTO;
import com.baeldung.orderservice.client.OrderResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@RestController
public class CustomerService {
@Autowired
private OrderClient orderClient;
private List<Customer> customers = Arrays.asList(
new Customer(1, "John", "Smith"),
new Customer(2, "Deny", "Dominic"));
@GetMapping
public List<Customer> getAllCustomers() {
return customers;
}
@GetMapping("/{id}")
public Customer getCustomerById(@PathVariable int id) {
return customers.stream()
.filter(customer -> customer.getId() == id)
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
@PostMapping(value = "/order")
public String sendOrder(@RequestBody Map<String, Object> body) {
OrderDTO dto = new OrderDTO();
dto.setCustomerId((Integer) body.get("customerId"));
dto.setItemId((String) body.get("itemId"));
OrderResponse response = orderClient.order(dto);
return response.getStatus();
}
} | 654 |
1,401 | <filename>v1/code/java/example/src/main/java/jvmgo/book/ch08/MultianewarrayDemo.java
package jvmgo.book.ch08;
public class MultianewarrayDemo {
public static void main(String[] args) {
new MultianewarrayDemo().test();
}
public void test() {
int[][][] x = new int[3][4][5];
}
}
| 136 |
2,479 | <filename>tools/third_party/websockets/example/unix_server.py
#!/usr/bin/env python
# WS server example listening on a Unix socket
import asyncio
import os.path
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
socket_path = os.path.join(os.path.dirname(__file__), "socket")
start_server = websockets.unix_serve(hello, socket_path)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
| 220 |
318 | <filename>src/main/resources/data/techreborn/recipes/chemical_reactor/synthetic_redstone_crystal.json
{
"type": "techreborn:chemical_reactor",
"power": 50,
"time": 1200,
"ingredients": [
{
"item": "minecraft:redstone",
"count": 32
},
{
"item": "minecraft:diamond"
}
],
"results": [
{
"item": "techreborn:synthetic_redstone_crystal"
}
]
}
| 167 |
351 | /**
* > Author: UncP
* > Github: www.github.com/UncP/Mushroom
* > License: BSD-3
* > Time: 2016-11-20 12:37:41
**/
#include <cassert>
#include <chrono>
#include <fcntl.h>
#include <unistd.h>
#include "../src/blink/slice.hpp"
#include "../src/blink/db.hpp"
#include "../src/blink/task.hpp"
#include "../src/blink/bounded_mapping_queue.hpp"
#include "../src/blink/thread_pool_mapping.hpp"
using namespace Mushroom;
static const int key_len = 16;
static int total;
double Do(const char *file, MushroomDB *db, bool (MushroomDB::*(fun))(KeySlice *))
{
BoundedMappingQueue<MushroomTask> *queue = new BoundedMappingQueue<MushroomTask>(1024, []() {
return new MushroomTask();
});
ThreadPoolMapping<MushroomTask> pool(queue, 4);
TempSlice(key);
int fd = open(file, O_RDONLY);
assert(fd > 0);
char buf[8192];
int curr = 0, ptr = 0, count = 0;
bool flag = true;
auto beg = std::chrono::high_resolution_clock::now();
for (; (ptr = pread(fd, buf, 8192, curr)) > 0 && flag; curr += ptr) {
while (--ptr && buf[ptr] != '\n' && buf[ptr] != '\0') buf[ptr] = '\0';
if (ptr) buf[ptr++] = '\0';
else break;
for (int i = 0; i < ptr; ++i) {
char *tmp = buf + i;
i += key_len;
assert(buf[i] == '\n' || buf[i] == '\0');
buf[i] = '\0';
key->page_no_ = 0;
memcpy(key->key_, tmp, key_len);
MushroomTask *task = queue->Get();
task->Assign(fun, db, key);
queue->Push();
if (++count == total) {
flag = false;
break;
}
}
}
close(fd);
pool.Clear();
delete queue;
auto end = std::chrono::high_resolution_clock::now();
auto t = std::chrono::duration<double, std::ratio<1>>(end - beg).count();
return t;
}
int main(int argc, char **argv)
{
const char *file = "../data/10000000";
assert(argc > 4);
uint32_t page_size = atoi(argv[1]) ? atoi(argv[1]) : 4096;
uint32_t pool_size = atoi(argv[2]) ? atoi(argv[2]) : 4800;
uint32_t hash_bits = atoi(argv[3]) ? atoi(argv[3]) : 10;
uint32_t seg_bits = atoi(argv[4]) ? atoi(argv[4]) : 4;
total = (argc == 6) ? atoi(argv[5]) : 1;
MushroomDB db("mushroom_test", key_len, page_size, pool_size, hash_bits, seg_bits);
double t1 = Do(file, &db, &MushroomDB::Put);
double t2 = Do(file, &db, &MushroomDB::Get);
db.Close();
printf("\033[31mtotal: %d\033[0m\n\033[32mput time: %f s\033[0m\n", total, t1);
printf("\033[34mget time: %f s\033[0m\n", t2);
return 0;
}
| 1,096 |
1,088 | # Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
"""SubGraph based GAT convolutional layer"""
import tensorflow as tf
from graphlearn.python.nn.tf.config import conf
from graphlearn.python.nn.tf.layers.sub_conv import SubConv
from graphlearn.python.nn.tf.utils.softmax import unsorted_segment_softmax
class GATConv(SubConv):
"""multi-head GAT convolutional layer.
"""
def __init__(self,
out_dim,
num_heads=1,
concat=False,
dropout=0.0,
use_bias=False,
name=''):
self._out_dim = out_dim
self._num_heads = num_heads
self._concat = concat
self._dropout = dropout
self._bias = use_bias
self._name = name
self._vars = {}
with tf.variable_scope(self._name + '/' + 'layer',
reuse=tf.AUTO_REUSE):
self._vars['attn_src'] = \
tf.get_variable(shape=[1, self._num_heads, self._out_dim],
name='attention_weights_src')
self._vars['attn_dst'] = \
tf.get_variable(shape=[1, self._num_heads, self._out_dim],
name='attention_weights_dst')
self._linear = \
tf.keras.layers.Dense(units=self._num_heads*self._out_dim,
use_bias=False,
name=name + 'w')
if self._bias:
if self._concat:
self._vars['bias'] =\
tf.Variable(tf.zeros([self._out_dim], dtype=tf.float32),
name='bias')
else:
self._vars['bias'] =\
tf.Variable(tf.zeros([self._num_heads * self._out_dim], dtype=tf.float32),
name='bias')
def forward(self, edge_index, node_vec, **kwargs):
"""
Multi-head attention coefficients are computed as following:
1.compute W*h_i(node_vec) using self._linear(node_vec).
2.compute src_e and dst_e individually using 'attn_src' and 'attn_dst'
3.add src_e and dst_e as e_ij and apply LeakyReLU.
4.compute alpha_ij using unsorted_segment_softmax.
Args:
edge_index: A Tensor. Edge index of subgraph.
node_vec: A Tensor. Node feature embeddings with shape
[batch_size, dim].
Returns:
A Tensor. Output embedding with shape [batch_size, output_dim].
"""
num_nodes = tf.shape(node_vec)[0]
# add self-loop.
diagnal_edge_index = tf.stack([tf.range(num_nodes, dtype=tf.int32)] * 2, axis=0)
edge_index = tf.concat([edge_index, diagnal_edge_index], axis=1)
# [batch_size, num_heads, output_dim]
src_h = dst_h = tf.reshape(self._linear(node_vec),
[-1, self._num_heads, self._out_dim])
# When computing attention coefficients alpha, the GAT concatenates src_h
# and dst_h at first. Here we first compute src_e and dst_e individually,
# and then add them as final coefficients in order to reduce memory usage.
# [batch_size, num_heads]
src_e = tf.reduce_sum(src_h * self._vars['attn_src'], axis=-1)
dst_e = tf.reduce_sum(dst_h * self._vars['attn_dst'], axis=-1)
# [num_edges, num_heads]
src_e = tf.gather(src_e, edge_index[0])
dst_e = tf.gather(dst_e, edge_index[1])
e = tf.nn.leaky_relu(src_e + dst_e)
alpha = unsorted_segment_softmax(e, edge_index[0], num_nodes)
if self._dropout and conf.training:
alpha = tf.nn.dropout(alpha, 1 - self._dropout)
# [num_edges, num_heads, output_dim]
nbr_input = tf.gather(dst_h, edge_index[1])
alpha = tf.tile(tf.expand_dims(alpha, axis=2),
[1, 1, self._out_dim])
# [batch_size, num_heads, output_dim]
out = tf.math.unsorted_segment_sum(nbr_input * alpha,
edge_index[0],
num_nodes)
if self._concat:
out = tf.concat(tf.split(out, self._num_heads, axis=1), axis=1)
else:
out = tf.reduce_mean(out, axis=1)
if self._bias:
out += self._vars['bias']
return out
| 2,101 |
1,056 | <filename>php/php.atoum/src/org/netbeans/modules/php/atoum/run/TapParser.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.php.atoum.run;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.netbeans.modules.php.spi.testing.run.TestCase;
public final class TapParser {
private static enum State {
OK,
OK_SKIP,
NOT_OK,
}
static final Logger LOGGER = Logger.getLogger(TapParser.class.getName());
private static final Pattern FILE_LINE_PATTERN = Pattern.compile("(.+):(\\d+)"); // NOI18N
private static final Pattern SUITE_TEST_PATTERN = Pattern.compile("([^:\\s]+)::([^\\(]+)\\(\\)"); // NOI18N
private final List<TestSuiteVo> testSuites = new ArrayList<>();
private final List<String> commentLines = new ArrayList<>();
private TestSuiteVo testSuite = null;
private TestCaseVo testCase = null;
private int testCaseCount = 0;
private State state = null;
public TapParser() {
}
public static boolean isTestCaseStart(String line) {
return line.startsWith("ok ") // NOI18N
|| line.startsWith("not ok "); // NOI18N
}
public List<TestSuiteVo> parse(String input, long runtime) {
for (String line : input.split("\\r?\\n|\\r")) { // NOI18N
parseLine(line.trim());
}
processNotOkLines();
setTimes(runtime);
return testSuites;
}
private void parseLine(String line) {
if (line.startsWith("1..")) { // NOI18N
return;
}
if (line.startsWith("ok ")) { // NOI18N
processNotOkLines();
assert state == null : state;
if (checkSkipped(line)) {
state = State.OK_SKIP;
testCase.setStatus(TestCase.Status.SKIPPED);
} else {
state = State.OK;
testCase = null;
}
} else if (line.startsWith("not ok ")) { // NOI18N
processNotOkLines();
assert state == null : state;
state = State.NOT_OK;
setSuiteTest(line);
testCase.setStatus(TestCase.Status.FAILED);
checkTodo(line);
} else {
processComment(line);
}
}
private boolean checkSkipped(String line) {
assert state == null : state;
if (line.contains("# SKIP ")) { // NOI18N
setSuiteTest(line);
return true;
}
return false;
}
private void checkTodo(String line) {
assert state == State.NOT_OK : state;
if (line.contains("# TODO ")) { // NOI18N
testCase.setStatus(TestCase.Status.PENDING);
}
}
private void processComment(String line) {
assert line.startsWith("#") : line;
line = line.substring(1).trim();
switch (state) {
case OK:
setSuiteTest(line);
testCase.setStatus(TestCase.Status.PASSED);
state = null;
break;
case OK_SKIP:
commentLines.add(line);
break;
case NOT_OK:
commentLines.add(line);
break;
default:
assert false : "Unknown state: " + state;
}
}
private void processNotOkLines() {
if (commentLines.isEmpty()) {
return;
}
assert testCase != null;
// last line
int lastIndex = commentLines.size() - 1;
String lastLine = commentLines.get(lastIndex);
if (setFileLine(lastLine)) {
commentLines.remove(lastIndex);
} else {
// XXX
// aborted test
if (lastLine.toLowerCase().endsWith(".php")) { // NOI18N
// php file
commentLines.remove(lastIndex);
testCase.setFile(lastLine);
}
if (testCase.getStatus() == TestCase.Status.FAILED) {
testCase.setStatus(TestCase.Status.ERROR);
}
}
// rest
StringBuilder message = null;
List<String> stackTrace = new ArrayList<>();
while (!commentLines.isEmpty()) {
String firstLine = commentLines.get(0);
commentLines.remove(0);
if (firstLine.equals("Stack trace:")) { // NOI18N
testCase.setStatus(TestCase.Status.ERROR);
stackTrace.addAll(processStackTrace(commentLines));
commentLines.clear();
} else if (firstLine.equals("-Reference") // NOI18N
|| firstLine.equals("-Expected")) { // NOI18N
processDiff(commentLines);
commentLines.clear();
} else {
if (message == null) {
message = new StringBuilder(200);
}
if (message.length() > 0) {
// unfortunately, \n not supported in the ui
message.append("; "); // NOI18N
}
message.append(firstLine);
}
}
String msg = null;
if (message != null) {
msg = message.toString();
testCase.setMessage(msg);
}
// append file with line number
// XXX remove if once aborted method contains file with line number as well
if (!lastLine.equals(msg)) {
stackTrace.add(lastLine);
}
testCase.setStackTrace(stackTrace);
// reset
state = null;
}
private List<String> processStackTrace(List<String> lines) {
List<String> stackTrace = new ArrayList<>(lines.size());
for (String line : lines) {
assert line.startsWith("#") : line;
stackTrace.add(line.substring(3));
}
return stackTrace;
}
private void processDiff(List<String> lines) {
StringBuilder diffExpected = new StringBuilder(200);
StringBuilder diffActual = new StringBuilder(200);
boolean diff = false;
for (String line : lines) {
if (line.startsWith("@@")) { // NOI18N
diff = true;
continue;
}
if (!diff) {
continue;
}
if (line.startsWith("+")) { // NOI18N
if (diffActual.length() > 0) {
diffActual.append("\n"); // NOI18N
}
diffActual.append(line.substring(1));
} else if (line.startsWith("-")) {
if (diffExpected.length() > 0) {
diffExpected.append("\n"); // NOI18N
}
diffExpected.append(line.substring(1));
} else {
// unknown line?
LOGGER.log(Level.INFO, "Unexpected DIFF line {0}", line);
}
}
testCase.setDiff(new TestCase.Diff(diffExpected.toString(), diffActual.toString()));
}
private void setSuiteTest(String line) {
Matcher matcher = SUITE_TEST_PATTERN.matcher(line);
boolean found = matcher.find();
assert found : line;
String suiteName = matcher.group(1);
String testName = matcher.group(2);
if (testSuite == null
|| !testSuite.getName().equals(suiteName)) {
testSuite = new TestSuiteVo(suiteName);
testSuites.add(testSuite);
}
assert testSuite != null;
assert suiteName.equals(testSuite.getName()) : testSuite;
testCase = new TestCaseVo(testName);
testSuite.addTestCase(testCase);
testCaseCount++;
}
private boolean setFileLine(String line) {
Matcher matcher = FILE_LINE_PATTERN.matcher(line);
if (!matcher.matches()) {
return false;
}
assert testCase != null;
String file = matcher.group(1);
String fileLine = matcher.group(2);
assert file != null : line;
testCase.setFile(file);
assert fileLine != null : line;
testCase.setLine(Integer.parseInt(fileLine));
return true;
}
private void setTimes(long runtime) {
long time = 0;
if (testCaseCount > 0) {
time = runtime / testCaseCount;
}
for (TestSuiteVo suite : testSuites) {
for (TestCaseVo kase : suite.getTestCases()) {
kase.setTime(time);
}
}
}
}
| 4,459 |
656 | #define LIBRG_IMPL
#include "librg.h"
#if !defined(LIBRG_LIBRARY_NOMAIN) && !defined(LIBRG_EMSCRIPTEN)
int main() {return 0;}
#endif
| 59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.