max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
1,160 | from pyglet.media import instrumentation as ins
def test_no_unknown_state_fields_in_mp_events():
all_fields = ins.MediaPlayerStateIterator.fields.keys()
ok = True
for evname in ins.mp_events:
if evname == "version":
continue
for name in ins.mp_events[evname]["update_names"]:
if name not in all_fields:
print("Error, in evname '%s' unknown field '%s' in 'update_names'" % (evname, name))
ok = False
for name in ins.mp_events[evname]["other_fields"]:
if name not in all_fields:
print("Error, in evname '%s' unknown field '%s' in 'other_fields'" % (evname, name))
ok = False
if ok:
print("test_no_unknown_state_fields_in_mp_events: passed")
def test_evname_in_mp_events_testcases():
ok = True
for evname in ins.mp_events:
if evname == "version":
continue
for i, args in enumerate(ins.mp_events[evname]["test_cases"]):
if evname != args[0]:
msg = "Error, for evname %s the testase #%d does not match evname"
print(msg % (evname, i))
ok = False
if ok:
print("test_evname_in_mp_events_testcases: passed")
test_no_unknown_state_fields_in_mp_events()
test_evname_in_mp_events_testcases()
| 627 |
324 | <filename>scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ruby/InstallRubyGems.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.jclouds.scriptbuilder.statements.ruby;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.scriptbuilder.domain.Statements.exec;
import static org.jclouds.scriptbuilder.domain.Statements.extractTargzAndFlattenIntoDirectory;
import java.net.URI;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.scriptbuilder.domain.OsFamily;
import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.scriptbuilder.domain.StatementList;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
/**
* Installs RubyGems onto a host.
*/
public class InstallRubyGems implements Statement {
public static final String DEFAULT_RUBYGEMS_VERSION = "1.8.10";
private static final String RUBYGEMS_URI_TEMPLATE = "http://production.cf.rubygems.org/rubygems/rubygems-%s.tgz";
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Optional<String> version = Optional.absent();
private boolean updateSystem = false;
private Optional<String> updateSystemVersion = Optional.absent();
private boolean updateExistingGems = false;
/**
* The version of RubyGems to install.
*/
public Builder version(@Nullable String version) {
this.version = Optional.fromNullable(version);
return this;
}
/**
* Update the gem system after installing RubyGems.
*/
public Builder updateSystem(boolean updateSystem) {
this.updateSystem = updateSystem;
this.updateSystemVersion = Optional.absent();
return this;
}
/**
* Update the gem system after installing RubyGems, forcing the update to
* a concrete version.
*/
public Builder updateSystem(boolean updateSystem, @Nullable String updateSystemVersion) {
this.updateSystem = updateSystem;
this.updateSystemVersion = Optional.fromNullable(updateSystemVersion);
return this;
}
/**
* Update the existing gems after installing RubyGems.
*/
public Builder updateExistingGems(boolean updateExistingGems) {
this.updateExistingGems = updateExistingGems;
return this;
}
public InstallRubyGems build() {
return new InstallRubyGems(version, updateSystem, updateSystemVersion, updateExistingGems);
}
}
private Optional<String> version;
private boolean updateSystem;
private Optional<String> updateSystemVersion;
private boolean updateExistingGems;
protected InstallRubyGems(Optional<String> version, boolean updateSystem, Optional<String> updateSystemVersion,
boolean updateExistingGems) {
this.version = checkNotNull(version, "version must be set");
this.updateSystem = updateSystem;
this.updateSystemVersion = checkNotNull(updateSystemVersion, "updateSystemVersion must be set");
this.updateExistingGems = updateExistingGems;
}
@Override
public String render(OsFamily family) {
if (family == OsFamily.WINDOWS) {
throw new UnsupportedOperationException("windows not yet implemented");
}
URI rubygemsUri = URI.create(String.format(RUBYGEMS_URI_TEMPLATE, version.or(DEFAULT_RUBYGEMS_VERSION)));
ImmutableList.Builder<Statement> statements = ImmutableList.builder();
statements.add(exec("if ! hash gem 2>/dev/null; then"));
statements.add(exec("("));
statements.add(extractTargzAndFlattenIntoDirectory(rubygemsUri, "/tmp/rubygems"));
statements.add(exec("{cd} /tmp/rubygems"));
statements.add(exec("ruby setup.rb --no-format-executable"));
statements.add(exec("{rm} -fr /tmp/rubygems"));
statements.add(exec(")"));
statements.add(exec("fi"));
if (updateSystem) {
statements.add(updateSystemVersion.isPresent() ? exec("gem update --system " + updateSystemVersion.get())
: exec("gem update --system"));
}
if (updateExistingGems) {
statements.add(exec("gem update --no-rdoc --no-ri"));
}
return new StatementList(statements.build()).render(family);
}
@Override
public Iterable<String> functionDependencies(OsFamily family) {
return ImmutableSet.<String> of();
}
}
| 1,790 |
381 | /*
* Copyright 2014 OpenMarket Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.androidsdk.core;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.matrix.androidsdk.rest.model.message.ImageInfo;
import java.io.File;
/**
* Static content utility methods.
*/
public class ContentUtils {
private static final String LOG_TAG = FileContentUtils.class.getSimpleName();
/**
* Build an ImageInfo object based on the image at the given path.
*
* @param filePath the path to the image in storage
* @return the image info
*/
public static ImageInfo getImageInfoFromFile(String filePath) {
ImageInfo imageInfo = new ImageInfo();
try {
Bitmap imageBitmap = BitmapFactory.decodeFile(filePath);
imageInfo.w = imageBitmap.getWidth();
imageInfo.h = imageBitmap.getHeight();
File file = new File(filePath);
imageInfo.size = file.length();
imageInfo.mimetype = FileContentUtils.getMimeType(filePath);
} catch (OutOfMemoryError oom) {
Log.e(LOG_TAG, "## getImageInfoFromFile() : oom", oom);
}
return imageInfo;
}
}
| 605 |
433 | package com.wuxiaolong.wewin.ui.juzimi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.wuxiaolong.wewin.model.MainModel;
import com.wuxiaolong.wewin.utils.AppConstants;
import com.wuxiaolong.wewin.utils.AppUtils;
import com.xiaomolongstudio.wewin.R;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by 吴小龙同學
* on 2015/11/22.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<MainModel> mMainList = new ArrayList<>();
private Activity activity;
private boolean hasTitle;
public RecyclerViewAdapter(Activity activity, boolean hasTitle) {
this.activity = activity;
this.hasTitle = hasTitle;
}
public List<MainModel> getmMainList() {
return mMainList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(parent.getContext(), R.layout.recycler_view_item, null);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Picasso.with(activity)
.load(mMainList.get(position).getIamgeUrl())
.placeholder(R.drawable.downloading)
.error(R.drawable.downloading)
.into(holder.imageView);
if (hasTitle) {
holder.title.setVisibility(View.VISIBLE);
holder.title.setText(mMainList.get(position).getTitle());
} else {
holder.title.setVisibility(View.GONE);
}
holder.imageView.setTag(mMainList.get(position).getIamgeUrl());
ViewCompat.setTransitionName(holder.imageView, mMainList.get(position).getIamgeUrl());
}
@Override
public int getItemCount() {
return mMainList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.imgView)
ImageView imageView;
@BindView(R.id.title)
TextView title;
public ViewHolder(final View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmap = null;
BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
if (bitmapDrawable != null) {
bitmap = bitmapDrawable.getBitmap();
}
Intent intent = new Intent(activity, ShowImageActivity.class);
intent.putExtra("mainList", (Serializable) mMainList);
intent.putExtra("position", getLayoutPosition());
intent.putExtra(AppConstants.COLOR, AppUtils.getPaletteColor(bitmap));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Pair<View, String> pair1 = Pair.create((View) imageView, mMainList.get(getLayoutPosition()).getIamgeUrl());
// Pair<View, String> pair2 = Pair.create((View) title, mMainList.get(getLayoutPosition()).getTitle());
// Log.d("wxl", "title===" + mMainList.get(getLayoutPosition()).getTitle());
// ActivityOptionsCompat options;
// options = ActivityOptionsCompat
// .makeSceneTransitionAnimation(activity, pair1, pair2);
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation(activity, itemView, mMainList.get(getLayoutPosition()).getIamgeUrl());
// ActivityOptionsCompat options = ActivityOptionsCompat
// .makeSceneTransitionAnimation(activity, itemView, AppConstants.TRANSIT_PIC);
ActivityCompat.startActivity(activity, intent, options.toBundle());
} else {
activity.startActivity(intent);
}
}
}
);
}
}
}
| 2,374 |
324 | <gh_stars>100-1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.cloudstack.compute.functions;
import static org.testng.AssertJUnit.assertEquals;
import java.net.URI;
import java.util.Set;
import org.jclouds.cloudstack.domain.Zone;
import org.jclouds.cloudstack.parse.ListZonesResponseTest;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import org.jclouds.location.suppliers.all.JustProvider;
import org.testng.annotations.Test;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
/**
* Tests {@code ZoneToLocation}
*/
@Test(singleThreaded = true, groups = "unit")
public class ZoneToLocationTest {
public static final JustProvider justProvider = new JustProvider("cloudstack", Suppliers.ofInstance(URI.create("foo")),
ImmutableSet.<String> of());
public static final ZoneToLocation function = new ZoneToLocation(justProvider);
public static final Location one = new LocationBuilder().parent(Iterables.get(justProvider.get(), 0)).scope(LocationScope.ZONE)
.description("San Jose 1").id("1").build();
public static final Location two = new LocationBuilder().parent(Iterables.get(justProvider.get(), 0)).scope(LocationScope.ZONE)
.description("Chicago").id("2").build();
@Test
public void test() {
Set<Location> expected = ImmutableSet.of(one, two);
Set<Zone> zones = new ListZonesResponseTest().expected();
Iterable<Location> locations = Iterables.transform(zones, function);
assertEquals(locations.toString(), expected.toString());
}
}
| 726 |
18,396 | <reponame>vanga-top/mediasoup
/*
* ekt.h
*
* interface to Encrypted Key Transport for SRTP
*
* <NAME>
* Cisco Systems, Inc.
*/
/*
*
* Copyright (c) 2001-2017 Cisco Systems, 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 Cisco Systems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS 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.
*
*/
/*
* EKT implementation strategy
*
* use stream_template approach
*
* in srtp_unprotect, when a new stream appears, check if template has
* EKT defined, and if it does, then apply EKT processing
*
* question: will we want to allow key-sharing templates in addition
* to EKT templates? could define a new ssrc_type_t that's associated
* with an EKT, e.g. ssrc_any_ekt.
*
*
*/
#ifndef SRTP_EKT_H
#define SRTP_EKT_H
// left in commented out as reminder to not include private headers
//#include "srtp_priv.h"
#ifdef __cplusplus
extern "C" {
#endif
#define SRTP_EKT_CIPHER_DEFAULT 1
#define SRTP_EKT_CIPHER_AES_128_ECB 1
#define SRTP_EKT_CIPHER_AES_192_KEY_WRAP 2
#define SRTP_EKT_CIPHER_AES_256_KEY_WRAP 3
typedef uint16_t srtp_ekt_spi_t;
unsigned srtp_ekt_octets_after_base_tag(srtp_ekt_stream_t ekt);
/*
* an srtp_policy_t structure can contain a pointer to an
* srtp_ekt_policy_t structure
*
* this structure holds all of the high level EKT information, and it
* is passed into libsrtp to indicate what policy should be in effect
*/
typedef struct srtp_ekt_policy_ctx_t {
srtp_ekt_spi_t spi; /* security parameter index */
uint8_t ekt_cipher_type;
uint8_t *ekt_key;
struct srtp_ekt_policy_ctx_t *next_ekt_policy;
} srtp_ekt_policy_ctx_t;
/*
* an srtp_ekt_data_t structure holds the data corresponding to an ekt key,
* spi, and so on
*/
typedef struct srtp_ekt_data_t {
srtp_ekt_spi_t spi;
uint8_t ekt_cipher_type;
srtp_aes_expanded_key_t ekt_enc_key;
srtp_aes_expanded_key_t ekt_dec_key;
struct ekt_data_t *next_ekt_data;
} srtp_ekt_data_t;
/*
* an srtp_stream_ctx_t can contain an srtp_ekt_stream_ctx_t
*
* an srtp_ekt_stream_ctx_t structure holds all of the EKT information for
* a specific SRTP stream
*/
typedef struct srtp_ekt_stream_ctx_t {
srtp_ekt_data_t *data;
uint16_t isn; /* initial sequence number */
uint8_t encrypted_master_key[SRTP_MAX_KEY_LEN];
} srtp_ekt_stream_ctx_t;
srtp_err_status_t srtp_ekt_alloc(srtp_ekt_stream_t *stream_data,
srtp_ekt_policy_t policy);
srtp_err_status_t srtp_ekt_stream_init(srtp_ekt_stream_t e,
srtp_ekt_spi_t spi,
void *ekt_key,
unsigned ekt_cipher_type);
srtp_err_status_t srtp_ekt_stream_init_from_policy(srtp_ekt_stream_t e,
srtp_ekt_policy_t p);
srtp_err_status_t srtp_stream_init_from_ekt(srtp_stream_t stream,
const void *srtcp_hdr,
unsigned pkt_octet_len);
void srtp_ekt_write_data(srtp_ekt_stream_t ekt,
uint8_t *base_tag,
unsigned base_tag_len,
int *packet_len,
srtp_xtd_seq_num_t pkt_index);
/*
* We handle EKT by performing some additional steps before
* authentication (copying the auth tag into a temporary location,
* zeroizing the "base tag" field in the packet)
*
* With EKT, the tag_len parameter is actually the base tag
* length
*/
srtp_err_status_t srtp_ekt_tag_verification_preproces(uint8_t *pkt_tag,
uint8_t *pkt_tag_copy,
unsigned tag_len);
srtp_err_status_t srtp_ekt_tag_verification_postproces(uint8_t *pkt_tag,
uint8_t *pkt_tag_copy,
unsigned tag_len);
/*
* @brief EKT pre-processing for srtcp tag generation
*
* This function does the pre-processing of the SRTCP authentication
* tag format. When EKT is used, it consists of writing the Encrypted
* Master Key, the SRTP ROC, the Initial Sequence Number, and SPI
* fields. The Base Authentication Tag field is set to the all-zero
* value
*
* When EKT is not used, this function is a no-op.
*
*/
srtp_err_status_t srtp_stream_srtcp_auth_tag_generation_preprocess(
const srtp_stream_t *s,
uint8_t *pkt_tag,
unsigned pkt_octet_len);
/* it's not clear that a tag_generation_postprocess function is needed */
srtp_err_status_t srtcp_auth_tag_generation_postprocess(void);
#ifdef __cplusplus
}
#endif
#endif /* SRTP_EKT_H */
| 2,653 |
8,054 | #ifndef EDITORMARKDOWNVIEWERADAPTER_H
#define EDITORMARKDOWNVIEWERADAPTER_H
#include "markdownvieweradapter.h"
namespace vnotex
{
class Buffer;
class EditorMarkdownViewerAdapter : public MarkdownViewerAdapter
{
Q_OBJECT
public:
EditorMarkdownViewerAdapter(Buffer *p_buffer, QObject *p_parent = nullptr);
void setBuffer(Buffer *p_buffer);
public slots:
private:
Buffer *m_buffer = nullptr;
};
}
#endif // EDITORMARKDOWNVIEWERADAPTER_H
| 203 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-cr8c-972v-rmp3",
"modified": "2022-03-29T00:01:39Z",
"published": "2022-03-17T00:00:24Z",
"aliases": [
"CVE-2022-0959"
],
"details": "When run in server mode, pgAdmin 4 allows users to store files on the server under individual storage directories. Files such as SQL scripts may be uploaded through the user interface. The URI to which upload requests are made fails to validate the upload path to prevent path traversal techniques being used to store files outside of the storage directory. A malicious, but authorised and authenticated user can construct an HTTP request using their existing CSRF token and session cookie to manually upload files to any location that the operating system user account under which pgAdmin is running has permission to write.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:N"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2022-0959"
},
{
"type": "WEB",
"url": "https://bugzilla.redhat.com/show_bug.cgi?id=2063759"
}
],
"database_specific": {
"cwe_ids": [
"CWE-434"
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 499 |
30,023 | {
"domain": "geocaching",
"name": "Geocaching",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/geocaching",
"requirements": ["geocachingapi==0.2.1"],
"dependencies": ["application_credentials"],
"codeowners": ["@Sholofly", "@reinder83"],
"iot_class": "cloud_polling"
}
| 120 |
480 | <reponame>raakasf/Cpp17-STL-Cookbook
#include <iostream>
#include <iomanip>
#include <random>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
template <typename T>
void print_distro(T distro, size_t samples)
{
default_random_engine e;
map<int, size_t> m;
for (size_t i {0}; i < samples; ++i) {
m[distro(e)] += 1;
}
size_t max_elm (max_element(begin(m), end(m),
[](const auto &a, const auto &b) { return a.second < b.second; })->second);
size_t max_div (max(max_elm / 100, size_t(1)));
for (const auto [randval, count] : m) {
if (count < max_elm / 200) { continue; }
cout << setw(3) << randval << " : "
<< string(count / max_div, '*') << '\n';
}
}
int main(int argc, char **argv)
{
if (argc != 2) {
cout << "Usage: " << argv[0] << " <samples>\n";
return 1;
}
size_t samples {stoull(argv[1])};
cout << "uniform_int_distribution\n";
print_distro(uniform_int_distribution<int>{0, 9}, samples);
cout << "normal_distribution\n";
print_distro(normal_distribution<double>{0.0, 2.0}, samples);
std::initializer_list<double> intervals {0, 5, 10, 30};
std::initializer_list<double> weights {0.2, 0.3, 0.5};
cout << "piecewise_constant_distribution\n";
print_distro(piecewise_constant_distribution<double>{begin(intervals), end(intervals), begin(weights)}, samples);
cout << "piecewise_linear_distribution\n";
std::initializer_list<double> weights2 {0, 1, 1, 0};
print_distro(piecewise_linear_distribution<double>{begin(intervals), end(intervals), begin(weights2)}, samples);
cout << "bernoulli_distribution\n";
print_distro(std::bernoulli_distribution{0.75}, samples);
cout << "discrete_distribution\n";
print_distro(discrete_distribution<int>{{1, 2, 4, 8}}, samples);
cout << "binomial_distribution\n";
print_distro(binomial_distribution<int>{10, 0.3}, samples);
cout << "negative_binomial_distribution\n";
print_distro(negative_binomial_distribution<int>{10, 0.8}, samples);
cout << "geometric_distribution\n";
print_distro(geometric_distribution<int>{0.4}, samples);
cout << "exponential_distribution\n";
print_distro(exponential_distribution<double>{0.4}, samples);
cout << "gamma_distribution\n";
print_distro(gamma_distribution<double>{1.5, 1.0}, samples);
cout << "weibull_distribution\n";
print_distro(weibull_distribution<double>{1.5, 1.0}, samples);
cout << "extreme_value_distribution\n";
print_distro(extreme_value_distribution<double>{0.0, 1.0}, samples);
cout << "lognormal_distribution\n";
print_distro(lognormal_distribution<double>{0.5, 0.5}, samples);
cout << "chi_squared_distribution\n";
print_distro(chi_squared_distribution<double>{1.0}, samples);
cout << "cauchy_distribution\n";
print_distro(cauchy_distribution<double>{0.0, 0.1}, samples);
cout << "fisher_f_distribution\n";
print_distro(fisher_f_distribution<double>{1.0, 1.0}, samples);
cout << "student_t_distribution\n";
print_distro(student_t_distribution<double>{1.0}, samples);
}
| 1,326 |
361 | <gh_stars>100-1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicecomb.it.deploy;
import io.vertx.core.json.Json;
public class DeployDefinition {
protected String deployName;
protected String displayName;
protected String startCompleteLog;
protected String workDir;
/**
* <pre>
* edge as the example:
* support:
* 1.absolute path: /home/xxx/it-edge/it-edge-1.0.0.jar
* 2.relate to work dir:
* if work dir is /home/xxx
* cmd is it-edge/it-edge-1.0.0.jar
* 3.run in ide, cmd is it-edge/it-edge-1.0.0.jar
* will try: integration-tests/target/it-edge/it-edge-1.0.0.jar
* 4.run in ide, cmd is it-edge
* will try: integration-tests/target/it-edge/it-edge-1.0.0.jar
* </pre>
*/
protected String cmd;
protected String[] args;
public String getDeployName() {
return deployName;
}
public void setDeployName(String deployName) {
this.deployName = deployName;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getStartCompleteLog() {
return startCompleteLog;
}
public void setStartCompleteLog(String startCompleteLog) {
this.startCompleteLog = startCompleteLog;
}
public String getWorkDir() {
return workDir;
}
public void setWorkDir(String workDir) {
this.workDir = workDir;
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String[] getArgs() {
return args;
}
public void setArgs(String[] args) {
this.args = args;
}
public void appendArgs(String arg) {
String[] result = new String[args.length + 1];
System.arraycopy(args, 0, result, 0, args.length);
result[args.length] = arg;
this.args = result;
}
public void appendArgs(String[] newArgs) {
String[] result = new String[args.length + newArgs.length];
System.arraycopy(args, 0, result, 0, args.length);
System.arraycopy(newArgs, 0, result, args.length, newArgs.length);
this.args = result;
}
public void init() {
if (displayName == null) {
displayName = deployName;
}
}
@Override
public String toString() {
return Json.encodePrettily(this);
}
}
| 1,037 |
728 | /**
* Copyright (c) 2011, University of Konstanz, Distributed Systems Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Konstanz 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.sirix.saxon.wrapper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Collections;
import java.util.Iterator;
import javax.annotation.Nonnegative;
import net.sf.saxon.Configuration;
import net.sf.saxon.event.Receiver;
import net.sf.saxon.om.DocumentInfo;
import net.sf.saxon.om.NamePool;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.om.SequenceIterator;
import net.sf.saxon.pattern.NodeTest;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.tree.iter.AxisIterator;
import net.sf.saxon.tree.util.FastStringBuffer;
import net.sf.saxon.value.Value;
import org.sirix.api.Axis;
import org.sirix.api.NodeReadTrx;
import org.sirix.api.Session;
import org.sirix.axis.DescendantAxis;
import org.sirix.axis.IncludeSelf;
import org.sirix.exception.SirixException;
import org.sirix.node.Kind;
import org.sirix.utils.LogWrapper;
import org.slf4j.LoggerFactory;
/**
*
* <p>
* Wraps a sirix document and represents a document node. Therefore it
* implements Saxon's DocumentInfo core interface and also represents a Node in
* Saxon's internal node implementation. Thus it extends <tt>NodeWrapper</tt>.
* </p>
*
* @author <NAME>, University of Konstanz
* @author <NAME>, University of Konstanz
*
*/
public final class DocumentWrapper implements DocumentInfo {
/** {@link LogWrapper} instance. */
private static final LogWrapper LOGWRAPPER = new LogWrapper(
LoggerFactory.getLogger(DocumentWrapper.class));
/** sirix database. */
final Session mSession;
/** The revision. */
final int mRevision;
/** Base URI of the document. */
String mBaseURI;
/** Saxon configuration. */
Configuration mConfig;
/** Unique document number. */
long mDocumentNumber;
/**
* Instance of {@link NodeWrapper}-implementation
*/
private final NodeWrapper mNodeWrapper;
/**
* Wrap a sirix document.
*
* @param session
* sirix {@link Session}
* @param revision
* the revision to open
* @param config
* Saxon {@link Configuration} instance
* @throws SirixException
* if sirix encounters an error
*/
public DocumentWrapper(final Session session,
@Nonnegative final int revision, final Configuration config)
throws SirixException {
checkArgument(revision >= 0, "revision must be >= 0!");
mSession = checkNotNull(session);
mRevision = revision;
mBaseURI = session.getResourceConfig().getResource().getAbsolutePath();
mConfig = checkNotNull(config);
mNodeWrapper = new NodeWrapper(this, 0);
}
/**
* Wrap a sirix document.
*
* @param session
* Sirix {@link Session}
* @param config
* Saxon {@link Configuration} instance
* @throws SirixException
* if Sirix encounters an error
*/
public DocumentWrapper(final Session session, final Configuration config)
throws SirixException {
this(session, session.getMostRecentRevisionNumber(), config);
}
@Override
public String[] getUnparsedEntity(final String name) {
throw new UnsupportedOperationException("Currently not supported by sirix!");
}
/**
* Get the unparsed entity with a given name.
*
* @return null: sirix does not provide access to unparsed entities.
*/
@SuppressWarnings("unchecked")
public Iterator<String> getUnparsedEntityNames() {
return (Iterator<String>) Collections.EMPTY_LIST.iterator();
}
@Override
public NodeInfo selectID(final String ID, final boolean getParent) {
try {
final NodeReadTrx rtx = mSession.beginNodeReadTrx();
final Axis axis = new DescendantAxis(rtx, IncludeSelf.YES);
while (axis.hasNext()) {
if (rtx.getKind() == Kind.ELEMENT) {
final int attCount = rtx.getAttributeCount();
if (attCount > 0) {
final long nodeKey = rtx.getNodeKey();
for (int index = 0; index < attCount; index++) {
rtx.moveToAttribute(index);
if ("xml:id".equalsIgnoreCase(rtx.getName().getLocalName())
&& ID.equals(rtx.getValue())) {
if (getParent) {
rtx.moveToParent();
}
return new NodeWrapper(this, rtx.getNodeKey());
}
rtx.moveTo(nodeKey);
}
}
}
axis.next();
}
rtx.close();
} catch (final SirixException e) {
LOGWRAPPER.error(e.getMessage(), e);
}
return null;
}
@Override
public NamePool getNamePool() {
return mConfig.getNamePool();
}
/**
* Set the configuration (containing the name pool used for all names in this
* document). Calling this method allocates a unique number to the document
* (unique within the Configuration); this will form the basis for testing
* node identity.
*
* @param config
* Saxon {@link Configuration} instance
*/
public void setConfiguration(final Configuration config) {
mConfig = config;
mDocumentNumber = config.getDocumentNumberAllocator()
.allocateDocumentNumber();
}
@Override
public Configuration getConfiguration() {
return mConfig;
}
@Override
public String getBaseURI() {
return mBaseURI;
}
/**
* Set the baseURI of the current document.
*
* @param baseURI
* usually the absolute path of the document
*/
void setBaseURI(final String baseURI) {
mBaseURI = checkNotNull(baseURI);
}
@Override
public Object getUserData(String arg0) {
return null;
}
@Override
public void setUserData(String arg0, Object arg1) {
}
@Override
public Value atomize() throws XPathException {
return getNodeWrapper().atomize();
}
@Override
public int compareOrder(NodeInfo arg0) {
return getNodeWrapper().compareOrder(arg0);
}
@Override
public void copy(Receiver arg0, int arg1, int arg2) throws XPathException {
getNodeWrapper().copy(arg0, arg1, arg2);
}
@Override
public void generateId(FastStringBuffer arg0) {
getNodeWrapper().generateId(arg0);
}
@Override
public String getAttributeValue(int arg0) {
return getNodeWrapper().getAttributeValue(arg0);
}
@Override
public int getColumnNumber() {
return getNodeWrapper().getColumnNumber();
}
@Override
public int[] getDeclaredNamespaces(int[] arg0) {
return getNodeWrapper().getDeclaredNamespaces(arg0);
}
@Override
public String getDisplayName() {
return getNodeWrapper().getDisplayName();
}
@Override
public long getDocumentNumber() {
return getNodeWrapper().getDocumentNumber();
}
@Override
public DocumentInfo getDocumentRoot() {
return getNodeWrapper().getDocumentRoot();
}
@Override
public int getFingerprint() {
return getNodeWrapper().getFingerprint();
}
@Override
public int getLineNumber() {
return getNodeWrapper().getLineNumber();
}
@Override
public String getLocalPart() {
return getNodeWrapper().getLocalPart();
}
@Override
public int getNameCode() {
return getNodeWrapper().getNameCode();
}
@Override
public int getNodeKind() {
return getNodeWrapper().getNodeKind();
}
@Override
public NodeInfo getParent() {
return getNodeWrapper().getParent();
}
@Override
public String getPrefix() {
return getNodeWrapper().getPrefix();
}
@Override
public NodeInfo getRoot() {
return getNodeWrapper().getRoot();
}
@Override
public String getStringValue() {
return getNodeWrapper().getStringValue();
}
@Override
public String getSystemId() {
return getNodeWrapper().getSystemId();
}
@Override
public int getTypeAnnotation() {
return getNodeWrapper().getTypeAnnotation();
}
@Override
public String getURI() {
return getNodeWrapper().getURI();
}
@Override
public boolean hasChildNodes() {
return getNodeWrapper().hasChildNodes();
}
@Override
public boolean isId() {
return getNodeWrapper().isId();
}
@Override
public boolean isIdref() {
return getNodeWrapper().isIdref();
}
@Override
public boolean isNilled() {
return getNodeWrapper().isNilled();
}
@Override
public boolean isSameNodeInfo(NodeInfo arg0) {
return getNodeWrapper().isSameNodeInfo(arg0);
}
@Override
public AxisIterator iterateAxis(byte arg0) {
return getNodeWrapper().iterateAxis(arg0);
}
@Override
public AxisIterator iterateAxis(byte arg0, NodeTest arg1) {
return getNodeWrapper().iterateAxis(arg0, arg1);
}
@Override
public void setSystemId(String arg0) {
getNodeWrapper().setSystemId(arg0);
}
@Override
public CharSequence getStringValueCS() {
return getNodeWrapper().getStringValueCS();
}
@Override
public SequenceIterator getTypedValue() throws XPathException {
return getNodeWrapper().getTypedValue();
}
public NodeWrapper getNodeWrapper() {
return mNodeWrapper;
}
}
| 3,438 |
679 | /**************************************************************
*
* 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.
*
*************************************************************/
#include "oox/drawingml/textliststylecontext.hxx"
#include "oox/drawingml/textparagraphpropertiescontext.hxx"
#include "oox/helper/attributelist.hxx"
using ::rtl::OUString;
using namespace ::oox::core;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
namespace oox { namespace drawingml {
// --------------------------------------------------------------------
// CT_TextListStyle
TextListStyleContext::TextListStyleContext( ContextHandler& rParent, TextListStyle& rTextListStyle )
: ContextHandler( rParent )
, mrTextListStyle( rTextListStyle )
{
}
TextListStyleContext::~TextListStyleContext()
{
}
// --------------------------------------------------------------------
void TextListStyleContext::endFastElement( sal_Int32 ) throw (SAXException, RuntimeException)
{
}
// --------------------------------------------------------------------
Reference< XFastContextHandler > TextListStyleContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& rxAttributes ) throw (SAXException, RuntimeException)
{
Reference< XFastContextHandler > xRet;
switch( aElementToken )
{
case A_TOKEN( defPPr ): // CT_TextParagraphProperties
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getListStyle()[ 0 ] ) );
break;
case A_TOKEN( outline1pPr ):
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getAggregationListStyle()[ 0 ] ) );
break;
case A_TOKEN( outline2pPr ):
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getAggregationListStyle()[ 1 ] ) );
break;
case A_TOKEN( lvl1pPr ):
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getListStyle()[ 0 ] ) );
break;
case A_TOKEN( lvl2pPr ):
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getListStyle()[ 1 ] ) );
break;
case A_TOKEN( lvl3pPr ):
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getListStyle()[ 2 ] ) );
break;
case A_TOKEN( lvl4pPr ):
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getListStyle()[ 3 ] ) );
break;
case A_TOKEN( lvl5pPr ):
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getListStyle()[ 4 ] ) );
break;
case A_TOKEN( lvl6pPr ):
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getListStyle()[ 5 ] ) );
break;
case A_TOKEN( lvl7pPr ):
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getListStyle()[ 6 ] ) );
break;
case A_TOKEN( lvl8pPr ):
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getListStyle()[ 7 ] ) );
break;
case A_TOKEN( lvl9pPr ):
xRet.set( new TextParagraphPropertiesContext( *this, rxAttributes, *mrTextListStyle.getListStyle()[ 8 ] ) );
break;
}
if ( !xRet.is() )
xRet.set( this );
return xRet;
}
// --------------------------------------------------------------------
} }
| 1,378 |
480 | <filename>polardbx-calcite/src/main/java/org/apache/calcite/sql/SqlAlterTableExpireLocalPartition.java
package org.apache.calcite.sql;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.util.SqlString;
import java.util.List;
/**
* see com/alibaba/polardbx/druid/sql/dialect/mysql/parser/MySqlStatementParser.java:7484
* key words: "EXPIRE"
*
* @author guxu
*/
public class SqlAlterTableExpireLocalPartition extends SqlAlterSpecification {
private static final SqlOperator OPERATOR = new SqlSpecialOperator("EXPIRE LOCAL PARTITION", SqlKind.EXPIRE_LOCAL_PARTITION);
protected SqlNode parent;
private final List<SqlIdentifier> partitions;
public SqlAlterTableExpireLocalPartition(SqlParserPos pos, List<SqlIdentifier> partitions) {
super(pos);
this.partitions = partitions;
}
@Override
public SqlOperator getOperator() {
return OPERATOR;
}
@Override
public List<SqlNode> getOperandList() {
return null;
}
public SqlNode getParent() {
return parent;
}
public void setParent(SqlNode parent) {
this.parent = parent;
}
public List<SqlIdentifier> getPartitions() {
return partitions;
}
public void addPartition(SqlIdentifier partition) {
this.partitions.add(partition);
}
@Override
public String toString() {
return "EXPIRE LOCAL PARTITION";
}
@Override
public SqlString toSqlString(SqlDialect dialect) {
return new SqlString(dialect ,toString());
}
}
| 617 |
981 | /*******************************************************************
* File automatically generated by rebuild_wrappers.py (v2.1.0.16) *
*******************************************************************/
#ifndef __wrappedxineramaUNDEFS_H_
#define __wrappedxineramaUNDEFS_H_
#endif // __wrappedxineramaUNDEFS_H_
| 82 |
2,542 | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#define NDP4_AUTO_VERSION_ROLLFORWARD
#define VER_VS_ASSEMBLYVERSION_STR_L L"10.0.0.0"
#define VER_VC_STLCLR_ASSEMBLYVERSION_STR_L L"2.0.0.0"
// Working set optimization: using file:..\..\bin\OptimizeFxRetarget.cs (.exe) to generate condensed tables with less string data and less pointers
#include "fixedsizestring.h"
namespace FxPolicyHelper
{
// Forward declarations from file:fxretarget_generated.hpp
extern LPCSTR const g_rgAssemblyNamePartStrings[];
extern LPCWSTR const g_rgAssemblyKeyVersionStrings[];
enum AppXBinderSupport
{
AppXBinder_Blocked = 0,
AppXBinder_Supported = 1
};
};
struct FrameworkConfig
{
// Working set optimization, store assembly name as 4-bytes, PKT/Version as 1-byte; long assembly names broken into parts stored in ANSI
unsigned char m_compressedName[4];
unsigned char m_nPKT;
unsigned char m_nNewVersion : 7;
unsigned char m_fSupportedInAppXBinder : 1;
const LPCWSTR GetPKT() const
{
return FxPolicyHelper::g_rgAssemblyKeyVersionStrings[m_nPKT];
}
const LPCWSTR GetNewVersion() const
{
return FxPolicyHelper::g_rgAssemblyKeyVersionStrings[m_nNewVersion];
}
BOOL IsSupportedInAppXBinder() const
{
_ASSERTE((m_fSupportedInAppXBinder == FxPolicyHelper::AppXBinder_Blocked) ||
(m_fSupportedInAppXBinder == FxPolicyHelper::AppXBinder_Supported));
return (m_fSupportedInAppXBinder == FxPolicyHelper::AppXBinder_Supported);
}
// Using template to avoid converting it to UNICODE when possible,
// more important avoid converting the ANSI string it's going to be compared with to be converted to UNICODE
template<typename T>
void GetFxAssemblyName(FixedSizeString<T> & output) const
{
output.DecodeName(_countof(m_compressedName), m_compressedName, FxPolicyHelper::g_rgAssemblyNamePartStrings);
}
};
#define StringHashIterator(name, table, asmName) StringHashEnumerator name(asmName, table ## _Hash, _countof(table ## _Hash), table ## _HashCollision);
#ifdef NEEDDATA
// This file is auto generated by file:..\..\bin\OptimizeFxRetarget.cs (.exe), saved in intermediate directory
#include "fxretarget_generated.hpp"
#endif
#ifdef ORIGINAL_SOURCE
typedef struct tagFrameworkConfig
{
LPCWSTR pwzName;
// culture by default is NULL/Neutral
// LPCWSTR pwzCulture;
LPCWSTR pwzPKT;
LPCWSTR pwzNewVersion;
FxPolicyHelper::AppXBinderSupport fSupportedInAppXBinder;
} FrameworkConfig;
const FrameworkConfig g_arFxPolicy[] =
{
// This table is parsed and processed by file:..\..\bin\OptimizeFxRetarget.cs (.exe):
// STARTDICTIONARY(FxPolicyHelper,AssemblyNamePart,AssemblyKeyVersion,FrameworkConfig,g_arFxPolicy)
{L"Accessibility", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"CustomMarshalers", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"ISymWrapper", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.JScript", MICROSOFT_PUBLICKEY_STR_L, VER_VS_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.VisualBasic", MICROSOFT_PUBLICKEY_STR_L, VER_VS_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"Microsoft.VisualBasic.Compatibility", MICROSOFT_PUBLICKEY_STR_L, VER_VS_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.VisualBasic.Compatibility.Data", MICROSOFT_PUBLICKEY_STR_L, VER_VS_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.VisualC", MICROSOFT_PUBLICKEY_STR_L, VER_VS_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"mscorlib", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Configuration", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Configuration.Install", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Data", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Data.OracleClient", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Data.SqlXml", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Deployment", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Design", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.DirectoryServices", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.DirectoryServices.Protocols", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Drawing", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Drawing.Design", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.EnterpriseServices", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Management", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Messaging", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Runtime.Remoting", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.Serialization.Formatters.Soap", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Security", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ServiceProcess", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Transactions", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Web", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.Mobile", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.RegularExpressions", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.Services", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported}, // Has to be supported in AppX, because it is in transitive closure of supported assemblies
{L"System.Windows.Forms", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Xml", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
#ifdef NDP4_AUTO_VERSION_ROLLFORWARD
// Post-Everett FX 2.0 assemblies:
{L"AspNetMMCExt", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"sysglobl", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.Build.Engine", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.Build.Framework", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
// FX 3.0 assemblies:
// Note: we shipped .NET 4.0 with entries in this list for PresentationCFFRasterizer and System.ServiceModel.Install
// even though these assemblies did not ship with .NET 4.0. To maintain 100% compatibility with 4.0 we will keep
// these in .NET 4.5, but we should remove them in a future SxS version of the Framework.
{L"PresentationCFFRasterizer", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked}, // See note above
{L"PresentationCore", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework.Aero", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework.Classic", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework.Luna", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework.Royale", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationUI", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"ReachFramework", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Printing", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Speech", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"UIAutomationClient", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"UIAutomationClientsideProviders", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"UIAutomationProvider", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"UIAutomationTypes", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"WindowsBase", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"WindowsFormsIntegration", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"SMDiagnostics", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.IdentityModel", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.IdentityModel.Selectors", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.IO.Log", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Runtime.Serialization", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ServiceModel", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ServiceModel.Install", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked}, // See note above
{L"System.ServiceModel.WasHosting", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Workflow.Activities", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Workflow.ComponentModel", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Workflow.Runtime", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.Transactions.Bridge", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"Microsoft.Transactions.Bridge.Dtc", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
// FX 3.5 assemblies:
{L"System.AddIn", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.AddIn.Contract", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.ComponentModel.Composition", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported}, // Shipping out-of-band
{L"System.Core", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Data.DataSetExtensions", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Data.Linq", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Xml.Linq", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.DirectoryServices.AccountManagement", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Management.Instrumentation", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Net", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ServiceModel.Web", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported}, // Needed for portable libraries
{L"System.Web.Extensions", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.Extensions.Design", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Windows.Presentation", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.WorkflowServices", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
// Microsoft.Data.Entity.Build.Tasks.dll should not be unified on purpose - it is supported SxS, i.e. both 3.5 and 4.0 versions can be loaded into CLR 4.0+.
// {L"Microsoft.Data.Entity.Build.Tasks", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L},
// FX 3.5 SP1 assemblies:
{L"System.ComponentModel.DataAnnotations", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Data.Entity", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Data.Entity.Design", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Data.Services", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Data.Services.Client", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Data.Services.Design", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.Abstractions", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.DynamicData", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.DynamicData.Design", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.Entity", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.Entity.Design", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.Routing", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
// FX 4.0 assemblies:
{L"Microsoft.Build", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.CSharp", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Dynamic", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Numerics", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Xaml", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
// Microsoft.Workflow.Compiler.exe:
// System.Workflow.ComponentModel.dll started to depend on Microsoft.Workflow.Compiler.exe in 4.0 RTM
{L"Microsoft.Workflow.Compiler", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
// FX 4.5 assemblies:
{L"Microsoft.Activities.Build", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.Build.Conversion.v4.0", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.Build.Tasks.v4.0", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.Build.Utilities.v4.0", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.Internal.Tasks.Dataflow", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.VisualBasic.Activities.Compiler", MICROSOFT_PUBLICKEY_STR_L, VER_VS_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.VisualC.STLCLR", MICROSOFT_PUBLICKEY_STR_L, VER_VC_STLCLR_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"Microsoft.Windows.ApplicationServer.Applications", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationBuildTasks", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework.Aero2", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework.AeroLite", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework-SystemCore", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework-SystemData", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework-SystemDrawing", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework-SystemXml", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"PresentationFramework-SystemXmlLinq", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Activities", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Activities.Core.Presentation", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Activities.DurableInstancing", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Activities.Presentation", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.ComponentModel.Composition.Registration", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Device", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.IdentityModel.Services", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.IO.Compression", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.IO.Compression.FileSystem", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Net.Http", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Net.Http.WebRequest", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Reflection.Context", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.Caching", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Runtime.DurableInstancing", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.WindowsRuntime", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.WindowsRuntime.UI.Xaml", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ServiceModel.Activation", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.ServiceModel.Activities", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.ServiceModel.Channels", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.ServiceModel.Discovery", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.ServiceModel.Internals", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ServiceModel.Routing", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.ServiceModel.ServiceMoniker40", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.ApplicationServices", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported}, // Has to be supported in AppX, because it is in transitive closure of supported assemblies
{L"System.Web.DataVisualization", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Web.DataVisualization.Design", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Windows.Controls.Ribbon", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Windows.Forms.DataVisualization", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Windows.Forms.DataVisualization.Design", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Windows.Input.Manipulations", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Xaml.Hosting", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"XamlBuildTask", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"XsdBuildTask", SHAREDLIB_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Blocked},
{L"System.Numerics.Vectors", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
// FX 4.5 facade assemblies:
{L"System.Collections", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Collections.Concurrent", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ComponentModel", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ComponentModel.Annotations", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ComponentModel.EventBasedAsync", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Diagnostics.Contracts", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Diagnostics.Debug", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Diagnostics.Tools", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Diagnostics.Tracing", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Dynamic.Runtime", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Globalization", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.IO", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Linq", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Linq.Expressions", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Linq.Parallel", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Linq.Queryable", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Net.Http.Rtc", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Net.NetworkInformation", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Net.Primitives", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Net.Requests", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ObjectModel", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Reflection", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Reflection.Emit", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Reflection.Emit.ILGeneration", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Reflection.Emit.Lightweight", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Reflection.Extensions", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Reflection.Primitives", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Resources.ResourceManager", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.Extensions", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.Handles", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.InteropServices", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.InteropServices.WindowsRuntime", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.Numerics", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.Serialization.Json", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.Serialization.Primitives", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Runtime.Serialization.Xml", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Security.Principal", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ServiceModel.Duplex", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ServiceModel.Http", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ServiceModel.NetTcp", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ServiceModel.Primitives", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.ServiceModel.Security", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Text.Encoding", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Text.Encoding.Extensions", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Text.RegularExpressions", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Threading", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Threading.Tasks", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Threading.Tasks.Parallel", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Threading.Timer", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Xml.ReaderWriter", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Xml.XDocument", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Xml.XmlSerializer", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
// Manually added facades
{L"System.Windows", MICROSOFT_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
{L"System.Xml.Serialization", ECMA_PUBLICKEY_STR_L, VER_ASSEMBLYVERSION_STR_L, FxPolicyHelper::AppXBinder_Supported},
#endif // NDP4_AUTO_VERSION_ROLLFORWARD
// ENDDICTIONARY
}; //g_arFxPolicy
#endif //ORIGINAL_SOURCE
| 13,517 |
839 | <gh_stars>100-1000
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.systest.jaxrs;
import org.apache.cxf.jaxrs.model.AbstractResourceInfo;
import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class JAXRSCxfContinuationsServlet3Test extends AbstractBusClientServerTestBase {
public static final String PORT = BookCxfContinuationServlet3Server.PORT;
@BeforeClass
public static void startServers() throws Exception {
AbstractResourceInfo.clearAllMaps();
createStaticBus();
assertTrue("server did not launch correctly",
launchServer(BookCxfContinuationServlet3Server.class));
}
@Test
public void testEncodedURL() throws Exception {
String id = "A%20B%20C"; // "A B C"
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet("http://localhost:" + PORT + "/bookstore/books/" + id);
try {
CloseableHttpResponse response = client.execute(get);
assertEquals("Encoded path '/" + id + "' is not handled successfully",
200, response.getStatusLine().getStatusCode());
assertEquals("Book description for id " + id + " is wrong",
"CXF in Action A B C", EntityUtils.toString(response.getEntity()));
} finally {
// Release current connection to the connection pool once you are done
get.releaseConnection();
}
}
}
| 889 |
678 | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/DataDetectorsUI.framework/DataDetectorsUI
*/
#import <DataDetectorsUI/EKEventEditViewDelegate.h>
#import <DataDetectorsUI/XXUnknownSuperclass.h>
#import <DataDetectorsUI/DataDetectorsUI-Structs.h>
@class UILabel, UIButton;
__attribute__((visibility("hidden")))
@interface DDLinksEventController : XXUnknownSuperclass <EKEventEditViewDelegate> {
@private
DDResult *_result; // 152 = 0x98
UILabel *_label; // 156 = 0x9c
UIButton *_button; // 160 = 0xa0
}
- (void)eventEditViewController:(id)controller didCompleteWithAction:(int)action; // 0xa081
- (void)buttonClicked:(id)clicked; // 0xa019
- (void)dealloc; // 0x9fd1
- (void)viewDidUnload; // 0x9fcd
- (void)didReceiveMemoryWarning; // 0x9fa1
- (id)nibBundle; // 0x9f69
- (id)nibName; // 0x9f5d
- (BOOL)shouldAutorotateToInterfaceOrientation:(int)interfaceOrientation; // 0x9f59
- (void)viewDidLoad; // 0x9e51
- (id)initWithResult:(DDResult *)result; // 0x9dfd
@end
| 401 |
763 | package org.batfish.representation.arista;
import com.google.common.collect.ImmutableSet;
import java.io.Serializable;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import org.batfish.datamodel.LineAction;
import org.batfish.datamodel.bgp.community.StandardCommunity;
@ParametersAreNonnullByDefault
public class StandardCommunityListLine implements Serializable {
private final @Nonnull LineAction _action;
private final @Nonnull Set<StandardCommunity> _communities;
public StandardCommunityListLine(LineAction action, Iterable<StandardCommunity> communities) {
_action = action;
_communities = ImmutableSet.copyOf(communities);
}
public @Nonnull LineAction getAction() {
return _action;
}
public @Nonnull Set<StandardCommunity> getCommunities() {
return _communities;
}
}
| 260 |
1,091 | <filename>apps/dhcprelay/app/src/main/java/org/onosproject/dhcprelay/store/DhcpFpmPrefixStore.java
/*
* Copyright 2017-present Open Networking Foundation
*
* 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.onosproject.dhcprelay.store;
import org.onosproject.routing.fpm.api.FpmRecord;
import org.onosproject.routing.fpm.api.FpmPrefixStore;
import org.onlab.packet.IpPrefix;
import java.util.Optional;
/**
* Interface to store DhcpFpm records.
*/
public interface DhcpFpmPrefixStore extends FpmPrefixStore {
/**
* Add a dhcp fpm record.
*
* @param prefix the route prefix in the advertisement
* @param fpmRecord the route for fpm
**/
public void addFpmRecord(IpPrefix prefix, FpmRecord fpmRecord);
/**
* Remove a dhcp fpm entry
* and return the removed record; return empty value if not exists.
*
* @param prefix the route prefix in the advertisement
* @return none
**/
public Optional<FpmRecord> removeFpmRecord(IpPrefix prefix);
}
| 503 |
1,077 | #import <Foundation/Foundation.h>
@interface QSRankCell : NSCell
@property CGFloat score;
@property NSInteger order;
@end
| 45 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Mornant","circ":"11ème circonscription","dpt":"Rhône","inscrits":4479,"abs":2159,"votants":2320,"blancs":135,"nuls":22,"exp":2163,"res":[{"nuance":"REM","nom":"<NAME>","voix":1143},{"nuance":"LR","nom":"<NAME>","voix":1020}]} | 114 |
303 | <reponame>henlo-birb/lovepotion
#pragma once
#include "objects/random/randomgenerator.h"
#include "common/lmath.h"
#include "common/module.h"
#include "common/vector.h"
#include "noise1234/noise1234.h"
#include "noise1234/simplexnoise1234.h"
#include <list>
namespace love
{
float GammaToLinear(float c);
float LinearToGamma(float c);
class Transform;
class Math : public Module
{
public:
struct Triangle
{
Triangle(const Vector2& x, const Vector2& y, const Vector2& z) : a(x), b(y), c(z)
{}
Vector2 a, b, c;
};
Math();
virtual ~Math() {};
ModuleType GetModuleType() const
{
return M_MATH;
}
const char* GetName() const override
{
return "love.math";
}
/* RandomGenerator */
RandomGenerator* GetRandomGenerator()
{
return &this->rng;
}
RandomGenerator* NewRandomGenerator();
Transform* NewTransform();
Transform* NewTransform(float x, float y, float a, float sx, float sy, float ox, float oy,
float kx, float ky);
/* LÖVE Functions */
static float GammaToLinear(float color);
static float LinearToGamma(float color);
std::vector<Triangle> Triangulate(const std::vector<Vector2>& polygon);
bool IsConvex(const std::vector<Vector2>& polygon);
private:
RandomGenerator rng;
/* Helper Functions */
inline bool IsCounterClockwise(const Vector2& a, const Vector2& b, const Vector2& c)
{
return ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) >= 0;
}
inline bool OnSameSide(const Vector2& a, const Vector2& b, const Vector2& c,
const Vector2& d)
{
float px = d.x - c.x, py = d.y - c.y;
// return det(p, a-c) * det(p, b-c) >= 0
float l = px * (a.y - c.y) - py * (a.x - c.x);
float m = px * (b.y - c.y) - py * (b.x - c.x);
return l * m >= 0;
}
inline bool PointInTriangle(const Vector2& p, const Vector2& a, const Vector2& b,
const Vector2& c)
{
return OnSameSide(p, a, b, c) && OnSameSide(p, b, a, c) && OnSameSide(p, c, a, b);
}
inline bool AnyPointInTriangle(const std::list<const Vector2*>& vertices, const Vector2& a,
const Vector2& b, const Vector2& c)
{
for (const Vector2* p : vertices)
{
if ((p != &a) && (p != &b) && (p != &c) &&
PointInTriangle(*p, a, b, c)) // oh god...
return true;
}
return false;
}
inline bool IsEar(const Vector2& a, const Vector2& b, const Vector2& c,
const std::list<const Vector2*>& vertices)
{
return IsCounterClockwise(a, b, c) && !AnyPointInTriangle(vertices, a, b, c);
}
};
} // namespace love
| 1,628 |
4,038 | <gh_stars>1000+
/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "PhongGL.h"
#if defined(MAGNUM_TARGET_GLES) || defined(MAGNUM_BUILD_DEPRECATED)
#include <Corrade/Containers/Array.h>
#endif
#include <Corrade/Containers/EnumSet.hpp>
#include <Corrade/Containers/Reference.h>
#include <Corrade/Containers/StringView.h>
#include <Corrade/Containers/StringStl.h>
#include <Corrade/Utility/FormatStl.h>
#include <Corrade/Utility/Resource.h>
#include "Magnum/GL/Context.h"
#include "Magnum/GL/Extensions.h"
#include "Magnum/GL/Shader.h"
#include "Magnum/GL/Texture.h"
#include "Magnum/Math/Color.h"
#include "Magnum/Math/Matrix3.h"
#include "Magnum/Math/Matrix4.h"
#ifndef MAGNUM_TARGET_GLES2
#include "Magnum/GL/Buffer.h"
#include "Magnum/GL/TextureArray.h"
#endif
#include "Magnum/Shaders/Implementation/CreateCompatibilityShader.h"
namespace Magnum { namespace Shaders {
namespace {
enum: Int {
AmbientTextureUnit = 0,
DiffuseTextureUnit = 1,
SpecularTextureUnit = 2,
NormalTextureUnit = 3
};
#ifndef MAGNUM_TARGET_GLES2
enum: Int {
ProjectionBufferBinding = 0,
TransformationBufferBinding = 1,
DrawBufferBinding = 2,
TextureTransformationBufferBinding = 3,
MaterialBufferBinding = 4,
LightBufferBinding = 5
};
#endif
}
PhongGL::PhongGL(const Flags flags, const UnsignedInt lightCount
#ifndef MAGNUM_TARGET_GLES2
, const UnsignedInt materialCount, const UnsignedInt drawCount
#endif
):
_flags{flags},
_lightCount{lightCount},
#ifndef MAGNUM_TARGET_GLES2
_materialCount{materialCount},
_drawCount{drawCount},
#endif
_lightColorsUniform{_lightPositionsUniform + Int(lightCount)},
_lightSpecularColorsUniform{_lightPositionsUniform + 2*Int(lightCount)},
_lightRangesUniform{_lightPositionsUniform + 3*Int(lightCount)}
{
CORRADE_ASSERT(!(flags & Flag::TextureTransformation) || (flags & (Flag::AmbientTexture|Flag::DiffuseTexture|Flag::SpecularTexture|Flag::NormalTexture)),
"Shaders::PhongGL: texture transformation enabled but the shader is not textured", );
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(flags >= Flag::InstancedObjectId) || !(flags & Flag::Bitangent),
"Shaders::PhongGL: Bitangent attribute binding conflicts with the ObjectId attribute, use a Tangent4 attribute with instanced object ID rendering instead", );
#endif
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(flags >= Flag::UniformBuffers) || materialCount,
"Shaders::PhongGL: material count can't be zero", );
CORRADE_ASSERT(!(flags >= Flag::UniformBuffers) || drawCount,
"Shaders::PhongGL: draw count can't be zero", );
#endif
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(flags & Flag::TextureArrays) || (flags & (Flag::AmbientTexture|Flag::DiffuseTexture|Flag::SpecularTexture|Flag::NormalTexture)),
"Shaders::PhongGL: texture arrays enabled but the shader is not textured", );
CORRADE_ASSERT(!(flags & Flag::UniformBuffers) || !(flags & Flag::TextureArrays) || flags >= (Flag::TextureArrays|Flag::TextureTransformation),
"Shaders::PhongGL: texture arrays require texture transformation enabled as well if uniform buffers are used", );
CORRADE_ASSERT(!(flags & Flag::LightCulling) || (flags & Flag::UniformBuffers),
"Shaders::PhongGL: light culling requires uniform buffers to be enabled", );
#endif
CORRADE_ASSERT(!(flags & Flag::SpecularTexture) || !(flags & (Flag::NoSpecular)),
"Shaders::PhongGL: specular texture requires the shader to not have specular disabled", );
#ifndef MAGNUM_TARGET_GLES
if(flags >= Flag::UniformBuffers)
MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED(GL::Extensions::ARB::uniform_buffer_object);
#endif
#ifndef MAGNUM_TARGET_GLES2
if(flags >= Flag::MultiDraw) {
#ifndef MAGNUM_TARGET_GLES
MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED(GL::Extensions::ARB::shader_draw_parameters);
#elif !defined(MAGNUM_TARGET_WEBGL)
MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED(GL::Extensions::ANGLE::multi_draw);
#else
MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED(GL::Extensions::WEBGL::multi_draw);
#endif
}
#endif
#ifndef MAGNUM_TARGET_GLES
if(flags >= Flag::TextureArrays)
MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED(GL::Extensions::EXT::texture_array);
#endif
#ifdef MAGNUM_BUILD_STATIC
/* Import resources on static build, if not already */
if(!Utility::Resource::hasGroup("MagnumShadersGL"))
importShaderResources();
#endif
Utility::Resource rs("MagnumShadersGL");
const GL::Context& context = GL::Context::current();
#ifndef MAGNUM_TARGET_GLES
CORRADE_ASSERT(!(flags >= Flag::UniformBuffers) || context.isExtensionSupported<GL::Extensions::ARB::uniform_buffer_object>(),
"Shaders::PhongGL: uniform buffers require" << GL::Extensions::ARB::uniform_buffer_object::string(), );
#endif
#ifndef MAGNUM_TARGET_GLES
const GL::Version version = context.supportedVersion({GL::Version::GL320, GL::Version::GL310, GL::Version::GL300, GL::Version::GL210});
#else
const GL::Version version = context.supportedVersion({GL::Version::GLES300, GL::Version::GLES200});
#endif
GL::Shader vert = Implementation::createCompatibilityShader(rs, version, GL::Shader::Type::Vertex);
GL::Shader frag = Implementation::createCompatibilityShader(rs, version, GL::Shader::Type::Fragment);
#ifndef MAGNUM_TARGET_GLES
std::string lightInitializer;
if(!(flags >= Flag::UniformBuffers) && lightCount) {
using namespace Containers::Literals;
/* Initializer for the light color / position / range arrays -- we need
a list of initializers joined by commas. For GLES we'll simply
upload the values directly. */
constexpr Containers::StringView lightPositionInitializerPreamble = "#define LIGHT_POSITION_INITIALIZER "_s;
constexpr Containers::StringView lightColorInitializerPreamble = "#define LIGHT_COLOR_INITIALIZER "_s;
constexpr Containers::StringView lightRangeInitializerPreamble = "#define LIGHT_RANGE_INITIALIZER "_s;
constexpr Containers::StringView lightPositionInitializerItem = "vec4(0.0, 0.0, 1.0, 0.0), "_s;
constexpr Containers::StringView lightColorInitializerItem = "vec3(1.0), "_s;
constexpr Containers::StringView lightRangeInitializerItem = "1.0/0.0, "_s;
lightInitializer.reserve(
lightPositionInitializerPreamble.size() +
lightColorInitializerPreamble.size() +
lightRangeInitializerPreamble.size() +
lightCount*(lightPositionInitializerItem.size() +
lightColorInitializerItem.size() +
lightRangeInitializerItem.size()));
lightInitializer.append(lightPositionInitializerPreamble);
for(std::size_t i = 0; i != lightCount; ++i)
lightInitializer.append(lightPositionInitializerItem);
/* Drop the last comma and add a newline at the end */
lightInitializer[lightInitializer.size() - 2] = '\n';
lightInitializer.resize(lightInitializer.size() - 1);
lightInitializer.append(lightColorInitializerPreamble);
for(std::size_t i = 0; i != lightCount; ++i)
lightInitializer.append(lightColorInitializerItem);
/* Drop the last comma and add a newline at the end */
lightInitializer[lightInitializer.size() - 2] = '\n';
lightInitializer.resize(lightInitializer.size() - 1);
lightInitializer.append(lightRangeInitializerPreamble);
for(std::size_t i = 0; i != lightCount; ++i)
lightInitializer.append(lightRangeInitializerItem);
/* Drop the last comma and add a newline at the end */
lightInitializer[lightInitializer.size() - 2] = '\n';
lightInitializer.resize(lightInitializer.size() - 1);
}
#endif
vert.addSource(flags & (Flag::AmbientTexture|Flag::DiffuseTexture|Flag::SpecularTexture|Flag::NormalTexture) ? "#define TEXTURED\n" : "")
.addSource(flags & Flag::NormalTexture ? "#define NORMAL_TEXTURE\n" : "")
.addSource(flags & Flag::Bitangent ? "#define BITANGENT\n" : "")
.addSource(flags & Flag::VertexColor ? "#define VERTEX_COLOR\n" : "")
.addSource(flags & Flag::TextureTransformation ? "#define TEXTURE_TRANSFORMATION\n" : "")
#ifndef MAGNUM_TARGET_GLES2
.addSource(flags & Flag::TextureArrays ? "#define TEXTURE_ARRAYS\n" : "")
#endif
.addSource(lightCount ? "#define HAS_LIGHTS\n" : "")
#ifndef MAGNUM_TARGET_GLES2
.addSource(flags >= Flag::InstancedObjectId ? "#define INSTANCED_OBJECT_ID\n" : "")
#endif
.addSource(flags & Flag::InstancedTransformation ? "#define INSTANCED_TRANSFORMATION\n" : "")
.addSource(flags >= Flag::InstancedTextureOffset ? "#define INSTANCED_TEXTURE_OFFSET\n" : "");
#ifndef MAGNUM_TARGET_GLES2
if(flags >= Flag::UniformBuffers) {
vert.addSource(Utility::formatString(
"#define UNIFORM_BUFFERS\n"
"#define DRAW_COUNT {}\n",
drawCount,
lightCount));
vert.addSource(flags >= Flag::MultiDraw ? "#define MULTI_DRAW\n" : "");
}
#endif
vert.addSource(rs.get("generic.glsl"))
.addSource(rs.get("Phong.vert"));
frag.addSource(flags & Flag::AmbientTexture ? "#define AMBIENT_TEXTURE\n" : "")
.addSource(flags & Flag::DiffuseTexture ? "#define DIFFUSE_TEXTURE\n" : "")
.addSource(flags & Flag::SpecularTexture ? "#define SPECULAR_TEXTURE\n" : "")
.addSource(flags & Flag::NormalTexture ? "#define NORMAL_TEXTURE\n" : "")
#ifndef MAGNUM_TARGET_GLES2
.addSource(flags & Flag::TextureArrays ? "#define TEXTURE_ARRAYS\n" : "")
#endif
.addSource(flags & Flag::Bitangent ? "#define BITANGENT\n" : "")
.addSource(flags & Flag::VertexColor ? "#define VERTEX_COLOR\n" : "")
.addSource(flags & Flag::AlphaMask ? "#define ALPHA_MASK\n" : "")
#ifndef MAGNUM_TARGET_GLES2
.addSource(flags & Flag::ObjectId ? "#define OBJECT_ID\n" : "")
.addSource(flags >= Flag::InstancedObjectId ? "#define INSTANCED_OBJECT_ID\n" : "")
#endif
.addSource(flags & Flag::NoSpecular ? "#define NO_SPECULAR\n" : "")
;
#ifndef MAGNUM_TARGET_GLES2
if(flags >= Flag::UniformBuffers) {
frag.addSource(Utility::formatString(
"#define UNIFORM_BUFFERS\n"
"#define DRAW_COUNT {}\n"
"#define MATERIAL_COUNT {}\n"
"#define LIGHT_COUNT {}\n",
drawCount,
materialCount,
lightCount));
frag.addSource(flags >= Flag::MultiDraw ? "#define MULTI_DRAW\n" : "")
.addSource(flags >= Flag::LightCulling ? "#define LIGHT_CULLING\n" : "");
} else
#endif
{
frag.addSource(Utility::formatString(
"#define LIGHT_COUNT {}\n"
"#define LIGHT_COLORS_LOCATION {}\n"
"#define LIGHT_SPECULAR_COLORS_LOCATION {}\n"
"#define LIGHT_RANGES_LOCATION {}\n",
lightCount,
_lightPositionsUniform + lightCount,
_lightPositionsUniform + 2*lightCount,
_lightPositionsUniform + 3*lightCount));
}
#ifndef MAGNUM_TARGET_GLES
if(!(flags >= Flag::UniformBuffers) && lightCount)
frag.addSource(std::move(lightInitializer));
#endif
frag.addSource(rs.get("generic.glsl"))
.addSource(rs.get("Phong.frag"));
CORRADE_INTERNAL_ASSERT_OUTPUT(GL::Shader::compile({vert, frag}));
attachShaders({vert, frag});
/* ES3 has this done in the shader directly and doesn't even provide
bindFragmentDataLocation() */
#if !defined(MAGNUM_TARGET_GLES) || defined(MAGNUM_TARGET_GLES2)
#ifndef MAGNUM_TARGET_GLES
if(!context.isExtensionSupported<GL::Extensions::ARB::explicit_attrib_location>(version))
#endif
{
bindAttributeLocation(Position::Location, "position");
if(lightCount)
bindAttributeLocation(Normal::Location, "normal");
if((flags & Flag::NormalTexture) && lightCount) {
bindAttributeLocation(Tangent::Location, "tangent");
if(flags & Flag::Bitangent)
bindAttributeLocation(Bitangent::Location, "bitangent");
}
if(flags & Flag::VertexColor)
bindAttributeLocation(Color3::Location, "vertexColor"); /* Color4 is the same */
if(flags & (Flag::AmbientTexture|Flag::DiffuseTexture|Flag::SpecularTexture))
bindAttributeLocation(TextureCoordinates::Location, "textureCoordinates");
#ifndef MAGNUM_TARGET_GLES2
if(flags & Flag::ObjectId) {
bindFragmentDataLocation(ColorOutput, "color");
bindFragmentDataLocation(ObjectIdOutput, "objectId");
}
if(flags >= Flag::InstancedObjectId)
bindAttributeLocation(ObjectId::Location, "instanceObjectId");
#endif
if(flags & Flag::InstancedTransformation)
bindAttributeLocation(TransformationMatrix::Location, "instancedTransformationMatrix");
if(flags >= Flag::InstancedTextureOffset)
bindAttributeLocation(TextureOffset::Location, "instancedTextureOffset");
}
#endif
CORRADE_INTERNAL_ASSERT_OUTPUT(link());
#ifndef MAGNUM_TARGET_GLES
if(!context.isExtensionSupported<GL::Extensions::ARB::explicit_uniform_location>(version))
#endif
{
#ifndef MAGNUM_TARGET_GLES2
if(flags >= Flag::UniformBuffers) {
if(_drawCount > 1) _drawOffsetUniform = uniformLocation("drawOffset");
} else
#endif
{
_transformationMatrixUniform = uniformLocation("transformationMatrix");
if(flags & Flag::TextureTransformation)
_textureMatrixUniform = uniformLocation("textureMatrix");
#ifndef MAGNUM_TARGET_GLES2
if(flags & Flag::TextureArrays)
_textureLayerUniform = uniformLocation("textureLayer");
#endif
_projectionMatrixUniform = uniformLocation("projectionMatrix");
_ambientColorUniform = uniformLocation("ambientColor");
if(lightCount) {
_normalMatrixUniform = uniformLocation("normalMatrix");
_diffuseColorUniform = uniformLocation("diffuseColor");
if(!(flags & Flag::NoSpecular)) {
_specularColorUniform = uniformLocation("specularColor");
_shininessUniform = uniformLocation("shininess");
}
if(flags & Flag::NormalTexture)
_normalTextureScaleUniform = uniformLocation("normalTextureScale");
_lightPositionsUniform = uniformLocation("lightPositions");
_lightColorsUniform = uniformLocation("lightColors");
if(!(flags & Flag::NoSpecular))
_lightSpecularColorsUniform = uniformLocation("lightSpecularColors");
_lightRangesUniform = uniformLocation("lightRanges");
}
if(flags & Flag::AlphaMask) _alphaMaskUniform = uniformLocation("alphaMask");
#ifndef MAGNUM_TARGET_GLES2
if(flags & Flag::ObjectId) _objectIdUniform = uniformLocation("objectId");
#endif
}
}
#ifndef MAGNUM_TARGET_GLES
if(flags && !context.isExtensionSupported<GL::Extensions::ARB::shading_language_420pack>(version))
#endif
{
if(flags & Flag::AmbientTexture) setUniform(uniformLocation("ambientTexture"), AmbientTextureUnit);
if(lightCount) {
if(flags & Flag::DiffuseTexture) setUniform(uniformLocation("diffuseTexture"), DiffuseTextureUnit);
if(flags & Flag::SpecularTexture) setUniform(uniformLocation("specularTexture"), SpecularTextureUnit);
if(flags & Flag::NormalTexture) setUniform(uniformLocation("normalTexture"), NormalTextureUnit);
}
#ifndef MAGNUM_TARGET_GLES2
if(flags >= Flag::UniformBuffers) {
setUniformBlockBinding(uniformBlockIndex("Projection"), ProjectionBufferBinding);
setUniformBlockBinding(uniformBlockIndex("Transformation"), TransformationBufferBinding);
setUniformBlockBinding(uniformBlockIndex("Draw"), DrawBufferBinding);
setUniformBlockBinding(uniformBlockIndex("Material"), MaterialBufferBinding);
if(flags & Flag::TextureTransformation)
setUniformBlockBinding(uniformBlockIndex("TextureTransformation"), TextureTransformationBufferBinding);
if(lightCount)
setUniformBlockBinding(uniformBlockIndex("Light"), LightBufferBinding);
}
#endif
}
/* Set defaults in OpenGL ES (for desktop they are set in shader code itself) */
#ifdef MAGNUM_TARGET_GLES
#ifndef MAGNUM_TARGET_GLES2
if(flags >= Flag::UniformBuffers) {
/* Draw offset is zero by default */
} else
#endif
{
/* Default to fully opaque white so we can see the textures */
if(flags & Flag::AmbientTexture) setAmbientColor(Magnum::Color4{1.0f});
else setAmbientColor(Magnum::Color4{0.0f});
setTransformationMatrix(Matrix4{Math::IdentityInit});
setProjectionMatrix(Matrix4{Math::IdentityInit});
if(lightCount) {
setDiffuseColor(Magnum::Color4{1.0f});
if(!(flags & Flag::NoSpecular)) {
setSpecularColor(Magnum::Color4{1.0f, 0.0f});
setShininess(80.0f);
}
if(flags & Flag::NormalTexture)
setNormalTextureScale(1.0f);
setLightPositions(Containers::Array<Vector4>{DirectInit, lightCount, Vector4{0.0f, 0.0f, 1.0f, 0.0f}});
Containers::Array<Magnum::Color3> colors{DirectInit, lightCount, Magnum::Color3{1.0f}};
setLightColors(colors);
if(!(flags & Flag::NoSpecular))
setLightSpecularColors(colors);
setLightRanges(Containers::Array<Float>{DirectInit, lightCount, Constants::inf()});
/* Light position is zero by default */
setNormalMatrix(Matrix3x3{Math::IdentityInit});
}
if(flags & Flag::TextureTransformation)
setTextureMatrix(Matrix3{Math::IdentityInit});
/* Texture layer is zero by default */
if(flags & Flag::AlphaMask) setAlphaMask(0.5f);
/* Object ID is zero by default */
}
#endif
}
#ifndef MAGNUM_TARGET_GLES2
PhongGL::PhongGL(const Flags flags, const UnsignedInt lightCount): PhongGL{flags, lightCount, 1, 1} {}
#endif
PhongGL& PhongGL::setAmbientColor(const Magnum::Color4& color) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setAmbientColor(): the shader was created with uniform buffers enabled", *this);
#endif
setUniform(_ambientColorUniform, color);
return *this;
}
PhongGL& PhongGL::setDiffuseColor(const Magnum::Color4& color) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setDiffuseColor(): the shader was created with uniform buffers enabled", *this);
#endif
if(_lightCount) setUniform(_diffuseColorUniform, color);
return *this;
}
PhongGL& PhongGL::setSpecularColor(const Magnum::Color4& color) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setSpecularColor(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(!(_flags >= Flag::NoSpecular),
"Shaders::PhongGL::setSpecularColor(): the shader was created with specular disabled", *this);
if(_lightCount) setUniform(_specularColorUniform, color);
return *this;
}
PhongGL& PhongGL::setShininess(Float shininess) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setShininess(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(!(_flags >= Flag::NoSpecular),
"Shaders::PhongGL::setShininess(): the shader was created with specular disabled", *this);
if(_lightCount) setUniform(_shininessUniform, shininess);
return *this;
}
PhongGL& PhongGL::setNormalTextureScale(const Float scale) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setNormalTextureScale(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(_flags & Flag::NormalTexture,
"Shaders::PhongGL::setNormalTextureScale(): the shader was not created with normal texture enabled", *this);
if(_lightCount) setUniform(_normalTextureScaleUniform, scale);
return *this;
}
PhongGL& PhongGL::setAlphaMask(Float mask) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setAlphaMask(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(_flags & Flag::AlphaMask,
"Shaders::PhongGL::setAlphaMask(): the shader was not created with alpha mask enabled", *this);
setUniform(_alphaMaskUniform, mask);
return *this;
}
#ifndef MAGNUM_TARGET_GLES2
PhongGL& PhongGL::setObjectId(UnsignedInt id) {
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setObjectId(): the shader was created with uniform buffers enabled", *this);
CORRADE_ASSERT(_flags & Flag::ObjectId,
"Shaders::PhongGL::setObjectId(): the shader was not created with object ID enabled", *this);
setUniform(_objectIdUniform, id);
return *this;
}
#endif
PhongGL& PhongGL::setTransformationMatrix(const Matrix4& matrix) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setTransformationMatrix(): the shader was created with uniform buffers enabled", *this);
#endif
setUniform(_transformationMatrixUniform, matrix);
return *this;
}
PhongGL& PhongGL::setNormalMatrix(const Matrix3x3& matrix) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setNormalMatrix(): the shader was created with uniform buffers enabled", *this);
#endif
if(_lightCount) setUniform(_normalMatrixUniform, matrix);
return *this;
}
PhongGL& PhongGL::setProjectionMatrix(const Matrix4& matrix) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setProjectionMatrix(): the shader was created with uniform buffers enabled", *this);
#endif
setUniform(_projectionMatrixUniform, matrix);
return *this;
}
PhongGL& PhongGL::setTextureMatrix(const Matrix3& matrix) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setTextureMatrix(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(_flags & Flag::TextureTransformation,
"Shaders::PhongGL::setTextureMatrix(): the shader was not created with texture transformation enabled", *this);
setUniform(_textureMatrixUniform, matrix);
return *this;
}
#ifndef MAGNUM_TARGET_GLES2
PhongGL& PhongGL::setTextureLayer(UnsignedInt id) {
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setTextureLayer(): the shader was created with uniform buffers enabled", *this);
CORRADE_ASSERT(_flags & Flag::TextureArrays,
"Shaders::PhongGL::setTextureLayer(): the shader was not created with texture arrays enabled", *this);
setUniform(_textureLayerUniform, id);
return *this;
}
#endif
PhongGL& PhongGL::setLightPositions(const Containers::ArrayView<const Vector4> positions) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setLightPositions(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(_lightCount == positions.size(),
"Shaders::PhongGL::setLightPositions(): expected" << _lightCount << "items but got" << positions.size(), *this);
if(_lightCount) setUniform(_lightPositionsUniform, positions);
return *this;
}
/* It's light, but can't be in the header because MSVC needs to know the size
of Vector3 for the initializer list use */
PhongGL& PhongGL::setLightPositions(const std::initializer_list<Vector4> positions) {
return setLightPositions(Containers::arrayView(positions));
}
#ifdef MAGNUM_BUILD_DEPRECATED
PhongGL& PhongGL::setLightPositions(const Containers::ArrayView<const Vector3> positions) {
Containers::Array<Vector4> fourComponent{NoInit, positions.size()};
for(std::size_t i = 0; i != positions.size(); ++i)
fourComponent[i] = Vector4{positions[i], 0.0f};
setLightPositions(fourComponent);
return *this;
}
PhongGL& PhongGL::setLightPositions(const std::initializer_list<Vector3> positions) {
CORRADE_IGNORE_DEPRECATED_PUSH
return setLightPositions(Containers::arrayView(positions));
CORRADE_IGNORE_DEPRECATED_POP
}
#endif
PhongGL& PhongGL::setLightPosition(const UnsignedInt id, const Vector4& position) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setLightPosition(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(id < _lightCount,
"Shaders::PhongGL::setLightPosition(): light ID" << id << "is out of bounds for" << _lightCount << "lights", *this);
setUniform(_lightPositionsUniform + id, position);
return *this;
}
#ifdef MAGNUM_BUILD_DEPRECATED
PhongGL& PhongGL::setLightPosition(UnsignedInt id, const Vector3& position) {
return setLightPosition(id, Vector4{position, 0.0f});
}
PhongGL& PhongGL::setLightPosition(const Vector3& position) {
/* Use the list variant to check the shader really has just one light */
return setLightPositions({Vector4{position, 0.0f}});
}
#endif
PhongGL& PhongGL::setLightColors(const Containers::ArrayView<const Magnum::Color3> colors) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setLightColors(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(_lightCount == colors.size(),
"Shaders::PhongGL::setLightColors(): expected" << _lightCount << "items but got" << colors.size(), *this);
if(_lightCount) setUniform(_lightColorsUniform, colors);
return *this;
}
#ifdef MAGNUM_BUILD_DEPRECATED
PhongGL& PhongGL::setLightColors(const Containers::ArrayView<const Magnum::Color4> colors) {
Containers::Array<Magnum::Color3> threeComponent{NoInit, colors.size()};
for(std::size_t i = 0; i != colors.size(); ++i)
threeComponent[i] = colors[i].rgb();
setLightColors(threeComponent);
return *this;
}
PhongGL& PhongGL::setLightColors(const std::initializer_list<Magnum::Color4> colors) {
CORRADE_IGNORE_DEPRECATED_PUSH
return setLightColors(Containers::arrayView(colors));
CORRADE_IGNORE_DEPRECATED_POP
}
#endif
PhongGL& PhongGL::setLightColors(const std::initializer_list<Magnum::Color3> colors) {
return setLightColors(Containers::arrayView(colors));
}
PhongGL& PhongGL::setLightColor(const UnsignedInt id, const Magnum::Color3& color) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setLightColor(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(id < _lightCount,
"Shaders::PhongGL::setLightColor(): light ID" << id << "is out of bounds for" << _lightCount << "lights", *this);
setUniform(_lightColorsUniform + id, color);
return *this;
}
#ifdef MAGNUM_BUILD_DEPRECATED
PhongGL& PhongGL::setLightColor(UnsignedInt id, const Magnum::Color4& color) {
return setLightColor(id, color.rgb());
}
PhongGL& PhongGL::setLightColor(const Magnum::Color4& color) {
/* Use the list variant to check the shader really has just one light */
return setLightColors({color.rgb()});
}
#endif
PhongGL& PhongGL::setLightSpecularColors(const Containers::ArrayView<const Magnum::Color3> colors) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setLightSpecularColors(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(_lightCount == colors.size(),
"Shaders::PhongGL::setLightSpecularColors(): expected" << _lightCount << "items but got" << colors.size(), *this);
CORRADE_ASSERT(!(_flags >= Flag::NoSpecular),
"Shaders::PhongGL::setLightSpecularColors(): the shader was created with specular disabled", *this);
if(_lightCount) setUniform(_lightSpecularColorsUniform, colors);
return *this;
}
PhongGL& PhongGL::setLightSpecularColors(const std::initializer_list<Magnum::Color3> colors) {
return setLightSpecularColors(Containers::arrayView(colors));
}
PhongGL& PhongGL::setLightSpecularColor(const UnsignedInt id, const Magnum::Color3& color) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setLightSpecularColor(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(id < _lightCount,
"Shaders::PhongGL::setLightSpecularColor(): light ID" << id << "is out of bounds for" << _lightCount << "lights", *this);
CORRADE_ASSERT(!(_flags >= Flag::NoSpecular),
"Shaders::PhongGL::setLightSpecularColor(): the shader was created with specular disabled", *this);
setUniform(_lightSpecularColorsUniform + id, color);
return *this;
}
PhongGL& PhongGL::setLightRanges(const Containers::ArrayView<const Float> ranges) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setLightRanges(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(_lightCount == ranges.size(),
"Shaders::PhongGL::setLightRanges(): expected" << _lightCount << "items but got" << ranges.size(), *this);
if(_lightCount) setUniform(_lightRangesUniform, ranges);
return *this;
}
PhongGL& PhongGL::setLightRanges(const std::initializer_list<Float> ranges) {
return setLightRanges(Containers::arrayView(ranges));
}
PhongGL& PhongGL::setLightRange(const UnsignedInt id, const Float range) {
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags >= Flag::UniformBuffers),
"Shaders::PhongGL::setLightRange(): the shader was created with uniform buffers enabled", *this);
#endif
CORRADE_ASSERT(id < _lightCount,
"Shaders::PhongGL::setLightRange(): light ID" << id << "is out of bounds for" << _lightCount << "lights", *this);
setUniform(_lightRangesUniform + id, range);
return *this;
}
#ifndef MAGNUM_TARGET_GLES2
PhongGL& PhongGL::setDrawOffset(const UnsignedInt offset) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::setDrawOffset(): the shader was not created with uniform buffers enabled", *this);
CORRADE_ASSERT(offset < _drawCount,
"Shaders::PhongGL::setDrawOffset(): draw offset" << offset << "is out of bounds for" << _drawCount << "draws", *this);
if(_drawCount > 1) setUniform(_drawOffsetUniform, offset);
return *this;
}
PhongGL& PhongGL::bindProjectionBuffer(GL::Buffer& buffer) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindProjectionBuffer(): the shader was not created with uniform buffers enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, ProjectionBufferBinding);
return *this;
}
PhongGL& PhongGL::bindProjectionBuffer(GL::Buffer& buffer, const GLintptr offset, const GLsizeiptr size) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindProjectionBuffer(): the shader was not created with uniform buffers enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, ProjectionBufferBinding, offset, size);
return *this;
}
PhongGL& PhongGL::bindTransformationBuffer(GL::Buffer& buffer) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindTransformationBuffer(): the shader was not created with uniform buffers enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, TransformationBufferBinding);
return *this;
}
PhongGL& PhongGL::bindTransformationBuffer(GL::Buffer& buffer, const GLintptr offset, const GLsizeiptr size) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindTransformationBuffer(): the shader was not created with uniform buffers enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, TransformationBufferBinding, offset, size);
return *this;
}
PhongGL& PhongGL::bindDrawBuffer(GL::Buffer& buffer) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindDrawBuffer(): the shader was not created with uniform buffers enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, DrawBufferBinding);
return *this;
}
PhongGL& PhongGL::bindDrawBuffer(GL::Buffer& buffer, const GLintptr offset, const GLsizeiptr size) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindDrawBuffer(): the shader was not created with uniform buffers enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, DrawBufferBinding, offset, size);
return *this;
}
PhongGL& PhongGL::bindTextureTransformationBuffer(GL::Buffer& buffer) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindTextureTransformationBuffer(): the shader was not created with uniform buffers enabled", *this);
CORRADE_ASSERT(_flags & Flag::TextureTransformation,
"Shaders::PhongGL::bindTextureTransformationBuffer(): the shader was not created with texture transformation enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, TextureTransformationBufferBinding);
return *this;
}
PhongGL& PhongGL::bindTextureTransformationBuffer(GL::Buffer& buffer, const GLintptr offset, const GLsizeiptr size) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindTextureTransformationBuffer(): the shader was not created with uniform buffers enabled", *this);
CORRADE_ASSERT(_flags & Flag::TextureTransformation,
"Shaders::PhongGL::bindTextureTransformationBuffer(): the shader was not created with texture transformation enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, TextureTransformationBufferBinding, offset, size);
return *this;
}
PhongGL& PhongGL::bindMaterialBuffer(GL::Buffer& buffer) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindMaterialBuffer(): the shader was not created with uniform buffers enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, MaterialBufferBinding);
return *this;
}
PhongGL& PhongGL::bindMaterialBuffer(GL::Buffer& buffer, const GLintptr offset, const GLsizeiptr size) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindMaterialBuffer(): the shader was not created with uniform buffers enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, MaterialBufferBinding, offset, size);
return *this;
}
PhongGL& PhongGL::bindLightBuffer(GL::Buffer& buffer) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindLightBuffer(): the shader was not created with uniform buffers enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, LightBufferBinding);
return *this;
}
PhongGL& PhongGL::bindLightBuffer(GL::Buffer& buffer, const GLintptr offset, const GLsizeiptr size) {
CORRADE_ASSERT(_flags >= Flag::UniformBuffers,
"Shaders::PhongGL::bindLightBuffer(): the shader was not created with uniform buffers enabled", *this);
buffer.bind(GL::Buffer::Target::Uniform, LightBufferBinding, offset, size);
return *this;
}
#endif
PhongGL& PhongGL::bindAmbientTexture(GL::Texture2D& texture) {
CORRADE_ASSERT(_flags & Flag::AmbientTexture,
"Shaders::PhongGL::bindAmbientTexture(): the shader was not created with ambient texture enabled", *this);
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags & Flag::TextureArrays),
"Shaders::PhongGL::bindAmbientTexture(): the shader was created with texture arrays enabled, use a Texture2DArray instead", *this);
#endif
texture.bind(AmbientTextureUnit);
return *this;
}
#ifndef MAGNUM_TARGET_GLES2
PhongGL& PhongGL::bindAmbientTexture(GL::Texture2DArray& texture) {
CORRADE_ASSERT(_flags & Flag::AmbientTexture,
"Shaders::PhongGL::bindAmbientTexture(): the shader was not created with ambient texture enabled", *this);
CORRADE_ASSERT(_flags & Flag::TextureArrays,
"Shaders::PhongGL::bindAmbientTexture(): the shader was not created with texture arrays enabled, use a Texture2D instead", *this);
texture.bind(AmbientTextureUnit);
return *this;
}
#endif
PhongGL& PhongGL::bindDiffuseTexture(GL::Texture2D& texture) {
CORRADE_ASSERT(_flags & Flag::DiffuseTexture,
"Shaders::PhongGL::bindDiffuseTexture(): the shader was not created with diffuse texture enabled", *this);
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags & Flag::TextureArrays),
"Shaders::PhongGL::bindDiffuseTexture(): the shader was created with texture arrays enabled, use a Texture2DArray instead", *this);
#endif
if(_lightCount) texture.bind(DiffuseTextureUnit);
return *this;
}
#ifndef MAGNUM_TARGET_GLES2
PhongGL& PhongGL::bindDiffuseTexture(GL::Texture2DArray& texture) {
CORRADE_ASSERT(_flags & Flag::DiffuseTexture,
"Shaders::PhongGL::bindDiffuseTexture(): the shader was not created with diffuse texture enabled", *this);
CORRADE_ASSERT(_flags & Flag::TextureArrays,
"Shaders::PhongGL::bindDiffuseTexture(): the shader was not created with texture arrays enabled, use a Texture2D instead", *this);
if(_lightCount) texture.bind(DiffuseTextureUnit);
return *this;
}
#endif
PhongGL& PhongGL::bindSpecularTexture(GL::Texture2D& texture) {
CORRADE_ASSERT(_flags & Flag::SpecularTexture,
"Shaders::PhongGL::bindSpecularTexture(): the shader was not created with specular texture enabled", *this);
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags & Flag::TextureArrays),
"Shaders::PhongGL::bindSpecularTexture(): the shader was created with texture arrays enabled, use a Texture2DArray instead", *this);
#endif
if(_lightCount) texture.bind(SpecularTextureUnit);
return *this;
}
#ifndef MAGNUM_TARGET_GLES2
PhongGL& PhongGL::bindSpecularTexture(GL::Texture2DArray& texture) {
CORRADE_ASSERT(_flags & Flag::SpecularTexture,
"Shaders::PhongGL::bindSpecularTexture(): the shader was not created with specular texture enabled", *this);
CORRADE_ASSERT(_flags & Flag::TextureArrays,
"Shaders::PhongGL::bindSpecularTexture(): the shader was not created with texture arrays enabled, use a Texture2D instead", *this);
if(_lightCount) texture.bind(SpecularTextureUnit);
return *this;
}
#endif
PhongGL& PhongGL::bindNormalTexture(GL::Texture2D& texture) {
CORRADE_ASSERT(_flags & Flag::NormalTexture,
"Shaders::PhongGL::bindNormalTexture(): the shader was not created with normal texture enabled", *this);
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags & Flag::TextureArrays),
"Shaders::PhongGL::bindNormalTexture(): the shader was created with texture arrays enabled, use a Texture2DArray instead", *this);
#endif
if(_lightCount) texture.bind(NormalTextureUnit);
return *this;
}
#ifndef MAGNUM_TARGET_GLES2
PhongGL& PhongGL::bindNormalTexture(GL::Texture2DArray& texture) {
CORRADE_ASSERT(_flags & Flag::NormalTexture,
"Shaders::PhongGL::bindNormalTexture(): the shader was not created with normal texture enabled", *this);
CORRADE_ASSERT(_flags & Flag::TextureArrays,
"Shaders::PhongGL::bindNormalTexture(): the shader was not created with texture arrays enabled, use a Texture2D instead", *this);
if(_lightCount) texture.bind(NormalTextureUnit);
return *this;
}
#endif
PhongGL& PhongGL::bindTextures(GL::Texture2D* ambient, GL::Texture2D* diffuse, GL::Texture2D* specular, GL::Texture2D* normal) {
CORRADE_ASSERT(_flags & (Flag::AmbientTexture|Flag::DiffuseTexture|Flag::SpecularTexture|Flag::NormalTexture),
"Shaders::PhongGL::bindTextures(): the shader was not created with any textures enabled", *this);
#ifndef MAGNUM_TARGET_GLES2
CORRADE_ASSERT(!(_flags & Flag::TextureArrays),
"Shaders::PhongGL::bindTextures(): the shader was created with texture arrays enabled, use a Texture2DArray instead", *this);
#endif
GL::AbstractTexture::bind(AmbientTextureUnit, {ambient, diffuse, specular, normal});
return *this;
}
Debug& operator<<(Debug& debug, const PhongGL::Flag value) {
debug << "Shaders::PhongGL::Flag" << Debug::nospace;
switch(value) {
/* LCOV_EXCL_START */
#define _c(v) case PhongGL::Flag::v: return debug << "::" #v;
_c(AmbientTexture)
_c(DiffuseTexture)
_c(SpecularTexture)
_c(NormalTexture)
_c(Bitangent)
_c(AlphaMask)
_c(VertexColor)
_c(TextureTransformation)
#ifndef MAGNUM_TARGET_GLES2
_c(InstancedObjectId)
_c(ObjectId)
#endif
_c(InstancedTransformation)
_c(InstancedTextureOffset)
#ifndef MAGNUM_TARGET_GLES2
_c(UniformBuffers)
_c(MultiDraw)
_c(TextureArrays)
_c(LightCulling)
#endif
_c(NoSpecular)
#undef _c
/* LCOV_EXCL_STOP */
}
return debug << "(" << Debug::nospace << reinterpret_cast<void*>(UnsignedInt(value)) << Debug::nospace << ")";
}
Debug& operator<<(Debug& debug, const PhongGL::Flags value) {
return Containers::enumSetDebugOutput(debug, value, "Shaders::PhongGL::Flags{}", {
PhongGL::Flag::AmbientTexture,
PhongGL::Flag::DiffuseTexture,
PhongGL::Flag::SpecularTexture,
PhongGL::Flag::NormalTexture,
PhongGL::Flag::Bitangent,
PhongGL::Flag::AlphaMask,
PhongGL::Flag::VertexColor,
PhongGL::Flag::InstancedTextureOffset, /* Superset of TextureTransformation */
PhongGL::Flag::TextureTransformation,
#ifndef MAGNUM_TARGET_GLES2
PhongGL::Flag::InstancedObjectId, /* Superset of ObjectId */
PhongGL::Flag::ObjectId,
#endif
PhongGL::Flag::InstancedTransformation,
#ifndef MAGNUM_TARGET_GLES2
PhongGL::Flag::MultiDraw, /* Superset of UniformBuffers */
PhongGL::Flag::UniformBuffers,
PhongGL::Flag::TextureArrays,
PhongGL::Flag::LightCulling,
#endif
PhongGL::Flag::NoSpecular
});
}
}}
| 16,949 |
328 | <reponame>junka007/springBoot-demos<gh_stars>100-1000
package com.ctg.test.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource(locations= {"classpath:remote-httpinvoke.xml","classpath:remote-rmi.xml","classpath:remote-hessian.xml"})
public class ApiServerApplication {
public static void main(String[] args) {
SpringApplication.run(ApiServerApplication.class, args);
}
}
| 176 |
2,151 | <reponame>mxzeng/gestures<gh_stars>1000+
// Copyright (c) 2014 The Chromium OS 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 GESTURES_COMPILER_SPECIFIC_H_
#define GESTURES_COMPILER_SPECIFIC_H_
// Compiler detection.
#if defined(__GNUC__)
#define COMPILER_GCC 1
#elif defined(_MSC_VER)
#define COMPILER_MSVC 1
#else
#error Please add support for your compiler in compiler_specific.h
#endif
// Tell the compiler a function is using a printf-style format string.
// |format_param| is the one-based index of the format string parameter;
// |dots_param| is the one-based index of the "..." parameter.
// For v*printf functions (which take a va_list), pass 0 for dots_param.
// (This is undocumented but matches what the system C headers do.)
#if defined(COMPILER_GCC)
#define PRINTF_FORMAT(format_param, dots_param) \
__attribute__((format(printf, format_param, dots_param)))
#else
#define PRINTF_FORMAT(format_param, dots_param)
#endif
#endif // GESTURES_COMPILER_SPECIFIC_H_
| 359 |
606 | <reponame>H07000223/FlycoBanner_Master
package com.flyco.bannersamples.utils;
import android.support.v4.view.ViewPager;
import com.flyco.banner.transform.DepthTransformer;
import com.flyco.banner.transform.FadeSlideTransformer;
import com.flyco.banner.transform.FlowTransformer;
import com.flyco.banner.transform.RotateDownTransformer;
import com.flyco.banner.transform.RotateUpTransformer;
import com.flyco.banner.transform.ZoomOutSlideTransformer;
import com.flyco.bannersamples.R;
import com.flyco.bannersamples.entity.BannerItem;
import java.util.ArrayList;
public class DataProvider {
public static String[] titles = new String[]{
"伪装者:胡歌演绎'痞子特工'",
"无心法师:生死离别!月牙遭虐杀",
"花千骨:尊上沦为花千骨",
"综艺饭:胖轩偷看夏天洗澡掀波澜",
"碟中谍4:阿汤哥高塔命悬一线,超越不可能",
};
public static String[] urls = new String[]{//640*360 360/640=0.5625
"http://photocdn.sohu.com/tvmobilemvms/20150907/144160323071011277.jpg",//伪装者:胡歌演绎"痞子特工"
"http://photocdn.sohu.com/tvmobilemvms/20150907/144158380433341332.jpg",//无心法师:生死离别!月牙遭虐杀
"http://photocdn.sohu.com/tvmobilemvms/20150907/144160286644953923.jpg",//花千骨:尊上沦为花千骨
"http://photocdn.sohu.com/tvmobilemvms/20150902/144115156939164801.jpg",//综艺饭:胖轩偷看夏天洗澡掀波澜
"http://photocdn.sohu.com/tvmobilemvms/20150907/144159406950245847.jpg",//碟中谍4:阿汤哥高塔命悬一线,超越不可能
};
public static ArrayList<BannerItem> getList() {
ArrayList<BannerItem> list = new ArrayList<>();
for (int i = 0; i < urls.length; i++) {
BannerItem item = new BannerItem();
item.imgUrl = urls[i];
item.title = titles[i];
list.add(item);
}
return list;
}
public static ArrayList<Integer> geUsertGuides() {
ArrayList<Integer> list = new ArrayList<>();
list.add(R.mipmap.guide_img_1);
list.add(R.mipmap.guide_img_2);
list.add(R.mipmap.guide_img_3);
list.add(R.mipmap.guide_img_4);
return list;
}
public static Class<? extends ViewPager.PageTransformer> transformers[] = new Class[]{
DepthTransformer.class,
FadeSlideTransformer.class,
FlowTransformer.class,
RotateDownTransformer.class,
RotateUpTransformer.class,
ZoomOutSlideTransformer.class,
};
}
| 1,339 |
3,459 | //
// Copyright (c) 2004 <NAME>
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from
// the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
//////////////////////////////////////////////////////////////////////////////
// Handy - An Atari Lynx Emulator //
// Copyright (c) 1996,1997 //
// <NAME> //
//////////////////////////////////////////////////////////////////////////////
// RAM object header file //
//////////////////////////////////////////////////////////////////////////////
// //
// This header file provides the interface definition for the RAM class //
// that emulates the Handy system RAM (64K) //
// //
// <NAME> //
// August 1997 //
// //
//////////////////////////////////////////////////////////////////////////////
// Revision History: //
// ----------------- //
// //
// 01Aug1997 KW Document header added & class documented. //
// //
//////////////////////////////////////////////////////////////////////////////
#ifndef RAM_H
#define RAM_H
#define RAM_SIZE 65536
#define RAM_ADDR_MASK 0xffff
#define DEFAULT_RAM_CONTENTS 0xff
class CRam : public CLynxBase
{
// Function members
public:
enum { HEADER_RAW_SIZE = 10 };
CRam(Stream* fp) MDFN_COLD;
~CRam() MDFN_COLD;
static bool TestMagic(const uint8* data, uint64 test_size) MDFN_COLD;
public:
void Reset(void) MDFN_COLD;
void Poke(uint32 addr, uint8 data){ mRamData[(uint16)addr]=data;};
uint8 Peek(uint32 addr){ return(mRamData[(uint16)addr]);};
uint32 ReadCycle(void) {return 5;};
uint32 WriteCycle(void) {return 5;};
uint32 ObjectSize(void) {return RAM_SIZE;};
uint8* GetRamPointer(void) { return mRamData; };
uint8 MD5[16];
uint32 InfoRAMSize;
// Data members
private:
uint8 mRamData[RAM_SIZE];
std::unique_ptr<uint8[]> mRamXORData;
uint16 boot_addr;
};
#endif
| 1,598 |
348 | {"nom":"Novella","circ":"2ème circonscription","dpt":"Haute-Corse","inscrits":109,"abs":48,"votants":61,"blancs":3,"nuls":3,"exp":55,"res":[{"nuance":"REM","nom":"<NAME>","voix":29},{"nuance":"REG","nom":"<NAME>","voix":26}]} | 91 |
2,707 | <reponame>ronaldocan/jetlinks-community
package org.jetlinks.community.network.tcp.parser.strateies;
import io.vertx.core.buffer.Buffer;
import org.jetlinks.community.ValueObject;
import org.jetlinks.community.network.tcp.parser.PayloadParser;
import org.jetlinks.core.Values;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class FixLengthPayloadParserBuilderTest {
@Test
void testFixLength() {
FixLengthPayloadParserBuilder builder = new FixLengthPayloadParserBuilder();
PayloadParser parser = builder.build(ValueObject.of(Collections.singletonMap("size", 5)));
List<String> arr = new ArrayList<>();
parser.handlePayload()
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
.subscribe(arr::add);
parser.handle(Buffer.buffer("123"));
parser.handle(Buffer.buffer("4567"));
parser.handle(Buffer.buffer("890"));
Assert.assertArrayEquals(arr.toArray(),new Object[]{
"12345","67890"
});
}
@Test
void testDelimited() {
DelimitedPayloadParserBuilder builder = new DelimitedPayloadParserBuilder();
PayloadParser parser = builder.build(ValueObject.of(Collections.singletonMap("delimited", "@@")));
List<String> arr = new ArrayList<>();
parser.handlePayload()
.map(buffer -> buffer.toString(StandardCharsets.UTF_8))
.subscribe(arr::add);
parser.handle(Buffer.buffer("123"));
parser.handle(Buffer.buffer("45@@67"));
parser.handle(Buffer.buffer("890@@111"));
Assert.assertArrayEquals(arr.toArray(),new Object[]{
"12345","67890"
});
}
} | 758 |
1,350 | <reponame>Manny27nyc/azure-sdk-for-java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.mediaservices.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Class for NoEncryption scheme. */
@Fluent
public final class NoEncryption {
@JsonIgnore private final ClientLogger logger = new ClientLogger(NoEncryption.class);
/*
* Representing supported protocols
*/
@JsonProperty(value = "enabledProtocols")
private EnabledProtocols enabledProtocols;
/**
* Get the enabledProtocols property: Representing supported protocols.
*
* @return the enabledProtocols value.
*/
public EnabledProtocols enabledProtocols() {
return this.enabledProtocols;
}
/**
* Set the enabledProtocols property: Representing supported protocols.
*
* @param enabledProtocols the enabledProtocols value to set.
* @return the NoEncryption object itself.
*/
public NoEncryption withEnabledProtocols(EnabledProtocols enabledProtocols) {
this.enabledProtocols = enabledProtocols;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (enabledProtocols() != null) {
enabledProtocols().validate();
}
}
}
| 579 |
353 | #pragma once
#include <c10/core/DeviceType.h>
#include <c10/core/DispatchKey.h>
#include <c10/util/Exception.h>
namespace c10 {
/**
* QEngine is an enum that is used to select the engine to run quantized ops.
* Keep this enum in sync with get_qengine_id() in
* torch/backends/quantized/__init__.py
*/
enum class QEngine : uint8_t {
NoQEngine = 0,
FBGEMM = 1,
QNNPACK = 2,
};
constexpr auto kNoQEngine = QEngine::NoQEngine;
constexpr auto kFBGEMM = QEngine::FBGEMM;
constexpr auto kQNNPACK = QEngine::QNNPACK;
inline std::string toString(QEngine qengine) {
switch (qengine) {
case kNoQEngine:
return "NoQEngine";
case kFBGEMM:
return "FBGEMM";
case kQNNPACK:
return "QNNPACK";
default:
TORCH_CHECK(
false,
"Unrecognized Quantized Engine: ",
static_cast<int>(qengine));
}
}
} // namespace c10
| 415 |
575 | <reponame>yxlao/webrtc-cpp-sample<filename>webrtc/include/third_party/blink/renderer/core/layout/ng/ng_outline_type.h
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_OUTLINE_TYPE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_OUTLINE_TYPE_H_
namespace blink {
// Outline styles
enum class NGOutlineType {
kDontIncludeBlockVisualOverflow, // Standard outline
kIncludeBlockVisualOverflow, // Focus outline
};
} // namespace blink
#endif
| 231 |
1,513 | <gh_stars>1000+
/*
*Copyright (c) 2013-2013, yinqiwen <<EMAIL>>
*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 Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
*AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
*IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
*ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
*CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
*SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
*INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
*CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
*ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
*THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TIMER_TASK_QUEUE_HPP_
#define TIMER_TASK_QUEUE_HPP_
#include "common.hpp"
#include "timer_task.hpp"
namespace ardb
{
class TimerTaskQueue
{
private:
TimerTask** m_queue;
uint32 m_queue_capacity;
uint32 m_size;
void FixUp(uint32 k);
void FixDown(uint32 k);
public:
TimerTaskQueue();
inline uint32 GetSize()
{
return m_size;
}
inline bool IsEmpty()
{
return m_size == 0;
}
void Add(TimerTask* task);
TimerTask* Get(uint32 i);
TimerTask* GetMin();
void RemoveMin();
void QuickRemove(uint32 i);
void Heapify();
void Clear();
int32 FindTaskIndex(TimerTask* task);
void RescheduleMin(uint64 newTime);
bool RescheduleTask(TimerTask* task, uint64 newTime);
~TimerTaskQueue();
};
}
#endif /* TIMER_TASK_QUEUE_HPP_ */
| 822 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-whwq-93f8-2jg6",
"modified": "2022-05-01T06:37:04Z",
"published": "2022-05-01T06:37:04Z",
"aliases": [
"CVE-2006-0014"
],
"details": "Buffer overflow in Microsoft Outlook Express 5.5 and 6 allows remote attackers to execute arbitrary code via a crafted Windows Address Book (WAB) file containing \"certain Unicode strings\" and modified length values.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2006-0014"
},
{
"type": "WEB",
"url": "https://docs.microsoft.com/en-us/security-updates/securitybulletins/2006/ms06-016"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/25535"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A1611"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A1682"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A1769"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A1771"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A1780"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A1791"
},
{
"type": "WEB",
"url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A812"
},
{
"type": "WEB",
"url": "http://lists.grok.org.uk/pipermail/full-disclosure/2006-April/045003.html"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/19617"
},
{
"type": "WEB",
"url": "http://securityreason.com/securityalert/691"
},
{
"type": "WEB",
"url": "http://securitytracker.com/id?1015898"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/archive/1/430645/100/0/threaded"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/17459"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2006/1321"
},
{
"type": "WEB",
"url": "http://www.zerodayinitiative.com/advisories/ZDI-06-007.html"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 1,314 |
7,353 | /**
* @file OTPCalculator.h
* @author <NAME> <<EMAIL>>
*
* @section LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the author 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 AUTHOR 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.
*
* @section DESCRIPTION
*
* Object that calculates OTPs.
*/
#ifndef BADVPN_SECURITY_OTPCALCULATOR_H
#define BADVPN_SECURITY_OTPCALCULATOR_H
#include <stdlib.h>
#include <string.h>
#include <misc/balign.h>
#include <misc/debug.h>
#include <security/BRandom.h>
#include <security/BEncryption.h>
#include <base/DebugObject.h>
/**
* Type for an OTP.
*/
typedef uint32_t otp_t;
/**
* Object that calculates OTPs.
*/
typedef struct {
DebugObject d_obj;
int num_otps;
int cipher;
int block_size;
size_t num_blocks;
otp_t *data;
} OTPCalculator;
/**
* Initializes the calculator.
* {@link BSecurity_GlobalInitThreadSafe} must have been done if this object
* will be used from a non-main thread.
*
* @param calc the object
* @param num_otps number of OTPs to generate from a seed. Must be >=0.
* @param cipher encryption cipher for calculating the OTPs. Must be valid
* according to {@link BEncryption_cipher_valid}.
* @return 1 on success, 0 on failure
*/
int OTPCalculator_Init (OTPCalculator *calc, int num_otps, int cipher) WARN_UNUSED;
/**
* Frees the calculator.
*
* @param calc the object
*/
void OTPCalculator_Free (OTPCalculator *calc);
/**
* Generates OTPs from the given key and IV.
*
* @param calc the object
* @param key encryption key
* @param iv initialization vector
* @param shuffle whether to shuffle the OTPs. Must be 1 or 0.
* @return pointer to an array of 32-bit OPTs. Constains as many OTPs as was specified
* in {@link OTPCalculator_Init}. Valid until the next generation or
* until the object is freed.
*/
otp_t * OTPCalculator_Generate (OTPCalculator *calc, uint8_t *key, uint8_t *iv, int shuffle);
#endif
| 1,066 |
2,270 | <gh_stars>1000+
//------------------------------------------------------------------------
// Project : VST SDK
//
// Category : Interfaces
// Filename : pluginterfaces/vst/ivstparameterfunctionname.h
// Created by : Steinberg, 03/2020
// Description : VST Parameter Function Name Interface
//
//-----------------------------------------------------------------------------
// This file is part of a Steinberg SDK. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this distribution
// and at www.steinberg.net/sdklicenses.
// No part of the SDK, including this file, may be copied, modified, propagated,
// or distributed except according to the terms contained in the LICENSE file.
//-----------------------------------------------------------------------------
#pragma once
#include "pluginterfaces/base/funknown.h"
#include "pluginterfaces/vst/vsttypes.h"
//------------------------------------------------------------------------
#include "pluginterfaces/base/falignpush.h"
//------------------------------------------------------------------------
//------------------------------------------------------------------------
namespace Steinberg {
namespace Vst {
namespace FunctionNameType {
//--------------------------------------------------------------------
const CString kCompGainReduction = "Comp:GainReduction"; /** */
const CString kCompGainReductionMax = "Comp:GainReductionMax";
const CString kCompGainReductionPeakHold = "Comp:GainReductionPeakHold";
const CString kCompResetGainReductionMax = "Comp:ResetGainReductionMax";
const CString kLowLatencyMode = "LowLatencyMode"; /** Useful for live situation where low
latency is required:
0 means LowLatency disable,
1 means LowLatency enable */
const CString kDryWetMix = "DryWetMix"; /** Allowing to mix the original (Dry) Signal with the processed one (Wet):
0.0 means Dry Signal only,
0.5 means 50% Dry Signal + 50% Wet Signal,
1.0 means Wet Signal only */
const CString kRandomize = "Randomize"; /** Allow to assign some randomized values to some
parameters in a controlled way*/
} // FunctionNameType
//------------------------------------------------------------------------
/** Edit controller component interface extension: Vst::IParameterFunctionName
\ingroup vstIPlug vst370
- [plug imp]
- [extends IEditController]
- [released: 3.7.0]
- [optional]
This interface allows the host to get a parameter associated to a specific meaning (a functionName) for a given unit.
The host can use this information, for example, for drawing a Gain Reduction meter in its own UI.
In order to get the plain value of this parameter, the host should use the IEditController::normalizedParamToPlain.
The host can automatically map parameters to dedicated UI controls, such as the wet-dry mix knob or Randomize button.
\section IParameterFunctionNameExample Example
\code{.cpp}
//------------------------------------------------------------------------
// here an example of how a VST3 plug-in could support this IParameterFunctionName interface.
// we need to define somewhere the iids:
in MyController class declaration
class MyController : public Vst::EditController, public Vst::IParameterFunctionName
{
...
tresult PLUGIN_API getParameterIDFromFunctionName (UnitID unitID, FIDString functionName,
Vst::ParamID& paramID) override;
...
OBJ_METHODS (MyController, Vst::EditController)
DEFINE_INTERFACES
...
DEF_INTERFACE (Vst::IParameterFunctionName)
END_DEFINE_INTERFACES (Vst::EditController)
...
}
#include "ivstparameterfunctionname.h"
namespace Steinberg {
namespace Vst {
DEF_CLASS_IID (IParameterFunctionName)
}
}
//------------------------------------------------------------------------
tresult PLUGIN_API MyController::getParameterIDFromFunctionName (UnitID unitID, FIDString functionName,
Vst::ParamID& paramID)
{
using namespace Vst;
paramID = kNoParamId;
if (unitID == kRootUnitId && FIDStringsEqual (functionName, kCompGainReduction))
paramID = kMyGainReductionId;
return (paramID != kNoParamId) ? kResultOk : kResultFalse;
}
//--- a host implementation example: --------------------
...
FUnknownPtr<Vst::IParameterFunctionName> functionName (mEditController->getIEditController ());
if (functionName)
{
Vst::ParamID paramID;
if (functionName->getParameterIDFromFunctionName (Vst::FunctionNameType::kCompGainReduction, paramID) == kResultTrue)
{
// paramID could be cached for performance issue
ParamValue norm = mEditController->getIEditController ()->getParamNormalized (paramID);
ParamValue plain = mEditController->getIEditController ()->normalizedParamToPlain (paramID, norm);
// plain is something like -6 (-6dB)
}
}
\endcode
*/
class IParameterFunctionName : public FUnknown
{
public:
//------------------------------------------------------------------------
/** Gets for the given unitID the associated paramID to a function Name.
Returns kResultFalse when no found parameter (paramID is set to kNoParamId in this case). */
virtual tresult PLUGIN_API getParameterIDFromFunctionName (UnitID unitID, FIDString functionName, ParamID& paramID) = 0;
//------------------------------------------------------------------------
static const FUID iid;
};
DECLARE_CLASS_IID (IParameterFunctionName, 0x6D21E1DC, 0x91199D4B, 0xA2A02FEF, 0x6C1AE55C)
//------------------------------------------------------------------------
} // namespace Vst
} // namespace Steinberg
//------------------------------------------------------------------------
#include "pluginterfaces/base/falignpop.h"
//------------------------------------------------------------------------
| 1,679 |
303 | <filename>include/objects/box2d/fixture/wrap_fixture.h
#pragma once
#include "common/luax.h"
#include "fixture.h"
namespace Wrap_Fixture
{
int GetType(lua_State* L);
int SetFriction(lua_State* L);
int SetRestitution(lua_State* L);
int SetDensity(lua_State* L);
int SetSensor(lua_State* L);
int GetFriction(lua_State* L);
int GetRestitution(lua_State* L);
int GetDensity(lua_State* L);
int IsSensor(lua_State* L);
int GetBody(lua_State* L);
int GetShape(lua_State* L);
int TestPoint(lua_State* L);
int RayCast(lua_State* L);
int SetFilterData(lua_State* L);
int GetFilterData(lua_State* L);
int SetCategory(lua_State* L);
int GetCategory(lua_State* L);
int SetMask(lua_State* L);
int GetMask(lua_State* L);
int SetUserdata(lua_State* L);
int GetUserdata(lua_State* L);
int GetBoundingBox(lua_State* L);
int GetMassData(lua_State* L);
int GetGroupIndex(lua_State* L);
int SetGroupIndex(lua_State* L);
int Destroy(lua_State* L);
int IsDestroyed(lua_State* L);
love::Fixture* CheckFixture(lua_State* L, int index);
int Register(lua_State* L);
} // namespace Wrap_Fixture
| 495 |
5,169 | {
"name": "KNBannerView",
"version": "2.0.1",
"summary": "A lightweight and beautiful banner for recycle and adapt rotate screen",
"description": "A lightweight and beautiful banner for recycle and adapt rotate screen",
"homepage": "https://github.com/LuKane/KNBannerView",
"license": "MIT",
"authors": {
"LuKane": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/LuKane/KNBannerView.git",
"tag": "2.0.1"
},
"source_files": "KNBannerView/KNBannerView/**/*.{h,m}",
"requires_arc": true,
"dependencies": {
"SDWebImage": [
"~> 5.0.0"
]
}
}
| 260 |
13,006 | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author saudet
// @author <NAME> (<EMAIL>)
//
#include <dnnl_types.h>
#include <ops/declarable/helpers/convolutions.h>
#include "mkldnnUtils.h"
using namespace dnnl;
namespace sd {
namespace mkldnnUtils {
//////////////////////////////////////////////////////////////////////
void getDims(const NDArray* array, const int rank, dnnl::memory::dims& mklDims){
std::vector<int64_t> vDims(rank);
for (auto i = 0; i < rank; i++) {
vDims[i] = array->sizeAt(i);
}
mklDims = dnnl::memory::dims(vDims);
}
//////////////////////////////////////////////////////////////////////
dnnl::memory::format_tag getFormat(const NDArray& arr) {
dnnl::memory::format_tag result;
switch (arr.rankOf()) {
case 1:
result = dnnl::memory::format_tag::a;
break;
case 2:
result = arr.ordering() == 'c' ? dnnl::memory::format_tag::ab : dnnl::memory::format_tag::ba;
break;
case 3:
result = arr.ordering() == 'c' ? dnnl::memory::format_tag::abc : dnnl::memory::format_tag::cba;
break;
case 4:
result = dnnl::memory::format_tag::abcd;
break;
case 5:
result = dnnl::memory::format_tag::abcde;
break;
case 6:
result = dnnl::memory::format_tag::abcdef;
break;
default:
throw std::invalid_argument("MKLDNN getFormat: do we really want to use arras with rank > 6 ?");
}
return result;
}
//////////////////////////////////////////////////////////////////////
void setBlockStrides(const NDArray& array, dnnl::memory::desc& mklMd, const std::vector<int>& permut) {
if (array.ews() != 1 || (array.rankOf() > 3 && array.ordering() == 'f') || !permut.empty()) {
mklMd.data.format_kind = dnnl_blocked; // overrides format
if(permut.empty())
for (auto i = 0; i < array.rankOf(); ++i)
mklMd.data.format_desc.blocking.strides[i] = array.strideAt(i);
else {
if(array.rankOf() != permut.size())
throw std::invalid_argument("mkldnnUtils::setBlockStrides: size of permut vector is not equal to array rank !");
for (auto i = 0; i < array.rankOf(); ++i)
mklMd.data.format_desc.blocking.strides[i] = array.strideAt(permut[i]);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
dnnl::memory loadDataToMklStream(const NDArray& array, const dnnl::engine& engine, const dnnl::stream& stream,
const dnnl::memory::desc& user_md, const dnnl::memory::desc& primitive_md, dnnl::memory& arg) {
auto user_mem = dnnl::memory(user_md, engine, const_cast<NDArray&>(array).buffer());
const bool bReorder = primitive_md != user_mem.get_desc();
auto mkl_mem = bReorder ? dnnl::memory(primitive_md, engine) : user_mem;
if (bReorder)
dnnl::reorder(user_mem, mkl_mem).execute(stream, user_mem, mkl_mem);
arg = mkl_mem;
return user_mem;
}
//////////////////////////////////////////////////////////////////////
void poolingMKLDNN(const NDArray *input, NDArray *output,
const int kD, const int kH, const int kW,
const int sD, const int sH, const int sW,
const int pD, const int pH, const int pW,
const int isNCHW, const dnnl::algorithm mode) {
// unfortunately mkl dnn doesn't support any format (dnnl::memory::format_tag::any) for input
const int rank = input->rankOf();
int bS, iC, iD, iH, iW, oC, oD, oH, oW, indIOioC, indIiH, indWoC, indWiC, indWkH, indOoH;
dnnl::memory::dims strides, kernel, padding, padding_r, xDims, zDims;
dnnl::memory::format_tag xzFrmat;
const auto type = dnnl::memory::data_type::f32;
if(rank == 4) { // 2d
ops::ConvolutionUtils::getSizesAndIndexesConv2d(isNCHW, 0, *input, *output, bS, iC, iH, iW, oC, oH, oW, indIOioC, indIiH, indWiC, indWoC, indWkH, indOoH);
strides = { sH, sW };
kernel = { kH, kW };
padding = { pH, pW };
padding_r = { (oH - 1) * sH - iH + kH - pH, (oW - 1) * sW - iW + kW - pW };
xDims = {bS, iC, iH, iW};
zDims = {bS, oC, oH, oW};
xzFrmat = isNCHW ? dnnl::memory::format_tag::nchw : dnnl::memory::format_tag::nhwc;
}
else { // 3d
ops::ConvolutionUtils::getSizesAndIndexesConv3d(isNCHW, 0, *input, *output, bS, iC, iD, iH, iW, oC, oD, oH, oW, indIOioC, indIiH, indWiC, indWoC, indWkH);
strides = { sD, sH, sW };
kernel = { kD, kH, kW };
padding = { pD, pH, pW };
padding_r = { (oD - 1) * sD - iD + kD - pD, (oH - 1) * sH - iH + kH - pH, (oW - 1) * sW - iW + kW - pW };
xDims = {bS, iC, iD, iH, iW};
zDims = {bS, oC, oD, oH, oW};
xzFrmat = isNCHW ? dnnl::memory::format_tag::ncdhw : dnnl::memory::format_tag::ndhwc;
}
std::vector<int> permut;
if(!isNCHW)
permut = rank == 4 ? std::vector<int>({0,3,1,2}) : std::vector<int>({0,4,1,2,3});
// memory descriptors for arrays
// input
dnnl::memory::desc x_mkl_md = dnnl::memory::desc(xDims, type, xzFrmat);
dnnl::memory::desc x_user_md = dnnl::memory::desc(xDims, type, xzFrmat);
mkldnnUtils::setBlockStrides(*input, x_user_md, permut);
// output
dnnl::memory::desc z_mkl_md = dnnl::memory::desc(zDims, type, dnnl::memory::format_tag::any);
dnnl::memory::desc z_user_md = dnnl::memory::desc(zDims, type, xzFrmat);
mkldnnUtils::setBlockStrides(*output, z_user_md, permut);
auto engine = mkldnnUtils::getEngine(LaunchContext::defaultContext()->engine());
// operation primitive description
dnnl::pooling_forward::desc op_desc(dnnl::prop_kind::forward_inference, mode, x_mkl_md, z_mkl_md, strides, kernel, padding, padding_r);
dnnl::pooling_forward::primitive_desc op_prim_desc(op_desc, engine);
// arguments (memory buffers) necessary for calculations
std::unordered_map<int, dnnl::memory> args;
dnnl::stream stream(engine);
// provide memory buffers and check whether reorder is required
// input
mkldnnUtils::loadDataToMklStream(*input, engine, stream, x_user_md, op_prim_desc.src_desc(), args[DNNL_ARG_SRC]);
// output
auto z_user_mem = mkldnnUtils::loadDataToMklStream(*output, engine, stream, z_user_md, op_prim_desc.dst_desc(), args[DNNL_ARG_DST]);
// run calculations
dnnl::pooling_forward(op_prim_desc).execute(stream, args);
// reorder outputs if necessary
if (op_prim_desc.dst_desc() != z_user_mem.get_desc())
dnnl::reorder(args[DNNL_ARG_DST], z_user_mem).execute(stream, args[DNNL_ARG_DST], z_user_mem);
stream.wait();
}
//////////////////////////////////////////////////////////////////////
void poolingBpMKLDNN(const NDArray *input, const NDArray *gradO, NDArray *gradI,
const int kD, const int kH, const int kW,
const int sD, const int sH, const int sW,
const int pD, const int pH, const int pW,
const int isNCHW, const dnnl::algorithm mode) {
// unfortunately mkl dnn doesn't support any format (dnnl::memory::format_tag::any) for input
const int rank = input->rankOf();
int bS, iC, iD, iH, iW, oC, oD, oH, oW, indIOioC, indIiH, indWoC, indWiC, indWkH, indOoH;
dnnl::memory::dims strides, kernel, padding, padding_r, xDims, zDims;
dnnl::memory::format_tag xzFrmat;
const auto type = dnnl::memory::data_type::f32;
if(rank == 4) { // 2d
ops::ConvolutionUtils::getSizesAndIndexesConv2d(isNCHW, 0, *input, *gradO, bS, iC, iH, iW, oC, oH, oW, indIOioC, indIiH, indWiC, indWoC, indWkH, indOoH);
strides = { sH, sW };
kernel = { kH, kW };
padding = { pH, pW };
padding_r = { (oH - 1) * sH - iH + kH - pH, (oW - 1) * sW - iW + kW - pW };
xDims = {bS, iC, iH, iW};
zDims = {bS, oC, oH, oW};
xzFrmat = isNCHW ? dnnl::memory::format_tag::nchw : dnnl::memory::format_tag::nhwc;
}
else { // 3d
ops::ConvolutionUtils::getSizesAndIndexesConv3d(isNCHW, 0, *input, *gradO, bS, iC, iD, iH, iW, oC, oD, oH, oW, indIOioC, indIiH, indWiC, indWoC, indWkH);
strides = { sD, sH, sW };
kernel = { kD, kH, kW };
padding = { pD, pH, pW };
padding_r = { (oD - 1) * sD - iD + kD - pD, (oH - 1) * sH - iH + kH - pH, (oW - 1) * sW - iW + kW - pW };
xDims = {bS, iC, iD, iH, iW};
zDims = {bS, oC, oD, oH, oW};
xzFrmat = isNCHW ? dnnl::memory::format_tag::ncdhw : dnnl::memory::format_tag::ndhwc;
}
std::vector<int> permut;
if(!isNCHW)
permut = rank == 4 ? std::vector<int>({0,3,1,2}) : std::vector<int>({0,4,1,2,3});
// memory descriptors for arrays
// input
dnnl::memory::desc x_mkl_md = dnnl::memory::desc(xDims, type, xzFrmat);
dnnl::memory::desc x_user_md = dnnl::memory::desc(xDims, type, xzFrmat);
mkldnnUtils::setBlockStrides(*input, x_user_md, permut);
// gradO
dnnl::memory::desc gradO_mkl_md = dnnl::memory::desc(zDims, type, dnnl::memory::format_tag::any);
dnnl::memory::desc gradO_user_md = dnnl::memory::desc(zDims, type, xzFrmat);
mkldnnUtils::setBlockStrides(*gradO, gradO_user_md, permut);
// gradI
dnnl::memory::desc gradI_mkl_md = dnnl::memory::desc(xDims, type, dnnl::memory::format_tag::any);
dnnl::memory::desc gradI_user_md = dnnl::memory::desc(xDims, type, xzFrmat);
mkldnnUtils::setBlockStrides(*gradI, gradI_user_md, permut);
auto engine = mkldnnUtils::getEngine(LaunchContext::defaultContext()->engine());
dnnl::stream stream(engine);
// forward primitive description
dnnl::pooling_forward::desc op_ff_desc(dnnl::prop_kind::forward, mode, x_mkl_md, gradO_mkl_md, strides, kernel, padding, padding_r);
dnnl::pooling_forward::primitive_desc op_ff_prim_desc(op_ff_desc, engine);
// backward primitive description
dnnl::pooling_backward::desc op_bp_desc(mode, gradI_mkl_md, gradO_mkl_md, strides, kernel, padding, padding_r);
dnnl::pooling_backward::primitive_desc op_bp_prim_desc(op_bp_desc, engine, op_ff_prim_desc);
// arguments (memory buffers) necessary for calculations
std::unordered_map<int, dnnl::memory> args;
// gradO
mkldnnUtils::loadDataToMklStream(*gradO, engine, stream, gradO_user_md, op_bp_prim_desc.diff_dst_desc(), args[DNNL_ARG_DIFF_DST]);
// gradI
auto gradI_user_mem = mkldnnUtils::loadDataToMklStream(*gradI, engine, stream, gradI_user_md, op_bp_prim_desc.diff_src_desc(), args[DNNL_ARG_DIFF_SRC]);
if(mode == algorithm::pooling_max) {
// input
mkldnnUtils::loadDataToMklStream(*input, engine, stream, x_user_md, op_ff_prim_desc.src_desc(), args[DNNL_ARG_SRC]);
// z
auto z_mkl_mem = dnnl::memory(op_ff_prim_desc.dst_desc(), engine);
args[DNNL_ARG_DST] = z_mkl_mem;
// auxiliary memory allocation
auto workspace = dnnl::memory(op_ff_prim_desc.workspace_desc(), engine);
args[DNNL_ARG_WORKSPACE] = workspace;
// run forward calculations
dnnl::pooling_forward(op_ff_prim_desc).execute(stream, args);
}
// run backward calculations
dnnl::pooling_backward(op_bp_prim_desc).execute(stream, args);
// reorder gradI if necessary
if (op_bp_prim_desc.diff_src_desc() != gradI_user_mem.get_desc())
dnnl::reorder(args[DNNL_ARG_DIFF_SRC], gradI_user_mem).execute(stream, args[DNNL_ARG_DIFF_SRC], gradI_user_mem);
stream.wait();
}
//////////////////////////////////////////////////////////////////////////
void getMKLDNNMemoryDescLrn(const NDArray* src, const NDArray* diff_src, const NDArray* dst,
dnnl::memory::desc* lrn_src_md, dnnl::memory::desc* lrn_diff_src_md, dnnl::memory::desc* lrn_dst_md,
dnnl::memory::desc* user_src_md, dnnl::memory::desc* user_diff_src_md, dnnl::memory::desc* user_dst_md, int axis) {
const Nd4jLong* shape = src->shapeInfo();
long rank = shape[0];
long dim1 = axis; // MKL-DNN supports only 1 axis, which has to be the "channel" one
long dim2 = axis >= 2 ? 1 : 2;
long dim3 = axis >= 3 ? 2 : 3;
dnnl::memory::dims lrn_src_tz = { (int)shape[1], (int)shape[dim1 + 1], rank > 2 ? (int)shape[dim2 + 1] : 1, rank > 3 ? (int)shape[dim3 + 1] : 1};
auto type = dnnl::memory::data_type::f32;
auto format = axis == 1 ? dnnl::memory::format_tag::nchw : dnnl::memory::format_tag::nhwc;
auto supposed_to_be_any_format = format; // doesn't work with "any"
if (src != nullptr && src->buffer() != nullptr && lrn_src_md != nullptr) {
*lrn_src_md = dnnl::memory::desc({ lrn_src_tz }, type, supposed_to_be_any_format);
*user_src_md = dnnl::memory::desc({ lrn_src_tz }, type, format);
user_src_md->data.format_kind = dnnl_blocked;
user_src_md->data.format_desc.blocking.strides[0] = src->stridesOf()[0];
user_src_md->data.format_desc.blocking.strides[1] = src->stridesOf()[dim1];
user_src_md->data.format_desc.blocking.strides[2] = rank > 2 ? src->stridesOf()[dim2] : 1;
user_src_md->data.format_desc.blocking.strides[3] = rank > 3 ? src->stridesOf()[dim3] : 1;
}
if (diff_src != nullptr && diff_src->buffer() != nullptr && lrn_diff_src_md != nullptr) {
*lrn_diff_src_md = dnnl::memory::desc({ lrn_src_tz }, type, supposed_to_be_any_format);
*user_diff_src_md = dnnl::memory::desc({ lrn_src_tz }, type, format);
user_diff_src_md->data.format_kind = dnnl_blocked;
user_diff_src_md->data.format_desc.blocking.strides[0] = diff_src->stridesOf()[0];
user_diff_src_md->data.format_desc.blocking.strides[1] = diff_src->stridesOf()[dim1];
user_diff_src_md->data.format_desc.blocking.strides[2] = rank > 2 ? diff_src->stridesOf()[dim2] : 1;
user_diff_src_md->data.format_desc.blocking.strides[3] = rank > 3 ? diff_src->stridesOf()[dim3] : 1;
}
if (dst != nullptr && dst->buffer() != nullptr && lrn_dst_md != nullptr) {
*lrn_dst_md = dnnl::memory::desc({ lrn_src_tz }, type, supposed_to_be_any_format);
*user_dst_md = dnnl::memory::desc({ lrn_src_tz }, type, format);
user_dst_md->data.format_kind = dnnl_blocked;
user_dst_md->data.format_desc.blocking.strides[0] = dst->stridesOf()[0];
user_dst_md->data.format_desc.blocking.strides[1] = dst->stridesOf()[dim1];
user_dst_md->data.format_desc.blocking.strides[2] = rank > 2 ? dst->stridesOf()[dim2] : 1;
user_dst_md->data.format_desc.blocking.strides[3] = rank > 3 ? dst->stridesOf()[dim3] : 1;
}
}
//////////////////////////////////////////////////////////////////////////
dnnl::engine& getEngine(void *ptr) {
auto eng = reinterpret_cast<dnnl::engine*>(ptr);
return *eng;
}
/*
//////////////////////////////////////////////////////////////////////////
void getMKLDNNMemoryDescPool2d(
int kH, int kW, int sH, int sW, int pH, int pW, int dH, int dW, int poolingMode, int extraParam0, bool isNCHW,
int bS, int iC, int iH, int iW, int oC, int oH, int oW,
const NDArray* src, const NDArray* diff_src, const NDArray* dst, dnnl::algorithm& algorithm,
dnnl::memory::desc* pool_src_md, dnnl::memory::desc* pool_diff_src_md, dnnl::memory::desc* pool_dst_md,
dnnl::memory::desc* user_src_md, dnnl::memory::desc* user_diff_src_md, dnnl::memory::desc* user_dst_md,
dnnl::memory::dims& pool_strides, dnnl::memory::dims& pool_kernel, dnnl::memory::dims& pool_padding, dnnl::memory::dims& pool_padding_r) {
dnnl::memory::dims pool_src_tz = { bS, iC, iH, iW };
dnnl::memory::dims pool_dst_tz = { bS, oC, oH, oW };
pool_strides = { sH, sW };
pool_kernel = { kH, kW };
pool_padding = { pH, pW };
pool_padding_r = { (oH - 1) * sH - iH + kH - pH,
(oW - 1) * sW - iW + kW - pW };
algorithm = poolingMode == 0 ? algorithm::pooling_max
: extraParam0 == 0 ? algorithm::pooling_avg_exclude_padding
: algorithm::pooling_avg_include_padding;
auto type = dnnl::memory::data_type::f32;
auto format = isNCHW ? dnnl::memory::format_tag::nchw : dnnl::memory::format_tag::nhwc;
auto supposed_to_be_any_format = dnnl::memory::format_tag::nChw8c; // doesn't work with "any"
if (src != nullptr && src->buffer() != nullptr && pool_src_md != nullptr) {
*pool_src_md = dnnl::memory::desc({ pool_src_tz }, type, supposed_to_be_any_format);
*user_src_md = dnnl::memory::desc({ pool_src_tz }, type, format);
user_src_md->data.format_kind = dnnl_blocked; // overrides "format = isNCHW ? nchw : nhwc"
user_src_md->data.format_desc.blocking.strides[0] = src->stridesOf()[isNCHW ? 0 : 0];
user_src_md->data.format_desc.blocking.strides[1] = src->stridesOf()[isNCHW ? 1 : 3];
user_src_md->data.format_desc.blocking.strides[2] = src->stridesOf()[isNCHW ? 2 : 1];
user_src_md->data.format_desc.blocking.strides[3] = src->stridesOf()[isNCHW ? 3 : 2];
}
if (diff_src != nullptr && diff_src->buffer() != nullptr && pool_diff_src_md != nullptr) {
*pool_diff_src_md = dnnl::memory::desc({ pool_src_tz }, type, supposed_to_be_any_format);
*user_diff_src_md = dnnl::memory::desc({ pool_src_tz }, type, format);
user_diff_src_md->data.format_kind = dnnl_blocked; // overrides "format = isNCHW ? nchw : nhwc"
user_diff_src_md->data.format_desc.blocking.strides[0] = diff_src->stridesOf()[isNCHW ? 0 : 0];
user_diff_src_md->data.format_desc.blocking.strides[1] = diff_src->stridesOf()[isNCHW ? 1 : 3];
user_diff_src_md->data.format_desc.blocking.strides[2] = diff_src->stridesOf()[isNCHW ? 2 : 1];
user_diff_src_md->data.format_desc.blocking.strides[3] = diff_src->stridesOf()[isNCHW ? 3 : 2];
}
if (dst != nullptr && dst->buffer() != nullptr && pool_dst_md != nullptr) {
*pool_dst_md = dnnl::memory::desc({ pool_dst_tz }, type, supposed_to_be_any_format);
*user_dst_md = dnnl::memory::desc({ pool_dst_tz }, type, format);
user_dst_md->data.format_kind = dnnl_blocked; // overrides "format = isNCHW ? nchw : nhwc"
user_dst_md->data.format_desc.blocking.strides[0] = dst->stridesOf()[isNCHW ? 0 : 0];
user_dst_md->data.format_desc.blocking.strides[1] = dst->stridesOf()[isNCHW ? 1 : 3];
user_dst_md->data.format_desc.blocking.strides[2] = dst->stridesOf()[isNCHW ? 2 : 1];
user_dst_md->data.format_desc.blocking.strides[3] = dst->stridesOf()[isNCHW ? 3 : 2];
}
};
//////////////////////////////////////////////////////////////////////////
void getMKLDNNMemoryDescPool3d(
int kD, int kH, int kW, int sD, int sH, int sW, int pD, int pH, int pW, int dD, int dH, int dW, int poolingMode, int extraParam0, bool isNCDHW,
int bS, int iC, int iD, int iH, int iW, int oC, int oD, int oH, int oW,
const NDArray* src, const NDArray* diff_src, const NDArray* dst, dnnl::algorithm& algorithm,
dnnl::memory::desc* pool_src_md, dnnl::memory::desc* pool_diff_src_md, dnnl::memory::desc* pool_dst_md,
dnnl::memory::desc* user_src_md, dnnl::memory::desc* user_diff_src_md, dnnl::memory::desc* user_dst_md,
dnnl::memory::dims& pool_strides, dnnl::memory::dims& pool_kernel, dnnl::memory::dims& pool_padding, dnnl::memory::dims& pool_padding_r) {
dnnl::memory::dims pool_src_tz = { bS, iC, iD, iH, iW };
dnnl::memory::dims pool_dst_tz = { bS, oC, oD, oH, oW };
pool_strides = { sD, sH, sW };
pool_kernel = { kD, kH, kW };
pool_padding = { pD, pH, pW };
pool_padding_r = { (oD - 1) * sD - iD + kD - pD,
(oH - 1) * sH - iH + kH - pH,
(oW - 1) * sW - iW + kW - pW };
algorithm = poolingMode == 0 ? algorithm::pooling_max
: extraParam0 == 0 ? algorithm::pooling_avg_exclude_padding
: algorithm::pooling_avg_include_padding;
auto type = dnnl::memory::data_type::f32;
auto format = isNCDHW ? dnnl::memory::format_tag::ncdhw : dnnl::memory::format_tag::ndhwc;
auto supposed_to_be_any_format = dnnl::memory::format_tag::nCdhw8c; // doesn't work with "any"
if (src != nullptr && src->buffer() != nullptr && pool_src_md != nullptr) {
*pool_src_md = dnnl::memory::desc({ pool_src_tz }, type, supposed_to_be_any_format);
*user_src_md = dnnl::memory::desc({ pool_src_tz }, type, format);
user_src_md->data.format_kind = dnnl_blocked; // overrides "format = isNCDHW ? ncdhw : ndhwc"
user_src_md->data.format_desc.blocking.strides[0] = src->stridesOf()[isNCDHW ? 0 : 0];
user_src_md->data.format_desc.blocking.strides[1] = src->stridesOf()[isNCDHW ? 1 : 4];
user_src_md->data.format_desc.blocking.strides[2] = src->stridesOf()[isNCDHW ? 2 : 1];
user_src_md->data.format_desc.blocking.strides[3] = src->stridesOf()[isNCDHW ? 3 : 2];
user_src_md->data.format_desc.blocking.strides[4] = src->stridesOf()[isNCDHW ? 4 : 3];
}
if (diff_src != nullptr && diff_src->buffer() != nullptr && pool_diff_src_md != nullptr) {
*pool_diff_src_md = dnnl::memory::desc({ pool_src_tz }, type, supposed_to_be_any_format);
*user_diff_src_md = dnnl::memory::desc({ pool_src_tz }, type, format);
user_diff_src_md->data.format_kind = dnnl_blocked; // overrides "format = isNCDHW ? ncdhw : ndhwc"
user_diff_src_md->data.format_desc.blocking.strides[0] = diff_src->stridesOf()[isNCDHW ? 0 : 0];
user_diff_src_md->data.format_desc.blocking.strides[1] = diff_src->stridesOf()[isNCDHW ? 1 : 4];
user_diff_src_md->data.format_desc.blocking.strides[2] = diff_src->stridesOf()[isNCDHW ? 2 : 1];
user_diff_src_md->data.format_desc.blocking.strides[3] = diff_src->stridesOf()[isNCDHW ? 3 : 2];
user_diff_src_md->data.format_desc.blocking.strides[4] = diff_src->stridesOf()[isNCDHW ? 4 : 3];
}
if (dst != nullptr && dst->buffer() != nullptr && pool_dst_md != nullptr) {
*pool_dst_md = dnnl::memory::desc({ pool_dst_tz }, type, supposed_to_be_any_format);
*user_dst_md = dnnl::memory::desc({ pool_dst_tz }, type, format);
user_dst_md->data.format_kind = dnnl_blocked; // overrides "format = isNCDHW ? ncdhw : ndhwc"
user_dst_md->data.format_desc.blocking.strides[0] = dst->stridesOf()[isNCDHW ? 0 : 0];
user_dst_md->data.format_desc.blocking.strides[1] = dst->stridesOf()[isNCDHW ? 1 : 4];
user_dst_md->data.format_desc.blocking.strides[2] = dst->stridesOf()[isNCDHW ? 2 : 1];
user_dst_md->data.format_desc.blocking.strides[3] = dst->stridesOf()[isNCDHW ? 3 : 2];
user_dst_md->data.format_desc.blocking.strides[4] = dst->stridesOf()[isNCDHW ? 4 : 3];
}
};
//////////////////////////////////////////////////////////////////////////
void getMKLDNNMemoryDescConv2d(
int kH, int kW, int sH, int sW, int pH, int pW, int dH, int dW, const int paddingMode, bool isNCHW,
int bS, int iC, int iH, int iW, int oC, int oH, int oW, const NDArray* src, const NDArray* diff_src,
const NDArray* weights, const NDArray* diff_weights, const NDArray* bias, const NDArray* dst,
dnnl::memory::desc* conv_src_md, dnnl::memory::desc* conv_diff_src_md, dnnl::memory::desc* conv_weights_md,
dnnl::memory::desc* conv_diff_weights_md, dnnl::memory::desc* conv_bias_md, dnnl::memory::desc* conv_dst_md,
dnnl::memory::desc* user_src_md, dnnl::memory::desc* user_diff_src_md, dnnl::memory::desc* user_weights_md,
dnnl::memory::desc* user_diff_weights_md, dnnl::memory::desc* user_bias_md, dnnl::memory::desc* user_dst_md,
dnnl::memory::dims& conv_strides, dnnl::memory::dims& conv_padding, dnnl::memory::dims& conv_padding_r, dnnl::memory::dims& conv_dilation) {
dnnl::memory::dims conv_src_tz = { bS, iC, iH, iW };
dnnl::memory::dims conv_weights_tz = { oC, iC, kH, kW };
dnnl::memory::dims conv_bias_tz = { oC };
dnnl::memory::dims conv_dst_tz = { bS, oC, oH, oW };
const int pWSame = (paddingMode == 2 && dW > 1) ? ((oW - 1) * sW + (kW - 1) * dW + 1 - iW) / 2 : pW; // dH == 1 for causal mode in conv1d
conv_strides = { sH, sW };
conv_padding = { pH, pW };
conv_padding_r = { (oH - 1) * sH - iH + kH - pH, (oW - 1) * sW - iW + kW - pWSame };
conv_dilation = { dH-1, dW-1};
auto type = dnnl::memory::data_type::f32;
auto format = isNCHW ? dnnl::memory::format_tag::nchw : dnnl::memory::format_tag::nhwc;
auto formatw = dnnl::memory::format_tag::hwio;
if (src != nullptr && conv_src_md != nullptr) {
*conv_src_md = dnnl::memory::desc({ conv_src_tz }, type, dnnl::memory::format_tag::any);
*user_src_md = dnnl::memory::desc({ conv_src_tz }, type, format);
user_src_md->data.format_kind = dnnl_blocked; // overrides "format = isNCHW ? nchw : nhwc"
user_src_md->data.format_desc.blocking.strides[0] = src->stridesOf()[isNCHW ? 0 : 0];
user_src_md->data.format_desc.blocking.strides[1] = src->stridesOf()[isNCHW ? 1 : 3];
user_src_md->data.format_desc.blocking.strides[2] = src->stridesOf()[isNCHW ? 2 : 1];
user_src_md->data.format_desc.blocking.strides[3] = src->stridesOf()[isNCHW ? 3 : 2];
}
if (diff_src != nullptr && conv_diff_src_md != nullptr) {
*conv_diff_src_md = dnnl::memory::desc({ conv_src_tz }, type, dnnl::memory::format_tag::any);
*user_diff_src_md = dnnl::memory::desc({ conv_src_tz }, type, format);
user_diff_src_md->data.format_kind = dnnl_blocked; // overrides "format = isNCHW ? nchw : nhwc"
user_diff_src_md->data.format_desc.blocking.strides[0] = diff_src->stridesOf()[isNCHW ? 0 : 0];
user_diff_src_md->data.format_desc.blocking.strides[1] = diff_src->stridesOf()[isNCHW ? 1 : 3];
user_diff_src_md->data.format_desc.blocking.strides[2] = diff_src->stridesOf()[isNCHW ? 2 : 1];
user_diff_src_md->data.format_desc.blocking.strides[3] = diff_src->stridesOf()[isNCHW ? 3 : 2];
}
if (weights != nullptr && conv_weights_md != nullptr) {
*conv_weights_md = dnnl::memory::desc({ conv_weights_tz }, type, dnnl::memory::format_tag::any);
*user_weights_md = dnnl::memory::desc({ conv_weights_tz }, type, formatw);
user_weights_md->data.format_kind = dnnl_blocked; // overrides "formatw = hwio"
user_weights_md->data.format_desc.blocking.strides[0] = weights->stridesOf()[3];
user_weights_md->data.format_desc.blocking.strides[1] = weights->stridesOf()[2];
user_weights_md->data.format_desc.blocking.strides[2] = weights->stridesOf()[0];
user_weights_md->data.format_desc.blocking.strides[3] = weights->stridesOf()[1];
}
if (diff_weights != nullptr && conv_diff_weights_md != nullptr) {
*conv_diff_weights_md = dnnl::memory::desc({ conv_weights_tz }, type, dnnl::memory::format_tag::any);
*user_diff_weights_md = dnnl::memory::desc({ conv_weights_tz }, type, formatw);
user_diff_weights_md->data.format_kind = dnnl_blocked; // overrides "formatw = hwio"
user_diff_weights_md->data.format_desc.blocking.strides[0] = diff_weights->stridesOf()[3];
user_diff_weights_md->data.format_desc.blocking.strides[1] = diff_weights->stridesOf()[2];
user_diff_weights_md->data.format_desc.blocking.strides[2] = diff_weights->stridesOf()[0];
user_diff_weights_md->data.format_desc.blocking.strides[3] = diff_weights->stridesOf()[1];
}
if (bias != nullptr && conv_bias_md != nullptr) {
*conv_bias_md = dnnl::memory::desc({ conv_bias_tz }, type, dnnl::memory::format_tag::any);
*user_bias_md = dnnl::memory::desc({ conv_bias_tz }, type, dnnl::memory::format_tag::x);
}
if (dst != nullptr && conv_dst_md != nullptr) {
*conv_dst_md = dnnl::memory::desc({ conv_dst_tz }, type, dnnl::memory::format_tag::any);
*user_dst_md = dnnl::memory::desc({ conv_dst_tz }, type, format);
user_dst_md->data.format_kind = dnnl_blocked; // overrides "format = isNCHW ? nchw : nhwc"
user_dst_md->data.format_desc.blocking.strides[0] = dst->stridesOf()[isNCHW ? 0 : 0];
user_dst_md->data.format_desc.blocking.strides[1] = dst->stridesOf()[isNCHW ? 1 : 3];
user_dst_md->data.format_desc.blocking.strides[2] = dst->stridesOf()[isNCHW ? 2 : 1];
user_dst_md->data.format_desc.blocking.strides[3] = dst->stridesOf()[isNCHW ? 3 : 2];
}
}
//////////////////////////////////////////////////////////////////////////
void getMKLDNNMemoryDescConv3d(
int kD, int kH, int kW, int sD, int sH, int sW, int pD, int pH, int pW, int dD, int dH, int dW, bool paddingMode, bool isNCDHW,
int bS, int iC, int iD, int iH, int iW, int oC, int oD, int oH, int oW, const NDArray* src, const NDArray* diff_src,
const NDArray* weights, const NDArray* diff_weights, const NDArray* bias, const NDArray* dst,
dnnl::memory::desc* conv_src_md, dnnl::memory::desc* conv_diff_src_md, dnnl::memory::desc* conv_weights_md,
dnnl::memory::desc* conv_diff_weights_md, dnnl::memory::desc* conv_bias_md, dnnl::memory::desc* conv_dst_md,
dnnl::memory::desc* user_src_md, dnnl::memory::desc* user_diff_src_md, dnnl::memory::desc* user_weights_md,
dnnl::memory::desc* user_diff_weights_md, dnnl::memory::desc* user_bias_md, dnnl::memory::desc* user_dst_md,
dnnl::memory::dims& conv_strides, dnnl::memory::dims& conv_padding, dnnl::memory::dims& conv_padding_r, dnnl::memory::dims& conv_dilation) {
dnnl::memory::dims conv_src_tz = { bS, iC, iD, iH, iW };
dnnl::memory::dims conv_weights_tz = { oC, iC, kD, kH, kW };
dnnl::memory::dims conv_bias_tz = { oC };
dnnl::memory::dims conv_dst_tz = { bS, oC, oD, oH, oW };
conv_strides = { sD, sH, sW };
conv_padding = { pD, pH, pW };
conv_padding_r = { (oD - 1) * sD - iD + kD - pD, (oH - 1) * sH - iH + kH - pH, (oW - 1) * sW - iW + kW - pW };
conv_dilation = { dD-1, dH-1, dW-1};
auto type = dnnl::memory::data_type::f32;
auto format = isNCDHW ? dnnl::memory::format_tag::ncdhw : dnnl::memory::format_tag::ndhwc;
auto formatw = dnnl::memory::format_tag::dhwio;
if (src != nullptr && conv_src_md != nullptr) {
*conv_src_md = dnnl::memory::desc({ conv_src_tz }, type, dnnl::memory::format_tag::any);
*user_src_md = dnnl::memory::desc({ conv_src_tz }, type, format);
user_src_md->data.format_kind = dnnl_blocked; // overrides "format = isNCDHW ? ncdhw : ndhwc"
user_src_md->data.format_desc.blocking.strides[0] = src->stridesOf()[isNCDHW ? 0 : 0];
user_src_md->data.format_desc.blocking.strides[1] = src->stridesOf()[isNCDHW ? 1 : 4];
user_src_md->data.format_desc.blocking.strides[2] = src->stridesOf()[isNCDHW ? 2 : 1];
user_src_md->data.format_desc.blocking.strides[3] = src->stridesOf()[isNCDHW ? 3 : 2];
user_src_md->data.format_desc.blocking.strides[4] = src->stridesOf()[isNCDHW ? 4 : 3];
}
if (diff_src != nullptr && conv_diff_src_md != nullptr) {
*conv_diff_src_md = dnnl::memory::desc({ conv_src_tz }, type, dnnl::memory::format_tag::any);
*user_diff_src_md = dnnl::memory::desc({ conv_src_tz }, type, format);
user_diff_src_md->data.format_kind = dnnl_blocked; // overrides "format = isNCDHW ? ncdhw : ndhwc"
user_diff_src_md->data.format_desc.blocking.strides[0] = diff_src->stridesOf()[isNCDHW ? 0 : 0];
user_diff_src_md->data.format_desc.blocking.strides[1] = diff_src->stridesOf()[isNCDHW ? 1 : 4];
user_diff_src_md->data.format_desc.blocking.strides[2] = diff_src->stridesOf()[isNCDHW ? 2 : 1];
user_diff_src_md->data.format_desc.blocking.strides[3] = diff_src->stridesOf()[isNCDHW ? 3 : 2];
user_diff_src_md->data.format_desc.blocking.strides[4] = diff_src->stridesOf()[isNCDHW ? 4 : 3];
}
if (weights != nullptr && conv_weights_md != nullptr) {
*conv_weights_md = dnnl::memory::desc({ conv_weights_tz }, type, dnnl::memory::format_tag::any);
*user_weights_md = dnnl::memory::desc({ conv_weights_tz }, type, formatw);
user_weights_md->data.format_kind = dnnl_blocked; // overrides "formatw = dhwio"
user_weights_md->data.format_desc.blocking.strides[0] = weights->stridesOf()[4];
user_weights_md->data.format_desc.blocking.strides[1] = weights->stridesOf()[3];
user_weights_md->data.format_desc.blocking.strides[2] = weights->stridesOf()[0];
user_weights_md->data.format_desc.blocking.strides[3] = weights->stridesOf()[1];
user_weights_md->data.format_desc.blocking.strides[4] = weights->stridesOf()[2];
}
if (diff_weights != nullptr && conv_diff_weights_md != nullptr) {
*conv_diff_weights_md = dnnl::memory::desc({ conv_weights_tz }, type, dnnl::memory::format_tag::any);
*user_diff_weights_md = dnnl::memory::desc({ conv_weights_tz }, type, formatw);
user_diff_weights_md->data.format_kind = dnnl_blocked; // overrides "formatw = dhwio"
user_diff_weights_md->data.format_desc.blocking.strides[0] = diff_weights->stridesOf()[4];
user_diff_weights_md->data.format_desc.blocking.strides[1] = diff_weights->stridesOf()[3];
user_diff_weights_md->data.format_desc.blocking.strides[2] = diff_weights->stridesOf()[0];
user_diff_weights_md->data.format_desc.blocking.strides[3] = diff_weights->stridesOf()[1];
user_diff_weights_md->data.format_desc.blocking.strides[4] = diff_weights->stridesOf()[2];
}
if (bias != nullptr && conv_bias_md != nullptr) {
*conv_bias_md = dnnl::memory::desc({ conv_bias_tz }, type, dnnl::memory::format_tag::any);
*user_bias_md = dnnl::memory::desc({ conv_bias_tz }, type, dnnl::memory::format_tag::x);
}
if (dst != nullptr && conv_dst_md != nullptr) {
*conv_dst_md = dnnl::memory::desc({ conv_dst_tz }, type, dnnl::memory::format_tag::any);
*user_dst_md = dnnl::memory::desc({ conv_dst_tz }, type, format);
user_dst_md->data.format_kind = dnnl_blocked; // overrides "format = isNCDHW ? ncdhw : ndhwc"
user_dst_md->data.format_desc.blocking.strides[0] = dst->stridesOf()[isNCDHW ? 0 : 0];
user_dst_md->data.format_desc.blocking.strides[1] = dst->stridesOf()[isNCDHW ? 1 : 4];
user_dst_md->data.format_desc.blocking.strides[2] = dst->stridesOf()[isNCDHW ? 2 : 1];
user_dst_md->data.format_desc.blocking.strides[3] = dst->stridesOf()[isNCDHW ? 3 : 2];
user_dst_md->data.format_desc.blocking.strides[4] = dst->stridesOf()[isNCDHW ? 4 : 3];
}
};
void getMKLDNNMemoryDescBatchNorm(const NDArray* src, const NDArray* diff_src, const NDArray* dst,
dnnl::memory::desc* batchnorm_src_md, dnnl::memory::desc* batchnorm_diff_src_md, dnnl::memory::desc* batchnorm_dst_md,
dnnl::memory::desc* user_src_md, dnnl::memory::desc* user_diff_src_md, dnnl::memory::desc* user_dst_md, int axis) {
const Nd4jLong* shape = src->shapeInfo();
Nd4jLong rank = shape[0];
Nd4jLong dim1 = axis; // MKL-DNN supports only 1 axis, which has to be the "channel" one
Nd4jLong dim2 = axis >= 2 ? 1 : 2;
Nd4jLong dim3 = axis >= 3 ? 2 : 3;
dnnl::memory::dims batchnorm_src_tz = { (int)shape[1], (int)shape[dim1 + 1], rank > 2 ? (int)shape[dim2 + 1] : 1, rank > 3 ? (int)shape[dim3 + 1] : 1};
auto type = dnnl::memory::data_type::f32;
auto format = dnnl::memory::format_tag::nchw;
auto supposed_to_be_any_format = dnnl::memory::format_tag::nChw8c; // doesn't work with "any"
if (src != nullptr && src->buffer() != nullptr && batchnorm_src_md != nullptr) {
*batchnorm_src_md = dnnl::memory::desc({ batchnorm_src_tz }, type, supposed_to_be_any_format);
*user_src_md = dnnl::memory::desc({ batchnorm_src_tz }, type, format);
user_src_md->data.format_kind = dnnl_blocked; // overrides format
user_src_md->data.format_desc.blocking.strides[0] = src->stridesOf()[0];
user_src_md->data.format_desc.blocking.strides[1] = src->stridesOf()[dim1];
user_src_md->data.format_desc.blocking.strides[2] = rank > 2 ? src->stridesOf()[dim2] : 1;
user_src_md->data.format_desc.blocking.strides[3] = rank > 3 ? src->stridesOf()[dim3] : 1;
}
if (diff_src != nullptr && diff_src->buffer() != nullptr && batchnorm_diff_src_md != nullptr) {
*batchnorm_diff_src_md = dnnl::memory::desc({ batchnorm_src_tz }, type, supposed_to_be_any_format);
*user_diff_src_md = dnnl::memory::desc({ batchnorm_src_tz }, type, format);
user_diff_src_md->data.format_kind = dnnl_blocked; // overrides format
user_diff_src_md->data.format_desc.blocking.strides[0] = diff_src->stridesOf()[0];
user_diff_src_md->data.format_desc.blocking.strides[1] = diff_src->stridesOf()[dim1];
user_diff_src_md->data.format_desc.blocking.strides[2] = rank > 2 ? diff_src->stridesOf()[dim2] : 1;
user_diff_src_md->data.format_desc.blocking.strides[3] = rank > 3 ? diff_src->stridesOf()[dim3] : 1;
}
if (dst != nullptr && dst->buffer() != nullptr && batchnorm_dst_md != nullptr) {
*batchnorm_dst_md = dnnl::memory::desc({ batchnorm_src_tz }, type, supposed_to_be_any_format);
*user_dst_md = dnnl::memory::desc({ batchnorm_src_tz }, type, format);
user_dst_md->data.format_kind = dnnl_blocked; // overrides format
user_dst_md->data.format_desc.blocking.strides[0] = dst->stridesOf()[0];
user_dst_md->data.format_desc.blocking.strides[1] = dst->stridesOf()[dim1];
user_dst_md->data.format_desc.blocking.strides[2] = rank > 2 ? dst->stridesOf()[dim2] : 1;
user_dst_md->data.format_desc.blocking.strides[3] = rank > 3 ? dst->stridesOf()[dim3] : 1;
}
};
*/
}
} | 17,425 |
553 | /**
* Copyright (C) <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.kagkarlsson.scheduler.task;
import com.github.kagkarlsson.scheduler.task.schedule.Schedule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.time.Instant;
import static java.lang.Math.pow;
import static java.lang.Math.round;
public interface FailureHandler<T> {
void onFailure(ExecutionComplete executionComplete, ExecutionOperations<T> executionOperations);
class ExponentialBackoffFailureHandler<T> implements FailureHandler<T> {
private static final Logger LOG = LoggerFactory.getLogger(ExponentialBackoffFailureHandler.class);
private static final double DEFAULT_MULTIPLIER = 1.5;
private final Duration sleepDuration;
private final double exponentialRate;
public ExponentialBackoffFailureHandler(Duration sleepDuration){
this.sleepDuration = sleepDuration;
this.exponentialRate = DEFAULT_MULTIPLIER;
}
public ExponentialBackoffFailureHandler(Duration sleepDuration, double exponentialRate){
this.sleepDuration = sleepDuration;
this.exponentialRate = exponentialRate;
}
@Override
public void onFailure(final ExecutionComplete executionComplete, final ExecutionOperations<T> executionOperations) {
long retryDurationMs = round(sleepDuration.toMillis() * pow(exponentialRate, executionComplete.getExecution().consecutiveFailures));
Instant nextTry = Instant.now().plusMillis(retryDurationMs);
LOG.debug("Execution failed. Retrying task {} at {}", executionComplete.getExecution().taskInstance, nextTry);
executionOperations.reschedule(executionComplete, nextTry);
}
}
class MaxRetriesFailureHandler<T> implements FailureHandler<T> {
private static final Logger LOG = LoggerFactory.getLogger(MaxRetriesFailureHandler.class);
private final int maxRetries;
private final FailureHandler<T> failureHandler;
public MaxRetriesFailureHandler(int maxRetries, FailureHandler<T> failureHandler){
this.maxRetries = maxRetries;
this.failureHandler = failureHandler;
}
@Override
public void onFailure(final ExecutionComplete executionComplete, final ExecutionOperations<T> executionOperations) {
int consecutiveFailures = executionComplete.getExecution().consecutiveFailures;
int totalNumberOfFailures = consecutiveFailures + 1;
if(totalNumberOfFailures > maxRetries){
LOG.error("Execution has failed {} times for task instance {}. Cancelling execution.", totalNumberOfFailures, executionComplete.getExecution().taskInstance);
executionOperations.stop();
}else{
this.failureHandler.onFailure(executionComplete, executionOperations);
}
}
}
class OnFailureRetryLater<T> implements FailureHandler<T> {
private static final Logger LOG = LoggerFactory.getLogger(CompletionHandler.OnCompleteReschedule.class);
private final Duration sleepDuration;
public OnFailureRetryLater(Duration sleepDuration) {
this.sleepDuration = sleepDuration;
}
@Override
public void onFailure(ExecutionComplete executionComplete, ExecutionOperations<T> executionOperations) {
Instant nextTry = Instant.now().plus(sleepDuration);
LOG.debug("Execution failed. Retrying task {} at {}", executionComplete.getExecution().taskInstance, nextTry);
executionOperations.reschedule(executionComplete, nextTry);
}
}
class OnFailureReschedule<T> implements FailureHandler<T> {
private static final Logger LOG = LoggerFactory.getLogger(CompletionHandler.OnCompleteReschedule.class);
private final Schedule schedule;
public OnFailureReschedule(Schedule schedule) {
this.schedule = schedule;
}
@Override
public void onFailure(ExecutionComplete executionComplete, ExecutionOperations<T> executionOperations) {
Instant nextExecution = schedule.getNextExecutionTime(executionComplete);
LOG.debug("Execution failed. Rescheduling task {} to {}", executionComplete.getExecution().taskInstance, nextExecution);
executionOperations.reschedule(executionComplete, nextExecution);
}
}
}
| 1,715 |
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.mapreduce;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileSystemTestHelper;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.security.UserGroupInformation;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests for JobSubmissionFiles Utility class.
*/
public class TestJobSubmissionFiles {
final private static String USER_1 = "<EMAIL>";
final private static String USER_1_SHORT_NAME = "user1";
final private static String GROUP1_NAME = "group1";
final private static String GROUP2_NAME = "group2";
final private static String GROUP3_NAME = "group3";
final private static String[] GROUP_NAMES = new String[] {GROUP1_NAME,
GROUP2_NAME, GROUP3_NAME };
@Test
public void testGetStagingDirWhenFullFileOwnerNameAndFullUserName()
throws IOException, InterruptedException {
Cluster cluster = mock(Cluster.class);
Configuration conf = new Configuration();
Path stagingPath = mock(Path.class);
UserGroupInformation user = UserGroupInformation
.createUserForTesting(USER_1, GROUP_NAMES);
assertEquals(USER_1, user.getUserName());
FileSystem fs = new FileSystemTestHelper.MockFileSystem();
when(cluster.getStagingAreaDir()).thenReturn(stagingPath);
when(stagingPath.getFileSystem(conf)).thenReturn(fs);
//Staging directory owner full principal name is in lower case.
String stagingDirOwner = USER_1.toLowerCase();
FileStatus fileStatus = new FileStatus(1, true, 1, 1, 100L, 100L,
FsPermission.getDefault(), stagingDirOwner, stagingDirOwner,
stagingPath);
when(fs.getFileStatus(stagingPath)).thenReturn(fileStatus);
assertEquals(stagingPath,
JobSubmissionFiles.getStagingDir(cluster, conf, user));
//Staging directory owner full principal name in upper and lower case
stagingDirOwner = USER_1;
fileStatus = new FileStatus(1, true, 1, 1, 100L, 100L,
FsPermission.getDefault(), stagingDirOwner, stagingDirOwner,
stagingPath);
when(fs.getFileStatus(stagingPath)).thenReturn(fileStatus);
assertEquals(stagingPath,
JobSubmissionFiles.getStagingDir(cluster, conf, user));
}
@Test(expected = IOException.class)
public void testGetStagingWhenFileOwnerNameAndCurrentUserNameDoesNotMatch()
throws IOException, InterruptedException {
Cluster cluster = mock(Cluster.class);
Configuration conf = new Configuration();
String stagingDirOwner = "someuser";
Path stagingPath = mock(Path.class);
UserGroupInformation user = UserGroupInformation
.createUserForTesting(USER_1, GROUP_NAMES);
assertEquals(USER_1, user.getUserName());
FileSystem fs = new FileSystemTestHelper.MockFileSystem();
FileStatus fileStatus = new FileStatus(1, true, 1, 1, 100L, 100L,
FsPermission.getDefault(), stagingDirOwner, stagingDirOwner,
stagingPath);
when(stagingPath.getFileSystem(conf)).thenReturn(fs);
when(fs.getFileStatus(stagingPath)).thenReturn(fileStatus);
when(cluster.getStagingAreaDir()).thenReturn(stagingPath);
assertEquals(stagingPath,
JobSubmissionFiles.getStagingDir(cluster, conf, user));
}
@Test
public void testGetStagingDirWhenShortFileOwnerNameAndFullUserName()
throws IOException, InterruptedException {
Cluster cluster = mock(Cluster.class);
Configuration conf = new Configuration();
String stagingDirOwner = USER_1_SHORT_NAME;
Path stagingPath = mock(Path.class);
UserGroupInformation user = UserGroupInformation
.createUserForTesting(USER_1, GROUP_NAMES);
assertEquals(USER_1, user.getUserName());
FileSystem fs = new FileSystemTestHelper.MockFileSystem();
FileStatus fileStatus = new FileStatus(1, true, 1, 1, 100L, 100L,
FsPermission.getDefault(), stagingDirOwner, stagingDirOwner,
stagingPath);
when(stagingPath.getFileSystem(conf)).thenReturn(fs);
when(fs.getFileStatus(stagingPath)).thenReturn(fileStatus);
when(cluster.getStagingAreaDir()).thenReturn(stagingPath);
assertEquals(stagingPath,
JobSubmissionFiles.getStagingDir(cluster, conf, user));
}
@Test
public void testGetStagingDirWhenShortFileOwnerNameAndShortUserName()
throws IOException, InterruptedException {
Cluster cluster = mock(Cluster.class);
Configuration conf = new Configuration();
String stagingDirOwner = USER_1_SHORT_NAME;
Path stagingPath = mock(Path.class);
UserGroupInformation user = UserGroupInformation
.createUserForTesting(USER_1_SHORT_NAME, GROUP_NAMES);
assertEquals(USER_1_SHORT_NAME, user.getUserName());
FileSystem fs = new FileSystemTestHelper.MockFileSystem();
FileStatus fileStatus = new FileStatus(1, true, 1, 1, 100L, 100L,
FsPermission.getDefault(), stagingDirOwner, stagingDirOwner,
stagingPath);
when(stagingPath.getFileSystem(conf)).thenReturn(fs);
when(fs.getFileStatus(stagingPath)).thenReturn(fileStatus);
when(cluster.getStagingAreaDir()).thenReturn(stagingPath);
assertEquals(stagingPath,
JobSubmissionFiles.getStagingDir(cluster, conf, user));
}
}
| 2,061 |
679 | <reponame>Grosskopf/openoffice<filename>main/xmlsecurity/source/framework/elementcollector.hxx<gh_stars>100-1000
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _ELEMENTCOLLECTOR_HXX
#define _ELEMENTCOLLECTOR_HXX
#include "elementmark.hxx"
#include <com/sun/star/xml/crypto/sax/XReferenceResolvedListener.hpp>
#include <com/sun/star/xml/crypto/sax/ElementMarkPriority.hpp>
class ElementCollector : public ElementMark
/****** elementcollector.hxx/CLASS ElementCollector ***************************
*
* NAME
* ElementCollector -- Class to manipulate an element collector
*
* FUNCTION
* This class is derived from the ElementMark class. Beyond the function
* of the ElementMark class, this class also maintains the priority, and
* manages the notify process
*
* HISTORY
* 05.01.2004 - implemented
*
* AUTHOR
* <NAME>
* Email: <EMAIL>
******************************************************************************/
{
private:
/*
* the notify priority, is one of following values:
* AFTERMODIFY - this ElementCollector will notify after all
* internal modifications have finished.
* BEFOREMODIFY - this ElementCollector must notify before any
* internal modification happens.
*/
com::sun::star::xml::crypto::sax::ElementMarkPriority m_nPriority;
/*
* the modify flag, representing whether which elementcollector will
* modify its data.
*/
bool m_bToModify;
/* the notify enable flag, see notifyListener method */
bool m_bAbleToNotify;
/* whether the listener has been notified */
bool m_bNotified;
/* the listener to be notified */
com::sun::star::uno::Reference<
com::sun::star::xml::crypto::sax::XReferenceResolvedListener > m_xReferenceResolvedListener;
public:
ElementCollector(
sal_Int32 nSecurityId,
sal_Int32 nBufferId,
com::sun::star::xml::crypto::sax::ElementMarkPriority nPriority,
bool bToModify,
const com::sun::star::uno::Reference<
com::sun::star::xml::crypto::sax::XReferenceResolvedListener >&
xReferenceResolvedListener);
virtual ~ElementCollector() {};
//bool isInternalNotificationSuppressed() const;
com::sun::star::xml::crypto::sax::ElementMarkPriority getPriority() const;
bool getModify() const;
void notifyListener();
bool isAbleToNotify() const;
void setReferenceResolvedListener(
const com::sun::star::uno::Reference<
com::sun::star::xml::crypto::sax::XReferenceResolvedListener >&
referenceResolvedListener);
void setSecurityId(sal_Int32 nSecurityId);
void doNotify();
ElementCollector* clone(
sal_Int32 nId,
com::sun::star::xml::crypto::sax::ElementMarkPriority nPriority ) const;
};
#endif
| 1,096 |
559 | /**
* Copyright (c) 2016-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.msl.util;
import java.nio.charset.StandardCharsets;
import com.netflix.msl.util.Base64.Base64Impl;
/**
* <p>Base64 encoder/decoder implementation that strictly enforces the validity
* of the encoding and does not exit early if an error is encountered.
* Whitespace (space, tab, newline, carriage return) are skipped.</p>
*
* <p>Based upon {@link javax.xml.bind.DatatypeConverter}.</p>
*
* @author <NAME> <<EMAIL>>
*/
public class Base64Secure implements Base64Impl {
/** The encode map. */
private static final char[] ENCODE_MAP = initEncodeMap();
/** The decode map. */
private static final byte[] DECODE_MAP = initDecodeMap();
/** Tab character value. */
private static final byte TAB = 9;
/** Newline character value. */
private static final byte NEWLINE = 10;
/** Carriage return character value. */
private static final byte CARRIAGE_RETURN = 13;
/** Space character value. */
private static final byte SPACE = 32;
/** Padding character sentinel value. */
private static final byte PADDING = 127;
/**
* @return the 64-character Base64 encode map.
*/
private static char[] initEncodeMap() {
final char[] map = new char[64];
for (int i = 0; i < 26; i++)
map[i] = (char)('A' + i);
for (int i = 26; i < 52; i++)
map[i] = (char)('a' + (i - 26));
for (int i = 52; i < 62; i++)
map[i] = (char)('0' + (i - 52));
map[62] = '+';
map[63] = '/';
return map;
}
/**
* @return the 128-byte Base64 decode map.
*/
private static byte[] initDecodeMap() {
final byte[] map = new byte[128];
for (int i = 0; i < 128; i++)
map[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
map[i] = (byte)(i - 'A');
for (int i = 'a'; i <= 'z'; i++)
map[i] = (byte)(i - 'a' + 26);
for (int i = '0'; i <= '9'; i++)
map[i] = (byte)(i - '0' + 52);
map['+'] = 62;
map['/'] = 63;
map['='] = PADDING;
return map;
}
/**
* @param i the value to encode.
* @return the character the value maps onto.
*/
private static char encode(final int i) {
return ENCODE_MAP[i & 0x3F];
}
/* (non-Javadoc)
* @see com.netflix.msl.util.Base64.Base64Impl#encode(byte[])
*/
@Override
public String encode(final byte[] b) {
// Allocate the character buffer.
final char[] buf = new char[((b.length + 2) / 3) * 4];
int ptr = 0;
// Encode elements until there are only 1 or 2 left.
int remaining = b.length;
int i;
for (i = 0; remaining >= 3; remaining -= 3, i += 3) {
buf[ptr++] = encode(b[i] >> 2);
buf[ptr++] = encode(((b[i] & 0x3) << 4) | ((b[i+1] >> 4) & 0xF));
buf[ptr++] = encode(((b[i + 1] & 0xF) << 2) | ((b[i + 2] >> 6) & 0x3));
buf[ptr++] = encode(b[i + 2] & 0x3F);
}
// If there is one final element...
if (remaining == 1) {
buf[ptr++] = encode(b[i] >> 2);
buf[ptr++] = encode(((b[i]) & 0x3) << 4);
buf[ptr++] = '=';
buf[ptr++] = '=';
}
// If there are two final elements...
else if (remaining == 2) {
buf[ptr++] = encode(b[i] >> 2);
buf[ptr++] = encode(((b[i] & 0x3) << 4) | ((b[i + 1] >> 4) & 0xF));
buf[ptr++] = encode((b[i + 1] & 0xF) << 2);
buf[ptr++] = '=';
}
// Return the encoded string.
return new String(buf);
}
/* (non-Javadoc)
* @see com.netflix.msl.util.Base64.Base64Impl#decode(java.lang.String)
*/
@Override
public byte[] decode(final String s) {
// Flag to remember if we've encountered an invalid character or have
// reached the end of the string prematurely.
boolean invalid = false;
// Convert string to ISO 8859-1 bytes.
final byte[] sb = s.getBytes(StandardCharsets.ISO_8859_1);
// Allocate the destination buffer, which may be too large due to
// whitespace.
final int strlen = sb.length;
final int outlen = strlen * 3 / 4;
final byte[] out = new byte[outlen];
int o = 0;
// Convert each quadruplet to three bytes.
final byte[] quadruplet = new byte[4];
int q = 0;
boolean lastQuad = false;
for (int i = 0; i < strlen; ++i) {
final byte c = sb[i];
// Ensure the character is not "negative".
if (c < 0) {
invalid = true;
continue;
}
// Lookup the character in the decoder map.
final byte b = DECODE_MAP[c];
// Skip invalid characters.
if (b == -1) {
// Flag invalid for non-whitespace.
if (c != SPACE && c != TAB && c != NEWLINE && c != CARRIAGE_RETURN)
invalid = true;
continue;
}
// If we already saw the last quadruplet, we shouldn't see anymore.
if (lastQuad)
invalid = true;
// Append value to quadruplet.
quadruplet[q++] = b;
// If the quadruplet is full, append it to the destination buffer.
if (q == 4) {
// If the quadruplet starts with padding, flag invalid.
if (quadruplet[0] == PADDING || quadruplet[1] == PADDING)
invalid = true;
// If the quadruplet ends with padding, this better be the last
// quadruplet.
if (quadruplet[2] == PADDING || quadruplet[3] == PADDING)
lastQuad = true;
// Decode into the destination buffer.
out[o++] = (byte)((quadruplet[0] << 2) | (quadruplet[1] >> 4));
if (quadruplet[2] != PADDING)
out[o++] = (byte)((quadruplet[1] << 4) | (quadruplet[2] >> 2));
if (quadruplet[3] != PADDING)
out[o++] = (byte)((quadruplet[2] << 6) | (quadruplet[3]));
// Reset the quadruplet index.
q = 0;
}
}
// If the quadruplet is not empty, flag invalid.
if (q != 0)
invalid = true;
// If invalid throw an exception.
if (invalid)
throw new IllegalArgumentException("Invalid Base64 encoded string: " + s);
// Always copy the destination buffer into the return buffer to
// maintain consistent runtime.
final byte[] ret = new byte[o];
System.arraycopy(out, 0, ret, 0, o);
return ret;
}
}
| 3,406 |
8,232 | <filename>tests/std/tests/Dev10_391723_bind_result_type/test.cpp
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#define _HAS_DEPRECATED_ADAPTOR_TYPEDEFS 1
#define _SILENCE_CXX17_ADAPTOR_TYPEDEFS_DEPRECATION_WARNING
#include <functional>
#include <type_traits>
using namespace std;
#define STATIC_ASSERT(...) static_assert(__VA_ARGS__, #__VA_ARGS__)
template <typename Correct, typename F>
void test(const F&) {
STATIC_ASSERT(is_same_v<Correct, typename F::result_type>);
}
int cat(int) {
return 5;
}
struct X {
int dog() {
return 6;
}
};
struct Y {
typedef int result_type;
int operator()(int) const {
return 7;
}
};
int main() {
X x;
test<int>(bind(cat, 10));
test<int>(bind(&cat, 10));
test<int>(bind(&X::dog, x));
test<int>(bind(Y(), 20));
test<double>(bind<double>(cat, 10));
test<double>(bind<double>(&cat, 10));
test<double>(bind<double>(&X::dog, x));
test<double>(bind<double>(Y(), 20));
}
| 507 |
4,168 | <filename>scripts/save_tag.py
import argparse
from git import git_command
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--tag", type=str, help="tag name", required=True)
parser.add_argument("--commit", type=str, help="commit hash", required=True)
args = parser.parse_args()
git_command("tag", "-d", args.tag, check=False)
git_command("tag", args.tag, args.commit)
git_command("push", "-f", "origin", args.tag)
| 171 |
1,405 | <reponame>jarekankowski/pegasus_spyware
package com.lenovo.safecenter.shortcut;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class WidgetProvider extends AppWidgetProvider {
public void onEnabled(Context context) {
super.onEnabled(context);
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.i("Widget", "WidgetProvider onUpdate");
context.startService(new Intent(context, WidgetUpdateService.class));
}
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals("com.lenovo.safecenter.ONEKEY_WIDGET_REFRESH")) {
context.startService(new Intent(context, WidgetUpdateService.class));
}
}
public void onDisabled(Context context) {
super.onDisabled(context);
context.stopService(new Intent(context, WidgetUpdateService.class));
}
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
}
}
| 428 |
2,392 | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 <NAME> <<EMAIL>>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#ifndef IGL_CROSS_H
#define IGL_CROSS_H
#include "igl_inline.h"
#include <Eigen/Core>
namespace igl
{
// Computes out = cross(a,b)
// Inputs:
// a left 3d vector
// b right 3d vector
// Outputs:
// out result 3d vector
IGL_INLINE void cross( const double *a, const double *b, double *out);
// Computes C = cross(A,B,2);
//
// Inputs:
// A #A by 3 list of row-vectors
// B #A by 3 list of row-vectors
// Outputs:
// C #A by 3 list of row-vectors
template <
typename DerivedA,
typename DerivedB,
typename DerivedC>
IGL_INLINE void cross(
const Eigen::PlainObjectBase<DerivedA> & A,
const Eigen::PlainObjectBase<DerivedB> & B,
Eigen::PlainObjectBase<DerivedC> & C);
}
#ifndef IGL_STATIC_LIBRARY
# include "cross.cpp"
#endif
#endif
| 446 |
402 | package javax0.license3j.io;
/**
* License can be stored in files in three different format:
*
* <ol>
* <li>BINARY is as the name suggests binary format</li>
* <li>BASE64 is the same as binary but encoded to be ascii using the Base64 encoding</li>
* <li>STRING is a textual, human readable format that can be edited using text editor</li>
* </ol>
*
*/
public enum IOFormat {
BINARY, BASE64, STRING
}
| 148 |
381 | #import <UIKit/UIKit.h>
FOUNDATION_EXPORT double Pods_MEVHorizontalContacts_ExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_MEVHorizontalContacts_ExampleVersionString[];
| 60 |
320 | <filename>Settings/Controls/TabPage.h
// Copyright (c) 2015, <NAME>.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#pragma once
#include <Windows.h>
#include <string>
#include <unordered_map>
#include "Dialog.h"
class Control;
class TabPage : public Dialog {
public:
TabPage(HINSTANCE hInstance, LPCWSTR tabTemplate, LPCWSTR title = L"");
HPROPSHEETPAGE PageHandle();
protected:
HINSTANCE _hInstance;
HPROPSHEETPAGE _pageHandle;
std::wstring _title;
static INT_PTR CALLBACK StaticTabProc(HWND hwndDlg, UINT uMsg,
WPARAM wParam, LPARAM lParam);
}; | 242 |
879 | package org.zstack.test.deployer;
import org.zstack.header.zone.ZoneInventory;
import org.zstack.test.ApiSenderException;
import org.zstack.test.deployer.schema.DeployerConfig;
import org.zstack.test.deployer.schema.ZoneConfig;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;
import java.util.List;
public class DefaultZoneDeployer implements ZoneDeployer<ZoneConfig> {
private CLogger logger = Utils.getLogger(DefaultZoneDeployer.class);
@Override
public Class<ZoneConfig> getSupportedDeployerClassType() {
return ZoneConfig.class;
}
@Override
public void deploy(List<ZoneConfig> zones, DeployerConfig config, Deployer deployer) throws ApiSenderException {
for (ZoneConfig zone : zones) {
ZoneInventory zinv = new ZoneInventory();
zinv.setName(zone.getName());
zinv.setDescription(zone.getDescription());
zinv = deployer.getApi().createZoneByFullConfig(zinv);
deployer.zones.put(zinv.getName(), zinv);
deployer.deployCluster(zone.getClusters(), zinv);
deployer.deployPrimaryStorage(zone.getPrimaryStorages(), zinv);
deployer.deployL2Network(zone.getL2Networks(), zinv);
deployer.attachBackupStorage(zone.getBackupStorageRef(), zinv);
}
}
}
| 527 |
752 |
import os
import re
import sys
from mtm.ioc.Inject import Inject
import mtm.util.Util as Util
from mtm.log.Logger import LogType
import shutil
from mtm.util.Assert import *
import mtm.log.ColorConsole as ColorConsole
class AnsiiCodes:
BLACK = "\033[1;30m"
DARKBLACK = "\033[0;30m"
RED = "\033[1;31m"
DARKRED = "\033[0;31m"
GREEN = "\033[1;32m"
DARKGREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
DARKYELLOW = "\033[0;33m"
BLUE = "\033[1;34m"
DARKBLUE = "\033[0;34m"
MAGENTA = "\033[1;35m"
DARKMAGENTA = "\033[0;35m"
CYAN = "\033[1;36m"
DARKCYAN = "\033[0;36m"
WHITE = "\033[1;37m"
DARKWHITE = "\033[0;37m"
END = "\033[0;0m"
class LogStreamConsole:
_log = Inject('Logger')
_sys = Inject('SystemHelper')
_varManager = Inject('VarManager')
_config = Inject('Config')
def __init__(self, verbose, veryVerbose):
self._verbose = verbose or veryVerbose
self._veryVerbose = veryVerbose
self._useColors = self._config.tryGetBool(False, 'LogStreamConsole', 'UseColors')
self._fileStream = None
if self._config.tryGetBool(False, 'LogStreamConsole', 'OutputToFilteredLog'):
self._fileStream = self._getFileStream()
if self._useColors:
self._initColors()
def _initColors(self):
self._defaultColors = ColorConsole.get_text_attr()
self._defaultBg = self._defaultColors & 0x0070
self._defaultFg = self._defaultColors & 0x0007
def log(self, logType, message):
assertIsNotNone(logType)
if logType == LogType.Noise and not self._veryVerbose:
return
if logType == LogType.Debug and not self._verbose:
return
if logType == LogType.Error:
self._output(logType, message, sys.stderr, self._useColors)
else:
self._output(logType, message, sys.stdout, self._useColors)
if self._fileStream:
self._output(logType, message, self._fileStream, False)
def _getFileStream(self):
primaryPath = self._varManager.expand('[LogFilteredPath]')
if not primaryPath:
raise Exception("Could not find path for log file")
previousPath = None
if self._varManager.hasKey('LogFilteredPreviousPath'):
previousPath = self._varManager.expand('[LogFilteredPreviousPath]')
# Keep one old build log
if os.path.isfile(primaryPath) and previousPath:
shutil.copy2(primaryPath, previousPath)
return open(primaryPath, 'w', encoding='utf-8', errors='ignore')
def _getHeadingIndent(self):
return self._log.getCurrentNumHeadings() * " "
def _output(self, logType, message, stream, useColors):
stream.write('\n')
stream.write(self._getHeadingIndent())
if not useColors or logType == LogType.Info:
stream.write(message)
stream.flush()
else:
ColorConsole.set_text_attr(self._getColorAttrs(logType))
stream.write(message)
stream.flush()
ColorConsole.set_text_attr(self._defaultColors)
def _getColorAttrs(self, logType):
if logType == LogType.HeadingStart:
return ColorConsole.FOREGROUND_CYAN | self._defaultBg | ColorConsole.FOREGROUND_INTENSITY
if logType == LogType.HeadingEnd:
return ColorConsole.FOREGROUND_BLACK | self._defaultBg | ColorConsole.FOREGROUND_INTENSITY
if logType == LogType.Good:
return ColorConsole.FOREGROUND_GREEN | self._defaultBg | ColorConsole.FOREGROUND_INTENSITY
if logType == LogType.Warn:
return ColorConsole.FOREGROUND_YELLOW | self._defaultBg | ColorConsole.FOREGROUND_INTENSITY
if logType == LogType.Error:
return ColorConsole.FOREGROUND_RED | self._defaultBg | ColorConsole.FOREGROUND_INTENSITY
assertThat(logType == LogType.Debug or logType == LogType.Noise)
return ColorConsole.FOREGROUND_BLACK | self._defaultBg | ColorConsole.FOREGROUND_INTENSITY
| 1,756 |
1,647 | <gh_stars>1000+
#ifndef PYTHONIC_BUILTIN_NOTIMPLEMENTEDERROR_HPP
#define PYTHONIC_BUILTIN_NOTIMPLEMENTEDERROR_HPP
#include "pythonic/include/builtins/NotImplementedError.hpp"
#include "pythonic/types/exceptions.hpp"
PYTHONIC_NS_BEGIN
namespace builtins
{
PYTHONIC_EXCEPTION_IMPL(NotImplementedError)
}
PYTHONIC_NS_END
#endif
| 151 |
746 |
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
/**
* This extension contains several a helper
* for creating a sha1 hash from instances of NSString
*/
@interface NSString (Sha1)
/**
* Creates a SHA1 (hash) representation of NSString.
*
* @return NSString
*/
- (NSString *)sha1;
@end
| 105 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-wvpv-ffcv-r6cw",
"modified": "2021-01-08T20:22:38Z",
"published": "2020-04-14T23:09:13Z",
"aliases": [
"CVE-2020-11005"
],
"summary": "Internal NCryptDecrypt method could be used externally from WindowsHello library.",
"details": "### Impact\nEvery user of the library before version 1.0.4.\n\n### Patches\nPatched in 1.0.4+.\n\n### Workarounds\nNone.\n\n### References\nhttps://github.com/SeppPenner/WindowsHello/issues/3\n\n### For more information\nIt this library is used to encrypt text and write the output to a txt file, another executable could be able to decrypt the text using the static method NCryptDecrypt from this same library without the need to use Windows Hello Authentication again.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:L/AC:H/PR:N/UI:N/S:U/C:H/I:N/A:N"
}
],
"affected": [
{
"package": {
"ecosystem": "NuGet",
"name": "HaemmerElectronics.SeppPenner.WindowsHello"
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.0.4"
}
]
}
]
}
],
"references": [
{
"type": "WEB",
"url": "https://github.com/SeppPenner/WindowsHello/security/advisories/GHSA-wvpv-ffcv-r6cw"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2020-11005"
},
{
"type": "WEB",
"url": "https://github.com/SeppPenner/WindowsHello/issues/3"
}
],
"database_specific": {
"cwe_ids": [
"CWE-288"
],
"severity": "MODERATE",
"github_reviewed": true
}
} | 849 |
4,124 | /**
* 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.jstorm.example.unittests.order;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.BasicOutputCollector;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseBasicBolt;
import backtype.storm.tuple.Tuple;
import com.alibaba.jstorm.common.metric.AsmCounter;
import com.alibaba.jstorm.common.metric.AsmMetric;
import com.alibaba.jstorm.metric.MetricClient;
import java.util.HashMap;
import java.util.Map;
/**
* @author binyang.dby
*/
public class InOrderTestBolt extends BaseBasicBolt
{
private Map<Integer, Integer> expected = new HashMap<>(); //store the taskIndex and the content has received before.
private transient MetricClient metricClient;
private transient AsmCounter successCounter;
private transient AsmCounter failCounter;
@Override
public void prepare(Map stormConf, TopologyContext context)
{
super.prepare(stormConf, context);
metricClient = new MetricClient(context);
successCounter = metricClient.registerCounter(InOrderTestMetricsDef.METRIC_BOLT_SUCCESS);
successCounter.setOp(AsmMetric.MetricOp.LOG & AsmMetric.MetricOp.REPORT);
failCounter = metricClient.registerCounter(InOrderTestMetricsDef.METRIC_BOLT_FAIL);
failCounter.setOp(AsmMetric.MetricOp.LOG & AsmMetric.MetricOp.REPORT);
}
@Override
public void execute(Tuple input, BasicOutputCollector collector) {
Integer c1 = input.getInteger(0);
Integer c2 = input.getInteger(1);
Integer expect = expected.get(c1);
if (expect == null)
expect = 0;
if (c2.intValue() == expect.intValue())
successCounter.inc();
else
failCounter.inc();
expect = c2 + 1;
expected.put(c1, expect);
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
}
}
| 913 |
3,102 | <reponame>medismailben/llvm-project
// RUN: %clang_cc1 -E %s | FileCheck %s --match-full-lines --strict-whitespace
// CHECK: # define X 3
#define H #
#define D define
#define DEFINE(a, b) H D a b
DEFINE(X, 3)
| 97 |
4,812 | //===---------------------- MicroOpQueueStage.cpp ---------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file defines the MicroOpQueueStage.
///
//===----------------------------------------------------------------------===//
#include "llvm/MCA/Stages/MicroOpQueueStage.h"
namespace llvm {
namespace mca {
#define DEBUG_TYPE "llvm-mca"
Error MicroOpQueueStage::moveInstructions() {
InstRef IR = Buffer[CurrentInstructionSlotIdx];
while (IR && checkNextStage(IR)) {
if (llvm::Error Val = moveToTheNextStage(IR))
return Val;
Buffer[CurrentInstructionSlotIdx].invalidate();
unsigned NormalizedOpcodes = getNormalizedOpcodes(IR);
CurrentInstructionSlotIdx += NormalizedOpcodes;
CurrentInstructionSlotIdx %= Buffer.size();
AvailableEntries += NormalizedOpcodes;
IR = Buffer[CurrentInstructionSlotIdx];
}
return llvm::ErrorSuccess();
}
MicroOpQueueStage::MicroOpQueueStage(unsigned Size, unsigned IPC,
bool ZeroLatencyStage)
: NextAvailableSlotIdx(0), CurrentInstructionSlotIdx(0), MaxIPC(IPC),
CurrentIPC(0), IsZeroLatencyStage(ZeroLatencyStage) {
Buffer.resize(Size ? Size : 1);
AvailableEntries = Buffer.size();
}
Error MicroOpQueueStage::execute(InstRef &IR) {
Buffer[NextAvailableSlotIdx] = IR;
unsigned NormalizedOpcodes = getNormalizedOpcodes(IR);
NextAvailableSlotIdx += NormalizedOpcodes;
NextAvailableSlotIdx %= Buffer.size();
AvailableEntries -= NormalizedOpcodes;
++CurrentIPC;
return llvm::ErrorSuccess();
}
Error MicroOpQueueStage::cycleStart() {
CurrentIPC = 0;
if (!IsZeroLatencyStage)
return moveInstructions();
return llvm::ErrorSuccess();
}
Error MicroOpQueueStage::cycleEnd() {
if (IsZeroLatencyStage)
return moveInstructions();
return llvm::ErrorSuccess();
}
} // namespace mca
} // namespace llvm
| 702 |
1,062 | {
"name" : "<NAME>",
"type" : "NATIVEC, JAVA"
"artifact" : "lib or class name",
"inputs" : [ "dataset1"],
"outputs" : [ "dataset1", "dataset2" ]
"optionalInputs" : [ "dataset2" ]
"extras" : [ "libname1", "libname2" ]
"dimensions" : [
{
"name" : "dim1",
"canSplit" : true or false, defaults to true
"overlapBefore" : optional int, defaults to zero
"overlapAfter" : optional int, defaults to zero
"maxSize" : optional int
"dependent" : true or false, defaults to false
}
]
}
| 221 |
388 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .teams_task_module_bot import TaskModuleBot
__all__ = ["TaskModuleBot"]
| 54 |
435 | <reponame>amaajemyfren/data
{
"copyright_text": "Creative Commons Attribution license (reuse allowed)",
"description": "One of the core concepts of Application Development, (not just in\npython), is the separation between the Business Logic and the User\nInterface. However there is a strong temptation to start with the user\ninterface and add the business logic to it some methodologies emphasize\nthis with the process of prototyping the (G)UI first. The danger is that\nyour business logic code can get too entangled with the UI and a change\nof platform or framework becomes almost impossible.\n\nThis presentation will show how to maintain a clear separation between\nthe Business Logic and the User Interface by starting with a command\nline interface using argparse and growing a GUI on top.\n\nWe will cover: - Why maintain the seperation - Using argparse - Adding a\nGUI layer with wxPython - Automating the GUI generation - Adding a web\ninterface - Testing advantages of this approach - Scripting advantages -\nSome packaging models.\n\nSlides and Samples all uploaded to\nhttps://github.com/GadgetSteve/EP2018\\_Talk\n",
"duration": 1511,
"language": "eng",
"recorded": "2018-07-26",
"related_urls": [
{
"label": "Conference schedule",
"url": "https://ep2018.europython.eu/p3/schedule/ep2018/"
}
],
"speakers": [
"<NAME>"
],
"tags": [],
"thumbnail_url": "https://i.ytimg.com/vi/7qLNrcYkQiY/maxresdefault.jpg",
"title": "Why develop a CLI (Command Line Interface) first?",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=7qLNrcYkQiY"
}
]
}
| 515 |
502 | <filename>tracer-core/src/main/java/com/alipay/common/tracer/core/reporter/stat/SofaTracerStatisticReporter.java<gh_stars>100-1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.common.tracer.core.reporter.stat;
import com.alipay.common.tracer.core.reporter.stat.model.StatKey;
import com.alipay.common.tracer.core.reporter.stat.model.StatValues;
import com.alipay.common.tracer.core.span.SofaTracerSpan;
import java.util.Map;
/**
* SofaTracerStatisticReporter
* <p>
* Reference: {com.alipay.common.tracer.tracer.StatTracer}
* </p>
* @author yangguanchao
* @since 2017/06/26
*/
public interface SofaTracerStatisticReporter {
/**
* get the period time
* @return
*/
long getPeriodTime();
/**
* Get the unique identifier of the statistic type
* @return
*/
String getStatTracerName();
/**
* Update data to the slot
* @param sofaTracerSpan
*/
void reportStat(SofaTracerSpan sofaTracerSpan);
/**
* Switch the current subscript and return the stat before switching
* @return
*/
Map<StatKey, StatValues> shiftCurrentIndex();
/**
* When the method is called, it indicates that a cycle has passed,
* to determine whether enough cycles have passed, and whether flush is needed.
*
* @return true:stat log can be printed and the framework will call {@link SofaTracerStatisticReporter#print}
*/
boolean shouldPrintNow();
/**
* Print, you can print to a local disk, or you can report to a remote server
* @param statKey
* @param values
*/
void print(StatKey statKey, long[] values);
/**
* close print
*/
void close();
}
| 815 |
1,444 |
package mage.cards.v;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.costs.mana.ColoredManaCost;
import mage.abilities.effects.common.ReturnToHandTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.ColoredManaSymbol;
import mage.constants.Zone;
import mage.target.common.TargetControlledPermanent;
/**
*
* @author Loki
*/
public final class VedalkenMastermind extends CardImpl {
public VedalkenMastermind(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{U}{U}");
this.subtype.add(SubType.VEDALKEN);
this.subtype.add(SubType.WIZARD);
this.power = new MageInt(1);
this.toughness = new MageInt(2);
// {U}{Tap}: Return target permanent you control to its owner's hand.
Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new ReturnToHandTargetEffect(), new ColoredManaCost(ColoredManaSymbol.U));
ability.addCost(new TapSourceCost());
ability.addTarget(new TargetControlledPermanent());
this.addAbility(ability);
}
private VedalkenMastermind(final VedalkenMastermind card) {
super(card);
}
@Override
public VedalkenMastermind copy() {
return new VedalkenMastermind(this);
}
}
| 556 |
1,426 | <filename>extensions/robospice-ui-spicelist-parent/robospice-ui-spicelist/src/main/java/com/octo/android/robospice/spicelist/simple/BitmapSpiceManager.java
package com.octo.android.robospice.spicelist.simple;
import com.octo.android.robospice.SpiceManager;
public class BitmapSpiceManager extends SpiceManager {
public BitmapSpiceManager() {
super(BitmapSpiceService.class);
}
/**
* For testing only.
* @param bitmapSpiceServiceClass
* the spice service to bind to.
*/
protected BitmapSpiceManager(Class<? extends BitmapSpiceService> bitmapSpiceServiceClass) {
super(bitmapSpiceServiceClass);
}
}
| 256 |
14,668 | <gh_stars>1000+
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.google.protobuf;
import static com.google.protobuf.UnittestLite.defaultBoolExtensionLite;
import static com.google.protobuf.UnittestLite.defaultBytesExtensionLite;
import static com.google.protobuf.UnittestLite.defaultCordExtensionLite;
import static com.google.protobuf.UnittestLite.defaultDoubleExtensionLite;
import static com.google.protobuf.UnittestLite.defaultFixed32ExtensionLite;
import static com.google.protobuf.UnittestLite.defaultFixed64ExtensionLite;
import static com.google.protobuf.UnittestLite.defaultFloatExtensionLite;
import static com.google.protobuf.UnittestLite.defaultForeignEnumExtensionLite;
import static com.google.protobuf.UnittestLite.defaultImportEnumExtensionLite;
import static com.google.protobuf.UnittestLite.defaultInt32ExtensionLite;
import static com.google.protobuf.UnittestLite.defaultInt64ExtensionLite;
import static com.google.protobuf.UnittestLite.defaultNestedEnumExtensionLite;
import static com.google.protobuf.UnittestLite.defaultSfixed32ExtensionLite;
import static com.google.protobuf.UnittestLite.defaultSfixed64ExtensionLite;
import static com.google.protobuf.UnittestLite.defaultSint32ExtensionLite;
import static com.google.protobuf.UnittestLite.defaultSint64ExtensionLite;
import static com.google.protobuf.UnittestLite.defaultStringExtensionLite;
import static com.google.protobuf.UnittestLite.defaultStringPieceExtensionLite;
import static com.google.protobuf.UnittestLite.defaultUint32ExtensionLite;
import static com.google.protobuf.UnittestLite.defaultUint64ExtensionLite;
import static com.google.protobuf.UnittestLite.oneofBytesExtensionLite;
import static com.google.protobuf.UnittestLite.oneofNestedMessageExtensionLite;
import static com.google.protobuf.UnittestLite.oneofStringExtensionLite;
import static com.google.protobuf.UnittestLite.oneofUint32ExtensionLite;
import static com.google.protobuf.UnittestLite.optionalBoolExtensionLite;
import static com.google.protobuf.UnittestLite.optionalBytesExtensionLite;
import static com.google.protobuf.UnittestLite.optionalCordExtensionLite;
import static com.google.protobuf.UnittestLite.optionalDoubleExtensionLite;
import static com.google.protobuf.UnittestLite.optionalFixed32ExtensionLite;
import static com.google.protobuf.UnittestLite.optionalFixed64ExtensionLite;
import static com.google.protobuf.UnittestLite.optionalFloatExtensionLite;
import static com.google.protobuf.UnittestLite.optionalForeignEnumExtensionLite;
import static com.google.protobuf.UnittestLite.optionalForeignMessageExtensionLite;
import static com.google.protobuf.UnittestLite.optionalGroupExtensionLite;
import static com.google.protobuf.UnittestLite.optionalImportEnumExtensionLite;
import static com.google.protobuf.UnittestLite.optionalImportMessageExtensionLite;
import static com.google.protobuf.UnittestLite.optionalInt32ExtensionLite;
import static com.google.protobuf.UnittestLite.optionalInt64ExtensionLite;
import static com.google.protobuf.UnittestLite.optionalLazyMessageExtensionLite;
import static com.google.protobuf.UnittestLite.optionalNestedEnumExtensionLite;
import static com.google.protobuf.UnittestLite.optionalNestedMessageExtensionLite;
import static com.google.protobuf.UnittestLite.optionalPublicImportMessageExtensionLite;
import static com.google.protobuf.UnittestLite.optionalSfixed32ExtensionLite;
import static com.google.protobuf.UnittestLite.optionalSfixed64ExtensionLite;
import static com.google.protobuf.UnittestLite.optionalSint32ExtensionLite;
import static com.google.protobuf.UnittestLite.optionalSint64ExtensionLite;
import static com.google.protobuf.UnittestLite.optionalStringExtensionLite;
import static com.google.protobuf.UnittestLite.optionalStringPieceExtensionLite;
import static com.google.protobuf.UnittestLite.optionalUint32ExtensionLite;
import static com.google.protobuf.UnittestLite.optionalUint64ExtensionLite;
import static com.google.protobuf.UnittestLite.packedBoolExtensionLite;
import static com.google.protobuf.UnittestLite.packedDoubleExtensionLite;
import static com.google.protobuf.UnittestLite.packedEnumExtensionLite;
import static com.google.protobuf.UnittestLite.packedFixed32ExtensionLite;
import static com.google.protobuf.UnittestLite.packedFixed64ExtensionLite;
import static com.google.protobuf.UnittestLite.packedFloatExtensionLite;
import static com.google.protobuf.UnittestLite.packedInt32ExtensionLite;
import static com.google.protobuf.UnittestLite.packedInt64ExtensionLite;
import static com.google.protobuf.UnittestLite.packedSfixed32ExtensionLite;
import static com.google.protobuf.UnittestLite.packedSfixed64ExtensionLite;
import static com.google.protobuf.UnittestLite.packedSint32ExtensionLite;
import static com.google.protobuf.UnittestLite.packedSint64ExtensionLite;
import static com.google.protobuf.UnittestLite.packedUint32ExtensionLite;
import static com.google.protobuf.UnittestLite.packedUint64ExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedBoolExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedBytesExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedCordExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedDoubleExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedFixed32ExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedFixed64ExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedFloatExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedForeignEnumExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedForeignMessageExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedGroupExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedImportEnumExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedImportMessageExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedInt32ExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedInt64ExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedLazyMessageExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedNestedEnumExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedNestedMessageExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedSfixed32ExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedSfixed64ExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedSint32ExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedSint64ExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedStringExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedStringPieceExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedUint32ExtensionLite;
import static com.google.protobuf.UnittestLite.repeatedUint64ExtensionLite;
import com.google.protobuf.UnittestImportLite.ImportEnumLite;
import com.google.protobuf.UnittestImportLite.ImportMessageLite;
import com.google.protobuf.UnittestImportPublicLite.PublicImportMessageLite;
import com.google.protobuf.UnittestLite.ForeignEnumLite;
import com.google.protobuf.UnittestLite.ForeignMessageLite;
import com.google.protobuf.UnittestLite.OptionalGroup_extension_lite;
import com.google.protobuf.UnittestLite.RepeatedGroup_extension_lite;
import com.google.protobuf.UnittestLite.TestAllExtensionsLite;
import com.google.protobuf.UnittestLite.TestAllTypesLite;
import com.google.protobuf.UnittestLite.TestPackedExtensionsLite;
/**
* Contains methods for setting fields of {@code TestAllTypesLite}, {@code TestAllExtensionsLite},
* and {@code TestPackedExtensionsLite}. This is analogous to the functionality in TestUtil.java but
* does not depend on the presence of any non-lite protos.
*
* <p>This code is not to be used outside of {@code com.google.protobuf} and subpackages.
*/
public final class TestUtilLite {
private TestUtilLite() {}
/** Helper to convert a String to ByteString. */
static ByteString toBytes(String str) {
return ByteString.copyFrom(str.getBytes(Internal.UTF_8));
}
/**
* Get a {@code TestAllTypesLite.Builder} with all fields set as they would be by {@link
* #setAllFields(TestAllTypesLite.Builder)}.
*/
public static TestAllTypesLite.Builder getAllLiteSetBuilder() {
TestAllTypesLite.Builder builder = TestAllTypesLite.newBuilder();
setAllFields(builder);
return builder;
}
/**
* Get a {@code TestAllExtensionsLite} with all fields set as they would be by {@link
* #setAllExtensions(TestAllExtensionsLite.Builder)}.
*/
public static TestAllExtensionsLite getAllLiteExtensionsSet() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.newBuilder();
setAllExtensions(builder);
return builder.build();
}
public static TestPackedExtensionsLite getLitePackedExtensionsSet() {
TestPackedExtensionsLite.Builder builder = TestPackedExtensionsLite.newBuilder();
setPackedExtensions(builder);
return builder.build();
}
/** Set every field of {@code builder} to the values expected by {@code assertAllFieldsSet()}. */
public static void setAllFields(TestAllTypesLite.Builder builder) {
builder.setOptionalInt32(101);
builder.setOptionalInt64(102);
builder.setOptionalUint32(103);
builder.setOptionalUint64(104);
builder.setOptionalSint32(105);
builder.setOptionalSint64(106);
builder.setOptionalFixed32(107);
builder.setOptionalFixed64(108);
builder.setOptionalSfixed32(109);
builder.setOptionalSfixed64(110);
builder.setOptionalFloat(111);
builder.setOptionalDouble(112);
builder.setOptionalBool(true);
builder.setOptionalString("115");
builder.setOptionalBytes(toBytes("116"));
builder.setOptionalGroup(TestAllTypesLite.OptionalGroup.newBuilder().setA(117).build());
builder.setOptionalNestedMessage(
TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build());
builder.setOptionalForeignMessage(ForeignMessageLite.newBuilder().setC(119).build());
builder.setOptionalImportMessage(ImportMessageLite.newBuilder().setD(120).build());
builder.setOptionalPublicImportMessage(PublicImportMessageLite.newBuilder().setE(126).build());
builder.setOptionalLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build());
builder.setOptionalNestedEnum(TestAllTypesLite.NestedEnum.BAZ);
builder.setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAZ);
builder.setOptionalImportEnum(ImportEnumLite.IMPORT_LITE_BAZ);
builder.setOptionalStringPiece("124");
builder.setOptionalCord("125");
// -----------------------------------------------------------------
builder.addRepeatedInt32(201);
builder.addRepeatedInt64(202);
builder.addRepeatedUint32(203);
builder.addRepeatedUint64(204);
builder.addRepeatedSint32(205);
builder.addRepeatedSint64(206);
builder.addRepeatedFixed32(207);
builder.addRepeatedFixed64(208);
builder.addRepeatedSfixed32(209);
builder.addRepeatedSfixed64(210);
builder.addRepeatedFloat(211);
builder.addRepeatedDouble(212);
builder.addRepeatedBool(true);
builder.addRepeatedString("215");
builder.addRepeatedBytes(toBytes("216"));
builder.addRepeatedGroup(TestAllTypesLite.RepeatedGroup.newBuilder().setA(217).build());
builder.addRepeatedNestedMessage(
TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build());
builder.addRepeatedForeignMessage(ForeignMessageLite.newBuilder().setC(219).build());
builder.addRepeatedImportMessage(ImportMessageLite.newBuilder().setD(220).build());
builder.addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build());
builder.addRepeatedNestedEnum(TestAllTypesLite.NestedEnum.BAR);
builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAR);
builder.addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAR);
builder.addRepeatedStringPiece("224");
builder.addRepeatedCord("225");
// Add a second one of each field.
builder.addRepeatedInt32(301);
builder.addRepeatedInt64(302);
builder.addRepeatedUint32(303);
builder.addRepeatedUint64(304);
builder.addRepeatedSint32(305);
builder.addRepeatedSint64(306);
builder.addRepeatedFixed32(307);
builder.addRepeatedFixed64(308);
builder.addRepeatedSfixed32(309);
builder.addRepeatedSfixed64(310);
builder.addRepeatedFloat(311);
builder.addRepeatedDouble(312);
builder.addRepeatedBool(false);
builder.addRepeatedString("315");
builder.addRepeatedBytes(toBytes("316"));
builder.addRepeatedGroup(TestAllTypesLite.RepeatedGroup.newBuilder().setA(317).build());
builder.addRepeatedNestedMessage(
TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build());
builder.addRepeatedForeignMessage(ForeignMessageLite.newBuilder().setC(319).build());
builder.addRepeatedImportMessage(ImportMessageLite.newBuilder().setD(320).build());
builder.addRepeatedLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build());
builder.addRepeatedNestedEnum(TestAllTypesLite.NestedEnum.BAZ);
builder.addRepeatedForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAZ);
builder.addRepeatedImportEnum(ImportEnumLite.IMPORT_LITE_BAZ);
builder.addRepeatedStringPiece("324");
builder.addRepeatedCord("325");
// -----------------------------------------------------------------
builder.setDefaultInt32(401);
builder.setDefaultInt64(402);
builder.setDefaultUint32(403);
builder.setDefaultUint64(404);
builder.setDefaultSint32(405);
builder.setDefaultSint64(406);
builder.setDefaultFixed32(407);
builder.setDefaultFixed64(408);
builder.setDefaultSfixed32(409);
builder.setDefaultSfixed64(410);
builder.setDefaultFloat(411);
builder.setDefaultDouble(412);
builder.setDefaultBool(false);
builder.setDefaultString("415");
builder.setDefaultBytes(toBytes("416"));
builder.setDefaultNestedEnum(TestAllTypesLite.NestedEnum.FOO);
builder.setDefaultForeignEnum(ForeignEnumLite.FOREIGN_LITE_FOO);
builder.setDefaultImportEnum(ImportEnumLite.IMPORT_LITE_FOO);
builder.setDefaultStringPiece("424");
builder.setDefaultCord("425");
builder.setOneofUint32(601);
builder.setOneofNestedMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build());
builder.setOneofString("603");
builder.setOneofBytes(toBytes("604"));
}
/**
* Get an unmodifiable {@link ExtensionRegistryLite} containing all the extensions of {@code
* TestAllExtensionsLite}.
*/
public static ExtensionRegistryLite getExtensionRegistryLite() {
ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance();
registerAllExtensionsLite(registry);
return registry.getUnmodifiable();
}
/**
* Register all of {@code TestAllExtensionsLite}'s extensions with the given {@link
* ExtensionRegistryLite}.
*/
public static void registerAllExtensionsLite(ExtensionRegistryLite registry) {
UnittestLite.registerAllExtensions(registry);
}
// ===================================================================
// Lite extensions
/**
* Set every field of {@code message} to the values expected by {@code assertAllExtensionsSet()}.
*/
public static void setAllExtensions(TestAllExtensionsLite.Builder message) {
message.setExtension(optionalInt32ExtensionLite, 101);
message.setExtension(optionalInt64ExtensionLite, 102L);
message.setExtension(optionalUint32ExtensionLite, 103);
message.setExtension(optionalUint64ExtensionLite, 104L);
message.setExtension(optionalSint32ExtensionLite, 105);
message.setExtension(optionalSint64ExtensionLite, 106L);
message.setExtension(optionalFixed32ExtensionLite, 107);
message.setExtension(optionalFixed64ExtensionLite, 108L);
message.setExtension(optionalSfixed32ExtensionLite, 109);
message.setExtension(optionalSfixed64ExtensionLite, 110L);
message.setExtension(optionalFloatExtensionLite, 111F);
message.setExtension(optionalDoubleExtensionLite, 112D);
message.setExtension(optionalBoolExtensionLite, true);
message.setExtension(optionalStringExtensionLite, "115");
message.setExtension(optionalBytesExtensionLite, toBytes("116"));
message.setExtension(
optionalGroupExtensionLite, OptionalGroup_extension_lite.newBuilder().setA(117).build());
message.setExtension(
optionalNestedMessageExtensionLite,
TestAllTypesLite.NestedMessage.newBuilder().setBb(118).build());
message.setExtension(
optionalForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(119).build());
message.setExtension(
optionalImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(120).build());
message.setExtension(
optionalPublicImportMessageExtensionLite,
PublicImportMessageLite.newBuilder().setE(126).build());
message.setExtension(
optionalLazyMessageExtensionLite,
TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build());
message.setExtension(optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ);
message.setExtension(optionalForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ);
message.setExtension(optionalImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAZ);
message.setExtension(optionalStringPieceExtensionLite, "124");
message.setExtension(optionalCordExtensionLite, "125");
// -----------------------------------------------------------------
message.addExtension(repeatedInt32ExtensionLite, 201);
message.addExtension(repeatedInt64ExtensionLite, 202L);
message.addExtension(repeatedUint32ExtensionLite, 203);
message.addExtension(repeatedUint64ExtensionLite, 204L);
message.addExtension(repeatedSint32ExtensionLite, 205);
message.addExtension(repeatedSint64ExtensionLite, 206L);
message.addExtension(repeatedFixed32ExtensionLite, 207);
message.addExtension(repeatedFixed64ExtensionLite, 208L);
message.addExtension(repeatedSfixed32ExtensionLite, 209);
message.addExtension(repeatedSfixed64ExtensionLite, 210L);
message.addExtension(repeatedFloatExtensionLite, 211F);
message.addExtension(repeatedDoubleExtensionLite, 212D);
message.addExtension(repeatedBoolExtensionLite, true);
message.addExtension(repeatedStringExtensionLite, "215");
message.addExtension(repeatedBytesExtensionLite, toBytes("216"));
message.addExtension(
repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(217).build());
message.addExtension(
repeatedNestedMessageExtensionLite,
TestAllTypesLite.NestedMessage.newBuilder().setBb(218).build());
message.addExtension(
repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(219).build());
message.addExtension(
repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(220).build());
message.addExtension(
repeatedLazyMessageExtensionLite,
TestAllTypesLite.NestedMessage.newBuilder().setBb(227).build());
message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAR);
message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAR);
message.addExtension(repeatedImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAR);
message.addExtension(repeatedStringPieceExtensionLite, "224");
message.addExtension(repeatedCordExtensionLite, "225");
// Add a second one of each field.
message.addExtension(repeatedInt32ExtensionLite, 301);
message.addExtension(repeatedInt64ExtensionLite, 302L);
message.addExtension(repeatedUint32ExtensionLite, 303);
message.addExtension(repeatedUint64ExtensionLite, 304L);
message.addExtension(repeatedSint32ExtensionLite, 305);
message.addExtension(repeatedSint64ExtensionLite, 306L);
message.addExtension(repeatedFixed32ExtensionLite, 307);
message.addExtension(repeatedFixed64ExtensionLite, 308L);
message.addExtension(repeatedSfixed32ExtensionLite, 309);
message.addExtension(repeatedSfixed64ExtensionLite, 310L);
message.addExtension(repeatedFloatExtensionLite, 311F);
message.addExtension(repeatedDoubleExtensionLite, 312D);
message.addExtension(repeatedBoolExtensionLite, false);
message.addExtension(repeatedStringExtensionLite, "315");
message.addExtension(repeatedBytesExtensionLite, toBytes("316"));
message.addExtension(
repeatedGroupExtensionLite, RepeatedGroup_extension_lite.newBuilder().setA(317).build());
message.addExtension(
repeatedNestedMessageExtensionLite,
TestAllTypesLite.NestedMessage.newBuilder().setBb(318).build());
message.addExtension(
repeatedForeignMessageExtensionLite, ForeignMessageLite.newBuilder().setC(319).build());
message.addExtension(
repeatedImportMessageExtensionLite, ImportMessageLite.newBuilder().setD(320).build());
message.addExtension(
repeatedLazyMessageExtensionLite,
TestAllTypesLite.NestedMessage.newBuilder().setBb(327).build());
message.addExtension(repeatedNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ);
message.addExtension(repeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ);
message.addExtension(repeatedImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAZ);
message.addExtension(repeatedStringPieceExtensionLite, "324");
message.addExtension(repeatedCordExtensionLite, "325");
// -----------------------------------------------------------------
message.setExtension(defaultInt32ExtensionLite, 401);
message.setExtension(defaultInt64ExtensionLite, 402L);
message.setExtension(defaultUint32ExtensionLite, 403);
message.setExtension(defaultUint64ExtensionLite, 404L);
message.setExtension(defaultSint32ExtensionLite, 405);
message.setExtension(defaultSint64ExtensionLite, 406L);
message.setExtension(defaultFixed32ExtensionLite, 407);
message.setExtension(defaultFixed64ExtensionLite, 408L);
message.setExtension(defaultSfixed32ExtensionLite, 409);
message.setExtension(defaultSfixed64ExtensionLite, 410L);
message.setExtension(defaultFloatExtensionLite, 411F);
message.setExtension(defaultDoubleExtensionLite, 412D);
message.setExtension(defaultBoolExtensionLite, false);
message.setExtension(defaultStringExtensionLite, "415");
message.setExtension(defaultBytesExtensionLite, toBytes("416"));
message.setExtension(defaultNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.FOO);
message.setExtension(defaultForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_FOO);
message.setExtension(defaultImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_FOO);
message.setExtension(defaultStringPieceExtensionLite, "424");
message.setExtension(defaultCordExtensionLite, "425");
message.setExtension(oneofUint32ExtensionLite, 601);
message.setExtension(
oneofNestedMessageExtensionLite,
TestAllTypesLite.NestedMessage.newBuilder().setBb(602).build());
message.setExtension(oneofStringExtensionLite, "603");
message.setExtension(oneofBytesExtensionLite, toBytes("604"));
}
// -------------------------------------------------------------------
/**
* Modify the repeated extensions of {@code message} to contain the values expected by {@code
* assertRepeatedExtensionsModified()}.
*/
public static void modifyRepeatedExtensions(TestAllExtensionsLite.Builder message) {
message.setExtension(repeatedInt32ExtensionLite, 1, 501);
message.setExtension(repeatedInt64ExtensionLite, 1, 502L);
message.setExtension(repeatedUint32ExtensionLite, 1, 503);
message.setExtension(repeatedUint64ExtensionLite, 1, 504L);
message.setExtension(repeatedSint32ExtensionLite, 1, 505);
message.setExtension(repeatedSint64ExtensionLite, 1, 506L);
message.setExtension(repeatedFixed32ExtensionLite, 1, 507);
message.setExtension(repeatedFixed64ExtensionLite, 1, 508L);
message.setExtension(repeatedSfixed32ExtensionLite, 1, 509);
message.setExtension(repeatedSfixed64ExtensionLite, 1, 510L);
message.setExtension(repeatedFloatExtensionLite, 1, 511F);
message.setExtension(repeatedDoubleExtensionLite, 1, 512D);
message.setExtension(repeatedBoolExtensionLite, 1, true);
message.setExtension(repeatedStringExtensionLite, 1, "515");
message.setExtension(repeatedBytesExtensionLite, 1, toBytes("516"));
message.setExtension(
repeatedGroupExtensionLite, 1, RepeatedGroup_extension_lite.newBuilder().setA(517).build());
message.setExtension(
repeatedNestedMessageExtensionLite,
1,
TestAllTypesLite.NestedMessage.newBuilder().setBb(518).build());
message.setExtension(
repeatedForeignMessageExtensionLite, 1, ForeignMessageLite.newBuilder().setC(519).build());
message.setExtension(
repeatedImportMessageExtensionLite, 1, ImportMessageLite.newBuilder().setD(520).build());
message.setExtension(
repeatedLazyMessageExtensionLite,
1,
TestAllTypesLite.NestedMessage.newBuilder().setBb(527).build());
message.setExtension(repeatedNestedEnumExtensionLite, 1, TestAllTypesLite.NestedEnum.FOO);
message.setExtension(repeatedForeignEnumExtensionLite, 1, ForeignEnumLite.FOREIGN_LITE_FOO);
message.setExtension(repeatedImportEnumExtensionLite, 1, ImportEnumLite.IMPORT_LITE_FOO);
message.setExtension(repeatedStringPieceExtensionLite, 1, "524");
message.setExtension(repeatedCordExtensionLite, 1, "525");
}
public static void setPackedExtensions(TestPackedExtensionsLite.Builder message) {
message.addExtension(packedInt32ExtensionLite, 601);
message.addExtension(packedInt64ExtensionLite, 602L);
message.addExtension(packedUint32ExtensionLite, 603);
message.addExtension(packedUint64ExtensionLite, 604L);
message.addExtension(packedSint32ExtensionLite, 605);
message.addExtension(packedSint64ExtensionLite, 606L);
message.addExtension(packedFixed32ExtensionLite, 607);
message.addExtension(packedFixed64ExtensionLite, 608L);
message.addExtension(packedSfixed32ExtensionLite, 609);
message.addExtension(packedSfixed64ExtensionLite, 610L);
message.addExtension(packedFloatExtensionLite, 611F);
message.addExtension(packedDoubleExtensionLite, 612D);
message.addExtension(packedBoolExtensionLite, true);
message.addExtension(packedEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAR);
// Add a second one of each field.
message.addExtension(packedInt32ExtensionLite, 701);
message.addExtension(packedInt64ExtensionLite, 702L);
message.addExtension(packedUint32ExtensionLite, 703);
message.addExtension(packedUint64ExtensionLite, 704L);
message.addExtension(packedSint32ExtensionLite, 705);
message.addExtension(packedSint64ExtensionLite, 706L);
message.addExtension(packedFixed32ExtensionLite, 707);
message.addExtension(packedFixed64ExtensionLite, 708L);
message.addExtension(packedSfixed32ExtensionLite, 709);
message.addExtension(packedSfixed64ExtensionLite, 710L);
message.addExtension(packedFloatExtensionLite, 711F);
message.addExtension(packedDoubleExtensionLite, 712D);
message.addExtension(packedBoolExtensionLite, false);
message.addExtension(packedEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ);
}
}
| 9,995 |
895 | <filename>source/core/slang-command-line.h
// slang-command-line.h
#ifndef SLANG_COMMAND_LINE_H
#define SLANG_COMMAND_LINE_H
#include "slang-string.h"
#include "slang-list.h"
namespace Slang {
struct ExecutableLocation
{
typedef ExecutableLocation ThisType;
enum Type
{
Unknown, ///< Not specified
Path, ///< The executable is set as a path (ie won't be searched for)
Name, ///< The executable is passed as a name which will be searched for
};
/// Set the executable path.
/// NOTE! On some targets the executable path *must* include an extension to be able to start as a process
void setPath(const String& path) { m_type = Type::Path; m_pathOrName = path; }
/// Set a filename (such that the path will be looked up)
void setName(const String& filename) { m_type = Type::Name; m_pathOrName = filename; }
void set(Type type, const String& pathOrName) { m_type = type; m_pathOrName = pathOrName; }
/// Set the executable path from a base directory and an executable name (no suffix such as '.exe' needed)
void set(const String& dir, const String& name);
/// Determines if it's a name or a path when it sets
void set(const String& nameOrPath);
/// Append as text to out.
void append(StringBuilder& out) const;
/// Reset state to be same as ctor
void reset() { m_type = Type::Unknown; m_pathOrName = String(); }
/// Equality means exactly the same definition.
/// *NOT* that exactly the same executable is specified
bool operator==(const ThisType& rhs) const { return m_type == rhs.m_type && m_pathOrName == rhs.m_pathOrName; }
bool operator!=(const ThisType& rhs) const { return !(*this == rhs); }
ExecutableLocation() {}
ExecutableLocation(const String& dir, const String& name) { set(dir, name); }
ExecutableLocation(Type type, const String& pathOrName) : m_type(type), m_pathOrName(pathOrName) {}
explicit ExecutableLocation(const String& nameOrPath) { set(nameOrPath); }
Type m_type = Type::Unknown;
String m_pathOrName;
};
struct CommandLine
{
typedef CommandLine ThisType;
/// Add args - assumed unescaped
void addArg(const String& in) { m_args.add(in); }
void addArgs(const String* args, Int argsCount) { for (Int i = 0; i < argsCount; ++i) addArg(args[i]); }
/// Find the index of an arg which is exact match for slice
SLANG_INLINE Index findArgIndex(const UnownedStringSlice& slice) const { return m_args.indexOf(slice); }
/// For handling args where the switch is placed directly in front of the path
void addPrefixPathArg(const char* prefix, const String& path, const char* pathPostfix = nullptr);
/// Get the total number of args
SLANG_FORCE_INLINE Index getArgCount() const { return m_args.getCount(); }
/// Reset to the initial state
void reset() { *this = CommandLine(); }
/// Append the args
void appendArgs(StringBuilder& out) const;
/// Append the command line to out
void append(StringBuilder& out) const;
/// convert into a string
String toString() const;
/// Convert just the args to string
String toStringArgs() const;
/// Set an executable location
void setExecutableLocation(const ExecutableLocation& loc) { m_executableLocation = loc; }
ExecutableLocation m_executableLocation; ///< The executable location
List<String> m_args; ///< The arguments (Stored *unescaped*)
};
}
#endif // SLANG_COMMAND_LINE_H
| 1,330 |
852 | #include "CondFormats/HcalObjects/interface/HcalRespCorrs.h"
#include "FWCore/Utilities/interface/typelookup.h"
TYPELOOKUP_DATA_REG(HcalRespCorrs);
| 60 |
335 | <gh_stars>100-1000
/*
Copyright (C) 2020 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file engine/mporcalculator.hpp
\brief The cube valuation calculator interface
\ingroup simulation
*/
#pragma once
#include <orea/engine/valuationcalculator.hpp>
namespace ore {
namespace analytics {
//! MPORCalculator
/*! Calculate NPV for default and close-out time grids
* Implicit assumption that MPOR-style date grid is being used
* Utilises NPVCalculator for actual NPV calculation
*
*/
class MPORCalculator : public ValuationCalculator {
public:
//! base ccy and index to write to
MPORCalculator(const boost::shared_ptr<NPVCalculator>& npvCalc, Size defaultIndex = 0, Size closeOutIndex = 1)
: npvCalc_(npvCalc), defaultIndex_(defaultIndex), closeOutIndex_(closeOutIndex) {}
void calculate(const boost::shared_ptr<Trade>& trade, Size tradeIndex,
const boost::shared_ptr<SimMarket>& simMarket, boost::shared_ptr<NPVCube>& outputCube,
boost::shared_ptr<NPVCube>& outputCubeNettingSet, const Date& date, Size dateIndex, Size sample,
bool isCloseOut = false) override;
void calculateT0(const boost::shared_ptr<Trade>& trade, Size tradeIndex,
const boost::shared_ptr<SimMarket>& simMarket, boost::shared_ptr<NPVCube>& outputCube,
boost::shared_ptr<NPVCube>& outputCubeNettingSet) override;
private:
boost::shared_ptr<NPVCalculator> npvCalc_;
Size defaultIndex_, closeOutIndex_;
};
} // namespace analytics
} // namespace ore
| 742 |
2,151 | // 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.tab;
/**
* A delegate to determine visibility of the browser controls.
*/
public interface BrowserControlsVisibilityDelegate {
/**
* @return Whether browser controls can be shown.
*/
boolean canShowBrowserControls();
/**
* @return Whether browser controls can be auto-hidden
* (e.g. in response to user scroll).
*/
boolean canAutoHideBrowserControls();
}
| 186 |
16,989 | <reponame>jobechoi/bazel<gh_stars>1000+
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.skyframe;
import com.google.common.collect.ImmutableList;
/** A simple {@link Differencer} that is manually informed of invalid/injected nodes. */
public interface RecordingDifferencer extends Differencer, Injectable {
@Override
Diff getDiff(WalkableGraph fromGraph, Version fromVersion, Version toVersion);
/** Stores the given values for invalidation. */
void invalidate(Iterable<SkyKey> values);
/**
* Invalidates the cached values of any values in error transiently.
*
* <p>If a future call to {@link MemoizingEvaluator#evaluate} requests a value that transitively
* depends on any value that was in an error state (or is one of these), they will be re-computed.
*/
default void invalidateTransientErrors() {
// All transient error values have a dependency on the single global ERROR_TRANSIENCE value,
// so we only have to invalidate that one value to catch everything.
invalidate(ImmutableList.of(ErrorTransienceValue.KEY));
}
}
| 462 |
21,684 | // Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_TABLES_TABLE_CONFIG_HPP_
#define CLUSTERING_ADMINISTRATION_TABLES_TABLE_CONFIG_HPP_
#include <memory>
#include <string>
#include <vector>
#include "clustering/administration/servers/config_client.hpp"
#include "clustering/administration/tables/table_common.hpp"
#include "containers/uuid.hpp"
#include "rdb_protocol/artificial_table/backend.hpp"
#include "rpc/semilattice/view.hpp"
class real_reql_cluster_interface_t;
/* This is publicly exposed so that it can be used to create the return value of
`table.reconfigure()`. */
ql::datum_t convert_table_config_to_datum(
namespace_id_t table_id,
const ql::datum_t &db_name_or_uuid,
const table_config_t &config,
admin_identifier_format_t identifier_format,
const server_name_map_t &server_names);
ql::datum_t convert_write_hook_to_datum(
const optional<write_hook_config_t> &write_hook);
class table_config_artificial_table_backend_t :
public common_table_artificial_table_backend_t
{
public:
table_config_artificial_table_backend_t(
rdb_context_t *rdb_context,
lifetime_t<name_resolver_t const &> name_resolver,
std::shared_ptr<semilattice_readwrite_view_t<
cluster_semilattice_metadata_t> > _semilattice_view,
real_reql_cluster_interface_t *_reql_cluster_interface,
admin_identifier_format_t _identifier_format,
server_config_client_t *_server_config_client,
table_meta_client_t *_table_meta_client);
~table_config_artificial_table_backend_t();
bool write_row(
auth::user_context_t const &user_context,
ql::datum_t primary_key,
bool pkey_was_autogenerated,
ql::datum_t *new_value_inout,
signal_t *interruptor_on_caller,
admin_err_t *error_out);
private:
void format_row(
auth::user_context_t const &user_context,
const namespace_id_t &table_id,
const table_config_and_shards_t &config,
const ql::datum_t &db_name_or_uuid,
signal_t *interruptor_on_home,
ql::datum_t *row_out)
THROWS_ONLY(interrupted_exc_t, no_such_table_exc_t, failed_table_op_exc_t);
void do_modify(
const namespace_id_t &table_id,
table_config_and_shards_t &&old_config,
table_config_t &&new_config_no_shards,
server_name_map_t &&new_server_names,
const name_string_t &old_db_name,
const name_string_t &new_db_name,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t, no_such_table_exc_t, failed_table_op_exc_t,
maybe_failed_table_op_exc_t, admin_op_exc_t);
void do_create(
const namespace_id_t &table_id,
table_config_t &&new_config_no_shards,
server_name_map_t &&new_server_names,
const name_string_t &new_db_name,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t, no_such_table_exc_t, failed_table_op_exc_t,
maybe_failed_table_op_exc_t, admin_op_exc_t);
rdb_context_t *rdb_context;
real_reql_cluster_interface_t *reql_cluster_interface;
server_config_client_t *server_config_client;
};
#endif /* CLUSTERING_ADMINISTRATION_TABLES_TABLE_CONFIG_HPP_ */
| 1,555 |
1,060 |
#ifndef __g_undo_h_
#define __g_undo_h_
/*
Infinite undo by <NAME> <<EMAIL>> Dec. 2011
Modified for Pd-vanilla by <NAME> <<EMAIL>> Jun. 2018
This is the home of infinite undo queue. Each root canvas has one of these.
Only canvas that is root will instantiate the pointer to t_undo_action struct.
All sub-canvases (including abstractions) will be linked to the root window.
Once the root window is destroyed, so is its undo queue. Each canvas (t_glist)
defined in g_canvas.h now also has information on t_undo_action queue and a
pointer to the last item in the doubly-linked list (queue).
First initialized undo is never filled (it is of a type 0). First (new) action
creates another t_undo_action and saves its contents there and updates "last"
pointer inside the t_canvas (t_glist).
t_undo_action requires canvas information in case we've deleted a canvas and
then undo its deletion which will in effect change its pointer (memory
location). Then we need to call check_canvas_pointers to update all of the old
(stale) undo actions to corresepond with the new memory location.
What about abstractions? Once they are recreated (e.g. after delete, followed
by an undo) all undo actions (except for its deletion in the parent window should
be purged since abstraction's state will now default to its original (saved) state.
Types of undo data:
0 - init data (start of the queue)
1 - connect
2 - disconnect
3 - cut, clear & typing into objects
4 - motion, including "tidy up" and stretching
5 - paste & duplicate
6 - apply
7 - arrange (to front/back)
8 - canvas apply
9 - create
10 - recreate
11 - change font
12 - meta: start undo sequence (undo sequences are undone/redone atomically)
13 - meta: end undo sequence
14 - internal object state
*/
#include "m_pd.h"
typedef enum
{
UNDO_INIT = 0,
UNDO_CONNECT, /* 1: OK */
UNDO_DISCONNECT, /* 2: OK */
UNDO_CUT, /* 3: OK */
UNDO_MOTION, /* 4: OK */
UNDO_PASTE, /* 5: OK */
UNDO_APPLY, /* 6: how to test? */
UNDO_ARRANGE, /* 7: FIXME: skipped */
UNDO_CANVAS_APPLY, /* 8: OK */
UNDO_CREATE, /* 9: OK */
UNDO_RECREATE, /* 10: OK */
UNDO_FONT, /* 11: OK */
UNDO_SEQUENCE_START, /* 12 start an atomic sequence of undo actions*/
UNDO_SEQUENCE_END, /* 13 end an atomic sequence of undo actions */
UNDO_OBJECT_STATE, /* 14: internal object state: t_atom-list to send to the object */
UNDO_LAST
} t_undo_type;
struct _undo_action
{
t_canvas *x; /* canvas undo is associated with */
t_undo_type type; /* defines what kind of data container it is */
void *data; /* each action will have a different data container */
char *name; /* name of current action */
struct _undo_action *prev; /* previous undo action */
struct _undo_action *next; /* next undo action */
};
#ifndef t_undo_action
#define t_undo_action struct _undo_action
#endif
struct _undo
{
t_undo_action *u_queue;
t_undo_action *u_last;
void *u_cleanstate; /* pointer to non-dirty state */
int u_doing; /* currently undoing */
};
#define t_undo struct _undo
EXTERN t_undo*canvas_undo_get(t_canvas*x);
EXTERN void canvas_undo_cleardirty(t_canvas *x);
EXTERN t_undo_action *canvas_undo_init(t_canvas *x);
EXTERN t_undo_action *canvas_undo_add(t_canvas *x,
t_undo_type type, const char *name, void *data);
EXTERN void canvas_undo_undo(t_canvas *x);
EXTERN void canvas_undo_redo(t_canvas *x);
EXTERN void canvas_undo_rebranch(t_canvas *x);
EXTERN void canvas_undo_check_canvas_pointers(t_canvas *x);
EXTERN void canvas_undo_purge_abstraction_actions(t_canvas *x);
EXTERN void canvas_undo_free(t_canvas *x);
/* --------- 1. connect ---------- */
EXTERN void *canvas_undo_set_connect(t_canvas *x,
int index1, int outno, int index2, int inno);
EXTERN int canvas_undo_connect(t_canvas *x, void *z, int action);
/* --------- 2. disconnect ------- */
EXTERN void *canvas_undo_set_disconnect(t_canvas *x,
int index1, int outno, int index2, int inno);
EXTERN int canvas_undo_disconnect(t_canvas *x, void *z, int action);
/* --------- 3. cut -------------- */
EXTERN void *canvas_undo_set_cut(t_canvas *x,
int mode);
EXTERN int canvas_undo_cut(t_canvas *x, void *z, int action);
/* --------- 4. move ------------- */
EXTERN void *canvas_undo_set_move(t_canvas *x, int selected);
EXTERN int canvas_undo_move(t_canvas *x, void *z, int action);
/* --------- 5. paste ------------ */
EXTERN void *canvas_undo_set_paste(t_canvas *x,
int offset, int duplicate, int d_offset);
EXTERN int canvas_undo_paste(t_canvas *x, void *z, int action);
/* --------- 6. apply ------------ */
EXTERN void *canvas_undo_set_apply(t_canvas *x,
int n);
EXTERN int canvas_undo_apply(t_canvas *x, void *z, int action);
/* --------- 7. arrange ---------- */
EXTERN void *canvas_undo_set_arrange(t_canvas *x,
t_gobj *obj, int newindex);
EXTERN int canvas_undo_arrange(t_canvas *x, void *z, int action);
/* --------- 8. canvas apply ----- */
EXTERN void *canvas_undo_set_canvas(t_canvas *x);
EXTERN int canvas_undo_canvas_apply(t_canvas *x, void *z, int action);
/* --------- 9. create ----------- */
EXTERN void *canvas_undo_set_create(t_canvas *x);
EXTERN int canvas_undo_create(t_canvas *x, void *z, int action);
/* --------- 10. recreate -------- */
EXTERN void *canvas_undo_set_recreate(t_canvas *x,
t_gobj *y, int old_pos);
EXTERN int canvas_undo_recreate(t_canvas *x, void *z, int action);
/* --------- 11. font ------------ */
EXTERN void *canvas_undo_set_font(t_canvas *x,
int font, t_float realresize, int whichresize);
EXTERN int canvas_undo_font(t_canvas *x, void *z, int action);
/* ------------------------------- */
#endif /* __g_undo_h_ */
| 2,081 |
1,127 | <filename>src/common/transformations/src/ngraph_ops/multiclass_nms_ie_internal.cpp
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ngraph_ops/multiclass_nms_ie_internal.hpp"
#include "../../core/shape_inference/include/multiclass_nms_shape_inference.hpp"
#include "itt.hpp"
using namespace std;
using namespace ngraph;
BWDCMP_RTTI_DEFINITION(op::internal::MulticlassNmsIEInternal);
op::internal::MulticlassNmsIEInternal::MulticlassNmsIEInternal(const Output<Node>& boxes,
const Output<Node>& scores,
const op::util::MulticlassNmsBase::Attributes& attrs)
: opset9::MulticlassNms(boxes, scores, attrs) {
constructor_validate_and_infer_types();
}
op::internal::MulticlassNmsIEInternal::MulticlassNmsIEInternal(const Output<Node>& boxes,
const Output<Node>& scores,
const Output<Node>& roisnum,
const op::util::MulticlassNmsBase::Attributes& attrs)
: opset9::MulticlassNms(boxes, scores, roisnum, attrs) {
constructor_validate_and_infer_types();
}
std::shared_ptr<Node> op::internal::MulticlassNmsIEInternal::clone_with_new_inputs(const OutputVector& new_args) const {
INTERNAL_OP_SCOPE(internal_MulticlassNmsIEInternal_clone_with_new_inputs);
if (new_args.size() == 3) {
return std::make_shared<MulticlassNmsIEInternal>(new_args.at(0), new_args.at(1), new_args.at(2), m_attrs);
} else if (new_args.size() == 2) {
return std::make_shared<MulticlassNmsIEInternal>(new_args.at(0), new_args.at(1), m_attrs);
}
throw ngraph::ngraph_error("Unsupported number of inputs: " + std::to_string(new_args.size()));
}
void op::internal::MulticlassNmsIEInternal::validate_and_infer_types() {
INTERNAL_OP_SCOPE(internal_MulticlassNmsIEInternal_validate_and_infer_types);
const auto output_type = get_attrs().output_type;
validate();
const auto& boxes_ps = get_input_partial_shape(0);
const auto& scores_ps = get_input_partial_shape(1);
std::vector<PartialShape> input_shapes = {boxes_ps, scores_ps};
if (get_input_size() == 3) {
const auto& roisnum_ps = get_input_partial_shape(2);
input_shapes.push_back(roisnum_ps);
}
std::vector<PartialShape> output_shapes = {{Dimension::dynamic(), 6},
{Dimension::dynamic(), 1},
{Dimension::dynamic()}};
shape_infer(this, input_shapes, output_shapes, true, true);
set_output_type(0, get_input_element_type(0), output_shapes[0]);
set_output_type(1, output_type, output_shapes[1]);
set_output_type(2, output_type, output_shapes[2]);
} | 1,387 |
770 | <gh_stars>100-1000
#include "tommath_private.h"
#ifdef BN_MP_GET_LL_C
/* LibTomMath, multiple-precision integer library -- <NAME> */
/* SPDX-License-Identifier: Unlicense */
MP_GET_SIGNED(mp_get_ll, mp_get_mag_ull, long long, unsigned long long)
#endif
| 98 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-3wh5-4rmj-5jxh",
"modified": "2022-05-02T03:36:56Z",
"published": "2022-05-02T03:36:56Z",
"aliases": [
"CVE-2009-2602"
],
"details": "R2 Newsletter Lite, Pro, and Stats stores sensitive information under the web root with insufficient access control, which allows remote attackers to download the database file via a direct request for admin.mdb.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2009-2602"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/35312"
},
{
"type": "WEB",
"url": "http://www.exploit-db.com/exploits/8849"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 382 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <objc/objc.h>
#include <QObject>
class QWindow;
namespace Editor
{
class WindowObserver
: public QObject
{
Q_OBJECT
public:
explicit WindowObserver(QWindow* window, QObject* parent);
virtual ~WindowObserver();
public slots:
void setWindowIsMoving(bool isMoving);
void setWindowIsResizing(bool isResizing);
signals:
void windowIsMovingOrResizingChanged(bool isMovingOrResizing);
private:
bool m_windowIsMoving;
bool m_windowIsResizing;
id m_windowObserver;
};
} // namespace editor
| 391 |
1,338 | <gh_stars>1000+
/*------------------------------------------------------------------------
Junction: Concurrent data structures in C++
Copyright (c) 2016 <NAME>
Distributed under the Simplified BSD License.
Original location: https://github.com/preshing/junction
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the LICENSE file for more information.
------------------------------------------------------------------------*/
#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_STDMAP_H
#define JUNCTION_EXTRA_IMPL_MAPADAPTER_STDMAP_H
#include <junction/Core.h>
#include <map>
#include <mutex>
namespace junction {
namespace extra {
class MapAdapter {
public:
static TURF_CONSTEXPR const char* getMapName() { return "std::map + std::mutex"; }
MapAdapter(ureg) {
}
class ThreadContext {
public:
ThreadContext(MapAdapter&, ureg) {
}
void registerThread() {
}
void unregisterThread() {
}
void update() {
}
};
class Map {
private:
std::mutex m_mutex;
typedef std::map<u32, void*> MapType;
MapType m_map;
public:
Map(ureg) {
}
void assign(u32 key, void* value) {
std::lock_guard<std::mutex> guard(m_mutex);
m_map[key] = value;
}
void* get(u32 key) {
std::lock_guard<std::mutex> guard(m_mutex);
MapType::iterator iter = m_map.find(key);
return (iter == m_map.end()) ? NULL : iter->second;
}
void erase(u32 key) {
std::lock_guard<std::mutex> guard(m_mutex);
m_map.erase(key);
}
class Iterator {
private:
Map& m_map;
MapType::iterator m_iter;
public:
Iterator(Map& map) : m_map(map), m_iter(m_map.m_map.begin()) {
}
void next() {
m_iter++;
}
bool isValid() const {
return m_iter != m_map.m_map.end();
}
u32 getKey() const {
return m_iter->first;
}
void* getValue() const {
return m_iter->second;
}
};
};
static ureg getInitialCapacity(ureg) {
return 0;
}
};
} // namespace extra
} // namespace junction
#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_STDMAP_H
| 1,159 |
419 | """
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLE - WINDOW RESIZE
Resize the menu when the window is resized.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2021 <NAME>. @ppizarror
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
"""
import pygame
import pygame_menu
pygame.init()
surface = pygame.display.set_mode((600, 400), pygame.RESIZABLE)
pygame.display.set_caption("Example resizable window")
menu = pygame_menu.Menu(
height=100,
theme=pygame_menu.themes.THEME_BLUE,
title='Welcome',
width=100
)
def on_resize() -> None:
"""
Function checked if the window is resized.
"""
window_size = surface.get_size()
new_w, new_h = 0.75 * window_size[0], 0.7 * window_size[1]
menu.resize(new_w, new_h)
print(f'New menu size: {menu.get_size()}')
menu.add.label('Resize the window!')
user_name = menu.add.text_input('Name: ', default='<NAME>', maxchar=10)
menu.add.selector('Difficulty: ', [('Hard', 1), ('Easy', 2)])
menu.add.button('Quit', pygame_menu.events.EXIT)
menu.enable()
on_resize() # Set initial size
if __name__ == '__main__':
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
break
if event.type == pygame.VIDEORESIZE:
# Update the surface
surface = pygame.display.set_mode((event.w, event.h),
pygame.RESIZABLE)
# Call the menu event
on_resize()
# Draw the menu
surface.fill((25, 0, 50))
menu.update(events)
menu.draw(surface)
pygame.display.flip()
| 1,032 |
335 | {
"word": "King",
"definitions": [
"A male ruler of an independent state",
"A male ruler who inherited his position by right of birth"
],
"parts-of-speech": "Noun"
} | 80 |
13,162 | #pragma once
#include <regex>
#include <fc/filesystem.hpp>
#include <fc/io/json.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/abi_def.hpp>
namespace eosio::trace_api::configuration_utils {
using namespace eosio;
/**
* Given a path (absolute or relative) to a file that contains a JSON-encoded ABI, return the parsed ABI
*
* @param file_name - a path to the ABI
* @param data_dir - the base path for relative file_name values
* @return the ABI implied
* @throws json_parse_exception if the JSON is malformed
*/
chain::abi_def abi_def_from_file(const std::string& file_name, const fc::path& data_dir )
{
fc::variant abi_variant;
auto abi_path = fc::path(file_name);
if (abi_path.is_relative()) {
abi_path = data_dir / abi_path;
}
EOS_ASSERT(fc::exists(abi_path) && !fc::is_directory(abi_path), chain::plugin_config_exception, "${path} does not exist or is not a file", ("path", abi_path.generic_string()));
try {
abi_variant = fc::json::from_file(abi_path);
} EOS_RETHROW_EXCEPTIONS(chain::json_parse_exception, "Fail to parse JSON from file: ${file}", ("file", abi_path.generic_string()));
chain::abi_def result;
fc::from_variant(abi_variant, result);
return result;
}
/**
* Given a string in the form <key>=<value> where key cannot contain an `=` character and value can contain anything
* return a pair of the two independent strings
*
* @param input
* @return
*/
std::pair<std::string, std::string> parse_kv_pairs( const std::string& input ) {
EOS_ASSERT(!input.empty(), chain::plugin_config_exception, "Key-Value Pair is Empty");
auto delim = input.find("=");
EOS_ASSERT(delim != std::string::npos, chain::plugin_config_exception, "Missing \"=\"");
EOS_ASSERT(delim != 0, chain::plugin_config_exception, "Missing Key");
EOS_ASSERT(delim + 1 != input.size(), chain::plugin_config_exception, "Missing Value");
return std::make_pair(input.substr(0, delim), input.substr(delim + 1));
}
} | 832 |
892 | <gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-2cwf-mxq6-x2pg",
"modified": "2022-05-01T07:13:46Z",
"published": "2022-05-01T07:13:46Z",
"aliases": [
"CVE-2006-3939"
],
"details": "ScriptsCenter ezUpload Pro 2.2.0 allows remote attackers to perform administrative activities without authentication in (1) filter.php, which permits changing the Extensions Mode file type; (2) access.php, which permits changing the Protection Method; (3) edituser.php, which permits adding upload capabilities to user accounts; (4) settings.php, which permits changing the admin information; and (5) index.php, which permits uploading of arbitrary files.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2006-3939"
},
{
"type": "WEB",
"url": "http://securityreason.com/securityalert/1305"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/archive/1/441172/100/0/threaded"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/19175"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
} | 500 |
640 | <reponame>jpoikela/z88dk<filename>include/_DEVELOPMENT/sccz80/arch/sms.h
// automatically generated by m4 from headers in proto subdir
#ifndef __ARCH_SMS_H__
#define __ARCH_SMS_H__
#include <arch.h>
#include <rect.h>
// GLOBAL VARIABLES
extern unsigned char GLOBAL_SMS_VDP_R0;
extern unsigned char GLOBAL_SMS_VDP_R1;
extern unsigned int GLOBAL_SMS_VRAM_SCREEN_MAP_ADDRESS;
extern unsigned int GLOBAL_SMS_VRAM_SPRITE_ATTRIBUTE_TABLE_ADDRESS;
extern unsigned int GLOBAL_SMS_VRAM_SPRITE_PATTERN_BASE_ADDRESS;
// IO MAPPED REGISTERS
#ifdef __CLANG
extern unsigned char IO_MEMORY_ENABLES;
extern unsigned char IO_JOYSTICK_PORT_CONTROL;
extern unsigned char IO_GUN_SPOT_VERTICAL;
extern unsigned char IO_GUN_SPOT_HORIZONTAL;
extern unsigned char IO_PSG;
extern unsigned char IO_VDP_DATA;
extern unsigned char IO_VDP_COMMAND;
extern unsigned char IO_VDP_STATUS;
extern unsigned char IO_JOYSTICK_READ_L;
extern unsigned char IO_JOYSTICK_READ_H;
extern unsigned char IO_3E;
extern unsigned char IO_3F;
extern unsigned char IO_7E;
extern unsigned char IO_7F;
extern unsigned char IO_BE;
extern unsigned char IO_BF;
extern unsigned char IO_DC;
extern unsigned char IO_DD;
#else
__sfr __at __IO_MEMORY_ENABLES IO_MEMORY_ENABLES;
__sfr __at __IO_JOYSTICK_PORT_CONTROL IO_JOYSTICK_PORT_CONTROL;
__sfr __at __IO_GUN_SPOT_VERTICAL IO_GUN_SPOT_VERTICAL;
__sfr __at __IO_GUN_SPOT_HORIZONTAL IO_GUN_SPOT_HORIZONTAL;
__sfr __at __IO_PSG IO_PSG;
__sfr __at __IO_VDP_DATA IO_VDP_DATA;
__sfr __at __IO_VDP_COMMAND IO_VDP_CONTROL; // same port
__sfr __at __IO_VDP_COMMAND IO_VDP_COMMAND; // same port
__sfr __at __IO_VDP_STATUS IO_VDP_STATUS; // same port
__sfr __at __IO_JOYSTICK_READ_L IO_JOYSTICK_READ_L;
__sfr __at __IO_JOYSTICK_READ_H IO_JOYSTICK_READ_H;
__sfr __at 0x3e IO_3E;
__sfr __at 0x3f IO_3F;
__sfr __at 0x7e IO_7E;
__sfr __at 0x7f IO_7F;
__sfr __at 0xbe IO_BE;
__sfr __at 0xbf IO_BF;
__sfr __at 0xdc IO_DC;
__sfr __at 0xdd IO_DD;
#endif
// MEMORY MAPPED REGISTERS
extern volatile unsigned char MM_FRAME2_CONTROL_REGISTER;
extern volatile unsigned char MM_FRAME1_CONTROL_REGISTER;
extern volatile unsigned char MM_FRAME0_CONTROL_REGISTER;
extern volatile unsigned char MM_FRAME2_RAM_CONTROL_REGISTER;
extern volatile unsigned char MM_FFFF;
extern volatile unsigned char MM_FFFE;
extern volatile unsigned char MM_FFFD;
extern volatile unsigned char MM_FFFC;
// VRAM ADDRESS ASSIGNMENT
#define SMS_VRAM_SCREEN_MAP_ADDRESS __SMS_VRAM_SCREEN_MAP_ADDRESS
#define SMS_VRAM_SPRITE_ATTRIBUTE_TABLE_ADDRESS __SMS_VRAM_SPRITE_ATTRIBUTE_TABLE_ADDRESS
#define SMS_VRAM_SPRITE_PATTERN_BASE_ADDRESS __SMS_VRAM_SPRITE_PATTERN_BASE_ADDRESS
// MISCELLANEOUS
extern void __LIB__ sms_border(unsigned char color) __smallc __z88dk_fastcall;
extern unsigned int __LIB__ sms_cxy2saddr(unsigned char x,unsigned char y) __smallc;
extern unsigned int __LIB__ sms_cxy2saddr_callee(unsigned char x,unsigned char y) __smallc __z88dk_callee;
#define sms_cxy2saddr(a,b) sms_cxy2saddr_callee(a,b)
extern void __LIB__ *sms_copy_font_8x8_to_vram(void *font,unsigned char num,unsigned char bgnd_color,unsigned char fgnd_color) __smallc;
extern void __LIB__ *sms_copy_font_8x8_to_vram_callee(void *font,unsigned char num,unsigned char bgnd_color,unsigned char fgnd_color) __smallc __z88dk_callee;
#define sms_copy_font_8x8_to_vram(a,b,c,d) sms_copy_font_8x8_to_vram_callee(a,b,c,d)
extern void __LIB__ sms_cls_wc(struct r_Rect8 *r,unsigned int background_char) __smallc;
extern void __LIB__ sms_cls_wc_callee(struct r_Rect8 *r,unsigned int background_char) __smallc __z88dk_callee;
#define sms_cls_wc(a,b) sms_cls_wc_callee(a,b)
extern void __LIB__ sms_scroll_wc_up(struct r_Rect8 *r,unsigned char rows,unsigned int background_char) __smallc;
extern void __LIB__ sms_scroll_wc_up_callee(struct r_Rect8 *r,unsigned char rows,unsigned int background_char) __smallc __z88dk_callee;
#define sms_scroll_wc_up(a,b,c) sms_scroll_wc_up_callee(a,b,c)
extern void __LIB__ sms_tiles_clear_area(struct r_Rect8 *r,unsigned int background_char) __smallc;
extern void __LIB__ sms_tiles_clear_area_callee(struct r_Rect8 *r,unsigned int background_char) __smallc __z88dk_callee;
#define sms_tiles_clear_area(a,b) sms_tiles_clear_area_callee(a,b)
extern void __LIB__ sms_tiles_get_area(struct r_Rect8 *r,void *dst) __smallc;
extern void __LIB__ sms_tiles_get_area_callee(struct r_Rect8 *r,void *dst) __smallc __z88dk_callee;
#define sms_tiles_get_area(a,b) sms_tiles_get_area_callee(a,b)
extern void __LIB__ sms_tiles_put_area(struct r_Rect8 *r,void *src) __smallc;
extern void __LIB__ sms_tiles_put_area_callee(struct r_Rect8 *r,void *src) __smallc __z88dk_callee;
#define sms_tiles_put_area(a,b) sms_tiles_put_area_callee(a,b)
// VDP
#define VDP_FEATURE_SHIFT_SPRITES __VDP_FEATURE_SHIFT_SPRITES
#define VDP_FEATURE_LINE_INTERRUPT __VDP_FEATURE_LINE_INTERRUPT
#define VDP_FEATURE_LEFT_COLUMN_BLANK __VDP_FEATURE_LEFT_COLUMN_BLANK
#define VDP_FEATURE_HSCROLL_INHIBIT __VDP_FEATURE_HSCROLL_INHIBIT
#define VDP_FEATURE_VSCROLL_INHIBIT __VDP_FEATURE_VSCROLL_INHIBIT
#define VDP_FEATURE_WIDE_SPRITES __VDP_FEATURE_WIDE_SPRITES
#define VDP_FEATURE_VBLANK_INTERRUPT __VDP_FEATURE_VBLANK_INTERRUPT
#define VDP_FEATURE_SHOW_DISPLAY __VDP_FEATURE_SHOW_DISPLAY
#define sms_display_off() sms_vdp_feature_disable(__VDP_FEATURE_SHOW_DISPLAY)
#define sms_display_on() sms_vdp_feature_enable(__VDP_FEATURE_SHOW_DISPLAY)
extern unsigned int __LIB__ sms_vdp_feature_disable(unsigned int features) __smallc __z88dk_fastcall;
extern unsigned int __LIB__ sms_vdp_feature_enable(unsigned int features) __smallc __z88dk_fastcall;
extern void __LIB__ sms_vdp_init(void *vdp_reg_array) __smallc __z88dk_fastcall;
extern void __LIB__ sms_vdp_set_read_address(unsigned int addr) __smallc __z88dk_fastcall;
extern void __LIB__ sms_vdp_set_write_address(unsigned int addr) __smallc __z88dk_fastcall;
// VRAM <-> MEMORY COPY OPERATIONS
extern void __LIB__ sms_copy_mem_to_vram(void *src,unsigned int n) __smallc;
extern void __LIB__ sms_copy_mem_to_vram_callee(void *src,unsigned int n) __smallc __z88dk_callee;
#define sms_copy_mem_to_vram(a,b) sms_copy_mem_to_vram_callee(a,b)
extern void __LIB__ sms_copy_mem_to_vram_unsafe(void *src,unsigned int n) __smallc;
extern void __LIB__ sms_copy_mem_to_vram_unsafe_callee(void *src,unsigned int n) __smallc __z88dk_callee;
#define sms_copy_mem_to_vram_unsafe(a,b) sms_copy_mem_to_vram_unsafe_callee(a,b)
extern void __LIB__ sms_copy_vram_to_mem(void *dst,unsigned int n) __smallc;
extern void __LIB__ sms_copy_vram_to_mem_callee(void *dst,unsigned int n) __smallc __z88dk_callee;
#define sms_copy_vram_to_mem(a,b) sms_copy_vram_to_mem_callee(a,b)
extern void __LIB__ sms_copy_vram_to_mem_unsafe(void *dst,unsigned int n) __smallc;
extern void __LIB__ sms_copy_vram_to_mem_unsafe_callee(void *dst,unsigned int n) __smallc __z88dk_callee;
#define sms_copy_vram_to_mem_unsafe(a,b) sms_copy_vram_to_mem_unsafe_callee(a,b)
extern void __LIB__ sms_set_vram(unsigned char c,unsigned int n) __smallc;
extern void __LIB__ sms_set_vram_callee(unsigned char c,unsigned int n) __smallc __z88dk_callee;
#define sms_set_vram(a,b) sms_set_vram_callee(a,b)
extern void __LIB__ sms_set_vram_unsafe(unsigned char c,unsigned int n) __smallc;
extern void __LIB__ sms_set_vram_unsafe_callee(unsigned char c,unsigned int n) __smallc __z88dk_callee;
#define sms_set_vram_unsafe(a,b) sms_set_vram_unsafe_callee(a,b)
extern void __LIB__ sms_setw_vram(unsigned int c,unsigned int n) __smallc;
extern void __LIB__ sms_setw_vram_callee(unsigned int c,unsigned int n) __smallc __z88dk_callee;
#define sms_setw_vram(a,b) sms_setw_vram_callee(a,b)
extern void __LIB__ sms_setw_vram_unsafe(unsigned int c,unsigned int n) __smallc;
extern void __LIB__ sms_setw_vram_unsafe_callee(unsigned int c,unsigned int n) __smallc __z88dk_callee;
#define sms_setw_vram_unsafe(a,b) sms_setw_vram_unsafe_callee(a,b)
extern unsigned int __LIB__ sms_memcpy_mem_to_cram(unsigned int cdst,void *src,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memcpy_mem_to_cram_callee(unsigned int cdst,void *src,unsigned int n) __smallc __z88dk_callee;
#define sms_memcpy_mem_to_cram(a,b,c) sms_memcpy_mem_to_cram_callee(a,b,c)
extern unsigned int __LIB__ sms_memcpy_mem_to_cram_unsafe(unsigned int cdst,void *src,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memcpy_mem_to_cram_unsafe_callee(unsigned int cdst,void *src,unsigned int n) __smallc __z88dk_callee;
#define sms_memcpy_mem_to_cram_unsafe(a,b,c) sms_memcpy_mem_to_cram_unsafe_callee(a,b,c)
extern unsigned int __LIB__ sms_memcpy_mem_to_vram(unsigned int dst,void *src,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memcpy_mem_to_vram_callee(unsigned int dst,void *src,unsigned int n) __smallc __z88dk_callee;
#define sms_memcpy_mem_to_vram(a,b,c) sms_memcpy_mem_to_vram_callee(a,b,c)
extern unsigned int __LIB__ sms_memcpy_mem_to_vram_unsafe(unsigned int dst,void *src,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memcpy_mem_to_vram_unsafe_callee(unsigned int dst,void *src,unsigned int n) __smallc __z88dk_callee;
#define sms_memcpy_mem_to_vram_unsafe(a,b,c) sms_memcpy_mem_to_vram_unsafe_callee(a,b,c)
extern unsigned int __LIB__ sms_memcpy_vram_to_mem(void *dst,unsigned int src,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memcpy_vram_to_mem_callee(void *dst,unsigned int src,unsigned int n) __smallc __z88dk_callee;
#define sms_memcpy_vram_to_mem(a,b,c) sms_memcpy_vram_to_mem_callee(a,b,c)
extern unsigned int __LIB__ sms_memcpy_vram_to_mem_unsafe(void *dst,unsigned int src,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memcpy_vram_to_mem_unsafe_callee(void *dst,unsigned int src,unsigned int n) __smallc __z88dk_callee;
#define sms_memcpy_vram_to_mem_unsafe(a,b,c) sms_memcpy_vram_to_mem_unsafe_callee(a,b,c)
extern unsigned int __LIB__ sms_memcpy_vram_to_vram(unsigned int dst,unsigned int src,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memcpy_vram_to_vram_callee(unsigned int dst,unsigned int src,unsigned int n) __smallc __z88dk_callee;
#define sms_memcpy_vram_to_vram(a,b,c) sms_memcpy_vram_to_vram_callee(a,b,c)
extern unsigned int __LIB__ sms_memcpy_vram_to_vram_unsafe(unsigned int dst,unsigned int src,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memcpy_vram_to_vram_unsafe_callee(unsigned int dst,unsigned int src,unsigned int n) __smallc __z88dk_callee;
#define sms_memcpy_vram_to_vram_unsafe(a,b,c) sms_memcpy_vram_to_vram_unsafe_callee(a,b,c)
extern unsigned int __LIB__ sms_memset_vram(unsigned int dst,unsigned char c,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memset_vram_callee(unsigned int dst,unsigned char c,unsigned int n) __smallc __z88dk_callee;
#define sms_memset_vram(a,b,c) sms_memset_vram_callee(a,b,c)
extern unsigned int __LIB__ sms_memset_vram_unsafe(unsigned int dst,unsigned char c,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memset_vram_unsafe_callee(unsigned int dst,unsigned char c,unsigned int n) __smallc __z88dk_callee;
#define sms_memset_vram_unsafe(a,b,c) sms_memset_vram_unsafe_callee(a,b,c)
extern unsigned int __LIB__ sms_memsetw_vram(unsigned int dst,unsigned int c,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memsetw_vram_callee(unsigned int dst,unsigned int c,unsigned int n) __smallc __z88dk_callee;
#define sms_memsetw_vram(a,b,c) sms_memsetw_vram_callee(a,b,c)
extern unsigned int __LIB__ sms_memsetw_vram_unsafe(unsigned int dst,unsigned int c,unsigned int n) __smallc;
extern unsigned int __LIB__ sms_memsetw_vram_unsafe_callee(unsigned int dst,unsigned int c,unsigned int n) __smallc __z88dk_callee;
#define sms_memsetw_vram_unsafe(a,b,c) sms_memsetw_vram_unsafe_callee(a,b,c)
#endif
| 5,291 |
387 | <filename>src/classes/java/io/InputStreamReader.java
/*
* Copyright (C) 2014, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The Java Pathfinder core (jpf-core) platform is 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 java.io;
/**
* how hard can it be to transform byte(s) into a char? I hate Unicode
*/
public class InputStreamReader extends Reader {
static final int BUF_SIZE=128;
private static Object lock = new Object(); // our peer has state
InputStream in;
byte[] bbuf = new byte[BUF_SIZE];
String charSetName=null;
public InputStreamReader (InputStream in){
this.in = in;
}
public InputStreamReader (InputStream in,String charSetName){
this.in = in;
this.charSetName = charSetName;
}
@Override
public void close () throws IOException {
in.close();
}
private native int decode (int b, boolean endOfInput);
@Override
public boolean ready() {
try {
return (in.available() > 0);
} catch (IOException iox){
return false;
}
}
@Override
public int read () throws IOException {
synchronized (lock){
while (true){
int b = in.read();
if (b < 0){
return -1;
}
int c = decode(b, (in.available() == 0));
if (c >= 0 ) {
return c;
}
}
}
}
native int decode (byte[] inBuf,int len,
char[] outBuf, int off,
boolean endOfInput);
@Override
public int read (char[] cbuf, int off, int len) throws IOException {
int r = 0;
boolean available = true;
synchronized (lock){
while (available && r < len){
// <2do> - so what if that backtracks? the peer might have
// iteration-specific state that gets lost. see native peer comments
int b = in.read(bbuf, 0, Math.min(len-r,bbuf.length));
if (b < 0){
return (r == 0) ? -1 : r;
}
// true if we have not reach the end of the input stream "in"
// and there are still more bytes available to be read
available = (in.available() > 0);
r += decode(bbuf,b, cbuf,off+r, !available);
}
}
return r;
}
}
| 1,108 |
2,858 | <gh_stars>1000+
"""
Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the MIT-style license found in the
LICENSE file in the root directory of this source tree.
"""
import argparse
import arrayfire as af
import glob
import numpy as np
import os
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
def convert_to_xywh(boxes):
xmin, ymin, xmax, ymax = np.split(boxes, 4, axis=1)
result = np.concatenate([xmin, ymin, xmax - xmin, ymax - ymin], axis=1);
return result
def softmax(x, axis=0):
"""Compute softmax values for each sets of scores in x."""
max_value = np.max(x, axis=axis, keepdims=True);
e_x = np.exp(x - max_value)
s = np.sum(e_x, axis=axis, keepdims=True)
return e_x / s
def cxcywh_to_xyxy(x):
x_c, y_c, w, h = np.split(x, 4, 2)
b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
(x_c + 0.5 * w), (y_c + 0.5 * h)]
return np.concatenate(b, axis=2)
def postprocess_fn(out_logits, out_bbox, target_sizes):
assert len(out_logits) == len(target_sizes)
assert target_sizes.shape[1] == 2
prob = softmax(out_logits, 2)
labels = np.argmax(prob[..., :-1], axis=2);
scores = np.amax(prob[..., :-1], axis=2)
boxes = cxcywh_to_xyxy(out_bbox)
img_h, img_w = np.split(target_sizes, 2, axis=1)
scale_fct = np.concatenate([img_w, img_h, img_w, img_h], axis=1);
boxes = boxes * scale_fct[:, None, :]
results = [{'scores': s, 'labels': l, 'boxes': b} for s, l, b in zip(scores, labels, boxes)]
return results;
def prepare_for_coco_detection(predictions):
coco_results = []
for original_id, prediction in predictions.items():
if len(prediction) == 0:
continue
boxes = prediction["boxes"]
boxes = convert_to_xywh(boxes).tolist()
scores = prediction["scores"].tolist()
labels = prediction["labels"].tolist()
coco_results.extend(
[
{
"image_id": original_id,
"category_id": labels[k],
"bbox": box,
"score": scores[k],
}
for k, box in enumerate(boxes)
]
)
return coco_results
def main(directory, coco_data):
data_type='val2017'
ann_file='{}/annotations/instances_{}.json'.format(coco_data, data_type)
coco=COCO(ann_file)
all_results = []
all_image_ids = []
glob_path = os.path.join(directory, '**', 'detection*.array')
files = glob.glob(glob_path)
assert(len(files) > 0)
for f in files:
image_sizes = af.read_array(f, key='imageSizes').to_ndarray()
image_sizes = np.transpose(image_sizes, (1, 0))
image_ids = af.read_array(f, key='imageIds').to_ndarray()
scores = af.read_array(f, key='scores').to_ndarray()
scores = np.transpose(scores, (2, 1, 0))
bboxes = af.read_array(f, key='bboxes').to_ndarray()
bboxes = np.transpose(bboxes, (2, 1, 0))
results = postprocess_fn(scores, bboxes, image_sizes)
res = { id : output for id, output in zip(image_ids, results) };
results = prepare_for_coco_detection(res)
image_ids = [ id for id in image_ids ];
all_results.extend(results)
all_image_ids.extend(image_ids)
coco_dt = coco.loadRes(all_results)
coco_eval = COCOeval(coco, coco_dt, 'bbox')
coco_eval.params.imgIds = all_image_ids
coco_eval.evaluate()
coco_eval.accumulate()
coco_eval.summarize()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--dir', default='/private/home/padentomasello/data/coco/output/')
parser.add_argument('--coco', default='/datasets01/COCO/022719/')
args = parser.parse_args()
main(args.dir, args.coco)
| 1,859 |
679 | <reponame>Grosskopf/openoffice<gh_stars>100-1000
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "MediaDescriptorHelper.hxx"
using namespace ::com::sun::star;
namespace apphelper
{
const short FLAG_DEPRECATED =1;
const short FLAG_MODEL =2;
#define WRITE_PROPERTY( MediaName, nFlags ) \
if(rProp.Name.equals(::rtl::OUString::createFromAscii(#MediaName))) \
{ \
if( rProp.Value >>= MediaName ) \
ISSET_##MediaName = sal_True; \
if(nFlags & FLAG_DEPRECATED) \
{ \
m_aDeprecatedProperties[nDeprecatedCount]=rProp;\
nDeprecatedCount++; \
} \
else \
{ \
m_aRegularProperties[nRegularCount]=rProp; \
nRegularCount++; \
if( nFlags & FLAG_MODEL) \
{ \
m_aModelProperties[nModelCount]=rProp; \
nModelCount++; \
} \
} \
}
MediaDescriptorHelper::MediaDescriptorHelper( const uno::Sequence<
beans::PropertyValue > & rMediaDescriptor )
{
impl_init();
m_aRegularProperties.realloc(0);
m_aRegularProperties.realloc(rMediaDescriptor.getLength());
sal_Int32 nRegularCount = 0;
m_aDeprecatedProperties.realloc(0);
m_aDeprecatedProperties.realloc(rMediaDescriptor.getLength());
sal_Int32 nDeprecatedCount = 0;
m_aAdditionalProperties.realloc(0);
m_aAdditionalProperties.realloc(rMediaDescriptor.getLength());
sal_Int32 nAdditionalCount = 0;
m_aModelProperties.realloc(0);
m_aModelProperties.realloc(rMediaDescriptor.getLength());
sal_Int32 nModelCount = 0;
//read given rMediaDescriptor and store in internal structures:
for( sal_Int32 i= rMediaDescriptor.getLength();i--;)
{
const beans::PropertyValue& rProp = rMediaDescriptor[i];
WRITE_PROPERTY( AsTemplate, FLAG_MODEL )
else WRITE_PROPERTY( Author, FLAG_MODEL )
else WRITE_PROPERTY( CharacterSet, FLAG_MODEL )
else WRITE_PROPERTY( Comment, FLAG_MODEL )
else WRITE_PROPERTY( ComponentData, FLAG_MODEL )
else WRITE_PROPERTY( FileName, FLAG_DEPRECATED )
else WRITE_PROPERTY( FilterData, FLAG_MODEL )
else WRITE_PROPERTY( FilterName, FLAG_MODEL )
else WRITE_PROPERTY( FilterFlags, FLAG_DEPRECATED)
else WRITE_PROPERTY( FilterOptions, FLAG_MODEL )
else WRITE_PROPERTY( FrameName, FLAG_MODEL )
else WRITE_PROPERTY( Hidden, FLAG_MODEL )
else WRITE_PROPERTY( HierarchicalDocumentName, FLAG_MODEL )
else WRITE_PROPERTY( OutputStream, 0 )
else WRITE_PROPERTY( InputStream, 0 )
else WRITE_PROPERTY( InteractionHandler, 0 )
else WRITE_PROPERTY( JumpMark, 0 )
else WRITE_PROPERTY( MediaType, FLAG_MODEL )
else WRITE_PROPERTY( OpenFlags, FLAG_DEPRECATED )
else WRITE_PROPERTY( OpenNewView, 0 )
else WRITE_PROPERTY( Overwrite, FLAG_MODEL )
else WRITE_PROPERTY( Password, FLAG_MODEL )
else WRITE_PROPERTY( PosSize, 0 )
else WRITE_PROPERTY( PostData, 0 )
else WRITE_PROPERTY( PostString, FLAG_DEPRECATED )
else WRITE_PROPERTY( Preview, FLAG_MODEL )
else WRITE_PROPERTY( ReadOnly, 0 )
else WRITE_PROPERTY( Referer, FLAG_MODEL )
else WRITE_PROPERTY( SetEmbedded, 0 )
else WRITE_PROPERTY( Silent, 0 )
else WRITE_PROPERTY( StatusIndicator, 0 )
else WRITE_PROPERTY( Storage, FLAG_MODEL )
else WRITE_PROPERTY( Stream, FLAG_MODEL )
else WRITE_PROPERTY( TemplateName, FLAG_DEPRECATED )
else WRITE_PROPERTY( TemplateRegionName, FLAG_DEPRECATED )
else WRITE_PROPERTY( Unpacked, FLAG_MODEL )
else WRITE_PROPERTY( URL, FLAG_MODEL )
else WRITE_PROPERTY( Version, FLAG_MODEL )
else WRITE_PROPERTY( ViewData, FLAG_MODEL )
else WRITE_PROPERTY( ViewId, FLAG_MODEL )
else WRITE_PROPERTY( WinExtent, FLAG_DEPRECATED )
else
{
m_aAdditionalProperties[nAdditionalCount]=rProp;
nAdditionalCount++;
}
}
m_aRegularProperties.realloc(nRegularCount);
m_aDeprecatedProperties.realloc(nDeprecatedCount);
m_aAdditionalProperties.realloc(nAdditionalCount);
m_aModelProperties.realloc(nModelCount);
}
void MediaDescriptorHelper::impl_init()
{
AsTemplate = sal_False;
ISSET_AsTemplate = sal_False;
ISSET_Author = sal_False;
ISSET_CharacterSet = sal_False;
ISSET_Comment = sal_False;
// ::com::sun::star::uno::Any ComponentData;
ISSET_ComponentData = sal_False;
ISSET_FileName = sal_False;
// ::com::sun::star::uno::Any FilterData;
ISSET_FilterData = sal_False;
ISSET_FilterName = sal_False;
ISSET_FilterFlags = sal_False;
ISSET_FilterOptions = sal_False;
ISSET_FrameName = sal_False;
Hidden = sal_False;
ISSET_Hidden = sal_False;
ISSET_HierarchicalDocumentName = sal_False;
ISSET_OutputStream = sal_False;
ISSET_InputStream = sal_False;
ISSET_InteractionHandler = sal_False;
ISSET_JumpMark = sal_False;
ISSET_MediaType = sal_False;
ISSET_OpenFlags = sal_False;
OpenNewView = sal_False;
ISSET_OpenNewView = sal_False;
Overwrite = sal_False;
ISSET_Overwrite = sal_False;
ISSET_Password = <PASSWORD>;
// ::com::sun::star::awt::Rectangle PosSize;
ISSET_PosSize = sal_False;
// ::com::sun::star::uno::Sequence< sal_Int8 > PostData;
ISSET_PostData = sal_False;
ISSET_PostString = sal_False;
Preview = sal_False;
ISSET_Preview = sal_False;
ReadOnly = sal_False;
ISSET_ReadOnly = sal_False;
ISSET_Referer = sal_False;
ISSET_StatusIndicator = sal_False;
Silent = sal_False;
ISSET_Silent = sal_False;
ISSET_TemplateName = sal_False;
ISSET_TemplateRegionName = sal_False;
Unpacked = sal_False;
ISSET_Unpacked = sal_False;
ISSET_URL = sal_False;
Version = 0;
ISSET_Version = sal_False;
// ::com::sun::star::uno::Any ViewData;
ISSET_ViewData = sal_False;
ViewId = 0;
ISSET_ViewId = sal_False;
ISSET_WinExtent = sal_False;
ISSET_Storage = sal_False;
ISSET_Stream = sal_False;
}
MediaDescriptorHelper::~MediaDescriptorHelper()
{
}
uno::Sequence< beans::PropertyValue > MediaDescriptorHelper
::getReducedForModel()
{
return m_aModelProperties;
}
}
| 2,627 |
348 | <gh_stars>100-1000
{"nom":"Val-de-Roulans","circ":"2ème circonscription","dpt":"Doubs","inscrits":119,"abs":54,"votants":65,"blancs":6,"nuls":6,"exp":53,"res":[{"nuance":"ECO","nom":"<NAME>","voix":31},{"nuance":"LR","nom":"<NAME>","voix":22}]} | 102 |
2,151 | // 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.payments;
import static org.chromium.chrome.browser.payments.PaymentRequestTestRule.DELAYED_RESPONSE;
import static org.chromium.chrome.browser.payments.PaymentRequestTestRule.HAVE_INSTRUMENTS;
import static org.chromium.chrome.browser.payments.PaymentRequestTestRule.IMMEDIATE_RESPONSE;
import static org.chromium.chrome.browser.payments.PaymentRequestTestRule.NO_INSTRUMENTS;
import android.content.DialogInterface;
import android.support.test.filters.MediumTest;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeSwitches;
import org.chromium.chrome.browser.autofill.AutofillTestHelper;
import org.chromium.chrome.browser.autofill.CardType;
import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile;
import org.chromium.chrome.browser.autofill.PersonalDataManager.CreditCard;
import org.chromium.chrome.browser.payments.PaymentRequestTestRule.MainActivityStartCallback;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
/**
* A payment integration test for a merchant that requests payment via Bob Pay or cards.
*/
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
public class PaymentRequestPaymentAppAndCardsTest implements MainActivityStartCallback {
@Rule
public PaymentRequestTestRule mPaymentRequestTestRule =
new PaymentRequestTestRule("payment_request_bobpay_and_cards_test.html", this);
@Override
public void onMainActivityStarted() throws InterruptedException, ExecutionException,
TimeoutException {
AutofillTestHelper helper = new AutofillTestHelper();
String billingAddressId = helper.setProfile(new AutofillProfile("", "https://example.com",
true, "<NAME>", "Google", "340 Main St", "CA", "Los Angeles", "", "90291", "",
"US", "310-310-6000", "<EMAIL>", "en-US"));
// Mastercard card without a billing address.
helper.setCreditCard(new CreditCard("", "https://example.com", true, true, "<NAME>",
"5454545454545454", "", "12", "2050", "mastercard", R.drawable.mc_card,
CardType.UNKNOWN, "" /* billingAddressId */, "" /* serverId */));
// Visa card with complete set of information.
helper.setCreditCard(new CreditCard("", "https://example.com", true, true, "<NAME>",
"4111111111111111", "", "12", "2050", "visa", R.drawable.visa_card,
CardType.UNKNOWN, billingAddressId, "" /* serverId */));
}
/**
* If Bob Pay does not have any instruments, show [visa, mastercard]. Here the payment app
* responds quickly.
*/
@Test
@MediumTest
@Feature({"Payments"})
public void testNoInstrumentsInFastBobPay()
throws InterruptedException, ExecutionException, TimeoutException {
runTest(NO_INSTRUMENTS, IMMEDIATE_RESPONSE);
}
/**
* If Bob Pay does not have any instruments, show [visa, mastercard]. Here the payment app
* responds slowly.
*/
@Test
@MediumTest
@Feature({"Payments"})
public void testNoInstrumentsInSlowBobPay()
throws InterruptedException, ExecutionException, TimeoutException {
runTest(NO_INSTRUMENTS, DELAYED_RESPONSE);
}
/**
* If Bob Pay has instruments, show [bobpay, visa, mastercard]. Here the payment app responds
* quickly.
*/
@Test
@MediumTest
@Feature({"Payments"})
public void testHaveInstrumentsInFastBobPay()
throws InterruptedException, ExecutionException, TimeoutException {
runTest(HAVE_INSTRUMENTS, IMMEDIATE_RESPONSE);
}
/**
* If Bob Pay has instruments, show [bobpay, visa, mastercard]. Here the payment app responds
* slowly.
*/
@Test
@MediumTest
@Feature({"Payments"})
public void testHaveInstrumentsInSlowBobPay()
throws InterruptedException, ExecutionException, TimeoutException {
runTest(HAVE_INSTRUMENTS, DELAYED_RESPONSE);
}
/** Test that going into the editor and cancelling will leave the row checked. */
@Test
@MediumTest
@Feature({"Payments"})
public void testEditPaymentMethodAndCancelEditorShouldKeepCardSelected()
throws InterruptedException, ExecutionException, TimeoutException {
mPaymentRequestTestRule.triggerUIAndWait(mPaymentRequestTestRule.getReadyToPay());
mPaymentRequestTestRule.clickInPaymentMethodAndWait(
R.id.payments_section, mPaymentRequestTestRule.getReadyForInput());
mPaymentRequestTestRule.expectPaymentMethodRowIsSelected(0);
mPaymentRequestTestRule.clickInPaymentMethodAndWait(
R.id.payments_add_option_button, mPaymentRequestTestRule.getReadyToEdit());
// Cancel the editor.
mPaymentRequestTestRule.clickInCardEditorAndWait(
R.id.payments_edit_cancel_button, mPaymentRequestTestRule.getReadyToPay());
// Expect the existing row to still be selected in the Shipping Address section.
mPaymentRequestTestRule.expectPaymentMethodRowIsSelected(0);
}
/** Test that going into "add" flow editor and cancelling will leave existing row checked. */
@Test
@MediumTest
@Feature({"Payments"})
public void testAddPaymentMethodAndCancelEditorShouldKeepExistingCardSelected()
throws InterruptedException, ExecutionException, TimeoutException {
mPaymentRequestTestRule.triggerUIAndWait(mPaymentRequestTestRule.getReadyToPay());
mPaymentRequestTestRule.clickInPaymentMethodAndWait(
R.id.payments_section, mPaymentRequestTestRule.getReadyForInput());
mPaymentRequestTestRule.expectPaymentMethodRowIsSelected(0);
mPaymentRequestTestRule.clickInPaymentMethodAndWait(
R.id.payments_open_editor_pencil_button, mPaymentRequestTestRule.getReadyToEdit());
// Cancel the editor.
mPaymentRequestTestRule.clickInCardEditorAndWait(
R.id.payments_edit_cancel_button, mPaymentRequestTestRule.getReadyToPay());
// Expect the row to still be selected in the Shipping Address section.
mPaymentRequestTestRule.expectPaymentMethodRowIsSelected(0);
}
private void runTest(int instrumentPresence, int responseSpeed) throws InterruptedException,
ExecutionException, TimeoutException {
mPaymentRequestTestRule.installPaymentApp(instrumentPresence, responseSpeed);
mPaymentRequestTestRule.triggerUIAndWait(mPaymentRequestTestRule.getReadyToPay());
mPaymentRequestTestRule.clickInPaymentMethodAndWait(
R.id.payments_section, mPaymentRequestTestRule.getReadyForInput());
// Check the number of instruments.
Assert.assertEquals(instrumentPresence == HAVE_INSTRUMENTS ? 3 : 2,
mPaymentRequestTestRule.getNumberOfPaymentInstruments());
// Check the labels of the instruments.
int i = 0;
if (instrumentPresence == HAVE_INSTRUMENTS) {
Assert.assertEquals(
"https://bobpay.com", mPaymentRequestTestRule.getPaymentInstrumentLabel(i++));
}
// \u0020\...\u2006 is four dots ellipsis, \u202A is the Left-To-Right Embedding (LTE) mark,
// \u202C is the Pop Directional Formatting (PDF) mark. Expected string with form
// 'Visa <LRE>****1111<PDF>\n<NAME>'.
Assert.assertEquals("Visa\u0020\u0020\u202A\u2022\u2006\u2022\u2006\u2022\u2006\u2022\u2006"
+ "1111\u202C\n<NAME>",
mPaymentRequestTestRule.getPaymentInstrumentLabel(i++));
// Expected string with form
// 'Visa <LRE>****5454<PDF>\n<NAME>\nBilling address required'.
Assert.assertEquals(
"Mastercard\u0020\u0020\u202A\u2022\u2006\u2022\u2006\u2022\u2006\u2022\u2006"
+ "5454\u202C\n<NAME>\nBilling address required",
mPaymentRequestTestRule.getPaymentInstrumentLabel(i++));
// Check the output of the selected instrument.
if (instrumentPresence == HAVE_INSTRUMENTS) {
mPaymentRequestTestRule.clickAndWait(
R.id.button_primary, mPaymentRequestTestRule.getDismissed());
mPaymentRequestTestRule.expectResultContains(
new String[] {"https://bobpay.com", "\"transaction\"", "1337"});
} else {
mPaymentRequestTestRule.clickAndWait(
R.id.button_primary, mPaymentRequestTestRule.getReadyForUnmaskInput());
mPaymentRequestTestRule.setTextInCardUnmaskDialogAndWait(
R.id.card_unmask_input, "123", mPaymentRequestTestRule.getReadyToUnmask());
mPaymentRequestTestRule.clickCardUnmaskButtonAndWait(
DialogInterface.BUTTON_POSITIVE, mPaymentRequestTestRule.getDismissed());
mPaymentRequestTestRule.expectResultContains(new String[] {
"<NAME>", "4111111111111111", "12", "2050", "basic-card", "123"});
}
}
}
| 3,726 |
936 | /*
* Copyright 2019, Yahoo Inc.
* Licensed under the Apache License, Version 2.0
* See LICENSE file in project root for terms.
*/
package com.yahoo.elide.core.filter.predicates;
import com.yahoo.elide.core.Path;
import com.yahoo.elide.core.Path.PathElement;
import com.yahoo.elide.core.filter.Operator;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* IN Insensitive Predicate class.
*/
public class InInsensitivePredicate extends FilterPredicate {
public InInsensitivePredicate(Path path, List<Object> values) {
super(path, Operator.IN_INSENSITIVE, values);
}
@SafeVarargs
public <T> InInsensitivePredicate(Path path, T... a) {
this(path, Arrays.asList(a));
}
public InInsensitivePredicate(PathElement pathElement, List<Object> values) {
this(new Path(Collections.singletonList(pathElement)), values);
}
@SafeVarargs
public <T> InInsensitivePredicate(PathElement pathElement, T... a) {
this(pathElement, Arrays.asList(a));
}
}
| 369 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-rr9h-4g6q-37gg",
"modified": "2022-05-01T07:36:26Z",
"published": "2022-05-01T07:36:26Z",
"aliases": [
"CVE-2006-6274"
],
"details": "SQL injection vulnerability in articles.asp in Expinion.net iNews (1) Publisher (iNP) 2.5 and earlier, and possibly (2) News Manager, allows remote attackers to execute arbitrary SQL commands via the ex parameter. NOTE: early reports of this issue reported it as XSS, but this was erroneous. The original report was for News Manager, but there is strong evidence that the correct product is Publisher.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2006-6274"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/30510"
},
{
"type": "WEB",
"url": "http://attrition.org/pipermail/vim/2006-November/001147.html"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/23123"
},
{
"type": "WEB",
"url": "http://securityreason.com/securityalert/1956"
},
{
"type": "WEB",
"url": "http://www.aria-security.com/forum/showthread.php?t=40"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/archive/1/452572/100/0/threaded"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/21296"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2006/4707"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 747 |
344 | <gh_stars>100-1000
/**
* TexturedMeshSample.java
*
* Copyright (c) 2013-2020, F(X)yz
* 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 F(X)yz, any associated website, 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 F(X)yz BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.fxyz3d.samples.shapes;
import java.util.function.Function;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import org.fxyz3d.controls.TextureImage;
import org.fxyz3d.geometry.Point3D;
import org.fxyz3d.scene.paint.Patterns.CarbonPatterns;
import org.fxyz3d.shapes.primitives.TexturedMesh;
import org.fxyz3d.shapes.primitives.helper.TriangleMeshHelper;
import org.fxyz3d.shapes.primitives.helper.TriangleMeshHelper.TextureType;
import org.fxyz3d.tools.NormalMap;
/**
*
* @author <NAME> aka jdub1581
*/
public abstract class TexturedMeshSample extends ShapeBaseSample<TexturedMesh> {
static {
TriangleMeshHelper.PARALLEL_ALLOWED = false;
}
//specific
protected final Property<TriangleMeshHelper.SectionType> sectionType = new SimpleObjectProperty<TriangleMeshHelper.SectionType>(model, "secType", TriangleMeshHelper.SectionType.CIRCLE) {
@Override
protected void invalidated() {
super.invalidated();
if (model != null) {
model.setSectionType(sectionType.getValue());
}
}
};
protected final Property<TextureType> textureType = new SimpleObjectProperty<TextureType>(model, "texType", TriangleMeshHelper.TextureType.NONE) {
@Override
protected void invalidated() {
super.invalidated();
if (model != null) {
switch (getValue()) {
case NONE:
model.setTextureModeNone(colorBinding.get());
if (useBumpMap.getValue() || invert.getValue()) {
useBumpMap.setValue(false);
invert.setValue(false);
}
break;
case IMAGE:
model.setTextureModeImage(textureImage.getValue()==null?null:textureImage.getValue().getSource());
if (useBumpMap.getValue() || invert.getValue()) {
useBumpMap.setValue(false);
invert.setValue(false);
}
break;
case PATTERN:
model.setTextureModePattern(patterns.get(), pattScale.getValue());
material.setSpecularColor(specColorBinding.get());
material.setSpecularPower(specularPower.doubleValue());
if (useBumpMap.getValue() || invert.getValue()) {
useBumpMap.setValue(false);
invert.setValue(false);
}
break;
case COLORED_VERTICES_1D:
model.setTextureModeVertices1D(1530, func.getValue());
if (useBumpMap.getValue() || invert.getValue()) {
useBumpMap.setValue(false);
invert.setValue(false);
}
break;
case COLORED_VERTICES_3D:
model.setTextureModeVertices3D(1530, dens.getValue());
if (useBumpMap.getValue() || invert.getValue()) {
useBumpMap.setValue(false);
invert.setValue(false);
}
break;
case COLORED_FACES:
model.setTextureModeFaces(1530);
if (useBumpMap.getValue() || invert.getValue()) {
useBumpMap.setValue(false);
invert.setValue(false);
}
break;
}
}
}
};
/*
TriangleMeshHelper.TextureType.NONE
*/
protected final ObjectProperty<Color> colorBinding = new SimpleObjectProperty<Color>(Color.BROWN) {
@Override
protected void invalidated() {
super.invalidated();
if (model != null && model.getTextureType().equals(TriangleMeshHelper.TextureType.NONE)) {
model.setDiffuseColor(get());
}
}
};
protected final IntegerProperty colors = new SimpleIntegerProperty(model, "Color :", 700) {
@Override
protected void invalidated() {
super.invalidated();
if (model != null) {
colorBinding.set(Color.hsb(360 * (1d - get() / 1530d), 1, 0.5));
}
}
};
/*
TriangleMeshHelper.TextureType.IMAGE
*/
protected final Property<TextureImage> textureImage = new SimpleObjectProperty(this, "Texture") {
@Override
protected void invalidated() {
if (model != null && model.getTextureType().equals(TriangleMeshHelper.TextureType.IMAGE)) {
//material.setDiffuseMap(textureImage.getValue());
model.setTextureModeImage(textureImage.getValue().getSource());
if (useBumpMap.getValue() || invert.getValue()) {
useBumpMap.setValue(false);
invert.setValue(false);
}
}
}
};
protected final ObjectProperty<CarbonPatterns> patterns = new SimpleObjectProperty<CarbonPatterns>(CarbonPatterns.DARK_CARBON) {
@Override
protected void invalidated() {
super.invalidated();
if (model != null && model.getTextureType().equals(TriangleMeshHelper.TextureType.PATTERN)) {
model.setCarbonPattern(patterns.getValue());
material.setSpecularColor(specColorBinding.get());
material.setSpecularPower(specularPower.doubleValue());
if (useBumpMap.get()) {
material.setBumpMap(new NormalMap(
bumpScale.doubleValue(), bumpFineScale.doubleValue(),
invert.getValue(), ((PhongMaterial) model.getMaterial()).getDiffuseMap()
));
}
}
}
};
/*
TriangleMeshHelper.TextureType.PATTERN
*/
protected final DoubleProperty pattScale = new SimpleDoubleProperty(this, "Pattern Scale: ", 2.0d) {
@Override
protected void invalidated() {
super.invalidated();
if (model != null && model.getTextureType().equals(TriangleMeshHelper.TextureType.PATTERN)) {
model.setPatternScale(pattScale.doubleValue());
}
}
};
/*
TriangleMeshHelper.TextureType.COLORED_VERTICES_3D
*/
protected final DoubleProperty densMax = new SimpleDoubleProperty(this, "Density Scale: ");
protected final Property<Function<Point3D, Number>> dens = new SimpleObjectProperty<Function<Point3D, Number>>(p -> p.x * p.y * p.z) {
@Override
protected void invalidated() {
super.invalidated();
if (model != null && model.getTextureType().equals(TriangleMeshHelper.TextureType.COLORED_VERTICES_3D)) {
model.setDensity(dens.getValue());
}
}
};
/*
TriangleMeshHelper.TextureType.COLORED_VERTICES_1D
*/
protected final Property<Function<Number, Number>> func = new SimpleObjectProperty<Function<Number, Number>>(t -> t) {
@Override
protected void invalidated() {
super.invalidated();
if (model != null && model.getTextureType().equals(TriangleMeshHelper.TextureType.COLORED_VERTICES_1D)) {
model.setFunction(func.getValue());
}
}
};
protected final Property<Boolean> invert = new SimpleBooleanProperty(this, "Invert Bump Map", false) {
@Override
protected void invalidated() {
if (model != null && useBumpMap.getValue()) {
if (model.getMaterial() != null && ((PhongMaterial) model.getMaterial()).getDiffuseMap() != null) {
((PhongMaterial) model.getMaterial()).setBumpMap(
new NormalMap(
bumpScale.doubleValue(), bumpFineScale.doubleValue(),
invert.getValue(), ((PhongMaterial) model.getMaterial()).getDiffuseMap()
)
);
}
}
}
};
protected final DoubleProperty bumpScale = new SimpleDoubleProperty(this, "Bump Scale", 27d) {
@Override
protected void invalidated() {
if (model != null) {
if (model.getMaterial() != null && ((PhongMaterial) model.getMaterial()).getDiffuseMap() != null) {
((PhongMaterial) model.getMaterial()).setBumpMap(
new NormalMap(
bumpScale.doubleValue(), bumpFineScale.doubleValue(),
invert.getValue(), ((PhongMaterial) model.getMaterial()).getDiffuseMap()
)
);
}
}
}
};
protected final ObjectProperty<Image> bumpMap = new SimpleObjectProperty<Image>(this, "bumpMap", null) {
@Override
protected void invalidated() {
if (model != null) {
}
}
};
protected final DoubleProperty bumpFineScale = new SimpleDoubleProperty(this, "Bump Fine Scale", 9d) {
@Override
protected void invalidated() {
if (model != null) {
if (model.getMaterial() != null && ((PhongMaterial) model.getMaterial()).getDiffuseMap() != null) {
((PhongMaterial) model.getMaterial()).setBumpMap(
new NormalMap(
bumpScale.doubleValue(), bumpFineScale.doubleValue(),
invert.getValue(), ((PhongMaterial) model.getMaterial()).getDiffuseMap()
)
);
}
}
}
};
protected final BooleanProperty useBumpMap = new SimpleBooleanProperty(this, "Generate Bump Map", false) {
@Override
protected void invalidated() {
if (get()) {
if (model != null) {
if (model.getMaterial() != null && ((PhongMaterial) model.getMaterial()).getDiffuseMap() != null) {
((PhongMaterial) model.getMaterial()).setBumpMap(
new NormalMap(
bumpScale.doubleValue(), bumpFineScale.doubleValue(),
invert.getValue(), ((PhongMaterial) model.getMaterial()).getDiffuseMap()
)
);
}
}
} else {
if (model != null) {
((PhongMaterial) model.getMaterial()).setBumpMap(null);
}
}
}
};
protected final DoubleProperty specularPower = new SimpleDoubleProperty(this, "Specular Power") {
@Override
protected void invalidated() {
if (model != null) {
if (model.getMaterial() != null) {
((PhongMaterial) model.getMaterial()).setSpecularPower(specularPower.getValue());
}
}
}
};
protected final ObjectProperty<Color> specColorBinding = new SimpleObjectProperty<Color>(Color.BLACK) {
@Override
protected void invalidated() {
super.invalidated();
if (model != null) {
material.setSpecularColor(get());
}
}
};
protected final IntegerProperty specColor = new SimpleIntegerProperty(this, "Specular Color", 1) {
@Override
protected void invalidated() {
super.invalidated();
if (model != null) {
specColorBinding.set(Color.hsb(360 * (1d - get() / 1530d), 1, 1));
}
}
};
}
| 6,726 |
1,738 | <filename>dev/Code/Framework/AzCore/AzCore/std/typetraits/is_integral.h<gh_stars>1000+
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#ifndef AZSTD_TYPE_TRAITS_IS_INTEGRAL_H
#define AZSTD_TYPE_TRAITS_IS_INTEGRAL_H 1
#include <AzCore/std/typetraits/integral_constant.h>
#include <AzCore/std/typetraits/bool_trait_def.h>
namespace AZStd
{
//* is a type T an [cv-qualified-] integral type described in the standard (3.9.1p3)
AZSTD_TYPE_TRAIT_BOOL_DEF1(is_integral, T, false)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, unsigned char, true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, unsigned short, true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, unsigned int, true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, unsigned long, true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, signed char, true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, signed short, true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, signed int, true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, signed long, true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, bool, true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, char, true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral,wchar_t,true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, ::AZ::u64, true)
AZSTD_TYPE_TRAIT_BOOL_CONST_VOLATILE_SPEC1(is_integral, ::AZ::s64, true)
}
#endif // AZSTD_TYPE_TRAITS_IS_INTEGRAL_H
#pragma once
| 827 |
435 | <reponame>amaajemyfren/data<filename>pycon-kr-2015/videos/gimmyeongsin-python-gaebaleul-wihan-coesangyi-muryo-gaebal-dogu-visual-studiowa-visual-studio-code-pycon-korea-2015.json
{
"description": "\ub9c8\uc774\ud06c\ub85c\uc18c\ud504\ud2b8\uc758 Visual Studio\ub294 \uc790\ud0c0\uac00 \uacf5\ud5cc\ud558\ub294 \uc138\uacc4 \ucd5c\uace0\uc758\n\uac1c\ubc1c\ub3c4\uad6c\uc785\ub2c8\ub2e4. Python \uac1c\ubc1c\uc790\ub294 \uc774\uc81c Python Tools for Visual\nStudio(PTVS)\ub97c \uc124\uce58\ud558\uc5ec Visual Studio\ub97c \ucd5c\uace0\uc758 Python \uac1c\ubc1c\ub3c4\uad6c\ub85c \ud655\uc7a5 \ud560\n\uc218 \uc788\uc2b5\ub2c8\ub2e4. PTVS\ub294 CPython, IronPython\uc744 \uac00\ub9ac\uc9c0 \uc54a\uace0, \ud3b8\uc9d1, \ube0c\ub77c\uc6b0\uc9d5,\n\uc778\ud138\ub808\uc13c\uc2a4 \uae30\ub2a5\uc744 \uc81c\uacf5\ud558\uace0, Python/C++\uc774 \ud63c\uc7ac\ub418\uc5b4 \uc788\ub294 \ud658\uacbd\uc774\ub098 Linux,\nMac OS \ud658\uacbd\uc5d0\uc11c\ub3c4 \ub514\ubc84\uae45\uc744 \ud560 \uc218 \uc788\uc2b5\ub2c8\ub2e4.\n\n\ubcf8 \uc138\uc158\uc5d0\uc11c\ub294 PTVS\uc758 \uc124\uce58\ub85c\ubd80\ud130 \uace0\uae09 \ub514\ubc84\uae45 \uc2dc\ub098\ub9ac\uc624\uae4c\uc9c0\ub97c \uc0b4\ud3b4\ubcf4\uace0,\nWindows/Linux/Mac OS\ub97c \ubaa8\ub450 \uc9c0\uc6d0\ud558\ub294 Cross Platform \ud3b8\uc9d1\ub3c4\uad6c\uc778 Visual\nStudio Code\uc5d0 \ub300\ud574\uc11c\ub3c4 \uac04\ub7b5\ud558 \uc0b4\ud3b4\ubd05\ub2c8\ub2e4.\n",
"duration": 2490,
"language": "kor",
"recorded": "2015-08-30",
"speakers": [
"<NAME>"
],
"thumbnail_url": "https://i.ytimg.com/vi/QzfalQn1lc0/hqdefault.jpg",
"title": "Python \uac1c\ubc1c\uc744 \uc704\ud55c \ucd5c\uc0c1\uc758 \ubb34\ub8cc \uac1c\ubc1c \ub3c4\uad6c Visual Studio\uc640 Visual Studio Code",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=QzfalQn1lc0"
}
]
}
| 1,030 |
727 | <filename>Frameworks/XADMaster.framework/Versions/A/PrivateHeaders/XAD7ZipBranchHandles.h
#import "CSBlockStreamHandle.h"
@interface XAD7ZipBranchHandle:CSBlockStreamHandle
{
CSHandle *parent;
off_t startoffs;
uint8_t inbuffer[4096];
int leftoverstart,leftoverlength;
uint32_t baseoffset;
}
-(id)initWithHandle:(CSHandle *)handle;
-(id)initWithHandle:(CSHandle *)handle propertyData:(NSData *)propertydata;
-(id)initWithHandle:(CSHandle *)handle length:(off_t)length;
-(id)initWithHandle:(CSHandle *)handle length:(off_t)length propertyData:(NSData *)propertydata;
-(void)dealloc;
-(void)resetBlockStream;
-(int)produceBlockAtOffset:(off_t)pos;
-(int)decodeBlock:(uint8_t *)block length:(int)length offset:(off_t)pos;
@end
@interface XAD7ZipBCJHandle:XAD7ZipBranchHandle { uint32_t state; }
@end
@interface XAD7ZipPPCHandle:XAD7ZipBranchHandle {}
@end
@interface XAD7ZipIA64Handle:XAD7ZipBranchHandle {}
@end
@interface XAD7ZipARMHandle:XAD7ZipBranchHandle {}
@end
@interface XAD7ZipThumbHandle:XAD7ZipBranchHandle {}
@end
@interface XAD7ZipSPARCHandle:XAD7ZipBranchHandle {}
@end
| 400 |
799 | <gh_stars>100-1000
import demistomock as demisto
from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
''' IMPORTS '''
import urllib3
from typing import Dict, Any
from datetime import datetime
from dateutil.parser import parse as parse_dt
import traceback
from functools import reduce
# Disable insecure warnings
urllib3.disable_warnings()
''' CONSTANTS '''
DATE_FORMAT = '%Y-%m-%d %I:%M:%S'
VERSION = 'v1.0.0'
USER_AGENT = f'Qintel-CortexXSOAR/{VERSION}'
VENDOR = 'Qintel'
PMI_REMOTE = 'https://pmi.api.qintel.com'
class Client(BaseClient):
"""Client class to interact with Qintel APIs"""
def __init__(self, base_url, verify=True, proxy=False, **kwargs):
super(Client, self).__init__(base_url, verify=verify, proxy=proxy)
self._headers = {
'User-Agent': USER_AGENT,
'Cf-Access-Client-Id': kwargs.get('client_id'),
'Cf-Access-Client-Secret': kwargs.get('client_secret')
}
def search(self, endpoint: str, params: dict) -> Dict[str, Any]:
return self._http_request(
method='GET',
url_suffix=endpoint,
params=params,
backoff_factor=0.5,
retries=5
)
def ping(self) -> Dict[str, Any]:
return self._http_request(
method='GET',
url_suffix='/users/me',
)
def test_module(client) -> str:
try:
client.ping()
except Exception as e:
return 'Test failed: {}'.format(e)
return 'ok'
def _make_timestamp(ts):
if not ts:
return
if isinstance(ts, int):
return datetime.fromtimestamp(ts)
if isinstance(ts, str):
return parse_dt(ts)
def _map_fields(d, path, default='Unknown'):
try:
value = reduce(dict.get, path, d)
except KeyError:
return default
if not value:
return default
return value
def _process_cve_attributes(data, rv):
rv['AffectedSystem'] = \
_map_fields(data, ('attributes', 'affected_system', 'name'))
rv['AffectedVersions'] = \
_map_fields(data, ('attributes', 'affected_system', 'versions'))
if isinstance(rv['AffectedVersions'], list):
rv['AffectedVersions'] = ', '.join(rv['AffectedVersions'])
rv['LastObserved'] = \
_make_timestamp(
_map_fields(data, ('attributes', 'last_observed'))
).strftime(DATE_FORMAT) # noqa
def _process_cve_observations(observ, rv):
observations_data = []
for obs in observ:
actor_label = _map_fields(obs, ('relationships', 'tags', 'data'), None)
if actor_label:
actor_label = _map_fields(actor_label[0], ('attributes', 'label'))
actor_type = _map_fields(obs, ('relationships', 'tags', 'data'), None)
if actor_type:
actor_type = _map_fields(actor_type[0], ('attributes', 'tag_type'))
exploit_type = _map_fields(obs, ('attributes', 'exploit_type'))
exploit_notes = _map_fields(obs, ('attributes', 'notes'), None)
ts_observ = None
timestamps = _map_fields(obs, ('attributes', 'timestamps'), None)
if timestamps:
for t in timestamps:
if t['context'] == 'observed':
ts_observ = \
_make_timestamp(t['value']).strftime(DATE_FORMAT)
observations_data.append(
{'actor': actor_label, 'actor_type': actor_type,
'exploit_type': exploit_type,
'exploit_notes': exploit_notes, 'date_observed': ts_observ})
rv['Observations'] = observations_data
def _process_cve_data(data, cve):
rv = {'id': cve}
_process_cve_attributes(data, rv)
observ = _map_fields(data, ('relationships', 'observations', 'data'), [])
_process_cve_observations(observ, rv)
return rv
def cve_command(client, **args):
cves = args.get('cve', '')
cves = argToList(cves)
command_results = []
for cve in cves:
search_params = {
'identifier': cve
}
response = client.search('cves', search_params)
if response and response.get('data'):
data = _process_cve_data(response['data'][0], cve)
# human readable output
columns = ['actor', 'actor_type', 'exploit_type', 'exploit_notes',
'date_observed']
header = f'Qintel vulnerability results for: {cve}'
metadata = f"**Vulnerability in {data['AffectedSystem']} " \
f"affecting versions: {data['AffectedVersions']}**\n"
metadata += f"**Last observed: {data['LastObserved']}**"
hr = tableToMarkdown(header, data['Observations'], columns,
metadata=metadata)
cve_return = Common.CVE(
id=cve,
cvss='None',
description='None',
published='None',
modified='None'
)
command_results.append(CommandResults(
outputs_prefix='Qintel.CVE',
outputs_key_field='id',
outputs=data,
indicator=cve_return,
readable_output=hr
))
else:
# human readable output
header = f'Qintel vulnerability results for: {cve}'
hr = tableToMarkdown(header, {})
command_results.append(CommandResults(
readable_output=hr
))
return command_results
def main() -> None:
params = demisto.params()
client_args = {
'client_id': params.get('credentials').get('identifier'),
'client_secret': params.get('credentials').get('password')
}
remote = params.get('remote', PMI_REMOTE)
proxy = params.get('proxy', False)
verify_ssl = not params.get('insecure', False)
command = demisto.command()
demisto.debug(f'Command being called is {command}')
try:
client = Client(remote, verify_ssl, proxy, **client_args)
args = demisto.args()
if command == 'test-module':
demisto.results(test_module(client))
elif command == 'cve':
return_results(cve_command(client, **args))
# Log exceptions
except Exception as e:
demisto.error(traceback.format_exc())
return_error(f'Failed to execute {command} command.\nError:\n{str(e)}')
if __name__ in ('__main__', '__builtin__', 'builtins'):
main()
| 2,996 |
1,144 | package org.eevolution.process;
/*
* #%L
* de.metas.adempiere.libero.libero
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import de.metas.document.engine.DocStatus;
import de.metas.document.engine.IDocument;
import de.metas.document.engine.IDocumentBL;
import de.metas.material.planning.pporder.IPPOrderBOMBL;
import de.metas.material.planning.pporder.IPPOrderBOMDAO;
import de.metas.process.IProcessPrecondition;
import de.metas.process.IProcessPreconditionsContext;
import de.metas.process.JavaProcess;
import de.metas.process.ProcessPreconditionsResolution;
import de.metas.util.Check;
import de.metas.util.Services;
import org.adempiere.ad.model.util.ModelByIdComparator;
import org.adempiere.exceptions.AdempiereException;
import org.compiere.model.ModelValidationEngine;
import org.compiere.model.ModelValidator;
import org.eevolution.api.CostCollectorType;
import org.eevolution.api.IPPCostCollectorDAO;
import org.eevolution.api.IPPOrderBL;
import org.eevolution.api.IPPOrderDAO;
import org.eevolution.api.PPOrderId;
import org.eevolution.model.I_PP_Cost_Collector;
import org.eevolution.model.I_PP_Order;
import org.eevolution.model.I_PP_Order_BOMLine;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* Unclose a manufacturing order.
*
* @author tsa
* Task 08731
*/
public class PP_Order_UnClose extends JavaProcess implements IProcessPrecondition
{
// services
private final IDocumentBL docActionBL = Services.get(IDocumentBL.class);
private final IPPOrderBL ppOrderBL = Services.get(IPPOrderBL.class);
private final IPPOrderDAO ppOrdersRepo = Services.get(IPPOrderDAO.class);
private final IPPOrderBOMDAO ppOrderBOMDAO = Services.get(IPPOrderBOMDAO.class);
private final IPPOrderBOMBL ppOrderBOMBL = Services.get(IPPOrderBOMBL.class);
private final IPPCostCollectorDAO ppCostCollectorDAO = Services.get(IPPCostCollectorDAO.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
final I_PP_Order ppOrder = context.getSelectedModel(I_PP_Order.class);
return ProcessPreconditionsResolution.acceptIf(isEligible(ppOrder));
}
private static boolean isEligible(@Nullable final I_PP_Order ppOrder)
{
if (ppOrder == null)
{
return false;
}
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(ppOrder.getDocStatus());
return docStatus.isClosed();
}
@Override
protected String doIt()
{
final PPOrderId ppOrderId = getPPOrderId();
final I_PP_Order ppOrder = ppOrdersRepo.getById(ppOrderId);
if (!isEligible(ppOrder))
{
throw new AdempiereException("@NotValid@ " + ppOrder);
}
unclose(ppOrder);
return MSG_OK;
}
private PPOrderId getPPOrderId()
{
Check.assumeEquals(getTableName(), I_PP_Order.Table_Name, "TableName");
return PPOrderId.ofRepoId(getRecord_ID());
}
private void unclose(final I_PP_Order ppOrder)
{
ModelValidationEngine.get().fireDocValidate(ppOrder, ModelValidator.TIMING_BEFORE_UNCLOSE);
//
// Unclose PP_Order's Qty
ppOrderBL.uncloseQtyOrdered(ppOrder);
ppOrdersRepo.save(ppOrder);
//
// Unclose PP_Order BOM Line's quantities
final List<I_PP_Order_BOMLine> lines = ppOrderBOMDAO.retrieveOrderBOMLines(ppOrder);
for (final I_PP_Order_BOMLine line : lines)
{
ppOrderBOMBL.unclose(line);
}
//
// Unclose activities
final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID());
ppOrderBL.uncloseActivities(ppOrderId);
// firing this before having updated the docstatus. This is how the *real* DocActions like MInvoice do it too.
ModelValidationEngine.get().fireDocValidate(ppOrder, ModelValidator.TIMING_AFTER_UNCLOSE);
//
// Update DocStatus
ppOrder.setDocStatus(IDocument.STATUS_Completed);
ppOrder.setDocAction(IDocument.ACTION_Close);
ppOrdersRepo.save(ppOrder);
//
// Reverse ALL cost collectors
reverseCostCollectorsGeneratedOnClose(ppOrderId);
}
private void reverseCostCollectorsGeneratedOnClose(final PPOrderId ppOrderId)
{
final ArrayList<I_PP_Cost_Collector> costCollectors = new ArrayList<>(ppCostCollectorDAO.getByOrderId(ppOrderId));
// Sort the cost collectors in reverse order of their creation,
// just to make sure we are reversing the effect from last one to first one.
costCollectors.sort(ModelByIdComparator.getInstance().reversed());
for (final I_PP_Cost_Collector cc : costCollectors)
{
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(cc.getDocStatus());
if (docStatus.isReversedOrVoided())
{
continue;
}
final CostCollectorType costCollectorType = CostCollectorType.ofCode(cc.getCostCollectorType());
if (costCollectorType == CostCollectorType.UsageVariance)
{
if (docStatus.isClosed())
{
cc.setDocStatus(DocStatus.Completed.getCode());
ppCostCollectorDAO.save(cc);
}
docActionBL.processEx(cc, IDocument.ACTION_Reverse_Correct, DocStatus.Reversed.getCode());
}
}
}
}
| 1,958 |
609 | <filename>thrill/api/gather.hpp
/*******************************************************************************
* thrill/api/gather.hpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2015 <NAME> <<EMAIL>>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#ifndef THRILL_API_GATHER_HEADER
#define THRILL_API_GATHER_HEADER
#include <thrill/api/action_node.hpp>
#include <thrill/api/dia.hpp>
#include <iostream>
#include <vector>
namespace thrill {
namespace api {
/*!
* \ingroup api_layer
*/
template <typename ValueType>
class GatherNode final : public ActionResultNode<std::vector<ValueType> >
{
public:
using Super = ActionResultNode<std::vector<ValueType> >;
using Super::context_;
template <typename ParentDIA>
GatherNode(const ParentDIA& parent, const char* label,
size_t target_id,
std::vector<ValueType>* out_vector)
: Super(parent.ctx(), label,
{ parent.id() }, { parent.node() }),
target_id_(target_id),
out_vector_(out_vector) {
assert(target_id_ < context_.num_workers());
auto pre_op_fn = [this](const ValueType& input) {
emitters_[target_id_].Put(input);
};
// close the function stack with our pre op and register it at parent
// node for output
auto lop_chain = parent.stack().push(pre_op_fn).fold();
parent.node()->AddChild(this, lop_chain);
}
void StartPreOp(size_t /* parent_index */) final {
emitters_ = stream_->GetWriters();
// close all but the target
for (size_t i = 0; i < emitters_.size(); i++) {
if (i == target_id_) continue;
emitters_[i].Close();
}
}
void StopPreOp(size_t /* parent_index */) final {
emitters_[target_id_].Close();
}
void Execute() final {
auto reader = stream_->GetCatReader(true /* consume */);
while (reader.HasNext()) {
out_vector_->push_back(reader.template Next<ValueType>());
}
}
const std::vector<ValueType>& result() const final {
return *out_vector_;
}
private:
//! target worker id, which collects vector, all other workers do not get
//! the data.
size_t target_id_;
//! Vector pointer to write elements to.
std::vector<ValueType>* out_vector_;
data::CatStreamPtr stream_ { context_.GetNewCatStream(this) };
data::CatStream::Writers emitters_;
};
template <typename ValueType, typename Stack>
std::vector<ValueType>
DIA<ValueType, Stack>::Gather(size_t target_id) const {
assert(IsValid());
using GatherNode = api::GatherNode<ValueType>;
std::vector<ValueType> output;
auto node = tlx::make_counting<GatherNode>(
*this, "Gather", target_id, &output);
node->RunScope();
return output;
}
template <typename ValueType, typename Stack>
void DIA<ValueType, Stack>::Gather(
size_t target_id, std::vector<ValueType>* out_vector) const {
assert(IsValid());
using GatherNode = api::GatherNode<ValueType>;
auto node = tlx::make_counting<GatherNode>(
*this, "Gather", target_id, out_vector);
node->RunScope();
}
} // namespace api
} // namespace thrill
#endif // !THRILL_API_GATHER_HEADER
/******************************************************************************/
| 1,377 |
504 | <filename>dddlib-codegen/dddlib-codegen-parser/src/test/java/org/dddlib/codegen/parser/YmlParserTest.java<gh_stars>100-1000
package org.dddlib.codegen.parser;
import org.dddlib.codegen.classdef.ClassDefinition;
import org.junit.Before;
import org.junit.Test;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by yyang on 2016/12/23.
*/
public class YmlParserTest {
private YmlParser instance;
@Before
public void setUp() throws Exception {
instance = new YmlParser();
}
@Test
public void parseReader() throws Exception {
}
@Test
public void parseClasspath() throws Exception {
Set<ClassDefinition> classDefinitions = instance.parseClasspath("/products.yml");
}
@Test
public void parseFile() throws Exception {
}
@Test
public void parseFileName() throws Exception {
}
@Test
public void accept() throws Exception {
assertThat(instance.accept("yml")).isTrue();
assertThat(instance.accept("json")).isFalse();
}
} | 393 |
2,151 | <reponame>google-ar/chromium
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_COMMON_PERMISSIONS_USB_DEVICE_PERMISSION_H_
#define EXTENSIONS_COMMON_PERMISSIONS_USB_DEVICE_PERMISSION_H_
#include <stdint.h>
#include <memory>
#include <set>
#include "extensions/common/permissions/api_permission.h"
#include "extensions/common/permissions/set_disjunction_permission.h"
#include "extensions/common/permissions/usb_device_permission_data.h"
namespace device {
class UsbDevice;
}
namespace extensions {
class Extension;
class UsbDevicePermission
: public SetDisjunctionPermission<UsbDevicePermissionData,
UsbDevicePermission> {
public:
struct CheckParam : public APIPermission::CheckParam {
static std::unique_ptr<CheckParam> ForUsbDevice(
const Extension* extension,
const device::UsbDevice* device);
// Creates check param that only checks vendor, product and interface ID
// permission properties. It will accept all interfaceClass properties. For
// example, created param would always accept {"intefaceClass": 3}
// permission, and it would accept {"vendorId": 2, "interfaceClass": 4} iff
// |vendor_id| is 2.
// Created check param failing means there are no permissions allowing
// access to the USB device. On the other hand, created check param passing
// does not necessarily mean there is a permission allowing access to the
// USB device - one should recheck the permission when complete USB device
// info is known.
// This is useful when trying to discard devices that do not match any
// usbDevice permission when complete USB device info is not known, without
// having to fetch available USB devices.
static std::unique_ptr<CheckParam> ForDeviceWithAnyInterfaceClass(
const Extension* extension,
uint16_t vendor_id,
uint16_t product_id,
int interface_id);
static std::unique_ptr<CheckParam> ForUsbDeviceAndInterface(
const Extension* extension,
const device::UsbDevice* device,
int interface_id);
static std::unique_ptr<CheckParam> ForHidDevice(const Extension* extension,
uint16_t vendor_id,
uint16_t product_id);
CheckParam(const Extension* extension,
uint16_t vendor_id,
uint16_t product_id,
std::unique_ptr<std::set<int>> interface_classes,
int interface_id);
~CheckParam();
const uint16_t vendor_id;
const uint16_t product_id;
const std::unique_ptr<std::set<int>> interface_classes;
const int interface_id;
const bool interface_class_allowed;
private:
DISALLOW_COPY_AND_ASSIGN(CheckParam);
};
explicit UsbDevicePermission(const APIPermissionInfo* info);
~UsbDevicePermission() override;
// SetDisjunctionPermission overrides.
bool FromValue(const base::Value* value,
std::string* error,
std::vector<std::string>* unhandled_permissions) override;
// APIPermission overrides
PermissionIDSet GetPermissions() const override;
};
} // namespace extensions
#endif // EXTENSIONS_COMMON_PERMISSIONS_USB_DEVICE_PERMISSION_H_
| 1,253 |
979 | <gh_stars>100-1000
import sublime
import sublime_plugin
class ReplaceFqcnCommand(sublime_plugin.TextCommand):
def run(self, edit, region_start, region_end, namespace, leading_separator):
region = sublime.Region(region_start, region_end)
if (leading_separator):
namespace = '\\' + namespace
self.view.replace(edit, region, namespace)
return True | 145 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.