max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
777 | // 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 COMPONENTS_CAST_CERTIFICATE_CAST_CERT_VALIDATOR_H_
#define COMPONENTS_CAST_CERTIFICATE_CAST_CERT_VALIDATOR_H_
#include <memory>
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/strings/string_piece.h"
#include "base/time/time.h"
namespace net {
class TrustStore;
}
namespace cast_certificate {
class CastCRL;
// Describes the policy for a Device certificate.
enum class CastDeviceCertPolicy {
// The device certificate is unrestricted.
NONE,
// The device certificate is for an audio-only device.
AUDIO_ONLY,
};
enum class CRLPolicy {
// Revocation is only checked if a CRL is provided.
CRL_OPTIONAL,
// Revocation is always checked. A missing CRL results in failure.
CRL_REQUIRED,
};
// An object of this type is returned by the VerifyDeviceCert function, and can
// be used for additional certificate-related operations, using the verified
// certificate.
class CertVerificationContext {
public:
CertVerificationContext() {}
virtual ~CertVerificationContext() {}
// Use the public key from the verified certificate to verify a
// sha1WithRSAEncryption |signature| over arbitrary |data|. Both |signature|
// and |data| hold raw binary data. Returns true if the signature was
// correct.
virtual bool VerifySignatureOverData(const base::StringPiece& signature,
const base::StringPiece& data) const = 0;
// Retrieve the Common Name attribute of the subject's distinguished name from
// the verified certificate, if present. Returns an empty string if no Common
// Name is found.
virtual std::string GetCommonName() const = 0;
private:
DISALLOW_COPY_AND_ASSIGN(CertVerificationContext);
};
// Verifies a cast device certficate given a chain of DER-encoded certificates,
// using the built-in Cast trust anchors.
//
// Inputs:
//
// * |certs| is a chain of DER-encoded certificates:
// * |certs[0]| is the target certificate (i.e. the device certificate).
// * |certs[1..n-1]| are intermediates certificates to use in path building.
// Their ordering does not matter.
//
// * |time| is the unix timestamp to use for determining if the certificate
// is expired.
//
// * |crl| is the CRL to check for certificate revocation status.
// If this is a nullptr, then revocation checking is currently disabled.
//
// * |crl_policy| is for choosing how to handle the absence of a CRL.
// If CRL_REQUIRED is passed, then an empty |crl| input would result
// in a failed verification. Otherwise, |crl| is ignored if it is absent.
//
// Outputs:
//
// Returns true on success, false on failure. On success the output
// parameters are filled with more details:
//
// * |context| is filled with an object that can be used to verify signatures
// using the device certificate's public key, as well as to extract other
// properties from the device certificate (Common Name).
// * |policy| is filled with an indication of the device certificate's policy
// (i.e. is it for audio-only devices or is it unrestricted?)
bool VerifyDeviceCert(const std::vector<std::string>& certs,
const base::Time& time,
std::unique_ptr<CertVerificationContext>* context,
CastDeviceCertPolicy* policy,
const CastCRL* crl,
CRLPolicy crl_policy) WARN_UNUSED_RESULT;
// This is an overloaded version of VerifyDeviceCert that allows
// the input of a custom TrustStore.
//
// For production use pass |trust_store| as nullptr to use the production trust
// store.
bool VerifyDeviceCertUsingCustomTrustStore(
const std::vector<std::string>& certs,
const base::Time& time,
std::unique_ptr<CertVerificationContext>* context,
CastDeviceCertPolicy* policy,
const CastCRL* crl,
CRLPolicy crl_policy,
net::TrustStore* trust_store) WARN_UNUSED_RESULT;
// Exposed only for unit-tests, not for use in production code.
// Production code would get a context from VerifyDeviceCert().
//
// Constructs a VerificationContext that uses the provided public key.
// The common name will be hardcoded to some test value.
std::unique_ptr<CertVerificationContext> CertVerificationContextImplForTest(
const base::StringPiece& spki);
} // namespace cast_certificate
#endif // COMPONENTS_CAST_CERTIFICATE_CAST_CERT_VALIDATOR_H_
| 1,455 |
346 | pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word + first + pyg
print pyg
else:
print 'empty'
| 87 |
517 | /*
* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =======================================================================
*/
package org.tensorflow.internal.buffer;
import java.util.Iterator;
import java.util.function.Function;
import org.tensorflow.ndarray.NdArray;
/**
* Produces sequence of bytes to be stored in a {@link ByteSequenceTensorBuffer}.
*
* @param <T> source of bytes (byte arrays or strings)
*/
public class ByteSequenceProvider<T> implements Iterable<byte[]> {
/**
* Constructor
*
* @param source source of data
* @param byteExtractor method that converts one value of the source into a sequence of bytes
*/
public ByteSequenceProvider(NdArray<T> source, Function<T, byte[]> byteExtractor) {
this.source = source;
this.byteExtractor = byteExtractor;
}
@Override
public Iterator<byte[]> iterator() {
return new Iterator<byte[]>() {
@Override
public boolean hasNext() {
return scalarIterator.hasNext();
}
@Override
public byte[] next() {
return byteExtractor.apply(scalarIterator.next().getObject());
}
private final Iterator<? extends NdArray<T>> scalarIterator = source.scalars().iterator();
};
}
/**
* @return total number of byte sequences that can be produced by this sequencer
*/
long numSequences() {
return source.size();
}
private final NdArray<T> source;
private final Function<T, byte[]> byteExtractor;
}
| 626 |
5,169 | <gh_stars>1000+
{
"name": "KSOOnboarding",
"version": "0.1.1",
"summary": "KSOOnboarding is an iOS framework for on-boarding new users.",
"description": "KSOOnboarding is an iOS framework for on-boarding new users. It can display a background image or video and provides flexible layout options. Each view consists of optional image, headline text, body text, and action text.",
"homepage": "https://github.com/Kosoku/KSOOnboarding",
"license": {
"type": "Apache 2.0",
"file": "LICENSE.txt"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/Kosoku/KSOOnboarding.git",
"tag": "0.1.1"
},
"platforms": {
"ios": "11.0"
},
"requires_arc": true,
"source_files": "KSOOnboarding/**/*.{h,m}",
"exclude_files": "KSOOnboarding/KSOOnboarding-Info.h",
"private_header_files": "KSOOnboarding/Private/*.h",
"resource_bundles": {
"KSOOnboarding": [
"KSOOnboarding/**/*.{lproj}"
]
},
"frameworks": [
"Foundation",
"UIKit",
"AVFoundation"
],
"dependencies": {
"Agamotto": [
],
"Ditko": [
],
"Stanley": [
]
}
}
| 468 |
319 | <reponame>Celebrate-future/openimaj
/**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.RedirectLocations;
import org.apache.http.protocol.HttpContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
/**
* Tests for the {@link HttpUtils}
*
* @author <NAME> (<EMAIL>)
*
*/
public class HttpUtilsTest {
protected Logger logger = LogManager.getLogger(HttpUtilsTest.class);
/**
* Test that the redirection handler is working
*
* @throws MalformedURLException
* @throws IOException
*/
@Test
public void testRedirect() throws MalformedURLException, IOException {
final String[][] links = new String[][] {
// new String[] { "http://t.co/kp7qdeL6",
// "http://www.openrightsgroup.org/press/releases/bruce-willis-right-to-challenge-apple#copyright"
// },
new String[] { "http://t.co/VJn1ISBl", "https://t.co/VJn1ISBl", "http://ow.ly/1mgxj1",
"http://www.electronicsweekly.com/Articles/2012/09/03/54467/raspberry-pi-goes-to-cambridge-to-get-free-os.htm",
"https://www.electronicsweekly.com/Articles/2012/09/03/54467/raspberry-pi-goes-to-cambridge-to-get-free-os.htm"
}
};
for (final String[] link : links) {
final String[] expecting = Arrays.copyOfRange(link, 1, link.length);
final String firstLink = link[0];
HttpUtils.readURLAsByteArrayInputStream(new URL(firstLink), new HttpUtils.MetaRefreshRedirectStrategy() {
int redirected = 0;
@Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
throws ProtocolException
{
final boolean isRedirect = super.isRedirected(request, response, context);
if (redirected < expecting.length) {
assertTrue(isRedirect);
final HttpUriRequest redirect = this.getRedirect(request, response, context);
final RedirectLocations redirectLocations = (RedirectLocations) context
.getAttribute(REDIRECT_LOCATIONS);
if (redirectLocations != null)
redirectLocations.remove(redirect.getURI());
final String uriString = redirect.getURI().toString();
assertEquals(expecting[redirected++], uriString);
}
if (redirected == links.length)
return false;
return isRedirect;
}
});
}
}
}
| 1,464 |
589 | package rocks.inspectit.agent.java.sensor.method.remote.client;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import rocks.inspectit.agent.java.hooking.IHook;
import rocks.inspectit.agent.java.sensor.method.AbstractMethodSensor;
import rocks.inspectit.agent.java.tracing.core.ClientInterceptor;
import rocks.inspectit.agent.java.tracing.core.adapter.AsyncClientAdapterProvider;
import rocks.inspectit.agent.java.tracing.core.listener.IAsyncSpanContextListener;
import rocks.inspectit.agent.java.util.ReflectionCache;
/**
* Abstract class for all remote async client sensors. Subclasses must implement
* {@link #getAsyncClientAdapterProvider()} that is passed to the {@link RemoteAsyncClientHook}
* during initialization.
* <p>
* Note that all remote async client sensors class names should be added to the
* {@link rocks.inspectit.agent.java.sensor.method.invocationsequence.InvocationSequenceHook}, as we
* don't want additional invocation children to be created if remote sensor did not create any
* tracing data.
*
* @author <NAME>
*
*/
public abstract class RemoteAsyncClientSensor extends AbstractMethodSensor {
/**
* One reflection cache for all instances of all remote client sensors.
*/
protected static final ReflectionCache CACHE = new ReflectionCache();
/**
* Client interceptor.
*/
@Autowired
private ClientInterceptor clientInterceptor;
/**
* Listener for firing async spans.
*/
@Autowired
private IAsyncSpanContextListener asyncSpanContextListener;
/**
* Hook.
*/
private RemoteAsyncClientHook hook;
/**
* Sub-classes should provide the correct requestAdapter provider based on the technology and
* framework they are targeting.
*
* @return {@link AsyncClientAdapterProvider}.
*/
protected abstract AsyncClientAdapterProvider getAsyncClientAdapterProvider();
/**
* {@inheritDoc}
*/
@Override
public IHook getHook() {
return hook;
}
/**
* {@inheritDoc}
*/
@Override
protected void initHook(Map<String, Object> parameters) {
AsyncClientAdapterProvider clientAdapterProvider = getAsyncClientAdapterProvider();
hook = new RemoteAsyncClientHook(clientInterceptor, clientAdapterProvider, asyncSpanContextListener);
}
}
| 650 |
338 | /**
* @file NumericalFactor.cpp
* @brief Numerical jacobians Factor
* @author <NAME>
* @date Nov 6, 2018
*/
#include <minisam/nonlinear/NumericalFactor.h>
#include <minisam/core/Eigen.h> // traits for Eigen
#include <minisam/core/Variables.h>
namespace minisam {
/* ************************************************************************** */
void NumericalFactor::print(std::ostream& out) const {
out << "Numerical jacobians Factor ";
switch (numerical_type_) {
case NumericalJacobianType::CENTRAL: {
out << "Central";
break;
}
case NumericalJacobianType::RIDDERS3: {
out << "Ridders(3, 1)";
break;
}
case NumericalJacobianType::RIDDERS5: {
out << "Ridders(5, 1)";
break;
}
default:
break;
}
out << ", delta = " << delta_ << std::endl;
Factor::print(out);
}
/* ************************************************************************** */
std::vector<Eigen::MatrixXd> NumericalFactor::numericalJacobiansImpl_(
const Variables& values) const {
// csst values to non-const for fast error evaluation by error() without copy
// TODO: breaking constness is nasty, a better way to avoid copying?
Variables& values_nonconst = const_cast<Variables&>(values);
// calculate error from values by modifying values
auto fv = [&values_nonconst, this](const std::shared_ptr<Variable>& v,
Key k) -> Eigen::VectorXd {
// keep a copy of original value
std::shared_ptr<Variable> v_copy = values_nonconst.at(k);
values_nonconst.update(k, v); // assign new value
// get error of updated values
Eigen::VectorXd err_updated = this->error(values_nonconst);
values_nonconst.update(k, v_copy); // copy back orginal value
return err_updated;
};
std::vector<Eigen::MatrixXd> jacobians;
for (Key k : keylist_) {
jacobians.push_back(
numericalJacobian<Eigen::VectorXd, std::shared_ptr<Variable>>(
std::bind(fv, std::placeholders::_1, k), values.at(k), delta_,
numerical_type_));
}
return jacobians;
}
} // namespace minisam
| 811 |
1,607 | <reponame>tendoasan/fastdex
package fastdex.idea.models;
import com.intellij.openapi.components.*;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.Nullable;
/**
* Created by huangyong on 17/2/14.
*/
@State(
name = "FastdexConfigurationStorage",
storages = @Storage(file = "fastdex-configuration.xml", roamingType = RoamingType.DISABLED)
)
public class FastdexConfiguration implements PersistentStateComponent<FastdexConfiguration> {
@Nullable
@Override
public FastdexConfiguration getState() {
return this;
}
@Override
public void loadState(FastdexConfiguration fastdexConfiguration) {
XmlSerializerUtil.copyBean(fastdexConfiguration, this);
}
public static FastdexConfiguration getInstance() {
return ServiceManager.getService(FastdexConfiguration.class);
}
}
| 317 |
1,338 | <reponame>Kirishikesan/haiku<filename>src/apps/terminal/SmartTabView.h
/*
* Copyright 2007-2010, Haiku. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
*/
#ifndef SMART_TAB_VIEW_H
#define SMART_TAB_VIEW_H
#include <TabView.h>
class BButton;
class BPopUpMenu;
class BScrollView;
class SmartTabView : public BTabView {
public:
class Listener;
public:
SmartTabView(BRect frame, const char* name,
button_width width = B_WIDTH_AS_USUAL,
uint32 resizingMode = B_FOLLOW_ALL,
uint32 flags = B_FULL_UPDATE_ON_RESIZE
| B_WILL_DRAW | B_NAVIGABLE_JUMP
| B_FRAME_EVENTS | B_NAVIGABLE);
SmartTabView(const char* name,
button_width width = B_WIDTH_AS_USUAL,
uint32 flags = B_FULL_UPDATE_ON_RESIZE
| B_WILL_DRAW | B_NAVIGABLE_JUMP
| B_FRAME_EVENTS | B_NAVIGABLE
| B_SUPPORTS_LAYOUT);
virtual ~SmartTabView();
void SetInsets(float left, float top, float right,
float bottom);
virtual void MouseDown(BPoint where);
virtual void AttachedToWindow();
virtual void AllAttached();
virtual void Select(int32 tab);
virtual void AddTab(BView* target, BTab* tab = NULL);
virtual BTab* RemoveTab(int32 index);
void MoveTab(int32 index, int32 newIndex);
virtual BRect DrawTabs();
void SetScrollView(BScrollView* scrollView);
void SetListener(Listener* listener)
{ fListener = listener; }
private:
int32 _ClickedTabIndex(const BPoint& point);
private:
BRect fInsets;
BScrollView* fScrollView;
Listener* fListener;
BButton* fFullScreenButton;
};
class SmartTabView::Listener {
public:
virtual ~Listener();
virtual void TabSelected(SmartTabView* tabView, int32 index);
virtual void TabDoubleClicked(SmartTabView* tabView,
BPoint point, int32 index);
virtual void TabMiddleClicked(SmartTabView* tabView,
BPoint point, int32 index);
virtual void TabRightClicked(SmartTabView* tabView,
BPoint point, int32 index);
};
#endif // SMART_TAB_VIEW_H
| 969 |
586 | <gh_stars>100-1000
#import <Foundation/Foundation.h>
#import "RecursiveRelationship+CoreDataClass.h"
@class FEMMapping;
@interface RecursiveRelationship (Mapping)
+ (FEMMapping *)defaultMapping;
@end
| 76 |
892 | <gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-7jhv-xq3r-8h9q",
"modified": "2022-05-01T07:44:25Z",
"published": "2022-05-01T07:44:25Z",
"aliases": [
"CVE-2006-7066"
],
"details": "Microsoft Internet Explorer 6 on Windows XP SP2 allows remote attackers to cause a denial of service (crash) by creating an object inside an iframe, deleting the frame by setting its location.href to about:blank, then accessing a property of the object within the deleted frame, which triggers a NULL pointer dereference. NOTE: it was later reported that 7.0.6000.16473 and earlier are also affected.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2006-7066"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/28068"
},
{
"type": "WEB",
"url": "http://archives.neohapsis.com/archives/bugtraq/2009-07/0193.html"
},
{
"type": "WEB",
"url": "http://blogs.securiteam.com/index.php/archives/554"
},
{
"type": "WEB",
"url": "http://browserfun.blogspot.com/2006/07/mobb-30-orphan-object-properties.html"
},
{
"type": "WEB",
"url": "http://websecurity.com.ua/3130/"
},
{
"type": "WEB",
"url": "http://www.osvdb.org/27533"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/19228"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
} | 704 |
2,449 | <filename>deploy-service/common/src/main/java/com/pinterest/deployservice/alerts/AlertAction.java
package com.pinterest.deployservice.alerts;
import com.pinterest.deployservice.bean.DeployBean;
import com.pinterest.deployservice.bean.EnvironBean;
/**
* AlertAction is the base class for an action for an alert
*/
public abstract class AlertAction {
public abstract Object perform(AlertContext context,
EnvironBean environ,
DeployBean lastDeploy,
int actionWindowInSeconds,
String operator) throws Exception;
}
| 280 |
1,118 | <filename>vendor/rinvex/countries/resources/translations/hm.json
{"deu":{"common":"Heard und die McDonaldinseln","official":"Heard und McDonaldinseln"},"fin":{"common":"Heard ja McDonaldinsaaret","official":"Heard ja McDonaldinsaaret"},"fra":{"common":"Îles Heard-et-MacDonald","official":"Des îles Heard et McDonald"},"hrv":{"common":"Otok Heard i otočje McDonald","official":"Otok Heard i otočje McDonald"},"ita":{"common":"Isole Heard e McDonald","official":"Isole Heard e McDonald"},"jpn":{"common":"ハード島とマクドナルド諸島","official":"ハード島とマクドナルド諸島"},"nld":{"common":"Heard-en McDonaldeilanden","official":"Heard en McDonaldeilanden"},"por":{"common":"Ilha Heard e Ilhas McDonald","official":"Ilha Heard e Ilhas McDonald"},"rus":{"common":"Остров Херд и острова Макдональд","official":"Остров Херд и острова Макдональд"},"spa":{"common":"Islas Heard y McDonald","official":"Islas Heard y McDonald"}}
| 329 |
348 | <reponame>chamberone/Leaflet.PixiOverlay<filename>docs/data/leg-t1/060/06007007.json<gh_stars>100-1000
{"nom":"Agnetz","circ":"7ème circonscription","dpt":"Oise","inscrits":2424,"abs":1043,"votants":1381,"blancs":28,"nuls":7,"exp":1346,"res":[{"nuance":"LR","nom":"M. <NAME>","voix":593},{"nuance":"REM","nom":"<NAME>","voix":317},{"nuance":"FN","nom":"M. <NAME>","voix":205},{"nuance":"FI","nom":"Mme <NAME>","voix":109},{"nuance":"SOC","nom":"M. <NAME>","voix":49},{"nuance":"COM","nom":"Mme <NAME>","voix":26},{"nuance":"DVD","nom":"<NAME>","voix":17},{"nuance":"DLF","nom":"M. <NAME>","voix":12},{"nuance":"EXG","nom":"Mme <NAME>","voix":9},{"nuance":"DVD","nom":"Mme <NAME>","voix":4},{"nuance":"DVG","nom":"M. <NAME>","voix":3},{"nuance":"DIV","nom":"Mme <NAME>","voix":2}]} | 323 |
575 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_WIN_UTIL_WIN_SERVICE_H_
#define CHROME_BROWSER_WIN_UTIL_WIN_SERVICE_H_
#include "chrome/services/util_win/public/mojom/util_win.mojom.h"
#include "mojo/public/cpp/bindings/remote.h"
// Spawns a new isolated instance of the Windows utility service and returns a
// remote interface to it. The lifetime of the service process is tied strictly
// to the lifetime of the returned Remote.
mojo::Remote<chrome::mojom::UtilWin> LaunchUtilWinServiceInstance();
#endif // CHROME_BROWSER_WIN_UTIL_WIN_SERVICE_H_
| 226 |
4,339 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.security.sandbox;
import java.security.DomainCombiner;
import java.security.PermissionCollection;
import java.security.ProtectionDomain;
/**
* A {@code IgniteDomainCombiner} updates ProtectionDomains with passed {@code Permissions}.
*/
public class IgniteDomainCombiner implements DomainCombiner {
/** */
private final ProtectionDomain pd;
/** */
public IgniteDomainCombiner(PermissionCollection perms) {
pd = new ProtectionDomain(null, perms);
}
/** {@inheritDoc} */
@Override public ProtectionDomain[] combine(ProtectionDomain[] currDomains, ProtectionDomain[] assignedDomains) {
if (currDomains == null || currDomains.length == 0)
return assignedDomains;
if (assignedDomains == null || assignedDomains.length == 0)
return new ProtectionDomain[] {pd};
ProtectionDomain[] res = new ProtectionDomain[assignedDomains.length + 1];
res[0] = pd;
System.arraycopy(assignedDomains, 0, res, 1, assignedDomains.length);
return res;
}
}
| 572 |
791 | <reponame>fengjixuchui/soso
#ifndef ALLOC_H
#define ALLOC_H
#include "common.h"
#include "process.h"
void initialize_kernel_heap();
void *ksbrk_page(int n);
void *kmalloc(uint32_t size);
void kfree(void *v_addr);
void initialize_program_break(Process* process, uint32_t size);
void *sbrk(Process* process, int n_bytes);
uint32_t get_kernel_heap_used();
struct MallocHeader
{
unsigned long size:31;
unsigned long used:1;
} __attribute__ ((packed));
typedef struct MallocHeader MallocHeader;
#endif // ALLOC_H
| 201 |
8,027 | <filename>test/com/facebook/buck/testutil/TestJar.java
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.testutil;
import com.google.common.io.ByteStreams;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
public class TestJar implements Closeable {
private final JarFile jarFile;
public TestJar(File file) throws IOException {
jarFile = new JarFile(file);
}
@Override
public void close() throws IOException {
jarFile.close();
}
public List<? extends ZipEntry> getZipEntries() {
return jarFile.stream().collect(Collectors.toList());
}
public List<String> getEntriesContent() {
List<String> result = new ArrayList<>();
for (ZipEntry zipEntry : getZipEntries()) {
try (InputStream entryStream = jarFile.getInputStream(zipEntry)) {
result.add(new String(ByteStreams.toByteArray(entryStream), StandardCharsets.UTF_8));
} catch (IOException e) {
throw new AssertionError(e);
}
}
return result;
}
}
| 577 |
2,290 | <reponame>pranayhere/ftgo-application
package net.chrisrichardson.ftgo.orderservice;
import net.chrisrichardson.ftgo.common.Address;
import net.chrisrichardson.ftgo.common.Money;
import net.chrisrichardson.ftgo.orderservice.domain.MenuItem;
import net.chrisrichardson.ftgo.orderservice.domain.Restaurant;
import net.chrisrichardson.ftgo.orderservice.messaging.RestaurantEventMapper;
import net.chrisrichardson.ftgo.restaurantservice.events.Menu;
import net.chrisrichardson.ftgo.restaurantservice.events.RestaurantCreated;
import java.util.Collections;
import java.util.List;
public class RestaurantMother {
public static final String AJANTA_RESTAURANT_NAME = "Ajanta";
public static final long AJANTA_ID = 1L;
public static final String CHICKEN_VINDALOO = "Chicken Vindaloo";
public static final String CHICKEN_VINDALOO_MENU_ITEM_ID = "1";
public static final Money CHICKEN_VINDALOO_PRICE = new Money("12.34");
public static final Address RESTAURANT_ADDRESS = new Address("1 Main Street", "Unit 99", "Oakland", "CA", "94611");
public static MenuItem CHICKEN_VINDALOO_MENU_ITEM = new MenuItem(CHICKEN_VINDALOO_MENU_ITEM_ID, CHICKEN_VINDALOO, CHICKEN_VINDALOO_PRICE);
public static final List<MenuItem> AJANTA_RESTAURANT_MENU_ITEMS = Collections.singletonList(CHICKEN_VINDALOO_MENU_ITEM);
public static final Restaurant AJANTA_RESTAURANT =
new Restaurant(AJANTA_ID, AJANTA_RESTAURANT_NAME, AJANTA_RESTAURANT_MENU_ITEMS);
public static RestaurantCreated makeAjantaRestaurantCreatedEvent() {
return new RestaurantCreated().withName(AJANTA_RESTAURANT_NAME)
.withAddress(RestaurantEventMapper.fromAddress(RESTAURANT_ADDRESS))
.withMenu(new Menu().withMenuItems(RestaurantEventMapper.fromMenuItems(AJANTA_RESTAURANT_MENU_ITEMS)));
}
}
| 662 |
1,058 | // Copyright (c) 2020-2021 ByteDance, Inc.
//
// 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.
//
// Created by <NAME> (<EMAIL>) on 2020-06-02.
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <errno.h>
#include <time.h>
#include <stdarg.h>
#include <inttypes.h>
#include <android/api-level.h>
#if defined(__LP64__)
#define BH_UTIL_PRIxADDR "016"PRIxPTR
#else
#define BH_UTIL_PRIxADDR "08"PRIxPTR
#endif
#define BH_UTIL_TEMP_FAILURE_RETRY(exp) ({ \
__typeof__(exp) _rc; \
do { \
errno = 0; \
_rc = (exp); \
} while (_rc == -1 && errno == EINTR); \
_rc; })
int bh_util_set_addr_protect(void *addr, int prot);
int bh_util_set_protect(void *start, void *end, int prot);
bool bh_util_starts_with(const char *str, const char* start);
bool bh_util_ends_with(const char* str, const char* ending);
size_t bh_util_trim_ending(char *start);
int bh_util_get_api_level(void);
int bh_util_write(int fd, const char *buf, size_t buf_len);
struct tm *bh_util_localtime_r(const time_t *timep, long gmtoff, struct tm *result);
size_t bh_util_vsnprintf(char *buffer, size_t buffer_size, const char *format, va_list args);
size_t bh_util_snprintf(char *buffer, size_t buffer_size, const char *format, ...);
| 908 |
324 | <gh_stars>100-1000
from waliki.plugins import BasePlugin, register
class TogetherJsPlugin(BasePlugin):
slug = 'togetherjs'
urls_page = []
register(TogetherJsPlugin)
| 58 |
2,338 | typedef int (*debug_callee) (int);
int
no_debug_caller_intermediate(int input, debug_callee callee)
{
int return_value = 0;
return_value = callee(input);
return return_value;
}
int
no_debug_caller (int input, debug_callee callee)
{
int return_value = 0;
return_value = no_debug_caller_intermediate (input, callee);
return return_value;
}
| 134 |
5,169 | <filename>Specs/5/8/6/SOComponentPods/0.1.2/SOComponentPods.podspec.json
{
"name": "SOComponentPods",
"version": "0.1.2",
"summary": "first SOComponentPods.",
"description": "\"A short description of SOComponentPods A short description of SOComponentPods A short description of SOComponentPods\nA short description of SOComponentPods \"",
"homepage": "https://github.com/SmileOcc/SOComponentPods",
"license": "Apache License, Version 2.0",
"authors": {
"SmileOcc": "https://github.com/SmileOcc"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/SmileOcc/SOComponentPods.git",
"tag": "0.1.2"
},
"requires_arc": true,
"exclude_files": "Classes/Exclude",
"dependencies": {
"AFNetworking": [
]
},
"subspecs": [
{
"name": "NetWorkEngine",
"preserve_paths": "SOPrivatePodsDemo/SOPrivatePodsDemo/CompentLab/NetworkEngine/SOPrivateFirstLib.framework",
"vendored_frameworks": "SOPrivatePodsDemo/SOPrivatePodsDemo/CompentLab/NetworkEngine/SOPrivateFirstLib.framework"
},
{
"name": "DataModel",
"source_files": "SOPrivatePodsDemo/SOPrivatePodsDemo/CompentLab/DataModel/**/*",
"public_header_files": "SOPrivatePodsDemo/SOPrivatePodsDemo/CompentLab/DataModel/**/*.h"
},
{
"name": "CommonTools",
"source_files": "SOPrivatePodsDemo/SOPrivatePodsDemo/CompentLab/CommonTools/**/*",
"public_header_files": "SOPrivatePodsDemo/SOPrivatePodsDemo/CompentLab/CommonTools/**/*.h"
},
{
"name": "UIKitAddition"
}
]
}
| 682 |
10,225 | package org.acme;
import io.quarkus.arc.profile.IfBuildProfile;
import javax.enterprise.context.ApplicationScoped;
import org.apache.commons.io.FileUtils;
import org.apache.commons.collections4.MultiSet;
public interface HelloService {
String name();
default String classFounds() {
String result = "";
try {
result += FileUtils.class.getSimpleName();
} catch (NoClassDefFoundError e) {
result += "?";
}
result += "/";
try {
result += MultiSet.class.getSimpleName();
} catch (NoClassDefFoundError e) {
result += "?";
}
return result;
}
@IfBuildProfile("foo")
@ApplicationScoped
class HelloServiceFoo implements HelloService{
@Override
public String name() {
return "from foo";
}
}
@IfBuildProfile("bar")
@ApplicationScoped
class HelloServiceBar implements HelloService{
@Override
public String name() {
return "from bar";
}
}
}
| 467 |
9,106 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "dispatchQueue/dispatchQueue.h"
#include "future/future.h"
#include "future/futureWait.h"
#include "motifCpp/libletAwareMemLeakDetection.h"
#include "testCheck.h"
#include "testExecutor.h"
namespace FutureTests {
TEST_CLASS_EX (ExecutorTest, LibletAwareMemLeakDetection) {
// MemoryLeakDetectionHook::TrackPerTest m_trackLeakPerTest;
TEST_METHOD(ExecutorReference) {
auto queue = MakeTestDispatchQueue();
Mso::DispatchQueue &queueRef = queue;
int value = 0;
auto future = Mso::PostFuture(queueRef, [&]() noexcept { value = 5; });
Mso::FutureWait(future);
TestCheckEqual(5, value);
}
TEST_METHOD(ExecutorConstReference) {
auto queue = MakeTestDispatchQueue();
Mso::DispatchQueue const &queueRef = queue;
int value = 0;
auto future = Mso::PostFuture(queueRef, [&]() noexcept { value = 5; });
Mso::FutureWait(future);
TestCheckEqual(5, value);
}
TEST_METHOD(ThrowingExecutorTestIntValue) {
auto queue = MakeTestDispatchQueue();
auto future = Mso::PostFuture(Mso::Executors::Executor::Throwing{queue}, []() -> int {
return 5;
}).Then(queue, [&](const Mso::Maybe<int> &value) noexcept {
TestCheck(value.IsValue());
TestCheckEqual(5, value.GetValue());
});
Mso::FutureWait(future);
}
TEST_METHOD(ThrowingExecutorTestIntException) {
auto queue = MakeTestDispatchQueue();
auto future = Mso::PostFuture(Mso::Executors::Executor::Throwing{queue}, []() -> int {
throw std::exception();
}).Then(queue, [&](const Mso::Maybe<int> &value) noexcept { TestCheck(value.IsError()); });
Mso::FutureWait(future);
}
TEST_METHOD(ThrowingExecutorTestVoidValue) {
auto queue = MakeTestDispatchQueue();
auto future = Mso::PostFuture(Mso::Executors::Executor::Throwing{queue}, []() {
// We return void
}).Then(queue, [&](const Mso::Maybe<void> &value) noexcept { TestCheck(value.IsValue()); });
Mso::FutureWait(future);
}
TEST_METHOD(ThrowingExecutorTestVoidException) {
auto queue = MakeTestDispatchQueue();
auto future = Mso::PostFuture(Mso::Executors::Executor::Throwing{queue}, []() -> void {
throw std::exception();
}).Then(queue, [&](const Mso::Maybe<void> &value) noexcept { TestCheck(value.IsError()); });
Mso::FutureWait(future);
}
TEST_METHOD(DefaultExecutorPostFuture) {
int value = 0;
auto future = Mso::PostFuture([&]() noexcept { value = 5; });
Mso::FutureWait(future);
TestCheckEqual(5, value);
}
};
} // namespace FutureTests
| 1,160 |
903 | <filename>jphp-runtime/src/php/runtime/invoke/cache/PropertyCallCache.java<gh_stars>100-1000
package php.runtime.invoke.cache;
import php.runtime.reflection.PropertyEntity;
public class PropertyCallCache extends CallCache<PropertyEntity> {
@Override
public Item[] newArrayData(int length) {
return new Item[length];
}
@Override
public Item[][] newArrayArrayData(int length) {
return new Item[length][];
}
}
| 156 |
679 | <filename>main/svtools/inc/svtools/svlbitm.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 _SVLBOXITM_HXX
#define _SVLBOXITM_HXX
#include "svtools/svtdllapi.h"
#ifndef LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _IMAGE_HXX
#include <vcl/image.hxx>
#endif
#include <svtools/svlbox.hxx>
class SvLBoxEntry;
#define SV_ITEM_ID_LBOXSTRING 1
#define SV_ITEM_ID_LBOXBMP 2
#define SV_ITEM_ID_LBOXBUTTON 3
#define SV_ITEM_ID_LBOXCONTEXTBMP 4
#define SV_ITEM_ID_EXTENDRLBOXSTRING 5
enum SvButtonState { SV_BUTTON_UNCHECKED, SV_BUTTON_CHECKED, SV_BUTTON_TRISTATE };
#define SV_BMP_UNCHECKED 0
#define SV_BMP_CHECKED 1
#define SV_BMP_TRISTATE 2
#define SV_BMP_HIUNCHECKED 3
#define SV_BMP_HICHECKED 4
#define SV_BMP_HITRISTATE 5
#define SV_BMP_STATICIMAGE 6
struct SvLBoxButtonData_Impl;
class SVT_DLLPUBLIC SvLBoxButtonData
{
private:
Link aLink;
long nWidth;
long nHeight;
SvLBoxButtonData_Impl* pImpl;
sal_Bool bDataOk;
SvButtonState eState;
SVT_DLLPRIVATE void SetWidthAndHeight();
SVT_DLLPRIVATE void InitData( sal_Bool bImagesFromDefault,
bool _bRadioBtn, const Control* pControlForSettings = NULL );
public:
// include creating default images (CheckBox or RadioButton)
SvLBoxButtonData( const Control* pControlForSettings );
SvLBoxButtonData( const Control* pControlForSettings, bool _bRadioBtn );
SvLBoxButtonData();
~SvLBoxButtonData();
sal_uInt16 GetIndex( sal_uInt16 nItemState );
inline long Width();
inline long Height();
void SetLink( const Link& rLink) { aLink=rLink; }
const Link& GetLink() const { return aLink; }
sal_Bool IsRadio();
// weil Buttons nicht von LinkHdl abgeleitet sind
void CallLink();
void StoreButtonState( SvLBoxEntry* pEntry, sal_uInt16 nItemFlags );
SvButtonState ConvertToButtonState( sal_uInt16 nItemFlags ) const;
inline SvButtonState GetActButtonState() const;
SvLBoxEntry* GetActEntry() const;
Image aBmps[24]; // Indizes siehe Konstanten BMP_ ....
void SetDefaultImages( const Control* pControlForSettings = NULL );
// set images according to the color scheeme of the Control
// pControlForSettings == NULL: settings are taken from Application
sal_Bool HasDefaultImages( void ) const;
};
inline long SvLBoxButtonData::Width()
{
if ( !bDataOk )
SetWidthAndHeight();
return nWidth;
}
inline long SvLBoxButtonData::Height()
{
if ( !bDataOk )
SetWidthAndHeight();
return nHeight;
}
inline SvButtonState SvLBoxButtonData::GetActButtonState() const
{
return eState;
}
// **********************************************************************
class SVT_DLLPUBLIC SvLBoxString : public SvLBoxItem
{
XubString aStr;
public:
SvLBoxString( SvLBoxEntry*,sal_uInt16 nFlags,const XubString& rStr);
SvLBoxString();
virtual ~SvLBoxString();
virtual sal_uInt16 IsA();
void InitViewData( SvLBox*,SvLBoxEntry*,SvViewDataItem* );
XubString GetText() const { return aStr; }
virtual XubString GetExtendText() const {return XubString();}
void SetText( SvLBoxEntry*, const XubString& rStr );
void Paint( const Point&, SvLBox& rDev, sal_uInt16 nFlags,SvLBoxEntry* );
SvLBoxItem* Create() const;
void Clone( SvLBoxItem* pSource );
};
class SvLBoxBmp : public SvLBoxItem
{
Image aBmp;
public:
SvLBoxBmp( SvLBoxEntry*, sal_uInt16 nFlags, Image );
SvLBoxBmp();
virtual ~SvLBoxBmp();
virtual sal_uInt16 IsA();
void InitViewData( SvLBox*,SvLBoxEntry*,SvViewDataItem* );
void SetBitmap( SvLBoxEntry*, Image );
void Paint( const Point&, SvLBox& rView, sal_uInt16 nFlags,SvLBoxEntry* );
SvLBoxItem* Create() const;
void Clone( SvLBoxItem* pSource );
};
#define SV_ITEMSTATE_UNCHECKED 0x0001
#define SV_ITEMSTATE_CHECKED 0x0002
#define SV_ITEMSTATE_TRISTATE 0x0004
#define SV_ITEMSTATE_HILIGHTED 0x0008
#define SV_STATE_MASK 0xFFF8 // zum Loeschen von UNCHECKED,CHECKED,TRISTATE
enum SvLBoxButtonKind
{
SvLBoxButtonKind_enabledCheckbox,
SvLBoxButtonKind_disabledCheckbox,
SvLBoxButtonKind_staticImage
};
class SVT_DLLPUBLIC SvLBoxButton : public SvLBoxItem
{
SvLBoxButtonData* pData;
SvLBoxButtonKind eKind;
sal_uInt16 nItemFlags;
sal_uInt16 nImgArrOffs;
sal_uInt16 nBaseOffs;
void ImplAdjustBoxSize( Size& io_rCtrlSize, ControlType i_eType, Window* pParent );
public:
// An SvLBoxButton can be of three different kinds: an
// enabled checkbox (the normal kind), a disabled checkbox
// (which cannot be modified via UI), or a static image
// (see SV_BMP_STATICIMAGE; nFlags are effectively ignored
// for that kind).
SvLBoxButton( SvLBoxEntry* pEntry,
SvLBoxButtonKind eTheKind, sal_uInt16 nFlags,
SvLBoxButtonData* pBData );
SvLBoxButton();
virtual ~SvLBoxButton();
void InitViewData( SvLBox*,SvLBoxEntry*,SvViewDataItem* );
virtual sal_uInt16 IsA();
void Check( SvLBox* pView, SvLBoxEntry*, sal_Bool bCheck );
virtual sal_Bool ClickHdl(SvLBox* pView, SvLBoxEntry* );
void Paint( const Point&, SvLBox& rView, sal_uInt16 nFlags,SvLBoxEntry* );
SvLBoxItem* Create() const;
void Clone( SvLBoxItem* pSource );
sal_uInt16 GetButtonFlags() const { return nItemFlags; }
sal_Bool IsStateChecked() const { return (sal_Bool)(nItemFlags & SV_ITEMSTATE_CHECKED)!=0; }
sal_Bool IsStateUnchecked() const { return (sal_Bool)(nItemFlags & SV_ITEMSTATE_UNCHECKED)!=0; }
sal_Bool IsStateTristate() const { return (sal_Bool)(nItemFlags & SV_ITEMSTATE_TRISTATE)!=0; }
sal_Bool IsStateHilighted() const { return (sal_Bool)(nItemFlags & SV_ITEMSTATE_HILIGHTED)!=0; }
void SetStateChecked();
void SetStateUnchecked();
void SetStateTristate();
void SetStateHilighted( sal_Bool bHilight );
SvLBoxButtonKind GetKind() const { return eKind; }
void SetBaseOffs( sal_uInt16 nOffs ) { nBaseOffs = nOffs; }
sal_uInt16 GetBaseOffs() const { return nBaseOffs; }
// Check whether this button can be modified via UI, sounding a beep if it
// cannot be modified:
bool CheckModification() const;
SvLBoxButtonData* GetButtonData() const{ return pData;}
};
inline void SvLBoxButton::SetStateChecked()
{
nItemFlags &= SV_STATE_MASK;
nItemFlags |= SV_ITEMSTATE_CHECKED;
}
inline void SvLBoxButton::SetStateUnchecked()
{
nItemFlags &= SV_STATE_MASK;
nItemFlags |= SV_ITEMSTATE_UNCHECKED;
}
inline void SvLBoxButton::SetStateTristate()
{
nItemFlags &= SV_STATE_MASK;
nItemFlags |= SV_ITEMSTATE_TRISTATE;
}
inline void SvLBoxButton::SetStateHilighted( sal_Bool bHilight )
{
if ( bHilight )
nItemFlags |= SV_ITEMSTATE_HILIGHTED;
else
nItemFlags &= ~SV_ITEMSTATE_HILIGHTED;
}
struct SvLBoxContextBmp_Impl;
class SVT_DLLPUBLIC SvLBoxContextBmp : public SvLBoxItem
{
SvLBoxContextBmp_Impl* m_pImpl;
public:
SvLBoxContextBmp( SvLBoxEntry*,sal_uInt16 nFlags,Image,Image,
sal_uInt16 nEntryFlagsBmp1);
SvLBoxContextBmp();
virtual ~SvLBoxContextBmp();
virtual sal_uInt16 IsA();
void InitViewData( SvLBox*,SvLBoxEntry*,SvViewDataItem* );
void Paint( const Point&, SvLBox& rView, sal_uInt16 nFlags,SvLBoxEntry* );
SvLBoxItem* Create() const;
void Clone( SvLBoxItem* pSource );
sal_Bool SetModeImages( const Image& _rBitmap1, const Image& _rBitmap2, BmpColorMode _eMode = BMP_COLOR_NORMAL );
void GetModeImages( Image& _rBitmap1, Image& _rBitmap2, BmpColorMode _eMode = BMP_COLOR_NORMAL ) const;
inline void SetBitmap1( const Image& _rImage, BmpColorMode _eMode = BMP_COLOR_NORMAL );
inline void SetBitmap2( const Image& _rImage, BmpColorMode _eMode = BMP_COLOR_NORMAL );
inline const Image& GetBitmap1( BmpColorMode _eMode = BMP_COLOR_NORMAL ) const;
inline const Image& GetBitmap2( BmpColorMode _eMode = BMP_COLOR_NORMAL ) const;
private:
Image& implGetImageStore( sal_Bool _bFirst, BmpColorMode _eMode );
};
inline void SvLBoxContextBmp::SetBitmap1( const Image& _rImage, BmpColorMode _eMode )
{
implGetImageStore( sal_True, _eMode ) = _rImage;
}
inline void SvLBoxContextBmp::SetBitmap2( const Image& _rImage, BmpColorMode _eMode )
{
implGetImageStore( sal_False, _eMode ) = _rImage;
}
inline const Image& SvLBoxContextBmp::GetBitmap1( BmpColorMode _eMode ) const
{
Image& rImage = const_cast< SvLBoxContextBmp* >( this )->implGetImageStore( sal_True, _eMode );
if ( !rImage )
// fallback to the "normal" image
rImage = const_cast< SvLBoxContextBmp* >( this )->implGetImageStore( sal_True, BMP_COLOR_NORMAL );
return rImage;
}
inline const Image& SvLBoxContextBmp::GetBitmap2( BmpColorMode _eMode ) const
{
Image& rImage = const_cast< SvLBoxContextBmp* >( this )->implGetImageStore( sal_False, _eMode );
if ( !rImage )
// fallback to the "normal" image
rImage = const_cast< SvLBoxContextBmp* >( this )->implGetImageStore( sal_True, BMP_COLOR_NORMAL );
return rImage;
}
#endif
| 4,048 |
1,223 | <gh_stars>1000+
/*
Copyright 2016 Nidium Inc. All rights reserved.
Use of this source code is governed by a MIT license
that can be found in the LICENSE file.
*/
/*
/!\ this class is not thread safe
TODO: windows ('shlwapi')
http://msdn.microsoft.com/en-us/library/windows/desktop/bb773559%28v=vs.85%29.aspx
*/
#ifndef core_path_h__
#define core_path_h__
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/param.h>
#include <ape_array.h>
struct JSContext;
namespace Nidium {
namespace IO {
class Stream;
}
namespace Core {
#define MAX_REGISTERED_SCHEMES 1024
extern char *g_m_Root;
extern char *g_m_Cwd;
#define SCHEME_DEFINE(prefix, streamclass, keepprefix) \
(struct Nidium::Core::Path::schemeInfo) \
{ \
.str = prefix, \
.base = streamclass::CreateStream, \
.GetBaseDir = streamclass::GetBaseDir, \
.keepPrefix = keepprefix, \
.AllowLocalFileStream = streamclass::AllowLocalFileStream, \
.AllowSyncStream = streamclass::AllowSyncStream \
}
#define URLSCHEME_MATCH(url, scheme) \
(strcmp(Nidium::Core::Path::GetScheme(url)->str, scheme "://") == 0)
#define SCHEME_MATCH(obj, scheme) (strcmp(obj->str, scheme "://") == 0)
class Path
{
public:
struct schemeInfo
{
const char *str;
Nidium::IO::Stream *(*base)(const char *);
const char *(*GetBaseDir)();
bool keepPrefix;
bool (*AllowLocalFileStream)();
bool (*AllowSyncStream)();
};
/*
allowAll defines if origin must match "cwd" stream class (if false)
*/
explicit Path(const char *origin,
bool allowAll = false,
bool noFilter = false);
#if 0
operator const char *() {
return m_Path;
}
#endif
const char *path() const
{
return m_Path;
}
const char *dir() const
{
return m_Dir;
}
const char *host() const
{
return m_Host;
}
Nidium::IO::Stream *CreateStream(bool onlySync = false) const
{
if (!m_Scheme || !m_Path) {
return NULL;
}
if (onlySync && !m_Scheme->AllowSyncStream()) {
return NULL;
}
return m_Scheme->base(m_Path);
}
schemeInfo *GetScheme() const
{
return m_Scheme;
}
bool static HasScheme(const char *str);
bool static IsRelative(const char *path);
~Path()
{
if (m_Path) {
free(m_Path);
}
if (m_Dir) {
free(m_Dir);
}
};
static void RegisterScheme(const schemeInfo &scheme,
bool isDefault = false);
static void UnRegisterSchemes();
static schemeInfo *GetScheme(const char *url, const char **pURL = NULL);
static char *Sanitize(const char *path, bool *outsideRoot = nullptr);
static void Chroot(const char *root)
{
if (g_m_Root != NULL && root != g_m_Root) {
free(g_m_Root);
}
g_m_Root = (root != NULL ? strdup(root) : NULL);
}
static void CD(const char *dir)
{
if (g_m_Cwd != NULL && dir != g_m_Cwd) {
free(g_m_Cwd);
}
g_m_Cwd = (dir != NULL ? strdup(dir) : NULL);
}
static char *GetDir(const char *fullpath);
static const char *GetRoot()
{
return g_m_Root;
}
static const char *GetCwd()
{
return g_m_Cwd;
}
static schemeInfo *GetCwdScheme()
{
if (!g_m_Cwd) {
return NULL;
}
return GetScheme(g_m_Cwd);
}
static int g_m_SchemesCount;
static struct schemeInfo g_m_Schemes[MAX_REGISTERED_SCHEMES];
static struct schemeInfo *g_m_DefaultScheme;
static void Makedirs(const char *dirWithSlashes);
static bool InDir(const char *dir, const char *root);
private:
void parse(const char *path);
void invalidatePath();
char *m_Path;
char *m_Dir;
char *m_Host;
schemeInfo *m_Scheme;
};
} // namespace Core
} // namespace Nidium
#endif
| 2,156 |
335 | {
"word": "Baby",
"definitions": [
"Comparatively small or immature of its kind.",
"(of vegetables) picked before reaching their usual size."
],
"parts-of-speech": "Adjective"
} | 80 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-f2rp-38vg-j3gh",
"modified": "2021-03-18T23:43:39Z",
"published": "2021-03-18T23:47:56Z",
"aliases": [
"CVE-2021-21384"
],
"summary": "Null characters not escaped",
"details": "### Impact\n\nAnyone using _Shescape_ to defend against shell injection may still be vulnerable against shell injection if the attacker manages to insert a [null character](https://en.wikipedia.org/wiki/Null_character) into the payload. For example (on Windows):\n\n```javascript\nconst cp = require(\"child_process\");\nconst shescape = require(\"shescape\");\n\nconst nullChar = String.fromCharCode(0);\nconst payload = \"foo\\\" && ls -al ${nullChar} && echo \\\"bar\";\nconsole.log(cp.execSync(`echo ${shescape.quote(payload)}`));\n// foototal 3\n// drwxr-xr-x 1 owner XXXXXX 0 Mar 13 18:44 .\n// drwxr-xr-x 1 owner XXXXXX 0 Mar 13 00:09 ..\n// drwxr-xr-x 1 owner XXXXXX 0 Mar 13 18:42 folder \n// -rw-r--r-- 1 owner XXXXXX 0 Mar 13 18:42 file\n```\n\n### Patches\n\nThe problem has been patched in [v1.1.3](https://github.com/ericcornelissen/shescape/releases/tag/v1.1.3) which you can upgrade to now. No further changes are required.\n\n### Workarounds\n\nAlternatively, null characters can be stripped out manually using e.g. `arg.replace(/\\u{0}/gu, \"\")`",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:L/AC:H/PR:N/UI:R/S:C/C:L/I:H/A:N"
}
],
"affected": [
{
"package": {
"ecosystem": "npm",
"name": "shescape"
},
"ranges": [
{
"type": "ECOSYSTEM",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.3"
}
]
}
]
}
],
"references": [
{
"type": "WEB",
"url": "https://github.com/ericcornelissen/shescape/security/advisories/GHSA-f2rp-38vg-j3gh"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2021-21384"
},
{
"type": "WEB",
"url": "https://github.com/ericcornelissen/shescape/commit/07a069a66423809cbedd61d980c11ca44a29ea2b"
},
{
"type": "WEB",
"url": "https://github.com/ericcornelissen/shescape/releases/tag/v1.1.3"
},
{
"type": "WEB",
"url": "https://www.npmjs.com/package/shescape"
}
],
"database_specific": {
"cwe_ids": [
"CWE-88"
],
"severity": "HIGH",
"github_reviewed": true
}
} | 1,291 |
329 | <reponame>VasiliCekaskin/nmatrix<gh_stars>100-1000
public class MatrixGenerator
{
// Matrix from Array begin
public static float[][] getMatrixFloat(float[] array, int row, int col)
{
float[][] matrix = new float[row][col];
for (int index=0, i=0; i < row ; i++){
for (int j=0; j < col; j++){
matrix[i][j]= array[index];
index++;
}
}
return matrix;
}
public static double[][] getMatrixDouble(double[] array, int row, int col)
{
double[][] matrix = new double[row][col];
for (int index=0, i=0; i < row ; i++){
for (int j=0; j < col; j++){
matrix[i][j]= array[index];
index++;
}
}
return matrix;
}
public static float[][] getMatrixColMajorFloat(float[] array, int col, int row)
{
float[][] matrix = new float[col][row];
for (int index=0, i=0; i < col ; i++){
for (int j=0; j < row; j++){
matrix[i][j]= array[index];
index++;
}
}
return matrix;
}
// Matrix from Array end
} | 508 |
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.
// ------------------------------------------------------------
#pragma once
namespace Communication
{
namespace TcpServiceCommunication
{
class ServiceCommunicationTransport
: public Common::TextTraceComponent<Common::TraceTaskCodes::FabricTransport>
, public Common::ComponentRoot
, public Api::IServiceCommunicationTransport
{
DENY_COPY(ServiceCommunicationTransport);
public:
static Common::ErrorCode Create(ServiceCommunicationTransportSettingsUPtr && settings,
std::wstring const & address,
Api::IServiceCommunicationTransportSPtr & transport);
virtual Common::ErrorCode RegisterCommunicationListener(
Communication::TcpServiceCommunication::ServiceMethodCallDispatcherSPtr const & dispatcher,
__out std::wstring &endpointAddress);
virtual Common::AsyncOperationSPtr BeginUnregisterCommunicationListener(
std::wstring const & servicePath,
Common::AsyncCallback const & callback,
Common::AsyncOperationSPtr const & parent);
virtual Common::ErrorCode EndUnregisterCommunicationListener(
Common::AsyncOperationSPtr const & asyncOperation);
virtual Common::AsyncOperationSPtr BeginRequest(
Transport::MessageUPtr && message,
Common::TimeSpan const & timeout,
Common::AsyncCallback const & callback,
Common::AsyncOperationSPtr const & parent);
virtual Common::ErrorCode EndRequest(
Common::AsyncOperationSPtr const & operation,
Transport::MessageUPtr & reply);
virtual Common::ErrorCode SendOneWay(
Transport::MessageUPtr && message);
virtual Common::ErrorCode Open();
virtual Common::ErrorCode Close();
virtual ServiceCommunicationTransportSettings const& GetSettings();
bool IsClosed();
~ServiceCommunicationTransport();
private:
ServiceCommunicationTransport(
ServiceCommunicationTransportSettingsUPtr && securitySettings,
std::wstring const & address);
std::wstring GetServiceLocation(std::wstring const & location);
Common::ErrorCode GenerateEndpoint(std::wstring const & location, __out std::wstring & endpointAddress);
void ProcessRequest(Transport::MessageUPtr &&, Transport::ReceiverContextUPtr &&);
void OnConnectComplete(Common::AsyncOperationSPtr const & operation,
bool expectedCompletedSynchronously);
void OnDisconnectComplete(Common::AsyncOperationSPtr const & operation,
bool expectedCompletedSynchronously);
void Cleanup();
Common::ErrorCode CloseCallerHoldingLock();
bool IsClosedCallerHoldingLock();
void OnDisconnect(Transport::ISendTarget const & sendTarget);
void OnConnect(std::wstring clientId, ServiceMethodCallDispatcherSPtr dispatcher);
Transport::ISendTarget::SPtr GetSendTarget(Transport::MessageUPtr const & message);
void CallDisconnectHandlerIfExists(ServiceMethodCallDispatcherSPtr const & dispatcher,
ClientConnectionStateInfoSPtr & connectionStateInfo);
ClientConnectionStateInfoSPtr CallConnectHandlerIfItsNewClient(std::wstring const & clientId,
ServiceMethodCallDispatcherSPtr const & dispatcher,
bool newClient);
void DisconnectClients(std::vector<ClientConnectionStateInfoSPtr> clientInfo,
ServiceMethodCallDispatcherSPtr const & dispatcher);
std::wstring listenAddress_;
std::wstring traceId_;
Transport::IDatagramTransportSPtr transport_;
Transport::DemuxerUPtr demuxer_;
ServiceCommunicationMessageHandlerCollectionUPtr messageHandlerCollection_;
Transport::RequestReply requestReply_;
Common::TimeSpan defaultTimeout_;
class OnConnectAsyncOperation;
class OnDisconnectAsyncOperation;
class UnRegisterAsyncOperation;
class DisconnectClientsAsyncOperation;
class ClientTable;
std::unique_ptr<ClientTable> clientTable_;
ServiceCommunicationTransportSettingsUPtr settings_;
uint64 openListenerCount_;
bool isClosed_;
Common::RwLock lock_;
Common::RwLock clientTablelock_;
};
}
}
| 2,271 |
2,279 | <reponame>deining/stork<gh_stars>1000+
import os
import sys
import boto3
import time
if "AWS_ACCESS_KEY_ID" not in os.environ or "AWS_SECRET_ACCESS_KEY" not in os.environ:
print("Error: Environment variables `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` must be set in order to upload to AWS S3.")
exit(1)
normalized_dir = filedir = os.path.dirname(os.path.realpath(__file__))
opj = os.path.join
def uploadFile(localPath, remotePath, extraArgs={}):
print(f"Called uploadFile: {localPath} → {remotePath}")
s3 = boto3.resource('s3')
s3.Bucket("files.stork-search.net").upload_file(localPath, remotePath, ExtraArgs=extraArgs)
def invalidate():
cloudfront = boto3.client("cloudfront")
cloudfront.create_invalidation(
DistributionId="E3PBNOZP9XRSWN",
InvalidationBatch={
'Paths': {
'Quantity': 1,
'Items': [
'/*',
]
},
'CallerReference': f"{time.time()}"
}
)
if __name__ == "__main__":
web_artifacts = [
{"filename": "stork.js", "contentType": "text/javascript"},
{"filename": "stork.wasm", "contentType": "application/wasm"},
{"filename": "basic.css", "contentType": "text/css"},
{"filename": "dark.css", "contentType": "text/css"},
]
binaries = [
"stork-macos-10-15",
"stork-ubuntu-20-04",
]
other_files = [
"federalist.st"
]
ref = sys.argv[1] # We'll upload to /releases/${ref}/*
print(f"Uploading files...")
for file in web_artifacts:
for destination_path in [
opj("releases", ref, file["filename"]),
opj("releases", "latest", file["filename"]),
file["filename"]
]:
source_path = opj(normalized_dir, "..", "web-artifacts", file["filename"])
uploadFile(source_path, destination_path, {'ContentType': file["contentType"]})
for binary in binaries:
for destination_path in [
opj("releases", ref, binary),
opj("releases", "latest", binary),
]:
source_path = opj(normalized_dir, "..", binary, "stork")
uploadFile(source_path, destination_path)
for file in other_files:
for destination_path in [
opj("releases", ref, file),
opj("releases", "latest", file),
file
]:
source_path = opj(normalized_dir, "..", file)
uploadFile(source_path, destination_path)
invalidate()
print("Cache invalidated.")
print("Done. Visit https://stork-search.net")
| 1,205 |
334 | #!/usr/bin/env python
#
# // SPDX-License-Identifier: BSD-3-CLAUSE
#
# (C) Copyright 2018, Xilinx, Inc.
#
from os import mkdir as _mkdir
from os.path import exists as _exists
import caffe
from xfdnn.rt.xdnn_rt_base import xdnnRT as _xdnnRT
from xfdnn.rt.xdnn_opt import CPUTransform, HWEmuTransform, FPGATransform
from xfdnn.tools.compile.bin.xfdnn_compiler_caffe import CaffeFrontend
class CaffexdnnRT(_xdnnRT):
def __init__ (self, args, **kwargs):
self.inputs = None
self.outputs = None
super(CaffexdnnRT, self).__init__(CaffeFrontend, args, **kwargs)
def load_graph(self, args, **kwargs):
graph = caffe.Net(args.networkfile, args.weights, caffe.TEST)
self.save = args.save
if self.save and not _exists(self.save):
_mkdir(self.save)
inputs = self.inputs if self.inputs else self.list_inputs_of_graph(graph)
outputs = self.outputs if self.outputs else self.list_outputs_of_graph(graph)
return graph, inputs, outputs, True
def list_inputs_of_graph(self, graph):
res = []
for name, layer in zip(graph._layer_names, graph.layers) :
print name, layer.type
if layer.type in ['Input']:
res.append(name)
return res
def list_outputs_of_graph(self, graph):
res = []
bset = set()
for name, bottoms in graph.bottom_names.items():
for bottom in bottoms :
bset.add(bottom)
for name, tops in graph.top_names.items() :
for top in tops :
if top not in bset :
res.append(name)
return res
def extract_subgraph(self, outputs, inputs, inclusive=False, filename=None):
pass
def device_transforms(self, args):
print "DEVICE",args.device
for partition in self.graph_partitions:
time_to_layer_list = zip(partition.schedule, partition.names)
print partition.supported
if partition.supported:
if args.device == "CPU":
opt = CPUTransform(time_to_layer_list, self.layerparameter_dict, args, self._graph)
elif args.device == "HWEmu":
opt = HWEmuTransform(time_to_layer_list, self.layerparameter_dict, args, self._graph)
#raise RuntimeError('not implemented yet')
#opt = HWEmuTransform(partition.inputs, pydotGraph, compilerSchedule, args)
elif args.device == "FPGA":
if not args.fpga_recipe:
args.fpga_recipe = {'start': [time_to_layer_list[0][1]], 'end': partition.outputs}
if args.xclbin:
opt = FPGATransform(time_to_layer_list, self.layerparameter_dict, self.compilerJson, args, self._graph)
else:
raise AttributeError("Must specify path to xclbin when device = FPGA")
else:
raise AttributeError("Unsupported device type", args.device)
else:
## default back to CPU implementation
opt = CPUTransform(time_to_layer_list, self.layerparameter_dict, args, self._graph)
#variables hold the inputs/consts of graph
partition.layers = opt.getLayers()
partition.variables = opt.variables
for l in partition.layers:
l.setup()
def rebuild_graph(self):
pass
def forward_exec(self, inputs, outputs=None, preprocess=None, **kwargs):
if not outputs:
outputs = self.outputs
else:
for output in outputs:
if isinstance(output, list):
raise TypeError('outputs should be flattened list of name strings')
print outputs
if not preprocess:
preprocess = self.preprocess
res = {}
data = preprocess(inputs, **kwargs)
for partition in self.graph_partitions:
data = partition.forward_exec(data, save=self.save)
for out_name, out_val in zip(partition.outputs, data):
if out_name in outputs:
res.update({out_name: out_val})
if self.save is not None:
with open(self.save+'/layers.txt', 'w') as f:
for partition in self.graph_partitions:
for name in partition.names:
f.write('_'.join(name.split('/'))+'\n')
self.save = None
return res
| 2,006 |
7,235 | <reponame>quaff/feign
/**
* Copyright 2012-2020 The Feign Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package feign.reactive;
import feign.InvocationHandlerFactory.MethodHandler;
import feign.Target;
import java.lang.reflect.Method;
import java.util.Map;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
public class ReactorInvocationHandler extends ReactiveInvocationHandler {
private final Scheduler scheduler;
ReactorInvocationHandler(Target<?> target,
Map<Method, MethodHandler> dispatch,
Scheduler scheduler) {
super(target, dispatch);
this.scheduler = scheduler;
}
@Override
protected Publisher invoke(Method method, MethodHandler methodHandler, Object[] arguments) {
Publisher<?> invocation = this.invokeMethod(methodHandler, arguments);
if (Flux.class.isAssignableFrom(method.getReturnType())) {
return Flux.from(invocation).subscribeOn(scheduler);
} else if (Mono.class.isAssignableFrom(method.getReturnType())) {
return Mono.from(invocation).subscribeOn(scheduler);
}
throw new IllegalArgumentException(
"Return type " + method.getReturnType().getName() + " is not supported");
}
}
| 535 |
1,350 | <filename>sdk/anomalydetector/azure-ai-anomalydetector/src/main/java/com/azure/ai/anomalydetector/models/DetectRequest.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.ai.anomalydetector.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The DetectRequest model. */
@Fluent
public final class DetectRequest {
/*
* Time series data points. Points should be sorted by timestamp in
* ascending order to match the anomaly detection result. If the data is
* not sorted correctly or there is duplicated timestamp, the API will not
* work. In such case, an error message will be returned.
*/
@JsonProperty(value = "series", required = true)
private List<TimeSeriesPoint> series;
/*
* Optional argument, can be one of yearly, monthly, weekly, daily, hourly,
* minutely, secondly, microsecond or none. If granularity is not present,
* it will be none by default. If granularity is none, the timestamp
* property in time series point can be absent.
*/
@JsonProperty(value = "granularity")
private TimeGranularity granularity;
/*
* Custom Interval is used to set non-standard time interval, for example,
* if the series is 5 minutes, request can be set as
* {"granularity":"minutely", "customInterval":5}.
*/
@JsonProperty(value = "customInterval")
private Integer customInterval;
/*
* Optional argument, periodic value of a time series. If the value is null
* or does not present, the API will determine the period automatically.
*/
@JsonProperty(value = "period")
private Integer period;
/*
* Optional argument, advanced model parameter, max anomaly ratio in a time
* series.
*/
@JsonProperty(value = "maxAnomalyRatio")
private Float maxAnomalyRatio;
/*
* Optional argument, advanced model parameter, between 0-99, the lower the
* value is, the larger the margin value will be which means less anomalies
* will be accepted.
*/
@JsonProperty(value = "sensitivity")
private Integer sensitivity;
/**
* Get the series property: Time series data points. Points should be sorted by timestamp in ascending order to
* match the anomaly detection result. If the data is not sorted correctly or there is duplicated timestamp, the API
* will not work. In such case, an error message will be returned.
*
* @return the series value.
*/
public List<TimeSeriesPoint> getSeries() {
return this.series;
}
/**
* Set the series property: Time series data points. Points should be sorted by timestamp in ascending order to
* match the anomaly detection result. If the data is not sorted correctly or there is duplicated timestamp, the API
* will not work. In such case, an error message will be returned.
*
* @param series the series value to set.
* @return the DetectRequest object itself.
*/
public DetectRequest setSeries(List<TimeSeriesPoint> series) {
this.series = series;
return this;
}
/**
* Get the granularity property: Optional argument, can be one of yearly, monthly, weekly, daily, hourly, minutely,
* secondly, microsecond or none. If granularity is not present, it will be none by default. If granularity is none,
* the timestamp property in time series point can be absent.
*
* @return the granularity value.
*/
public TimeGranularity getGranularity() {
return this.granularity;
}
/**
* Set the granularity property: Optional argument, can be one of yearly, monthly, weekly, daily, hourly, minutely,
* secondly, microsecond or none. If granularity is not present, it will be none by default. If granularity is none,
* the timestamp property in time series point can be absent.
*
* @param granularity the granularity value to set.
* @return the DetectRequest object itself.
*/
public DetectRequest setGranularity(TimeGranularity granularity) {
this.granularity = granularity;
return this;
}
/**
* Get the customInterval property: Custom Interval is used to set non-standard time interval, for example, if the
* series is 5 minutes, request can be set as {"granularity":"minutely", "customInterval":5}.
*
* @return the customInterval value.
*/
public Integer getCustomInterval() {
return this.customInterval;
}
/**
* Set the customInterval property: Custom Interval is used to set non-standard time interval, for example, if the
* series is 5 minutes, request can be set as {"granularity":"minutely", "customInterval":5}.
*
* @param customInterval the customInterval value to set.
* @return the DetectRequest object itself.
*/
public DetectRequest setCustomInterval(Integer customInterval) {
this.customInterval = customInterval;
return this;
}
/**
* Get the period property: Optional argument, periodic value of a time series. If the value is null or does not
* present, the API will determine the period automatically.
*
* @return the period value.
*/
public Integer getPeriod() {
return this.period;
}
/**
* Set the period property: Optional argument, periodic value of a time series. If the value is null or does not
* present, the API will determine the period automatically.
*
* @param period the period value to set.
* @return the DetectRequest object itself.
*/
public DetectRequest setPeriod(Integer period) {
this.period = period;
return this;
}
/**
* Get the maxAnomalyRatio property: Optional argument, advanced model parameter, max anomaly ratio in a time
* series.
*
* @return the maxAnomalyRatio value.
*/
public Float getMaxAnomalyRatio() {
return this.maxAnomalyRatio;
}
/**
* Set the maxAnomalyRatio property: Optional argument, advanced model parameter, max anomaly ratio in a time
* series.
*
* @param maxAnomalyRatio the maxAnomalyRatio value to set.
* @return the DetectRequest object itself.
*/
public DetectRequest setMaxAnomalyRatio(Float maxAnomalyRatio) {
this.maxAnomalyRatio = maxAnomalyRatio;
return this;
}
/**
* Get the sensitivity property: Optional argument, advanced model parameter, between 0-99, the lower the value is,
* the larger the margin value will be which means less anomalies will be accepted.
*
* @return the sensitivity value.
*/
public Integer getSensitivity() {
return this.sensitivity;
}
/**
* Set the sensitivity property: Optional argument, advanced model parameter, between 0-99, the lower the value is,
* the larger the margin value will be which means less anomalies will be accepted.
*
* @param sensitivity the sensitivity value to set.
* @return the DetectRequest object itself.
*/
public DetectRequest setSensitivity(Integer sensitivity) {
this.sensitivity = sensitivity;
return this;
}
}
| 2,390 |
30,023 | {
"domain": "ue_smart_radio",
"name": "Logitech UE Smart Radio",
"documentation": "https://www.home-assistant.io/integrations/ue_smart_radio",
"codeowners": [],
"iot_class": "cloud_polling"
}
| 76 |
32,544 | <gh_stars>1000+
package com.baeldung.persistence.dao;
import com.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository;
@Repository
public class FooDao extends AbstractJpaDAO<Foo> implements IFooDao {
public FooDao() {
super();
setClazz(Foo.class);
}
// API
}
| 133 |
679 | <filename>main/vcl/unx/kde4/KDESalFrame.cxx
/**************************************************************
*
* 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.
*
*************************************************************/
#define Region QtXRegion
#include <QColor>
#include <QStyle>
#include <kconfig.h>
#include <kglobal.h>
#include <kmenubar.h>
#include <kconfiggroup.h>
#include <kmainwindow.h>
#include <kapplication.h>
#include <ktoolbar.h>
#undef Region
#include "KDESalFrame.hxx"
#include "KDEXLib.hxx"
#include "KDESalGraphics.hxx"
#include <tools/color.hxx>
#include <vcl/settings.hxx>
#include <vcl/font.hxx>
#include <svdata.hxx>
#include <unx/pspgraphics.h>
#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif
KDESalFrame::KDESalFrame( SalFrame* pParent, sal_uLong nState ) :
X11SalFrame( pParent, nState )
{
}
void KDESalFrame::Show( sal_Bool bVisible, sal_Bool bNoActivate )
{
if ( !GetParent() && ! (GetStyle() & SAL_FRAME_STYLE_INTRO) )
{
KDEXLib* pXLib = static_cast<KDEXLib*>(GetDisplay()->GetXLib());
pXLib->doStartup();
}
X11SalFrame::Show( bVisible, bNoActivate );
}
/** Helper function to convert colors.
*/
static Color toColor( const QColor &rColor )
{
return Color( rColor.red(), rColor.green(), rColor.blue() );
}
/** Helper function to read untranslated text entry from KConfig configuration repository.
*/
static OUString readEntryUntranslated( KConfigGroup *pGroup, const char *pKey )
{
return OUString::createFromAscii( (const char *) pGroup->readEntryUntranslated( pKey ).toAscii() );
}
#if 0
/** Helper function to read color from KConfig configuration repository.
*/
static Color readColor( KConfigGroup *pGroup, const char *pKey )
{
return toColor( pGroup->readEntry( pKey, QColor(Qt::white) ) );
}
#endif
/** Helper function to add information to Font from QFont.
Mostly grabbed from the Gtk+ vclplug (salnativewidgets-gtk.cxx).
*/
static Font toFont( const QFont &rQFont, const ::com::sun::star::lang::Locale& rLocale )
{
psp::FastPrintFontInfo aInfo;
QFontInfo qFontInfo( rQFont );
// set family name
aInfo.m_aFamilyName = String( (const char *) rQFont.family().toUtf8(), RTL_TEXTENCODING_UTF8 );
// set italic
aInfo.m_eItalic = ( qFontInfo.italic()? psp::italic::Italic: psp::italic::Upright );
// set weight
int nWeight = qFontInfo.weight();
if ( nWeight <= QFont::Light )
aInfo.m_eWeight = psp::weight::Light;
else if ( nWeight <= QFont::Normal )
aInfo.m_eWeight = psp::weight::Normal;
else if ( nWeight <= QFont::DemiBold )
aInfo.m_eWeight = psp::weight::SemiBold;
else if ( nWeight <= QFont::Bold )
aInfo.m_eWeight = psp::weight::Bold;
else
aInfo.m_eWeight = psp::weight::UltraBold;
// set width
int nStretch = rQFont.stretch();
if ( nStretch <= QFont::UltraCondensed )
aInfo.m_eWidth = psp::width::UltraCondensed;
else if ( nStretch <= QFont::ExtraCondensed )
aInfo.m_eWidth = psp::width::ExtraCondensed;
else if ( nStretch <= QFont::Condensed )
aInfo.m_eWidth = psp::width::Condensed;
else if ( nStretch <= QFont::SemiCondensed )
aInfo.m_eWidth = psp::width::SemiCondensed;
else if ( nStretch <= QFont::Unstretched )
aInfo.m_eWidth = psp::width::Normal;
else if ( nStretch <= QFont::SemiExpanded )
aInfo.m_eWidth = psp::width::SemiExpanded;
else if ( nStretch <= QFont::Expanded )
aInfo.m_eWidth = psp::width::Expanded;
else if ( nStretch <= QFont::ExtraExpanded )
aInfo.m_eWidth = psp::width::ExtraExpanded;
else
aInfo.m_eWidth = psp::width::UltraExpanded;
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "font name BEFORE system match: \"%s\"\n", OUStringToOString( aInfo.m_aFamilyName, RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
// match font to e.g. resolve "Sans"
psp::PrintFontManager::get().matchFont( aInfo, rLocale );
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "font match %s, name AFTER: \"%s\"\n",
aInfo.m_nID != 0 ? "succeeded" : "failed",
OUStringToOString( aInfo.m_aFamilyName, RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
// font height
int nPointHeight = qFontInfo.pointSize();
if ( nPointHeight <= 0 )
nPointHeight = rQFont.pointSize();
// Create the font
Font aFont( aInfo.m_aFamilyName, Size( 0, nPointHeight ) );
if( aInfo.m_eWeight != psp::weight::Unknown )
aFont.SetWeight( PspGraphics::ToFontWeight( aInfo.m_eWeight ) );
if( aInfo.m_eWidth != psp::width::Unknown )
aFont.SetWidthType( PspGraphics::ToFontWidth( aInfo.m_eWidth ) );
if( aInfo.m_eItalic != psp::italic::Unknown )
aFont.SetItalic( PspGraphics::ToFontItalic( aInfo.m_eItalic ) );
if( aInfo.m_ePitch != psp::pitch::Unknown )
aFont.SetPitch( PspGraphics::ToFontPitch( aInfo.m_ePitch ) );
return aFont;
}
/** Implementation of KDE integration's main method.
*/
void KDESalFrame::UpdateSettings( AllSettings& rSettings )
{
StyleSettings style( rSettings.GetStyleSettings() );
bool bSetTitleFont = false;
// General settings
QPalette pal = kapp->palette();
style.SetActiveColor(toColor(pal.color(QPalette::Active, QPalette::Window)));
style.SetDeactiveColor(toColor(pal.color(QPalette::Inactive, QPalette::Window)));
style.SetActiveColor2(toColor(pal.color(QPalette::Active, QPalette::Window)));
style.SetDeactiveColor2(toColor(pal.color(QPalette::Inactive, QPalette::Window)));
style.SetActiveTextColor(toColor(pal.color(QPalette::Active, QPalette::WindowText)));
style.SetDeactiveTextColor(toColor(pal.color(QPalette::Inactive, QPalette::WindowText)));
// WM settings
KConfig *pConfig = KGlobal::config().data();
if ( pConfig )
{
KConfigGroup aGroup = pConfig->group( "WM" );
const char *pKey;
pKey = "titleFont";
if ( aGroup.hasKey( pKey ) )
{
Font aFont = toFont( aGroup.readEntry( pKey, QFont() ), rSettings.GetUILocale() );
style.SetTitleFont( aFont );
bSetTitleFont = true;
}
aGroup = pConfig->group( "Icons" );
pKey = "Theme";
if ( aGroup.hasKey( pKey ) )
style.SetPreferredSymbolsStyleName( readEntryUntranslated( &aGroup, pKey ) );
//toolbar
pKey = "toolbarFont";
if ( aGroup.hasKey( pKey ) )
{
Font aFont = toFont( aGroup.readEntry( pKey, QFont() ), rSettings.GetUILocale() );
style.SetToolFont( aFont );
}
}
Color aFore = toColor( pal.color( QPalette::Active, QPalette::WindowText ) );
Color aBack = toColor( pal.color( QPalette::Active, QPalette::Window ) );
Color aText = toColor( pal.color( QPalette::Active, QPalette::Text ) );
Color aBase = toColor( pal.color( QPalette::Active, QPalette::Base ) );
Color aButn = toColor( pal.color( QPalette::Active, QPalette::ButtonText ) );
Color aMid = toColor( pal.color( QPalette::Active, QPalette::Mid ) );
Color aHigh = toColor( pal.color( QPalette::Active, QPalette::Highlight ) );
// Foreground
style.SetRadioCheckTextColor( aFore );
style.SetLabelTextColor( aFore );
style.SetInfoTextColor( aFore );
style.SetDialogTextColor( aFore );
style.SetGroupTextColor( aFore );
// Text
style.SetFieldTextColor( aText );
style.SetFieldRolloverTextColor( aText );
style.SetWindowTextColor( aText );
style.SetHelpTextColor( aText );
// Base
style.SetFieldColor( aBase );
style.SetHelpColor( aBase );
style.SetWindowColor( aBase );
style.SetActiveTabColor( aBase );
// Buttons
style.SetButtonTextColor( aButn );
style.SetButtonRolloverTextColor( aButn );
// Disable color
style.SetDisableColor( aMid );
// Workspace
style.SetWorkspaceColor( aMid );
// Background
style.Set3DColors( aBack );
style.SetFaceColor( aBack );
style.SetInactiveTabColor( aBack );
style.SetDialogColor( aBack );
if( aBack == COL_LIGHTGRAY )
style.SetCheckedColor( Color( 0xCC, 0xCC, 0xCC ) );
else
{
Color aColor2 = style.GetLightColor();
style.
SetCheckedColor( Color( (sal_uInt8)(((sal_uInt16)aBack.GetRed()+(sal_uInt16)aColor2.GetRed())/2),
(sal_uInt8)(((sal_uInt16)aBack.GetGreen()+(sal_uInt16)aColor2.GetGreen())/2),
(sal_uInt8)(((sal_uInt16)aBack.GetBlue()+(sal_uInt16)aColor2.GetBlue())/2)
) );
}
// Selection
style.SetHighlightColor( aHigh );
style.SetHighlightTextColor( toColor(pal.color( QPalette::HighlightedText)) );
// Font
Font aFont = toFont( kapp->font(), rSettings.GetUILocale() );
style.SetAppFont( aFont );
style.SetHelpFont( aFont );
if( !bSetTitleFont )
{
style.SetTitleFont( aFont );
}
style.SetFloatTitleFont( aFont );
style.SetMenuFont( aFont ); // will be changed according to pMenuBar
//style.SetToolFont( aFont ); //already set above
style.SetLabelFont( aFont );
style.SetInfoFont( aFont );
style.SetRadioCheckFont( aFont );
style.SetPushButtonFont( aFont );
style.SetFieldFont( aFont );
style.SetIconFont( aFont );
style.SetGroupFont( aFont );
int flash_time = QApplication::cursorFlashTime();
style.SetCursorBlinkTime( flash_time != 0 ? flash_time/2 : STYLE_CURSOR_NOBLINKTIME );
// Menu
style.SetSkipDisabledInMenus( TRUE );
KMenuBar* pMenuBar = new KMenuBar();
if ( pMenuBar )
{
// Color
QPalette qMenuCG = pMenuBar->palette();
// Menu text and background color, theme specific
Color aMenuFore = toColor( qMenuCG.color( QPalette::WindowText ) );
Color aMenuBack = toColor( qMenuCG.color( QPalette::Window ) );
aMenuFore = toColor( qMenuCG.color( QPalette::ButtonText ) );
aMenuBack = toColor( qMenuCG.color( QPalette::Button ) );
style.SetMenuTextColor( aMenuFore );
style.SetMenuBarTextColor( aMenuFore );
style.SetMenuColor( aMenuBack );
style.SetMenuBarColor( aMenuBack );
style.SetMenuHighlightColor( toColor ( qMenuCG.color( QPalette::Highlight ) ) );
style.SetMenuHighlightTextColor( aMenuFore );
// set special menubar higlight text color
if ( kapp->style()->inherits( "HighContrastStyle" ) )
ImplGetSVData()->maNWFData.maMenuBarHighlightTextColor = toColor( qMenuCG.color( QPalette::HighlightedText ) );
else
ImplGetSVData()->maNWFData.maMenuBarHighlightTextColor = aMenuFore;
// Font
aFont = toFont( pMenuBar->font(), rSettings.GetUILocale() );
style.SetMenuFont( aFont );
}
delete pMenuBar;
// Scroll bar size
style.SetScrollBarSize( kapp->style()->pixelMetric( QStyle::PM_ScrollBarExtent ) );
rSettings.SetStyleSettings( style );
}
void KDESalFrame::ReleaseGraphics( SalGraphics *pGraphics )
{
for( int i = 0; i < nMaxGraphics; i++ )
{
if( m_aGraphics[i].pGraphics == pGraphics )
{
m_aGraphics[i].bInUse = false;
break;
}
}
}
void KDESalFrame::updateGraphics( bool bClear )
{
Drawable aDrawable = bClear ? None : GetWindow();
for( int i = 0; i < nMaxGraphics; i++ )
{
if( m_aGraphics[i].bInUse )
m_aGraphics[i].pGraphics->SetDrawable( aDrawable, GetScreenNumber() );
}
}
KDESalFrame::~KDESalFrame()
{
}
KDESalFrame::GraphicsHolder::~GraphicsHolder()
{
delete pGraphics;
}
SalGraphics* KDESalFrame::GetGraphics()
{
if( GetWindow() )
{
for( int i = 0; i < nMaxGraphics; i++ )
{
if( ! m_aGraphics[i].bInUse )
{
m_aGraphics[i].bInUse = true;
if( ! m_aGraphics[i].pGraphics )
{
m_aGraphics[i].pGraphics = new KDESalGraphics();
m_aGraphics[i].pGraphics->Init( this, GetWindow(), GetScreenNumber() );
}
return m_aGraphics[i].pGraphics;
}
}
}
return NULL;
}
| 5,365 |
348 | <gh_stars>100-1000
{"nom":"Labastide-Paumès","circ":"8ème circonscription","dpt":"Haute-Garonne","inscrits":121,"abs":58,"votants":63,"blancs":10,"nuls":9,"exp":44,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":30},{"nuance":"SOC","nom":"<NAME>","voix":14}]} | 109 |
426 | <filename>include/carve/face_decl.hpp
// Copyright 2006-2015 <NAME> (<EMAIL>).
//
// This file is part of the Carve CSG Library (http://carve-csg.com/)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include <carve/carve.hpp>
#include <carve/aabb.hpp>
#include <carve/geom2d.hpp>
#include <carve/geom3d.hpp>
#include <carve/matrix.hpp>
#include <carve/tag.hpp>
#include <carve/vector.hpp>
#include <list>
#include <map>
#include <vector>
namespace carve {
namespace poly {
struct Object;
template <unsigned ndim>
class Vertex;
template <unsigned ndim>
class Edge;
template <unsigned ndim>
struct p2_adapt_project {
typedef carve::geom2d::P2 (*proj_t)(const carve::geom::vector<ndim>&);
proj_t proj;
p2_adapt_project(proj_t _proj) : proj(_proj) {}
carve::geom2d::P2 operator()(const carve::geom::vector<ndim>& v) const {
return proj(v);
}
carve::geom2d::P2 operator()(const carve::geom::vector<ndim>* v) const {
return proj(*v);
}
carve::geom2d::P2 operator()(const Vertex<ndim>& v) const {
return proj(v.v);
}
carve::geom2d::P2 operator()(const Vertex<ndim>* v) const {
return proj(v->v);
}
};
template <unsigned ndim>
class Face : public tagable {
public:
typedef Vertex<ndim> vertex_t;
typedef typename Vertex<ndim>::vector_t vector_t;
typedef Edge<ndim> edge_t;
typedef Object obj_t;
typedef carve::geom::aabb<ndim> aabb_t;
typedef carve::geom::plane<ndim> plane_t;
typedef carve::geom2d::P2 (*project_t)(const vector_t&);
typedef vector_t (*unproject_t)(const carve::geom2d::P2&, const plane_t&);
protected:
std::vector<const vertex_t*> vertices; // pointer into polyhedron.vertices
std::vector<const edge_t*> edges; // pointer into polyhedron.edges
project_t getProjector(bool positive_facing, int axis);
unproject_t getUnprojector(bool positive_facing, int axis);
public:
typedef typename std::vector<const vertex_t*>::iterator vertex_iter_t;
typedef
typename std::vector<const vertex_t*>::const_iterator const_vertex_iter_t;
typedef typename std::vector<const edge_t*>::iterator edge_iter_t;
typedef typename std::vector<const edge_t*>::const_iterator const_edge_iter_t;
obj_t* owner;
aabb_t aabb;
plane_t plane_eqn;
int manifold_id;
int group_id;
project_t project;
unproject_t unproject;
Face(const std::vector<const vertex_t*>& _vertices,
bool delay_recalc = false);
Face(const vertex_t* v1, const vertex_t* v2, const vertex_t* v3,
bool delay_recalc = false);
Face(const vertex_t* v1, const vertex_t* v2, const vertex_t* v3,
const vertex_t* v4, bool delay_recalc = false);
template <typename iter_t>
Face(const Face* base, iter_t vbegin, iter_t vend, bool flipped) {
init(base, vbegin, vend, flipped);
}
Face(const Face* base, const std::vector<const vertex_t*>& _vertices,
bool flipped) {
init(base, _vertices, flipped);
}
Face() {}
~Face() {}
bool recalc();
template <typename iter_t>
Face* init(const Face* base, iter_t vbegin, iter_t vend, bool flipped);
Face* init(const Face* base, const std::vector<const vertex_t*>& _vertices,
bool flipped);
template <typename iter_t>
Face* create(iter_t vbegin, iter_t vend, bool flipped) const;
Face* create(const std::vector<const vertex_t*>& _vertices,
bool flipped) const;
Face* clone(bool flipped = false) const;
void invert();
void getVertexLoop(std::vector<const vertex_t*>& loop) const;
const vertex_t*& vertex(size_t idx);
const vertex_t* vertex(size_t idx) const;
size_t nVertices() const;
vertex_iter_t vbegin() { return vertices.begin(); }
vertex_iter_t vend() { return vertices.end(); }
const_vertex_iter_t vbegin() const { return vertices.begin(); }
const_vertex_iter_t vend() const { return vertices.end(); }
std::vector<carve::geom::vector<2> > projectedVertices() const;
const edge_t*& edge(size_t idx);
const edge_t* edge(size_t idx) const;
size_t nEdges() const;
edge_iter_t ebegin() { return edges.begin(); }
edge_iter_t eend() { return edges.end(); }
const_edge_iter_t ebegin() const { return edges.begin(); }
const_edge_iter_t eend() const { return edges.end(); }
bool containsPoint(const vector_t& p) const;
bool containsPointInProjection(const vector_t& p) const;
bool simpleLineSegmentIntersection(const carve::geom::linesegment<ndim>& line,
vector_t& intersection) const;
IntersectionClass lineSegmentIntersection(
const carve::geom::linesegment<ndim>& line, vector_t& intersection) const;
vector_t centroid() const;
p2_adapt_project<ndim> projector() const {
return p2_adapt_project<ndim>(project);
}
void swap(Face<ndim>& other);
};
struct hash_face_ptr {
template <unsigned ndim>
size_t operator()(const Face<ndim>* const& f) const {
return (size_t)f;
}
};
namespace face {
template <unsigned ndim>
static inline carve::geom2d::P2 project(
const Face<ndim>* f, const typename Face<ndim>::vector_t& v) {
return f->project(v);
}
template <unsigned ndim>
static inline carve::geom2d::P2 project(
const Face<ndim>& f, const typename Face<ndim>::vector_t& v) {
return f.project(v);
}
template <unsigned ndim>
static inline typename Face<ndim>::vector_t unproject(
const Face<ndim>* f, const carve::geom2d::P2& p) {
return f->unproject(p, f->plane_eqn);
}
template <unsigned ndim>
static inline typename Face<ndim>::vector_t unproject(
const Face<ndim>& f, const carve::geom2d::P2& p) {
return f.unproject(p, f.plane_eqn);
}
} // namespace face
} // namespace poly
} // namespace carve
| 2,443 |
1,615 | <filename>MLN-iOS/Example/Pods/Headers/Public/ArgoUI/NSAttributedString+MLNUIKit.h
//
// NSAttributedString+MLNUIKit.h
//
//
// Created by MoMo on 2019/4/26.
//
#import <Foundation/Foundation.h>
@class MLNUIStyleString;
NS_ASSUME_NONNULL_BEGIN
@interface NSAttributedString (MLNUIKit)
@property (nonatomic, weak) MLNUIStyleString *luaui_styleString;
@end
NS_ASSUME_NONNULL_END
| 162 |
1,568 | <gh_stars>1000+
from __future__ import print_function
'''
Permuted multiples
Problem 52
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
'''
i = 1
while True:
if sorted(list(str(i))) == \
sorted(list(str(2*i))) == \
sorted(list(str(3*i))) == \
sorted(list(str(4*i))) == \
sorted(list(str(5*i))) == \
sorted(list(str(6*i))):
break
i += 1
print(i) | 230 |
416 | //
// GameController.h
// GameController
//
// Copyright (c) 2012 Apple Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#if TARGET_OS_IPHONE
#import <UIKit/UIViewController.h>
#else
#import <AppKit/NSViewController.h>
#endif
#import <GameController/GCExtern.h>
#import <GameController/GCColor.h>
#import <GameController/GCDeviceLight.h>
#import <GameController/GCDeviceBattery.h>
#import <GameController/GCControllerElement.h>
#import <GameController/GCControllerAxisInput.h>
#import <GameController/GCControllerButtonInput.h>
#import <GameController/GCControllerDirectionPad.h>
#import <GameController/GCControllerTouchpad.h>
#import <GameController/GCDeviceCursor.h>
#import <GameController/GCMotion.h>
#import <GameController/GCPhysicalInputProfile.h>
#import <GameController/GCInputNames.h>
#import <GameController/GCGamepad.h>
#import <GameController/GCGamepadSnapshot.h>
#import <GameController/GCExtendedGamepad.h>
#import <GameController/GCExtendedGamepadSnapshot.h>
#import <GameController/GCKeyCodes.h>
#import <GameController/GCKeyNames.h>
#import <GameController/GCKeyboardInput.h>
#import <GameController/GCMouseInput.h>
#import <GameController/GCXboxGamepad.h>
#import <GameController/GCDualShockGamepad.h>
#import <GameController/GCMicroGamepad.h>
#import <GameController/GCMicroGamepadSnapshot.h>
#import <GameController/GCDirectionalGamepad.h>
#import <GameController/GCDevice.h>
#import <GameController/GCController.h>
#import <GameController/GCKeyboard.h>
#import <GameController/GCMouse.h>
#import <GameController/GCEventViewController.h>
#import <GameController/GCDeviceHaptics.h>
| 572 |
474 | <reponame>ValuesFeng/AndroidPicturePicker<gh_stars>100-1000
package io.valuesfeng.picker.utils;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
import io.valuesfeng.picker.ImageSelectActivity;
/**
* Created by zaiyong on 2015/6/6.
*/
public class PicturePickerUtils {
private PicturePickerUtils() {
}
/**
* Obtains the selection result passed to your {@link Activity#onActivityResult(int, int, Intent)}.
*
* @param data the data.
* @return the selected {@link Uri}s.
*/
public static List<Uri> obtainResult(Intent data) {
return data.getParcelableArrayListExtra(ImageSelectActivity.EXTRA_RESULT_SELECTION);
}
public static List<String> obtainResult(ContentResolver resolver, Intent data) {
List<Uri> uris = data.getParcelableArrayListExtra(ImageSelectActivity.EXTRA_RESULT_SELECTION);
List<String> paths = new ArrayList<>();
for (Uri uri : uris) {
paths.add(PhotoMetadataUtils.getPath(resolver, uri));
}
return paths;
}
}
| 443 |
2,291 | {
"id" : 137,
"status" : "Fixed",
"summary" : "osmdroid and andnav share many sources .. AND .jar does not contains osmdroid files.",
"labels" : [ "Type-Defect", "Priority-Medium" ],
"stars" : 0,
"commentCount" : 3,
"comments" : [ {
"id" : 0,
"commenterId" : 1778308742751796674,
"content" : "First, thanks for those great libraries ! And for opensourcing andnav.\r\n\r\nThe org.andnav and org.osmdroid share many almost identical sources files.\r\nSome are just prefixed by OpenStreetMap.\r\n\r\neg: geopoint.java or mymath.java and many many more.\r\nDid i break something ?\r\n\r\n\r\nBy the way, downloading the jar file 1.10, I discovered that it was missing all osmdroid specific files. Is it normal too ?!\r\n\r\n\r\nCheers,\r\n<NAME>",
"timestamp" : 1294997378,
"attachments" : [ ]
}, {
"id" : 1,
"commenterId" : 8937367184059112911,
"content" : "The org.andnav should be deleted in the near future. See issue 130 and issue 112.\r\n\r\nThanks for submitting this issue as a reminder!\r\n\r\nThe latest jar is osmdroid-android-3.0.0.jar.\r\n\r\n",
"timestamp" : 1295000912,
"attachments" : [ ]
}, {
"id" : 2,
"commenterId" : 8937367184059112911,
"content" : "This issue was closed by revision r747.",
"timestamp" : 1295510318,
"attachments" : [ ]
} ]
} | 533 |
1,562 | //
// GADAdValue.h
// Google Mobile Ads SDK
//
// Copyright 2019 Google LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, GADAdValuePrecision) {
/// An ad value with unknown precision.
GADAdValuePrecisionUnknown = 0,
/// An ad value estimated from aggregated data.
GADAdValuePrecisionEstimated = 1,
/// A publisher-provided ad value, such as manual CPMs in a mediation group.
GADAdValuePrecisionPublisherProvided = 2,
/// The precise value paid for this ad.
GADAdValuePrecisionPrecise = 3
};
@class GADAdValue;
/// Handles ad events that are estimated to have earned money.
typedef void (^GADPaidEventHandler)(GADAdValue *_Nonnull value);
/// The monetary value earned from an ad.
@interface GADAdValue : NSObject <NSCopying>
/// The precision of the reported ad value.
@property(nonatomic, readonly) GADAdValuePrecision precision;
/// The ad's value.
@property(nonatomic, nonnull, readonly) NSDecimalNumber *value;
/// The value's currency code.
@property(nonatomic, nonnull, readonly) NSString *currencyCode;
@end
| 340 |
371 | # Copyright (c) 2020 BlenderNPR and contributors. MIT license.
import os, time
from itertools import chain
from Malt.Parameter import Parameter, Type
import bpy
from BlenderMalt import malt_path_getter, malt_path_setter
from . MaltProperties import MaltPropertyGroup
from . import MaltPipeline
def get_pipeline_graph(context):
if context is None or context.space_data is None or context.space_data.edit_tree is None:
return None
return context.space_data.edit_tree.get_pipeline_graph()
class MaltTree(bpy.types.NodeTree):
bl_label = "Malt Node Tree"
bl_icon = 'NODETREE'
@classmethod
def poll(cls, context):
return context.scene.render.engine == 'MALT'
def poll_material(self, material):
return material.malt.shader_nodes is self
graph_type: bpy.props.StringProperty(name='Type')
library_source : bpy.props.StringProperty(name="Shader Library", subtype='FILE_PATH',
set=malt_path_setter('library_source'), get=malt_path_getter('library_source'))
disable_updates : bpy.props.BoolProperty(name="Disable Updates", default=False)
malt_parameters : bpy.props.PointerProperty(type=MaltPropertyGroup)
def get_source_language(self):
return self.get_pipeline_graph().language
def get_transpiler(self):
if self.get_source_language() == 'GLSL':
return GLSLTranspiler
elif self.get_source_language() == 'Python':
return PythonTranspiler
def get_library_path(self):
if self.library_source != '':
src_path = bpy.path.abspath(self.library_source, library=self.library)
if os.path.exists(src_path):
return src_path
return None
def get_library(self):
library_path = self.get_library_path()
if library_path:
return get_libraries()[library_path]
else:
return get_empty_library()
def get_full_library(self):
#TODO: Cache
result = get_empty_library()
result['functions'].update(self.get_pipeline_graph().functions)
result['structs'].update(self.get_pipeline_graph().structs)
result['functions'].update(self.get_library()['functions'])
result['structs'].update(self.get_library()['structs'])
return result
def get_pipeline_graph(self):
bridge = MaltPipeline.get_bridge()
if bridge and self.graph_type in bridge.graphs:
return bridge.graphs[self.graph_type]
return None
def cast(self, from_type, to_type):
cast_function = f'{to_type}_from_{from_type}'
lib = self.get_full_library()
if cast_function in lib['functions']:
#TODO: If more than 1 parameter, check if they have default values
if len(lib['functions'][cast_function]['parameters']) == 1:
return cast_function
return None
def get_struct_type(self, struct_type):
lib = self.get_full_library()
if struct_type in lib['structs']:
return lib['structs'][struct_type]
return None
def get_generated_source_dir(self):
import os, tempfile
base_path = tempfile.gettempdir()
if bpy.context.blend_data.is_saved or self.library:
base_path = bpy.path.abspath('//', library=self.library)
return os.path.join(base_path,'malt-shaders')
def get_generated_source_path(self):
import os
file_prefix = 'temp'
if self.library:
file_prefix = bpy.path.basename(self.library.filepath).split('.')[0]
elif bpy.context.blend_data.is_saved:
file_prefix = bpy.path.basename(bpy.context.blend_data.filepath).split('.')[0]
pipeline_graph = self.get_pipeline_graph()
if pipeline_graph:
return os.path.join(self.get_generated_source_dir(),'{}-{}{}'.format(file_prefix, self.name, pipeline_graph.file_extension))
return None
def get_generated_source(self):
output_nodes = []
linked_nodes = []
pipeline_graph = self.get_pipeline_graph()
if pipeline_graph:
for node in self.nodes:
if isinstance(node, MaltIONode) and node.is_output:
output_nodes.append(node)
linked_nodes.append(node)
def add_node_inputs(node, list):
for input in node.inputs:
if input.is_linked:
new_node = input.links[0].from_node
if new_node not in list:
add_node_inputs(new_node, list)
list.append(new_node)
if new_node not in linked_nodes:
linked_nodes.append(new_node)
transpiler = self.get_transpiler()
def get_source(output):
nodes = []
add_node_inputs(output, nodes)
code = ''
for node in nodes:
if isinstance(node, MaltNode):
code += node.get_source_code(transpiler) + '\n'
code += output.get_source_code(transpiler)
return code
shader ={}
for output in output_nodes:
shader[output.io_type] = get_source(output)
shader['GLOBAL'] = ''
library_path = self.get_library_path()
if library_path:
shader['GLOBAL'] += '#include "{}"\n'.format(library_path)
for node in linked_nodes:
if isinstance(node, MaltNode):
shader['GLOBAL'] += node.get_source_global_parameters(transpiler)
return pipeline_graph.generate_source(shader)
def reload_nodes(self):
self.disable_updates = True
try:
for node in self.nodes:
if isinstance(node, MaltNode):
node.setup()
for node in self.nodes:
if isinstance(node, MaltNode):
node.update()
except:
import traceback
traceback.print_exc()
self.disable_updates = False
def update(self):
if self.disable_updates:
return
if self.get_pipeline_graph() is None:
return
self.disable_updates = True
try:
for link in self.links:
try:
if (link.from_socket.array_size != link.to_socket.array_size or
(link.from_socket.data_type != link.to_socket.data_type and
self.cast(link.from_socket.data_type, link.to_socket.data_type) is None)):
self.links.remove(link)
except:
pass
source = self.get_generated_source()
source_dir = self.get_generated_source_dir()
source_path = self.get_generated_source_path()
import pathlib
pathlib.Path(source_dir).mkdir(parents=True, exist_ok=True)
with open(source_path,'w') as f:
f.write(source)
from BlenderMalt import MaltMaterial
MaltMaterial.track_shader_changes()
except:
import traceback
traceback.print_exc()
self.disable_updates = False
# Force a depsgraph update.
# Otherwise these will be outddated in scene_eval
self.update_tag()
def setup_node_trees():
graphs = MaltPipeline.get_bridge().graphs
for name, graph in graphs.items():
preload_menus(graph.structs, graph.functions)
track_library_changes(force_update=True, disable_tree_updates=True)
for tree in bpy.data.node_groups:
if tree.bl_idname == 'MaltTree':
tree.reload_nodes()
tree.update()
__LIBRARIES = {}
def get_libraries():
return __LIBRARIES
def get_empty_library():
return {
'structs':{},
'functions':{},
'paths':[],
}
__TIMESTAMP = time.time()
def track_library_changes(force_update=False, disable_tree_updates=False):
if bpy.context.scene.render.engine != 'MALT' and force_update == False:
return 1
global __LIBRARIES
global __TIMESTAMP
start_time = time.time()
#purge unused libraries
new_dic = {}
for tree in bpy.data.node_groups:
if isinstance(tree, MaltTree):
src_path = tree.get_library_path()
if src_path:
if src_path in __LIBRARIES:
new_dic[src_path] = __LIBRARIES[src_path]
else:
new_dic[src_path] = None
__LIBRARIES = new_dic
needs_update = set()
for path, library in __LIBRARIES.items():
root_dir = os.path.dirname(path)
if os.path.exists(path):
if library is None:
needs_update.add(path)
else:
for sub_path in library['paths']:
sub_path = os.path.join(root_dir, sub_path)
if os.path.exists(sub_path):
# Don't track individual files granularly since macros can completely change them
if os.stat(sub_path).st_mtime > __TIMESTAMP:
needs_update.add(path)
break
if len(needs_update) > 0:
results = MaltPipeline.get_bridge().reflect_source_libraries(needs_update)
for path, reflection in results.items():
__LIBRARIES[path] = reflection
preload_menus(reflection['structs'], reflection['functions'])
if disable_tree_updates == False:
for tree in bpy.data.node_groups:
if isinstance(tree, MaltTree):
src_path = tree.get_library_path()
if src_path and src_path in needs_update:
tree.update()
__TIMESTAMP = start_time
return 0.1
__TYPE_COLORS = {}
def get_type_color(type):
if type not in __TYPE_COLORS:
import random, hashlib
seed = hashlib.sha1(type.encode('ascii')).digest()
rand = random.Random(seed)
__TYPE_COLORS[type] = (rand.random(),rand.random(),rand.random(),1.0)
return __TYPE_COLORS[type]
#TODO: Send transpiler along graph types
class SourceTranspiler():
@classmethod
def asignment(self, name, asignment):
pass
@classmethod
def declaration(self, type, size, name, initialization=None):
pass
@classmethod
def global_reference(self, node_name, parameter_name):
pass
@classmethod
def global_declaration(self, type, size, name, initialization=None):
pass
@classmethod
def parameter_reference(self, node_name, parameter_name):
pass
@classmethod
def io_parameter_reference(self, parameter_name, io_type):
return parameter_name
@classmethod
def is_instantiable_type(self, type):
return True
@classmethod
def call(self, name, parameters=[], full_statement=False):
pass
@classmethod
def result(self, result):
pass
@classmethod
def scoped(self, code):
pass
class GLSLTranspiler(SourceTranspiler):
@classmethod
def asignment(self, name, asignment):
return f'{name} = {asignment};\n'
@classmethod
def declaration(self, type, size, name, initialization=None):
array = '' if size == 0 else f'[{size}]'
asignment = f' = {initialization}' if initialization else ''
return f'{type} {name}{array}{asignment};\n'
@classmethod
def global_reference(self, node_name, parameter_name):
return f'U_0{node_name}_0_{parameter_name}'
@classmethod
def global_declaration(self, type, size, name, initialization=None):
return 'uniform ' + self.declaration(type, size, name, initialization)
@classmethod
def parameter_reference(self, node_name, parameter_name):
return f'{node_name}_0_{parameter_name}'
@classmethod
def is_instantiable_type(self, type):
return type.startswith('sampler') == False
@classmethod
def call(self, function, name, parameters=[], post_parameter_initialization = ''):
src = ''
for i, parameter in enumerate(function['parameters']):
if parameter['io'] in ['out','inout']:
initialization = parameters[i]
src_reference = self.parameter_reference(name, parameter['name'])
src += self.declaration(parameter['type'], parameter['size'], src_reference, initialization)
parameters[i] = src_reference
src += post_parameter_initialization
initialization = f'{function["name"]}({",".join(parameters)})'
if function['type'] != 'void' and self.is_instantiable_type(function['type']):
src += self.declaration(function['type'], 0, self.parameter_reference(name, 'result'), initialization)
else:
src += initialization + ';\n'
return src
@classmethod
def result(self, result):
return f'return {result};\n'
@classmethod
def scoped(self, code):
import textwrap
code = textwrap.indent(code, '\t')
return f'{{\n{code}}}\n'
class PythonTranspiler(SourceTranspiler):
@classmethod
def asignment(self, name, asignment):
return f'{name} = {asignment}\n'
@classmethod
def declaration(self, type, size, name, initialization=None):
if initialization is None: initialization = 'None'
return self.asignment(name, initialization)
@classmethod
def global_reference(self, node_name, parameter_name):
return f'PARAMETERS["{node_name}"]["{parameter_name}"]'
@classmethod
def global_declaration(self, type, size, name, initialization=None):
return ''
return self.declaration(type, size, name, initialization)
@classmethod
def parameter_reference(self, node_name, parameter_name):
return f'{node_name}_parameters["{parameter_name}"]'
@classmethod
def io_parameter_reference(self, parameter_name, io_type):
if io_type == 'out':
return f'OUT["{parameter_name}"]'
else:
return f'IN["{parameter_name}"]'
@classmethod
def call(self, function, name, parameters=[], post_parameter_initialization = ''):
src = ''
src += f'{name}_parameters = {{}}\n'
for i, parameter in enumerate(function['parameters']):
initialization = parameters[i]
if initialization is None:
initialization = 'None'
parameter_reference = self.parameter_reference(name, parameter['name'])
src += f'{parameter_reference} = {initialization}\n'
src += post_parameter_initialization
src += f'run_node("{name}", "{function["name"]}", {name}_parameters)\n'
return src
@classmethod
def result(self, result):
return f'return {result}\n'
@classmethod
def scoped(self, code):
import textwrap
code = textwrap.indent(code, '\t')
return f'if True:\n{code}'
class MaltSocket(bpy.types.NodeSocket):
bl_label = "Malt Node Socket"
def on_type_update(self, context):
self.node.on_socket_update(self)
data_type: bpy.props.StringProperty(update=on_type_update)
array_size: bpy.props.IntProperty(default=0, update=on_type_update)
default_initialization: bpy.props.StringProperty(default='')
show_in_material_panel: bpy.props.BoolProperty(default=True)
def is_instantiable_type(self):
return self.data_type.startswith('sampler') == False
def get_source_reference(self, target_type=None):
if not self.is_instantiable_type() and not self.is_output and self.get_linked() is not None:
self.get_linked().get_source_reference()
else:
reference = self.node.get_source_socket_reference(self)
if target_type and target_type != self.data_type:
cast_function = self.node.id_data.cast(self.data_type, target_type)
return f'{cast_function}({reference})'
return reference
def get_source_global_reference(self):
return self.id_data.get_transpiler().global_reference(self.node.get_source_name(), self.name)
def is_struct_member(self):
return '.' in self.name
def get_struct_socket(self):
if self.is_struct_member():
struct_socket_name = self.name.split('.')[0]
if self.is_output:
return self.node.outputs[struct_socket_name]
else:
return self.node.inputs[struct_socket_name]
return None
def get_source_initialization(self):
if self.is_linked:
return self.get_linked().get_source_reference(self.data_type)
elif self.default_initialization != '':
return self.default_initialization
elif self.is_struct_member() and (self.get_struct_socket().is_linked or self.get_struct_socket().default_initialization != ''):
return None
else:
return self.get_source_global_reference()
def get_linked(self):
def get_linked_internal(socket):
if len(socket.links) == 0:
return None
else:
link = socket.links[0]
linked = link.to_socket if socket.is_output else link.from_socket
if isinstance(linked.node, bpy.types.NodeReroute):
sockets = linked.node.inputs if linked.is_output else linked.node.outputs
if len(sockets) == 0:
return None
return get_linked_internal(sockets[0])
else:
return linked
return get_linked_internal(self)
def get_ui_label(self):
type = self.data_type
if self.array_size > 0:
type += f'[{self.array_size}]'
if self.is_output:
return f'({type}) : {self.name}'
else:
return f'{self.name} : ({type})'
def draw(self, context, layout, node, text):
if context.region.type != 'UI' or self.get_source_global_reference() == self.get_source_initialization():
text = self.get_ui_label()
node.draw_socket(context, layout, self, text)
if context.region.type == 'UI':
icon = 'HIDE_OFF' if self.show_in_material_panel else 'HIDE_ON'
layout.prop(self, 'show_in_material_panel', text='', icon=icon)
def setup_shape(self):
from Malt.Parameter import Parameter
base_type = True
try:
Parameter.from_glsl_type(self.data_type)
except:
base_type = False
array_type = self.array_size > 0
if base_type:
if array_type:
self.display_shape = 'CIRCLE_DOT'
else:
self.display_shape = 'CIRCLE'
else:
if array_type:
self.display_shape = 'SQUARE_DOT'
else:
self.display_shape = 'SQUARE'
def draw_color(self, context, node):
return get_type_color(self.data_type)
class MaltNode():
malt_parameters : bpy.props.PointerProperty(type=MaltPropertyGroup)
disable_updates : bpy.props.BoolProperty(name="Disable Updates", default=False)
first_setup : bpy.props.BoolProperty(default=True)
# Blender will trigger update callbacks even before init and update has finished
# So we use some wrappers to get a more sane behaviour
def _disable_updates_wrapper(self, function):
tree = self.id_data
tree.disable_updates = True
self.disable_updates = True
try:
function()
except:
import traceback
traceback.print_exc()
tree.disable_updates = False
self.disable_updates = False
def init(self, context):
self._disable_updates_wrapper(self.malt_init)
def setup(self, context=None):
self._disable_updates_wrapper(self.malt_setup)
self.first_setup = False
def update(self):
if self.disable_updates:
return
self._disable_updates_wrapper(self.malt_update)
def malt_init(self):
pass
def malt_setup(self):
pass
def malt_update(self):
pass
def on_socket_update(self, socket):
pass
def setup_sockets(self, inputs, outputs, expand_structs=True):
from Malt.Parameter import Parameter, Type
def _expand_structs(sockets):
result = {}
for name, dic in sockets.items():
result[name] = dic
struct_type = self.id_data.get_struct_type(dic['type'])
if struct_type:
for member in struct_type['members']:
result[f"{name}.{member['name']}"] = member
return result
if expand_structs:
inputs = _expand_structs(inputs)
outputs = _expand_structs(outputs)
def setup(current, new):
remove = []
for e in current.keys():
if e not in new:
#TODO: deactivate linked, don't delete them?
remove.append(current[e])
for e in remove:
current.remove(e)
for name, dic in new.items():
type = dic['type']
size = dic['size'] if 'size' in dic else 0
if name not in current:
current.new('MaltSocket', name)
if isinstance(type, Parameter):
current[name].data_type = type.type_string()
current[name].array_size = 0 #TODO
else:
current[name].data_type = type
current[name].array_size = size
try:
current[name].default_initialization = dic['meta']['init']
except:
current[name].default_initialization = ''
setup(self.inputs, inputs)
setup(self.outputs, outputs)
parameters = {}
for name, input in self.inputs.items():
parameter = None
if name in inputs.keys() and isinstance(inputs[name]['type'], Parameter):
parameter = inputs[name]['type']
elif input.array_size == 0:
try:
parameter = Parameter.from_glsl_type(input.data_type)
parameter.default_value = eval(inputs[name]['meta']['value'])
except:
pass
if parameter:
parameters[input.name] = parameter
self.malt_parameters.setup(parameters, skip_private=False)
self.setup_socket_shapes()
if self.first_setup:
self.setup_width()
def setup_width(self):
max_len = len(self.name)
for input in self.inputs.values():
max_len = max(max_len, len(input.get_ui_label()))
for output in self.outputs.values():
max_len = max(max_len, len(output.get_ui_label()))
#TODO: Measure actual string width
self.width = max(self.width, max_len * 10)
def get_source_name(self):
name = self.name.replace('.','_')
name = '_' + ''.join(char for char in name if char.isalnum() or char == '_')
return name.replace('__','_')
def get_source_code(self, transpiler):
if self.id_data.get_source_language() == 'GLSL':
return '/*{} not implemented*/'.format(self)
elif self.id_data.get_source_language() == 'Python':
return '# {} not implemented'.format(self)
def get_source_socket_reference(self, socket):
if self.id_data.get_source_language() == 'GLSL':
return '/*{} not implemented*/'.format(socket.name)
elif self.id_data.get_source_language() == 'Python':
return '# {} not implemented'.format(socket.name)
def sockets_to_global_parameters(self, sockets, transpiler):
code = ''
for socket in sockets:
if socket.data_type != '' and socket.get_linked() is None and socket.is_struct_member() == False:
code += transpiler.global_declaration(socket.data_type, socket.array_size, socket.get_source_global_reference())
return code
def get_source_global_parameters(self, transpiler):
return self.sockets_to_global_parameters(self.inputs, transpiler)
def setup_socket_shapes(self):
for socket in chain(self.inputs.values(), self.outputs.values()):
socket.setup_shape()
def draw_socket(self, context, layout, socket, text):
layout.label(text=text)
if socket.is_output == False and socket.is_linked == False and socket.default_initialization == '':
if socket.is_struct_member() and (socket.get_struct_socket().is_linked or socket.get_struct_socket().default_initialization != ''):
return
self.malt_parameters.draw_parameter(layout, socket.name, None, is_node_socket=True)
@classmethod
def poll(cls, ntree):
return ntree.bl_idname == 'MaltTree'
def draw_label(self):
return self.name
class MaltStructNode(bpy.types.Node, MaltNode):
bl_label = "Struct Node"
def malt_setup(self, context=None):
if self.first_setup:
self.name = self.struct_type
inputs = {}
inputs[self.struct_type] = {'type' : self.struct_type}
outputs = {}
outputs[self.struct_type] = {'type' : self.struct_type}
self.setup_sockets(inputs, outputs)
struct_type : bpy.props.StringProperty(update=MaltNode.setup)
def get_struct(self):
graph = self.id_data.get_pipeline_graph()
if self.struct_type in graph.structs:
return graph.structs[self.struct_type]
else:
return self.id_data.get_library()['structs'][self.struct_type]
def get_source_socket_reference(self, socket):
if socket.name == self.struct_type:
return self.get_source_name()
else:
return socket.name.replace(self.struct_type, self.get_source_name())
def struct_input_is_linked(self):
return self.inputs[self.struct_type].get_linked() is not None
def get_source_code(self, transpiler):
code = ''
for input in self.inputs:
initialization = input.get_source_initialization()
if input.is_struct_member():
if initialization:
code += transpiler.asignment(input.get_source_reference(), initialization)
else:
code += transpiler.declaration(input.data_type, 0, self.get_source_name(), initialization)
return code
class MaltFunctionNode(bpy.types.Node, MaltNode):
bl_label = "Function Node"
def malt_setup(self):
function = self.get_function()
if self.first_setup:
self.name = function['name']
inputs = {}
outputs = {}
if function['type'] != 'void':
outputs['result'] = {'type': function['type']} #TODO: Array return type
for parameter in function['parameters']:
if parameter['io'] in ['out','inout']:
outputs[parameter['name']] = parameter
if parameter['io'] in ['','in','inout']:
inputs[parameter['name']] = parameter
self.setup_sockets(inputs, outputs)
function_type : bpy.props.StringProperty(update=MaltNode.setup)
def get_function(self):
graph = self.id_data.get_pipeline_graph()
if self.function_type in graph.functions:
return graph.functions[self.function_type]
else:
return self.id_data.get_library()['functions'][self.function_type]
def get_source_socket_reference(self, socket):
transpiler = self.id_data.get_transpiler()
if transpiler.is_instantiable_type(socket.data_type):
return transpiler.parameter_reference(self.get_source_name(), socket.name)
else:
source = self.get_source_code(transpiler)
return source.splitlines()[-1].split('=')[-1].split(';')[0]
def get_source_code(self, transpiler):
function = self.get_function()
source_name = self.get_source_name()
post_parameter_initialization = ''
for input in self.inputs:
if input.is_struct_member():
initialization = input.get_source_initialization()
if initialization:
post_parameter_initialization += transpiler.asignment(input.get_source_reference(), initialization)
parameters = []
for parameter in function['parameters']:
initialization = None
if parameter['io'] in ['','in','inout']:
socket = self.inputs[parameter['name']]
initialization = socket.get_source_initialization()
parameters.append(initialization)
return transpiler.call(function, source_name, parameters, post_parameter_initialization)
class MaltIONode(bpy.types.Node, MaltNode):
bl_label = "IO Node"
properties: bpy.props.PointerProperty(type=MaltPropertyGroup)
is_output: bpy.props.BoolProperty()
def malt_setup(self):
function = self.get_function()
if self.first_setup:
self.name = self.io_type + (' Output' if self.is_output else ' Input')
inputs = {}
outputs = {}
if function['type'] != 'void' and self.is_output:
inputs['result'] = {'type': function['type']}
for parameter in function['parameters']:
if parameter['io'] in ['out','inout'] and self.is_output:
if parameter['io'] == 'inout':
if 'meta' not in parameter: parameter['meta'] = {}
parameter['meta']['init'] = parameter['name']
inputs[parameter['name']] = parameter
if parameter['io'] in ['','in','inout'] and self.is_output == False:
outputs[parameter['name']] = parameter
self.setup_sockets(inputs, outputs)
io_type : bpy.props.StringProperty(update=MaltNode.setup)
def get_function(self):
graph = self.id_data.get_pipeline_graph()
return graph.graph_IO[self.io_type]
def get_source_socket_reference(self, socket):
io = 'out' if self.is_output else 'in'
return self.id_data.get_transpiler().io_parameter_reference(socket.name, io)
def get_source_code(self, transpiler):
code = ''
if self.is_output:
function = self.get_function()
for socket in self.inputs:
if socket.name == 'result':
code += transpiler.declaration(socket.data_type, socket.array_size, socket.name)
initialization = socket.get_source_initialization()
if initialization:
code += transpiler.asignment(socket.get_source_reference(), initialization)
if function['type'] != 'void':
code += transpiler.result(self.inputs['result'].get_source_reference())
return code
class MaltInlineNode(bpy.types.Node, MaltNode):
bl_label = "Inline Code Node"
def code_update(self, context):
#update the node tree
self.id_data.update()
code : bpy.props.StringProperty(update=code_update)
def on_socket_update(self, socket):
self.update()
self.id_data.update()
def malt_init(self):
self.setup()
def malt_setup(self):
if self.first_setup:
self.name = 'Inline Code'
self.malt_update()
def malt_update(self):
last = 0
for i, input in enumerate(self.inputs):
if input.data_type != '' or input.get_linked():
last = i + 1
variables = 'abcdefgh'[:min(last+1,8)]
inputs = {}
for var in variables:
inputs[var] = {'type': ''}
if var in self.inputs:
input = self.inputs[var]
linked = self.inputs[var].get_linked()
if linked and linked.data_type != '':
inputs[var] = {'type': linked.data_type, 'size': linked.array_size}
else:
inputs[var] = {'type': input.data_type, 'size': input.array_size}
outputs = { 'result' : {'type': ''} }
if 'result' in self.outputs:
out = self.outputs['result'].get_linked()
if out:
outputs['result'] = {'type': out.data_type, 'size': out.array_size}
self.setup_sockets(inputs, outputs)
def draw_buttons(self, context, layout):
layout.prop(self, 'code', text='')
def draw_socket(self, context, layout, socket, text):
if socket.is_output == False:
layout = layout.split(factor=0.66)
row = layout.row(align=True).split(factor=0.1)
row.alignment = 'LEFT'
MaltNode.draw_socket(self, context, row, socket, socket.name)
layout.prop(socket, 'data_type', text='')
else:
MaltNode.draw_socket(self, context, layout, socket, socket.name)
def get_source_socket_reference(self, socket):
return '{}_0_{}'.format(self.get_source_name(), socket.name)
def get_source_code(self, transpiler):
code = ''
result_socket = self.outputs['result']
code += transpiler.declaration(result_socket.data_type, result_socket.array_size, result_socket.get_source_reference())
scoped_code = ''
for input in self.inputs:
if input.data_type != '':
initialization = input.get_source_initialization()
scoped_code += transpiler.declaration(input.data_type, input.array_size, input.name, initialization)
if self.code != '':
scoped_code += transpiler.asignment(self.outputs['result'].get_source_reference(), self.code)
return code + transpiler.scoped(scoped_code)
class MaltArrayIndexNode(bpy.types.Node, MaltNode):
bl_label = "Array Index Node"
def malt_init(self):
self.setup()
def malt_setup(self):
if self.first_setup:
self.name = 'Array Index'
self.setup_sockets({ 'array' : {'type': '', 'size': 1}, 'index' : {'type': Parameter(0, Type.INT) }},
{'element' : {'type': ''} })
def malt_update(self):
inputs = {
'array' : {'type': '', 'size': 1},
'index' : {'type': Parameter(0, Type.INT) }
}
outputs = { 'element' : {'type': ''} }
linked = self.inputs['array'].get_linked()
if linked and linked.array_size > 0:
inputs['array']['type'] = linked.data_type
inputs['array']['size'] = linked.array_size
outputs['element']['type'] = linked.data_type
self.setup_sockets(inputs, outputs)
def get_source_socket_reference(self, socket):
return '{}_0_{}'.format(self.get_source_name(), socket.name)
def get_source_code(self, transpiler):
array = self.inputs['array']
index = self.inputs['index']
element = self.outputs['element']
element_reference = index.get_source_global_reference()
if index.get_linked():
element_reference = index.get_linked().get_source_reference()
initialization = '{}[{}]'.format(array.get_linked().get_source_reference(), element_reference)
return transpiler.declaration(element.data_type, element.array_size, element.get_source_reference(), initialization)
class NODE_PT_MaltNodeTree(bpy.types.Panel):
bl_space_type = 'NODE_EDITOR'
bl_region_type = 'UI'
bl_category = "Malt Nodes"
bl_label = "Malt Node Tree UI"
@classmethod
def poll(cls, context):
return context.space_data.tree_type == 'MaltTree'
def draw(self, context):
layout = self.layout
#layout.prop(context.space_data.node_tree, 'generated_source')
def preload_menus(structs, functions):
files = set()
for name, struct in structs.items():
files.add(struct['file'])
for file in files:
get_structs_menu(file)
files = set()
for name, function in functions.items():
files.add(function['file'])
for file in files:
get_functions_menu(file)
def insert_node(layout, type, label, settings = {}):
operator = layout.operator("node.add_node", text=label)
operator.type = type
operator.use_transform = True
for name, value in settings.items():
item = operator.settings.add()
item.name = name
item.value = value
return operator
__FUNCTION_MENUES = {}
def get_functions_menu(file):
global __FUNCTION_MENUES
if file not in __FUNCTION_MENUES.keys():
file_to_label = file.replace('\\', '/').replace('/', ' - ').replace('.glsl', '').replace('_',' ')
class_name = 'MALT_MT_functions_' + str(len(__FUNCTION_MENUES))
def draw(self, context):
graph = get_pipeline_graph(context)
if graph:
library_functions = context.space_data.node_tree.get_library()['functions']
for name, function in chain(graph.functions.items(), library_functions.items()):
if function['file'] == file:
insert_node(self.layout, "MaltFunctionNode", name.replace('_', ' '), settings={
'function_type' : repr(name)
})
menu_type = type(class_name, (bpy.types.Menu,), {
"bl_space_type": 'NODE_EDITOR',
"bl_label": file_to_label,
"draw": draw,
})
bpy.utils.register_class(menu_type)
__FUNCTION_MENUES[file] = class_name
return __FUNCTION_MENUES[file]
__STRUCT_MENUES = {}
def get_structs_menu(file):
global __STRUCT_MENUES
if file not in __STRUCT_MENUES:
file_to_label = file.replace('\\', '/').replace('/', ' - ').replace('.glsl', '').replace('_',' ')
class_name = 'MALT_MT_structs_' + str(len(__STRUCT_MENUES))
def draw(self, context):
graph = get_pipeline_graph(context)
if graph:
library_structs = context.space_data.node_tree.get_library()['structs']
for name, struct in chain(graph.structs.items(), library_structs.items()):
if struct['file'] == file:
insert_node(self.layout, "MaltStructNode", name.replace('_', ' '), settings={
'struct_type' : repr(name)
})
menu_type = type(class_name, (bpy.types.Menu,), {
"bl_space_type": 'NODE_EDITOR',
"bl_label": file_to_label,
"draw": draw,
})
bpy.utils.register_class(menu_type)
__STRUCT_MENUES[file] = class_name
return __STRUCT_MENUES[file]
class MALT_MT_NodeFunctions(bpy.types.Menu):
bl_label = "Malt Node Functions Menu"
def draw(self, context):
graph = get_pipeline_graph(context)
if graph:
files = set()
library_functions = context.space_data.node_tree.get_library()['functions']
for name, function in chain(library_functions.items(), graph.functions.items()):
files.add(function['file'])
for file in sorted(files):
self.layout.menu(get_functions_menu(file))
class MALT_MT_NodeStructs(bpy.types.Menu):
bl_label = "Malt Node Structs Menu"
def draw(self, context):
graph = get_pipeline_graph(context)
if graph:
files = set()
library_structs = context.space_data.node_tree.get_library()['structs']
for name, struct in chain(library_structs.items(), graph.structs.items()):
files.add(struct['file'])
for file in sorted(files):
self.layout.menu(get_structs_menu(file))
class MALT_MT_NodeInputs(bpy.types.Menu):
bl_label = "Malt Node Inputs Menu"
def draw(self, context):
graph = get_pipeline_graph(context)
if graph:
for name in sorted(graph.graph_IO):
insert_node(self.layout, "MaltIONode", name + ' Input', settings={
'is_output' : repr(False),
'io_type' : repr(name),
})
class MALT_MT_NodeOutputs(bpy.types.Menu):
bl_label = "Malt Node Outputs Menu"
def draw(self, context):
graph = get_pipeline_graph(context)
if graph:
for name in sorted(graph.graph_IO):
insert_node(self.layout, "MaltIONode", name + ' Ouput', settings={
'is_output' : repr(True),
'io_type' : repr(name),
})
class MALT_MT_NodeOther(bpy.types.Menu):
bl_label = "Malt Node Other Menu"
def draw(self, context):
graph = get_pipeline_graph(context)
if graph:
insert_node(self.layout, "MaltInlineNode", 'Inline Code')
insert_node(self.layout, "MaltArrayIndexNode", 'Array Index')
def add_node_ui(self, context):
if context.space_data.tree_type != 'MaltTree':
return
if context.space_data.node_tree is None:
self.layout.label(text='No active node tree')
return
if context.space_data.node_tree.graph_type == '':
self.layout.label(text='No graph type selected')
return
graph = get_pipeline_graph(context)
if graph:
self.layout.menu("MALT_MT_NodeFunctions", text='Functions')
self.layout.menu("MALT_MT_NodeStructs", text='Structs')
self.layout.menu("MALT_MT_NodeInputs", text='Inputs')
self.layout.menu("MALT_MT_NodeOutputs", text='Outputs')
self.layout.menu("MALT_MT_NodeOther", text='Other')
def node_header_ui(self, context):
if context.space_data.tree_type != 'MaltTree' or context.space_data.node_tree is None:
return
#self.layout.use_property_split=True
#self.layout.alignment = 'LEFT'
self.layout.prop(context.space_data.node_tree, 'library_source',text='')
self.layout.prop_search(context.space_data.node_tree, 'graph_type', context.scene.world.malt, 'graph_types',text='')
#self.layout.prop(context.space_data.node_tree, 'edit_material',text='')
classes = (
MaltTree,
NODE_PT_MaltNodeTree,
MaltSocket,
#MaltNode,
MaltStructNode,
MaltFunctionNode,
MaltIONode,
MaltInlineNode,
MaltArrayIndexNode,
MALT_MT_NodeFunctions,
MALT_MT_NodeStructs,
MALT_MT_NodeInputs,
MALT_MT_NodeOutputs,
MALT_MT_NodeOther,
)
def register():
for _class in classes: bpy.utils.register_class(_class)
bpy.types.NODE_MT_add.append(add_node_ui)
bpy.types.NODE_HT_header.append(node_header_ui)
bpy.app.timers.register(track_library_changes, persistent=True)
def unregister():
bpy.types.NODE_MT_add.remove(add_node_ui)
bpy.types.NODE_HT_header.remove(node_header_ui)
for _class in reversed(classes): bpy.utils.unregister_class(_class)
bpy.app.timers.unregister(track_library_changes)
| 20,142 |
348 | {"nom":"Créteil","circ":"1ère circonscription","dpt":"Val-de-Marne","inscrits":13626,"abs":7849,"votants":5777,"blancs":588,"nuls":168,"exp":5021,"res":[{"nuance":"REM","nom":"M. <NAME>","voix":3095},{"nuance":"LR","nom":"M. <NAME>","voix":1926}]} | 102 |
32,544 | <filename>gradle-5/java-exec/src/main/java/com/baeldung/gradle/exec/MainClass.java
package com.baeldung.gradle.exec;
public class MainClass {
public static void main(String[] args) {
System.out.println("Goodbye cruel world ...");
}
}
| 97 |
856 | //
// Copyright © 2019 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "RefDepthToSpaceWorkload.hpp"
#include "DepthToSpace.hpp"
#include "RefWorkloadUtils.hpp"
namespace armnn
{
void RefDepthToSpaceWorkload::Execute() const
{
Execute(m_Data.m_Inputs, m_Data.m_Outputs);
}
void RefDepthToSpaceWorkload::ExecuteAsync(WorkingMemDescriptor &workingMemDescriptor)
{
Execute(workingMemDescriptor.m_Inputs, workingMemDescriptor.m_Outputs);
}
void RefDepthToSpaceWorkload::Execute(std::vector<ITensorHandle*> inputs, std::vector<ITensorHandle*> outputs) const
{
ARMNN_SCOPED_PROFILING_EVENT(Compute::CpuRef, "RefDepthToSpaceWorkload_Execute");
const TensorInfo inputInfo = GetTensorInfo(inputs[0]);
DepthToSpace(inputInfo,
m_Data.m_Parameters,
inputs[0]->Map(),
outputs[0]->Map(),
GetDataTypeSize(inputInfo.GetDataType()));
}
} // namespace armnn
| 396 |
30,023 | """Test reproduce state for Input text."""
from homeassistant.core import State
from homeassistant.helpers.state import async_reproduce_state
from homeassistant.setup import async_setup_component
VALID_TEXT1 = "Test text"
VALID_TEXT2 = "LoremIpsum"
INVALID_TEXT1 = "This text is too long!"
INVALID_TEXT2 = "Short"
async def test_reproducing_states(hass, caplog):
"""Test reproducing Input text states."""
# Setup entity for testing
assert await async_setup_component(
hass,
"input_text",
{
"input_text": {
"test_text": {"min": "6", "max": "10", "initial": VALID_TEXT1}
}
},
)
# These calls should do nothing as entities already in desired state
await async_reproduce_state(
hass,
[
State("input_text.test_text", VALID_TEXT1),
# Should not raise
State("input_text.non_existing", VALID_TEXT1),
],
)
# Test that entity is in desired state
assert hass.states.get("input_text.test_text").state == VALID_TEXT1
# Try reproducing with different state
await async_reproduce_state(
hass,
[
State("input_text.test_text", VALID_TEXT2),
# Should not raise
State("input_text.non_existing", VALID_TEXT2),
],
)
# Test that the state was changed
assert hass.states.get("input_text.test_text").state == VALID_TEXT2
# Test setting state to invalid state (length too long)
await async_reproduce_state(hass, [State("input_text.test_text", INVALID_TEXT1)])
# The entity state should be unchanged
assert hass.states.get("input_text.test_text").state == VALID_TEXT2
# Test setting state to invalid state (length too short)
await async_reproduce_state(hass, [State("input_text.test_text", INVALID_TEXT2)])
# The entity state should be unchanged
assert hass.states.get("input_text.test_text").state == VALID_TEXT2
| 795 |
1,350 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.storage.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;
/** Encryption identity for the storage account. */
@Fluent
public class EncryptionIdentity {
@JsonIgnore private final ClientLogger logger = new ClientLogger(EncryptionIdentity.class);
/*
* Resource identifier of the UserAssigned identity to be associated with
* server-side encryption on the storage account.
*/
@JsonProperty(value = "userAssignedIdentity")
private String encryptionUserAssignedIdentity;
/**
* Get the encryptionUserAssignedIdentity property: Resource identifier of the UserAssigned identity to be
* associated with server-side encryption on the storage account.
*
* @return the encryptionUserAssignedIdentity value.
*/
public String encryptionUserAssignedIdentity() {
return this.encryptionUserAssignedIdentity;
}
/**
* Set the encryptionUserAssignedIdentity property: Resource identifier of the UserAssigned identity to be
* associated with server-side encryption on the storage account.
*
* @param encryptionUserAssignedIdentity the encryptionUserAssignedIdentity value to set.
* @return the EncryptionIdentity object itself.
*/
public EncryptionIdentity withEncryptionUserAssignedIdentity(String encryptionUserAssignedIdentity) {
this.encryptionUserAssignedIdentity = encryptionUserAssignedIdentity;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| 605 |
2,146 | #include <lcms2.h>
int main() {
}
| 18 |
1,276 | <reponame>parallel101/course
#include <set>
#include <unordered_set>
#include "printer.h"
using namespace std;
int main() {
set<int> a = {1, 4, 2, 8, 5, 7};
unordered_set<int> b = {1, 4, 2, 8, 5, 7};
cout << "set: " << a << endl;
cout << "unordered_set: " << b << endl;
return 0;
}
| 140 |
32,544 | <reponame>DBatOWL/tutorials<filename>core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetOperationsUnitTest.java
package com.baeldung.set;
import static org.junit.Assert.*;
import org.apache.commons.collections4.SetUtils;
import org.junit.Test;
import com.google.common.collect.Sets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SetOperationsUnitTest {
private Set<Integer> setA = setOf(1,2,3,4);
private Set<Integer> setB = setOf(2,4,6,8);
private static Set<Integer> setOf(Integer... values) {
return new HashSet<Integer>(Arrays.asList(values));
}
@Test
public void givenTwoSets_WhenWeRetainAll_ThenWeIntersectThem() {
Set<Integer> intersectSet = new HashSet<>(setA);
intersectSet.retainAll(setB);
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoSets_WhenWeAddAll_ThenWeUnionThem() {
Set<Integer> unionSet = new HashSet<>(setA);
unionSet.addAll(setB);
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
@Test
public void givenTwoSets_WhenRemoveAll_ThenWeGetTheDifference() {
Set<Integer> differenceSet = new HashSet<>(setA);
differenceSet.removeAll(setB);
assertEquals(setOf(1,3), differenceSet);
}
@Test
public void givenTwoStreams_WhenWeFilterThem_ThenWeCanGetTheIntersect() {
Set<Integer> intersectSet = setA.stream()
.filter(setB::contains)
.collect(Collectors.toSet());
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoStreams_WhenWeConcatThem_ThenWeGetTheUnion() {
Set<Integer> unionSet = Stream.concat(setA.stream(), setB.stream())
.collect(Collectors.toSet());
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
@Test
public void givenTwoStreams_WhenWeFilterThem_ThenWeCanGetTheDifference() {
Set<Integer> differenceSet = setA.stream()
.filter(val -> !setB.contains(val))
.collect(Collectors.toSet());
assertEquals(setOf(1,3), differenceSet);
}
@Test
public void givenTwoSets_WhenWeUseApacheCommonsIntersect_ThenWeGetTheIntersect() {
Set<Integer> intersectSet = SetUtils.intersection(setA, setB);
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoSets_WhenWeUseApacheCommonsUnion_ThenWeGetTheUnion() {
Set<Integer> unionSet = SetUtils.union(setA, setB);
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
@Test
public void givenTwoSets_WhenWeUseGuavaIntersect_ThenWeGetTheIntersect() {
Set<Integer> intersectSet = Sets.intersection(setA, setB);
assertEquals(setOf(2,4), intersectSet);
}
@Test
public void givenTwoSets_WhenWeUseGuavaUnion_ThenWeGetTheUnion() {
Set<Integer> unionSet = Sets.union(setA, setB);
assertEquals(setOf(1,2,3,4,6,8), unionSet);
}
}
| 1,356 |
544 | <filename>Data/include/Poco/Data/AutoTransaction.h
//
// AutoTransaction.h
//
// Library: Data
// Package: DataCore
// Module: AutoTransaction
//
// Forward header for the Transaction class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Data_AutoTransaction_INCLUDED
#define Data_AutoTransaction_INCLUDED
#include "Poco/Data/Transaction.h"
namespace Poco {
namespace Data {
typedef Transaction AutoTransaction;
} } // namespace Poco::Data
#endif // Data_AutoTransaction_INCLUDED
| 187 |
321 | <filename>src/App/Editor/InspectorRegistry.cpp
#include <Utopia/App/Editor/InspectorRegistry.h>
#include <UECS/CmptType.h>
#include <unordered_map>
#include <functional>
using namespace Ubpa::Utopia;
struct InspectorRegistry::Impl {
Visitor<void(void*, InspectContext)> inspector;
};
InspectorRegistry::InspectorRegistry() : pImpl{ new Impl } {}
InspectorRegistry::~InspectorRegistry() { delete pImpl; }
void InspectorRegistry::RegisterCmpt(UECS::CmptType type, std::function<void(void*, InspectContext)> cmptInspectFunc) {
pImpl->inspector.Register(type.HashCode(), std::move(cmptInspectFunc));
}
void InspectorRegistry::RegisterAsset(const std::type_info& typeinfo, std::function<void(void*, InspectContext)> assetInspectFunc) {
pImpl->inspector.Register(typeinfo.hash_code(), std::move(assetInspectFunc));
}
bool InspectorRegistry::IsRegisteredCmpt(UECS::CmptType type) const {
return pImpl->inspector.IsRegistered(type.HashCode());
}
bool InspectorRegistry::IsRegisteredAsset(const std::type_info& typeinfo) const {
return pImpl->inspector.IsRegistered(typeinfo.hash_code());
}
void InspectorRegistry::Inspect(const UECS::World* world, UECS::CmptPtr cmpt) {
pImpl->inspector.Visit(cmpt.Type().HashCode(), cmpt.Ptr(), InspectContext{ world, pImpl->inspector });
}
void InspectorRegistry::Inspect(const std::type_info& typeinfo, void* asset) {
pImpl->inspector.Visit(typeinfo.hash_code(), asset, InspectContext{ nullptr, pImpl->inspector });
}
| 506 |
335 | <gh_stars>100-1000
{
"word": "Wilderness",
"definitions": [
"An uncultivated, uninhabited, and inhospitable region.",
"A neglected or abandoned area.",
"A position of disfavour, especially in a political context."
],
"parts-of-speech": "Noun"
} | 113 |
682 | #pragma once
#include <string>
#include <vector>
#include "tatum/TimingGraphFwd.hpp"
#include "tatum/util/tatum_range.hpp"
namespace tatum {
/**
* TimingAnalyzer represents an abstract interface for all timing analyzers,
* which can be:
* - updated (update_timing())
* - reset (reset_timing()).
*
* This is the most abstract interface provided (it does not allow access
* to any calculated data). As a result this interface is suitable for
* code that needs to update timing analysis, but does not *use* the
* analysis results itself.
*
* If you need the analysis results you should be using one of the dervied
* classes.
*
* \see SetupTimingAnalyzer
* \see HoldTimingAnalyzer
* \see SetupHoldTimingAnalyzer
*/
class TimingAnalyzer {
public:
typedef tatum::util::Range<std::vector<NodeId>::const_iterator> node_range;
public:
virtual ~TimingAnalyzer() {}
///Perform timing analysis to update timing information (i.e. arrival & required times)
void update_timing() { update_timing_impl(); }
///Invalidates the specified edge in the timing graph (for incremental updates)
void invalidate_edge(const EdgeId edge) { invalidate_edge_impl(edge); }
///Returns the set of nodes which were modified by the last call to update_timing()
node_range modified_nodes() const { return modified_nodes_impl(); }
double get_profiling_data(std::string key) const { return get_profiling_data_impl(key); }
virtual size_t num_unconstrained_startpoints() const { return num_unconstrained_startpoints_impl(); }
virtual size_t num_unconstrained_endpoints() const { return num_unconstrained_endpoints_impl(); }
protected:
virtual void update_timing_impl() = 0;
virtual void invalidate_edge_impl(const EdgeId edge) = 0;
virtual node_range modified_nodes_impl() const = 0;
virtual double get_profiling_data_impl(std::string key) const = 0;
virtual size_t num_unconstrained_startpoints_impl() const = 0;
virtual size_t num_unconstrained_endpoints_impl() const = 0;
};
} //namepsace
| 725 |
14,668 | <reponame>zealoussnow/chromium
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_MEDIA_WEBRTC_DESKTOP_MEDIA_PICKER_FACTORY_H_
#define CHROME_BROWSER_MEDIA_WEBRTC_DESKTOP_MEDIA_PICKER_FACTORY_H_
#include <memory>
#include <vector>
#include "base/callback_forward.h"
#include "chrome/browser/media/webrtc/desktop_media_list.h"
#include "chrome/browser/media/webrtc/desktop_media_picker.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/media_stream_request.h"
#include "content/public/browser/web_contents.h"
// Interface for factory creating DesktopMediaList and DesktopMediaPicker
// instances.
class DesktopMediaPickerFactory {
public:
DesktopMediaPickerFactory(const DesktopMediaPickerFactory&) = delete;
DesktopMediaPickerFactory& operator=(const DesktopMediaPickerFactory&) =
delete;
virtual ~DesktopMediaPickerFactory();
virtual std::unique_ptr<DesktopMediaPicker> CreatePicker(
const content::MediaStreamRequest* request) = 0;
virtual std::vector<std::unique_ptr<DesktopMediaList>> CreateMediaList(
const std::vector<DesktopMediaList::Type>& types,
content::WebContents* web_contents,
DesktopMediaList::WebContentsFilter includable_web_contents_filter) = 0;
protected:
DesktopMediaPickerFactory();
};
#endif // CHROME_BROWSER_MEDIA_WEBRTC_DESKTOP_MEDIA_PICKER_FACTORY_H_
| 504 |
1,482 | x = None # type: List[str, a]
y = None # type: Dict[int, Any] # int
x : source.python
: source.python
= : keyword.operator.assignment.python, source.python
: source.python
None : constant.language.python, source.python
: source.python
# : comment.line.number-sign.python, meta.typehint.comment.python, source.python
type: : comment.line.number-sign.python, comment.typehint.directive.notation.python, meta.typehint.comment.python, source.python
: comment.line.number-sign.python, meta.typehint.comment.python, source.python
List : comment.line.number-sign.python, comment.typehint.type.notation.python, meta.typehint.comment.python, source.python
[ : comment.line.number-sign.python, comment.typehint.punctuation.notation.python, meta.typehint.comment.python, source.python
str : comment.line.number-sign.python, comment.typehint.type.notation.python, meta.typehint.comment.python, source.python
, : comment.line.number-sign.python, comment.typehint.punctuation.notation.python, meta.typehint.comment.python, source.python
: comment.line.number-sign.python, meta.typehint.comment.python, source.python
a : comment.line.number-sign.python, comment.typehint.variable.notation.python, meta.typehint.comment.python, source.python
] : comment.line.number-sign.python, comment.typehint.punctuation.notation.python, meta.typehint.comment.python, source.python
y : source.python
: source.python
= : keyword.operator.assignment.python, source.python
: source.python
None : constant.language.python, source.python
: source.python
# : comment.line.number-sign.python, meta.typehint.comment.python, source.python
type: : comment.line.number-sign.python, comment.typehint.directive.notation.python, meta.typehint.comment.python, source.python
: comment.line.number-sign.python, meta.typehint.comment.python, source.python
Dict : comment.line.number-sign.python, comment.typehint.type.notation.python, meta.typehint.comment.python, source.python
[ : comment.line.number-sign.python, comment.typehint.punctuation.notation.python, meta.typehint.comment.python, source.python
int : comment.line.number-sign.python, comment.typehint.type.notation.python, meta.typehint.comment.python, source.python
, : comment.line.number-sign.python, comment.typehint.punctuation.notation.python, meta.typehint.comment.python, source.python
: comment.line.number-sign.python, meta.typehint.comment.python, source.python
Any : comment.line.number-sign.python, comment.typehint.type.notation.python, meta.typehint.comment.python, source.python
] : comment.line.number-sign.python, comment.typehint.punctuation.notation.python, meta.typehint.comment.python, source.python
: comment.line.number-sign.python, meta.typehint.comment.python, source.python
# : comment.line.number-sign.python, punctuation.definition.comment.python, source.python
int : comment.line.number-sign.python, source.python
| 1,296 |
386 | /*
This file is a part of
QVGE - Qt Visual Graph Editor
(c) 2016-2020 <NAME> (<EMAIL>)
It can be used freely, maintaining the information above.
*/
#pragma once
#include <QtCore/QString>
class CEditorScene;
/**
Common interface to file format serializers.
*/
class IFileSerializer
{
public:
virtual QString description() const = 0;
virtual QString filters() const = 0;
virtual QString defaultFileExtension() const = 0;
virtual bool loadSupported() const = 0;
virtual bool load(const QString& fileName, CEditorScene& scene, QString* lastError = nullptr) const = 0;
virtual bool saveSupported() const = 0;
virtual bool save(const QString& fileName, CEditorScene& scene, QString* lastError = nullptr) const = 0;
};
| 224 |
517 | <gh_stars>100-1000
package com.groupon.seleniumgridextras.tasks;
import com.google.gson.JsonObject;
import com.groupon.seleniumgridextras.config.RuntimeConfig;
import com.groupon.seleniumgridextras.tasks.config.TaskDescriptions;
import com.groupon.seleniumgridextras.utilities.FileIOUtility;
import com.groupon.seleniumgridextras.utilities.json.JsonCodec;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import java.io.File;
import java.util.Map;
/**
* Created with IntelliJ IDEA. User: dima Date: 7/2/14 Time: 10:41 AM To change this template use
* File | Settings | File Templates.
*/
public class UpdateNodeConfig extends ExecuteOSTask {
private static Logger logger = Logger.getLogger(UpdateNodeConfig.class);
public UpdateNodeConfig() {
setEndpoint(TaskDescriptions.Endpoints.UPDATE_NODE_CONFIG);
setDescription(TaskDescriptions.Description.UPDATE_NODE_CONFIG);
JsonObject params = new JsonObject();
setAcceptedParams(params);
params.addProperty(JsonCodec.WebDriver.Grid.NODE,
"(Required) - Name of the node who's config needs to be updated");
params.addProperty(JsonCodec.Config.FILENAME, "(Required) - Name of the config to be update");
params.addProperty(JsonCodec.Config.CONTENT, "(Required) - Base64 encoded string of content");
setRequestType("GET");
setResponseType("json");
setClassname(this.getClass().getCanonicalName().toString());
setCssClass("btn-success");
setButtonText(TaskDescriptions.UI.ButtonText.UPDATE_NODE_CONFIG);
setEnabledInGui(true);
getJsonResponse()
.addKeyDescriptions(JsonCodec.WebDriver.Grid.NODE, "Node for which config was updated");
getJsonResponse()
.addKeyDescriptions(JsonCodec.Config.FILENAME, "Name of the config file updated");
}
@Override
public JsonObject execute() {
getJsonResponse()
.addKeyValues(JsonCodec.ERROR, "node, filename, content are required parameters");
return getJsonResponse().getJson();
}
@Override
public JsonObject execute(Map<String, String> parameter) {
if (parameter.isEmpty() || !parameter.containsKey(JsonCodec.WebDriver.Grid.NODE) || !parameter
.containsKey(
JsonCodec.Config.FILENAME)
|| !parameter.containsKey(JsonCodec.Config.CONTENT)) {
return execute();
} else {
byte[] decodedBytes = Base64.decodeBase64(parameter.get(JsonCodec.Config.CONTENT));
final String decodedString = new String(decodedBytes);
logger.info(decodedString);
final String node = parameter.get(JsonCodec.WebDriver.Grid.NODE);
final
File filename =
new File(
RuntimeConfig.getConfig().getConfigsDirectory() + RuntimeConfig.getOS()
.getFileSeparator() + node + RuntimeConfig
.getOS().getFileSeparator() + parameter
.get(JsonCodec.Config.FILENAME));
createNodeDirIfNotExisting(filename);
logger.info(
"Update to node '" + node + "' file '" + filename.getAbsolutePath() + " was called");
logger.debug(decodedString);
try {
FileIOUtility.writePrettyJsonToFile(filename, decodedString);
getJsonResponse().addKeyValues(JsonCodec.WebDriver.Grid.NODE, node);
getJsonResponse().addKeyValues(JsonCodec.Config.FILENAME, filename.getAbsolutePath());
} catch (Exception error) {
logger.warn(error.toString());
getJsonResponse().addKeyValues(JsonCodec.ERROR, error.toString());
}
return getJsonResponse().getJson();
}
}
protected void createNodeDirIfNotExisting(File node) {
createConfigsDirIfNotExisting(RuntimeConfig.getConfig().getConfigsDirectory());
if (!node.getParentFile().exists()) {
logger.info("Node's config dir didn't exist so we will create it");
node.getParentFile().mkdir();
}
}
protected void createConfigsDirIfNotExisting(File config) {
if (!config.exists()) {
logger.info("Configs dir didn't exist so we will create it");
config.mkdir();
}
}
}
| 1,544 |
1,337 | /*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.haulmont.cuba.gui;
import com.haulmont.bali.util.Preconditions;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.config.WindowInfo;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.gui.screen.OpenMode;
import com.haulmont.cuba.gui.screen.Screen;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Map;
/**
* Legacy window manager.
*
* @deprecated Use {@link Screens}, {@link Dialogs} and {@link Notifications} APIs instead.
*/
@Deprecated
public interface WindowManager extends Screens {
/**
* Constant that is passed to {@link Window#close(String)} and {@link Window#close(String, boolean)} methods when
* the screen is closed by window manager. Propagated to {@link Window.CloseListener#windowClosed}.
*/
String MAIN_MENU_ACTION_ID = "mainMenu";
/**
* How to open a screen: {@link #NEW_TAB}, {@link #THIS_TAB}, {@link #DIALOG}, {@link #NEW_WINDOW}.
* <br>
* You can set additional parameters for window using builder style methods:
* <pre>
* openEditor("sales$Customer.edit", customer,
* OpenType.DIALOG.width(300).resizable(false), params);
* </pre>
*/
final class OpenType {
/**
* Open a screen in new tab of the main window.
* <br> In Web Client with {@code AppWindow.Mode.SINGLE} the new screen replaces current screen.
*/
public static final OpenType NEW_TAB = new OpenType(OpenMode.NEW_TAB, false);
/**
* Open a screen on top of the current tab screens stack.
*/
public static final OpenType THIS_TAB = new OpenType(OpenMode.THIS_TAB, false);
/**
* Open a screen as modal dialog.
*/
public static final OpenType DIALOG = new OpenType(OpenMode.DIALOG, false);
/**
* In Desktop Client open a screen in new main window, in Web Client the same as new {@link #NEW_TAB}
*/
public static final OpenType NEW_WINDOW = new OpenType(OpenMode.NEW_WINDOW, false);
private OpenMode openMode;
private boolean mutable = true;
private Float width;
private SizeUnit widthUnit;
private Float height;
private SizeUnit heightUnit;
private Integer positionX;
private Integer positionY;
private Boolean resizable;
private Boolean closeable;
private Boolean modal;
private Boolean closeOnClickOutside;
private Boolean maximized;
public OpenType(OpenMode openMode) {
this.openMode = openMode;
}
private OpenType(OpenMode openMode, boolean mutable) {
this.openMode = openMode;
this.mutable = mutable;
}
public OpenMode getOpenMode() {
return openMode;
}
public OpenType setOpenMode(OpenMode openMode) {
OpenType instance = getMutableInstance();
instance.openMode = openMode;
return instance;
}
public SizeUnit getHeightUnit() {
return heightUnit;
}
public OpenType setHeightUnit(SizeUnit heightUnit) {
OpenType instance = getMutableInstance();
instance.heightUnit = heightUnit;
return instance;
}
public Float getHeight() {
return height;
}
/**
* @deprecated Use {@link #height(Float)} instead.
*/
@Deprecated
public OpenType height(Integer height) {
return height(height.floatValue());
}
/**
* @deprecated Use {@link #setHeight(Float)} instead.
*/
@Deprecated
public OpenType setHeight(Integer height) {
return setHeight(height.floatValue());
}
public OpenType height(Float height) {
OpenType instance = getMutableInstance();
instance.height = height;
return instance;
}
public OpenType setHeight(Float height) {
OpenType instance = getMutableInstance();
instance.height = height;
return instance;
}
public OpenType height(String height) {
return setHeight(height);
}
public OpenType setHeight(String height) {
OpenType instance = getMutableInstance();
SizeWithUnit size = SizeWithUnit.parseStringSize(height);
instance.height = size.getSize();
instance.heightUnit = size.getUnit();
return instance;
}
public OpenType heightAuto() {
OpenType instance = getMutableInstance();
instance.height = -1.0f;
instance.heightUnit = SizeUnit.PIXELS;
return instance;
}
@Nullable
public String getHeightString() {
if (height == null) {
return null;
}
return height + (heightUnit != null ? heightUnit.getSymbol() : "px");
}
public SizeUnit getWidthUnit() {
return widthUnit;
}
public OpenType setWidthUnit(SizeUnit widthUnit) {
OpenType instance = getMutableInstance();
instance.widthUnit = widthUnit;
return instance;
}
public Float getWidth() {
return width;
}
@Nullable
public String getWidthString() {
if (width == null) {
return null;
}
return width + (widthUnit != null ? widthUnit.getSymbol() : "px");
}
/**
* @deprecated Use {@link #width(Float)} instead.
*/
@Deprecated
public OpenType width(Integer width) {
return width(width.floatValue());
}
/**
* @deprecated Use {@link #setWidth(Float)} instead.
*/
@Deprecated
public OpenType setWidth(Integer width) {
return setWidth(width.floatValue());
}
public OpenType width(Float width) {
OpenType instance = getMutableInstance();
instance.width = width;
return instance;
}
public OpenType setWidth(Float width) {
OpenType instance = getMutableInstance();
instance.width = width;
return instance;
}
public OpenType width(String width) {
return setWidth(width);
}
public OpenType setWidth(String width) {
OpenType instance = getMutableInstance();
SizeWithUnit size = SizeWithUnit.parseStringSize(width);
instance.width = size.getSize();
instance.widthUnit = size.getUnit();
return instance;
}
public OpenType widthAuto() {
OpenType instance = getMutableInstance();
instance.width = -1.0f;
instance.widthUnit = SizeUnit.PIXELS;
return instance;
}
public Integer getPositionX() {
return positionX;
}
public OpenType setPositionX(Integer positionX) {
OpenType instance = getMutableInstance();
instance.positionX = positionX;
return instance;
}
public OpenType positionX(Integer positionX) {
OpenType instance = getMutableInstance();
instance.positionX = positionX;
return instance;
}
public Integer getPositionY() {
return positionY;
}
public OpenType setPositionY(Integer positionY) {
OpenType instance = getMutableInstance();
instance.positionY = positionY;
return instance;
}
public OpenType positionY(Integer positionY) {
OpenType instance = getMutableInstance();
instance.positionY = positionY;
return instance;
}
public OpenType center() {
OpenType instance = getMutableInstance();
instance.positionX = null;
instance.positionY = null;
return instance;
}
public Boolean getResizable() {
return resizable;
}
public OpenType setResizable(Boolean resizable) {
OpenType instance = getMutableInstance();
instance.resizable = resizable;
return instance;
}
public OpenType resizable(Boolean resizable) {
OpenType instance = getMutableInstance();
instance.resizable = resizable;
return instance;
}
public Boolean getCloseable() {
return closeable;
}
public OpenType closeable(Boolean closeable) {
OpenType instance = getMutableInstance();
instance.closeable = closeable;
return instance;
}
public OpenType setCloseable(Boolean closeable) {
OpenType instance = getMutableInstance();
instance.closeable = closeable;
return instance;
}
public Boolean getModal() {
return modal;
}
public OpenType modal(Boolean modal) {
OpenType instance = getMutableInstance();
instance.modal = modal;
return instance;
}
public OpenType setModal(Boolean modal) {
OpenType instance = getMutableInstance();
instance.modal = modal;
return instance;
}
/**
* @return true if a window can be closed by click on outside window area
*/
public Boolean getCloseOnClickOutside() {
return closeOnClickOutside;
}
/**
* Set closeOnClickOutside to true if a window should be closed by click on outside window area.
* It works when a window has a modal mode.
*/
public OpenType closeOnClickOutside(Boolean closeOnClickOutside) {
OpenType instance = getMutableInstance();
instance.closeOnClickOutside = closeOnClickOutside;
return instance;
}
/**
* Set closeOnClickOutside to true if a window should be closed by click on outside window area.
* It works when a window has a modal mode.
*/
public OpenType setCloseOnClickOutside(Boolean closeOnClickOutside) {
OpenType instance = getMutableInstance();
instance.closeOnClickOutside = closeOnClickOutside;
return instance;
}
/**
* @return true if a window is maximized across the screen.
*/
public Boolean getMaximized() {
return maximized;
}
/**
* Set maximized to true if a window should be maximized across the screen.
*/
public OpenType maximized(Boolean maximized) {
OpenType instance = getMutableInstance();
instance.maximized = maximized;
return instance;
}
/**
* Set maximized to true if a window should be maximized across the screen.
*/
public OpenType setMaximized(Boolean maximized) {
OpenType instance = getMutableInstance();
instance.maximized = maximized;
return instance;
}
private OpenType getMutableInstance() {
if (!mutable) {
return copy();
}
return this;
}
public static OpenType valueOf(String openTypeString) {
Preconditions.checkNotNullArgument(openTypeString, "openTypeString should not be null");
switch (openTypeString) {
case "NEW_TAB":
return NEW_TAB;
case "THIS_TAB":
return THIS_TAB;
case "DIALOG":
return DIALOG;
case "NEW_WINDOW":
return NEW_WINDOW;
default:
throw new IllegalArgumentException("Unable to parse OpenType");
}
}
public OpenType copy() {
OpenType openType = new OpenType(openMode);
openType.setModal(modal);
openType.setResizable(resizable);
openType.setCloseable(closeable);
openType.setHeight(height);
openType.setHeightUnit(heightUnit);
openType.setWidth(width);
openType.setWidthUnit(widthUnit);
openType.setCloseOnClickOutside(closeOnClickOutside);
openType.setMaximized(maximized);
openType.setPositionX(positionX);
openType.setPositionY(positionY);
return openType;
}
}
/**
* @deprecated Use {@link Screens#getOpenedScreens()} instead.
*/
@Deprecated
Collection<Window> getOpenWindows();
/**
* Select tab with window in main tabsheet.
*
* @deprecated Use {@link Screens#getOpenedScreens()} and {@link WindowStack#select()} instead.
*/
@Deprecated
void selectWindowTab(Window window);
/**
* @deprecated Please use {@link Window#setCaption(String)} ()} and {@link Window#setDescription(String)} ()} methods.
*/
@Deprecated
default void setWindowCaption(Window window, String caption, String description) {
window.setCaption(caption);
window.setDescription(description);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Deprecated
Window openWindow(WindowInfo windowInfo, OpenType openType, Map<String, Object> params);
@Deprecated
Window openWindow(WindowInfo windowInfo, OpenType openType);
@Deprecated
Window.Editor openEditor(WindowInfo windowInfo, Entity item, OpenType openType,
Datasource parentDs);
@Deprecated
Window.Editor openEditor(WindowInfo windowInfo, Entity item, OpenType openType);
@Deprecated
Window.Editor openEditor(WindowInfo windowInfo, Entity item, OpenType openType, Map<String, Object> params);
@Deprecated
Window.Editor openEditor(WindowInfo windowInfo, Entity item,
OpenType openType, Map<String, Object> params,
Datasource parentDs);
// used only for legacy screens
Screen createEditor(WindowInfo windowInfo, Entity item, OpenType openType, Map<String, Object> params);
@Deprecated
Window.Lookup openLookup(WindowInfo windowInfo, Window.Lookup.Handler handler,
OpenType openType, Map<String, Object> params);
@Deprecated
Window.Lookup openLookup(WindowInfo windowInfo, Window.Lookup.Handler handler, OpenType openType);
@Deprecated
Frame openFrame(Frame parentFrame, Component parent, WindowInfo windowInfo);
@Deprecated
Frame openFrame(Frame parentFrame, Component parent, WindowInfo windowInfo, Map<String, Object> params);
@Deprecated
Frame openFrame(Frame parentFrame, Component parent, @Nullable String id,
WindowInfo windowInfo, Map<String, Object> params);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Deprecated
default void close(Window window) {
remove(window.getFrameOwner());
}
/**
* Opens default screen. Implemented only for the web module.
* <p>
* Default screen can be defined with the {@code cuba.web.defaultScreenId} application property.
*/
@Deprecated
default void openDefaultScreen() {
// todo move to ScreenTools bean
}
/**
* Show notification with {@link Frame.NotificationType#HUMANIZED}. <br>
* Supports line breaks ({@code \n}).
*
* @param caption text
*/
@Deprecated
void showNotification(String caption);
/**
* Show notification. <br>
* Supports line breaks ({@code \n}).
*
* @param caption text
* @param type defines how to display the notification.
* Don't forget to escape data from the database in case of {@code *_HTML} types!
*/
@Deprecated
void showNotification(String caption, Frame.NotificationType type);
/**
* Show notification with caption description. <br>
* Supports line breaks ({@code \n}).
*
* @param caption caption
* @param description text
* @param type defines how to display the notification.
* Don't forget to escape data from the database in case of {@code *_HTML} types!
*/
@Deprecated
void showNotification(String caption, String description, Frame.NotificationType type);
/**
* Show message dialog with title and message. <br>
* Supports line breaks ({@code \n}) for non HTML messageType.
*
* @param title dialog title
* @param message text
* @param messageType defines how to display the dialog.
* Don't forget to escape data from the database in case of {@code *_HTML} types!
*/
@Deprecated
void showMessageDialog(String title, String message, Frame.MessageType messageType);
/**
* Show options dialog with title and message. <br>
* Supports line breaks ({@code \n}) for non HTML messageType.
*
* @param title dialog title
* @param message text
* @param messageType defines how to display the dialog.
* Don't forget to escape data from the database in case of {@code *_HTML} types!
* @param actions available actions
*/
@Deprecated
void showOptionDialog(String title, String message, Frame.MessageType messageType, Action[] actions);
/**
* Shows exception dialog with default caption, message and displays stacktrace of given throwable.
*
* @param throwable throwable
*/
@Deprecated
void showExceptionDialog(Throwable throwable);
/**
* Shows exception dialog with given caption, message and displays stacktrace of given throwable.
*
* @param throwable throwable
* @param caption dialog caption
* @param message dialog message
*/
@Deprecated
void showExceptionDialog(Throwable throwable, @Nullable String caption, @Nullable String message);
/**
* Open a web page in browser.
* <br>
* It is recommended to use {@link WebBrowserTools} instead.
*
* @param url URL of the page
* @param params optional parameters.
* <br>The following parameters are recognized by Web client:
* <ul>
* <li>{@code target} - String value used as the target name in a
* window.open call in the client. This means that special values such as
* "_blank", "_self", "_top", "_parent" have special meaning. If not specified, "_blank" is used.</li>
* <li> {@code width} - Integer value specifying the width of the browser window in pixels</li>
* <li> {@code height} - Integer value specifying the height of the browser window in pixels</li>
* <li> {@code border} - String value specifying the border style of the window of the browser window.
* Possible values are "DEFAULT", "MINIMAL", "NONE".</li>
* </ul>
* Desktop client doesn't support any parameters and just ignores them.
* @see WebBrowserTools#showWebPage(String, Map)
*/
@Deprecated
void showWebPage(String url, @Nullable Map<String, Object> params);
} | 8,383 |
5,823 | <gh_stars>1000+
// Copyright 2013 The Flutter 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 FLUTTER_FML_MAPPING_H_
#define FLUTTER_FML_MAPPING_H_
#include <initializer_list>
#include <memory>
#include <string>
#include <vector>
#include "flutter/fml/build_config.h"
#include "flutter/fml/file.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/native_library.h"
#include "flutter/fml/unique_fd.h"
namespace fml {
class Mapping {
public:
Mapping();
virtual ~Mapping();
virtual size_t GetSize() const = 0;
virtual const uint8_t* GetMapping() const = 0;
// Whether calling madvise(DONTNEED) on the mapping is non-destructive.
// Generally true for file-mapped memory and false for anonymous memory.
virtual bool IsDontNeedSafe() const = 0;
private:
FML_DISALLOW_COPY_AND_ASSIGN(Mapping);
};
class FileMapping final : public Mapping {
public:
enum class Protection {
kRead,
kWrite,
kExecute,
};
explicit FileMapping(const fml::UniqueFD& fd,
std::initializer_list<Protection> protection = {
Protection::kRead});
~FileMapping() override;
static std::unique_ptr<FileMapping> CreateReadOnly(const std::string& path);
static std::unique_ptr<FileMapping> CreateReadOnly(
const fml::UniqueFD& base_fd,
const std::string& sub_path = "");
static std::unique_ptr<FileMapping> CreateReadExecute(
const std::string& path);
static std::unique_ptr<FileMapping> CreateReadExecute(
const fml::UniqueFD& base_fd,
const std::string& sub_path = "");
// |Mapping|
size_t GetSize() const override;
// |Mapping|
const uint8_t* GetMapping() const override;
// |Mapping|
bool IsDontNeedSafe() const override;
uint8_t* GetMutableMapping();
bool IsValid() const;
private:
bool valid_ = false;
size_t size_ = 0;
uint8_t* mapping_ = nullptr;
uint8_t* mutable_mapping_ = nullptr;
#if OS_WIN
fml::UniqueFD mapping_handle_;
#endif
FML_DISALLOW_COPY_AND_ASSIGN(FileMapping);
};
class DataMapping final : public Mapping {
public:
explicit DataMapping(std::vector<uint8_t> data);
explicit DataMapping(const std::string& string);
~DataMapping() override;
// |Mapping|
size_t GetSize() const override;
// |Mapping|
const uint8_t* GetMapping() const override;
// |Mapping|
bool IsDontNeedSafe() const override;
private:
std::vector<uint8_t> data_;
FML_DISALLOW_COPY_AND_ASSIGN(DataMapping);
};
class NonOwnedMapping final : public Mapping {
public:
using ReleaseProc = std::function<void(const uint8_t* data, size_t size)>;
NonOwnedMapping(const uint8_t* data,
size_t size,
const ReleaseProc& release_proc = nullptr,
bool dontneed_safe = false);
~NonOwnedMapping() override;
// |Mapping|
size_t GetSize() const override;
// |Mapping|
const uint8_t* GetMapping() const override;
// |Mapping|
bool IsDontNeedSafe() const override;
private:
const uint8_t* const data_;
const size_t size_;
const ReleaseProc release_proc_;
const bool dontneed_safe_;
FML_DISALLOW_COPY_AND_ASSIGN(NonOwnedMapping);
};
/// A Mapping like NonOwnedMapping, but uses Free as its release proc.
class MallocMapping final : public Mapping {
public:
MallocMapping();
/// Creates a MallocMapping for a region of memory (without copying it).
/// The function will `abort()` if the malloc fails.
/// @param data The starting address of the mapping.
/// @param size The size of the mapping in bytes.
MallocMapping(uint8_t* data, size_t size);
MallocMapping(fml::MallocMapping&& mapping);
~MallocMapping() override;
/// Copies the data from `begin` to `end`.
/// It's templated since void* arithemetic isn't allowed and we want support
/// for `uint8_t` and `char`.
template <typename T>
static MallocMapping Copy(const T* begin, const T* end) {
FML_DCHECK(end > begin);
size_t length = end - begin;
return Copy(begin, length);
}
/// Copies a region of memory into a MallocMapping.
/// The function will `abort()` if the malloc fails.
/// @param begin The starting address of where we will copy.
/// @param length The length of the region to copy in bytes.
static MallocMapping Copy(const void* begin, size_t length);
// |Mapping|
size_t GetSize() const override;
// |Mapping|
const uint8_t* GetMapping() const override;
// |Mapping|
bool IsDontNeedSafe() const override;
/// Removes ownership of the data buffer.
/// After this is called; the mapping will point to nullptr.
[[nodiscard]] uint8_t* Release();
private:
uint8_t* data_;
size_t size_;
FML_DISALLOW_COPY_AND_ASSIGN(MallocMapping);
};
class SymbolMapping final : public Mapping {
public:
SymbolMapping(fml::RefPtr<fml::NativeLibrary> native_library,
const char* symbol_name);
~SymbolMapping() override;
// |Mapping|
size_t GetSize() const override;
// |Mapping|
const uint8_t* GetMapping() const override;
// |Mapping|
bool IsDontNeedSafe() const override;
private:
fml::RefPtr<fml::NativeLibrary> native_library_;
const uint8_t* mapping_ = nullptr;
FML_DISALLOW_COPY_AND_ASSIGN(SymbolMapping);
};
} // namespace fml
#endif // FLUTTER_FML_MAPPING_H_
| 1,941 |
773 | import os
import pandas as pd
import collections
import zipfile
from six.moves import urllib
from ..common.utils import logger
def maybe_download_casas(zipfilename, url, filepathinzip, localpath):
"""Download the CASAS file if not present, and extract the relevant txt file."""
if os.path.exists(os.path.join(localpath, filepathinzip)):
return os.path.join(localpath, filepathinzip)
local_filename = os.path.join(localpath, zipfilename)
if not os.path.exists(local_filename):
local_filename, _ = urllib.request.urlretrieve(url + zipfilename,
local_filename)
statinfo = os.stat(local_filename)
if os.path.exists(local_filename) and statinfo.st_size > 0:
with zipfile.ZipFile(local_filename) as f:
casasfile = f.extract(filepathinzip, localpath)
return casasfile
return None
def write_sensor_data_as_document(cas):
localpath = "/Users/moy/work/git_public/word2vec-data/sensor"
with open(localpath + '/sensor_data.txt', 'w') as f:
f.write(" ".join(cas.sensor_seq))
class Casas(object):
def __init__(self, sensor_seq=None, sensor_enc=None,
sensors=None, sensor2code=None, code2sensor=None,
dataset_path=None):
self.sensor_seq = sensor_seq
self.sensor_enc = sensor_enc
self.sensors = sensors
self.sensor2code = sensor2code
self.code2sensor = code2sensor
if dataset_path is not None:
self.load_data(dataset_path)
def load_data(self, dataset_path):
self.sensor_seq, self.sensor_enc, self.sensors, self.sensor2code, self.code2sensor = \
Casas.read_sensor_data(dataset_path)
@staticmethod
def build_dataset(words, n_words=10000):
"""Process raw inputs into a dataset."""
# count = [['UNK', -1]]
count = []
count.extend(collections.Counter(words).most_common(n_words - 1))
dictionary = dict()
for word, _ in count:
dictionary[word] = len(dictionary)
data = list()
unk_count = 0
for word in words:
index = dictionary.get(word, 0)
# if index == 0: # dictionary['UNK']
# unk_count += 1
data.append(index)
# count[0][1] = unk_count
reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
return data, count, dictionary, reversed_dictionary
@staticmethod
def read_sensor_data(dataset_path):
logger.debug("dataset_path: %s" % dataset_path)
data = pd.read_csv(dataset_path,
header=None, sep='\t',
names=['x0', 'x1', 'x2', 'x3', 'x4'], dtype={'x2': str}
# parse_dates=dataset_def.date_columns, index_col=dataset_def.index_column,
# squeeze=True, date_parser=date_parser
)
logger.debug("Raw data shape: %s" % str(data.shape))
# retain only the sensor ON/OFF readings
sensor_data = data[data['x1'].str.startswith(("M", "MA"))]
# logger.debug(sensor_data)
logger.debug("filtered sensor_data.shape: %s" % str(sensor_data.shape))
# list of all sensors
sensors = sensor_data.x1.unique()
logger.debug("All sensors:\n%s" % str(sensors))
# sequential training data
sensor_seq = list(sensor_data.x1.values)
logger.debug("len(sensor_seq): %d" % len(sensor_seq))
if False:
sensor2code = {}
code2sensor = {}
for i, sensor in enumerate(sorted(sensors)):
sensor2code[sensor] = i
code2sensor[i] = sensor
sensor_enc = [sensor2code[sensor] for sensor in sensor_seq]
else:
sensor_enc, count, sensor2code, code2sensor = Casas.build_dataset(sensor_seq)
logger.debug(count)
return sensor_seq, sensor_enc, sensors, sensor2code, code2sensor
| 1,901 |
326 | /*-------------------------------------------------------------------------
*
* gtm_txn.h
*
*
* Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
* Portions Copyright (c) 2010-2012 Postgres-XC Development Group
*
* $PostgreSQL$
*
*-------------------------------------------------------------------------
*/
#ifndef _GTM_TXN_H
#define _GTM_TXN_H
#include "gtm/libpq-be.h"
#include "gtm/gtm_c.h"
#include "gtm/gtm_lock.h"
#include "gtm/gtm_list.h"
#include "gtm/stringinfo.h"
/* ----------------
* Special transaction ID values
*
* BootstrapGlobalTransactionId is the XID for "bootstrap" operations, and
* FrozenGlobalTransactionId is used for very old tuples. Both should
* always be considered valid.
*
* FirstNormalGlobalTransactionId is the first "normal" transaction id.
* Note: if you need to change it, you must change pg_class.h as well.
* ----------------
*/
#define BootstrapGlobalTransactionId ((GlobalTransactionId) 1)
#define FrozenGlobalTransactionId ((GlobalTransactionId) 2)
#define FirstNormalGlobalTransactionId ((GlobalTransactionId) 3)
#define MaxGlobalTransactionId ((GlobalTransactionId) 0xFFFFFFFF)
/* ----------------
* transaction ID manipulation macros
* ----------------
*/
#define GlobalTransactionIdIsNormal(xid) ((xid) >= FirstNormalGlobalTransactionId)
#define GlobalTransactionIdEquals(id1, id2) ((id1) == (id2))
#define GlobalTransactionIdStore(xid, dest) (*(dest) = (xid))
#define StoreInvalidGlobalTransactionId(dest) (*(dest) = InvalidGlobalTransactionId)
/* advance a transaction ID variable, handling wraparound correctly */
#define GlobalTransactionIdAdvance(dest) \
do { \
(dest)++; \
if ((dest) < FirstNormalGlobalTransactionId) \
(dest) = FirstNormalGlobalTransactionId; \
} while(0)
/* back up a transaction ID variable, handling wraparound correctly */
#define GlobalTransactionIdRetreat(dest) \
do { \
(dest)--; \
} while ((dest) < FirstNormalGlobalTransactionId)
typedef int XidStatus;
#define TRANSACTION_STATUS_IN_PROGRESS 0x00
#define TRANSACTION_STATUS_COMMITTED 0x01
#define TRANSACTION_STATUS_ABORTED 0x02
/*
* prototypes for functions in transam/transam.c
*/
extern bool GlobalTransactionIdDidCommit(GlobalTransactionId transactionId);
extern bool GlobalTransactionIdDidAbort(GlobalTransactionId transactionId);
extern void GlobalTransactionIdAbort(GlobalTransactionId transactionId);
extern bool GlobalTransactionIdPrecedes(GlobalTransactionId id1, GlobalTransactionId id2);
extern bool GlobalTransactionIdPrecedesOrEquals(GlobalTransactionId id1, GlobalTransactionId id2);
extern bool GlobalTransactionIdFollows(GlobalTransactionId id1, GlobalTransactionId id2);
extern bool GlobalTransactionIdFollowsOrEquals(GlobalTransactionId id1, GlobalTransactionId id2);
/* in transam/varsup.c */
extern GlobalTransactionId GTM_GetGlobalTransactionId(GTM_TransactionHandle handle);
extern GlobalTransactionId GTM_GetGlobalTransactionIdMulti(GTM_TransactionHandle handle[], int txn_count);
extern GlobalTransactionId ReadNewGlobalTransactionId(void);
extern void SetGlobalTransactionIdLimit(GlobalTransactionId oldest_datfrozenxid);
extern void SetNextGlobalTransactionId(GlobalTransactionId gxid);
extern void GTM_SetShuttingDown(void);
/* For restoration point backup */
extern bool GTM_NeedXidRestoreUpdate(void);
extern void GTM_WriteRestorePointXid(FILE *f);
typedef enum GTM_States
{
GTM_STARTING,
GTM_RUNNING,
GTM_SHUTTING_DOWN
} GTM_States;
/* Global transaction states at the GTM */
typedef enum GTM_TransactionStates
{
GTM_TXN_STARTING,
GTM_TXN_IN_PROGRESS,
GTM_TXN_PREPARE_IN_PROGRESS,
GTM_TXN_PREPARED,
GTM_TXN_COMMIT_IN_PROGRESS,
GTM_TXN_COMMITTED,
GTM_TXN_ABORT_IN_PROGRESS,
GTM_TXN_ABORTED
} GTM_TransactionStates;
typedef struct GTM_TransactionInfo
{
GTM_TransactionHandle gti_handle;
GTM_ThreadID gti_thread_id;
bool gti_in_use;
GlobalTransactionId gti_gxid;
GTM_TransactionStates gti_state;
char *gti_coordname;
GlobalTransactionId gti_xmin;
GTM_IsolationLevel gti_isolevel;
bool gti_readonly;
GTMProxy_ConnID gti_backend_id;
char *nodestring; /* List of nodes prepared */
char *gti_gid;
GTM_SnapshotData gti_current_snapshot;
bool gti_snapshot_set;
GTM_RWLock gti_lock;
bool gti_vacuum;
} GTM_TransactionInfo;
#define GTM_MAX_2PC_NODES 16
/* By default a GID length is limited to 256 bits in PostgreSQL */
#define GTM_MAX_GID_LEN 256
#define GTM_MAX_NODESTRING_LEN 1024
#define GTM_CheckTransactionHandle(x) ((x) >= 0 && (x) < GTM_MAX_GLOBAL_TRANSACTIONS)
#define GTM_IsTransSerializable(x) ((x)->gti_isolevel == GTM_ISOLATION_SERIALIZABLE)
typedef struct GTM_Transactions
{
uint32 gt_txn_count;
GTM_States gt_gtm_state;
GTM_RWLock gt_XidGenLock;
/*
* These fields are protected by XidGenLock
*/
GlobalTransactionId gt_nextXid; /* next XID to assign */
GlobalTransactionId gt_backedUpXid; /* backed up, restoration point */
GlobalTransactionId gt_oldestXid; /* cluster-wide minimum datfrozenxid */
GlobalTransactionId gt_xidVacLimit; /* start forcing autovacuums here */
GlobalTransactionId gt_xidWarnLimit; /* start complaining here */
GlobalTransactionId gt_xidStopLimit; /* refuse to advance nextXid beyond here */
GlobalTransactionId gt_xidWrapLimit; /* where the world ends */
/*
* These fields are protected by TransArrayLock.
*/
GlobalTransactionId gt_latestCompletedXid; /* newest XID that has committed or
* aborted */
GlobalTransactionId gt_recent_global_xmin;
int32 gt_lastslot;
GTM_TransactionInfo gt_transactions_array[GTM_MAX_GLOBAL_TRANSACTIONS];
gtm_List *gt_open_transactions;
GTM_RWLock gt_TransArrayLock;
} GTM_Transactions;
extern GTM_Transactions GTMTransactions;
/*
* This macro should be used with READ lock held on gt_TransArrayLock as the
* number of open transactions might change when counting open transactions
* if a lock is not hold.
*/
#define GTM_CountOpenTransactions() (gtm_list_length(GTMTransactions.gt_open_transactions))
/*
* Two hash tables will be maintained to quickly find the
* GTM_TransactionInfo block given either the GXID or the GTM_TransactionHandle.
*/
GTM_TransactionInfo *GTM_HandleToTransactionInfo(GTM_TransactionHandle handle);
GTM_TransactionHandle GTM_GXIDToHandle(GlobalTransactionId gxid);
GTM_TransactionHandle GTM_GIDToHandle(char *gid);
/* Transaction Control */
void GTM_InitTxnManager(void);
GTM_TransactionHandle GTM_BeginTransaction(char *coord_name,
GTM_IsolationLevel isolevel,
bool readonly);
int GTM_BeginTransactionMulti(char *coord_name,
GTM_IsolationLevel isolevel[],
bool readonly[],
GTMProxy_ConnID connid[],
int txn_count,
GTM_TransactionHandle txns[]);
int GTM_RollbackTransaction(GTM_TransactionHandle txn);
int GTM_RollbackTransactionMulti(GTM_TransactionHandle txn[], int txn_count, int status[]);
int GTM_RollbackTransactionGXID(GlobalTransactionId gxid);
int GTM_CommitTransaction(GTM_TransactionHandle txn);
int GTM_CommitTransactionMulti(GTM_TransactionHandle txn[], int txn_count, int status[]);
int GTM_CommitTransactionGXID(GlobalTransactionId gxid);
int GTM_PrepareTransaction(GTM_TransactionHandle txn);
int GTM_StartPreparedTransaction(GTM_TransactionHandle txn,
char *gid,
char *nodestring);
int GTM_StartPreparedTransactionGXID(GlobalTransactionId gxid,
char *gid,
char *nodestring);
int GTM_GetGIDData(GTM_TransactionHandle prepared_txn,
GlobalTransactionId *prepared_gxid,
char **nodestring);
uint32 GTM_GetAllPrepared(GlobalTransactionId gxids[], uint32 gxidcnt);
GTM_TransactionStates GTM_GetStatus(GTM_TransactionHandle txn);
GTM_TransactionStates GTM_GetStatusGXID(GlobalTransactionId gxid);
int GTM_GetAllTransactions(GTM_TransactionInfo txninfo[], uint32 txncnt);
void GTM_RemoveAllTransInfos(int backend_id);
GTM_Snapshot GTM_GetSnapshotData(GTM_TransactionInfo *my_txninfo,
GTM_Snapshot snapshot);
GTM_Snapshot GTM_GetTransactionSnapshot(GTM_TransactionHandle handle[],
int txn_count, int *status);
void GTM_FreeCachedTransInfo(void);
void ProcessBeginTransactionCommand(Port *myport, StringInfo message);
void ProcessBkupBeginTransactionCommand(Port *myport, StringInfo message);
void GTM_BkupBeginTransactionMulti(char *coord_name,
GTM_TransactionHandle *txn,
GTM_IsolationLevel *isolevel,
bool *readonly,
GTMProxy_ConnID *connid,
int txn_count);
void ProcessBeginTransactionCommandMulti(Port *myport, StringInfo message);
void ProcessBeginTransactionGetGXIDCommand(Port *myport, StringInfo message);
void ProcessCommitTransactionCommand(Port *myport, StringInfo message, bool is_backup);
void ProcessCommitPreparedTransactionCommand(Port *myport, StringInfo message, bool is_backup);
void ProcessRollbackTransactionCommand(Port *myport, StringInfo message, bool is_backup);
void ProcessStartPreparedTransactionCommand(Port *myport, StringInfo message, bool is_backup);
void ProcessPrepareTransactionCommand(Port *myport, StringInfo message, bool is_backup);
void ProcessGetGIDDataTransactionCommand(Port *myport, StringInfo message);
void ProcessGetGXIDTransactionCommand(Port *myport, StringInfo message);
void ProcessGXIDListCommand(Port *myport, StringInfo message);
void ProcessGetNextGXIDTransactionCommand(Port *myport, StringInfo message);
void ProcessBeginTransactionGetGXIDAutovacuumCommand(Port *myport, StringInfo message);
void ProcessBkupBeginTransactionGetGXIDAutovacuumCommand(Port *myport, StringInfo message);
void ProcessBeginTransactionGetGXIDCommandMulti(Port *myport, StringInfo message);
void ProcessCommitTransactionCommandMulti(Port *myport, StringInfo message, bool is_backup);
void ProcessRollbackTransactionCommandMulti(Port *myport, StringInfo message, bool is_backup) ;
void GTM_SaveTxnInfo(FILE *ctlf);
void GTM_RestoreTxnInfo(FILE *ctlf, GlobalTransactionId next_gxid);
void GTM_BkupBeginTransaction(char *coord_name,
GTM_TransactionHandle txn,
GTM_IsolationLevel isolevel,
bool readonly);
void ProcessBkupBeginTransactionGetGXIDCommand(Port *myport, StringInfo message);
void ProcessBkupBeginTransactionGetGXIDCommandMulti(Port *myport, StringInfo message);
/*
* In gtm_snap.c
*/
void ProcessGetSnapshotCommand(Port *myport, StringInfo message, bool get_gxid);
void ProcessGetSnapshotCommandMulti(Port *myport, StringInfo message);
void GTM_FreeSnapshotData(GTM_Snapshot snapshot);
#endif
| 3,645 |
419 | <reponame>namasikanam/MultipartyPSI
/*
* C++ class to implement a polynomial type and to allow
* arithmetic on polynomials whose elements are float numbers
*
* WARNING: This class has been cobbled together for a specific use with
* the MIRACL library. It is not complete, and may not work in other
* applications
*
* See Knuth The Art of Computer Programming Vol.2, Chapter 4.6
*/
#ifndef FPOLY_H
#define FPOLY_H
#include "floating.h"
class fterm
{
public:
Float an;
int n;
fterm *next;
};
class FPoly
{
fterm *start;
public:
FPoly() {start=NULL;}
FPoly(const FPoly&);
void clear();
fterm* addterm(Float,int,fterm *pos=NULL);
void multerm(Float,int);
Float coeff(int) const;
BOOL iszero() const;
FPoly& operator=(const FPoly&);
FPoly& operator+=(const FPoly&);
FPoly& operator-=(const FPoly&);
FPoly& operator*=(const Float&);
FPoly& divxn(FPoly&,int);
FPoly& mulxn(int);
friend int degree(const FPoly&);
friend FPoly twobytwo(const FPoly&,const FPoly&);
friend FPoly pow2bypow2(const FPoly&,const FPoly&,int);
friend FPoly powsof2(const FPoly&,int,const FPoly&,int);
friend FPoly special(const FPoly&,const FPoly&);
friend FPoly operator+(const FPoly&,const FPoly&);
friend FPoly operator-(const FPoly&,const FPoly&);
friend FPoly operator*(const FPoly&,const FPoly&);
friend FPoly operator*(const FPoly&,const Float&);
friend ostream& operator<<(ostream&,const FPoly&);
~FPoly();
};
#endif
| 588 |
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.
*
*************************************************************/
#ifndef SAX_FASTSERIALIZER_HXX
#define SAX_FASTSERIALIZER_HXX
#include <com/sun/star/xml/sax/XFastSerializer.hpp>
#include <com/sun/star/xml/sax/XFastTokenHandler.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <cppuhelper/implbase2.hxx>
#include <stack>
#include "sax/dllapi.h"
#include "sax/fshelper.hxx"
#define SERIALIZER_IMPLEMENTATION_NAME "com.sun.star.comp.extensions.xml.sax.FastSerializer"
#define SERIALIZER_SERVICE_NAME "com.sun.star.xml.sax.FastSerializer"
namespace sax_fastparser {
class SAX_DLLPUBLIC FastSaxSerializer : public ::cppu::WeakImplHelper2< ::com::sun::star::xml::sax::XFastSerializer, ::com::sun::star::lang::XServiceInfo >
{
public:
explicit FastSaxSerializer( );
virtual ~FastSaxSerializer();
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > getOutputStream() {return mxOutputStream;}
// The implementation details
static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void);
static ::rtl::OUString getImplementationName_Static();
// XFastSerializer
virtual void SAL_CALL startDocument( ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL endDocument( ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL startFastElement( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL startUnknownElement( const ::rtl::OUString& Namespace, const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL endFastElement( ::sal_Int32 Element )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL endUnknownElement( const ::rtl::OUString& Namespace, const ::rtl::OUString& Name )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL singleFastElement( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL singleUnknownElement( const ::rtl::OUString& Namespace, const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL characters( const ::rtl::OUString& aChars )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setOutputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& xOutputStream )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setFastTokenHandler( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastTokenHandler >& xFastTokenHandler )
throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw ( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw ( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw ( ::com::sun::star::uno::RuntimeException );
// C++ helpers
virtual void SAL_CALL writeId( ::sal_Int32 Element );
static ::rtl::OUString escapeXml( const ::rtl::OUString& s );
public:
/** From now on, don't write directly to the stream, but to top of a stack.
This is to be able to change the order of the data being written.
If you need to write eg.
p, r, rPr, [something], /rPr, t, [text], /r, /p,
but get it in order
p, r, t, [text], /t, rPr, [something], /rPr, /r, /p,
simply do
p, r, mark(), t, [text], /t, mark(), rPr, [something], /rPr,
mergeTopMarks( true ), mergeTopMarks(), /r, /p
and you are done.
*/
void mark();
/** Merge 2 topmost marks.
There are 3 possibilities - prepend the top before the second top-most
mark, append it, or append it later; prepending brings the possibility
to switch parts of the output, appending later allows to write some
output in advance.
Writes the result to the output stream if the mark stack becomes empty
by the operation.
When the MERGE_MARKS_POSTPONE is specified, the merge happens just
before the next merge.
@see mark()
*/
void mergeTopMarks( sax_fastparser::MergeMarksEnum eMergeType = sax_fastparser::MERGE_MARKS_APPEND );
private:
::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > mxOutputStream;
::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastTokenHandler > mxFastTokenHandler;
typedef ::com::sun::star::uno::Sequence< ::sal_Int8 > Int8Sequence;
class ForMerge
{
Int8Sequence maData;
Int8Sequence maPostponed;
public:
ForMerge() : maData(), maPostponed() {}
Int8Sequence& getData();
void prepend( const Int8Sequence &rWhat );
void append( const Int8Sequence &rWhat );
void postpone( const Int8Sequence &rWhat );
private:
static void merge( Int8Sequence &rTop, const Int8Sequence &rMerge, bool bAppend );
};
::std::stack< ForMerge > maMarkStack;
void writeFastAttributeList( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs );
void write( const ::rtl::OUString& s );
protected:
/** Forward the call to the output stream, or write to the stack.
The latter in the case that we are inside a mark().
*/
void writeBytes( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aData ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
};
} // namespace sax_fastparser
#endif
| 2,658 |
14,668 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_POLICY_CORE_COMMON_REMOTE_COMMANDS_TEST_SUPPORT_TESTING_REMOTE_COMMANDS_SERVER_H_
#define COMPONENTS_POLICY_CORE_COMMON_REMOTE_COMMANDS_TEST_SUPPORT_TESTING_REMOTE_COMMANDS_SERVER_H_
#include <stddef.h>
#include <memory>
#include <string>
#include <vector>
#include "base/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread_checker.h"
#include "components/policy/core/common/remote_commands/remote_command_job.h"
#include "components/policy/proto/device_management_backend.pb.h"
namespace base {
class TickClock;
class SingleThreadTaskRunner;
} // namespace base
namespace policy {
// Callback called when a command's result is reported back to the server.
using ResultReportedCallback =
base::OnceCallback<void(const enterprise_management::RemoteCommandResult&)>;
std::string SignDataWithTestKey(const std::string& data);
// This class implements server-side logic for remote commands service tests. It
// acts just like a queue, and there are mainly two exposed methods for this
// purpose. Test authors are expected to call IssueCommand() to add commands to
// the queue in their tests. FetchCommands() should be called when serving a
// request to the server intercepted e.g. via a net::URLRequestInterceptor or a
// mock CloudPolicyClient.
// In addition, this class also supports verifying command result sent back to
// server, and test authors should provide a callback for this purpose when
// issuing a command.
// All methods except FetchCommands() should be called from the same thread, and
// FetchCommands() can be called from any thread.
// Note that test author is responsible for ensuring that FetchCommands() is not
// called from another thread after |this| has been destroyed.
class TestingRemoteCommandsServer {
public:
TestingRemoteCommandsServer();
TestingRemoteCommandsServer(const TestingRemoteCommandsServer&) = delete;
TestingRemoteCommandsServer& operator=(const TestingRemoteCommandsServer&) =
delete;
virtual ~TestingRemoteCommandsServer();
using RemoteCommandResults =
std::vector<enterprise_management::RemoteCommandResult>;
using RemoteCommands = std::vector<enterprise_management::SignedData>;
// Add a command that will be returned on the next FetchCommands() call.
// |clock_| will be used to get the command issue time.
// |reported_callback| will be called from the same thread when a command
// result is reported back to the server.
void IssueCommand(const enterprise_management::SignedData& signed_data,
ResultReportedCallback reported_callback);
// Calling this will tell the server to return no commands on the next
// call to FetchCommands().
// All issued commands will instead be returned the second time
// FetchCommands() is called.
void OnNextFetchCommandsCallReturnNothing();
// Fetch commands, acknowledging all commands up to and including
// |last_command_id|, and provide |previous_job_results| as results for
// previous commands. |last_command_id| can be a nullptr which indicates that
// no commands will be acknowledged.
// See the protobuf definition for a definition of the protocol between server
// and client for remote command fetching.
// Unlike every other methods in the class, this method can be called from
// any thread.
RemoteCommands FetchCommands(
std::unique_ptr<RemoteCommandJob::UniqueIDType> last_command_id,
const RemoteCommandResults& previous_job_results);
// Set alternative clock for obtaining the command issue time. The default
// clock uses the system clock.
void SetClock(const base::TickClock* clock);
// Get the number of commands for which no results have been reported yet.
// This number also includes commands which have not been fetched yet.
size_t NumberOfCommandsPendingResult() const;
// The latest command ID generated by server.
RemoteCommandJob::UniqueIDType last_command_id() const {
return last_generated_unique_id_;
}
RemoteCommandJob::UniqueIDType GetNextCommandId() {
return ++last_generated_unique_id_;
}
private:
struct RemoteCommandWithCallback;
void HandleRemoteCommandResults(const RemoteCommandResults& results);
void ReportJobResult(
ResultReportedCallback reported_callback,
const enterprise_management::RemoteCommandResult& job_result) const;
// If true no commands will be returned to the caller of the next
// FetchCommands() call.
bool return_nothing_for_next_fetch_ = false;
// The main command queue.
std::vector<RemoteCommandWithCallback> commands_;
// The latest command ID generated by server. This test server generates
// strictly monotonically increasing unique IDs.
RemoteCommandJob::UniqueIDType last_generated_unique_id_ = 0;
// Clock used to generate command issue time when IssueCommand() is called.
raw_ptr<const base::TickClock> clock_;
// A lock protecting the command queues, as well as generated and acknowledged
// IDs.
base::Lock lock_;
// The thread on which this test server is created, usually the UI thread.
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
// A weak pointer created early so that it can be accessed from other threads.
base::WeakPtr<TestingRemoteCommandsServer> weak_ptr_to_this_;
base::ThreadChecker thread_checker_;
base::WeakPtrFactory<TestingRemoteCommandsServer> weak_factory_{this};
};
} // namespace policy
#endif // COMPONENTS_POLICY_CORE_COMMON_REMOTE_COMMANDS_TEST_SUPPORT_TESTING_REMOTE_COMMANDS_SERVER_H_
| 1,643 |
301 | {
"name": "dlnacast",
"version": "0.0.3",
"description": "cast local media to your TV using UPnP/DLNA",
"main": "index.js",
"bin": {
"dlnacast": "./index.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com/xat/dlnacast"
},
"author": "<NAME>",
"contributors": [
"<NAME> <<EMAIL>>"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/xat/dlnacast/issues"
},
"homepage": "https://github.com/xat/dlnacast",
"dependencies": {
"keypress": "^0.2.1",
"mime": "^1.3.4",
"minimist": "^1.1.1",
"renderer-finder": "^0.1.0",
"static-file-server": "0.0.4",
"upnp-mediarenderer-client": "https://registry.npmjs.org/upnp-mediarenderer-client/-/upnp-mediarenderer-client-1.0.0.tgz"
}
}
| 400 |
315 | <filename>inlong-manager/manager-web/src/main/java/org/apache/inlong/manager/web/controller/StorageController.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.inlong.manager.web.controller;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import org.apache.inlong.manager.common.beans.Response;
import org.apache.inlong.manager.common.enums.OperationType;
import org.apache.inlong.manager.common.pojo.datastorage.BaseStorageInfo;
import org.apache.inlong.manager.common.pojo.datastorage.BaseStorageListVO;
import org.apache.inlong.manager.common.pojo.datastorage.StoragePageRequest;
import org.apache.inlong.manager.common.pojo.query.ColumnInfoBean;
import org.apache.inlong.manager.common.pojo.query.ConnectionInfo;
import org.apache.inlong.manager.common.pojo.query.DatabaseDetail;
import org.apache.inlong.manager.common.pojo.query.TableQueryBean;
import org.apache.inlong.manager.common.util.LoginUserUtil;
import org.apache.inlong.manager.service.core.DataSourceService;
import org.apache.inlong.manager.service.core.StorageService;
import org.apache.inlong.manager.service.core.operationlog.OperationLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Data storage control layer
*/
@RestController
@RequestMapping("/storage")
@Api(tags = "Data Storage")
public class StorageController {
@Autowired
private DataSourceService dataSourceService;
@Autowired
private StorageService storageService;
@RequestMapping(value = "/save", method = RequestMethod.POST)
@OperationLog(operation = OperationType.CREATE)
@ApiOperation(value = "Save storage information")
public Response<Integer> save(@RequestBody BaseStorageInfo storageInfo) {
return Response.success(storageService.save(storageInfo, LoginUserUtil.getLoginUserDetail().getUserName()));
}
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
@ApiOperation(value = "Query storage information")
@ApiImplicitParams({
@ApiImplicitParam(name = "storageType", dataTypeClass = String.class, required = true),
@ApiImplicitParam(name = "id", dataTypeClass = Integer.class, required = true)
})
public Response<BaseStorageInfo> get(@RequestParam String storageType, @PathVariable Integer id) {
return Response.success(storageService.getById(storageType, id));
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ApiOperation(value = "Query data storage list based on conditions")
public Response<PageInfo<? extends BaseStorageListVO>> listByCondition(StoragePageRequest request) {
return Response.success(storageService.listByCondition(request));
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
@OperationLog(operation = OperationType.UPDATE)
@ApiOperation(value = "Modify data storage information")
public Response<Boolean> update(@RequestBody BaseStorageInfo storageInfo) {
return Response.success(storageService.update(storageInfo, LoginUserUtil.getLoginUserDetail().getUserName()));
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
@OperationLog(operation = OperationType.DELETE)
@ApiOperation(value = "Delete data storage information")
@ApiImplicitParams({
@ApiImplicitParam(name = "storageType", dataTypeClass = String.class, required = true),
@ApiImplicitParam(name = "id", dataTypeClass = Integer.class, required = true)
})
public Response<Boolean> delete(@RequestParam String storageType, @PathVariable Integer id) {
boolean result = storageService.delete(storageType, id, LoginUserUtil.getLoginUserDetail().getUserName());
return Response.success(result);
}
@RequestMapping(value = "/query/testConnection", method = RequestMethod.POST)
@ApiOperation(value = "Test the connection")
public Response<Boolean> testConnection(@RequestBody ConnectionInfo connectionInfo) {
return Response.success(dataSourceService.testConnection(connectionInfo));
}
@RequestMapping(value = "/query/createDb", method = RequestMethod.POST)
@ApiOperation(value = "Create database if not exists")
public Response<Object> createDb(@RequestBody TableQueryBean queryBean) throws Exception {
dataSourceService.createDb(queryBean);
return Response.success();
}
@RequestMapping(value = "/query/columns", method = RequestMethod.POST)
@ApiOperation(value = "Query table columns")
public Response<List<ColumnInfoBean>> queryColumns(@RequestBody TableQueryBean queryBean) throws Exception {
return Response.success(dataSourceService.queryColumns(queryBean));
}
@RequestMapping(value = "/query/dbDetail", method = RequestMethod.POST)
@ApiOperation(value = "Query database detail")
public Response<DatabaseDetail> queryDbDetail(@RequestBody TableQueryBean queryBean) throws Exception {
return Response.success(dataSourceService.queryDbDetail(queryBean));
}
}
| 1,947 |
600 | <filename>engine/source/gamelib/sprite.c
/*
* OpenBOR - http://www.chronocrash.com
* -----------------------------------------------------------------------
* All rights reserved, see LICENSE in OpenBOR root for details.
*
* Copyright (c) 2004 - 2014 OpenBOR Team
*/
/////////////////////////////////////////////////////////////////////////////
/*#include <stdio.h>
#include <string.h>*/
#include "globals.h"
#include "types.h"
#include "sprite.h"
#include "transform.h"
/////////////////////////////////////////////////////////////////////////////
static void putsprite_(
unsigned char *dest, int x, int xmin, int xmax, int *linetab, int h, int screenwidth
)
{
for(; h > 0; h--, dest += screenwidth)
{
register int lx = x;
unsigned char *data = ((unsigned char *)linetab) + (*linetab);
linetab++;
while(lx < xmax)
{
register int count = *data++;
if(count == 0xFF)
{
break;
}
lx += count;
if(lx >= xmax)
{
break;
}
count = *data++;
if(!count)
{
continue;
}
if((lx + count) <= xmin)
{
lx += count;
data += count;
continue;
}
if(lx < xmin)
{
int diff = lx - xmin;
count += diff;
data -= diff;
lx = xmin;
}
if((lx + count) > xmax)
{
count = xmax - lx;
}
memcpy(dest + lx, data, count);
data += count;
lx += count;
}
}
}
static void putsprite_flip_(
unsigned char *dest, int x, int xmin, int xmax, int *linetab, int h, int screenwidth
)
{
for(; h > 0; h--, dest += screenwidth)
{
register int lx = x;
unsigned char *data = ((unsigned char *)linetab) + (*linetab);
linetab++;
while(lx > xmin)
{
register int count = *data++;
if(count == 0xFF)
{
break;
}
lx -= count;
if(lx <= xmin)
{
break;
}
count = *data++;
if(!count)
{
continue;
}
if((lx - count) >= xmax)
{
lx -= count;
data += count;
continue;
}
if(lx > xmax)
{
int diff = (lx - xmax);
count -= diff;
data += diff;
lx = xmax;
}
if((lx - count) < xmin)
{
count = lx - xmin;
}
for(; count > 0; count--)
{
dest[--lx] = *data++;
}
//lx--;
//u8revcpy(dest+lx, data, count);
//lx-=count-1;
//data+=count;
}
}
}
static void putsprite_remap_(
unsigned char *dest, int x, int xmin, int xmax, int *linetab, int h, int screenwidth,
unsigned char *remap
)
{
for(; h > 0; h--, dest += screenwidth)
{
register int lx = x;
unsigned char *data = ((unsigned char *)linetab) + (*linetab);
linetab++;
while(lx < xmax)
{
register int count = *data++;
if(count == 0xFF)
{
break;
}
lx += count;
if(lx >= xmax)
{
break;
}
count = *data++;
if(!count)
{
continue;
}
if((lx + count) <= xmin)
{
lx += count;
data += count;
continue;
}
if(lx < xmin)
{
int diff = lx - xmin;
count += diff;
data -= diff;
lx = xmin;
}
if((lx + count) > xmax)
{
count = xmax - lx;
}
for(; count > 0; count--)
{
dest[lx++] = remap[((int)(*data++)) & 0xFF];
}
//u8pcpy(dest+lx, data, remap, count);
//lx+=count;
//data+=count;
}
}
}
static void putsprite_remap_flip_(
unsigned char *dest, int x, int xmin, int xmax, int *linetab, int h, int screenwidth,
unsigned char *remap
)
{
for(; h > 0; h--, dest += screenwidth)
{
register int lx = x;
unsigned char *data = ((unsigned char *)linetab) + (*linetab);
linetab++;
while(lx > xmin)
{
register int count = *data++;
if(count == 0xFF)
{
break;
}
lx -= count;
if(lx <= xmin)
{
break;
}
count = *data++;
if(!count)
{
continue;
}
if((lx - count) >= xmax)
{
lx -= count;
data += count;
continue;
}
if(lx > xmax)
{
int diff = (lx - xmax);
count -= diff;
data += diff;
lx = xmax;
}
if((lx - count) < xmin)
{
count = lx - xmin;
}
for(; count > 0; count--)
{
dest[--lx] = remap[((int)(*data++)) & 0xFF];
}
//lx--;
//u8revpcpy(dest+lx, data, remap, count);
//lx-=count-1;
//data+=count;
}
}
}
//src high dest low
static void putsprite_remapblend_(
unsigned char *dest, int x, int xmin, int xmax, int *linetab, int h, int screenwidth,
unsigned char *remap, unsigned char *blend
)
{
for(; h > 0; h--, dest += screenwidth)
{
register int lx = x;
unsigned char *data = ((unsigned char *)linetab) + (*linetab);
linetab++;
while(lx < xmax)
{
register int count = *data++;
if(count == 0xFF)
{
break;
}
lx += count;
if(lx >= xmax)
{
break;
}
count = *data++;
if(!count)
{
continue;
}
if((lx + count) <= xmin)
{
lx += count;
data += count;
continue;
}
if(lx < xmin)
{
int diff = lx - xmin;
count += diff;
data -= diff;
lx = xmin;
}
if((lx + count) > xmax)
{
count = xmax - lx;
}
for(; count > 0; count--)
{
dest[lx] = blend[(remap[(((int)(*data++)) & 0xFF)] << 8) | dest[lx]];
lx++;
}
}
}
}
static void putsprite_remapblend_flip_(
unsigned char *dest, int x, int xmin, int xmax, int *linetab, int h, int screenwidth,
unsigned char *remap, unsigned char *blend
)
{
for(; h > 0; h--, dest += screenwidth)
{
register int lx = x;
unsigned char *data = ((unsigned char *)linetab) + (*linetab);
linetab++;
while(lx > xmin)
{
register int count = *data++;
if(count == 0xFF)
{
break;
}
lx -= count;
if(lx <= xmin)
{
break;
}
count = *data++;
if(!count)
{
continue;
}
if((lx - count) >= xmax)
{
lx -= count;
data += count;
continue;
}
if(lx > xmax)
{
int diff = (lx - xmax);
count -= diff;
data += diff;
lx = xmax;
}
if((lx - count) < xmin)
{
count = lx - xmin;
}
for(; count > 0; count--)
{
--lx;
dest[lx] = blend[(remap[(((int)(*data++)) & 0xFF)] << 8) | dest[lx]];
}
}
}
}
static void putsprite_blend_(
unsigned char *dest, int x, int xmin, int xmax, int *linetab, int h, int screenwidth,
unsigned char *blend
)
{
for(; h > 0; h--, dest += screenwidth)
{
register int lx = x;
unsigned char *data = ((unsigned char *)linetab) + (*linetab);
linetab++;
while(lx < xmax)
{
register int count = *data++;
if(count == 0xFF)
{
break;
}
lx += count;
if(lx >= xmax)
{
break;
}
count = *data++;
if(!count)
{
continue;
}
if((lx + count) <= xmin)
{
lx += count;
data += count;
continue;
}
if(lx < xmin)
{
int diff = lx - xmin;
count += diff;
data -= diff;
lx = xmin;
}
if((lx + count) > xmax)
{
count = xmax - lx;
}
for(; count > 0; count--)
{
dest[lx] = blend[((((int)(*data++)) & 0xFF) << 8) | dest[lx]];
lx++;
}
}
}
}
static void putsprite_blend_flip_(
unsigned char *dest, int x, int xmin, int xmax, int *linetab, int h, int screenwidth,
unsigned char *blend
)
{
for(; h > 0; h--, dest += screenwidth)
{
register int lx = x;
unsigned char *data = ((unsigned char *)linetab) + (*linetab);
linetab++;
while(lx > xmin)
{
register int count = *data++;
if(count == 0xFF)
{
break;
}
lx -= count;
if(lx <= xmin)
{
break;
}
count = *data++;
if(!count)
{
continue;
}
if((lx - count) >= xmax)
{
lx -= count;
data += count;
continue;
}
if(lx > xmax)
{
int diff = (lx - screenwidth);
count -= diff;
data += diff;
lx = screenwidth;
}
if((lx - count) < xmin)
{
count = lx - xmin;
}
for(; count > 0; count--)
{
--lx;
dest[lx] = blend[((((int)(*data++)) & 0xFF) << 8) | dest[lx]];
}
}
}
}
/////////////////////////////////////////////////////////////////////////////
void putsprite_8(
int x, int y, int is_flip, s_sprite *sprite, s_screen *screen,
unsigned char *remap, unsigned char *blend
)
{
int *linetab;
int w, h;
unsigned char *dest;
// Get screen size
int screenwidth = screen->width;
int xmin = useclip ? MAX(clipx1, 0) : 0,
xmax = useclip ? MIN(clipx2, screen->width) : screen->width,
ymin = useclip ? MAX(clipy1, 0) : 0,
ymax = useclip ? MIN(clipy2, screen->height) : screen->height;
// Adjust coords for centering
if(is_flip)
{
x += sprite->centerx;
}
else
{
x -= sprite->centerx;
}
y -= sprite->centery;
// Get sprite dimensions
w = sprite->width;
h = sprite->height;
// trivial clip all directions
if(is_flip)
{
if(x - w >= xmax)
{
return;
}
if(x <= xmin)
{
return;
}
}
else
{
if(x >= xmax)
{
return;
}
if((x + w) <= xmin)
{
return;
}
}
if(y >= ymax)
{
return;
}
if((y + h) <= ymin)
{
return;
}
// Init line table pointer
linetab = (int *)(sprite->data);
// clip top
if(y < ymin)
{
h += y - ymin; // subtract from height
linetab -= y - ymin; // add to linetab
y = ymin; // add to y
}
// clip bottom
if((y + h) > ymax)
{
h = ymax - y;
}
// calculate destination pointer
dest = ((unsigned char *)(screen->data)) + y * screenwidth;
if(blend && remap)
{
if(is_flip)
{
putsprite_remapblend_flip_(dest, x, xmin, xmax, linetab, h, screenwidth, remap, blend);
}
else
{
putsprite_remapblend_ (dest, x, xmin, xmax , linetab, h, screenwidth, remap, blend);
}
}
else if(blend)
{
if(is_flip)
{
putsprite_blend_flip_(dest, x, xmin, xmax, linetab, h, screenwidth, blend);
}
else
{
putsprite_blend_ (dest, x, xmin, xmax , linetab, h, screenwidth, blend);
}
}
else if(remap)
{
if(is_flip)
{
putsprite_remap_flip_(dest, x, xmin, xmax, linetab, h, screenwidth, remap);
}
else
{
putsprite_remap_ (dest, x, xmin, xmax , linetab, h, screenwidth, remap);
}
}
else
{
if(is_flip)
{
putsprite_flip_ (dest, x, xmin, xmax, linetab, h, screenwidth);
}
else
{
putsprite_ (dest, x, xmin, xmax , linetab, h, screenwidth);
}
}
}
/////////////////////////////////////////////////////////////////////////////
// scalex scaley flipy ...
void putsprite_ex(int x, int y, s_sprite *frame, s_screen *screen, s_drawmethod *drawmethod)
{
gfx_entry gfx;
if(!drawmethod->scalex || !drawmethod->scaley)
{
return; // zero size
}
// no scale, no shift, no flip, no fill, so use common method
if(!drawmethod->water.watermode && drawmethod->scalex == 256 && drawmethod->scaley == 256 && !drawmethod->flipy && !drawmethod->shiftx && drawmethod->fillcolor == TRANSPARENT_IDX && !drawmethod->rotate)
{
if(drawmethod->flipx)
{
x += drawmethod->centerx;
}
else
{
x -= drawmethod->centerx;
}
y -= drawmethod->centery;
switch(screen->pixelformat)
{
case PIXEL_8:
putsprite_8(x, y, drawmethod->flipx, frame, screen, drawmethod->table, drawmethod->alpha > 0 ? blendtables[drawmethod->alpha - 1] : NULL);
break;
case PIXEL_16:
putsprite_x8p16(x, y, drawmethod->flipx, frame, screen, (unsigned short *)drawmethod->table, getblendfunction16(drawmethod->alpha));
break;
case PIXEL_32:
putsprite_x8p32(x, y, drawmethod->flipx, frame, screen, (unsigned *)drawmethod->table, getblendfunction32(drawmethod->alpha));
break;
}
return;
}
gfx.sprite = frame;
if(drawmethod->water.watermode == 3 && drawmethod->water.beginsize > 0)
{
gfx_draw_plane(screen, &gfx, x, y, frame->centerx, frame->centery, drawmethod);
}
else if(drawmethod->water.watermode && drawmethod->water.amplitude)
{
gfx_draw_water(screen, &gfx, x, y, frame->centerx, frame->centery, drawmethod);
}
else if(drawmethod->rotate)
{
gfx_draw_rotate(screen, &gfx, x, y, frame->centerx, frame->centery, drawmethod);
}
else
{
gfx_draw_scale(screen, &gfx, x, y, frame->centerx, frame->centery, drawmethod);
}
}
static void _putsprite(int x, int y, s_sprite *sprite, s_screen *screen, s_drawmethod *drawmethod)
{
if(!drawmethod || drawmethod->flag == 0)
{
goto plainsprite;
}
putsprite_ex(x, y, sprite, screen, drawmethod);
return;
plainsprite:
switch(screen->pixelformat)
{
case PIXEL_8:
putsprite_8(x, y, 0, sprite, screen, NULL, NULL);
break;
case PIXEL_16:
putsprite_x8p16(x, y, 0, sprite, screen, (unsigned short *)sprite->palette, NULL);
break;
case PIXEL_32:
putsprite_x8p32(x, y, 0, sprite, screen, (unsigned *)sprite->palette, NULL);
break;
}
}
void putsprite(int x, int y, s_sprite *sprite, s_screen *screen, s_drawmethod *drawmethod)
{
int xrepeat, yrepeat, xspan, yspan, i, j, dx, dy;
drawmethod_global_init(drawmethod);
if(drawmethod && drawmethod->flag)
{
xrepeat = drawmethod->xrepeat;
yrepeat = drawmethod->yrepeat;
xspan = drawmethod->xspan;
yspan = drawmethod->yspan;
}
else
{
xrepeat = yrepeat = 1;
xspan = yspan = 0;
}
for(j = 0, dy = y; j < yrepeat; j++, dy += yspan)
{
for(i = 0, dx = x; i < xrepeat; i++, dx += xspan)
{
_putsprite(dx, dy, sprite, screen, drawmethod);
}
}
}
/////////////////////////////////////////////////////////////////////////////
//
// NULL for dest means do not actually encode
//
unsigned encodesprite(
int centerx, int centery,
s_bitmap *bitmap, s_sprite *dest
)
{
int x, x0, y, w, h, xoffset, origwidth;
unsigned char *data;
int *linetab;
unsigned char *src = bitmap->data;
int pb = PAL_BYTES, extrab;
if(dest)
{
dest->magic = sprite_magic;
}
if(bitmap->clipped_width <= 0 || bitmap->clipped_height <= 0)
{
// Image is empty (or bad), create an empty sprite
if(dest)
{
//dest->is_flip_of = NULL;
dest->centerx = 0;
dest->centery = 0;
dest->width = 0;
dest->height = 0;
dest->pixelformat = bitmap->pixelformat;
dest->mask = NULL;
dest->palette = NULL;
}
return sizeof(s_sprite);
}
w = bitmap->clipped_width;
h = bitmap->clipped_height;
xoffset = bitmap->clipped_x_offset;
origwidth = bitmap->width;
if(dest)
{
//dest->is_flip_of = NULL;
dest->centerx = centerx;
dest->centery = centery;
dest->width = w;
dest->height = h;
dest->pixelformat = bitmap->pixelformat;
dest->mask = NULL;
}
linetab = (int *)(dest->data);
data = (unsigned char *)(linetab + h);
src += bitmap->clipped_y_offset * origwidth;
src += xoffset;
for(y = 0; y < h; y++, src += origwidth)
{
if(dest)
{
linetab[y] = ((size_t)data) - ((size_t)(linetab + y));
}
x = 0;
for(;;)
{
// search for the first visible pixel
x0 = x;
for(; (x < w) && ((x - x0) < 0xFE); x++)
{
if(src[x])
{
break;
}
}
// handle EOL
if(x >= w)
{
if(dest)
{
*data = 0xFF;
}
data++;
break;
}
// encode clearcount
if(dest)
{
*data = x - x0;
}
data++;
// if we're still not visible, encode a null visible count and continue
if(!src[x])
{
if(dest)
{
*data = 0;
}
data++;
continue;
}
// search for the first invisible pixel
x0 = x;
for(; (x < w) && ((x - x0) < 0xFF); x++)
{
if(!src[x])
{
break;
}
}
// encode viscount and visible pixels
if(dest)
{
*data++ = x - x0;
memcpy(data, src + x0, x - x0);
data += x - x0;
}
else
{
data += 1 + (x - x0);
}
}
}
if(!bitmap->palette)
{
pb = extrab = 0;
}
else
{
extrab = ((size_t)data) - ((size_t)dest);
extrab %= 4;
extrab = 4 - extrab;
extrab %= 4;
}
//point palette to the last byte of the pixel data
if(dest)
{
if(bitmap->palette) // if the bitmap contains palette, copy it
{
dest->palette = ((unsigned char *)data) + extrab ;
memcpy(dest->palette, bitmap->palette, pb);
}
else
{
dest->palette = NULL;
}
}
return ((size_t)data) - ((size_t)dest) + extrab + pb + ANYNUMBER;
}
/////////////////////////////////////////////////////////////////////////////
unsigned fakey_encodesprite(s_bitmap *bitmap)
{
return encodesprite(0, 0, bitmap, NULL);
}
/////////////////////////////////////////////////////////////////////////////
| 12,290 |
486 | <filename>javatests/de/jflex/testcase/include/IncludeGoldenTest.java<gh_stars>100-1000
// test: include
package de.jflex.testcase.include;
import de.jflex.testing.testsuite.golden.AbstractGoldenTest;
import de.jflex.testing.testsuite.golden.GoldenInOutFilePair;
import de.jflex.util.scanner.ScannerFactory;
import java.io.File;
import org.junit.Test;
/**
* tests include files, i.e. <a href="https://github.com/jflex-de/jflex/issues/51">yyPushStream and
* yyPopStream bug</a>
*
* <p>Note: This test was generated from {@code jflex-testsuite-maven-plugin} test cases. The test
* relies on golden files for testing, expecting the scanner to output logs on the {@code
* System.out}. Please migrate to proper unit tests, as describe in <a
* href="https://github.com/jflex-de/jflex/tree/master/javatests/de/jflex/testcase">
* //javatest/jflex/testcase</a>.
*/
// TODO Migrate this test to proper unit tests.
public class IncludeGoldenTest extends AbstractGoldenTest {
/** Creates a scanner conforming to the {@code include.flex} specification. */
private final ScannerFactory<IncludeScanner> scannerFactory =
ScannerFactory.of(IncludeScanner::new);
private final File testRuntimeDir = new File("javatests/de/jflex/testcase/include");
@Test
public void goldenTest0() throws Exception {
GoldenInOutFilePair golden =
new GoldenInOutFilePair(
new File(testRuntimeDir, "include-0.input"),
new File(testRuntimeDir, "include-0.output"));
compareSystemOutWith(golden);
IncludeScanner scanner = scannerFactory.createScannerForFile(golden.inputFile);
while (!scanner.yyatEOF()) {
System.out.println(scanner.yylex());
}
}
}
| 585 |
5,813 | /*
* 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.druid.segment.indexing.granularity;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.collect.Iterators;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.java.util.common.granularity.Granularity;
import org.apache.druid.java.util.common.guava.Comparators;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
public abstract class BaseGranularitySpec implements GranularitySpec
{
public static final Boolean DEFAULT_ROLLUP = Boolean.TRUE;
public static final Granularity DEFAULT_SEGMENT_GRANULARITY = Granularities.DAY;
public static final Granularity DEFAULT_QUERY_GRANULARITY = Granularities.NONE;
protected final List<Interval> inputIntervals;
protected final Boolean rollup;
public BaseGranularitySpec(List<Interval> inputIntervals, Boolean rollup)
{
this.inputIntervals = inputIntervals == null ? Collections.emptyList() : inputIntervals;
this.rollup = rollup == null ? DEFAULT_ROLLUP : rollup;
}
@Override
@JsonProperty("intervals")
public List<Interval> inputIntervals()
{
return inputIntervals;
}
@Override
@JsonProperty("rollup")
public boolean isRollup()
{
return rollup;
}
@Override
public Optional<Interval> bucketInterval(DateTime dt)
{
return getLookupTableBuckets().bucketInterval(dt);
}
@Override
public TreeSet<Interval> materializedBucketIntervals()
{
return getLookupTableBuckets().materializedIntervals();
}
protected abstract LookupIntervalBuckets getLookupTableBuckets();
@Override
public Map<String, Object> asMap(ObjectMapper objectMapper)
{
return objectMapper.convertValue(
this,
new TypeReference<Map<String, Object>>() {}
);
}
/**
* This is a helper class to facilitate sharing the code for sortedBucketIntervals among
* the various GranularitySpec implementations. In particular, the UniformGranularitySpec
* needs to avoid materializing the intervals when the need to traverse them arises.
*/
protected static class LookupIntervalBuckets
{
private final Iterable<Interval> intervalIterable;
private final TreeSet<Interval> intervals;
/**
* @param intervalIterable The intervals to materialize
*/
public LookupIntervalBuckets(Iterable<Interval> intervalIterable)
{
this.intervalIterable = intervalIterable;
// The tree set will be materialized on demand (see below) to avoid client code
// blowing up when constructing this data structure and when the
// number of intervals is very large...
this.intervals = new TreeSet<>(Comparators.intervalsByStartThenEnd());
}
/**
* Returns a bucket interval using a fast lookup into an efficient data structure
* where all the intervals have been materialized
*
* @param dt The date time to lookup
* @return An Optional containing the interval for the given DateTime if it exists
*/
public Optional<Interval> bucketInterval(DateTime dt)
{
final Interval interval = materializedIntervals().floor(new Interval(dt, DateTimes.MAX));
if (interval != null && interval.contains(dt)) {
return Optional.of(interval);
} else {
return Optional.absent();
}
}
/**
* @return An iterator to traverse the materialized intervals. The traversal will be done in
* order as dictated by Comparators.intervalsByStartThenEnd()
*/
public Iterator<Interval> iterator()
{
return materializedIntervals().iterator();
}
/**
* Helper method to avoid collecting the intervals from the iterator
*
* @return The TreeSet of materialized intervals
*/
public TreeSet<Interval> materializedIntervals()
{
if (intervalIterable != null && intervalIterable.iterator().hasNext() && intervals.isEmpty()) {
Iterators.addAll(intervals, intervalIterable.iterator());
}
return intervals;
}
}
}
| 1,622 |
372 | /*
* 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.sysds.test.component.federated;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.sysds.runtime.matrix.data.LibMatrixMult;
import org.apache.sysds.runtime.matrix.data.MatrixBlock;
import org.apache.sysds.test.TestUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(value = Parameterized.class)
public class FedWorkerMatrixMultiply extends FedWorkerBase {
private final MatrixBlock mbl;
private final MatrixBlock mbr;
@Parameters
public static Collection<Object[]> data() {
final ArrayList<Object[]> tests = new ArrayList<>();
final int port = startWorker();
final MatrixBlock mb10x10_1 = TestUtils.generateTestMatrixBlock(10, 10, 0.5, 9.5, 1.0, 1342);
final MatrixBlock mb10x10_2 = TestUtils.generateTestMatrixBlock(10, 10, 0.5, 9.5, 1.0, 222);
final MatrixBlock mb10x10_1_r = TestUtils.round(mb10x10_1);
final MatrixBlock mb10x10_2_r = TestUtils.round(mb10x10_2);
tests.add(new Object[] {port, mb10x10_1, mb10x10_2});
tests.add(new Object[] {port, mb10x10_1_r, mb10x10_2_r});
final MatrixBlock mb3x10 = TestUtils.generateTestMatrixBlock(3, 10, 0.5, 9.5, 1.0, 324);
final MatrixBlock mb10x4 = TestUtils.generateTestMatrixBlock(10, 4, 0.5, 9.5, 1.0, 324);
tests.add(new Object[] {port, mb3x10, mb10x10_2});
tests.add(new Object[] {port, mb10x10_1_r, mb10x4});
return tests;
}
public FedWorkerMatrixMultiply(int port, MatrixBlock mbl, MatrixBlock mbr) {
super(port);
this.mbl = mbl;
this.mbr = mbr;
}
@Test
public void matrixMultiplication() {
// local
final MatrixBlock expected = LibMatrixMult.matrixMult(mbl, mbr);
// Federated
final long idl = putMatrixBlock(mbl);
final long idr = putMatrixBlock(mbr);
final long idOut = matrixMult(idl, idr);
final MatrixBlock mbr = getMatrixBlock(idOut);
// Compare
TestUtils.compareMatricesBitAvgDistance(expected, mbr, 0, 0,
"Not equivalent matrix block returned from federated site");
}
@Test
public void matrixMultiplicationChainRight() {
// local
final MatrixBlock e1 = LibMatrixMult.matrixMult(mbl, mbr);
if(e1.getNumColumns() != mbr.getNumRows())
return; // skipping because test is invalid.
final MatrixBlock e2 = LibMatrixMult.matrixMult(e1, mbr);
final MatrixBlock e3 = LibMatrixMult.matrixMult(e2, mbr);
// Federated
final long idl = putMatrixBlock(mbl);
final long idr = putMatrixBlock(mbr);
final long ide1 = matrixMult(idl, idr);
final long ide2 = matrixMult(ide1, idr);
final long ide3 = matrixMult(ide2, idr);
final MatrixBlock mbr = getMatrixBlock(ide3);
// Compare
TestUtils.compareMatricesBitAvgDistance(e3, mbr, 0, 0,
"Not equivalent matrix block returned from federated site");
}
@Test
public void matrixMultiplicationChainLeft() {
// local
final MatrixBlock e1 = LibMatrixMult.matrixMult(mbl, mbr);
if(mbl.getNumColumns() != e1.getNumRows())
return; // skipping because test is invalid.
final MatrixBlock e2 = LibMatrixMult.matrixMult(mbl, e1);
final MatrixBlock e3 = LibMatrixMult.matrixMult(mbl, e2);
// Federated
final long idl = putMatrixBlock(mbl);
final long idr = putMatrixBlock(mbr);
final long ide1 = matrixMult(idl, idr);
final long ide2 = matrixMult(idl, ide1);
final long ide3 = matrixMult(idl, ide2);
final MatrixBlock mbr = getMatrixBlock(ide3);
// Compare
TestUtils.compareMatricesBitAvgDistance(e3, mbr, 0, 0,
"Not equivalent matrix block returned from federated site");
}
}
| 1,546 |
2,890 | package com.github.ltsopensource.autoconfigure.resolver;
import com.github.ltsopensource.autoconfigure.AutoConfigContext;
import com.github.ltsopensource.autoconfigure.PropertiesConfigurationFactory;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;
/**
* @author <NAME> (<EMAIL>) on 4/20/16.
*/
public class JavaBeanResolver extends AbstractResolver {
public static final JavaBeanResolver INSTANCE = new JavaBeanResolver();
@Override
public void resolve(AutoConfigContext context, PropertyDescriptor descriptor, Class<?> propertyType) {
final Map<String, String> includeMap = new HashMap<String, String>();
doFilter(context, descriptor, new Filter() {
@Override
public boolean onCondition(String name, String key, String value) {
return key.startsWith(name);
}
@Override
public boolean call(String name, String key, String value) {
String subKey = key.substring(name.length() + 1);
includeMap.put(subKey, value);
return true;
}
});
Object value = PropertiesConfigurationFactory.createPropertiesConfiguration(propertyType, null, includeMap);
if (value != null) {
writeProperty(context, descriptor, value);
}
}
}
| 521 |
428 | <filename>src/cpp/f00340_gameplantnode.hpp<gh_stars>100-1000
// class GamePlantNode {
// };
class GamePlantNode {
public:
FIVector4 begPoint;
FIVector4 endPoint;
//FIVector4 ctrPoint;
FIVector4 tangent;
FIVector4 baseShoot;
//float rotation;
float shootLength;
float begThickness;
float endThickness;
float midThickness;
float sphereRad;
FIVector4 startEndWidth;
FIVector4 upVec;
GamePlantNode* parent;
GamePlantNode* children;
int maxChildren;
int numChildren;
GamePlantNode() {
sphereRad = 0.0f;
parent = NULL;
children = NULL;
upVec.setFXYZ(0.0f,0.0f,1.0f);
}
void updateTangent(float angleInRadians) {
tangent.setFXYZRef(&endPoint);
tangent.addXYZRef(&begPoint,-1.0f);
tangent.normalize();
baseShoot.setFXYZRef(&tangent);
baseShoot.rotate(angleInRadians, E_PLANE_XZ);
baseShoot.normalize();
shootLength = begPoint.distance(&endPoint);
// ctrPoint.copyFrom(&begPoint);
// if (parent == NULL) {
// ctrPoint.addXYZRef(&endPoint);
// ctrPoint.multXYZ(0.5f);
// }
// else {
// ctrPoint.addXYZRef(&(parent->tangent), shootLength/2.0f);
// }
}
void init(
GamePlantNode* _parent,
int _maxChildren,
int _numChildren
) {
parent = _parent;
maxChildren = _maxChildren;
numChildren = _numChildren;
sphereRad = 0.0f;
if (maxChildren > 0) {
if (children == NULL) {
children = new GamePlantNode[maxChildren];
}
else {
}
}
}
};
| 642 |
17,242 | // Copyright 2019 The MediaPipe Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mediapipe/framework/formats/matrix.h"
#include <algorithm>
#include "mediapipe/framework/port/core_proto_inc.h"
#include "mediapipe/framework/port/logging.h"
#include "mediapipe/framework/port/proto_ns.h"
#include "mediapipe/framework/port/ret_check.h"
namespace mediapipe {
void MatrixDataProtoFromMatrix(const Matrix& matrix, MatrixData* matrix_data) {
const int rows = matrix.rows();
const int cols = matrix.cols();
matrix_data->set_rows(rows);
matrix_data->set_cols(cols);
matrix_data->clear_layout();
proto_ns::RepeatedField<float>(matrix.data(), matrix.data() + rows * cols)
.Swap(matrix_data->mutable_packed_data());
}
void MatrixFromMatrixDataProto(const MatrixData& matrix_data, Matrix* matrix) {
CHECK_EQ(matrix_data.rows() * matrix_data.cols(),
matrix_data.packed_data_size());
if (matrix_data.layout() == MatrixData::ROW_MAJOR) {
matrix->resize(matrix_data.cols(), matrix_data.rows());
} else {
matrix->resize(matrix_data.rows(), matrix_data.cols());
}
std::copy(matrix_data.packed_data().begin(), matrix_data.packed_data().end(),
matrix->data());
if (matrix_data.layout() == MatrixData::ROW_MAJOR) {
matrix->transposeInPlace();
}
}
#if !defined(MEDIAPIPE_MOBILE) && !defined(MEDIAPIPE_LITE)
std::string MatrixAsTextProto(const Matrix& matrix) {
MatrixData matrix_data;
MatrixDataProtoFromMatrix(matrix, &matrix_data);
return matrix_data.DebugString();
}
void MatrixFromTextProto(const std::string& text_proto, Matrix* matrix) {
CHECK(matrix);
MatrixData matrix_data;
CHECK(proto_ns::TextFormat::ParseFromString(text_proto, &matrix_data));
MatrixFromMatrixDataProto(matrix_data, matrix);
}
#endif // !defined(MEDIAPIPE_MOBILE) && !defined(MEDIAPIPE_LITE)
} // namespace mediapipe
| 831 |
422 | <reponame>hhoppe/Mesh-processing-library<gh_stars>100-1000
// -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt
#include "libHh/EList.h"
using namespace hh;
int main() {
{
struct A {
explicit A(int i) : _i(i) {}
int _i;
EListNode _node;
};
EList list;
A a1(1);
a1._node.link_after(list.delim());
A a2(2);
a2._node.link_after(&a1._node);
int count = 0;
for (EListNode* node : list) {
dummy_use(node);
count++;
}
SHOW(count);
#if 0
// Creating a member function (templated on the class Struct and offset) did not work on win,
// because it was not able to parse the offsetof() function as a template argument.
// Instead, creating a templated subclass worked.
for (auto pa : list.outer_range<A, 8>()) SHOW(pa->_i); // works
for (auto pa : list.outer_range<A, offsetof(A, _node)>()) SHOW(pa->_i); // fails on win
for (auto pa : list.outer_range<A, (offsetof(A, _node))>()) SHOW(pa->_i); // fails on win
const size_t off = offsetof(A, _node);
for (auto pa : list.outer_range<A, off>()) SHOW(pa->_i); // works
for (auto pa : EList::OuterRange<A, off>{list}) SHOW(pa->_i); // works
for (auto pa : EList::OuterRange<A, offsetof(A, _node)>{list}) SHOW(pa->_i); // works
#endif
SHOW("2");
for (A* pa : HH_ELIST_RANGE(list, A, _node)) SHOW(pa->_i);
a2._node.relink_before(&a1._node);
SHOW("relink a2");
for (A* pa : HH_ELIST_RANGE(list, A, _node)) SHOW(pa->_i);
a1._node.unlink();
SHOW("unlink a1");
for (A* pa : HH_ELIST_RANGE(list, A, _node)) SHOW(pa->_i);
a2._node.unlink();
SHOW("unlink a2");
for (A* pa : HH_ELIST_RANGE(list, A, _node)) SHOW(pa->_i);
}
}
| 765 |
1,239 | #include "leptfuzz.h"
extern "C" int
LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if(size<3) return 0;
leptSetStdNullHandler();
PIX *pixs_payload = pixReadMemSpix(data, size);
if(pixs_payload == NULL) return 0;
PIX *pix1, *pix2, *pix3, *pix4, *pix5, *return_pix1, *payload_copy;
pix1 = pixRead("../test8.jpg");
payload_copy = pixCopy(NULL, pixs_payload);
pixBackgroundNormGrayArray(payload_copy, pix1, 10, 10, 10, 10, 256, 10, 10, &pix2);
pixDestroy(&pix1);
pixDestroy(&pix2);
pixDestroy(&payload_copy);
pix1 = pixRead("../test8.jpg");
payload_copy = pixCopy(NULL, pixs_payload);
pixBackgroundNormGrayArrayMorph(payload_copy, pix1, 6, 5, 256, &pix2);
pixDestroy(&pix1);
pixDestroy(&pix2);
pixDestroy(&payload_copy);
pix1 = pixRead("../test8.jpg");
payload_copy = pixCopy(NULL, pixs_payload);
return_pix1 = pixBackgroundNormMorph(payload_copy, pix1, 6, 5, 256);
pixDestroy(&pix1);
pixDestroy(&payload_copy);
pixDestroy(&return_pix1);
pix1 = pixRead("../test8.jpg");
pix2 = pixRead("../test8.jpg");
payload_copy = pixCopy(NULL, pixs_payload);
pixBackgroundNormRGBArrays(payload_copy, pix1, pix2, 10, 10, 10, 10, 130, 10, 10, &pix3, &pix4, &pix5);
pixDestroy(&pix1);
pixDestroy(&pix2);
pixDestroy(&pix3);
pixDestroy(&pix4);
pixDestroy(&pix5);
pixDestroy(&payload_copy);
pix1 = pixRead("../test8.jpg");
payload_copy = pixCopy(NULL, pixs_payload);
pixBackgroundNormRGBArraysMorph(payload_copy, pix1, 6, 33, 130, &pix2, &pix3, &pix4);
pixDestroy(&pix1);
pixDestroy(&pix2);
pixDestroy(&pix3);
pixDestroy(&pix4);
pixDestroy(&payload_copy);
payload_copy = pixCopy(NULL, pixs_payload);
pixContrastNorm(payload_copy, payload_copy, 10, 10, 3, 0, 0);
pixDestroy(&payload_copy);
pix1 = pixRead("../test8.jpg");
payload_copy = pixCopy(NULL, pixs_payload);
return_pix1 = pixGlobalNormNoSatRGB(payload_copy, pix1, 3, 3, 3, 2, 0.9);
pixDestroy(&pix1);
pixDestroy(&payload_copy);
pixDestroy(&return_pix1);
payload_copy = pixCopy(NULL, pixs_payload);
pixThresholdSpreadNorm(payload_copy, L_SOBEL_EDGE, 10, 0, 0, 0.7, -25, 255, 10, &pix1, &pix2, &pix3);
pixDestroy(&pix1);
pixDestroy(&pix2);
pixDestroy(&pix3);
pixDestroy(&payload_copy);
pixDestroy(&pixs_payload);
return 0;
}
| 1,041 |
8,747 | <filename>components/mdns/host_test/main/main.c
#include <stdio.h>
#include "mdns.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
static const char *TAG = "mdns-test";
static void query_mdns_host(const char * host_name)
{
ESP_LOGI(TAG, "Query A: %s.local", host_name);
struct esp_ip4_addr addr;
addr.addr = 0;
esp_err_t err = mdns_query_a(host_name, 2000, &addr);
if(err){
if(err == ESP_ERR_NOT_FOUND){
ESP_LOGW(TAG, "%x: Host was not found!", (err));
return;
}
ESP_LOGE(TAG, "Query Failed: %x", (err));
return;
}
ESP_LOGI(TAG, "Query A: %s.local resolved to: " IPSTR, host_name, IP2STR(&addr));
}
int main(int argc , char *argv[])
{
setvbuf(stdout, NULL, _IONBF, 0);
const esp_netif_inherent_config_t base_cg = { .if_key = "WIFI_STA_DEF", .if_desc = "eth2" };
esp_netif_config_t cfg = { .base = &base_cg };
esp_netif_t *sta = esp_netif_new(&cfg);
mdns_init();
mdns_hostname_set("myesp");
ESP_LOGI(TAG, "mdns hostname set to: [%s]", "myesp");
//set default mDNS instance name
mdns_instance_name_set("myesp-inst");
//structure with TXT records
mdns_txt_item_t serviceTxtData[3] = {
{"board","esp32"},
{"u","user"},
{"p","password"}
};
vTaskDelay(1000);
ESP_ERROR_CHECK(mdns_service_add("myesp-service2", "_http", "_tcp", 80, serviceTxtData, 3));
vTaskDelay(2000);
query_mdns_host("david-comp");
vTaskDelay(2000);
esp_netif_destroy(sta);
mdns_free();
ESP_LOGI(TAG, "Exit");
return 0;
}
| 778 |
1,738 | <reponame>jeikabu/lumberyard
/*
* 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 AZCORE_MATH_AABB_H
#define AZCORE_MATH_AABB_H 1
#include <AzCore/base.h>
#include <AzCore/Math/Vector3.h>
namespace AZ
{
class Obb;
/**
* An axis aligned bounding box. It is defined as an closed set, i.e. it includes the boundary, so it
* will always include at least one point.
*/
class Aabb
{
friend void MathReflect(class BehaviorContext&);
friend void MathReflect(class SerializeContext&);
public:
//AZ_DECLARE_CLASS_POOL_ALLOCATOR(Aabb);
AZ_TYPE_INFO(Aabb, "{A54C2B36-D5B8-46A1-A529-4EBDBD2450E7}")
Aabb() { }
///Creates a null AABB, this is an invalid AABB which has no size, but is useful as adding a point to it will make it valid
static AZ_MATH_FORCE_INLINE const Aabb CreateNull() { Aabb result; result.m_min = Vector3(g_fltMax); result.m_max = Vector3(-g_fltMax); return result; }
static AZ_MATH_FORCE_INLINE const Aabb CreateFromPoint(const Vector3& p)
{
Aabb aabb;
aabb.m_min = p;
aabb.m_max = p;
return aabb;
}
static AZ_MATH_FORCE_INLINE const Aabb CreateFromMinMax(const Vector3& min, const Vector3& max)
{
Aabb aabb;
aabb.m_min = min;
aabb.m_max = max;
AZ_Assert(aabb.IsValid(), "Min must be less than Max");
return aabb;
}
static AZ_MATH_FORCE_INLINE const Aabb CreateCenterHalfExtents(const Vector3& center, const Vector3& halfExtents)
{
Aabb aabb;
aabb.m_min = center - halfExtents;
aabb.m_max = center + halfExtents;
return aabb;
}
static AZ_MATH_FORCE_INLINE const Aabb CreateCenterRadius(const Vector3& center, const VectorFloat& radius) { return CreateCenterHalfExtents(center, Vector3(radius)); }
///Creates an AABB which contains the specified points
static AZ_MATH_FORCE_INLINE const Aabb CreatePoints(const Vector3* pts, int numPts)
{
Aabb aabb = Aabb::CreateFromPoint(pts[0]);
for (int i = 1; i < numPts; ++i)
{
aabb.AddPoint(pts[i]);
}
return aabb;
}
///Creates an AABB which contains the specified OBB
static const Aabb CreateFromObb(const Obb& obb);
AZ_MATH_FORCE_INLINE const Vector3& GetMin() const { return m_min; }
AZ_MATH_FORCE_INLINE const Vector3& GetMax() const { return m_max; }
AZ_MATH_FORCE_INLINE void Set(const Vector3& min, const Vector3& max)
{
m_min = min;
m_max = max;
AZ_Assert(IsValid(), "Min must be less than Max");
}
AZ_MATH_FORCE_INLINE void SetMin(const Vector3& min) { m_min = min; }
AZ_MATH_FORCE_INLINE void SetMax(const Vector3& max) { m_max = max; }
AZ_FORCE_INLINE bool operator==(const AZ::Aabb& aabb) const
{
return (GetMin() == aabb.GetMin()) && (GetMax() == aabb.GetMax());
}
AZ_FORCE_INLINE bool operator!=(const AZ::Aabb& aabb) const
{
return !(*this == aabb);
}
AZ_MATH_FORCE_INLINE const VectorFloat GetWidth() const { return m_max.GetX() - m_min.GetX(); }
AZ_MATH_FORCE_INLINE const VectorFloat GetHeight() const { return m_max.GetY() - m_min.GetY(); }
AZ_MATH_FORCE_INLINE const VectorFloat GetDepth() const { return m_max.GetZ() - m_min.GetZ(); }
AZ_MATH_FORCE_INLINE const Vector3 GetExtents() const { return m_max - m_min; }
AZ_MATH_FORCE_INLINE const Vector3 GetCenter() const { return 0.5f * (m_min + m_max); }
AZ_MATH_FORCE_INLINE void GetAsSphere(Vector3& center, VectorFloat& radius) const
{
center = GetCenter();
radius = (m_max - center).GetLength();
}
AZ_MATH_FORCE_INLINE bool Contains(const Vector3& v) const
{
return v.IsGreaterEqualThan(m_min) && v.IsLessEqualThan(m_max);
}
AZ_MATH_FORCE_INLINE bool Contains(const Aabb& aabb) const
{
return aabb.GetMin().IsGreaterEqualThan(m_min) && aabb.GetMax().IsLessEqualThan(m_max);
}
AZ_MATH_FORCE_INLINE bool Overlaps(const Aabb& aabb) const
{
return m_min.IsLessEqualThan(aabb.m_max) && m_max.IsGreaterEqualThan(aabb.m_min);
}
AZ_MATH_FORCE_INLINE void Expand(const Vector3& delta)
{
AZ_Assert(delta.IsGreaterEqualThan(Vector3::CreateZero()), "delta must be positive");
m_min -= delta;
m_max += delta;
}
AZ_MATH_FORCE_INLINE const Aabb GetExpanded(const Vector3& delta) const
{
AZ_Assert(delta.IsGreaterEqualThan(Vector3::CreateZero()), "delta must be positive");
return Aabb::CreateFromMinMax(m_min - delta, m_max + delta);
}
AZ_MATH_FORCE_INLINE void AddPoint(const Vector3& p)
{
m_min = m_min.GetMin(p);
m_max = m_max.GetMax(p);
}
AZ_MATH_FORCE_INLINE void AddAabb(const Aabb& box)
{
m_min = m_min.GetMin(box.GetMin());
m_max = m_max.GetMax(box.GetMax());
}
///Calculates distance from the AABB to specified point, a point inside the AABB will return zero
AZ_MATH_FORCE_INLINE const VectorFloat GetDistance(const Vector3& p) const
{
Vector3 closest = p.GetClamp(m_min, m_max);
return p.GetDistance(closest);
}
///Calculates squared distance from the AABB to specified point, a point inside the AABB will return zero
AZ_MATH_FORCE_INLINE const VectorFloat GetDistanceSq(const Vector3& p) const
{
Vector3 closest = p.GetClamp(m_min, m_max);
return p.GetDistanceSq(closest);
}
///Calculates maximum distance from the AABB to specified point.
///This will always be at least the distance from the center to the corner, even for points inside the AABB.
AZ_MATH_FORCE_INLINE const VectorFloat GetMaxDistance(const Vector3& p) const
{
Vector3 farthest(Vector3::CreateSelectCmpGreaterEqual(p, GetCenter(), m_min, m_max));
return p.GetDistance(farthest);
}
///Calculates maximum squared distance from the AABB to specified point.
///This will always be at least the squared distance from the center to the corner, even for points inside the AABB.
AZ_MATH_FORCE_INLINE const VectorFloat GetMaxDistanceSq(const Vector3& p) const
{
Vector3 farthest(Vector3::CreateSelectCmpGreaterEqual(p, GetCenter(), m_min, m_max));
return p.GetDistanceSq(farthest);
}
///Clamps the AABB to be contained within the specified AABB
AZ_MATH_FORCE_INLINE const Aabb GetClamped(const Aabb& clamp) const
{
Aabb clampedAabb = Aabb::CreateFromMinMax(m_min, m_max);
clampedAabb.Clamp(clamp);
return clampedAabb;
}
AZ_MATH_FORCE_INLINE void Clamp(const Aabb& clamp)
{
m_min = m_min.GetClamp(clamp.m_min, clamp.m_max);
m_max = m_max.GetClamp(clamp.m_min, clamp.m_max);
}
AZ_MATH_FORCE_INLINE void SetNull()
{
m_min = Vector3(g_fltMax);
m_max = Vector3(-g_fltMax);
}
AZ_MATH_FORCE_INLINE void Translate(const Vector3& offset)
{
m_min += offset;
m_max += offset;
}
AZ_MATH_FORCE_INLINE const Aabb GetTranslated(const Vector3& offset) const
{
return Aabb::CreateFromMinMax(m_min + offset, m_max + offset);
}
AZ_MATH_FORCE_INLINE float GetSurfaceArea() const
{
VectorFloat w = GetWidth();
VectorFloat h = GetHeight();
VectorFloat d = GetDepth();
return VectorFloat(2.0f) * (w * h + h * d + d * w);
}
/************************************************************************
*
************************************************************************/
void ApplyTransform(const Transform& transform);
/**
* Transforms an Aabb and returns the resulting Obb.
*/
const class Obb GetTransformedObb(const Transform& transform) const;
/**
* Returns a new AABB containing the transformed AABB
*/
AZ_MATH_FORCE_INLINE const Aabb GetTransformedAabb(const Transform& transform) const
{
Aabb aabb = Aabb::CreateFromMinMax(m_min, m_max);
aabb.ApplyTransform(transform);
return aabb;
}
AZ_MATH_FORCE_INLINE bool IsValid() const { return m_min.IsLessEqualThan(m_max); }
AZ_MATH_FORCE_INLINE bool IsFinite() const { return m_min.IsFinite() && m_max.IsFinite(); }
protected:
Vector3 m_min;
Vector3 m_max;
};
}
#endif
#pragma once | 4,435 |
1,572 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.authenticator.otp;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static com.google.common.truth.Truth.assertThat;
import static org.hamcrest.Matchers.equalTo;
import android.app.Instrumentation;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import com.google.android.apps.authenticator.otp.AccountDb.AccountIndex;
import com.google.android.apps.authenticator.otp.AccountDb.OtpType;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator.testing.TestUtilities;
import com.google.android.apps.authenticator.util.annotations.FixWhenMinSdkVersion;
import com.google.android.apps.authenticator2.R;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Unit tests for {@link EnterKeyActivity}. */
@RunWith(AndroidJUnit4.class)
@SmallTest
public class EnterKeyActivityTest {
private EnterKeyActivity activity;
private Instrumentation instr;
private EditText keyEntryField;
private EditText accountName;
private TextInputLayout keyEntryFieldInputLayout;
private RadioButton typeTotp;
private RadioButton typeHotp;
private Button submitButton;
private AccountDb accountDb;
@Rule public ActivityTestRule<EnterKeyActivity> activityTestRule =
new ActivityTestRule<>(
EnterKeyActivity.class, /* initialTouchMode= */ false, /* launchActivity= */ false);
@Before
public void setUp() throws Exception {
DependencyInjector.resetForIntegrationTesting(
InstrumentationRegistry.getInstrumentation().getTargetContext());
TestUtilities.withLaunchPreventingStartActivityListenerInDependencyResolver();
accountDb = DependencyInjector.getAccountDb();
instr = InstrumentationRegistry.getInstrumentation();
activity = activityTestRule.launchActivity(null);
accountName = activity.findViewById(R.id.account_name);
keyEntryField = activity.findViewById(R.id.key_value);
typeTotp = activity.findViewById(R.id.type_choice_totp);
typeHotp = activity.findViewById(R.id.type_choice_hotp);
submitButton = activity.findViewById(R.id.add_account_button_enter_key);
keyEntryFieldInputLayout = activity.findViewById(R.id.key_value_input_layout);
}
@After
public void tearDown() throws Exception {
DependencyInjector.close();
}
@Test
public void testPreconditions() {
// check that the test has input fields
assertThat(accountName).isNotNull();
assertThat(keyEntryField).isNotNull();
assertThat(typeTotp).isNotNull();
assertThat(typeHotp).isNotNull();
assertThat(typeTotp.isChecked() || typeHotp.isChecked()).isTrue();
}
@Test
public void testStartingFieldValues() {
assertThat(accountName.getText().toString()).isEqualTo("");
assertThat(keyEntryField.getText().toString()).isEqualTo("");
assertThat(activity.getResources().getStringArray(R.array.type)[OtpType.TOTP.value])
.isEqualTo(typeTotp.getText().toString());
assertThat(activity.getResources().getStringArray(R.array.type)[OtpType.HOTP.value])
.isEqualTo(typeHotp.getText().toString());
}
@Test
public void testFieldsAreOnScreen() {
onView(equalTo(accountName)).check(matches(isDisplayed()));
onView(equalTo(keyEntryField)).check(matches(isDisplayed()));
onView(equalTo(typeTotp)).check(matches(isDisplayed()));
onView(equalTo(typeHotp)).check(matches(isDisplayed()));
onView(equalTo(submitButton)).check(matches(isDisplayed()));
}
private void checkCorrectEntry(
String accountName, String expectedIndexName, AccountDb.OtpType type) {
// enter account name
TestUtilities.setText(instr, this.accountName, accountName);
// enter key
TestUtilities.setText(instr, keyEntryField, "7777777777777777");
if (type == OtpType.TOTP) {
TestUtilities.clickView(instr, typeTotp);
} else {
TestUtilities.clickView(instr, typeHotp);
}
assertThat(activity.isFinishing()).isFalse();
// save
TestUtilities.clickView(instr, submitButton);
// check activity's resulting update of database.
AccountIndex index = new AccountIndex(expectedIndexName, null);
assertThat(accountDb.indexExists(index)).isTrue();
assertThat(accountDb.getType(index)).isEqualTo(type);
assertThat(accountDb.getCounter(index).intValue()).isEqualTo(0);
assertThat(activity.isFinishing()).isTrue();
}
@Test
public void testCorrectEntryTOTP() {
String accountName = "<EMAIL>";
checkCorrectEntry(accountName, accountName, AccountDb.OtpType.TOTP);
assertThat(accountDb.getAccounts()).hasSize(1);
}
@Test
public void testCorrectEntryHOTP() {
String accountName = "<EMAIL>";
checkCorrectEntry(accountName, accountName, AccountDb.OtpType.HOTP);
assertThat(accountDb.getAccounts()).hasSize(1);
}
@Test
public void testCorrectEntryWithDuplicateNullIssuerName() {
String accountName = "<EMAIL>";
accountDb.add(accountName, "2222222222222222", OtpType.TOTP, null, null, null);
checkCorrectEntry(accountName, accountName + "(1)", AccountDb.OtpType.TOTP);
assertThat(accountDb.getAccounts()).hasSize(2);
}
@Test
public void testCorrectEntryWithDuplicateIssuerName() {
String accountName = "<EMAIL>";
accountDb.add(
accountName, "2222222222222222", OtpType.TOTP, null, null, AccountDb.GOOGLE_ISSUER_NAME);
checkCorrectEntry(accountName, accountName, AccountDb.OtpType.TOTP);
assertThat(accountDb.getAccounts()).hasSize(2);
}
@Test
public void testCorrectEntryWithFullyQualifiedNameAndDuplicateNullIssuerName() {
String accountName = "<EMAIL>";
accountDb.add(accountName, "2222222222222222", OtpType.TOTP, null, null, null);
// Enter a fully qualified account name with an issuer in front
accountName = AccountDb.GOOGLE_ISSUER_NAME + ":" + accountName;
// No collision should occur
checkCorrectEntry(accountName, accountName, AccountDb.OtpType.TOTP);
assertThat(accountDb.getAccounts()).hasSize(2);
}
@Test
public void testCorrectEntryWithFullyQualifiedNameAndDuplicateIssuerName() {
String accountName = "<EMAIL>";
accountDb.add(
accountName, "2222222222222222", OtpType.TOTP, null, null, AccountDb.GOOGLE_ISSUER_NAME);
// Enter a fully qualified account name with an issuer in front
accountName = AccountDb.GOOGLE_ISSUER_NAME + ":" + accountName;
// The null issuer always displays the unaltered version of the name, even after a collision
checkCorrectEntry(accountName, accountName, AccountDb.OtpType.TOTP);
assertThat(accountDb.getAccounts()).hasSize(2);
}
@Test
public void testSubmitFailsWithShortKey() {
TestUtilities.setText(instr, accountName, "<EMAIL>");
TestUtilities.clickView(instr, typeTotp);
// enter bad key without submitting, check status message
TestUtilities.setText(instr, keyEntryField, "@@");
assertThat(keyEntryFieldInputLayout.getError().toString())
.isEqualTo(activity.getString(R.string.enter_key_illegal_char));
// clear bad keys, see status message is cleared.
TestUtilities.setText(instr, keyEntryField, "");
assertThat(keyEntryFieldInputLayout.getError()).isNull();
// enter short key, check status message is empty
TestUtilities.setText(instr, keyEntryField, "77777");
assertThat(keyEntryFieldInputLayout.getError()).isNull();
// submit short key, and verify no updates to database and check status msg.
TestUtilities.clickView(instr, submitButton);
assertThat(activity.isFinishing()).isFalse();
assertThat(accountDb.getAccounts()).isEmpty();
assertThat(keyEntryFieldInputLayout.getError().toString())
.isEqualTo(activity.getString(R.string.enter_key_too_short));
// check key field is unchanged.
assertThat(keyEntryField.getText().toString()).isEqualTo("77777");
// submit empty key.
TestUtilities.setText(instr, keyEntryField, "");
TestUtilities.clickView(instr, submitButton);
assertThat(activity.isFinishing()).isFalse();
assertThat(accountDb.getAccounts()).isEmpty();
assertThat(keyEntryFieldInputLayout.getError().toString())
.isEqualTo(activity.getString(R.string.enter_key_too_short));
}
@Test
public void testSubmitWithEmptyAccountName() {
TestUtilities.setText(instr, keyEntryField, "7777777777777777");
TestUtilities.clickView(instr, typeTotp);
// enter empty name
TestUtilities.setText(instr, accountName, "");
TestUtilities.clickView(instr, submitButton);
assertThat(accountDb.getAccounts()).hasSize(1);
assertThat(accountDb.getSecret(new AccountIndex("", null))).isEqualTo("7777777777777777");
}
@Test
public void testSubmitWithWeirdAccountName() {
TestUtilities.setText(instr, keyEntryField, "7777777777777777");
TestUtilities.clickView(instr, typeTotp);
// enter empty name
TestUtilities.setText(instr, accountName, ",,");
TestUtilities.clickView(instr, submitButton);
assertThat(accountDb.getAccounts()).hasSize(1);
assertThat(accountDb.getSecret(new AccountIndex(",,", null))).isEqualTo("7777777777777777");
}
}
| 3,487 |
5,169 | <reponame>morizotter/Specs<filename>Specs/BPPhotoLibrarian/1.0.0/BPPhotoLibrarian.podspec.json
{
"name": "BPPhotoLibrarian",
"version": "1.0.0",
"summary": "Simple helpers for accessing the iOS photo library.",
"homepage": "https://github.com/brianpartridge/BPPhotoLibrarian",
"license": {
"type": "MIT",
"file": "LICENSE.txt"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/brianpartridge/BPPhotoLibrarian.git",
"tag": "1.0.0"
},
"platforms": {
"ios": "6.0"
},
"source_files": [
"BPPhotoLibrarian",
"BPPhotoLibrarian/**/*.{h,m}"
],
"frameworks": [
"AssetsLibrary",
"MobileCoreServices"
],
"requires_arc": true
}
| 303 |
1,338 | <reponame>Kirishikesan/haiku<gh_stars>1000+
#include <Application.h>
#include <View.h>
#include <Window.h>
class MouseView : public BView {
public:
MouseView(BRect frame, bool noHistory);
~MouseView();
virtual void AttachedToWindow();
virtual void MouseMoved(BPoint point, uint32 transit,
const BMessage *message);
virtual void MouseDown(BPoint point);
virtual void MouseUp(BPoint point);
private:
bool fNoHistory;
};
MouseView::MouseView(BRect frame, bool noHistory)
: BView(frame, "MouseView", B_FOLLOW_ALL, B_WILL_DRAW),
fNoHistory(noHistory)
{
SetViewColor(255, 255, 200);
if (noHistory)
SetHighColor(200, 0, 0);
else
SetHighColor(0, 200, 0);
}
MouseView::~MouseView()
{
}
void
MouseView::AttachedToWindow()
{
if (fNoHistory)
SetEventMask(0, B_NO_POINTER_HISTORY);
}
void
MouseView::MouseDown(BPoint point)
{
SetMouseEventMask(0, B_NO_POINTER_HISTORY);
SetHighColor(0, 0, 200);
}
void
MouseView::MouseUp(BPoint point)
{
if (fNoHistory)
SetHighColor(200, 0, 0);
else
SetHighColor(0, 200, 0);
}
void
MouseView::MouseMoved(BPoint point, uint32 transit, const BMessage *message)
{
FillRect(BRect(point - BPoint(1, 1), point + BPoint(1, 1)));
snooze(25000);
}
// #pragma mark -
int
main(int argc, char** argv)
{
BApplication app("application/x-vnd.Simon-NoPointerHistory");
BWindow* window = new BWindow(BRect(100, 100, 700, 400), "Window",
B_TITLED_WINDOW, B_QUIT_ON_WINDOW_CLOSE);
window->AddChild(new MouseView(BRect(10, 10, 295, 290), true));
window->AddChild(new MouseView(BRect(305, 10, 590, 290), false));
window->Show();
app.Run();
return 0;
}
| 641 |
319 | <reponame>imshyam/mintube
package com.shapps.mintubeapp.adapter;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.shapps.mintubeapp.R;
public class SuggestionCursorAdapter extends CursorAdapter {
private SearchView searchView;
public SuggestionCursorAdapter(Context context, Cursor c, boolean autoRequery, SearchView searchView) {
super(context, c, autoRequery);
this.searchView = searchView;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.search_suggestion_list_item, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
final TextView suggest = view.findViewById(R.id.suggest);
ImageView putInSearchBox = view.findViewById(R.id.put_in_search_box);
String body = cursor.getString(cursor.getColumnIndexOrThrow("suggestion"));
suggest.setText(body);
suggest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchView.setQuery(suggest.getText(), true);
searchView.clearFocus();
}
});
putInSearchBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchView.setQuery(suggest.getText(), false);
}
});
}
}
| 675 |
550 | <gh_stars>100-1000
import os
import warnings
from IPython import get_ipython
from glue.core.hub import HubListener
from glue.core import BaseData, Subset
from glue.core import command
from glue.core.command import ApplySubsetState
from glue.core.state import save
from glue.core import message as msg
from glue.core.exceptions import IncompatibleDataException
from glue.core.state import lookup_class_with_patches
from echo import delay_callback, ignore_callback
from glue.core.layer_artist import LayerArtistContainer
from glue.viewers.common.state import ViewerState
from glue.viewers.common.layer_artist import LayerArtist
from glue.config import layer_artist_maker
__all__ = ['BaseViewer', 'Viewer']
def get_layer_artist_from_registry(data, viewer):
"""
Check whether any plugins define an appropriate custom layer artist for
the specified data and viewer.
"""
for maker in layer_artist_maker.members:
layer_artist = maker.function(viewer, data)
if layer_artist is not None:
return layer_artist
class BaseViewer(HubListener):
"""
The base class for all viewers.
"""
LABEL = 'Override this'
def __init__(self, session):
self._session = session
self._data = session.data_collection
self._hub = None
def register_to_hub(self, hub):
self._hub = hub
@property
def session(self):
return self._session
def request_add_layer(self, layer):
""" Issue a command to add a layer """
cmd = command.AddLayer(layer=layer, viewer=self)
self._session.command_stack.do(cmd)
def add_layer(self, layer):
if isinstance(layer, BaseData):
self.add_data(layer)
elif isinstance(layer, Subset):
self.add_subset(layer)
def remove_layer(self, layer):
pass
def add_data(self, data):
raise NotImplementedError()
def add_subset(self, subset):
raise NotImplementedError()
def __str__(self):
return self.LABEL
def __gluestate__(self, context):
return dict(session=context.id(self._session))
@classmethod
def __setgluestate__(cls, rec, context):
session = context.object(rec['session'])
return cls(session)
def apply_subset_state(self, subset_state, override_mode=None):
cmd = ApplySubsetState(data_collection=self._data,
subset_state=subset_state,
override_mode=override_mode)
self._session.command_stack.do(cmd)
TEMPLATE_SCRIPT = """
# This script was produced by glue and can be used to further customize a
# particular plot.
### Package imports
{imports}
### Set up data
data_collection = load('{data}')
### Set up viewer
{header}
### Set up layers
{layers}
### Legend
{legend}
### Finalize viewer
{footer}
""".strip()
class Viewer(BaseViewer):
"""
A viewer class that uses a state class to represent the overall viewer
state, and uses layer artists and state classes to handle each dataset
and subset in the data viewer.
"""
# The LayerArtistContainer class/subclass to use
_layer_artist_container_cls = LayerArtistContainer
# The state class/subclass to use
_state_cls = ViewerState
_data_artist_cls = LayerArtist
_subset_artist_cls = LayerArtist
allow_duplicate_data = False
allow_duplicate_subset = False
large_data_size = None
def __init__(self, session, state=None):
super(Viewer, self).__init__(session)
# Set up the state which will contain everything needed to represent
# the current state of the viewer
self.state = state or self._state_cls()
self.state.data_collection = session.data_collection
# Create the layer artist container, which is the object in which
# we will add LayerArtist objects
self._layer_artist_container = self._layer_artist_container_cls()
# When layer artists are removed from the layer artist container, we
# need to make sure we remove matching layer states in the viewer state
# layers attribute.
self._layer_artist_container.on_changed(self._sync_state_layers)
# And vice-versa when layer states are removed from the viewer state, we
# need to keep the layer_artist_container in sync
self.state.add_callback('layers', self._sync_layer_artist_container, priority=10000)
self.state.add_callback('layers', self.draw_legend)
def draw_legend(self, *args):
pass
def _sync_state_layers(self, *args):
# Remove layer state objects that no longer have a matching layer
for layer_state in self.state.layers:
if layer_state.layer not in self._layer_artist_container:
self.state.layers.remove(layer_state)
def _sync_layer_artist_container(self, *args):
# Remove layer artists that no longer have a matching layer state
layer_states = set(layer_state.layer for layer_state in self.state.layers)
for layer_artist in self._layer_artist_container:
if layer_artist.layer not in layer_states:
self._layer_artist_container.remove(layer_artist)
def warn(self, message, *args, **kwargs):
warnings.warn(message)
return True
def add_data(self, data):
# Check if data already exists in viewer
if not self.allow_duplicate_data and data in self._layer_artist_container:
return True
if self.large_data_size is not None and data.size >= self.large_data_size:
proceed = self.warn('Add large data set?', 'Data set {0:s} has {1:d} points, and '
'may render slowly.'.format(data.label, data.size),
default='Cancel', setting='show_large_data_warning')
if not proceed:
return False
if data not in self.session.data_collection:
raise IncompatibleDataException("Data not in DataCollection")
# Create layer artist and add to container. First check whether any
# plugins want to make a custom layer artist.
layer = get_layer_artist_from_registry(data, self) or self.get_data_layer_artist(data)
if layer is None:
return False
# When adding a layer artist to the layer artist container, zorder
# gets set automatically - however since we call a forced update of the
# layer after adding it to the container we can ignore any callbacks
# related to zorder. We also then need to set layer.state.zorder manually.
with ignore_callback(layer.state, 'zorder'):
self._layer_artist_container.append(layer)
layer.update()
self.draw_legend() # need to be called here because callbacks are ignored in previous step
# Add existing subsets to viewer
for subset in data.subsets:
self.add_subset(subset)
return True
def remove_data(self, data):
with delay_callback(self.state, 'layers'):
for layer_state in self.state.layers[::-1]:
if isinstance(layer_state.layer, BaseData):
if layer_state.layer is data:
self.state.layers.remove(layer_state)
else:
if layer_state.layer.data is data:
self.state.layers.remove(layer_state)
def get_data_layer_artist(self, layer=None, layer_state=None):
return self.get_layer_artist(self._data_artist_cls, layer=layer, layer_state=layer_state)
def get_subset_layer_artist(self, layer=None, layer_state=None):
return self.get_layer_artist(self._subset_artist_cls, layer=layer, layer_state=layer_state)
def get_layer_artist(self, cls, layer=None, layer_state=None):
return cls(self.state, layer=layer, layer_state=layer_state)
def add_subset(self, subset):
# Check if subset already exists in viewer
if not self.allow_duplicate_subset and subset in self._layer_artist_container:
return True
# Create layer artist and add to container. First check whether any
# plugins want to make a custom layer artist.
layer = get_layer_artist_from_registry(subset, self) or self.get_subset_layer_artist(subset)
if layer is None:
return False
# When adding a layer artist to the layer artist container, zorder
# gets set automatically - however since we call a forced update of the
# layer after adding it to the container we can ignore any callbacks
# related to zorder.
with ignore_callback(layer.state, 'zorder'):
self._layer_artist_container.append(layer)
layer.update()
self.draw_legend() # need to be called here because callbacks are ignored in previous step
return True
def remove_subset(self, subset):
if subset in self._layer_artist_container:
self._layer_artist_container.pop(subset)
def _add_subset(self, message):
self.add_subset(message.subset)
def _update_data(self, message):
if message.data in self._layer_artist_container:
for layer_artist in self._layer_artist_container:
if isinstance(layer_artist.layer, Subset):
if layer_artist.layer.data is message.data:
layer_artist.update()
else:
if layer_artist.layer is message.data:
layer_artist.update()
def _update_subset(self, message):
if message.attribute == 'style':
return
if message.subset in self._layer_artist_container:
for layer_artist in self._layer_artist_container[message.subset]:
layer_artist.update()
def _remove_subset(self, message):
self.remove_subset(message.subset)
def options_widget(self):
return self.options
def _subset_has_data(self, x):
return x.sender.data in self._layer_artist_container.layers
def _has_data_or_subset(self, x):
return x.sender in self._layer_artist_container.layers
def _remove_data(self, message):
self.remove_data(message.data)
def _is_appearance_settings(self, msg):
return ('BACKGROUND_COLOR' in msg.settings or
'FOREGROUND_COLOR' in msg.settings)
def register_to_hub(self, hub):
super(Viewer, self).register_to_hub(hub)
hub.subscribe(self, msg.SubsetCreateMessage,
handler=self._add_subset,
filter=self._subset_has_data)
hub.subscribe(self, msg.SubsetUpdateMessage,
handler=self._update_subset,
filter=self._has_data_or_subset)
hub.subscribe(self, msg.SubsetDeleteMessage,
handler=self._remove_subset,
filter=self._has_data_or_subset)
hub.subscribe(self, msg.NumericalDataChangedMessage,
handler=self._update_data,
filter=self._has_data_or_subset)
hub.subscribe(self, msg.DataCollectionDeleteMessage,
handler=self._remove_data)
hub.subscribe(self, msg.ComponentsChangedMessage,
handler=self._update_data,
filter=self._has_data_or_subset)
hub.subscribe(self, msg.ExternallyDerivableComponentsChangedMessage,
handler=self._update_data,
filter=self._has_data_or_subset)
hub.subscribe(self, msg.SettingsChangeMessage,
self._update_appearance_from_settings,
filter=self._is_appearance_settings)
hub.subscribe(self, msg.ComputationMessage,
self._update_computation,
filter=self._has_layer_artist)
hub.subscribe(self, msg.LayerArtistDisabledMessage,
self.draw_legend,
filter=self._has_layer_artist)
def _has_layer_artist(self, message):
return message.layer_artist in self.layers
def _update_computation(self, message=None):
pass
def _update_appearance_from_settings(self, message=None):
pass
def __gluestate__(self, context):
return dict(state=self.state.__gluestate__(context),
session=context.id(self._session),
layers=list(map(context.do, self.layers)),
_protocol=1)
@classmethod
def __setgluestate__(cls, rec, context):
session = context.object(rec['session'])
viewer_state = cls._state_cls.__setgluestate__(rec['state'], context)
viewer = cls(session, state=viewer_state)
viewer.register_to_hub(session.hub)
# Restore layer artists. Ideally we would delay instead of ignoring the
# callback here.
with viewer._layer_artist_container.ignore_callbacks():
for l in rec['layers']:
cls = lookup_class_with_patches(l.pop('_type'))
layer_state = context.object(l['state'])
layer_artist = viewer.get_layer_artist(cls, layer_state=layer_state)
layer_state.viewer_state = viewer.state
viewer._layer_artist_container.append(layer_artist)
viewer.draw_legend() # need to be called here because callbacks are ignored in previous step
return viewer
def cleanup(self):
if self._hub is not None:
self.unregister(self._hub)
self._layer_artist_container.clear_callbacks()
self._layer_artist_container.clear()
# Remove any references to the viewer in the IPython namespace. We use
# list() here to force an explicit copy since we are modifying the
# dictionary in-place
shell = get_ipython()
if shell is not None:
for key in list(shell.user_ns):
if shell.user_ns[key] is self:
shell.user_ns.pop(key)
def remove_layer(self, layer):
self._layer_artist_container.pop(layer)
@property
def layers(self):
"""Return a tuple of layers in this viewer.
A layer is a visual representation of a dataset or subset within
the viewer"""
return tuple(self._layer_artist_container)
def _script_header(self):
raise NotImplementedError()
def _script_legend(self):
return [], ""
def _script_footer(self):
raise NotImplementedError()
def export_as_script(self, filename):
data_filename = os.path.relpath(filename) + '.data'
save(data_filename, self.session.data_collection)
imports = ['from glue.core.state import load']
imports_header, header = self._script_header()
imports.extend(imports_header)
layers = ""
for ilayer, layer in enumerate(self.layers):
if layer.layer.label:
layers += '## Layer {0}: {1}\n\n'.format(ilayer + 1, layer.layer.label)
else:
layers += '## Layer {0}\n\n'.format(ilayer + 1)
if layer.visible and layer.enabled:
if isinstance(layer.layer, BaseData):
index = self.session.data_collection.index(layer.layer)
layers += "layer_data = data_collection[{0}]\n\n".format(index)
else:
dindex = self.session.data_collection.index(layer.layer.data)
sindex = layer.layer.data.subsets.index(layer.layer)
layers += ("layer_data = data_collection[{0}].subsets[{1}]\n\n"
.format(dindex, sindex))
imports_layer, layer_script = layer._python_exporter(layer)
if layer_script is None:
continue
imports.extend(imports_layer)
layers += layer_script.strip() + "\n"
imports_legend, legend = self._script_legend()
imports.extend(imports_legend)
imports_footer, footer = self._script_footer()
imports.extend(imports_footer)
imports = os.linesep.join(sorted(set(imports),
key=lambda s: s.strip('# ')))
# The sorting key is added keep together similar but commented imports
# Typical ex:
# matplotlib.use('Agg')
# # matplotlib.use('qt5Agg')
script = TEMPLATE_SCRIPT.format(data=os.path.basename(data_filename),
imports=imports.strip(),
header=header.strip(),
layers=layers.strip(),
legend=legend.strip(),
footer=footer.strip())
with open(filename, 'w') as f:
f.write(script)
| 7,281 |
2,587 | package cn.hikyson.godeye.core.internal.modules.fps;
import androidx.annotation.Keep;
import java.io.Serializable;
@Keep
public class FpsConfig implements Serializable {
public long intervalMillis;
public FpsConfig(long intervalMillis) {
this.intervalMillis = intervalMillis;
}
public FpsConfig() {
this.intervalMillis = 2000;
}
public long intervalMillis() {
return intervalMillis;
}
@Override
public String toString() {
return "FpsConfig{" +
"intervalMillis=" + intervalMillis +
'}';
}
} | 249 |
568 | <gh_stars>100-1000
package com.jim.framework.web.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by jiang on 2016/12/22.
*/
public class BaseService {
protected Logger logger = LoggerFactory.getLogger(getClass().getName());
}
| 108 |
301 | package commons.model;
import java.util.Map;
import com.google.gson.annotations.SerializedName;
public class Command {
private String capabilityId;
private String sensorId;
@SerializedName("command")
private Map<String, Object> properties;
public String getCapabilityId() {
return capabilityId;
}
public void setCapabilityId(String capabilityId) {
this.capabilityId = capabilityId;
}
public String getSensorId() {
return sensorId;
}
public void setSensorId(String sensorId) {
this.sensorId = sensorId;
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
}
| 223 |
3,645 | /*
* Copyright (c) 2003 <NAME> <<EMAIL>>
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "libavutil/attributes.h"
#include "libavutil/cpu.h"
#include "libavutil/mem.h"
#include "libavutil/x86/asm.h"
#include "libavfilter/vf_spp.h"
#if HAVE_MMX_INLINE
static void hardthresh_mmx(int16_t dst[64], const int16_t src[64],
int qp, const uint8_t *permutation)
{
int bias = 0; //FIXME
unsigned int threshold1;
threshold1 = qp * ((1<<4) - bias) - 1;
#define REQUANT_CORE(dst0, dst1, dst2, dst3, src0, src1, src2, src3) \
"movq " #src0 ", %%mm0 \n" \
"movq " #src1 ", %%mm1 \n" \
"movq " #src2 ", %%mm2 \n" \
"movq " #src3 ", %%mm3 \n" \
"psubw %%mm4, %%mm0 \n" \
"psubw %%mm4, %%mm1 \n" \
"psubw %%mm4, %%mm2 \n" \
"psubw %%mm4, %%mm3 \n" \
"paddusw %%mm5, %%mm0 \n" \
"paddusw %%mm5, %%mm1 \n" \
"paddusw %%mm5, %%mm2 \n" \
"paddusw %%mm5, %%mm3 \n" \
"paddw %%mm6, %%mm0 \n" \
"paddw %%mm6, %%mm1 \n" \
"paddw %%mm6, %%mm2 \n" \
"paddw %%mm6, %%mm3 \n" \
"psubusw %%mm6, %%mm0 \n" \
"psubusw %%mm6, %%mm1 \n" \
"psubusw %%mm6, %%mm2 \n" \
"psubusw %%mm6, %%mm3 \n" \
"psraw $3, %%mm0 \n" \
"psraw $3, %%mm1 \n" \
"psraw $3, %%mm2 \n" \
"psraw $3, %%mm3 \n" \
\
"movq %%mm0, %%mm7 \n" \
"punpcklwd %%mm2, %%mm0 \n" /*A*/ \
"punpckhwd %%mm2, %%mm7 \n" /*C*/ \
"movq %%mm1, %%mm2 \n" \
"punpcklwd %%mm3, %%mm1 \n" /*B*/ \
"punpckhwd %%mm3, %%mm2 \n" /*D*/ \
"movq %%mm0, %%mm3 \n" \
"punpcklwd %%mm1, %%mm0 \n" /*A*/ \
"punpckhwd %%mm7, %%mm3 \n" /*C*/ \
"punpcklwd %%mm2, %%mm7 \n" /*B*/ \
"punpckhwd %%mm2, %%mm1 \n" /*D*/ \
\
"movq %%mm0, " #dst0 " \n" \
"movq %%mm7, " #dst1 " \n" \
"movq %%mm3, " #dst2 " \n" \
"movq %%mm1, " #dst3 " \n"
__asm__ volatile(
"movd %2, %%mm4 \n"
"movd %3, %%mm5 \n"
"movd %4, %%mm6 \n"
"packssdw %%mm4, %%mm4 \n"
"packssdw %%mm5, %%mm5 \n"
"packssdw %%mm6, %%mm6 \n"
"packssdw %%mm4, %%mm4 \n"
"packssdw %%mm5, %%mm5 \n"
"packssdw %%mm6, %%mm6 \n"
REQUANT_CORE( (%1), 8(%1), 16(%1), 24(%1), (%0), 8(%0), 64(%0), 72(%0))
REQUANT_CORE(32(%1), 40(%1), 48(%1), 56(%1),16(%0),24(%0), 48(%0), 56(%0))
REQUANT_CORE(64(%1), 72(%1), 80(%1), 88(%1),32(%0),40(%0), 96(%0),104(%0))
REQUANT_CORE(96(%1),104(%1),112(%1),120(%1),80(%0),88(%0),112(%0),120(%0))
: : "r" (src), "r" (dst), "g" (threshold1+1), "g" (threshold1+5), "g" (threshold1-4) //FIXME maybe more accurate then needed?
);
dst[0] = (src[0] + 4) >> 3;
}
static void softthresh_mmx(int16_t dst[64], const int16_t src[64],
int qp, const uint8_t *permutation)
{
int bias = 0; //FIXME
unsigned int threshold1;
threshold1 = qp*((1<<4) - bias) - 1;
#undef REQUANT_CORE
#define REQUANT_CORE(dst0, dst1, dst2, dst3, src0, src1, src2, src3) \
"movq " #src0 ", %%mm0 \n" \
"movq " #src1 ", %%mm1 \n" \
"pxor %%mm6, %%mm6 \n" \
"pxor %%mm7, %%mm7 \n" \
"pcmpgtw %%mm0, %%mm6 \n" \
"pcmpgtw %%mm1, %%mm7 \n" \
"pxor %%mm6, %%mm0 \n" \
"pxor %%mm7, %%mm1 \n" \
"psubusw %%mm4, %%mm0 \n" \
"psubusw %%mm4, %%mm1 \n" \
"pxor %%mm6, %%mm0 \n" \
"pxor %%mm7, %%mm1 \n" \
"movq " #src2 ", %%mm2 \n" \
"movq " #src3 ", %%mm3 \n" \
"pxor %%mm6, %%mm6 \n" \
"pxor %%mm7, %%mm7 \n" \
"pcmpgtw %%mm2, %%mm6 \n" \
"pcmpgtw %%mm3, %%mm7 \n" \
"pxor %%mm6, %%mm2 \n" \
"pxor %%mm7, %%mm3 \n" \
"psubusw %%mm4, %%mm2 \n" \
"psubusw %%mm4, %%mm3 \n" \
"pxor %%mm6, %%mm2 \n" \
"pxor %%mm7, %%mm3 \n" \
\
"paddsw %%mm5, %%mm0 \n" \
"paddsw %%mm5, %%mm1 \n" \
"paddsw %%mm5, %%mm2 \n" \
"paddsw %%mm5, %%mm3 \n" \
"psraw $3, %%mm0 \n" \
"psraw $3, %%mm1 \n" \
"psraw $3, %%mm2 \n" \
"psraw $3, %%mm3 \n" \
\
"movq %%mm0, %%mm7 \n" \
"punpcklwd %%mm2, %%mm0 \n" /*A*/ \
"punpckhwd %%mm2, %%mm7 \n" /*C*/ \
"movq %%mm1, %%mm2 \n" \
"punpcklwd %%mm3, %%mm1 \n" /*B*/ \
"punpckhwd %%mm3, %%mm2 \n" /*D*/ \
"movq %%mm0, %%mm3 \n" \
"punpcklwd %%mm1, %%mm0 \n" /*A*/ \
"punpckhwd %%mm7, %%mm3 \n" /*C*/ \
"punpcklwd %%mm2, %%mm7 \n" /*B*/ \
"punpckhwd %%mm2, %%mm1 \n" /*D*/ \
\
"movq %%mm0, " #dst0 " \n" \
"movq %%mm7, " #dst1 " \n" \
"movq %%mm3, " #dst2 " \n" \
"movq %%mm1, " #dst3 " \n"
__asm__ volatile(
"movd %2, %%mm4 \n"
"movd %3, %%mm5 \n"
"packssdw %%mm4, %%mm4 \n"
"packssdw %%mm5, %%mm5 \n"
"packssdw %%mm4, %%mm4 \n"
"packssdw %%mm5, %%mm5 \n"
REQUANT_CORE( (%1), 8(%1), 16(%1), 24(%1), (%0), 8(%0), 64(%0), 72(%0))
REQUANT_CORE(32(%1), 40(%1), 48(%1), 56(%1),16(%0),24(%0), 48(%0), 56(%0))
REQUANT_CORE(64(%1), 72(%1), 80(%1), 88(%1),32(%0),40(%0), 96(%0),104(%0))
REQUANT_CORE(96(%1),104(%1),112(%1),120(%1),80(%0),88(%0),112(%0),120(%0))
: : "r" (src), "r" (dst), "g" (threshold1), "rm" (4) //FIXME maybe more accurate then needed?
);
dst[0] = (src[0] + 4) >> 3;
}
static void store_slice_mmx(uint8_t *dst, const int16_t *src,
int dst_stride, int src_stride,
int width, int height, int log2_scale,
const uint8_t dither[8][8])
{
int y;
for (y = 0; y < height; y++) {
uint8_t *dst1 = dst;
const int16_t *src1 = src;
__asm__ volatile(
"movq (%3), %%mm3 \n"
"movq (%3), %%mm4 \n"
"movd %4, %%mm2 \n"
"pxor %%mm0, %%mm0 \n"
"punpcklbw %%mm0, %%mm3 \n"
"punpckhbw %%mm0, %%mm4 \n"
"psraw %%mm2, %%mm3 \n"
"psraw %%mm2, %%mm4 \n"
"movd %5, %%mm2 \n"
"1: \n"
"movq (%0), %%mm0 \n"
"movq 8(%0), %%mm1 \n"
"paddw %%mm3, %%mm0 \n"
"paddw %%mm4, %%mm1 \n"
"psraw %%mm2, %%mm0 \n"
"psraw %%mm2, %%mm1 \n"
"packuswb %%mm1, %%mm0 \n"
"movq %%mm0, (%1) \n"
"add $16, %0 \n"
"add $8, %1 \n"
"cmp %2, %1 \n"
" jb 1b \n"
: "+r" (src1), "+r"(dst1)
: "r"(dst + width), "r"(dither[y]), "g"(log2_scale), "g"(MAX_LEVEL - log2_scale)
);
src += src_stride;
dst += dst_stride;
}
}
#endif /* HAVE_MMX_INLINE */
av_cold void ff_spp_init_x86(SPPContext *s)
{
#if HAVE_MMX_INLINE
int cpu_flags = av_get_cpu_flags();
if (cpu_flags & AV_CPU_FLAG_MMX) {
int64_t bps;
s->store_slice = store_slice_mmx;
av_opt_get_int(s->dct, "bits_per_sample", 0, &bps);
if (bps <= 8) {
switch (s->mode) {
case 0: s->requantize = hardthresh_mmx; break;
case 1: s->requantize = softthresh_mmx; break;
}
}
}
#endif
}
| 8,672 |
10,225 | package io.quarkus.restclient.deployment;
import org.jboss.jandex.DotName;
import io.quarkus.builder.item.MultiBuildItem;
/**
* Used to mark a custom annotation and its associated JAX-RS client provider
*/
public final class RestClientAnnotationProviderBuildItem extends MultiBuildItem {
private final DotName annotationName;
private final Class<?> providerClass;
public RestClientAnnotationProviderBuildItem(DotName annotationName, Class<?> providerClass) {
this.annotationName = annotationName;
this.providerClass = providerClass;
}
public RestClientAnnotationProviderBuildItem(String annotationName, Class<?> providerClass) {
this.annotationName = DotName.createSimple(annotationName);
this.providerClass = providerClass;
}
public DotName getAnnotationName() {
return annotationName;
}
public Class<?> getProviderClass() {
return providerClass;
}
}
| 307 |
449 | <gh_stars>100-1000
#!/bin/python3
import pandas as pd
import numpy as np
from pandas_datareader import data
import matplotlib.pyplot as plt
import h5py
def load_financial_data(start_date, end_date,output_file):
try:
df = pd.read_pickle(output_file)
print('File data found...reading GOOG data')
except FileNotFoundError:
print('File not found...downloading the GOOG data')
df = data.DataReader('GOOG', 'yahoo', start_date, end_date)
df.to_pickle(output_file)
return df
goog_data=load_financial_data(start_date='2001-01-01',
end_date = '2018-01-01',
output_file='goog_data.pkl')
goog_data.to_hdf('goog_data.h5','goog_data',mode='w',format='table',data_columns=True)
h = h5py.File('goog_data.h5')
print(h['goog_data']['table'])
print(h['goog_data']['table'][:])
for attributes in h['goog_data']['table'].attrs.items():
print(attributes)
| 418 |
1,676 | <filename>chat-sdk-core-ui/src/main/java/sdk/chat/ui/binders/MessageBinder.java
package sdk.chat.ui.binders;
import android.content.Context;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import sdk.chat.core.types.MessageSendStatusFormatter;
import sdk.chat.core.utils.CurrentLocale;
import sdk.chat.ui.chat.model.MessageHolder;
import sdk.chat.ui.module.UIModule;
public class MessageBinder {
public DateFormat messageTimeComparisonDateFormat(Context context) {
return new SimpleDateFormat("dd-M-yyyy hh:mm", CurrentLocale.get(context));
}
public void onBindSendStatus(TextView textView, MessageHolder holder) {
if (UIModule.config().dateFormat != null) {
DateFormat format = new SimpleDateFormat(UIModule.config().dateFormat, CurrentLocale.get());
textView.setText(format.format(holder.getCreatedAt()));
}
String status = MessageSendStatusFormatter.format(textView.getContext(), holder.getStatus(), holder.getUploadPercentage());
String timeString = status + " " + textView.getText();
textView.setText(timeString);
}
}
| 418 |
3,974 | <gh_stars>1000+
package io.cucumber.gherkin;
import io.cucumber.messages.types.Envelope;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
// This tests that the message library exposes its version. This test is hard to do in the
// library itself since it requires running against a packaged version (jar).
public class MessageVersionTest {
@Test
public void message_library_has_version() {
assertNotNull(Envelope.class.getPackage().getImplementationVersion());
}
}
| 160 |
19,628 | package com.didichuxing.doraemonkit.aop.map;
import android.location.Location;
import com.amap.api.maps.LocationSource;
import com.didichuxing.doraemonkit.kit.gpsmock.GpsMockManager;
import com.didichuxing.doraemonkit.util.LogHelper;
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:3/25/21-16:08
* 描 述:
* 修订历史:
* ================================================
*/
public class AMapLocationChangedListenerProxy implements LocationSource.OnLocationChangedListener {
private static final String TAG = "AMapLocationChangedListenerProxy";
LocationSource.OnLocationChangedListener mOnLocationChangedListener;
public AMapLocationChangedListenerProxy(LocationSource.OnLocationChangedListener mOnLocationChangedListener) {
this.mOnLocationChangedListener = mOnLocationChangedListener;
}
@Override
public void onLocationChanged(Location location) {
if (GpsMockManager.getInstance().isMocking()) {
location.setLatitude(GpsMockManager.getInstance().getLatitude());
location.setLongitude(GpsMockManager.getInstance().getLongitude());
}
LogHelper.i(TAG, "===onLocationChanged====");
if (mOnLocationChangedListener != null) {
mOnLocationChangedListener.onLocationChanged(location);
}
}
}
| 501 |
6,717 | /* Copyright (c) 2006-2007 <NAME>
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#ifndef _NSOBJCRUNTIME_H_
#define _NSOBJCRUNTIME_H_
#import <objc/objc.h>
#import <stdarg.h>
#import <stdint.h>
#import <limits.h>
#import <TargetConditionals.h>
#import <Foundation/FoundationExport.h>
#import <Availability.h>
#define NS_INLINE static inline
// FIXME: do we really need all of these conditions
#if (__cplusplus && __cplusplus >= 201103L && (__has_extension(cxx_strong_enums) || __has_feature(objc_fixed_enum))) || \
(!__cplusplus && __has_feature(objc_fixed_enum))
#define NS_ENUM(_type, _name) \
enum _name : _type _name; \
enum _name : _type
#else
#define NS_ENUM(_type, _name) \
_type _name; \
enum
#endif
#if !defined(NS_REQUIRES_NIL_TERMINATION)
#define NS_REQUIRES_NIL_TERMINATION __attribute__((sentinel(0, 1)))
#endif
#ifndef NS_RETURNS_RETAINED
#if __has_feature(attribute_ns_returns_retained)
#define NS_RETURNS_RETAINED __attribute__((ns_returns_retained))
#else
#define NS_RETURNS_RETAINED
#endif
#endif
#ifndef NS_RETURNS_NOT_RETAINED
#if __has_feature(attribute_ns_returns_not_retained)
#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
#else
#define NS_RETURNS_NOT_RETAINED
#endif
#endif
#ifndef CF_RETURNS_RETAINED
#if __has_feature(attribute_cf_returns_retained)
#define CF_RETURNS_RETAINED __attribute__((cf_returns_retained))
#else
#define CF_RETURNS_RETAINED
#endif
#endif
#ifndef CF_RETURNS_NOT_RETAINED
#if __has_feature(attribute_cf_returns_not_retained)
#define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained))
#else
#define CF_RETURNS_NOT_RETAINED
#endif
#endif
#ifndef NS_CONSUMED
#if __has_feature(attribute_ns_consumed)
#define NS_CONSUMED __attribute__((ns_consumed))
#else
#define NS_CONSUMED
#endif
#endif
#ifndef CF_CONSUMED
#if __has_feature(attribute_cf_consumed)
#define CF_CONSUMED __attribute__((cf_consumed))
#else
#define CF_CONSUMED
#endif
#endif
#ifndef NS_FORMAT_FUNCTION
#define NS_FORMAT_FUNCTION(F, A) __attribute__((format(NSString, F, A)))
#endif
#ifndef NS_FORMAT_ARGUMENT
#ifdef __clang__
#define NS_FORMAT_ARGUMENT(x) __attribute__((format_arg(x)))
#else
#define NS_FORMAT_ARGUMENT(x)
#endif
#endif
#if __has_attribute(objc_requires_property_definitions)
#define NS_REQUIRES_PROPERTY_DEFINITIONS __attribute__((objc_requires_property_definitions))
#else
#define NS_REQUIRES_PROPERTY_DEFINITIONS
#endif
#ifndef NS_NONATOMIC_IOSONLY
#define NS_NONATOMIC_IOSONLY nonatomic
#endif
@class NSString;
#define NSINTEGER_DEFINED 1
#if defined(__LP64__)
typedef long NSInteger;
typedef unsigned long NSUInteger;
#define NSIntegerMax LONG_MAX
#define NSIntegerMin LONG_MIN
#define NSUIntegerMax ULONG_MAX
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#define NSIntegerMax INT_MAX
#define NSIntegerMin INT_MIN
#define NSUIntegerMax UINT_MAX
#endif
enum {
NSOrderedAscending = -1,
NSOrderedSame = 0,
NSOrderedDescending = 1,
};
typedef NSInteger NSComparisonResult;
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
typedef double NSTimeInterval;
#define NSNotFound NSIntegerMax
#ifndef MIN
#define MIN(a, b) \
({ \
__typeof__(a) _a = (a); \
__typeof__(b) _b = (b); \
(_a < _b) ? _a : _b; \
})
#endif
#ifndef MAX
#define MAX(a, b) \
({ \
__typeof__(a) _a = (a); \
__typeof__(b) _b = (b); \
(_a > _b) ? _a : _b; \
})
#endif
#ifndef ABS
#define ABS(a) \
({ \
__typeof__(a) _a = (a); \
(_a < 0) ? -_a : _a; \
})
#endif
#ifdef _WINOBJC_DO_NOT_USE_NSLOG
#define NSLOG_ANNOTATION __attribute__((unavailable("NSLog should not be used internally.")))
#else
#define NSLOG_ANNOTATION
#endif
FOUNDATION_EXPORT void NSLog(NSString* format, ...) NS_FORMAT_FUNCTION(1, 2) NSLOG_ANNOTATION;
FOUNDATION_EXPORT void NSLogv(NSString* format, va_list args) NS_FORMAT_FUNCTION(1, 0) NSLOG_ANNOTATION;
FOUNDATION_EXPORT const char* NSGetSizeAndAlignment(const char* type, NSUInteger* size, NSUInteger* alignment);
FOUNDATION_EXPORT SEL NSSelectorFromString(NSString* selectorName);
FOUNDATION_EXPORT NSString* NSStringFromSelector(SEL selector);
FOUNDATION_EXPORT Class NSClassFromString(NSString* className);
FOUNDATION_EXPORT NSString* NSStringFromClass(Class aClass);
FOUNDATION_EXPORT NSString* NSStringFromProtocol(Protocol* proto);
FOUNDATION_EXPORT Protocol* NSProtocolFromString(NSString* namestr);
#ifndef NS_BLOCKS_AVAILABLE
#if __BLOCKS__
#define NS_BLOCKS_AVAILABLE 1
#else
#define NS_BLOCKS_AVAILABLE 0
#endif
#endif
#ifndef NS_UNAVAILABLE
#define NS_UNAVAILABLE UNAVAILABLE_ATTRIBUTE
#endif
#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif
#ifndef NS_SWIFT_NOTHROW
#define NS_SWIFT_NOTHROW
#endif
#ifndef NS_REFINED_FOR_SWIFT
#define NS_REFINED_FOR_SWIFT
#endif
#ifndef NS_SWIFT_NAME
#define NS_SWIFT_NAME
#endif
#ifdef NS_SWIFT_UNAVAILABLE
#define NS_SWIFT_UNAVAILABLE
#endif
#ifndef NS_ASSUME_NONNULL_BEGIN
#if __has_feature(assume_nonnull)
#define NS_ASSUME_NONNULL_BEGIN _Pragma("clang assume_nonnull begin")
#define NS_ASSUME_NONNULL_END _Pragma("clang assume_nonnull end")
#else
#define NS_ASSUME_NONNULL_BEGIN
#define NS_ASSUME_NONNULL_END
#endif
#endif
#if (!__has_feature(objc_arc))
#ifndef __autoreleasing
#define __autoreleasing
#endif
#ifndef __strong
#define __strong
#endif
#ifndef __weak
#define __weak
#endif
#ifndef __unsafe_unretained
#define __unsafe_unretained
#endif
#endif
#if __has_feature(nullability)
#ifndef __nullable
#define __nullable _Nullable
#endif
#endif
#ifndef NS_AVAILABLE
#define NS_AVAILABLE(x, y)
#endif
#ifndef NS_AVAILABLE_IOS
#define NS_AVAILABLE_IOS(x)
#endif
#ifndef NS_DEPRECATED_IOS
#define NS_DEPRECATED_IOS(x, y)
#endif
#ifndef NS_EXTENSION_UNAVAILABLE_IOS
#define NS_EXTENSION_UNAVAILABLE_IOS(x)
#endif
#ifdef __cplusplus
#define NS_OPTIONS(_t, _n) \
_t _n; \
enum : _t
#else
#define NS_OPTIONS(_t, _n) \
enum _n : _t _n; \
enum _n : _t
#endif
enum {
NSSortConcurrent = 1UL,
NSSortStable = 16UL,
};
typedef uint32_t NSSortOptions;
enum {
NSEnumerationConcurrent = 1,
NSEnumerationReverse = 2,
};
typedef uint32_t NSEnumerationOptions;
FOUNDATION_EXPORT const double NSFoundationVersionNumber;
#define NSFoundationVersionNumber_iPhoneOS_2_0 678.24
#define NSFoundationVersionNumber_iPhoneOS_2_1 678.26
#define NSFoundationVersionNumber_iPhoneOS_2_2 678.29
#define NSFoundationVersionNumber_iPhoneOS_3_0 678.47
#define NSFoundationVersionNumber_iPhoneOS_3_1 678.51
#define NSFoundationVersionNumber_iPhoneOS_3_2 678.60
#define NSFoundationVersionNumber_iOS_4_0 751.32
#define NSFoundationVersionNumber_iOS_4_1 751.37
#define NSFoundationVersionNumber_iOS_4_2 751.49
#define NSFoundationVersionNumber_iOS_4_3 751.49
#define NSFoundationVersionNumber_iOS_5_0 881.00
#define NSFoundationVersionNumber_iOS_5_1 890.10
#define NSFoundationVersionNumber_iOS_6_0 993.00
#define NSFoundationVersionNumber_iOS_6_1 993.00
#define NSFoundationVersionNumber_iOS_7_0 1047.20
#define NSFoundationVersionNumber_iOS_7_1 1047.25
#define NSFoundationVersionNumber_iOS_8_0 1140.11
#define NSFoundationVersionNumber_iOS_8_1 1141.1
#define NSFoundationVersionNumber_iOS_8_2 1142.14
#define NSFoundationVersionNumber_iOS_8_3 1144.17
#ifndef NS_VALID_UNTIL_END_OF_SCOPE
#define NS_VALID_UNTIL_END_OF_SCOPE __attribute__((objc_precise_lifetime))
#endif
#ifndef NS_RETURNS_INNER_POINTER
#define NS_RETURNS_INNER_POINTER __attribute__((objc_returns_inner_pointer))
#endif
#endif /* _NSOBJCRUNTIME_H_ */ | 3,614 |
581 | <reponame>ddiepo-pjr/phasar<gh_stars>100-1000
/******************************************************************************
* Copyright (c) 2017 <NAME>.
* All rights reserved. This program and the accompanying materials are made
* available under the terms of LICENSE.txt.
*
* Contributors:
* <NAME> and others
*****************************************************************************/
#include "gtest/gtest.h"
#include <iostream>
#include "phasar/DB/ProjectIRDB.h"
#include "phasar/PhasarLLVM/ControlFlow/LLVMBasedICFG.h"
#include "phasar/PhasarLLVM/DataFlowSolver/WPDS/Problems/WPDSLinearConstantAnalysis.h"
#include "phasar/PhasarLLVM/DataFlowSolver/WPDS/Problems/WPDSSolverTest.h"
#include "phasar/PhasarLLVM/DataFlowSolver/WPDS/Solver/WPDSSolver.h"
#include "phasar/PhasarLLVM/Pointer/LLVMPointsToInfo.h"
#include "phasar/PhasarLLVM/TypeHierarchy/LLVMTypeHierarchy.h"
#include "phasar/PhasarLLVM/Utils/BinaryDomain.h"
#include "phasar/Utils/Logger.h"
#include "llvm/Support/raw_ostream.h"
#include "boost/filesystem/operations.hpp"
using namespace std;
using namespace psr;
// int main(int argc, char **argv) {
// initializeLogger(false);
// if (argc < 4 || !bfs::exists(argv[1]) || bfs::is_directory(argv[1])) {
// std::cerr << "usage: <prog> <ir file> <ID or LCA> <DIRECTION>\n";
// return 1;
// }
// string DFA(argv[2]);
// if (DFA != "ID" && DFA != "LCA") {
// std::cerr << "analysis is not valid!\n";
// return 1;
// }
// string DIRECTION(argv[3]);
// if (!(DIRECTION == "FORWARD" || DIRECTION == "BACKWARD")) {
// std::cerr << "analysis direction must be FORWARD or BACKWARD\n";
// return 1;
// }
// initializeLogger(false);
// ProjectIRDB DB({argv[1]});
// const llvm::Function *F;
// if ((F = DB.getFunctionDefinition("main"))) {
// LLVMTypeHierarchy H(DB);
// LLVMPointsToInfo PT(DB);
// LLVMBasedICFG I(H, DB, CallGraphAnalysisType::OTF, {"main"});
// auto Ret = &F->back().back();
// cout << "RESULTS AT: " << llvmIRToString(Ret) << '\n';
// if (DFA == "ID") {
// WPDSSolverTest T(&DB, &H, &I, &PT, {"main"});
// WPDSSolver<WPDSSolverTest::n_t, WPDSSolverTest::d_t,
// WPDSSolverTest::f_t,
// WPDSSolverTest::t_t, WPDSSolverTest::v_t,
// WPDSSolverTest::l_t, WPDSSolverTest::i_t>
// S(T);
// S.solve();
// auto Results = S.resultsAt(Ret);
// cout << "Results:\n";
// for (auto &Result : Results) {
// Result.first->print(llvm::outs());
// cout << '\n';
// }
// } else if (DFA == "LCA") {
// std::cout << "LCA" << std::endl;
// // WPDSLinearConstantAnalysis L(&DB, &H, &I, &PT, {"main"});
// // WPDSSolver<
// // WPDSLinearConstantAnalysis::n_t,
// WPDSLinearConstantAnalysis::d_t,
// // WPDSLinearConstantAnalysis::f_t,
// WPDSLinearConstantAnalysis::t_t,
// // WPDSLinearConstantAnalysis::v_t,
// WPDSLinearConstantAnalysis::l_t,
// // WPDSLinearConstantAnalysis::i_t>
// // S(L);
// // S.solve();
// // auto Results = S.resultsAt(Ret);
// // cout << "Results:\n";
// // if (!Results.empty()) {
// // for (auto &Result : Results) {
// // Result.first->print(llvm::outs());
// // cout << " - with value: ";
// // L.printEdgeFact(cout, Result.second);
// // std::cout << '\n';
// // }
// // } else {
// // cout << "Results are empty!\n";
// // }
// }
// std::cout << "DONE!\n";
// } else {
// std::cerr << "error: file does not contain a 'main' function!\n";
// }
// return 0;
// }
int main(int Argc, char **Argv) {
::testing::InitGoogleTest(&Argc, Argv);
return RUN_ALL_TESTS();
}
| 1,709 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.