max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
575 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ASH_LOGIN_ENROLLMENT_ENROLLMENT_SCREEN_H_
#define CHROME_BROWSER_ASH_LOGIN_ENROLLMENT_ENROLLMENT_SCREEN_H_
#include <memory>
#include <string>
#include "base/callback.h"
#include "base/cancelable_callback.h"
#include "base/compiler_specific.h"
#include "base/gtest_prod_util.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/ash/authpolicy/authpolicy_helper.h"
#include "chrome/browser/ash/login/enrollment/enrollment_screen_view.h"
#include "chrome/browser/ash/login/enrollment/enterprise_enrollment_helper.h"
#include "chrome/browser/ash/login/screens/base_screen.h"
#include "chrome/browser/ash/login/wizard_context.h"
#include "chrome/browser/chromeos/policy/active_directory_join_delegate.h"
#include "chrome/browser/chromeos/policy/enrollment_config.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/policy/core/common/cloud/enterprise_metrics.h"
#include "net/base/backoff_entry.h"
namespace base {
class ElapsedTimer;
}
namespace chromeos {
class ScreenManager;
namespace test {
class EnrollmentHelperMixin;
}
// The screen implementation that links the enterprise enrollment UI into the
// OOBE wizard.
class EnrollmentScreen
: public BaseScreen,
public EnterpriseEnrollmentHelper::EnrollmentStatusConsumer,
public EnrollmentScreenView::Controller,
public ActiveDirectoryJoinDelegate {
public:
enum class Result { COMPLETED, BACK, SKIPPED_FOR_TESTS };
static std::string GetResultString(Result result);
using ScreenExitCallback = base::RepeatingCallback<void(Result result)>;
EnrollmentScreen(EnrollmentScreenView* view,
const ScreenExitCallback& exit_callback);
~EnrollmentScreen() override;
static EnrollmentScreen* Get(ScreenManager* manager);
// Setup how this screen will handle enrollment.
void SetEnrollmentConfig(const policy::EnrollmentConfig& enrollment_config);
// EnrollmentScreenView::Controller implementation:
void OnLoginDone(const std::string& user,
const std::string& auth_code) override;
void OnRetry() override;
void OnCancel() override;
void OnConfirmationClosed() override;
void OnActiveDirectoryCredsProvided(const std::string& machine_name,
const std::string& distinguished_name,
int encryption_types,
const std::string& username,
const std::string& password) override;
void OnDeviceAttributeProvided(const std::string& asset_id,
const std::string& location) override;
// EnterpriseEnrollmentHelper::EnrollmentStatusConsumer implementation:
void OnAuthError(const GoogleServiceAuthError& error) override;
void OnEnrollmentError(policy::EnrollmentStatus status) override;
void OnOtherError(EnterpriseEnrollmentHelper::OtherError error) override;
void OnDeviceEnrolled() override;
void OnDeviceAttributeUploadCompleted(bool success) override;
void OnDeviceAttributeUpdatePermission(bool granted) override;
void OnRestoreAfterRollbackCompleted() override;
// ActiveDirectoryJoinDelegate implementation:
void JoinDomain(const std::string& dm_token,
const std::string& domain_join_config,
OnDomainJoinedCallback on_joined_callback) override;
// Notification that the browser is being restarted.
void OnBrowserRestart();
// Used for testing.
EnrollmentScreenView* GetView() { return view_; }
void set_exit_callback_for_testing(const ScreenExitCallback& callback) {
exit_callback_ = callback;
}
protected:
// BaseScreen:
bool MaybeSkip(WizardContext* context) override;
void ShowImpl() override;
void HideImpl() override;
// Expose the exit_callback to test screen overrides.
ScreenExitCallback* exit_callback() { return &exit_callback_; }
private:
friend class ZeroTouchEnrollmentScreenUnitTest;
friend class AutomaticReenrollmentScreenUnitTest;
friend class test::EnrollmentHelperMixin;
FRIEND_TEST_ALL_PREFIXES(AttestationAuthEnrollmentScreenTest, TestCancel);
FRIEND_TEST_ALL_PREFIXES(ForcedAttestationAuthEnrollmentScreenTest,
TestCancel);
FRIEND_TEST_ALL_PREFIXES(MultiAuthEnrollmentScreenTest, TestCancel);
FRIEND_TEST_ALL_PREFIXES(ZeroTouchEnrollmentScreenUnitTest, Retry);
FRIEND_TEST_ALL_PREFIXES(ZeroTouchEnrollmentScreenUnitTest, TestSuccess);
FRIEND_TEST_ALL_PREFIXES(ZeroTouchEnrollmentScreenUnitTest,
DoNotRetryOnTopOfUser);
FRIEND_TEST_ALL_PREFIXES(ZeroTouchEnrollmentScreenUnitTest,
DoNotRetryAfterSuccess);
// The authentication mechanisms that this class can use.
enum Auth {
AUTH_ATTESTATION,
AUTH_OAUTH,
};
// Sets the current config to use for enrollment.
void SetConfig();
// Creates an enrollment helper if needed.
void CreateEnrollmentHelper();
// Clears auth in `enrollment_helper_`. Deletes `enrollment_helper_` and runs
// `callback` on completion. See the comment for
// EnterpriseEnrollmentHelper::ClearAuth for details.
void ClearAuth(base::OnceClosure callback);
// Used as a callback for EnterpriseEnrollmentHelper::ClearAuth.
virtual void OnAuthCleared(base::OnceClosure callback);
// Shows successful enrollment status after all enrollment related file
// operations are completed.
void ShowEnrollmentStatusOnSuccess();
// Logs an UMA event in one of the "Enrollment.*" histograms, depending on
// `enrollment_mode_`.
void UMA(policy::MetricEnrollment sample);
// Do attestation based enrollment.
void AuthenticateUsingAttestation();
// Starts flow that would handle necessary steps to restore after version
// rollback.
void RestoreAfterRollback();
// Shows the interactive screen. Resets auth then shows the signin screen.
void ShowInteractiveScreen();
// Shows the signin screen. Used as a callback to run after auth reset.
void ShowSigninScreen();
// Shows the device attribute prompt screen.
// Used as a callback to run after successful enrollment.
void ShowAttributePromptScreen();
// Record metrics when we encounter an enrollment error.
void RecordEnrollmentErrorMetrics();
// Advance to the next authentication mechanism if possible.
bool AdvanceToNextAuth();
// Similar to OnRetry(), but responds to a timer instead of the user
// pressing the Retry button.
void AutomaticRetry();
// Processes a request to retry enrollment.
// Called by OnRetry() and AutomaticRetry().
void ProcessRetry();
// Callback for Active Directory domain join.
void OnActiveDirectoryJoined(const std::string& machine_name,
const std::string& username,
authpolicy::ErrorType error,
const std::string& machine_domain);
EnrollmentScreenView* view_;
ScreenExitCallback exit_callback_;
policy::EnrollmentConfig config_;
policy::EnrollmentConfig enrollment_config_;
// 'Current' and 'Next' authentication mechanisms to be used.
Auth current_auth_ = AUTH_OAUTH;
Auth next_auth_ = AUTH_OAUTH;
bool enrollment_failed_once_ = false;
bool enrollment_succeeded_ = false;
std::string enrolling_user_domain_;
std::unique_ptr<base::ElapsedTimer> elapsed_timer_;
net::BackoffEntry::Policy retry_policy_;
std::unique_ptr<net::BackoffEntry> retry_backoff_;
base::CancelableOnceClosure retry_task_;
int num_retries_ = 0;
std::unique_ptr<EnterpriseEnrollmentHelper> enrollment_helper_;
OnDomainJoinedCallback on_joined_callback_;
// Helper to call AuthPolicyClient and cancel calls if needed. Used to join
// Active Directory domain.
std::unique_ptr<AuthPolicyHelper> authpolicy_login_helper_;
base::WeakPtrFactory<EnrollmentScreen> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(EnrollmentScreen);
};
} // namespace chromeos
#endif // CHROME_BROWSER_ASH_LOGIN_ENROLLMENT_ENROLLMENT_SCREEN_H_
| 2,708 |
1,144 | package de.metas.vertical.creditscore.creditpass.interceptor;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
import org.adempiere.ad.modelvalidator.annotations.DocValidate;
import org.adempiere.ad.modelvalidator.annotations.Interceptor;
import org.adempiere.ad.modelvalidator.annotations.ModelChange;
import org.adempiere.exceptions.AdempiereException;
import org.apache.commons.lang3.StringUtils;
import org.compiere.model.ModelValidator;
import org.compiere.util.Env;
import org.springframework.stereotype.Component;
/*
* #%L
* de.metas.vertical.creditscore.creditpass.interceptor
*
* Copyright (C) 2018 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import de.metas.bpartner.BPartnerId;
import de.metas.i18n.IMsgBL;
import de.metas.i18n.ITranslatableString;
import de.metas.util.Services;
import de.metas.vertical.creditscore.base.spi.model.ResultCode;
import de.metas.vertical.creditscore.base.spi.model.TransactionResult;
import de.metas.vertical.creditscore.base.spi.service.TransactionResultService;
import de.metas.vertical.creditscore.creditpass.CreditPassConstants;
import de.metas.vertical.creditscore.creditpass.model.CreditPassConfig;
import de.metas.vertical.creditscore.creditpass.model.CreditPassConfigPaymentRule;
import de.metas.vertical.creditscore.creditpass.model.extended.I_C_Order;
import de.metas.vertical.creditscore.creditpass.repository.CreditPassConfigRepository;
import lombok.NonNull;
@Interceptor(I_C_Order.class)
@Component
public class C_Order
{
private final TransactionResultService transactionResultService;
private final CreditPassConfigRepository creditPassConfigRepository;
public C_Order(@NonNull final TransactionResultService transactionResultService,
@NonNull final CreditPassConfigRepository creditPassConfigRepository)
{
this.transactionResultService = transactionResultService;
this.creditPassConfigRepository = creditPassConfigRepository;
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW,
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = { I_C_Order.COLUMNNAME_PaymentRule,
})
public void setCreditPassInfo(final I_C_Order order)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID());
final CreditPassConfig config = creditPassConfigRepository.getConfigByBPartnerId(bPartnerId);
final Optional<TransactionResult> transactionResult = transactionResultService.findLastTransactionResult(order.getPaymentRule(), BPartnerId.ofRepoId(order.getC_BPartner_ID()));
final Optional<CreditPassConfig> configuration = Optional.ofNullable(config);
final IMsgBL msgBL = Services.get(IMsgBL.class);
if (configuration.isPresent() && configuration.get().getCreditPassConfigPaymentRuleList().stream()
.map(CreditPassConfigPaymentRule::getPaymentRule)
.anyMatch(pr -> StringUtils.equals(pr, order.getPaymentRule())))
{
if (transactionResult.filter(tr -> tr.getRequestDate().until(LocalDateTime.now(), ChronoUnit.DAYS) < config.getRetryDays()).isPresent())
{
if (transactionResult.filter(tr -> tr.getResultCodeEffective() == ResultCode.P).isPresent())
{
order.setCreditpassFlag(false);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_STATUS_SUCCESS_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
else
{
order.setCreditpassFlag(true);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_REQUEST_NEEDED_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
}
else
{
order.setCreditpassFlag(true);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_REQUEST_NEEDED_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
}
else
{
order.setCreditpassFlag(false);
final ITranslatableString message = msgBL.getTranslatableMsgText(CreditPassConstants.CREDITPASS_REQUEST_NOT_NEEDED_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE })
public void validateCreditpassForOrder(final I_C_Order order)
{
if (order.getCreditpassFlag() && order.isSOTrx())
{
final ITranslatableString message = Services.get(IMsgBL.class).getTranslatableMsgText(CreditPassConstants.ORDER_COMPLETED_CREDITPASS_ERROR);
throw new AdempiereException(message);
}
}
}
| 1,741 |
735 | /*
* Copyright (C) 2004 <NAME>.
* Copyright (C) 2006, 2007, 2014, 2018 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 03. September 2004 by <NAME>
*/
package com.thoughtworks.xstream.io.xml;
import java.io.StringReader;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import com.thoughtworks.acceptance.someobjects.X;
import com.thoughtworks.acceptance.someobjects.Y;
import com.thoughtworks.xstream.XStream;
import junit.framework.TestCase;
public class JDomAcceptanceTest extends TestCase {
private XStream xstream;
@Override
protected void setUp() throws Exception {
super.setUp();
xstream = new XStream();
xstream.alias("x", X.class);
xstream.allowTypes(X.class);
}
public void testUnmarshalsObjectFromJDOM() throws Exception {
final String xml = "<x>"
+ " <aStr>joe</aStr>"
+ " <anInt>8</anInt>"
+ " <innerObj>"
+ " <yField>walnes</yField>"
+ " </innerObj>"
+ "</x>";
final Document doc = new SAXBuilder().build(new StringReader(xml));
try (final JDomReader reader = new JDomReader(doc)) {
final X x = xstream.<X>unmarshal(reader);
assertEquals("joe", x.aStr);
assertEquals(8, x.anInt);
assertEquals("walnes", x.innerObj.yField);
}
}
public void testMarshalsObjectToJDOM() {
final X x = new X();
x.anInt = 9;
x.aStr = "zzz";
x.innerObj = new Y();
x.innerObj.yField = "ooo";
final String expected = "<x>\n"
+ " <aStr>zzz</aStr>\n"
+ " <anInt>9</anInt>\n"
+ " <innerObj>\n"
+ " <yField>ooo</yField>\n"
+ " </innerObj>\n"
+ "</x>";
try (final JDomWriter writer = new JDomWriter()) {
xstream.marshal(x, writer);
final List<Element> result = writer.getTopLevelNodes();
assertEquals("Result list should contain exactly 1 element", 1, result.size());
final XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setLineSeparator("\n"));
assertEquals(expected, outputter.outputString(result));
}
}
}
| 1,129 |
1,020 | package org.robobinding.widget.abslistview;
import java.util.Map;
import java.util.Set;
import org.robobinding.viewattribute.property.TwoWayPropertyViewAttribute;
import org.robobinding.widget.AbstractMultiTypePropertyViewAttributeTest;
import org.robobinding.widget.abslistview.CheckedItemPositionsAttribute.MapCheckedItemPositionsAttribute;
import org.robobinding.widget.abslistview.CheckedItemPositionsAttribute.SetCheckedItemPositionsAttribute;
import org.robobinding.widget.abslistview.CheckedItemPositionsAttribute.SparseBooleanArrayCheckedItemPositionsAttribute;
import org.robolectric.annotation.Config;
import android.util.SparseBooleanArray;
import android.widget.AbsListView;
/**
*
* @since 1.0
* @version $Revision: 1.0 $
* @author <NAME>
*/
@Config(manifest = Config.NONE)
public class CheckedItemPositionsAttributeTest extends AbstractMultiTypePropertyViewAttributeTest {
@Override
protected void setTypeMappingExpectations() {
forPropertyType(SparseBooleanArray.class).expectAttributeType(SparseBooleanArrayCheckedItemPositionsAttribute.class);
forPropertyType(Set.class).expectAttributeType(SetCheckedItemPositionsAttribute.class);
forPropertyType(Map.class).expectAttributeType(MapCheckedItemPositionsAttribute.class);
}
@Override
protected TwoWayPropertyViewAttribute<AbsListView, ?, ?> createViewAttribute(Class<?> propertyType) {
return new CheckedItemPositionsAttribute().create(null, propertyType);
}
} | 425 |
750 | from unittest import TestCase
from unittest.mock import MagicMock, patch
from piccolo.apps.migrations.commands.check import CheckMigrationManager, check
from piccolo.conf.apps import AppRegistry
from piccolo.utils.sync import run_sync
class TestCheckMigrationCommand(TestCase):
@patch.object(
CheckMigrationManager,
"get_app_registry",
)
def test_check_migrations(self, get_app_registry: MagicMock):
get_app_registry.return_value = AppRegistry(
apps=["piccolo.apps.user.piccolo_app"]
)
# Make sure it runs without raising an exception:
run_sync(check())
| 241 |
2,338 | // RUN: %clang_cc1 -fsyntax-only -fbracket-depth 2 -verify -std=c++17 %s
template <class T, T... V> struct seq {
constexpr bool zero() { return (true && ... && (V == 0)); }; // expected-error {{instantiating fold expression with 3 arguments exceeded expression nesting limit of 2}} \
expected-note {{use -fbracket-depth}}
};
constexpr unsigned N = 3;
auto x = __make_integer_seq<seq, int, N>{};
static_assert(!x.zero(), ""); // expected-note {{in instantiation of member function}}
| 220 |
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.
*
*************************************************************/
package connectivity.tools;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.sdb.XOfficeDatabaseDocument;
import com.sun.star.sdbc.SQLException;
import com.sun.star.uno.UnoRuntime;
import helper.URLHelper;
import java.io.File;
class FlatFileDatabase extends AbstractDatabase
{
// --------------------------------------------------------------------------------------------------------
protected FlatFileDatabase( final XMultiServiceFactory i_orb, final String i_urlSubScheme ) throws Exception
{
super(i_orb);
m_urlSubScheme = i_urlSubScheme;
createDBDocument();
}
// --------------------------------------------------------------------------------------------------------
protected FlatFileDatabase(final XMultiServiceFactory i_orb, final String i_existingDocumentURL,
final String i_urlSubScheme ) throws Exception
{
super( i_orb, i_existingDocumentURL );
m_urlSubScheme = i_urlSubScheme;
final XPropertySet dsProperties = UnoRuntime.queryInterface(XPropertySet.class, m_databaseDocument.getDataSource());
final String url = (String)dsProperties.getPropertyValue( "URL" );
final String expectedURLPrefix = "sdbc:" + m_urlSubScheme + ":";
if ( !url.startsWith( expectedURLPrefix ) )
throw new IllegalArgumentException( i_existingDocumentURL + " is of wrong type" );
final String location = url.substring( expectedURLPrefix.length() );
m_tableFileLocation = new File( location );
if ( m_tableFileLocation.isDirectory() )
throw new IllegalArgumentException( "unsupported table file location (must be a folder)" );
}
/**
* returns a {@link File} which represents the folder where the database's table files reside.
*/
public File getTableFileLocation()
{
return m_tableFileLocation;
}
/** creates an empty database document in a temporary location
*/
private void createDBDocument() throws Exception
{
final File documentFile = File.createTempFile( m_urlSubScheme, ".odb" );
if ( documentFile.exists() )
documentFile.delete();
m_tableFileLocation = new File(documentFile.getParent() + File.separator + documentFile.getName().replace(".odb", "") + File.separator );
m_tableFileLocation.mkdir();
//subPath.deleteOnExit();
m_databaseDocumentFile = URLHelper.getFileURLFromSystemPath(documentFile);
final String path = URLHelper.getFileURLFromSystemPath( m_tableFileLocation.getPath() );
m_databaseDocument = UnoRuntime.queryInterface( XOfficeDatabaseDocument.class,
m_orb.createInstance("com.sun.star.sdb.OfficeDatabaseDocument"));
m_dataSource = new DataSource(m_orb, m_databaseDocument.getDataSource());
final XPropertySet dsProperties = UnoRuntime.queryInterface(XPropertySet.class, m_databaseDocument.getDataSource());
dsProperties.setPropertyValue("URL", "sdbc:" + m_urlSubScheme + ":" + path);
final XStorable storable = UnoRuntime.queryInterface( XStorable.class, m_databaseDocument );
storable.storeAsURL( m_databaseDocumentFile, new PropertyValue[] { } );
}
/** drops the table with a given name
@param _name
the name of the table to drop
@param _ifExists
TRUE if it should be dropped only when it exists.
*/
public void dropTable(final String _name,final boolean _ifExists) throws SQLException
{
String dropStatement = "DROP TABLE \"" + _name;
executeSQL(dropStatement);
}
final String m_urlSubScheme;
File m_tableFileLocation = null;
}
| 1,524 |
3,428 | <gh_stars>1000+
{"id":"01028","group":"easy-ham-1","checksum":{"type":"MD5","value":"9bc3697b9d9eb23fc4427b482b012f40"},"text":"From <EMAIL> Thu Sep 19 13:01:41 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: [email protected]\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 1006916F03\n\tfor <jm@localhost>; Thu, 19 Sep 2002 13:01:41 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Thu, 19 Sep 2002 13:01:41 +0100 (IST)\nReceived: from listman.spamassassin.taint.org (listman.spamassassin.taint.org [66.187.233.211]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g8J9kbC14322 for\n <<EMAIL>>; Thu, 19 Sep 2002 10:46:37 +0100\nReceived: from listman.spamassassin.taint.org (localhost.localdomain [127.0.0.1]) by\n listman.redhat.com (Postfix) with ESMTP id E59D23ECE2; Thu, 19 Sep 2002\n 05:47:01 -0400 (EDT)\nDelivered-To: <EMAIL>assin.taint.org\nReceived: from int-mx1.corp.spamassassin.taint.org (int-mx1.corp.spamassassin.taint.org\n [172.16.52.254]) by listman.redhat.com (Postfix) with ESMTP id 90B8A3ECE2\n for <<EMAIL>>; Thu, 19 Sep 2002 05:46:14 -0400 (EDT)\nReceived: (from mail@localhost) by int-mx1.corp.spamassassin.taint.org (8.11.6/8.11.6)\n id g8J9kEq09095 for <EMAIL>; Thu, 19 Sep 2002\n 05:46:14 -0400\nReceived: from mx1.spamassassin.taint.org (mx1.spamassassin.taint.org [172.16.48.31]) by\n int-mx1.corp.redhat.com (8.11.6/8.11.6) with SMTP id g8J9kEh09088 for\n <<EMAIL>>; Thu, 19 Sep 2002 05:46:14 -0400\nReceived: from hobbit.linuxworks.com.au\n (CPE-203-51-198-239.qld.bigpond.net.au [203.51.198.239]) by mx1.redhat.com\n (8.11.6/8.11.6) with SMTP id g8J9Swi03770 for <<EMAIL>>;\n Thu, 19 Sep 2002 05:28:58 -0400\nReceived: (from tony@localhost) by hobbit.linuxworks.com.au\n (8.11.6/8.11.6) id g8J9k1308152; Thu, 19 Sep 2002 19:46:01 +1000\nMessage-Id: <<EMAIL>>\nTo: <EMAIL>\nFrom: <NAME> <<EMAIL>>\nX-Face: ]IrGs{LrofDtGfsrG!As5=G'2HRr2zt:H>djXb5@v|Dr!jOelxzAZ`!}(\"]}]\n Q!)1w#X;)nLlb'XhSu,QL>;)L/l06wsI?rv-xy6%Y1e\"BUiV%)mU;]f-5<#U6\n UthZ0QrF7\\_p#q}*Cn}jd|XT~7P7ik]Q!2u%aTtvc;)zfH\\:3f<[a:)M\nOrganization: Linux Works for network\nX-Mailer: nmh-1.0.4 exmh-2.4\nX-Os: Linux-2.4 RedHat 7.2\nSubject: customising FTOC display for specific folders...\nX-Loop: <EMAIL>int.org\nSender: <EMAIL>\nErrors-To: <EMAIL>\nX-Beenthere: [email protected]\nX-Mailman-Version: 2.0.1\nPrecedence: bulk\nReply-To: <EMAIL>\nList-Help: <mailto:<EMAIL>@spamassassin.taint.org?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <https://listman.spamassassin.taint.org/mailman/listinfo/exmh-users>,\n <mailto:<EMAIL>?subject=subscribe>\nList-Id: Discussion list for EXMH users <exmh-users.spamassassin.taint.org>\nList-Unsubscribe: <https://listman.spamassassin.taint.org/mailman/listinfo/exmh-users>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <https://listman.spamassassin.taint.org/mailman/private/exmh-users/>\nDate: Thu, 19 Sep 2002 19:46:01 +1000\n\nIs there any way to customise the folder table of contents for\nspecific folders?\n\nI know it is possible to do per-folder customisation with components\nand replcomps for message templates, but what about -form format\nfiles for scan?\n\nCheers\nTony\n\n\n\n_______________________________________________\nExmh-users mailing list\n<EMAIL>.<EMAIL>\nhttps://listman.redhat.com/mailman/listinfo/exmh-users\n\n\n"} | 1,621 |
435 | {
"alias": "video/1973/python-and-the-ska-0",
"category": "SciPy 2013",
"copyright_text": "https://www.youtube.com/t/terms",
"description": "Authors: <NAME> SKA South Africa, <NAME> SKA South\nAfrica\n\nTrack: Astronomy and Astrophysics\n\nThe Square Kilometer Array will be one of the prime scientific data\ngenerates in the next few decades.\n\nConstruction is scheduled to commence in late 2016 and last for the best\npart of a decade. Current estimates put data volume generation near 1\nExabyte per day with 2-3 ExaFLOPs of processing required to handle this\ndata.\n\nAs a host country, South Africa is constructing a large precursor\ntelescope known as MeerKAT. Once complete this will be the most\nsensitive telescope of it's kind in the world - until dwarfed by the\nSKA.\n\nWe make extensive use of Python from the entire Monitor and Control\nsystem through to data handling and processing.\n\nThis talk looks at our current usage of Python, and our desire to see\nthe entire high performance processing chain being able to call itself\nPythonic.\n\nWe will discuss some of the challenges specific to the radio astronomy\nenvironment and how we believe Python can contribute, particularly when\nit comes to the trade off between development time and performance.\n",
"duration": null,
"id": 1973,
"language": "eng",
"quality_notes": "",
"recorded": "2013-07-01",
"slug": "python-and-the-ska-0",
"speakers": [
"<NAME>",
"<NAME>"
],
"summary": "We will discuss some of the challenges specific to the radio astronomy\nenvironment and how we believe Python can contribute, particularly when\nit comes to the trade off between development time and performance.\n",
"tags": [
"astronomy",
"astrophysics"
],
"thumbnail_url": "https://i1.ytimg.com/vi/dRFiI29y7KA/hqdefault.jpg",
"title": "Python and the SKA",
"videos": [
{
"length": 0,
"type": "youtube",
"url": "https://www.youtube.com/watch?v=dRFiI29y7KA"
}
]
}
| 626 |
10,876 | <reponame>Nuclearfossil/vcpkg
#define ANGLE_COMMIT_HASH "invalid-hash"
#define ANGLE_COMMIT_HASH_SIZE 12
#define ANGLE_COMMIT_DATE "invalid-date"
| 66 |
6,342 | <reponame>DemarcusL/django_wiki_lab
from allauth.socialaccount.providers.oauth2.urls import default_urlpatterns
from .provider import ZoomProvider
urlpatterns = default_urlpatterns(ZoomProvider)
| 65 |
433 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.source;
import java.io.Serializable;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import org.redkale.service.Local;
import org.redkale.util.*;
/**
*
*
* @author zhangjx
*/
/**
* DataSource的Memory实现类 <br>
* 注意: javax.persistence.jdbc.url 需要指定为 memory:source
*
* <p>
* 详情见: https://redkale.org
*
* @author zhangjx
*/
@Local
@AutoLoad(false)
@SuppressWarnings("unchecked")
@ResourceType(DataSource.class)
public class DataMemorySource extends DataSqlSource implements SearchSource {
public DataMemorySource(String unitName, URL persistFile, Properties readprop, Properties writeprop) {
super(unitName, persistFile, "memory", readprop, writeprop);
this.cacheForbidden = false;
}
@Local
@Override
public String getType() {
return "memory";
}
@Override
@Local
public <T> void compile(Class<T> clazz) {
EntityInfo entityInfo = EntityInfo.compile(clazz, this);
if (entityInfo.getCache() == null) new EntityCache<>(entityInfo, null).clear();
}
@Override
public <T> int updateMapping(final Class<T> clazz) {
return 0;
}
@Override
public <T> CompletableFuture<Integer> updateMappingAsync(final Class<T> clazz) {
return CompletableFuture.completedFuture(0);
}
@Override
protected boolean isOnlyCache(EntityInfo info) {
return true;
}
@Local
@Override
public int directExecute(String sql) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Local
@Override
public int[] directExecute(String... sqls) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Local
@Override
public <V> V directQuery(String sql, Function<DataResultSet, V> handler) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected boolean isAsync() {
return true;
}
@Override
protected String prepareParamSign(int index) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
protected <T> CompletableFuture<Integer> insertDB(EntityInfo<T> info, T... entitys) {
return CompletableFuture.completedFuture(0);
}
@Override
protected <T> CompletableFuture<Integer> deleteDB(EntityInfo<T> info, Flipper flipper, String sql) {
return CompletableFuture.completedFuture(0);
}
@Override
protected <T> CompletableFuture<Integer> clearTableDB(EntityInfo<T> info, final String table, String sql) {
return CompletableFuture.completedFuture(0);
}
@Override
protected <T> CompletableFuture<Integer> dropTableDB(EntityInfo<T> info, final String table, String sql) {
return CompletableFuture.completedFuture(0);
}
@Override
protected <T> CompletableFuture<Integer> updateEntityDB(EntityInfo<T> info, T... entitys) {
return CompletableFuture.completedFuture(0);
}
@Override
protected <T> CompletableFuture<Integer> updateColumnDB(EntityInfo<T> info, Flipper flipper, String sql, boolean prepared, Object... params) {
return CompletableFuture.completedFuture(0);
}
@Override
protected <T, N extends Number> CompletableFuture<Map<String, N>> getNumberMapDB(EntityInfo<T> info, String sql, FilterFuncColumn... columns) {
return CompletableFuture.completedFuture(null);
}
@Override
protected <T> CompletableFuture<Number> getNumberResultDB(EntityInfo<T> info, String sql, Number defVal, String column) {
return CompletableFuture.completedFuture(defVal);
}
@Override
protected <T, K extends Serializable, N extends Number> CompletableFuture<Map<K, N>> queryColumnMapDB(EntityInfo<T> info, String sql, String keyColumn) {
return CompletableFuture.completedFuture(null);
}
@Override
protected <T, K extends Serializable, N extends Number> CompletableFuture<Map<K[], N[]>> queryColumnMapDB(final EntityInfo<T> info, final String sql, final ColumnNode[] funcNodes, final String[] groupByColumns) {
return CompletableFuture.completedFuture(null);
}
@Override
protected <T> CompletableFuture<T> findDB(EntityInfo<T> info, String sql, boolean onlypk, SelectColumn selects) {
return CompletableFuture.completedFuture(null);
}
@Override
protected <T> CompletableFuture<Serializable> findColumnDB(EntityInfo<T> info, String sql, boolean onlypk, String column, Serializable defValue) {
return CompletableFuture.completedFuture(null);
}
@Override
protected <T> CompletableFuture<Boolean> existsDB(EntityInfo<T> info, String sql, boolean onlypk) {
return CompletableFuture.completedFuture(false);
}
@Override
protected <T> CompletableFuture<Sheet<T>> querySheetDB(EntityInfo<T> info, final boolean readcache, boolean needtotal, final boolean distinct, SelectColumn selects, Flipper flipper, FilterNode node) {
return CompletableFuture.completedFuture(new Sheet<>(0, new ArrayList()));
}
}
| 1,888 |
504 | package org.dayatang.dddlib.event.api;
import org.dayatang.utils.Assert;
import java.util.Date;
import java.util.UUID;
/**
* 领域事件基类,领域事件代表具有业务含义的事件,例如员工调动或者机构调整
* Created by yyang on 14-9-12.
*/
public abstract class AbstractEvent implements Event {
private String id = UUID.randomUUID().toString();
private Date occurredOn = new Date();
private int version = 1;
public AbstractEvent() {
this(new Date(), 1);
}
/**
* @param occurredOn 发生时间
*/
public AbstractEvent(Date occurredOn) {
this(occurredOn, 1);
}
/**
* @param occurredOn 发生时间
* @param version 版本
*/
public AbstractEvent(Date occurredOn, int version) {
Assert.notNull(occurredOn);
this.occurredOn = new Date(occurredOn.getTime());
this.version = version;
}
/**
* 获得事件ID
*
* @return 事件的ID
*/
@Override
public String id() {
return id;
}
/**
* 获得事件发生时间
*
* @return 事件发生时间
*/
@Override
public Date occurredOn() {
return occurredOn;
}
/**
* 获得版本
*
* @return 事件的版本
*/
@Override
public int version() {
return version;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof AbstractEvent)) {
return false;
}
AbstractEvent that = (AbstractEvent) other;
return this.id().equals(that.id());
}
@Override
public int hashCode() {
return id.hashCode();
}
} | 839 |
416 | <reponame>neilalex/SublimeWebInspector
# not implemented now
| 22 |
303 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from django.contrib import admin as django_admin
from ..service.engine import EngineService
from ..models import EnginePatch
from ..forms.engine_patch import engine_patch_formset, EnginePatchForm
class EnginePatchInline(django_admin.StackedInline):
formset = engine_patch_formset
form = EnginePatchForm
model = EnginePatch
extra = 0
verbose_name = "Patch Version"
class EngineAdmin(admin.DjangoServicesAdmin):
service_class = EngineService
search_fields = ("engine_type__name",)
readonly_fields = ("version2", "full_inicial_version")
list_display = ("engine_type", "version", "is_active",
"version2", "full_inicial_version")
list_filter = ("engine_type", "is_active")
save_on_top = True
ordering = ('engine_type__name', )
inlines = [EnginePatchInline]
def get_queryset(self, request):
qs = super(EngineAdmin, self).get_queryset(request)
return qs.order_by('engine_type__name', 'version')
| 378 |
850 | /* Copyright 2016 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.
==============================================================================*/
#ifndef THIRD_PARTY_TENSORFLOW_CORE_LIB_IO_COMPRESSED_OUTPUTBUFFER_H_
#define THIRD_PARTY_TENSORFLOW_CORE_LIB_IO_COMPRESSED_OUTPUTBUFFER_H_
#include <zlib.h>
#include <string>
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/zlib_compression_options.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/file_system.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace io {
// Provides support for writing compressed output to file using zlib
// (http://www.zlib.net/).
// A given instance of an ZlibOutputBuffer is NOT safe for concurrent use
// by multiple threads
class ZlibOutputBuffer : public WritableFile {
public:
// Create an ZlibOutputBuffer for `file` with two buffers that cache the
// 1. input data to be deflated
// 2. the deflated output
// with sizes `input_buffer_bytes` and `output_buffer_bytes` respectively.
// Does not take ownership of `file`.
// output_buffer_bytes should be greater than 1.
ZlibOutputBuffer(
WritableFile* file,
int32 input_buffer_bytes, // size of z_stream.next_in buffer
int32 output_buffer_bytes, // size of z_stream.next_out buffer
const ZlibCompressionOptions& zlib_options);
~ZlibOutputBuffer();
// Initializes some state necessary for the output buffer. This call is
// required before any other operation on the buffer.
Status Init();
// Adds `data` to the compression pipeline.
//
// The input data is buffered in `z_stream_input_` and is compressed in bulk
// when the buffer gets full. The compressed output is not immediately
// written to file but rather buffered in `z_stream_output_` and gets written
// to file when the buffer is full.
//
// To immediately write contents to file call `Flush()`.
Status Append(const StringPiece& data) override;
// Deflates any cached input and writes all output to file.
Status Flush() override;
// Compresses any cached input and writes all output to file. This must be
// called before the destructor to avoid any data loss.
//
// Contrary to `Flush()` this informs zlib that it should not expect any
// further input by using Z_FINISH flush mode. Also cleans up z_stream.
//
// After calling this, any further calls to `Write()`, `Flush()` or `Close()`
// will fail.
Status Close() override;
// Deflates any cached input, writes all output to file and syncs it.
Status Sync() override;
private:
WritableFile* file_; // Not owned
Status init_status_;
size_t input_buffer_capacity_;
size_t output_buffer_capacity_;
// Buffer for storing contents read from input `file_`.
// TODO(srbs): Consider using circular buffers. That would greatly simplify
// the implementation.
std::unique_ptr<Bytef[]> z_stream_input_;
// Buffer for storing deflated contents of `file_`.
std::unique_ptr<Bytef[]> z_stream_output_;
ZlibCompressionOptions const zlib_options_;
// Configuration passed to `deflate`.
//
// z_stream_->next_in:
// Next byte to compress. Points to some byte in z_stream_input_ buffer.
// z_stream_->avail_in:
// Number of bytes available to be compressed at this time.
// z_stream_->next_out:
// Next byte to write compressed data to. Points to some byte in
// z_stream_output_ buffer.
// z_stream_->avail_out:
// Number of free bytes available at write location.
std::unique_ptr<z_stream> z_stream_;
// Adds `data` to `z_stream_input_`.
// Throws if `data.size()` > AvailableInputSpace().
void AddToInputBuffer(StringPiece data);
// Returns the total space available in z_input_stream_ buffer.
int32 AvailableInputSpace() const;
// Deflate contents in z_stream_input_ and store results in z_stream_output_.
// The contents of output stream are written to file if more space is needed.
// On successful termination it is assured that:
// - z_stream_->avail_in == 0
// - z_stream_->avail_out > 0
//
// Note: This method does not flush contents to file.
// Returns non-ok status if writing contents to file fails.
Status DeflateBuffered(bool last = false);
// Appends contents of `z_stream_output_` to `file_`.
// Returns non-OK status if writing to file fails.
Status FlushOutputBufferToFile();
// Calls `deflate()` and returns DataLoss Status if it failed.
Status Deflate(int flush);
static bool IsSyncOrFullFlush(uint8 flush_mode) {
return flush_mode == Z_SYNC_FLUSH || flush_mode == Z_FULL_FLUSH;
}
TF_DISALLOW_COPY_AND_ASSIGN(ZlibOutputBuffer);
};
} // namespace io
} // namespace tensorflow
#endif // THIRD_PARTY_TENSORFLOW_CORE_LIB_IO_COMPRESSED_OUTPUTBUFFER_H_
| 1,645 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.identity;
import com.azure.identity.implementation.util.ValidationUtil;
/**
* Fluent credential builder for instantiating a {@link AzureCliCredential}.
*
* @see AzureCliCredential
*/
public class AzureCliCredentialBuilder extends CredentialBuilderBase<AzureCliCredentialBuilder> {
private String tenantId;
/**
* Sets the tenant ID of the application.
*
* @param tenantId the tenant ID of the application.
* @return An updated instance of this builder with the tenant id set as specified.
*/
public AzureCliCredentialBuilder tenantId(String tenantId) {
ValidationUtil.validateTenantIdCharacterRange(getClass().getSimpleName(), tenantId);
this.tenantId = tenantId;
return this;
}
/**
* Creates a new {@link AzureCliCredential} with the current configurations.
*
* @return a {@link AzureCliCredential} with the current configurations.
*/
public AzureCliCredential build() {
return new AzureCliCredential(tenantId, identityClientOptions);
}
}
| 393 |
2,453 | <reponame>haozhiyu1990/XVim2
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <IDEKit/XCLogUnitTestAdapter.h>
@interface XCLogUnitTestWorkerAdapter : XCLogUnitTestAdapter
{
}
- (id)secondRowStringForDataNode:(id)arg1;
- (double)_baseHeightOfRowForDataNode:(id)arg1;
- (BOOL)displaysBadge;
- (id)badgeImageForDataNode:(id)arg1;
- (id)imageForDataNode:(id)arg1;
@end
| 191 |
347 | package org.ovirt.engine.core.common.action;
import java.io.Serializable;
public enum LoginResult implements Serializable {
Autheticated,
CantAuthenticate,
NoPermission,
PasswordExpired;
public int getValue() {
return this.ordinal();
}
public static LoginResult forValue(int value) {
return values()[value];
}
}
| 132 |
679 | <reponame>Grosskopf/openoffice
/**************************************************************
*
* 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 _GSTPLAYER_HXX
#define _GSTPLAYER_HXX
#include "gstcommon.hxx"
#include <glib.h>
// necessary for mixed environments with GStreamer-0.10 and GLib versions < 2.8
#ifndef G_GNUC_NULL_TERMINATED
#if __GNUC__ >= 4
#define G_GNUC_NULL_TERMINATED __attribute__((__sentinel__))
#else
#define G_GNUC_NULL_TERMINATED
#endif
#endif
struct _GOptionGroup;
typedef struct _GOptionGroup GOptionGroup;
#include <gst/gst.h>
#include "com/sun/star/media/XPlayer.hdl"
#include <cppuhelper/compbase2.hxx>
#include <cppuhelper/basemutex.hxx>
namespace avmedia
{
namespace gst
{
class Window;
// ---------------
// - Player_Impl -
// ---------------
typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::media::XPlayer,
::com::sun::star::lang::XServiceInfo > Player_BASE;
class Player : public cppu::BaseMutex,
public Player_BASE
{
public:
// static create method instead of public Ctor
static Player* create( const ::rtl::OUString& rURL );
~Player();
//protected:
// XPlayer
virtual void SAL_CALL start()
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL stop()
throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL isPlaying()
throw( ::com::sun::star::uno::RuntimeException );
virtual double SAL_CALL getDuration()
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setMediaTime( double fTime )
throw( ::com::sun::star::uno::RuntimeException );
virtual double SAL_CALL getMediaTime()
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setStopTime( double fTime )
throw( ::com::sun::star::uno::RuntimeException );
virtual double SAL_CALL getStopTime()
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setRate( double fRate )
throw( ::com::sun::star::uno::RuntimeException );
virtual double SAL_CALL getRate()
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setPlaybackLoop( sal_Bool bSet )
throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL isPlaybackLoop()
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setMute( sal_Bool bSet )
throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Bool SAL_CALL isMute()
throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setVolumeDB( sal_Int16 nVolumeDB )
throw( ::com::sun::star::uno::RuntimeException );
virtual sal_Int16 SAL_CALL getVolumeDB()
throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::awt::Size SAL_CALL getPreferredPlayerWindowSize()
throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Reference< ::com::sun::star::media::XPlayerWindow > SAL_CALL createPlayerWindow(
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
throw( ::com::sun::star::uno::RuntimeException );
virtual ::com::sun::star::uno::Reference< ::com::sun::star::media::XFrameGrabber > SAL_CALL createFrameGrabber()
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 );
// these are public because the C callbacks call them
virtual gboolean busCallback( GstBus* pBus,
GstMessage* pMsg );
virtual gboolean idle();
virtual gpointer run();
virtual GstBusSyncReply handleCreateWindow( GstBus* pBus,
GstMessage* pMsg );
protected:
// ::cppu::OComponentHelper
virtual void SAL_CALL disposing(void);
Player( GString* pURI = NULL );
void implQuitThread();
bool implInitPlayer();
bool implIsInitialized() const
{
return( g_atomic_int_get( &mnInitialized ) > 0 );
}
private:
Player( const Player& );
Player& operator=( const Player& );
static void implHandleNewElementFunc( GstBin* pBin,
GstElement* pElement,
gpointer pData );
static void implHandleNewPadFunc( GstElement* pElem,
GstPad* pPad,
gpointer pData );
protected:
GMutex* mpMutex;
GCond* mpCond;
GThread* mpThread;
GMainContext* mpContext;
GMainLoop* mpLoop;
GstElement* mpPlayer;
GString* mpURI;
private:
::avmedia::gst::Window* mpPlayerWindow;
gint mnIsVideoSource;
gint mnVideoWidth;
gint mnVideoHeight;
gint mnInitialized;
gint mnVolumeDB;
gint mnLooping;
gint mnQuit;
gint mnVideoWindowSet;
gint mnInitFail;
};
} // namespace gst
} // namespace avmedia
#endif // _GSTPLAYER_HXX
| 2,333 |
398 | <reponame>regadas/chill
/*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.twitter.chill.java;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.twitter.chill.IKryoRegistrar;
import com.twitter.chill.SingleRegistrar;
import java.lang.reflect.Field;
import java.util.*;
/**
* A kryo {@link Serializer} for unmodifiable collections created via {@link Collections#unmodifiableCollection(Collection)}.
* <p>
* Note: This serializer does not support cyclic references, so if one of the objects
* gets set the list as attribute this might cause an error during deserialization.
* </p>
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class UnmodifiableCollectionSerializer extends UnmodifiableJavaCollectionSerializer<Collection<?>> {
@SuppressWarnings("unchecked")
static public IKryoRegistrar registrar() {
return new SingleRegistrar(Collections.unmodifiableCollection(Collections.EMPTY_SET).getClass(),
new UnmodifiableCollectionSerializer());
}
@Override
protected Field getInnerField() throws Exception {
return Class.forName("java.util.Collections$UnmodifiableCollection").getDeclaredField("c");
}
@Override
protected Collection<?> newInstance(Collection<?> c) {
return Collections.unmodifiableCollection(c);
}
}
| 596 |
4,071 | <filename>xdl/xdl/core/framework/slab_allocator.cc
/* Copyright (C) 2016-2018 Alibaba Group Holding Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "xdl/core/framework/slab_allocator.h"
#include "xdl/core/utils/logging.h"
#include <iostream>
namespace xdl {
namespace {
int32_t level(uint64_t v) {
uint64_t v2 = v & (v >> 1);
if (v2 != 0) {
if ((v2 & (v2 >> 2)) != 0) {
return 4;
} else if ((v2 & (v >> 2)) != 0) {
return 3;
} else {
return 2;
}
} else {
if (v != 0) {
return 1;
} else {
return 0;
}
}
}
} // namespace
SlabAllocator::SlabAllocator(Allocator* internal, size_t allocate_size,
size_t segment_size, size_t block_size)
: counter_(0), internal_(internal), allocate_size_(allocate_size),
segment_size_(segment_size), block_size_(block_size) {
XDL_CHECK(allocate_size_ >= (segment_size_ * block_size_ * kChunkSize))
<< "AllocateSize should be more than SegmentSize * BlockSize * ChunkSize";
XDL_CHECK(allocate_size_ % (segment_size_ * block_size_ * kChunkSize) == 0)
<< "AllocateSize should be diveded by SegmentSize * BlockSize * ChunkSize";
chunk_count_ = allocate_size_ / segment_size_ / block_size_ / kChunkSize;
segment_allocate_size_ = allocate_size_ / segment_size_;
segment_.reset(new Segment[segment_size_]);
allocations_.reset(new void*[kAllocationSize]);
for (int i = 0; i < kAllocationSize; i++) {
allocations_[i] = nullptr;
}
allocations_size_ = 0;
}
SlabAllocator::~SlabAllocator() {
for (size_t i = 0; i < allocations_size_; i++) {
internal_->Deallocate(allocations_[i]);
}
}
void* SlabAllocator::Allocate(size_t size) {
if (size == 0) {
return nullptr;
}
int32_t block = size / block_size_;
if (size % block_size_ != 0) {
block++;
}
XDL_CHECK(block <= kMaxBlockForAllocate) << "Cannot Allocate size " << size;
int32_t seg_id = counter_++ % segment_size_;
return SegmentAllocate(seg_id, block);
}
void SlabAllocator::Deallocate(void* buf) {
XDL_CHECK(TryDeallocate(buf)) << "Buddy Allocator Error! Invalid buf " << buf;
}
bool SlabAllocator::TryDeallocate(void* buf) {
if (buf == nullptr) {
return true;
}
int seg_id, line_id, block_id;
bool ok = FindBlock(buf, &seg_id, &line_id, &block_id);
if (!ok) {
return false;
}
Free(seg_id, line_id, block_id);
return true;
}
void* SlabAllocator::SegmentAllocate(int seg_id, int32_t block) {
Segment& segment = segment_[seg_id];
std::unique_lock<std::mutex> lock(segment.mu_);
int i = seg_id;
for (i = block; i <= kMaxBlockForAllocate; i++) {
if (segment.links[i].next != &segment.links[i]) {
break;
}
}
LinkNode* node;
if (i == kMaxBlockForAllocate + 1) {
AllocateSegmentLine(seg_id);
node = segment.links[kMaxBlockForAllocate].next;
} else {
node = segment.links[i].next;
}
node->prev->next = node->next;
node->next->prev = node->prev;
uint64_t mask = (1ul << block) - 1;
int loc;
for (loc = 0; loc < kChunkSize; loc++) {
if (((node->allocate_mask >> loc) & mask) == mask) {
break;
}
}
XDL_CHECK(loc < kChunkSize) << "Internal Error";
if (node->chunk_id == 1) {
LinkNode* nodex = node - 1;
}
node->allocate_mask = node->allocate_mask & ~(mask << loc);
node->allocate_head_mask = node->allocate_head_mask | (1ul << loc);
int32_t node_level = level(node->allocate_mask);
node->prev = &segment.links[node_level];
node->next = segment.links[node_level].next;
node->prev->next = node;
node->next->prev = node;
return static_cast<char*>(segment.lines[node->line_id].ptr)
+ block_size_ * (kChunkSize * node->chunk_id + loc);
}
void SlabAllocator::AllocateSegmentLine(int seg_id) {
void* ptr; {
std::unique_lock<std::mutex> lock(allocate_mu_);
if (segment_[seg_id].lines.size() < allocations_size_) {
ptr = static_cast<char*>(allocations_[segment_[seg_id].lines.size()]) +
segment_allocate_size_ * seg_id;
} else {
allocations_[allocations_size_] = internal_->Allocate(allocate_size_);
ptr = static_cast<char*>(allocations_[allocations_size_]) +
segment_allocate_size_ * seg_id;
allocations_size_++;
}
}
int32_t line_id = segment_[seg_id].lines.size();
segment_[seg_id].lines.emplace_back();
SegmentLine& line = segment_[seg_id].lines.back();
LinkNode* prev = &segment_[seg_id].links[kMaxBlockForAllocate];
LinkNode* end = prev->next;
line.ptr = ptr;
line.link_list.reset(new LinkNode[chunk_count_]);
for (size_t i = 0; i < chunk_count_; i++) {
LinkNode* node = &line.link_list[i];
node->prev = prev;
prev->next = node;
prev = node;
node->line_id = line_id;
node->chunk_id = i;
// 0123456789ABCDEF F*16
node->allocate_mask = 0xFFFFFFFFFFFFFFFFL;
node->allocate_head_mask = 0;
}
line.link_list[chunk_count_ - 1].next = end;
end->prev = &line.link_list[chunk_count_ - 1];
}
bool SlabAllocator::FindBlock(
void* ptr, int* seg_id, int* line_id, int* block_id) {
size_t line_size = allocations_size_;
size_t i;
for (i = 0; i < line_size; i++) {
void* beg = allocations_[i];
void* end = static_cast<char*>(allocations_[i]) + allocate_size_;
if (ptr >= beg && ptr < end) {
int diff = static_cast<char*>(ptr) - static_cast<char*>(beg);
*line_id = i;
*seg_id = diff / segment_allocate_size_;
*block_id = (diff % segment_allocate_size_) / block_size_;
return true;
}
}
return false;
}
void SlabAllocator::Free(int seg_id, int line_id, int block_id) {
Segment& segment = segment_[seg_id];
std::unique_lock<std::mutex> lock(segment.mu_);
int chunk_id = block_id / kChunkSize;
int b_id = block_id % kChunkSize;
LinkNode* node = &segment.lines[line_id].link_list[chunk_id];
node->prev->next = node->next;
node->next->prev = node->prev;
node->allocate_mask = node->allocate_mask | (1ul << b_id);
node->allocate_head_mask = node->allocate_head_mask & ~(1ul << b_id);
uint64_t mask = (1ul << b_id) << 1;
while ((node->allocate_mask & mask) == 0 &&
(node->allocate_head_mask & mask) == 0 && mask != 0) {
node->allocate_mask = node->allocate_mask | mask;
mask = mask << 1;
}
int32_t node_level = level(node->allocate_mask);
node->prev = &segment.links[node_level];
node->next = segment.links[node_level].next;
node->prev->next = node;
node->next->prev = node;
}
} // namespace xdl
| 2,870 |
2,338 | //===- lib/MC/MCFragment.cpp - Assembler Fragment Implementation ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCFragment.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/MC/MCAsmLayout.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdint>
#include <utility>
using namespace llvm;
MCAsmLayout::MCAsmLayout(MCAssembler &Asm) : Assembler(Asm) {
// Compute the section layout order. Virtual sections must go last.
for (MCSection &Sec : Asm)
if (!Sec.isVirtualSection())
SectionOrder.push_back(&Sec);
for (MCSection &Sec : Asm)
if (Sec.isVirtualSection())
SectionOrder.push_back(&Sec);
}
bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
const MCSection *Sec = F->getParent();
const MCFragment *LastValid = LastValidFragment.lookup(Sec);
if (!LastValid)
return false;
assert(LastValid->getParent() == Sec);
return F->getLayoutOrder() <= LastValid->getLayoutOrder();
}
bool MCAsmLayout::canGetFragmentOffset(const MCFragment *F) const {
MCSection *Sec = F->getParent();
MCSection::iterator I;
if (MCFragment *LastValid = LastValidFragment[Sec]) {
// Fragment already valid, offset is available.
if (F->getLayoutOrder() <= LastValid->getLayoutOrder())
return true;
I = ++MCSection::iterator(LastValid);
} else
I = Sec->begin();
// A fragment ordered before F is currently being laid out.
const MCFragment *FirstInvalidFragment = &*I;
if (FirstInvalidFragment->IsBeingLaidOut)
return false;
return true;
}
void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
// If this fragment wasn't already valid, we don't need to do anything.
if (!isFragmentValid(F))
return;
// Otherwise, reset the last valid fragment to the previous fragment
// (if this is the first fragment, it will be NULL).
LastValidFragment[F->getParent()] = F->getPrevNode();
}
void MCAsmLayout::ensureValid(const MCFragment *F) const {
MCSection *Sec = F->getParent();
MCSection::iterator I;
if (MCFragment *Cur = LastValidFragment[Sec])
I = ++MCSection::iterator(Cur);
else
I = Sec->begin();
// Advance the layout position until the fragment is valid.
while (!isFragmentValid(F)) {
assert(I != Sec->end() && "Layout bookkeeping error");
const_cast<MCAsmLayout *>(this)->layoutFragment(&*I);
++I;
}
}
uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
ensureValid(F);
assert(F->Offset != ~UINT64_C(0) && "Address not set!");
return F->Offset;
}
// Simple getSymbolOffset helper for the non-variable case.
static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbol &S,
bool ReportError, uint64_t &Val) {
if (!S.getFragment()) {
if (ReportError)
report_fatal_error("unable to evaluate offset to undefined symbol '" +
S.getName() + "'");
return false;
}
Val = Layout.getFragmentOffset(S.getFragment()) + S.getOffset();
return true;
}
static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S,
bool ReportError, uint64_t &Val) {
if (!S.isVariable())
return getLabelOffset(Layout, S, ReportError, Val);
// If SD is a variable, evaluate it.
MCValue Target;
if (!S.getVariableValue()->evaluateAsValue(Target, Layout))
report_fatal_error("unable to evaluate offset for variable '" +
S.getName() + "'");
uint64_t Offset = Target.getConstant();
const MCSymbolRefExpr *A = Target.getSymA();
if (A) {
uint64_t ValA;
if (!getLabelOffset(Layout, A->getSymbol(), ReportError, ValA))
return false;
Offset += ValA;
}
const MCSymbolRefExpr *B = Target.getSymB();
if (B) {
uint64_t ValB;
if (!getLabelOffset(Layout, B->getSymbol(), ReportError, ValB))
return false;
Offset -= ValB;
}
Val = Offset;
return true;
}
bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
return getSymbolOffsetImpl(*this, S, false, Val);
}
uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
uint64_t Val;
getSymbolOffsetImpl(*this, S, true, Val);
return Val;
}
const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
if (!Symbol.isVariable())
return &Symbol;
const MCExpr *Expr = Symbol.getVariableValue();
MCValue Value;
if (!Expr->evaluateAsValue(Value, *this)) {
Assembler.getContext().reportError(
Expr->getLoc(), "expression could not be evaluated");
return nullptr;
}
const MCSymbolRefExpr *RefB = Value.getSymB();
if (RefB) {
Assembler.getContext().reportError(
Expr->getLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
"' could not be evaluated in a subtraction expression");
return nullptr;
}
const MCSymbolRefExpr *A = Value.getSymA();
if (!A)
return nullptr;
const MCSymbol &ASym = A->getSymbol();
const MCAssembler &Asm = getAssembler();
if (ASym.isCommon()) {
Asm.getContext().reportError(Expr->getLoc(),
"Common symbol '" + ASym.getName() +
"' cannot be used in assignment expr");
return nullptr;
}
return &ASym;
}
uint64_t MCAsmLayout::getSectionAddressSize(const MCSection *Sec) const {
// The size is the last fragment's end offset.
const MCFragment &F = Sec->getFragmentList().back();
return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
}
uint64_t MCAsmLayout::getSectionFileSize(const MCSection *Sec) const {
// Virtual sections have no file size.
if (Sec->isVirtualSection())
return 0;
// Otherwise, the file size is the same as the address space size.
return getSectionAddressSize(Sec);
}
uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
const MCEncodedFragment *F,
uint64_t FOffset, uint64_t FSize) {
uint64_t BundleSize = Assembler.getBundleAlignSize();
assert(BundleSize > 0 &&
"computeBundlePadding should only be called if bundling is enabled");
uint64_t BundleMask = BundleSize - 1;
uint64_t OffsetInBundle = FOffset & BundleMask;
uint64_t EndOfFragment = OffsetInBundle + FSize;
// There are two kinds of bundling restrictions:
//
// 1) For alignToBundleEnd(), add padding to ensure that the fragment will
// *end* on a bundle boundary.
// 2) Otherwise, check if the fragment would cross a bundle boundary. If it
// would, add padding until the end of the bundle so that the fragment
// will start in a new one.
if (F->alignToBundleEnd()) {
// Three possibilities here:
//
// A) The fragment just happens to end at a bundle boundary, so we're good.
// B) The fragment ends before the current bundle boundary: pad it just
// enough to reach the boundary.
// C) The fragment ends after the current bundle boundary: pad it until it
// reaches the end of the next bundle boundary.
//
// Note: this code could be made shorter with some modulo trickery, but it's
// intentionally kept in its more explicit form for simplicity.
if (EndOfFragment == BundleSize)
return 0;
else if (EndOfFragment < BundleSize)
return BundleSize - EndOfFragment;
else { // EndOfFragment > BundleSize
return 2 * BundleSize - EndOfFragment;
}
} else if (OffsetInBundle > 0 && EndOfFragment > BundleSize)
return BundleSize - OffsetInBundle;
else
return 0;
}
/* *** */
void ilist_alloc_traits<MCFragment>::deleteNode(MCFragment *V) { V->destroy(); }
MCFragment::MCFragment(FragmentType Kind, bool HasInstructions,
MCSection *Parent)
: Parent(Parent), Atom(nullptr), Offset(~UINT64_C(0)), LayoutOrder(0),
Kind(Kind), IsBeingLaidOut(false), HasInstructions(HasInstructions) {
if (Parent && !isa<MCDummyFragment>(*this))
Parent->getFragmentList().push_back(this);
}
void MCFragment::destroy() {
// First check if we are the sentinal.
if (Kind == FragmentType(~0)) {
delete this;
return;
}
switch (Kind) {
case FT_Align:
delete cast<MCAlignFragment>(this);
return;
case FT_Data:
delete cast<MCDataFragment>(this);
return;
case FT_CompactEncodedInst:
delete cast<MCCompactEncodedInstFragment>(this);
return;
case FT_Fill:
delete cast<MCFillFragment>(this);
return;
case FT_Nops:
delete cast<MCNopsFragment>(this);
return;
case FT_Relaxable:
delete cast<MCRelaxableFragment>(this);
return;
case FT_Org:
delete cast<MCOrgFragment>(this);
return;
case FT_Dwarf:
delete cast<MCDwarfLineAddrFragment>(this);
return;
case FT_DwarfFrame:
delete cast<MCDwarfCallFrameFragment>(this);
return;
case FT_LEB:
delete cast<MCLEBFragment>(this);
return;
case FT_BoundaryAlign:
delete cast<MCBoundaryAlignFragment>(this);
return;
case FT_SymbolId:
delete cast<MCSymbolIdFragment>(this);
return;
case FT_CVInlineLines:
delete cast<MCCVInlineLineTableFragment>(this);
return;
case FT_CVDefRange:
delete cast<MCCVDefRangeFragment>(this);
return;
case FT_PseudoProbe:
delete cast<MCPseudoProbeAddrFragment>(this);
return;
case FT_Dummy:
delete cast<MCDummyFragment>(this);
return;
}
}
// Debugging methods
namespace llvm {
raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
OS << "<MCFixup" << " Offset:" << AF.getOffset()
<< " Value:" << *AF.getValue()
<< " Kind:" << AF.getKind() << ">";
return OS;
}
} // end namespace llvm
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void MCFragment::dump() const {
raw_ostream &OS = errs();
OS << "<";
switch (getKind()) {
case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
case MCFragment::FT_Data: OS << "MCDataFragment"; break;
case MCFragment::FT_CompactEncodedInst:
OS << "MCCompactEncodedInstFragment"; break;
case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
case MCFragment::FT_Nops:
OS << "MCFNopsFragment";
break;
case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
case MCFragment::FT_BoundaryAlign: OS<<"MCBoundaryAlignFragment"; break;
case MCFragment::FT_SymbolId: OS << "MCSymbolIdFragment"; break;
case MCFragment::FT_CVInlineLines: OS << "MCCVInlineLineTableFragment"; break;
case MCFragment::FT_CVDefRange: OS << "MCCVDefRangeTableFragment"; break;
case MCFragment::FT_PseudoProbe:
OS << "MCPseudoProbe";
break;
case MCFragment::FT_Dummy: OS << "MCDummyFragment"; break;
}
OS << "<MCFragment " << (const void *)this << " LayoutOrder:" << LayoutOrder
<< " Offset:" << Offset << " HasInstructions:" << hasInstructions();
if (const auto *EF = dyn_cast<MCEncodedFragment>(this))
OS << " BundlePadding:" << static_cast<unsigned>(EF->getBundlePadding());
OS << ">";
switch (getKind()) {
case MCFragment::FT_Align: {
const auto *AF = cast<MCAlignFragment>(this);
if (AF->hasEmitNops())
OS << " (emit nops)";
OS << "\n ";
OS << " Alignment:" << AF->getAlignment()
<< " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
<< " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
break;
}
case MCFragment::FT_Data: {
const auto *DF = cast<MCDataFragment>(this);
OS << "\n ";
OS << " Contents:[";
const SmallVectorImpl<char> &Contents = DF->getContents();
for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
if (i) OS << ",";
OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
}
OS << "] (" << Contents.size() << " bytes)";
if (DF->fixup_begin() != DF->fixup_end()) {
OS << ",\n ";
OS << " Fixups:[";
for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
ie = DF->fixup_end(); it != ie; ++it) {
if (it != DF->fixup_begin()) OS << ",\n ";
OS << *it;
}
OS << "]";
}
break;
}
case MCFragment::FT_CompactEncodedInst: {
const auto *CEIF =
cast<MCCompactEncodedInstFragment>(this);
OS << "\n ";
OS << " Contents:[";
const SmallVectorImpl<char> &Contents = CEIF->getContents();
for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
if (i) OS << ",";
OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
}
OS << "] (" << Contents.size() << " bytes)";
break;
}
case MCFragment::FT_Fill: {
const auto *FF = cast<MCFillFragment>(this);
OS << " Value:" << static_cast<unsigned>(FF->getValue())
<< " ValueSize:" << static_cast<unsigned>(FF->getValueSize())
<< " NumValues:" << FF->getNumValues();
break;
}
case MCFragment::FT_Nops: {
const auto *NF = cast<MCNopsFragment>(this);
OS << " NumBytes:" << NF->getNumBytes()
<< " ControlledNopLength:" << NF->getControlledNopLength();
break;
}
case MCFragment::FT_Relaxable: {
const auto *F = cast<MCRelaxableFragment>(this);
OS << "\n ";
OS << " Inst:";
F->getInst().dump_pretty(OS);
OS << " (" << F->getContents().size() << " bytes)";
break;
}
case MCFragment::FT_Org: {
const auto *OF = cast<MCOrgFragment>(this);
OS << "\n ";
OS << " Offset:" << OF->getOffset()
<< " Value:" << static_cast<unsigned>(OF->getValue());
break;
}
case MCFragment::FT_Dwarf: {
const auto *OF = cast<MCDwarfLineAddrFragment>(this);
OS << "\n ";
OS << " AddrDelta:" << OF->getAddrDelta()
<< " LineDelta:" << OF->getLineDelta();
break;
}
case MCFragment::FT_DwarfFrame: {
const auto *CF = cast<MCDwarfCallFrameFragment>(this);
OS << "\n ";
OS << " AddrDelta:" << CF->getAddrDelta();
break;
}
case MCFragment::FT_LEB: {
const auto *LF = cast<MCLEBFragment>(this);
OS << "\n ";
OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
break;
}
case MCFragment::FT_BoundaryAlign: {
const auto *BF = cast<MCBoundaryAlignFragment>(this);
OS << "\n ";
OS << " BoundarySize:" << BF->getAlignment().value()
<< " LastFragment:" << BF->getLastFragment()
<< " Size:" << BF->getSize();
break;
}
case MCFragment::FT_SymbolId: {
const auto *F = cast<MCSymbolIdFragment>(this);
OS << "\n ";
OS << " Sym:" << F->getSymbol();
break;
}
case MCFragment::FT_CVInlineLines: {
const auto *F = cast<MCCVInlineLineTableFragment>(this);
OS << "\n ";
OS << " Sym:" << *F->getFnStartSym();
break;
}
case MCFragment::FT_CVDefRange: {
const auto *F = cast<MCCVDefRangeFragment>(this);
OS << "\n ";
for (std::pair<const MCSymbol *, const MCSymbol *> RangeStartEnd :
F->getRanges()) {
OS << " RangeStart:" << RangeStartEnd.first;
OS << " RangeEnd:" << RangeStartEnd.second;
}
break;
}
case MCFragment::FT_PseudoProbe: {
const auto *OF = cast<MCPseudoProbeAddrFragment>(this);
OS << "\n ";
OS << " AddrDelta:" << OF->getAddrDelta();
break;
}
case MCFragment::FT_Dummy:
break;
}
OS << ">";
}
#endif
| 6,579 |
778 | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: <NAME>
//
//
#if !defined(KRATOS_KRATOS_H_INCLUDED )
#define KRATOS_KRATOS_H_INCLUDED
///@defgroup KratosCore Kratos Core
///@brief The Kratos core comprises a basic set of classes used by all applications.
// System includes
// External includes
// Project includes
#include "includes/define.h"
#include "includes/ublas_interface.h"
#include "geometries/point.h"
namespace Kratos
{
} // namespace Kratos.
#endif // KRATOS_KRATOS_H_INCLUDED defined
| 353 |
789 |
def init_logging():
import logging
logging.basicConfig(format="%(asctime)-15s: %(levelname)s: %(message)s",
level=logging.INFO)
| 78 |
4,772 | <filename>jpa/deferred/src/main/java/example/repo/Customer1902Repository.java
package example.repo;
import example.model.Customer1902;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface Customer1902Repository extends CrudRepository<Customer1902, Long> {
List<Customer1902> findByLastName(String lastName);
}
| 115 |
775 | <filename>ote_sdk/ote_sdk/serialization/label_mapper.py
#
# Copyright (C) 2021-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
""" This module contains the mapper for label related entities """
import json
from typing import Dict, Union, cast
from ote_sdk.entities.color import Color
from ote_sdk.entities.id import ID
from ote_sdk.entities.label import Domain, LabelEntity
from ote_sdk.entities.label_schema import (
LabelGraph,
LabelGroup,
LabelGroupType,
LabelSchemaEntity,
LabelTree,
)
from .datetime_mapper import DatetimeMapper
from .id_mapper import IDMapper
class ColorMapper:
"""
This class maps a `Color` entity to a serialized dictionary, and vice versa
"""
@staticmethod
def forward(instance: Color) -> dict:
"""Serializes to dict."""
return {
"red": instance.red,
"green": instance.green,
"blue": instance.blue,
"alpha": instance.alpha,
}
@staticmethod
def backward(instance: dict) -> Color:
"""Deserializes from dict."""
return Color(
instance["red"], instance["green"], instance["blue"], instance["alpha"]
)
class LabelMapper:
"""
This class maps a `Label` entity to a serialized dictionary, and vice versa
"""
@staticmethod
def forward(
instance: LabelEntity,
) -> dict:
"""Serializes to dict."""
return {
"_id": IDMapper().forward(instance.id_),
"name": instance.name,
"color": ColorMapper().forward(instance.color),
"hotkey": instance.hotkey,
"domain": str(instance.domain),
"creation_date": DatetimeMapper.forward(instance.creation_date),
"is_empty": instance.is_empty,
}
@staticmethod
def backward(instance: dict) -> LabelEntity:
"""Deserializes from dict."""
label_id = IDMapper().backward(instance["_id"])
domain = str(instance.get("domain"))
label_domain = Domain[domain]
label = LabelEntity(
id=label_id,
name=instance["name"],
color=ColorMapper().backward(instance["color"]),
hotkey=instance.get("hotkey", ""),
domain=label_domain,
creation_date=DatetimeMapper.backward(instance["creation_date"]),
is_empty=instance.get("is_empty", False),
)
return label
class LabelGroupMapper:
"""
This class maps a `LabelGroup` entity to a serialized dictionary, and vice versa
"""
@staticmethod
def forward(instance: LabelGroup) -> dict:
"""Serializes to dict."""
return {
"_id": IDMapper().forward(instance.id_),
"name": instance.name,
"label_ids": [IDMapper().forward(label.id_) for label in instance.labels],
"relation_type": instance.group_type.name,
}
@staticmethod
def backward(instance: dict, all_labels: Dict[ID, LabelEntity]) -> LabelGroup:
"""Deserializes from dict."""
return LabelGroup(
id=IDMapper().backward(instance["_id"]),
name=instance["name"],
group_type=LabelGroupType[instance["relation_type"]],
labels=[
all_labels[IDMapper().backward(label_id)]
for label_id in instance["label_ids"]
],
)
class LabelGraphMapper:
"""
This class maps a `LabelGraph` entity to a serialized dictionary, and vice versa
"""
@staticmethod
def forward(instance: Union[LabelGraph, LabelTree]) -> dict:
"""Serializes to dict."""
return {
"type": instance.type,
"directed": instance.directed,
"nodes": [IDMapper().forward(label.id_) for label in instance.nodes],
"edges": [
(IDMapper().forward(edge[0].id_), IDMapper().forward(edge[1].id_))
for edge in instance.edges
],
}
@staticmethod
def backward(
instance: dict, all_labels: Dict[ID, LabelEntity]
) -> Union[LabelTree, LabelGraph]:
"""Deserializes from dict."""
output: Union[LabelTree, LabelGraph]
instance_type = instance["type"]
if instance_type == "tree":
output = LabelTree()
elif instance_type == "graph":
output = LabelGraph(instance["directed"])
else:
raise ValueError(f"Unsupported type `{instance_type}` for label graph")
label_map = {
label_id: all_labels.get(IDMapper().backward(label_id))
for label_id in instance["nodes"]
}
for label in label_map.values():
output.add_node(label)
for edge in instance["edges"]:
output.add_edge(label_map[edge[0]], label_map[edge[1]])
return output
class LabelSchemaMapper:
"""
This class maps a `LabelSchema` entity to a serialized dictionary, and vice versa
"""
@staticmethod
def forward(
instance: LabelSchemaEntity,
) -> dict:
"""Serializes to dict."""
label_groups = [
LabelGroupMapper().forward(group)
for group in instance.get_groups(include_empty=True)
]
return {
"label_tree": LabelGraphMapper().forward(instance.label_tree),
"label_groups": label_groups,
"all_labels": {
IDMapper().forward(label.id_): LabelMapper().forward(label)
for label in instance.get_labels(True)
},
}
@staticmethod
def backward(instance: dict) -> LabelSchemaEntity:
"""Deserializes from dict."""
all_labels = {
IDMapper().backward(id): LabelMapper().backward(label)
for id, label in instance["all_labels"].items()
}
label_tree = LabelGraphMapper().backward(instance["label_tree"], all_labels)
label_groups = [
LabelGroupMapper().backward(label_group, all_labels)
for label_group in instance["label_groups"]
]
output = LabelSchemaEntity(
label_tree=cast(LabelTree, label_tree),
label_groups=label_groups,
)
return output
def label_schema_to_bytes(label_schema: LabelSchemaEntity) -> bytes:
"""
Returns json-serialized LabelSchemaEntity as bytes.
"""
serialized_label_schema = LabelSchemaMapper.forward(label_schema)
return json.dumps(serialized_label_schema, indent=4).encode()
| 2,859 |
1,475 | /*
* 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.geode.gradle.testing.isolation;
/**
* Represents a range of ports.
*/
public class PortRange {
private final int lowerBound;
private final int upperBound;
public PortRange(int lowerBound, int upperBound) {
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
public int lowerBound() {
return lowerBound;
}
public int upperBound() {
return upperBound;
}
public int size() {
return upperBound - lowerBound + 1;
}
/**
* Partition this port range into a number of sub-ranges and return the selected sub-range.
* The partitions are such that sizes of the largest and smallest differ by no more than 1.
*/
public PortRange partition(int partitionIndex, int numberOfPartitions) {
int partitionLowerBound = partitionLowerBound(partitionIndex, numberOfPartitions);
int partitionUpperBound = partitionLowerBound(partitionIndex + 1, numberOfPartitions) - 1;
return new PortRange(partitionLowerBound, partitionUpperBound);
}
@Override
public String toString() {
return "[" + +lowerBound + "," + upperBound + ']';
}
private int partitionLowerBound(int partitionIndex, int numberOfPartitions) {
return lowerBound() + size() * partitionIndex / numberOfPartitions;
}
}
| 564 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-j2cr-8pw5-rpvq",
"modified": "2022-04-30T18:13:19Z",
"published": "2022-04-30T18:13:19Z",
"aliases": [
"CVE-2000-0269"
],
"details": "Emacs 20 does not properly set permissions for a slave PTY device when starting a new subprocess, which allows local users to read or modify communications between Emacs and the subprocess.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2000-0269"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/1125"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/templates/archive.pike?list=1&date=2000-04-15&msg=<EMAIL>"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "LOW",
"github_reviewed": false
}
} | 396 |
839 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.binding.soap.interceptor;
import java.util.logging.Logger;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.apache.cxf.binding.soap.SoapFault;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.common.i18n.Message;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.phase.Phase;
public class CheckFaultInterceptor extends AbstractSoapInterceptor {
private static final Logger LOG = LogUtils.getL7dLogger(CheckFaultInterceptor.class);
public CheckFaultInterceptor() {
this(Phase.POST_PROTOCOL);
}
public CheckFaultInterceptor(String phase) {
super(phase);
}
public void handleMessage(SoapMessage message) {
XMLStreamReader xmlReader = message.getContent(XMLStreamReader.class);
if (xmlReader == null) {
return;
}
try {
// advance to first tag.
int x = xmlReader.getEventType();
while (x != XMLStreamConstants.START_ELEMENT
&& x != XMLStreamConstants.END_ELEMENT
&& xmlReader.hasNext()) {
x = xmlReader.next();
}
if (!xmlReader.hasNext()) {
//end of document, just return
return;
}
} catch (XMLStreamException e) {
throw new SoapFault(new Message("XML_STREAM_EXC", LOG, e.getMessage()), e,
message.getVersion().getSender());
}
if (message.getVersion().getFault().equals(xmlReader.getName()) && isRequestor(message)) {
Endpoint ep = message.getExchange().getEndpoint();
message.getInterceptorChain().abort();
if (ep.getInFaultObserver() != null) {
ep.getInFaultObserver().onMessage(message);
}
}
}
}
| 1,083 |
679 | <reponame>Grosskopf/openoffice
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "Tickmarks_Equidistant.hxx"
#include "ViewDefines.hxx"
#include <rtl/math.hxx>
#include <tools/debug.hxx>
#include <memory>
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;
using namespace ::rtl::math;
using ::basegfx::B2DVector;
//static
double EquidistantTickFactory::getMinimumAtIncrement( double fMin, const ExplicitIncrementData& rIncrement )
{
//the returned value will be <= fMin and on a Major Tick given by rIncrement
if(rIncrement.Distance<=0.0)
return fMin;
double fRet = rIncrement.BaseValue +
floor( approxSub( fMin, rIncrement.BaseValue )
/ rIncrement.Distance)
*rIncrement.Distance;
if( fRet > fMin )
{
if( !approxEqual(fRet, fMin) )
fRet -= rIncrement.Distance;
}
return fRet;
}
//static
double EquidistantTickFactory::getMaximumAtIncrement( double fMax, const ExplicitIncrementData& rIncrement )
{
//the returned value will be >= fMax and on a Major Tick given by rIncrement
if(rIncrement.Distance<=0.0)
return fMax;
double fRet = rIncrement.BaseValue +
floor( approxSub( fMax, rIncrement.BaseValue )
/ rIncrement.Distance)
*rIncrement.Distance;
if( fRet < fMax )
{
if( !approxEqual(fRet, fMax) )
fRet += rIncrement.Distance;
}
return fRet;
}
EquidistantTickFactory::EquidistantTickFactory(
const ExplicitScaleData& rScale, const ExplicitIncrementData& rIncrement )
: m_rScale( rScale )
, m_rIncrement( rIncrement )
, m_xInverseScaling(NULL)
, m_pfCurrentValues(NULL)
{
//@todo: make sure that the scale is valid for the scaling
m_pfCurrentValues = new double[getTickDepth()];
if( m_rScale.Scaling.is() )
{
m_xInverseScaling = m_rScale.Scaling->getInverseScaling();
DBG_ASSERT( m_xInverseScaling.is(), "each Scaling needs to return a inverse Scaling" );
}
double fMin = m_fScaledVisibleMin = m_rScale.Minimum;
if( m_xInverseScaling.is() )
{
m_fScaledVisibleMin = m_rScale.Scaling->doScaling(m_fScaledVisibleMin);
if(m_rIncrement.PostEquidistant )
fMin = m_fScaledVisibleMin;
}
double fMax = m_fScaledVisibleMax = m_rScale.Maximum;
if( m_xInverseScaling.is() )
{
m_fScaledVisibleMax = m_rScale.Scaling->doScaling(m_fScaledVisibleMax);
if(m_rIncrement.PostEquidistant )
fMax = m_fScaledVisibleMax;
}
//--
m_fOuterMajorTickBorderMin = EquidistantTickFactory::getMinimumAtIncrement( fMin, m_rIncrement );
m_fOuterMajorTickBorderMax = EquidistantTickFactory::getMaximumAtIncrement( fMax, m_rIncrement );
//--
m_fOuterMajorTickBorderMin_Scaled = m_fOuterMajorTickBorderMin;
m_fOuterMajorTickBorderMax_Scaled = m_fOuterMajorTickBorderMax;
if(!m_rIncrement.PostEquidistant && m_xInverseScaling.is() )
{
m_fOuterMajorTickBorderMin_Scaled = m_rScale.Scaling->doScaling(m_fOuterMajorTickBorderMin);
m_fOuterMajorTickBorderMax_Scaled = m_rScale.Scaling->doScaling(m_fOuterMajorTickBorderMax);
//check validity of new range: m_fOuterMajorTickBorderMin <-> m_fOuterMajorTickBorderMax
//it is assumed here, that the original range in the given Scale is valid
if( !rtl::math::isFinite(m_fOuterMajorTickBorderMin_Scaled) )
{
m_fOuterMajorTickBorderMin += m_rIncrement.Distance;
m_fOuterMajorTickBorderMin_Scaled = m_rScale.Scaling->doScaling(m_fOuterMajorTickBorderMin);
}
if( !rtl::math::isFinite(m_fOuterMajorTickBorderMax_Scaled) )
{
m_fOuterMajorTickBorderMax -= m_rIncrement.Distance;
m_fOuterMajorTickBorderMax_Scaled = m_rScale.Scaling->doScaling(m_fOuterMajorTickBorderMax);
}
}
}
EquidistantTickFactory::~EquidistantTickFactory()
{
delete[] m_pfCurrentValues;
}
sal_Int32 EquidistantTickFactory::getTickDepth() const
{
return static_cast<sal_Int32>(m_rIncrement.SubIncrements.size()) + 1;
}
void EquidistantTickFactory::addSubTicks( sal_Int32 nDepth, uno::Sequence< uno::Sequence< double > >& rParentTicks ) const
{
EquidistantTickIter aIter( rParentTicks, m_rIncrement, 0, nDepth-1 );
double* pfNextParentTick = aIter.firstValue();
if(!pfNextParentTick)
return;
double fLastParentTick = *pfNextParentTick;
pfNextParentTick = aIter.nextValue();
if(!pfNextParentTick)
return;
sal_Int32 nMaxSubTickCount = this->getMaxTickCount( nDepth );
if(!nMaxSubTickCount)
return;
uno::Sequence< double > aSubTicks(nMaxSubTickCount);
sal_Int32 nRealSubTickCount = 0;
sal_Int32 nIntervalCount = m_rIncrement.SubIncrements[nDepth-1].IntervalCount;
double* pValue = NULL;
for(; pfNextParentTick; fLastParentTick=*pfNextParentTick, pfNextParentTick = aIter.nextValue())
{
for( sal_Int32 nPartTick = 1; nPartTick<nIntervalCount; nPartTick++ )
{
pValue = this->getMinorTick( nPartTick, nDepth
, fLastParentTick, *pfNextParentTick );
if(!pValue)
continue;
aSubTicks[nRealSubTickCount] = *pValue;
nRealSubTickCount++;
}
}
aSubTicks.realloc(nRealSubTickCount);
rParentTicks[nDepth] = aSubTicks;
if(static_cast<sal_Int32>(m_rIncrement.SubIncrements.size())>nDepth)
addSubTicks( nDepth+1, rParentTicks );
}
sal_Int32 EquidistantTickFactory::getMaxTickCount( sal_Int32 nDepth ) const
{
//return the maximum amount of ticks
//possibly open intervals at the two ends of the region are handled as if they were completely visible
//(this is necessary for calculating the sub ticks at the borders correctly)
if( nDepth >= getTickDepth() )
return 0;
if( m_fOuterMajorTickBorderMax < m_fOuterMajorTickBorderMin )
return 0;
if( m_rIncrement.Distance<=0.0)
return 0;
double fSub;
if(m_rIncrement.PostEquidistant )
fSub = approxSub( m_fScaledVisibleMax, m_fScaledVisibleMin );
else
fSub = approxSub( m_rScale.Maximum, m_rScale.Minimum );
if (!isFinite(fSub))
return 0;
sal_Int32 nIntervalCount = static_cast<sal_Int32>( fSub / m_rIncrement.Distance );
nIntervalCount+=3;
for(sal_Int32 nN=0; nN<nDepth-1; nN++)
{
if( m_rIncrement.SubIncrements[nN].IntervalCount>1 )
nIntervalCount *= m_rIncrement.SubIncrements[nN].IntervalCount;
}
sal_Int32 nTickCount = nIntervalCount;
if(nDepth>0 && m_rIncrement.SubIncrements[nDepth-1].IntervalCount>1)
nTickCount = nIntervalCount * (m_rIncrement.SubIncrements[nDepth-1].IntervalCount-1);
return nTickCount;
}
double* EquidistantTickFactory::getMajorTick( sal_Int32 nTick ) const
{
m_pfCurrentValues[0] = m_fOuterMajorTickBorderMin + nTick*m_rIncrement.Distance;
if(m_pfCurrentValues[0]>m_fOuterMajorTickBorderMax)
{
if( !approxEqual(m_pfCurrentValues[0],m_fOuterMajorTickBorderMax) )
return NULL;
}
if(m_pfCurrentValues[0]<m_fOuterMajorTickBorderMin)
{
if( !approxEqual(m_pfCurrentValues[0],m_fOuterMajorTickBorderMin) )
return NULL;
}
//return always the value after scaling
if(!m_rIncrement.PostEquidistant && m_xInverseScaling.is() )
m_pfCurrentValues[0] = m_rScale.Scaling->doScaling( m_pfCurrentValues[0] );
return &m_pfCurrentValues[0];
}
double* EquidistantTickFactory::getMinorTick( sal_Int32 nTick, sal_Int32 nDepth
, double fStartParentTick, double fNextParentTick ) const
{
//check validity of arguments
{
//DBG_ASSERT( fStartParentTick < fNextParentTick, "fStartParentTick >= fNextParentTick");
if(fStartParentTick >= fNextParentTick)
return NULL;
if(nDepth>static_cast<sal_Int32>(m_rIncrement.SubIncrements.size()) || nDepth<=0)
return NULL;
//subticks are only calculated if they are laying between parent ticks:
if(nTick<=0)
return NULL;
if(nTick>=m_rIncrement.SubIncrements[nDepth-1].IntervalCount)
return NULL;
}
bool bPostEquidistant = m_rIncrement.SubIncrements[nDepth-1].PostEquidistant;
double fAdaptedStartParent = fStartParentTick;
double fAdaptedNextParent = fNextParentTick;
if( !bPostEquidistant && m_xInverseScaling.is() )
{
fAdaptedStartParent = m_xInverseScaling->doScaling(fStartParentTick);
fAdaptedNextParent = m_xInverseScaling->doScaling(fNextParentTick);
}
double fDistance = (fAdaptedNextParent - fAdaptedStartParent)/m_rIncrement.SubIncrements[nDepth-1].IntervalCount;
m_pfCurrentValues[nDepth] = fAdaptedStartParent + nTick*fDistance;
//return always the value after scaling
if(!bPostEquidistant && m_xInverseScaling.is() )
m_pfCurrentValues[nDepth] = m_rScale.Scaling->doScaling( m_pfCurrentValues[nDepth] );
if( !isWithinOuterBorder( m_pfCurrentValues[nDepth] ) )
return NULL;
return &m_pfCurrentValues[nDepth];
}
bool EquidistantTickFactory::isWithinOuterBorder( double fScaledValue ) const
{
if(fScaledValue>m_fOuterMajorTickBorderMax_Scaled)
return false;
if(fScaledValue<m_fOuterMajorTickBorderMin_Scaled)
return false;
return true;
}
bool EquidistantTickFactory::isVisible( double fScaledValue ) const
{
if(fScaledValue>m_fScaledVisibleMax)
{
if( !approxEqual(fScaledValue,m_fScaledVisibleMax) )
return false;
}
if(fScaledValue<m_fScaledVisibleMin)
{
if( !approxEqual(fScaledValue,m_fScaledVisibleMin) )
return false;
}
return true;
}
void EquidistantTickFactory::getAllTicks( ::std::vector< ::std::vector< TickInfo > >& rAllTickInfos ) const
{
uno::Sequence< uno::Sequence< double > > aAllTicks;
//create point sequences for each tick depth
sal_Int32 nDepthCount = this->getTickDepth();
sal_Int32 nMaxMajorTickCount = this->getMaxTickCount( 0 );
aAllTicks.realloc(nDepthCount);
aAllTicks[0].realloc(nMaxMajorTickCount);
sal_Int32 nRealMajorTickCount = 0;
double* pValue = NULL;
for( sal_Int32 nMajorTick=0; nMajorTick<nMaxMajorTickCount; nMajorTick++ )
{
pValue = this->getMajorTick( nMajorTick );
if(!pValue)
continue;
aAllTicks[0][nRealMajorTickCount] = *pValue;
nRealMajorTickCount++;
}
if(!nRealMajorTickCount)
return;
aAllTicks[0].realloc(nRealMajorTickCount);
if(nDepthCount>0)
this->addSubTicks( 1, aAllTicks );
//so far we have added all ticks between the outer major tick marks
//this was necessary to create sub ticks correctly
//now we reduce all ticks to the visible ones that lie between the real borders
sal_Int32 nDepth = 0;
sal_Int32 nTick = 0;
for( nDepth = 0; nDepth < nDepthCount; nDepth++)
{
sal_Int32 nInvisibleAtLowerBorder = 0;
sal_Int32 nInvisibleAtUpperBorder = 0;
//we need only to check all ticks within the first major interval at each border
sal_Int32 nCheckCount = 1;
for(sal_Int32 nN=0; nN<nDepth; nN++)
{
if( m_rIncrement.SubIncrements[nN].IntervalCount>1 )
nCheckCount *= m_rIncrement.SubIncrements[nN].IntervalCount;
}
uno::Sequence< double >& rTicks = aAllTicks[nDepth];
sal_Int32 nCount = rTicks.getLength();
//check lower border
for( nTick=0; nTick<nCheckCount && nTick<nCount; nTick++)
{
if( !isVisible( rTicks[nTick] ) )
nInvisibleAtLowerBorder++;
}
//check upper border
for( nTick=nCount-1; nTick>nCount-1-nCheckCount && nTick>=0; nTick--)
{
if( !isVisible( rTicks[nTick] ) )
nInvisibleAtUpperBorder++;
}
//resize sequence
if( !nInvisibleAtLowerBorder && !nInvisibleAtUpperBorder)
continue;
if( !nInvisibleAtLowerBorder )
rTicks.realloc(nCount-nInvisibleAtUpperBorder);
else
{
sal_Int32 nNewCount = nCount-nInvisibleAtUpperBorder-nInvisibleAtLowerBorder;
if(nNewCount<0)
nNewCount=0;
uno::Sequence< double > aOldTicks(rTicks);
rTicks.realloc(nNewCount);
for(nTick = 0; nTick<nNewCount; nTick++)
rTicks[nTick] = aOldTicks[nInvisibleAtLowerBorder+nTick];
}
}
//fill return value
rAllTickInfos.resize(aAllTicks.getLength());
for( nDepth=0 ;nDepth<aAllTicks.getLength(); nDepth++ )
{
sal_Int32 nCount = aAllTicks[nDepth].getLength();
::std::vector< TickInfo >& rTickInfoVector = rAllTickInfos[nDepth];
rTickInfoVector.clear();
rTickInfoVector.reserve( nCount );
for(sal_Int32 nN = 0; nN<nCount; nN++)
{
TickInfo aTickInfo(m_xInverseScaling);
aTickInfo.fScaledTickValue = aAllTicks[nDepth][nN];
rTickInfoVector.push_back(aTickInfo);
}
}
}
void EquidistantTickFactory::getAllTicksShifted( ::std::vector< ::std::vector< TickInfo > >& rAllTickInfos ) const
{
ExplicitIncrementData aShiftedIncrement( m_rIncrement );
aShiftedIncrement.BaseValue = m_rIncrement.BaseValue-m_rIncrement.Distance/2.0;
EquidistantTickFactory( m_rScale, aShiftedIncrement ).getAllTicks(rAllTickInfos);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
EquidistantTickIter::EquidistantTickIter( const uno::Sequence< uno::Sequence< double > >& rTicks
, const ExplicitIncrementData& rIncrement
, sal_Int32 nMinDepth, sal_Int32 nMaxDepth )
: m_pSimpleTicks(&rTicks)
, m_pInfoTicks(0)
, m_rIncrement(rIncrement)
, m_nMinDepth(0), m_nMaxDepth(0)
, m_nTickCount(0), m_pnPositions(NULL)
, m_pnPreParentCount(NULL), m_pbIntervalFinished(NULL)
, m_nCurrentDepth(-1), m_nCurrentPos(-1), m_fCurrentValue( 0.0 )
{
initIter( nMinDepth, nMaxDepth );
}
EquidistantTickIter::EquidistantTickIter( ::std::vector< ::std::vector< TickInfo > >& rTicks
, const ExplicitIncrementData& rIncrement
, sal_Int32 nMinDepth, sal_Int32 nMaxDepth )
: m_pSimpleTicks(NULL)
, m_pInfoTicks(&rTicks)
, m_rIncrement(rIncrement)
, m_nMinDepth(0), m_nMaxDepth(0)
, m_nTickCount(0), m_pnPositions(NULL)
, m_pnPreParentCount(NULL), m_pbIntervalFinished(NULL)
, m_nCurrentDepth(-1), m_nCurrentPos(-1), m_fCurrentValue( 0.0 )
{
initIter( nMinDepth, nMaxDepth );
}
void EquidistantTickIter::initIter( sal_Int32 /*nMinDepth*/, sal_Int32 nMaxDepth )
{
m_nMaxDepth = nMaxDepth;
if(nMaxDepth<0 || m_nMaxDepth>getMaxDepth())
m_nMaxDepth=getMaxDepth();
sal_Int32 nDepth = 0;
for( nDepth = 0; nDepth<=m_nMaxDepth ;nDepth++ )
m_nTickCount += getTickCount(nDepth);
if(!m_nTickCount)
return;
m_pnPositions = new sal_Int32[m_nMaxDepth+1];
m_pnPreParentCount = new sal_Int32[m_nMaxDepth+1];
m_pbIntervalFinished = new bool[m_nMaxDepth+1];
m_pnPreParentCount[0] = 0;
m_pbIntervalFinished[0] = false;
double fParentValue = getTickValue(0,0);
for( nDepth = 1; nDepth<=m_nMaxDepth ;nDepth++ )
{
m_pbIntervalFinished[nDepth] = false;
sal_Int32 nPreParentCount = 0;
sal_Int32 nCount = getTickCount(nDepth);
for(sal_Int32 nN = 0; nN<nCount; nN++)
{
if(getTickValue(nDepth,nN) < fParentValue)
nPreParentCount++;
else
break;
}
m_pnPreParentCount[nDepth] = nPreParentCount;
if(nCount)
{
double fNextParentValue = getTickValue(nDepth,0);
if( fNextParentValue < fParentValue )
fParentValue = fNextParentValue;
}
}
}
EquidistantTickIter::~EquidistantTickIter()
{
delete[] m_pnPositions;
delete[] m_pnPreParentCount;
delete[] m_pbIntervalFinished;
}
sal_Int32 EquidistantTickIter::getStartDepth() const
{
//find the depth of the first visible tickmark:
//it is the depth of the smallest value
sal_Int32 nReturnDepth=0;
double fMinValue = DBL_MAX;
for(sal_Int32 nDepth = 0; nDepth<=m_nMaxDepth ;nDepth++ )
{
sal_Int32 nCount = getTickCount(nDepth);
if( !nCount )
continue;
double fThisValue = getTickValue(nDepth,0);
if(fThisValue<fMinValue)
{
nReturnDepth = nDepth;
fMinValue = fThisValue;
}
}
return nReturnDepth;
}
double* EquidistantTickIter::firstValue()
{
if( gotoFirst() )
{
m_fCurrentValue = getTickValue(m_nCurrentDepth, m_pnPositions[m_nCurrentDepth]);
return &m_fCurrentValue;
}
return NULL;
}
TickInfo* EquidistantTickIter::firstInfo()
{
if( m_pInfoTicks && gotoFirst() )
return &(*m_pInfoTicks)[m_nCurrentDepth][m_pnPositions[m_nCurrentDepth]];
return NULL;
}
sal_Int32 EquidistantTickIter::getIntervalCount( sal_Int32 nDepth )
{
if(nDepth>static_cast<sal_Int32>(m_rIncrement.SubIncrements.size()) || nDepth<0)
return 0;
if(!nDepth)
return m_nTickCount;
return m_rIncrement.SubIncrements[nDepth-1].IntervalCount;
}
bool EquidistantTickIter::isAtLastPartTick()
{
if(!m_nCurrentDepth)
return false;
sal_Int32 nIntervalCount = getIntervalCount( m_nCurrentDepth );
if(!nIntervalCount || nIntervalCount == 1)
return true;
if( m_pbIntervalFinished[m_nCurrentDepth] )
return false;
sal_Int32 nPos = m_pnPositions[m_nCurrentDepth]+1;
if(m_pnPreParentCount[m_nCurrentDepth])
nPos += nIntervalCount-1 - m_pnPreParentCount[m_nCurrentDepth];
bool bRet = nPos && nPos % (nIntervalCount-1) == 0;
if(!nPos && !m_pnPreParentCount[m_nCurrentDepth]
&& m_pnPositions[m_nCurrentDepth-1]==-1 )
bRet = true;
return bRet;
}
bool EquidistantTickIter::gotoFirst()
{
if( m_nMaxDepth<0 )
return false;
if( !m_nTickCount )
return false;
for(sal_Int32 nDepth = 0; nDepth<=m_nMaxDepth ;nDepth++ )
m_pnPositions[nDepth] = -1;
m_nCurrentPos = 0;
m_nCurrentDepth = getStartDepth();
m_pnPositions[m_nCurrentDepth] = 0;
return true;
}
bool EquidistantTickIter::gotoNext()
{
if( m_nCurrentPos < 0 )
return false;
m_nCurrentPos++;
if( m_nCurrentPos >= m_nTickCount )
return false;
if( m_nCurrentDepth==m_nMaxDepth && isAtLastPartTick() )
{
do
{
m_pbIntervalFinished[m_nCurrentDepth] = true;
m_nCurrentDepth--;
}
while( m_nCurrentDepth && isAtLastPartTick() );
}
else if( m_nCurrentDepth<m_nMaxDepth )
{
do
{
m_nCurrentDepth++;
}
while( m_nCurrentDepth<m_nMaxDepth );
}
m_pbIntervalFinished[m_nCurrentDepth] = false;
m_pnPositions[m_nCurrentDepth] = m_pnPositions[m_nCurrentDepth]+1;
return true;
}
bool EquidistantTickIter::gotoIndex( sal_Int32 nTickIndex )
{
if( nTickIndex < 0 )
return false;
if( nTickIndex >= m_nTickCount )
return false;
if( nTickIndex < m_nCurrentPos )
if( !gotoFirst() )
return false;
while( nTickIndex > m_nCurrentPos )
if( !gotoNext() )
return false;
return true;
}
sal_Int32 EquidistantTickIter::getCurrentIndex() const
{
return m_nCurrentPos;
}
sal_Int32 EquidistantTickIter::getMaxIndex() const
{
return m_nTickCount-1;
}
double* EquidistantTickIter::nextValue()
{
if( gotoNext() )
{
m_fCurrentValue = getTickValue(m_nCurrentDepth, m_pnPositions[m_nCurrentDepth]);
return &m_fCurrentValue;
}
return NULL;
}
TickInfo* EquidistantTickIter::nextInfo()
{
if( m_pInfoTicks && gotoNext() &&
static_cast< sal_Int32 >(
(*m_pInfoTicks)[m_nCurrentDepth].size()) > m_pnPositions[m_nCurrentDepth] )
{
return &(*m_pInfoTicks)[m_nCurrentDepth][m_pnPositions[m_nCurrentDepth]];
}
return NULL;
}
//.............................................................................
} //namespace chart
//.............................................................................
| 9,778 |
7,482 | /******************************************************************************
*
* Freescale Semiconductor Inc.
* (c) Copyright 2004-2010 Freescale Semiconductor, Inc.
* ALL RIGHTS RESERVED.
*
**************************************************************************//*!
*
* @file disk.c
*
* @author
*
* @version
*
* @date May-08-2009
*
* @brief RAM Disk has been emulated via this Mass Storage Demo
*****************************************************************************/
/******************************************************************************
* Includes
*****************************************************************************/
#include "types.h" /* User Defined Data Types */
#include "hidef.h" /* for EnableInterrupts macro */
#include <string.h>
#include <stdlib.h> /* ANSI memory controls */
#include "stdio.h"
#include "derivative.h" /* include peripheral declarations */
#include "usb_msc.h" /* USB MSC Class Header File */
#include "disk.h" /* Disk Application Header File */
#include "usb_class.h"
#include "FAT16.h"
#include "sci.h"
#if defined(__MCF52xxx_H__)
#include "Wdt_cfv2.h"
#include "SD_cfv2.h"
#endif
#ifdef MCU_mcf51jf128
#include "SD_cfv1_plus.h"
#endif
#if (defined MCU_MK60N512VMD100) || (defined MCU_MK70F12) || (defined MCU_MK21D5)
#include "SD_kinetis.h"
#endif
#if (defined _MCF51MM256_H) || (defined _MCF51JE256_H)
#include "exceptions.h"
#endif
/* skip the inclusion in dependency statge */
#ifndef __NO_SETJMP
#include <stdio.h>
#endif
#include <stdlib.h>
#include <string.h>
/*****************************************************************************
* Constant and Macro's - None
*****************************************************************************/
/*****************************************************************************
* Global Functions Prototypes
*****************************************************************************/
void TestApp_Init(void);
extern void Watchdog_Reset(void);
extern uint_8 filetype; /* image file type */
uint_32 file_size; /* bytes */
uint_8 new_file;
uint_8 error=FLASH_IMAGE_SUCCESS;
boolean boot_complete = FALSE;
/****************************************************************************
* Global Variables
****************************************************************************/
/* Add all the variables needed for disk.c to this structure */
DISK_GLOBAL_VARIABLE_STRUCT g_disk;
unsigned char BootloaderStatus = BootloaderReady;
/* Write data to SD*/
static LBA_APP_STRUCT lba_data;
static uint_8 lba_file_info_data[512];
static uint_32 block_position = 0;
static uint_16 buff_postion = 0;
static boolean video_flag = FALSE;
static uint_16 image_position = 0;
static uint_8 data_bff[512];
static uint_8 pre_data=0,cur_data=0,next_data=0;
static uint_8 info_flag=FALSE;
static uint_32 total_block=0,num_image=0;
static uint_32 dwScale,dwRate;
static uint_32 frame_rate;
/*****************************************************************************
* Local Types - None
*****************************************************************************/
/*****************************************************************************
* Local Functions Prototypes
*****************************************************************************/
void USB_App_Callback(uint_8 controller_ID, uint_8 event_type, void* val);
void MSD_Event_Callback(uint_8 controller_ID, uint_8 event_type, void* val);
void Disk_App(void);
/*****************************************************************************
* Local Variables
*****************************************************************************/
/*****************************************************************************
* Local Functions
*****************************************************************************/
static void Sd_Write (uchar_ptr data_ptr);
static void Sd_Prepare_Data (uint_8_ptr data_ptr);
/******************************************************************************
*
* @name Disk_App
*
* @brief
*
* @param None
*
* @return None
*
*****************************************************************************/
void Disk_App(void)
{
/* Body */
uint_32 i = 0;
uint_32 j = 0;
if(TRUE== boot_complete)
{
/* De-Init MSD device */
for(i=0;i<1000;i++)
for(j=0;j<1000;j++) ;
USB_Class_MSC_DeInit(USB_CONTROLLER_ID);
boot_complete = FALSE;
for(i=0;i<1000;i++)
for(j=0;j<1000;j++) ;
/* Re-enumerate MSD device */
DisableInterrupts;
USB_Class_MSC_Init(g_disk.app_controller_ID,
USB_App_Callback,NULL, MSD_Event_Callback);
EnableInterrupts;
} /* EndIf */
return;
} /* EndBody */
/******************************************************************************
*
* @name USB_App_Callback
*
* @brief This function handles the callback
*
* @param controller_ID : To Identify the controller
* @param event_type : value of the event
* @param val : gives the configuration value
*
* @return None
*
*****************************************************************************/
void USB_App_Callback
(
uint_8 controller_ID,
uint_8 event_type,
void* val
)
{
/* Body */
UNUSED (controller_ID);
UNUSED (val);
if(event_type == USB_APP_BUS_RESET)
{
g_disk.start_app=FALSE;
}
else
{
if(event_type == USB_APP_ENUM_COMPLETE)
{
g_disk.start_app=TRUE;
}
else
{
if(event_type == USB_APP_ERROR)
{
/* add user code for error handling */
} /* EndIf */
} /* EndIf */
} /* EndIf */
return;
} /* EndBody */
/******************************************************************************
*
* @name MSD_Event_Callback
*
* @brief This function handles the callback
*
* @param controller_ID : To Identify the controller
* @param event_type : value of the event
* @param val : gives the configuration value
*
* @return None
*
*****************************************************************************/
void MSD_Event_Callback
(
uint_8 controller_ID,
uint_8 event_type,
void* val
)
{
/* Body */
PTR_LBA_APP_STRUCT lba_data_ptr;
uint_32 i;
uint_32 count;
uint_8_ptr prevent_removal_ptr, load_eject_start_ptr;
PTR_DEVICE_LBA_INFO_STRUCT device_lba_info_ptr;
UNUSED (controller_ID);
switch(event_type)
{
case USB_APP_DATA_RECEIVED :
break;
case USB_APP_SEND_COMPLETE :
break;
case USB_MSC_START_STOP_EJECT_MEDIA :
load_eject_start_ptr = (uint_8_ptr)val;
UNUSED(load_eject_start_ptr);
/* Code to be added by user for starting, stopping or
ejecting the disk drive. e.g. starting/stopping the motor in
case of CD/DVD*/
break;
case USB_MSC_DEVICE_READ_REQUEST :
/* copy data from storage device before sending it on USB Bus
(Called before calling send_data on BULK IN endpoints)*/
lba_data_ptr = (PTR_LBA_APP_STRUCT)val;
/* read data from mass storage device to driver buffer */
FATReadLBA(lba_data_ptr->offset>>9,lba_data_ptr->buff_ptr);
break;
case USB_MSC_DEVICE_WRITE_REQUEST :
/* copy data from USb buffer to Storage device
(Called before after recv_data on BULK OUT endpoints)*/
lba_data_ptr = (PTR_LBA_APP_STRUCT)val;
if((lba_data_ptr->offset>>9)== FATTable0Sec0)
{
/* write new file */
new_file = TRUE;
} /* EndIf */
if(((lba_data_ptr->offset>>9)== FATRootDirSec0)&&(new_file == TRUE))
{
/* read file size of the file was received */
/* search for the file entry was received */
/* each file entry contain 32 bytes */
for(i = lba_data_ptr->size -32; i>0; i -=32)
{
if(*(lba_data_ptr->buff_ptr +i) != 0)
{
break;
} /* EndIf */
} /* Endfor */
/* the file size field is offet 28 of file entry */
#if (defined __MK_xxx_H__) || (defined MCU_MK70F12)
file_size = *(uint_32*)( lba_data_ptr->buff_ptr + i + 28);
#else
file_size = BYTESWAP32(*(uint_32*)( lba_data_ptr->buff_ptr + i + 28));
#endif
new_file = FALSE;
} /* EndIf */
if((lba_data_ptr->offset>>9)>= FATDataSec0)
{
Sd_Prepare_Data(lba_data_ptr->buff_ptr);
} /* EndIf */
/* rest of file */
if(((lba_data_ptr->offset>>9) - FATDataSec0) == ((file_size -1)/512))
{
boot_complete=TRUE; /*tranfer file done */
*((uint_32*)lba_file_info_data) = ieee_ntohl(total_block);
*((uint_32*)(lba_file_info_data+4)) = ieee_ntohl(num_image);
*((uint_32*)(lba_file_info_data+8)) = ieee_ntohl(frame_rate);
for (count=12 ; count<512 ; count ++)
{
*(lba_file_info_data+count) = 0xFF;
}
lba_data.offset = 0x00010000;
lba_data.size = 0x200;
lba_data.buff_ptr = lba_file_info_data;
SD_Write_Block(&lba_data);
BootloaderStatus = BootloaderSuccess;
} /* EndIf */
break;
case USB_MSC_DEVICE_FORMAT_COMPLETE :
break;
case USB_MSC_DEVICE_REMOVAL_REQUEST :
prevent_removal_ptr = (uint_8_ptr) val;
if(SUPPORT_DISK_LOCKING_MECHANISM)
{
g_disk.disk_lock = *prevent_removal_ptr;
}
else
{
if((!SUPPORT_DISK_LOCKING_MECHANISM)&&(!(*prevent_removal_ptr)))
{
/*there is no support for disk locking and removal of medium is enabled*/
/* code to be added here for this condition, if required */
} /* EndIf */
} /* EndIf */
break;
case USB_MSC_DEVICE_GET_INFO :
device_lba_info_ptr = (PTR_DEVICE_LBA_INFO_STRUCT)val;
device_lba_info_ptr->total_lba_device_supports = TOTAL_LOGICAL_ADDRESS_BLOCKS;
device_lba_info_ptr->length_of_each_lba_of_device = LENGTH_OF_EACH_LAB;
device_lba_info_ptr->num_lun_supported = LOGICAL_UNIT_SUPPORTED;
break;
default :
break;
} /* EndSwitch */
return;
} /* EndBody */
/******************************************************************************
*
* @name TestApp_Init
*
* @brief This function is the entry for mouse (or other usuage)
*
* @param None
*
* @return None
**
*****************************************************************************/
void TestApp_Init(void)
{
/* Body */
uint_8 error;
#if !(defined _MC9S08JM60_H)
//sci_init();
#endif
SD_Init();
(void)SD_ReadCSD();
/* initialize the Global Variable Structure */
USB_memzero(&g_disk, sizeof(DISK_GLOBAL_VARIABLE_STRUCT));
g_disk.app_controller_ID = USB_CONTROLLER_ID;
DisableInterrupts;
#if (defined _MCF51MM256_H) || (defined _MCF51JE256_H)
usb_int_dis();
#endif
/* Initialize the USB interface */
error = USB_Class_MSC_Init(g_disk.app_controller_ID,
USB_App_Callback,NULL, MSD_Event_Callback);
UNUSED(error);
EnableInterrupts;
#if (defined _MCF51MM256_H) || (defined _MCF51JE256_H)
usb_int_en();
#endif
} /* EndBody */
/******************************************************************************
*
* @name TestApp_Task
*
* @brief Application task function. It is called from the main loop
*
* @param None
*
* @return None
*
*****************************************************************************
* Application task function. It is called from the main loop
*****************************************************************************/
void TestApp_Task(void)
{
/* Body */
/* call the periodic task function */
USB_MSC_Periodic_Task();
/*check whether enumeration is complete or not */
if(g_disk.start_app==TRUE)
{
Disk_App();
} /* EndIf */
} /* EndBody */
/******************************************************************************
*
* @name Sd_Write
*
* @brief This function is the entry for mouse (or other usage)
*
* @param data_ptr
*
* @return None
**
*****************************************************************************/
static void Sd_Write (uint_8_ptr data_ptr)
{
/* Body */
lba_data.offset = 0x00011200 + 512*block_position;
lba_data.size = 0x200;
lba_data.buff_ptr = (uint_8_ptr)data_ptr;
SD_Write_Block(&lba_data);
block_position++;
} /* EndBody */
/******************************************************************************
*
* @name Sd_Prepare_Data
*
* @brief This function is the entry for mouse (or other usuage)
*
* @param data_ptr
*
* @return None
**
*****************************************************************************/
static void Sd_Prepare_Data (uint_8_ptr data_ptr)
{
/* Body */
uint_8_ptr buffer;
uint_16 j = 0;
buffer = data_ptr;
if(TRUE==info_flag)
{
/*The buffer isn't contain video header*/
for(j= 0;j<LENGTH_OF_EACH_LAB;j++,buff_postion++)
{
pre_data=cur_data;
cur_data=next_data;
next_data= buffer[j];
if(( 0xFF==cur_data)&&(0xD8==next_data))
{
video_flag = TRUE;
num_image++;
}
if(TRUE==video_flag )
{
if ((0xFF==pre_data)&&(0xD9==cur_data))
{
video_flag = FALSE;
} /* EndIf */
data_bff[image_position++]= cur_data;
} /* EndIf */
if ( 512==image_position)
{
Sd_Write(data_bff);
image_position = 0;
total_block ++;
} /* EndIf */
} /* EndFor */
}
else
{
/*Read video header to get video information*/
dwScale = (buffer[128])|(buffer[129]<<8)|(buffer[130]<<16)|(buffer[131]<<24);
dwRate = (buffer[132])|(buffer[133]<<8)|(buffer[134]<<16)|(buffer[135]<<24);
frame_rate=(uint_32)(dwRate/dwScale);
info_flag=TRUE;
} /* EndIf */
} /* EndBody */
/* EOF */
| 5,133 |
332 | <gh_stars>100-1000
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.springframework.xd.test.fixtures;
import org.springframework.util.Assert;
/**
* Test fixture that creates a tap.
* @author <NAME>
*/
public class Tap extends AbstractModuleFixture<Tap> {
private String streamName;
/**
* Create a tap stream with the provided name.
*
* @param streamName name of the tap stream.
*/
public Tap(String streamName) {
Assert.hasText(streamName, "StreamName must not be empty nor null");
this.streamName = streamName;
}
/**
* Renders the default DSL for this fixture.
*/
@Override
protected String toDSL() {
StringBuilder dsl = new StringBuilder("tap:stream:");
dsl.append(streamName);
if (label != null) {
dsl.append(".");
dsl.append(label);
}
return dsl.toString();
}
}
| 421 |
345 | <gh_stars>100-1000
package com.github.theholywaffle.teamspeak3.commands.parameter;
/*
* #%L
* TeamSpeak 3 Java API
* %%
* Copyright (C) 2014 <NAME>
* %%
* 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.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
public class ArrayParameter extends Parameter {
private final int parametersPerEntry;
private final List<Parameter> parameters;
public ArrayParameter(int numberOfEntries) {
this(numberOfEntries, 1);
}
public ArrayParameter(int numberOfEntries, int parametersPerEntry) {
this.parametersPerEntry = parametersPerEntry;
this.parameters = new ArrayList<>(numberOfEntries * parametersPerEntry);
}
public ArrayParameter add(Parameter p) {
parameters.add(p);
return this;
}
@Override
public void appendTo(StringBuilder str) {
if (parameters.isEmpty()) return;
// First entry without |
parameters.get(0).appendTo(str);
for (int i = 1; i < parametersPerEntry; ++i) {
str.append(' ');
parameters.get(i).appendTo(str);
}
// Remaining entries separated with |
for (int offset = parametersPerEntry; offset < parameters.size(); offset += parametersPerEntry) {
str.append('|');
parameters.get(offset).appendTo(str);
for (int i = 1; i < parametersPerEntry; ++i) {
str.append(' ');
parameters.get(offset + i).appendTo(str);
}
}
}
}
| 732 |
1,037 | <filename>photup-demo/select_photo_library/src/com/zhaojian/jolly/utils/Utils.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zhaojian.jolly.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.location.Location;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.FloatMath;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.ScaleAnimation;
import com.zhaojian.jolly.constant.Constants;
import com.zhaojian.select_photo_library.R;
public class Utils {
public static Bitmap drawViewOntoBitmap(View view) {
Bitmap image = Bitmap
.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(image);
view.draw(canvas);
return image;
}
public static Animation createScaleAnimation(View view, int parentWidth, int parentHeight,
int toX, int toY) {
// Difference in X and Y
final int diffX = toX - view.getLeft();
final int diffY = toY - view.getTop();
// Calculate actual distance using pythagors
float diffDistance = FloatMath.sqrt((toX * toX) + (toY * toY));
float parentDistance = FloatMath
.sqrt((parentWidth * parentWidth) + (parentHeight * parentHeight));
ScaleAnimation scaleAnimation = new ScaleAnimation(1f, 0f, 1f, 0f, Animation.ABSOLUTE,
diffX,
Animation.ABSOLUTE, diffY);
scaleAnimation.setFillAfter(true);
scaleAnimation.setInterpolator(new DecelerateInterpolator());
scaleAnimation.setDuration(Math.round(diffDistance / parentDistance
* Constants.SCALE_ANIMATION_DURATION_FULL_DISTANCE));
return scaleAnimation;
}
// And to convert the image URI to the direct file system path of the image
// file
public static String getPathFromContentUri(ContentResolver cr, Uri contentUri) {
String returnValue = null;
if (ContentResolver.SCHEME_CONTENT.equals(contentUri.getScheme())) {
// can post image
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = cr.query(contentUri, proj, null, null, null);
if (null != cursor) {
if (cursor.moveToFirst()) {
returnValue = cursor
.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
}
cursor.close();
}
} else if (ContentResolver.SCHEME_FILE.equals(contentUri.getScheme())) {
returnValue = contentUri.getPath();
}
return returnValue;
}
public static int getOrientationFromContentUri(ContentResolver cr, Uri contentUri) {
int returnValue = 0;
if (ContentResolver.SCHEME_CONTENT.equals(contentUri.getScheme())) {
// can post image
String[] proj = {MediaStore.Images.Media.ORIENTATION};
Cursor cursor = cr.query(contentUri, proj, null, null, null);
if (null != cursor) {
if (cursor.moveToFirst()) {
returnValue = cursor.getInt(cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.ORIENTATION));
}
cursor.close();
}
} else if (ContentResolver.SCHEME_FILE.equals(contentUri.getScheme())) {
returnValue = MediaUtils.getExifOrientation(contentUri.getPath());
}
return returnValue;
}
public static Bitmap decodeImage(final ContentResolver resolver, final Uri uri,
final int MAX_DIM)
throws FileNotFoundException {
// Get original dimensions
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(resolver.openInputStream(uri), null, o);
} catch (SecurityException se) {
se.printStackTrace();
return null;
}
final int origWidth = o.outWidth;
final int origHeight = o.outHeight;
// Holds returned bitmap
Bitmap bitmap;
o.inJustDecodeBounds = false;
o.inScaled = false;
o.inPurgeable = true;
o.inInputShareable = true;
o.inDither = true;
o.inPreferredConfig = Bitmap.Config.RGB_565;
if (origWidth > MAX_DIM || origHeight > MAX_DIM) {
int k = 1;
int tmpHeight = origHeight, tmpWidth = origWidth;
while ((tmpWidth / 2) >= MAX_DIM || (tmpHeight / 2) >= MAX_DIM) {
tmpWidth /= 2;
tmpHeight /= 2;
k *= 2;
}
o.inSampleSize = k;
bitmap = BitmapFactory.decodeStream(resolver.openInputStream(uri), null, o);
} else {
bitmap = BitmapFactory.decodeStream(resolver.openInputStream(uri), null, o);
}
if (null != bitmap) {
}
return bitmap;
}
public static boolean hasCamera(Context context) {
PackageManager pm = context.getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)
|| pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT);
}
public static File getCameraPhotoFile() {
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(dir, "photup_" + System.currentTimeMillis() + ".jpg");
}
public static Bitmap rotate(Bitmap original, final int angle) {
if ((angle % 360) == 0) {
return original;
}
final boolean dimensionsChanged = angle == 90 || angle == 270;
final int oldWidth = original.getWidth();
final int oldHeight = original.getHeight();
final int newWidth = dimensionsChanged ? oldHeight : oldWidth;
final int newHeight = dimensionsChanged ? oldWidth : oldHeight;
Bitmap bitmap = Bitmap.createBitmap(newWidth, newHeight, original.getConfig());
Canvas canvas = new Canvas(bitmap);
Matrix matrix = new Matrix();
matrix.preTranslate((newWidth - oldWidth) / 2f, (newHeight - oldHeight) / 2f);
matrix.postRotate(angle, bitmap.getWidth() / 2f, bitmap.getHeight() / 2);
canvas.drawBitmap(original, matrix, null);
original.recycle();
return bitmap;
}
public static boolean newerThan(long compareTime, int threshold) {
return compareTime > (System.currentTimeMillis() - threshold);
}
public static String formatDistance(final int distance) {
if (distance < 1000) {
return distance + "m";
} else {
return String.format("%.2fkm", distance / 1000f);
}
}
public static void scanMediaJpegFile(final Context context, final File file,
final OnScanCompletedListener listener) {
MediaScannerConnection
.scanFile(context, new String[]{file.getAbsolutePath()}, new String[]{"image/jpg"},
listener);
}
public static int getSpinnerItemResId() {
if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
return android.R.layout.simple_spinner_item;
} else {
return R.layout.layout_spinner_item;
}
}
public static Location getExifLocation(String filepath) {
Location location = null;
try {
final ExifInterface exif = new ExifInterface(filepath);
final float[] latLong = new float[2];
if (exif.getLatLong(latLong)) {
location = new Location("");
location.setLatitude(latLong[0]);
location.setLongitude(latLong[1]);
}
} catch (IOException ex) {
ex.printStackTrace();
}
return location;
}
}
| 3,777 |
14,668 | {
"testResult": {
"testPath" : "DummySuite.DummyCase",
"status": "PASS",
"expected": true,
"outputArtifacts":{
"trace/1.json": {
"contentType":"application/json",
"filePath":"FULL_TRACE_FILE_PATH"
}
},
"tags":[
{"key":"tbmv2","value":"renderingMetric"},
{"key":"tbmv2","value":"umaMetric"}
]
}
}
| 179 |
2,542 | {
"Default": {
},
"Tests": [
{
"Name": "FMScale_SP3R_phw(LAB)",
"Type": "V2_DllTest",
"Owners": "lemai",
"Environment": "Iaas",
"ResourcesRequired": "Server:21;Group=Failover-Scale",
"TestExecutionParameters": {
"SetupType": "XCopy",
"SetupTimeout": "3600",
"PerfTestTaskName": "FMScale_SP3R_phw (LAB)",
"ExpectedResultsFileName": "FailoverScalePerfExpectedResults.xml",
"ConfigName": "WinFabricTest\\Config\\Failover_Scale_pHW_IPv6.txt",
"DllPath": "MS.Test.WinFabric.Cases.dll",
"ClassName": "FailoverTestCases",
"TaskName": "FMScale_SP3R",
"InstalledFeaturesFile": "Config\\FailoverScalePHWInstalledFeatures.txt",
"ExecutionTimeout": "64800",
"CleanupType": "XCopy",
"CleanupTimeout": "28800"
}
}
]
}
| 409 |
815 | /***************************************************************************************************
* Copyright 2021 NVIDIA Corporation. All rights reserved.
**************************************************************************************************/
/// \file
/// \brief Bounding box type.
#ifndef MI_NEURAYLIB_IBBOX_H
#define MI_NEURAYLIB_IBBOX_H
#include <mi/math/bbox.h>
#include <mi/neuraylib/icompound.h>
#include <mi/neuraylib/typedefs.h>
namespace mi {
/** \addtogroup mi_neuray_compounds
@{
*/
/// This interface represents bounding boxes.
///
/// It can be used to represent bounding boxes by an interface derived from #mi::base::IInterface.
///
/// \see #mi::Bbox3_struct
class IBbox3 :
public base::Interface_declare<0x107953d0,0x70a0,0x48f5,0xb1,0x17,0x68,0x8e,0x7b,0xf8,0x85,0xa1,
ICompound>
{
public:
/// Returns the bounding box represented by this interface.
virtual Bbox3_struct get_value() const = 0;
/// Returns the bounding box represented by this interface.
virtual void get_value( Bbox3_struct& value) const = 0;
/// Sets the bounding box represented by this interface.
virtual void set_value( const Bbox3_struct& value) = 0;
/// Returns the bounding box represented by this interface.
///
/// This inline method exists for the user's convenience since #mi::math::Bbox
/// is not derived from #mi::math::Bbox_struct.
inline void get_value( Bbox3& value) const {
Bbox3_struct value_struct;
get_value( value_struct);
value = value_struct;
}
/// Sets the bounding box represented by this interface.
///
/// This inline method exists for the user's convenience since #mi::math::Bbox
/// is not derived from #mi::math::Bbox_struct.
inline void set_value( const Bbox3& value) {
Bbox3_struct value_struct = value;
set_value( value_struct);
}
using ICompound::get_value;
using ICompound::set_value;
};
/*@}*/ // end group mi_neuray_compounds
} // namespace mi
#endif // MI_NEURAYLIB_IBBOX_H
| 734 |
679 | <filename>main/reportdesign/source/ui/dlg/Navigator.cxx<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.
*
*************************************************************/
#include "precompiled_rptui.hxx"
#include "Navigator.hxx"
#include "uistrings.hrc"
#include "ReportController.hxx"
#include "UITools.hxx"
#include "RptUndo.hxx"
#include "reportformula.hxx"
#include <com/sun/star/container/XContainerListener.hpp>
#include <com/sun/star/report/XReportDefinition.hpp>
#include <com/sun/star/report/XFixedText.hpp>
#include <com/sun/star/report/XFixedLine.hpp>
#include <com/sun/star/report/XFormattedField.hpp>
#include <com/sun/star/report/XImageControl.hpp>
#include <com/sun/star/report/XShape.hpp>
#include <svx/globlmn.hrc>
#include <svx/svxids.hrc>
#include "helpids.hrc"
#include "RptResId.hrc"
#include "rptui_slotid.hrc"
#include <tools/debug.hxx>
#include <comphelper/propmultiplex.hxx>
#include <comphelper/containermultiplexer.hxx>
#include <comphelper/types.hxx>
#include "cppuhelper/basemutex.hxx"
#include "comphelper/SelectionMultiplex.hxx"
#include <svtools/svtreebx.hxx>
#include <svl/solar.hrc>
#include "ReportVisitor.hxx"
#include "ModuleHelper.hxx"
#include <rtl/ref.hxx>
#include <boost/bind.hpp>
#include <memory>
#include <algorithm>
#define RID_SVXIMG_COLLAPSEDNODE (RID_FORMS_START + 2)
#define RID_SVXIMG_EXPANDEDNODE (RID_FORMS_START + 3)
#define DROP_ACTION_TIMER_INITIAL_TICKS 10
#define DROP_ACTION_TIMER_SCROLL_TICKS 3
#define DROP_ACTION_TIMER_TICK_BASE 10
namespace rptui
{
using namespace ::com::sun::star;
using namespace utl;
using namespace ::comphelper;
sal_uInt16 lcl_getImageId(const uno::Reference< report::XReportComponent>& _xElement)
{
sal_uInt16 nId = 0;
uno::Reference< report::XFixedLine> xFixedLine(_xElement,uno::UNO_QUERY);
if ( uno::Reference< report::XFixedText>(_xElement,uno::UNO_QUERY).is() )
nId = SID_FM_FIXEDTEXT;
else if ( xFixedLine.is() )
nId = xFixedLine->getOrientation() ? SID_INSERT_VFIXEDLINE : SID_INSERT_HFIXEDLINE;
else if ( uno::Reference< report::XFormattedField>(_xElement,uno::UNO_QUERY).is() )
nId = SID_FM_EDIT;
else if ( uno::Reference< report::XImageControl>(_xElement,uno::UNO_QUERY).is() )
nId = SID_FM_IMAGECONTROL;
else if ( uno::Reference< report::XShape>(_xElement,uno::UNO_QUERY).is() )
nId = SID_DRAWTBX_CS_BASIC;
return nId;
}
// -----------------------------------------------------------------------------
::rtl::OUString lcl_getName(const uno::Reference< beans::XPropertySet>& _xElement)
{
OSL_ENSURE(_xElement.is(),"Found report element which is NULL!");
::rtl::OUString sTempName;
_xElement->getPropertyValue(PROPERTY_NAME) >>= sTempName;
::rtl::OUStringBuffer sName = sTempName;
uno::Reference< report::XFixedText> xFixedText(_xElement,uno::UNO_QUERY);
uno::Reference< report::XReportControlModel> xReportModel(_xElement,uno::UNO_QUERY);
if ( xFixedText.is() )
{
sName.append(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" : ")));
sName.append(xFixedText->getLabel());
}
else if ( xReportModel.is() && _xElement->getPropertySetInfo()->hasPropertyByName(PROPERTY_DATAFIELD) )
{
ReportFormula aFormula( xReportModel->getDataField() );
if ( aFormula.isValid() )
{
sName.append(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" : ")));
sName.append( aFormula.getUndecoratedContent() );
}
}
return sName.makeStringAndClear();
}
// -----------------------------------------------------------------------------
class NavigatorTree : public ::cppu::BaseMutex
, public SvTreeListBox
, public reportdesign::ITraverseReport
, public comphelper::OSelectionChangeListener
, public ::comphelper::OPropertyChangeListener
{
class UserData;
friend class UserData;
class UserData : public ::cppu::BaseMutex
,public ::comphelper::OPropertyChangeListener
,public ::comphelper::OContainerListener
{
uno::Reference< uno::XInterface > m_xContent;
::rtl::Reference< comphelper::OPropertyChangeMultiplexer> m_pListener;
::rtl::Reference< comphelper::OContainerListenerAdapter> m_pContainerListener;
NavigatorTree* m_pTree;
public:
UserData(NavigatorTree* _pTree,const uno::Reference<uno::XInterface>& _xContent);
~UserData();
inline uno::Reference< uno::XInterface > getContent() const { return m_xContent; }
inline void setContent(const uno::Reference< uno::XInterface >& _xContent) { m_xContent = _xContent; }
protected:
// OPropertyChangeListener
virtual void _propertyChanged(const beans::PropertyChangeEvent& _rEvent) throw( uno::RuntimeException);
// OContainerListener
virtual void _elementInserted( const container::ContainerEvent& _rEvent ) throw(uno::RuntimeException);
virtual void _elementRemoved( const container::ContainerEvent& _Event ) throw(uno::RuntimeException);
virtual void _elementReplaced( const container::ContainerEvent& _rEvent ) throw(uno::RuntimeException);
virtual void _disposing(const lang::EventObject& _rSource) throw( uno::RuntimeException);
};
enum DROP_ACTION { DA_SCROLLUP, DA_SCROLLDOWN, DA_EXPANDNODE };
AutoTimer m_aDropActionTimer;
Timer m_aSynchronizeTimer;
ImageList m_aNavigatorImages;
ImageList m_aNavigatorImagesHC;
Point m_aTimerTriggered; // die Position, an der der DropTimer angeschaltet wurde
DROP_ACTION m_aDropActionType;
OReportController& m_rController;
SvLBoxEntry* m_pMasterReport;
SvLBoxEntry* m_pDragedEntry;
::rtl::Reference< comphelper::OPropertyChangeMultiplexer> m_pReportListener;
::rtl::Reference< comphelper::OSelectionChangeMultiplexer> m_pSelectionListener;
unsigned short m_nTimerCounter;
SvLBoxEntry* insertEntry(const ::rtl::OUString& _sName,SvLBoxEntry* _pParent,sal_uInt16 _nImageId,sal_uLong _nPosition,UserData* _pData);
void traverseSection(const uno::Reference< report::XSection>& _xSection,SvLBoxEntry* _pParent,sal_uInt16 _nImageId,sal_uLong _nPosition = LIST_APPEND);
void traverseFunctions(const uno::Reference< report::XFunctions>& _xFunctions,SvLBoxEntry* _pParent);
NavigatorTree(const NavigatorTree&);
void operator =(const NavigatorTree&);
protected:
virtual void Command( const CommandEvent& rEvt );
// DragSourceHelper overridables
virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );
// DropTargetHelper overridables
virtual sal_Int8 AcceptDrop( const AcceptDropEvent& _rEvt );
virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& _rEvt );
// OSelectionChangeListener
virtual void _disposing(const lang::EventObject& _rSource) throw( uno::RuntimeException);
// OPropertyChangeListener
virtual void _propertyChanged(const beans::PropertyChangeEvent& _rEvent) throw( uno::RuntimeException);
// OContainerListener Helper
void _elementInserted( const container::ContainerEvent& _rEvent );
void _elementRemoved( const container::ContainerEvent& _Event );
void _elementReplaced( const container::ContainerEvent& _rEvent );
public:
NavigatorTree(Window* pParent,OReportController& _rController );
virtual ~NavigatorTree();
DECL_LINK(OnEntrySelDesel, NavigatorTree*);
DECL_LINK( OnDropActionTimer, void* );
virtual void _selectionChanged( const lang::EventObject& aEvent ) throw (uno::RuntimeException);
// ITraverseReport
virtual void traverseReport(const uno::Reference< report::XReportDefinition>& _xReport);
virtual void traverseReportFunctions(const uno::Reference< report::XFunctions>& _xFunctions);
virtual void traverseReportHeader(const uno::Reference< report::XSection>& _xSection);
virtual void traverseReportFooter(const uno::Reference< report::XSection>& _xSection);
virtual void traversePageHeader(const uno::Reference< report::XSection>& _xSection);
virtual void traversePageFooter(const uno::Reference< report::XSection>& _xSection);
virtual void traverseGroups(const uno::Reference< report::XGroups>& _xGroups);
virtual void traverseGroup(const uno::Reference< report::XGroup>& _xGroup);
virtual void traverseGroupFunctions(const uno::Reference< report::XFunctions>& _xFunctions);
virtual void traverseGroupHeader(const uno::Reference< report::XSection>& _xSection);
virtual void traverseGroupFooter(const uno::Reference< report::XSection>& _xSection);
virtual void traverseDetail(const uno::Reference< report::XSection>& _xSection);
SvLBoxEntry* find(const uno::Reference< uno::XInterface >& _xContent);
void removeEntry(SvLBoxEntry* _pEntry,bool _bRemove = true);
private:
using SvTreeListBox::ExecuteDrop;
};
DBG_NAME(rpt_NavigatorTree)
// -----------------------------------------------------------------------------
NavigatorTree::NavigatorTree( Window* pParent,OReportController& _rController )
:SvTreeListBox( pParent, WB_TABSTOP| WB_HASBUTTONS|WB_HASLINES|WB_BORDER|WB_HSCROLL|WB_HASBUTTONSATROOT )
,comphelper::OSelectionChangeListener(m_aMutex)
,OPropertyChangeListener(m_aMutex)
,m_aTimerTriggered(-1,-1)
,m_aDropActionType( DA_SCROLLUP )
,m_rController(_rController)
,m_pMasterReport(NULL)
,m_pDragedEntry(NULL)
,m_nTimerCounter( DROP_ACTION_TIMER_INITIAL_TICKS )
{
DBG_CTOR(rpt_NavigatorTree,NULL);
m_pReportListener = new OPropertyChangeMultiplexer(this,m_rController.getReportDefinition().get());
m_pReportListener->addProperty(PROPERTY_PAGEHEADERON);
m_pReportListener->addProperty(PROPERTY_PAGEFOOTERON);
m_pReportListener->addProperty(PROPERTY_REPORTHEADERON);
m_pReportListener->addProperty(PROPERTY_REPORTFOOTERON);
m_pSelectionListener = new OSelectionChangeMultiplexer(this,&m_rController);
SetHelpId( HID_REPORT_NAVIGATOR_TREE );
m_aNavigatorImages = ImageList( ModuleRes( RID_SVXIMGLIST_RPTEXPL ) );
m_aNavigatorImagesHC = ImageList( ModuleRes( RID_SVXIMGLIST_RPTEXPL_HC ) );
SetNodeBitmaps(
m_aNavigatorImages.GetImage( RID_SVXIMG_COLLAPSEDNODE ),
m_aNavigatorImages.GetImage( RID_SVXIMG_EXPANDEDNODE ),
BMP_COLOR_NORMAL
);
SetNodeBitmaps(
m_aNavigatorImagesHC.GetImage( RID_SVXIMG_COLLAPSEDNODE ),
m_aNavigatorImagesHC.GetImage( RID_SVXIMG_EXPANDEDNODE ),
BMP_COLOR_HIGHCONTRAST
);
SetDragDropMode(0xFFFF);
EnableInplaceEditing( sal_False );
SetSelectionMode(MULTIPLE_SELECTION);
Clear();
m_aDropActionTimer.SetTimeoutHdl(LINK(this, NavigatorTree, OnDropActionTimer));
SetSelectHdl(LINK(this, NavigatorTree, OnEntrySelDesel));
SetDeselectHdl(LINK(this, NavigatorTree, OnEntrySelDesel));
}
// -----------------------------------------------------------------------------
NavigatorTree::~NavigatorTree()
{
SvLBoxEntry* pCurrent = First();
while ( pCurrent )
{
delete static_cast<UserData*>(pCurrent->GetUserData());
pCurrent = Next(pCurrent);
}
m_pReportListener->dispose();
m_pSelectionListener->dispose();
DBG_DTOR(rpt_NavigatorTree,NULL);
}
//------------------------------------------------------------------------------
void NavigatorTree::Command( const CommandEvent& rEvt )
{
sal_Bool bHandled = sal_False;
switch( rEvt.GetCommand() )
{
case COMMAND_CONTEXTMENU:
{
// die Stelle, an der geklickt wurde
SvLBoxEntry* ptClickedOn = NULL;
::Point aWhere;
if (rEvt.IsMouseEvent())
{
aWhere = rEvt.GetMousePosPixel();
ptClickedOn = GetEntry(aWhere);
if (ptClickedOn == NULL)
break;
if ( !IsSelected(ptClickedOn) )
{
SelectAll(sal_False);
Select(ptClickedOn, sal_True);
SetCurEntry(ptClickedOn);
}
}
else
{
ptClickedOn = GetCurEntry();
if ( !ptClickedOn )
break;
aWhere = GetEntryPosition(ptClickedOn);
}
UserData* pData = static_cast<UserData*>(ptClickedOn->GetUserData());
uno::Reference< report::XFunctionsSupplier> xSupplier(pData->getContent(),uno::UNO_QUERY);
uno::Reference< report::XFunctions> xFunctions(pData->getContent(),uno::UNO_QUERY);
uno::Reference< report::XGroup> xGroup(pData->getContent(),uno::UNO_QUERY);
sal_Bool bDeleteAllowed = m_rController.isEditable() && (xGroup.is() ||
uno::Reference< report::XFunction>(pData->getContent(),uno::UNO_QUERY).is());
PopupMenu aContextMenu( ModuleRes( RID_MENU_NAVIGATOR ) );
sal_uInt16 nCount = aContextMenu.GetItemCount();
for (sal_uInt16 i = 0; i < nCount; ++i)
{
if ( MENUITEM_SEPARATOR != aContextMenu.GetItemType(i))
{
sal_uInt16 nId = aContextMenu.GetItemId(i);
aContextMenu.CheckItem(nId,m_rController.isCommandChecked(nId));
sal_Bool bEnabled = m_rController.isCommandEnabled(nId);
if ( nId == SID_RPT_NEW_FUNCTION )
aContextMenu.EnableItem(nId,m_rController.isEditable() && (xSupplier.is() || xFunctions.is()) );
// special condition, check for function and group
else if ( nId == SID_DELETE )
aContextMenu.EnableItem(SID_DELETE,bDeleteAllowed);
else
aContextMenu.EnableItem(nId,bEnabled);
}
} // for (sal_uInt16 i = 0; i < nCount; ++i)
sal_uInt16 nId = aContextMenu.Execute(this, aWhere);
if ( nId )
{
uno::Sequence< beans::PropertyValue> aArgs;
if ( nId == SID_RPT_NEW_FUNCTION )
{
aArgs.realloc(1);
aArgs[0].Value <<= (xFunctions.is() ? xFunctions : xSupplier->getFunctions());
}
else if ( nId == SID_DELETE )
{
if ( xGroup.is() )
nId = SID_GROUP_REMOVE;
aArgs.realloc(1);
aArgs[0].Name = PROPERTY_GROUP;
aArgs[0].Value <<= pData->getContent();
}
m_rController.executeUnChecked(nId,aArgs);
}
bHandled = sal_True;
} break;
}
if (!bHandled)
SvTreeListBox::Command( rEvt );
}
// -----------------------------------------------------------------------------
sal_Int8 NavigatorTree::AcceptDrop( const AcceptDropEvent& _rEvt )
{
sal_Int8 nDropOption = DND_ACTION_NONE;
::Point aDropPos = _rEvt.maPosPixel;
if (_rEvt.mbLeaving)
{
if (m_aDropActionTimer.IsActive())
m_aDropActionTimer.Stop();
}
else
{
bool bNeedTrigger = false;
// auf dem ersten Eintrag ?
if ((aDropPos.Y() >= 0) && (aDropPos.Y() < GetEntryHeight()))
{
m_aDropActionType = DA_SCROLLUP;
bNeedTrigger = true;
}
else if ((aDropPos.Y() < GetSizePixel().Height()) && (aDropPos.Y() >= GetSizePixel().Height() - GetEntryHeight()))
{
m_aDropActionType = DA_SCROLLDOWN;
bNeedTrigger = true;
}
else
{
SvLBoxEntry* pDropppedOn = GetEntry(aDropPos);
if (pDropppedOn && (GetChildCount(pDropppedOn) > 0) && !IsExpanded(pDropppedOn))
{
m_aDropActionType = DA_EXPANDNODE;
bNeedTrigger = true;
}
}
if (bNeedTrigger && (m_aTimerTriggered != aDropPos))
{
// neu anfangen zu zaehlen
m_nTimerCounter = DROP_ACTION_TIMER_INITIAL_TICKS;
// die Pos merken, da ich auch AcceptDrops bekomme, wenn sich die Maus gar nicht bewegt hat
m_aTimerTriggered = aDropPos;
// und den Timer los
if (!m_aDropActionTimer.IsActive()) // gibt es den Timer schon ?
{
m_aDropActionTimer.SetTimeout(DROP_ACTION_TIMER_TICK_BASE);
m_aDropActionTimer.Start();
}
}
else if (!bNeedTrigger)
m_aDropActionTimer.Stop();
}
return nDropOption;
}
// -------------------------------------------------------------------------
sal_Int8 NavigatorTree::ExecuteDrop( const ExecuteDropEvent& /*_rEvt*/ )
{
// _rEvt.mnAction;
return DND_ACTION_NONE;
}
// -------------------------------------------------------------------------
void NavigatorTree::StartDrag( sal_Int8 /*_nAction*/, const Point& _rPosPixel )
{
m_pDragedEntry = GetEntry(_rPosPixel);
if ( m_pDragedEntry )
{
EndSelection();
}
}
//------------------------------------------------------------------------
IMPL_LINK( NavigatorTree, OnDropActionTimer, void*, EMPTYARG )
{
if (--m_nTimerCounter > 0)
return 0L;
switch ( m_aDropActionType )
{
case DA_EXPANDNODE:
{
SvLBoxEntry* pToExpand = GetEntry(m_aTimerTriggered);
if (pToExpand && (GetChildCount(pToExpand) > 0) && !IsExpanded(pToExpand))
// tja, eigentlich muesste ich noch testen, ob die Node nicht schon expandiert ist, aber ich
// habe dazu weder in den Basisklassen noch im Model eine Methode gefunden ...
// aber ich denke, die BK sollte es auch so vertragen
Expand(pToExpand);
// nach dem Expand habe ich im Gegensatz zum Scrollen natuerlich nix mehr zu tun
m_aDropActionTimer.Stop();
}
break;
case DA_SCROLLUP :
ScrollOutputArea( 1 );
m_nTimerCounter = DROP_ACTION_TIMER_SCROLL_TICKS;
break;
case DA_SCROLLDOWN :
ScrollOutputArea( -1 );
m_nTimerCounter = DROP_ACTION_TIMER_SCROLL_TICKS;
break;
}
return 0L;
}
// -----------------------------------------------------------------------------
IMPL_LINK(NavigatorTree, OnEntrySelDesel, NavigatorTree*, /*pThis*/)
{
if ( !m_pSelectionListener->locked() )
{
m_pSelectionListener->lock();
SvLBoxEntry* pEntry = GetCurEntry();
uno::Any aSelection;
if ( IsSelected(pEntry) )
aSelection <<= static_cast<UserData*>(pEntry->GetUserData())->getContent();
m_rController.select(aSelection);
m_pSelectionListener->unlock();
}
return 0L;
}
// -----------------------------------------------------------------------------
void NavigatorTree::_selectionChanged( const lang::EventObject& aEvent ) throw (uno::RuntimeException)
{
m_pSelectionListener->lock();
uno::Reference< view::XSelectionSupplier> xSelectionSupplier(aEvent.Source,uno::UNO_QUERY);
uno::Any aSec = xSelectionSupplier->getSelection();
uno::Sequence< uno::Reference< report::XReportComponent > > aSelection;
aSec >>= aSelection;
if ( !aSelection.getLength() )
{
uno::Reference< uno::XInterface> xSelection(aSec,uno::UNO_QUERY);
SvLBoxEntry* pEntry = find(xSelection);
if ( pEntry && !IsSelected(pEntry) )
{
Select(pEntry, sal_True);
SetCurEntry(pEntry);
}
else if ( !pEntry )
SelectAll(sal_False,sal_False);
}
else
{
const uno::Reference< report::XReportComponent >* pIter = aSelection.getConstArray();
const uno::Reference< report::XReportComponent >* pEnd = pIter + aSelection.getLength();
for (; pIter != pEnd; ++pIter)
{
SvLBoxEntry* pEntry = find(*pIter);
if ( pEntry && !IsSelected(pEntry) )
{
Select(pEntry, sal_True);
SetCurEntry(pEntry);
}
}
}
m_pSelectionListener->unlock();
}
// -----------------------------------------------------------------------------
SvLBoxEntry* NavigatorTree::insertEntry(const ::rtl::OUString& _sName,SvLBoxEntry* _pParent,sal_uInt16 _nImageId,sal_uLong _nPosition,UserData* _pData)
{
SvLBoxEntry* pEntry = NULL;
if ( _nImageId )
{
const Image aImage( m_aNavigatorImages.GetImage( _nImageId ) );
pEntry = InsertEntry(_sName,aImage,aImage,_pParent,sal_False,_nPosition,_pData);
if ( pEntry )
{
const Image aImageHC( m_aNavigatorImagesHC.GetImage( _nImageId ) );
SetExpandedEntryBmp( pEntry, aImageHC, BMP_COLOR_HIGHCONTRAST );
SetCollapsedEntryBmp( pEntry, aImageHC, BMP_COLOR_HIGHCONTRAST );
}
}
else
pEntry = InsertEntry(_sName,_pParent,sal_False,_nPosition,_pData);
return pEntry;
}
// -----------------------------------------------------------------------------
void NavigatorTree::traverseSection(const uno::Reference< report::XSection>& _xSection,SvLBoxEntry* _pParent,sal_uInt16 _nImageId,sal_uLong _nPosition)
{
SvLBoxEntry* pSection = insertEntry(_xSection->getName(),_pParent,_nImageId,_nPosition,new UserData(this,_xSection));
const sal_Int32 nCount = _xSection->getCount();
for (sal_Int32 i = 0; i < nCount; ++i)
{
uno::Reference< report::XReportComponent> xElement(_xSection->getByIndex(i),uno::UNO_QUERY_THROW);
OSL_ENSURE(xElement.is(),"Found report element which is NULL!");
insertEntry(lcl_getName(xElement.get()),pSection,lcl_getImageId(xElement),LIST_APPEND,new UserData(this,xElement));
uno::Reference< report::XReportDefinition> xSubReport(xElement,uno::UNO_QUERY);
if ( xSubReport.is() )
{
m_pMasterReport = find(_xSection->getReportDefinition());
reportdesign::OReportVisitor aSubVisitor(this);
aSubVisitor.start(xSubReport);
}
}
}
// -----------------------------------------------------------------------------
void NavigatorTree::traverseFunctions(const uno::Reference< report::XFunctions>& _xFunctions,SvLBoxEntry* _pParent)
{
SvLBoxEntry* pFunctions = insertEntry(String(ModuleRes(RID_STR_FUNCTIONS)),_pParent,SID_RPT_NEW_FUNCTION,LIST_APPEND,new UserData(this,_xFunctions));
const sal_Int32 nCount = _xFunctions->getCount();
for (sal_Int32 i = 0; i< nCount; ++i)
{
uno::Reference< report::XFunction> xElement(_xFunctions->getByIndex(i),uno::UNO_QUERY);
insertEntry(xElement->getName(),pFunctions,SID_RPT_NEW_FUNCTION,LIST_APPEND,new UserData(this,xElement));
}
}
// -----------------------------------------------------------------------------
SvLBoxEntry* NavigatorTree::find(const uno::Reference< uno::XInterface >& _xContent)
{
SvLBoxEntry* pRet = NULL;
if ( _xContent.is() )
{
SvLBoxEntry* pCurrent = First();
while ( pCurrent )
{
UserData* pData = static_cast<UserData*>(pCurrent->GetUserData());
OSL_ENSURE(pData,"No UserData set an entry!");
if ( pData->getContent() == _xContent )
{
pRet = pCurrent;
break;
}
pCurrent = Next(pCurrent);
}
}
return pRet;
}
// -----------------------------------------------------------------------------
// ITraverseReport
// -----------------------------------------------------------------------------
void NavigatorTree::traverseReport(const uno::Reference< report::XReportDefinition>& _xReport)
{
insertEntry(_xReport->getName(),m_pMasterReport,SID_SELECT_REPORT,LIST_APPEND,new UserData(this,_xReport));
}
// -----------------------------------------------------------------------------
void NavigatorTree::traverseReportFunctions(const uno::Reference< report::XFunctions>& _xFunctions)
{
SvLBoxEntry* pReport = find(_xFunctions->getParent());
traverseFunctions(_xFunctions,pReport);
}
// -----------------------------------------------------------------------------
void NavigatorTree::traverseReportHeader(const uno::Reference< report::XSection>& _xSection)
{
SvLBoxEntry* pReport = find(_xSection->getReportDefinition());
traverseSection(_xSection,pReport,SID_REPORTHEADERFOOTER);
}
// -----------------------------------------------------------------------------
void NavigatorTree::traverseReportFooter(const uno::Reference< report::XSection>& _xSection)
{
SvLBoxEntry* pReport = find(_xSection->getReportDefinition());
traverseSection(_xSection,pReport,SID_REPORTHEADERFOOTER);
}
// -----------------------------------------------------------------------------
void NavigatorTree::traversePageHeader(const uno::Reference< report::XSection>& _xSection)
{
SvLBoxEntry* pReport = find(_xSection->getReportDefinition());
traverseSection(_xSection,pReport,SID_PAGEHEADERFOOTER);
}
// -----------------------------------------------------------------------------
void NavigatorTree::traversePageFooter(const uno::Reference< report::XSection>& _xSection)
{
SvLBoxEntry* pReport = find(_xSection->getReportDefinition());
traverseSection(_xSection,pReport,SID_PAGEHEADERFOOTER);
}
// -----------------------------------------------------------------------------
void NavigatorTree::traverseGroups(const uno::Reference< report::XGroups>& _xGroups)
{
SvLBoxEntry* pReport = find(_xGroups->getReportDefinition());
insertEntry(String(ModuleRes(RID_STR_GROUPS)),pReport,SID_SORTINGANDGROUPING,LIST_APPEND,new UserData(this,_xGroups));
}
// -----------------------------------------------------------------------------
void NavigatorTree::traverseGroup(const uno::Reference< report::XGroup>& _xGroup)
{
uno::Reference< report::XGroups> xGroups(_xGroup->getParent(),uno::UNO_QUERY);
SvLBoxEntry* pGroups = find(xGroups);
OSL_ENSURE(pGroups,"No Groups inserted so far. Why!");
insertEntry(_xGroup->getExpression(),pGroups,SID_GROUP,rptui::getPositionInIndexAccess(xGroups.get(),_xGroup),new UserData(this,_xGroup));
}
// -----------------------------------------------------------------------------
void NavigatorTree::traverseGroupFunctions(const uno::Reference< report::XFunctions>& _xFunctions)
{
SvLBoxEntry* pGroup = find(_xFunctions->getParent());
traverseFunctions(_xFunctions,pGroup);
}
// -----------------------------------------------------------------------------
void NavigatorTree::traverseGroupHeader(const uno::Reference< report::XSection>& _xSection)
{
SvLBoxEntry* pGroup = find(_xSection->getGroup());
OSL_ENSURE(pGroup,"No group found");
traverseSection(_xSection,pGroup,SID_GROUPHEADER,1);
}
// -----------------------------------------------------------------------------
void NavigatorTree::traverseGroupFooter(const uno::Reference< report::XSection>& _xSection)
{
SvLBoxEntry* pGroup = find(_xSection->getGroup());
OSL_ENSURE(pGroup,"No group found");
traverseSection(_xSection,pGroup,SID_GROUPFOOTER);
}
// -----------------------------------------------------------------------------
void NavigatorTree::traverseDetail(const uno::Reference< report::XSection>& _xSection)
{
uno::Reference< report::XReportDefinition> xReport = _xSection->getReportDefinition();
SvLBoxEntry* pParent = find(xReport);
traverseSection(_xSection,pParent,SID_ICON_DETAIL);
}
// -----------------------------------------------------------------------------
void NavigatorTree::_propertyChanged(const beans::PropertyChangeEvent& _rEvent) throw( uno::RuntimeException)
{
uno::Reference< report::XReportDefinition> xReport(_rEvent.Source,uno::UNO_QUERY);
if ( xReport.is() )
{
sal_Bool bEnabled = sal_False;
_rEvent.NewValue >>= bEnabled;
if ( bEnabled )
{
SvLBoxEntry* pParent = find(xReport);
if ( _rEvent.PropertyName == PROPERTY_REPORTHEADERON )
{
sal_uLong nPos = xReport->getReportHeaderOn() ? 2 : 1;
traverseSection(xReport->getReportHeader(),pParent,SID_REPORTHEADERFOOTER,nPos);
}
else if ( _rEvent.PropertyName == PROPERTY_PAGEHEADERON )
{
traverseSection(xReport->getPageHeader(),pParent, SID_PAGEHEADERFOOTER,1);
}
else if ( _rEvent.PropertyName == PROPERTY_PAGEFOOTERON )
traverseSection(xReport->getPageFooter(),pParent, SID_PAGEHEADERFOOTER);
else if ( _rEvent.PropertyName == PROPERTY_REPORTFOOTERON )
{
sal_uLong nPos = xReport->getPageFooterOn() ? (GetLevelChildCount(pParent) - 1) : LIST_APPEND;
traverseSection(xReport->getReportFooter(),pParent,SID_REPORTHEADERFOOTER,nPos);
}
}
}
}
// -----------------------------------------------------------------------------
void NavigatorTree::_elementInserted( const container::ContainerEvent& _rEvent )
{
SvLBoxEntry* pEntry = find(_rEvent.Source);
uno::Reference<beans::XPropertySet> xProp(_rEvent.Element,uno::UNO_QUERY_THROW);
::rtl::OUString sName;
uno::Reference< beans::XPropertySetInfo> xInfo = xProp->getPropertySetInfo();
if ( xInfo.is() )
{
if ( xInfo->hasPropertyByName(PROPERTY_NAME) )
xProp->getPropertyValue(PROPERTY_NAME) >>= sName;
else if ( xInfo->hasPropertyByName(PROPERTY_EXPRESSION) )
xProp->getPropertyValue(PROPERTY_EXPRESSION) >>= sName;
}
uno::Reference< report::XGroup> xGroup(xProp,uno::UNO_QUERY);
if ( xGroup.is() )
{
reportdesign::OReportVisitor aSubVisitor(this);
aSubVisitor.start(xGroup);
}
else
{
uno::Reference< report::XReportComponent> xElement(xProp,uno::UNO_QUERY);
if ( xProp.is() )
sName = lcl_getName(xProp);
insertEntry(sName,pEntry,(!xElement.is() ? sal_uInt16(SID_RPT_NEW_FUNCTION) : lcl_getImageId(xElement)),LIST_APPEND,new UserData(this,xProp));
}
if ( !IsExpanded(pEntry) )
Expand(pEntry);
}
// -----------------------------------------------------------------------------
void NavigatorTree::_elementRemoved( const container::ContainerEvent& _rEvent )
{
uno::Reference<beans::XPropertySet> xProp(_rEvent.Element,uno::UNO_QUERY);
SvLBoxEntry* pEntry = find(xProp);
OSL_ENSURE(pEntry,"NavigatorTree::_elementRemoved: No Entry found!");
if ( pEntry )
{
SvLBoxEntry* pParent = GetParent(pEntry);
removeEntry(pEntry);
PaintEntry(pParent);
}
}
// -----------------------------------------------------------------------------
void NavigatorTree::_elementReplaced( const container::ContainerEvent& _rEvent )
{
uno::Reference<beans::XPropertySet> xProp(_rEvent.ReplacedElement,uno::UNO_QUERY);
SvLBoxEntry* pEntry = find(xProp);
if ( pEntry )
{
UserData* pData = static_cast<UserData*>(pEntry->GetUserData());
xProp.set(_rEvent.Element,uno::UNO_QUERY);
pData->setContent(xProp);
::rtl::OUString sName;
xProp->getPropertyValue(PROPERTY_NAME) >>= sName;
SetEntryText(pEntry,sName);
}
}
// -----------------------------------------------------------------------------
void NavigatorTree::_disposing(const lang::EventObject& _rSource)throw( uno::RuntimeException)
{
removeEntry(find(_rSource.Source));
}
// -----------------------------------------------------------------------------
void NavigatorTree::removeEntry(SvLBoxEntry* _pEntry,bool _bRemove)
{
if ( _pEntry )
{
SvLBoxEntry* pChild = FirstChild(_pEntry);
while( pChild )
{
removeEntry(pChild,false);
pChild = NextSibling(pChild);
}
delete static_cast<UserData*>(_pEntry->GetUserData());
if ( _bRemove )
GetModel()->Remove(_pEntry);
}
}
DBG_NAME(rpt_NavigatorTree_UserData)
// -----------------------------------------------------------------------------
NavigatorTree::UserData::UserData(NavigatorTree* _pTree,const uno::Reference<uno::XInterface>& _xContent)
: OPropertyChangeListener(m_aMutex)
, OContainerListener(m_aMutex)
, m_xContent(_xContent)
, m_pTree(_pTree)
{
DBG_CTOR(rpt_NavigatorTree_UserData,NULL);
uno::Reference<beans::XPropertySet> xProp(m_xContent,uno::UNO_QUERY);
if ( xProp.is() )
{
uno::Reference< beans::XPropertySetInfo> xInfo = xProp->getPropertySetInfo();
if ( xInfo.is() )
{
m_pListener = new ::comphelper::OPropertyChangeMultiplexer(this,xProp);
if ( xInfo->hasPropertyByName(PROPERTY_NAME) )
m_pListener->addProperty(PROPERTY_NAME);
else if ( xInfo->hasPropertyByName(PROPERTY_EXPRESSION) )
m_pListener->addProperty(PROPERTY_EXPRESSION);
if ( xInfo->hasPropertyByName(PROPERTY_DATAFIELD) )
m_pListener->addProperty(PROPERTY_DATAFIELD);
if ( xInfo->hasPropertyByName(PROPERTY_LABEL) )
m_pListener->addProperty(PROPERTY_LABEL);
if ( xInfo->hasPropertyByName(PROPERTY_HEADERON) )
m_pListener->addProperty(PROPERTY_HEADERON);
if ( xInfo->hasPropertyByName(PROPERTY_FOOTERON) )
m_pListener->addProperty(PROPERTY_FOOTERON);
}
}
uno::Reference< container::XContainer> xContainer(m_xContent,uno::UNO_QUERY);
if ( xContainer.is() )
{
m_pContainerListener = new ::comphelper::OContainerListenerAdapter(this,xContainer);
}
}
// -----------------------------------------------------------------------------
NavigatorTree::UserData::~UserData()
{
DBG_DTOR(rpt_NavigatorTree_UserData,NULL);
if ( m_pContainerListener.is() )
m_pContainerListener->dispose();
if ( m_pListener.is() )
m_pListener->dispose();
}
// -----------------------------------------------------------------------------
// OPropertyChangeListener
void NavigatorTree::UserData::_propertyChanged(const beans::PropertyChangeEvent& _rEvent) throw( uno::RuntimeException)
{
SvLBoxEntry* pEntry = m_pTree->find(_rEvent.Source);
OSL_ENSURE(pEntry,"No entry could be found! Why not!");
const bool bFooterOn = (PROPERTY_FOOTERON == _rEvent.PropertyName);
try
{
if ( bFooterOn || PROPERTY_HEADERON == _rEvent.PropertyName )
{
sal_Int32 nPos = 1;
uno::Reference< report::XGroup> xGroup(_rEvent.Source,uno::UNO_QUERY);
::std::mem_fun_t< sal_Bool,OGroupHelper> pIsOn = ::std::mem_fun(&OGroupHelper::getHeaderOn);
::std::mem_fun_t< uno::Reference<report::XSection> ,OGroupHelper> pMemFunSection = ::std::mem_fun(&OGroupHelper::getHeader);
if ( bFooterOn )
{
pIsOn = ::std::mem_fun(&OGroupHelper::getFooterOn);
pMemFunSection = ::std::mem_fun(&OGroupHelper::getFooter);
nPos = m_pTree->GetChildCount(pEntry) - 1;
}
OGroupHelper aGroupHelper(xGroup);
if ( pIsOn(&aGroupHelper) )
{
if ( bFooterOn )
++nPos;
m_pTree->traverseSection(pMemFunSection(&aGroupHelper),pEntry,bFooterOn ? SID_GROUPFOOTER : SID_GROUPHEADER,nPos);
}
//else
// m_pTree->removeEntry(m_pTree->GetEntry(pEntry,nPos));
}
else if ( PROPERTY_EXPRESSION == _rEvent.PropertyName)
{
::rtl::OUString sNewName;
_rEvent.NewValue >>= sNewName;
m_pTree->SetEntryText(pEntry,sNewName);
}
else if ( PROPERTY_DATAFIELD == _rEvent.PropertyName || PROPERTY_LABEL == _rEvent.PropertyName || PROPERTY_NAME == _rEvent.PropertyName )
{
uno::Reference<beans::XPropertySet> xProp(_rEvent.Source,uno::UNO_QUERY);
m_pTree->SetEntryText(pEntry,lcl_getName(xProp));
}
}
catch(uno::Exception)
{}
}
// -----------------------------------------------------------------------------
void NavigatorTree::UserData::_elementInserted( const container::ContainerEvent& _rEvent ) throw(uno::RuntimeException)
{
m_pTree->_elementInserted( _rEvent );
}
// -----------------------------------------------------------------------------
void NavigatorTree::UserData::_elementRemoved( const container::ContainerEvent& _rEvent ) throw(uno::RuntimeException)
{
m_pTree->_elementRemoved( _rEvent );
}
// -----------------------------------------------------------------------------
void NavigatorTree::UserData::_elementReplaced( const container::ContainerEvent& _rEvent ) throw(uno::RuntimeException)
{
m_pTree->_elementReplaced( _rEvent );
}
// -----------------------------------------------------------------------------
void NavigatorTree::UserData::_disposing(const lang::EventObject& _rSource) throw( uno::RuntimeException)
{
m_pTree->_disposing( _rSource );
}
// -----------------------------------------------------------------------------
// class ONavigatorImpl
// -----------------------------------------------------------------------------
class ONavigatorImpl
{
ONavigatorImpl(const ONavigatorImpl&);
void operator =(const ONavigatorImpl&);
public:
ONavigatorImpl(OReportController& _rController,ONavigator* _pParent);
virtual ~ONavigatorImpl();
uno::Reference< report::XReportDefinition> m_xReport;
::rptui::OReportController& m_rController;
::std::auto_ptr<NavigatorTree> m_pNavigatorTree;
};
ONavigatorImpl::ONavigatorImpl(OReportController& _rController,ONavigator* _pParent)
:m_xReport(_rController.getReportDefinition())
,m_rController(_rController)
,m_pNavigatorTree(new NavigatorTree(_pParent,_rController))
{
reportdesign::OReportVisitor aVisitor(m_pNavigatorTree.get());
aVisitor.start(m_xReport);
m_pNavigatorTree->Expand(m_pNavigatorTree->find(m_xReport));
lang::EventObject aEvent(m_rController);
m_pNavigatorTree->_selectionChanged(aEvent);
}
//------------------------------------------------------------------------
ONavigatorImpl::~ONavigatorImpl()
{
}
// -----------------------------------------------------------------------------
DBG_NAME( rpt_ONavigator )
const long STD_WIN_SIZE_X = 210;
const long STD_WIN_SIZE_Y = 280;
const long LISTBOX_BORDER = 2;
//========================================================================
// class ONavigator
//========================================================================
ONavigator::ONavigator( Window* _pParent
,OReportController& _rController)
: FloatingWindow( _pParent, ModuleRes(RID_NAVIGATOR) )
{
DBG_CTOR( rpt_ONavigator,NULL);
m_pImpl.reset(new ONavigatorImpl(_rController,this));
//Size aSpace = LogicToPixel( Size( 7, 120), MAP_APPFONT );
//Size aOutSize(nMaxTextWidth + m_aHeader.GetSizePixel().Width() + 3*aSpace.Width(),aSpace.Height());
//SetMinOutputSizePixel(aOutSize);
//SetOutputSizePixel(aOutSize);
FreeResource();
m_pImpl->m_pNavigatorTree->Show();
m_pImpl->m_pNavigatorTree->GrabFocus();
SetSizePixel(Size(STD_WIN_SIZE_X,STD_WIN_SIZE_Y));
Show();
}
// -----------------------------------------------------------------------------
//------------------------------------------------------------------------
ONavigator::~ONavigator()
{
DBG_DTOR( rpt_ONavigator,NULL);
}
//------------------------------------------------------------------------------
void ONavigator::Resize()
{
FloatingWindow::Resize();
Point aPos(GetPosPixel());
Size aSize( GetOutputSizePixel() );
//////////////////////////////////////////////////////////////////////
// Groesse der form::ListBox anpassen
Point aLBPos( LISTBOX_BORDER, LISTBOX_BORDER );
Size aLBSize( aSize );
aLBSize.Width() -= (2*LISTBOX_BORDER);
aLBSize.Height() -= (2*LISTBOX_BORDER);
m_pImpl->m_pNavigatorTree->SetPosSizePixel( aLBPos, aLBSize );
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ONavigator::GetFocus()
{
Window::GetFocus();
if ( m_pImpl->m_pNavigatorTree.get() )
m_pImpl->m_pNavigatorTree->GrabFocus();
}
// =============================================================================
} // rptui
// =============================================================================
| 16,323 |
3,442 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.java.sip.communicator.plugin.notificationconfiguration;
import java.io.*;
import net.java.sip.communicator.plugin.desktoputil.*;
import org.jitsi.util.*;
/**
* Filter to display only the sound files in the filechooser.
*
* @author <NAME>
* @author <NAME>
*/
public class SoundFilter
extends SipCommFileFilter
{
/**
* All acceptable sound formats. If null, then this sound filter will accept
* all sound formats available in SoundFileUtils.
*/
private String[] soundFormats = null;
/**
* Creates a new sound filter which accepts all sound format available in
* SoundFileUtils.
*/
public SoundFilter()
{
super();
}
/**
* Creates a new sound filter which accepts only sound format corresponding
* to the list given in parameter.
*
* @param soundFormats The list of sound format to accept.
*/
public SoundFilter(String[] soundFormats)
{
super();
if(soundFormats != null)
{
this.soundFormats = new String[soundFormats.length];
System.arraycopy(
soundFormats,
0,
this.soundFormats,
0,
soundFormats.length);
}
}
/**
* Method which describes differents permits extensions and defines which
* file or directory will be displayed in the filechoser.
*
* @param f file for the test
*
* @return boolean true if the File is a Directory or a sound file. And
* return false in the other cases.
*/
@Override
public boolean accept(File f)
{
// Tests if the file passed in argument is a directory.
if (f.isDirectory())
{
return true;
}
// Else, tests if the exension is correct.
else
{
return SoundFileUtils.isSoundFile(f, this.soundFormats);
}
}
/**
* Method which describes, in the file chooser, the text representing the
* permit extension files.
*
* @return String which is displayed in the sound file chooser.
*/
@Override
public String getDescription()
{
String desc = "Sound File (";
if(this.soundFormats != null)
{
for(int i = 0; i < this.soundFormats.length; ++i)
{
if(i != 0)
{
desc += ", ";
}
desc += "*." + this.soundFormats[i];
}
}
else
{
desc += "*.au, *.mid, *.mod, *.mp2, *.mp3, *.ogg, *.ram, *.wav, "
+ "*.wma";
}
desc += ")";
return desc;
}
}
| 1,421 |
32,544 | package com.baeldung.blockchain;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class BlockchainUnitTest {
public static List<Block> blockchain = new ArrayList<Block>();
public static int prefix = 4;
public static String prefixString = new String(new char[prefix]).replace('\0', '0');
@BeforeClass
public static void setUp() {
Block genesisBlock = new Block("The is the Genesis Block.", "0", new Date().getTime());
genesisBlock.mineBlock(prefix);
blockchain.add(genesisBlock);
Block firstBlock = new Block("The is the First Block.", genesisBlock.getHash(), new Date().getTime());
firstBlock.mineBlock(prefix);
blockchain.add(firstBlock);
}
@Test
public void givenBlockchain_whenNewBlockAdded_thenSuccess() {
Block newBlock = new Block("The is a New Block.", blockchain.get(blockchain.size() - 1)
.getHash(), new Date().getTime());
newBlock.mineBlock(prefix);
assertTrue(newBlock.getHash()
.substring(0, prefix)
.equals(prefixString));
blockchain.add(newBlock);
}
@Test
public void givenBlockchain_whenValidated_thenSuccess() {
boolean flag = true;
for (int i = 0; i < blockchain.size(); i++) {
String previousHash = i == 0 ? "0"
: blockchain.get(i - 1)
.getHash();
flag = blockchain.get(i)
.getHash()
.equals(blockchain.get(i)
.calculateBlockHash())
&& previousHash.equals(blockchain.get(i)
.getPreviousHash())
&& blockchain.get(i)
.getHash()
.substring(0, prefix)
.equals(prefixString);
if (!flag)
break;
}
assertTrue(flag);
}
@AfterClass
public static void tearDown() {
blockchain.clear();
}
}
| 957 |
371 | /**
* 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.bigtop.datagenerators.bigpetstore.generators.purchase;
import java.util.Map;
import org.apache.bigtop.datagenerators.bigpetstore.datamodels.Product;
import org.apache.bigtop.datagenerators.samplers.SeedFactory;
import org.apache.bigtop.datagenerators.samplers.pdfs.MultinomialPDF;
import org.apache.bigtop.datagenerators.samplers.samplers.RouletteWheelSampler;
import org.apache.bigtop.datagenerators.samplers.samplers.Sampler;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
public class MultinomialPurchasingModel implements PurchasingModel<MultinomialPDF<Product>>
{
private static final long serialVersionUID = 5863830733003282570L;
private final ImmutableMap<String, MultinomialPDF<Product>> productPDFs;
public MultinomialPurchasingModel(Map<String, MultinomialPDF<Product>> productPDFs)
{
this.productPDFs = ImmutableMap.copyOf(productPDFs);
}
@Override
public ImmutableSet<String> getProductCategories()
{
return productPDFs.keySet();
}
@Override
public MultinomialPDF<Product> getProfile(String category)
{
return productPDFs.get(category);
}
@Override
public PurchasingProcesses buildProcesses(SeedFactory seedFactory)
{
Map<String, Sampler<Product>> processes = Maps.newHashMap();
for(String category : getProductCategories())
{
MultinomialPDF<Product> pdf = productPDFs.get(category);
processes.put(category, RouletteWheelSampler.create(pdf, seedFactory));
}
return new PurchasingProcesses(processes);
}
}
| 709 |
782 | // Copyright (c) 2018 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
/*
//
// Purpose:
// DCT + quantization+level shift and
// range convert functions (Inverse transform)
//
// Contents:
// mfxiDCTQuantInv8x8LS_JPEG_16s16u_C1R
//
*/
#include "precomp.h"
#ifndef __OWNJ_H__
#include "ownj.h"
#endif
#include "ps_anarith.h"
#if (_IPP >= _IPP_W7) || (_IPP32E >= _IPP32E_M7)
#include <emmintrin.h>
extern void mfxdct_8x8_inv_32f(Ipp32f* x, Ipp32f* y);
static const __ALIGN16 Ipp32f fLS[4] = { 2048., 2048., 2048., 2048. };
static const __ALIGN16 Ipp16u iST[8] = { 4095, 4095, 4095, 4095, 4095, 4095, 4095, 4095 };
extern void mfxdct_qnt_inv_8x8_ls(
const Ipp16s* pSrc,
Ipp16u* pDst,
int dstStep,
const Ipp32f* pQntInvTbl)
{
// int i;
__ALIGN16 __m128 _fS0, _fS1, _fS2;
__ALIGN16 __m128i _iS0, _iS1, _iS2, _iST, _iZR;
__ALIGN16 Ipp32f wb[64];
__ALIGN16 Ipp32f wb2[64]; /* 665 clocks with second buf (690 with only one) */
if(!((intptr_t)pQntInvTbl & 15) && !((intptr_t)pSrc & 15))
{
_iS0 = _mm_load_si128((__m128i*)(pSrc + 0));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_load_ps(pQntInvTbl);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_load_ps(pQntInvTbl + 4);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 0, _fS1);
_mm_store_ps(wb + 4, _fS0);
_iS0 = _mm_load_si128((__m128i*)(pSrc + 8));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_load_ps(pQntInvTbl + 8);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_load_ps(pQntInvTbl + 12);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 8, _fS1);
_mm_store_ps(wb + 12, _fS0);
_iS0 = _mm_load_si128((__m128i*)(pSrc + 16));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_load_ps(pQntInvTbl + 16);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_load_ps(pQntInvTbl + 20);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 16, _fS1);
_mm_store_ps(wb + 20, _fS0);
_iS0 = _mm_load_si128((__m128i*)(pSrc + 24));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_load_ps(pQntInvTbl + 24);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_load_ps(pQntInvTbl + 28);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 24, _fS1);
_mm_store_ps(wb + 28, _fS0);
_iS0 = _mm_load_si128((__m128i*)(pSrc + 32));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_load_ps(pQntInvTbl + 32);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_load_ps(pQntInvTbl + 36);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 32, _fS1);
_mm_store_ps(wb + 36, _fS0);
_iS0 = _mm_load_si128((__m128i*)(pSrc + 40));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_load_ps(pQntInvTbl + 40);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_load_ps(pQntInvTbl + 44);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 40, _fS1);
_mm_store_ps(wb + 44, _fS0);
_iS0 = _mm_load_si128((__m128i*)(pSrc + 48));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_load_ps(pQntInvTbl + 48);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_load_ps(pQntInvTbl + 52);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 48, _fS1);
_mm_store_ps(wb + 52, _fS0);
_iS0 = _mm_load_si128((__m128i*)(pSrc + 56));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_load_ps(pQntInvTbl + 56);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_load_ps(pQntInvTbl + 60);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 56, _fS1);
_mm_store_ps(wb + 60, _fS0);
}
else
{
_iS0 = _mm_loadu_si128((__m128i*)(pSrc + 0));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_loadu_ps(pQntInvTbl);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_loadu_ps(pQntInvTbl + 4);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 0, _fS1);
_mm_store_ps(wb + 4, _fS0);
_iS0 = _mm_loadu_si128((__m128i*)(pSrc + 8));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_loadu_ps(pQntInvTbl + 8);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_loadu_ps(pQntInvTbl + 12);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 8, _fS1);
_mm_store_ps(wb + 12, _fS0);
_iS0 = _mm_loadu_si128((__m128i*)(pSrc + 16));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_loadu_ps(pQntInvTbl + 16);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_loadu_ps(pQntInvTbl + 20);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 16, _fS1);
_mm_store_ps(wb + 20, _fS0);
_iS0 = _mm_loadu_si128((__m128i*)(pSrc + 24));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_loadu_ps(pQntInvTbl + 24);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_loadu_ps(pQntInvTbl + 28);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 24, _fS1);
_mm_store_ps(wb + 28, _fS0);
_iS0 = _mm_loadu_si128((__m128i*)(pSrc + 32));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_loadu_ps(pQntInvTbl + 32);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_loadu_ps(pQntInvTbl + 36);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 32, _fS1);
_mm_store_ps(wb + 36, _fS0);
_iS0 = _mm_loadu_si128((__m128i*)(pSrc + 40));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_loadu_ps(pQntInvTbl + 40);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_loadu_ps(pQntInvTbl + 44);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 40, _fS1);
_mm_store_ps(wb + 44, _fS0);
_iS0 = _mm_loadu_si128((__m128i*)(pSrc + 48));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_loadu_ps(pQntInvTbl + 48);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_loadu_ps(pQntInvTbl + 52);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 48, _fS1);
_mm_store_ps(wb + 52, _fS0);
_iS0 = _mm_loadu_si128((__m128i*)(pSrc + 56));
_iS1 = _mm_srai_epi16(_iS0, 15);
_iS2 = _mm_unpacklo_epi16(_iS0, _iS1);
_iS0 = _mm_unpackhi_epi16(_iS0, _iS1);
_fS1 = _mm_cvtepi32_ps(_iS2);
_fS0 = _mm_cvtepi32_ps(_iS0);
_fS2 = _mm_loadu_ps(pQntInvTbl + 56);
_fS1 = _mm_mul_ps(_fS1, _fS2);
_fS2 = _mm_loadu_ps(pQntInvTbl + 60);
_fS0 = _mm_mul_ps(_fS0, _fS2);
_mm_store_ps(wb + 56, _fS1);
_mm_store_ps(wb + 60, _fS0);
}
mfxdct_8x8_inv_32f(wb, wb2);
_iZR = _mm_setzero_si128();
_iST = _mm_load_si128((__m128i*)iST);
_fS2 = _mm_load_ps(fLS);
_fS0 = _mm_load_ps(wb2 + 0);
_fS0 = _mm_add_ps(_fS0, _fS2);
_fS1 = _mm_load_ps(wb2 + 4);
_fS1 = _mm_add_ps(_fS1, _fS2);
_iS0 = _mm_cvttps_epi32(_fS0);
_iS1 = _mm_cvttps_epi32(_fS1);
_iS0 = _mm_packs_epi32(_iS0,_iS1);
// saturate to 0...4095
_iS0 = _mm_max_epi16(_iS0,_iZR);
_iS0 = _mm_min_epi16(_iS0,_iST);
_mm_storeu_si128((__m128i*)((Ipp8u*)pDst + 0*dstStep), _iS0);
_fS0 = _mm_load_ps(wb2 + 8);
_fS0 = _mm_add_ps(_fS0, _fS2);
_fS1 = _mm_load_ps(wb2 + 12);
_fS1 = _mm_add_ps(_fS1, _fS2);
_iS0 = _mm_cvttps_epi32(_fS0);
_iS1 = _mm_cvttps_epi32(_fS1);
_iS0 = _mm_packs_epi32(_iS0, _iS1);
// saturate to 0...4095
_iS0 = _mm_max_epi16(_iS0,_iZR);
_iS0 = _mm_min_epi16(_iS0,_iST);
_mm_storeu_si128((__m128i*)((Ipp8u*)pDst + 1*dstStep), _iS0);
_fS0 = _mm_load_ps(wb2 + 16);
_fS0 = _mm_add_ps(_fS0, _fS2);
_fS1 = _mm_load_ps(wb2 + 20);
_fS1 = _mm_add_ps(_fS1, _fS2);
_iS0 = _mm_cvttps_epi32(_fS0);
_iS1 = _mm_cvttps_epi32(_fS1);
_iS0 = _mm_packs_epi32(_iS0, _iS1);
// saturate to 0...4095
_iS0 = _mm_max_epi16(_iS0,_iZR);
_iS0 = _mm_min_epi16(_iS0,_iST);
_mm_storeu_si128((__m128i*)((Ipp8u*)pDst + 2*dstStep), _iS0);
_fS0 = _mm_load_ps(wb2 + 24);
_fS0 = _mm_add_ps(_fS0, _fS2);
_fS1 = _mm_load_ps(wb2 + 28);
_fS1 = _mm_add_ps(_fS1, _fS2);
_iS0 = _mm_cvttps_epi32(_fS0);
_iS1 = _mm_cvttps_epi32(_fS1);
_iS0 = _mm_packs_epi32(_iS0, _iS1);
// saturate to 0...4095
_iS0 = _mm_max_epi16(_iS0,_iZR);
_iS0 = _mm_min_epi16(_iS0,_iST);
_mm_storeu_si128((__m128i*)((Ipp8u*)pDst + 3*dstStep), _iS0);
_fS0 = _mm_load_ps(wb2 + 32);
_fS0 = _mm_add_ps(_fS0, _fS2);
_fS1 = _mm_load_ps(wb2 + 36);
_fS1 = _mm_add_ps(_fS1, _fS2);
_iS0 = _mm_cvttps_epi32(_fS0);
_iS1 = _mm_cvttps_epi32(_fS1);
_iS0 = _mm_packs_epi32(_iS0, _iS1);
// saturate to 0...4095
_iS0 = _mm_max_epi16(_iS0,_iZR);
_iS0 = _mm_min_epi16(_iS0,_iST);
_mm_storeu_si128((__m128i*)((Ipp8u*)pDst + 4*dstStep), _iS0);
_fS0 = _mm_load_ps(wb2 + 40);
_fS0 = _mm_add_ps(_fS0, _fS2);
_fS1 = _mm_load_ps(wb2 + 44);
_fS1 = _mm_add_ps(_fS1, _fS2);
_iS0 = _mm_cvttps_epi32(_fS0);
_iS1 = _mm_cvttps_epi32(_fS1);
_iS0 = _mm_packs_epi32(_iS0, _iS1);
// saturate to 0...4095
_iS0 = _mm_max_epi16(_iS0,_iZR);
_iS0 = _mm_min_epi16(_iS0,_iST);
_mm_storeu_si128((__m128i*)((Ipp8u*)pDst + 5*dstStep), _iS0);
_fS0 = _mm_load_ps(wb2 + 48);
_fS0 = _mm_add_ps(_fS0, _fS2);
_fS1 = _mm_load_ps(wb2 + 52);
_fS1 = _mm_add_ps(_fS1, _fS2);
_iS0 = _mm_cvttps_epi32(_fS0);
_iS1 = _mm_cvttps_epi32(_fS1);
_iS0 = _mm_packs_epi32(_iS0, _iS1);
// saturate to 0...4095
_iS0 = _mm_max_epi16(_iS0,_iZR);
_iS0 = _mm_min_epi16(_iS0,_iST);
_mm_storeu_si128((__m128i*)((Ipp8u*)pDst + 6*dstStep), _iS0);
_fS0 = _mm_load_ps(wb2 + 56);
_fS0 = _mm_add_ps(_fS0, _fS2);
_fS1 = _mm_load_ps(wb2 + 60);
_fS1 = _mm_add_ps(_fS1, _fS2);
_iS0 = _mm_cvttps_epi32(_fS0);
_iS1 = _mm_cvttps_epi32(_fS1);
_iS0 = _mm_packs_epi32(_iS0, _iS1);
// saturate to 0...4095
_iS0 = _mm_max_epi16(_iS0,_iZR);
_iS0 = _mm_min_epi16(_iS0,_iST);
_mm_storeu_si128((__m128i*)((Ipp8u*)pDst + 7*dstStep), _iS0);
return;
} /* mfxdct_qnt_fwd_8x8_ls() */
#endif
| 7,777 |
3,282 | <reponame>1060680253/AndroidChromium<filename>app/src/main/java/org/chromium/chrome/browser/signin/AccountSigninView.java
// 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.
package org.chromium.chrome.browser.signin;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.Callback;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.externalauth.ExternalAuthUtils;
import org.chromium.chrome.browser.externalauth.UserRecoverableErrorHandler;
import org.chromium.chrome.browser.firstrun.ProfileDataCache;
import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.chrome.browser.profiles.ProfileDownloader;
import org.chromium.chrome.browser.signin.AccountTrackerService.OnSystemAccountsSeededListener;
import org.chromium.chrome.browser.signin.ConfirmImportSyncDataDialog.ImportSyncType;
import org.chromium.components.signin.AccountManagerHelper;
import org.chromium.ui.text.NoUnderlineClickableSpan;
import org.chromium.ui.text.SpanApplier;
import org.chromium.ui.text.SpanApplier.SpanInfo;
import org.chromium.ui.widget.ButtonCompat;
import java.util.List;
// TODO(gogerald): refactor common part into one place after redesign all sign in screens.
/**
* This view allows the user to select an account to log in to, add an account,
* cancel account selection, etc. Users of this class should
* {@link AccountSigninView#setListener(Listener)} and
* {@link AccountSigninView#setDelegate(Delegate)} after the view has been inflated.
*/
public class AccountSigninView extends FrameLayout implements ProfileDownloader.Observer {
/**
* Callbacks for various account selection events.
*/
public interface Listener {
/**
* The user canceled account selection.
*/
public void onAccountSelectionCanceled();
/**
* The user wants to make a new account.
*/
public void onNewAccount();
/**
* The user completed the View and selected an account.
* @param accountName The name of the account
* @param settingsClicked If true, user requested to see their sync settings, if false
* they just clicked Done.
*/
public void onAccountSelected(String accountName, boolean settingsClicked);
/**
* Failed to set the forced account because it wasn't found.
* @param forcedAccountName The name of the forced-sign-in account
*/
public void onFailedToSetForcedAccount(String forcedAccountName);
}
// TODO(peconn): Investigate expanding the Delegate to simplify the Listener implementations.
/**
* Provides UI objects for new UI component creation.
*/
public interface Delegate {
/**
* Provides an Activity for the View to check GMSCore version.
*/
public Activity getActivity();
/**
* Provides a FragmentManager for the View to create dialogs. This is done through a
* different mechanism than getActivity().getFragmentManager() as a potential fix to
* https://crbug.com/646978 on the theory that getActivity() and getFragmentManager()
* return null at different times.
*/
public FragmentManager getFragmentManager();
}
private static final String TAG = "AccountSigninView";
private static final String SETTINGS_LINK_OPEN = "<LINK1>";
private static final String SETTINGS_LINK_CLOSE = "</LINK1>";
private AccountManagerHelper mAccountManagerHelper;
private List<String> mAccountNames;
private AccountSigninChooseView mSigninChooseView;
private ButtonCompat mPositiveButton;
private Button mNegativeButton;
private Button mMoreButton;
private Listener mListener;
private Delegate mDelegate;
private String mForcedAccountName;
private ProfileDataCache mProfileData;
private boolean mSignedIn;
private int mCancelButtonTextId;
private boolean mIsChildAccount;
private boolean mIsGooglePlayServicesOutOfDate;
private UserRecoverableErrorHandler.ModalDialog mGooglePlayServicesUpdateErrorHandler;
private AccountSigninConfirmationView mSigninConfirmationView;
private ImageView mSigninAccountImage;
private TextView mSigninAccountName;
private TextView mSigninAccountEmail;
private TextView mSigninSettingsControl;
public AccountSigninView(Context context, AttributeSet attrs) {
super(context, attrs);
mAccountManagerHelper = AccountManagerHelper.get(getContext().getApplicationContext());
}
/**
* Initializes this view with profile data cache, delegate and listener.
* @param profileData ProfileDataCache that will be used to call to retrieve user account info.
* @param delegate The UI object creation delegate.
* @param listener The account selection event listener.
*/
public void init(ProfileDataCache profileData, Delegate delegate, Listener listener) {
mProfileData = profileData;
mProfileData.setObserver(this);
mDelegate = delegate;
mListener = listener;
showSigninPage();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mSigninChooseView = (AccountSigninChooseView) findViewById(R.id.account_signin_choose_view);
mSigninChooseView.setAddNewAccountObserver(new AccountSigninChooseView.Observer() {
@Override
public void onAddNewAccount() {
mListener.onNewAccount();
RecordUserAction.record("Signin_AddAccountToDevice");
}
});
mPositiveButton = (ButtonCompat) findViewById(R.id.positive_button);
mNegativeButton = (Button) findViewById(R.id.negative_button);
mMoreButton = (Button) findViewById(R.id.more_button);
// A workaround for Android support library ignoring padding set in XML. b/20307607
int padding = getResources().getDimensionPixelSize(R.dimen.fre_button_padding);
ApiCompatibilityUtils.setPaddingRelative(mPositiveButton, padding, 0, padding, 0);
ApiCompatibilityUtils.setPaddingRelative(mNegativeButton, padding, 0, padding, 0);
// TODO(peconn): Ensure this is changed to R.string.cancel when used in Settings > Sign In.
mCancelButtonTextId = R.string.no_thanks;
mSigninConfirmationView =
(AccountSigninConfirmationView) findViewById(R.id.signin_confirmation_view);
mSigninConfirmationView.setScrolledToBottomObserver(
new AccountSigninConfirmationView.Observer() {
@Override
public void onScrolledToBottom() {
setUpMoreButtonVisible(false);
}
});
mSigninAccountImage = (ImageView) findViewById(R.id.signin_account_image);
mSigninAccountName = (TextView) findViewById(R.id.signin_account_name);
mSigninAccountEmail = (TextView) findViewById(R.id.signin_account_email);
mSigninSettingsControl = (TextView) findViewById(R.id.signin_settings_control);
// For the spans to be clickable.
mSigninSettingsControl.setMovementMethod(LinkMovementMethod.getInstance());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
updateAccounts();
}
@Override
public void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
if (visibility == View.VISIBLE) {
updateAccounts();
return;
}
if (visibility == View.INVISIBLE && mGooglePlayServicesUpdateErrorHandler != null) {
mGooglePlayServicesUpdateErrorHandler.cancelDialog();
}
}
/**
* Changes the visuals slightly for when this view appears in the recent tabs page instead of
* in first run.
* This is currently used when signing in from the Recent Tabs or Bookmarks pages.
*/
public void configureForRecentTabsOrBookmarksPage() {
mCancelButtonTextId = R.string.cancel;
setUpCancelButton();
}
/**
* Enable or disable UI elements so the user can't select an account, cancel, etc.
*
* @param enabled The state to change to.
*/
public void setButtonsEnabled(boolean enabled) {
mPositiveButton.setEnabled(enabled);
mNegativeButton.setEnabled(enabled);
}
/**
* Refresh the list of available system accounts asynchronously. This is a convenience method
* that will ignore whether the accounts updating was actually successful.
*/
private void updateAccounts() {
updateAccounts(new Callback<Boolean>() {
@Override
public void onResult(Boolean result) {}
});
}
/**
* Refresh the list of available system accounts asynchronously.
*
* @param callback Called once the accounts have been refreshed. Boolean indicates whether the
* accounts haven been successfully updated.
*/
private void updateAccounts(final Callback<Boolean> callback) {
if (mSignedIn || mProfileData == null) {
callback.onResult(false);
return;
}
if (!checkGooglePlayServicesAvailable()) {
setUpSigninButton(false);
callback.onResult(false);
return;
}
final List<String> oldAccountNames = mAccountNames;
final AlertDialog updatingGmsDialog;
if (mIsGooglePlayServicesOutOfDate) {
updatingGmsDialog = new AlertDialog.Builder(getContext())
.setCancelable(false)
.setView(R.layout.updating_gms_progress_view)
.create();
updatingGmsDialog.show();
} else {
updatingGmsDialog = null;
}
mAccountManagerHelper.getGoogleAccountNames(new Callback<List<String>>() {
@Override
public void onResult(List<String> result) {
if (updatingGmsDialog != null) {
updatingGmsDialog.dismiss();
}
mIsGooglePlayServicesOutOfDate = false;
if (mSignedIn) {
// If sign-in completed in the mean time, return in order to avoid showing the
// wrong state in the UI.
return;
}
mAccountNames = result;
int accountToSelect = 0;
if (isInForcedAccountMode()) {
accountToSelect = mAccountNames.indexOf(mForcedAccountName);
if (accountToSelect < 0) {
mListener.onFailedToSetForcedAccount(mForcedAccountName);
callback.onResult(false);
return;
}
} else {
accountToSelect = getIndexOfNewElement(
oldAccountNames, mAccountNames,
mSigninChooseView.getSelectedAccountPosition());
}
int oldSelectedAccount = mSigninChooseView.getSelectedAccountPosition();
mSigninChooseView.updateAccounts(mAccountNames, accountToSelect, mProfileData);
if (mAccountNames.isEmpty()) {
setUpSigninButton(false);
callback.onResult(true);
return;
}
setUpSigninButton(true);
mProfileData.update();
// Determine how the accounts have changed. Each list should only have unique
// elements.
if (oldAccountNames == null || oldAccountNames.isEmpty()) {
callback.onResult(true);
return;
}
if (!mAccountNames.get(accountToSelect).equals(
oldAccountNames.get(oldSelectedAccount))) {
// Any dialogs that may have been showing are now invalid (they were created
// for the previously selected account).
ConfirmSyncDataStateMachine
.cancelAllDialogs(mDelegate.getFragmentManager());
if (mAccountNames.containsAll(oldAccountNames)) {
// A new account has been added and no accounts have been deleted. We
// will have changed the account selection to the newly added account, so
// shortcut to the confirm signin page.
showConfirmSigninPageAccountTrackerServiceCheck();
}
}
callback.onResult(true);
}
});
}
private boolean checkGooglePlayServicesAvailable() {
ExternalAuthUtils extAuthUtils = ExternalAuthUtils.getInstance();
if (mGooglePlayServicesUpdateErrorHandler == null) {
mGooglePlayServicesUpdateErrorHandler = new UserRecoverableErrorHandler.ModalDialog(
mDelegate.getActivity());
}
int resultCode = extAuthUtils.canUseGooglePlayServicesResultCode(
getContext(), mGooglePlayServicesUpdateErrorHandler);
if (extAuthUtils.isGooglePlayServicesUpdateRequiredError(resultCode)) {
mIsGooglePlayServicesOutOfDate = true;
}
return resultCode == ConnectionResult.SUCCESS;
}
/**
* Attempt to select a new element that is in the new list, but not in the old list.
* If no such element exist and both the new and the old lists are the same then keep
* the selection. Otherwise select the first element.
* @param oldList Old list of user accounts.
* @param newList New list of user accounts.
* @param oldIndex Index of the selected account in the old list.
* @return The index of the new element, if it does not exist but lists are the same the
* return the old index, otherwise return 0.
*/
private static int getIndexOfNewElement(
List<String> oldList, List<String> newList, int oldIndex) {
if (oldList == null || newList == null) return 0;
if (oldList.size() == newList.size() && oldList.containsAll(newList)) return oldIndex;
if (oldList.size() + 1 == newList.size()) {
for (int i = 0; i < newList.size(); i++) {
if (!oldList.contains(newList.get(i))) return i;
}
}
return 0;
}
@Override
public void onProfileDownloaded(String accountId, String fullName, String givenName,
Bitmap bitmap) {
mSigninChooseView.updateAccountProfileImages(mProfileData);
if (mSignedIn) updateSignedInAccountInfo();
}
private void updateSignedInAccountInfo() {
String selectedAccountEmail = getSelectedAccountName();
mSigninAccountImage.setImageBitmap(mProfileData.getImage(selectedAccountEmail));
String name = null;
if (mIsChildAccount) name = mProfileData.getGivenName(selectedAccountEmail);
if (name == null) name = mProfileData.getFullName(selectedAccountEmail);
if (name == null) name = selectedAccountEmail;
String text = String.format(getResources().getString(R.string.signin_hi_name), name);
mSigninAccountName.setText(text);
mSigninAccountEmail.setText(selectedAccountEmail);
}
/**
* Updates the view to show that sign in has completed.
* This should only be used if the user is not currently signed in (eg on the First
* Run Experience).
*/
public void switchToSignedMode() {
// TODO(peconn): Add a warning here
showConfirmSigninPage();
}
private void showSigninPage() {
mSignedIn = false;
mSigninConfirmationView.setVisibility(View.GONE);
mSigninChooseView.setVisibility(View.VISIBLE);
setUpCancelButton();
updateAccounts();
}
private void showConfirmSigninPage() {
mSignedIn = true;
updateSignedInAccountInfo();
mSigninChooseView.setVisibility(View.GONE);
mSigninConfirmationView.setVisibility(View.VISIBLE);
setButtonsEnabled(true);
setUpConfirmButton();
setUpUndoButton();
NoUnderlineClickableSpan settingsSpan = new NoUnderlineClickableSpan() {
@Override
public void onClick(View widget) {
mListener.onAccountSelected(getSelectedAccountName(), true);
RecordUserAction.record("Signin_Signin_WithAdvancedSyncSettings");
}
};
mSigninSettingsControl.setText(
SpanApplier.applySpans(getSettingsControlDescription(mIsChildAccount),
new SpanInfo(SETTINGS_LINK_OPEN, SETTINGS_LINK_CLOSE, settingsSpan)));
}
private void showConfirmSigninPageAccountTrackerServiceCheck() {
// Disable the buttons to prevent them being clicked again while waiting for the callbacks.
setButtonsEnabled(false);
// Ensure that the AccountTrackerService has a fully up to date GAIA id <-> email mapping,
// as this is needed for the previous account check.
if (AccountTrackerService.get(getContext()).checkAndSeedSystemAccounts()) {
showConfirmSigninPagePreviousAccountCheck();
} else {
AccountTrackerService.get(getContext()).addSystemAccountsSeededListener(
new OnSystemAccountsSeededListener() {
@Override
public void onSystemAccountsSeedingComplete() {
AccountTrackerService.get(getContext())
.removeSystemAccountsSeededListener(this);
showConfirmSigninPagePreviousAccountCheck();
}
@Override
public void onSystemAccountsChanged() {}
});
}
}
private void showConfirmSigninPagePreviousAccountCheck() {
String accountName = getSelectedAccountName();
ConfirmSyncDataStateMachine.run(PrefServiceBridge.getInstance().getSyncLastAccountName(),
accountName, ImportSyncType.PREVIOUS_DATA_FOUND,
mDelegate.getFragmentManager(),
getContext(), new ConfirmImportSyncDataDialog.Listener() {
@Override
public void onConfirm(boolean wipeData) {
SigninManager.wipeSyncUserDataIfRequired(wipeData)
.then(new Callback<Void>() {
@Override
public void onResult(Void v) {
showConfirmSigninPage();
}
});
}
@Override
public void onCancel() {
setButtonsEnabled(true);
}
});
}
private void setUpCancelButton() {
setNegativeButtonVisible(true);
mNegativeButton.setText(getResources().getText(mCancelButtonTextId));
mNegativeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setButtonsEnabled(false);
mListener.onAccountSelectionCanceled();
}
});
}
private void setUpSigninButton(boolean hasAccounts) {
if (hasAccounts) {
mPositiveButton.setText(R.string.continue_sign_in);
mPositiveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showConfirmSigninPageAccountTrackerServiceCheck();
}
});
} else {
mPositiveButton.setText(R.string.choose_account_sign_in);
mPositiveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!checkGooglePlayServicesAvailable()) {
return;
}
RecordUserAction.record("Signin_AddAccountToDevice");
mListener.onNewAccount();
}
});
}
setUpMoreButtonVisible(false);
}
private void setUpUndoButton() {
setNegativeButtonVisible(!isInForcedAccountMode());
if (isInForcedAccountMode()) return;
mNegativeButton.setText(getResources().getText(R.string.undo));
mNegativeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
RecordUserAction.record("Signin_Undo_Signin");
showSigninPage();
}
});
}
private void setUpConfirmButton() {
mPositiveButton.setText(getResources().getText(R.string.signin_accept));
mPositiveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mListener.onAccountSelected(getSelectedAccountName(), false);
RecordUserAction.record("Signin_Signin_WithDefaultSyncSettings");
}
});
setUpMoreButtonVisible(true);
}
/*
* mMoreButton is used to scroll mSigninConfirmationView down. It displays at the same position
* as mPositiveButton.
*/
private void setUpMoreButtonVisible(boolean enabled) {
if (enabled) {
mPositiveButton.setVisibility(View.GONE);
mMoreButton.setVisibility(View.VISIBLE);
mMoreButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mSigninConfirmationView.smoothScrollBy(0, mSigninConfirmationView.getHeight());
RecordUserAction.record("Signin_MoreButton_Shown");
}
});
} else {
mPositiveButton.setVisibility(View.VISIBLE);
mMoreButton.setVisibility(View.GONE);
}
}
private void setNegativeButtonVisible(boolean enabled) {
if (enabled) {
mNegativeButton.setVisibility(View.VISIBLE);
findViewById(R.id.positive_button_end_padding).setVisibility(View.GONE);
} else {
mNegativeButton.setVisibility(View.GONE);
findViewById(R.id.positive_button_end_padding).setVisibility(View.INVISIBLE);
}
}
private String getSettingsControlDescription(boolean childAccount) {
if (childAccount) {
return getResources().getString(R.string.signin_signed_in_settings_description) + '\n'
+ getResources().getString(R.string.signin_signed_in_description_uca_addendum);
} else {
return getResources().getString(R.string.signin_signed_in_settings_description);
}
}
/**
* @param isChildAccount Whether this view is for a child account.
*/
public void setIsChildAccount(boolean isChildAccount) {
mIsChildAccount = isChildAccount;
}
/**
* Switches the view to "no choice, just a confirmation" forced-account mode.
* @param forcedAccountName An account that should be force-selected.
*/
public void switchToForcedAccountMode(String forcedAccountName) {
mForcedAccountName = forcedAccountName;
updateAccounts(new Callback<Boolean>() {
@Override
public void onResult(Boolean result) {
if (!result) return;
assert TextUtils.equals(getSelectedAccountName(), mForcedAccountName);
switchToSignedMode();
assert TextUtils.equals(getSelectedAccountName(), mForcedAccountName);
}
});
}
/**
* @return Whether the view is in signed in mode.
*/
public boolean isSignedIn() {
return mSignedIn;
}
/**
* @return Whether the view is in "no choice, just a confirmation" forced-account mode.
*/
public boolean isInForcedAccountMode() {
return mForcedAccountName != null;
}
private String getSelectedAccountName() {
return mAccountNames.get(mSigninChooseView.getSelectedAccountPosition());
}
}
| 10,583 |
21,793 | <gh_stars>1000+
{
"URL": "https://echo.hoppscotch.io",
"HOST": "echo.hoppscotch.io",
"X-COUNTRY": "IN",
"BODY_VALUE": "body_value",
"BODY_KEY": "body_key"
}
| 85 |
438 | {
"DESCRIPTION": "˙ɹǝsn ɐ uɐq",
"USAGE": "ban <ɹǝsn> [uosɐǝɹ] [ǝɯᴉʇ]",
"TITLE": "pƎNN∀q",
"MISSING_USER": "I can't punish someone not in this server.",
"TOO_POWERFUL": "˙ɹǝʍod ɹᴉǝɥʇ oʇ ǝnp ɹǝsn sᴉɥʇ uɐq oʇ ǝlqɐun ɯɐ I",
"DESC": "˙{{NAME}} ɯoɹɟ pǝuuɐq uǝǝq ǝʌɐɥ no⅄",
"BAN_BY": ":ʎq pǝuuɐq",
"SUCCESS": "˙*pǝuuɐq ʎllnɟssǝɔɔns sɐʍ <@{{USER}}>*"
}
| 286 |
492 | <filename>torngas/logger/__init__.py<gh_stars>100-1000
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.handlers
from tornado.log import LogFormatter
from loggers import ProcessLogTimedFileHandler
from client import SysLogger, syslogger
def enable_pretty_logging(options=None, logger=None):
if options is None:
from tornado.options import options
if options.logging is None or options.logging.lower() == 'none':
return
if logger is None:
logger = logging.getLogger()
logger.setLevel(getattr(logging, options.logging.upper()))
if options.log_file_prefix:
rotate_mode = options.log_rotate_mode
if rotate_mode == 'size':
channel = logging.handlers.RotatingFileHandler(
filename=options.log_file_prefix,
maxBytes=options.log_file_max_size,
backupCount=options.log_file_num_backups)
elif rotate_mode == 'time':
channel = logging.handlers.TimedRotatingFileHandler(
filename=options.log_file_prefix,
when=options.log_rotate_when,
interval=options.log_rotate_interval,
backupCount=options.log_file_num_backups)
else:
error_message = 'The value of log_rotate_mode option should be ' + \
'"size" or "time", not "%s".' % rotate_mode
raise ValueError(error_message)
channel.setFormatter(LogFormatter(color=False))
logger.addHandler(channel)
if (options.log_to_stderr or
(options.log_to_stderr is None and not logger.handlers)):
# Set up color if we are in a tty and curses is installed
channel = logging.StreamHandler()
channel.setFormatter(LogFormatter())
logger.addHandler(channel)
| 785 |
1,323 | //
// GJCFImageBrowserViewControllerDelegate.h
// GJCommonFoundation
//
// Created by ZYVincent QQ:1003081775 on 14-10-30.
// Copyright (c) 2014年 ZYProSoft. All rights reserved.
//
#import <Foundation/Foundation.h>
@class GJCUImageBrowserViewController;
@protocol GJCUImageBrowserViewControllerDataSource <NSObject>
/**
* 设定自定义工具栏
*
* @param browserController
*
* @return
*/
- (UIView *)imageBrowserShouldCustomBottomToolBar:(GJCUImageBrowserViewController *)browserController;
/**
* 设定自定义导航栏右上角
*
* @param browserController
*
* @return
*/
- (UIView *)imageBrowserShouldCustomRightNavigationBarItem:(GJCUImageBrowserViewController *)browserController;
/**
* 设定自定义导航条背景
*
* @param browserController
*
* @return
*/
- (UIImage *)imageBrowserShouldCustomNavigationBar:(GJCUImageBrowserViewController *)browserController;
/**
* 将要消失
*
* @param browserController
*/
- (void)imageBrowserWillCancel:(GJCUImageBrowserViewController *)browserController;
/**
* 删除完显示指定位置的图片执行此回调
*
* @param browserController
* @param index
*/
- (void)imageBrowser:(GJCUImageBrowserViewController *)browserController didFinishRemoveAtIndex:(NSInteger)index;
/**
* 删除仅剩的最后一张图片的时候执行此回调
*
* @param browserController
*/
- (void)imageBrowserShouldReturnWhileRemoveLastOnlyImage:(GJCUImageBrowserViewController *)browserController;
@end
| 557 |
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.web.sys;
import com.haulmont.cuba.core.global.UserSessionSource;
import com.haulmont.cuba.core.sys.AbstractUserSessionSource;
import com.haulmont.cuba.core.sys.AppContext;
import com.haulmont.cuba.core.sys.SecurityContext;
import com.haulmont.cuba.security.app.UserSessionService;
import com.haulmont.cuba.security.global.MismatchedUserSessionException;
import com.haulmont.cuba.security.global.UserSession;
import com.haulmont.cuba.web.App;
import com.haulmont.cuba.web.AppUI;
import com.haulmont.cuba.web.Connection;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.UUID;
@Component(UserSessionSource.NAME)
public class WebUserSessionSource extends AbstractUserSessionSource {
public static final String REQUEST_ATTR = "CUBA_USER_SESSION";
@Inject
private UserSessionService userSessionService;
@Override
public boolean checkCurrentUserSession() {
if (App.isBound()) {
App app = App.getInstance();
Connection connection = app.getConnection();
return connection.isConnected() && connection.getSession() != null;
} else {
SecurityContext securityContext = AppContext.getSecurityContext();
if (securityContext == null) {
return false;
}
if (securityContext.getSession() != null) {
return true;
} else if (AppContext.isStarted()) {
try {
getUserSessionFromMiddleware(securityContext.getSessionId());
return true;
} catch (Exception e) {
return false;
}
} else
return false;
}
}
@Override
public UserSession getUserSession() {
UserSession session;
if (App.isBound()) {
AppUI ui = AppUI.getCurrent();
if (ui != null) {
session = ui.getUserSession();
if (session == null) {
session = ui.getApp().getConnection().getSession();
}
checkUiSession(session, ui);
} else {
session = App.getInstance().getConnection().getSession();
}
} else {
SecurityContext securityContext = AppContext.getSecurityContextNN();
if (securityContext.getSession() != null) {
session = securityContext.getSession();
} else {
session = getUserSessionFromMiddleware(securityContext.getSessionId());
}
}
if (session == null) {
throw new IllegalStateException("No user session");
}
return session;
}
protected UserSession getUserSessionFromMiddleware(UUID sessionId) {
UserSession userSession = null;
HttpServletRequest request = null;
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
request = ((ServletRequestAttributes) requestAttributes).getRequest();
}
if (request != null) {
userSession = (UserSession) request.getAttribute(REQUEST_ATTR);
}
if (userSession != null) {
return userSession;
}
userSession = userSessionService.getUserSession(sessionId);
if (request != null) {
request.setAttribute(REQUEST_ATTR, userSession);
}
return userSession;
}
protected void checkUiSession(UserSession session, AppUI ui) {
Connection connection = ui.getApp().getConnection();
UserSession appUserSession = connection.getSession();
boolean appAuthenticated = connection.isAuthenticated();
boolean uiAuthenticated = ui.hasAuthenticatedSession();
if (!appAuthenticated && uiAuthenticated) {
throw new MismatchedUserSessionException(session.getId());
}
if (appAuthenticated && uiAuthenticated
&& !Objects.equals(appUserSession, session)) {
throw new MismatchedUserSessionException(session.getId());
}
}
} | 2,010 |
428 | <reponame>DCNick3/remill
/*
* Copyright (c) 2021 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <llvm/IR/Instruction.h>
#include "remill/BC/Version.h"
/* In llvm-11 llvm::CallSite got partially replace by llvm::AbstractCallSite
* for read-only operations and llvm::CallBase was made public (was considered
* implementation before)
* This header tries to provide at least some compatibility for what is
* currently used.
*/
#if LLVM_VERSION_NUMBER < LLVM_VERSION(11, 0)
# include <llvm/IR/CallSite.h>
namespace remill::compat::llvm {
struct CallSite : private ::llvm::CallSite {
using parent = ::llvm::CallSite;
/* List of "allowed" methods (thanks to private inheritance)
* that prevent user from accidentally using functionality that
* would break other llvm version.
* If you want to add method here, make sure other versions have it
* as well.
*/
using parent::isCall;
using parent::isInvoke;
using parent::parent;
using parent::operator bool;
using parent::getCalledFunction;
using parent::getCalledValue;
using parent::getInstruction;
using parent::setCalledFunction;
};
} // namespace remill::compat::llvm
#else
# include <llvm/Analysis/InlineCost.h>
# include <llvm/IR/AbstractCallSite.h>
# include <llvm/Transforms/Utils/Cloning.h>
namespace remill::compat::llvm {
struct CallSite {
::llvm::CallBase *cb;
CallSite(::llvm::Instruction *inst)
: cb(::llvm::dyn_cast_or_null<::llvm::CallBase>(inst)) {}
CallSite(::llvm::User *user)
: CallSite(::llvm::dyn_cast_or_null<::llvm::Instruction>(user)) {}
bool isInvoke() const {
return cb && ::llvm::isa<::llvm::InvokeInst>(*cb);
}
bool isCall() const {
return cb && ::llvm::isa<::llvm::CallInst>(*cb);
}
::llvm::Value *getCalledValue() {
if (!static_cast<bool>(*this)) {
return nullptr;
}
return cb->getCalledOperand();
}
::llvm::Function *getCalledFunction() const {
if (!*this) {
return nullptr;
}
return cb->getCalledFunction();
}
void setCalledFunction(::llvm::Function *fn) {
return cb->setCalledFunction(fn);
}
operator bool() const {
return cb;
}
::llvm::CallBase *getInstruction() {
return cb;
}
};
} // namespace remill::compat::llvm
#endif
| 979 |
436 | <filename>src/maestral/cli/__init__.py
"""
This module contains the command line interface of Maestral. Keep all heavy imports
local to the command or method that requires them to ensure a responsive CLI.
"""
from .cli_main import main
__all__ = ["main"]
| 72 |
429 | <filename>Main/Forms/VolumePropertiesDialog.h
/*
Copyright (c) 2008 TrueCrypt Developers Association. All rights reserved.
Governed by the TrueCrypt License 3.0 the full text of which is contained in
the file License.txt included in TrueCrypt binary and source code distribution
packages.
*/
#ifndef TC_HEADER_Main_Forms_VolumePropertiesDialog
#define TC_HEADER_Main_Forms_VolumePropertiesDialog
#include "Forms.h"
#include "Main/Main.h"
namespace TrueCrypt
{
class VolumePropertiesDialog : public VolumePropertiesDialogBase
{
public:
VolumePropertiesDialog (wxWindow* parent, const VolumeInfo &volumeInfo);
void AppendToList (const string &name, const wxString &value);
};
}
#endif // TC_HEADER_Main_Forms_VolumePropertiesDialog
| 225 |
5,169 | <reponame>Gantios/Specs
{
"name": "Touchtest",
"version": "1.5.10",
"summary": "Functional Test Automation library for iOS applications.",
"license": {
"type": "Apache License, Version 2.0",
"file": "LICENSE"
},
"social_media_url": "https://twitter.com/cloudtest",
"source": {
"git": "https://github.com/SOASTA/Touchtest-iOS.git",
"tag": "1.5.10"
},
"homepage": "https://github.com/SOASTA/Touchtest-iOS",
"authors": {
"SOASTA": "<EMAIL>"
},
"platforms": {
"ios": "6.0"
},
"source_files": "include/*.h",
"public_header_files": "include/*.h",
"preserve_paths": "libTouchTestDriver.a",
"ios": {
"vendored_libraries": "libTouchTestDriver.a"
},
"libraries": [
"z",
"xml2",
"TouchTestDriver"
],
"frameworks": [
"CFNetwork",
"CoreGraphics",
"OpenGLES",
"CoreLocation",
"MapKit",
"QuartzCore",
"IOKit",
"WebKit"
],
"user_target_xcconfig": {
"OTHER_LDFLAGS": "-F$(SDKROOT)$(SYSTEM_LIBRARY_DIR)/PrivateFrameworks/"
},
"requires_arc": true
}
| 466 |
918 | //Copyright (c) 2008-2016 <NAME> and <NAME>, Inc.
//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/qvm/mat_operations.hpp>
#include <boost/qvm/mat.hpp>
using namespace boost::qvm;
namespace
n1
{
struct user_matrix1 { float a[3][3]; };
struct user_matrix2 { float a[3][3]; };
}
namespace
n2
{
struct user_matrix1 { float a[3][3]; };
struct user_matrix2 { float a[3][3]; };
}
namespace
boost
{
namespace
qvm
{
template <>
struct
mat_traits<n1::user_matrix1>
{
typedef float scalar_type;
static int const rows=3;
static int const cols=3;
template <int R,int C>
static inline scalar_type & write_element( n1::user_matrix1 & m ) { return m.a[R][C]; }
template <int R,int C>
static inline scalar_type read_element( n1::user_matrix1 const & m ) { return m.a[R][C]; }
static inline scalar_type & write_element_idx( int r, int c, n1::user_matrix1 & m ) { return m.a[r][c]; }
static inline scalar_type read_element_idx( int r, int c, n1::user_matrix1 const & m ) { return m.a[r][c]; }
};
template <>
struct
mat_traits<n1::user_matrix2>
{
typedef float scalar_type;
static int const rows=3;
static int const cols=3;
template <int R,int C>
static inline scalar_type & write_element( n1::user_matrix2 & m ) { return m.a[R][C]; }
template <int R,int C>
static inline scalar_type read_element( n1::user_matrix2 const & m ) { return m.a[R][C]; }
static inline scalar_type & write_element_idx( int r, int c, n1::user_matrix2 & m ) { return m.a[r][c]; }
static inline scalar_type read_element_idx( int r, int c, n1::user_matrix2 const & m ) { return m.a[r][c]; }
};
template <>
struct
mat_traits<n2::user_matrix1>
{
typedef float scalar_type;
static int const rows=3;
static int const cols=3;
template <int R,int C>
static inline scalar_type & write_element( n2::user_matrix1 & m ) { return m.a[R][C]; }
template <int R,int C>
static inline scalar_type read_element( n2::user_matrix1 const & m ) { return m.a[R][C]; }
static inline scalar_type & write_element_idx( int r, int c, n2::user_matrix1 & m ) { return m.a[r][c]; }
static inline scalar_type read_element_idx( int r, int c, n2::user_matrix1 const & m ) { return m.a[r][c]; }
};
template <>
struct
mat_traits<n2::user_matrix2>
{
typedef float scalar_type;
static int const rows=3;
static int const cols=3;
template <int R,int C>
static inline scalar_type & write_element( n2::user_matrix2 & m ) { return m.a[R][C]; }
template <int R,int C>
static inline scalar_type read_element( n2::user_matrix2 const & m ) { return m.a[R][C]; }
static inline scalar_type & write_element_idx( int r, int c, n2::user_matrix2 & m ) { return m.a[r][c]; }
static inline scalar_type read_element_idx( int r, int c, n2::user_matrix2 const & m ) { return m.a[r][c]; }
};
template <>
struct
deduce_mat2<n2::user_matrix1,n2::user_matrix2,3,3>
{ typedef n2::user_matrix1 type; };
template <>
struct
deduce_mat2<n2::user_matrix2,n2::user_matrix1,3,3>
{ typedef n2::user_matrix1 type; };
}
}
void
f()
{
{
n1::user_matrix1 m1;
n1::user_matrix2 m2;
n1::user_matrix1 m = m1 * m2;
}
{
n2::user_matrix1 m1;
n2::user_matrix2 m2;
n2::user_matrix1 m = m1 * m2;
}
{
float m[3][3];
(void) inverse(m);
}
}
| 2,260 |
14,668 | <reponame>zealoussnow/chromium
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/services/secure_channel/fake_secure_channel_connection.h"
#include <utility>
#include <vector>
#include "base/callback.h"
#include "base/check.h"
#include "chromeos/services/secure_channel/file_transfer_update_callback.h"
#include "chromeos/services/secure_channel/public/mojom/secure_channel_types.mojom.h"
#include "chromeos/services/secure_channel/register_payload_file_request.h"
namespace chromeos {
namespace secure_channel {
FakeSecureChannelConnection::SentMessage::SentMessage(
const std::string& feature,
const std::string& payload)
: feature(feature), payload(payload) {}
FakeSecureChannelConnection::FakeSecureChannelConnection(
std::unique_ptr<Connection> connection)
: SecureChannel(std::move(connection)) {}
FakeSecureChannelConnection::~FakeSecureChannelConnection() {
if (destructor_callback_)
std::move(destructor_callback_).Run();
}
void FakeSecureChannelConnection::ChangeStatus(const Status& new_status) {
Status old_status = status_;
status_ = new_status;
// Copy to prevent channel from being removed during handler.
std::vector<Observer*> observers_copy = observers_;
for (auto* observer : observers_copy) {
observer->OnSecureChannelStatusChanged(this, old_status, status_);
}
}
void FakeSecureChannelConnection::ReceiveMessage(const std::string& feature,
const std::string& payload) {
// Copy to prevent channel from being removed during handler.
std::vector<Observer*> observers_copy = observers_;
for (auto* observer : observers_copy)
observer->OnMessageReceived(this, feature, payload);
}
void FakeSecureChannelConnection::CompleteSendingMessage(int sequence_number) {
DCHECK(next_sequence_number_ > sequence_number);
// Copy to prevent channel from being removed during handler.
std::vector<Observer*> observers_copy = observers_;
for (auto* observer : observers_copy)
observer->OnMessageSent(this, sequence_number);
}
void FakeSecureChannelConnection::Initialize() {
was_initialized_ = true;
ChangeStatus(Status::CONNECTING);
}
int FakeSecureChannelConnection::SendMessage(const std::string& feature,
const std::string& payload) {
sent_messages_.push_back(SentMessage(feature, payload));
return next_sequence_number_++;
}
void FakeSecureChannelConnection::RegisterPayloadFile(
int64_t payload_id,
mojom::PayloadFilesPtr payload_files,
FileTransferUpdateCallback file_transfer_update_callback,
base::OnceCallback<void(bool)> registration_result_callback) {
register_payload_file_requests_.emplace_back(
payload_id, std::move(file_transfer_update_callback));
std::move(registration_result_callback).Run(/*success=*/true);
}
void FakeSecureChannelConnection::Disconnect() {
if (status() == Status::DISCONNECTING || status() == Status::DISCONNECTED)
return;
if (status() == Status::CONNECTING)
ChangeStatus(Status::DISCONNECTED);
else
ChangeStatus(Status::DISCONNECTING);
}
void FakeSecureChannelConnection::AddObserver(Observer* observer) {
observers_.push_back(observer);
}
void FakeSecureChannelConnection::RemoveObserver(Observer* observer) {
observers_.erase(std::find(observers_.begin(), observers_.end(), observer),
observers_.end());
}
void FakeSecureChannelConnection::GetConnectionRssi(
base::OnceCallback<void(absl::optional<int32_t>)> callback) {
std::move(callback).Run(rssi_to_return_);
}
absl::optional<std::string>
FakeSecureChannelConnection::GetChannelBindingData() {
return channel_binding_data_;
}
} // namespace secure_channel
} // namespace chromeos
| 1,250 |
367 | @import Foundation;
@protocol MTLDevice, MTLLibrary, MTLCommandQueue;
@interface MBEContext : NSObject
@property (strong) id<MTLDevice> device;
@property (strong) id<MTLLibrary> library;
@property (strong) id<MTLCommandQueue> commandQueue;
+ (instancetype)newContext;
@end
| 99 |
930 | <reponame>SapphireFX/overlap2d<filename>overlap2d/test/java/com/uwsoft/editor/proxy/PluginManagerTest.java
package com.uwsoft.editor.proxy;
import com.commons.plugins.O2DPlugin;
import com.commons.plugins.PluginAPI;
import com.uwsoft.editor.view.stage.Sandbox;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.ArrayList;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Sandbox.class)
public class PluginManagerTest {
private PluginManager pluginManager;
@Mock
private O2DPlugin plugin;
@Before
public void setUp() throws Exception {
initMocks(this);
mockStatic(Sandbox.class);
when(Sandbox.getInstance()).thenReturn(mock(Sandbox.class));
pluginManager = new PluginManager();
pluginManager.onRegister();
}
@Test
public void shouldAbleToRegisterPlugin() throws Exception {
O2DPlugin o2DPlugin = pluginManager.registerPlugin(plugin);
ArrayList<O2DPlugin> plugins = (ArrayList<O2DPlugin>) Whitebox.getInternalState(pluginManager, "plugins");
assertThat(o2DPlugin, not(nullValue()));
assertThat(plugins, hasSize(1));
}
@Test
public void shouldSetEverythingAfterInit() throws Exception {
pluginManager.initPlugin(plugin);
verify(plugin).setAPI(any(PluginAPI.class));
}
@Test
public void shouldDoNothingWhenInitSamePluginSecondTime() throws Exception {
pluginManager.initPlugin(plugin);
reset(plugin);
pluginManager.initPlugin(plugin);
verify(plugin, never()).setAPI(any(PluginAPI.class));
}
} | 827 |
895 | <reponame>visor-tax/NgKeyboardTracker<filename>NgKeyboardTracker/NgPseudoInputAccessoryViewCoordinator.h
//
// NgPseudoInputAccessoryViewCoordinator.h
// NgKeyboardTracker
//
// Created by <NAME> on 3/7/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
/**
* Instance of this class creates and manages one instance of pseudo inputAccessoryView.
* You can create instance of this class via `NgKeyboardTracker` instance.
*
* The coordinator will reports keyboard layout updates to `NgKeyboardTracker` that created it.
*/
@interface NgPseudoInputAccessoryViewCoordinator : NSObject
#pragma mark Properties
@property (nonatomic, strong, readonly) UIView * pseudoInputAccessoryView;
- (instancetype)init UNAVAILABLE_ATTRIBUTE;
#pragma mark Input Accessory Height
- (void)setPseudoInputAccessoryViewHeight:(CGFloat)height;
- (CGFloat)pseudoInputAccessoryViewHeight;
#pragma mark Convenience Methods
/**
* If `isActive` is true, it means the pseudo input accessory view managed by this coordinator
* is presently attached to keyboard
*/
- (BOOL)isActive;
@end
| 354 |
4,140 | <filename>common/src/java/org/apache/hadoop/hive/common/JvmMetricsInfo.java<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.common;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import org.apache.hadoop.metrics2.MetricsInfo;
/**
* JVM and logging related metrics info instances. Ported from Hadoop JvmMetricsInfo.
*/
public enum JvmMetricsInfo implements MetricsInfo {
JvmMetrics("JVM related metrics etc."), // record info
// metrics
MemNonHeapUsedM("Non-heap memory used in MB"),
MemNonHeapCommittedM("Non-heap memory committed in MB"),
MemNonHeapMaxM("Non-heap memory max in MB"),
MemHeapUsedM("Heap memory used in MB"),
MemHeapCommittedM("Heap memory committed in MB"),
MemHeapMaxM("Heap memory max in MB"),
MemMaxM("Max memory size in MB"),
GcCount("Total GC count"),
GcTimeMillis("Total GC time in milliseconds"),
ThreadsNew("Number of new threads"),
ThreadsRunnable("Number of runnable threads"),
ThreadsBlocked("Number of blocked threads"),
ThreadsWaiting("Number of waiting threads"),
ThreadsTimedWaiting("Number of timed waiting threads"),
ThreadsTerminated("Number of terminated threads"),
LogFatal("Total number of fatal log events"),
LogError("Total number of error log events"),
LogWarn("Total number of warning log events"),
LogInfo("Total number of info log events"),
GcNumWarnThresholdExceeded("Number of times that the GC warn threshold is exceeded"),
GcNumInfoThresholdExceeded("Number of times that the GC info threshold is exceeded"),
GcTotalExtraSleepTime("Total GC extra sleep time in milliseconds");
private final String desc;
JvmMetricsInfo(String desc) { this.desc = desc; }
@Override public String description() { return desc; }
@Override public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name()).add("description", desc)
.toString();
}
}
| 793 |
371 | import wandb
class WandbLogger:
def __init__(self,
log_dir,
ids=list(),
training_name='test',
*args, **kwargs):
wandb.login()
wandb.init(project='RLs',
# config=records_dict,
id=training_name,
resume='allow')
self._is_multi_logger = True if len(ids) > 1 else False
self._register_keys = {}
def write(self, summaries, step, *args, **kwargs):
if self._is_multi_logger:
_summaries = {}
for k, v in summaries.items():
for _k, _v in v.items():
_summaries[k + '_' + _k] = _v
else:
_summaries = summaries
self._check_is_registered(_summaries)
_summaries.update({
self._register_keys[list(_summaries.keys())[0]]: step
})
wandb.log(_summaries)
def _check_is_registered(self, summaries):
if list(summaries.keys())[0] in self._register_keys.keys():
return
else:
step_metric = f'step{len(self._register_keys)}'
self._register_keys.update({
list(summaries.keys())[0]: step_metric
})
for k, v in summaries.items():
wandb.run.define_metric(k, step_metric=step_metric)
| 752 |
533 | # _*_ coding: utf-8 _*_
"""
Created by Allen7D on 2018/6/17.
↓↓↓ 产品接口 ↓↓↓
"""
from app.extensions.api_docs.redprint import Redprint
from app.extensions.api_docs.v1 import product as api_doc
from app.core.token_auth import auth
from app.models.product import Product
from app.dao.product import ProductDao
from app.libs.error_code import Success
from app.core.utils import paginate
from app.validators.forms import CountValidator, CategoryIDValidator, ReorderValidator
__author__ = 'Allen7D'
api = Redprint(name='product', module='产品', api_doc=api_doc)
@api.route('/recent', methods=['GET'])
@api.doc(args=['count'])
def get_recent():
'''最新的商品'''
count = CountValidator().validate_for_api().count.data
rv = ProductDao.get_most_recent(count=count)
return Success(rv)
@api.route('/all/by_category', methods=['GET'])
@api.doc(args=['g.query.category_id'])
def get_all_by_category():
'''查询类别下所有商品'''
category_id = CategoryIDValidator().nt_data.category_id
product_list = Product.query.filter_by(category_id=category_id).all()
return Success({
'items': product_list
})
@api.route('/list/by_category', methods=['GET'])
@api.doc(args=['g.query.page', 'g.query.size', 'g.query.category_id'], auth=True)
@auth.login_required
def get_list_by_category():
'''查询类别下商品列表'''
category_id = CategoryIDValidator().nt_data.category_id
page, size = paginate()
rv = ProductDao.get_list_by_category(c_id=category_id, page=page, size=size)
return Success(rv)
@api.route('/<int:id>', methods=['GET'])
@api.doc(args=['g.path.product_id'])
def get_product(id):
'''查询商品'''
product = ProductDao.get_product(id=id)
return Success(product)
@api.route('', methods=['POST'])
@api.route_meta(auth='新增商品', module='商品')
@api.doc(auth=True)
@auth.group_required
def create_product():
'''新增商品'''
return Success(error_code=1)
@api.route('/<int:id>', methods=['PUT'])
@api.route_meta(auth='更新商品', module='商品')
@api.doc(args=['g.path.product_id'], auth=True)
@auth.group_required
def update_product(id):
'''更新商品'''
return Success(error_code=1)
@api.route('/<int:id>', methods=['DELETE'])
@api.route_meta(auth='删除商品', module='商品')
@api.doc(args=['g.path.product_id'], auth=True)
@auth.group_required
def delete_product(id):
'''删除商品'''
ProductDao.delete_product(id)
return Success(error_code=2)
@api.route('/<int:id>/reorder', methods=['PUT'])
@api.route_meta(auth='排序商品图片', module='商品')
@api.doc(args=['g.path.product_id', 'g.body.src_order', 'g.body.dest_order'], auth=True)
@auth.group_required
def reorder_image(id):
'''排序商品图片'''
validator = ReorderValidator().nt_data
ProductDao.reorder_image(p_id=id, src_order=validator.src_order, dest_order=validator.dest_order)
return Success(error_code=1) | 1,292 |
4,544 | <reponame>agolo/haystack
import re
def clean_wiki_text(text: str) -> str:
"""
Clean wikipedia text by removing multiple new lines, removing extremely short lines,
adding paragraph breaks and removing empty paragraphs
"""
# get rid of multiple new lines
while "\n\n" in text:
text = text.replace("\n\n", "\n")
# remove extremely short lines
lines = text.split("\n")
cleaned = []
for l in lines:
if len(l) > 30:
cleaned.append(l)
elif l[:2] == "==" and l[-2:] == "==":
cleaned.append(l)
text = "\n".join(cleaned)
# add paragraphs (identified by wiki section title which is always in format "==Some Title==")
text = text.replace("\n==", "\n\n\n==")
# remove empty paragrahps
text = re.sub(r"(==.*==\n\n\n)", "", text)
return text
| 339 |
521 | <filename>third_party/virtualbox/include/VBox/vmm/cfgm.h<gh_stars>100-1000
/** @file
* CFGM - Configuration Manager.
*/
/*
* Copyright (C) 2006-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
#ifndef ___VBox_vmm_cfgm_h
#define ___VBox_vmm_cfgm_h
#include <VBox/types.h>
#include <iprt/stdarg.h>
/** @defgroup grp_cfgm The Configuration Manager API
* @ingroup grp_vmm
* @{
*/
/**
* Configuration manager value type.
*/
typedef enum CFGMVALUETYPE
{
/** Integer value. */
CFGMVALUETYPE_INTEGER = 1,
/** String value. */
CFGMVALUETYPE_STRING,
/** Bytestring value. */
CFGMVALUETYPE_BYTES
} CFGMVALUETYPE;
/** Pointer to configuration manager property type. */
typedef CFGMVALUETYPE *PCFGMVALUETYPE;
RT_C_DECLS_BEGIN
#ifdef IN_RING3
/** @defgroup grp_cfgm_r3 The CFGM Host Context Ring-3 API
* @{
*/
typedef enum CFGMCONFIGTYPE
{
/** pvConfig points to nothing, use defaults. */
CFGMCONFIGTYPE_NONE = 0,
/** pvConfig points to a IMachine interface. */
CFGMCONFIGTYPE_IMACHINE
} CFGMCONFIGTYPE;
/**
* CFGM init callback for constructing the configuration tree.
*
* This is called from the emulation thread, and the one interfacing the VM
* can make any necessary per-thread initializations at this point.
*
* @returns VBox status code.
* @param pUVM The user mode VM handle.
* @param pVM The cross context VM structure.
* @param pvUser The argument supplied to VMR3Create().
*/
typedef DECLCALLBACK(int) FNCFGMCONSTRUCTOR(PUVM pUVM, PVM pVM, void *pvUser);
/** Pointer to a FNCFGMCONSTRUCTOR(). */
typedef FNCFGMCONSTRUCTOR *PFNCFGMCONSTRUCTOR;
VMMR3DECL(int) CFGMR3Init(PVM pVM, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUser);
VMMR3DECL(int) CFGMR3Term(PVM pVM);
VMMR3DECL(int) CFGMR3ConstructDefaultTree(PVM pVM);
VMMR3DECL(PCFGMNODE) CFGMR3CreateTree(PUVM pUVM);
VMMR3DECL(int) CFGMR3DestroyTree(PCFGMNODE pRoot);
VMMR3DECL(void) CFGMR3Dump(PCFGMNODE pRoot);
VMMR3DECL(int) CFGMR3DuplicateSubTree(PCFGMNODE pRoot, PCFGMNODE *ppCopy);
VMMR3DECL(int) CFGMR3ReplaceSubTree(PCFGMNODE pRoot, PCFGMNODE pNewRoot);
VMMR3DECL(int) CFGMR3InsertSubTree(PCFGMNODE pNode, const char *pszName, PCFGMNODE pSubTree, PCFGMNODE *ppChild);
VMMR3DECL(int) CFGMR3InsertNode(PCFGMNODE pNode, const char *pszName, PCFGMNODE *ppChild);
VMMR3DECL(int) CFGMR3InsertNodeF(PCFGMNODE pNode, PCFGMNODE *ppChild,
const char *pszNameFormat, ...) RT_IPRT_FORMAT_ATTR(3, 4);
VMMR3DECL(int) CFGMR3InsertNodeFV(PCFGMNODE pNode, PCFGMNODE *ppChild,
const char *pszNameFormat, va_list Args) RT_IPRT_FORMAT_ATTR(3, 0);
VMMR3DECL(void) CFGMR3SetRestrictedRoot(PCFGMNODE pNode);
VMMR3DECL(void) CFGMR3RemoveNode(PCFGMNODE pNode);
VMMR3DECL(int) CFGMR3InsertInteger(PCFGMNODE pNode, const char *pszName, uint64_t u64Integer);
VMMR3DECL(int) CFGMR3InsertString(PCFGMNODE pNode, const char *pszName, const char *pszString);
VMMR3DECL(int) CFGMR3InsertStringN(PCFGMNODE pNode, const char *pszName, const char *pszString, size_t cchString);
VMMR3DECL(int) CFGMR3InsertStringF(PCFGMNODE pNode, const char *pszName,
const char *pszFormat, ...) RT_IPRT_FORMAT_ATTR(3, 4);
VMMR3DECL(int) CFGMR3InsertStringFV(PCFGMNODE pNode, const char *pszName,
const char *pszFormat, va_list va) RT_IPRT_FORMAT_ATTR(3, 0);
VMMR3DECL(int) CFGMR3InsertStringW(PCFGMNODE pNode, const char *pszName, PCRTUTF16 pwszValue);
VMMR3DECL(int) CFGMR3InsertBytes(PCFGMNODE pNode, const char *pszName, const void *pvBytes, size_t cbBytes);
VMMR3DECL(int) CFGMR3InsertValue(PCFGMNODE pNode, PCFGMLEAF pValue);
VMMR3DECL(int) CFGMR3RemoveValue(PCFGMNODE pNode, const char *pszName);
/** @name CFGMR3CopyTree flags.
* @{ */
/** Reserved value disposition \#0. */
#define CFGM_COPY_FLAGS_RESERVED_VALUE_DISP_0 UINT32_C(0x00000000)
/** Reserved value disposition \#1. */
#define CFGM_COPY_FLAGS_RESERVED_VALUE_DISP_1 UINT32_C(0x00000001)
/** Replace exiting values. */
#define CFGM_COPY_FLAGS_REPLACE_VALUES UINT32_C(0x00000002)
/** Ignore exiting values. */
#define CFGM_COPY_FLAGS_IGNORE_EXISTING_VALUES UINT32_C(0x00000003)
/** Value disposition mask. */
#define CFGM_COPY_FLAGS_VALUE_DISP_MASK UINT32_C(0x00000003)
/** Replace exiting keys. */
#define CFGM_COPY_FLAGS_RESERVED_KEY_DISP UINT32_C(0x00000000)
/** Replace exiting keys. */
#define CFGM_COPY_FLAGS_MERGE_KEYS UINT32_C(0x00000010)
/** Replace exiting keys. */
#define CFGM_COPY_FLAGS_REPLACE_KEYS UINT32_C(0x00000020)
/** Ignore existing keys. */
#define CFGM_COPY_FLAGS_IGNORE_EXISTING_KEYS UINT32_C(0x00000030)
/** Key disposition. */
#define CFGM_COPY_FLAGS_KEY_DISP_MASK UINT32_C(0x00000030)
/** @} */
VMMR3DECL(int) CFGMR3CopyTree(PCFGMNODE pDstTree, PCFGMNODE pSrcTree, uint32_t fFlags);
VMMR3DECL(bool) CFGMR3Exists( PCFGMNODE pNode, const char *pszName);
VMMR3DECL(int) CFGMR3QueryType( PCFGMNODE pNode, const char *pszName, PCFGMVALUETYPE penmType);
VMMR3DECL(int) CFGMR3QuerySize( PCFGMNODE pNode, const char *pszName, size_t *pcb);
VMMR3DECL(int) CFGMR3QueryInteger( PCFGMNODE pNode, const char *pszName, uint64_t *pu64);
VMMR3DECL(int) CFGMR3QueryIntegerDef( PCFGMNODE pNode, const char *pszName, uint64_t *pu64, uint64_t u64Def);
VMMR3DECL(int) CFGMR3QueryString( PCFGMNODE pNode, const char *pszName, char *pszString, size_t cchString);
VMMR3DECL(int) CFGMR3QueryStringDef( PCFGMNODE pNode, const char *pszName, char *pszString, size_t cchString, const char *pszDef);
VMMR3DECL(int) CFGMR3QueryBytes( PCFGMNODE pNode, const char *pszName, void *pvData, size_t cbData);
/** @name Helpers
* @{
*/
VMMR3DECL(int) CFGMR3QueryU64( PCFGMNODE pNode, const char *pszName, uint64_t *pu64);
VMMR3DECL(int) CFGMR3QueryU64Def( PCFGMNODE pNode, const char *pszName, uint64_t *pu64, uint64_t u64Def);
VMMR3DECL(int) CFGMR3QueryS64( PCFGMNODE pNode, const char *pszName, int64_t *pi64);
VMMR3DECL(int) CFGMR3QueryS64Def( PCFGMNODE pNode, const char *pszName, int64_t *pi64, int64_t i64Def);
VMMR3DECL(int) CFGMR3QueryU32( PCFGMNODE pNode, const char *pszName, uint32_t *pu32);
VMMR3DECL(int) CFGMR3QueryU32Def( PCFGMNODE pNode, const char *pszName, uint32_t *pu32, uint32_t u32Def);
VMMR3DECL(int) CFGMR3QueryS32( PCFGMNODE pNode, const char *pszName, int32_t *pi32);
VMMR3DECL(int) CFGMR3QueryS32Def( PCFGMNODE pNode, const char *pszName, int32_t *pi32, int32_t i32Def);
VMMR3DECL(int) CFGMR3QueryU16( PCFGMNODE pNode, const char *pszName, uint16_t *pu16);
VMMR3DECL(int) CFGMR3QueryU16Def( PCFGMNODE pNode, const char *pszName, uint16_t *pu16, uint16_t u16Def);
VMMR3DECL(int) CFGMR3QueryS16( PCFGMNODE pNode, const char *pszName, int16_t *pi16);
VMMR3DECL(int) CFGMR3QueryS16Def( PCFGMNODE pNode, const char *pszName, int16_t *pi16, int16_t i16Def);
VMMR3DECL(int) CFGMR3QueryU8( PCFGMNODE pNode, const char *pszName, uint8_t *pu8);
VMMR3DECL(int) CFGMR3QueryU8Def( PCFGMNODE pNode, const char *pszName, uint8_t *pu8, uint8_t u8Def);
VMMR3DECL(int) CFGMR3QueryS8( PCFGMNODE pNode, const char *pszName, int8_t *pi8);
VMMR3DECL(int) CFGMR3QueryS8Def( PCFGMNODE pNode, const char *pszName, int8_t *pi8, int8_t i8Def);
VMMR3DECL(int) CFGMR3QueryBool( PCFGMNODE pNode, const char *pszName, bool *pf);
VMMR3DECL(int) CFGMR3QueryBoolDef( PCFGMNODE pNode, const char *pszName, bool *pf, bool fDef);
VMMR3DECL(int) CFGMR3QueryPort( PCFGMNODE pNode, const char *pszName, PRTIOPORT pPort);
VMMR3DECL(int) CFGMR3QueryPortDef( PCFGMNODE pNode, const char *pszName, PRTIOPORT pPort, RTIOPORT PortDef);
VMMR3DECL(int) CFGMR3QueryUInt( PCFGMNODE pNode, const char *pszName, unsigned int *pu);
VMMR3DECL(int) CFGMR3QueryUIntDef( PCFGMNODE pNode, const char *pszName, unsigned int *pu, unsigned int uDef);
VMMR3DECL(int) CFGMR3QuerySInt( PCFGMNODE pNode, const char *pszName, signed int *pi);
VMMR3DECL(int) CFGMR3QuerySIntDef( PCFGMNODE pNode, const char *pszName, signed int *pi, signed int iDef);
VMMR3DECL(int) CFGMR3QueryPtr( PCFGMNODE pNode, const char *pszName, void **ppv);
VMMR3DECL(int) CFGMR3QueryPtrDef( PCFGMNODE pNode, const char *pszName, void **ppv, void *pvDef);
VMMR3DECL(int) CFGMR3QueryGCPtr( PCFGMNODE pNode, const char *pszName, PRTGCPTR pGCPtr);
VMMR3DECL(int) CFGMR3QueryGCPtrDef( PCFGMNODE pNode, const char *pszName, PRTGCPTR pGCPtr, RTGCPTR GCPtrDef);
VMMR3DECL(int) CFGMR3QueryGCPtrU( PCFGMNODE pNode, const char *pszName, PRTGCUINTPTR pGCPtr);
VMMR3DECL(int) CFGMR3QueryGCPtrUDef( PCFGMNODE pNode, const char *pszName, PRTGCUINTPTR pGCPtr, RTGCUINTPTR GCPtrDef);
VMMR3DECL(int) CFGMR3QueryGCPtrS( PCFGMNODE pNode, const char *pszName, PRTGCINTPTR pGCPtr);
VMMR3DECL(int) CFGMR3QueryGCPtrSDef( PCFGMNODE pNode, const char *pszName, PRTGCINTPTR pGCPtr, RTGCINTPTR GCPtrDef);
VMMR3DECL(int) CFGMR3QueryStringAlloc( PCFGMNODE pNode, const char *pszName, char **ppszString);
VMMR3DECL(int) CFGMR3QueryStringAllocDef(PCFGMNODE pNode, const char *pszName, char **ppszString, const char *pszDef);
/** @} */
/** @name Tree Navigation and Enumeration.
* @{
*/
VMMR3DECL(PCFGMNODE) CFGMR3GetRoot(PVM pVM);
VMMR3DECL(PCFGMNODE) CFGMR3GetRootU(PUVM pUVM);
VMMR3DECL(PCFGMNODE) CFGMR3GetParent(PCFGMNODE pNode);
VMMR3DECL(PCFGMNODE) CFGMR3GetParentEx(PVM pVM, PCFGMNODE pNode);
VMMR3DECL(PCFGMNODE) CFGMR3GetChild(PCFGMNODE pNode, const char *pszPath);
VMMR3DECL(PCFGMNODE) CFGMR3GetChildF(PCFGMNODE pNode, const char *pszPathFormat, ...) RT_IPRT_FORMAT_ATTR(2, 3);
VMMR3DECL(PCFGMNODE) CFGMR3GetChildFV(PCFGMNODE pNode, const char *pszPathFormat, va_list Args) RT_IPRT_FORMAT_ATTR(3, 0);
VMMR3DECL(PCFGMNODE) CFGMR3GetFirstChild(PCFGMNODE pNode);
VMMR3DECL(PCFGMNODE) CFGMR3GetNextChild(PCFGMNODE pCur);
VMMR3DECL(int) CFGMR3GetName(PCFGMNODE pCur, char *pszName, size_t cchName);
VMMR3DECL(size_t) CFGMR3GetNameLen(PCFGMNODE pCur);
VMMR3DECL(bool) CFGMR3AreChildrenValid(PCFGMNODE pNode, const char *pszzValid);
VMMR3DECL(PCFGMLEAF) CFGMR3GetFirstValue(PCFGMNODE pCur);
VMMR3DECL(PCFGMLEAF) CFGMR3GetNextValue(PCFGMLEAF pCur);
VMMR3DECL(int) CFGMR3GetValueName(PCFGMLEAF pCur, char *pszName, size_t cchName);
VMMR3DECL(size_t) CFGMR3GetValueNameLen(PCFGMLEAF pCur);
VMMR3DECL(CFGMVALUETYPE) CFGMR3GetValueType(PCFGMLEAF pCur);
VMMR3DECL(bool) CFGMR3AreValuesValid(PCFGMNODE pNode, const char *pszzValid);
VMMR3DECL(int) CFGMR3ValidateConfig(PCFGMNODE pNode, const char *pszNode,
const char *pszValidValues, const char *pszValidNodes,
const char *pszWho, uint32_t uInstance);
/** @} */
/** @} */
#endif /* IN_RING3 */
RT_C_DECLS_END
/** @} */
#endif
| 6,131 |
758 | package com.clover_studio.spikachatmodule.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by ubuntu_ivo on 17.07.15..
*/
public class CustomTextView extends TextView{
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
}
| 296 |
1,425 | <reponame>amatiushkin/tinkerpop<gh_stars>1000+
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.language.grammar;
import org.antlr.v4.runtime.tree.ParseTree;
import org.apache.tinkerpop.gremlin.process.traversal.Scope;
/**
* Traversal enum parser parses all the enums like (e.g. {@link Scope} in graph traversal.
*/
public class TraversalEnumParser {
/**
* Parse enum text from a parse tree context into a enum object
* @param enumType : class of enum
* @param context : parse tree context
* @return enum object
*/
public static <E extends Enum<E>, C extends ParseTree> E parseTraversalEnumFromContext(final Class<E> enumType, final C context) {
final String text = context.getText();
final String className = enumType.getSimpleName();
// Support qualified class names like (ex: T.id or Scope.local)
if (text.startsWith(className)) {
final String strippedText = text.substring(className.length() + 1);
return E.valueOf(enumType, strippedText);
} else {
return E.valueOf(enumType, text);
}
}
}
| 613 |
381 | <filename>grouter/src/main/java/com/grouter/GRouter.java
package com.grouter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Wiki on 19/7/28.
*/
@SuppressWarnings({"unused", "UnusedReturnValue", "WeakerAccess"})
public abstract class GRouter {
private Map<String, HashMap<String, String>> schemeActivityMap = new HashMap<>();
private Map<String, HashMap<String, String>> schemeComponentMap = new HashMap<>();
private Map<String, HashMap<String, String>> schemeTaskMap = new HashMap<>();
private boolean isInit = false;
private String scheme;
/**
* 仅仅作为URI占位使用,在匹配路径是没有任何意义,匹配路径只用到scheme
*/
private String host;
private HashMap<String, String> activityMap = new HashMap<>();
private HashMap<String, String> componentMap = new HashMap<>();
private HashMap<String, String> taskMap = new HashMap<>();
List<GRouterInterceptor> interceptors = new ArrayList<>();
private static GRouter instance;
// private static boolean ignoreExported = false;
/**
* 获取GRouter实例,是的单Project项目会使用当前Project生成的GRouterInitializer,如果多Project就使用默认的。
*/
public static GRouter getInstance() {
if (instance == null) {
try {
Class clazz = Class.forName("com.grouter.GRouterInitializer");
instance = (GRouter) clazz.newInstance();
} catch (Exception e) {
instance = new DefaultMultiProjectGRouter();
Log.e("GRouter", "DefaultMultiProjectGRouter");
LoggerUtils.handleException(e);
}
}
return instance;
}
/**
* 建议在 Application.Create() 进行初始化,可以多次调用
*
* @param context Application
*/
public void init(@NonNull Context context, @Nullable String buildType, @Nullable Map<String, Object> params) {
this.isInit = true;
for (GRouterInterceptor interceptor : interceptors) {
interceptor.init(context, buildType, params);
}
}
public GRouter(String scheme, String host, HashMap<String, String> activityMap, HashMap<String, String> componentMap, HashMap<String, String> taskMap) {
if (TextUtils.isEmpty(scheme)) {
return;
}
this.scheme = scheme;
this.host = host;
this.schemeActivityMap.put(scheme, activityMap);
this.schemeComponentMap.put(scheme, componentMap);
this.schemeTaskMap.put(scheme, taskMap);
this.activityMap = activityMap;
this.componentMap = componentMap;
this.taskMap = taskMap;
}
/**
* 用于Activity 注入 RouterField 参数,可以独立使用
*/
public static void inject(Activity activity) {
RouterInject.inject(activity);
}
/**
* 通常是在 onNewIntent 调用,用于解析二级跳转
*/
public static void inject(Activity activity, Intent intent) {
RouterInject.inject(activity, intent);
}
/**
* 用于Fragment 注入 RouterField 参数,可以独立使用
*/
public static void inject(Fragment fragment) {
RouterInject.inject(fragment);
}
public static Serialization serialization;
/**
* 设置JSON序列化工具
*/
public static void setSerialization(Serialization serialization) {
GRouter.serialization = serialization;
}
static Serialization getSerialization() {
return serialization;
}
/**
* 添加拦截器
*/
public void addInterceptor(GRouterInterceptor interceptor) {
if (isInit) {
LoggerUtils.handleException(new Exception("Please add 'addInterceptor()' before 'init()'"));
}
boolean addInterceptor = false;
for (int i = 0; i < interceptors.size(); i++) {
if (interceptor.priority() > interceptors.get(i).priority()) {
interceptors.add(i, interceptor);
addInterceptor = true;
break;
}
}
if (!addInterceptor) {
interceptors.add(interceptor);
}
}
void addInterceptor(String className) {
try {
Class<?> cls = Class.forName(className);
addInterceptor((GRouterInterceptor) cls.newInstance());
} catch (Exception e) {
LoggerUtils.handleException(e);
}
}
/**
* 通过URL跳转页面。
*
* @param context Activity or Context
* @param url grouter://activity/user?uid=1
* @return 是否成功跳转
*/
public GActivityBuilder.Result startActivity(Context context, String url) {
try {
Uri uri = Uri.parse(url);
if (TextUtils.isEmpty(uri.getScheme())) {
throw new URISyntaxException(url, "URL lack scheme(eg: grouter://xxx/xxx)");
}
return activityBuilder(uri).start(context);
} catch (Exception e) {
LoggerUtils.handleException(e);
}
return new GActivityBuilder.Result(false);
}
public GActivityBuilder.Result startActivity(Activity activity, String url, @Nullable Bundle options) {
try {
Uri uri = Uri.parse(url);
if (TextUtils.isEmpty(uri.getScheme())) {
throw new URISyntaxException(url, "URL lack scheme(eg: grouter://xxx/xxx)");
}
return activityBuilder(uri).start(activity, options);
} catch (Exception e) {
LoggerUtils.handleException(e);
}
return new GActivityBuilder.Result(false);
}
public GActivityBuilder.Result startActivity(Fragment fragment, String url) {
return startActivity(fragment, url, null);
}
public GActivityBuilder.Result startActivity(Fragment fragment, String url, @Nullable Bundle options) {
try {
Uri uri = Uri.parse(url);
if (TextUtils.isEmpty(uri.getScheme())) {
throw new URISyntaxException(url, "URL lack scheme(eg: grouter://xxx/xxx)");
}
return activityBuilder(uri).start(fragment.getActivity());
} catch (Exception e) {
LoggerUtils.handleException(e);
}
return new GActivityBuilder.Result(false);
}
/**
* 通过URL跳转页面。
*
* @param activity Activity
* @param url grouter://activity/user?uid=1
* @param requestCode requestCode > 0
* @return 是否成功跳转
*/
public GActivityBuilder.Result startActivityForResult(Activity activity, String url, int requestCode) {
return startActivityForResult(activity, url, requestCode, null);
}
public GActivityBuilder.Result startActivityForResult(Activity activity, String url, int requestCode, @Nullable Bundle options) {
try {
Uri uri = Uri.parse(url);
if (TextUtils.isEmpty(uri.getScheme())) {
throw new URISyntaxException(url, "URL lack scheme(eg: grouter://xxx/xxx)");
}
return activityBuilder(uri).startForResult(activity, requestCode, options);
} catch (Exception e) {
LoggerUtils.handleException(e);
}
return new GActivityBuilder.Result(false);
}
/**
* 通过URL跳转页面。
*
* @param fragment Fragment
* @param url grouter://activity/user?uid=1
* @param requestCode requestCode > 0
* @return 是否成功跳转
*/
public GActivityBuilder.Result startActivityForResult(Fragment fragment, String url, int requestCode) {
return startActivityForResult(fragment, url, requestCode, null);
}
public GActivityBuilder.Result startActivityForResult(Fragment fragment, String url, int requestCode, @Nullable Bundle options) {
try {
Uri uri = Uri.parse(url);
if (TextUtils.isEmpty(uri.getScheme())) {
throw new URISyntaxException(url, "URL lack scheme(eg: grouter://xxx/xxx)");
}
return activityBuilder(uri).startForResult(fragment, requestCode, options);
} catch (Exception e) {
LoggerUtils.handleException(e);
}
return new GActivityBuilder.Result(false);
}
public String getHost() {
return host;
}
public String getScheme() {
return scheme;
}
/**
* 适用于多Project单scheme项目,跨Project调用。如果是当前Project建议使用GActivityCenter
*/
public GActivityBuilder activityBuilder(Uri uri) {
String cls = getActivityClassString(uri);
// 解析多级跳转
String nextNavString = uri.getQueryParameter("nextNav");
if (nextNavString != null && nextNavString.length() > 0) {
try {
Uri nextNavUri = Uri.parse(nextNavString);
if (TextUtils.isEmpty(nextNavUri.getScheme())) {
throw new URISyntaxException(nextNavString, "URL lack scheme(eg: grouter://xxx/xxx)");
}
return new GActivityBuilder(cls, uri).nextNav(activityBuilder(nextNavUri));
} catch (Exception e) {
LoggerUtils.handleException(e);
}
}
return new GActivityBuilder(cls, uri);
}
/**
* 适用于多Project单scheme项目,跨Project调用。如果是当前Project建议使用GActivityCenter
*/
public GActivityBuilder activityBuilder(String path) {
String cls = getActivityClassString(path);
if (cls != null) {
return new GActivityBuilder(cls);
}
Uri uri = new Uri.Builder().scheme(scheme).authority("activity").path(path).build();
return activityBuilder(uri);
}
/**
* 适用于多Project多scheme项目,跨Project调用。如果是当前Project建议使用GActivityCenter
*/
public GActivityBuilder activityBuilder(String scheme, String path) {
Uri uri = new Uri.Builder().scheme(scheme).authority("activity").path(path).build();
return activityBuilder(uri);
}
/**
* 用于多Project项目,用于在Project注册其他的Project生成的GRouter
*
* @param project 其他关联的Project的生成类
*/
public void registerMultiProject(GRouter project) {
if (isInit) {
throw new RuntimeException("registerMultiProject must be 'GRouter.getInstance().init(context)' before.");
}
if (!TextUtils.isEmpty(project.getScheme())) {
HashMap<String, String> tmp = schemeActivityMap.get(project.getScheme());
if (tmp == null) {
schemeActivityMap.put(project.getScheme(), project.activityMap);
} else {
tmp.putAll(project.activityMap);
}
}
if (!TextUtils.isEmpty(project.getScheme())) {
HashMap<String, String> tmp = schemeComponentMap.get(project.getScheme());
if (tmp == null) {
schemeComponentMap.put(project.getScheme(), project.componentMap);
} else {
tmp.putAll(project.componentMap);
}
}
if (!TextUtils.isEmpty(project.getScheme())) {
HashMap<String, String> tmp = schemeTaskMap.get(project.getScheme());
if (tmp == null) {
schemeTaskMap.put(project.getScheme(), project.taskMap);
} else {
tmp.putAll(project.taskMap);
}
}
if (schemeActivityMap.size() == 1) {
this.activityMap.putAll(project.activityMap);
this.componentMap.putAll(project.componentMap);
this.taskMap.putAll(project.taskMap);
}
for (GRouterInterceptor interceptor : project.interceptors) {
addInterceptor(interceptor);
}
}
private String getActivityClassString(Uri uri) {
HashMap<String, String> tmp = schemeActivityMap.get(uri.getScheme());
if (tmp == null) {
return null;
}
if (uri.getPath() != null && uri.getPath().length() > 0) {
return tmp.get(uri.getPath().substring(1));
}
return null;
}
private String getTaskClassString(Uri uri) {
HashMap<String, String> tmp = schemeTaskMap.get(uri.getScheme());
if (tmp == null) {
return null;
}
if (uri.getPath() != null && uri.getPath().length() > 0) {
return tmp.get(uri.getPath().substring(1));
}
return null;
}
String getActivityClassString(String path) {
if (path.startsWith("/")) {
path = path.substring(1);
}
return activityMap.get(path);
}
public String getComponentClassString(String path) {
if (path.startsWith("/")) {
path = path.substring(1);
}
if (schemeComponentMap.size() > 1 && path.contains("://")) {
Uri uri = Uri.parse(path);
HashMap<String, String> tmp = schemeComponentMap.get(uri.getScheme());
if (tmp != null && uri.getPath() != null && uri.getPath().length() > 0) {
String result = tmp.get(uri.getPath().substring(1));
if (result != null) {
return result;
}
}
}
return componentMap.get(path);
}
private String getTaskClassString(String path) {
if (path.startsWith("/")) {
path = path.substring(1);
}
if (schemeTaskMap.size() > 1 && path.contains("://")) {
Uri uri = Uri.parse(path);
HashMap<String, String> tmp = schemeTaskMap.get(uri.getScheme());
if (tmp != null && uri.getPath() != null && uri.getPath().length() > 0) {
String result = tmp.get(uri.getPath().substring(1));
if (result != null) {
return result;
}
}
}
return taskMap.get(path);
}
/**
* 用于RouterActivity传递对象参数的序列化和反序列化,
* GRouter不提供JSON序列化和反序列化工具,提供接口给开发者,可以使用FastJson或者GSON等JSON库适配。
*/
public interface Serialization {
String serialize(Object object);
<T> T deserializeObject(String json, Class<T> clazz);
<T> List<T> deserializeList(String json, Class<T> clazz);
}
/**
* 非下沉式组件间单Task服务获取,通过path获取Task实例。如果是当前Project建议使用GTaskCenter
*
* @param urlOrPath 如果是单scheme可以直接使用path访问,eg. GetUserInfo,
* 如果是多scheme跨Project访问需要scheme,eg. grouter://task/GetUserInfo or
* 或者带有参数请求,grouter://task/GetUserInfo?uid=1
* @return Task实例
*/
public GRouterTaskBuilder taskBuilder(String urlOrPath) {
Uri uri;
String clazzName;
if (urlOrPath.contains("://")) {
uri = Uri.parse(urlOrPath);
clazzName = getTaskClassString(uri);
} else {
uri = new Uri.Builder().scheme(scheme).authority("task").path(urlOrPath).build();
clazzName = getTaskClassString(urlOrPath);
}
return new GRouterTaskBuilder(clazzName, uri);
}
public GRouterTaskBuilder taskBuilder(String scheme, String path) {
Uri uri = new Uri.Builder().scheme(scheme).authority("task").path(path).build();
return taskBuilder(uri.toString());
}
/**
* 通过路径获取Component
*/
public Object getComponent(String path) {
String clazzName = getComponentClassString(path);
if (clazzName == null) {
return null;
}
return ComponentUtils.getInstance(Object.class, clazzName, null, null);
}
/**
* 传入协议名称
*/
public <T> T getComponent(String path, Class<T> protocol) {
String clazzName = getComponentClassString(path);
if (clazzName == null) {
return null;
}
return ComponentUtils.getInstance(protocol, clazzName, null, null);
}
}
| 7,694 |
3,508 | package com.fishercoder;
import com.fishercoder.solutions._1273;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class _1273Test {
private static _1273.Solution1 solution1;
private static int[] parent;
private static int[] value;
@BeforeClass
public static void setup() {
solution1 = new _1273.Solution1();
}
@Test
public void test1() {
parent = new int[]{-1, 0, 0, 1, 2, 2, 2};
value = new int[]{1, -2, 4, 0, -2, -1, -1};
assertEquals(2, solution1.deleteTreeNodes(7, parent, value));
}
@Test
public void test2() {
parent = new int[]{-1, 0, 0, 1, 2, 2, 2};
value = new int[]{1, -2, 3, 0, -2, -1, 0};
assertEquals(2, solution1.deleteTreeNodes(7, parent, value));
}
@Test
public void test3() {
parent = new int[]{-1, 0, 0, 1, 2, 2, 2};
value = new int[]{1, -2, 4, 0, -2, -1, -2};
assertEquals(6, solution1.deleteTreeNodes(7, parent, value));
}
@Test
public void test4() {
parent = new int[]{-1, 0, 0, 1, 2, 2, 2};
value = new int[]{3, -2, 4, 0, -2, -1, -2};
assertEquals(0, solution1.deleteTreeNodes(7, parent, value));
}
}
| 587 |
881 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from django.test import TestCase
from gcloud.tests import mock
from gcloud.tests.mock import MagicMock
from gcloud.utils.components import PluginServiceApiClient
from gcloud.utils.components import get_remote_plugin_name
GET_PAAS_PLUGIN_INFO = "gcloud.utils.components.PluginServiceApiClient.get_paas_plugin_info"
TEST_RESULT = {
"result": True,
"results": [{"code": "code1", "name": "name1"}, {"code": "code2", "name": "name2"}],
"count": 2,
}
TEST_LIMIT = 100
TEST_OFFSET = 0
class TestGetRemotePluginName(TestCase):
def test_call_success(self):
with mock.patch("gcloud.utils.components.env.USE_PLUGIN_SERVICE", "1"):
with mock.patch(GET_PAAS_PLUGIN_INFO, MagicMock(return_value=TEST_RESULT)):
plugin_info = get_remote_plugin_name(limit=TEST_LIMIT, offset=TEST_OFFSET)
PluginServiceApiClient.get_paas_plugin_info.assert_called_once_with(
search_term=None, environment="prod", limit=TEST_LIMIT, offset=TEST_OFFSET
)
self.assertEqual(plugin_info, {"code1": "name1", "code2": "name2"})
| 678 |
852 |
#include "CondFormats/RPCObjects/interface/LinkBoardSpec.h"
#include <sstream>
LinkBoardSpec::LinkBoardSpec(bool m, int l, int n) : theMaster(m), theLinkBoardNumInLink(l), theCode(n) {}
void LinkBoardSpec::add(const FebConnectorSpec& feb) { theFebs.push_back(feb); }
const FebConnectorSpec* LinkBoardSpec::feb(int febInputNum) const {
//FIXME - temporary implementaion, to be replace by LUT (in preparation)
typedef std::vector<FebConnectorSpec>::const_iterator IT;
for (IT it = theFebs.begin(); it != theFebs.end(); it++) {
if (febInputNum == it->linkBoardInputNum())
return &(*it);
}
return nullptr;
}
std::string LinkBoardSpec::linkBoardName() const {
std::ostringstream lbName;
std::string char1Val[2] = {"B", "E"}; // 1,2
std::string char2Val[3] = {"N", "M", "P"}; // 0,1,2
std::string char4Val[9] = {"0", "1", "2", "3", "A", "B", "C", "D", "E"}; // 0,...,8
int n3 = theCode % 10;
int num3 = (theCode % 100) / 10;
int n2 = (theCode % 1000) / 100;
int n1 = (theCode % 10000) / 1000;
int wheel = (theCode % 100000) / 10000;
if (n2 == 0)
wheel = -wheel;
int sector = theCode / 100000;
std::string sign = "";
if (wheel > 0)
sign = "+";
lbName << "LB_R" << char1Val[n1 - 1] << sign << wheel << "_S" << sector << "_" << char1Val[n1 - 1] << char2Val[n2]
<< num3 << char4Val[n3] << "_CH" << theLinkBoardNumInLink;
return lbName.str();
}
std::string LinkBoardSpec::print(int depth) const {
std::ostringstream str;
std::string type = (theMaster) ? "master" : "slave";
str << " LinkBoardSpec: " << std::endl
<< " --->" << type << " linkBoardNumInLink: " << theLinkBoardNumInLink << std::endl;
depth--;
if (depth >= 0) {
typedef std::vector<FebConnectorSpec>::const_iterator IT;
for (IT it = theFebs.begin(); it != theFebs.end(); it++)
str << (*it).print(depth);
}
return str.str();
}
| 811 |
8,649 | <gh_stars>1000+
package org.hswebframework.web.authorization.annotation;
import java.lang.annotation.*;
@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Dimension {
String type();
String[] id() default {};
Logical logical() default Logical.DEFAULT;
String[] description() default {};
boolean ignore() default false;
} | 132 |
14,668 | <reponame>zealoussnow/chromium<filename>chrome/updater/mac/signing/unbranded_config.py
# Copyright 2020 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.
from .build_props_config import BuildPropsCodeSignConfig
class UnbrandedCodeSignConfig(BuildPropsCodeSignConfig):
"""A CodeSignConfig used for signing non-official Updater builds."""
@property
def packaging_dir(self):
return 'Updater Packaging'
@property
def provisioning_profile_basename(self):
return None
| 192 |
1,755 | //============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
//============================================================================
#ifndef fides_datamodel_DataModelHelperFunctions_H
#define fides_datamodel_DataModelHelperFunctions_H
#include <fides/predefined/InternalMetadataSource.h>
#include <fides_rapidjson.h>
// clang-format off
#include FIDES_RAPIDJSON(rapidjson/document.h)
// clang-format on
#include <string>
namespace fides
{
namespace predefined
{
/// Set a string in a rapidjson::Value object
rapidjson::Value SetString(rapidjson::Document::AllocatorType& allocator, const std::string& str);
/// Creates DOM for an ArrayBasic
void CreateArrayBasic(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& dataSource,
const std::string& variable,
bool isStatic = false,
const std::string& arrayType = "basic",
const std::string& isVector = "");
/// Creates DOM for an ArrayCartesianProduct
void CreateArrayCartesianProduct(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
std::shared_ptr<InternalMetadataSource> source,
const std::string& dataSource);
/// Creates DOM for an ArrayXGCCoordinates
void CreateArrayXGCCoordinates(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& dataSource,
const std::string& variable);
/// Creates DOM for an ArrayXGCField
void CreateArrayXGCField(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& dataSource,
const std::string& variable);
/// Creates DOM for an ValueVariableDimensions
void CreateValueVariableDimensions(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& source,
const std::string& dataSource,
const std::string& variable);
/// Creates DOM for an ValueScalar
void CreateValueScalar(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& memberName,
const std::string& source,
const std::string& dataSource,
const std::string& variable);
/// Creates DOM for an ValueArray
void CreateValueArray(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
std::shared_ptr<InternalMetadataSource> source,
const std::string& attrName,
const std::string& memberName,
const std::string& dataSourceName);
void CreateValueArrayVariable(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& variableName,
const std::string& dataSourceName,
const std::string& memberName);
/// Creates DOM for an ValueArray when the vector is already known
template <typename ValueType>
inline void CreateValueArray(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& memberName,
std::vector<ValueType> values)
{
rapidjson::Value obj(rapidjson::kObjectType);
obj.AddMember("source", "array", allocator);
rapidjson::Value vals(rapidjson::kArrayType);
for (size_t i = 0; i < values.size(); ++i)
{
vals.PushBack(values[i], allocator);
}
obj.AddMember("values", vals, allocator);
auto name = SetString(allocator, memberName);
parent.AddMember(name, obj, allocator);
}
/// Creates DOM for ArrayUniformPointCoordinates
template <typename OriginType, typename SpacingType>
inline void CreateArrayUniformPointCoordinates(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& dimFieldName,
const std::vector<OriginType>& origin,
const std::vector<SpacingType>& spacing)
{
rapidjson::Value coordObj(rapidjson::kObjectType);
rapidjson::Value arrObj(rapidjson::kObjectType);
arrObj.AddMember("array_type", "uniform_point_coordinates", allocator);
CreateValueVariableDimensions(allocator, arrObj, "variable_dimensions", "source", dimFieldName);
CreateValueArray(allocator, arrObj, "origin", origin);
CreateValueArray(allocator, arrObj, "spacing", spacing);
coordObj.AddMember("array", arrObj, allocator);
parent.AddMember("coordinate_system", coordObj, allocator);
}
inline void CreateArrayUniformPointCoordinates(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& dimFieldName,
const std::string& originFieldName,
const std::string& spacingFieldName)
{
rapidjson::Value coordObj(rapidjson::kObjectType);
rapidjson::Value arrObj(rapidjson::kObjectType);
arrObj.AddMember("array_type", "uniform_point_coordinates", allocator);
CreateValueArrayVariable(allocator, arrObj, dimFieldName, "source", "dimensions");
CreateValueArrayVariable(allocator, arrObj, originFieldName, "source", "origin");
CreateValueArrayVariable(allocator, arrObj, spacingFieldName, "source", "spacing");
coordObj.AddMember("array", arrObj, allocator);
parent.AddMember("coordinate_system", coordObj, allocator);
}
inline void CreateArrayRectilinearPointCoordinates(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& xCoordsName,
const std::string& yCoordsName,
const std::string& zCoordsName)
{
rapidjson::Value coordObj(rapidjson::kObjectType);
rapidjson::Value arrObj(rapidjson::kObjectType);
arrObj.AddMember("array_type", "cartesian_product", allocator);
rapidjson::Value xcObj(rapidjson::kObjectType);
CreateArrayBasic(allocator, xcObj, "source", xCoordsName);
arrObj.AddMember("x_array", xcObj, allocator);
rapidjson::Value ycObj(rapidjson::kObjectType);
CreateArrayBasic(allocator, ycObj, "source", yCoordsName);
arrObj.AddMember("y_array", ycObj, allocator);
rapidjson::Value zcObj(rapidjson::kObjectType);
CreateArrayBasic(allocator, zcObj, "source", zCoordsName);
arrObj.AddMember("z_array", zcObj, allocator);
coordObj.AddMember("array", arrObj, allocator);
parent.AddMember("coordinate_system", coordObj, allocator);
}
inline void CreateArrayUnstructuredPointCoordinates(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& CoordsName)
{
rapidjson::Value coordObj(rapidjson::kObjectType);
rapidjson::Value arrObj(rapidjson::kObjectType);
arrObj.AddMember("array_type", "basic", allocator);
arrObj.AddMember("data_source", "source", allocator);
arrObj.AddMember("variable", SetString(allocator, CoordsName), allocator);
coordObj.AddMember("array", arrObj, allocator);
parent.AddMember("coordinate_system", coordObj, allocator);
}
inline void CreateStructuredCellset(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& dimFieldName)
{
rapidjson::Value csObj(rapidjson::kObjectType);
csObj.AddMember("cell_set_type", "structured", allocator);
CreateValueScalar(allocator, csObj, "dimensions", "array_variable", "source", dimFieldName);
parent.AddMember("cell_set", csObj, allocator);
}
inline void CreateUnstructuredSingleTypeCellset(rapidjson::Document::AllocatorType& allocator,
rapidjson::Value& parent,
const std::string& connectivityName,
const std::string& cellType)
{
rapidjson::Value cellSetObj(rapidjson::kObjectType);
cellSetObj.AddMember("cell_set_type", "single_type", allocator);
cellSetObj.AddMember("cell_type", SetString(allocator, cellType), allocator);
cellSetObj.AddMember("data_source", "source", allocator);
cellSetObj.AddMember("variable", SetString(allocator, connectivityName), allocator);
parent.AddMember("cell_set", cellSetObj, allocator);
}
/// Creates DOM for the underlying array for a wildcard field
/// that is being expanded
rapidjson::Document CreateFieldArrayDoc(const std::string& variable,
const std::string& source = "source",
const std::string& arrayType = "basic",
const std::string& isVector = "auto");
}
}
#endif
| 4,358 |
622 | #include "settings.h"
#if _DEBUG
std::string Settings::serverIP = "127.0.0.1"; //server ip
int Settings::serverPort = 1337; //server port
std::string Settings::fileName = "lilithDEBUG.exe"; //file name
std::string Settings::folderName = "lilithDEBUG folder"; //name of folder where file is located
std::string Settings::startupName = "lilithDEBUG startup"; //startup name in registry / taskmgr
std::string Settings::logFileName = "log.txt"; //name of log file
std::string Settings::installLocation = "APPDATA"; //install location (appdata, programdata etc)
std::string Settings::keylogPath = "keylog.txt"; //path of the keylog file
bool Settings::installSelf = false; //specifies whether the program should install itself
bool Settings::startOnNextBoot = false; //specifies whether it should startup the installed clone of itself NOW or ON THE NEXT BOOT (ONLY IMPORTANT FOR INSTALLATION PROCESS)
bool Settings::meltSelf = false; //specifies whether the installed clone should delete the initial file
bool Settings::setStartupSelf = false; //specifies whether the program is to be started on system boot
bool Settings::logEvents = true; //specifies whether the program should log events (like errors etc)
bool Settings::logKeys = false; //[EARLY STAGE, VERY RESOURCE-DEMANDING] //specifies whether the program should log the users keystrokes
#else
std::string Settings::serverIP = "sample.ip.net"; /*windistupdate.ddns.net*/ //server ip
int Settings::serverPort = 1337; //server port
std::string Settings::fileName = "lilithRELEASE.exe"; //file name
std::string Settings::folderName = "lilithRELEASE folder"; //name of folder where file is located
std::string Settings::startupName = "lilithRELEASE startup"; //startup name in registry / taskmgr
std::string Settings::logFileName = "log.txt"; //name of log file
std::string Settings::installLocation = "APPDATA"; //install location (appdata, programdata etc)
std::string Settings::keylogPath = "keylog.txt";
bool Settings::installSelf = true; //specifies whether the program should install itself
bool Settings::startOnNextBoot = false; //specifies whether it should startup the installed clone of itself NOW or ON THE NEXT BOOT (ONLY IMPORTANT FOR INSTALLATION PROCESS)
bool Settings::meltSelf = false; //specifies whether the installed clone should delete the initial file
bool Settings::setStartupSelf = true; //specifies whether the program is to be started on system boot
bool Settings::logEvents = true; //specifies whether the program should log events (like errors etc)
bool Settings::logKeys = false; //[EARLY STAGE, VERY RESOURCE-DEMANDING] //specifies whether the program should log the users keystrokes
#endif | 799 |
687 | import torch
import pytorch3d
from pytorch3d.ops import sample_points_from_meshes
from pytorch3d.io import load_objs_as_meshes, save_ply
import time
'''
you can use this code to sample ground-truth meshes
input_obj -> mesh to sample
output_ply -> sampled points and normals from input_obj
'''
device = torch.device('cpu')
num_samples = 75000
input_obj = '~/code/pc2mesh/data/test.obj'
output_ply = '~/code/pc2mesh/data/test.ply'
mesh = load_objs_as_meshes([input_obj], device=device)
xyz, normals = sample_points_from_meshes(mesh, num_samples=num_samples, return_normals=True)
save_ply(output_ply, verts=xyz[0, :], verts_normals=normals[0, :])
| 247 |
399 | <filename>library/common/extensions/retry/options/network_configuration/config.h
#pragma once
#include <string>
#include "envoy/upstream/retry.h"
#include "source/common/protobuf/message_validator_impl.h"
#include "library/common/extensions/retry/options/network_configuration/predicate.h"
#include "library/common/extensions/retry/options/network_configuration/predicate.pb.h"
#include "library/common/extensions/retry/options/network_configuration/predicate.pb.validate.h"
namespace Envoy {
namespace Extensions {
namespace Retry {
namespace Options {
class NetworkConfigurationRetryOptionsPredicateFactory
: public Upstream::RetryOptionsPredicateFactory {
public:
Upstream::RetryOptionsPredicateConstSharedPtr
createOptionsPredicate(const Protobuf::Message& config,
Upstream::RetryExtensionFactoryContext& context) override {
return std::make_shared<NetworkConfigurationRetryOptionsPredicate>(
MessageUtil::downcastAndValidate<
const envoymobile::extensions::retry::options::network_configuration::
NetworkConfigurationOptionsPredicate&>(
config, ProtobufMessage::getStrictValidationVisitor()),
context);
}
std::string name() const override {
return "envoy.retry_options_predicates.network_configuration";
}
ProtobufTypes::MessagePtr createEmptyConfigProto() override {
return std::make_unique<envoymobile::extensions::retry::options::network_configuration::
NetworkConfigurationOptionsPredicate>();
}
};
DECLARE_FACTORY(NetworkConfigurationRetryOptionsPredicateFactory);
} // namespace Options
} // namespace Retry
} // namespace Extensions
} // namespace Envoy
| 579 |
438 | {
"DESCRIPTION": "Stuur een uitnodigingslink zodat mensen mij aan hun server kunnen toevoegen.",
"USAGE": "uitnodigen",
"LINK": "🤖 [Nodig me uit op jouw server]({{LINK}} 'Je weet dat je wil')"
}
| 92 |
923 | package com.architjn.acjmusicplayer.task;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.afollestad.async.Action;
import com.architjn.acjmusicplayer.R;
import com.architjn.acjmusicplayer.utils.handlers.ArtistImgHandler;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Created by architjn on 18/12/15.
*/
public class FetchArtist {
private int random;
private ArtistImgHandler handler;
private String url;
private Context context;
private String name;
private String jsonResult;
private Bitmap downloadedImg;
public FetchArtist(Context context, String name, int random, ArtistImgHandler handler) {
this.context = context;
this.name = name;
this.context = context;
this.name = name;
this.random = random;
this.handler = handler;
if (name == null || name.matches("<unknown>")) {
} else {
StringBuilder builder = new StringBuilder();
builder.append(context.getResources().getString(R.string.artist_fetch_url));
try {
builder.append("&artist=" + URLEncoder.encode(name, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
builder.append("&api_key=" + context.getResources().getString(R.string.api));
builder.append("&format=json");
this.url = builder.toString();
runTask();
}
}
public void runTask() {
new Action<String>() {
@NonNull
@Override
public String id() {
return name; //some unique Id
}
@Nullable
@Override
protected String run() throws InterruptedException {
backgroundTask();
return null;
}
@Override
protected void done(@Nullable String result) {
}
}.execute();
}
private void backgroundTask() {
List<NameValuePair> params = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent())
.toString();
if (jsonResult != null) {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray imageArray = jsonResponse.getJSONObject("artist").getJSONArray("image");
for (int i = 0; i < imageArray.length(); i++) {
JSONObject image = imageArray.getJSONObject(i);
if (image.optString("size").matches("large") &&
!image.optString("#text").matches("")) {
downloadedImg = downloadBitmap(image.optString("#text"));
String newUrl = saveImageToStorage(downloadedImg);
handler.updateArtistArtWorkInDB(name, newUrl);
handler.onDownloadComplete(newUrl);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (ClientProtocolException e) {
Log.e("e", "error1");
e.printStackTrace();
} catch (IOException e) {
Log.e("e", "error2");
e.printStackTrace();
}
}
private String saveImageToStorage(Bitmap bitmap) {
StringBuilder fileName = new StringBuilder();
fileName.append("cache-img-");
Calendar c = Calendar.getInstance();
fileName.append(c.get(Calendar.DATE)).append("-");
fileName.append(c.get(Calendar.MONTH)).append("-");
fileName.append(c.get(Calendar.YEAR)).append("-");
fileName.append(c.get(Calendar.HOUR)).append("-");
fileName.append(c.get(Calendar.MINUTE)).append("-");
fileName.append(c.get(Calendar.SECOND)).append("-");
fileName.append(random).append("-");
fileName.append((random / 3) * 5);
fileName.append(".png");
File sdCardDirectory = Environment.getExternalStorageDirectory();
String filePath = sdCardDirectory + "/" + context.getResources()
.getString(R.string.app_name) + "/artist/";
(new File(filePath)).mkdirs();
File noMedia = new File(filePath, ".nomedia");
if (!noMedia.exists()) try {
noMedia.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
File image = new File(filePath, fileName.toString());
if (image.exists()) image.delete();
try {
FileOutputStream out = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
return image.getPath();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
//forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
| 3,861 |
923 | <gh_stars>100-1000
// Ouzel by <NAME>
#ifndef OUZEL_GRAPHICS_RENDERTARGET_HPP
#define OUZEL_GRAPHICS_RENDERTARGET_HPP
#include <memory>
#include <vector>
#include "RenderDevice.hpp"
#include "../math/Color.hpp"
#include "../math/Size.hpp"
namespace ouzel::graphics
{
class Graphics;
class Texture;
class RenderTarget final
{
public:
RenderTarget() = default;
RenderTarget(Graphics& initGraphics,
const std::vector<Texture*>& initColorTextures,
Texture* initDepthTexture);
auto& getResource() const noexcept { return resource; }
auto& getColorTextures() const noexcept { return colorTextures; }
auto getDepthTexture() const noexcept { return depthTexture; }
private:
RenderDevice::Resource resource;
std::vector<Texture*> colorTextures;
Texture* depthTexture = nullptr;
};
}
#endif // OUZEL_GRAPHICS_RENDERTARGET_HPP
| 387 |
3,428 | {"id":"00408","group":"easy-ham-1","checksum":{"type":"MD5","value":"d52d0dde484c37acb79bfdc18d4a2aa9"},"text":"From <EMAIL> Tue Sep 3 18:04:36 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 39FBF16F56\n\tfor <jm@localhost>; Tue, 3 Sep 2002 18:04:36 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Tue, 03 Sep 2002 18:04:36 +0100 (IST)\nReceived: from webnote.net (mail.webnote.net [193.120.211.219]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g83H0wZ28126 for\n <<EMAIL>>; Tue, 3 Sep 2002 18:01:04 +0100\nReceived: from xent.com ([172.16.58.3]) by webnote.net (8.9.3/8.9.3)\n with ESMTP id SAA02554 for <<EMAIL>>; Tue, 3 Sep 2002 18:01:14 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id 9FC4D2940E8; Tue, 3 Sep 2002 09:53:02 -0700 (PDT)\nDelivered-To: <EMAIL>\nReceived: from mail.datastore.ca (unknown [207.61.5.2]) by xent.com\n (Postfix) with ESMTP id 68F07294099 for <<EMAIL>>; Tue,\n 3 Sep 2002 09:52:12 -0700 (PDT)\nReceived: from maya.dyndns.org [207.61.5.143] by mail.datastore.ca\n (SMTPD32-7.00) id A982B010040; Tue, 03 Sep 2002 12:55:30 -0400\nReceived: by maya.dyndns.org (Postfix, from userid 501) id 02C1F1C327;\n Tue, 3 Sep 2002 12:53:58 -0400 (EDT)\nTo: \"<NAME>\" <<EMAIL>>\nCc: <EMAIL>\nSubject: Re: Signers weren't angry young men (was: Java is for kiddies)\nReferences: <<EMAIL>cql<EMAIL>>\nFrom: <NAME> <<EMAIL>>\nX-Home-Page: http://www.teledyn.com\nOrganization: TCI Business Innovation through Open Source Computing\nMessage-Id: <<EMAIL>>\nReply-To: <NAME> <<EMAIL>>\nX-Url: http://www.teledyn.com/\nMIME-Version: 1.0\nContent-Type: text/plain; charset=us-ascii\nSender: fork-admin@x<EMAIL>.com\nErrors-To: [email protected]\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of Roh<NAME> <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: 03 Sep 2002 12:53:58 -0400\n\n\nI stand corrected --- I'd thought I'd seen a display there listing in\nthe Ben Franklin museum which showed them as ranging in age from 19 to\njust over 30 for the oldest, most in their early twenties.\n\n-- \n<NAME> <<EMAIL>> TeleDynamics Communications Inc\n Business Advantage through Community Software : http://www.teledyn.com\n\"Computers are useless. They can only give you answers.\"(Pablo Picasso)\n\n\n"} | 1,181 |
4,640 | /*
* 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.
*/
/*!
* \file tvm/arith/constraint_extract.cc
*/
#include "constraint_extract.h"
#include <tvm/arith/analyzer.h>
#include <tvm/tir/expr.h>
#include "pattern_match.h"
namespace tvm {
namespace arith {
void CollectConstraints(const PrimExpr& expr, Analyzer* analyzer, std::vector<PrimExpr>* collect) {
collect->push_back(expr);
PVar<PrimExpr> x, y;
if ((x && y).Match(expr)) {
CollectConstraints(x.Eval(), analyzer, collect);
CollectConstraints(y.Eval(), analyzer, collect);
} else if ((!(x || y)).Match(expr)) {
CollectConstraints(analyzer->rewrite_simplify(tir::Not(x.Eval())), analyzer, collect);
CollectConstraints(analyzer->rewrite_simplify(tir::Not(y.Eval())), analyzer, collect);
}
}
std::vector<PrimExpr> ExtractConstraints(const PrimExpr& expr) {
std::vector<PrimExpr> out;
Analyzer analyzer;
CollectConstraints(expr, &analyzer, &out);
return out;
}
} // namespace arith
} // namespace tvm
| 567 |
3,857 | /**
* Tencent is pleased to support the open source community by making QMUI_iOS available.
* Copyright (C) 2016-2021 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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.
*/
//
// QMUINavigationBarScrollingAnimator.h
// QMUIKit
//
// Created by QMUI Team on 2018/O/16.
//
#import "QMUIScrollAnimator.h"
NS_ASSUME_NONNULL_BEGIN
/**
实现通过界面上的 UIScrollView 滚动来控制顶部导航栏外观的类,导航栏外观会跟随滚动距离的变化而变化。
使用方式:
1. 用 init 方法初始化。
2. 通过 scrollView 属性关联一个 UIScrollView。
3. 修改 offsetYToStartAnimation 调整动画触发的滚动位置。
4. 修改 distanceToStopAnimation 调整动画触发后滚动多久到达终点。
@note 注意,由于在同个 UINavigationController 里的所有 viewController 的 navigationBar 都是共享的,所以如果修改了 navigationBar 的样式,需要自行处理界面切换时 navigationBar 的样式恢复。
@note 注意,为了性能考虑,在 progress 达到 0 后再往上滚,或者 progress 达到 1 后再往下滚,都不会再触发那一系列 animationBlock。
*/
@interface QMUINavigationBarScrollingAnimator : QMUIScrollAnimator
/// 指定要关联的 UINavigationBar,若不指定,会自动寻找当前 App 可视界面上的 navigationBar
@property(nullable, nonatomic, weak) UINavigationBar *navigationBar;
/**
contentOffset.y 到达哪个值即开始动画,默认为 0
@note 注意,如果 adjustsOffsetYWithInsetTopAutomatically 为 YES,则实际计算时的值为 (-contentInset.top + offsetYToStartAnimation),这时候 offsetYToStartAnimation = 0 则表示在列表默认的停靠位置往下拉就会触发临界点。
*/
@property(nonatomic, assign) CGFloat offsetYToStartAnimation;
/// 控制从 offsetYToStartAnimation 开始,要滚动多长的距离就打到动画结束的位置,默认为 44
@property(nonatomic, assign) CGFloat distanceToStopAnimation;
/// 传给 offsetYToStartAnimation 的值是否要自动叠加上 -contentInset.top,默认为 YES。
@property(nonatomic, assign) BOOL adjustsOffsetYWithInsetTopAutomatically;
/// 当前滚动位置对应的进度
@property(nonatomic, assign, readonly) float progress;
/**
如果为 NO,则当 progress 的值不再变化(例如达到 0 后继续往上滚动,或者达到 1 后继续往下滚动)时,就不会再触发动画,从而提升性能。
如果为 YES,则任何时候只要有滚动产生,动画就会被触发,适合运用到类似 Plain Style 的 UITableView 里在滚动时也要适配停靠的 sectionHeader 的场景(因为需要不断计算当前正在停靠的 sectionHeader 是哪一个)。
默认为 NO
*/
@property(nonatomic, assign) BOOL continuous;
/**
用于控制不同滚动位置下的表现,总的动画 block,如果定义了这个,则滚动时不会再调用后面那几个 block
@param animator 当前的 animator 对象
@param progress 当前滚动位置处于 offsetYToStartAnimation 到 (offsetYToStartAnimation + distanceToStopAnimation) 之间的哪个进度
*/
@property(nullable, nonatomic, copy) void (^animationBlock)(QMUINavigationBarScrollingAnimator * _Nonnull animator, float progress);
/**
返回不同滚动位置下对应的背景图
@param animator 当前的 animator 对象
@param progress 当前滚动位置处于 offsetYToStartAnimation 到 (offsetYToStartAnimation + distanceToStopAnimation) 之间的哪个进度
*/
@property(nullable, nonatomic, copy) UIImage * (^backgroundImageBlock)(QMUINavigationBarScrollingAnimator * _Nonnull animator, float progress);
/**
返回不同滚动位置下对应的导航栏底部分隔线的图片
@param animator 当前的 animator 对象
@param progress 当前滚动位置处于 offsetYToStartAnimation 到 (offsetYToStartAnimation + distanceToStopAnimation) 之间的哪个进度
*/
@property(nullable, nonatomic, copy) UIImage * (^shadowImageBlock)(QMUINavigationBarScrollingAnimator * _Nonnull animator, float progress);
/**
返回不同滚动位置下对应的导航栏的 tintColor
@param animator 当前的 animator 对象
@param progress 当前滚动位置处于 offsetYToStartAnimation 到 (offsetYToStartAnimation + distanceToStopAnimation) 之间的哪个进度
*/
@property(nullable, nonatomic, copy) UIColor * (^tintColorBlock)(QMUINavigationBarScrollingAnimator * _Nonnull animator, float progress);
/**
返回不同滚动位置下对应的导航栏的 titleView tintColor,注意只能对使用了 navigationItem.titleView 生效(QMUICommonViewController 的子类默认用了 QMUINavigationTitleView,所以也可以生效)。
@param animator 当前的 animator 对象
@param progress 当前滚动位置处于 offsetYToStartAnimation 到 (offsetYToStartAnimation + distanceToStopAnimation) 之间的哪个进度
*/
@property(nullable, nonatomic, copy) UIColor * (^titleViewTintColorBlock)(QMUINavigationBarScrollingAnimator * _Nonnull animator, float progress);
/**
返回不同滚动位置下对应的状态栏样式
@param animator 当前的 animator 对象
@param progress 当前滚动位置处于 offsetYToStartAnimation 到 (offsetYToStartAnimation + distanceToStopAnimation) 之间的哪个进度
@warning 需在项目的 Info.plist 文件内设置字段 “View controller-based status bar appearance” 的值为 NO 才能生效,如果不设置,或者值为 YES,则请自行通过系统提供的 - preferredStatusBarStyle 方法来实现,statusbarStyleBlock 无效
*/
@property(nullable, nonatomic, copy) UIStatusBarStyle (^statusbarStyleBlock)(QMUINavigationBarScrollingAnimator * _Nonnull animator, float progress);
/**
返回不同滚动位置下对应的导航栏的 barTintColor
@param animator 当前的 animator 对象
@param progress 当前滚动位置处于 offsetYToStartAnimation 到 (offsetYToStartAnimation + distanceToStopAnimation) 之间的哪个进度
*/
@property(nonatomic, copy) UIColor * (^barTintColorBlock)(QMUINavigationBarScrollingAnimator * _Nonnull animator, float progress);
@end
NS_ASSUME_NONNULL_END
| 3,003 |
889 | <gh_stars>100-1000
import PIL
import torch.nn.functional as F
import torch
from collections.abc import Sequence, Iterable
import warnings
from torchvision.transforms import functional as F
class CropResizeTransform(object):
"""Crop the image to min(h,w) then resize it
Args:
size (sequence or int): Desired output size. If size is a sequence like
(h, w), output size will be matched to this. If size is an int,
smaller edge of the image will be matched to this number.
i.e, if height > width, then image will be rescaled to
(size * height / width, size)
interpolation (int, optional): Desired interpolation. Default is
``PIL.Image.BILINEAR``
"""
def __init__(self, size, interpolation=PIL.Image.BILINEAR):
self.size = size
self.interpolation = interpolation
def __call__(self, img):
"""
Args:
img (PIL Image): Image to be scaled.
Returns:
PIL Image: Rescaled image.
"""
width, height = img.size
h, w = self.size
v_scale = height / h
h_scale = width / w
scale = min(h_scale, v_scale)
min_size = [scale * h, scale * w]
img = F.center_crop(img, min_size)
return F.resize(img, self.size, self.interpolation)
def __repr__(self):
interpolate_str = _pil_interpolation_to_str[self.interpolation]
return self.__class__.__name__ + '(size={0}, interpolation={1})'.format(self.size, interpolate_str)
| 648 |
1,822 | // Copyright (C) 2014 <NAME>
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <hpx/local/future.hpp>
#include <hpx/local/init.hpp>
#include <hpx/modules/testing.hpp>
#include <chrono>
#include <functional>
int global;
int& foo()
{
return global;
}
void test_make_ready_future()
{
hpx::future<int&> f = hpx::make_ready_future(std::ref(global));
HPX_TEST_EQ(&f.get(), &global);
hpx::future<int&> f_at = hpx::make_ready_future_at(
std::chrono::system_clock::now() + std::chrono::seconds(1),
std::ref(global));
HPX_TEST_EQ(&f_at.get(), &global);
hpx::future<int&> f_after =
hpx::make_ready_future_after(std::chrono::seconds(1), std::ref(global));
HPX_TEST_EQ(&f_after.get(), &global);
}
void test_async()
{
hpx::future<int&> f = hpx::async(&foo);
HPX_TEST_EQ(&f.get(), &global);
hpx::future<int&> f_sync = hpx::async(hpx::launch::sync, &foo);
HPX_TEST_EQ(&f_sync.get(), &global);
}
int hpx_main()
{
test_make_ready_future();
test_async();
return hpx::local::finalize();
}
int main(int argc, char* argv[])
{
HPX_TEST_EQ_MSG(hpx::local::init(hpx_main, argc, argv), 0,
"HPX main exited with non-zero status");
return hpx::util::report_errors();
}
| 630 |
1,738 | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <AzToolsFramework/ToolsComponents/EditorComponentBase.h>
#include <AzToolsFramework/ToolsComponents/EditorVisibilityBus.h>
#include <AzFramework/Entity/EntityDebugDisplayBus.h>
#include <AzCore/Component/TransformBus.h>
#include <AzCore/Component/TickBus.h>
#include <LegacyEntityConversion/LegacyEntityConversionBus.h>
#include "Lightning/LightningComponentBus.h"
#include "LightningComponent.h"
namespace Lightning
{
class LightningConverter;
class EditorLightningComponent;
/**
* Editor side of the Lightning Configuration
*/
class EditorLightningConfiguration
: public LightningConfiguration
{
public:
AZ_TYPE_INFO_LEGACY(EditorLightningConfiguration, "{7D8B140F-D2C9-573A-94CE-A7884079BF09}", LightningConfiguration);
AZ_CLASS_ALLOCATOR(EditorLightningConfiguration, AZ::SystemAllocator,0);
static void Reflect(AZ::ReflectContext* context);
};
/**
* Editor side of the Lightning Component
*/
class EditorLightningComponent
: public AzToolsFramework::Components::EditorComponentBase
, public LightningComponentRequestBus::Handler
{
friend class LightningConverter;
public:
AZ_COMPONENT(EditorLightningComponent, "{50FDA3BF-3B84-4EF5-BB87-00C17AC963D7}", AzToolsFramework::Components::EditorComponentBase);
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides);
static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible);
static void Reflect(AZ::ReflectContext* context);
~EditorLightningComponent() = default;
// LightningComponentRequestBus implementation
void StartEffect() {/*Do nothing for the editor impl*/}
void SetStartOnActivate(bool startOnActivate) override { m_config.m_startOnActivate = startOnActivate; }
bool GetStartOnActivate() override { return m_config.m_startOnActivate; }
void SetRelativeToPlayer(bool relativeToPlayer) override { m_config.m_relativeToPlayer = relativeToPlayer; }
bool GetRelativeToPlayer() override { return m_config.m_relativeToPlayer; }
void SetLightningParticleEntity(AZ::EntityId particleEntity) override { m_config.m_lightningParticleEntity = particleEntity; }
AZ::EntityId GetLightningParticleEntity() override { return m_config.m_lightningParticleEntity; }
void SetLightEntity(AZ::EntityId lightEntity) override { m_config.m_lightEntity = lightEntity; }
AZ::EntityId GetLightEntity() override { return m_config.m_lightEntity; }
void SetSkyHighlightEntity(AZ::EntityId skyHighlightEntity) override { m_config.m_skyHighlightEntity = skyHighlightEntity; }
AZ::EntityId GetSkyHighlightEntity() override { return m_config.m_skyHighlightEntity; }
void SetAudioEntity(AZ::EntityId audioEntity) override { m_config.m_audioThunderEntity = audioEntity; }
AZ::EntityId GetAudioEntity() override { return m_config.m_audioThunderEntity; }
void SetSpeedOfSoundScale(float speedOfSoundScale) override { m_config.m_speedOfSoundScale = speedOfSoundScale; }
float GetSpeedOfSoundScale() override { return m_config.m_speedOfSoundScale; }
void SetLightRadiusVariation(float lightRadiusVariation) override { m_config.m_lightRadiusVariation = lightRadiusVariation; }
float GetLightRadiusVariation() override { return m_config.m_lightRadiusVariation; }
void SetLightIntensityVariation(float lightIntensityVariation) override { m_config.m_lightIntensityVariation = lightIntensityVariation; }
float GetLightIntensityVariation() override { return m_config.m_lightIntensityVariation; }
void SetParticleSizeVariation(float particleSizeVariation) override { m_config.m_particleSizeVariation = particleSizeVariation; }
float GetParticleSizeVariation() override { return m_config.m_particleSizeVariation; }
void SetLightningDuration(double lightningDuration) override { m_config.m_lightningDuration = lightningDuration; }
double GetLightningDuration() override { return m_config.m_lightningDuration; }
void BuildGameEntity(AZ::Entity* gameEntity);
protected:
EditorLightningConfiguration m_config; ///< Serialized configuration for the component
};
/**
* Converter for legacy lightning entities
*
* Technically lightning entities don't directly convert to Lightning components
* but this seemed like the right place to keep this converter. Instead lightning
* entities are broken up into a series of components to be more modular.
*/
class LightningConverter : public AZ::LegacyConversion::LegacyConversionEventBus::Handler
{
public:
AZ_CLASS_ALLOCATOR(LightningConverter, AZ::SystemAllocator, 0);
LightningConverter() {}
// ------------------- LegacyConversionEventBus::Handler -----------------------------
AZ::LegacyConversion::LegacyConversionResult ConvertEntity(CBaseObject* pEntityToConvert) override;
bool BeforeConversionBegins() override;
bool AfterConversionEnds() override;
// END ----------------LegacyConversionEventBus::Handler ------------------------------
};
} // namespace Lightning
| 1,904 |
1,020 | <reponame>icse18-refactorings/RoboBinding
package org.robobinding.widget.adapterview;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.robobinding.attribute.Attributes.aValueModelAttribute;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.robobinding.BindingContext;
import org.robobinding.ItemBindingContext;
/**
*
* @since 1.0
* @version $Revision: 1.0 $
* @author <NAME>
*/
@RunWith(MockitoJUnitRunner.class)
public class SourceAttributeTest {
private final String attributeValue = "{property_name}";
private final String propertyName = "property_name";
@Mock
private DataSetAdapterBuilder dataSetAdapterBuilder;
@Mock
private BindingContext bindingContext;
@Mock
private ItemBindingContext itemBindingContext;
@Test
public void whenBinding_thenSetDataSetValueModelOnDataSetAdapterBuilder() {
when(bindingContext.navigateToItemContext(propertyName)).thenReturn(itemBindingContext);
SourceAttribute sourceAttribute = new SourceAttribute(dataSetAdapterBuilder);
sourceAttribute.setAttribute(aValueModelAttribute(attributeValue));
sourceAttribute.bindTo(bindingContext);
verify(dataSetAdapterBuilder).setBindingContext(itemBindingContext);
}
}
| 452 |
726 | <reponame>Diffblue-benchmarks/Landy8530-DesignPatterns
package org.landy.singleton.lazy;
/**
* //懒汉式单例
//特点:在外部类被调用的时候内部类才会被加载
//内部类一定是要在方法调用之前初始化
//巧妙地避免了线程安全问题
//这种形式兼顾饿汉式的内存浪费,也兼顾synchronized性能问题
//完美地屏蔽了这两个缺点
//史上最牛B的单例模式的实现方式
* Created by Landy on 2018/8/20.
*/
public class LazyThree {
//如果去掉static,就可以被反射强制访问,调用两次了
private static boolean initialized = false;
//防止反射注入
//默认使用LazyThree的时候,会先初始化内部类
//如果没使用的话,内部类是不加载的
private LazyThree(){
synchronized (LazyThree.class){
if(initialized == false){
initialized = !initialized;
}else{
throw new RuntimeException("单例已被侵犯");
}
}
}
//每一个关键字都不是多余的
//static 是为了使单例的空间共享
//final 保证这个方法不会被重写,重载
public static final LazyThree getInstance(){
//在返回结果以前,一定会先加载内部类
return LazyHolder.LAZY;
}
//默认不加载
private static class LazyHolder{
private static final LazyThree LAZY = new LazyThree();
}
}
| 848 |
711 | <gh_stars>100-1000
package com.java110.intf.store;
import com.java110.config.feign.FeignConfiguration;
import com.java110.dto.contractTypeSpec.ContractTypeSpecDto;
import com.java110.po.contractTypeSpec.ContractTypeSpecPo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
/**
* @ClassName IContractTypeSpecInnerServiceSMO
* @Description 合同类型规格接口类
* @Author wuxw
* @Date 2019/4/24 9:04
* @Version 1.0
* add by wuxw 2019/4/24
**/
@FeignClient(name = "store-service", configuration = {FeignConfiguration.class})
@RequestMapping("/contractTypeSpecApi")
public interface IContractTypeSpecInnerServiceSMO {
@RequestMapping(value = "/saveContractTypeSpec", method = RequestMethod.POST)
public int saveContractTypeSpec(@RequestBody ContractTypeSpecPo contractTypeSpecPo);
@RequestMapping(value = "/updateContractTypeSpec", method = RequestMethod.POST)
public int updateContractTypeSpec(@RequestBody ContractTypeSpecPo contractTypeSpecPo);
@RequestMapping(value = "/deleteContractTypeSpec", method = RequestMethod.POST)
public int deleteContractTypeSpec(@RequestBody ContractTypeSpecPo contractTypeSpecPo);
/**
* <p>查询小区楼信息</p>
*
* @param contractTypeSpecDto 数据对象分享
* @return ContractTypeSpecDto 对象数据
*/
@RequestMapping(value = "/queryContractTypeSpecs", method = RequestMethod.POST)
List<ContractTypeSpecDto> queryContractTypeSpecs(@RequestBody ContractTypeSpecDto contractTypeSpecDto);
/**
* 查询<p>小区楼</p>总记录数
*
* @param contractTypeSpecDto 数据对象分享
* @return 小区下的小区楼记录数
*/
@RequestMapping(value = "/queryContractTypeSpecsCount", method = RequestMethod.POST)
int queryContractTypeSpecsCount(@RequestBody ContractTypeSpecDto contractTypeSpecDto);
}
| 747 |
1,418 | package aima.core.probability.bayes.exact;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import aima.core.probability.CategoricalDistribution;
import aima.core.probability.RandomVariable;
import aima.core.probability.bayes.BayesInference;
import aima.core.probability.bayes.BayesianNetwork;
import aima.core.probability.bayes.FiniteNode;
import aima.core.probability.bayes.Node;
import aima.core.probability.domain.FiniteDomain;
import aima.core.probability.proposition.AssignmentProposition;
import aima.core.probability.util.ProbabilityTable;
import aima.core.util.Util;
/**
* Artificial Intelligence A Modern Approach (3rd Edition): Figure 14.9, page
* 525.<br>
* <br>
*
* <pre>
* function ENUMERATION-ASK(X, e, bn) returns a distribution over X
* inputs: X, the query variable
* e, observed values for variables E
* bn, a Bayes net with variables {X} ∪ E ∪ Y /* Y = hidden variables //
*
* Q(X) <- a distribution over X, initially empty
* for each value x<sub>i</sub> of X do
* Q(x<sub>i</sub>) <- ENUMERATE-ALL(bn.VARS, e<sub>x<sub>i</sub></sub>)
* where e<sub>x<sub>i</sub></sub> is e extended with X = x<sub>i</sub>
* return NORMALIZE(Q(X))
*
* ---------------------------------------------------------------------------------------------------
*
* function ENUMERATE-ALL(vars, e) returns a real number
* if EMPTY?(vars) then return 1.0
* Y <- FIRST(vars)
* if Y has value y in e
* then return P(y | parents(Y)) * ENUMERATE-ALL(REST(vars), e)
* else return ∑<sub>y</sub> P(y | parents(Y)) * ENUMERATE-ALL(REST(vars), e<sub>y</sub>)
* where e<sub>y</sub> is e extended with Y = y
* </pre>
*
* Figure 14.9 The enumeration algorithm for answering queries on Bayesian
* networks. <br>
* <br>
* <b>Note:</b> The implementation has been extended to handle queries with
* multiple variables. <br>
*
* @author <NAME>
*/
public class EnumerationAsk implements BayesInference {
public EnumerationAsk() {
}
// function ENUMERATION-ASK(X, e, bn) returns a distribution over X
/**
* The ENUMERATION-ASK algorithm in Figure 14.9 evaluates expression trees
* (Figure 14.8) using depth-first recursion.
*
* @param X
* the query variables.
* @param observedEvidence
* observed values for variables E.
* @param bn
* a Bayes net with variables {X} ∪ E ∪ Y /* Y = hidden
* variables //
* @return a distribution over the query variables.
*/
public CategoricalDistribution enumerationAsk(final RandomVariable[] X,
final AssignmentProposition[] observedEvidence,
final BayesianNetwork bn) {
// Q(X) <- a distribution over X, initially empty
final ProbabilityTable Q = new ProbabilityTable(X);
final ObservedEvidence e = new ObservedEvidence(X, observedEvidence, bn);
// for each value x<sub>i</sub> of X do
ProbabilityTable.Iterator di = new ProbabilityTable.Iterator() {
int cnt = 0;
/**
* <pre>
* Q(x<sub>i</sub>) <- ENUMERATE-ALL(bn.VARS, e<sub>x<sub>i</sub></sub>)
* where e<sub>x<sub>i</sub></sub> is e extended with X = x<sub>i</sub>
* </pre>
*/
public void iterate(Map<RandomVariable, Object> possibleWorld,
double probability) {
for (int i = 0; i < X.length; i++) {
e.setExtendedValue(X[i], possibleWorld.get(X[i]));
}
Q.setValue(cnt,
enumerateAll(bn.getVariablesInTopologicalOrder(), e));
cnt++;
}
};
Q.iterateOverTable(di);
// return NORMALIZE(Q(X))
return Q.normalize();
}
//
// START-BayesInference
public CategoricalDistribution ask(final RandomVariable[] X,
final AssignmentProposition[] observedEvidence,
final BayesianNetwork bn) {
return this.enumerationAsk(X, observedEvidence, bn);
}
// END-BayesInference
//
//
// PROTECTED METHODS
//
// function ENUMERATE-ALL(vars, e) returns a real number
protected double enumerateAll(List<RandomVariable> vars, ObservedEvidence e) {
// if EMPTY?(vars) then return 1.0
if (0 == vars.size()) {
return 1;
}
// Y <- FIRST(vars)
RandomVariable Y = Util.first(vars);
// if Y has value y in e
if (e.containsValue(Y)) {
// then return P(y | parents(Y)) * ENUMERATE-ALL(REST(vars), e)
return e.posteriorForParents(Y) * enumerateAll(Util.rest(vars), e);
}
/**
* <pre>
* else return ∑<sub>y</sub> P(y | parents(Y)) * ENUMERATE-ALL(REST(vars), e<sub>y</sub>)
* where e<sub>y</sub> is e extended with Y = y
* </pre>
*/
double sum = 0;
for (Object y : ((FiniteDomain) Y.getDomain()).getPossibleValues()) {
e.setExtendedValue(Y, y);
sum += e.posteriorForParents(Y) * enumerateAll(Util.rest(vars), e);
}
return sum;
}
protected class ObservedEvidence {
private BayesianNetwork bn = null;
private Object[] extendedValues = null;
private int hiddenStart = 0;
private int extendedIdx = 0;
private RandomVariable[] var = null;
private Map<RandomVariable, Integer> varIdxs = new HashMap<RandomVariable, Integer>();
public ObservedEvidence(RandomVariable[] queryVariables,
AssignmentProposition[] e, BayesianNetwork bn) {
this.bn = bn;
int maxSize = bn.getVariablesInTopologicalOrder().size();
extendedValues = new Object[maxSize];
var = new RandomVariable[maxSize];
// query variables go first
int idx = 0;
for (int i = 0; i < queryVariables.length; i++) {
var[idx] = queryVariables[i];
varIdxs.put(var[idx], idx);
idx++;
}
// initial evidence variables go next
for (int i = 0; i < e.length; i++) {
var[idx] = e[i].getTermVariable();
varIdxs.put(var[idx], idx);
extendedValues[idx] = e[i].getValue();
idx++;
}
extendedIdx = idx - 1;
hiddenStart = idx;
// the remaining slots are left open for the hidden variables
for (RandomVariable rv : bn.getVariablesInTopologicalOrder()) {
if (!varIdxs.containsKey(rv)) {
var[idx] = rv;
varIdxs.put(var[idx], idx);
idx++;
}
}
}
public void setExtendedValue(RandomVariable rv, Object value) {
int idx = varIdxs.get(rv);
extendedValues[idx] = value;
if (idx >= hiddenStart) {
extendedIdx = idx;
} else {
extendedIdx = hiddenStart - 1;
}
}
public boolean containsValue(RandomVariable rv) {
return varIdxs.get(rv) <= extendedIdx;
}
public double posteriorForParents(RandomVariable rv) {
Node n = bn.getNode(rv);
if (!(n instanceof FiniteNode)) {
throw new IllegalArgumentException(
"Enumeration-Ask only works with finite Nodes.");
}
FiniteNode fn = (FiniteNode) n;
Object[] vals = new Object[1 + fn.getParents().size()];
int idx = 0;
for (Node pn : n.getParents()) {
vals[idx] = extendedValues[varIdxs.get(pn.getRandomVariable())];
idx++;
}
vals[idx] = extendedValues[varIdxs.get(rv)];
return fn.getCPT().getValue(vals);
}
}
//
// PRIVATE METHODS
//
} | 3,019 |
1,244 | <reponame>omeranson/musl
#undef __WORDSIZE
#define __WORDSIZE 32
#define R15 0
#define R14 1
#define R13 2
#define R12 3
#define RBP 4
#define RBX 5
#define R11 6
#define R10 7
#define R9 8
#define R8 9
#define RAX 10
#define RCX 11
#define RDX 12
#define RSI 13
#define RDI 14
#define ORIG_RAX 15
#define RIP 16
#define CS 17
#define EFLAGS 18
#define RSP 19
#define SS 20
#define FS_BASE 21
#define GS_BASE 22
#define DS 23
#define ES 24
#define FS 25
#define GS 26
| 266 |
594 | /* Test that __builtin_prefetch does no harm.
Prefetch using all valid combinations of rw and locality values.
These must be compile-time constants. */
#define NO_TEMPORAL_LOCALITY 0
#define LOW_TEMPORAL_LOCALITY 1
#define MODERATE_TEMPORAL_LOCALITY 1
#define HIGH_TEMPORAL_LOCALITY 3
#define WRITE_ACCESS 1
#define READ_ACCESS 0
enum locality { none, low, moderate, high };
enum rw { read, write };
int arr[10];
void
good_const (const int *p)
{
__builtin_prefetch (p, 0, 0);
__builtin_prefetch (p, 0, 1);
__builtin_prefetch (p, 0, 2);
__builtin_prefetch (p, READ_ACCESS, 3);
__builtin_prefetch (p, 1, NO_TEMPORAL_LOCALITY);
__builtin_prefetch (p, 1, LOW_TEMPORAL_LOCALITY);
__builtin_prefetch (p, 1, MODERATE_TEMPORAL_LOCALITY);
__builtin_prefetch (p, WRITE_ACCESS, HIGH_TEMPORAL_LOCALITY);
}
void
good_enum (const int *p)
{
__builtin_prefetch (p, read, none);
__builtin_prefetch (p, read, low);
__builtin_prefetch (p, read, moderate);
__builtin_prefetch (p, read, high);
__builtin_prefetch (p, write, none);
__builtin_prefetch (p, write, low);
__builtin_prefetch (p, write, moderate);
__builtin_prefetch (p, write, high);
}
void
good_expr (const int *p)
{
__builtin_prefetch (p, 1 - 1, 6 - (2 * 3));
__builtin_prefetch (p, 1 + 0, 1 + 2);
}
void
good_vararg (const int *p)
{
__builtin_prefetch (p, 0, 3);
__builtin_prefetch (p, 0);
__builtin_prefetch (p, 1);
__builtin_prefetch (p);
}
int
main ()
{
good_const (arr);
good_enum (arr);
good_expr (arr);
good_vararg (arr);
exit (0);
}
| 682 |
3,631 | /*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.dmn.core.compiler;
import java.util.HashMap;
import java.util.Map;
import org.kie.dmn.api.core.DMNType;
public class DMNScope {
private DMNScope parent;
private Map<String, DMNType> variables = new HashMap<>( );
public DMNScope() {
}
public DMNScope(DMNScope parent ) {
this.parent = parent;
}
public void setVariable( String name, DMNType type ) {
this.variables.put( name, type );
}
public DMNType resolve( String name ) {
DMNType type = this.variables.get( name );
if( type == null && this.parent != null ) {
return this.parent.resolve( name );
}
return type;
}
public Map<String, DMNType> getVariables() {
return this.variables;
}
}
| 488 |
471 | /////////////////////////////////////////////////////////////////////////////
// Name: wx/osx/dcprint.h
// Purpose: wxPrinterDC class
// Author: <NAME>
// Modified by:
// Created: 1998-01-01
// Copyright: (c) <NAME>
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_DCPRINT_H_
#define _WX_DCPRINT_H_
#include "wx/dc.h"
#include "wx/dcgraph.h"
#include "wx/cmndata.h"
class wxNativePrinterDC ;
class WXDLLIMPEXP_CORE wxPrinterDCImpl: public wxGCDCImpl
{
public:
#if wxUSE_PRINTING_ARCHITECTURE
wxPrinterDCImpl( wxPrinterDC *owner, const wxPrintData& printdata );
virtual ~wxPrinterDCImpl();
virtual bool StartDoc( const wxString& WXUNUSED(message) ) ;
virtual void EndDoc(void) ;
virtual void StartPage(void) ;
virtual void EndPage(void) ;
wxRect GetPaperRect() const;
wxPrintData& GetPrintData() { return m_printData; }
virtual wxSize GetPPI() const;
protected:
virtual void DoGetSize( int *width, int *height ) const;
wxPrintData m_printData ;
wxNativePrinterDC* m_nativePrinterDC ;
private:
DECLARE_CLASS(wxPrinterDC)
#endif // wxUSE_PRINTING_ARCHITECTURE
};
#endif
// _WX_DCPRINT_H_
| 487 |
2,389 | <reponame>Ankit01Mishra/java
package io.kubernetes.client.openapi.models;
import io.kubernetes.client.fluent.VisitableBuilder;
import java.lang.Object;
import java.lang.Boolean;
public class V1HostAliasBuilder extends io.kubernetes.client.openapi.models.V1HostAliasFluentImpl<io.kubernetes.client.openapi.models.V1HostAliasBuilder> implements io.kubernetes.client.fluent.VisitableBuilder<io.kubernetes.client.openapi.models.V1HostAlias,io.kubernetes.client.openapi.models.V1HostAliasBuilder>{
public V1HostAliasBuilder() {
this(false);
}
public V1HostAliasBuilder(java.lang.Boolean validationEnabled) {
this(new V1HostAlias(), validationEnabled);
}
public V1HostAliasBuilder(io.kubernetes.client.openapi.models.V1HostAliasFluent<?> fluent) {
this(fluent, false);
}
public V1HostAliasBuilder(io.kubernetes.client.openapi.models.V1HostAliasFluent<?> fluent,java.lang.Boolean validationEnabled) {
this(fluent, new V1HostAlias(), validationEnabled);
}
public V1HostAliasBuilder(io.kubernetes.client.openapi.models.V1HostAliasFluent<?> fluent,io.kubernetes.client.openapi.models.V1HostAlias instance) {
this(fluent, instance, false);
}
public V1HostAliasBuilder(io.kubernetes.client.openapi.models.V1HostAliasFluent<?> fluent,io.kubernetes.client.openapi.models.V1HostAlias instance,java.lang.Boolean validationEnabled) {
this.fluent = fluent;
fluent.withHostnames(instance.getHostnames());
fluent.withIp(instance.getIp());
this.validationEnabled = validationEnabled;
}
public V1HostAliasBuilder(io.kubernetes.client.openapi.models.V1HostAlias instance) {
this(instance,false);
}
public V1HostAliasBuilder(io.kubernetes.client.openapi.models.V1HostAlias instance,java.lang.Boolean validationEnabled) {
this.fluent = this;
this.withHostnames(instance.getHostnames());
this.withIp(instance.getIp());
this.validationEnabled = validationEnabled;
}
io.kubernetes.client.openapi.models.V1HostAliasFluent<?> fluent;
java.lang.Boolean validationEnabled;
public io.kubernetes.client.openapi.models.V1HostAlias build() {
V1HostAlias buildable = new V1HostAlias();
buildable.setHostnames(fluent.getHostnames());
buildable.setIp(fluent.getIp());
return buildable;
}
public boolean equals(java.lang.Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
V1HostAliasBuilder that = (V1HostAliasBuilder) o;
if (fluent != null &&fluent != this ? !fluent.equals(that.fluent) :that.fluent != null &&fluent != this ) return false;
if (validationEnabled != null ? !validationEnabled.equals(that.validationEnabled) :that.validationEnabled != null) return false;
return true;
}
public int hashCode() {
return java.util.Objects.hash(fluent, validationEnabled, super.hashCode());
}
} | 1,025 |
441 | <reponame>vinhig/rbfx
// File: crn_dxt5a.cpp
// See Copyright Notice and license at the end of inc/crnlib.h
#include "crn_core.h"
#include "crn_dxt5a.h"
#include "crn_ryg_dxt.hpp"
#include "crn_dxt_fast.h"
#include "crn_intersect.h"
namespace crnlib {
dxt5_endpoint_optimizer::dxt5_endpoint_optimizer()
: m_pParams(NULL),
m_pResults(NULL) {
m_unique_values.reserve(16);
m_unique_value_weights.reserve(16);
}
bool dxt5_endpoint_optimizer::compute(const params& p, results& r) {
m_pParams = &p;
m_pResults = &r;
if ((!p.m_num_pixels) || (!p.m_pPixels))
return false;
m_unique_values.resize(0);
m_unique_value_weights.resize(0);
for (uint i = 0; i < 256; i++)
m_unique_value_map[i] = -1;
for (uint i = 0; i < p.m_num_pixels; i++) {
uint alpha = p.m_pPixels[i][p.m_comp_index];
int index = m_unique_value_map[alpha];
if (index == -1) {
index = m_unique_values.size();
m_unique_value_map[alpha] = index;
m_unique_values.push_back(static_cast<uint8>(alpha));
m_unique_value_weights.push_back(0);
}
m_unique_value_weights[index]++;
}
if (m_unique_values.size() == 1) {
r.m_block_type = 0;
r.m_reordered = false;
r.m_error = 0;
r.m_first_endpoint = m_unique_values[0];
r.m_second_endpoint = m_unique_values[0];
memset(r.m_pSelectors, 0, p.m_num_pixels);
return true;
}
m_trial_selectors.resize(m_unique_values.size());
m_best_selectors.resize(m_unique_values.size());
r.m_error = cUINT64_MAX;
for (uint i = 0; i < m_unique_values.size() - 1; i++) {
const uint low_endpoint = m_unique_values[i];
for (uint j = i + 1; j < m_unique_values.size(); j++) {
const uint high_endpoint = m_unique_values[j];
evaluate_solution(low_endpoint, high_endpoint);
}
}
if ((m_pParams->m_quality >= cCRNDXTQualityBetter) && (m_pResults->m_error)) {
m_flags.resize(256 * 256);
m_flags.clear_all_bits();
const int cProbeAmount = (m_pParams->m_quality == cCRNDXTQualityUber) ? 16 : 8;
for (int l_delta = -cProbeAmount; l_delta <= cProbeAmount; l_delta++) {
const int l = m_pResults->m_first_endpoint + l_delta;
if (l < 0)
continue;
else if (l > 255)
break;
const uint bit_index = l * 256;
for (int h_delta = -cProbeAmount; h_delta <= cProbeAmount; h_delta++) {
const int h = m_pResults->m_second_endpoint + h_delta;
if (h < 0)
continue;
else if (h > 255)
break;
//if (m_flags.get_bit(bit_index + h))
// continue;
if ((m_flags.get_bit(bit_index + h)) || (m_flags.get_bit(h * 256 + l)))
continue;
m_flags.set_bit(bit_index + h);
evaluate_solution(static_cast<uint>(l), static_cast<uint>(h));
}
}
}
m_pResults->m_reordered = false;
if (m_pResults->m_first_endpoint == m_pResults->m_second_endpoint) {
for (uint i = 0; i < m_best_selectors.size(); i++)
m_best_selectors[i] = 0;
} else if (m_pResults->m_block_type) {
//if (l > h)
// eight alpha
// else
// six alpha
if (m_pResults->m_first_endpoint > m_pResults->m_second_endpoint) {
utils::swap(m_pResults->m_first_endpoint, m_pResults->m_second_endpoint);
m_pResults->m_reordered = true;
for (uint i = 0; i < m_best_selectors.size(); i++)
m_best_selectors[i] = g_six_alpha_invert_table[m_best_selectors[i]];
}
} else if (!(m_pResults->m_first_endpoint > m_pResults->m_second_endpoint)) {
utils::swap(m_pResults->m_first_endpoint, m_pResults->m_second_endpoint);
m_pResults->m_reordered = true;
for (uint i = 0; i < m_best_selectors.size(); i++)
m_best_selectors[i] = g_eight_alpha_invert_table[m_best_selectors[i]];
}
for (uint i = 0; i < m_pParams->m_num_pixels; i++) {
uint alpha = m_pParams->m_pPixels[i][m_pParams->m_comp_index];
int index = m_unique_value_map[alpha];
m_pResults->m_pSelectors[i] = m_best_selectors[index];
}
return true;
}
void dxt5_endpoint_optimizer::evaluate_solution(uint low_endpoint, uint high_endpoint) {
for (uint block_type = 0; block_type < (m_pParams->m_use_both_block_types ? 2U : 1U); block_type++) {
uint selector_values[8];
if (!block_type)
dxt5_block::get_block_values8(selector_values, low_endpoint, high_endpoint);
else
dxt5_block::get_block_values6(selector_values, low_endpoint, high_endpoint);
uint64 trial_error = 0;
for (uint i = 0; i < m_unique_values.size(); i++) {
const uint val = m_unique_values[i];
const uint weight = m_unique_value_weights[i];
uint best_selector_error = UINT_MAX;
uint best_selector = 0;
for (uint j = 0; j < 8; j++) {
int selector_error = val - selector_values[j];
selector_error = selector_error * selector_error * (int)weight;
if (static_cast<uint>(selector_error) < best_selector_error) {
best_selector_error = selector_error;
best_selector = j;
if (!best_selector_error)
break;
}
}
m_trial_selectors[i] = static_cast<uint8>(best_selector);
trial_error += best_selector_error;
if (trial_error > m_pResults->m_error)
break;
}
if (trial_error < m_pResults->m_error) {
m_pResults->m_error = trial_error;
m_pResults->m_first_endpoint = static_cast<uint8>(low_endpoint);
m_pResults->m_second_endpoint = static_cast<uint8>(high_endpoint);
m_pResults->m_block_type = static_cast<uint8>(block_type);
m_best_selectors.swap(m_trial_selectors);
if (!trial_error)
break;
}
}
}
} // namespace crnlib
| 2,598 |
432 | <reponame>suhaowen/high-java<filename>src/main/java/com/changyu/foryou/model/FoodWithSales.java<gh_stars>100-1000
package com.changyu.foryou.model;
public class FoodWithSales {
private Long foodId;
private String foodName;
private Integer sales;
public Long getFoodId() {
return foodId;
}
public void setFoodId(Long foodId) {
this.foodId = foodId;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public Integer getSales() {
return sales;
}
public void setSales(Integer sales) {
this.sales = sales;
}
}
| 229 |
728 | <gh_stars>100-1000
/*
* Copyright 2020 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "TestSuite.h"
#include "test-libmongoc.h"
#include <mongoc-timeout-private.h>
void
_test_mongoc_timeout_new_success (int64_t expected)
{
mongoc_timeout_t *timeout;
timeout = mongoc_timeout_new_timeout_int64 (expected);
BSON_ASSERT (mongoc_timeout_is_set (timeout));
BSON_ASSERT (expected == mongoc_timeout_get_timeout_ms (timeout));
mongoc_timeout_destroy (timeout);
}
void
_test_mongoc_timeout_new_failure (int64_t try, const char *err_msg)
{
capture_logs (true);
BSON_ASSERT (!mongoc_timeout_new_timeout_int64 (try));
ASSERT_CAPTURED_LOG ("mongoc", MONGOC_LOG_LEVEL_ERROR, err_msg);
clear_captured_logs ();
}
void
test_mongoc_timeout_new (void)
{
mongoc_timeout_t *timeout = NULL;
BSON_ASSERT (!mongoc_timeout_is_set (timeout));
BSON_ASSERT (timeout = mongoc_timeout_new ());
BSON_ASSERT (!mongoc_timeout_is_set (timeout));
mongoc_timeout_destroy (timeout);
_test_mongoc_timeout_new_failure (-1, "timeout must not be negative");
_test_mongoc_timeout_new_failure (INT64_MIN, "timeout must not be negative");
_test_mongoc_timeout_new_success (0);
_test_mongoc_timeout_new_success (1);
_test_mongoc_timeout_new_success (INT64_MAX);
}
void
_test_mongoc_timeout_set_failure (mongoc_timeout_t *timeout,
int64_t try,
const char *err_msg)
{
capture_logs (true);
BSON_ASSERT (!mongoc_timeout_set_timeout_ms (timeout, try));
ASSERT_CAPTURED_LOG ("mongoc", MONGOC_LOG_LEVEL_ERROR, err_msg);
clear_captured_logs ();
BSON_ASSERT (!mongoc_timeout_is_set (timeout));
}
void
_test_mongoc_timeout_set_success (mongoc_timeout_t *timeout, int64_t expected)
{
BSON_ASSERT (mongoc_timeout_set_timeout_ms (timeout, expected));
BSON_ASSERT (mongoc_timeout_is_set (timeout));
BSON_ASSERT (expected == mongoc_timeout_get_timeout_ms (timeout));
}
void
test_mongoc_timeout_set (void)
{
mongoc_timeout_t *timeout = NULL;
timeout = mongoc_timeout_new ();
BSON_ASSERT (!mongoc_timeout_is_set (timeout));
_test_mongoc_timeout_set_failure (
timeout, -1, "timeout must not be negative");
_test_mongoc_timeout_set_failure (
timeout, INT64_MIN, "timeout must not be negative");
_test_mongoc_timeout_set_success (timeout, 0);
_test_mongoc_timeout_set_success (timeout, 1);
_test_mongoc_timeout_set_success (timeout, INT64_MAX);
mongoc_timeout_destroy (timeout);
}
void
test_mongoc_timeout_get (void)
{
mongoc_timeout_t *timeout = NULL;
int64_t expected;
BSON_ASSERT (timeout = mongoc_timeout_new ());
BSON_ASSERT (!mongoc_timeout_is_set (timeout));
expected = 1;
mongoc_timeout_set_timeout_ms (timeout, expected);
BSON_ASSERT (mongoc_timeout_is_set (timeout));
BSON_ASSERT (expected == mongoc_timeout_get_timeout_ms (timeout));
mongoc_timeout_destroy (timeout);
}
void
_test_mongoc_timeout_copy (mongoc_timeout_t *expected)
{
mongoc_timeout_t *actual = mongoc_timeout_copy (expected);
/* assert different memory addresses */
BSON_ASSERT (expected != actual);
BSON_ASSERT (mongoc_timeout_is_set (actual) ==
mongoc_timeout_is_set (expected));
if (mongoc_timeout_is_set (actual)) {
BSON_ASSERT (mongoc_timeout_get_timeout_ms (actual) ==
mongoc_timeout_get_timeout_ms (expected));
}
mongoc_timeout_destroy (actual);
}
void
test_mongoc_timeout_copy (void)
{
mongoc_timeout_t *timeout = NULL;
timeout = mongoc_timeout_new ();
_test_mongoc_timeout_copy (timeout);
mongoc_timeout_destroy (timeout);
timeout = mongoc_timeout_new_timeout_int64 (1);
_test_mongoc_timeout_copy (timeout);
mongoc_timeout_destroy (timeout);
}
void
test_mongoc_timeout_destroy (void)
{
mongoc_timeout_destroy (NULL);
}
void
test_timeout_install (TestSuite *suite)
{
TestSuite_Add (suite, "/Timeout/new", test_mongoc_timeout_new);
TestSuite_Add (suite, "/Timeout/set", test_mongoc_timeout_set);
TestSuite_Add (suite, "/Timeout/get", test_mongoc_timeout_get);
TestSuite_Add (suite, "/Timeout/copy", test_mongoc_timeout_copy);
TestSuite_Add (suite, "/Timeout/destroy", test_mongoc_timeout_destroy);
}
| 1,844 |
324 | <reponame>tormath1/jclouds<filename>apis/ec2/src/main/java/org/jclouds/ec2/options/DescribeRegionsOptions.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.ec2.options;
import java.util.Arrays;
import java.util.Set;
import org.jclouds.ec2.options.internal.BaseEC2RequestOptions;
/**
* Contains options supported in the Form API for the DescribeRegions operation. <h2>
* Usage</h2> The recommended way to instantiate a DescribeRegionsOptions object is to statically
* import DescribeRegionsOptions.Builder.* and invoke a static creation method followed by an
* instance mutator (if needed):
* <p/>
* <code>
* import static org.jclouds.ec2.options.DescribeRegionsOptions.Builder.*
* <p/>
* EC2Api connection = // get connection
* Future<Set<ImageMetadata>> images = connection.getRegionsAndRegionsServices().describeRegions(regions("us-east-1a", "us-east-1b"));
* <code>
*
* @see <a
* href="http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-DescribeRegions.html"
* />
*/
public class DescribeRegionsOptions extends BaseEC2RequestOptions {
/**
* Name of a Region.
*/
public DescribeRegionsOptions regions(String... regions) {
String[] regionStrings = Arrays.copyOf(regions, regions.length, String[].class);
indexFormValuesWithPrefix("RegionName", regionStrings);
return this;
}
public Set<String> getZones() {
return getFormValuesWithKeysPrefixedBy("RegionName.");
}
public static class Builder {
/**
* @see DescribeRegionsOptions#regions(String[] )
*/
public static DescribeRegionsOptions regions(String... regions) {
DescribeRegionsOptions options = new DescribeRegionsOptions();
return options.regions(regions);
}
}
}
| 805 |
4,036 | typedef unsigned long size_t;
void * operator new[](size_t count, int arg1, int arg2);
template<typename T>
void callNew(T arg) {
new(2, 3) int[5];
}
void callCallNew() {
callNew(1);
}
| 84 |
1,014 | <filename>Database/Equities/Countries/Denmark/Industries/Industrial Distribution.json
{
"AOJ-P.CO": {
"short_name": "Brdr. A & O Johansen prf. A/S",
"long_name": "Br\u00f8drene A & O Johansen A/S",
"summary": "Br\u00c3\u00b8drene A & O Johansen A/S, together with its subsidiaries, sells and distributes technical installation materials and tools in Denmark, Sweden, Norway, and Estonia. The company offers plumbing, heating, and sanitary ware products; electrical equipment and components; and water supply and drainage products and tools. It serves plumbers, electricians, building contractors, sewer contractors, construction companies, municipalities, utilities, and public institutions. The company operates through 50 stores in Denmark, as well as sells its products online through BilligVVS.dk, LavprisVVS.dk, VVSochBad.se, BilligVVS.no, Greenline.dk, LavprisEL.dk, LampeGuru.dk, and Lampeguru.no websites. Br\u00c3\u00b8drene A & O Johansen A/S was founded in 1914 and is headquartered in Albertslund, Denmark.",
"currency": "DKK",
"sector": "Industrials",
"industry": "Industrial Distribution",
"exchange": "CPH",
"market": "dk_market",
"country": "Denmark",
"state": null,
"city": "Albertslund",
"zipcode": "2620",
"website": "http://www.ao.dk",
"market_cap": "Mid Cap"
}
} | 522 |
1,355 | // Copyright (c) 2018 <NAME>
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#ifndef INCLUDE_JET_IMPLICIT_SURFACE3_H_
#define INCLUDE_JET_IMPLICIT_SURFACE3_H_
#include <jet/surface3.h>
namespace jet {
//! Abstract base class for 3-D implicit surface.
class ImplicitSurface3 : public Surface3 {
public:
//! Default constructor.
ImplicitSurface3(
const Transform3& transform = Transform3(),
bool isNormalFlipped = false);
//! Copy constructor.
ImplicitSurface3(const ImplicitSurface3& other);
//! Default destructor.
virtual ~ImplicitSurface3();
//! Returns signed distance from the given point \p otherPoint.
double signedDistance(const Vector3D& otherPoint) const;
protected:
//! Returns signed distance from the given point \p otherPoint in local
//! space.
virtual double signedDistanceLocal(const Vector3D& otherPoint) const = 0;
private:
double closestDistanceLocal(const Vector3D& otherPoint) const override;
bool isInsideLocal(const Vector3D& otherPoint) const override;
};
//! Shared pointer type for the ImplicitSurface3.
typedef std::shared_ptr<ImplicitSurface3> ImplicitSurface3Ptr;
} // namespace jet
#endif // INCLUDE_JET_IMPLICIT_SURFACE3_H_
| 449 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.