max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,338
/* * Copyright 2004-2006, the Haiku project. All rights reserved. * Distributed under the terms of the MIT License. * * Authors in chronological order: * <EMAIL> * <NAME> * <NAME> */ #include "KeyboardView.h" #include <Bitmap.h> #include <Button.h> #include <Catalog.h> #include <InterfaceDefs.h> #include <LayoutBuilder.h> #include <Locale.h> #include <Slider.h> #include <TextControl.h> #include <Window.h> #include "InputConstants.h" #include "KeyboardSettings.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "KeyboardView" KeyboardView::KeyboardView() : BGroupView() { // Create the "Key repeat rate" slider... fRepeatSlider = new BSlider("key_repeat_rate", B_TRANSLATE("Key repeat rate"), new BMessage(kMsgSliderrepeatrate), 20, 300, B_HORIZONTAL); fRepeatSlider->SetHashMarks(B_HASH_MARKS_BOTTOM); fRepeatSlider->SetHashMarkCount(5); fRepeatSlider->SetLimitLabels(B_TRANSLATE("Slow"), B_TRANSLATE("Fast")); fRepeatSlider->SetExplicitMinSize(BSize(200, B_SIZE_UNSET)); // Create the "Delay until key repeat" slider... fDelaySlider = new BSlider("delay_until_key_repeat", B_TRANSLATE("Delay until key repeat"), new BMessage(kMsgSliderdelayrate), 250000, 1000000, B_HORIZONTAL); fDelaySlider->SetHashMarks(B_HASH_MARKS_BOTTOM); fDelaySlider->SetHashMarkCount(4); fDelaySlider->SetLimitLabels(B_TRANSLATE("Short"), B_TRANSLATE("Long")); // Create the "Typing test area" text box... BTextControl* textcontrol = new BTextControl( NULL, B_TRANSLATE("Typing test area"), new BMessage('TTEA')); textcontrol->SetAlignment(B_ALIGN_LEFT, B_ALIGN_CENTER); textcontrol->SetExplicitMinSize( BSize(textcontrol->StringWidth(B_TRANSLATE("Typing test area")), B_SIZE_UNSET)); // Build the layout BLayoutBuilder::Group<>(this, B_VERTICAL, B_USE_DEFAULT_SPACING) .Add(fRepeatSlider) .Add(fDelaySlider) .Add(textcontrol) .AddGlue(); } KeyboardView::~KeyboardView() { } void KeyboardView::Draw(BRect updateFrame) { BPoint pt; pt.x = fRepeatSlider->Frame().right + 10; if (fIconBitmap != NULL) { pt.y = fRepeatSlider->Frame().bottom - 35 - fIconBitmap->Bounds().Height() / 3; DrawBitmap(fIconBitmap, pt); } if (fClockBitmap != NULL) { pt.y = fDelaySlider->Frame().bottom - 35 - fClockBitmap->Bounds().Height() / 3; DrawBitmap(fClockBitmap, pt); } }
931
356
package com.zjb.volley.core.cache; /** * time: 2015/8/19 * description: * * @author sunjianfei */ public class NoCache implements Cache { public NoCache() { } public void clear() { } public Entry get(String key) { return null; } public void put(String key, Entry entry) { } public void invalidate(String key, boolean fullExpire) { } public void remove(String key) { } public void initialize() { } }
185
1,077
<gh_stars>1000+ import json import requests from anime_downloader.sites.anime import Anime, AnimeEpisode, SearchResult from anime_downloader.sites import helpers class AnimeOnline(Anime, sitename='animeonline360'): sitename = 'animeonline360' @classmethod def search(cls, query): try: r = helpers.soupify(helpers.get('https://animeonline360.me/', params={'s': query})).select('div.title') results = [{"title": x.text, "url": x.a['href']} for x in r] search_results = [ SearchResult( title=i['title'], url=i['url'], meta_info={ 'version_key_dubbed': 'Dubbed', 'version_key_subbed': 'Subbed', } ) for i in results ] return search_results except: return "" def _scrape_episodes(self): if '/movies/' in self.url: return [self.url] data = helpers.soupify(helpers.get(self.url)).select('div.episodiotitle > a') return [i.get('href') for i in data[::-1]] def _scrape_metadata(self): self.title = helpers.soupify(helpers.get(self.url)).title.text.split('|')[0].strip().title() class AnimeOnlineEpisode(AnimeEpisode, sitename='animeonline360'): def _get_sources(self): return [('animeonline360', self.url)]
765
14,668
<gh_stars>1000+ // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/component_updater/chrome_component_updater_configurator.h" #include <memory> #include <string> #include <vector> #include "base/bind.h" #include "base/callback.h" #include "base/memory/raw_ptr.h" #include "base/strings/sys_string_conversions.h" #include "base/version.h" #include "build/branding_buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/component_updater/component_updater_utils.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/update_client/chrome_update_query_params_delegate.h" #include "chrome/common/channel_info.h" #include "components/component_updater/component_updater_command_line_config_policy.h" #include "components/component_updater/configurator_impl.h" #include "components/prefs/pref_service.h" #include "components/services/patch/content/patch_service.h" #include "components/services/unzip/content/unzip_service.h" #include "components/update_client/activity_data_service.h" #include "components/update_client/crx_downloader_factory.h" #include "components/update_client/net/network_chromium.h" #include "components/update_client/patch/patch_impl.h" #include "components/update_client/protocol_handler.h" #include "components/update_client/unzip/unzip_impl.h" #include "components/update_client/unzipper.h" #include "components/update_client/update_query_params.h" #include "content/public/browser/browser_thread.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #if defined(OS_WIN) #include "base/enterprise_util.h" #include "chrome/installer/util/google_update_settings.h" #endif namespace component_updater { namespace { class ChromeConfigurator : public update_client::Configurator { public: ChromeConfigurator(const base::CommandLine* cmdline, PrefService* pref_service); // update_client::Configurator overrides. double InitialDelay() const override; int NextCheckDelay() const override; int OnDemandDelay() const override; int UpdateDelay() const override; std::vector<GURL> UpdateUrl() const override; std::vector<GURL> PingUrl() const override; std::string GetProdId() const override; base::Version GetBrowserVersion() const override; std::string GetChannel() const override; std::string GetLang() const override; std::string GetOSLongName() const override; base::flat_map<std::string, std::string> ExtraRequestParams() const override; std::string GetDownloadPreference() const override; scoped_refptr<update_client::NetworkFetcherFactory> GetNetworkFetcherFactory() override; scoped_refptr<update_client::CrxDownloaderFactory> GetCrxDownloaderFactory() override; scoped_refptr<update_client::UnzipperFactory> GetUnzipperFactory() override; scoped_refptr<update_client::PatcherFactory> GetPatcherFactory() override; bool EnabledDeltas() const override; bool EnabledBackgroundDownloader() const override; bool EnabledCupSigning() const override; PrefService* GetPrefService() const override; update_client::ActivityDataService* GetActivityDataService() const override; bool IsPerUserInstall() const override; std::unique_ptr<update_client::ProtocolHandlerFactory> GetProtocolHandlerFactory() const override; private: friend class base::RefCountedThreadSafe<ChromeConfigurator>; ConfiguratorImpl configurator_impl_; raw_ptr<PrefService> pref_service_; // This member is not owned by this class. scoped_refptr<update_client::NetworkFetcherFactory> network_fetcher_factory_; scoped_refptr<update_client::CrxDownloaderFactory> crx_downloader_factory_; scoped_refptr<update_client::UnzipperFactory> unzip_factory_; scoped_refptr<update_client::PatcherFactory> patch_factory_; ~ChromeConfigurator() override = default; }; // Allows the component updater to use non-encrypted communication with the // update backend. The security of the update checks is enforced using // a custom message signing protocol and it does not depend on using HTTPS. ChromeConfigurator::ChromeConfigurator(const base::CommandLine* cmdline, PrefService* pref_service) : configurator_impl_(ComponentUpdaterCommandLineConfigPolicy(cmdline), false), pref_service_(pref_service) { DCHECK(pref_service_); } double ChromeConfigurator::InitialDelay() const { return configurator_impl_.InitialDelay(); } int ChromeConfigurator::NextCheckDelay() const { return configurator_impl_.NextCheckDelay(); } int ChromeConfigurator::OnDemandDelay() const { return configurator_impl_.OnDemandDelay(); } int ChromeConfigurator::UpdateDelay() const { return configurator_impl_.UpdateDelay(); } std::vector<GURL> ChromeConfigurator::UpdateUrl() const { return configurator_impl_.UpdateUrl(); } std::vector<GURL> ChromeConfigurator::PingUrl() const { return configurator_impl_.PingUrl(); } std::string ChromeConfigurator::GetProdId() const { return update_client::UpdateQueryParams::GetProdIdString( update_client::UpdateQueryParams::ProdId::CHROME); } base::Version ChromeConfigurator::GetBrowserVersion() const { return configurator_impl_.GetBrowserVersion(); } std::string ChromeConfigurator::GetChannel() const { return chrome::GetChannelName(chrome::WithExtendedStable(true)); } std::string ChromeConfigurator::GetLang() const { return ChromeUpdateQueryParamsDelegate::GetLang(); } std::string ChromeConfigurator::GetOSLongName() const { return configurator_impl_.GetOSLongName(); } base::flat_map<std::string, std::string> ChromeConfigurator::ExtraRequestParams() const { return configurator_impl_.ExtraRequestParams(); } std::string ChromeConfigurator::GetDownloadPreference() const { #if defined(OS_WIN) // This group policy is supported only on Windows and only for enterprises. return base::IsMachineExternallyManaged() ? base::SysWideToUTF8( GoogleUpdateSettings::GetDownloadPreference()) : std::string(); #else return std::string(); #endif } scoped_refptr<update_client::NetworkFetcherFactory> ChromeConfigurator::GetNetworkFetcherFactory() { if (!network_fetcher_factory_) { network_fetcher_factory_ = base::MakeRefCounted<update_client::NetworkFetcherChromiumFactory>( g_browser_process->system_network_context_manager() ->GetSharedURLLoaderFactory(), // Never send cookies for component update downloads. base::BindRepeating([](const GURL& url) { return false; })); } return network_fetcher_factory_; } scoped_refptr<update_client::CrxDownloaderFactory> ChromeConfigurator::GetCrxDownloaderFactory() { if (!crx_downloader_factory_) { crx_downloader_factory_ = update_client::MakeCrxDownloaderFactory(GetNetworkFetcherFactory()); } return crx_downloader_factory_; } scoped_refptr<update_client::UnzipperFactory> ChromeConfigurator::GetUnzipperFactory() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!unzip_factory_) { unzip_factory_ = base::MakeRefCounted<update_client::UnzipChromiumFactory>( base::BindRepeating(&unzip::LaunchUnzipper)); } return unzip_factory_; } scoped_refptr<update_client::PatcherFactory> ChromeConfigurator::GetPatcherFactory() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!patch_factory_) { patch_factory_ = base::MakeRefCounted<update_client::PatchChromiumFactory>( base::BindRepeating(&patch::LaunchFilePatcher)); } return patch_factory_; } bool ChromeConfigurator::EnabledDeltas() const { return configurator_impl_.EnabledDeltas(); } bool ChromeConfigurator::EnabledBackgroundDownloader() const { return configurator_impl_.EnabledBackgroundDownloader(); } bool ChromeConfigurator::EnabledCupSigning() const { return configurator_impl_.EnabledCupSigning(); } PrefService* ChromeConfigurator::GetPrefService() const { return pref_service_; } update_client::ActivityDataService* ChromeConfigurator::GetActivityDataService() const { return nullptr; } bool ChromeConfigurator::IsPerUserInstall() const { return component_updater::IsPerUserInstall(); } std::unique_ptr<update_client::ProtocolHandlerFactory> ChromeConfigurator::GetProtocolHandlerFactory() const { return configurator_impl_.GetProtocolHandlerFactory(); } } // namespace scoped_refptr<update_client::Configurator> MakeChromeComponentUpdaterConfigurator( const base::CommandLine* cmdline, PrefService* pref_service) { return base::MakeRefCounted<ChromeConfigurator>(cmdline, pref_service); } } // namespace component_updater
2,935
1,405
<reponame>jarekankowski/pegasus_spyware<filename>sample4/recompiled_java/sources/com/lenovo/safecenter/mmsutils/MMSReciver.java package com.lenovo.safecenter.mmsutils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; import com.lenovo.lps.sus.a.a.a.b; import com.lenovo.safecenter.floatwindow.util.SettingUtil; import java.io.UnsupportedEncodingException; public class MMSReciver extends BroadcastReceiver { public static final String TAG = "Push Receiver"; Context a; Intent b; public void onReceive(Context context, Intent intent) { Log.v("Push Receiver", "Intent recieved: " + intent.getAction()); if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) { Log.i("Push Receiver", "SMS: " + intent.getAction()); Toast.makeText(context, "SMS_RECEIVED", 1).show(); } if (intent.getAction().equals("android.provider.Telephony.WAP_PUSH_RECEIVED")) { Log.v("Push Receiver", "PUSH: " + intent.getAction()); Toast.makeText(context, "PUSH MSG", 1).show(); } Log.v("Push Receiver", "MMSReciver abortBroadcast();"); this.a = context; this.b = intent; new Thread() { /* class com.lenovo.safecenter.mmsutils.MMSReciver.AnonymousClass1 */ public final void run() { byte[] pushData = MMSReciver.this.b.getByteArrayExtra(SettingUtil.DATA); GenericPdu pdu = new TyuMMSParser(pushData).parse(); if (pdu == null) { Log.e("Push Receiver", "Invalid PUSH data"); return; } try { Log.v("Push Receiver", new String(pushData, b.a)); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } String val_from = pdu.getFrom().getString(); switch (pdu.getMessageType()) { case 130: NotificationInd npdu = (NotificationInd) pdu; try { Log.v("Push Receiver", new String(npdu.getContentLocation(), b.a)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { Log.v("Push Receiver", npdu.getSubject().getString()); } catch (Exception e1) { e1.printStackTrace(); } try { Log.v("Push Receiver", new String(npdu.getTransactionId(), b.a)); } catch (UnsupportedEncodingException e3) { e3.printStackTrace(); } try { Log.v("Push Receiver", new String(npdu.getMessageClass(), b.a)); break; } catch (UnsupportedEncodingException e4) { e4.printStackTrace(); break; } } Log.v("Push Receiver", val_from); MMSReciver.this.a = null; MMSReciver.this.b = null; } }.start(); abortBroadcast(); } }
1,876
672
// BUILD: $CC foo1.c -dynamiclib -install_name $RUN_DIR/libfoo1.dylib -o $BUILD_DIR/libfoo1.dylib // BUILD: $CC foo2.c -dynamiclib -install_name $RUN_DIR/libfoo2.dylib -o $BUILD_DIR/libfoo2.dylib // BUILD: $CC foo3.c -dynamiclib -install_name $RUN_DIR/libfoo3.dylib -o $BUILD_DIR/libfoo3.dylib // BUILD: $CC main.c -o $BUILD_DIR/dlopen-RTLD_LOCAL-coalesce.exe -DRUN_DIR="$RUN_DIR" // RUN: ./dlopen-RTLD_LOCAL-coalesce.exe #include <stdio.h> #include <stdlib.h> #include <string.h> #include <dlfcn.h> /// /// This tests the interaction of RTLD_LOCAL and weak-def coalescing. /// /// Normally, (for correct C++ ODR), dyld coalesces all weak-def symbols /// across all images, so that only one copy of each weak symbol name /// is in use. But, dlopen with RTLD_LOCAL means to "hide" the symbols in /// that one (top) image being loaded. /// /// // main *coalA // libfoo1.dylib coalA *coalB // libfoo2.dylib coalA coalB coalC // loaded with RTLD_LOCAL // libfoo3.dylib coalA coalB *coalC // typedef int (*IntProc)(void); int __attribute__((weak)) coalA = 0; int main() { printf("[BEGIN] dlopen-RTLD_LOCAL-coalesce\n"); /// /// Load three foo dylibs in order /// void* handle1 = dlopen(RUN_DIR "/libfoo1.dylib", RTLD_GLOBAL); void* handle2 = dlopen(RUN_DIR "/libfoo2.dylib", RTLD_LOCAL); void* handle3 = dlopen(RUN_DIR "/libfoo3.dylib", RTLD_GLOBAL); if ( handle1 == NULL ) { printf("[FAIL] dlopen-RTLD_LOCAL-coalesce: dlopen(libfoo1.dylib, RTLD_GLOBAL) failed but it should have worked: %s\n", dlerror()); return 0; } if ( handle2 == NULL ) { printf("[FAIL] dlopen-RTLD_LOCAL-coalesce: dlopen(libfoo2.dylib, RTLD_LOCAL) failed but it should have worked: %s\n", dlerror()); return 0; } if ( handle3 == NULL ) { printf("[FAIL] dlopen-RTLD_LOCAL-coalesce: dlopen(libfoo3.dylib, RTLD_GLOBAL) failed but it should have worked: %s\n", dlerror()); return 0; } /// /// Get accessor functions /// IntProc foo1_coalA = (IntProc)dlsym(handle1, "foo1_coalA"); IntProc foo1_coalB = (IntProc)dlsym(handle1, "foo1_coalB"); IntProc foo2_coalA = (IntProc)dlsym(handle2, "foo2_coalA"); IntProc foo2_coalB = (IntProc)dlsym(handle2, "foo2_coalB"); IntProc foo2_coalC = (IntProc)dlsym(handle2, "foo2_coalC"); IntProc foo3_coalA = (IntProc)dlsym(handle3, "foo3_coalA"); IntProc foo3_coalB = (IntProc)dlsym(handle3, "foo3_coalB"); IntProc foo3_coalC = (IntProc)dlsym(handle3, "foo3_coalC"); if ( !foo1_coalA || !foo1_coalB || !foo2_coalA || !foo2_coalB || !foo2_coalC || !foo3_coalA || !foo3_coalB || !foo3_coalC ) { printf("[FAIL] dlopen-RTLD_LOCAL-coalesce: dlsym() failed\n"); return 0; } /// /// Get values for each coal[ABC] seen in each image /// int foo1A = (*foo1_coalA)(); int foo1B = (*foo1_coalB)(); int foo2A = (*foo2_coalA)(); int foo2B = (*foo2_coalB)(); int foo2C = (*foo2_coalC)(); int foo3A = (*foo3_coalA)(); int foo3B = (*foo3_coalB)(); int foo3C = (*foo3_coalC)(); printf("coalA in main: %d\n", coalA); printf("coalA in libfoo1: %d\n", foo1A); printf("coalA in libfoo2: %d\n", foo2A); printf("coalA in libfoo3: %d\n", foo3A); printf("coalB in libfoo1: %d\n", foo1B); printf("coalB in libfoo2: %d\n", foo2B); printf("coalB in libfoo3: %d\n", foo3B); printf("coalC in libfoo2: %d\n", foo2C); printf("coalC in libfoo3: %d\n", foo3C); /// /// Verify coalescing was done properly (foo2 was skipped because of RTLD_LOCAL) /// if ( (foo1A != 0) || (foo2A != 0) || (foo3A != 0) || (coalA != 0) ) { printf("[FAIL] dlopen-RTLD_LOCAL-coalesce: coalA was not coalesced properly\n"); return 0; } if ( (foo1B != 1) || (foo2B != 1) || (foo3B != 1) ) { printf("[FAIL] dlopen-RTLD_LOCAL-coalesce: coalB was not coalesced properly\n"); return 0; } if ( (foo2C != 2) || (foo3C != 3) ) { printf("[FAIL] dlopen-RTLD_LOCAL-coalesce: coalC was not coalesced properly\n"); return 0; } printf("[PASS] dlopen-RTLD_LOCAL-coalesce\n"); return 0; }
1,996
834
<filename>installer/centos-7-x86_64/run_scripts/setup.py #!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. import argparse import os import platform import shutil import subprocess import sys def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--reload", help="Clear setup config, and reload", action="store_true" ) return parser.parse_args() class SetupFboss: FRUID_CONF = "fruid.json" FRUID_DIR_PATH = "/var/facebook/fboss" FRUID_FULL_PATH = os.path.join(FRUID_DIR_PATH, FRUID_CONF) BDE_CONF = "bde.conf" BDE_CONF_FULL_PATH = os.path.join("/etc/modprobe.d", BDE_CONF) BCM_CONF = "bcm.conf" BCM_CONF_DIR_PATH = "/etc/coop" BCM_CONF_FULL_PATH = os.path.join(BCM_CONF_DIR_PATH, BCM_CONF) USER_BDE = "linux-user-bde" KERNEL_BDE = "linux-kernel-bde" USER_BDE_KO = USER_BDE + ".ko" KERNEL_BDE_KO = KERNEL_BDE + ".ko" KMOD_FULL_PATH = os.path.join("/lib/modules/" + platform.uname().release) USER_BDE_KO_FULL_PATH = os.path.join(KMOD_FULL_PATH, USER_BDE_KO) KERNEL_BDE_KO_FULL_PATH = os.path.join(KMOD_FULL_PATH, KERNEL_BDE_KO) # Unfortunately, lsmod prints _ (underscore) for - (dash) LSMOD_USER_BDE = "linux_user_bde" LSMOD_KERNEL_BDE = "linux_kernel_bde" SRC_USER_BDE_KO_FULL_PATH = os.path.join(os.environ["FBOSS_KMODS"], USER_BDE_KO) SRC_KERNEL_BDE_KO_FULL_PATH = os.path.join(os.environ["FBOSS_KMODS"], KERNEL_BDE_KO) BCM_CONFIG_DIR = os.path.join(os.environ["FBOSS_DATA"], "bcm_configs") TH = "th" TH3 = "th3" def __init__(self): output = subprocess.check_output(["lspci"]).decode("utf-8").split("\n") if [x for x in output if "Broadcom" in x and "BCM56960" in x]: self.src_fruid_full_path = os.path.join( *[os.environ["FBOSS_DATA"], SetupFboss.TH, SetupFboss.FRUID_CONF] ) self.src_bde_full_path = os.path.join( *[os.environ["FBOSS_DATA"], SetupFboss.TH, SetupFboss.BDE_CONF] ) PLATFORM = "WEDGE100S+RSW" self.src_bcm_conf_full_path = os.path.join( SetupFboss.BCM_CONFIG_DIR, PLATFORM + "-bcm.conf" ) elif [x for x in output if "Broadcom" in x and "b980" in x]: self.src_fruid_full_path = os.path.join( *[os.environ["FBOSS_DATA"], SetupFboss.TH3, SetupFboss.FRUID_CONF] ) self.src_bde_full_path = os.path.join( *[os.environ["FBOSS_DATA"], SetupFboss.TH3, SetupFboss.BDE_CONF] ) PLATFORM = "MINIPACK+FSW" self.src_bcm_conf_full_path = os.path.join( SetupFboss.BCM_CONFIG_DIR, PLATFORM + "-bcm.conf" ) def _cleanup_old_setup(self): if os.path.exists(SetupFboss.FRUID_FULL_PATH): os.remove(SetupFboss.FRUID_FULL_PATH) if os.path.exists(SetupFboss.BCM_CONF_FULL_PATH): os.remove(SetupFboss.BCM_CONF_FULL_PATH) if os.path.exists(SetupFboss.BDE_CONF_FULL_PATH): os.remove(SetupFboss.BDE_CONF_FULL_PATH) subprocess.run(["modprobe", "-r", SetupFboss.USER_BDE]) subprocess.run(["modprobe", "-r", SetupFboss.KERNEL_BDE]) if os.path.exists(SetupFboss.USER_BDE_KO_FULL_PATH): os.remove(SetupFboss.USER_BDE_KO_FULL_PATH) if os.path.exists(SetupFboss.KERNEL_BDE_KO_FULL_PATH): os.remove(SetupFboss.KERNEL_BDE_KO_FULL_PATH) def _copy_configs(self): if not os.path.exists(SetupFboss.FRUID_FULL_PATH): if not os.path.exists(SetupFboss.FRUID_DIR_PATH): os.mkdir(SetupFboss.FRUID_DIR_PATH) shutil.copy(self.src_fruid_full_path, SetupFboss.FRUID_FULL_PATH) if not os.path.exists(SetupFboss.BCM_CONF_FULL_PATH): if not os.path.exists(SetupFboss.BCM_CONF_DIR_PATH): os.mkdir(SetupFboss.BCM_CONF_DIR_PATH) shutil.copy(self.src_bcm_conf_full_path, SetupFboss.BCM_CONF_FULL_PATH) if not os.path.exists(SetupFboss.BDE_CONF_FULL_PATH): shutil.copy(self.src_bde_full_path, SetupFboss.BDE_CONF_FULL_PATH) def _link_kmods(self): new_kmod = False if not os.path.exists(SetupFboss.USER_BDE_KO_FULL_PATH): subprocess.run( [ "ln", "-s", SetupFboss.SRC_USER_BDE_KO_FULL_PATH, "-t", SetupFboss.KMOD_FULL_PATH, ] ) new_kmod = True if not os.path.exists(SetupFboss.KERNEL_BDE_KO_FULL_PATH): subprocess.run( [ "ln", "-s", SetupFboss.SRC_KERNEL_BDE_KO_FULL_PATH, "-t", SetupFboss.KMOD_FULL_PATH, ] ) new_kmod = True if new_kmod: subprocess.run(["depmod", "-a"]) def _load_kmods(self): output = subprocess.check_output(["lsmod"]).decode("utf-8").split("\n") if not [x for x in output if SetupFboss.LSMOD_USER_BDE in x]: subprocess.run(["modprobe", SetupFboss.USER_BDE]) if not [x for x in output if SetupFboss.LSMOD_KERNEL_BDE in x]: subprocess.run(["modprobe", SetupFboss.KERNEL_BDE]) def run(self, args): if args.reload: self._cleanup_old_setup() self._copy_configs() self._link_kmods() self._load_kmods() if __name__ == "__main__": if "FBOSS" not in os.environ: sys.exit(f"FBOSS is unset. Run 'source ./bin/setup_fboss_env' to set it up.") else: print(f"Running setup.py with FBOSS={os.environ['FBOSS']}") args = parse_args() SetupFboss().run(args)
3,145
318
package xyz.msws.nope.checks.movement.flight; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; import xyz.msws.nope.NOPE; import xyz.msws.nope.modules.checks.Check; import xyz.msws.nope.modules.checks.CheckType; import xyz.msws.nope.modules.checks.Global.Stat; import xyz.msws.nope.modules.data.CPlayer; /** * Same as @see Flight1 but different onGround detection * * @author imodm * */ public class Flight2 implements Check, Listener { private NOPE plugin; @Override public CheckType getType() { return CheckType.MOVEMENT; } @Override public void register(NOPE plugin) { this.plugin = plugin; Bukkit.getPluginManager().registerEvents(this, plugin); } @EventHandler public void onMove(PlayerMoveEvent event) { Player player = event.getPlayer(); CPlayer cp = plugin.getCPlayer(player); if (player.isFlying() || cp.isInWeirdBlock() || player.isInsideVehicle()) return; if (cp.timeSince(Stat.FLYING) < 500 || cp.timeSince(Stat.RIPTIDE) < 1000) return; Location to = event.getTo(), from = event.getFrom(); if (to.getY() != from.getY()) return; if (player.getNearbyEntities(2, 3, 2).stream().anyMatch(e -> e.getType() == EntityType.BOAT)) return; for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { if (player.getLocation().clone().add(x, -.1, z).getBlock().getType().isSolid()) return; if (player.getLocation().clone().add(x, -1.5, z).getBlock().getType().isSolid()) return; if (player.getLocation().clone().add(x, 0, z).getBlock().getType() != Material.AIR) return; } } if (cp.timeSince(Stat.FLIGHT_GROUNDED) < 1000) return; if (cp.timeSince(Stat.LILY_PAD) < 500) return; cp.flagHack(this, 20); } @Override public String getCategory() { return "Flight"; } @Override public String getDebugName() { return "Flight#2"; } @Override public boolean lagBack() { return true; } }
831
2,583
<reponame>onelsonic/armory from arm.logicnode.arm_nodes import * class SpawnObjectByNameNode(ArmLogicTreeNode): """Spawns an object bearing the given name, even if not present in the active scene""" bl_idname = 'LNSpawnObjectByNameNode' bl_label = 'Spawn Object By Name' arm_version = 1 property0: HaxePointerProperty( 'property0', type=bpy.types.Scene, name='Scene', description='The scene from which to take the object') def arm_init(self, context): self.add_input('ArmNodeSocketAction', 'In') self.add_input('ArmStringSocket', 'Name') self.add_input('ArmDynamicSocket', 'Transform') self.add_input('ArmBoolSocket', 'Children', default_value=True) self.add_output('ArmNodeSocketAction', 'Out') self.add_output('ArmNodeSocketObject', 'Object') def draw_buttons(self, context, layout): layout.prop_search(self, 'property0', bpy.data, "scenes")
363
1,109
<gh_stars>1000+ /******************************************************************************* * Copyright 2016 Intuit * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.intuit.wasabi.auditlogobjects; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.intuit.wasabi.authenticationobjects.UserInfo; import com.intuit.wasabi.experimentobjects.Application; import com.intuit.wasabi.experimentobjects.Bucket; import com.intuit.wasabi.experimentobjects.Experiment; import com.intuit.wasabi.experimentobjects.ExperimentBase; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.TimeZone; /** * Represents an AuditLogEntry. */ @JsonSerialize(using = AuditLogEntry.Serializer.class) public class AuditLogEntry { private final Calendar time; private final UserInfo user; private final AuditLogAction action; private final Application.Name applicationName; private final Experiment.Label experimentLabel; private final Experiment.ID experimentId; private final Bucket.Label bucketLabel; private final String changedProperty; private final String before; private final String after; /** * Creates an AuditLogEntry. * * @param time the event time (required) * @param user the event user (required) * @param action the event action (required) */ public AuditLogEntry(Calendar time, UserInfo user, AuditLogAction action) { this(time, user, action, null, null, null, null, null); } /** * Creates an AuditLogEntry. * * @param time the event time (required) * @param user the event user (required) * @param action the event action (required) * @param experiment the experiment (if applicable) * @param bucketLabel the bucket label (if applicable) * @param changedProperty the changed property (if applicable) * @param before the property before (if applicable) * @param after the property after (if applicable) */ public AuditLogEntry(Calendar time, UserInfo user, AuditLogAction action, ExperimentBase experiment, Bucket.Label bucketLabel, String changedProperty, String before, String after) { this(time, user, action, experiment == null ? null : experiment.getApplicationName(), experiment == null ? null : experiment.getLabel(), experiment == null ? null : experiment.getID(), bucketLabel, changedProperty, before, after); } /** * Creates an AuditLogEntry. Usually you want to use the other constructors as they have a better parameter order. * * @see #AuditLogEntry(Calendar, UserInfo, AuditLogAction) * @see #AuditLogEntry(Calendar, UserInfo, AuditLogAction, ExperimentBase, Bucket.Label, String, String, String) * * * @param time the event time (required) * @param user the event invoking user (required) * @param action the event action (required) * @param applicationName application name (if applicable) * @param experimentLabel the experiment label (if applicable) * @param experimentId the experiment ID(if applicable) * @param bucketLabel the bucket label (if applicable) * @param changedProperty the changed property (if applicable) * @param before the property before (if applicable) * @param after the property after (if applicable) */ public AuditLogEntry(Calendar time, UserInfo user, AuditLogAction action, Application.Name applicationName, Experiment.Label experimentLabel, Experiment.ID experimentId, Bucket.Label bucketLabel, String changedProperty, String before, String after) { if (time == null) { throw new IllegalArgumentException("time must not be null"); } if (user == null) { throw new IllegalArgumentException("username must not be null"); } if (action == null) { throw new IllegalArgumentException("action must not be null"); } this.time = time; this.user = user; this.action = action; this.applicationName = applicationName; this.experimentLabel = experimentLabel; this.experimentId = experimentId; this.bucketLabel = bucketLabel; this.changedProperty = changedProperty; this.before = before; this.after = after; } /** * Returns a reconstructed user object. Does not contain the UserId. * * @return the user of this entry (no Id) */ public UserInfo getUser() { return user; } /** * The time of this entry. * * @return the time */ public Calendar getTime() { return time; } /** * Returns an ISO 8601 timestamp with zulu time of this entry's time. * * @return an ISO 8601 timestamp * @see <a href="https://en.wikipedia.org/wiki/ISO_8601">wikipedia.org/wiki/ISO_8601</a> */ public String getTimeString() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf.format(time.getTime()).replace("+0000", "Z"); } /** * The action associated with this entry. * * @return an action. */ public AuditLogAction getAction() { return action; } /** * The application of this entry. * * @return the application. */ public Application.Name getApplicationName() { return applicationName; } /** * The experiment label. * * @return the experiment label. */ public Experiment.Label getExperimentLabel() { return experimentLabel; } /** * The experiment ID. * * @return the experiment ID. */ public Experiment.ID getExperimentId() { return experimentId; } /** * The bucket label. * * @return the bucket label. */ public Bucket.Label getBucketLabel() { return bucketLabel; } /** * The name of the changed property. * * @return the changed property's name. */ public String getChangedProperty() { return changedProperty; } /** * The property value before the change. * * @return the last value */ public String getBefore() { return before; } /** * The property value after the change. * * @return the value after */ public String getAfter() { return after; } /** * Returns a String representation of this entry. * * @return a string representation. */ @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } /** * A serializer for the AuditLogEntry for Jackson. */ public static class Serializer extends JsonSerializer<AuditLogEntry> { /** * Method that can be called to ask implementation to serialize * values of type this serializer handles. * * @param value Value to serialize; can <b>not</b> be null. * @param jgen Generator used to output resulting Json content * @param provider Provider that can be used to get serializers for */ @Override public void serialize(AuditLogEntry value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); // time jgen.writeObjectField("time", value.getTime()); // user jgen.writeObjectField("user", value.getUser()); // action jgen.writeFieldName("action"); jgen.writeStartObject(); jgen.writeStringField("type", value.getAction().toString()); jgen.writeStringField("message", AuditLogAction.getDescription(value)); jgen.writeEndObject(); // application if (value.getApplicationName() != null) { jgen.writeObjectField("applicationName", value.getApplicationName()); } // experiment if (value.getExperimentLabel() != null || value.getExperimentId() != null) { jgen.writeFieldName("experiment"); jgen.writeStartObject(); if (value.getExperimentLabel() != null) { jgen.writeObjectField("experimentLabel", value.getExperimentLabel()); } if (value.getExperimentId() != null) { jgen.writeObjectField("experimentId", value.getExperimentId()); } jgen.writeEndObject(); } // bucket if (value.getBucketLabel() != null) { jgen.writeObjectField("bucketLabel", value.getBucketLabel()); } // changed property if (value.getChangedProperty() != null) { jgen.writeFieldName("change"); jgen.writeStartObject(); jgen.writeStringField("changedAttribute", value.getChangedProperty()); if (value.getBefore() != null) { jgen.writeStringField("before", value.getBefore()); } if (value.getAfter() != null) { jgen.writeStringField("after", value.getAfter()); } jgen.writeEndObject(); } jgen.writeEndObject(); } } }
4,135
335
<reponame>mrslezak/Engine /* Copyright (C) 2019 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <algorithm> #include <qle/termstructures/crosscurrencypricetermstructure.hpp> using QuantLib::Date; using QuantLib::Handle; using QuantLib::Natural; using QuantLib::Quote; using QuantLib::Time; using QuantLib::YieldTermStructure; using std::max; using std::min; using std::vector; namespace QuantExt { CrossCurrencyPriceTermStructure::CrossCurrencyPriceTermStructure( const QuantLib::Date& referenceDate, const QuantLib::Handle<PriceTermStructure>& basePriceTs, const QuantLib::Handle<QuantLib::Quote>& fxSpot, const QuantLib::Handle<QuantLib::YieldTermStructure>& baseCurrencyYts, const QuantLib::Handle<QuantLib::YieldTermStructure>& yts, const QuantLib::Currency& currency) : PriceTermStructure(referenceDate, basePriceTs->calendar(), basePriceTs->dayCounter()), basePriceTs_(basePriceTs), fxSpot_(fxSpot), baseCurrencyYts_(baseCurrencyYts), yts_(yts), currency_(currency) { registration(); } CrossCurrencyPriceTermStructure::CrossCurrencyPriceTermStructure( Natural settlementDays, const QuantLib::Handle<PriceTermStructure>& basePriceTs, const QuantLib::Handle<QuantLib::Quote>& fxSpot, const QuantLib::Handle<QuantLib::YieldTermStructure>& baseCurrencyYts, const QuantLib::Handle<QuantLib::YieldTermStructure>& yts, const QuantLib::Currency& currency) : PriceTermStructure(settlementDays, basePriceTs->calendar(), basePriceTs->dayCounter()), basePriceTs_(basePriceTs), fxSpot_(fxSpot), baseCurrencyYts_(baseCurrencyYts), yts_(yts), currency_(currency) { registration(); } Date CrossCurrencyPriceTermStructure::maxDate() const { return min(basePriceTs_->maxDate(), min(baseCurrencyYts_->maxDate(), yts_->maxDate())); } Time CrossCurrencyPriceTermStructure::maxTime() const { return min(basePriceTs_->maxTime(), min(baseCurrencyYts_->maxTime(), yts_->maxTime())); } Time CrossCurrencyPriceTermStructure::minTime() const { return basePriceTs_->minTime(); } vector<Date> CrossCurrencyPriceTermStructure::pillarDates() const { return basePriceTs_->pillarDates(); } QuantLib::Real CrossCurrencyPriceTermStructure::priceImpl(QuantLib::Time t) const { // Price in base currency times the FX forward, number of units of currency per unit of base currency. return basePriceTs_->price(t, true) * fxSpot_->value() * baseCurrencyYts_->discount(t, true) / yts_->discount(t, true); } void CrossCurrencyPriceTermStructure::registration() { registerWith(basePriceTs_); registerWith(fxSpot_); registerWith(baseCurrencyYts_); registerWith(yts_); } } // namespace QuantExt
1,048
480
<reponame>weicao/galaxysql<gh_stars>100-1000 /* * Copyright [2013-2021], Alibaba Group Holding Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.polardbx.optimizer.core.datatype; import com.alibaba.polardbx.common.exception.NotSupportException; import com.alibaba.polardbx.common.type.MySQLStandardFieldType; import com.alibaba.polardbx.optimizer.core.row.Row; import java.sql.ResultSet; import java.sql.SQLException; /** * bytes 类型 * * @author mengshi.sunmengshi 2014年1月21日 下午5:16:00 * @since 5.0.0 */ public class BytesType extends AbstractDataType<byte[]> { @Override public Class getDataClass() { return byte[].class; } @Override public byte[] getMaxValue() { return new byte[] {Byte.MAX_VALUE}; } @Override public byte[] getMinValue() { return new byte[] {Byte.MIN_VALUE}; } @Override public Calculator getCalculator() { throw new NotSupportException("bytes类型不支持计算操作"); } @Override public ResultGetter getResultGetter() { return new ResultGetter() { @Override public Object get(ResultSet rs, int index) throws SQLException { return rs.getBytes(index); } @Override public Object get(Row rs, int index) { Object val = rs.getObject(index); return convertFrom(val); } }; } @Override public int compare(Object o1, Object o2) { if (o1 == o2) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } byte[] value = convertFrom(o1); byte[] targetValue = convertFrom(o2); int notZeroOffset = 0; int targetNotZeroOffset = 0; for (notZeroOffset = 0; notZeroOffset < value.length; notZeroOffset++) { if (value[notZeroOffset] != 0) { break; } } for (targetNotZeroOffset = 0; targetNotZeroOffset < targetValue.length; targetNotZeroOffset++) { if (targetValue[targetNotZeroOffset] != 0) { break; } } int actualLength = value.length - notZeroOffset; int actualTargetLength = targetValue.length - targetNotZeroOffset; if (actualLength > actualTargetLength) { return 1; } else if (actualLength < actualTargetLength) { return -1; } else { int index = notZeroOffset; int targetIndex = targetNotZeroOffset; while (true) { if (index >= value.length || targetIndex >= targetValue.length) { break; } short shortValue = (short) (value[index] & 0xff); short shortTargetValue = (short) (targetValue[targetIndex] & 0xff); boolean re = (shortValue == shortTargetValue); if (re) { index++; targetIndex++; continue; } else { return shortValue > shortTargetValue ? 1 : -1; } } return 0; } } @Override public int getSqlType() { return java.sql.Types.BINARY; } @Override public String getStringSqlType() { return "BINARY"; } @Override public MySQLStandardFieldType fieldType() { return MySQLStandardFieldType.MYSQL_TYPE_VAR_STRING; } }
1,852
814
import logging import os import numpy as np import glob import json from dataclasses import dataclass from typing import List, Dict, Callable, Tuple, Generator, Set, Sequence, Optional, Union import torch from tqdm import tqdm from transformers import DataProcessor, PreTrainedTokenizer from tython import Program, TastNode, _RULES_BY_KIND, Rule, RULES from challenges import Challenge, Solution, SolverSolution, verify_solutions logger = logging.getLogger(__name__) def get_QAs(challenges_path, max_ticks=1000, min_tries=0, verify_sols=True, all_instances=False): # Create examples challenges_files = glob.glob(challenges_path) logger.info(f"Loading puzzles and solutions from {challenges_files}") challenge_configs = [] seen_challenges = set() for f_name in challenges_files: chs = json.load(open(f_name, 'r')) for ch in chs: if not all_instances and not ch['name'].endswith('_0'): continue if ch['name'] not in seen_challenges: challenge_configs.append(ch) seen_challenges.add(ch['name']) seen_challenges.add(ch['name']) # Parse challenges. challenges = {} for config in challenge_configs: #ch = Challenge(config, max_ticks=max_ticks) ch = Challenge(config) if ch.prog is not None: challenges[ch.name] = ch if len(challenge_configs) == 0: logger.warning("Couldn't parse any puzzles.") return [], [] logger.info("Successfully parsed {} ({:.2f}%) out of {} puzzles.".format( len(challenges.keys()), 100 * len(challenges.keys()) / len(challenge_configs), len(challenge_configs))) if verify_sols: verify_solutions(challenges.values()) # zzz TODO: only last solutions #QAs = [(ch.f_str, s.prog) for ch in challenges.values() # for s in ch.gold_solutions if s.prog is not None and (s.count is None or s.count >= min_tries)] #QAs = [(ch.f_str, s.prog) for ch in challenges.values() if len(ch.gold_solutions) > 0 # for s in [ch.gold_solutions[-1]] if s.prog is not None] QAs = [] for ch in challenges.values(): added_one_sol = False if len(ch.gold_solutions) == 0: continue for s in reversed(ch.gold_solutions): if not added_one_sol and s.prog is not None: QAs.append((ch.f_str, s.prog)) added_one_sol = True logger.info(f"collected {len(QAs)} QAs") sol_kinds = [ch.sol_kind for ch in challenges.values()] return QAs, sol_kinds def get_Q_trees(challenges_path, max_ticks=1000): # Create examples challenges_files = glob.glob(challenges_path) logger.info(f"Loading puzzles from {challenges_files}") challenge_configs = [] seen_challenges = set() for f_name in challenges_files: chs = json.load(open(f_name, 'r')) for ch in chs: if ch['name'] not in seen_challenges: challenge_configs.append(ch) seen_challenges.add(ch['name']) seen_challenges.add(ch['name']) # Parse challenges. challenges = {} for config in challenge_configs: ch = Challenge(config, max_ticks=max_ticks) if ch.prog is not None: challenges[ch.name] = ch if len(challenge_configs) == 0: logger.warning("Couldn't parse any puzzles.") return [], [] logger.info("Successfully parsed {} ({:.2f}%) out of {} challenges.".format( len(challenges.keys()), 100 * len(challenges.keys()) / len(challenge_configs), len(challenge_configs))) QAs = [(ch.f_str, ch.prog) for ch in challenges.values()] sol_kinds = [ch.sol_kind for ch in challenges.values()] return QAs, sol_kinds def get_Q_augs(challenges_path, max_ticks=1000): challenges_files = glob.glob(challenges_path) logger.info(f"Loading puzzles and augmentations from {challenges_files}") if len(challenges_files) == 0: return [] challenge_configs = [] seen_challenges = set() for f_name in challenges_files: chs = json.load(open(f_name, 'r')) for ch in chs: if ch['name'] not in seen_challenges: challenge_configs.append(ch) seen_challenges.add(ch['name']) seen_challenges.add(ch['name']) # Parse augmentations. QAs = [] for config in challenge_configs: try: aug = Program(config['aug']) QAs.append((config["sat"], aug)) except Exception as e: logger.error(f"Exception parsing augmentation '{config['name']}' ('{config['aug']}'): {e}") logger.info("Successfully parsed {} ({:.2f}%) out of {} puzzles and augmentations.".format( len(QAs), 100 * len(QAs) / len(challenge_configs), len(challenge_configs))) return QAs @dataclass class InputExample: """ A single training/test example. Args: guid: Unique id for the example. puzzle_str: string. The untokenized text of the puzzle. parent_ind: int. The index of the parent rule from the RULES list. child_num: int. The index of the child to predict for. label: (Optional) int. The rule index (in RULES list) for the child_num of the parent rule. target_kind: (Optional) kind. The kind of the rule we are looking for. parent in the solution of the puzzle. """ guid: str puzzle_str: str parent_ind: int child_num: int label: Optional[int] = None target_kind: Optional = -1 # -1 is the default since None is a valid kind. def to_json_string(self): """Serializes this instance to a JSON string.""" return json.dumps(dataclasses.asdict(self), indent=2) + "\n" @dataclass(frozen=True) class InputFeatures: """ A single set of features of data. Property names are the same names as the corresponding inputs to a model. Args: input_ids: Indices of input sequence tokens in the vocabulary. attention_mask: Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: Usually ``1`` for tokens that are NOT MASKED, ``0`` for MASKED (padded) tokens. token_type_ids: (Optional) Segment token indices to indicate first and second portions of the inputs. Only some models use them. softmax_mask: Mask for softmax. Only include children of the current rule. parent_ind: The index of the parent rule from the RULES list. child_num: The index of the child to predict for. label: (Optional) Label corresponding to the input. """ input_ids: List[int] attention_mask: Optional[List[int]] = None token_type_ids: Optional[List[int]] = None softmax_mask: torch.int = None parent_ind: int = int child_num: int = None label: Optional[int] = None def to_json_string(self): """Serializes this instance to a JSON string.""" return json.dumps(dataclasses.asdict(self)) + "\n" def traverse_ans_tree(prog: Program): ''' Collect all rules with their features. ''' # Initiate with root (parent_ind=len(RULES) rules = [[prog.tree.rule.index, len(RULES), 0]] queue = [prog.tree] while queue: node = queue.pop() if not isinstance(node, TastNode) or not _RULES_BY_KIND.get(node.nt): continue parent_ind = node.rule.index for num_child, child in enumerate(node.children): if not hasattr(child, 'nt') or child.nt == 'LIT': continue rules.append([child.rule.index, parent_ind, num_child]) queue.append(child) return rules class PuzzleProcessor(DataProcessor): def __init__(self): super().__init__() def get_train_examples(self, QAs: List[Tuple[str, Program]]): examples = [] targets = [] i = 0 for q_str, a in tqdm(QAs): rules = traverse_ans_tree(a) for r in rules: target_rule = r[0] parent_ind, child_num = r[1:] targets.append(target_rule) guid = "%s-%s" % ("train", i) i += 1 examples.append( InputExample(guid=guid, puzzle_str=q_str, parent_ind=parent_ind, child_num=child_num, label=target_rule, target_kind=RULES[target_rule].nt )) return examples def get_test_examples(self, QAs: List[Tuple[str, Program]]): ''' For now, assume there is gold answer. ''' return self.get_train_examples(QAs) def get_questions(self, QAs: List[Tuple[str, Program]]): ''' Get an InputExample per question (ignoring the solution tree) ''' examples = [] i = 0 for q_str, a in tqdm(QAs): guid = "%s-%s" % ("question", i) i += 1 examples.append( InputExample(guid=guid, puzzle_str=q_str, parent_ind=-1, child_num=-1, label=None)) return examples def get_labels(self): """See base class.""" return list(range(len(RULES))) def convert_examples_to_features( examples: List[InputExample], tokenizer: PreTrainedTokenizer, max_length: Optional[int] = None, label_list=None, output_mode='classification', loud=False, rules_by_kind=_RULES_BY_KIND ): """ Convert ``InputExamples`` to ``InputFeatures`` Args: examples: List of ``InputExamples`` tokenizer: Instance of a tokenizer that will tokenize the examples max_length: Maximum example length. Defaults to the tokenizer's max_len label_list: List of labels. Can be obtained from the processor using the ``processor.get_labels()`` method output_mode: String indicating the output mode. Either ``regression`` or ``classification`` Returns: A list of ``InputFeatures`` which can be fed to the model. """ if max_length is None: max_length = tokenizer.max_len processor = PuzzleProcessor() if label_list is None: label_list = processor.get_labels() label_map = {label: i for i, label in enumerate(label_list)} def label_from_example(example: InputExample) -> Union[int, float, None]: if example.label is None: return None if output_mode == "classification": return label_map[example.label] elif output_mode == "regression": return float(example.label) raise KeyError(output_mode) parent_inds = [example.parent_ind for example in examples] child_nums = [example.child_num for example in examples] labels = [label_from_example(example) for example in examples] target_kinds = [example.target_kind for example in examples] output_masks = [] for rule_ind, target_kind in zip(labels, target_kinds): mask = np.zeros(len(RULES) + 1) # +1 for root (which is always masked) if target_kind is None or target_kind != -1: mask_inds = [r.index for r in rules_by_kind[target_kind]] for ind in mask_inds: mask[ind] = 1 mask = torch.IntTensor(mask).to_sparse() output_masks.append(mask) elif rule_ind is not None: mask_inds = [r.index for r in rules_by_kind[RULES[rule_ind].nt]] for ind in mask_inds: mask[ind] = 1 assert rule_ind in mask_inds mask = torch.IntTensor(mask).to_sparse() output_masks.append(mask) else: output_masks.append(None) batch_encoding = tokenizer.batch_encode_plus( [example.puzzle_str for example in examples], max_length=max_length, pad_to_max_length=True, ) features = [] for i in range(len(examples)): inputs = {k: batch_encoding[k][i] for k in batch_encoding} feature = InputFeatures(**inputs, softmax_mask=output_masks[i], parent_ind=parent_inds[i], child_num=child_nums[i], label=labels[i]) features.append(feature) if loud: for i, example in enumerate(examples[:5]): logger.info("*** Example ***") logger.info("guid: %s" % (example.guid)) logger.info("features: %s" % features[i]) return features
5,738
362
#ifndef KGR_KANGARU_INCLUDE_KANGARU_AUTOCALL_HPP #define KGR_KANGARU_INCLUDE_KANGARU_AUTOCALL_HPP #include "detail/meta_list.hpp" #include "detail/utils.hpp" #include "detail/traits.hpp" #include "detail/injected.hpp" #include "detail/container_service.hpp" #include "container.hpp" namespace kgr { namespace detail { template<typename, typename, typename> struct autocall_function_helper; /* * This class implements all autocall functions that a definition must implement for autocall. * * All autocall specialization extends this one. * * It extending autocall is only way to enable autocall in a service. */ template<typename Map, typename... Ts> struct autocall_base { using autocall_functions = meta_list<Ts...>; using map = Map; private: template<typename, typename, typename> friend struct autocall_function_helper; // TODO: Remove this function since it doesn't belong here anymore. template<typename T, typename M, typename F, std::size_t... S> static void autocall_helper(seq<S...>, inject_t<container_service> cs, T& service) { cs.forward().invoke<M>([&](function_argument_t<S, typename F::value_type>... args) { service.call(F::value, std::forward<function_argument_t<S, typename F::value_type>>(args)...); }); } }; } // namespace detail /* * This alias simply to transform a member function address to a type. */ template<typename T, typename std::decay<T>::type t> using method = std::integral_constant<typename std::decay<T>::type, t>; /* * This class wraps a method and tell explicitly which services are needed. */ template<typename M, typename... Ps> struct invoke : M { using parameters = detail::meta_list<Ps...>; }; /* * The class that defines autocall with the default map. */ template<typename... Ts> struct autocall : detail::autocall_base<kgr::map<>, Ts...> {}; /* * Specialization of autocall when a map is sent as first parameter. */ template<typename... Maps, typename... Ts> struct autocall<kgr::map<Maps...>, Ts...> : detail::autocall_base<kgr::map<Maps...>, Ts...> {}; } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_AUTOCALL_HPP
750
1,052
<reponame>tom-huntington/learn-c-the-hard-way-lectures<gh_stars>1000+ #include "minunit.h" #include <dlfcn.h> #include "statserve.h" #include <lcthw/bstrlib.h> #include <lcthw/ringbuffer.h> #include <assert.h> typedef struct LineTest { char *line; bstring result; char *description; } LineTest; int attempt_line(LineTest test) { int rc = -1; bstring result = NULL; bstring line = bfromcstr(test.line); RingBuffer *send_rb = RingBuffer_create(1024); rc = parse_line(line, send_rb); check(rc == 0, "Failed to parse line."); result = RingBuffer_get_all(send_rb); check(result != NULL, "Ring buffer empty."); check(biseq(result, test.result), "Got the wrong output: %s expected %s", bdata(result), bdata(test.result)); bdestroy(line); RingBuffer_destroy(send_rb); return 1; // using 1 for tests error: log_err("Failed to process test %s: got %s", test.line, bdata(result)); if(line) bdestroy(line); if(send_rb) RingBuffer_destroy(send_rb); return 0; } int run_test_lines(LineTest *tests, int count) { int i = 0; for(i = 0; i < count; i++) { check(attempt_line(tests[i]), "Failed to run %s", tests[i].description); } return 1; error: return 0; } char *test_create() { LineTest tests[] = { {.line = "create /zed 100", .result = &OK, .description = "create zed failed"}, {.line = "create /joe 100", .result = &OK, .description = "create joe failed"}, }; mu_assert(run_test_lines(tests, 2), "Failed to run create tests."); return NULL; } char *test_sample() { struct tagbstring sample1 = bsStatic("100.000000\n"); LineTest tests[] = { {.line = "sample /zed 100", .result = &sample1, .description = "sample zed failed."} }; mu_assert(run_test_lines(tests, 1), "Failed to run sample tests."); return NULL; } char *all_tests() { mu_suite_start(); int rc = setup_data_store(); mu_assert(rc == 0, "Failed to setup the data store."); mu_run_test(test_create); mu_run_test(test_sample); return NULL; } RUN_TESTS(all_tests);
882
348
{"nom":"<NAME>","circ":"2ème circonscription","dpt":"Vendée","inscrits":3237,"abs":1830,"votants":1407,"blancs":100,"nuls":56,"exp":1251,"res":[{"nuance":"MDM","nom":"Mme <NAME>","voix":718},{"nuance":"LR","nom":"Mme <NAME>","voix":533}]}
98
3,428
<reponame>ghalimi/stdlib {"id":"00620","group":"easy-ham-1","checksum":{"type":"MD5","value":"8d1ccac5b4a36e47f5f168c19e6ac573"},"text":"From <EMAIL> Wed Sep 18 17:43:34 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id EA23316F03\n\tfor <jm@localhost>; Wed, 18 Sep 2002 17:43:33 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 18 Sep 2002 17:43:33 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g8IGDeC06492 for <<EMAIL>>;\n Wed, 18 Sep 2002 17:13:40 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id 3C54E2940E3; Wed, 18 Sep 2002 09:10:06 -0700 (PDT)\nDelivered-To: <EMAIL>\nReceived: from tisch.mail.mindspring.net (tisch.mail.mindspring.net\n [207.69.200.157]) by xent.com (Postfix) with ESMTP id 459DC29409E for\n <<EMAIL>>; Wed, 18 Sep 2002 09:09:05 -0700 (PDT)\nReceived: from user-119ac86.biz.mindspring.com ([66.149.49.6]) by\n tisch.mail.mindspring.net with esmtp (Exim 3.33 #1) id 17rhQz-0003iE-00;\n Wed, 18 Sep 2002 12:12:14 -0400\nMIME-Version: 1.0\nX-Sender: <EMAIL>\nMessage-Id: <p<EMAIL>bb9ae46820c6e@[66.149.49.6]>\nIn-Reply-To: <<EMAIL>>\nReferences: <<EMAIL>.0209172137100.51<EMAIL>>\n <<EMAIL>>\nTo: Rodent of Unusual Size <<EMAIL>>,\n\tFlatware or Road Kill? <<EMAIL>>\nFrom: \"<NAME>\" <<EMAIL>>\nSubject: Re: boycotting yahoo\nContent-Type: text/plain; charset=\"us-ascii\"\nSender: [email protected]\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 <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: Wed, 18 Sep 2002 11:06:01 -0400\n\nAt 7:13 AM -0400 on 9/18/02, Rodent of Unusual Size wrote:\n\n\n> SmartGroups, I think.\n\n<NAME>'s Interesting People list just went over to\n<http://www.listbox.com>\n\nCheers,\nRAH\n\n-- \n-----------------\n<NAME> <mailto: <EMAIL>>\nThe Internet Bearer Underwriting Corporation <http://www.ibuc.com/>\n44 Farquhar Street, Boston, MA 02131 USA\n\"... however it may deserve respect for its usefulness and antiquity,\n[predicting the end of the world] has not been found agreeable to\nexperience.\" -- <NAME>, 'Decline and Fall of the Roman Empire'\n\n\n"}
1,148
852
import FWCore.ParameterSet.Config as cms process = cms.Process("TEST") process.load("CondCore.DBCommon.CondDBCommon_cfi") process.CondDBCommon.connect = cms.string("sqlite_file:tagDB.db") process.CondDBCommon.DBParameters.messageLevel = 0 process.PoolDBESSource = cms.ESSource("PoolDBESSource", process.CondDBCommon, globaltag = cms.string('MYTREE1::All'), toGet = cms.VPSet(cms.PSet( connect=cms.untracked.string('sqlite_file:extradata.db'), record = cms.string('anotherPedestalsRcd'), tag = cms.untracked.string('anothertag'), label = cms.untracked.string('') ) ) ) process.source = cms.Source("EmptyIOVSource", lastValue = cms.uint64(3), timetype = cms.string('runnumber'), firstValue = cms.uint64(1), interval = cms.uint64(1) ) process.get = cms.EDFilter("EventSetupRecordDataGetter", toGet = cms.VPSet(cms.PSet( record = cms.string('anotherPedestalsRcd'), data = cms.vstring('Pedestals') ), cms.PSet( record = cms.string('PedestalsRcd'), data = cms.vstring('Pedestals/lab3d', 'Pedestals/lab2') )), verbose = cms.untracked.bool(True) ) process.p = cms.Path(process.get)
549
798
<filename>src/test/java/picard/illumina/parser/readers/LocsFileReaderTest.java package picard.illumina.parser.readers; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import picard.PicardException; import java.io.File; public class LocsFileReaderTest { private static final File TestDir = new File("testdata/picard/illumina/readerTests"); public static final File LocsFile = new File(TestDir, "s_1_6.locs"); public static final int ExpectedTile = 6; public static final int ExpectedLane = 1; public static final int NumValues = 200; public static final float [][] FloatCoords = { {1703.0117f, 64.01593f}, {1660.3038f, 64.08882f}, {1769.7501f, 65.12467f}, {1726.6725f, 68.367805f}, {1401.213f, 72.07282f}, {1358.2775f, 72.07892f}, {1370.5197f, 77.699715f}, {1661.5403f, 77.70719f}, {1682.0504f, 78.76725f}, {1563.8765f, 79.08009f} }; public static final int [][] QSeqCoords = { {18030, 1640}, {17603, 1641}, {18698, 1651}, {18267, 1684}, {15012, 1721}, {14583, 1721}, {14705, 1777}, {17615, 1777}, {17821, 1788}, {16639, 1791} }; public static final int [] Indices = { 0, 1, 19, 59, 100, 101, 179, 180, 198, 199 }; @Test public void passingFileTest() { final LocsFileReader reader = new LocsFileReader(LocsFile); int tdIndex = 0; int nextIndex = Indices[tdIndex]; for(int i = 0; i < NumValues; i++) { Assert.assertTrue(reader.hasNext()); final AbstractIlluminaPositionFileReader.PositionInfo piLocs = reader.next(); if(i == nextIndex) { PosFileReaderTest.comparePositionInfo(piLocs, FloatCoords[tdIndex][0], FloatCoords[tdIndex][1], QSeqCoords[tdIndex][0], QSeqCoords[tdIndex][1], ExpectedLane, ExpectedTile, i); if(tdIndex < Indices.length-1) { nextIndex = Indices[++tdIndex]; } } } Assert.assertFalse(reader.hasNext()); } @DataProvider(name = "invalidFiles") public Object[][]invalidFiles() { return new Object[][] { {"s_1_7.locs"}, {"s_1_8.locs"}, {"s_1_9.locs"}, {"s_1_10.locs"}, {"s_f2af.locs"} }; } @Test(expectedExceptions = PicardException.class, dataProvider = "invalidFiles") public void invalidFilesTest(final String fileName) { final LocsFileReader reader = new LocsFileReader(new File(TestDir, fileName)); } }
1,305
715
#include<bits/stdc++.h> #define max 1000 using namespace std; int findLongestFromACell(int i, int j, int mat[max][max], int dp[max][max], int n){ if (i<0 || i>=n || j<0 || j>=n) return 0; if (dp[i][j] != -1) return dp[i][j]; if (j<n-1 && ((mat[i][j] +1) == mat[i][j+1])) return dp[i][j] = 1 + findLongestFromACell(i,j+1,mat,dp); if (j>0 && (mat[i][j] +1 == mat[i][j-1])) return dp[i][j] = 1 + findLongestFromACell(i,j-1,mat,dp); if (i>0 && (mat[i][j] +1 == mat[i-1][j])) return dp[i][j] = 1 + findLongestFromACell(i-1,j,mat,dp); if (i<n-1 && (mat[i][j] +1 == mat[i+1][j])) return dp[i][j] = 1 + findLongestFromACell(i+1,j,mat,dp); return dp[i][j] = 1; } int finLongestOverAll(int mat[max][max], n){ int result = 1; int dp[n][n]; memset(dp, -1, sizeof dp); for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ if (dp[i][j] == -1) findLongestFromACell(i, j, mat, dp, n); result = max(result, dp[i][j]); } } return result; } int main(){ int n; int mat[max][max] cin>>n; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cin>>mat[i][j]; } } cout << "Length of the longest path is "<< finLongestOverAll(mat, n)<<endl; return 0; }
710
6,098
<gh_stars>1000+ package water.rapids.ast.prims.filters.dropduplicates; import water.Scope; import water.fvec.Frame; import water.fvec.Vec; import water.rapids.Merge; import water.util.ArrayUtils; import java.util.Arrays; /** * Drops duplicated rows of a Frame */ public class DropDuplicateRows { private static final String LABEL_COLUMN_NAME = "label"; final Frame sourceFrame; final int[] comparedColumnIndices; final KeepOrder keepOrder; /** * @param sourceFrame Frame to perform the row de-duplication on * @param comparedColumnIndices Indices of columns to consider during the comparison * @param keepOrder Which rows to keep. */ public DropDuplicateRows(final Frame sourceFrame, final int[] comparedColumnIndices, final KeepOrder keepOrder) { this.sourceFrame = sourceFrame; this.comparedColumnIndices = comparedColumnIndices; this.keepOrder = keepOrder; } public Frame dropDuplicates() { Frame outputFrame = null; try { Scope.enter(); final Vec labelVec = Scope.track(Vec.makeSeq(1, sourceFrame.numRows())); final Frame fr = new Frame(sourceFrame); fr.add(LABEL_COLUMN_NAME, labelVec); final Frame sortedFrame = Scope.track(sortByComparedColumns(fr)); final Frame chunkBoundaries = Scope.track(new CollectChunkBorderValuesTask() .doAll(sortedFrame.types(), sortedFrame) .outputFrame(null, sortedFrame.names(), sortedFrame.domains())); final Frame deDuplicatedFrame = Scope.track(new DropDuplicateRowsTask(chunkBoundaries, comparedColumnIndices) .doAll(sortedFrame.types(), sortedFrame) .outputFrame(null, sortedFrame.names(), sortedFrame.domains())); // Removing duplicates, domains remain the same // Before the final sorted duplicated is created, remove the unused datasets to free some space early chunkBoundaries.remove(); sortedFrame.remove(); outputFrame = Scope.track(Merge.sort(deDuplicatedFrame, deDuplicatedFrame.numCols() - 1)); outputFrame.remove(outputFrame.numCols() - 1).remove(); return outputFrame; } finally { if (outputFrame != null) { Scope.exit(outputFrame.keys()); } else { Scope.exit(); // Clean up in case of any exception/error. } } } /** * Creates a copy of the original dataset, sorted by all compared columns. * The sort is done with respect to {@link KeepOrder} value. * * @return A new Frame sorted by all compared columns. */ private Frame sortByComparedColumns(Frame fr) { final int labelColumnIndex = fr.find(LABEL_COLUMN_NAME); final int[] sortByColumns = ArrayUtils.append(comparedColumnIndices, labelColumnIndex); final boolean ascendingSort = KeepOrder.First == keepOrder; final int[] sortOrder = new int[sortByColumns.length]; // Compared columns are always sorted in the same order Arrays.fill(sortOrder, 0, sortOrder.length - 1, Merge.ASCENDING); // Label column is sorted differently based on DropOrder sortOrder[sortOrder.length - 1] = ascendingSort ? Merge.ASCENDING : Merge.DESCENDING; return Merge.sort(fr, sortByColumns, sortOrder); } }
1,106
830
/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef DEEPMATH_HOL_KERNEL_H_ #define DEEPMATH_HOL_KERNEL_H_ #include <stdint.h> #include <map> #include <memory> #include <set> #include <string> #include <tuple> #include <vector> namespace hol { class Type; class Term; class Thm; typedef std::shared_ptr<const Type> TypePtr; typedef std::shared_ptr<const Term> TermPtr; typedef std::shared_ptr<const Thm> ThmPtr; // TODO(geoffreyi) make a Symbol class which uses fast pointer comparison typedef std::string TypeVar; typedef uint64_t TypeCon; typedef std::string TermVar; typedef uint64_t ConstId; // This corresponds to the ML type: // // type hol_type = private // Tyvar of string // | Tyapp of string * hol_type list class Type final { // Private struct for make_shared purposes struct Secret {}; public: bool operator==(const Type& rhs) const; bool operator!=(const Type& rhs) const { return !(*this == rhs); } bool operator<(const Type& rhs) const; bool is_vartype() const { return kind_ == TYVAR; } bool is_type() const { return kind_ == TYAPP; } const TypeVar dest_vartype() const { return type_var_; } const std::tuple<TypeCon, std::vector<TypePtr> >& dest_type() const { return type_; } friend TypePtr mk_vartype(const TypeVar value); friend TypePtr mk_type(const TypeCon type_con, const std::vector<TypePtr>& args); friend TypePtr type_subst(const std::map<TypeVar, TypePtr>& instantiation, const TypePtr& term); friend std::tuple<TypeCon, std::tuple<ConstId, ConstId>, std::tuple<ThmPtr, ThmPtr> > new_basic_type_definition(const ThmPtr& existence_proof); friend std::set<TypeVar> tyvars(const TypePtr& type); ~Type(); // Public but uncallable so that make_shared works explicit Type(const TypeVar value, Secret) : kind_(TYVAR), type_var_(value) {} Type(const TypeCon type_con, const std::vector<TypePtr>& args, Secret) : kind_(TYAPP), type_(make_tuple(type_con, args)) {} private: friend class Term; static TypePtr unsafe_tyapp(const TypeCon type_con, const std::vector<TypePtr>& args) { return std::make_shared<Type>(type_con, args, Secret()); } enum TypeKind { TYVAR, TYAPP }; // kind_ remembers if the type is a type variable or type application const TypeKind kind_; union { const TypeVar type_var_; const std::tuple<TypeCon, std::vector<TypePtr> > type_; }; }; TypePtr mk_vartype(const TypeVar type_var); TypeCon new_type(uint64_t arity); uint64_t get_type_arity(TypeCon type_con); class VariableOrdering { public: bool operator()(const std::tuple<TermVar, TypePtr>& a, const std::tuple<TermVar, TypePtr>& b) const; }; typedef std::map<std::tuple<TermVar, TypePtr>, TermPtr, VariableOrdering> Substitution; class TermOrdering { public: bool operator()(const TermPtr& a, const TermPtr& b) const; }; // This corresponds to the ML type: // // type term = private // Var of string * hol_type // | Const of string * hol_type // | Comb of term * term // | Abs of term * term class Term final { // Private struct for make_shared purposes struct Secret {}; public: bool operator==(const Term& rhs) const; bool operator!=(const Term& rhs) const { return !(*this == rhs); } bool is_var() const { return kind_ == VAR; } bool is_const() const { return kind_ == CONST; } bool is_comb() const { return kind_ == COMB; } bool is_abs() const { return kind_ == ABS; } TypePtr type_of() const; // Returns the free variables of a term std::set<std::tuple<TermVar, TypePtr> > frees() const; // Checks if all free variables of a term appear in set bool freesin(std::set<std::tuple<TermVar, TypePtr>, VariableOrdering>*) const; // Returns the free type variables of a term std::set<TypeVar> type_vars_in_term() const; const std::tuple<TermVar, TypePtr>& dest_var() const { return term_var_; } const std::tuple<ConstId, TypePtr>& dest_const() const { return term_const_; } const std::tuple<TermPtr, TermPtr>& dest_comb() const { return term_comb_; } const std::tuple<TermVar, TypePtr, TermPtr>& dest_abs() const { return term_abs_; } // Return the operator and the operand of an application respectively const TermPtr& rator() const { return std::get<0>(dest_comb()); } // "rand()" is the name used in HOL that we want to keep even if // NOLINTNEXTLINE "lint" believes it is a call to random number generation const TermPtr& rand() const { return std::get<1>(dest_comb()); } friend TermPtr mk_var(const TermVar term_var, const TypePtr& type); friend TermPtr mk_var(const std::tuple<TermVar, TypePtr>& value); friend TermPtr mk_const(ConstId const_id, const std::map<TypeVar, TypePtr>& subst); friend TermPtr mk_comb(const TermPtr& terml, const TermPtr& termr); friend TermPtr mk_abs(TermVar term_var, const TypePtr& type, const TermPtr& term); friend TermPtr mk_abs(const std::tuple<TermVar, TypePtr>& var, const TermPtr& term); // Substitution of terms for variables friend TermPtr vsubst(Substitution* subst, const TermPtr& term); // Type instantiation friend TermPtr inst(const std::map<TypeVar, TypePtr>& instantiation, const TermPtr& term); friend ThmPtr REFL(const TermPtr& term); friend ThmPtr TRANS(const ThmPtr& left_eq, const ThmPtr& right_eq); friend ThmPtr MK_COMB(const ThmPtr& fun_eq, const ThmPtr& arg_eq); friend ThmPtr ABS(const std::tuple<TermVar, TypePtr>& var, const ThmPtr& eq); friend ThmPtr BETA(const TermPtr& term); friend ThmPtr DEDUCT_ANTISYM(const ThmPtr& thm1, const ThmPtr& thm2); friend ThmPtr INST(Substitution* subst, const ThmPtr& thm); friend ThmPtr new_basic_definition(const TermPtr& definition); friend std::tuple<TypeCon, std::tuple<ConstId, ConstId>, std::tuple<ThmPtr, ThmPtr> > new_basic_type_definition(const ThmPtr& existence_proof); ~Term(); // Public but uncallable for make_shared purposes Term(const TermVar i, const TypePtr& t, Secret) : kind_(VAR), term_var_(std::make_tuple(i, t)) {} explicit Term(const std::tuple<TermVar, TypePtr>& value, Secret) : kind_(VAR), term_var_(value) {} Term(const ConstId i, const TypePtr& t, Secret) : kind_(CONST), term_const_(std::make_tuple(i, t)) {} Term(const TermPtr& l, const TermPtr& r, Secret) : kind_(COMB), term_comb_(std::make_tuple(l, r)) {} Term(const TermVar i, const TypePtr& ty, const TermPtr& t, Secret) : kind_(ABS), term_abs_(std::make_tuple(i, ty, t)) {} private: static TermPtr unsafe_var(const TermVar term_var, const TypePtr& type) { return std::make_shared<Term>(term_var, type, Secret()); } static TermPtr unsafe_var(const std::tuple<TermVar, TypePtr>& value) { return std::make_shared<Term>(value, Secret()); } static TermPtr unsafe_const(const ConstId const_id, const TypePtr& type) { return std::make_shared<Term>(const_id, type, Secret()); } static TermPtr unsafe_comb(const TermPtr& l, const TermPtr& r) { return std::make_shared<Term>(l, r, Secret()); } static TermPtr unsafe_abs(const TermVar v, const TypePtr& ty, const TermPtr& t) { return std::make_shared<Term>(v, ty, t, Secret()); } static TermPtr unsafe_mk_eq(const TermPtr& lhs, const TermPtr& rhs); static TermPtr vsubst_rec(Substitution* s, const TermPtr& tm); static std::tuple<TermPtr, bool> inst_rec( const std::map<TermPtr, TermPtr, TermOrdering>& env, const std::map<TypeVar, TypePtr>& instantiation, const TermPtr& term); enum TermKind { VAR, CONST, COMB, ABS }; // kind_ stores the term constructor used to build the term const int8_t kind_; union { const std::tuple<TermVar, TypePtr> term_var_; const std::tuple<ConstId, TypePtr> term_const_; const std::tuple<TermPtr, TermPtr> term_comb_; const std::tuple<TermVar, TypePtr, TermPtr> term_abs_; }; }; TermPtr mk_var(TermVar var_id, const TypePtr& type); TermPtr mk_const(ConstId const_id, const std::map<TypeVar, TypePtr>& subst); TermPtr mk_abs(TermVar term_var, const TypePtr& type, const TermPtr& term); TermPtr mk_comb(const TermPtr& function, const TermPtr& argument); ConstId new_constant(const TypePtr& type); const TypePtr& get_const_type(ConstId const_id); // Comparator on terms, which returns 0 for alpha-equal terms int8_t alphaorder(const TermPtr& tm1, const TermPtr& tm2); const TypeCon type_con_bool = static_cast<TypeCon>(0); const TypeCon type_con_fun = static_cast<TypeCon>(1); const TypeVar type_var_alpha = static_cast<TypeVar>("A"); const ConstId const_eq = static_cast<ConstId>(0); const TypePtr type_bool = mk_type(type_con_bool, std::vector<TypePtr>()); const TypePtr type_alpha = mk_vartype(type_var_alpha); class Thm final { // Private struct for make_shared purposes struct Secret {}; public: const std::set<TermPtr, TermOrdering> hyps_; const TermPtr concl_; friend ThmPtr REFL(const TermPtr& term); friend ThmPtr TRANS(const ThmPtr& left_eq, const ThmPtr& right_eq); friend ThmPtr MK_COMB(const ThmPtr& fun_eq, const ThmPtr& arg_eq); friend ThmPtr ABS(const std::tuple<TermVar, TypePtr>& var, const ThmPtr& eq); friend ThmPtr ASSUME(const TermPtr& term); friend ThmPtr BETA(const TermPtr& term); friend ThmPtr EQ_MP(const ThmPtr& prop_eq, const ThmPtr& prop); friend ThmPtr DEDUCT_ANTISYM(const ThmPtr& thm1, const ThmPtr& thm2); friend ThmPtr INST_TYPE(const std::map<TypeVar, TypePtr>& inst, const ThmPtr& thm); friend ThmPtr INST(Substitution* subst, const ThmPtr& thm); friend ThmPtr new_axiom(const TermPtr& term); friend ThmPtr new_basic_definition(const TermPtr& definition); friend std::tuple<TypeCon, std::tuple<ConstId, ConstId>, std::tuple<ThmPtr, ThmPtr> > new_basic_type_definition(const ThmPtr& existence_proof); // Public but uncallable for make_shared use Thm(const std::set<TermPtr, TermOrdering>& hyps, const TermPtr& concl, Secret) : hyps_(hyps), concl_(concl) {} private: static ThmPtr mk(const std::set<TermPtr, TermOrdering>& hyps, const TermPtr& concl) { return std::make_shared<Thm>(hyps, concl, Secret()); } }; // t // -------- // |- t = t ThmPtr REFL(const TermPtr& term); // h1 |- l = m h2 |- m' = r // --------------------------- (provided m alpha-equal to m') // h1 \/ h2 |- l = r ThmPtr TRANS(const ThmPtr& left_eq, const ThmPtr& right_eq); // h1 |- f = g h2 |- a = b // -------------------------- (provided types match) // h1 \/ h2 |- f a = g b ThmPtr MK_COMB(const ThmPtr& fun_eq, const ThmPtr& arg_eq); // v h |- l = r // ------------------ (provided x is free in h) // h |- \v. l = \v. r ThmPtr ABS(const std::tuple<TermVar, TypePtr>& var, const ThmPtr& eq); // t : bool // -------- // t |- t ThmPtr ASSUME(const TermPtr& term); // (\x. t) x // ---------------- // |- (\x. t) x = t ThmPtr BETA(const TermPtr& term); // h1 |- f = g h2 |- f' // ----------------------- (if f is alpha-equal to f') // h1 \/ h2 |- g ThmPtr EQ_MP(const ThmPtr& prop_eq, const ThmPtr& prop); // h1 |- c1 h2 |- c2 // --------------------------------- // (h1 - c2) \/ (h2 - c1) |- c1 = c2 ThmPtr DEDUCT_ANTISYM(const ThmPtr& thm1, const ThmPtr& thm2); // {(v1, t1), ..., (vn, tn)} h |- p // -------------------------------------------- // h[v1:=t1,...,vn:=tn] |- p[v1:=t1,...,vn:=tn] ThmPtr INST_TYPE(const std::map<TypeVar, TypePtr>& inst, const ThmPtr& thm); // {(x1, t1), ..., (xn, tn)} h |- p // -------------------------------------------- // h[x1:=t1,...,xn:=tn] |- p[x1:=t1,...,xn:=tn] ThmPtr INST(Substitution* subst, const ThmPtr& thm); // t : bool // -------- // |- t ThmPtr new_axiom(const TermPtr& term); // t // -------- (provided t has no free variables and all tyvars are in its type) // |- c = t ThmPtr new_basic_definition(const TermPtr& definition); // |- P t // ----------------------------------------------------------------- // ty abs rep |- abs(rep a) = a |- P r = (rep(abs r) = r) std::tuple<TypeCon, std::tuple<ConstId, ConstId>, std::tuple<ThmPtr, ThmPtr> > new_basic_type_definition(const ThmPtr& existence_proof); } // namespace hol #endif // DEEPMATH_HOL_KERNEL_H_
4,893
935
<reponame>kITerE/managarm #pragma once #include <netserver/nic.hpp> #include <core/virtio/core.hpp> namespace nic::virtio { std::shared_ptr<nic::Link> makeShared(std::unique_ptr<virtio_core::Transport>); } // namespace nic::virtio
94
595
<reponame>erique/embeddedsw /****************************************************************************** * Copyright (C) 2018 – 2020 Xilinx, Inc. All rights reserved. * SPDX-License-Identifier: MIT ******************************************************************************/ /*****************************************************************************/ /** * * @file xv_hdmirx1.c * * This is the main file for Xilinx HDMI RX core. Please see xv_hdmirx1.h for * more details of the driver. * * <pre> * MODIFICATION HISTORY: * * Ver Who Date Changes * ----- ------ -------- ------------------------------------------------------- * 1.00 EB 22/06/18 Initial release. * </pre> * ******************************************************************************/ #ifndef XV_HDMIRX1_FRL_H_ #define XV_HDMIRX1_FRL_H_ /**< Prevent circular inclusions * by using protection macros */ #ifdef __cplusplus extern "C" { #endif /***************************** Include Files *********************************/ #include "xil_types.h" #include "xil_assert.h" #include "xstatus.h" /************************** Constant Definitions *****************************/ /**************************** Type Definitions *******************************/ /** @name HDMI RX FRL SCDC Fields * @ { */ typedef enum { XV_HDMIRX1_SCDCFIELD_SINK_VER = 0, XV_HDMIRX1_SCDCFIELD_SOURCE_VER, XV_HDMIRX1_SCDCFIELD_CED_UPDATE, XV_HDMIRX1_SCDCFIELD_SOURCE_TEST_UPDATE, XV_HDMIRX1_SCDCFIELD_FRL_START, XV_HDMIRX1_SCDCFIELD_FLT_UPDATE, XV_HDMIRX1_SCDCFIELD_RSED_UPDATE, XV_HDMIRX1_SCDCFIELD_SCRAMBLER_EN, XV_HDMIRX1_SCDCFIELD_SCRAMBLER_STAT, XV_HDMIRX1_SCDCFIELD_FLT_NO_RETRAIN, XV_HDMIRX1_SCDCFIELD_FRL_RATE, XV_HDMIRX1_SCDCFIELD_FFE_LEVELS, XV_HDMIRX1_SCDCFIELD_FLT_NO_TIMEOUT, XV_HDMIRX1_SCDCFIELD_LNS_LOCK, XV_HDMIRX1_SCDCFIELD_FLT_READY, XV_HDMIRX1_SCDCFIELD_LN0_LTP_REQ, XV_HDMIRX1_SCDCFIELD_LN1_LTP_REQ, XV_HDMIRX1_SCDCFIELD_LN2_LTP_REQ, XV_HDMIRX1_SCDCFIELD_LN3_LTP_REQ, XV_HDMIRX1_SCDCFIELD_CH0_ERRCNT_LSB, XV_HDMIRX1_SCDCFIELD_CH0_ERRCNT_MSB, XV_HDMIRX1_SCDCFIELD_CH1_ERRCNT_LSB, XV_HDMIRX1_SCDCFIELD_CH1_ERRCNT_MSB, XV_HDMIRX1_SCDCFIELD_CH2_ERRCNT_LSB, XV_HDMIRX1_SCDCFIELD_CH2_ERRCNT_MSB, XV_HDMIRX1_SCDCFIELD_CED_CHECKSUM, XV_HDMIRX1_SCDCFIELD_CH3_ERRCNT_LSB, XV_HDMIRX1_SCDCFIELD_CH3_ERRCNT_MSB, XV_HDMIRX1_SCDCFIELD_RSCCNT_LSB, XV_HDMIRX1_SCDCFIELD_RSCCNT_MSB, XV_HDMIRX1_SCDCFIELD_SIZE } XV_HdmiRx1_FrlScdcFieldType; /** @name HDMI RX FRL training state * @ { */ typedef enum { XV_HDMIRX1_FRLSTATE_LTS_L, /* LTS:L*/ /* XV_HDMIRX1_FRLSTATE_LTS_1, // LTS:1*/ XV_HDMIRX1_FRLSTATE_LTS_2, /* LTS:2*/ XV_HDMIRX1_FRLSTATE_LTS_3_RATE_CH, /* LTS:3 (Rate Change)*/ XV_HDMIRX1_FRLSTATE_LTS_3_ARM_LNK_RDY, /* LTS:3 (ARM Link Ready)*/ XV_HDMIRX1_FRLSTATE_LTS_3_ARM_VID_RDY, /* LTS:3 (ARM Video Ready)*/ XV_HDMIRX1_FRLSTATE_LTS_3_LTP_DET, /* LTS:3 (LTP Detected)*/ XV_HDMIRX1_FRLSTATE_LTS_3_TMR, /* LTS:3 (Timer Event)*/ XV_HDMIRX1_FRLSTATE_LTS_3, /* LTS:3*/ XV_HDMIRX1_FRLSTATE_LTS_3_RDY, /* LTS:3 (Ready)*/ /* XV_HDMIRX1_FRLSTATE_LTS_4, // LTS:4*/ /* XV_HDMIRX1_FRLSTATE_LTS_P_ARM, // LTS:P (Step 1)*/ XV_HDMIRX1_FRLSTATE_LTS_P, /* LTS:P*/ XV_HDMIRX1_FRLSTATE_LTS_P_TIMEOUT, /* LTS:P (Timeout)*/ XV_HDMIRX1_FRLSTATE_LTS_P_FRL_RDY, /* LTS:P (FRL_START = 1)*/ XV_HDMIRX1_FRLSTATE_LTS_P_VID_RDY /* LTS:P (Skew Locked)*/ } XV_HdmiRx1_FrlTrainingState; /** @name HDMI RX LTP Type * @ { */ typedef enum { XV_HDMIRX1_LTP_SUCCESS = 0, XV_HDMIRX1_LTP_ALL_ONES, XV_HDMIRX1_LTP_ALL_ZEROES, XV_HDMIRX1_LTP_NYQUIST_CLOCK, XV_HDMIRX1_LTP_RXDDE_COMPLIANCE, XV_HDMIRX1_LTP_LFSR0, XV_HDMIRX1_LTP_LFSR1, XV_HDMIRX1_LTP_LFSR2, XV_HDMIRX1_LTP_LFSR3, XV_HDMIRX1_LTP_FFE_CHANGE = 0xE, XV_HDMIRX1_LTP_RATE_CHANGE } XV_HdmiRx1_FrlLtpType; typedef union { u32 Data; /**< All the 4 lanes */ u8 Byte[4]; /**< Each of the lanes */ } XV_HdmiRx1_FrlFfeAdjType; typedef union { u32 Data; u8 Byte[4]; } XV_HdmiRx1_FrlLtp; /** * This typedef contains DDC registers offset, mask, shift. */ typedef struct { /* XV_HdmiRx1_ScdcFieldType Field; /\**< SCDC Field *\/ */ u8 Offset; /**< Register offset */ u8 Mask; /**< Bits mask */ u8 Shift; /**< Bits shift */ } XV_HdmiRx1_FrlScdcField; /** * This typedef contains audio stream specific data structure */ typedef struct { XV_HdmiRx1_FrlTrainingState TrainingState; /**< Fixed Rate Link * State */ u32 TimerCnt; /**< FRL Timer */ u8 LineRate; /**< Current Line * Rate from FRL * rate*/ u32 CurFrlRate; /**< Current FRL Rate * supported */ u8 Lanes; /**< Current number of * lanes used */ u8 FfeLevels; /**< Number of Supported * FFE Levels for the * current FRL Rate */ u8 FfeSuppFlag; /**< RX Core's support * of FFE Levels */ u8 FltUpdateAsserted; XV_HdmiRx1_FrlLtp Ltp; /**< LTP to be detected * by the RX core and * queried by source. */ XV_HdmiRx1_FrlLtp DefaultLtp; /**< LTP which will be * used by RX core for * link training */ XV_HdmiRx1_FrlFfeAdjType LaneFfeAdjReq; /**< The RxFFE for each * of the lanes */ u8 FltNoTimeout; u8 FltNoRetrain; u8 LtpMatchWaitCounts; u8 LtpMatchedCounts; u8 LtpMatchPollCounts; } XV_HdmiRx1_Frl; /*****************************************************************************/ /** * * This macro enables interrupt in the HDMI RX FRL peripheral. * * @param InstancePtr is a pointer to the XV_HdmiRx1 core instance. * * @return None. * * @note C-style signature: * void XV_HdmiRx1_FrlIntrEnable(XV_HdmiRx1 *InstancePtr) * ******************************************************************************/ #define XV_HdmiRx1_FrlIntrEnable(InstancePtr) \ XV_HdmiRx1_WriteReg((InstancePtr)->Config.BaseAddress, \ (XV_HDMIRX1_FRL_CTRL_SET_OFFSET), (XV_HDMIRX1_FRL_CTRL_IE_MASK)) /*****************************************************************************/ /** * * This macro disables interrupt in the HDMI RX FRL peripheral. * * @param InstancePtr is a pointer to the XV_HdmiRx1 core instance. * * @return None. * * @note C-style signature: * void XV_HdmiRx1_FrlIntrDisable(XV_HdmiRx1 *InstancePtr) * ******************************************************************************/ #define XV_HdmiRx1_FrlIntrDisable(InstancePtr) \ XV_HdmiRx1_WriteReg((InstancePtr)->Config.BaseAddress, \ (XV_HDMIRX1_FRL_CTRL_CLR_OFFSET), (XV_HDMIRX1_FRL_CTRL_IE_MASK)) /*****************************************************************************/ /** * * This macro sets the ratio of video clock to video clock enable of RX Core's * FRL peripheral. * * @param InstancePtr is a pointer to the XHdmi_Rx core instance. * * @param Value specifies the Video Clock * * @return None. * * @note C-style signature: * void XV_HdmiRx1_SetFrlVClkVckeRatio(XV_HdmiRx1 *InstancePtr, * u16 Value) * ******************************************************************************/ #define XV_HdmiRx1_SetFrlVClkVckeRatio(InstancePtr, Value) \ { \ XV_HdmiRx1_WriteReg((InstancePtr)->Config.BaseAddress, \ (XV_HDMIRX1_FRL_VCLK_VCKE_RATIO_OFFSET), \ (Value)); \ } /*****************************************************************************/ /** * * This macro enables FRL Skew Lock Event. * * @param InstancePtr is a pointer to the XV_HdmiRx1 core instance. * * @return None. * * @note C-style signature: * void XV_HdmiRx1_SkewLockEvtEnable(XV_HdmiRx1 *InstancePtr) * ******************************************************************************/ #define XV_HdmiRx1_SkewLockEvtEnable(InstancePtr) \ XV_HdmiRx1_WriteReg((InstancePtr)->Config.BaseAddress, \ (XV_HDMIRX1_FRL_CTRL_SET_OFFSET), \ (XV_HDMIRX1_FRL_CTRL_SKEW_EVT_EN_MASK)) /*****************************************************************************/ /** * * This macro disables FRL Skew Lock Event. * * @param InstancePtr is a pointer to the XV_HdmiRx1 core instance. * * @return None. * * @note C-style signature: * void XV_HdmiRx1_SkewLockEvtDisable(XV_HdmiRx1 *InstancePtr) * ******************************************************************************/ #define XV_HdmiRx1_SkewLockEvtDisable(InstancePtr) \ XV_HdmiRx1_WriteReg((InstancePtr)->Config.BaseAddress, \ (XV_HDMIRX1_FRL_CTRL_CLR_OFFSET), \ (XV_HDMIRX1_FRL_CTRL_SKEW_EVT_EN_MASK)) /************************** Function Prototypes ******************************/ /************************** Variable Declarations ****************************/ /************************** Variable Declarations ****************************/ #ifdef __cplusplus } #endif #endif /* End of protection macro */
4,208
9,402
<gh_stars>1000+ // // This program is used to split fsharp-deeptail.il into separate tests. // // Algorithm is just to split on the newline delimited ldstr opcodes // within the main@ function, and generate file names from the ldstr, // replacing special characters with underscores. // // git rm fsharp-deeptail-* // rm fsharp-deeptail-* // g++ split-fsharp.cpp && ./a.out < fsharp-deeptail.il // git add fsharp-deeptail/* // // Note This is valid C++98 for use with older compilers, where C++11 would be desirable. #include <stdlib.h> #include <iostream> #include <fstream> #include <vector> #include <string> #include <assert.h> #include <string.h> #include <set> #include <stdio.h> using namespace std; #include <sys/stat.h> #ifdef _WIN32 #include <direct.h> #endif typedef vector<string> strings_t; struct test_t { string name; strings_t content; }; typedef vector<test_t> tests_t; static void CreateDir (const char *a) { #ifdef _WIN32 _mkdir (a); #else mkdir (a, 0777); #endif } int main () { typedef set<string> names_t; // consider map<string, vector<string>> tests; names_t names; string line; strings_t prefix; tests_t tests; test_t test_dummy; test_t *test = &test_dummy; strings_t suffix; while (getline (cin, line)) { prefix.push_back (line); if (line == ".entrypoint") break; } CreateDir ("tailcall"); CreateDir ("tailcall/fsharp-deeptail"); const string marker_ldstr = "ldstr \""; // start of each test, and contains name const string marker_ldc_i4_0 = "ldc.i4.0"; // start of suffix while (getline (cin, line)) { // tests are delimited by empty lines if (line.length() == 0) { if (tests.size() && tests.back().name.length()) { names_t::iterator a = names.find(tests.back().name); if (a != names.end()) { fprintf(stderr, "duplicate %s\n", a->c_str()); exit(1); } names.insert(names.end(), tests.back().name); } tests.resize (tests.size () + 1); test = &tests.back (); assert (getline (cin, line)); // tests start with ldstr //printf("%s\n", line.c_str()); const bool ldstr = line.length () >= marker_ldstr.length () && memcmp(line.c_str (), marker_ldstr.c_str (), marker_ldstr.length ()) == 0; const bool ldc_i4_0 = line.length () >= marker_ldc_i4_0.length () && memcmp(line.c_str (), marker_ldc_i4_0.c_str (), marker_ldc_i4_0.length ()) == 0; assert (ldstr || ldc_i4_0); if (ldc_i4_0) { suffix.push_back (line); break; } string name1 = &line [marker_ldstr.length ()]; *strchr ((char*)name1.c_str (), '"') = 0; // truncate at quote test->name = name1.c_str (); #if 1 // Change some chars to underscores. for (string::iterator c = test->name.begin(); c != test->name.end(); ++c) if (strchr("<>", *c)) *c = '_'; #else // remove some chars while (true) { size_t c; if ((c = test->name.find('<')) != string::npos) { test->name = test->name.replace(c, 1, "_"); continue; } if ((c = test->name.find('>')) != string::npos) { test->name = test->name.replace(c, 1, "_"); continue; } if ((c = test->name.find("..")) != string::npos) { test->name = test->name.replace(c, 2, "_"); continue; } if ((c = test->name.find("__")) != string::npos) { test->name = test->name.replace(c, 2, "_"); continue; } if ((c = test->name.find('.')) != string::npos) { test->name = test->name.replace(c, 1, "_"); continue; } break; } #endif //printf("%s\n", test->name.c_str()); } test->content.push_back (line); } while (getline (cin, line)) suffix.push_back (line); for (tests_t::const_iterator t = tests.begin(); t != tests.end(); ++t) { if (t->name.length() == 0) continue; //printf("%s\n", t->name.c_str()); FILE* output = fopen(("tailcall/fsharp-deeptail/" + t->name + ".il").c_str(), "w"); for (strings_t::const_iterator a = prefix.begin(); a != prefix.end(); ++a) fprintf(output, "%s\n", a->c_str()); fputs("\n", output); for (strings_t::const_iterator a = t->content.begin(); a != t->content.end(); ++a) fprintf(output, "%s\n", a->c_str()); fputs("\n", output); for (strings_t::const_iterator a = suffix.begin(); a != suffix.end(); ++a) fprintf(output, "%s\n", a->c_str()); fclose(output); } #if 0 for (names_t::const_iterator t = names.begin(); t != names.end(); ++t) fputs(("\ttailcall/fsharp-deeptail/" + *t + ".il \\\n").c_str(), stdout); for (names_t::const_iterator t = names.begin(); t != names.end(); ++t) fputs(("INTERP_DISABLED_TESTS += tailcall/fsharp-deeptail/" + *t + ".exe\n").c_str(), stdout); for (names_t::const_iterator t = names.begin(); t != names.end(); ++t) fputs(("#PLATFORM_DISABLED_TESTS += tailcall/fsharp-deeptail/" + *t + ".exe\n").c_str(), stdout); for (names_t::const_iterator t = names.begin(); t != names.end(); ++t) fputs(("PLATFORM_DISABLED_TESTS += tailcall/fsharp-deeptail/" + *t + ".exe\n").c_str(), stdout); #endif }
2,155
5,169
<reponame>Gantios/Specs { "name": "ToolProject", "version": "2.0.0", "summary": "this is a convenience tool class for my working.", "homepage": "https://github.com/afeng159/ToolClass", "license": "MIT", "authors": { "<EMAIL>": "<EMAIL>" }, "platforms": { "ios": null }, "source": { "git": "https://github.com/afeng159/ToolClass.git", "tag": "2.0.0" }, "source_files": "ToolProject/Class/*", "public_header_files": "ToolProject/Class/ToolClass.h", "frameworks": "Security", "requires_arc": true }
218
679
<filename>main/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XSpellAlternatives_impl.java<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ import com.sun.star.lang.Locale; public class XSpellAlternatives_impl implements com.sun.star.linguistic2.XSpellAlternatives { String aWord; Locale aLanguage; String[] aAlt; // list of alternatives, may be empty. short nType; // type of failure public XSpellAlternatives_impl( String aWord, Locale aLanguage, short nFailureType, String[] aAlt ) { this.aWord = aWord; this.aLanguage = aLanguage; this.aAlt = aAlt; this.nType = nFailureType; //!! none of these cases should ever occur! //!! values provided only for safety if (this.aWord == null) this.aWord = new String(); if (this.aLanguage == null) this.aLanguage = new Locale(); // having no alternatives is OK though. // still for safety an empty existing array has to be provided. if (this.aAlt == null) this.aAlt = new String[]{}; } // XSpellAlternatives public String getWord() throws com.sun.star.uno.RuntimeException { return aWord; } public Locale getLocale() throws com.sun.star.uno.RuntimeException { return aLanguage; } public short getFailureType() throws com.sun.star.uno.RuntimeException { return nType; } public short getAlternativesCount() throws com.sun.star.uno.RuntimeException { return (short) aAlt.length; } public String[] getAlternatives() throws com.sun.star.uno.RuntimeException { return aAlt; } };
1,006
5,169
{ "name": "HJQCornerRadius", "version": "0.0.1", "summary": "A runTime to improve the performance of the CornerRadius framework of HJQCornerRadius.", "homepage": "https://github.com/XiaoHanGe/HJQCornerRadius", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "韩俊强": "<EMAIL>" }, "platforms": { "ios": "7.0" }, "source": { "git": "https://github.com/XiaoHanGe/HJQCornerRadius.git", "tag": "0.0.1" }, "source_files": "CornerRadius/**/*.{h,m}", "requires_arc": true }
244
1,561
#include <stdio.h> #include <webots/motor.h> #include <webots/robot.h> #include <webots/touch_sensor.h> #include "../../../lib/ts_assertion.h" #include "../../../lib/ts_utils.h" #define TIME_STEP 16 int main(int argc, char **argv) { ts_setup(argv[0]); WbDeviceTag ts = wb_robot_get_device("touch sensor"); WbDeviceTag motor = wb_robot_get_device("linear motor"); wb_touch_sensor_enable(ts, TIME_STEP); int i; for (i = 0; i < 20; i++) { wb_motor_set_position(motor, -0.01 * i); wb_robot_step(TIME_STEP); double value = wb_touch_sensor_get_value(ts); value = wb_touch_sensor_get_value(ts); // printf("i=%d value = %g\n",i,value); if (i < 10) ts_assert_double_in_delta(value, 0.0, 0.0, "The \"bumper\" TouchSensor should return 0.0 when there is no collision."); else ts_assert_double_in_delta(value, 1.0, 0.0, "The \"bumper\" TouchSensor should return 1.0 when there is a collision."); } ts_send_success(); return EXIT_SUCCESS; }
428
317
<filename>Modules/Learning/Supervised/include/otbSVMMachineLearningModel.hxx /* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbSVMMachineLearningModel_hxx #define otbSVMMachineLearningModel_hxx #include <fstream> #include "itkMacro.h" #include "otbSVMMachineLearningModel.h" #include "otbOpenCVUtils.h" namespace otb { template <class TInputValue, class TOutputValue> SVMMachineLearningModel<TInputValue, TOutputValue>::SVMMachineLearningModel() : m_SVMModel(cv::ml::SVM::create()), m_SVMType(CvSVM::C_SVC), m_KernelType(CvSVM::RBF), m_Degree(0), m_Gamma(1), m_Coef0(0), m_C(1), m_Nu(0), m_P(0), m_TermCriteriaType(CV_TERMCRIT_ITER), m_MaxIter(1000), m_Epsilon(FLT_EPSILON), m_ParameterOptimization(false), m_OutputDegree(0), m_OutputGamma(1), m_OutputCoef0(0), m_OutputC(1), m_OutputNu(0), m_OutputP(0) { this->m_ConfidenceIndex = true; this->m_IsRegressionSupported = true; } /** Train the machine learning model */ template <class TInputValue, class TOutputValue> void SVMMachineLearningModel<TInputValue, TOutputValue>::Train() { // Check that the SVM type is compatible with the chosen mode (classif/regression) if (bool(m_SVMType == CvSVM::NU_SVR || m_SVMType == CvSVM::EPS_SVR) != this->m_RegressionMode) { itkGenericExceptionMacro( "SVM type incompatible with chosen mode (classification or regression." "SVM types for classification are C_SVC, NU_SVC, ONE_CLASS. " "SVM types for regression are NU_SVR, EPS_SVR"); } // convert listsample to opencv matrix cv::Mat samples; otb::ListSampleToMat<InputListSampleType>(this->GetInputListSample(), samples); cv::Mat labels; otb::ListSampleToMat<TargetListSampleType>(this->GetTargetListSample(), labels); cv::Mat var_type = cv::Mat(this->GetInputListSample()->GetMeasurementVectorSize() + 1, 1, CV_8U); var_type.setTo(cv::Scalar(CV_VAR_NUMERICAL)); // all inputs are numerical if (!this->m_RegressionMode) // Classification var_type.at<uchar>(this->GetInputListSample()->GetMeasurementVectorSize(), 0) = CV_VAR_CATEGORICAL; m_SVMModel->setType(m_SVMType); m_SVMModel->setKernel(m_KernelType); m_SVMModel->setDegree(m_Degree); m_SVMModel->setGamma(m_Gamma); m_SVMModel->setCoef0(m_Coef0); m_SVMModel->setC(m_C); m_SVMModel->setNu(m_Nu); m_SVMModel->setP(m_P); m_SVMModel->setTermCriteria(cv::TermCriteria(m_TermCriteriaType, m_MaxIter, m_Epsilon)); if (!m_ParameterOptimization) { m_SVMModel->train(cv::ml::TrainData::create(samples, cv::ml::ROW_SAMPLE, labels, cv::noArray(), cv::noArray(), cv::noArray(), var_type)); } else { m_SVMModel->trainAuto(cv::ml::TrainData::create(samples, cv::ml::ROW_SAMPLE, labels, cv::noArray(), cv::noArray(), cv::noArray(), var_type)); } m_OutputDegree = m_SVMModel->getDegree(); m_OutputGamma = m_SVMModel->getGamma(); m_OutputCoef0 = m_SVMModel->getCoef0(); m_OutputC = m_SVMModel->getC(); m_OutputNu = m_SVMModel->getNu(); m_OutputP = m_SVMModel->getP(); } template <class TInputValue, class TOutputValue> typename SVMMachineLearningModel<TInputValue, TOutputValue>::TargetSampleType SVMMachineLearningModel<TInputValue, TOutputValue>::DoPredict(const InputSampleType& input, ConfidenceValueType* quality, ProbaSampleType* proba) const { TargetSampleType target; // convert listsample to Mat cv::Mat sample; otb::SampleToMat<InputSampleType>(input, sample); double result = m_SVMModel->predict(sample); target[0] = static_cast<TOutputValue>(result); if (quality != nullptr) { (*quality) = m_SVMModel->predict(sample, cv::noArray(), cv::ml::StatModel::RAW_OUTPUT); } if (proba != nullptr && !this->m_ProbaIndex) itkExceptionMacro("Probability per class not available for this classifier !"); return target; } template <class TInputValue, class TOutputValue> void SVMMachineLearningModel<TInputValue, TOutputValue>::Save(const std::string& filename, const std::string& name) { cv::FileStorage fs(filename, cv::FileStorage::WRITE); fs << (name.empty() ? m_SVMModel->getDefaultName() : cv::String(name)) << "{"; m_SVMModel->write(fs); fs << "}"; fs.release(); } template <class TInputValue, class TOutputValue> void SVMMachineLearningModel<TInputValue, TOutputValue>::Load(const std::string& filename, const std::string& name) { cv::FileStorage fs(filename, cv::FileStorage::READ); m_SVMModel->read(name.empty() ? fs.getFirstTopLevelNode() : fs[name]); } template <class TInputValue, class TOutputValue> bool SVMMachineLearningModel<TInputValue, TOutputValue>::CanReadFile(const std::string& file) { std::ifstream ifs; ifs.open(file); if (!ifs) { std::cerr << "Could not read file " << file << std::endl; return false; } while (!ifs.eof()) { std::string line; std::getline(ifs, line); // if (line.find(m_SVMModel->getName()) != std::string::npos) if (line.find(CV_TYPE_NAME_ML_SVM) != std::string::npos || line.find(m_SVMModel->getDefaultName()) != std::string::npos) { return true; } } ifs.close(); return false; } template <class TInputValue, class TOutputValue> bool SVMMachineLearningModel<TInputValue, TOutputValue>::CanWriteFile(const std::string& itkNotUsed(file)) { return false; } template <class TInputValue, class TOutputValue> void SVMMachineLearningModel<TInputValue, TOutputValue>::PrintSelf(std::ostream& os, itk::Indent indent) const { // Call superclass implementation Superclass::PrintSelf(os, indent); } } // end namespace otb #endif
2,400
7,746
<reponame>jar-ben/z3 /*++ Copyright (c) 2011 Microsoft Corporation Module Name: probe.h Abstract: Evaluates/Probes a goal. A probe is used to build tactics (aka strategies) that makes decisions based on the structure of a goal. The current implementation is very simple. Author: <NAME> (leonardo) 2011-10-13. Revision History: --*/ #pragma once #include "tactic/goal.h" class probe { public: class result { double m_value; public: result(double v = 0.0):m_value(v) {} result(unsigned v):m_value(static_cast<double>(v)) {} result(int v):m_value(static_cast<double>(v)) {} result(bool b):m_value(b ? 1.0 : 0.0) {} bool is_true() const { return m_value != 0.0; } double get_value() const { return m_value; } }; private: unsigned m_ref_count; public: probe():m_ref_count(0) {} virtual ~probe() {} void inc_ref() { ++m_ref_count; } void dec_ref() { SASSERT(m_ref_count > 0); --m_ref_count; if (m_ref_count == 0) dealloc(this); } virtual result operator()(goal const & g) = 0; }; typedef ref<probe> probe_ref; probe * mk_const_probe(double val); probe * mk_memory_probe(); probe * mk_depth_probe(); probe * mk_size_probe(); /* ADD_PROBE("memory", "amount of used memory in megabytes.", "mk_memory_probe()") ADD_PROBE("depth", "depth of the input goal.", "mk_depth_probe()") ADD_PROBE("size", "number of assertions in the given goal.", "mk_size_probe()") */ probe * mk_num_exprs_probe(); probe * mk_num_consts_probe(); probe * mk_num_bool_consts_probe(); probe * mk_num_arith_consts_probe(); probe * mk_num_bv_consts_probe(); /* ADD_PROBE("num-exprs", "number of expressions/terms in the given goal.", "mk_num_exprs_probe()") ADD_PROBE("num-consts", "number of non Boolean constants in the given goal.", "mk_num_consts_probe()") ADD_PROBE("num-bool-consts", "number of Boolean constants in the given goal.", "mk_num_bool_consts_probe()") ADD_PROBE("num-arith-consts", "number of arithmetic constants in the given goal.", "mk_num_arith_consts_probe()") ADD_PROBE("num-bv-consts", "number of bit-vector constants in the given goal.", "mk_num_bv_consts_probe()") */ probe * mk_produce_proofs_probe(); probe * mk_produce_models_probe(); probe * mk_produce_unsat_cores_probe(); /* ADD_PROBE("produce-proofs", "true if proof generation is enabled for the given goal.", "mk_produce_proofs_probe()") ADD_PROBE("produce-model", "true if model generation is enabled for the given goal.", "mk_produce_models_probe()") ADD_PROBE("produce-unsat-cores", "true if unsat-core generation is enabled for the given goal.", "mk_produce_unsat_cores_probe()") */ probe * mk_has_quantifier_probe(); probe * mk_has_pattern_probe(); /* ADD_PROBE("has-quantifiers", "true if the goal contains quantifiers.", "mk_has_quantifier_probe()") ADD_PROBE("has-patterns", "true if the goal contains quantifiers with patterns.", "mk_has_pattern_probe()") */ // Some basic combinators for probes probe * mk_not(probe * p1); probe * mk_and(probe * p1, probe * p2); probe * mk_or(probe * p1, probe * p2); probe * mk_implies(probe * p1, probe * p2); probe * mk_eq(probe * p1, probe * p2); probe * mk_neq(probe * p1, probe * p2); probe * mk_le(probe * p1, probe * p2); probe * mk_lt(probe * p1, probe * p2); probe * mk_ge(probe * p1, probe * p2); probe * mk_gt(probe * p1, probe * p2); probe * mk_add(probe * p1, probe * p2); probe * mk_sub(probe * p1, probe * p2); probe * mk_mul(probe * p1, probe * p2); probe * mk_div(probe * p1, probe * p2); probe * mk_is_propositional_probe(); probe * mk_is_qfbv_probe(); probe * mk_is_qfaufbv_probe(); probe * mk_is_qfufbv_probe(); /* ADD_PROBE("is-propositional", "true if the goal is in propositional logic.", "mk_is_propositional_probe()") ADD_PROBE("is-qfbv", "true if the goal is in QF_BV.", "mk_is_qfbv_probe()") ADD_PROBE("is-qfaufbv", "true if the goal is in QF_AUFBV.", "mk_is_qfaufbv_probe()") */
1,630
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.recoveryservicesbackup.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; /** Additional information on the backed up item. */ @Fluent public final class MabFileFolderProtectedItemExtendedInfo { @JsonIgnore private final ClientLogger logger = new ClientLogger(MabFileFolderProtectedItemExtendedInfo.class); /* * Last time when the agent data synced to service. */ @JsonProperty(value = "lastRefreshedAt") private OffsetDateTime lastRefreshedAt; /* * The oldest backup copy available. */ @JsonProperty(value = "oldestRecoveryPoint") private OffsetDateTime oldestRecoveryPoint; /* * Number of backup copies associated with the backup item. */ @JsonProperty(value = "recoveryPointCount") private Integer recoveryPointCount; /** * Get the lastRefreshedAt property: Last time when the agent data synced to service. * * @return the lastRefreshedAt value. */ public OffsetDateTime lastRefreshedAt() { return this.lastRefreshedAt; } /** * Set the lastRefreshedAt property: Last time when the agent data synced to service. * * @param lastRefreshedAt the lastRefreshedAt value to set. * @return the MabFileFolderProtectedItemExtendedInfo object itself. */ public MabFileFolderProtectedItemExtendedInfo withLastRefreshedAt(OffsetDateTime lastRefreshedAt) { this.lastRefreshedAt = lastRefreshedAt; return this; } /** * Get the oldestRecoveryPoint property: The oldest backup copy available. * * @return the oldestRecoveryPoint value. */ public OffsetDateTime oldestRecoveryPoint() { return this.oldestRecoveryPoint; } /** * Set the oldestRecoveryPoint property: The oldest backup copy available. * * @param oldestRecoveryPoint the oldestRecoveryPoint value to set. * @return the MabFileFolderProtectedItemExtendedInfo object itself. */ public MabFileFolderProtectedItemExtendedInfo withOldestRecoveryPoint(OffsetDateTime oldestRecoveryPoint) { this.oldestRecoveryPoint = oldestRecoveryPoint; return this; } /** * Get the recoveryPointCount property: Number of backup copies associated with the backup item. * * @return the recoveryPointCount value. */ public Integer recoveryPointCount() { return this.recoveryPointCount; } /** * Set the recoveryPointCount property: Number of backup copies associated with the backup item. * * @param recoveryPointCount the recoveryPointCount value to set. * @return the MabFileFolderProtectedItemExtendedInfo object itself. */ public MabFileFolderProtectedItemExtendedInfo withRecoveryPointCount(Integer recoveryPointCount) { this.recoveryPointCount = recoveryPointCount; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
1,160
3,102
<filename>tools/clang/test/SemaCXX/alignment-of-derived-class.cpp // RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++11 // expected-no-diagnostics // Test that the alignment of a empty direct base class is correctly // inherited by the derived class. struct A { } __attribute__ ((aligned(16))); static_assert(__alignof(A) == 16, "A should be aligned to 16 bytes"); struct B1 : public A { }; static_assert(__alignof(B1) == 16, "B1 should be aligned to 16 bytes"); struct B2 : public A { } __attribute__ ((aligned(2))); static_assert(__alignof(B2) == 16, "B2 should be aligned to 16 bytes"); struct B3 : public A { } __attribute__ ((aligned(4))); static_assert(__alignof(B3) == 16, "B3 should be aligned to 16 bytes"); struct B4 : public A { } __attribute__ ((aligned(8))); static_assert(__alignof(B4) == 16, "B4 should be aligned to 16 bytes"); struct B5 : public A { } __attribute__ ((aligned(16))); static_assert(__alignof(B5) == 16, "B5 should be aligned to 16 bytes"); struct B6 : public A { } __attribute__ ((aligned(32))); static_assert(__alignof(B6) == 32, "B6 should be aligned to 32 bytes");
391
1,745
<reponame>Milerius/bsf //************************************ bs::framework - Copyright 2018 <NAME> **************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #include "String/BsUnicode.h" #include "Platform/BsPlatform.h" #include "Platform/BsDropTarget.h" #include "RenderAPI/BsRenderWindow.h" #include "Math/BsRect2I.h" #include "Private/MacOS/BsMacOSDropTarget.h" #include "Private/MacOS/BsMacOSWindow.h" #include "CoreThread/BsCoreThread.h" namespace bs { Vector<CocoaDragAndDrop::DropArea> CocoaDragAndDrop::sDropAreas; Mutex CocoaDragAndDrop::sMutex; Vector<CocoaDragAndDrop::DragAndDropOp> CocoaDragAndDrop::sQueuedOperations; Vector<CocoaDragAndDrop::DropAreaOp> CocoaDragAndDrop::sQueuedAreaOperations; DropTarget::DropTarget(const RenderWindow* ownerWindow, const Rect2I& area) : mArea(area), mActive(false), mOwnerWindow(ownerWindow), mDropType(DropTargetType::None) { CocoaDragAndDrop::registerDropTarget(this); } DropTarget::~DropTarget() { CocoaDragAndDrop::unregisterDropTarget(this); _clear(); } void DropTarget::setArea(const Rect2I& area) { mArea = area; CocoaDragAndDrop::updateDropTarget(this); } void CocoaDragAndDrop::registerDropTarget(DropTarget* target) { Lock lock(sMutex); sQueuedAreaOperations.push_back(DropAreaOp(target, DropAreaOpType::Register, target->getArea())); } void CocoaDragAndDrop::unregisterDropTarget(DropTarget* target) { Lock lock(sMutex); sQueuedAreaOperations.push_back(DropAreaOp(target, DropAreaOpType::Unregister)); } void CocoaDragAndDrop::updateDropTarget(DropTarget* target) { Lock lock(sMutex); sQueuedAreaOperations.push_back(DropAreaOp(target, DropAreaOpType::Update, target->getArea())); } void CocoaDragAndDrop::update() { THROW_IF_CORE_THREAD // First handle any queued registration/unregistration { Lock lock(sMutex); for(auto& entry : sQueuedAreaOperations) { CocoaWindow* areaWindow; entry.target->_getOwnerWindow()->getCustomAttribute("COCOA_WINDOW", &areaWindow); switch(entry.type) { case DropAreaOpType::Register: sDropAreas.push_back(DropArea(entry.target, entry.area)); areaWindow->_registerForDragAndDrop(); break; case DropAreaOpType::Unregister: // Remove any operations queued for this target for(auto iter = sQueuedOperations.begin(); iter !=sQueuedOperations.end();) { if(iter->target == entry.target) iter = sQueuedOperations.erase(iter); else ++iter; } // Remove the area { auto iterFind = std::find_if(sDropAreas.begin(), sDropAreas.end(), [&](const DropArea& area) { return area.target == entry.target; }); sDropAreas.erase(iterFind); } areaWindow->_unregisterForDragAndDrop(); break; case DropAreaOpType::Update: { auto iterFind = std::find_if(sDropAreas.begin(), sDropAreas.end(), [&](const DropArea& area) { return area.target == entry.target; }); if (iterFind != sDropAreas.end()) iterFind->area = entry.area; } break; } } sQueuedAreaOperations.clear(); } // Actually trigger events Vector<DragAndDropOp> operations; { Lock lock(sMutex); std::swap(operations, sQueuedOperations); } for(auto& op : operations) { switch(op.type) { case DragAndDropOpType::Enter: op.target->onEnter(op.position.x, op.position.y); break; case DragAndDropOpType::DragOver: op.target->onDragOver(op.position.x, op.position.y); break; case DragAndDropOpType::Drop: op.target->_setFileList(op.fileList); op.target->onDrop(op.position.x, op.position.y); break; case DragAndDropOpType::Leave: op.target->_clear(); op.target->onLeave(); break; } } } bool CocoaDragAndDrop::_notifyDragEntered(UINT32 windowId, const Vector2I& position) { THROW_IF_CORE_THREAD bool eventAccepted = false; for(auto& entry : sDropAreas) { UINT32 areaWindowId = 0; entry.target->_getOwnerWindow()->getCustomAttribute("WINDOW_ID", &areaWindowId); if(areaWindowId != windowId) continue; if(entry.area.contains(position)) { if(!entry.target->_isActive()) { Lock lock(sMutex); sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Enter, entry.target, position)); entry.target->_setActive(true); } eventAccepted = true; } } return eventAccepted; } bool CocoaDragAndDrop::_notifyDragMoved(UINT32 windowId, const Vector2I& position) { THROW_IF_CORE_THREAD bool eventAccepted = false; for(auto& entry : sDropAreas) { UINT32 areaWindowId = 0; entry.target->_getOwnerWindow()->getCustomAttribute("WINDOW_ID", &areaWindowId); if(areaWindowId != windowId) continue; if (entry.area.contains(position)) { if (entry.target->_isActive()) { Lock lock(sMutex); sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::DragOver, entry.target, position)); } else { Lock lock(sMutex); sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Enter, entry.target, position)); } entry.target->_setActive(true); eventAccepted = true; } else { // Cursor left previously active target's area if (entry.target->_isActive()) { { Lock lock(sMutex); sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Leave, entry.target)); } entry.target->_setActive(false); } } } return eventAccepted; } void CocoaDragAndDrop::_notifyDragLeft(UINT32 windowId) { THROW_IF_CORE_THREAD for(auto& entry : sDropAreas) { UINT32 areaWindowId = 0; entry.target->_getOwnerWindow()->getCustomAttribute("WINDOW_ID", &areaWindowId); if(areaWindowId != windowId) continue; if(entry.target->_isActive()) { { Lock lock(sMutex); sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Leave, entry.target)); } entry.target->_setActive(false); } } } bool CocoaDragAndDrop::_notifyDragDropped(UINT32 windowId, const Vector2I& position, const Vector<Path>& paths) { THROW_IF_CORE_THREAD bool eventAccepted = false; for(auto& entry : sDropAreas) { UINT32 areaWindowId = 0; entry.target->_getOwnerWindow()->getCustomAttribute("WINDOW_ID", &areaWindowId); if(areaWindowId != windowId) continue; if(!entry.target->_isActive()) continue; Lock lock(sMutex); sQueuedOperations.push_back(DragAndDropOp(DragAndDropOpType::Drop, entry.target, position, paths)); eventAccepted = true; entry.target->_setActive(false); } return eventAccepted; } }
2,801
1,958
package com.freetymekiyan.algorithms.level.medium; import java.util.Arrays; /** * 318. Maximum Product of Word Lengths * <p> * Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not * share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, * return 0. * <p> * Example 1: * <p> * Input: ["abcw","baz","foo","bar","xtfn","abcdef"] * Output: 16 * Explanation: The two words can be "abcw", "xtfn". * Example 2: * <p> * Input: ["a","ab","abc","d","cd","bcd","abcd"] * Output: 4 * Explanation: The two words can be "ab", "cd". * Example 3: * <p> * Input: ["a","aa","aaa","aaaa"] * Output: 0 * Explanation: No such pair of words. * <p> * Companies: Google, Work Applications * <p> * Related Topics: Bit Manipulation */ public class MaximumProductOfWordLengths { public int maxProduct(String[] words) { Arrays.sort(words, (s1, s2) -> s2.length() - s1.length()); int[] masks = new int[words.length]; for (int i = 0; i < words.length; i++) { masks[i] = getBitMask(words[i]); } int max = 0; for (int i = 0; i < words.length - 1; i++) { if (words[i].length() * words[i].length() <= max) break; for (int j = i + 1; j < words.length; j++) { if ((masks[i] & masks[j]) == 0) { max = Math.max(max, words[i].length() * words[j].length()); break; } } } return max; } private int getBitMask(String s) { int mask = 0; for (int i = 0; i < s.length(); i++) { int index = s.charAt(i) - 'a'; mask |= 1 << index; } return mask; } }
667
756
# -*- coding: utf-8 -*- """ Created on Mon Apr 9 11:45:59 2018 @author: tghosh """ import config import numpy as np import os class GloVe: def __init__(self, embd_dim=50): if embd_dim not in [50, 100, 200, 300]: raise ValueError('embedding dim should be one of [50, 100, 200, 300]') self.EMBEDDING_DIM = embd_dim self.embedding_matrix = None def _load(self): print('Reading {} dim GloVe vectors'.format(self.EMBEDDING_DIM)) self.embeddings_index = {} with open(os.path.join(config.GLOVE_DIR, 'glove.6B.'+str(self.EMBEDDING_DIM)+'d.txt'),encoding="utf8") as fin: for line in fin: try: values = line.split() coefs = np.asarray(values[1:], dtype='float32') word = values[0] self.embeddings_index[word] = coefs except: print(line) print('Found %s word vectors.' % len(self.embeddings_index)) def _init_embedding_matrix(self, word_index_dict, oov_words_file='OOV-Words.txt'): self.embedding_matrix = np.zeros((len(word_index_dict)+2 , self.EMBEDDING_DIM)) # +1 for the 0 word index from paddings. not_found_words=0 missing_word_index = [] with open(oov_words_file, 'w') as f: for word, i in word_index_dict.items(): embedding_vector = self.embeddings_index.get(word) if embedding_vector is not None: # words not found in embedding index will be all-zeros. self.embedding_matrix[i] = embedding_vector else: not_found_words+=1 f.write(word + ','+str(i)+'\n') missing_word_index.append(i) #oov by average vector: self.embedding_matrix[1] = np.mean(self.embedding_matrix, axis=0) for indx in missing_word_index: self.embedding_matrix[indx] = np.random.rand(self.EMBEDDING_DIM)+ self.embedding_matrix[1] print("words not found in embeddings: {}".format(not_found_words)) def get_embedding(self, word_index_dict): if self.embedding_matrix is None: self._load() self._init_embedding_matrix(word_index_dict) return self.embedding_matrix def update_embeddings(self, word_index_dict, other_embedding, other_word_index): num_updated = 0 for word, i in other_word_index.items(): if word_index_dict.get(word) is not None: embedding_vector = other_embedding[i] this_vocab_word_indx = word_index_dict.get(word) #print("BEFORE", self.embedding_matrix[this_vocab_word_indx]) self.embedding_matrix[this_vocab_word_indx] = embedding_vector #print("AFTER", self.embedding_matrix[this_vocab_word_indx]) num_updated+=1 print('{} words are updated out of {}'.format(num_updated, len(word_index_dict))) class Word2Vec(GloVe): def __init__(self, embd_dim=50): super().__init__(embd_dim=embd_dim) def _load(self): print('Reading {} dim Gensim Word2Vec vectors'.format(self.EMBEDDING_DIM)) self.embeddings_index = {} with open(os.path.join(config.WORD2VEC_DIR, 'word2vec_'+str(self.EMBEDDING_DIM)+'_imdb.txt'),encoding="utf8") as fin: for line in fin: try: values = line.split() coefs = np.asarray(values[1:], dtype='float32') word = values[0] self.embeddings_index[word] = coefs except: print(line) print('Found %s word vectors.' % len(self.embeddings_index)) #test #glove=Word2Vec(50) #initial_embeddings = glove.get_embedding({'good':2, 'movie':3})
2,067
1,686
<filename>pkg/remote/test/aws_ec2_subnet_multiple/aws_subnet-subnet-05810d3f933925f6d.res.golden.json<gh_stars>1000+ { "Typ": "<KEY> "Val": "<KEY> "Err": null }
76
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Coray","circ":"6ème circonscription","dpt":"Finistère","inscrits":1356,"abs":669,"votants":687,"blancs":32,"nuls":30,"exp":625,"res":[{"nuance":"REM","nom":"<NAME>","voix":358},{"nuance":"LR","nom":"Mme <NAME>","voix":267}]}
110
1,127
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "openvino/frontend/paddle/node_context.hpp" #include "openvino/frontend/paddle/visibility.hpp" #include "openvino/opsets/opset8.hpp" namespace ov { namespace frontend { namespace paddle { namespace op { NamedOutputs matrix_nms(const NodeContext& node) { using namespace opset8; using namespace element; auto bboxes = node.get_input("BBoxes"); auto scores = node.get_input("Scores"); auto score_threshold = node.get_attribute<float>("score_threshold"); auto post_threshold = node.get_attribute<float>("post_threshold"); auto nms_top_k = node.get_attribute<int>("nms_top_k"); auto keep_top_k = node.get_attribute<int>("keep_top_k"); auto background_class = node.get_attribute<int>("background_label"); auto gaussian_sigma = node.get_attribute<float>("gaussian_sigma"); auto use_gaussian = node.get_attribute<bool>("use_gaussian"); auto decay_function = MatrixNms::DecayFunction::LINEAR; if (use_gaussian) { decay_function = MatrixNms::DecayFunction::GAUSSIAN; } auto out_names = node.get_output_names(); PADDLE_OP_CHECK(node, out_names.size() == 3 || out_names.size() == 2, "Unexpected number of outputs of MatrixNMS: " + std::to_string(out_names.size())); element::Type type_num = i32; bool return_rois_num = true; auto it = std::find(out_names.begin(), out_names.end(), "RoisNum"); if (it != out_names.end()) { type_num = node.get_out_port_type("RoisNum"); } else { return_rois_num = false; } auto type_index = node.get_out_port_type("Index"); PADDLE_OP_CHECK(node, (type_index == i32 || type_index == i64) && (type_num == i32 || type_num == i64), "Unexpected data type of outputs of MatrixNMS"); auto normalized = node.get_attribute<bool>("normalized"); NamedOutputs named_outputs; std::vector<Output<Node>> nms_outputs; MatrixNms::Attributes attrs; attrs.nms_top_k = nms_top_k; attrs.post_threshold = post_threshold; attrs.score_threshold = score_threshold; attrs.sort_result_type = MatrixNms::SortResultType::SCORE; attrs.keep_top_k = keep_top_k; attrs.background_class = background_class; attrs.normalized = normalized; attrs.output_type = type_index; attrs.sort_result_across_batch = false; attrs.decay_function = decay_function; attrs.gaussian_sigma = gaussian_sigma; nms_outputs = std::make_shared<MatrixNms>(bboxes, scores, attrs)->outputs(); named_outputs["Out"] = {nms_outputs[0]}; named_outputs["Index"] = {nms_outputs[1]}; if (return_rois_num) { named_outputs["RoisNum"] = {nms_outputs[2]}; if (type_num != type_index) { // adapter auto node_convert = std::make_shared<Convert>(nms_outputs[2], type_num); named_outputs["RoisNum"] = {node_convert}; } } return named_outputs; } } // namespace op } // namespace paddle } // namespace frontend } // namespace ov
1,298
1,479
<reponame>pratyushmahapatra/echo #define arena_bin_index JEMALLOC_N(arena_bin_index) #define arena_boot JEMALLOC_N(arena_boot) #define arena_dalloc JEMALLOC_N(arena_dalloc) #define arena_dalloc_bin JEMALLOC_N(arena_dalloc_bin) #define arena_dalloc_large JEMALLOC_N(arena_dalloc_large) #define arena_malloc JEMALLOC_N(arena_malloc) #define arena_malloc_large JEMALLOC_N(arena_malloc_large) #define arena_malloc_small JEMALLOC_N(arena_malloc_small) #define arena_new JEMALLOC_N(arena_new) #define arena_palloc JEMALLOC_N(arena_palloc) #define arena_prof_accum JEMALLOC_N(arena_prof_accum) #define arena_prof_ctx_get JEMALLOC_N(arena_prof_ctx_get) #define arena_prof_ctx_set JEMALLOC_N(arena_prof_ctx_set) #define arena_prof_promoted JEMALLOC_N(arena_prof_promoted) #define arena_purge_all JEMALLOC_N(arena_purge_all) #define arena_ralloc JEMALLOC_N(arena_ralloc) #define arena_ralloc_no_move JEMALLOC_N(arena_ralloc_no_move) #define arena_run_regind JEMALLOC_N(arena_run_regind) #define arena_salloc JEMALLOC_N(arena_salloc) #define arena_salloc_demote JEMALLOC_N(arena_salloc_demote) #define arena_stats_merge JEMALLOC_N(arena_stats_merge) #define arena_tcache_fill_small JEMALLOC_N(arena_tcache_fill_small) #define arenas_bin_i_index JEMALLOC_N(arenas_bin_i_index) #define arenas_extend JEMALLOC_N(arenas_extend) #define arenas_lrun_i_index JEMALLOC_N(arenas_lrun_i_index) #define atomic_add_uint32 JEMALLOC_N(atomic_add_uint32) #define atomic_add_uint64 JEMALLOC_N(atomic_add_uint64) #define atomic_sub_uint32 JEMALLOC_N(atomic_sub_uint32) #define atomic_sub_uint64 JEMALLOC_N(atomic_sub_uint64) #define base_alloc JEMALLOC_N(base_alloc) #define base_boot JEMALLOC_N(base_boot) #define base_node_alloc JEMALLOC_N(base_node_alloc) #define base_node_dealloc JEMALLOC_N(base_node_dealloc) #define bitmap_full JEMALLOC_N(bitmap_full) #define bitmap_get JEMALLOC_N(bitmap_get) #define bitmap_info_init JEMALLOC_N(bitmap_info_init) #define bitmap_info_ngroups JEMALLOC_N(bitmap_info_ngroups) #define bitmap_init JEMALLOC_N(bitmap_init) #define bitmap_set JEMALLOC_N(bitmap_set) #define bitmap_sfu JEMALLOC_N(bitmap_sfu) #define bitmap_size JEMALLOC_N(bitmap_size) #define bitmap_unset JEMALLOC_N(bitmap_unset) #define bt_init JEMALLOC_N(bt_init) #define buferror JEMALLOC_N(buferror) #define choose_arena JEMALLOC_N(choose_arena) #define choose_arena_hard JEMALLOC_N(choose_arena_hard) #define chunk_alloc JEMALLOC_N(chunk_alloc) #define chunk_alloc_dss JEMALLOC_N(chunk_alloc_dss) #define chunk_alloc_mmap JEMALLOC_N(chunk_alloc_mmap) #define chunk_alloc_mmap_noreserve JEMALLOC_N(chunk_alloc_mmap_noreserve) #define chunk_alloc_swap JEMALLOC_N(chunk_alloc_swap) #define chunk_boot JEMALLOC_N(chunk_boot) #define chunk_dealloc JEMALLOC_N(chunk_dealloc) #define chunk_dealloc_dss JEMALLOC_N(chunk_dealloc_dss) #define chunk_dealloc_mmap JEMALLOC_N(chunk_dealloc_mmap) #define chunk_dealloc_swap JEMALLOC_N(chunk_dealloc_swap) #define chunk_dss_boot JEMALLOC_N(chunk_dss_boot) #define chunk_in_dss JEMALLOC_N(chunk_in_dss) #define chunk_in_swap JEMALLOC_N(chunk_in_swap) #define chunk_mmap_boot JEMALLOC_N(chunk_mmap_boot) #define chunk_swap_boot JEMALLOC_N(chunk_swap_boot) #define chunk_swap_enable JEMALLOC_N(chunk_swap_enable) #define ckh_bucket_search JEMALLOC_N(ckh_bucket_search) #define ckh_count JEMALLOC_N(ckh_count) #define ckh_delete JEMALLOC_N(ckh_delete) #define ckh_evict_reloc_insert JEMALLOC_N(ckh_evict_reloc_insert) #define ckh_insert JEMALLOC_N(ckh_insert) #define ckh_isearch JEMALLOC_N(ckh_isearch) #define ckh_iter JEMALLOC_N(ckh_iter) #define ckh_new JEMALLOC_N(ckh_new) #define ckh_pointer_hash JEMALLOC_N(ckh_pointer_hash) #define ckh_pointer_keycomp JEMALLOC_N(ckh_pointer_keycomp) #define ckh_rebuild JEMALLOC_N(ckh_rebuild) #define ckh_remove JEMALLOC_N(ckh_remove) #define ckh_search JEMALLOC_N(ckh_search) #define ckh_string_hash JEMALLOC_N(ckh_string_hash) #define ckh_string_keycomp JEMALLOC_N(ckh_string_keycomp) #define ckh_try_bucket_insert JEMALLOC_N(ckh_try_bucket_insert) #define ckh_try_insert JEMALLOC_N(ckh_try_insert) #define create_zone JEMALLOC_N(create_zone) #define ctl_boot JEMALLOC_N(ctl_boot) #define ctl_bymib JEMALLOC_N(ctl_bymib) #define ctl_byname JEMALLOC_N(ctl_byname) #define ctl_nametomib JEMALLOC_N(ctl_nametomib) #define extent_tree_ad_first JEMALLOC_N(extent_tree_ad_first) #define extent_tree_ad_insert JEMALLOC_N(extent_tree_ad_insert) #define extent_tree_ad_iter JEMALLOC_N(extent_tree_ad_iter) #define extent_tree_ad_iter_recurse JEMALLOC_N(extent_tree_ad_iter_recurse) #define extent_tree_ad_iter_start JEMALLOC_N(extent_tree_ad_iter_start) #define extent_tree_ad_last JEMALLOC_N(extent_tree_ad_last) #define extent_tree_ad_new JEMALLOC_N(extent_tree_ad_new) #define extent_tree_ad_next JEMALLOC_N(extent_tree_ad_next) #define extent_tree_ad_nsearch JEMALLOC_N(extent_tree_ad_nsearch) #define extent_tree_ad_prev JEMALLOC_N(extent_tree_ad_prev) #define extent_tree_ad_psearch JEMALLOC_N(extent_tree_ad_psearch) #define extent_tree_ad_remove JEMALLOC_N(extent_tree_ad_remove) #define extent_tree_ad_reverse_iter JEMALLOC_N(extent_tree_ad_reverse_iter) #define extent_tree_ad_reverse_iter_recurse JEMALLOC_N(extent_tree_ad_reverse_iter_recurse) #define extent_tree_ad_reverse_iter_start JEMALLOC_N(extent_tree_ad_reverse_iter_start) #define extent_tree_ad_search JEMALLOC_N(extent_tree_ad_search) #define extent_tree_szad_first JEMALLOC_N(extent_tree_szad_first) #define extent_tree_szad_insert JEMALLOC_N(extent_tree_szad_insert) #define extent_tree_szad_iter JEMALLOC_N(extent_tree_szad_iter) #define extent_tree_szad_iter_recurse JEMALLOC_N(extent_tree_szad_iter_recurse) #define extent_tree_szad_iter_start JEMALLOC_N(extent_tree_szad_iter_start) #define extent_tree_szad_last JEMALLOC_N(extent_tree_szad_last) #define extent_tree_szad_new JEMALLOC_N(extent_tree_szad_new) #define extent_tree_szad_next JEMALLOC_N(extent_tree_szad_next) #define extent_tree_szad_nsearch JEMALLOC_N(extent_tree_szad_nsearch) #define extent_tree_szad_prev JEMALLOC_N(extent_tree_szad_prev) #define extent_tree_szad_psearch JEMALLOC_N(extent_tree_szad_psearch) #define extent_tree_szad_remove JEMALLOC_N(extent_tree_szad_remove) #define extent_tree_szad_reverse_iter JEMALLOC_N(extent_tree_szad_reverse_iter) #define extent_tree_szad_reverse_iter_recurse JEMALLOC_N(extent_tree_szad_reverse_iter_recurse) #define extent_tree_szad_reverse_iter_start JEMALLOC_N(extent_tree_szad_reverse_iter_start) #define extent_tree_szad_search JEMALLOC_N(extent_tree_szad_search) #define hash JEMALLOC_N(hash) #define huge_boot JEMALLOC_N(huge_boot) #define huge_dalloc JEMALLOC_N(huge_dalloc) #define huge_malloc JEMALLOC_N(huge_malloc) #define huge_palloc JEMALLOC_N(huge_palloc) #define huge_prof_ctx_get JEMALLOC_N(huge_prof_ctx_get) #define huge_prof_ctx_set JEMALLOC_N(huge_prof_ctx_set) #define huge_ralloc JEMALLOC_N(huge_ralloc) #define huge_ralloc_no_move JEMALLOC_N(huge_ralloc_no_move) #define huge_salloc JEMALLOC_N(huge_salloc) #define iallocm JEMALLOC_N(iallocm) #define icalloc JEMALLOC_N(icalloc) #define idalloc JEMALLOC_N(idalloc) #define imalloc JEMALLOC_N(imalloc) #define ipalloc JEMALLOC_N(ipalloc) #define iralloc JEMALLOC_N(iralloc) #define isalloc JEMALLOC_N(isalloc) #define ivsalloc JEMALLOC_N(ivsalloc) #define jemalloc_darwin_init JEMALLOC_N(jemalloc_darwin_init) #define jemalloc_postfork JEMALLOC_N(jemalloc_postfork) #define jemalloc_prefork JEMALLOC_N(jemalloc_prefork) #define malloc_cprintf JEMALLOC_N(malloc_cprintf) #define malloc_mutex_destroy JEMALLOC_N(malloc_mutex_destroy) #define malloc_mutex_init JEMALLOC_N(malloc_mutex_init) #define malloc_mutex_lock JEMALLOC_N(malloc_mutex_lock) #define malloc_mutex_trylock JEMALLOC_N(malloc_mutex_trylock) #define malloc_mutex_unlock JEMALLOC_N(malloc_mutex_unlock) #define malloc_printf JEMALLOC_N(malloc_printf) #define malloc_write JEMALLOC_N(malloc_write) #define mb_write JEMALLOC_N(mb_write) #define pow2_ceil JEMALLOC_N(pow2_ceil) #define prof_backtrace JEMALLOC_N(prof_backtrace) #define prof_boot0 JEMALLOC_N(prof_boot0) #define prof_boot1 JEMALLOC_N(prof_boot1) #define prof_boot2 JEMALLOC_N(prof_boot2) #define prof_ctx_get JEMALLOC_N(prof_ctx_get) #define prof_ctx_set JEMALLOC_N(prof_ctx_set) #define prof_free JEMALLOC_N(prof_free) #define prof_gdump JEMALLOC_N(prof_gdump) #define prof_idump JEMALLOC_N(prof_idump) #define prof_lookup JEMALLOC_N(prof_lookup) #define prof_malloc JEMALLOC_N(prof_malloc) #define prof_mdump JEMALLOC_N(prof_mdump) #define prof_realloc JEMALLOC_N(prof_realloc) #define prof_sample_accum_update JEMALLOC_N(prof_sample_accum_update) #define prof_sample_threshold_update JEMALLOC_N(prof_sample_threshold_update) #define prof_tdata_init JEMALLOC_N(prof_tdata_init) #define pthread_create JEMALLOC_N(pthread_create) #define rtree_get JEMALLOC_N(rtree_get) #define rtree_get_locked JEMALLOC_N(rtree_get_locked) #define rtree_new JEMALLOC_N(rtree_new) #define rtree_set JEMALLOC_N(rtree_set) #define s2u JEMALLOC_N(s2u) #define sa2u JEMALLOC_N(sa2u) #define stats_arenas_i_bins_j_index JEMALLOC_N(stats_arenas_i_bins_j_index) #define stats_arenas_i_index JEMALLOC_N(stats_arenas_i_index) #define stats_arenas_i_lruns_j_index JEMALLOC_N(stats_arenas_i_lruns_j_index) #define stats_cactive_add JEMALLOC_N(stats_cactive_add) #define stats_cactive_get JEMALLOC_N(stats_cactive_get) #define stats_cactive_sub JEMALLOC_N(stats_cactive_sub) #define stats_print JEMALLOC_N(stats_print) #define szone2ozone JEMALLOC_N(szone2ozone) #define tcache_alloc_easy JEMALLOC_N(tcache_alloc_easy) #define tcache_alloc_large JEMALLOC_N(tcache_alloc_large) #define tcache_alloc_small JEMALLOC_N(tcache_alloc_small) #define tcache_alloc_small_hard JEMALLOC_N(tcache_alloc_small_hard) #define tcache_bin_flush_large JEMALLOC_N(tcache_bin_flush_large) #define tcache_bin_flush_small JEMALLOC_N(tcache_bin_flush_small) #define tcache_boot JEMALLOC_N(tcache_boot) #define tcache_create JEMALLOC_N(tcache_create) #define tcache_dalloc_large JEMALLOC_N(tcache_dalloc_large) #define tcache_dalloc_small JEMALLOC_N(tcache_dalloc_small) #define tcache_destroy JEMALLOC_N(tcache_destroy) #define tcache_event JEMALLOC_N(tcache_event) #define tcache_get JEMALLOC_N(tcache_get) #define tcache_stats_merge JEMALLOC_N(tcache_stats_merge) #define thread_allocated_get JEMALLOC_N(thread_allocated_get) #define thread_allocated_get_hard JEMALLOC_N(thread_allocated_get_hard) #define u2s JEMALLOC_N(u2s)
4,810
1,532
<reponame>OmegaZhou/MAgent #ifndef MAGNET_RENDER_BACKEND_UTILITY_EXCEPTION_H_ #define MAGNET_RENDER_BACKEND_UTILITY_EXCEPTION_H_ #include <string> #include <stdexcept> #include "utility.h" namespace magent { namespace render { class BaseException : public std::runtime_error { public: explicit BaseException(const std::string &message) : std::runtime_error(message) {} explicit BaseException(const char *message) : std::runtime_error(message) {} }; class RenderException : public BaseException { public: explicit RenderException(const std::string &message) : BaseException("magent::render::RenderException: \"" + message + "\"") {} explicit RenderException(const char *message) : BaseException("magent::render::RenderException: \"" + std::string(message) + "\"") {} }; } // namespace render } // namespace magent #endif //MAGNET_RENDER_BACKEND_UTILITY_EXCEPTION_H_
305
797
// // ALPHAConversion.h // Alpha // // Created by <NAME> on 09/06/15. // Copyright © 2015 Unified Sense. All rights reserved. // #import "ALPHADataConverterSource.h" #import "ALPHAConverterManager.h"
78
4,283
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.map.listener; import com.hazelcast.core.EntryEvent; /** * Invoked upon expiration-based removal of an entry. * <p> * Expiration-based entry removals can happen in two different ways: * <ul> * <li> time-to-live-seconds based expiration</li> * <li> max-idle-time based expiration</li> * </ul> * * @param <K> the type of key. * @param <V> the type of value. * * @since 3.6 */ @FunctionalInterface public interface EntryExpiredListener<K, V> extends MapListener { /** * Invoked upon expiration of an entry. * * @param event the event invoked when an entry is expired. */ void entryExpired(EntryEvent<K, V> event); }
398
892
<filename>advisories/unreviewed/2022/05/GHSA-2xxh-f8r3-hvvr/GHSA-2xxh-f8r3-hvvr.json { "schema_version": "1.2.0", "id": "GHSA-2xxh-f8r3-hvvr", "modified": "2022-05-13T01:45:34Z", "published": "2022-05-13T01:45:34Z", "aliases": [ "CVE-2017-3523" ], "details": "Vulnerability in the MySQL Connectors component of Oracle MySQL (subcomponent: Connector/J). Supported versions that are affected are 5.1.40 and earlier. Difficult to exploit vulnerability allows low privileged attacker with network access via multiple protocols to compromise MySQL Connectors. While the vulnerability is in MySQL Connectors, attacks may significantly impact additional products. Successful attacks of this vulnerability can result in takeover of MySQL Connectors. CVSS 3.0 Base Score 8.5 (Confidentiality, Integrity and Availability impacts). CVSS Vector: (CVSS:3.0/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:H/A:H).", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:H/PR:L/UI:N/S:C/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2017-3523" }, { "type": "WEB", "url": "http://www.debian.org/security/2017/dsa-3840" }, { "type": "WEB", "url": "http://www.oracle.com/technetwork/security-advisory/cpuapr2017-3236618.html" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/97982" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
679
1,248
#include "common.h" #include "declarations.h" #include "kernel/vc4_packet.h" //returns max index static uint32_t drawCommon(VkCommandBuffer commandBuffer, int32_t vertexOffset) { assert(commandBuffer); _commandBuffer* cb = commandBuffer; assert(((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->memGuard == 0xDDDDDDDD); //TODO handle cases when submitting >65k vertices in a VBO //TODO HW-2116 workaround //TODO GFXH-515 / SW-5891 workaround //TODO make this as lightweight as possible to make sure //as many drawcalls can be submitted as possible //uint32_t vertexBufferDirty; //uint32_t indexBufferDirty; ///uint32_t viewportDirty; ///uint32_t lineWidthDirty; ///uint32_t depthBiasDirty; ///uint32_t depthBoundsDirty; //uint32_t graphicsPipelineDirty; //uint32_t computePipelineDirty; //uint32_t subpassDirty; //uint32_t blendConstantsDirty; //uint32_t scissorDirty; //uint32_t stencilCompareMaskDirty; //uint32_t stencilWriteMaskDirty; //uint32_t stencilReferenceDirty; //uint32_t descriptorSetDirty; //uint32_t pushConstantDirty; static uint32_t drawCommon1; PROFILESTART(&drawCommon1); //TODO multiple viewports VkViewport vp; vp = cb->graphicsPipeline->viewports[0]; for(uint32_t c = 0; c < cb->graphicsPipeline->dynamicStateCount; ++c) { if(cb->graphicsPipeline->dynamicStates[c] == VK_DYNAMIC_STATE_VIEWPORT) { vp = cb->viewport; } } //if(cb->lineWidthDirty) { //Line width clFit(&commandBuffer->binCl, V3D21_LINE_WIDTH_length); clInsertLineWidth(&commandBuffer->binCl, cb->graphicsPipeline->lineWidth); cb->lineWidthDirty = 0; } //if(cb->viewportDirty) { //Clip Window clFit(&commandBuffer->binCl, V3D21_CLIP_WINDOW_length); clInsertClipWindow(&commandBuffer->binCl, vp.width, vp.height, vp.y, //bottom pixel coord vp.x); //left pixel coord //Vulkan conventions, Y flipped [1...-1] bottom->top //Clipper XY Scaling clFit(&commandBuffer->binCl, V3D21_CLIPPER_XY_SCALING_length); clInsertClipperXYScaling(&commandBuffer->binCl, (float)(vp.width) * 0.5f * 16.0f, 1.0f * (float)(vp.height) * 0.5f * 16.0f); //Viewport Offset clFit(&commandBuffer->binCl, V3D21_VIEWPORT_OFFSET_length); clInsertViewPortOffset(&commandBuffer->binCl, vp.width * 0.5f + vp.x, vp.height * 0.5f + vp.y); cb->viewportDirty = 0; } //if(cb->depthBiasDirty || cb->depthBoundsDirty) { //Configuration Bits clFit(&commandBuffer->binCl, V3D21_CONFIGURATION_BITS_length); clInsertConfigurationBits(&commandBuffer->binCl, 1, //earlyz updates enable cb->graphicsPipeline->depthTestEnable, //earlyz enable cb->graphicsPipeline->depthWriteEnable && cb->graphicsPipeline->depthTestEnable, //z updates enable cb->graphicsPipeline->depthTestEnable ? getCompareOp(cb->graphicsPipeline->depthCompareOp) : V3D_COMPARE_FUNC_ALWAYS, //depth compare func 0, //coverage read mode 0, //coverage pipe select 0, //coverage update mode 0, //coverage read type cb->graphicsPipeline->rasterizationSamples > 1, //rasterizer oversample mode cb->graphicsPipeline->depthBiasEnable, //depth offset enable cb->graphicsPipeline->frontFace == VK_FRONT_FACE_CLOCKWISE, //clockwise !(cb->graphicsPipeline->cullMode & VK_CULL_MODE_BACK_BIT), //enable back facing primitives !(cb->graphicsPipeline->cullMode & VK_CULL_MODE_FRONT_BIT)); //enable front facing primitives clFit(&commandBuffer->binCl, V3D21_DEPTH_OFFSET_length); float depthBiasConstant = cb->graphicsPipeline->depthBiasConstantFactor; float depthBiasSlope = cb->graphicsPipeline->depthBiasSlopeFactor; for(uint32_t c = 0; c < cb->graphicsPipeline->dynamicStateCount; ++c) { if(cb->graphicsPipeline->dynamicStates[c] == VK_DYNAMIC_STATE_DEPTH_BIAS) { depthBiasConstant = cb->depthBiasConstantFactor; depthBiasSlope = cb->depthBiasSlopeFactor; break; } } clInsertDepthOffset(&commandBuffer->binCl, depthBiasConstant, depthBiasSlope); //Vulkan conventions, we expect the resulting NDC space Z axis to be in range [0...1] close->far //cb->graphicsPipeline->minDepthBounds; //Clipper Z Scale and Offset clFit(&commandBuffer->binCl, V3D21_CLIPPER_Z_SCALE_AND_OFFSET_length); //offset, scale float scale = vp.maxDepth - vp.minDepth; float offset = vp.minDepth; clInsertClipperZScaleOffset(&commandBuffer->binCl, offset, scale); cb->vertexBufferDirty = 0; cb->depthBoundsDirty = 0; } //Point size clFit(&commandBuffer->binCl, V3D21_POINT_SIZE_length); clInsertPointSize(&commandBuffer->binCl, 1.0f); //TODO? //Flat Shade Flags clFit(&commandBuffer->binCl, V3D21_FLAT_SHADE_FLAGS_length); clInsertFlatShadeFlags(&commandBuffer->binCl, 0); //GL Shader State clFit(&commandBuffer->binCl, V3D21_GL_SHADER_STATE_length); clInsertShaderState(&commandBuffer->binCl, 0, //shader state record address 0, //extended shader state record cb->graphicsPipeline->vertexAttributeDescriptionCount & 0x7); //number of attribute arrays, 0 -> 8 _shaderModule* vertModule = 0, *fragModule = 0; //it could be that all stages are contained in a single module, or have separate modules if(cb->graphicsPipeline->modules[ulog2(VK_SHADER_STAGE_FRAGMENT_BIT)]) { fragModule = cb->graphicsPipeline->modules[ulog2(VK_SHADER_STAGE_FRAGMENT_BIT)]; } if(cb->graphicsPipeline->modules[ulog2(VK_SHADER_STAGE_VERTEX_BIT)]) { vertModule = cb->graphicsPipeline->modules[ulog2(VK_SHADER_STAGE_VERTEX_BIT)]; } if(!vertModule) { vertModule = fragModule; } if(!fragModule) { fragModule = vertModule; } assert(fragModule); assert(vertModule); assert(fragModule->bos[VK_RPI_ASSEMBLY_TYPE_FRAGMENT]); assert(vertModule->bos[VK_RPI_ASSEMBLY_TYPE_VERTEX]); assert(vertModule->bos[VK_RPI_ASSEMBLY_TYPE_COORDINATE]); PROFILEEND(&drawCommon1); static uint32_t drawCommon2; PROFILESTART(&drawCommon2); //emit shader record ControlListAddress fragCode = { .handle = fragModule->bos[VK_RPI_ASSEMBLY_TYPE_FRAGMENT], .offset = 0, }; ControlListAddress vertCode = { .handle = vertModule->bos[VK_RPI_ASSEMBLY_TYPE_VERTEX], .offset = 0, }; ControlListAddress coordCode = { .handle = vertModule->bos[VK_RPI_ASSEMBLY_TYPE_COORDINATE], .offset = 0, }; commandBuffer->shaderRecCount++; clFit(&commandBuffer->shaderRecCl, 12 * sizeof(uint32_t) + 104 + 8 * 32); ControlList relocCl = commandBuffer->shaderRecCl; uint32_t attribCount = 0; uint32_t attribSelectBits = 0; for(uint32_t c = 0 ; c < cb->graphicsPipeline->vertexAttributeDescriptionCount; ++c) { if(cb->vertexBuffers[cb->graphicsPipeline->vertexAttributeDescriptions[c].binding]) { attribCount++; attribSelectBits |= 1 << cb->graphicsPipeline->vertexAttributeDescriptions[c].location; } } //attrib size is simply how many times we read VPM (x4 bytes) in VS and CS //attrib records: //base address, num bytes, stride are for the kernel side to assemble our vpm //VPM offsets: these would be how many vpm reads were before a specific attrib (x4 bytes) //we don't really have that info, so we have to play with strides/formats uint32_t vertexAttribSize = 0, coordAttribSize = 0; for(uint32_t c = 0; c < cb->graphicsPipeline->vertexAttributeDescriptionCount; ++c) { vertexAttribSize += getFormatBpp(cb->graphicsPipeline->vertexAttributeDescriptions[c].format) >> 3; if(cb->graphicsPipeline->vertexAttributeDescriptions[c].location == 0) { //this should be the vertex coordinates location coordAttribSize = getFormatBpp(cb->graphicsPipeline->vertexAttributeDescriptions[c].format) >> 3; } } assert(vertModule->numVertVPMreads == vertexAttribSize >> 2); assert(vertModule->numCoordVPMreads == coordAttribSize >> 2); if(commandBuffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) { uint32_t offset = commandBuffer->shaderRecCl.nextFreeByteOffset - commandBuffer->shaderRecCl.offset; clFit(&commandBuffer->shaderRecRelocCl, 12); clInsertData(&commandBuffer->shaderRecRelocCl, 4, &offset); offset += 4; clInsertData(&commandBuffer->shaderRecRelocCl, 4, &offset); offset += 4; clInsertData(&commandBuffer->shaderRecRelocCl, 4, &offset); clFit(&commandBuffer->shaderRecRelocCl, 4 * attribCount); for(uint32_t c = 0; c < attribCount; ++c) { uint32_t offset = commandBuffer->shaderRecCl.nextFreeByteOffset - commandBuffer->shaderRecCl.offset + 12 + c * 4; clInsertData(&commandBuffer->shaderRecRelocCl, 4, &offset); } } //number of attribs //3 is the number of type of possible shaders for(uint32_t c = 0; c < (3 + attribCount)*4; ++c) { clInsertNop(&commandBuffer->shaderRecCl); } clFit(&commandBuffer->handlesCl, (3 + 8)*4); clInsertShaderRecord(&commandBuffer->shaderRecCl, &relocCl, &commandBuffer->handlesCl, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesBufOffset + cb->handlesCl.offset, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesSize, !fragModule->hasThreadSwitch, 0, //TODO point size included in shaded vertex data? 1, //enable clipping 0, //TODO fragment number of used uniforms? fragModule->numVaryings, //fragment number of varyings 0, //fragment uniform address? fragCode, //fragment code address 0, //TODO vertex number of used uniforms? attribSelectBits, //vertex attribute array select bits vertexAttribSize, //vertex total attribute size 0, //vertex uniform address vertCode, //vertex shader code address 0, //TODO coordinate number of used uniforms? //TODO how do we know which attribute contains the vertices? //for now the first one will be hardcoded to have the vertices... 1 << 0, //coordinate attribute array select bits coordAttribSize, //coordinate total attribute size 0, //coordinate uniform address coordCode //coordinate shader code address ); uint32_t vertexAttribOffsets[8] = {}; uint32_t coordAttribOffsets[8] = {}; for(uint32_t c = 1; c < 8; ++c) { for(uint32_t d = 0; d < cb->graphicsPipeline->vertexAttributeDescriptionCount; ++d) { if(cb->graphicsPipeline->vertexAttributeDescriptions[d].location < c) { vertexAttribOffsets[c] += getFormatBpp(cb->graphicsPipeline->vertexAttributeDescriptions[d].format) >> 3; } } } for(uint32_t c = 1; c < 8; ++c) { coordAttribOffsets[c] = vertexAttribOffsets[1]; } uint32_t maxIndex = 0xffff; for(uint32_t c = 0 ; c < cb->graphicsPipeline->vertexAttributeDescriptionCount; ++c) { if(cb->vertexBuffers[cb->graphicsPipeline->vertexAttributeDescriptions[c].binding]) { uint32_t formatByteSize = getFormatBpp(cb->graphicsPipeline->vertexAttributeDescriptions[c].format) >> 3; uint32_t stride = cb->graphicsPipeline->vertexBindingDescriptions[cb->graphicsPipeline->vertexAttributeDescriptions[c].binding].stride; if(stride > 0) { uint32_t usedIndices = (cb->vertexBuffers[cb->graphicsPipeline->vertexAttributeDescriptions[c].binding]->boundMem->size - cb->graphicsPipeline->vertexAttributeDescriptions[c].offset - vertexOffset * stride - cb->vertexBufferOffsets[cb->graphicsPipeline->vertexAttributeDescriptions[c].binding] - cb->vertexBuffers[cb->graphicsPipeline->vertexAttributeDescriptions[c].binding]->boundOffset - formatByteSize) / stride; if(usedIndices < maxIndex) { maxIndex = usedIndices; } } ControlListAddress vertexBuffer = { .handle = cb->vertexBuffers[cb->graphicsPipeline->vertexAttributeDescriptions[c].binding]->boundMem->bo, .offset = cb->graphicsPipeline->vertexAttributeDescriptions[c].offset + vertexOffset * stride + cb->vertexBufferOffsets[cb->graphicsPipeline->vertexAttributeDescriptions[c].binding] + cb->vertexBuffers[cb->graphicsPipeline->vertexAttributeDescriptions[c].binding]->boundOffset, }; clInsertAttributeRecord(&commandBuffer->shaderRecCl, &relocCl, &commandBuffer->handlesCl, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesBufOffset + cb->handlesCl.offset, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesSize, vertexBuffer, //reloc address formatByteSize, stride, vertexAttribOffsets[cb->graphicsPipeline->vertexAttributeDescriptions[c].location], //vertex vpm offset coordAttribOffsets[cb->graphicsPipeline->vertexAttributeDescriptions[c].location] //coordinte vpm offset ); } } PROFILEEND(&drawCommon2); static uint32_t drawCommon3; PROFILESTART(&drawCommon3); //write uniforms _pipelineLayout* pl = cb->graphicsPipeline->layout; assert(vertModule->numVertVPMwrites - 3 == fragModule->numVaryings); assert(vertModule->numCoordVPMwrites == 7); uint32_t numTextureSamples = 0; uint32_t numFragUniformReads = 0; //kernel side expects relocations first! for(uint32_t c = 0; c < fragModule->numMappings[VK_RPI_ASSEMBLY_TYPE_FRAGMENT]; ++c) { VkRpiAssemblyMappingEXT mapping = fragModule->mappings[VK_RPI_ASSEMBLY_TYPE_FRAGMENT][c]; if(mapping.mappingType == VK_RPI_ASSEMBLY_MAPPING_TYPE_DESCRIPTOR) { numTextureSamples++; if(mapping.descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER || mapping.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE || mapping.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { _descriptorSet* ds = getMapElement(pl->descriptorSetBindingMap, mapping.descriptorSet); _descriptorImage* di = getMapElement(ds->imageBindingMap, mapping.descriptorBinding); di += mapping.descriptorArrayElement; //emit reloc for texture BO clFit(&commandBuffer->handlesCl, 4); uint32_t idx = clGetHandleIndex(&commandBuffer->handlesCl, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesBufOffset + cb->handlesCl.offset, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesSize, di->imageView->image->boundMem->bo); //emit tex bo reloc index clFit(&commandBuffer->uniformsCl, 4); clInsertData(&commandBuffer->uniformsCl, 4, &idx); if(commandBuffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) { uint32_t offset = commandBuffer->uniformsCl.nextFreeByteOffset - commandBuffer->uniformsCl.offset - 4; clFit(&commandBuffer->uniformRelocCl, 4); clInsertData(&commandBuffer->uniformRelocCl, 4, &offset); } numFragUniformReads++; } else if(mapping.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || mapping.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER || mapping.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC || mapping.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) { _descriptorSet* ds = getMapElement(pl->descriptorSetBindingMap, mapping.descriptorSet); _descriptorBuffer* db = getMapElement(ds->bufferBindingMap, mapping.descriptorBinding); db += mapping.descriptorArrayElement; //emit reloc for BO clFit(&commandBuffer->handlesCl, 4); uint32_t idx = clGetHandleIndex(&commandBuffer->handlesCl, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesBufOffset + cb->handlesCl.offset, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesSize, db->buffer->boundMem->bo); //emit bo reloc index clFit(&commandBuffer->uniformsCl, 4); clInsertData(&commandBuffer->uniformsCl, 4, &idx); if(commandBuffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) { uint32_t offset = commandBuffer->uniformsCl.nextFreeByteOffset - commandBuffer->uniformsCl.offset - 4; clFit(&commandBuffer->uniformRelocCl, 4); clInsertData(&commandBuffer->uniformRelocCl, 4, &offset); } numFragUniformReads++; } else if(mapping.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER || mapping.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER) { _descriptorSet* ds = getMapElement(pl->descriptorSetBindingMap, mapping.descriptorSet); _descriptorTexelBuffer* dtb = getMapElement(ds->texelBufferBindingMap, mapping.descriptorBinding); dtb += mapping.descriptorArrayElement; //emit reloc for BO clFit(&commandBuffer->handlesCl, 4); uint32_t idx = clGetHandleIndex(&commandBuffer->handlesCl, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesBufOffset + cb->handlesCl.offset, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesSize, dtb->bufferView->buffer->boundMem->bo); //emit bo reloc index clFit(&commandBuffer->uniformsCl, 4); clInsertData(&commandBuffer->uniformsCl, 4, &idx); if(commandBuffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) { uint32_t offset = commandBuffer->uniformsCl.nextFreeByteOffset - commandBuffer->uniformsCl.offset - 4; clFit(&commandBuffer->uniformRelocCl, 4); clInsertData(&commandBuffer->uniformRelocCl, 4, &offset); } numFragUniformReads++; } else { assert(0); //shouldn't happen } } } assert(numTextureSamples == fragModule->numTextureSamples); //after relocs we can proceed with the usual uniforms for(uint32_t c = 0; c < fragModule->numMappings[VK_RPI_ASSEMBLY_TYPE_FRAGMENT]; ++c) { VkRpiAssemblyMappingEXT mapping = fragModule->mappings[VK_RPI_ASSEMBLY_TYPE_FRAGMENT][c]; if(mapping.mappingType == VK_RPI_ASSEMBLY_MAPPING_TYPE_PUSH_CONSTANT) { numFragUniformReads++; clFit(&commandBuffer->uniformsCl, 4); clInsertData(&commandBuffer->uniformsCl, 4, cb->pushConstantBufferPixel + mapping.resourceOffset); } else if(mapping.mappingType == VK_RPI_ASSEMBLY_MAPPING_TYPE_DESCRIPTOR) { if(mapping.descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER || mapping.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE || mapping.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) { _descriptorSet* ds = getMapElement(pl->descriptorSetBindingMap, mapping.descriptorSet); _descriptorImage* di = getMapElement(ds->imageBindingMap, mapping.descriptorBinding); di += mapping.descriptorArrayElement; uint32_t cubemapStride = di->imageView->image->size / 6; //fprintf(stderr, "cubemap stride %i\n", cubemapStride); uint32_t numLevels = 0; numLevels = di->imageView->subresourceRange.levelCount < di->imageView->image->miplevels ? di->imageView->subresourceRange.levelCount : di->imageView->image->miplevels; uint32_t params[4]; encodeTextureUniform(params, numLevels - 1, getTextureDataType(di->imageView->interpretedFormat), di->imageView->viewType == VK_IMAGE_VIEW_TYPE_CUBE, cubemapStride >> 12, //cubemap stride in multiples of 4KB (di->imageView->subresourceRange.baseArrayLayer * cubemapStride + di->imageView->image->levelOffsets[0] + di->imageView->image->boundOffset) >> 12, //Image level 0 offset in multiples of 4KB di->imageView->image->height & 2047, di->imageView->image->width & 2047, getMinFilterType(di->sampler->minFilter, di->sampler->mipmapMode), di->sampler->magFilter == VK_FILTER_NEAREST, getWrapMode(di->sampler->addressModeU), getWrapMode(di->sampler->addressModeV), di->sampler->disableAutoLod ); uint32_t size = 0; if(di->imageView->viewType == VK_IMAGE_VIEW_TYPE_1D) { size = 4; } else if(di->imageView->viewType == VK_IMAGE_VIEW_TYPE_2D) { size = 8; } else if(di->imageView->viewType == VK_IMAGE_VIEW_TYPE_CUBE) { size = 12; } else { assert(0); //unsupported } //TMU0_B requires an extra uniform written //we need to signal that somehow from API side //if mode is cubemap we don't need an extra uniform, it's included! if(di->imageView->viewType != VK_IMAGE_VIEW_TYPE_CUBE && di->sampler->disableAutoLod) { size += 4; } numFragUniformReads += size >> 2; //emit tex parameters clFit(&commandBuffer->uniformsCl, size); clInsertData(&commandBuffer->uniformsCl, size, params); } } } //assert(numFragUniformReads == fragModule->numFragUniformReads); PROFILEEND(&drawCommon3); static uint32_t drawCommon4; PROFILESTART(&drawCommon4); uint32_t numVertUniformReads = 0; //vertex and then coordinate for(uint32_t c = 0; c < vertModule->numMappings[VK_RPI_ASSEMBLY_TYPE_VERTEX]; ++c) { VkRpiAssemblyMappingEXT mapping = vertModule->mappings[VK_RPI_ASSEMBLY_TYPE_VERTEX][c]; if(mapping.mappingType == VK_RPI_ASSEMBLY_MAPPING_TYPE_PUSH_CONSTANT) { numVertUniformReads++; clFit(&commandBuffer->uniformsCl, 4); clInsertData(&commandBuffer->uniformsCl, 4, cb->pushConstantBufferVertex + mapping.resourceOffset); } else if(mapping.mappingType == VK_RPI_ASSEMBLY_MAPPING_TYPE_DESCRIPTOR) { } else { assert(0); //shouldn't happen } } assert(numVertUniformReads == vertModule->numVertUniformReads); uint32_t numCoordUniformReads = 0; //if there are no coordinate mappings, just use the vertex ones VkRpiAssemblyTypeEXT coordMappingType = VK_RPI_ASSEMBLY_TYPE_COORDINATE; if(vertModule->numMappings[VK_RPI_ASSEMBLY_TYPE_COORDINATE] < 1) { coordMappingType = VK_RPI_ASSEMBLY_TYPE_VERTEX; } for(uint32_t c = 0; c < vertModule->numMappings[coordMappingType]; ++c) { VkRpiAssemblyMappingEXT mapping = vertModule->mappings[coordMappingType][c]; if(mapping.mappingType == VK_RPI_ASSEMBLY_MAPPING_TYPE_PUSH_CONSTANT) { numCoordUniformReads++; clFit(&commandBuffer->uniformsCl, 4); clInsertData(&commandBuffer->uniformsCl, 4, cb->pushConstantBufferVertex + mapping.resourceOffset); } else if(mapping.mappingType == VK_RPI_ASSEMBLY_MAPPING_TYPE_DESCRIPTOR) { } else { assert(0); //shouldn't happen } } assert(numCoordUniformReads == vertModule->numCoordUniformReads); PROFILEEND(&drawCommon4); return maxIndex; } /* * https://www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#vkCmdDraw */ void RPIFUNC(vkCmdDraw)(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) { PROFILESTART(RPIFUNC(vkCmdDraw)); assert(commandBuffer); if(instanceCount != 1 || firstInstance != 0) { unsigned instancing; UNSUPPORTED(instancing); } assert((firstVertex + vertexCount) <= ((1<<16) - 1)); drawCommon(commandBuffer, 0); _commandBuffer* cb = commandBuffer; //Submit draw call: vertex Array Primitives clFit(&commandBuffer->binCl, V3D21_VERTEX_ARRAY_PRIMITIVES_length); clInsertVertexArrayPrimitives(&commandBuffer->binCl, firstVertex, vertexCount, getPrimitiveMode(cb->graphicsPipeline->topology)); ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->numDrawCallsSubmitted++; PROFILEEND(RPIFUNC(vkCmdDraw)); } VKAPI_ATTR void VKAPI_CALL RPIFUNC(vkCmdDrawIndexed)( VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) { PROFILESTART(RPIFUNC(vkCmdDrawIndexed)); assert(commandBuffer); if(instanceCount != 1 || firstInstance != 0) { unsigned instancing; UNSUPPORTED(instancing); } assert((firstIndex + indexCount) <= ((1<<16) - 1)); uint32_t maxIndex = drawCommon(commandBuffer, vertexOffset); _commandBuffer* cb = commandBuffer; clFit(&commandBuffer->handlesCl, 4); uint32_t idx = clGetHandleIndex(&commandBuffer->handlesCl, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesBufOffset + cb->handlesCl.offset, ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->handlesSize, cb->indexBuffer->boundMem->bo); clInsertGEMRelocations(&commandBuffer->binCl, idx, 0); if(commandBuffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) { uint32_t offset = commandBuffer->binCl.nextFreeByteOffset - commandBuffer->binCl.offset - 8; clFit(&commandBuffer->gemRelocCl, 4); clInsertData(&commandBuffer->gemRelocCl, 4, &offset); } //Submit draw call: vertex Array Primitives clFit(&commandBuffer->binCl, V3D21_VERTEX_ARRAY_PRIMITIVES_length); clInsertIndexedPrimitiveList(&commandBuffer->binCl, maxIndex, //max index cb->indexBuffer->boundOffset + cb->indexBufferOffset + firstIndex * 2, indexCount, 1, //we only support 16 bit indices getPrimitiveMode(cb->graphicsPipeline->topology)); ((CLMarker*)getCPAptrFromOffset(cb->binCl.CPA, cb->binCl.currMarkerOffset))->numDrawCallsSubmitted++; PROFILEEND(RPIFUNC(vkCmdDrawIndexed)); } VKAPI_ATTR void VKAPI_CALL RPIFUNC(vkCmdDrawIndexedIndirect)( VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride) { UNSUPPORTED(vkCmdDrawIndexedIndirect); } VKAPI_ATTR void VKAPI_CALL RPIFUNC(vkCmdDrawIndirect)( VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride) { UNSUPPORTED(vkCmdDrawIndirect); }
10,702
403
/* * Camunda Platform REST API * OpenApi Spec for Camunda Platform REST API. * * The version of the OpenAPI document: 7.16.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.camunda.consulting.openapi.client.model; import java.util.Objects; import java.util.Arrays; import com.camunda.consulting.openapi.client.model.ExternalTaskQueryDto; import com.camunda.consulting.openapi.client.model.HistoricProcessInstanceQueryDto; import com.camunda.consulting.openapi.client.model.ProcessInstanceQueryDto; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * SetRetriesForExternalTasksDto */ @JsonPropertyOrder({ SetRetriesForExternalTasksDto.JSON_PROPERTY_RETRIES, SetRetriesForExternalTasksDto.JSON_PROPERTY_EXTERNAL_TASK_IDS, SetRetriesForExternalTasksDto.JSON_PROPERTY_PROCESS_INSTANCE_IDS, SetRetriesForExternalTasksDto.JSON_PROPERTY_EXTERNAL_TASK_QUERY, SetRetriesForExternalTasksDto.JSON_PROPERTY_PROCESS_INSTANCE_QUERY, SetRetriesForExternalTasksDto.JSON_PROPERTY_HISTORIC_PROCESS_INSTANCE_QUERY }) @JsonTypeName("SetRetriesForExternalTasksDto") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-11-19T11:53:20.948992+01:00[Europe/Berlin]") public class SetRetriesForExternalTasksDto { public static final String JSON_PROPERTY_RETRIES = "retries"; private Integer retries; public static final String JSON_PROPERTY_EXTERNAL_TASK_IDS = "externalTaskIds"; private List<String> externalTaskIds = null; public static final String JSON_PROPERTY_PROCESS_INSTANCE_IDS = "processInstanceIds"; private List<String> processInstanceIds = null; public static final String JSON_PROPERTY_EXTERNAL_TASK_QUERY = "externalTaskQuery"; private ExternalTaskQueryDto externalTaskQuery; public static final String JSON_PROPERTY_PROCESS_INSTANCE_QUERY = "processInstanceQuery"; private ProcessInstanceQueryDto processInstanceQuery; public static final String JSON_PROPERTY_HISTORIC_PROCESS_INSTANCE_QUERY = "historicProcessInstanceQuery"; private HistoricProcessInstanceQueryDto historicProcessInstanceQuery; public SetRetriesForExternalTasksDto retries(Integer retries) { this.retries = retries; return this; } /** * The number of retries to set for the external task. Must be &gt;&#x3D; 0. If this is 0, an incident is created and the task cannot be fetched anymore unless the retries are increased again. Can not be null. * @return retries **/ @javax.annotation.Nullable @ApiModelProperty(value = "The number of retries to set for the external task. Must be >= 0. If this is 0, an incident is created and the task cannot be fetched anymore unless the retries are increased again. Can not be null.") @JsonProperty(JSON_PROPERTY_RETRIES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public Integer getRetries() { return retries; } public void setRetries(Integer retries) { this.retries = retries; } public SetRetriesForExternalTasksDto externalTaskIds(List<String> externalTaskIds) { this.externalTaskIds = externalTaskIds; return this; } public SetRetriesForExternalTasksDto addExternalTaskIdsItem(String externalTaskIdsItem) { if (this.externalTaskIds == null) { this.externalTaskIds = new ArrayList<>(); } this.externalTaskIds.add(externalTaskIdsItem); return this; } /** * The ids of the external tasks to set the number of retries for. * @return externalTaskIds **/ @javax.annotation.Nullable @ApiModelProperty(value = "The ids of the external tasks to set the number of retries for.") @JsonProperty(JSON_PROPERTY_EXTERNAL_TASK_IDS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public List<String> getExternalTaskIds() { return externalTaskIds; } public void setExternalTaskIds(List<String> externalTaskIds) { this.externalTaskIds = externalTaskIds; } public SetRetriesForExternalTasksDto processInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; return this; } public SetRetriesForExternalTasksDto addProcessInstanceIdsItem(String processInstanceIdsItem) { if (this.processInstanceIds == null) { this.processInstanceIds = new ArrayList<>(); } this.processInstanceIds.add(processInstanceIdsItem); return this; } /** * The ids of process instances containing the tasks to set the number of retries for. * @return processInstanceIds **/ @javax.annotation.Nullable @ApiModelProperty(value = "The ids of process instances containing the tasks to set the number of retries for.") @JsonProperty(JSON_PROPERTY_PROCESS_INSTANCE_IDS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public List<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } public SetRetriesForExternalTasksDto externalTaskQuery(ExternalTaskQueryDto externalTaskQuery) { this.externalTaskQuery = externalTaskQuery; return this; } /** * Get externalTaskQuery * @return externalTaskQuery **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_EXTERNAL_TASK_QUERY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public ExternalTaskQueryDto getExternalTaskQuery() { return externalTaskQuery; } public void setExternalTaskQuery(ExternalTaskQueryDto externalTaskQuery) { this.externalTaskQuery = externalTaskQuery; } public SetRetriesForExternalTasksDto processInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { this.processInstanceQuery = processInstanceQuery; return this; } /** * Get processInstanceQuery * @return processInstanceQuery **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PROCESS_INSTANCE_QUERY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public ProcessInstanceQueryDto getProcessInstanceQuery() { return processInstanceQuery; } public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { this.processInstanceQuery = processInstanceQuery; } public SetRetriesForExternalTasksDto historicProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { this.historicProcessInstanceQuery = historicProcessInstanceQuery; return this; } /** * Get historicProcessInstanceQuery * @return historicProcessInstanceQuery **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_HISTORIC_PROCESS_INSTANCE_QUERY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { this.historicProcessInstanceQuery = historicProcessInstanceQuery; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SetRetriesForExternalTasksDto setRetriesForExternalTasksDto = (SetRetriesForExternalTasksDto) o; return Objects.equals(this.retries, setRetriesForExternalTasksDto.retries) && Objects.equals(this.externalTaskIds, setRetriesForExternalTasksDto.externalTaskIds) && Objects.equals(this.processInstanceIds, setRetriesForExternalTasksDto.processInstanceIds) && Objects.equals(this.externalTaskQuery, setRetriesForExternalTasksDto.externalTaskQuery) && Objects.equals(this.processInstanceQuery, setRetriesForExternalTasksDto.processInstanceQuery) && Objects.equals(this.historicProcessInstanceQuery, setRetriesForExternalTasksDto.historicProcessInstanceQuery); } @Override public int hashCode() { return Objects.hash(retries, externalTaskIds, processInstanceIds, externalTaskQuery, processInstanceQuery, historicProcessInstanceQuery); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SetRetriesForExternalTasksDto {\n"); sb.append(" retries: ").append(toIndentedString(retries)).append("\n"); sb.append(" externalTaskIds: ").append(toIndentedString(externalTaskIds)).append("\n"); sb.append(" processInstanceIds: ").append(toIndentedString(processInstanceIds)).append("\n"); sb.append(" externalTaskQuery: ").append(toIndentedString(externalTaskQuery)).append("\n"); sb.append(" processInstanceQuery: ").append(toIndentedString(processInstanceQuery)).append("\n"); sb.append(" historicProcessInstanceQuery: ").append(toIndentedString(historicProcessInstanceQuery)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3,279
504
<reponame>steakknife/pcgeos /*********************************************************************** * * Copyright (c) Geoworks 1995 -- All Rights Reserved * * GEOWORKS CONFIDENTIAL * * PROJECT: Socket * MODULE: PPP Driver * FILE: slcompress.c * * AUTHOR: <NAME>: May 12, 1995 * * ROUTINES: * Name Description * ---- ----------- * sl_compress_init * sl_compress_tcp * sl_uncompress_tcp * * REVISION HISTORY: * Date Name Description * ---- ---- ----------- * 5/12/95 jwu Initial version * * DESCRIPTION: * Van Jacobson TCP header compression. * Routines to compress and uncomopress TCP packets (for * transmission over low speed serial lines). The code is * basically taken straight from the RFC for compressing TCP/IP * headers. * * $Id: slcompress.c,v 1.7 97/04/10 18:37:49 jwu Exp $ * ***********************************************************************/ /* * * Copyright (c) 1989 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * <NAME> (<EMAIL>), Dec 31, 1989: * - Initial distribution. */ #ifdef __HIGHC__ #pragma Comment("@" __FILE__) #endif # include <ppp.h> /* * Handle of memory block holding compression data. * Block must be locked before use. 10/25/95 - jwu */ Handle sc_comp = 0; /*********************************************************************** * sl_compress_init *********************************************************************** * SYNOPSIS: Initialize compression. * CALLED BY: SetVJCompression * RETURN: nothing * * STRATEGY: If data block exists, free it. * If rx_slots and tx_slots are both zero, then return. * Else * allocate data block with enough room for rx_slots * for the receiving state * if no memory, log reason and call lcp_close. * (if we're this low on memory, can't have a decent * connection, anyways.) * else store block handle and initialize slcompress * header in block * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * jwu 5/12/95 Initial Revision * ***********************************************************************/ void sl_compress_init (int rx_slots, int tx_slots, unsigned char cid) { struct slcompress *comp; unsigned short compSize; /* * Free old data block, if any. */ PPPFreeBlock(sc_comp); sc_comp = 0; /* * Only initialize if compression is being used. Allocate the * memory block for storing all the compression state data. * Called from driver's thread so we will own the data block. */ if (rx_slots || tx_slots) { compSize = rx_slots * sizeof(struct cstate_r) + sizeof(struct slcompress); sc_comp = MemAlloc(compSize, HF_DYNAMIC, HAF_ZERO_INIT | HAF_LOCK); if (sc_comp) { /* * Initialize compression header information. Block zeroed * during allocation so only need to set non-zero fields. * Set last_cs to point to what will be the first transmit * slot when it is allocated. */ comp = (struct slcompress *)MemDeref(sc_comp); comp -> sl_size = comp -> last_cs = compSize; comp -> rx_slots = rx_slots; comp -> max_tx_slots = tx_slots; comp -> flags = SLF_TOSS | (cid ? SLF_CID : 0); MemUnlock(sc_comp); } else { link_error = SDE_INSUFFICIENT_MEMORY; LOG3(LOG_IF, (LOG_NO_MEM_COMP)); DOLOG(shutdown_reason = "VJCOMP: Insufficient memory";) lcp_close(0); } } } /* ENCODE encodes a number that is known to be non-zero. ENCODEZ * checks for zero (since zero has to be encoded in the long, 3 byte * form). */ #define ENCODE(n) { \ if ((unsigned short)(n) >= 256) { \ *cp++ = 0; \ cp[1] = (n); \ cp[0] = (n) >> 8; \ cp += 2; \ } else { \ *cp++ = (n); \ } \ } #define ENCODEZ(n) { \ if ((unsigned short)(n) >= 256 || (unsigned short)(n) == 0) { \ *cp++ = 0; \ cp[1] = (n); \ cp[0] = (n) >> 8; \ cp += 2; \ } else { \ *cp++ = (n); \ } \ } /* * Decode a long value. */ #define DECODEL(f) { \ if (*cp == 0) {\ (f) = htonl(ntohl(f) + ((cp[1] << 8) | cp[2])); \ cp += 3; \ } else { \ (f) = htonl(ntohl(f) + (unsigned long)*cp++); \ } \ } #define DECODES(f) { \ if (*cp == 0) {\ (f) = htons(ntohs(f) + ((cp[1] << 8) | cp[2])); \ cp += 3; \ } else { \ (f) = htons(ntohs(f) + (unsigned long)*cp++); \ } \ } #define DECODEU(f) { \ if (*cp == 0) {\ (f) = htons((cp[1] << 8) | cp[2]); \ cp += 3; \ } else { \ (f) = htons((unsigned long)*cp++); \ } \ } /*********************************************************************** * sl_compress_tcp *********************************************************************** * SYNOPSIS: Compress a TCP header. * CALLED BY: ppp_ip_output * RETURN: packet type * * STRATEGY: If packet is not compressible, return TYPE_IP. * If no transmit slots exist, * create one, returning TYPE_IP if no memory * else search for it, starting at first transmit slot * (last points to first) * if not found * if not at max slots, alloc one and insert in * front of list * do uncompressed_tcp if successful else * reuse oldest slot and do uncompressed_tcp * else move slot to front of list * compress header * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * jwu 5/12/95 Initial Revision * ***********************************************************************/ int sl_compress_tcp (PACKET *p, struct iphdr *iph) /*PACKET *p;*/ /* old-style function declaration needed here */ /*struct iphdr *iph;*/ { unsigned int hlen = iph -> ip_hl; struct tcphdr *oth; struct tcphdr *th; unsigned long deltaS, deltaA; unsigned int changes = 0; unsigned char new_seq[16]; unsigned char *cp = new_seq; struct slcompress *comp; struct cstate_t *c, *lastcs; int result = TYPE_IP; /* * Bail if this is an IP fragment or if the TCP packet isn't * `compressible' (i.e. ACK isn't set or some other control bit * is set). (We assume the caller has already made sure the * packet is IP proto TCP). */ if ((iph -> ip_off & htons(0x3ffff)) || p -> MH_dataSize < 40) return (TYPE_IP); th = (struct tcphdr *)&((dword *)iph)[hlen]; if ((th -> th_flags & (TH_SYN|TH_FIN|TH_RST|TH_ACK)) != TH_ACK) return (TYPE_IP); /* * Packet is compressible -- we're going to send either a * COMPRESSED_TCP or UNCOMPRESSED_TCP packet. Either way we need * to locate (or create) the connection state. Special case the * most recently used connection since it's most likely to be used * again & we don't have to do any reordering if it's used. */ MemLock(sc_comp); comp = (struct slcompress *)MemDeref(sc_comp); if (comp -> tx_slots == 0) { unsigned short newSize = comp -> sl_size + sizeof(struct cstate_t); if (MemReAlloc(sc_comp, newSize, HAF_ZERO_INIT)) { comp = (struct slcompress *)MemDeref(sc_comp); c = (struct cstate_t *)((byte *)comp + comp -> sl_size); c -> cst_next = comp -> last_cs; c -> cst_id = comp -> tx_slots++; comp -> sl_size = newSize; goto hlenThenUncomp; } else goto unlockAndReturn; /* no memory for any slots :( */ } /* * Find the connection slot by searching through the circular list, * starting with the first slot (pointed to by the last slot). * The third line of the "if" statement checks both ports at once. */ lastcs = (struct cstate_t *)((byte *)comp + comp -> last_cs); c = (struct cstate_t *)((byte *)comp + lastcs -> cst_next); if (iph -> ip_src != c -> cst_ip.ip_src || iph -> ip_dst != c -> cst_ip.ip_dst || *(dword *)th != ((dword *)&c -> cst_ip)[c -> cst_ip.ip_hl]) { /* * Wasn't the first -- search for it. * * States are kept in a circularly linked list with * last_cs pointing to the end of the list. The * list is kept in lru order by moving a state to the * head of the list whenever it is referenced. Since * the list is short and, empirically, the connection * we want is almost always near the front, we locate * states via linear search. If we don't find a state * for the datagram, the oldest state is (re-)used. */ struct cstate_t *lcs; do { lcs = c; c = (struct cstate_t *)((byte *)comp + c -> cst_next); if (iph -> ip_src == c -> cst_ip.ip_src && iph -> ip_dst == c -> cst_ip.ip_dst && *(dword *)th == ((dword *)&c -> cst_ip)[c -> cst_ip.ip_hl]) goto found; } while (c != lastcs); /* * Didn't find it -- re-use oldest cstate, unless we * are able to allocate a new transmit slot. Send an * uncompressed packet that tells the other side what * connection number we're using for this conversation. * Note that since the state list is circular, the oldest * state points to the newest and we only need to set * last_cs to update the lru linkage. */ if (comp -> tx_slots < comp -> max_tx_slots) { unsigned short newSize = comp -> sl_size + sizeof(struct cstate_t); if (MemReAlloc(sc_comp, newSize, HAF_ZERO_INIT)) { comp = (struct slcompress *)MemDeref(sc_comp); lastcs = (struct cstate_t *)((byte *)comp + comp -> last_cs); c = (struct cstate_t *)((byte *)comp + comp -> sl_size); c -> cst_next = lastcs -> cst_next; /* points to first */ lastcs -> cst_next = comp -> sl_size; /* points to new */ c -> cst_id = comp -> tx_slots++; comp -> sl_size = newSize; goto hlenThenUncomp; } /* else fall through to reuse oldest slot */ } /* * Re-use oldest cstate. (transmit slot) */ comp -> last_cs = (byte *)lcs - (byte *)comp; /* offset in bytes */ hlenThenUncomp: /* * Adjust hlen to include TCP header and convert to bytes. */ hlen += th -> th_off; hlen <<= 2; if (hlen > p -> MH_dataSize) goto unlockAndReturn; else goto uncompressed; found: /* * Found it -- move to the front on the connection list. */ if (c == lastcs) comp -> last_cs = (byte *)lcs - (byte *)comp; else { lcs -> cst_next = c -> cst_next; c -> cst_next = lastcs -> cst_next; lastcs -> cst_next = (byte *)c - (byte *)comp; } } /* * Make sure that only what we expect to change changed. The first * line of the `if' checks the IP protocol version, header length & * type of service. The 2nd line checks the "Don't fragment" bit. * The 3rd line checks the time-to-live and protocol (the protocol * check is unnecessary but costless). The 4th line checks the TCP * header length. The 5th line checks IP options, if any. The 6th * line checks TCP options, if any. If any of these things are * different between the previous & current datagram, we send the * current datagram `uncompressed'. */ oth = (struct tcphdr *)&((dword *)&c -> cst_ip)[hlen]; deltaS = hlen; hlen += th -> th_off; hlen <<= 2; if (hlen > p -> MH_dataSize) goto unlockAndReturn; if (((unsigned short *)iph)[0] != ((unsigned short *)&c -> cst_ip)[0] || ((unsigned short *)iph)[3] != ((unsigned short *)&c -> cst_ip)[3] || ((unsigned short *)iph)[4] != ((unsigned short *)&c -> cst_ip)[4] || th -> th_off != oth -> th_off || (deltaS > 5 && memcmp(iph + 1, &c -> cst_ip + 1, (deltaS - 5) << 2)) || (th -> th_off > 5 && memcmp(th + 1, oth + 1, (th -> th_off - 5) << 2))) goto uncompressed; /* * Figure out which of the changing fields changed. The * receiver expects changes in the order: urgent, window, * ack, seq (the order minimizes the number of temporaries * needed in this section of code). */ if (th -> th_flags & TH_URG) { deltaS = ntohs(th -> th_urp); ENCODEZ(deltaS); changes |= NEW_U; } else if (th -> th_urp != oth -> th_urp) /* argh! URG not set but urp changed -- a sensible * implementation should never do this but RFC793 * doesn't prohibit the change so we have to deal * with it. */ goto uncompressed; if ((deltaS = (unsigned short)(ntohs(th -> th_win) - ntohs(oth -> th_win))) != 0) { ENCODE(deltaS); changes |= NEW_W; } if ((deltaA = ntohl(th -> th_ack) - ntohl(oth -> th_ack)) != 0) { if (deltaA > 0x0000ffff) goto uncompressed; ENCODE(deltaA); changes |= NEW_A; } if ((deltaS = ntohl(th -> th_seq) - ntohl(oth -> th_seq)) != 0) { if (deltaS > 0x0000ffff) goto uncompressed; ENCODE(deltaS); changes |= NEW_S; } switch (changes) { case 0: /* * Nothing changed. If this packet contains data and the * last one didn't, this is probably a data packet following * an ack (normal on an interactive connection) and we send * it compressed. Otherwise it's probably a retransmit, * retransmitted ack or window probe. Send it uncompressed * in case the other side missed the compressed version. */ if (iph -> ip_len != c -> cst_ip.ip_len && ntohs(c -> cst_ip.ip_len) == hlen) break; /* (fall through) */ case SPECIAL_I: case SPECIAL_D: /* * actual changes match one of our special case encodings -- * send packet uncompressed. */ goto uncompressed; case NEW_S|NEW_A: if (deltaS == deltaA && deltaS == ntohs(c -> cst_ip.ip_len) - hlen) { /* special case for echoed terminal traffic */ changes = SPECIAL_I; cp = new_seq; } break; case NEW_S: if (deltaS == ntohs(c -> cst_ip.ip_len) - hlen) { /* special case for data xfer */ changes = SPECIAL_D; cp = new_seq; } break; } deltaS = ntohs(iph -> ip_id) - ntohs(c -> cst_ip.ip_id); if (deltaS != 1) { ENCODEZ(deltaS); changes |= NEW_I; } if (th -> th_flags & TH_PUSH) changes |= TCP_PUSH_BIT; /* * Grab the cksum before we overwrite it below. Then update our * state with this packet's header. */ deltaA = ntohs(th -> th_cksum); memcpy(&c -> cst_ip, iph, hlen); /* * We want to use the original packet as our compressed packet. * (cp - new_seq) is the number of bytes we need for compressed * sequence numbers. In addition we need one byte for the change * mask, one for the connection id and two for the tcp checksum. * So, (cp - new_seq) + 4 bytes of header are needed. hlen is how * many bytes of the original packet to toss so subtract the two to * get the new packet size. */ deltaS = cp - new_seq; cp = (unsigned char *)iph; if ((comp -> flags & SLF_CID) == 0 || comp -> last_xmit != c -> cst_id) { comp -> last_xmit = c -> cst_id; hlen -= deltaS + 4; cp += hlen; *cp++ = changes | NEW_C; *cp++ = c -> cst_id; } else { hlen -= deltaS + 3; cp += hlen; *cp++ = changes; } p -> MH_dataSize -= hlen; p -> MH_dataOffset += hlen; *cp++ = deltaA >> 8; *cp++ = deltaA; memcpy(cp, new_seq, deltaS); result = TYPE_COMPRESSED_TCP; goto unlockAndReturn; uncompressed: /* * Update connection state c & send uncompressed packet ('uncompressed' * means a regular ip/tcp packet but with the 'conversation id' we hope * to use on future compressed packets in the protocol field). */ memcpy(&c -> cst_ip, iph, hlen); iph -> ip_p = c -> cst_id; comp -> last_xmit = c -> cst_id; result = TYPE_UNCOMPRESSED_TCP; unlockAndReturn: MemUnlock(sc_comp); return(result); } /*********************************************************************** * sl_uncompress_tcp *********************************************************************** * SYNOPSIS: Uncompress a TCP header. * CALLED BY: ip_vj_comp_input * ip_vj_uncomp_input * RETURN: length of uncompressed datagram * *bufp pointing to start of decompressed TCP/IP header * * STRATEGY: Find start of receive slots in data block * and proceed with uncompressing the TCP/IP header * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * jwu 5/12/95 Initial Revision * ***********************************************************************/ int sl_uncompress_tcp (unsigned char **bufp, int len, unsigned int type) { struct slcompress *comp; struct cstate_r *c; unsigned char *cp; unsigned int hlen, changes; struct tcphdr *th; struct iphdr *iph; int result = 0; /* * Find start of array of receive slots. */ MemLock(sc_comp); comp = (struct slcompress *)MemDeref(sc_comp); c = (struct cstate_r *)((byte *)comp + sizeof(struct slcompress)); /* * Verify connection id is within range. Replace the connection * id in the IP header with the protocol. Can stop tossing packets * now that we have received an explicit connection id. Copy the * TCP/IP header into the receive slot. Zero checksum field because * it needs to be zero when uncompressing compressed packets. */ if (type == TYPE_UNCOMPRESSED_TCP) { iph = (struct iphdr *) *bufp; if ((int)iph -> ip_p >= comp -> rx_slots) goto bad; c = &c[comp -> last_recv = iph -> ip_p]; comp -> flags &= ~SLF_TOSS; iph -> ip_p = IPPROTO_TCP; hlen = iph -> ip_hl; hlen += ((struct tcphdr *)&((dword *)iph)[hlen]) -> th_off; hlen <<= 2; memcpy(&c -> csr_ip, iph, hlen); c -> csr_ip.ip_cksum = 0; c -> csr_hlen = hlen; result = len; goto unlockAndReturn; } if (type != TYPE_COMPRESSED_TCP) goto bad; /* * We've got a compressed packet. Time to go to work. */ cp = *bufp; changes = *cp++; if (changes & NEW_C) { /* * Make sure the state index is in range, then grab the state. * If we have a good state index, clear the 'discard' flag. */ if ((int)*cp >= comp -> rx_slots) goto bad; comp -> flags &= ~SLF_TOSS; comp -> last_recv = *cp++; } else { /* * This packet has an implicit state index. If we've * had a line error since the last time we got an * explicit state index, we have to toss the packet. */ if (comp -> flags & SLF_TOSS) { goto unlockAndReturn; } } c = &c[comp -> last_recv]; hlen = c -> csr_ip.ip_hl << 2; th = (struct tcphdr *)&((unsigned char *)&c -> csr_ip)[hlen]; th -> th_cksum = htons((*cp << 8) | cp[1]); cp += 2; if (changes & TCP_PUSH_BIT) th -> th_flags |= TH_PUSH; else th -> th_flags &= ~TH_PUSH; switch (changes & SPECIALS_MASK) { case SPECIAL_I: { unsigned int i = ntohs(c -> csr_ip.ip_len) - c -> csr_hlen; th -> th_ack = htonl(ntohl(th -> th_ack) + i); th -> th_seq = htonl(ntohl(th -> th_seq) + i); } break; case SPECIAL_D: { th -> th_seq = htonl(ntohl(th -> th_seq) + ntohs(c -> csr_ip.ip_len) - c -> csr_hlen); } break; default: if (changes & NEW_U) { th -> th_flags |= TH_URG; DECODEU(th -> th_urp) } else th -> th_flags &= ~TH_URG; if (changes & NEW_W) DECODES(th -> th_win) if (changes & NEW_A) DECODEL(th -> th_ack) if (changes & NEW_S) DECODEL(th -> th_seq) break; } if (changes & NEW_I) DECODES(c -> csr_ip.ip_id) else c -> csr_ip.ip_id = htons(ntohs(c -> csr_ip.ip_id) + 1); /* * At this point, cp points to the first byte of data in the * packet. If we're not aligned on a 4-byte boundary, copy the * data forward so the ip & tcp headers will be aligned. Then back up * cp by the tcp/ip header length to make room for the reconstructed * header (we assume the packet we were handed has enough space to * prepend 128 bytes of header). Adjust the length to account for * the new header & fill in the IP total length. */ len -= (cp - *bufp); if (len < 0) /* we must have dropped some characters */ goto bad; if ((unsigned long)cp & 3) { if (len > 0) (void) memmove((char *)((unsigned long)cp & ~3), cp, len); cp = (unsigned char *)((unsigned long)cp & ~3); } cp -= c -> csr_hlen; len += c -> csr_hlen; c -> csr_ip.ip_len = htons(len); memcpy(cp, &c -> csr_ip, c -> csr_hlen); *bufp = cp; /* recompute the ip header checksum */ { unsigned short *bp = (unsigned short *)cp; unsigned long chksum; for (chksum = 0; hlen > 0; hlen -= 2) chksum += *bp++; chksum = (chksum & 0x0000ffff) + (chksum >> 16); chksum = (chksum & 0x0000ffff) + (chksum >> 16); ((struct iphdr *)cp) -> ip_cksum = ~chksum; } result = len; goto unlockAndReturn; bad: comp -> flags |= SLF_TOSS; unlockAndReturn: MemUnlock(sc_comp); return (result); }
9,416
764
<filename>erc20/0x0f1Ed66c251BcB52ecF7E67ac64Bb72482048aDB.json { "symbol": "SEER", "address": "0x0f1Ed66c251BcB52ecF7E67ac64Bb72482048aDB", "overview":{ "en": "SEER is a Public Blockchain Platform For Sports Industry,Based on Graphene Toolkit.SEER USES the market mechanism to let users express their judgment on future events and gather the wisdom and views of many people to effectively predict future events. SEER provides a neutral and credible decentralized reality prediction market service for users by introducing the function of multi-host decentralized prediction machine (Oracle). At the same time, SEER integrates the council and arbitration mechanism, making SEER efficient, neutral, credible and autonomous.", "zh": "SEER是一条服务文化体育行业的高性能区块链底层公链,基于石墨烯技术开发,集成下一代现实预测市场、资产发行流转和赛事众筹等模块,任何人都能很方便地在其上搭建DAPP。SEER特性有:纯公链设计、自动调节的系统参数、避免分叉的中枢神经协议等。" }, "email": "<EMAIL>", "website": "https://seer.best", "whitepaper": "https://www.seer.best/download/SEER_cn.pdf", "state": "NORMAL", "published_on": "2018-01-09", "initial_price":{ "ETH":"0.000005 ETH", "USD":"0.0009 USD", "BTC":"0.00000011 BTC" }, "links": { "blog": "https://seer.best/index.php?catid=3", "twitter": "https://twitter.com/info_seer", "telegram": "https://t.me/Seer_English_Group", "github": "https://github.com/seer-project", "facebook": "https://www.facebook.com/groups/SEERatBITFINEX/" } }
722
519
<reponame>dlsimple/rds_dbsync<gh_stars>100-1000 #ifndef PG_MISC_H #define PG_MISC_H #include "postgres_fe.h" #include "lib/stringinfo.h" #include "lib/stringinfo.h" #include "common/fe_memutils.h" #include "libpq-fe.h" #include "access/transam.h" #include "libpq/pqformat.h" #include "pqexpbuffer.h" #ifdef WIN32 typedef CRITICAL_SECTION pthread_mutex_t; typedef HANDLE ThreadHandle; typedef DWORD ThreadId; typedef unsigned thid_t; typedef struct Thread { ThreadHandle os_handle; thid_t thid; }Thread; typedef CRITICAL_SECTION pthread_mutex_t; typedef DWORD pthread_t; #define pthread_mutex_lock(A) (EnterCriticalSection(A),0) #define pthread_mutex_trylock(A) win_pthread_mutex_trylock((A)) #define pthread_mutex_unlock(A) (LeaveCriticalSection(A), 0) #define pthread_mutex_init(A,B) (InitializeCriticalSection(A),0) #define pthread_mutex_lock(A) (EnterCriticalSection(A),0) #define pthread_mutex_trylock(A) win_pthread_mutex_trylock((A)) #define pthread_mutex_unlock(A) (LeaveCriticalSection(A), 0) #define pthread_mutex_destroy(A) (DeleteCriticalSection(A), 0) #else typedef pthread_t ThreadHandle; typedef pthread_t ThreadId; typedef pthread_t thid_t; typedef struct Thread { pthread_t os_handle; } Thread; #define SIGALRM 14 #endif #define MaxAllocSize ((Size) 0x3fffffff) /* 1 gigabyte - 1 */ extern bool WaitThreadEnd(int n, Thread *th); extern void ThreadExit(int code); extern int ThreadCreate(Thread *th, void *(*start)(void *arg), void *arg); extern PGconn *pglogical_connect(const char *connstring, const char *connname); extern bool is_greenplum(PGconn *conn); extern size_t quote_literal_internal(char *dst, const char *src, size_t len); extern int start_copy_origin_tx(PGconn *conn, const char *snapshot, int pg_version, bool is_greenplum); extern int finish_copy_origin_tx(PGconn *conn); extern int start_copy_target_tx(PGconn *conn, int pg_version, bool is_greenplum); extern int finish_copy_target_tx(PGconn *conn); extern int ExecuteSqlStatement(PGconn *conn, const char *query); extern int setup_connection(PGconn *conn, int remoteVersion, bool is_greenplum); #endif
844
807
/* *Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.testing.security.firingrange.tests.reflected; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.testing.security.firingrange.utils.Responses; import com.google.testing.security.firingrange.utils.Templates; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Handles reflected XSS on JSON via content sniffing. Note that this method reacts * to a callback parameter which is not directly linked from the HTML pages. Scanners * should be able to identify it themselves. */ public class ContentSniffing extends HttpServlet { @VisibleForTesting static final String ECHOED_PARAM = "q"; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String echoedParam = Strings.nullToEmpty(request.getParameter(ECHOED_PARAM)); echoedParam = echoedParam.replace("\"", "\\\""); String template = Templates.getTemplate("json.tmpl", getClass()); String testType = Splitter.on('/').splitToList(request.getPathInfo()).get(1); String contentType; switch (testType) { case "json": contentType = "application/json"; break; case "plaintext": contentType = "text/plain"; break; default: throw new IllegalArgumentException(); } Responses.sendXssed(response, Templates.replacePayload(template, echoedParam), contentType); } }
673
2,270
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2020 - Raw Material Software Limited JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 6 End-User License Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020). End User License Agreement: www.juce.com/juce-6-licence Privacy Policy: www.juce.com/juce-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ #pragma once //============================================================================== namespace CodeHelpers { String indent (const String& code, int numSpaces, bool indentFirstLine); String unindent (const String& code, int numSpaces); String createIncludeStatement (const File& includedFile, const File& targetFile); String createIncludeStatement (const String& includePath); String createIncludePathIncludeStatement (const String& includedFilename); String stringLiteral (const String& text, int maxLineLength = -1); String floatLiteral (double value, int numDecPlaces); String boolLiteral (bool value); String colourToCode (Colour); String justificationToCode (Justification); String alignFunctionCallParams (const String& call, const StringArray& parameters, int maxLineLength); String getLeadingWhitespace (String line); int getBraceCount (String::CharPointerType line); bool getIndentForCurrentBlock (CodeDocument::Position pos, const String& tab, String& blockIndent, String& lastLineIndent); }
640
472
import os import torch import logging import numpy as np import pickle from common.speedometer import BatchEndParam from common.utility.image_processing_cv import trans_coords_from_patch_to_org_3d from common.utility.image_processing_cv import rescale_pose_from_patch_to_camera from torch.nn.parallel.scatter_gather import gather from common_pytorch.common_loss.loss_recorder import LossRecorder from common.utility.image_processing_cv import flip def trainNet(nth_epoch, train_data_loader, network, optimizer, loss_config, loss_func, speedometer=None): """ :param nth_epoch: :param train_data_loader: batch_size, dataset.db_length :param network: :param optimizer: :param loss_config: :param loss_func: :param speedometer: :param tensor_board: :return: """ network.train() loss_recorder = LossRecorder() for idx, _data in enumerate(train_data_loader): batch_data = _data[0] batch_label = _data[1] batch_label_weight = _data[2] optimizer.zero_grad() batch_data = batch_data.cuda() batch_label = batch_label.cuda() batch_label_weight = batch_label_weight.cuda() preds = network(batch_data) del batch_data loss = loss_func(preds, batch_label, batch_label_weight) del batch_label, batch_label_weight del preds loss.backward() optimizer.step() loss_recorder.update(loss.detach(), train_data_loader.batch_size) del loss if speedometer != None: speedometer(BatchEndParam(epoch=nth_epoch, nbatch=idx, total_batch=train_data_loader.dataset.db_length // train_data_loader.batch_size, add_step=True, eval_metric=None, loss_metric=loss_recorder, locals=locals())) return loss_recorder.get_avg() def validNet(valid_data_loader, network, loss_config, result_func, loss_func, merge_flip_func, patch_width, patch_height, devices, flip_pair, flip_test=True, flip_fea_merge=True): """ :param nth_epoch: :param valid_data_loader: :param network: :param loss_config: :param result_func: :param loss_func: :param patch_size: :param devices: :param tensor_board: :return: """ print('in valid') network.eval() loss_recorder = LossRecorder() preds_in_patch_with_score = [] with torch.no_grad(): for idx, _data in enumerate(valid_data_loader): batch_data = _data[0] if batch_data.shape[1] != 3: flip_test = False batch_label = _data[1] batch_label_weight = _data[2] batch_data = batch_data.cuda() batch_label = batch_label.cuda() batch_label_weight = batch_label_weight.cuda() preds = network(batch_data) if flip_test: batch_data_flip = flip(batch_data, dims=3) preds_flip = network(batch_data_flip) del batch_data # loss loss = loss_func(preds, batch_label, batch_label_weight) del batch_label loss_recorder.update(loss.detach(), valid_data_loader.batch_size) del loss # get joint result in patch image if len(devices) > 1: preds = gather(preds, 0) if flip_test: if len(devices) > 1: preds_flip = gather(preds_flip, 0) if flip_fea_merge: preds = merge_flip_func(preds, preds_flip, flip_pair) preds_in_patch_with_score.append(result_func(loss_config, patch_width, patch_height, preds)) else: pipws = result_func(loss_config, patch_width, patch_height, preds) pipws_flip = result_func(loss_config, patch_width, patch_height, preds_flip) pipws_flip[:, :, 0] = patch_width - pipws_flip[:, :, 0] - 1 for pair in flip_pair: tmp = pipws_flip[:, pair[0], :].copy() pipws_flip[:, pair[0], :] = pipws_flip[:, pair[1], :].copy() pipws_flip[:, pair[1], :] = tmp.copy() preds_in_patch_with_score.append((pipws + pipws_flip) * 0.5) else: preds_in_patch_with_score.append(result_func(loss_config, patch_width, patch_height, preds)) del preds, batch_label_weight _p = np.asarray(preds_in_patch_with_score) _p = _p.reshape((_p.shape[0] * _p.shape[1], _p.shape[2], _p.shape[3])) preds_in_patch_with_score = _p[0: valid_data_loader.dataset.num_samples] return preds_in_patch_with_score, loss_recorder.get_avg() def evalNet(nth_epoch, preds_in_patch_with_score, valid_data_loader, imdb, patch_width, patch_height , rect_3d_width, rect_3d_height, final_output_path): """ :param nth_epoch: :param preds_in_patch_with_score: :param gts: :param convert_func: :param eval_func: :return: """ print("in eval") # From patch to original image coordinate system imdb_list = valid_data_loader.dataset.db preds_in_img_with_score = [] for n_sample in range(valid_data_loader.dataset.num_samples): preds_in_img_with_score.append( trans_coords_from_patch_to_org_3d(preds_in_patch_with_score[n_sample], imdb_list[n_sample]['center_x'], imdb_list[n_sample]['center_y'], imdb_list[n_sample]['width'], imdb_list[n_sample]['height'], patch_width, patch_height, rect_3d_width, rect_3d_height)) preds_in_img_with_score = np.asarray(preds_in_img_with_score) # Evaluate name_value = imdb.evaluate(preds_in_img_with_score.copy(), final_output_path) for name, value in name_value: logging.info('Epoch[%d] Validation-%s=%f', nth_epoch, name, value) def evalNetChallenge(nth_epoch, preds_in_patch, valid_data_loader, imdb, final_output_path): """ :param nth_epoch: :param preds_in_patch_with: :param gts: :param convert_func: :param eval_func: :return: """ target_bone_length = 4502.881 # train+val # target_bone_length = 4522.828 # train # target_bone_length = 4465.869 # val print("in eval") # 4. From patch to original image coordinate system imdb_list = valid_data_loader.dataset.db preds_in_camera_space = [] for n_sample in range(valid_data_loader.dataset.num_samples): preds_in_camera_space.append( rescale_pose_from_patch_to_camera(preds_in_patch[n_sample], target_bone_length, imdb_list[n_sample]['parent_ids'])) preds_in_camera_space = np.asarray(preds_in_camera_space)[:, :, 0:3] # 5. Convert joint type preds_in_camera_space_cvt = preds_in_camera_space.copy() # 6. Evaluate name_value = imdb.evaluate(preds_in_camera_space_cvt, final_output_path) for name, value in name_value: logging.info('Epoch[%d] Validation-%s=%f', nth_epoch, name, value) return preds_in_patch
3,539
755
<gh_stars>100-1000 /* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import java.util.UUID; import javax.annotation.Nullable; import io.reactivex.ObservableTransformer; import io.reactivex.Observer; /** * Manges unlocking, locking, and destroying observables based on the lifecycle of an activity or * fragment. An Activity or fragment must call: * <ul> * <li>{@link #onCreate(ObservableManager, Bundle, Object)}</li> * <li>{@link #onResume()}</li> * <li>{@link #onPause()}</li> * <li>{@link #onDestroy(Activity)}</li> * <li>{@link #onSaveInstanceState(Bundle)}</li> * </ul> * in corresponding methods. */ @SuppressWarnings("WeakerAccess") public class GroupLifecycleManager { private static final String KEY_STATE = "KEY_GROUPLIFECYCLEMANAGER_STATE"; private final ObservableManager observableManager; private final ObservableGroup group; private boolean hasSavedState; private GroupLifecycleManager(ObservableManager observableManager, ObservableGroup group) { this.observableManager = observableManager; this.group = group; } /** Call this method from your Activity or Fragment's onCreate method */ public static GroupLifecycleManager onCreate(ObservableManager observableManager, @Nullable Bundle savedState, @Nullable Object target) { ObservableGroup group; if (savedState != null) { State state = savedState.getParcelable(KEY_STATE); Preconditions.checkState(state != null, "Must call onSaveInstanceState() first"); // First check the instance ID before restoring state. If it's not the same instance, // then we have to create a new group since the previous one is already destroyed. // Android can sometimes reuse the same instance after saving state and we can't reliably // determine when that happens. This is a workaround for that behavior. if (state.managerId != observableManager.id()) { group = observableManager.newGroup(); } else { group = observableManager.getGroup(state.groupId); } } else { group = observableManager.newGroup(); } group.lock(); GroupLifecycleManager manager = new GroupLifecycleManager(observableManager, group); if (target != null) { manager.initializeAutoTaggingAndResubscription(target); } return manager; } /** @return the {@link ObservableGroup} associated to this instance */ public ObservableGroup group() { return group; } /** * Calls {@link ObservableGroup#transform(Observer)} for the group managed by * this instance. */ public <T> ObservableTransformer<? super T, T> transform(Observer<? super T> observer) { return group.transform(observer); } /** * Calls {@link ObservableGroup#transform(Observer, String)} for the group managed by * this instance. */ public <T> ObservableTransformer<? super T, T> transform(Observer<? super T> observer, String observableTag) { return group.transform(observer, observableTag); } /** * Call {@link ObservableGroup#hasObservables(Observer)} for the group managed by * this instance. */ public boolean hasObservables(Observer<?> observer) { return group.hasObservables(observer); } /** * Call {@link ObservableGroup#hasObservable(Observer, String)} for the group managed by * this instance. */ public boolean hasObservable(Observer<?> observer, String observableTag) { return group.hasObservable(observer, observableTag); } /** * Calls * {@link ObservableGroup#initializeAutoTaggingAndResubscription(Object)} (Object, Class)} * for the group managed by this instance. */ public void initializeAutoTaggingAndResubscription(Object target) { Preconditions.checkNotNull(target, "Target cannot be null"); group.initializeAutoTaggingAndResubscription(target); } /** * Calls * {@link ObservableGroup#initializeAutoTaggingAndResubscriptionInTargetClassOnly(Object, Class)} * for the group managed by this instance. */ public <T> void initializeAutoTaggingAndResubscriptionInTargetClassOnly(T target, Class<T> targetClass) { group.initializeAutoTaggingAndResubscriptionInTargetClassOnly(target, targetClass); } /** * Calls {@link ObservableGroup#cancelAllObservablesForObserver(Observer)} (Observer)} * for the group associated with this instance. */ public void cancelAllObservablesForObserver(Observer<?> observer) { group.cancelAllObservablesForObserver(observer); } /** * Calls {@link ObservableGroup#cancelAndRemove(Observer, String)} for the group * associated with this instance. */ public void cancelAndRemove(Observer<?> observer, String observableTag) { group.cancelAndRemove(observer, observableTag); } private void onDestroy(boolean isFinishing) { if (isFinishing) { observableManager.destroy(group); } else { group().removeNonResubscribableObservers(); group.dispose(); } } /** Call this method from your Activity or Fragment's onDestroy method */ public void onDestroy(@Nullable Activity activity) { // We need to track whether the current Activity is finishing or not in order to decide if we // should destroy the ObservableGroup. If the Activity is not finishing, then we should not // destroy it, since we know that we're probably restoring state at some point and reattaching // to the existing ObservableGroup. If saveState() was not called, then it's likely that we're // being destroyed and are not ever coming back. However, this isn't perfect, especially // when using fragments in a ViewPager. We might want to allow users to explicitly destroy it // instead, in order to mitigate this issue. // Also in some situations it seems like an Activity can be recreated even though its // isFinishing() property is set to true. For this reason, we must also check // isChangingConfigurations() to make sure it's safe to destroy the group. onDestroy(!hasSavedState || (activity != null && activity.isFinishing() && !activity.isChangingConfigurations())); } /** Call this method from your Activity or Fragment's onDestroy method */ public void onDestroy(Fragment fragment) { onDestroy(fragment.getActivity()); } /** Call this method from your Activity or Fragment's onResume method */ public void onResume() { hasSavedState = false; unlock(); } /** Call this method from your Activity or Fragment's onPause method */ public void onPause() { lock(); } private void lock() { group.lock(); } private void unlock() { group.unlock(); } /** Call this method from your Activity or Fragment's onSaveInstanceState method */ public void onSaveInstanceState(Bundle outState) { hasSavedState = true; outState.putParcelable(KEY_STATE, new State(observableManager.id(), group.id())); } static class State implements Parcelable { final UUID managerId; final long groupId; State(UUID managerId, long groupId) { this.managerId = managerId; this.groupId = groupId; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeSerializable(managerId); dest.writeLong(groupId); } public static final Parcelable.Creator<State> CREATOR = new Parcelable.Creator<State>() { @Override public State[] newArray(int size) { return new State[size]; } @Override public State createFromParcel(Parcel source) { return new State((UUID) source.readSerializable(), source.readLong()); } }; } }
2,627
669
<reponame>vpisarev/onnxruntime // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <algorithm> #include <functional> #include <vector> #include <cmath> #include "core/common/common.h" #include "core/common/path.h" #include "core/framework/allocator.h" #include "core/optimizer/graph_transformer.h" #include "core/framework/tensor_shape.h" #include "core/framework/tensorprotoutils.h" #include "core/graph/onnx_protobuf.h" #include "core/util/math.h" namespace onnxruntime { class Initializer final { public: // Construct an initializer with the provided name and data type, with all values initialized to 0 Initializer(ONNX_NAMESPACE::TensorProto_DataType data_type, std::string_view name, gsl::span<const int64_t> dims); Initializer(const ONNX_NAMESPACE::TensorProto& tensor_proto, const Path& model_path); ~Initializer() = default; void ToProto(ONNX_NAMESPACE::TensorProto& tensor_proto) const { tensor_proto = utils::TensorToTensorProto(data_, name_); } ONNX_NAMESPACE::TensorProto ToFP16(const std::string& name) const; ONNX_NAMESPACE::TensorProto ToBFloat16(const std::string& name) const; int data_type() const { return data_.GetElementType(); } std::string_view name() const { return name_; } template <typename T> T* data() { return data_.MutableData<T>(); } template <typename T> const T* data() const { return data_.Data<T>(); } const int8_t* raw_data() const { return reinterpret_cast<const int8_t*>(data_.DataRaw()); } gsl::span<const int64_t> dims() const { return data_.Shape().GetDims(); } int64_t size() const { return data_.Shape().Size(); } Initializer& add(float value); Initializer& add(const Initializer& other); Initializer& sub(const Initializer& other); Initializer& mul(const Initializer& other); Initializer& div(const Initializer& other); Initializer& sqrt(); void scale_by_axis(const Initializer& other, int axis); private: std::string name_; Tensor data_; }; } // namespace onnxruntime
795
852
#ifndef L1Trigger_TrackFindingTMTT_L1track3D_h #define L1Trigger_TrackFindingTMTT_L1track3D_h #include "DataFormats/Math/interface/deltaPhi.h" #include "L1Trigger/TrackFindingTMTT/interface/L1trackBase.h" #include "L1Trigger/TrackFindingTMTT/interface/Settings.h" #include "L1Trigger/TrackFindingTMTT/interface/Utility.h" #include "L1Trigger/TrackFindingTMTT/interface/TP.h" #include "L1Trigger/TrackFindingTMTT/interface/Stub.h" #include "L1Trigger/TrackFindingTMTT/interface/Sector.h" #include "L1Trigger/TrackFindingTMTT/interface/HTrphi.h" #include <vector> #include <string> #include <unordered_set> #include <utility> //=== L1 track candidate found in 3 dimensions. //=== Gives access to all stubs on track and to its 3D helix parameters. //=== Also calculates & gives access to associated truth particle (Tracking Particle) if any. namespace tmtt { class L1track3D : public L1trackBase { public: // Seeding layers of tracklet pattern reco. enum TrackletSeedType { L1L2, L2L3, L3L4, L5L6, D1D2, D3D4, L1D1, L2D1, L3L4L2, L5L6L4, L2L3D1, D1D2L2, NONE }; public: L1track3D(const Settings* settings, const std::vector<Stub*>& stubs, std::pair<unsigned int, unsigned int> cellLocationHT, std::pair<float, float> helixRphi, std::pair<float, float> helixRz, float helixD0, unsigned int iPhiSec, unsigned int iEtaReg, unsigned int optoLinkID, bool mergedHTcell) : L1trackBase(), settings_(settings), stubs_(stubs), stubsConst_(stubs_.begin(), stubs_.end()), cellLocationHT_(cellLocationHT), helixRphi_(helixRphi), helixRz_(helixRz), helixD0_(helixD0), iPhiSec_(iPhiSec), iEtaReg_(iEtaReg), optoLinkID_(optoLinkID), mergedHTcell_(mergedHTcell), seedLayerType_(TrackletSeedType::NONE), seedPS_(999) { nLayers_ = Utility::countLayers(settings, stubs_); // Count tracker layers these stubs are in matchedTP_ = Utility::matchingTP(settings, stubs_, nMatchedLayers_, matchedStubs_); // Find associated truth particle & calculate info about match. } // TMTT tracking: constructor L1track3D(const Settings* settings, const std::vector<Stub*>& stubs, std::pair<unsigned int, unsigned int> cellLocationHT, std::pair<float, float> helixRphi, std::pair<float, float> helixRz, unsigned int iPhiSec, unsigned int iEtaReg, unsigned int optoLinkID, bool mergedHTcell) : L1track3D( settings, stubs, cellLocationHT, helixRphi, helixRz, 0.0, iPhiSec, iEtaReg, optoLinkID, mergedHTcell) {} ~L1track3D() override = default; //--- Set/get optional info for tracklet tracks. // Tracklet seeding layer pair (from Tracklet::calcSeedIndex()) void setSeedLayerType(unsigned int seedLayerType) { seedLayerType_ = static_cast<TrackletSeedType>(seedLayerType); } TrackletSeedType seedLayerType() const { return seedLayerType_; } // Tracklet seed stub pair uses PS modules (from FPGATracket::PSseed()) void setSeedPS(unsigned int seedPS) { seedPS_ = seedPS; } unsigned int seedPS() const { return seedPS_; } // Best stub (stub with smallest Phi residual in each layer/disk) void setBestStubs(std::unordered_set<const Stub*> bestStubs) { bestStubs_ = bestStubs; } std::unordered_set<const Stub*> bestStubs() const { return bestStubs_; } //--- Get information about the reconstructed track. // Get stubs on track candidate. const std::vector<const Stub*>& stubsConst() const override { return stubsConst_; } const std::vector<Stub*>& stubs() const override { return stubs_; } // Get number of stubs on track candidate. unsigned int numStubs() const override { return stubs_.size(); } // Get number of tracker layers these stubs are in. unsigned int numLayers() const override { return nLayers_; } // Get cell location of track candidate in r-phi Hough Transform array in units of bin number. std::pair<unsigned int, unsigned int> cellLocationHT() const override { return cellLocationHT_; } // The two conventionally agreed track helix parameters relevant in r-phi plane. i.e. (q/Pt, phi0) std::pair<float, float> helixRphi() const { return helixRphi_; } // The two conventionally agreed track helix parameters relevant in r-z plane. i.e. (z0, tan_lambda) std::pair<float, float> helixRz() const { return helixRz_; } //--- Return chi variables, (both digitized & undigitized), which are the stub coords. relative to track. std::vector<float> chiPhi() { std::vector<float> result; for (const Stub* s : stubs_) { float chi_phi = reco::deltaPhi(s->phi(), this->phi0() - s->r() * this->qOverPt() * settings_->invPtToDphi()); result.push_back(chi_phi); } return result; } std::vector<int> chiPhiDigi() { std::vector<int> result; const float phiMult = pow(2, settings_->phiSBits()) / settings_->phiSRange(); for (const float& chi_phi : this->chiPhi()) { int iDigi_chi_phi = floor(chi_phi * phiMult); result.push_back(iDigi_chi_phi); } return result; } std::vector<float> chiZ() { std::vector<float> result; for (const Stub* s : stubs_) { float chi_z = s->z() - (this->z0() + s->r() * this->tanLambda()); result.push_back(chi_z); } return result; } std::vector<int> chiZDigi() { std::vector<int> result; const float zMult = pow(2, settings_->zBits()) / settings_->zRange(); for (const float& chi_z : this->chiZ()) { int iDigi_chi_z = floor(chi_z * zMult); result.push_back(iDigi_chi_z); } return result; } //--- User-friendlier access to the helix parameters. float qOverPt() const override { return helixRphi_.first; } float charge() const { return (this->qOverPt() > 0 ? 1 : -1); } float invPt() const { return std::abs(this->qOverPt()); } // Protect pt against 1/pt = 0. float pt() const { constexpr float small = 1.0e-6; return 1. / (small + this->invPt()); } float d0() const { return helixD0_; } // Hough transform assumes d0 = 0. float phi0() const override { return helixRphi_.second; } float z0() const { return helixRz_.first; } float tanLambda() const { return helixRz_.second; } float theta() const { return atan2(1., this->tanLambda()); } // Use atan2 to ensure 0 < theta < pi. float eta() const { return -log(tan(0.5 * this->theta())); } // Phi and z coordinates at which track crosses "chosenR" values used by r-phi HT and rapidity sectors respectively. float phiAtChosenR() const { return reco::deltaPhi(this->phi0() - (settings_->invPtToDphi() * settings_->chosenRofPhi()) * this->qOverPt(), 0.); } float zAtChosenR() const { return (this->z0() + (settings_->chosenRofZ()) * this->tanLambda()); } // neglects transverse impact parameter & track curvature. //--- Get phi sector and eta region used by track finding code that this track is in. unsigned int iPhiSec() const override { return iPhiSec_; } unsigned int iEtaReg() const override { return iEtaReg_; } //--- Opto-link ID used to send this track from HT to Track Fitter unsigned int optoLinkID() const override { return optoLinkID_; } //--- Was this track produced from a marged HT cell (e.g. 2x2)? bool mergedHTcell() const { return mergedHTcell_; } //--- Get information about its association (if any) to a truth Tracking Particle. // Get best matching tracking particle (=nullptr if none). const TP* matchedTP() const override { return matchedTP_; } // Get the matched stubs with this Tracking Particle const std::vector<const Stub*>& matchedStubs() const override { return matchedStubs_; } // Get number of matched stubs with this Tracking Particle unsigned int numMatchedStubs() const override { return matchedStubs_.size(); } // Get number of tracker layers with matched stubs with this Tracking Particle unsigned int numMatchedLayers() const override { return nMatchedLayers_; } // Get purity of stubs on track candidate (i.e. fraction matching best Tracking Particle) float purity() const { return numMatchedStubs() / float(numStubs()); } //--- For debugging purposes. // Remove incorrect stubs from the track using truth information. // Also veto tracks where the HT cell estimated from the true helix parameters is inconsistent with the cell the HT found the track in, (since probable duplicates). // Also veto tracks that match a truth particle not used for the algo efficiency measurement. // Return a boolean indicating if the track should be kept. (i.e. Is genuine & non-duplicate). bool cheat() { bool keep = false; std::vector<Stub*> stubsSel; if (matchedTP_ != nullptr) { // Genuine track for (Stub* s : stubs_) { const TP* tp = s->assocTP(); if (tp != nullptr) { if (matchedTP_->index() == tp->index()) { stubsSel.push_back(s); // This stub was produced by same truth particle as rest of track, so keep it. } } } } stubs_ = stubsSel; stubsConst_ = std::vector<const Stub*>(stubs_.begin(), stubs_.end()); nLayers_ = Utility::countLayers(settings_, stubs_); // Count tracker layers these stubs are in matchedTP_ = Utility::matchingTP(settings_, stubs_, nMatchedLayers_, matchedStubs_); // Find associated truth particle & calculate info about match. bool genuine = (matchedTP_ != nullptr); if (genuine && matchedTP_->useForAlgEff()) { Sector secTmp(settings_, iPhiSec_, iEtaReg_); HTrphi htRphiTmp(settings_, iPhiSec_, iEtaReg_, secTmp.etaMin(), secTmp.etaMax(), secTmp.phiCentre()); std::pair<unsigned int, unsigned int> trueCell = htRphiTmp.trueCell(matchedTP_); std::pair<unsigned int, unsigned int> htCell = this->cellLocationHT(); bool consistent = (htCell == trueCell); // If true, track is probably not a duplicate. if (mergedHTcell_) { // If this is a merged cell, check other elements of merged cell. std::pair<unsigned int, unsigned int> htCell10(htCell.first + 1, htCell.second); std::pair<unsigned int, unsigned int> htCell01(htCell.first, htCell.second + 1); std::pair<unsigned int, unsigned int> htCell11(htCell.first + 1, htCell.second + 1); if (htCell10 == trueCell) consistent = true; if (htCell01 == trueCell) consistent = true; if (htCell11 == trueCell) consistent = true; } if (consistent) keep = true; } return keep; // Indicate if track should be kept. } private: //--- Configuration parameters const Settings* settings_; //--- Information about the reconstructed track. std::vector<Stub*> stubs_; std::vector<const Stub*> stubsConst_; std::unordered_set<const Stub*> bestStubs_; unsigned int nLayers_; std::pair<unsigned int, unsigned int> cellLocationHT_; std::pair<float, float> helixRphi_; std::pair<float, float> helixRz_; float helixD0_; unsigned int iPhiSec_; unsigned int iEtaReg_; unsigned int optoLinkID_; bool mergedHTcell_; //--- Optional info used for tracklet tracks. TrackletSeedType seedLayerType_; unsigned int seedPS_; //--- Information about its association (if any) to a truth Tracking Particle. const TP* matchedTP_; std::vector<const Stub*> matchedStubs_; unsigned int nMatchedLayers_; }; } // namespace tmtt #endif
4,934
488
<reponame>chauffer/BulletSharpUnity3d #include "main.h" extern "C" { EXPORT bool btCharacterControllerInterface_canJump(btCharacterControllerInterface* obj); EXPORT void btCharacterControllerInterface_jump(btCharacterControllerInterface* obj); EXPORT bool btCharacterControllerInterface_onGround(btCharacterControllerInterface* obj); EXPORT void btCharacterControllerInterface_playerStep(btCharacterControllerInterface* obj, btCollisionWorld* collisionWorld, btScalar dt); EXPORT void btCharacterControllerInterface_preStep(btCharacterControllerInterface* obj, btCollisionWorld* collisionWorld); EXPORT void btCharacterControllerInterface_reset(btCharacterControllerInterface* obj, btCollisionWorld* collisionWorld); EXPORT void btCharacterControllerInterface_setUpInterpolate(btCharacterControllerInterface* obj, bool value); EXPORT void btCharacterControllerInterface_setWalkDirection(btCharacterControllerInterface* obj, const btScalar* walkDirection); EXPORT void btCharacterControllerInterface_setVelocityForTimeInterval(btCharacterControllerInterface* obj, const btScalar* velocity, btScalar timeInterval); EXPORT void btCharacterControllerInterface_warp(btCharacterControllerInterface* obj, const btScalar* origin); }
329
1,826
<gh_stars>1000+ package com.vladsch.flexmark.ext.jekyll.tag; import com.vladsch.flexmark.util.ast.Block; import com.vladsch.flexmark.util.ast.BlockContent; import com.vladsch.flexmark.util.ast.Node; import com.vladsch.flexmark.util.sequence.BasedSequence; import org.jetbrains.annotations.NotNull; import java.util.List; /** * A JekyllTag block node */ public class JekyllTagBlock extends Block { @Override public void getAstExtra(@NotNull StringBuilder out) { } @NotNull @Override public BasedSequence[] getSegments() { return Node.EMPTY_SEGMENTS; } public JekyllTagBlock() { } public JekyllTagBlock(BasedSequence chars) { super(chars); } public JekyllTagBlock(BasedSequence chars, List<BasedSequence> lineSegments) { super(chars, lineSegments); } public JekyllTagBlock(List<BasedSequence> lineSegments) { super(lineSegments); } public JekyllTagBlock(BlockContent blockContent) { super(blockContent); } public JekyllTagBlock(Node node) { super(); appendChild(node); this.setCharsFromContent(); } }
464
1,768
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Mon 30 Apr 2007 at 13:26:26 PST by lamport // modified on Thu Nov 29 21:53:11 PST 2001 by yuanyu package tlc2.util; /** A <code>BitVector</code> is an ordered list of bits of potentially unbounded size. The index of the first bit in a bit vector is 0.<p> This class is unmonitored; it is the responsibility of clients to guarantee thread safety. The read-only methods are <code>get</code> and <code>iterator</code>. Written by <NAME> and <NAME> */ import java.io.IOException; import java.io.Serializable; public class BitVector implements Serializable { private static final long serialVersionUID = 901734230891583097L; private long[] word; // words of this bit vector public BitVector() { this.word = null; } /** * Constructor for a new bit vector that is expected to contain bits * with indices 0 through <code>initCapacity-1</code>. */ public BitVector(int initCapacity) { int len = (initCapacity == 0) ? 0 : ((initCapacity - 1)/64 + 1); this.word = new long[len]; } /** * Constructor for a new bit vector that is expected to contain bits with * indices 0 through <code>initCapacity-1</code>. All bits are initially set * to <code>true</code> */ public BitVector(int initCapacity, boolean initValue) { int len = (initCapacity == 0) ? 0 : ((initCapacity - 1) / 64 + 1); this.word = new long[len]; if (initValue) { set(0, len); } } /** Initialize this bit vector to be a copy of <code>bv</code>. */ public BitVector(BitVector bv) { int len = bv.word.length; this.word = new long[len]; System.arraycopy(bv.word, 0, this.word, 0, len); } public boolean equals(Object o) { if (!(o instanceof BitVector)) return false; BitVector other = (BitVector)o; int minLen = Math.min(this.word.length, other.word.length); for (int i = 0; i < minLen; i++) { if (this.word[i] != other.word[i]) return false; } if (this.word.length != other.word.length) { int maxLen = Math.max(this.word.length, other.word.length); long[] tail = (maxLen == this.word.length) ? this.word : other.word; for (int i = minLen; i < maxLen; i++) { if (tail[i] != 0L) return false; } } return true; } public int hashCode() { int res = 0; for (int i = 0; i < this.word.length; i++) { long w = this.word[i]; if (w != 0) { res ^= (int)(w & 0xffffL); res ^= (int)(w >>> 32); } } return res; } /** Reset all of this bit vector's bits. */ public void clear() { for (int i = 0; i < this.word.length; i++) { this.word[i] = 0L; } } /** Return the bit at index <code>i</code>. */ public boolean get(int i) { int wd = i / 64; if (wd >= this.word.length) return false; int bit = i % 64; return (this.word[wd] & (1L << bit)) != 0L; } /** Set the bit at index <code>i</code> to <code>true</code>. */ public void set(int i) { int wd = i / 64; if (wd >= this.word.length) this.grow(wd); int bit = i % 64; this.word[wd] |= (1L << bit); } /** Set all the bits with indices in the closed interval <code>[lo, hi]</code>. */ public void set(int lo, int hi) { int lwd = lo / 64; int hwd = hi / 64; if (hwd >= this.word.length) this.grow(hwd); int lbit = lo % 64; int hbit = hi % 64; if (lwd < hwd) { for (int i = lwd+1; i < hwd; i++) { this.word[i] = -1L; } this.word[lwd] = (-1L << lbit); this.word[hwd] = (-1L >>> (63-hbit)); } else { if (lo <= hi) { this.word[lwd] = (-1L << lbit) & (-1L >>> (63-hbit)); } } } /** * Returns this {@link BitVector} is a bit string with the MSB to the left * and the LSB to the right. * * @see java.lang.Object#toString() */ public String toString() { final StringBuffer buf = new StringBuffer(this.word.length * 64); for (int i = this.word.length * 64; i >= 0; i--) { if (get(i)) { buf.append("1"); } else { buf.append("0"); } } buf.append("]"); return buf.toString().replaceAll("^0*","["); // Replace leading zeros with "[" } public String toString(int start, int length) { return toString(start, length, '1', '0'); } public String toString(int start, int length, char one, char zero) { final StringBuffer buf = new StringBuffer(length); for (int i = 0; i < length; i++) { if (get(start + i)) { buf.append(one); } else { buf.append(zero); } } return "[" + buf.reverse().toString() + "]"; } /** * @return The number of bits set true */ public int trueCnt() { int res = 0; for (int i = 0; i < this.word.length * 64; i++) { // addr in long[] int wd = i / 64; // addr in long[x] int bit = i % 64; if ((this.word[wd] & (1L << bit)) != 0L) { res++; } } return res; } /** Set the bit at index <code>i</code> to <code>false</code>. */ public void reset(int i) { int wd = i / 64; if (wd >= this.word.length) this.grow(wd); int bit = i % 64; this.word[wd] &= ~(1L << bit); } /** Set the bit at index <code>i</code> to <code>val</code>. */ public void set(int i, boolean val) { int wd = i / 64; if (wd >= this.word.length) this.grow(wd); int bit = i % 64; if (val) { this.word[wd] |= (1L << bit); } else { this.word[wd] &= ~(1L << bit); } } /** Write the bit vector to a file. */ public void write(BufferedRandomAccessFile raf) throws IOException { int len = this.word.length; raf.writeNat(len); for (int i = 0; i < len; i++) { raf.writeLong(this.word[i]); } } /** Read a bit vector from a file */ public void read(BufferedRandomAccessFile raf) throws IOException { int len = raf.readNat(); this.word = new long[len]; for (int i = 0; i < len; i++) { this.word[i] = raf.readLong(); } } /** Grow this bit vector to contain at least <code>wd+1</code> words. */ private void grow(int wd) { // Assert.check(wd >= this.word.length); int newLen = Math.max(this.word.length, wd + 1); long[] tmp = new long[newLen]; System.arraycopy(this.word, 0, tmp, 0, this.word.length); this.word = tmp; } /** A <code>BitVector.Iter</code> is an object for enumerating the set bits of a given bit vector in order. While the iterator is being used, the bit vector should not be modified.*/ public static class Iter { /*@ non_null */ long[] word; // pointer to bit vector's 'word' array int wd; // index of next word to consider int bit; // index of next bit to consider long mask; // mask of next bit to consider //@ invariant this.wd >= 0 //@ invariant this.mask == (1L << this.bit) /** Construct an empty <code>Iter</code> object. The <code>init</code> method must be called before this iterator can be used. */ public Iter() { /*SKIP*/ } /** Initialize this <code>Iter</code> object for iterating over <code>bv</code>. */ public Iter(BitVector bv) { this.init(bv); } /** Reinitialize this <code>BVIter</code> object for iterating over <code>bv</code>. */ public void init(BitVector bv) { this.word = bv.word; this.wd = 0; this.bit = 0; this.mask = 1L; } /** Return the index of the next set bit in this iterator's bit vector, or -1 if there are no more such bits. */ public int next() { for (; this.wd < this.word.length; this.wd++) { long w = this.word[this.wd]; for (; this.bit < 64; this.bit++, this.mask <<= 1) { if ((w & this.mask) != 0L) { int res = (this.wd * 64) + this.bit; // advance to next bit for next call this.bit++; if (this.bit < 64) { this.mask <<= 1; } else { this.wd++; this.bit = 0; this.mask = 1L; } return res; } } this.bit = 0; this.mask = 1L; } return -1; } } }
3,386
15,577
<reponame>Vxider/ClickHouse #include <Storages/MergeTree/MergeTreeReaderInMemory.h> #include <Storages/MergeTree/MergeTreeDataPartInMemory.h> #include <DataTypes/DataTypeArray.h> #include <DataTypes/NestedUtils.h> #include <Columns/ColumnArray.h> namespace DB { namespace ErrorCodes { extern const int CANNOT_READ_ALL_DATA; extern const int ARGUMENT_OUT_OF_BOUND; } MergeTreeReaderInMemory::MergeTreeReaderInMemory( DataPartInMemoryPtr data_part_, NamesAndTypesList columns_, const StorageMetadataPtr & metadata_snapshot_, MarkRanges mark_ranges_, MergeTreeReaderSettings settings_) : IMergeTreeReader(data_part_, std::move(columns_), metadata_snapshot_, nullptr, nullptr, std::move(mark_ranges_), std::move(settings_), {}) , part_in_memory(std::move(data_part_)) { for (const auto & name_and_type : columns) { auto [name, type] = getColumnFromPart(name_and_type); /// If array of Nested column is missing in part, /// we have to read its offsets if they exist. if (!part_in_memory->block.has(name) && typeid_cast<const DataTypeArray *>(type.get())) if (auto offset_position = findColumnForOffsets(name)) positions_for_offsets[name] = *offset_position; } } size_t MergeTreeReaderInMemory::readRows(size_t from_mark, bool continue_reading, size_t max_rows_to_read, Columns & res_columns) { if (!continue_reading) total_rows_read = 0; size_t total_marks = data_part->index_granularity.getMarksCount(); if (from_mark >= total_marks) throw Exception("Mark " + toString(from_mark) + " is out of bound. Max mark: " + toString(total_marks), ErrorCodes::ARGUMENT_OUT_OF_BOUND); size_t num_columns = res_columns.size(); checkNumberOfColumns(num_columns); size_t part_rows = part_in_memory->block.rows(); if (total_rows_read >= part_rows) throw Exception("Cannot read data in MergeTreeReaderInMemory. Rows already read: " + toString(total_rows_read) + ". Rows in part: " + toString(part_rows), ErrorCodes::CANNOT_READ_ALL_DATA); size_t rows_to_read = std::min(max_rows_to_read, part_rows - total_rows_read); auto column_it = columns.begin(); for (size_t i = 0; i < num_columns; ++i, ++column_it) { auto name_type = getColumnFromPart(*column_it); /// Copy offsets, if array of Nested column is missing in part. auto offsets_it = positions_for_offsets.find(name_type.name); if (offsets_it != positions_for_offsets.end() && !name_type.isSubcolumn()) { const auto & source_offsets = assert_cast<const ColumnArray &>( *part_in_memory->block.getByPosition(offsets_it->second).column).getOffsets(); if (res_columns[i] == nullptr) res_columns[i] = name_type.type->createColumn(); auto mutable_column = res_columns[i]->assumeMutable(); auto & res_offstes = assert_cast<ColumnArray &>(*mutable_column).getOffsets(); size_t start_offset = total_rows_read ? source_offsets[total_rows_read - 1] : 0; for (size_t row = 0; row < rows_to_read; ++row) res_offstes.push_back(source_offsets[total_rows_read + row] - start_offset); res_columns[i] = std::move(mutable_column); } else if (part_in_memory->hasColumnFiles(name_type)) { auto block_column = getColumnFromBlock(part_in_memory->block, name_type); if (rows_to_read == part_rows) { res_columns[i] = block_column; } else { if (res_columns[i] == nullptr) res_columns[i] = name_type.type->createColumn(); auto mutable_column = res_columns[i]->assumeMutable(); mutable_column->insertRangeFrom(*block_column, total_rows_read, rows_to_read); res_columns[i] = std::move(mutable_column); } } } total_rows_read += rows_to_read; return rows_to_read; } }
1,801
903
<gh_stars>100-1000 """ test_etl_job.py ~~~~~~~~~~~~~~~ This module contains unit tests for the transformation steps of the ETL job defined in etl_job.py. It makes use of a local version of PySpark that is bundled with the PySpark package. """ import unittest import json from pyspark.sql.functions import mean from dependencies.spark import start_spark from jobs.etl_job import transform_data class SparkETLTests(unittest.TestCase): """Test suite for transformation in etl_job.py """ def setUp(self): """Start Spark, define config and path to test data """ self.config = json.loads("""{"steps_per_floor": 21}""") self.spark, *_ = start_spark() self.test_data_path = 'tests/test_data/' def tearDown(self): """Stop Spark """ self.spark.stop() def test_transform_data(self): """Test data transformer. Using small chunks of input data and expected output data, we test the transformation step to make sure it's working as expected. """ # assemble input_data = ( self.spark .read .parquet(self.test_data_path + 'employees')) expected_data = ( self.spark .read .parquet(self.test_data_path + 'employees_report')) expected_cols = len(expected_data.columns) expected_rows = expected_data.count() expected_avg_steps = ( expected_data .agg(mean('steps_to_desk').alias('avg_steps_to_desk')) .collect()[0] ['avg_steps_to_desk']) # act data_transformed = transform_data(input_data, 21) cols = len(expected_data.columns) rows = expected_data.count() avg_steps = ( expected_data .agg(mean('steps_to_desk').alias('avg_steps_to_desk')) .collect()[0] ['avg_steps_to_desk']) # assert self.assertEqual(expected_cols, cols) self.assertEqual(expected_rows, rows) self.assertEqual(expected_avg_steps, avg_steps) self.assertTrue([col in expected_data.columns for col in data_transformed.columns]) if __name__ == '__main__': unittest.main()
1,035
2,195
""" Implements 'propagation', whereby terms from the full ConceptNet graph are assigned vectors from the embeddings produced by retrofitting against the reduced graph. """ import numpy as np import pandas as pd from scipy.sparse import diags from conceptnet5.builders.reduce_assoc import ConceptNetAssociationGraph from conceptnet5.uri import get_uri_language from conceptnet5.vectors import replace_numbers from .formats import load_hdf, save_hdf from .sparse_matrix_builder import SparseMatrixBuilder class ConceptNetAssociationGraphForPropagation(ConceptNetAssociationGraph): """ Subclass of ConceptNetAssociationGraph specialized for use in making the full graph of a set of associations as required for propagation. """ def __init__(self): super().__init__() self.edges = set() def add_edge(self, left, right, value, dataset, relation): """ In addition to the superclass's handling of a new edge, saves the edges as a set of (left, right) pairs. """ # Use URIs that have the additional standardization for vector-space labels, # replacing sequences of digits with the # sign. left = replace_numbers(left) right = replace_numbers(right) super().add_edge(left, right, value, dataset, relation) self.edges.add((left, right)) self.edges.add((right, left)) # save undirected edges def sharded_propagate( assoc_filename, embedding_filename, output_filename, nshards=6, iterations=20 ): """ A wrapper around propagate which reduces memory requirements by splitting the embedding into shards (along the dimensions of the embedding feature space). """ # frame_box is basically a reference to a single large DataFrame. The # DataFrame will at times be present or absent. When it's present, the list # contains one item, which is the DataFrame. When it's absent, the list # is empty. frame_box = [load_hdf(embedding_filename)] adjacency_matrix, combined_index, n_new_english = make_adjacency_matrix( assoc_filename, frame_box[0].index ) shard_width = frame_box[0].shape[1] // nshards for i in range(nshards): temp_filename = output_filename + '.shard%d' % i shard_from = shard_width * i shard_to = shard_from + shard_width if len(frame_box) == 0: frame_box.append(load_hdf(embedding_filename)) embedding_shard = pd.DataFrame(frame_box[0].iloc[:, shard_from:shard_to]) # Delete full_dense_frame while running retrofitting, because it takes # up a lot of memory and we can reload it from disk later. frame_box.clear() propagated = propagate( combined_index, embedding_shard, adjacency_matrix, n_new_english, iterations=iterations, ) save_hdf(propagated, temp_filename) del propagated def make_adjacency_matrix(assoc_filename, embedding_vocab): """ Build a sparse adjacency matrix for the ConceptNet graph presented in the given assoc file, including all terms from the given embedding vocabulary and removing all terms from connected components of the graph that do not overlap that vocabulary. Also builds an index giving all terms from the resulting joined graph+embedding vocabulary in the order corresponding to the rows and columns of the matrix. Note that it is guaranteed that the terms from the embedding vocabulary will preceed the remaining terms in that index, and that among the remaining terms the terms in English will follow all the others. Returns the matrix and index, and the number of new English terms. """ # First eliminate all connected components of the graph that don't # overlap the vocabulary of the embedding; we can't do anything with # those terms. graph = ConceptNetAssociationGraphForPropagation.from_csv( assoc_filename, reject_negative_relations=False ) component_labels = graph.find_components() # Get the labels of components that overlap the embedding vocabulary. good_component_labels = set( label for term, label in component_labels.items() if term in embedding_vocab ) # Now get the concepts in those components. good_concepts = set( term for term, label in component_labels.items() if label in good_component_labels ) del component_labels, good_component_labels # Put terms from the embedding first, then terms from the good part # of the graph neither from the embedding nor in English, then terms # from the good part of the graph in English but not from the embedding. # # (In the corner case where either of these addtional sets of terms is # empty, construction of a pandas index will fail using generator rather # than list comprehensions.) new_vocab = good_concepts - set(embedding_vocab) good_concepts = embedding_vocab.append( pd.Index([term for term in new_vocab if get_uri_language(term) != 'en']) ) n_good_concepts_not_new_en = len(good_concepts) good_concepts = good_concepts.append( pd.Index([term for term in new_vocab if get_uri_language(term) == 'en']) ) del new_vocab n_new_english = len(good_concepts) - n_good_concepts_not_new_en good_concepts_map = {term: i for i, term in enumerate(good_concepts)} # Convert the good part of the graph to an adjacency matrix representation. # Note: the edges added differ slightly from the way it is done in (e.g.) # build_from_conceptnet_table (in sparse_matrix_builder.py), in that we # do not add edges linking specific senses of terms to their more general # forms (as defined by uri_prefixes). Currently no such specific senses # show up in the input to retrofitting (i.e. the output of # build_from_conceptnet_table), so it doesn't matter, but in the future # we may want to add such edges here as well. builder = SparseMatrixBuilder() for v, w in graph.edges: try: index0 = good_concepts_map[v] index1 = good_concepts_map[w] builder[index0, index1] = 1 except KeyError: pass # one of v, w wasn't good del graph adjacency_matrix = builder.tocsr( shape=(len(good_concepts), len(good_concepts)), dtype=np.int8 ) return adjacency_matrix, good_concepts, n_new_english def propagate( combined_index, embedding, adjacency_matrix, n_new_english, iterations=20 ): """ For as many non-English terms as possible in the ConceptNet graph whose edges are presented in the given adjacency matrix (with corresponding term labels in the given index), find a vector in the target space of the vector embedding presented in the given embedding file. """ # Propagate the vectors from the embeddings to the remaining # terms, following the edges of the graph. embedding_dimension = embedding.values.shape[1] new_vocab_size = len(combined_index) - embedding.values.shape[0] vectors = np.vstack( [ embedding.values, np.zeros( (new_vocab_size, embedding_dimension), dtype=embedding.values.dtype ), ] ) for iteration in range(iterations): zero_indicators = np.abs(vectors).sum(1) == 0 if not np.any(zero_indicators): break # Find terms with zero vectors having neighbors with nonzero vectors. nonzero_indicators = np.logical_not(zero_indicators) fringe = adjacency_matrix.dot(nonzero_indicators.astype(np.int8)) != 0 fringe = np.logical_and(fringe, zero_indicators) # Update each as the average of its nonzero neighbors adjacent_nonzeros = adjacency_matrix[fringe, :].dot( diags([nonzero_indicators.astype(np.int8)], [0], format='csc') ) n_adjacent_nonzeros = adjacent_nonzeros.sum(axis=1).A[:, 0] weights = 1.0 / n_adjacent_nonzeros vectors[fringe, :] = adjacency_matrix[fringe, :].dot(vectors) vectors[fringe, :] = diags([weights], [0], format='csr').dot(vectors[fringe, :]) n_old_plus_new_non_en = len(combined_index) - n_new_english result = pd.DataFrame( index=combined_index[0:n_old_plus_new_non_en], data=vectors[0:n_old_plus_new_non_en, :], ) return result
3,114
1,858
/* * Tencent is pleased to support the open source community by making TENCENT SOTER available. * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * https://opensource.org/licenses/BSD-3-Clause * 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.tencent.soter.demo.net; import android.support.annotation.NonNull; import com.tencent.soter.wrapper.wrap_net.ISoterNetCallback; import com.tencent.soter.wrapper.wrap_net.IWrapGetChallengeStr; import org.json.JSONException; import org.json.JSONObject; /** * Created by henryye on 2017/4/27. * */ public class RemoteGetChallengeStr extends RemoteBase implements IWrapGetChallengeStr{ private static final String TAG = "SoterDemo.RemoteGetChallengeStr"; private static final String KEY_RESULT_CHALLENGE = "challengeStr"; private static final String DEMO_CHALLENGE = "I'm a demo challenge string"; private ISoterNetCallback<GetChallengeResult> mCallback = null; @Override public void setRequest(@NonNull GetChallengeRequest requestDataModel) { JSONObject requestJson = new JSONObject(); // nothing to set setRequestJson(requestJson); } @Override public void setCallback(ISoterNetCallback<GetChallengeResult> callback) { this.mCallback = callback; } @Override JSONObject getSimulateJsonResult(JSONObject requestJson) { JSONObject jsonObject = new JSONObject(); try { jsonObject.put(KEY_RESULT_CHALLENGE, DEMO_CHALLENGE); } catch (JSONException e) { e.printStackTrace(); } return jsonObject; } @Override public void execute() { super.execute(); } @Override void onNetworkEnd(JSONObject resultJson) { if(mCallback != null) { if(resultJson != null) { String challenge = resultJson.optString(KEY_RESULT_CHALLENGE); this.mCallback.onNetEnd(new GetChallengeResult(challenge)); } else { this.mCallback.onNetEnd(null); } } } @Override protected String getNetUrl() { return BASE_URL + "/get_challenge"; } }
940
451
<reponame>kikislater/micmac #include "StdAfx.h" #include "TracePack.h" using namespace std; typedef struct { string name; int (*func)( int, char ** ); } command_t; int snapshot_func( int, char ** ); int list_func( int, char ** ); int getfile_func( int, char ** ); int setstate_func( int, char ** ); int pack_from_script_func( int, char ** ); int replay_func( int, char ** ); int test_func( int, char ** ); int add_ignored_func( int, char ** ); int help_func( int, char ** ); command_t g_commands[] = { { "snapshot", snapshot_func }, { "list", list_func }, { "getfile", getfile_func }, { "setstate", setstate_func }, { "pack_from_script", pack_from_script_func }, { "replay", replay_func }, { "test", test_func }, { "add_ignored", add_ignored_func }, { "help", help_func }, { "", NULL } // signify the end of the list }; int help_func( int argc, char **argv ) { cout << "Commands" << endl; command_t *itCommand = g_commands; while ( itCommand->func!=NULL ) { cout << "\t" << itCommand->name << endl; itCommand++; } return EXIT_SUCCESS; } int snapshot_func( int argc, char **argv ) { if ( argc!=2 ){ cout << "not enough args" << endl; return EXIT_FAILURE; } const ctPath anchor( (string)(argv[1]) ); const cElFilename packname( (string)(argv[0]) ); TracePack pack( packname, anchor ); if ( packname.exists() ){ if ( !pack.load() ){ cerr << "[" << packname.str_unix() << "] exists but cannot be read as a TracePack file" << endl; return EXIT_FAILURE; } else cout << "[" << packname.str_unix() << "] loaded, the pack will be updated" << endl; } else cout << "[" << packname.str_unix() << "] does not exist, a new pack has been created at date " << pack.date() << endl; cout << "snaping [" << anchor.str() << "] to [" << packname.str_unix() << "]" << endl; pack.addState(); const unsigned int nbStates = pack.nbStates(); cerr << nbStates << " state" << (nbStates>1?'s':'\0') << endl; if ( !pack.save() ){ cerr << RED_ERROR << "unable to save to [" << packname.str_unix() << "]" << endl; return EXIT_FAILURE; } #ifdef __DEBUG_TRACE_PACK TracePack pack2( packname, anchor ); pack2.load(); if ( !pack.trace_compare( pack2 ) ){ cerr << RED_DEBUG_ERROR << "pack [" << packname.str_unix() << "] is not equal to its write+read copy" << endl; exit(EXIT_FAILURE); } #endif return EXIT_SUCCESS; } bool get_list_registry_number( const string &i_argument, unsigned int &o_iRegistry, bool &o_listState ) { if ( i_argument.length()<2 ) return false; if ( i_argument[0]=='s' ) o_listState=true; else if ( i_argument[0]=='r' ) o_listState=false; else return false; int i = atoi( i_argument.substr(1).c_str() ); if ( i<0 ) return false; o_iRegistry = (unsigned int)i; return true; } int list_func( int argc, char **argv ) { if ( argc==0 ){ cerr << "not enough args" << endl; return EXIT_FAILURE; } const cElFilename filename( (string)(argv[0]) ); TracePack pack( filename, ctPath() ); if ( !pack.load() ){ cerr << RED_ERROR << "unable to load [" << filename.str_unix() << "]" << endl; return EXIT_FAILURE; } if ( argc>0 ){ const unsigned int nbStates = pack.nbStates(); cout << "pack [" << filename.str_unix() << ']' << endl; cout << "\t- creation date " << pack.date() << " (UTC)"<< endl; cout << "\t- " << nbStates << (nbStates>1?" registries":" registry") << endl; cout << "commands" << endl; vector<cElCommand> commands; pack.getAllCommands( commands ); for ( unsigned int iCmd=0; iCmd<nbStates; iCmd++ ) cout << '\t' << iCmd << " [" << commands[iCmd].str() << "]" << endl; } if ( argc==2 ){ bool listState; unsigned int iRegistry; if ( !get_list_registry_number( argv[1], iRegistry, listState ) ){ cerr << RED_ERROR << "third argument should be sXXX if you want to list a state or rXXX if you want to list a raw registry" << endl; return EXIT_FAILURE; } if ( iRegistry>=pack.nbStates() ){ cerr << RED_ERROR << "index " << iRegistry << " out of range (the pack has " << pack.nbStates() << " states)" << endl; return EXIT_FAILURE; } if ( listState ){ TracePack::Registry reg; pack.getState( (unsigned int)iRegistry, reg ); cout << "state " << iRegistry << endl; reg.dump( cout, "\t" ); } else{ cout << "raw registry " << iRegistry << endl; pack.getRegistry(iRegistry).dump( cout, "\t" ); } } return EXIT_SUCCESS; } int getfile_func( int argc, char **argv ) { if ( argc!=4 ){ cerr << "usage: packname iState file_to_extract output_directory" << endl; return EXIT_FAILURE; } const cElFilename itemName( (string)(argv[2]) ); const ctPath outputDirectory( argv[3] ); if ( !outputDirectory.exists() ) { cerr << RED_ERROR << "output directory [" << outputDirectory.str() << "] does not exist" << endl; return EXIT_FAILURE; } const cElFilename outputFile( outputDirectory, itemName ); if ( outputFile.exists() ) { cerr << RED_ERROR << "output file [" << outputFile.str_unix() << "] already not exist" << endl; return EXIT_FAILURE; } const cElFilename packname( (string)(argv[0]) ); TracePack pack( packname, outputDirectory ); if ( !pack.load() ) { cerr << RED_ERROR << "unable to load [" << packname.str_unix() << "]" << endl; return EXIT_FAILURE; } const unsigned int nbStates = pack.nbStates(); const int signed_iState = atoi( argv[1] ); const unsigned int iState = (unsigned int)signed_iState; if ( signed_iState<0 || iState>=nbStates ) { cerr << RED_ERROR << "invalid state index : " << signed_iState << " (pack has " << nbStates << " state" << (nbStates>1?"s":"") << endl; return EXIT_FAILURE; } if ( !pack.copyItemOnDisk( iState, itemName ) ) { cerr << RED_ERROR << "unable to copy item [" << itemName.str_unix() << "] from [" << packname.str_unix() << "]:s" << iState << " to directory [" << outputDirectory.str() << ']' << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } int setstate_func( int argc, char **argv ) { //setstate packname istate anchor if ( argc!=3 ) { cerr << "usage: packname iState output_directory" << endl; return EXIT_FAILURE; } const cElFilename packname( (string)(argv[0]) ); if ( !packname.exists() ) { cerr << RED_ERROR << "pack [" << packname.str_unix() << "] does not exist" << endl; return EXIT_FAILURE; } const int iState_s = atoi( argv[1] ); if ( iState_s<0 ) { cerr << RED_ERROR << "state index " << iState_s << " is invalid" << endl; return EXIT_FAILURE; } const unsigned int iState = (unsigned int)iState_s; const ctPath anchor( argv[2] ); if ( !anchor.exists() && !anchor.create() ) { cerr << RED_ERROR << "cannot create directory [" << anchor.str() << "]" << endl; return EXIT_FAILURE; } TracePack pack( packname, anchor ); if ( !pack.load() ) { cerr << RED_ERROR << "loading a pack from file [" << packname.str_unix() << "] failed" << endl; return EXIT_FAILURE; } const unsigned int nbStates = pack.nbStates(); if ( iState>=nbStates ) { cerr << "ERROR: state index " << iState << " out of range (" << nbStates << " state" << (nbStates>1?'s':'\0') << " in pack [" << packname.str_unix() << "])" << endl; return EXIT_FAILURE; } pack.setState( iState ); return EXIT_SUCCESS; } void generate_dictionary( int &io_argc, char **i_argv, map<string,string> &o_dictionary ) { const string prefix = "${", suffix = "}"; for ( int i=io_argc-1; i>=0; i-- ) { string arg=i_argv[i], var, val; size_t pos = arg.find( '=' ); if ( pos==string::npos || pos==0 || pos==arg.length()-1 ) return; var = arg.substr( 0, pos ); val = arg.substr( pos+1 ); o_dictionary[prefix+var+suffix] = val; io_argc--; } } int pack_from_script_func( int argc, char **argv ) { map<string,string> dictionary; generate_dictionary( argc, argv, dictionary ); if ( argc<2 ) { cerr << "usage: packfile scriptfile source_directory [VAR1=value1 VAR2=value2 ...]" << endl; return EXIT_FAILURE; } const cElFilename packname( (string)(argv[0]) ); if ( packname.exists() ) { cerr << RED_ERROR << "pack [" << packname.str_unix() << "] already exist" << endl; return EXIT_FAILURE; } const cElFilename scriptname( (string)(argv[1]) ); if ( !scriptname.exists() ) { cerr << RED_ERROR << "script [" << scriptname.str_unix() << "] does not exist" << endl; return EXIT_FAILURE; } ctPath anchor; anchor = ctPath( (string)(argv[2]) ); if ( anchor.isAncestorOf( packname ) ) { cerr << RED_ERROR << "pack file [" << packname.str_unix() << "] is inside source directory [" << anchor.str() << "]" << endl; return EXIT_FAILURE; } if ( !anchor.exists() ) { cerr << RED_ERROR << "reference directory [" << anchor.str() << "] does not exist" << endl; return EXIT_FAILURE; } dictionary["${SITE_PATH}"] = anchor.str(); cout << "--- using directory [" << anchor.str() << "]" << endl; cout << "--- dictionary" << endl; map<string,string>::iterator itDico = dictionary.begin(); while ( itDico!=dictionary.end() ) { cout << itDico->first << " -> " << itDico->second << endl; itDico++; } cout << endl; list<cElCommand> commands; if ( !load_script( scriptname, commands ) ) { cerr << RED_ERROR << "script file [" << scriptname.str_unix() << "] cannot be loaded" << endl; return EXIT_FAILURE; } // create initial state TracePack pack( packname, anchor ); pack.addState(); pack.save(); list<cElCommand>::iterator itCmd = commands.begin(); unsigned int iCmd = 0; while ( itCmd!=commands.end() ){ cout << "command " << iCmd << " : [" << itCmd->str() << ']' << endl; cElCommand originalCommand = *itCmd; if ( itCmd->replace( dictionary ) ) cout << "command " << iCmd << " : [" << itCmd->str() << ']' << endl; if ( !itCmd->system() ){ cerr << RED_ERROR << "command " << iCmd << " = " << endl; cerr << "[" << itCmd->str() << "]" << endl; cerr << "failed." << endl; return EXIT_FAILURE; } pack.addState( originalCommand ); pack.save(); #ifdef __DEBUG_TRACE_PACK TracePack pack2( packname, anchor ); pack2.load(); if ( !pack.trace_compare(pack2) ){ cerr << RED_DEBUG_ERROR << "pack!=load(write(pack))" << endl; exit(EXIT_FAILURE); } #endif itCmd++; iCmd++; } return EXIT_SUCCESS; } // this function make sure an empty directory of name i_directory exists // return false if the directory already exist but is not empty // or if the directory does not exist and couldn't be created bool is_empty_or_create( const ctPath &i_directory, bool &o_removeEmpty ) { if ( i_directory.exists() ){ if ( !i_directory.isEmpty() ){ cerr << RED_ERROR << "directory [" << i_directory.str() << "] exists and is not empty" << endl; return false; } o_removeEmpty = false; } else if ( !i_directory.create() ){ cerr << RED_ERROR << "cannot create directory [" << i_directory.str() << "]" << endl; return false; } else o_removeEmpty = true; return true; } void print_items_differences( unsigned int i_iStep, const list<TracePack::Registry::Item> &i_inRefItems, const list<TracePack::Registry::Item> &i_inRunItems ) { cout << RED_ERROR << "differences occured at step " << i_iStep << endl; if ( i_inRefItems.size()!=0 ){ cout << "reference only items :" << endl; list<TracePack::Registry::Item>::const_iterator itItem = i_inRefItems.begin(); while ( itItem!=i_inRefItems.end() ) (*itItem++).dump(cout,"\t"); if ( i_inRunItems.size()!=0 ) cout << endl; } if ( i_inRunItems.size()!=0 ){ cout << "run only items :" << endl; list<TracePack::Registry::Item>::const_iterator itItem = i_inRunItems.begin(); while ( itItem!=i_inRunItems.end() ) (*itItem++).dump(cout,"\t"); } } int replay_func( int argc, char **argv ) { map<string,string> dictionary; generate_dictionary( argc, argv, dictionary ); if ( argc<3 ){ cerr << "usage: packname destination_directory temporary_directory [VAR1=value1 VAR2=value2 ...]" << endl; return EXIT_FAILURE; } const cElFilename packname( (string)(argv[0]) ); if ( !packname.exists() ){ cerr << RED_ERROR << "pack [" << packname.str_unix() << "] does not exist" << endl; return EXIT_FAILURE; } cout << "--- pack name = [" << packname.str_unix() << ']' << endl; ctPath run_directory( (string)(argv[1]) ); bool runRemoveEmpty; if ( !is_empty_or_create( run_directory, runRemoveEmpty ) ) return EXIT_FAILURE; //setWorkingDirectory( run_directory ); cout << "--- monitored directory = [" << run_directory.str() << ']' << endl; // create a temporary directory for file content comparison ctPath ref_directory( (string)(argv[2]) ); bool refRemoveEmpty; if ( !is_empty_or_create( ref_directory, refRemoveEmpty ) ) return EXIT_FAILURE; cout << "--- temporary directory = [" << ref_directory.str() << ']' << endl; dictionary["${SITE_PATH}"] = run_directory.str(); TracePack ref_pack( packname, run_directory ), // anchor is set to run directory for initial state extraction, it is later set to ref directory run_pack( cElFilename("run_pack.pack"), run_directory ); if ( !ref_pack.load() ) cerr << RED_ERROR << "cannot load pack [" << packname.str_unix() << "]" << endl; unsigned int nbStates = ref_pack.nbStates(); if ( nbStates==0 ){ cerr << RED_WARNING << "pack [" << packname.str_unix() << "] is empty" << endl; return EXIT_SUCCESS; } // run pack ignore the same files as reference pack list<cElFilename> files = ref_pack.getIgnoredFiles(); run_pack.addIgnored( files ); list<ctPath> paths = ref_pack.getIgnoredDirectories(); run_pack.addIgnored( paths ); vector<cElCommand> commands; ref_pack.getAllCommands( commands ); // set anchor to pack's initial state cout << "--- setting [" << run_directory.str() << "] to initial state" << endl; ref_pack.setState(0); ref_pack.setAnchor( ref_directory ); // ref directory is where file are extracted for comparison run_pack.addState(); TracePack::Registry refReg = ref_pack.getRegistry(0), runReg = run_pack.getRegistry(0); list<TracePack::Registry::Item> onlyInRef, onlyInRun, inBoth, differentFromDisk; if ( !TracePack::Registry::compare_states( refReg, runReg, onlyInRef, onlyInRun, inBoth ) ){ print_items_differences( 0, onlyInRef, onlyInRun ); return EXIT_FAILURE; } for ( unsigned int iState=1; iState<nbStates; iState++ ){ cout << "--- processing registry " << iState << endl; cout << "\toriginal command = [" << commands[iState].str() << "]" << endl; commands[iState].replace( dictionary ); cout << "\tcommand = [" << commands[iState].str() << "]" << endl; if ( commands[iState].nbTokens()==0 ) cerr << RED_WARNING << "the command of this registry is empty" << endl; if ( !commands[iState].system() ){ cout << RED_ERROR << "command failed" << endl; return EXIT_FAILURE; } run_pack.addState(); refReg = ref_pack.getRegistry( iState ); runReg = run_pack.getRegistry( iState ); list<TracePack::Registry::Item> onlyInRef, onlyInRun, inBoth, differentFromDisk; if ( !TracePack::Registry::compare_states( refReg, runReg, onlyInRef, onlyInRun, inBoth ) ){ print_items_differences( iState, onlyInRef, onlyInRun ); return EXIT_FAILURE; } ref_pack.compareWithItemsOnDisk( iState, run_directory, inBoth, differentFromDisk ); if ( differentFromDisk.size()!=0 ){ cout << "\033[1;31m---> differences occured at step " << iState << "\033[0m" << endl; cout << "files with data different from pack" << endl; list<TracePack::Registry::Item>::const_iterator itItem = differentFromDisk.begin(); while ( itItem!=differentFromDisk.end() ){ cout << "\t" << TD_Type_to_string( itItem->m_type ) << " on [" << itItem->m_filename.str_unix() << "]" << endl; itItem++; } return EXIT_FAILURE; } cout << endl; } if ( runRemoveEmpty ) run_directory.remove(); else run_directory.removeContent(); if ( refRemoveEmpty ) ref_directory.remove(); else ref_directory.removeContent(); return EXIT_SUCCESS; } string normalizeCommand( char *i_command ) { vector<char> res( strlen( i_command )+1 ); // remove starting '-' char *itSrc = i_command; while ( *itSrc!='\0' && *itSrc=='-' ) itSrc++; // lower all letters char *itDst = res.data(); while ( *itSrc!='\0' ) *itDst++ = tolower( *itSrc++ ); *itDst = '\0'; return string( res.data() ); } void test_type_raw_conversion() { // test type<->raw conversions { // string<->raw const string str_ref = "I'm a string<->raw conversion test and I am correct"; // writing vector<char> buffer; buffer.resize( string_raw_size(str_ref) ); char *it = buffer.data(); string_to_raw_data( str_ref, false, it ); // reading string str2; const char *it_const = (const char *)buffer.data(); string_from_raw_data( it_const, false, str2 ); if ( str_ref!=str2 ){ cerr << RED_DEBUG_ERROR << "string<->raw conversion failed, str2=[" << str2 << "]" << endl; exit(EXIT_FAILURE); } } { // cElDate<->raw cElDate date_ref = cElDate::NoDate; cElDate::getCurrentDate_UTC( date_ref ); // writing vector<char> buffer; buffer.resize( date_ref.raw_size() ); char *it = buffer.data(); date_ref.to_raw_data( false, it ); // reading cElDate date2 = cElDate::NoDate; const char *it_const = (const char *)buffer.data(); date2.from_raw_data( it_const, false ); if ( date_ref!=date2 ){ cerr << RED_DEBUG_ERROR << "cElDate<->raw conversion failed, cElDate2=[" << date_ref << "]" << endl; exit(EXIT_FAILURE); } } { // cElCommandToken<->raw //ctRawString cmd_ref("ls"); ctPath cmd_ref("ls"); // writing vector<char> buffer; buffer.resize( cmd_ref.raw_size() ); char *it = buffer.data(); cmd_ref.to_raw_data( false, it ); // reading const char *it_const = (const char *)buffer.data(); cElCommandToken *cmd2 = cElCommandToken::from_raw_data( it_const, false ); if ( *cmd2!=cmd_ref ) { cerr << RED_DEBUG_ERROR << "cElCommand<->raw conversion failed, cmd2="; cmd2->trace(cerr); exit(EXIT_FAILURE); } delete cmd2; } { // cElCommande<->raw cElCommand cmd_ref; cmd_ref.add( ctRawString("ls") ); cmd_ref.add( ctRawString("-l") ); cmd_ref.add( ctPath("../") ); // writing vector<char> buffer; buffer.resize( cmd_ref.raw_size() ); char *it = buffer.data(); cmd_ref.to_raw_data( false, it ); // reading cElCommand cmd2; const char *it_const = (const char *)buffer.data(); cmd2.from_raw_data( it_const, false ); if ( cmd_ref!=cmd2 ) { string s = cmd2.str(); cerr << RED_DEBUG_ERROR << "cElCommand<->raw conversion failed, cmd2=[" << s << "] ---" << endl; exit(EXIT_FAILURE); } } } bool create_random_file( const cElFilename &i_filename, U_INT8 i_size ) { srand( time(NULL) ); ofstream fdst( i_filename.str_unix().c_str(), ios::binary ); if ( !fdst ) { #ifdef __DEBUG_TRACE_PACK cerr << RED_DEBUG_ERROR << "create_random_file: unable to open file [" << i_filename.str_unix() << "] for writing" << endl; exit(EXIT_FAILURE); #endif return false; } const U_INT8 buffer_size = 10e6; U_INT8 remaining = i_size; vector<char> buffer( buffer_size ); char *data = buffer.data(); while ( remaining ) { U_INT8 blockSize = std::min( remaining, buffer_size ); // generate random block char *itData = data; U_INT8 i = blockSize; while ( i-- ) (*itData++)=(char)( rand()%256 ); // write block fdst.write( data, blockSize ); remaining -= blockSize; } fdst.close(); #ifdef __DEBUG_TRACE_PACK if ( i_size!=i_filename.getSize() ){ cerr << RED_ERROR << "create_random_file: size of generated file [" << i_filename.str_unix() << "] = " << i_filename.getSize() << " != " << i_size << endl; exit(EXIT_FAILURE); } #endif return true; } cElFilename getfilename( unsigned int i_i ) { //return ( stringstream() << "a_list_of_data_chunk." << i_i ).str(); stringstream ss; ss << "a_list_of_data_chunks." << i_i; return cElFilename( ss.str() ); } class RandomEntry { public: virtual ~RandomEntry(){} virtual bool isFileEntry(){ return false; } template <class T> T & spe(){ return *((T*)this); } virtual bool createRandom() = 0; virtual void trace( ostream &io_out ) const = 0; }; class FileEntry : public RandomEntry { public: cElFilename m_filename; U_INT8 m_fileSize; FileEntry( const cElFilename &i_filename, U_INT8 i_size ):m_filename(i_filename),m_fileSize(i_size){} void trace( ostream &io_out ) const { io_out << "\t\tentries.push_back( new FileEntry( cElFilename( \"" << m_filename.str_unix() << "\" ), " << m_fileSize << " ) );" << endl; } bool isFileEntry(){ return true; } bool createRandom() { bool res = ( m_filename.m_path.create() && create_random_file( m_filename, m_fileSize ) ); if ( !res ){ cout << RED_ERROR << "unable to create a random file of size " << m_fileSize << " named [" << m_filename.str_unix() << "]" << endl; return false; } return true; } void remove_file() const { if ( !m_filename.remove() ) cerr << RED_WARNING << "test_chunk_io: cannot remove file [" << m_filename.str_unix() << ']' << endl; } void remove_path() const { if ( !m_filename.m_path.isWorkingDirectory() && !m_filename.m_path.removeEmpty() ) cerr << RED_WARNING << "test_chunk_io: cannot remove directory [" << m_filename.m_path.str() << ']' << endl; } }; class BufferEntry : public RandomEntry { public: unsigned char m_type; vector<char> m_buffer; BufferEntry( unsigned char i_type, unsigned int i_size ):m_type(i_type),m_buffer(i_size){} void trace( ostream &io_out ) const { io_out << "\t\tentries.push_back( new BufferEntry( " << (int)m_type << ", " << m_buffer.size() << " ) );" << endl; } bool createRandom() { for ( unsigned int i=0; i<m_buffer.size(); i++ ) m_buffer[i] = (char)( rand()%256 ); return true; } bool isFileEntry(){ return false; } }; bool check_items( const list<ChunkStream::Item*> &i_items, const list<RandomEntry*> &i_entries, const cElFilename i_temporaryFile ) { if ( i_items.size()<i_entries.size() ){ cout << RED_ERROR << "test_chunk_io: nb ChunkStream items = " << i_items.size() << " < nb entries = " << i_entries.size() << endl; return false; } else { // comparing read files and files on disk list<ChunkStream::Item*>::const_reverse_iterator itItem = i_items.rbegin(); list<RandomEntry*>::const_reverse_iterator itEntry = i_entries.rbegin(); unsigned int iItem = 0; while ( itEntry!=i_entries.rend() ) { if ( (**itItem).isFileItem()!=(**itEntry).isFileEntry() ){ cout << RED_ERROR << "test_chunk_io: item " << iItem << " is of type " << ((**itItem).isFileItem()?"File":"Buffer") << " but entry if of type " << ((**itEntry).isFileEntry()?"File":"Buffer") << endl; return false; } else { if ( (**itItem).isFileItem() ) { ChunkStream::FileItem &item = (**itItem).specialize<ChunkStream::FileItem>(); FileEntry &entry = (**itEntry).spe<FileEntry>(); if ( item.copyToFile( i_temporaryFile ) ) { if ( is_equivalent( entry.m_filename, i_temporaryFile ) ) cout << "\t\t--- [" << entry.m_filename.str_unix() << "] checked." << endl; else{ cout << RED_ERROR << "test_chunk_io: file [" << item.m_storedFilename.str_unix() << "] is not equivalent to its original self" << endl; return false; } } else{ cout << RED_ERROR << "test_chunk_io: cannot extract [" << item.m_storedFilename.str_unix() << "]" << endl; return false; } } else { ChunkStream::BufferItem &item = (**itItem).specialize<ChunkStream::BufferItem>(); BufferEntry &entry = (**itEntry).spe<BufferEntry>(); if ( item.m_type!=entry.m_type ){ cout << RED_ERROR << "test_chunk_io: BufferItem of type " << (int)item.m_type << " but type " << entry.m_type << " is expected" << endl; return false; } else if ( item.m_buffer.size()!=entry.m_buffer.size() ){ cout << RED_ERROR << "test_chunk_io: BufferItem of length " << (int)item.m_buffer.size() << " but a length of " << entry.m_buffer.size() << " is expected" << endl; return false; } else if ( memcmp( item.m_buffer.data(), entry.m_buffer.data(), entry.m_buffer.size() )!=0 ){ cout << RED_ERROR << "test_chunk_io: BufferItem content is different from expected" << endl; return false; } else cout << "\t\t--- a BufferItem of type " << (int)item.m_type << " and length " << item.m_buffer.size() << " checked." << endl; } } itItem++; itEntry++; iItem++; } } return true; } void generate_random_entries( const unsigned int i_nbSets, const unsigned int i_nbItemsPerSet, const U_INT8 i_maxEntrySize, list<list<RandomEntry*> > &o_entries ) { cout << "---> generate random entries list" << endl; o_entries.clear(); for ( unsigned int iSet=0; iSet<i_nbSets; iSet++ ){ list<RandomEntry*> entries; for ( unsigned int iEntry=0; iEntry<i_nbItemsPerSet; iEntry++ ){ unsigned int size = ( rand()%i_maxEntrySize )+1; if ( ( rand()%2 )==0 ) entries.push_back( new FileEntry( cElFilename( ( (rand()%2)==0?generate_random_string(5,10):string(".") )+"/"+generate_random_string(5,10) ), size ) ); else entries.push_back( new BufferEntry( rand()%64, size ) ); } o_entries.push_back(entries); } cout << "<--- done\n" << endl; /* cout << "---> load entries list" << endl; { list<RandomEntry*> entries; entries.push_back( new FileEntry( cElFilename( "tzJbjtjACE/vgalkqZ" ), 605 ) ); entries.push_back( new BufferEntry( 33, 240 ) ); entries.push_back( new FileEntry( cElFilename( "jfJcxt/tybHW" ), 462 ) ); entries.push_back( new FileEntry( cElFilename( "ZrXHT" ), 860 ) ); entries.push_back( new FileEntry( cElFilename( "ELBjUqplOl" ), 721 ) ); entries.push_back( new BufferEntry( 42, 957 ) ); entries.push_back( new BufferEntry( 48, 874 ) ); entries.push_back( new BufferEntry( 4, 115 ) ); entries.push_back( new BufferEntry( 16, 387 ) ); entries.push_back( new BufferEntry( 47, 992 ) ); o_entries.push_back(entries); } { list<RandomEntry*> entries; entries.push_back( new FileEntry( cElFilename( "TlngVIpdEX" ), 336 ) ); entries.push_back( new FileEntry( cElFilename( "waeSFv" ), 192 ) ); entries.push_back( new FileEntry( cElFilename( "an_empty_file0" ), 0 ) ); entries.push_back( new FileEntry( cElFilename( "XQxfSeBmg" ), 66 ) ); entries.push_back( new FileEntry( cElFilename( "GJCJL/mzWMaVXK" ), 207 ) ); entries.push_back( new BufferEntry( 0, 742 ) ); entries.push_back( new FileEntry( cElFilename( "tuZRLrtb" ), 802 ) ); entries.push_back( new BufferEntry( 21, 185 ) ); entries.push_back( new BufferEntry( 44, 719 ) ); entries.push_back( new BufferEntry( 17, 214 ) ); entries.push_back( new BufferEntry( 50, 989 ) ); entries.push_back( new FileEntry( cElFilename( "an_empty_file" ), 0 ) ); // a long name //entries.push_back( new FileEntry( cElFilename( generate_random_string(i_maxEntrySize) ), 1024 ) ); o_entries.push_back(entries); } cout << "<--- done\n" << endl; */ } bool add_items( const list<list<RandomEntry*> > &i_entries, ChunkStream &io_stream, const cElFilename &i_temporaryFile ) { list<list<RandomEntry*> >::const_iterator itList = i_entries.begin(); size_t iSet = 0; while ( itList!=i_entries.end() ){ cout << "---> set " << iSet++ << endl; const list<RandomEntry*> &entries = *itList++; if ( !io_stream.writeOpen() ){ cout << RED_ERROR << "add_items: unable to open ChunkStream [" << io_stream.getFilename(0).str_unix() << "] for writing" << endl; return false; } cout << "\t---> writing chunks" << endl; list<RandomEntry*>::const_iterator itEntry = entries.begin(); while ( itEntry!=entries.end() ) { if ( (*itEntry)->isFileEntry() ) { // generate a random file FileEntry &entry = (*itEntry)->spe<FileEntry>(); if ( entry.createRandom() ) io_stream.write_file( entry.m_filename, entry.m_filename ); } else // a buffer chunk { // generate a random buffer BufferEntry &entry = (*itEntry)->spe<BufferEntry>(); if ( entry.createRandom() ) io_stream.write_buffer( entry.m_type, entry.m_buffer ); } itEntry++; } cout << "\t<--- done" << endl; cout << "\t---> reading Items" << endl; list<ChunkStream::Item*> items; if ( !io_stream.read( 0, 0, items ) ) cout << RED_ERROR << "add_items: error while reading chunkStream [" << io_stream.getFilename(0).str_unix() << "]" << endl; cout << "\t<--- done" << endl; // compare write+read Items and initial Entries cout << "\t---> checking read items" << endl; if ( !check_items( items, entries, i_temporaryFile ) ){ cout << RED_ERROR << "add_items: error checking write+read items in stream [" << io_stream.getFilename(0).str_unix() << "]" << endl; return false; } cout << "\t<--- done" << endl; clear_item_list( items ); cout << "<--- done" << endl; } return true; } void trace_all_entries( const cElFilename &i_filename, const list<list<RandomEntry*> > &i_all_entries ) { ofstream dst( i_filename.str_unix().c_str() ); if ( !dst ){ cout << RED_ERROR << "trace_all_entries: cannot open trace file [" << i_filename.str_unix() << endl; exit(EXIT_FAILURE); } list<list<RandomEntry*> >::const_iterator itList = i_all_entries.begin(); while ( itList!=i_all_entries.end() ){ dst << "\t{" << endl; dst << "\t\tlist<RandomEntry*> entries;" << endl; list<RandomEntry*>::const_iterator itEntry = itList->begin(); while ( itEntry!=itList->end() ) (*itEntry++)->trace(dst); dst << "\t\to_entries.push_back(entries);" << endl; dst << "\t}" << endl; itList++; } } void remove_all_entries( const list<list<RandomEntry*> > &i_all_entries ) { // remove all files list<list<RandomEntry*> >::const_iterator itList = i_all_entries.begin(); while ( itList!=i_all_entries.end() ){ list<RandomEntry*>::const_iterator itEntry = itList->begin(); while ( itEntry!=itList->end() ){ if ( (*itEntry)->isFileEntry() ) (*itEntry)->spe<FileEntry>().remove_file(); itEntry++; } itList++; } // remove all empty directories itList = i_all_entries.begin(); while ( itList!=i_all_entries.end() ){ list<RandomEntry*>::const_iterator itEntry = itList->begin(); while ( itEntry!=itList->end() ){ if ( (*itEntry)->isFileEntry() ) (*itEntry)->spe<FileEntry>().remove_path(); itEntry++; } itList++; } // delete RandomEntries items itList = i_all_entries.begin(); while ( itList!=i_all_entries.end() ){ list<RandomEntry*>::const_iterator itEntry = itList->begin(); while ( itEntry!=itList->end() ) delete (*itEntry++); itList++; } } void test_chunk_stream() { // create random items registry, ignored lists or file srand( time(NULL) ); cElFilename streamName("a_stream"); const U_INT8 maxChunkSize = 4e9; ChunkStream chunkStream( streamName, maxChunkSize, false ); // false = reverseByteOrder const unsigned int nbSets = 2; const unsigned int nbEntriesPerSet = 10; list<list<RandomEntry*> > all_entries; generate_random_entries( nbSets, nbEntriesPerSet, 1<<20, all_entries ); cElFilename traceFile("trace"); trace_all_entries( traceFile, all_entries ); cElFilename temporaryFile( "comparisonTemporaryFile" ); // temporary file for file data comparison if ( !add_items( all_entries, chunkStream, temporaryFile ) ) cerr << RED_ERROR << "test_chunk_stream: items couldn't be written then read correctly" << endl; cout << endl; cout << "---> cleaning" << endl; // remove temporary file for file comparison if ( temporaryFile.exists() ) temporaryFile.remove(); // remove entries trace file if ( traceFile.exists() ) traceFile.remove(); // remove entry files and delete allocated objects remove_all_entries( all_entries ); // clear stream if ( !chunkStream.remove() ) cout << RED_ERROR << "test_chunk_stream: unable to remove chunkStream [" << chunkStream.getFilename(0).str_unix() << ']' << endl; cout << "--- done" << endl; } char * __copy_string( const string &i_str ) { char *cstr = new char[i_str.length()+1]; strcpy( cstr, i_str.c_str() ); return cstr; } int test_func( int argc, char **argv ) { test_type_raw_conversion(); test_chunk_stream(); int return_code = EXIT_FAILURE; char **args = NULL; ofstream f; ctPath tempDirectory("test_trace_pack"); cElFilename packName("test.pack"); if ( tempDirectory.exists() ){ cerr << RED_ERROR << "test_trace_pack: temporary directory [" << tempDirectory.str() << "] already exists" << endl; return EXIT_FAILURE; } if ( !tempDirectory.create() ){ cerr << RED_ERROR << "test_trace_pack: cannot create temporary directory [" << tempDirectory.str() << "]" << endl; return EXIT_FAILURE; } // create a test script cElFilename scriptName( "test.script" ); if ( scriptName.exists() ){ cerr << RED_ERROR << "test_trace_pack: test script [" << scriptName.str_unix() << "] already exists" << endl; goto test_trace_pack_clean; } f.open( scriptName.str_unix().c_str() ); if ( !f ){ cerr << RED_ERROR << "test_trace_pack: test script file [" << scriptName.str_unix() << "] cannot be opened for writing" << endl; goto test_trace_pack_clean; } f << "echo \"i am toto\" > toto" << endl; f << "echo ls > tata && chmod +x tata" << endl; #if ELISE_windows f << "date /T > titi && time /T >> titi" << endl; f << "del toto" << endl; #else f << "date > titi" << endl; f << "rm titi" << endl; #endif f.close(); // create arguments to call pack_from_script_func setWorkingDirectory( tempDirectory ); args = new char*[3]; args[0] = __copy_string( string("../")+packName.str_unix() ); args[1] = __copy_string( string("../")+scriptName.str_unix() ); args[2] = __copy_string( "./" ); return_code = pack_from_script_func( 3, args ); setWorkingDirectory( ctPath("../") ); test_trace_pack_clean: if ( scriptName.exists() ) scriptName.remove(); if ( tempDirectory.exists() ) tempDirectory.remove(); if ( args!=NULL ){ delete [] args[0]; delete [] args[1]; delete [] args[2]; delete [] args; } ChunkStream stream( packName, 0, true ); stream.remove(); return return_code; } void parse_ignored_files_and_paths( int i_argc, char **i_argv, list<cElFilename> &o_filenames, list<ctPath> &o_paths ) { o_filenames.clear(); o_paths.clear(); int iarg; for ( iarg=0; iarg<i_argc; iarg++ ){ if ( strcmp(i_argv[iarg], "PATH")==0 ) break; o_filenames.push_back( cElFilename( string(i_argv[iarg]) ) ); } for ( iarg++; iarg<i_argc; iarg++ ) o_paths.push_back( ctPath( string(i_argv[iarg]) ) ); } int add_ignored_func( int argc, char **argv ) { if ( argc<1 ){ cerr << "usage: packname [file0 file1 ...] [PATH path0 path1 ...]" << endl; return EXIT_FAILURE; } const cElFilename packname( (string)(argv[0]) ); if ( !packname.exists() ){ cerr << RED_ERROR << "pack [" << packname.str_unix() << "] does not exist" << endl; return EXIT_FAILURE; } TracePack pack( packname, ctPath() ); if ( !pack.load() ){ cerr << RED_ERROR << "cannot load pack [" << packname.str_unix() << "]" << endl; return EXIT_FAILURE; } if ( argc>1 ){ list<cElFilename> filenames; list<ctPath> paths; parse_ignored_files_and_paths( argc-1, argv+1, filenames, paths ); if ( pack.addIgnored( filenames ) || pack.addIgnored( paths ) ){ cout << "ignored lists changed" << endl; if ( !pack.save() ){ cout << RED_ERROR << "cannot save pack [" << packname.str_unix() << endl; return EXIT_FAILURE; } } } const list<ctPath> &paths = pack.getIgnoredDirectories(); cout << paths.size() << " ignored path" << (paths.size()==0?'\0':'s') << endl; list<ctPath>::const_iterator itPath = paths.begin(); while ( itPath!=paths.end() ) cout << "\t[" << (*itPath++).str() << "]" << endl; const list<cElFilename> &files = pack.getIgnoredFiles(); cout << files.size() << " ignored file" << (files.size()==0?'\0':'s') << endl; list<cElFilename>::const_iterator itFile = files.begin(); while ( itFile!=files.end() ) cout << "\t[" << (*itFile++).str_unix() << "]" << endl; return EXIT_SUCCESS; } bool test_prerequisites() { #ifdef __DEBUG_TRACE_PACK if ( sizeof(U_INT4)!=4 ) { cerr << RED_ERROR << "sizeof(INT4)!=4" << endl; return false; } if ( sizeof(U_INT8)!=8 ) { cerr << RED_ERROR << "sizeof(INT8)!=8" << endl; return false; } if ( sizeof(REAL4)!=4 ) { cerr << RED_ERROR << "sizeof(REAL4)!=4" << endl; return false; } if ( sizeof(REAL8)!=8 ) { cerr << RED_ERROR << "sizeof(REAL8)!=8" << endl; return false; } if ( FLT_MANT_DIG!=24 || DBL_MANT_DIG!=53 ) cerr << "WARNING: single and/or double precision floating-point numbers do not conform to IEEE 754, you may experiment problems while sharing pack files with other systems" << endl; cout << "test_prerequisites: ok." << endl; #endif return true; } int main( int argc, char **argv ) { if ( !test_prerequisites() ) return EXIT_FAILURE; if ( argc<2 ) return help_func(0,NULL); string command = normalizeCommand( argv[1] ); command_t *itCommand = g_commands; while ( itCommand->func!=NULL ) { if (command==itCommand->name) return (*itCommand->func)(argc-2, argv+2); itCommand++; } #ifdef __DEBUG_C_EL_COMMAND cout << "__nb_distroyed : " << cElCommandToken::__nb_distroyed << endl; cout << "__nb_created : " << cElCommandToken::__nb_created << endl; if ( cElCommandToken::__nb_distroyed!=cElCommandToken::__nb_created ) cerr << RED_DEBUG_ERROR << "some cElCommandToken have not been freed : " << cElCommandToken::__nb_created << " created, " << cElCommandToken::__nb_distroyed << " distroyed" << endl; #endif return help_func(0,NULL); }
16,052
834
<filename>snippets/cpp/VS_Snippets_Winforms/Classic DataGridCell.DataGridCell Example/CPP/source.cpp #using <System.dll> #using <System.Windows.Forms.dll> #using <System.Drawing.dll> #using <System.Data.dll> using namespace System; using namespace System::Data; using namespace System::Drawing; using namespace System::Windows::Forms; public ref class Form1: public Form { protected: DataGrid^ dataGrid1; // <Snippet1> private: void SetCell() { // Set the focus to the cell specified by the DataGridCell. DataGridCell dc; dc.RowNumber = 1; dc.ColumnNumber = 1; dataGrid1->CurrentCell = dc; } // </Snippet1> };
245
1,884
package com.github.sarxos.webcam.ds.raspberrypi; import java.util.Map; import com.github.sarxos.webcam.WebcamDevice; /** * ClassName: RaspiyuvDriver <br/> * Runs camera for specific time, and take uncompressed YUV/RGB capture at end * if requested. date: Jan 31, 2019 10:57:58 AM <br/> * java wrapper for raspiyuv * * @author <EMAIL> alexmao86 * @version * @since JDK 1.8 */ public class RaspiYUVDriver extends IPCDriver { private final static String[] DEFAULT_ARGUMENTS = { "--width", "320", "--height", "240", "--timelapse", "10", "--timeout", "0" }; /** * Creates a new instance of RaspiYUVDriver. * * @param command */ public RaspiYUVDriver() { super(Constants.COMMAND_RASPIYUV); } @Override protected String[] getDefaultOptions() { return DEFAULT_ARGUMENTS; } @Override protected WebcamDevice createIPCDevice(int camSelect, Map<String, String> parameters) { return new RaspiYUVDevice(camSelect, parameters, this); } }
359
4,303
<reponame>OAID/Halide package com.example.helloandroidcamera2; import android.util.Log; /** * Java wrappers for fast filters implemented in Halide. */ public class HalideFilters { // Load native Halide shared library. static { System.loadLibrary("HelloAndroidCamera2"); } /** * Copy one Yuv image to another. They must have the same size (but can * have different strides). Uses Halide for fast UV deinterleaving if * formats are compatible. * @return true if it succeeded. */ public static boolean copy(HalideYuvBufferT src, HalideYuvBufferT dst) { return HalideFilters.copyHalide(src.handle(), dst.handle()); } /** * A Halide-accelerated edge detector on the luminance channel. * @return true if it succeeded. */ public static boolean edgeDetect(HalideYuvBufferT src, HalideYuvBufferT dst) { return HalideFilters.edgeDetectHalide(src.handle(), dst.handle()); } /** * A Halide-accelerated native copy between two native Yuv handles. * @return true if it succeeded. */ private static native boolean copyHalide(long srcYuvHandle, long dstYuvHandle); /** * A Halide-accelerated edge detector on the luminance channel. Chroma is set to 128. * @return true if it succeeded. */ private static native boolean edgeDetectHalide(long srcYuvHandle, long dstYuvHandle); }
486
1,442
<reponame>VersiraSec/epsilon-cfw #ifndef SEQUENCE_VALUES_CONTROLLER_H #define SEQUENCE_VALUES_CONTROLLER_H #include "../../shared/sequence_store.h" #include "../../shared/sequence_title_cell.h" #include "../../shared/values_controller.h" #include "interval_parameter_controller.h" namespace Sequence { class ValuesController : public Shared::ValuesController { public: ValuesController(Escher::Responder * parentResponder, Escher::InputEventHandlerDelegate * inputEventHandlerDelegate, Escher::ButtonRowController * header); // TableViewDataSource KDCoordinate columnWidth(int i) override; void willDisplayCellAtLocation(Escher::HighlightCell * cell, int i, int j) override; // ButtonRowDelegate Escher::Button * buttonAtIndex(int index, Escher::ButtonRowController::Position position) const override { return const_cast<Escher::Button *>(&m_setIntervalButton); } // AlternateEmptyViewDelegate I18n::Message emptyMessage() override; // Parameters controllers getters IntervalParameterController * intervalParameterController() override { return &m_intervalParameterController; } private: constexpr static int k_maxNumberOfDisplayableSequences = 3; constexpr static int k_maxNumberOfDisplayableCells = k_maxNumberOfDisplayableSequences * k_maxNumberOfDisplayableRows; // ValuesController void setStartEndMessages(Shared::IntervalParameterController * controller, int column) override { setDefaultStartEndMessages(); } void setDefaultStartEndMessages(); I18n::Message valuesParameterMessageAtColumn(int columnIndex) const override; int maxNumberOfCells() override { return k_maxNumberOfDisplayableCells; } int maxNumberOfFunctions() override { return k_maxNumberOfDisplayableSequences; } // EditableCellViewController bool setDataAtLocation(double floatBody, int columnIndex, int rowIndex) override; // Model getters Shared::SequenceStore * functionStore() const override { return static_cast<Shared::SequenceStore *>(Shared::ValuesController::functionStore()); } Shared::Interval * intervalAtColumn(int columnIndex) override; // Function evaluation memoization static constexpr int k_valuesCellBufferSize = Poincare::PrintFloat::charSizeForFloatsWithPrecision(Poincare::Preferences::LargeNumberOfSignificantDigits); char * memoizedBufferAtIndex(int i) override { assert(i >= 0 && i < k_maxNumberOfDisplayableCells); return m_memoizedBuffer[i]; } int valuesCellBufferSize() const override{ return k_valuesCellBufferSize; } int numberOfMemoizedColumn() override { return k_maxNumberOfDisplayableSequences; } void fillMemoizedBuffer(int i, int j, int index) override; // Parameters controllers getter Escher::ViewController * functionParameterController() override; // Cells & view Escher::SelectableTableView * selectableTableView() override { return &m_selectableTableView; } int abscissaCellsCount() const override { return k_maxNumberOfDisplayableRows; } Escher::EvenOddEditableTextCell * abscissaCells(int j) override { assert (j >= 0 && j < k_maxNumberOfDisplayableRows); return &m_abscissaCells[j]; } int abscissaTitleCellsCount() const override { return 1; } Escher::EvenOddMessageTextCell * abscissaTitleCells(int j) override { assert (j >= 0 && j < abscissaTitleCellsCount()); return &m_abscissaTitleCell; } Shared::SequenceTitleCell * functionTitleCells(int j) override { assert(j >= 0 && j < k_maxNumberOfDisplayableSequences); return &m_sequenceTitleCells[j]; } Escher::EvenOddBufferTextCell * floatCells(int j) override { assert(j >= 0 && j < k_maxNumberOfDisplayableCells); return &m_floatCells[j]; } Escher::SelectableTableView m_selectableTableView; Shared::SequenceTitleCell m_sequenceTitleCells[k_maxNumberOfDisplayableSequences]; Escher::EvenOddBufferTextCell m_floatCells[k_maxNumberOfDisplayableCells]; Escher::EvenOddMessageTextCell m_abscissaTitleCell; Escher::EvenOddEditableTextCell m_abscissaCells[k_maxNumberOfDisplayableRows]; #if COPY_COLUMN Shared::ValuesFunctionParameterController m_sequenceParameterController; #endif IntervalParameterController m_intervalParameterController; Escher::Button m_setIntervalButton; mutable char m_memoizedBuffer[k_maxNumberOfDisplayableCells][k_valuesCellBufferSize]; }; } #endif
1,318
506
<reponame>sykeotic/GASShooter // Copyright 2020 <NAME>. #pragma once #include "CoreMinimal.h" #include "AttributeSet.h" #include "AbilitySystemComponent.h" #include "GSAttributeSetBase.generated.h" // Uses macros from AttributeSet.h #define ATTRIBUTE_ACCESSORS(ClassName, PropertyName) \ GAMEPLAYATTRIBUTE_PROPERTY_GETTER(ClassName, PropertyName) \ GAMEPLAYATTRIBUTE_VALUE_GETTER(PropertyName) \ GAMEPLAYATTRIBUTE_VALUE_SETTER(PropertyName) \ GAMEPLAYATTRIBUTE_VALUE_INITTER(PropertyName) /** * */ UCLASS() class GASSHOOTER_API UGSAttributeSetBase : public UAttributeSet { GENERATED_BODY() public: UGSAttributeSetBase(); // Current Health, when 0 we expect owner to die unless prevented by an ability. Capped by MaxHealth. // Positive changes can directly use this. // Negative changes to Health should go through Damage meta attribute. UPROPERTY(BlueprintReadOnly, Category = "Health", ReplicatedUsing = OnRep_Health) FGameplayAttributeData Health; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, Health) // MaxHealth is its own attribute since GameplayEffects may modify it UPROPERTY(BlueprintReadOnly, Category = "Health", ReplicatedUsing = OnRep_MaxHealth) FGameplayAttributeData MaxHealth; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, MaxHealth) // Health regen rate will passively increase Health every second UPROPERTY(BlueprintReadOnly, Category = "Health", ReplicatedUsing = OnRep_HealthRegenRate) FGameplayAttributeData HealthRegenRate; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, HealthRegenRate) // Current Mana, used to execute special abilities. Capped by MaxMana. UPROPERTY(BlueprintReadOnly, Category = "Mana", ReplicatedUsing = OnRep_Mana) FGameplayAttributeData Mana; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, Mana) // MaxMana is its own attribute since GameplayEffects may modify it UPROPERTY(BlueprintReadOnly, Category = "Mana", ReplicatedUsing = OnRep_MaxMana) FGameplayAttributeData MaxMana; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, MaxMana) // Mana regen rate will passively increase Mana every second UPROPERTY(BlueprintReadOnly, Category = "Mana", ReplicatedUsing = OnRep_ManaRegenRate) FGameplayAttributeData ManaRegenRate; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, ManaRegenRate) // Current stamina, used to execute special abilities. Capped by MaxStamina. UPROPERTY(BlueprintReadOnly, Category = "Stamina", ReplicatedUsing = OnRep_Stamina) FGameplayAttributeData Stamina; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, Stamina) // MaxStamina is its own attribute since GameplayEffects may modify it UPROPERTY(BlueprintReadOnly, Category = "Stamina", ReplicatedUsing = OnRep_MaxStamina) FGameplayAttributeData MaxStamina; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, MaxStamina) // Stamina regen rate will passively increase Stamina every second UPROPERTY(BlueprintReadOnly, Category = "Stamina", ReplicatedUsing = OnRep_StaminaRegenRate) FGameplayAttributeData StaminaRegenRate; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, StaminaRegenRate) // Current shield acts like temporary health. When depleted, damage will drain regular health. UPROPERTY(BlueprintReadOnly, Category = "Shield", ReplicatedUsing = OnRep_Shield) FGameplayAttributeData Shield; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, Shield) // Maximum shield that we can have. UPROPERTY(BlueprintReadOnly, Category = "Shield", ReplicatedUsing = OnRep_MaxShield) FGameplayAttributeData MaxShield; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, MaxShield) // Shield regen rate will passively increase Shield every second UPROPERTY(BlueprintReadOnly, Category = "Shield", ReplicatedUsing = OnRep_ShieldRegenRate) FGameplayAttributeData ShieldRegenRate; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, ShieldRegenRate) // Armor reduces the amount of damage done by attackers UPROPERTY(BlueprintReadOnly, Category = "Armor", ReplicatedUsing = OnRep_Armor) FGameplayAttributeData Armor; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, Armor) // Damage is a meta attribute used by the DamageExecution to calculate final damage, which then turns into -Health // Temporary value that only exists on the Server. Not replicated. UPROPERTY(BlueprintReadOnly, Category = "Damage") FGameplayAttributeData Damage; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, Damage) // MoveSpeed affects how fast characters can move. UPROPERTY(BlueprintReadOnly, Category = "MoveSpeed", ReplicatedUsing = OnRep_MoveSpeed) FGameplayAttributeData MoveSpeed; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, MoveSpeed) UPROPERTY(BlueprintReadOnly, Category = "Character Level", ReplicatedUsing = OnRep_CharacterLevel) FGameplayAttributeData CharacterLevel; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, CharacterLevel) // Experience points gained from killing enemies. Used to level up (not implemented in this project). UPROPERTY(BlueprintReadOnly, Category = "XP", ReplicatedUsing = OnRep_XP) FGameplayAttributeData XP; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, XP) // Experience points awarded to the character's killers. Used to level up (not implemented in this project). UPROPERTY(BlueprintReadOnly, Category = "XP", ReplicatedUsing = OnRep_XPBounty) FGameplayAttributeData XPBounty; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, XPBounty) // Gold gained from killing enemies. Used to purchase items (not implemented in this project). UPROPERTY(BlueprintReadOnly, Category = "Gold", ReplicatedUsing = OnRep_Gold) FGameplayAttributeData Gold; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, Gold) // Gold awarded to the character's killer. Used to purchase items (not implemented in this project). UPROPERTY(BlueprintReadOnly, Category = "Gold", ReplicatedUsing = OnRep_GoldBounty) FGameplayAttributeData GoldBounty; ATTRIBUTE_ACCESSORS(UGSAttributeSetBase, GoldBounty) virtual void PreAttributeChange(const FGameplayAttribute& Attribute, float& NewValue) override; virtual void PostGameplayEffectExecute(const FGameplayEffectModCallbackData& Data) override; virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; protected: FGameplayTag HeadShotTag; // Helper function to proportionally adjust the value of an attribute when it's associated max attribute changes. // (i.e. When MaxHealth increases, Health increases by an amount that maintains the same percentage as before) void AdjustAttributeForMaxChange(FGameplayAttributeData& AffectedAttribute, const FGameplayAttributeData& MaxAttribute, float NewMaxValue, const FGameplayAttribute& AffectedAttributeProperty); /** * These OnRep functions exist to make sure that the ability system internal representations are synchronized properly during replication **/ UFUNCTION() virtual void OnRep_Health(const FGameplayAttributeData& OldHealth); UFUNCTION() virtual void OnRep_MaxHealth(const FGameplayAttributeData& OldMaxHealth); UFUNCTION() virtual void OnRep_HealthRegenRate(const FGameplayAttributeData& OldHealthRegenRate); UFUNCTION() virtual void OnRep_Mana(const FGameplayAttributeData& OldMana); UFUNCTION() virtual void OnRep_MaxMana(const FGameplayAttributeData& OldMaxMana); UFUNCTION() virtual void OnRep_ManaRegenRate(const FGameplayAttributeData& OldManaRegenRate); UFUNCTION() virtual void OnRep_Stamina(const FGameplayAttributeData& OldStamina); UFUNCTION() virtual void OnRep_MaxStamina(const FGameplayAttributeData& OldMaxStamina); UFUNCTION() virtual void OnRep_StaminaRegenRate(const FGameplayAttributeData& OldStaminaRegenRate); UFUNCTION() virtual void OnRep_Shield(const FGameplayAttributeData& OldShield); UFUNCTION() virtual void OnRep_MaxShield(const FGameplayAttributeData& OldMaxShield); UFUNCTION() virtual void OnRep_ShieldRegenRate(const FGameplayAttributeData& OldShieldRegenRate); UFUNCTION() virtual void OnRep_Armor(const FGameplayAttributeData& OldArmor); UFUNCTION() virtual void OnRep_MoveSpeed(const FGameplayAttributeData& OldMoveSpeed); UFUNCTION() virtual void OnRep_CharacterLevel(const FGameplayAttributeData& OldCharacterLevel); UFUNCTION() virtual void OnRep_XP(const FGameplayAttributeData& OldXP); UFUNCTION() virtual void OnRep_XPBounty(const FGameplayAttributeData& OldXPBounty); UFUNCTION() virtual void OnRep_Gold(const FGameplayAttributeData& OldGold); UFUNCTION() virtual void OnRep_GoldBounty(const FGameplayAttributeData& OldGoldBounty); };
2,505
852
<filename>CalibTracker/SiPixelESProducers/src/SiPixelGainCalibrationOfflineSimService.cc /* * ===================================================================================== * * Filename: SiPixelGainCalibrationOfflineSimService.cc * * Description: * * Version: 1.0 (some functionality moved from ../interface/SiPixelGainCalibrationOfflineSimService.h) * Created: 04/16/2008 10:35:35 AM * * Author: <NAME> (<EMAIL>) * University of California, Davis * * ===================================================================================== */ #include "CalibTracker/SiPixelESProducers/interface/SiPixelGainCalibrationOfflineSimService.h" float SiPixelGainCalibrationOfflineSimService::getPedestal(const uint32_t& detID, const int& col, const int& row) { bool isDead = false; bool isNoisy = false; float pedestalValue = this->getPedestalByPixel(detID, col, row, isDead, isNoisy); if (isDead || isNoisy) { this->throwExepctionForBadRead("Offline getPedestal()", detID, col, row, pedestalValue); return 0.0; } return pedestalValue; } float SiPixelGainCalibrationOfflineSimService::getGain(const uint32_t& detID, const int& col, const int& row) { bool isDead = false; bool isNoisy = false; float gainValue = this->getGainByColumn(detID, col, row, isDead, isNoisy); if (isDead || isNoisy) { this->throwExepctionForBadRead("Offline getGain()", detID, col, row, gainValue); return 0.0; } return gainValue; } bool SiPixelGainCalibrationOfflineSimService::isDead(const uint32_t& detID, const int& col, const int& row) { bool isDead = false; bool isNoisy = false; try { this->getPedestalByPixel(detID, col, row, isDead, isNoisy); } catch (cms::Exception& e) { // Do not stop processing if you check if a nonexistant pixel is dead edm::LogInfo("SiPixelGainCalibrationOfflineSimService") << "Attempting to check if nonexistant pixel is dead. Exception message: " << e.what(); isDead = false; } return isDead; } bool SiPixelGainCalibrationOfflineSimService::isNoisy(const uint32_t& detID, const int& col, const int& row) { bool isDead = false; bool isNoisy = false; try { this->getPedestalByPixel(detID, col, row, isDead, isNoisy); } catch (cms::Exception& e) { // Do not stop processing if you check if a nonexistant pixel is dead edm::LogInfo("SiPixelGainCalibrationOfflineSimService") << "Attempting to check if nonexistant pixel is noisy. Exception message: " << e.what(); isNoisy = false; } return isNoisy; } bool SiPixelGainCalibrationOfflineSimService::isDeadColumn(const uint32_t& detID, const int& col, const int& row) { bool isDead = false; bool isNoisy = false; try { this->getGainByColumn(detID, col, row, isDead, isNoisy); // the gain column average can flag a whole column as bad } catch (cms::Exception& e) { // Do not stop processing if you check if a nonexistant pixel is dead edm::LogInfo("SiPixelGainCalibrationOfflineSimService") << "Attempting to check if nonexistant pixel is dead. Exception message: " << e.what(); isDead = false; } return isDead; } bool SiPixelGainCalibrationOfflineSimService::isNoisyColumn(const uint32_t& detID, const int& col, const int& row) { bool isDead = false; bool isNoisy = false; try { this->getGainByColumn(detID, col, row, isDead, isNoisy); // the gain column average can flag a whole column as bad } catch (cms::Exception& e) { // Do not stop processing if you check if a nonexistant pixel is dead edm::LogInfo("SiPixelGainCalibrationOfflineSimService") << "Attempting to check if nonexistant pixel is Noisy. Exception message: " << e.what(); isNoisy = false; } return isNoisy; }
1,300
428
<filename>Java/Loon-Neo/src/loon/action/collision/CollisionHelper.java /** * Copyright 2008 - 2015 The Loon Game Engine 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. * * @project loon * @author cping * @email:<EMAIL> * @version 0.5 */ package loon.action.collision; import loon.canvas.Image; import loon.canvas.LColor; import loon.geom.BoxSize; import loon.geom.Line; import loon.geom.Point; import loon.geom.RectBox; import loon.geom.Shape; import loon.geom.ShapeUtils; import loon.geom.Vector2f; import loon.geom.Vector3f; import loon.geom.XY; import loon.geom.XYZ; import loon.utils.MathUtils; import loon.utils.TArray; /** * 碰撞事件检测与处理工具类,内部是一系列碰撞检测与处理方法的集合 */ public final class CollisionHelper extends ShapeUtils { private CollisionHelper() { } private static final RectBox rectTemp1 = new RectBox(); private static final RectBox rectTemp2 = new RectBox(); /** * 检查两个坐标值是否在指定的碰撞半径内 * * @param x1 * @param y1 * @param r1 * @param x2 * @param y2 * @param r2 * @return */ public static boolean isCollision(float x1, float y1, float r1, float x2, float y2, float r2) { float a = r1 + r2; float dx = x1 - x2; float dy = y1 - y2; return a * a > dx * dx + dy * dy; } /** * 获得两个三维体间初始XYZ位置的距离 * * @param target * @param beforePlace * @param distance * @return */ public static Vector3f getDistantPoint(XYZ target, XYZ source, float distance) { float deltaX = target.getX() - source.getX(); float deltaY = target.getY() - source.getY(); float deltaZ = target.getZ() - source.getZ(); float dist = MathUtils.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ); deltaX /= dist; deltaY /= dist; deltaZ /= dist; return new Vector3f(target.getX() - distance * deltaX, target.getY() - distance * deltaY, target.getZ() - distance * deltaZ); } /** * 获得两个三维体间初始XYZ位置的距离 * * @param target * @param source * @param distance * @return */ public static Vector2f distantPoint(XY target, XY source, float distance) { float deltaX = target.getX() - source.getX(); float deltaY = target.getY() - source.getY(); float dist = MathUtils.sqrt(deltaX * deltaX + deltaY * deltaY); deltaX /= dist; deltaY /= dist; return new Vector2f(target.getX() - distance * deltaX, target.getY() - distance * deltaY); } /** * 获得两个矩形间初始XY位置的距离 * * @param target * @param beforePlace * @return */ public static float getDistance(final BoxSize target, final BoxSize beforePlace) { if (target == null || beforePlace == null) { return 0f; } final float xdiff = target.getX() - beforePlace.getX(); final float ydiff = target.getY() - beforePlace.getY(); return MathUtils.sqrt(xdiff * xdiff + ydiff * ydiff); } /** * 获得多个点间距离 * * @param target * @param beforePlace * @param afterPlace * @param distance * @return */ public static final float getDistance(XY target, XY beforePlace, XY afterPlace, float distance) { return getDistance(target, beforePlace, afterPlace, distance, false); } /** * 获得多个点间距离 * * @param target * @param beforePlace * @param afterPlace * @param distance * @param limit * @return */ public static final float getDistance(XY target, XY beforePlace, XY afterPlace, float distance, boolean limit) { float before = MathUtils.abs(target.getX() - beforePlace.getX()) + MathUtils.abs(target.getY() - beforePlace.getY()); float after = MathUtils.abs(target.getX() - afterPlace.getX()) + MathUtils.abs(target.getY() - afterPlace.getY()); if (limit && before > distance) { return 0; } return 1f * (before - after) / after; } /** * 检查两个矩形是否发生了碰撞 * * @param rect1 * @param rect2 * @return */ public static boolean isRectToRect(BoxSize rect1, BoxSize rect2) { if (rect1 == null || rect2 == null) { return false; } return intersects(rect1.getX(), rect1.getY(), rect1.getWidth(), rect1.getHeight(), rect2.getX(), rect2.getY(), rect2.getWidth(), rect2.getHeight()); } /** * 判断两个圆形是否发生了碰撞 * * @param rect1 * @param rect2 * @return */ public static boolean isCircToCirc(BoxSize rect1, BoxSize rect2) { Point middle1 = getMiddlePoint(rect1); Point middle2 = getMiddlePoint(rect2); float distance = middle1.distanceTo(middle2); float radius1 = rect1.getWidth() / 2; float radius2 = rect2.getWidth() / 2; return (distance - radius2) < radius1; } /** * 检查矩形与圆形是否发生了碰撞 * * @param rect1 * @param rect2 * @return */ public static boolean isRectToCirc(BoxSize rect1, BoxSize rect2) { float radius = rect2.getWidth() / 2; float minX = rect1.getX(); float minY = rect1.getY(); float maxX = rect1.getX() + rect1.getWidth(); float maxY = rect1.getY() + rect1.getHeight(); Point middle = getMiddlePoint(rect2); Point upperLeft = new Point(minX, minY); Point upperRight = new Point(maxX, minY); Point downLeft = new Point(minX, maxY); Point downRight = new Point(maxX, maxY); boolean collided = true; if (!isPointToLine(upperLeft, upperRight, middle, radius)) { if (!isPointToLine(upperRight, downRight, middle, radius)) { if (!isPointToLine(upperLeft, downLeft, middle, radius)) { if (!isPointToLine(downLeft, downRight, middle, radius)) { collided = false; } } } } return collided; } /** * 换算点线距离 * * @param point1 * @param point2 * @param middle * @param radius * @return */ private static boolean isPointToLine(XY point1, XY point2, XY middle, float radius) { Line line = new Line(point1, point2); float distance = line.ptLineDist(middle); return distance < radius; } /** * 返回中间距离的Point2D形式 * * @param rectangle * @return */ private static Point getMiddlePoint(BoxSize rectangle) { return new Point(rectangle.getCenterX(), rectangle.getCenterY()); } /** * 判定指定的两张图片之间是否产生了碰撞 * * @param src * @param x1 * @param y1 * @param dest * @param x2 * @param y2 * @return */ public boolean isPixelCollide(Image src, float x1, float y1, Image dest, float x2, float y2) { float width1 = x1 + src.width() - 1, height1 = y1 + src.height() - 1, width2 = x2 + dest.width() - 1, height2 = y2 + dest.height() - 1; int xstart = (int) MathUtils.max(x1, x2), ystart = (int) MathUtils.max(y1, y2), xend = (int) MathUtils.min(width1, width2), yend = (int) MathUtils.min(height1, height2); int toty = MathUtils.abs(yend - ystart); int totx = MathUtils.abs(xend - xstart); for (int y = 1; y < toty - 1; y++) { int ny = MathUtils.abs(ystart - (int) y1) + y; int ny1 = MathUtils.abs(ystart - (int) y2) + y; for (int x = 1; x < totx - 1; x++) { int nx = MathUtils.abs(xstart - (int) x1) + x; int nx1 = MathUtils.abs(xstart - (int) x2) + x; try { if (((src.getPixel(nx, ny) & LColor.TRANSPARENT) != 0x00) && ((dest.getPixel(nx1, ny1) & LColor.TRANSPARENT) != 0x00)) { return true; } else if (getPixelData(src, nx, ny)[0] != 0 && getPixelData(dest, nx1, ny1)[0] != 0) { return true; } } catch (Throwable e) { } } } return false; } private static final int[] getPixelData(Image image, int x, int y) { return LColor.getRGBs(image.getPixel(x, y)); } public static boolean isPointInRect(float rectX, float rectY, float rectW, float rectH, float x, float y) { if (x >= rectX && x <= rectX + rectW) { if (y >= rectY && y <= rectY + rectH) { return true; } } return false; } public static final boolean intersects(RectBox rect, float x, float y) { if (rect != null) { if (rect.Left() <= x && x < rect.Right() && rect.Top() <= y && y < rect.Bottom()) return true; } return false; } public static final boolean intersects(float sx, float sy, float width, float height, float x, float y) { return (x >= sx) && ((x - sx) < width) && (y >= sy) && ((y - sy) < height); } /** * 判断指定大小的两组像素是否相交 * * @param rectA * @param dataA * @param rectB * @param dataB * @return */ public static boolean intersects(RectBox rectA, int[] dataA, RectBox rectB, int[] dataB) { int top = (int) MathUtils.max(rectA.getY(), rectB.getY()); int bottom = (int) MathUtils.min(rectA.getBottom(), rectB.getBottom()); int left = (int) MathUtils.max(rectA.getX(), rectB.getX()); int right = (int) MathUtils.min(rectA.getRight(), rectB.getRight()); for (int y = top; y < bottom; y++) { for (int x = left; x < right; x++) { int colorA = dataA[(int) ((x - rectA.x) + (y - rectA.y) * rectA.width)]; int colorB = dataB[(int) ((x - rectB.x) + (y - rectB.y) * rectB.width)]; if (colorA >>> 24 != 0 && colorB >>> 24 != 0) { return true; } } } return false; } /** * 判断两个Shape是否相交 * * @param s1 * @param s2 * @return */ public static final boolean intersects(Shape s1, Shape s2) { if (s1 == null || s2 == null) { return false; } return s1.intersects(s2); } public static final int[] intersects(RectBox rect1, RectBox rect2) { if (rect1.Left() < rect2.Right() && rect2.Left() < rect1.Right() && rect1.Top() < rect2.Bottom() && rect2.Top() < rect1.Bottom()) { return new int[] { rect1.Left() < rect2.Left() ? rect2.Left() - rect1.Left() : 0, rect1.Top() < rect2.Top() ? rect2.Top() - rect1.Top() : 0, rect1.Right() > rect2.Right() ? rect1.Right() - rect2.Right() : 0, rect1.Bottom() > rect2.Bottom() ? rect1.Bottom() - rect2.Bottom() : 0 }; } return null; } public static final boolean intersects(float x, float y, float width, float height, float dx, float dy, float dw, float dh) { return intersects(x, y, width, height, dx, dy, dw, dh, false); } public static final boolean intersects(float x, float y, float width, float height, float dx, float dy, float dw, float dh, boolean touchingIsIn) { rectTemp1.setBounds(x, y, width, height).normalize(); rectTemp2.setBounds(dx, dy, dw, dh).normalize(); if (touchingIsIn) { if (rectTemp1.x + rectTemp1.width == rectTemp2.x) { return true; } if (rectTemp1.x == rectTemp2.x + rectTemp2.width) { return true; } if (rectTemp1.y + rectTemp1.height == rectTemp2.y) { return true; } if (rectTemp1.y == rectTemp2.y + rectTemp2.height) { return true; } } return rectTemp1.intersects(rectTemp2); } /** * 计算并返回两个正方形之间的碰撞间距值 * * @param rect1 * @param rect2 * @return */ public static float squareRects(BoxSize rect1, BoxSize rect2) { if (rect1 == null || rect2 == null) { return 0f; } return squareRects(rect1.getX(), rect1.getY(), rect1.getWidth(), rect1.getHeight(), rect2.getX(), rect2.getY(), rect2.getWidth(), rect2.getHeight()); } /** * 计算并返回两个正方形之间的碰撞间距值 * * @param x1 * @param y1 * @param w1 * @param h1 * @param x2 * @param y2 * @param w2 * @param h2 * @return */ public static float squareRects(float x1, float y1, float w1, float h1, float x2, float y2, float w2, float h2) { if (x1 < x2 + w2 && x2 < x1 + w1) { if (y1 < y2 + h2 && y2 < y1 + h1) { return 0f; } if (y1 > y2) { return (y1 - (y2 + h2)) * (y1 - (y2 + h2)); } return (y2 - (y1 + h1)) * (y2 - (y1 + h1)); } if (y1 < y2 + h2 && y2 < y1 + h1) { if (x1 > x2) { return (x1 - (x2 + w2)) * (x1 - (x2 + w2)); } return (x2 - (x1 + w1)) * (x2 - (x1 + w1)); } if (x1 > x2) { if (y1 > y2) { return MathUtils.distSquared((x2 + w2), (y2 + h2), x1, y1); } return MathUtils.distSquared(x2 + w2, y2, x1, y1 + h1); } if (y1 > y2) { return MathUtils.distSquared(x2, y2 + h2, x1 + w1, y1); } return MathUtils.distSquared(x2, y2, x1 + w1, y1 + h1); } /** * 计算并返回指定位置与指定正方形之间的碰撞间距值 * * @param xy * @param box * @return */ public static float squarePointRect(XY xy, BoxSize box) { if (xy == null || box == null) { return 0f; } return squarePointRect(xy.getX(), xy.getY(), box.getX(), box.getY(), box.getWidth(), box.getHeight()); } /** * 计算并返回指定位置与指定正方形之间的碰撞间距值 * * @param px * @param py * @param rx * @param ry * @param rw * @param rh * @return */ public static float squarePointRect(float px, float py, float rx, float ry, float rw, float rh) { if (px >= rx && px <= rx + rw) { if (py >= ry && py <= ry + rh) { return 0f; } if (py > ry) { return (py - (ry + rh)) * (py - (ry + rh)); } return (ry - py) * (ry - py); } if (py >= ry && py <= ry + rh) { if (px > rx) { return (px - (rx + rw)) * (px - (rx + rw)); } return (rx - px) * (rx - px); } if (px > rx) { if (py > ry) { return MathUtils.distSquared(rx + rw, ry + rh, px, py); } return MathUtils.distSquared(rx + rw, ry, px, py); } if (py > ry) { return MathUtils.distSquared(rx, ry + rh, px, py); } return MathUtils.distSquared(rx, ry, px, py); } /** * 判断两个Shape是否存在包含关系 * * @param s1 * @param s2 * @return */ public static final boolean contains(Shape s1, Shape s2) { if (s1 == null || s2 == null) { return false; } return s1.contains(s2); } public static final boolean contains(float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh) { return (dx >= sx && dy >= sy && ((dx + dw) <= (sx + sw)) && ((dy + dh) <= (sy + sh))); } public static final boolean contains(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { return (dx >= sx && dy >= sy && ((dx + dw) <= (sx + sw)) && ((dy + dh) <= (sy + sh))); } public static final boolean containsIsometric(int x, int y, int w, int h, int px, int py) { float mx = w / 2; float my = h / 2; float ix = px - x; float iy = py - y; if (iy > my) { iy = my - (iy - my); } if ((ix > mx + 1 + (2 * iy)) || (ix < mx - 1 - (2 * iy))) { return false; } return true; } public static final boolean containsHexagon(int x, int y, int w, int h, int px, int py) { float mx = w / 4; float my = h / 2; float hx = px - x; float hy = py - y; if (hx > mx * 3) { hx = mx - (hx - mx * 3); } else if (hx > mx) { return py >= y && py <= y + h; } if ((hy > my + 1 + (2 * hx)) || (hy < my - 1 - (2 * hx))) { return false; } return true; } public static final void confine(RectBox rect, RectBox field) { int x = rect.Right() > field.Right() ? field.Right() - (int) rect.getWidth() : rect.Left(); if (x < field.Left()) { x = field.Left(); } int y = (int) (rect.Bottom() > field.Bottom() ? field.Bottom() - rect.getHeight() : rect.Top()); if (y < field.Top()) { y = field.Top(); } rect.offset(x, y); } public static final Line getLine(Shape shape, int s, int e) { float[] start = shape.getPoint(s); float[] end = shape.getPoint(e); Line line = new Line(start[0], start[1], end[0], end[1]); return line; } public static final Line getLine(Shape shape, float sx, float sy, int e) { float[] end = shape.getPoint(e); Line line = new Line(sx, sy, end[0], end[1]); return line; } public static final boolean checkAABBvsAABB(XY p1, float w1, float h1, XY p2, float w2, float h2) { return checkAABBvsAABB(p1.getX(), p1.getY(), w1, h1, p2.getX(), p2.getY(), w2, h2); } public static final boolean checkAABBvsAABB(float x1, float y1, float w1, float h1, float x2, float y2, float w2, float h2) { return !(x1 > x2 + w2 || x1 + w1 < x2) && !(y1 > y2 + h2 || y1 + h1 < y2); } public static final boolean checkAABBvsAABB(XY p1Min, XY p1Max, XY p2Min, XY p2Max) { return checkAABBvsAABB(p1Min.getX(), p1Min.getY(), p1Max.getX() - p1Min.getX(), p1Max.getY() - p1Min.getY(), p2Min.getX(), p2Min.getY(), p2Max.getX() - p2Min.getX(), p2Max.getY() - p2Min.getY()); } public static final boolean checkAABBvsAABB(XYZ p1, float w1, float h1, float t1, XYZ p2, float w2, float h2, float t2) { return checkAABBvsAABB(p1.getX(), p1.getY(), p1.getZ(), w1, h1, t1, p2.getX(), p2.getY(), p2.getZ(), w2, h2, t2); } public static final boolean checkAABBvsAABB(float x1, float y1, float z1, float w1, float h1, float t1, float x2, float y2, float z2, float w2, float h2, float t2) { return !(x1 > x2 + w2 || x1 + w1 < x2) && !(y1 > y2 + h2 || y1 + h1 < y2) && !(z1 > z2 + t2 || z1 + t1 < z2); } public static final boolean checkAABBvsAABB(XYZ p1Min, XYZ p1Max, XYZ p2Min, XYZ p2Max) { return checkAABBvsAABB(p1Min.getX(), p1Min.getY(), p1Min.getZ(), p1Max.getX() - p1Min.getX(), p1Max.getY() - p1Min.getY(), p1Max.getZ() - p1Min.getZ(), p2Min.getX(), p2Min.getY(), p1Min.getZ(), p2Max.getX() - p2Min.getX(), p2Max.getY() - p2Min.getY(), p2Max.getZ() - p2Min.getZ()); } public static final boolean checkCircleCircle(XY p1, float r1, XY p2, float r2) { return checkCircleCircle(p1.getX(), p1.getY(), r1, p2.getX(), p2.getY(), r2); } public static final boolean checkCircleCircle(float x1, float y1, float r1, float x2, float y2, float r2) { float distance = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); float radiusSumSq = (r1 + r2) * (r1 + r2); return distance <= radiusSumSq; } public static final boolean checkSphereSphere(XYZ p1, float r1, XYZ p2, float r2) { return checkSphereSphere(p1.getX(), p1.getY(), p1.getZ(), r1, p2.getX(), p2.getY(), p2.getZ(), r2); } public static final boolean checkSphereSphere(float x1, float y1, float z1, float r1, float x2, float y2, float z2, float r2) { float distance = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1); float radiusSumSq = (r1 + r2) * (r1 + r2); return distance <= radiusSumSq; } public static final float getJumpVelocity(float gravity, float distance) { return MathUtils.sqrt(2 * distance * gravity); } public final static boolean checkAngle(float angle, float actual) { return actual > angle - 22.5f && actual < angle + 22.5f; } /** * 判断两点坐标是否存在移动 * * @param distance * @param startPoints * @param endPoint * @return */ public static final boolean isMoved(float distance, XY startPoints, XY endPoint) { return isMoved(distance, startPoints.getX(), startPoints.getY(), endPoint.getX(), endPoint.getY()); } /** * 判断两点坐标是否存在移动 * * @param distance * @param sx * @param sy * @param dx * @param dy * @return */ public static final boolean isMoved(float distance, float sx, float sy, float dx, float dy) { float xDistance = dx - sx; float yDistance = dy - sy; if (MathUtils.abs(xDistance) < distance && MathUtils.abs(yDistance) < distance) { return false; } return true; } public static final Vector2f nearestToLine(Vector2f p1, Vector2f p2, Vector2f p3, Vector2f n) { int ax = (int) (p2.x - p1.x), ay = (int) (p2.y - p1.y); float u = (p3.x - p1.x) * ax + (p3.y - p1.y) * ay; u /= (ax * ax + ay * ay); n.x = p1.x + MathUtils.round(ax * u); n.y = p1.y + MathUtils.round(ay * u); return n; } public static final boolean lineIntersection(XY p1, XY p2, boolean seg1, XY p3, XY p4, boolean seg2, Vector2f result) { float y43 = p4.getY() - p3.getY(); float x21 = p2.getX() - p1.getX(); float x43 = p4.getX() - p3.getX(); float y21 = p2.getY() - p1.getY(); float denom = y43 * x21 - x43 * y21; if (denom == 0) { return false; } float y13 = p1.getY() - p3.getY(); float x13 = p1.getX() - p3.getX(); float ua = (x43 * y13 - y43 * x13) / denom; if (seg1 && ((ua < 0) || (ua > 1))) { return false; } if (seg2) { float ub = (x21 * y13 - y21 * x13) / denom; if ((ub < 0) || (ub > 1)) { return false; } } float x = p1.getX() + ua * x21; float y = p1.getY() + ua * y21; result.setLocation(x, y); return true; } public static final boolean lineIntersection(XY p1, XY p2, XY p3, XY p4, Vector2f ptIntersection) { float num1 = ((p4.getY() - p3.getY()) * (p2.getX() - p1.getX())) - ((p4.getX() - p3.getX()) * (p2.getY() - p1.getY())); float num2 = ((p4.getX() - p3.getX()) * (p1.getY() - p3.getY())) - ((p4.getY() - p3.getY()) * (p1.getX() - p3.getX())); float num3 = ((p2.getX() - p1.getX()) * (p1.getY() - p3.getY())) - ((p2.getY() - p1.getY()) * (p1.getX() - p3.getX())); if (num1 != 0f) { float num4 = num2 / num1; float num5 = num3 / num1; if (((num4 >= 0f) && (num4 <= 1f)) && ((num5 >= 0f) && (num5 <= 1f))) { ptIntersection.x = (int) (p1.getX() + (num4 * (p2.getX() - p1.getX()))); ptIntersection.y = (int) (p1.getY() + (num4 * (p2.getY() - p1.getY()))); return true; } } return false; } public static final int whichSide(XY p1, float theta, XY p2) { theta += MathUtils.PI / 2; float x = (int) (p1.getX() + MathUtils.round(1000 * MathUtils.cos(theta))); float y = (int) (p1.getY() + MathUtils.round(1000 * MathUtils.sin(theta))); return MathUtils.iceil(dotf(p1.getX(), p1.getY(), p2.getX(), p2.getY(), x, y)); } public static final void shiftToContain(RectBox tainer, RectBox tained) { if (tained.x < tainer.x) { tainer.x = tained.x; } if (tained.y < tainer.y) { tainer.y = tained.y; } if (tained.x + tained.width > tainer.x + tainer.width) { tainer.x = tained.x - (tainer.width - tained.width); } if (tained.y + tained.height > tainer.y + tainer.height) { tainer.y = tained.y - (tainer.height - tained.height); } } /** * 将目标矩形添加到原始矩形的边界。 * * @param source * @param target * @return */ public static final RectBox add(RectBox source, RectBox target) { if (target == null) { return new RectBox(source); } else if (source == null) { source = new RectBox(target); } else { source.add(target); } return source; } /** * 填充指定瓦片的边界。瓦片从左到右,从上到下。 * * @param width * @param height * @param tileWidth * @param tileHeight * @param tileIndex * @return */ public static final RectBox getTile(int width, int height, int tileWidth, int tileHeight, int tileIndex) { return getTile(width, height, tileWidth, tileHeight, tileIndex, null); } /** * 填充指定瓦片的边界。瓦片从左到右,从上到下。 * * @param width * @param height * @param tileWidth * @param tileHeight * @param tileIndex * @param result */ public static final RectBox getTile(int width, int height, int tileWidth, int tileHeight, int tileIndex, RectBox result) { if (result == null) { result = new RectBox(); } int tilesPerRow = width / tileWidth; if (tilesPerRow == 0) { result.setBounds(0, 0, width, height); } else { int row = tileIndex / tilesPerRow; int col = tileIndex % tilesPerRow; result.setBounds(tileWidth * col, tileHeight * row, tileWidth, tileHeight); } return result; } /** * 获得指定线经过的点 * * @param line * @param stepRate * @return */ public static final TArray<Vector2f> getBresenhamPoints(Line line, float stepRate) { if (stepRate < 1f) { stepRate = 1f; } TArray<Vector2f> results = new TArray<Vector2f>(); float x1 = MathUtils.round(line.getX1()); float y1 = MathUtils.round(line.getY1()); float x2 = MathUtils.round(line.getX2()); float y2 = MathUtils.round(line.getY2()); float dx = MathUtils.abs(x2 - x1); float dy = MathUtils.abs(y2 - y1); float sx = (x1 < x2) ? 1 : -1; float sy = (y1 < y2) ? 1 : -1; int err = MathUtils.ceil(dx) - MathUtils.ceil(dy); results.add(new Vector2f(x1, y1)); int i = 1; while (!((x1 == x2) && (y1 == y2))) { int e2 = err << 1; if (e2 > -dy) { err -= dy; x1 += sx; } if (e2 < dx) { err += dx; y1 += sy; } if (i % stepRate == 0) { results.add(new Vector2f(x1, y1)); } i++; } return results; } }
11,112
1,382
/* PipeWire * * Copyright © 2020 <NAME> * Copyright © 2021 <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef PULSE_SERVER_VOLUME_H #define PULSE_SERVER_VOLUME_H #include <stdbool.h> #include <stdint.h> #include "format.h" struct spa_pod; struct volume { uint8_t channels; float values[CHANNELS_MAX]; }; #define VOLUME_INIT \ (struct volume) { \ .channels = 0, \ } struct volume_info { struct volume volume; struct channel_map map; bool mute; float level; float base; uint32_t steps; #define VOLUME_HW_VOLUME (1<<0) #define VOLUME_HW_MUTE (1<<1) uint32_t flags; }; #define VOLUME_INFO_INIT \ (struct volume_info) { \ .volume = VOLUME_INIT, \ .mute = false, \ .level = 1.0, \ .base = 1.0, \ .steps = 256, \ } static inline bool volume_valid(const struct volume *vol) { if (vol->channels == 0 || vol->channels > CHANNELS_MAX) return false; return true; } static inline void volume_make(struct volume *vol, uint8_t channels) { uint8_t i; for (i = 0; i < channels; i++) vol->values[i] = 1.0f; vol->channels = channels; } int volume_compare(struct volume *vol, struct volume *other); int volume_parse_param(const struct spa_pod *param, struct volume_info *info, bool monitor); #endif
788
1,537
<gh_stars>1000+ c.NotebookApp.ip = '0.0.0.0' c.NotebookApp.notebook_dir = '/home/root/notebooks' c.NotebookApp.password = '<PASSWORD>:<PASSWORD>' c.NotebookApp.port = 9090 c.NotebookApp.iopub_data_rate_limit = 100000000
96
312
/* * Copyright 2016-2021 The jetcd 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 io.etcd.jetcd.common; import java.util.concurrent.atomic.AtomicBoolean; public abstract class Service implements AutoCloseable { private final AtomicBoolean running; protected Service() { this.running = new AtomicBoolean(); } public void start() { if (this.running.compareAndSet(false, true)) { doStart(); } } public void stop() { if (this.running.compareAndSet(true, false)) { doStop(); } } public void restart() { stop(); start(); } @Override public void close() { stop(); } public boolean isRunning() { return running.get(); } protected abstract void doStart(); protected abstract void doStop(); }
477
3,402
{ "uuid" : "cd92588f-b987-4a12-c90f-e32c44346c64", "version" : "2.1", "name" : "twenty_dim", "description" : "", "lookups" : [ ], "dimensions" : [ { "table" : "DEFAULT.FIFTY_DIM", "columns" : [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T"] }], "metrics" : [ "AAA" ], "last_modified" : 1457444314662, "fact_table" : "DEFAULT.FIFTY_DIM", "filter_condition" : "", "partition_desc" : { "partition_date_column" : null, "partition_time_column" : null, "partition_date_start" : 0, "partition_date_format" : "yyyyMMdd", "partition_time_format" : "HH:mm:ss", "partition_type" : "APPEND", "partition_condition_builder" : "org.apache.kylin.metadata.model.PartitionDesc$DefaultPartitionConditionBuilder" } }
380
672
<reponame>snowp/spectator /* * Copyright 2014-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spectator.api; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.function.LongSupplier; public class SwapMeterTest { private static final LongSupplier VERSION = () -> 0L; private final ManualClock clock = new ManualClock(); private final Registry registry = new DefaultRegistry(); private final Id counterId = registry.createId("counter"); private final Id gaugeId = registry.createId("gauge"); private final Id timerId = registry.createId("timer"); private final Id distSummaryId = registry.createId("distSummary"); @Test public void wrappedCounters() { Counter c = new DefaultCounter(clock, counterId); SwapCounter sc1 = new SwapCounter(registry, VERSION, counterId, c); SwapCounter sc2 = new SwapCounter(registry, VERSION, counterId, sc1); Assertions.assertFalse(sc2.hasExpired()); sc2.increment(); Assertions.assertEquals(1, c.count()); Assertions.assertEquals(1, sc1.count()); Assertions.assertEquals(1, sc2.count()); } @Test public void wrapExpiredCounter() { ExpiringRegistry registry = new ExpiringRegistry(clock); Counter c = registry.counter(counterId); clock.setWallTime(60000 * 30); SwapCounter s1 = new SwapCounter(registry, VERSION, counterId, c); s1.increment(); Assertions.assertEquals(1, c.count()); Assertions.assertEquals(1, s1.count()); } @Test public void wrapExpiredTimer() { ExpiringRegistry registry = new ExpiringRegistry(clock); Timer t = registry.timer(timerId); clock.setWallTime(60000 * 30); SwapTimer s1 = new SwapTimer(registry, VERSION, timerId, t); s1.record(42, TimeUnit.NANOSECONDS); Assertions.assertEquals(1, t.count()); Assertions.assertEquals(1, s1.count()); } @Test public void wrapExpiredGauge() { ExpiringRegistry registry = new ExpiringRegistry(clock); Gauge c = registry.gauge(gaugeId); clock.setWallTime(60000 * 30); SwapGauge s1 = new SwapGauge(registry, VERSION, gaugeId, c); s1.set(1.0); Assertions.assertEquals(1.0, c.value(), 1e-12); Assertions.assertEquals(1.0, s1.value(), 1e-12); } @Test public void wrapExpiredDistSummary() { ExpiringRegistry registry = new ExpiringRegistry(clock); DistributionSummary c = registry.distributionSummary(distSummaryId); clock.setWallTime(60000 * 30); SwapDistributionSummary s1 = new SwapDistributionSummary(registry, VERSION, distSummaryId, c); s1.record(1); Assertions.assertEquals(1, c.count()); Assertions.assertEquals(1, s1.count()); } @Test public void versionUpdateExpiration() { AtomicLong version = new AtomicLong(); Counter c = new DefaultCounter(clock, counterId); SwapCounter sc = new SwapCounter(registry, version::get, counterId, c); sc.increment(); Assertions.assertFalse(sc.hasExpired()); version.incrementAndGet(); Assertions.assertTrue(sc.hasExpired()); sc.increment(); Assertions.assertFalse(sc.hasExpired()); } }
1,270
584
/* Copyright 2013 Adobe 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) */ /*************************************************************************************************/ #ifndef STLAB_ITERATOR_SET_NEXT_HPP #define STLAB_ITERATOR_SET_NEXT_HPP /*************************************************************************************************/ namespace stlab { /*************************************************************************************************/ namespace unsafe { /*************************************************************************************************/ template <typename I> // I models NodeIterator struct set_next_fn; // Must be specialized /*************************************************************************************************/ template <typename I> // I models NodeIterator inline void set_next(I x, I y) { set_next_fn<I>()(x, y); } /*************************************************************************************************/ template <typename I> // T models ForwardNodeIterator inline void splice_node_range(I location, I first, I last) { I successor(std::next(location)); set_next(location, first); set_next(last, successor); } template <typename I> // I models ForwardNodeIterator inline void skip_next_node(I location) { set_next(location, std::next(std::next(location))); } template <typename I> // I models BidirectionalNodeIterator inline void skip_node(I location) { set_next(std::prev(location), std::next(location)); } /*************************************************************************************************/ } // namespace unsafe /*************************************************************************************************/ } // namespace stlab /*************************************************************************************************/ #endif // STLAB_ITERATOR_SET_NEXT_HPP /*************************************************************************************************/
467
324
@interface NSString (NSStringAdditions) - (NSString*) URLEncodedString; - (NSString*) URLDecodedString; - (NSString*) md5; @end
48
1,609
<filename>src/main/java/org/springframework/session/Session.java<gh_stars>1000+ /* * Copyright 2002-2015 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.session; import java.util.Set; /** * Provides a way to identify a user in an agnostic way. This allows the session to be used by an HttpSession, WebSocket * Session, or even non web related sessions. * * @author <NAME> * @since 1.0 */ public interface Session { /** * Gets a unique string that identifies the {@link Session} * * @return a unique string that identifies the {@link Session} */ String getId(); /** * Gets the Object associated with the specified name or null if no Object is associated to that name. * * @param attributeName the name of the attribute to get * @return the Object associated with the specified name or null if no Object is associated to that name * @param <T> The return type of the attribute */ <T> T getAttribute(String attributeName); /** * Gets the attribute names that have a value associated with it. Each value can be passed into {@link org.springframework.session.Session#getAttribute(String)} to obtain the attribute value. * * @return the attribute names that have a value associated with it. * @see #getAttribute(String) */ Set<String> getAttributeNames(); /** * Sets the attribute value for the provided attribute name. If the attributeValue is null, it has the same result as removing the attribute with {@link org.springframework.session.Session#removeAttribute(String)} . * * @param attributeName the attribute name to set * @param attributeValue the value of the attribute to set. If null, the attribute will be removed. */ void setAttribute(String attributeName, Object attributeValue); /** * Removes the attribute with the provided attribute name * @param attributeName the name of the attribute to remove */ void removeAttribute(String attributeName); }
646
606
/* # _____ ___ ____ ___ ____ # ____| | ____| | | |____| # | ___| |____ ___| ____| | \ PS2DEV Open Source Project. #----------------------------------------------------------------------- # Copyright 2005, ps2dev - http://www.ps2dev.org # Licenced under GNU Library General Public License version 2 */ /** * @file * audsrv helpers. */ #ifndef __COMMON_H__ #define __COMMON_H__ /** Helper function to easily create threads * @param func thread procedure * @param priority thread priority (usually 40) * @param param optional argument for thread procedure * @returns thread_id (int), negative on error * * Creates a thread based on the given parameter. Upon completion, * thread is started. */ int create_thread(void *func, int priority, void *param); /** Helper to print buffer in hex. Useful for debugging. * @param ptr pointer to buffer * @param len buffer length */ void print_hex_buffer(unsigned char *ptr, int len); #endif
321
7,482
<reponame>Davidfind/rt-thread<filename>bsp/imx6sx/iMX6_Platform_SDK/sdk/include/mx6sl/registers/regsssi.h /* * Copyright (c) 2012, Freescale Semiconductor, Inc. * All rights reserved. * * THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL FREESCALE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_SSI_REGISTERS_H__ #define __HW_SSI_REGISTERS_H__ #include "regs.h" /* * i.MX6SL SSI * * SSI * * Registers defined in this header file: * - HW_SSI_STXn - SSI Transmit Data Register n * - HW_SSI_SRXn - SSI Receive Data Register n * - HW_SSI_SCR - SSI Control Register * - HW_SSI_SISR - SSI Interrupt Status Register * - HW_SSI_SIER - SSI Interrupt Enable Register * - HW_SSI_STCR - SSI Transmit Configuration Register * - HW_SSI_SRCR - SSI Receive Configuration Register * - HW_SSI_STCCR - SSI Transmit Clock Control Register * - HW_SSI_SRCCR - SSI Receive Clock Control Register * - HW_SSI_SFCSR - SSI FIFO Control/Status Register * - HW_SSI_SACNT - SSI AC97 Control Register * - HW_SSI_SACADD - SSI AC97 Command Address Register * - HW_SSI_SACDAT - SSI AC97 Command Data Register * - HW_SSI_SATAG - SSI AC97 Tag Register * - HW_SSI_STMSK - SSI Transmit Time Slot Mask Register * - HW_SSI_SRMSK - SSI Receive Time Slot Mask Register * - HW_SSI_SACCST - SSI AC97 Channel Status Register * - HW_SSI_SACCEN - SSI AC97 Channel Enable Register * - HW_SSI_SACCDIS - SSI AC97 Channel Disable Register * * - hw_ssi_t - Struct containing all module registers. */ //! @name Module base addresses //@{ #ifndef REGS_SSI_BASE #define HW_SSI_INSTANCE_COUNT (3) //!< Number of instances of the SSI module. #define HW_SSI1 (1) //!< Instance number for SSI1. #define HW_SSI2 (2) //!< Instance number for SSI2. #define HW_SSI3 (3) //!< Instance number for SSI3. #define REGS_SSI1_BASE (0x02028000) //!< Base address for SSI instance number 1. #define REGS_SSI2_BASE (0x0202c000) //!< Base address for SSI instance number 2. #define REGS_SSI3_BASE (0x02030000) //!< Base address for SSI instance number 3. //! @brief Get the base address of SSI by instance number. //! @param x SSI instance number, from 1 through 3. #define REGS_SSI_BASE(x) ( (x) == HW_SSI1 ? REGS_SSI1_BASE : (x) == HW_SSI2 ? REGS_SSI2_BASE : (x) == HW_SSI3 ? REGS_SSI3_BASE : 0x00d00000) //! @brief Get the instance number given a base address. //! @param b Base address for an instance of SSI. #define REGS_SSI_INSTANCE(b) ( (b) == REGS_SSI1_BASE ? HW_SSI1 : (b) == REGS_SSI2_BASE ? HW_SSI2 : (b) == REGS_SSI3_BASE ? HW_SSI3 : 0) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_STXn - SSI Transmit Data Register n //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_STXn - SSI Transmit Data Register n (RW) * * Reset value: 0x00000000 * * Enable SSI (SSIEN=1) before writing to SSI Transmit Data Registers. */ typedef union _hw_ssi_stxn { reg32_t U; struct _hw_ssi_stxn_bitfields { unsigned STXN : 32; //!< [31:0] SSI Transmit Data. } B; } hw_ssi_stxn_t; #endif /*! * @name Constants and macros for entire SSI_STXn register */ //@{ //! @brief Number of instances of the SSI_STXn register. #define HW_SSI_STXn_COUNT (2) #define HW_SSI_STXn_ADDR(n, x) (REGS_SSI_BASE(x) + 0x0 + (0x4 * (n))) #ifndef __LANGUAGE_ASM__ #define HW_SSI_STXn(x, n) (*(volatile hw_ssi_stxn_t *) HW_SSI_STXn_ADDR(n, x)) #define HW_SSI_STXn_RD(x, n) (HW_SSI_STXn(x, n).U) #define HW_SSI_STXn_WR(x, n, v) (HW_SSI_STXn(x, n).U = (v)) #define HW_SSI_STXn_SET(x, n, v) (HW_SSI_STXn_WR(x, n, HW_SSI_STXn_RD(x, n) | (v))) #define HW_SSI_STXn_CLR(x, n, v) (HW_SSI_STXn_WR(x, n, HW_SSI_STXn_RD(x, n) & ~(v))) #define HW_SSI_STXn_TOG(x, n, v) (HW_SSI_STXn_WR(x, n, HW_SSI_STXn_RD(x, n) ^ (v))) #endif //@} /* * constants & macros for individual SSI_STXn bitfields */ /*! @name Register SSI_STXn, field STXN[31:0] (RW) * * SSI Transmit Data. These bits store the data to be transmitted by the These are implemented as * the first word of their respective Tx FIFOs. Data written to these registers is transferred to * the Transmit Shift Register (TXSR), when shifting of the previous data is complete. If both FIFOs * are in use, data is alternately transferred from STX0 and STX1, to TXSR. Multiple writes to the * STX registers will not result in the previous data being over-written by the subsequent data. * STX1 can only be used in Two-Channel mode of operation. Protection from over-writing is present * irrespective of whether the transmitter is enabled or not. Example 1: If Tx FIFO0 is in use and * user writes Data1... Data16 to STX0, Data16 will not over-write Data1. Data1... Data15 are stored * in the FIFO while Data16 is discarded. Example 2: If Tx FIFO0 is not in use and user writes * Data1, Data2 to STX0, then Data2 will not over-write Data1 and will be discarded. */ //@{ #define BP_SSI_STXn_STXN (0) //!< Bit position for SSI_STXn_STXN. #define BM_SSI_STXn_STXN (0xffffffff) //!< Bit mask for SSI_STXn_STXN. //! @brief Get value of SSI_STXn_STXN from a register value. #define BG_SSI_STXn_STXN(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STXn_STXN) >> BP_SSI_STXn_STXN) //! @brief Format value for bitfield SSI_STXn_STXN. #define BF_SSI_STXn_STXN(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STXn_STXN) & BM_SSI_STXn_STXN) #ifndef __LANGUAGE_ASM__ //! @brief Set the STXN field to a new value. #define BW_SSI_STXn_STXN(x, n, v) (HW_SSI_STXn_WR(x, n, (HW_SSI_STXn_RD(x, n) & ~BM_SSI_STXn_STXN) | BF_SSI_STXn_STXN(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_SRXn - SSI Receive Data Register n //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SRXn - SSI Receive Data Register n (RO) * * Reset value: 0x00000000 */ typedef union _hw_ssi_srxn { reg32_t U; struct _hw_ssi_srxn_bitfields { unsigned SRXN : 32; //!< [31:0] SSI Receive Data. } B; } hw_ssi_srxn_t; #endif /*! * @name Constants and macros for entire SSI_SRXn register */ //@{ //! @brief Number of instances of the SSI_SRXn register. #define HW_SSI_SRXn_COUNT (2) #define HW_SSI_SRXn_ADDR(n, x) (REGS_SSI_BASE(x) + 0x8 + (0x4 * (n))) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SRXn(x, n) (*(volatile hw_ssi_srxn_t *) HW_SSI_SRXn_ADDR(n, x)) #define HW_SSI_SRXn_RD(x, n) (HW_SSI_SRXn(x, n).U) #endif //@} /* * constants & macros for individual SSI_SRXn bitfields */ /*! @name Register SSI_SRXn, field SRXN[31:0] (RO) * * SSI Receive Data. These bits store the data received by the These are implemented as the first * word of their respective Rx FIFOs. These bits receive data from the RXSR depending on the mode of * operation. In case both FIFOs are in use, data is transferred to each data register alternately. * SRX1 can only be used in Two-Channel mode of operation. */ //@{ #define BP_SSI_SRXn_SRXN (0) //!< Bit position for SSI_SRXn_SRXN. #define BM_SSI_SRXn_SRXN (0xffffffff) //!< Bit mask for SSI_SRXn_SRXN. //! @brief Get value of SSI_SRXn_SRXN from a register value. #define BG_SSI_SRXn_SRXN(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRXn_SRXN) >> BP_SSI_SRXn_SRXN) //@} //------------------------------------------------------------------------------------------- // HW_SSI_SCR - SSI Control Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SCR - SSI Control Register (RW) * * Reset value: 0x00000000 * * The SSI Control Register (SSI_SCR) sets up the SSI reset is controlled by bit 0 in the SSI_SCR. * SSI operating modes are also selected in this register (except AC97 mode which is selected in the * SSI_SACNT register). */ typedef union _hw_ssi_scr { reg32_t U; struct _hw_ssi_scr_bitfields { unsigned SSIEN : 1; //!< [0] SSIEN - SSI Enable unsigned TE : 1; //!< [1] Transmit Enable. unsigned RE : 1; //!< [2] Receive Enable. unsigned NET : 1; //!< [3] Network Mode. unsigned SYN : 1; //!< [4] Synchronous Mode. unsigned I2S_MODE : 2; //!< [6:5] I2S Mode Select. unsigned SYS_CLK_EN : 1; //!< [7] Network Clock (Oversampling Clock) Enable. unsigned TCH_EN : 1; //!< [8] Two-Channel Operation Enable. unsigned CLK_IST : 1; //!< [9] Clock Idle State. unsigned TFR_CLK_DIS : 1; //!< [10] Transmit Frame Clock Disable. unsigned RFR_CLK_DIS : 1; //!< [11] Receive Frame Clock Disable. unsigned SYNC_TX_FS : 1; //!< [12] SYNC_FS_TX bit provides a safe window for TE to be visible to the internal circuit which is just after FS occurrence. unsigned RESERVED0 : 19; //!< [31:13] Reserved } B; } hw_ssi_scr_t; #endif /*! * @name Constants and macros for entire SSI_SCR register */ //@{ #define HW_SSI_SCR_ADDR(x) (REGS_SSI_BASE(x) + 0x10) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SCR(x) (*(volatile hw_ssi_scr_t *) HW_SSI_SCR_ADDR(x)) #define HW_SSI_SCR_RD(x) (HW_SSI_SCR(x).U) #define HW_SSI_SCR_WR(x, v) (HW_SSI_SCR(x).U = (v)) #define HW_SSI_SCR_SET(x, v) (HW_SSI_SCR_WR(x, HW_SSI_SCR_RD(x) | (v))) #define HW_SSI_SCR_CLR(x, v) (HW_SSI_SCR_WR(x, HW_SSI_SCR_RD(x) & ~(v))) #define HW_SSI_SCR_TOG(x, v) (HW_SSI_SCR_WR(x, HW_SSI_SCR_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_SCR bitfields */ /*! @name Register SSI_SCR, field SSIEN[0] (RW) * * SSIEN - SSI Enable This bit is used to enable/disable the SSI. When disabled, all SSI status bits * are preset to the same state produced by the power-on reset, all control bits are unaffected, the * contents of Tx and Rx FIFOs are cleared. When SSI is disabled, all internal clocks are disabled * (except register access clock). * * Values: * - DISABLED = 0 - SSI is disabled. * - ENABLED = 1 - SSI is enabled. */ //@{ #define BP_SSI_SCR_SSIEN (0) //!< Bit position for SSI_SCR_SSIEN. #define BM_SSI_SCR_SSIEN (0x00000001) //!< Bit mask for SSI_SCR_SSIEN. //! @brief Get value of SSI_SCR_SSIEN from a register value. #define BG_SSI_SCR_SSIEN(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_SSIEN) >> BP_SSI_SCR_SSIEN) //! @brief Format value for bitfield SSI_SCR_SSIEN. #define BF_SSI_SCR_SSIEN(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_SSIEN) & BM_SSI_SCR_SSIEN) #ifndef __LANGUAGE_ASM__ //! @brief Set the SSIEN field to a new value. #define BW_SSI_SCR_SSIEN(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_SSIEN) | BF_SSI_SCR_SSIEN(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SCR_SSIEN_V(v) BF_SSI_SCR_SSIEN(BV_SSI_SCR_SSIEN__##v) #define BV_SSI_SCR_SSIEN__DISABLED (0x0) //!< SSI is disabled. #define BV_SSI_SCR_SSIEN__ENABLED (0x1) //!< SSI is enabled. //@} /*! @name Register SSI_SCR, field TE[1] (RW) * * Transmit Enable. This control bit enables the transmit section of the SSI. It enables the * transfer of the contents of the STX registers to the TXSR and also enables the internal transmit * clock. The transmit section is enabled when this bit is set and a frame boundary is detected. * When this bit is cleared, the transmitter continues to send data until the end of the current * frame and then stops. Data can be written to the STX registers with the TE bit cleared (the * corresponding TDE bit will be cleared). If the TE bit is cleared and then set again before the * second to last bit of the last time slot in the current frame, data transmission continues * without interruption. The normal transmit enable sequence is to write data to the STX register(s) * and then set the TE bit. The normal disable sequence is to clear the TE and TIE bits after the * TDE bit is set. In gated clock mode, clearing the TE bit results in the clock stopping after the * data currently in TXSR has shifted out. When the TE bit is set, the clock starts immediately (for * internal gated clock mode). TE should not be toggled in the same frame. After enabling/disabling * transmission, SSI expects 4 setup clock cycles before arrival of frame-sync for frame-sync to be * accepted/rejected by In case of fewer clock cycles, there is high probability of the frame-sync * to get missed. Note: If continuos clock is not provided, SSI expects 6 clock cycles before * arrival of frame-sync for frame-sync to be accepted by * * Values: * - DISABLED = 0 - Transmit section disabled. * - ENABLED = 1 - Transmit section enabled. */ //@{ #define BP_SSI_SCR_TE (1) //!< Bit position for SSI_SCR_TE. #define BM_SSI_SCR_TE (0x00000002) //!< Bit mask for SSI_SCR_TE. //! @brief Get value of SSI_SCR_TE from a register value. #define BG_SSI_SCR_TE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_TE) >> BP_SSI_SCR_TE) //! @brief Format value for bitfield SSI_SCR_TE. #define BF_SSI_SCR_TE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_TE) & BM_SSI_SCR_TE) #ifndef __LANGUAGE_ASM__ //! @brief Set the TE field to a new value. #define BW_SSI_SCR_TE(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_TE) | BF_SSI_SCR_TE(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SCR_TE_V(v) BF_SSI_SCR_TE(BV_SSI_SCR_TE__##v) #define BV_SSI_SCR_TE__DISABLED (0x0) //!< Transmit section disabled. #define BV_SSI_SCR_TE__ENABLED (0x1) //!< Transmit section enabled. //@} /*! @name Register SSI_SCR, field RE[2] (RW) * * Receive Enable. This control bit enables the receive section of the SSI. When this bit is * enabled, data reception starts with the arrival of the next frame sync. If data is being received * when this bit is cleared, data reception continues until the end of the current frame and then * stops. If this bit is set again before the second to last bit of the last time slot in the * current frame, then reception continues without interruption. RE should not be toggled in the * same frame. * * Values: * - DISABLED = 0 - Receive section disabled. * - ENABLED = 1 - Receive section enabled. */ //@{ #define BP_SSI_SCR_RE (2) //!< Bit position for SSI_SCR_RE. #define BM_SSI_SCR_RE (0x00000004) //!< Bit mask for SSI_SCR_RE. //! @brief Get value of SSI_SCR_RE from a register value. #define BG_SSI_SCR_RE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_RE) >> BP_SSI_SCR_RE) //! @brief Format value for bitfield SSI_SCR_RE. #define BF_SSI_SCR_RE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_RE) & BM_SSI_SCR_RE) #ifndef __LANGUAGE_ASM__ //! @brief Set the RE field to a new value. #define BW_SSI_SCR_RE(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_RE) | BF_SSI_SCR_RE(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SCR_RE_V(v) BF_SSI_SCR_RE(BV_SSI_SCR_RE__##v) #define BV_SSI_SCR_RE__DISABLED (0x0) //!< Receive section disabled. #define BV_SSI_SCR_RE__ENABLED (0x1) //!< Receive section enabled. //@} /*! @name Register SSI_SCR, field NET[3] (RW) * * Network Mode. This bit controls whether SSI is in network mode or not. * * Values: * - DISABLED = 0 - Network mode not selected. * - ENABLED = 1 - Network mode selected. */ //@{ #define BP_SSI_SCR_NET (3) //!< Bit position for SSI_SCR_NET. #define BM_SSI_SCR_NET (0x00000008) //!< Bit mask for SSI_SCR_NET. //! @brief Get value of SSI_SCR_NET from a register value. #define BG_SSI_SCR_NET(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_NET) >> BP_SSI_SCR_NET) //! @brief Format value for bitfield SSI_SCR_NET. #define BF_SSI_SCR_NET(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_NET) & BM_SSI_SCR_NET) #ifndef __LANGUAGE_ASM__ //! @brief Set the NET field to a new value. #define BW_SSI_SCR_NET(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_NET) | BF_SSI_SCR_NET(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SCR_NET_V(v) BF_SSI_SCR_NET(BV_SSI_SCR_NET__##v) #define BV_SSI_SCR_NET__DISABLED (0x0) //!< Network mode not selected. #define BV_SSI_SCR_NET__ENABLED (0x1) //!< Network mode selected. //@} /*! @name Register SSI_SCR, field SYN[4] (RW) * * Synchronous Mode. This bit controls whether SSI is in synchronous mode or not. In synchronous * mode, the transmit and receive sections of SSI share a common clock port (STCK) and frame sync * port (STFS). * * Values: * - ASYNC_MODE = 0 - Asynchronous mode selected. * - SYNC_MODE = 1 - Synchronous mode selected. */ //@{ #define BP_SSI_SCR_SYN (4) //!< Bit position for SSI_SCR_SYN. #define BM_SSI_SCR_SYN (0x00000010) //!< Bit mask for SSI_SCR_SYN. //! @brief Get value of SSI_SCR_SYN from a register value. #define BG_SSI_SCR_SYN(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_SYN) >> BP_SSI_SCR_SYN) //! @brief Format value for bitfield SSI_SCR_SYN. #define BF_SSI_SCR_SYN(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_SYN) & BM_SSI_SCR_SYN) #ifndef __LANGUAGE_ASM__ //! @brief Set the SYN field to a new value. #define BW_SSI_SCR_SYN(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_SYN) | BF_SSI_SCR_SYN(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SCR_SYN_V(v) BF_SSI_SCR_SYN(BV_SSI_SCR_SYN__##v) #define BV_SSI_SCR_SYN__ASYNC_MODE (0x0) //!< Asynchronous mode selected. #define BV_SSI_SCR_SYN__SYNC_MODE (0x1) //!< Synchronous mode selected. //@} /*! @name Register SSI_SCR, field I2S_MODE[6:5] (RW) * * I2S Mode Select. These bits allow the SSI to operate in Normal, I2S Master or I2S Slave mode. * Refer to for a detailed description of I2S Mode of operation. Refer to for details regarding * settings. */ //@{ #define BP_SSI_SCR_I2S_MODE (5) //!< Bit position for SSI_SCR_I2S_MODE. #define BM_SSI_SCR_I2S_MODE (0x00000060) //!< Bit mask for SSI_SCR_I2S_MODE. //! @brief Get value of SSI_SCR_I2S_MODE from a register value. #define BG_SSI_SCR_I2S_MODE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_I2S_MODE) >> BP_SSI_SCR_I2S_MODE) //! @brief Format value for bitfield SSI_SCR_I2S_MODE. #define BF_SSI_SCR_I2S_MODE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_I2S_MODE) & BM_SSI_SCR_I2S_MODE) #ifndef __LANGUAGE_ASM__ //! @brief Set the I2S_MODE field to a new value. #define BW_SSI_SCR_I2S_MODE(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_I2S_MODE) | BF_SSI_SCR_I2S_MODE(v))) #endif //@} /*! @name Register SSI_SCR, field SYS_CLK_EN[7] (RW) * * Network Clock (Oversampling Clock) Enable. When set, this bit allows the SSI to output the * network clock at the SRCK port, provided that synchronous mode, and transmit internal clock mode * are set. The relationship between bit clock and network clock is determined by DIV2, PSR, and PM * bits. This feature is especially useful in I2S Master mode to output network clock (oversampling * clock) on SRCK port. * * Values: * - NOT_OUTPUT = 0 - network clock not output on SRCK port. * - OUTPUT = 1 - network clock output on SRCK port. */ //@{ #define BP_SSI_SCR_SYS_CLK_EN (7) //!< Bit position for SSI_SCR_SYS_CLK_EN. #define BM_SSI_SCR_SYS_CLK_EN (0x00000080) //!< Bit mask for SSI_SCR_SYS_CLK_EN. //! @brief Get value of SSI_SCR_SYS_CLK_EN from a register value. #define BG_SSI_SCR_SYS_CLK_EN(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_SYS_CLK_EN) >> BP_SSI_SCR_SYS_CLK_EN) //! @brief Format value for bitfield SSI_SCR_SYS_CLK_EN. #define BF_SSI_SCR_SYS_CLK_EN(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_SYS_CLK_EN) & BM_SSI_SCR_SYS_CLK_EN) #ifndef __LANGUAGE_ASM__ //! @brief Set the SYS_CLK_EN field to a new value. #define BW_SSI_SCR_SYS_CLK_EN(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_SYS_CLK_EN) | BF_SSI_SCR_SYS_CLK_EN(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SCR_SYS_CLK_EN_V(v) BF_SSI_SCR_SYS_CLK_EN(BV_SSI_SCR_SYS_CLK_EN__##v) #define BV_SSI_SCR_SYS_CLK_EN__NOT_OUTPUT (0x0) //!< network clock not output on SRCK port. #define BV_SSI_SCR_SYS_CLK_EN__OUTPUT (0x1) //!< network clock output on SRCK port. //@} /*! @name Register SSI_SCR, field TCH_EN[8] (RW) * * Two-Channel Operation Enable. This bit allows SSI to operate in the two-channel mode.In this mode * while receiving, the RXSR transfers data to SRX0 and SRX1 alternately and while transmitting, * data is alternately transferred from STX0 and STX1 to TXSR. For an even number of slots, Two- * Channel Operation can be enabled to optimize usage of both FIFOs or disabled as in the case of * odd number of active slots. This feature is especially useful in I2S mode, where data for Left * Speaker can be placed in Tx-FIFO0 and for Right speaker in Tx-FIFO1. * * Values: * - DISABLED = 0 - Two-channel mode disabled. * - ENABLED = 1 - Two-channel mode enabled. */ //@{ #define BP_SSI_SCR_TCH_EN (8) //!< Bit position for SSI_SCR_TCH_EN. #define BM_SSI_SCR_TCH_EN (0x00000100) //!< Bit mask for SSI_SCR_TCH_EN. //! @brief Get value of SSI_SCR_TCH_EN from a register value. #define BG_SSI_SCR_TCH_EN(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_TCH_EN) >> BP_SSI_SCR_TCH_EN) //! @brief Format value for bitfield SSI_SCR_TCH_EN. #define BF_SSI_SCR_TCH_EN(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_TCH_EN) & BM_SSI_SCR_TCH_EN) #ifndef __LANGUAGE_ASM__ //! @brief Set the TCH_EN field to a new value. #define BW_SSI_SCR_TCH_EN(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_TCH_EN) | BF_SSI_SCR_TCH_EN(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SCR_TCH_EN_V(v) BF_SSI_SCR_TCH_EN(BV_SSI_SCR_TCH_EN__##v) #define BV_SSI_SCR_TCH_EN__DISABLED (0x0) //!< Two-channel mode disabled. #define BV_SSI_SCR_TCH_EN__ENABLED (0x1) //!< Two-channel mode enabled. //@} /*! @name Register SSI_SCR, field CLK_IST[9] (RW) * * Clock Idle State. This bit controls the idle state of the transmit clock port during SSI internal * gated mode. Note: When Clock idle state is '1' the clock polarity should always be negedge * triggered and when Clock idle = '0' the clock polarity should always be positive edge triggered. * * Values: * - IDLE_0 = 0 - Clock idle state is '0'. * - IDLE_1 = 1 - Clock idle state is '1'. */ //@{ #define BP_SSI_SCR_CLK_IST (9) //!< Bit position for SSI_SCR_CLK_IST. #define BM_SSI_SCR_CLK_IST (0x00000200) //!< Bit mask for SSI_SCR_CLK_IST. //! @brief Get value of SSI_SCR_CLK_IST from a register value. #define BG_SSI_SCR_CLK_IST(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_CLK_IST) >> BP_SSI_SCR_CLK_IST) //! @brief Format value for bitfield SSI_SCR_CLK_IST. #define BF_SSI_SCR_CLK_IST(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_CLK_IST) & BM_SSI_SCR_CLK_IST) #ifndef __LANGUAGE_ASM__ //! @brief Set the CLK_IST field to a new value. #define BW_SSI_SCR_CLK_IST(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_CLK_IST) | BF_SSI_SCR_CLK_IST(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SCR_CLK_IST_V(v) BF_SSI_SCR_CLK_IST(BV_SSI_SCR_CLK_IST__##v) #define BV_SSI_SCR_CLK_IST__IDLE_0 (0x0) //!< Clock idle state is '0'. #define BV_SSI_SCR_CLK_IST__IDLE_1 (0x1) //!< Clock idle state is '1'. //@} /*! @name Register SSI_SCR, field TFR_CLK_DIS[10] (RW) * * Transmit Frame Clock Disable. This bit provide option to keep the Frame-sync and Clock enabled or * disabled after current transmit frame, in which transmitter is disabled by clearing TE bit. * Writing to this bit has effect only when SSI is enabled TE is disabled. * * Values: * - CONTINUE = 0 - Continue Frame-sync/Clock generation after current frame during which TE is cleared. This may be * required when Frame-sync and Clocks are required from SSI, even when no data is to be * received. * - STOP = 1 - Stop Frame-sync/Clock generation at next frame boundary. This will be effective also in case where * transmitter is already disabled in current or previous frames. */ //@{ #define BP_SSI_SCR_TFR_CLK_DIS (10) //!< Bit position for SSI_SCR_TFR_CLK_DIS. #define BM_SSI_SCR_TFR_CLK_DIS (0x00000400) //!< Bit mask for SSI_SCR_TFR_CLK_DIS. //! @brief Get value of SSI_SCR_TFR_CLK_DIS from a register value. #define BG_SSI_SCR_TFR_CLK_DIS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_TFR_CLK_DIS) >> BP_SSI_SCR_TFR_CLK_DIS) //! @brief Format value for bitfield SSI_SCR_TFR_CLK_DIS. #define BF_SSI_SCR_TFR_CLK_DIS(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_TFR_CLK_DIS) & BM_SSI_SCR_TFR_CLK_DIS) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFR_CLK_DIS field to a new value. #define BW_SSI_SCR_TFR_CLK_DIS(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_TFR_CLK_DIS) | BF_SSI_SCR_TFR_CLK_DIS(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SCR_TFR_CLK_DIS_V(v) BF_SSI_SCR_TFR_CLK_DIS(BV_SSI_SCR_TFR_CLK_DIS__##v) #define BV_SSI_SCR_TFR_CLK_DIS__CONTINUE (0x0) //!< Continue Frame-sync/Clock generation after current frame during which TE is cleared. This may be required when Frame-sync and Clocks are required from SSI, even when no data is to be received. #define BV_SSI_SCR_TFR_CLK_DIS__STOP (0x1) //!< Stop Frame-sync/Clock generation at next frame boundary. This will be effective also in case where transmitter is already disabled in current or previous frames. //@} /*! @name Register SSI_SCR, field RFR_CLK_DIS[11] (RW) * * Receive Frame Clock Disable. This bit provides the option to keep the Frame-sync and Clock * enabled or to disable them after the receive frame in which the receiver is disabled. Writing to * this bit has effect only when RE is disabled.The receiver is disabled by clearing the RE bit. * * Values: * - CONTINUE = 0 - Continue Frame-sync/Clock generation after current frame during which RE is cleared. This may be * required when Frame-sync and Clocks are required from SSI, even when no data is to be * received. * - STOP = 1 - Stop Frame-sync/Clock generation at next frame boundary. This will be effective also in case where * receiver is already disabled in current or previous frames. */ //@{ #define BP_SSI_SCR_RFR_CLK_DIS (11) //!< Bit position for SSI_SCR_RFR_CLK_DIS. #define BM_SSI_SCR_RFR_CLK_DIS (0x00000800) //!< Bit mask for SSI_SCR_RFR_CLK_DIS. //! @brief Get value of SSI_SCR_RFR_CLK_DIS from a register value. #define BG_SSI_SCR_RFR_CLK_DIS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_RFR_CLK_DIS) >> BP_SSI_SCR_RFR_CLK_DIS) //! @brief Format value for bitfield SSI_SCR_RFR_CLK_DIS. #define BF_SSI_SCR_RFR_CLK_DIS(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_RFR_CLK_DIS) & BM_SSI_SCR_RFR_CLK_DIS) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFR_CLK_DIS field to a new value. #define BW_SSI_SCR_RFR_CLK_DIS(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_RFR_CLK_DIS) | BF_SSI_SCR_RFR_CLK_DIS(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SCR_RFR_CLK_DIS_V(v) BF_SSI_SCR_RFR_CLK_DIS(BV_SSI_SCR_RFR_CLK_DIS__##v) #define BV_SSI_SCR_RFR_CLK_DIS__CONTINUE (0x0) //!< Continue Frame-sync/Clock generation after current frame during which RE is cleared. This may be required when Frame-sync and Clocks are required from SSI, even when no data is to be received. #define BV_SSI_SCR_RFR_CLK_DIS__STOP (0x1) //!< Stop Frame-sync/Clock generation at next frame boundary. This will be effective also in case where receiver is already disabled in current or previous frames. //@} /*! @name Register SSI_SCR, field SYNC_TX_FS[12] (RW) * * SYNC_FS_TX bit provides a safe window for TE to be visible to the internal circuit which is just * after FS occurrence. When SYNC_TX_FS is set, TE(SCR[1]) gets latched on FS occurrence & latched * TE is used to enable/disable SSI transmitter. TE needs setup of 2 bit-clock cycles before * occurrence of FS. If TE is changed within 2 bit-clock cycles of FS occurrence, there is high * probability that TE will be latched on next FS. Note: With TFR_CLK_DIS feature on, TE is used * directly to enable transmitter in following cases (i) Sync mode & Rx disabled (ii) Async Mode. * Latched-TE is used to disable the transmitter. This bit has no relevance in gated mode and AC97 * mode. * * Values: * - TE_NOT_LATCHED = 0 - TE not latched with FS occurrence & used directly for transmitter enable/disable. * - TE_LATCHED = 1 - TE latched with FS occurrence & latched-TE used for transmitter enable/disable. */ //@{ #define BP_SSI_SCR_SYNC_TX_FS (12) //!< Bit position for SSI_SCR_SYNC_TX_FS. #define BM_SSI_SCR_SYNC_TX_FS (0x00001000) //!< Bit mask for SSI_SCR_SYNC_TX_FS. //! @brief Get value of SSI_SCR_SYNC_TX_FS from a register value. #define BG_SSI_SCR_SYNC_TX_FS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SCR_SYNC_TX_FS) >> BP_SSI_SCR_SYNC_TX_FS) //! @brief Format value for bitfield SSI_SCR_SYNC_TX_FS. #define BF_SSI_SCR_SYNC_TX_FS(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SCR_SYNC_TX_FS) & BM_SSI_SCR_SYNC_TX_FS) #ifndef __LANGUAGE_ASM__ //! @brief Set the SYNC_TX_FS field to a new value. #define BW_SSI_SCR_SYNC_TX_FS(x, v) (HW_SSI_SCR_WR(x, (HW_SSI_SCR_RD(x) & ~BM_SSI_SCR_SYNC_TX_FS) | BF_SSI_SCR_SYNC_TX_FS(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SCR_SYNC_TX_FS_V(v) BF_SSI_SCR_SYNC_TX_FS(BV_SSI_SCR_SYNC_TX_FS__##v) #define BV_SSI_SCR_SYNC_TX_FS__TE_NOT_LATCHED (0x0) //!< TE not latched with FS occurrence & used directly for transmitter enable/disable. #define BV_SSI_SCR_SYNC_TX_FS__TE_LATCHED (0x1) //!< TE latched with FS occurrence & latched-TE used for transmitter enable/disable. //@} //------------------------------------------------------------------------------------------- // HW_SSI_SISR - SSI Interrupt Status Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SISR - SSI Interrupt Status Register (W1C) * * Reset value: 0x00003003 * * The SSI Interrupt Status Register (SSI_SISR) is used to monitor the SSI. This register is used by * the core to interrogate the status of the In gated mode of operation the TFS, RFS, TLS, RLS, TFRC * and RFRC bits of AISR register are not generated. The status bits are described in the following * table. SSI Status flags are valid when SSI is enabled. See and for interrupt source mapping. All * the flags in the SSI_SISR are updated after the first bit of the next SSI word has completed * transmission or reception. Certain status bits (ROE0/1 and TUE0/1) are cleared by writing 1 to * the corresponding interrupt status bit in SSI_SISR. */ typedef union _hw_ssi_sisr { reg32_t U; struct _hw_ssi_sisr_bitfields { unsigned TFE0 : 1; //!< [0] Transmit FIFO Empty 0. unsigned TFE1 : 1; //!< [1] Transmit FIFO Empty 1. unsigned RFF0 : 1; //!< [2] Receive FIFO Full 0. unsigned RFF1 : 1; //!< [3] Receive FIFO Full 1. unsigned RLS : 1; //!< [4] Receive Last Time Slot. unsigned TLS : 1; //!< [5] Transmit Last Time Slot. unsigned RFS : 1; //!< [6] Receive Frame Sync. unsigned TFS : 1; //!< [7] Transmit Frame Sync. unsigned TUE0 : 1; //!< [8] Transmitter Underrun Error 0. unsigned TUE1 : 1; //!< [9] Transmitter Underrun Error 1. unsigned ROE0 : 1; //!< [10] Receiver Overrun Error 0. unsigned ROE1 : 1; //!< [11] Receiver Overrun Error 1. unsigned TDE0 : 1; //!< [12] Transmit Data Register Empty 0. unsigned TDE1 : 1; //!< [13] Transmit Data Register Empty 1. unsigned RDR0 : 1; //!< [14] Receive Data Ready 0. unsigned RDR1 : 1; //!< [15] Receive Data Ready 1. unsigned RXT : 1; //!< [16] Receive Tag Updated. unsigned CMDDU : 1; //!< [17] Command Data Register Updated. unsigned CMDAU : 1; //!< [18] Command Address Register Updated. unsigned RESERVED0 : 4; //!< [22:19] Reserved unsigned TFRC : 1; //!< [23] Transmit Frame Complete. unsigned RFRC : 1; //!< [24] Receive Frame Complete. unsigned RESERVED1 : 7; //!< [31:25] Reserved } B; } hw_ssi_sisr_t; #endif /*! * @name Constants and macros for entire SSI_SISR register */ //@{ #define HW_SSI_SISR_ADDR(x) (REGS_SSI_BASE(x) + 0x14) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SISR(x) (*(volatile hw_ssi_sisr_t *) HW_SSI_SISR_ADDR(x)) #define HW_SSI_SISR_RD(x) (HW_SSI_SISR(x).U) #define HW_SSI_SISR_WR(x, v) (HW_SSI_SISR(x).U = (v)) #define HW_SSI_SISR_SET(x, v) (HW_SSI_SISR_WR(x, HW_SSI_SISR_RD(x) | (v))) #define HW_SSI_SISR_CLR(x, v) (HW_SSI_SISR_WR(x, HW_SSI_SISR_RD(x) & ~(v))) #define HW_SSI_SISR_TOG(x, v) (HW_SSI_SISR_WR(x, HW_SSI_SISR_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_SISR bitfields */ /*! @name Register SSI_SISR, field TFE0[0] (RO) * * Transmit FIFO Empty 0. This flag is set when the empty slots in Tx FIFO exceed or are equal to * the selected Tx FIFO WaterMark 0 (TFWM0) threshold. The setting of TFE0 only causes an interrupt * when TIE and TFE0_EN are set and Tx FIFO0 is enabled. The TFE0 bit is automatically cleared when * the data level in Tx FIFO0 becomes more than the amount specified by the watermark bits. The TFE0 * bit is set by POR and SSI reset. * * Values: * - HAS_DATA = 0 - Transmit FIFO0 has data for transmission. * - EMPTY = 1 - Transmit FIFO0 is empty. */ //@{ #define BP_SSI_SISR_TFE0 (0) //!< Bit position for SSI_SISR_TFE0. #define BM_SSI_SISR_TFE0 (0x00000001) //!< Bit mask for SSI_SISR_TFE0. //! @brief Get value of SSI_SISR_TFE0 from a register value. #define BG_SSI_SISR_TFE0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_TFE0) >> BP_SSI_SISR_TFE0) //! @brief Macro to simplify usage of value macros. #define BF_SSI_SISR_TFE0_V(v) BF_SSI_SISR_TFE0(BV_SSI_SISR_TFE0__##v) #define BV_SSI_SISR_TFE0__HAS_DATA (0x0) //!< Transmit FIFO0 has data for transmission. #define BV_SSI_SISR_TFE0__EMPTY (0x1) //!< Transmit FIFO0 is empty. //@} /*! @name Register SSI_SISR, field TFE1[1] (RO) * * Transmit FIFO Empty 1. This flag is set when the empty slots in Tx FIFO exceed or are equal to * the selected Tx FIFO WaterMark 1 (TFWM1) threshold and the Two-Channel mode is selected. The * setting of TFE1 only causes an interrupt when TIE and TFE1_EN are set, Tx FIFO1 is enabled and * Two-Channel mode is selected. The TFE1 bit is automatically cleared when the data level in Tx * FIFO1 becomes more than the amount specified by the watermark bits. The TFE1 bit is set by POR * and SSI reset. * * Values: * - HAS_DATA = 0 - Transmit FIFO1 has data for transmission. * - EMPTY = 1 - Transmit FIFO1 is empty. */ //@{ #define BP_SSI_SISR_TFE1 (1) //!< Bit position for SSI_SISR_TFE1. #define BM_SSI_SISR_TFE1 (0x00000002) //!< Bit mask for SSI_SISR_TFE1. //! @brief Get value of SSI_SISR_TFE1 from a register value. #define BG_SSI_SISR_TFE1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_TFE1) >> BP_SSI_SISR_TFE1) //! @brief Macro to simplify usage of value macros. #define BF_SSI_SISR_TFE1_V(v) BF_SSI_SISR_TFE1(BV_SSI_SISR_TFE1__##v) #define BV_SSI_SISR_TFE1__HAS_DATA (0x0) //!< Transmit FIFO1 has data for transmission. #define BV_SSI_SISR_TFE1__EMPTY (0x1) //!< Transmit FIFO1 is empty. //@} /*! @name Register SSI_SISR, field RFF0[2] (RO) * * Receive FIFO Full 0. This flag is set when Rx FIFO0 is enabled and the data level in Rx FIFO0 * reaches the selected Rx FIFO WaterMark 0 (RFWM0) threshold. The setting of RFF0 only causes an * interrupt when RIE and RFF0_EN are set and Rx FIFO0 is enabled. RFF0 is automatically cleared * when the amount of data in Rx FIFO0 falls below the threshold. The RFF0 bit is cleared by POR and * SSI reset. When Rx FIFO0 contains 15 words, the maximum it can hold, all further data received * (for storage in this FIFO) is ignored until the FIFO contents are read. * * Values: * - NOT_FULL = 0 - Space available in Receive FIFO0. * - FULL = 1 - Receive FIFO0 is full. */ //@{ #define BP_SSI_SISR_RFF0 (2) //!< Bit position for SSI_SISR_RFF0. #define BM_SSI_SISR_RFF0 (0x00000004) //!< Bit mask for SSI_SISR_RFF0. //! @brief Get value of SSI_SISR_RFF0 from a register value. #define BG_SSI_SISR_RFF0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_RFF0) >> BP_SSI_SISR_RFF0) //! @brief Macro to simplify usage of value macros. #define BF_SSI_SISR_RFF0_V(v) BF_SSI_SISR_RFF0(BV_SSI_SISR_RFF0__##v) #define BV_SSI_SISR_RFF0__NOT_FULL (0x0) //!< Space available in Receive FIFO0. #define BV_SSI_SISR_RFF0__FULL (0x1) //!< Receive FIFO0 is full. //@} /*! @name Register SSI_SISR, field RFF1[3] (RO) * * Receive FIFO Full 1. This flag is set when Rx FIFO1 is enabled, the data level in Rx FIFO1 * reaches the selected Rx FIFO WaterMark 1 (RFWM1) threshold and the SSI is in Two-Channel mode. * The setting of RFF1 only causes an interrupt when RIE and RFF1_EN are set, Rx FIFO1 is enabled * and the Two-Channel mode is selected. RFF1 is automatically cleared when the amount of data in Rx * FIFO1 falls below the threshold. The RFF1 bit is cleared by POR and SSI reset. When Rx FIFO1 * contains 15 words, the maximum it can hold, all further data received (for storage in this FIFO) * is ignored until the FIFO contents are read. * * Values: * - NOT_FULL = 0 - Space available in Receive FIFO1. * - FULL = 1 - Receive FIFO1 is full. */ //@{ #define BP_SSI_SISR_RFF1 (3) //!< Bit position for SSI_SISR_RFF1. #define BM_SSI_SISR_RFF1 (0x00000008) //!< Bit mask for SSI_SISR_RFF1. //! @brief Get value of SSI_SISR_RFF1 from a register value. #define BG_SSI_SISR_RFF1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_RFF1) >> BP_SSI_SISR_RFF1) //! @brief Macro to simplify usage of value macros. #define BF_SSI_SISR_RFF1_V(v) BF_SSI_SISR_RFF1(BV_SSI_SISR_RFF1__##v) #define BV_SSI_SISR_RFF1__NOT_FULL (0x0) //!< Space available in Receive FIFO1. #define BV_SSI_SISR_RFF1__FULL (0x1) //!< Receive FIFO1 is full. //@} /*! @name Register SSI_SISR, field RLS[4] (RO) * * Receive Last Time Slot. This flag indicates the last time slot in a frame. When set, it indicates * that the current time slot is the last receive time slot of the frame. RLS is set at the end of * the last time slot and causes the SSI to issue an interrupt (if RIE and RLS_EN are set). RLS is * cleared when the SISR is read with this bit set. The RLS bit is cleared by POR and SSI reset. * * Values: * - 0 - Current time slot is not last time slot of frame. * - 1 - Current time slot is the last receive time slot of frame. */ //@{ #define BP_SSI_SISR_RLS (4) //!< Bit position for SSI_SISR_RLS. #define BM_SSI_SISR_RLS (0x00000010) //!< Bit mask for SSI_SISR_RLS. //! @brief Get value of SSI_SISR_RLS from a register value. #define BG_SSI_SISR_RLS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_RLS) >> BP_SSI_SISR_RLS) //@} /*! @name Register SSI_SISR, field TLS[5] (RO) * * Transmit Last Time Slot. This flag indicates the last time slot in a frame. When set, it * indicates that the current time slot is the last time slot of the frame. TLS is set at the start * of the last transmit time slot and causes the SSI to issue an interrupt (if TIE and TLS_EN are * set). TLS is not generated when frame rate is 1 in normal mode of operation. TLS is cleared when * the SISR is read with this bit set. The TLS bit is cleared by POR and SSI reset. * * Values: * - 0 - Current time slot is not last time slot of frame. * - 1 - Current time slot is the last transmit time slot of frame. */ //@{ #define BP_SSI_SISR_TLS (5) //!< Bit position for SSI_SISR_TLS. #define BM_SSI_SISR_TLS (0x00000020) //!< Bit mask for SSI_SISR_TLS. //! @brief Get value of SSI_SISR_TLS from a register value. #define BG_SSI_SISR_TLS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_TLS) >> BP_SSI_SISR_TLS) //@} /*! @name Register SSI_SISR, field RFS[6] (RO) * * Receive Frame Sync. This flag indicates the occurrence of receive frame sync. In Network mode, * the RFS bit is set when the first slot of the frame is being received. It is cleared when the * next slot begins to be received. In Normal mode, this bit is always high (When DC = 0). This flag * causes an interrupt if RIE and RFS_EN are set. The RFS bit is cleared by POR and SSI reset. * * Values: * - 0 - No Occurrence of Receive frame sync. * - 1 - Receive frame sync occurred during reception of next word in SRX registers. */ //@{ #define BP_SSI_SISR_RFS (6) //!< Bit position for SSI_SISR_RFS. #define BM_SSI_SISR_RFS (0x00000040) //!< Bit mask for SSI_SISR_RFS. //! @brief Get value of SSI_SISR_RFS from a register value. #define BG_SSI_SISR_RFS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_RFS) >> BP_SSI_SISR_RFS) //@} /*! @name Register SSI_SISR, field TFS[7] (RO) * * Transmit Frame Sync. This flag indicates the occurrence of transmit frame sync. Data written to * the STX registers during the time slot when the TFS flag is set, is sent during the second time * slot (in Network mode) or in the next first time slot (in Normal mode). In Network mode, the TFS * bit is set during transmission of the first time slot of the frame and is then cleared when * starting transmission of the next time slot. In Normal mode, this bit is high for the first time * slot. This flag causes an interrupt if TIE and TFS_EN are set. The TFS bit is cleared by POR and * SSI reset. * * Values: * - 0 - No Occurrence of Transmit frame sync. * - 1 - Transmit frame sync occurred during transmission of last word written to STX registers. */ //@{ #define BP_SSI_SISR_TFS (7) //!< Bit position for SSI_SISR_TFS. #define BM_SSI_SISR_TFS (0x00000080) //!< Bit mask for SSI_SISR_TFS. //! @brief Get value of SSI_SISR_TFS from a register value. #define BG_SSI_SISR_TFS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_TFS) >> BP_SSI_SISR_TFS) //@} /*! @name Register SSI_SISR, field TUE0[8] (W1C) * * Transmitter Underrun Error 0. This flag is set when the TXSR is empty (no data to be * transmitted), the TDE0 flag is set and a transmit time slot occurs. When a transmit underrun * error occurs, the previous data is retransmitted. In Network mode, each time slot requires data * transmission (unless masked through STMSK register), when the transmitter is enabled (TE is set). * The TUE0 flag causes an interrupt if TIE and TUE0_EN are set. The TUE0 bit is cleared by POR and * SSI reset. It is also cleared by writing '1' to this bit. * * Values: * - 0 - Default interrupt issued to the Core. * - 1 - Exception interrupt issued to the Core. */ //@{ #define BP_SSI_SISR_TUE0 (8) //!< Bit position for SSI_SISR_TUE0. #define BM_SSI_SISR_TUE0 (0x00000100) //!< Bit mask for SSI_SISR_TUE0. //! @brief Get value of SSI_SISR_TUE0 from a register value. #define BG_SSI_SISR_TUE0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_TUE0) >> BP_SSI_SISR_TUE0) //! @brief Format value for bitfield SSI_SISR_TUE0. #define BF_SSI_SISR_TUE0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SISR_TUE0) & BM_SSI_SISR_TUE0) #ifndef __LANGUAGE_ASM__ //! @brief Set the TUE0 field to a new value. #define BW_SSI_SISR_TUE0(x, v) (HW_SSI_SISR_WR(x, (HW_SSI_SISR_RD(x) & ~BM_SSI_SISR_TUE0) | BF_SSI_SISR_TUE0(v))) #endif //@} /*! @name Register SSI_SISR, field TUE1[9] (W1C) * * Transmitter Underrun Error 1. This flag is set when the TXSR is empty (no data to be * transmitted), the TDE1 flag is set, a transmit time slot occurs and the SSI is in Two-Channel * mode. When a transmit underrun error occurs, the previous data is retransmitted. In Network mode, * each time slot requires data transmission (unless masked through STMSK register), when the * transmitter is enabled (TE is set). The TUE1 flag causes an interrupt if TIE and TUE1_EN are set. * The TUE1 bit is cleared by POR and SSI reset. It is also cleared by writing '1' to this bit. * * Values: * - 0 - Default interrupt issued to the Core. * - 1 - Exception interrupt issued to the Core. */ //@{ #define BP_SSI_SISR_TUE1 (9) //!< Bit position for SSI_SISR_TUE1. #define BM_SSI_SISR_TUE1 (0x00000200) //!< Bit mask for SSI_SISR_TUE1. //! @brief Get value of SSI_SISR_TUE1 from a register value. #define BG_SSI_SISR_TUE1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_TUE1) >> BP_SSI_SISR_TUE1) //! @brief Format value for bitfield SSI_SISR_TUE1. #define BF_SSI_SISR_TUE1(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SISR_TUE1) & BM_SSI_SISR_TUE1) #ifndef __LANGUAGE_ASM__ //! @brief Set the TUE1 field to a new value. #define BW_SSI_SISR_TUE1(x, v) (HW_SSI_SISR_WR(x, (HW_SSI_SISR_RD(x) & ~BM_SSI_SISR_TUE1) | BF_SSI_SISR_TUE1(v))) #endif //@} /*! @name Register SSI_SISR, field ROE0[10] (W1C) * * Receiver Overrun Error 0. This flag is set when the RXSR is filled and ready to transfer to SRX0 * register or to Rx FIFO 0 (when enabled) and these are already full. If Rx FIFO 0 is enabled, this * is indicated by RFF0 flag, else this is indicated by the RDR0 flag. The RXSR is not transferred * in this case. The ROE0 flag causes an interrupt if RIE and ROE0_EN are set. The ROE0 bit is * cleared by POR and SSI reset. It is also cleared by writing '1' to this bit. Clearing the RE bit * does not affect the ROE0 bit. * * Values: * - 0 - Default interrupt issued to the Core. * - 1 - Exception interrupt issued to the Core. */ //@{ #define BP_SSI_SISR_ROE0 (10) //!< Bit position for SSI_SISR_ROE0. #define BM_SSI_SISR_ROE0 (0x00000400) //!< Bit mask for SSI_SISR_ROE0. //! @brief Get value of SSI_SISR_ROE0 from a register value. #define BG_SSI_SISR_ROE0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_ROE0) >> BP_SSI_SISR_ROE0) //! @brief Format value for bitfield SSI_SISR_ROE0. #define BF_SSI_SISR_ROE0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SISR_ROE0) & BM_SSI_SISR_ROE0) #ifndef __LANGUAGE_ASM__ //! @brief Set the ROE0 field to a new value. #define BW_SSI_SISR_ROE0(x, v) (HW_SSI_SISR_WR(x, (HW_SSI_SISR_RD(x) & ~BM_SSI_SISR_ROE0) | BF_SSI_SISR_ROE0(v))) #endif //@} /*! @name Register SSI_SISR, field ROE1[11] (W1C) * * Receiver Overrun Error 1. This flag is set when the RXSR is filled and ready to transfer to SRX1 * register or to Rx FIFO 1 (when enabled) and these are already full and Two-Channel mode is * selected. If Rx FIFO 1 is enabled, this is indicated by RFF1 flag, else this is indicated by the * RDR1 flag. The RXSR is not transferred in this case. The ROE1 flag causes an interrupt if RIE and * ROE1_EN are set. The ROE1 bit is cleared by POR and SSI reset. It is also cleared by writing '1' * to this bit. Clearing the RE bit does not affect the ROE1 bit. * * Values: * - 0 - Default interrupt issued to the Core. * - 1 - Exception interrupt issued to the Core. */ //@{ #define BP_SSI_SISR_ROE1 (11) //!< Bit position for SSI_SISR_ROE1. #define BM_SSI_SISR_ROE1 (0x00000800) //!< Bit mask for SSI_SISR_ROE1. //! @brief Get value of SSI_SISR_ROE1 from a register value. #define BG_SSI_SISR_ROE1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_ROE1) >> BP_SSI_SISR_ROE1) //! @brief Format value for bitfield SSI_SISR_ROE1. #define BF_SSI_SISR_ROE1(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SISR_ROE1) & BM_SSI_SISR_ROE1) #ifndef __LANGUAGE_ASM__ //! @brief Set the ROE1 field to a new value. #define BW_SSI_SISR_ROE1(x, v) (HW_SSI_SISR_WR(x, (HW_SSI_SISR_RD(x) & ~BM_SSI_SISR_ROE1) | BF_SSI_SISR_ROE1(v))) #endif //@} /*! @name Register SSI_SISR, field TDE0[12] (RO) * * Transmit Data Register Empty 0. This flag is set whenever data is transferred to TXSR from STX0 * register. If Tx FIFO 0 is enabled, this occurs when there is at least one empty slot in STX0 or * Tx FIFO 0. If Tx FIFO 0 is not enabled, this occurs when the contents of STX0 are transferred to * TXSR. The TDE0 bit is cleared when the Core writes to STX0. If TIE and TDE0_EN are set, an SSI * Transmit Data 0 interrupt request is issued on setting of TDE0 bit. The TDE0 bit is cleared by * POR and SSI reset. * * Values: * - 0 - Data available for transmission. * - 1 - Data needs to be written by the Core for transmission. */ //@{ #define BP_SSI_SISR_TDE0 (12) //!< Bit position for SSI_SISR_TDE0. #define BM_SSI_SISR_TDE0 (0x00001000) //!< Bit mask for SSI_SISR_TDE0. //! @brief Get value of SSI_SISR_TDE0 from a register value. #define BG_SSI_SISR_TDE0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_TDE0) >> BP_SSI_SISR_TDE0) //@} /*! @name Register SSI_SISR, field TDE1[13] (RO) * * Transmit Data Register Empty 1. This flag is set whenever data is transferred to TXSR from STX1 * register and Two-Channel mode is selected. If Tx FIFO1 is enabled, this occurs when there is at * least one empty slot in STX1 or Tx FIFO1. If Tx FIFO1 is not enabled, this occurs when the * contents of STX1 are transferred to TXSR. The TDE1 bit is cleared when the Core writes to STX1. * If TIE and TDE1_EN are set, an SSI Transmit Data 1 interrupt request is issued on setting of TDE1 * bit. The TDE1 bit is cleared by POR and SSI reset. * * Values: * - 0 - Data available for transmission. * - 1 - Data needs to be written by the Core for transmission. */ //@{ #define BP_SSI_SISR_TDE1 (13) //!< Bit position for SSI_SISR_TDE1. #define BM_SSI_SISR_TDE1 (0x00002000) //!< Bit mask for SSI_SISR_TDE1. //! @brief Get value of SSI_SISR_TDE1 from a register value. #define BG_SSI_SISR_TDE1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_TDE1) >> BP_SSI_SISR_TDE1) //@} /*! @name Register SSI_SISR, field RDR0[14] (RO) * * Receive Data Ready 0. This flag bit is set when SRX0 or Rx FIFO 0 is loaded with a new value. * RDR0 is cleared when the Core reads the SRX0 register. If Rx FIFO 0 is enabled, RDR0 is cleared * when the FIFO is empty. If RIE and RDR0_EN are set, a Receive Data 0 interrupt request is issued * on setting of RDR0 bit in case Rx FIFO0 is disabled, if the FIFO is enabled, the interrupt is * issued on RFF0 assertion. The RDR0 bit is cleared by POR and SSI reset. * * Values: * - 0 - No new data for Core to read. * - 1 - New data for Core to read. */ //@{ #define BP_SSI_SISR_RDR0 (14) //!< Bit position for SSI_SISR_RDR0. #define BM_SSI_SISR_RDR0 (0x00004000) //!< Bit mask for SSI_SISR_RDR0. //! @brief Get value of SSI_SISR_RDR0 from a register value. #define BG_SSI_SISR_RDR0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_RDR0) >> BP_SSI_SISR_RDR0) //@} /*! @name Register SSI_SISR, field RDR1[15] (RO) * * Receive Data Ready 1. This flag bit is set when SRX1 or Rx FIFO 1 is loaded with a new value and * Two-Channel mode is selected. RDR1 is cleared when the Core reads the SRX1 register. If Rx FIFO 1 * is enabled, RDR1 is cleared when the FIFO is empty. If RIE and RDR1_EN are set, a Receive Data 1 * interrupt request is issued on setting of RDR1 bit in case Rx FIFO1 is disabled, if the FIFO is * enabled, the interrupt is issued on RFF1 assertion. The RDR1 bit is cleared by POR and SSI reset. * * Values: * - 0 - No new data for Core to read. * - 1 - New data for Core to read. */ //@{ #define BP_SSI_SISR_RDR1 (15) //!< Bit position for SSI_SISR_RDR1. #define BM_SSI_SISR_RDR1 (0x00008000) //!< Bit mask for SSI_SISR_RDR1. //! @brief Get value of SSI_SISR_RDR1 from a register value. #define BG_SSI_SISR_RDR1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_RDR1) >> BP_SSI_SISR_RDR1) //@} /*! @name Register SSI_SISR, field RXT[16] (RO) * * Receive Tag Updated. This status bit is set each time there is a difference in the previous and * current value of the received tag. It causes the Receive Tag Interrupt (if RXT_EN bit is set). * This bit is cleared on reading the SATAG register. * * Values: * - 0 - No change in SATAG register. * - 1 - SATAG register updated with different value. */ //@{ #define BP_SSI_SISR_RXT (16) //!< Bit position for SSI_SISR_RXT. #define BM_SSI_SISR_RXT (0x00010000) //!< Bit mask for SSI_SISR_RXT. //! @brief Get value of SSI_SISR_RXT from a register value. #define BG_SSI_SISR_RXT(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_RXT) >> BP_SSI_SISR_RXT) //@} /*! @name Register SSI_SISR, field CMDDU[17] (RO) * * Command Data Register Updated. This bit causes the Command Data Updated interrupt (when CMDDU_EN * bit is set). This status bit is set each time there is a difference in the previous and current * value of the received Command Data. This bit is cleared on reading the SACDAT register. * * Values: * - 0 - No change in SACDAT register. * - 1 - SACDAT register updated with different value. */ //@{ #define BP_SSI_SISR_CMDDU (17) //!< Bit position for SSI_SISR_CMDDU. #define BM_SSI_SISR_CMDDU (0x00020000) //!< Bit mask for SSI_SISR_CMDDU. //! @brief Get value of SSI_SISR_CMDDU from a register value. #define BG_SSI_SISR_CMDDU(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_CMDDU) >> BP_SSI_SISR_CMDDU) //@} /*! @name Register SSI_SISR, field CMDAU[18] (RO) * * Command Address Register Updated. This bit causes the Command Address Updated interrupt (when * CMDAU_EN bit is set). This status bit is set each time there is a difference in the previous and * current value of the received Command Address. This bit is cleared on reading the SACADD * register. * * Values: * - 0 - No change in SACADD register. * - 1 - SACADD register updated with different value. */ //@{ #define BP_SSI_SISR_CMDAU (18) //!< Bit position for SSI_SISR_CMDAU. #define BM_SSI_SISR_CMDAU (0x00040000) //!< Bit mask for SSI_SISR_CMDAU. //! @brief Get value of SSI_SISR_CMDAU from a register value. #define BG_SSI_SISR_CMDAU(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_CMDAU) >> BP_SSI_SISR_CMDAU) //@} /*! @name Register SSI_SISR, field TFRC[23] (RO) * * Transmit Frame Complete. This flag is set at the end of the frame during which Transmitter is * disabled. If Transmit Frame & Clock are not disabled in the same frame, this flag is also set at * the end of the frame in which Transmit Frame & Clock are disabled. See description of TFR_CLK_DIS * bit for more details on how to disable Transmit Frame & Clock or keep them enabled after * transmitter is disabled. * * Values: * - 0 - End of Frame not reached * - 1 - End of frame reached after disabling TE or disabling TFR_CLK_DIS, when transmitter is already * disabled. */ //@{ #define BP_SSI_SISR_TFRC (23) //!< Bit position for SSI_SISR_TFRC. #define BM_SSI_SISR_TFRC (0x00800000) //!< Bit mask for SSI_SISR_TFRC. //! @brief Get value of SSI_SISR_TFRC from a register value. #define BG_SSI_SISR_TFRC(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_TFRC) >> BP_SSI_SISR_TFRC) //@} /*! @name Register SSI_SISR, field RFRC[24] (RO) * * Receive Frame Complete. This flag is set at the end of the frame during which Receiver is * disabled. If Receive Frame & Clock are not disabled in the same frame, this flag is also set at * the end of the frame in which Receive Frame & Clock are disabled. See the description of * RFR_CLK_DIS bit for more details on how to disable Receiver Frame & Clock or keep them enabled * after receiver is disabled. * * Values: * - 0 - End of Frame not reached * - 1 - End of frame reached after disabling RE or disabling RFR_CLK_DIS, when receiver is already disabled. */ //@{ #define BP_SSI_SISR_RFRC (24) //!< Bit position for SSI_SISR_RFRC. #define BM_SSI_SISR_RFRC (0x01000000) //!< Bit mask for SSI_SISR_RFRC. //! @brief Get value of SSI_SISR_RFRC from a register value. #define BG_SSI_SISR_RFRC(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SISR_RFRC) >> BP_SSI_SISR_RFRC) //@} //------------------------------------------------------------------------------------------- // HW_SSI_SIER - SSI Interrupt Enable Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SIER - SSI Interrupt Enable Register (RW) * * Reset value: 0x00003003 * * The SSI Interrupt Enable Register (SIER) is a 25-bit register used to set up the SSI interrupts * and DMA requests. */ typedef union _hw_ssi_sier { reg32_t U; struct _hw_ssi_sier_bitfields { unsigned TFE0IE : 1; //!< [0] Transmit FIFO Empty 0 Interrupt Enable. unsigned TFE1IE : 1; //!< [1] Transmit FIFO Empty 1 Interrupt Enable. unsigned RFF0IE : 1; //!< [2] Receive FIFO Full 0 Interrupt Enable. unsigned RFF1IE : 1; //!< [3] Receive FIFO Full 1 Interrupt Enable. unsigned RLSIE : 1; //!< [4] Receive Last Time Slot Interrupt Enable. unsigned TLSIE : 1; //!< [5] Transmit Last Time Slot Interrupt Enable. unsigned RFSIE : 1; //!< [6] Receive Frame Sync Interrupt Enable. unsigned TFSIE : 1; //!< [7] Transmit Frame Sync Interrupt Enable. unsigned TUE0IE : 1; //!< [8] Transmitter Underrun Error 0 Interrupt Enable. unsigned TUE1IE : 1; //!< [9] Transmitter Underrun Error 1 Interrupt Enable. unsigned ROE0IE : 1; //!< [10] Receiver Overrun Error 0 Interrupt Enable. unsigned ROE1IE : 1; //!< [11] Receiver Overrun Error 1 Interrupt Enable. unsigned TDE0IE : 1; //!< [12] Transmit Data Register Empty 0 Interrupt Enable. unsigned TDE1IE : 1; //!< [13] Transmit Data Register Empty 1 Interrupt Enable. unsigned RDR0IE : 1; //!< [14] Receive Data Ready 0 Interrupt Enable. unsigned RDR1IE : 1; //!< [15] Receive Data Ready 1 Interrupt Enable. unsigned RXTIE : 1; //!< [16] Receive Tag Updated Interrupt Enable. unsigned CMDDUIE : 1; //!< [17] Command Data Register Updated Interrupt Enable. unsigned CMDAUIE : 1; //!< [18] Command Address Register Updated Interrupt Enable. unsigned TIE : 1; //!< [19] Transmit Interrupt Enable. unsigned TDMAE : 1; //!< [20] Transmit DMA Enable. unsigned RIE : 1; //!< [21] Receive Interrupt Enable. unsigned RDMAE : 1; //!< [22] Receive DMA Enable. unsigned TFRCIE : 1; //!< [23] Transmit Frame Complete Interrupt Enable. unsigned RFRCIE : 1; //!< [24] Receive Frame Complete Interrupt Enable. unsigned RESERVED0 : 7; //!< [31:25] Reserved } B; } hw_ssi_sier_t; #endif /*! * @name Constants and macros for entire SSI_SIER register */ //@{ #define HW_SSI_SIER_ADDR(x) (REGS_SSI_BASE(x) + 0x18) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SIER(x) (*(volatile hw_ssi_sier_t *) HW_SSI_SIER_ADDR(x)) #define HW_SSI_SIER_RD(x) (HW_SSI_SIER(x).U) #define HW_SSI_SIER_WR(x, v) (HW_SSI_SIER(x).U = (v)) #define HW_SSI_SIER_SET(x, v) (HW_SSI_SIER_WR(x, HW_SSI_SIER_RD(x) | (v))) #define HW_SSI_SIER_CLR(x, v) (HW_SSI_SIER_WR(x, HW_SSI_SIER_RD(x) & ~(v))) #define HW_SSI_SIER_TOG(x, v) (HW_SSI_SIER_WR(x, HW_SSI_SIER_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_SIER bitfields */ /*! @name Register SSI_SIER, field TFE0IE[0] (RW) * * Transmit FIFO Empty 0 Interrupt Enable. Enable Bit. Controls whether the corresponding status bit * in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_TFE0IE (0) //!< Bit position for SSI_SIER_TFE0IE. #define BM_SSI_SIER_TFE0IE (0x00000001) //!< Bit mask for SSI_SIER_TFE0IE. //! @brief Get value of SSI_SIER_TFE0IE from a register value. #define BG_SSI_SIER_TFE0IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_TFE0IE) >> BP_SSI_SIER_TFE0IE) //! @brief Format value for bitfield SSI_SIER_TFE0IE. #define BF_SSI_SIER_TFE0IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_TFE0IE) & BM_SSI_SIER_TFE0IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFE0IE field to a new value. #define BW_SSI_SIER_TFE0IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_TFE0IE) | BF_SSI_SIER_TFE0IE(v))) #endif //@} /*! @name Register SSI_SIER, field TFE1IE[1] (RW) * * Transmit FIFO Empty 1 Interrupt Enable. Enable Bit. Controls whether the corresponding status bit * in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_TFE1IE (1) //!< Bit position for SSI_SIER_TFE1IE. #define BM_SSI_SIER_TFE1IE (0x00000002) //!< Bit mask for SSI_SIER_TFE1IE. //! @brief Get value of SSI_SIER_TFE1IE from a register value. #define BG_SSI_SIER_TFE1IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_TFE1IE) >> BP_SSI_SIER_TFE1IE) //! @brief Format value for bitfield SSI_SIER_TFE1IE. #define BF_SSI_SIER_TFE1IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_TFE1IE) & BM_SSI_SIER_TFE1IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFE1IE field to a new value. #define BW_SSI_SIER_TFE1IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_TFE1IE) | BF_SSI_SIER_TFE1IE(v))) #endif //@} /*! @name Register SSI_SIER, field RFF0IE[2] (RW) * * Receive FIFO Full 0 Interrupt Enable. Enable Bit. Controls whether the corresponding status bit * in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_RFF0IE (2) //!< Bit position for SSI_SIER_RFF0IE. #define BM_SSI_SIER_RFF0IE (0x00000004) //!< Bit mask for SSI_SIER_RFF0IE. //! @brief Get value of SSI_SIER_RFF0IE from a register value. #define BG_SSI_SIER_RFF0IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_RFF0IE) >> BP_SSI_SIER_RFF0IE) //! @brief Format value for bitfield SSI_SIER_RFF0IE. #define BF_SSI_SIER_RFF0IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_RFF0IE) & BM_SSI_SIER_RFF0IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFF0IE field to a new value. #define BW_SSI_SIER_RFF0IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_RFF0IE) | BF_SSI_SIER_RFF0IE(v))) #endif //@} /*! @name Register SSI_SIER, field RFF1IE[3] (RW) * * Receive FIFO Full 1 Interrupt Enable. Enable Bit. Controls whether the corresponding status bit * in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_RFF1IE (3) //!< Bit position for SSI_SIER_RFF1IE. #define BM_SSI_SIER_RFF1IE (0x00000008) //!< Bit mask for SSI_SIER_RFF1IE. //! @brief Get value of SSI_SIER_RFF1IE from a register value. #define BG_SSI_SIER_RFF1IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_RFF1IE) >> BP_SSI_SIER_RFF1IE) //! @brief Format value for bitfield SSI_SIER_RFF1IE. #define BF_SSI_SIER_RFF1IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_RFF1IE) & BM_SSI_SIER_RFF1IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFF1IE field to a new value. #define BW_SSI_SIER_RFF1IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_RFF1IE) | BF_SSI_SIER_RFF1IE(v))) #endif //@} /*! @name Register SSI_SIER, field RLSIE[4] (RW) * * Receive Last Time Slot Interrupt Enable. Enable Bit. Controls whether the corresponding status * bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_RLSIE (4) //!< Bit position for SSI_SIER_RLSIE. #define BM_SSI_SIER_RLSIE (0x00000010) //!< Bit mask for SSI_SIER_RLSIE. //! @brief Get value of SSI_SIER_RLSIE from a register value. #define BG_SSI_SIER_RLSIE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_RLSIE) >> BP_SSI_SIER_RLSIE) //! @brief Format value for bitfield SSI_SIER_RLSIE. #define BF_SSI_SIER_RLSIE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_RLSIE) & BM_SSI_SIER_RLSIE) #ifndef __LANGUAGE_ASM__ //! @brief Set the RLSIE field to a new value. #define BW_SSI_SIER_RLSIE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_RLSIE) | BF_SSI_SIER_RLSIE(v))) #endif //@} /*! @name Register SSI_SIER, field TLSIE[5] (RO) * * Transmit Last Time Slot Interrupt Enable. Enable Bit. Controls whether the corresponding status * bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_TLSIE (5) //!< Bit position for SSI_SIER_TLSIE. #define BM_SSI_SIER_TLSIE (0x00000020) //!< Bit mask for SSI_SIER_TLSIE. //! @brief Get value of SSI_SIER_TLSIE from a register value. #define BG_SSI_SIER_TLSIE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_TLSIE) >> BP_SSI_SIER_TLSIE) //@} /*! @name Register SSI_SIER, field RFSIE[6] (RW) * * Receive Frame Sync Interrupt Enable. Enable Bit. Controls whether the corresponding status bit in * SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_RFSIE (6) //!< Bit position for SSI_SIER_RFSIE. #define BM_SSI_SIER_RFSIE (0x00000040) //!< Bit mask for SSI_SIER_RFSIE. //! @brief Get value of SSI_SIER_RFSIE from a register value. #define BG_SSI_SIER_RFSIE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_RFSIE) >> BP_SSI_SIER_RFSIE) //! @brief Format value for bitfield SSI_SIER_RFSIE. #define BF_SSI_SIER_RFSIE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_RFSIE) & BM_SSI_SIER_RFSIE) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFSIE field to a new value. #define BW_SSI_SIER_RFSIE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_RFSIE) | BF_SSI_SIER_RFSIE(v))) #endif //@} /*! @name Register SSI_SIER, field TFSIE[7] (RW) * * Transmit Frame Sync Interrupt Enable. Enable Bit. Controls whether the corresponding status bit * in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_TFSIE (7) //!< Bit position for SSI_SIER_TFSIE. #define BM_SSI_SIER_TFSIE (0x00000080) //!< Bit mask for SSI_SIER_TFSIE. //! @brief Get value of SSI_SIER_TFSIE from a register value. #define BG_SSI_SIER_TFSIE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_TFSIE) >> BP_SSI_SIER_TFSIE) //! @brief Format value for bitfield SSI_SIER_TFSIE. #define BF_SSI_SIER_TFSIE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_TFSIE) & BM_SSI_SIER_TFSIE) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFSIE field to a new value. #define BW_SSI_SIER_TFSIE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_TFSIE) | BF_SSI_SIER_TFSIE(v))) #endif //@} /*! @name Register SSI_SIER, field TUE0IE[8] (RW) * * Transmitter Underrun Error 0 Interrupt Enable. Enable Bit. Controls whether the corresponding * status bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_TUE0IE (8) //!< Bit position for SSI_SIER_TUE0IE. #define BM_SSI_SIER_TUE0IE (0x00000100) //!< Bit mask for SSI_SIER_TUE0IE. //! @brief Get value of SSI_SIER_TUE0IE from a register value. #define BG_SSI_SIER_TUE0IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_TUE0IE) >> BP_SSI_SIER_TUE0IE) //! @brief Format value for bitfield SSI_SIER_TUE0IE. #define BF_SSI_SIER_TUE0IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_TUE0IE) & BM_SSI_SIER_TUE0IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the TUE0IE field to a new value. #define BW_SSI_SIER_TUE0IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_TUE0IE) | BF_SSI_SIER_TUE0IE(v))) #endif //@} /*! @name Register SSI_SIER, field TUE1IE[9] (RW) * * Transmitter Underrun Error 1 Interrupt Enable. Enable Bit. Controls whether the corresponding * status bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_TUE1IE (9) //!< Bit position for SSI_SIER_TUE1IE. #define BM_SSI_SIER_TUE1IE (0x00000200) //!< Bit mask for SSI_SIER_TUE1IE. //! @brief Get value of SSI_SIER_TUE1IE from a register value. #define BG_SSI_SIER_TUE1IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_TUE1IE) >> BP_SSI_SIER_TUE1IE) //! @brief Format value for bitfield SSI_SIER_TUE1IE. #define BF_SSI_SIER_TUE1IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_TUE1IE) & BM_SSI_SIER_TUE1IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the TUE1IE field to a new value. #define BW_SSI_SIER_TUE1IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_TUE1IE) | BF_SSI_SIER_TUE1IE(v))) #endif //@} /*! @name Register SSI_SIER, field ROE0IE[10] (RW) * * Receiver Overrun Error 0 Interrupt Enable. Enable Bit. Controls whether the corresponding status * bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_ROE0IE (10) //!< Bit position for SSI_SIER_ROE0IE. #define BM_SSI_SIER_ROE0IE (0x00000400) //!< Bit mask for SSI_SIER_ROE0IE. //! @brief Get value of SSI_SIER_ROE0IE from a register value. #define BG_SSI_SIER_ROE0IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_ROE0IE) >> BP_SSI_SIER_ROE0IE) //! @brief Format value for bitfield SSI_SIER_ROE0IE. #define BF_SSI_SIER_ROE0IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_ROE0IE) & BM_SSI_SIER_ROE0IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the ROE0IE field to a new value. #define BW_SSI_SIER_ROE0IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_ROE0IE) | BF_SSI_SIER_ROE0IE(v))) #endif //@} /*! @name Register SSI_SIER, field ROE1IE[11] (RW) * * Receiver Overrun Error 1 Interrupt Enable. Enable Bit. Controls whether the corresponding status * bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_ROE1IE (11) //!< Bit position for SSI_SIER_ROE1IE. #define BM_SSI_SIER_ROE1IE (0x00000800) //!< Bit mask for SSI_SIER_ROE1IE. //! @brief Get value of SSI_SIER_ROE1IE from a register value. #define BG_SSI_SIER_ROE1IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_ROE1IE) >> BP_SSI_SIER_ROE1IE) //! @brief Format value for bitfield SSI_SIER_ROE1IE. #define BF_SSI_SIER_ROE1IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_ROE1IE) & BM_SSI_SIER_ROE1IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the ROE1IE field to a new value. #define BW_SSI_SIER_ROE1IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_ROE1IE) | BF_SSI_SIER_ROE1IE(v))) #endif //@} /*! @name Register SSI_SIER, field TDE0IE[12] (RW) * * Transmit Data Register Empty 0 Interrupt Enable. Enable Bit. Controls whether the corresponding * status bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_TDE0IE (12) //!< Bit position for SSI_SIER_TDE0IE. #define BM_SSI_SIER_TDE0IE (0x00001000) //!< Bit mask for SSI_SIER_TDE0IE. //! @brief Get value of SSI_SIER_TDE0IE from a register value. #define BG_SSI_SIER_TDE0IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_TDE0IE) >> BP_SSI_SIER_TDE0IE) //! @brief Format value for bitfield SSI_SIER_TDE0IE. #define BF_SSI_SIER_TDE0IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_TDE0IE) & BM_SSI_SIER_TDE0IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the TDE0IE field to a new value. #define BW_SSI_SIER_TDE0IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_TDE0IE) | BF_SSI_SIER_TDE0IE(v))) #endif //@} /*! @name Register SSI_SIER, field TDE1IE[13] (RW) * * Transmit Data Register Empty 1 Interrupt Enable. Enable Bit. Controls whether the corresponding * status bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_TDE1IE (13) //!< Bit position for SSI_SIER_TDE1IE. #define BM_SSI_SIER_TDE1IE (0x00002000) //!< Bit mask for SSI_SIER_TDE1IE. //! @brief Get value of SSI_SIER_TDE1IE from a register value. #define BG_SSI_SIER_TDE1IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_TDE1IE) >> BP_SSI_SIER_TDE1IE) //! @brief Format value for bitfield SSI_SIER_TDE1IE. #define BF_SSI_SIER_TDE1IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_TDE1IE) & BM_SSI_SIER_TDE1IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the TDE1IE field to a new value. #define BW_SSI_SIER_TDE1IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_TDE1IE) | BF_SSI_SIER_TDE1IE(v))) #endif //@} /*! @name Register SSI_SIER, field RDR0IE[14] (RW) * * Receive Data Ready 0 Interrupt Enable. Enable Bit. Controls whether the corresponding status bit * in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_RDR0IE (14) //!< Bit position for SSI_SIER_RDR0IE. #define BM_SSI_SIER_RDR0IE (0x00004000) //!< Bit mask for SSI_SIER_RDR0IE. //! @brief Get value of SSI_SIER_RDR0IE from a register value. #define BG_SSI_SIER_RDR0IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_RDR0IE) >> BP_SSI_SIER_RDR0IE) //! @brief Format value for bitfield SSI_SIER_RDR0IE. #define BF_SSI_SIER_RDR0IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_RDR0IE) & BM_SSI_SIER_RDR0IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the RDR0IE field to a new value. #define BW_SSI_SIER_RDR0IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_RDR0IE) | BF_SSI_SIER_RDR0IE(v))) #endif //@} /*! @name Register SSI_SIER, field RDR1IE[15] (RW) * * Receive Data Ready 1 Interrupt Enable. Enable Bit. Controls whether the corresponding status bit * in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_RDR1IE (15) //!< Bit position for SSI_SIER_RDR1IE. #define BM_SSI_SIER_RDR1IE (0x00008000) //!< Bit mask for SSI_SIER_RDR1IE. //! @brief Get value of SSI_SIER_RDR1IE from a register value. #define BG_SSI_SIER_RDR1IE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_RDR1IE) >> BP_SSI_SIER_RDR1IE) //! @brief Format value for bitfield SSI_SIER_RDR1IE. #define BF_SSI_SIER_RDR1IE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_RDR1IE) & BM_SSI_SIER_RDR1IE) #ifndef __LANGUAGE_ASM__ //! @brief Set the RDR1IE field to a new value. #define BW_SSI_SIER_RDR1IE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_RDR1IE) | BF_SSI_SIER_RDR1IE(v))) #endif //@} /*! @name Register SSI_SIER, field RXTIE[16] (RW) * * Receive Tag Updated Interrupt Enable. Enable Bit. Controls whether the corresponding status bit * in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_RXTIE (16) //!< Bit position for SSI_SIER_RXTIE. #define BM_SSI_SIER_RXTIE (0x00010000) //!< Bit mask for SSI_SIER_RXTIE. //! @brief Get value of SSI_SIER_RXTIE from a register value. #define BG_SSI_SIER_RXTIE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_RXTIE) >> BP_SSI_SIER_RXTIE) //! @brief Format value for bitfield SSI_SIER_RXTIE. #define BF_SSI_SIER_RXTIE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_RXTIE) & BM_SSI_SIER_RXTIE) #ifndef __LANGUAGE_ASM__ //! @brief Set the RXTIE field to a new value. #define BW_SSI_SIER_RXTIE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_RXTIE) | BF_SSI_SIER_RXTIE(v))) #endif //@} /*! @name Register SSI_SIER, field CMDDUIE[17] (RW) * * Command Data Register Updated Interrupt Enable. Enable Bit. Controls whether the corresponding * status bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_CMDDUIE (17) //!< Bit position for SSI_SIER_CMDDUIE. #define BM_SSI_SIER_CMDDUIE (0x00020000) //!< Bit mask for SSI_SIER_CMDDUIE. //! @brief Get value of SSI_SIER_CMDDUIE from a register value. #define BG_SSI_SIER_CMDDUIE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_CMDDUIE) >> BP_SSI_SIER_CMDDUIE) //! @brief Format value for bitfield SSI_SIER_CMDDUIE. #define BF_SSI_SIER_CMDDUIE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_CMDDUIE) & BM_SSI_SIER_CMDDUIE) #ifndef __LANGUAGE_ASM__ //! @brief Set the CMDDUIE field to a new value. #define BW_SSI_SIER_CMDDUIE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_CMDDUIE) | BF_SSI_SIER_CMDDUIE(v))) #endif //@} /*! @name Register SSI_SIER, field CMDAUIE[18] (RW) * * Command Address Register Updated Interrupt Enable. Enable Bit. Controls whether the corresponding * status bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_CMDAUIE (18) //!< Bit position for SSI_SIER_CMDAUIE. #define BM_SSI_SIER_CMDAUIE (0x00040000) //!< Bit mask for SSI_SIER_CMDAUIE. //! @brief Get value of SSI_SIER_CMDAUIE from a register value. #define BG_SSI_SIER_CMDAUIE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_CMDAUIE) >> BP_SSI_SIER_CMDAUIE) //! @brief Format value for bitfield SSI_SIER_CMDAUIE. #define BF_SSI_SIER_CMDAUIE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_CMDAUIE) & BM_SSI_SIER_CMDAUIE) #ifndef __LANGUAGE_ASM__ //! @brief Set the CMDAUIE field to a new value. #define BW_SSI_SIER_CMDAUIE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_CMDAUIE) | BF_SSI_SIER_CMDAUIE(v))) #endif //@} /*! @name Register SSI_SIER, field TIE[19] (RW) * * Transmit Interrupt Enable. This control bit allows the SSI to issue transmitter data related * interrupts to the Core. Refer to for a detailed description of this bit. * * Values: * - 0 - SSI Transmitter Interrupt requests disabled. * - 1 - SSI Transmitter Interrupt requests enabled. */ //@{ #define BP_SSI_SIER_TIE (19) //!< Bit position for SSI_SIER_TIE. #define BM_SSI_SIER_TIE (0x00080000) //!< Bit mask for SSI_SIER_TIE. //! @brief Get value of SSI_SIER_TIE from a register value. #define BG_SSI_SIER_TIE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_TIE) >> BP_SSI_SIER_TIE) //! @brief Format value for bitfield SSI_SIER_TIE. #define BF_SSI_SIER_TIE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_TIE) & BM_SSI_SIER_TIE) #ifndef __LANGUAGE_ASM__ //! @brief Set the TIE field to a new value. #define BW_SSI_SIER_TIE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_TIE) | BF_SSI_SIER_TIE(v))) #endif //@} /*! @name Register SSI_SIER, field TDMAE[20] (RW) * * Transmit DMA Enable. This bit allows SSI to request for DMA transfers. When enabled, DMA requests * are generated when any of the TFE0/1 bits in the SISR are set and if the corresponding TFEN bit * is also set. If the corresponding FIFO is disabled, a DMA request is generated when the * corresponding TDE bit is set. * * Values: * - 0 - SSI Transmitter DMA requests disabled. * - 1 - SSI Transmitter DMA requests enabled. */ //@{ #define BP_SSI_SIER_TDMAE (20) //!< Bit position for SSI_SIER_TDMAE. #define BM_SSI_SIER_TDMAE (0x00100000) //!< Bit mask for SSI_SIER_TDMAE. //! @brief Get value of SSI_SIER_TDMAE from a register value. #define BG_SSI_SIER_TDMAE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_TDMAE) >> BP_SSI_SIER_TDMAE) //! @brief Format value for bitfield SSI_SIER_TDMAE. #define BF_SSI_SIER_TDMAE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_TDMAE) & BM_SSI_SIER_TDMAE) #ifndef __LANGUAGE_ASM__ //! @brief Set the TDMAE field to a new value. #define BW_SSI_SIER_TDMAE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_TDMAE) | BF_SSI_SIER_TDMAE(v))) #endif //@} /*! @name Register SSI_SIER, field RIE[21] (RW) * * Receive Interrupt Enable. This control bit allows the SSI to issue receiver related interrupts to * the Core. Refer to for a detailed description of this bit. * * Values: * - 0 - SSI Receiver Interrupt requests disabled. * - 1 - SSI Receiver Interrupt requests enabled. */ //@{ #define BP_SSI_SIER_RIE (21) //!< Bit position for SSI_SIER_RIE. #define BM_SSI_SIER_RIE (0x00200000) //!< Bit mask for SSI_SIER_RIE. //! @brief Get value of SSI_SIER_RIE from a register value. #define BG_SSI_SIER_RIE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_RIE) >> BP_SSI_SIER_RIE) //! @brief Format value for bitfield SSI_SIER_RIE. #define BF_SSI_SIER_RIE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_RIE) & BM_SSI_SIER_RIE) #ifndef __LANGUAGE_ASM__ //! @brief Set the RIE field to a new value. #define BW_SSI_SIER_RIE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_RIE) | BF_SSI_SIER_RIE(v))) #endif //@} /*! @name Register SSI_SIER, field RDMAE[22] (RW) * * Receive DMA Enable. This bit allows SSI to request for DMA transfers. When enabled, DMA requests * are generated when any of the RFF0/1 bits in the SISR are set and if the corresponding RFEN bit * is also set. If the corresponding FIFO is disabled, a DMA request is generated when the * corresponding RDR bit is set. * * Values: * - 0 - SSI Receiver DMA requests disabled. * - 1 - SSI Receiver DMA requests enabled. */ //@{ #define BP_SSI_SIER_RDMAE (22) //!< Bit position for SSI_SIER_RDMAE. #define BM_SSI_SIER_RDMAE (0x00400000) //!< Bit mask for SSI_SIER_RDMAE. //! @brief Get value of SSI_SIER_RDMAE from a register value. #define BG_SSI_SIER_RDMAE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_RDMAE) >> BP_SSI_SIER_RDMAE) //! @brief Format value for bitfield SSI_SIER_RDMAE. #define BF_SSI_SIER_RDMAE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_RDMAE) & BM_SSI_SIER_RDMAE) #ifndef __LANGUAGE_ASM__ //! @brief Set the RDMAE field to a new value. #define BW_SSI_SIER_RDMAE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_RDMAE) | BF_SSI_SIER_RDMAE(v))) #endif //@} /*! @name Register SSI_SIER, field TFRCIE[23] (RW) * * Transmit Frame Complete Interrupt Enable. Enable Bit. Controls whether the corresponding status * bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_TFRCIE (23) //!< Bit position for SSI_SIER_TFRCIE. #define BM_SSI_SIER_TFRCIE (0x00800000) //!< Bit mask for SSI_SIER_TFRCIE. //! @brief Get value of SSI_SIER_TFRCIE from a register value. #define BG_SSI_SIER_TFRCIE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_TFRCIE) >> BP_SSI_SIER_TFRCIE) //! @brief Format value for bitfield SSI_SIER_TFRCIE. #define BF_SSI_SIER_TFRCIE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_TFRCIE) & BM_SSI_SIER_TFRCIE) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFRCIE field to a new value. #define BW_SSI_SIER_TFRCIE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_TFRCIE) | BF_SSI_SIER_TFRCIE(v))) #endif //@} /*! @name Register SSI_SIER, field RFRCIE[24] (RW) * * Receive Frame Complete Interrupt Enable. Enable Bit. Controls whether the corresponding status * bit in SISR can issue an interrupt to the core or not. * * Values: * - 0 - Corresponding status bit cannot issue interrupt. * - 1 - Corresponding status bit can issue interrupt. */ //@{ #define BP_SSI_SIER_RFRCIE (24) //!< Bit position for SSI_SIER_RFRCIE. #define BM_SSI_SIER_RFRCIE (0x01000000) //!< Bit mask for SSI_SIER_RFRCIE. //! @brief Get value of SSI_SIER_RFRCIE from a register value. #define BG_SSI_SIER_RFRCIE(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SIER_RFRCIE) >> BP_SSI_SIER_RFRCIE) //! @brief Format value for bitfield SSI_SIER_RFRCIE. #define BF_SSI_SIER_RFRCIE(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SIER_RFRCIE) & BM_SSI_SIER_RFRCIE) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFRCIE field to a new value. #define BW_SSI_SIER_RFRCIE(x, v) (HW_SSI_SIER_WR(x, (HW_SSI_SIER_RD(x) & ~BM_SSI_SIER_RFRCIE) | BF_SSI_SIER_RFRCIE(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_STCR - SSI Transmit Configuration Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_STCR - SSI Transmit Configuration Register (RW) * * Reset value: 0x00000200 * * The SSI Transmit Configuration Register (SSI_STCR) is a read/write control register used to * direct the transmit operation of the STCR controls the direction of the bit clock and frame sync * ports, STCK and STFS. Interrupt enable bit for the transmit sections is provided in this control * register. The Power-on reset clears all SSI_STCR bits. However, SSI reset does not affect the * SSI_STCR bits. The SSI_STCR bits are described in the following paragraphs. See the Programmable * Registers section for the programming model of the SSI. The SSI Control Register (SSI_SCR) must * first be set to enable interrupts. Next, the SSI interrupt bit in the Interrupt Enable Register * (SSI_SIER) must be set to enable the interrupt. Finally, the interrupt can be enabled from within * the */ typedef union _hw_ssi_stcr { reg32_t U; struct _hw_ssi_stcr_bitfields { unsigned TEFS : 1; //!< [0] Transmit Early Frame Sync. unsigned TFSL : 1; //!< [1] Transmit Frame Sync Length. unsigned TFSI : 1; //!< [2] Transmit Frame Sync Invert. unsigned TSCKP : 1; //!< [3] Transmit Clock Polarity. unsigned TSHFD : 1; //!< [4] Transmit Shift Direction. unsigned TXDIR : 1; //!< [5] Transmit Clock Direction. unsigned TFDIR : 1; //!< [6] Transmit Frame Direction. unsigned TFEN0 : 1; //!< [7] Transmit FIFO Enable 0. unsigned TFEN1 : 1; //!< [8] Transmit FIFO Enable 1. unsigned TXBIT0 : 1; //!< [9] Transmit Bit 0. unsigned RESERVED0 : 22; //!< [31:10] Reserved } B; } hw_ssi_stcr_t; #endif /*! * @name Constants and macros for entire SSI_STCR register */ //@{ #define HW_SSI_STCR_ADDR(x) (REGS_SSI_BASE(x) + 0x1c) #ifndef __LANGUAGE_ASM__ #define HW_SSI_STCR(x) (*(volatile hw_ssi_stcr_t *) HW_SSI_STCR_ADDR(x)) #define HW_SSI_STCR_RD(x) (HW_SSI_STCR(x).U) #define HW_SSI_STCR_WR(x, v) (HW_SSI_STCR(x).U = (v)) #define HW_SSI_STCR_SET(x, v) (HW_SSI_STCR_WR(x, HW_SSI_STCR_RD(x) | (v))) #define HW_SSI_STCR_CLR(x, v) (HW_SSI_STCR_WR(x, HW_SSI_STCR_RD(x) & ~(v))) #define HW_SSI_STCR_TOG(x, v) (HW_SSI_STCR_WR(x, HW_SSI_STCR_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_STCR bitfields */ /*! @name Register SSI_STCR, field TEFS[0] (RW) * * Transmit Early Frame Sync. This bit controls when the frame sync is initiated for the transmit * section. The frame sync signal is deasserted after one bit-for-bit length frame sync and after * one word-for-word length frame sync. In case of synchronous operation, the frame sync can also be * initiated on receiving the first bit of data. * * Values: * - FIRST_BIT = 0 - Transmit frame sync initiated as the first bit of data is transmitted. * - ONE_BIT_BEFORE = 1 - Transmit frame sync is initiated one bit before the data is transmitted. */ //@{ #define BP_SSI_STCR_TEFS (0) //!< Bit position for SSI_STCR_TEFS. #define BM_SSI_STCR_TEFS (0x00000001) //!< Bit mask for SSI_STCR_TEFS. //! @brief Get value of SSI_STCR_TEFS from a register value. #define BG_SSI_STCR_TEFS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCR_TEFS) >> BP_SSI_STCR_TEFS) //! @brief Format value for bitfield SSI_STCR_TEFS. #define BF_SSI_STCR_TEFS(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCR_TEFS) & BM_SSI_STCR_TEFS) #ifndef __LANGUAGE_ASM__ //! @brief Set the TEFS field to a new value. #define BW_SSI_STCR_TEFS(x, v) (HW_SSI_STCR_WR(x, (HW_SSI_STCR_RD(x) & ~BM_SSI_STCR_TEFS) | BF_SSI_STCR_TEFS(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_STCR_TEFS_V(v) BF_SSI_STCR_TEFS(BV_SSI_STCR_TEFS__##v) #define BV_SSI_STCR_TEFS__FIRST_BIT (0x0) //!< Transmit frame sync initiated as the first bit of data is transmitted. #define BV_SSI_STCR_TEFS__ONE_BIT_BEFORE (0x1) //!< Transmit frame sync is initiated one bit before the data is transmitted. //@} /*! @name Register SSI_STCR, field TFSL[1] (RW) * * Transmit Frame Sync Length. This bit controls the length of the frame sync signal to be generated * or recognized for the transmit section. The length of a word-long frame sync is same as the * length of the data word selected by WL[3:0]. * * Values: * - ONE_WORD = 0 - Transmit frame sync is one-word long. * - ONE_CLOCK_BIT = 1 - Transmit frame sync is one-clock-bit long. */ //@{ #define BP_SSI_STCR_TFSL (1) //!< Bit position for SSI_STCR_TFSL. #define BM_SSI_STCR_TFSL (0x00000002) //!< Bit mask for SSI_STCR_TFSL. //! @brief Get value of SSI_STCR_TFSL from a register value. #define BG_SSI_STCR_TFSL(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCR_TFSL) >> BP_SSI_STCR_TFSL) //! @brief Format value for bitfield SSI_STCR_TFSL. #define BF_SSI_STCR_TFSL(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCR_TFSL) & BM_SSI_STCR_TFSL) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFSL field to a new value. #define BW_SSI_STCR_TFSL(x, v) (HW_SSI_STCR_WR(x, (HW_SSI_STCR_RD(x) & ~BM_SSI_STCR_TFSL) | BF_SSI_STCR_TFSL(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_STCR_TFSL_V(v) BF_SSI_STCR_TFSL(BV_SSI_STCR_TFSL__##v) #define BV_SSI_STCR_TFSL__ONE_WORD (0x0) //!< Transmit frame sync is one-word long. #define BV_SSI_STCR_TFSL__ONE_CLOCK_BIT (0x1) //!< Transmit frame sync is one-clock-bit long. //@} /*! @name Register SSI_STCR, field TFSI[2] (RW) * * Transmit Frame Sync Invert. This bit controls the active state of the frame sync I/O signal for * the transmit section of SSI. * * Values: * - ACTIVE_HIGH = 0 - Transmit frame sync is active high. * - ACTIVE_LOW = 1 - Transmit frame sync is active low. */ //@{ #define BP_SSI_STCR_TFSI (2) //!< Bit position for SSI_STCR_TFSI. #define BM_SSI_STCR_TFSI (0x00000004) //!< Bit mask for SSI_STCR_TFSI. //! @brief Get value of SSI_STCR_TFSI from a register value. #define BG_SSI_STCR_TFSI(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCR_TFSI) >> BP_SSI_STCR_TFSI) //! @brief Format value for bitfield SSI_STCR_TFSI. #define BF_SSI_STCR_TFSI(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCR_TFSI) & BM_SSI_STCR_TFSI) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFSI field to a new value. #define BW_SSI_STCR_TFSI(x, v) (HW_SSI_STCR_WR(x, (HW_SSI_STCR_RD(x) & ~BM_SSI_STCR_TFSI) | BF_SSI_STCR_TFSI(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_STCR_TFSI_V(v) BF_SSI_STCR_TFSI(BV_SSI_STCR_TFSI__##v) #define BV_SSI_STCR_TFSI__ACTIVE_HIGH (0x0) //!< Transmit frame sync is active high. #define BV_SSI_STCR_TFSI__ACTIVE_LOW (0x1) //!< Transmit frame sync is active low. //@} /*! @name Register SSI_STCR, field TSCKP[3] (RW) * * Transmit Clock Polarity. This bit controls which bit clock edge is used to clock out data for the * transmit section. Note: TSCKP is 0 CLK_IST = 0; TSCKP is 1CLK_IST = 1 * * Values: * - RISING_EDGE = 0 - Data clocked out on rising edge of bit clock. * - FALLING_EDGE = 1 - Data clocked out on falling edge of bit clock. */ //@{ #define BP_SSI_STCR_TSCKP (3) //!< Bit position for SSI_STCR_TSCKP. #define BM_SSI_STCR_TSCKP (0x00000008) //!< Bit mask for SSI_STCR_TSCKP. //! @brief Get value of SSI_STCR_TSCKP from a register value. #define BG_SSI_STCR_TSCKP(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCR_TSCKP) >> BP_SSI_STCR_TSCKP) //! @brief Format value for bitfield SSI_STCR_TSCKP. #define BF_SSI_STCR_TSCKP(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCR_TSCKP) & BM_SSI_STCR_TSCKP) #ifndef __LANGUAGE_ASM__ //! @brief Set the TSCKP field to a new value. #define BW_SSI_STCR_TSCKP(x, v) (HW_SSI_STCR_WR(x, (HW_SSI_STCR_RD(x) & ~BM_SSI_STCR_TSCKP) | BF_SSI_STCR_TSCKP(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_STCR_TSCKP_V(v) BF_SSI_STCR_TSCKP(BV_SSI_STCR_TSCKP__##v) #define BV_SSI_STCR_TSCKP__RISING_EDGE (0x0) //!< Data clocked out on rising edge of bit clock. #define BV_SSI_STCR_TSCKP__FALLING_EDGE (0x1) //!< Data clocked out on falling edge of bit clock. //@} /*! @name Register SSI_STCR, field TSHFD[4] (RW) * * Transmit Shift Direction. This bit controls whether the MSB or LSB will be transmitted first in a * sample. The CODEC device labels the MSB as bit 0, whereas the Core labels the LSB as bit 0. * Therefore, when using a standard CODEC, Core MSB (CODEC LSB) is shifted in first (TSHFD cleared). * * Values: * - MSB_FIRST = 0 - Data transmitted MSB first. * - LSB_FIRST = 1 - Data transmitted LSB first. */ //@{ #define BP_SSI_STCR_TSHFD (4) //!< Bit position for SSI_STCR_TSHFD. #define BM_SSI_STCR_TSHFD (0x00000010) //!< Bit mask for SSI_STCR_TSHFD. //! @brief Get value of SSI_STCR_TSHFD from a register value. #define BG_SSI_STCR_TSHFD(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCR_TSHFD) >> BP_SSI_STCR_TSHFD) //! @brief Format value for bitfield SSI_STCR_TSHFD. #define BF_SSI_STCR_TSHFD(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCR_TSHFD) & BM_SSI_STCR_TSHFD) #ifndef __LANGUAGE_ASM__ //! @brief Set the TSHFD field to a new value. #define BW_SSI_STCR_TSHFD(x, v) (HW_SSI_STCR_WR(x, (HW_SSI_STCR_RD(x) & ~BM_SSI_STCR_TSHFD) | BF_SSI_STCR_TSHFD(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_STCR_TSHFD_V(v) BF_SSI_STCR_TSHFD(BV_SSI_STCR_TSHFD__##v) #define BV_SSI_STCR_TSHFD__MSB_FIRST (0x0) //!< Data transmitted MSB first. #define BV_SSI_STCR_TSHFD__LSB_FIRST (0x1) //!< Data transmitted LSB first. //@} /*! @name Register SSI_STCR, field TXDIR[5] (RW) * * Transmit Clock Direction. This bit controls the direction and source of the clock signal used to * clock the TXSR. Internally generated clock is output through the STCK port. External clock is * taken from this port. Refer to for details of clock pin configurations. * * Values: * - EXTERNAL = 0 - Transmit Clock is external. * - INTERNAL = 1 - Transmit Clock generated internally. */ //@{ #define BP_SSI_STCR_TXDIR (5) //!< Bit position for SSI_STCR_TXDIR. #define BM_SSI_STCR_TXDIR (0x00000020) //!< Bit mask for SSI_STCR_TXDIR. //! @brief Get value of SSI_STCR_TXDIR from a register value. #define BG_SSI_STCR_TXDIR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCR_TXDIR) >> BP_SSI_STCR_TXDIR) //! @brief Format value for bitfield SSI_STCR_TXDIR. #define BF_SSI_STCR_TXDIR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCR_TXDIR) & BM_SSI_STCR_TXDIR) #ifndef __LANGUAGE_ASM__ //! @brief Set the TXDIR field to a new value. #define BW_SSI_STCR_TXDIR(x, v) (HW_SSI_STCR_WR(x, (HW_SSI_STCR_RD(x) & ~BM_SSI_STCR_TXDIR) | BF_SSI_STCR_TXDIR(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_STCR_TXDIR_V(v) BF_SSI_STCR_TXDIR(BV_SSI_STCR_TXDIR__##v) #define BV_SSI_STCR_TXDIR__EXTERNAL (0x0) //!< Transmit Clock is external. #define BV_SSI_STCR_TXDIR__INTERNAL (0x1) //!< Transmit Clock generated internally. //@} /*! @name Register SSI_STCR, field TFDIR[6] (RW) * * Transmit Frame Direction. This bit controls the direction and source of the transmit frame sync * signal. Internally generated frame sync signal is sent out through the STFS port and external * frame sync is taken from the same port. * * Values: * - EXTERNAL = 0 - Frame Sync is external. * - INTERNAL = 1 - Frame Sync generated internally. */ //@{ #define BP_SSI_STCR_TFDIR (6) //!< Bit position for SSI_STCR_TFDIR. #define BM_SSI_STCR_TFDIR (0x00000040) //!< Bit mask for SSI_STCR_TFDIR. //! @brief Get value of SSI_STCR_TFDIR from a register value. #define BG_SSI_STCR_TFDIR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCR_TFDIR) >> BP_SSI_STCR_TFDIR) //! @brief Format value for bitfield SSI_STCR_TFDIR. #define BF_SSI_STCR_TFDIR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCR_TFDIR) & BM_SSI_STCR_TFDIR) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFDIR field to a new value. #define BW_SSI_STCR_TFDIR(x, v) (HW_SSI_STCR_WR(x, (HW_SSI_STCR_RD(x) & ~BM_SSI_STCR_TFDIR) | BF_SSI_STCR_TFDIR(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_STCR_TFDIR_V(v) BF_SSI_STCR_TFDIR(BV_SSI_STCR_TFDIR__##v) #define BV_SSI_STCR_TFDIR__EXTERNAL (0x0) //!< Frame Sync is external. #define BV_SSI_STCR_TFDIR__INTERNAL (0x1) //!< Frame Sync generated internally. //@} /*! @name Register SSI_STCR, field TFEN0[7] (RW) * * Transmit FIFO Enable 0. This bit enables transmit FIFO 0. When enabled, the FIFO allows 15 * samples to be transmitted by the SSI per channel (a 9th sample can be shifting out) before TDE0 * bit is set. When the FIFO is disabled, an interrupt is generated when a single sample is * transferred to the transmit shift register (provided the interrupt is enabled). * * Values: * - 0 - Transmit FIFO 0 disabled. * - 1 - Transmit FIFO 0 enabled. */ //@{ #define BP_SSI_STCR_TFEN0 (7) //!< Bit position for SSI_STCR_TFEN0. #define BM_SSI_STCR_TFEN0 (0x00000080) //!< Bit mask for SSI_STCR_TFEN0. //! @brief Get value of SSI_STCR_TFEN0 from a register value. #define BG_SSI_STCR_TFEN0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCR_TFEN0) >> BP_SSI_STCR_TFEN0) //! @brief Format value for bitfield SSI_STCR_TFEN0. #define BF_SSI_STCR_TFEN0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCR_TFEN0) & BM_SSI_STCR_TFEN0) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFEN0 field to a new value. #define BW_SSI_STCR_TFEN0(x, v) (HW_SSI_STCR_WR(x, (HW_SSI_STCR_RD(x) & ~BM_SSI_STCR_TFEN0) | BF_SSI_STCR_TFEN0(v))) #endif //@} /*! @name Register SSI_STCR, field TFEN1[8] (RW) * * Transmit FIFO Enable 1. This bit enables transmit FIFO 1. When enabled, the FIFO allows 15 * samples to be transmitted by the SSI (per channel) (a 9th sample can be shifting out) before TDE1 * bit is set. When the FIFO is disabled, an interrupt is generated when a single sample is * transferred to the transmit shift register (provided the interrupt is enabled). * * Values: * - 0 - Transmit FIFO 1 disabled. * - 1 - Transmit FIFO 1 enabled. */ //@{ #define BP_SSI_STCR_TFEN1 (8) //!< Bit position for SSI_STCR_TFEN1. #define BM_SSI_STCR_TFEN1 (0x00000100) //!< Bit mask for SSI_STCR_TFEN1. //! @brief Get value of SSI_STCR_TFEN1 from a register value. #define BG_SSI_STCR_TFEN1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCR_TFEN1) >> BP_SSI_STCR_TFEN1) //! @brief Format value for bitfield SSI_STCR_TFEN1. #define BF_SSI_STCR_TFEN1(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCR_TFEN1) & BM_SSI_STCR_TFEN1) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFEN1 field to a new value. #define BW_SSI_STCR_TFEN1(x, v) (HW_SSI_STCR_WR(x, (HW_SSI_STCR_RD(x) & ~BM_SSI_STCR_TFEN1) | BF_SSI_STCR_TFEN1(v))) #endif //@} /*! @name Register SSI_STCR, field TXBIT0[9] (RW) * * Transmit Bit 0. This control bit allows SSI to transmit the data word from bit position 0 or * 15/31 in the transmit shift register. The shifting data direction can be MSB or LSB first, * controlled by the TSHFD bit. * * Values: * - MSB_ALIGNED = 0 - Shifting with respect to bit 31 (if word length = 16, 18, 20, 22 or 24) or bit 15 (if word length = * 8, 10 or 12) of transmit shift register (MSB aligned). * - LSB_ALIGNED = 1 - Shifting with respect to bit 0 of transmit shift register (LSB aligned). */ //@{ #define BP_SSI_STCR_TXBIT0 (9) //!< Bit position for SSI_STCR_TXBIT0. #define BM_SSI_STCR_TXBIT0 (0x00000200) //!< Bit mask for SSI_STCR_TXBIT0. //! @brief Get value of SSI_STCR_TXBIT0 from a register value. #define BG_SSI_STCR_TXBIT0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCR_TXBIT0) >> BP_SSI_STCR_TXBIT0) //! @brief Format value for bitfield SSI_STCR_TXBIT0. #define BF_SSI_STCR_TXBIT0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCR_TXBIT0) & BM_SSI_STCR_TXBIT0) #ifndef __LANGUAGE_ASM__ //! @brief Set the TXBIT0 field to a new value. #define BW_SSI_STCR_TXBIT0(x, v) (HW_SSI_STCR_WR(x, (HW_SSI_STCR_RD(x) & ~BM_SSI_STCR_TXBIT0) | BF_SSI_STCR_TXBIT0(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_STCR_TXBIT0_V(v) BF_SSI_STCR_TXBIT0(BV_SSI_STCR_TXBIT0__##v) #define BV_SSI_STCR_TXBIT0__MSB_ALIGNED (0x0) //!< Shifting with respect to bit 31 (if word length = 16, 18, 20, 22 or 24) or bit 15 (if word length = 8, 10 or 12) of transmit shift register (MSB aligned). #define BV_SSI_STCR_TXBIT0__LSB_ALIGNED (0x1) //!< Shifting with respect to bit 0 of transmit shift register (LSB aligned). //@} //------------------------------------------------------------------------------------------- // HW_SSI_SRCR - SSI Receive Configuration Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SRCR - SSI Receive Configuration Register (RW) * * Reset value: 0x00000200 * * The SSI Receive Configuration Register (SSI_SRCR) is a read/write control register used to direct * the receive operation of the SSI. SSI.SRCR controls the direction of the bit clock and frame sync * ports, SRCK and SRFS. Interrupt enable bit for the transmit sections is provided in this control * register. The Power-on reset clears all SSI_SRCR bits. However, SSI reset does not affect the * SSI_SRCR bits. */ typedef union _hw_ssi_srcr { reg32_t U; struct _hw_ssi_srcr_bitfields { unsigned REFS : 1; //!< [0] Receive Early Frame Sync. unsigned RFSL : 1; //!< [1] Receive Frame Sync Length. unsigned RFSI : 1; //!< [2] Receive Frame Sync Invert. unsigned RSCKP : 1; //!< [3] Receive Clock Polarity. unsigned RSHFD : 1; //!< [4] Receive Shift Direction. unsigned RXDIR : 1; //!< [5] Receive Clock Direction. unsigned RFDIR : 1; //!< [6] Receive Frame Direction. unsigned RFEN0 : 1; //!< [7] Receive FIFO Enable 0. unsigned RFEN1 : 1; //!< [8] Receive FIFO Enable 1. unsigned RXBIT0 : 1; //!< [9] Receive Bit 0. unsigned RXEXT : 1; //!< [10] Receive Data Extension. unsigned RESERVED0 : 21; //!< [31:11] Reserved } B; } hw_ssi_srcr_t; #endif /*! * @name Constants and macros for entire SSI_SRCR register */ //@{ #define HW_SSI_SRCR_ADDR(x) (REGS_SSI_BASE(x) + 0x20) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SRCR(x) (*(volatile hw_ssi_srcr_t *) HW_SSI_SRCR_ADDR(x)) #define HW_SSI_SRCR_RD(x) (HW_SSI_SRCR(x).U) #define HW_SSI_SRCR_WR(x, v) (HW_SSI_SRCR(x).U = (v)) #define HW_SSI_SRCR_SET(x, v) (HW_SSI_SRCR_WR(x, HW_SSI_SRCR_RD(x) | (v))) #define HW_SSI_SRCR_CLR(x, v) (HW_SSI_SRCR_WR(x, HW_SSI_SRCR_RD(x) & ~(v))) #define HW_SSI_SRCR_TOG(x, v) (HW_SSI_SRCR_WR(x, HW_SSI_SRCR_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_SRCR bitfields */ /*! @name Register SSI_SRCR, field REFS[0] (RW) * * Receive Early Frame Sync. This bit controls when the frame sync is initiated for the receive * section. The frame sync is disabled after one bit-for-bit length frame sync and after one word- * for-word length frame sync. * * Values: * - FIRST_BIT = 0 - Receive frame sync initiated as the first bit of data is received. * - ONE_BIT_BEFORE = 1 - Receive frame sync is initiated one bit before the data is received. */ //@{ #define BP_SSI_SRCR_REFS (0) //!< Bit position for SSI_SRCR_REFS. #define BM_SSI_SRCR_REFS (0x00000001) //!< Bit mask for SSI_SRCR_REFS. //! @brief Get value of SSI_SRCR_REFS from a register value. #define BG_SSI_SRCR_REFS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCR_REFS) >> BP_SSI_SRCR_REFS) //! @brief Format value for bitfield SSI_SRCR_REFS. #define BF_SSI_SRCR_REFS(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCR_REFS) & BM_SSI_SRCR_REFS) #ifndef __LANGUAGE_ASM__ //! @brief Set the REFS field to a new value. #define BW_SSI_SRCR_REFS(x, v) (HW_SSI_SRCR_WR(x, (HW_SSI_SRCR_RD(x) & ~BM_SSI_SRCR_REFS) | BF_SSI_SRCR_REFS(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SRCR_REFS_V(v) BF_SSI_SRCR_REFS(BV_SSI_SRCR_REFS__##v) #define BV_SSI_SRCR_REFS__FIRST_BIT (0x0) //!< Receive frame sync initiated as the first bit of data is received. #define BV_SSI_SRCR_REFS__ONE_BIT_BEFORE (0x1) //!< Receive frame sync is initiated one bit before the data is received. //@} /*! @name Register SSI_SRCR, field RFSL[1] (RW) * * Receive Frame Sync Length. This bit controls the length of the frame sync signal to be generated * or recognized for the receive section. The length of a word-long frame sync is same as the length * of the data word selected by WL[3:0]. * * Values: * - ONE_WORD = 0 - Receive frame sync is one-word long. * - ONE_CLOCK_BIT = 1 - Receive frame sync is one-clock-bit long. */ //@{ #define BP_SSI_SRCR_RFSL (1) //!< Bit position for SSI_SRCR_RFSL. #define BM_SSI_SRCR_RFSL (0x00000002) //!< Bit mask for SSI_SRCR_RFSL. //! @brief Get value of SSI_SRCR_RFSL from a register value. #define BG_SSI_SRCR_RFSL(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCR_RFSL) >> BP_SSI_SRCR_RFSL) //! @brief Format value for bitfield SSI_SRCR_RFSL. #define BF_SSI_SRCR_RFSL(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCR_RFSL) & BM_SSI_SRCR_RFSL) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFSL field to a new value. #define BW_SSI_SRCR_RFSL(x, v) (HW_SSI_SRCR_WR(x, (HW_SSI_SRCR_RD(x) & ~BM_SSI_SRCR_RFSL) | BF_SSI_SRCR_RFSL(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SRCR_RFSL_V(v) BF_SSI_SRCR_RFSL(BV_SSI_SRCR_RFSL__##v) #define BV_SSI_SRCR_RFSL__ONE_WORD (0x0) //!< Receive frame sync is one-word long. #define BV_SSI_SRCR_RFSL__ONE_CLOCK_BIT (0x1) //!< Receive frame sync is one-clock-bit long. //@} /*! @name Register SSI_SRCR, field RFSI[2] (RW) * * Receive Frame Sync Invert. This bit controls the active state of the frame sync I/O signal for * the receive section of SSI. * * Values: * - ACTIVE_HIGH = 0 - Receive frame sync is active high. * - ACTIVE_LOW = 1 - Receive frame sync is active low. */ //@{ #define BP_SSI_SRCR_RFSI (2) //!< Bit position for SSI_SRCR_RFSI. #define BM_SSI_SRCR_RFSI (0x00000004) //!< Bit mask for SSI_SRCR_RFSI. //! @brief Get value of SSI_SRCR_RFSI from a register value. #define BG_SSI_SRCR_RFSI(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCR_RFSI) >> BP_SSI_SRCR_RFSI) //! @brief Format value for bitfield SSI_SRCR_RFSI. #define BF_SSI_SRCR_RFSI(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCR_RFSI) & BM_SSI_SRCR_RFSI) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFSI field to a new value. #define BW_SSI_SRCR_RFSI(x, v) (HW_SSI_SRCR_WR(x, (HW_SSI_SRCR_RD(x) & ~BM_SSI_SRCR_RFSI) | BF_SSI_SRCR_RFSI(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SRCR_RFSI_V(v) BF_SSI_SRCR_RFSI(BV_SSI_SRCR_RFSI__##v) #define BV_SSI_SRCR_RFSI__ACTIVE_HIGH (0x0) //!< Receive frame sync is active high. #define BV_SSI_SRCR_RFSI__ACTIVE_LOW (0x1) //!< Receive frame sync is active low. //@} /*! @name Register SSI_SRCR, field RSCKP[3] (RW) * * Receive Clock Polarity. This bit controls which bit clock edge is used to latch in data for the * receive section. * * Values: * - FALLING_EDGE = 0 - Data latched on falling edge of bit clock. * - RISING_EDGE = 1 - Data latched on rising edge of bit clock. */ //@{ #define BP_SSI_SRCR_RSCKP (3) //!< Bit position for SSI_SRCR_RSCKP. #define BM_SSI_SRCR_RSCKP (0x00000008) //!< Bit mask for SSI_SRCR_RSCKP. //! @brief Get value of SSI_SRCR_RSCKP from a register value. #define BG_SSI_SRCR_RSCKP(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCR_RSCKP) >> BP_SSI_SRCR_RSCKP) //! @brief Format value for bitfield SSI_SRCR_RSCKP. #define BF_SSI_SRCR_RSCKP(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCR_RSCKP) & BM_SSI_SRCR_RSCKP) #ifndef __LANGUAGE_ASM__ //! @brief Set the RSCKP field to a new value. #define BW_SSI_SRCR_RSCKP(x, v) (HW_SSI_SRCR_WR(x, (HW_SSI_SRCR_RD(x) & ~BM_SSI_SRCR_RSCKP) | BF_SSI_SRCR_RSCKP(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SRCR_RSCKP_V(v) BF_SSI_SRCR_RSCKP(BV_SSI_SRCR_RSCKP__##v) #define BV_SSI_SRCR_RSCKP__FALLING_EDGE (0x0) //!< Data latched on falling edge of bit clock. #define BV_SSI_SRCR_RSCKP__RISING_EDGE (0x1) //!< Data latched on rising edge of bit clock. //@} /*! @name Register SSI_SRCR, field RSHFD[4] (RW) * * Receive Shift Direction. This bit controls whether the MSB or LSB will be received first in a * sample. The CODEC device labels the MSB as bit 0, whereas the Core labels the LSB as bit 0. * Therefore, when using a standard CODEC, Core MSB (CODEC LSB) is shifted in first (RSHFD cleared). * * Values: * - MSB_FIRST = 0 - Data received MSB first. * - LSB_FIRST = 1 - Data received LSB first. */ //@{ #define BP_SSI_SRCR_RSHFD (4) //!< Bit position for SSI_SRCR_RSHFD. #define BM_SSI_SRCR_RSHFD (0x00000010) //!< Bit mask for SSI_SRCR_RSHFD. //! @brief Get value of SSI_SRCR_RSHFD from a register value. #define BG_SSI_SRCR_RSHFD(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCR_RSHFD) >> BP_SSI_SRCR_RSHFD) //! @brief Format value for bitfield SSI_SRCR_RSHFD. #define BF_SSI_SRCR_RSHFD(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCR_RSHFD) & BM_SSI_SRCR_RSHFD) #ifndef __LANGUAGE_ASM__ //! @brief Set the RSHFD field to a new value. #define BW_SSI_SRCR_RSHFD(x, v) (HW_SSI_SRCR_WR(x, (HW_SSI_SRCR_RD(x) & ~BM_SSI_SRCR_RSHFD) | BF_SSI_SRCR_RSHFD(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SRCR_RSHFD_V(v) BF_SSI_SRCR_RSHFD(BV_SSI_SRCR_RSHFD__##v) #define BV_SSI_SRCR_RSHFD__MSB_FIRST (0x0) //!< Data received MSB first. #define BV_SSI_SRCR_RSHFD__LSB_FIRST (0x1) //!< Data received LSB first. //@} /*! @name Register SSI_SRCR, field RXDIR[5] (RW) * * Receive Clock Direction. This bit controls the direction and source of the clock signal used to * clock the RXSR. Internally generated clock is output through the SRCK port. External clock is * taken from this port. Refer to for details on clock pin configurations. * * Values: * - EXTERNAL = 0 - Receive Clock is external. * - INTERNAL = 1 - Receive Clock generated internally. */ //@{ #define BP_SSI_SRCR_RXDIR (5) //!< Bit position for SSI_SRCR_RXDIR. #define BM_SSI_SRCR_RXDIR (0x00000020) //!< Bit mask for SSI_SRCR_RXDIR. //! @brief Get value of SSI_SRCR_RXDIR from a register value. #define BG_SSI_SRCR_RXDIR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCR_RXDIR) >> BP_SSI_SRCR_RXDIR) //! @brief Format value for bitfield SSI_SRCR_RXDIR. #define BF_SSI_SRCR_RXDIR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCR_RXDIR) & BM_SSI_SRCR_RXDIR) #ifndef __LANGUAGE_ASM__ //! @brief Set the RXDIR field to a new value. #define BW_SSI_SRCR_RXDIR(x, v) (HW_SSI_SRCR_WR(x, (HW_SSI_SRCR_RD(x) & ~BM_SSI_SRCR_RXDIR) | BF_SSI_SRCR_RXDIR(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SRCR_RXDIR_V(v) BF_SSI_SRCR_RXDIR(BV_SSI_SRCR_RXDIR__##v) #define BV_SSI_SRCR_RXDIR__EXTERNAL (0x0) //!< Receive Clock is external. #define BV_SSI_SRCR_RXDIR__INTERNAL (0x1) //!< Receive Clock generated internally. //@} /*! @name Register SSI_SRCR, field RFDIR[6] (RW) * * Receive Frame Direction. This bit controls the direction and source of the receive frame sync * signal. Internally generated frame sync signal is sent out through the SRFS port and external * frame sync is taken from the same port. * * Values: * - EXTERNAL = 0 - Frame Sync is external. * - INTERNAL = 1 - Frame Sync generated internally. */ //@{ #define BP_SSI_SRCR_RFDIR (6) //!< Bit position for SSI_SRCR_RFDIR. #define BM_SSI_SRCR_RFDIR (0x00000040) //!< Bit mask for SSI_SRCR_RFDIR. //! @brief Get value of SSI_SRCR_RFDIR from a register value. #define BG_SSI_SRCR_RFDIR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCR_RFDIR) >> BP_SSI_SRCR_RFDIR) //! @brief Format value for bitfield SSI_SRCR_RFDIR. #define BF_SSI_SRCR_RFDIR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCR_RFDIR) & BM_SSI_SRCR_RFDIR) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFDIR field to a new value. #define BW_SSI_SRCR_RFDIR(x, v) (HW_SSI_SRCR_WR(x, (HW_SSI_SRCR_RD(x) & ~BM_SSI_SRCR_RFDIR) | BF_SSI_SRCR_RFDIR(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SRCR_RFDIR_V(v) BF_SSI_SRCR_RFDIR(BV_SSI_SRCR_RFDIR__##v) #define BV_SSI_SRCR_RFDIR__EXTERNAL (0x0) //!< Frame Sync is external. #define BV_SSI_SRCR_RFDIR__INTERNAL (0x1) //!< Frame Sync generated internally. //@} /*! @name Register SSI_SRCR, field RFEN0[7] (RW) * * Receive FIFO Enable 0. This bit enables receive FIFO 0. When enabled, the FIFO allows 15 samples * to be received by the SSI (per channel) (a 16th sample can be shifting in) before RDR0 bit is * set. When the FIFO is disabled, an interrupt is generated when a single sample is received by the * SSI (provided the interrupt is enabled). * * Values: * - 0 - Receive FIFO 0 disabled. * - 1 - Receive FIFO 0 enabled. */ //@{ #define BP_SSI_SRCR_RFEN0 (7) //!< Bit position for SSI_SRCR_RFEN0. #define BM_SSI_SRCR_RFEN0 (0x00000080) //!< Bit mask for SSI_SRCR_RFEN0. //! @brief Get value of SSI_SRCR_RFEN0 from a register value. #define BG_SSI_SRCR_RFEN0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCR_RFEN0) >> BP_SSI_SRCR_RFEN0) //! @brief Format value for bitfield SSI_SRCR_RFEN0. #define BF_SSI_SRCR_RFEN0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCR_RFEN0) & BM_SSI_SRCR_RFEN0) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFEN0 field to a new value. #define BW_SSI_SRCR_RFEN0(x, v) (HW_SSI_SRCR_WR(x, (HW_SSI_SRCR_RD(x) & ~BM_SSI_SRCR_RFEN0) | BF_SSI_SRCR_RFEN0(v))) #endif //@} /*! @name Register SSI_SRCR, field RFEN1[8] (RW) * * Receive FIFO Enable 1. This bit enables receive FIFO 1. When enabled, the FIFO allows 15 samples * to be received by the SSI per channel (a 16th sample can be shifting in) before RDR1 bit is set. * When the FIFO is disabled, an interrupt is generated when a single sample is received by the SSI * (provided the interrupt is enabled). * * Values: * - 0 - Receive FIFO 1 disabled. * - 1 - Receive FIFO 1 enabled. */ //@{ #define BP_SSI_SRCR_RFEN1 (8) //!< Bit position for SSI_SRCR_RFEN1. #define BM_SSI_SRCR_RFEN1 (0x00000100) //!< Bit mask for SSI_SRCR_RFEN1. //! @brief Get value of SSI_SRCR_RFEN1 from a register value. #define BG_SSI_SRCR_RFEN1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCR_RFEN1) >> BP_SSI_SRCR_RFEN1) //! @brief Format value for bitfield SSI_SRCR_RFEN1. #define BF_SSI_SRCR_RFEN1(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCR_RFEN1) & BM_SSI_SRCR_RFEN1) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFEN1 field to a new value. #define BW_SSI_SRCR_RFEN1(x, v) (HW_SSI_SRCR_WR(x, (HW_SSI_SRCR_RD(x) & ~BM_SSI_SRCR_RFEN1) | BF_SSI_SRCR_RFEN1(v))) #endif //@} /*! @name Register SSI_SRCR, field RXBIT0[9] (RW) * * Receive Bit 0. This control bit allows SSI to receive the data word at bit position 0 or 15/31 in * the receive shift register. The shifting data direction can be MSB or LSB first, controlled by * the RSHFD bit. * * Values: * - MSB_ALIGNED = 0 - Shifting with respect to bit 31 (if word length = 16, 18, 20, 22 or 24) or bit 15 (if word length = * 8, 10 or 12) of receive shift register (MSB aligned). * - LSB_ALIGNED = 1 - Shifting with respect to bit 0 of receive shift register (LSB aligned). */ //@{ #define BP_SSI_SRCR_RXBIT0 (9) //!< Bit position for SSI_SRCR_RXBIT0. #define BM_SSI_SRCR_RXBIT0 (0x00000200) //!< Bit mask for SSI_SRCR_RXBIT0. //! @brief Get value of SSI_SRCR_RXBIT0 from a register value. #define BG_SSI_SRCR_RXBIT0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCR_RXBIT0) >> BP_SSI_SRCR_RXBIT0) //! @brief Format value for bitfield SSI_SRCR_RXBIT0. #define BF_SSI_SRCR_RXBIT0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCR_RXBIT0) & BM_SSI_SRCR_RXBIT0) #ifndef __LANGUAGE_ASM__ //! @brief Set the RXBIT0 field to a new value. #define BW_SSI_SRCR_RXBIT0(x, v) (HW_SSI_SRCR_WR(x, (HW_SSI_SRCR_RD(x) & ~BM_SSI_SRCR_RXBIT0) | BF_SSI_SRCR_RXBIT0(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SRCR_RXBIT0_V(v) BF_SSI_SRCR_RXBIT0(BV_SSI_SRCR_RXBIT0__##v) #define BV_SSI_SRCR_RXBIT0__MSB_ALIGNED (0x0) //!< Shifting with respect to bit 31 (if word length = 16, 18, 20, 22 or 24) or bit 15 (if word length = 8, 10 or 12) of receive shift register (MSB aligned). #define BV_SSI_SRCR_RXBIT0__LSB_ALIGNED (0x1) //!< Shifting with respect to bit 0 of receive shift register (LSB aligned). //@} /*! @name Register SSI_SRCR, field RXEXT[10] (RW) * * Receive Data Extension. This control bit allows SSI to store the received data word in sign * extended form. This bit affects data storage only in case received data is LSB aligned * (SRCR[9]=1) * * Values: * - OFF = 0 - Sign extension turned off. * - ON = 1 - Sign extension turned on. */ //@{ #define BP_SSI_SRCR_RXEXT (10) //!< Bit position for SSI_SRCR_RXEXT. #define BM_SSI_SRCR_RXEXT (0x00000400) //!< Bit mask for SSI_SRCR_RXEXT. //! @brief Get value of SSI_SRCR_RXEXT from a register value. #define BG_SSI_SRCR_RXEXT(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCR_RXEXT) >> BP_SSI_SRCR_RXEXT) //! @brief Format value for bitfield SSI_SRCR_RXEXT. #define BF_SSI_SRCR_RXEXT(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCR_RXEXT) & BM_SSI_SRCR_RXEXT) #ifndef __LANGUAGE_ASM__ //! @brief Set the RXEXT field to a new value. #define BW_SSI_SRCR_RXEXT(x, v) (HW_SSI_SRCR_WR(x, (HW_SSI_SRCR_RD(x) & ~BM_SSI_SRCR_RXEXT) | BF_SSI_SRCR_RXEXT(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SRCR_RXEXT_V(v) BF_SSI_SRCR_RXEXT(BV_SSI_SRCR_RXEXT__##v) #define BV_SSI_SRCR_RXEXT__OFF (0x0) //!< Sign extension turned off. #define BV_SSI_SRCR_RXEXT__ON (0x1) //!< Sign extension turned on. //@} //------------------------------------------------------------------------------------------- // HW_SSI_STCCR - SSI Transmit Clock Control Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_STCCR - SSI Transmit Clock Control Register (RW) * * Reset value: 0x00040000 * * The SSI Transmit and Receive Control (SSI_STCCR and SSI_SRCCR) registers are 19-bit, read/write * control registers used to direct the operation of the SSI. The Clock Controller Module (CCM) can * source the SSI clock (SSI's sys clock from CCM's ssi_clk_root) from multiple sources and perform * fractional division to support commonly used audio bit rates. The CCM can maintain the SSI's sys * clock frequency at a constant rate even in cases where the ipg_clk (from CCM) frequency changes. * These registers control the SSI clock generator, bit and frame sync rates, word length, and * number of words per frame for the serial data. The SSI.STCCR register is dedicated to the * transmit section, and the SSI_SRCCR register is dedicated to the receive section except in * Synchronous mode, in which the SSI_STCCR register controls both the receive and transmit * sections. Power-on reset clears all SSI_STCCR and SSI_SRCCR bits. SSI reset does not affect the * SSI_STCCR and SSI_SRCCR bits. The control bits are described in the following paragraphs. * Although the bit patterns of the SSI_STCCR and SSI_SRCCR registers are the same, the contents of * these two registers can be programmed differently. SSI Data Length WL3 WL2 WL1 WL0 Number of * Bits/Word Supported in Implementation 0 0 0 0 2 No 0 0 0 1 4 No 0 0 1 0 6 No 0 0 1 1 8 Yes 0 1 0 * 0 10 Yes 0 1 0 1 12 Yes 0 1 1 0 14 No 0 1 1 1 16 Yes 1 0 0 0 18 Yes 1 0 0 1 20 Yes 1 0 1 0 22 Yes * 1 0 1 1 24 Yes 1 1 0 0 26 No 1 1 0 1 28 No 1 1 1 0 30 No 1 1 1 1 32 No */ typedef union _hw_ssi_stccr { reg32_t U; struct _hw_ssi_stccr_bitfields { unsigned PM7_PM0 : 8; //!< [7:0] Prescaler Modulus Select. unsigned DC4_DC0 : 5; //!< [12:8] Frame Rate Divider Control. unsigned WL3_WL0 : 4; //!< [16:13] Word Length Control. unsigned PSR : 1; //!< [17] Prescaler Range. unsigned DIV2 : 1; //!< [18] Divide By 2. unsigned RESERVED0 : 13; //!< [31:19] Reserved } B; } hw_ssi_stccr_t; #endif /*! * @name Constants and macros for entire SSI_STCCR register */ //@{ #define HW_SSI_STCCR_ADDR(x) (REGS_SSI_BASE(x) + 0x24) #ifndef __LANGUAGE_ASM__ #define HW_SSI_STCCR(x) (*(volatile hw_ssi_stccr_t *) HW_SSI_STCCR_ADDR(x)) #define HW_SSI_STCCR_RD(x) (HW_SSI_STCCR(x).U) #define HW_SSI_STCCR_WR(x, v) (HW_SSI_STCCR(x).U = (v)) #define HW_SSI_STCCR_SET(x, v) (HW_SSI_STCCR_WR(x, HW_SSI_STCCR_RD(x) | (v))) #define HW_SSI_STCCR_CLR(x, v) (HW_SSI_STCCR_WR(x, HW_SSI_STCCR_RD(x) & ~(v))) #define HW_SSI_STCCR_TOG(x, v) (HW_SSI_STCCR_WR(x, HW_SSI_STCCR_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_STCCR bitfields */ /*! @name Register SSI_STCCR, field PM7_PM0[7:0] (RW) * * Prescaler Modulus Select. These bits control the prescale divider in the clock generator. This * prescaler is used only in Internal Clock mode to divide the internal clock. The bit clock output * is available at the clock port. A divide ratio from 1 to 256 (PM[7:0] = 0x00 to 0xFF) can be * selected. Refer to for details regarding settings. */ //@{ #define BP_SSI_STCCR_PM7_PM0 (0) //!< Bit position for SSI_STCCR_PM7_PM0. #define BM_SSI_STCCR_PM7_PM0 (0x000000ff) //!< Bit mask for SSI_STCCR_PM7_PM0. //! @brief Get value of SSI_STCCR_PM7_PM0 from a register value. #define BG_SSI_STCCR_PM7_PM0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCCR_PM7_PM0) >> BP_SSI_STCCR_PM7_PM0) //! @brief Format value for bitfield SSI_STCCR_PM7_PM0. #define BF_SSI_STCCR_PM7_PM0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCCR_PM7_PM0) & BM_SSI_STCCR_PM7_PM0) #ifndef __LANGUAGE_ASM__ //! @brief Set the PM7_PM0 field to a new value. #define BW_SSI_STCCR_PM7_PM0(x, v) (HW_SSI_STCCR_WR(x, (HW_SSI_STCCR_RD(x) & ~BM_SSI_STCCR_PM7_PM0) | BF_SSI_STCCR_PM7_PM0(v))) #endif //@} /*! @name Register SSI_STCCR, field DC4_DC0[12:8] (RW) * * Frame Rate Divider Control. These bits are used to control the divide ratio for the programmable * frame rate dividers. The divide ratio works on the word clock. In Normal mode, this ratio * determines the word transfer rate. In Network mode, this ratio sets the number of words per * frame. The divide ratio ranges from 1 to 32 in Normal mode and from 2 to 32 in Network mode. In * Normal mode, a divide ratio of 1 (DC=00000) provides continuous periodic data word transfer. A * bit-length frame sync must be used in this case. These bits can be programmed with values ranging * from "00000" to "11111" to control the number of words in a frame. */ //@{ #define BP_SSI_STCCR_DC4_DC0 (8) //!< Bit position for SSI_STCCR_DC4_DC0. #define BM_SSI_STCCR_DC4_DC0 (0x00001f00) //!< Bit mask for SSI_STCCR_DC4_DC0. //! @brief Get value of SSI_STCCR_DC4_DC0 from a register value. #define BG_SSI_STCCR_DC4_DC0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCCR_DC4_DC0) >> BP_SSI_STCCR_DC4_DC0) //! @brief Format value for bitfield SSI_STCCR_DC4_DC0. #define BF_SSI_STCCR_DC4_DC0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCCR_DC4_DC0) & BM_SSI_STCCR_DC4_DC0) #ifndef __LANGUAGE_ASM__ //! @brief Set the DC4_DC0 field to a new value. #define BW_SSI_STCCR_DC4_DC0(x, v) (HW_SSI_STCCR_WR(x, (HW_SSI_STCCR_RD(x) & ~BM_SSI_STCCR_DC4_DC0) | BF_SSI_STCCR_DC4_DC0(v))) #endif //@} /*! @name Register SSI_STCCR, field WL3_WL0[16:13] (RW) * * Word Length Control. These bits are used to control the length of the data words being * transferred by the SSI. These bits control the Word Length Divider in the Clock Generator. They * also control the frame sync pulse length when the FSL bit is cleared. In I2S Master mode, the SSI * works with a fixed word length of 32, and the WL bits are used to control the amount of valid * data in those 32 bits. In AC97 Mode of operation, if word length is set to any value other than * 16 bits, it will result in a word length of 20 bits. */ //@{ #define BP_SSI_STCCR_WL3_WL0 (13) //!< Bit position for SSI_STCCR_WL3_WL0. #define BM_SSI_STCCR_WL3_WL0 (0x0001e000) //!< Bit mask for SSI_STCCR_WL3_WL0. //! @brief Get value of SSI_STCCR_WL3_WL0 from a register value. #define BG_SSI_STCCR_WL3_WL0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCCR_WL3_WL0) >> BP_SSI_STCCR_WL3_WL0) //! @brief Format value for bitfield SSI_STCCR_WL3_WL0. #define BF_SSI_STCCR_WL3_WL0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCCR_WL3_WL0) & BM_SSI_STCCR_WL3_WL0) #ifndef __LANGUAGE_ASM__ //! @brief Set the WL3_WL0 field to a new value. #define BW_SSI_STCCR_WL3_WL0(x, v) (HW_SSI_STCCR_WR(x, (HW_SSI_STCCR_RD(x) & ~BM_SSI_STCCR_WL3_WL0) | BF_SSI_STCCR_WL3_WL0(v))) #endif //@} /*! @name Register SSI_STCCR, field PSR[17] (RW) * * Prescaler Range. This bit controls a fixed divide-by-eight prescaler in series with the variable * prescaler. It extends the range of the prescaler for those cases where a slower bit clock is * required. 0 Prescaler bypassed. 1 Prescaler used to divide clock by 8. */ //@{ #define BP_SSI_STCCR_PSR (17) //!< Bit position for SSI_STCCR_PSR. #define BM_SSI_STCCR_PSR (0x00020000) //!< Bit mask for SSI_STCCR_PSR. //! @brief Get value of SSI_STCCR_PSR from a register value. #define BG_SSI_STCCR_PSR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCCR_PSR) >> BP_SSI_STCCR_PSR) //! @brief Format value for bitfield SSI_STCCR_PSR. #define BF_SSI_STCCR_PSR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCCR_PSR) & BM_SSI_STCCR_PSR) #ifndef __LANGUAGE_ASM__ //! @brief Set the PSR field to a new value. #define BW_SSI_STCCR_PSR(x, v) (HW_SSI_STCCR_WR(x, (HW_SSI_STCCR_RD(x) & ~BM_SSI_STCCR_PSR) | BF_SSI_STCCR_PSR(v))) #endif //@} /*! @name Register SSI_STCCR, field DIV2[18] (RW) * * Divide By 2. This bit controls a divide-by-two divider in series with the rest of the prescalers. * 0 Divider bypassed. 1 Divider used to divide clock by 2. */ //@{ #define BP_SSI_STCCR_DIV2 (18) //!< Bit position for SSI_STCCR_DIV2. #define BM_SSI_STCCR_DIV2 (0x00040000) //!< Bit mask for SSI_STCCR_DIV2. //! @brief Get value of SSI_STCCR_DIV2 from a register value. #define BG_SSI_STCCR_DIV2(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STCCR_DIV2) >> BP_SSI_STCCR_DIV2) //! @brief Format value for bitfield SSI_STCCR_DIV2. #define BF_SSI_STCCR_DIV2(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STCCR_DIV2) & BM_SSI_STCCR_DIV2) #ifndef __LANGUAGE_ASM__ //! @brief Set the DIV2 field to a new value. #define BW_SSI_STCCR_DIV2(x, v) (HW_SSI_STCCR_WR(x, (HW_SSI_STCCR_RD(x) & ~BM_SSI_STCCR_DIV2) | BF_SSI_STCCR_DIV2(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_SRCCR - SSI Receive Clock Control Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SRCCR - SSI Receive Clock Control Register (RW) * * Reset value: 0x00040000 * * The SSI Transmit and Receive Control (SSI_STCCR and SSI_SRCCR) registers are 19-bit, read/write * control registers used to direct the operation of the SSI. The Clock Controller Module (CCM) can * source the SSI clock (SSI's sys clock-from CCM's ssi_clk_root) from multiple sources and perform * fractional division to support commonly used audio bit rates. The CCM can maintain the SSI's sys * clock frequency at a constant rate even in cases where the ipg_clk from CCM frequency changes. * These registers control the SSI clock generator, bit and frame sync rates, word length, and * number of words per frame for the serial data. The SSI_STCCR register is dedicated to the * transmit section, and the SSI_SRCCR register is dedicated to the receive section except in * Synchronous mode, in which the SSI_STCCR register controls both the receive and transmit * sections. Power-on reset clears all SSI_STCCR and SSI_SRCCR bits. SSI reset does not affect the * SSI_STCCR and SSI_SRCCR bits. The control bits are described in the following paragraphs. * Although the bit patterns of the SSI_STCCR and SSI_SRCCR registers are the same, the contents of * these two registers can be programmed differently. SSI Data Length WL3 WL2 WL1 WL0 Number of * Bits/Word Supported in Implementation 0 0 0 0 2 No 0 0 0 1 4 No 0 0 1 0 6 No 0 0 1 1 8 Yes 0 1 0 * 0 10 Yes 0 1 0 1 12 Yes 0 1 1 0 14 No 0 1 1 1 16 Yes 1 0 0 0 18 Yes 1 0 0 1 20 Yes 1 0 1 0 22 Yes * 1 0 1 1 24 Yes 1 1 0 0 26 No 1 1 0 1 28 No 1 1 1 0 30 No 1 1 1 1 32 No */ typedef union _hw_ssi_srccr { reg32_t U; struct _hw_ssi_srccr_bitfields { unsigned PM7_PM0 : 8; //!< [7:0] Prescaler Modulus Select. unsigned DC4_DC0 : 5; //!< [12:8] Frame Rate Divider Control. unsigned WL3_WL0 : 4; //!< [16:13] Word Length Control. unsigned PSR : 1; //!< [17] Prescaler Range. unsigned DIV2 : 1; //!< [18] Divide By 2. unsigned RESERVED0 : 13; //!< [31:19] Reserved } B; } hw_ssi_srccr_t; #endif /*! * @name Constants and macros for entire SSI_SRCCR register */ //@{ #define HW_SSI_SRCCR_ADDR(x) (REGS_SSI_BASE(x) + 0x28) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SRCCR(x) (*(volatile hw_ssi_srccr_t *) HW_SSI_SRCCR_ADDR(x)) #define HW_SSI_SRCCR_RD(x) (HW_SSI_SRCCR(x).U) #define HW_SSI_SRCCR_WR(x, v) (HW_SSI_SRCCR(x).U = (v)) #define HW_SSI_SRCCR_SET(x, v) (HW_SSI_SRCCR_WR(x, HW_SSI_SRCCR_RD(x) | (v))) #define HW_SSI_SRCCR_CLR(x, v) (HW_SSI_SRCCR_WR(x, HW_SSI_SRCCR_RD(x) & ~(v))) #define HW_SSI_SRCCR_TOG(x, v) (HW_SSI_SRCCR_WR(x, HW_SSI_SRCCR_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_SRCCR bitfields */ /*! @name Register SSI_SRCCR, field PM7_PM0[7:0] (RW) * * Prescaler Modulus Select. These bits control the prescale divider in the clock generator. This * prescaler is used only in Internal Clock mode to divide the internal clock. The bit clock output * is available at the clock port. A divide ratio from 1 to 256 (PM[7:0] = 0x00 to 0xFF) can be * selected. Refer to for details regarding settings. */ //@{ #define BP_SSI_SRCCR_PM7_PM0 (0) //!< Bit position for SSI_SRCCR_PM7_PM0. #define BM_SSI_SRCCR_PM7_PM0 (0x000000ff) //!< Bit mask for SSI_SRCCR_PM7_PM0. //! @brief Get value of SSI_SRCCR_PM7_PM0 from a register value. #define BG_SSI_SRCCR_PM7_PM0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCCR_PM7_PM0) >> BP_SSI_SRCCR_PM7_PM0) //! @brief Format value for bitfield SSI_SRCCR_PM7_PM0. #define BF_SSI_SRCCR_PM7_PM0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCCR_PM7_PM0) & BM_SSI_SRCCR_PM7_PM0) #ifndef __LANGUAGE_ASM__ //! @brief Set the PM7_PM0 field to a new value. #define BW_SSI_SRCCR_PM7_PM0(x, v) (HW_SSI_SRCCR_WR(x, (HW_SSI_SRCCR_RD(x) & ~BM_SSI_SRCCR_PM7_PM0) | BF_SSI_SRCCR_PM7_PM0(v))) #endif //@} /*! @name Register SSI_SRCCR, field DC4_DC0[12:8] (RW) * * Frame Rate Divider Control. These bits are used to control the divide ratio for the programmable * frame rate dividers. The divide ratio works on the word clock. In Normal mode, this ratio * determines the word transfer rate. In Network mode, this ratio sets the number of words per * frame. The divide ratio ranges from 1 to 32 in Normal mode and from 2 to 32 in Network mode. In * Normal mode, a divide ratio of 1 (DC=00000) provides continuous periodic data word transfer. A * bit-length frame sync must be used in this case. These bits can be programmed with values ranging * from "00000" to "11111" to control the number of words in a frame. */ //@{ #define BP_SSI_SRCCR_DC4_DC0 (8) //!< Bit position for SSI_SRCCR_DC4_DC0. #define BM_SSI_SRCCR_DC4_DC0 (0x00001f00) //!< Bit mask for SSI_SRCCR_DC4_DC0. //! @brief Get value of SSI_SRCCR_DC4_DC0 from a register value. #define BG_SSI_SRCCR_DC4_DC0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCCR_DC4_DC0) >> BP_SSI_SRCCR_DC4_DC0) //! @brief Format value for bitfield SSI_SRCCR_DC4_DC0. #define BF_SSI_SRCCR_DC4_DC0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCCR_DC4_DC0) & BM_SSI_SRCCR_DC4_DC0) #ifndef __LANGUAGE_ASM__ //! @brief Set the DC4_DC0 field to a new value. #define BW_SSI_SRCCR_DC4_DC0(x, v) (HW_SSI_SRCCR_WR(x, (HW_SSI_SRCCR_RD(x) & ~BM_SSI_SRCCR_DC4_DC0) | BF_SSI_SRCCR_DC4_DC0(v))) #endif //@} /*! @name Register SSI_SRCCR, field WL3_WL0[16:13] (RW) * * Word Length Control. These bits are used to control the length of the data words being * transferred by the SSI. These bits control the Word Length Divider in the Clock Generator. They * also control the frame sync pulse length when the FSL bit is cleared. In I2S Master mode, the SSI * works with a fixed word length of 32, and the WL bits are used to control the amount of valid * data in those 32 bits. In AC97 Mode of operation, if word length is set to any value other than * 16 bits, it will result in a word length of 20 bits. */ //@{ #define BP_SSI_SRCCR_WL3_WL0 (13) //!< Bit position for SSI_SRCCR_WL3_WL0. #define BM_SSI_SRCCR_WL3_WL0 (0x0001e000) //!< Bit mask for SSI_SRCCR_WL3_WL0. //! @brief Get value of SSI_SRCCR_WL3_WL0 from a register value. #define BG_SSI_SRCCR_WL3_WL0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCCR_WL3_WL0) >> BP_SSI_SRCCR_WL3_WL0) //! @brief Format value for bitfield SSI_SRCCR_WL3_WL0. #define BF_SSI_SRCCR_WL3_WL0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCCR_WL3_WL0) & BM_SSI_SRCCR_WL3_WL0) #ifndef __LANGUAGE_ASM__ //! @brief Set the WL3_WL0 field to a new value. #define BW_SSI_SRCCR_WL3_WL0(x, v) (HW_SSI_SRCCR_WR(x, (HW_SSI_SRCCR_RD(x) & ~BM_SSI_SRCCR_WL3_WL0) | BF_SSI_SRCCR_WL3_WL0(v))) #endif //@} /*! @name Register SSI_SRCCR, field PSR[17] (RW) * * Prescaler Range. This bit controls a fixed divide-by-eight prescaler in series with the variable * prescaler. It extends the range of the prescaler for those cases where a slower bit clock is * required. 0 Prescaler bypassed. 1 Prescaler used to divide clock by 8. */ //@{ #define BP_SSI_SRCCR_PSR (17) //!< Bit position for SSI_SRCCR_PSR. #define BM_SSI_SRCCR_PSR (0x00020000) //!< Bit mask for SSI_SRCCR_PSR. //! @brief Get value of SSI_SRCCR_PSR from a register value. #define BG_SSI_SRCCR_PSR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCCR_PSR) >> BP_SSI_SRCCR_PSR) //! @brief Format value for bitfield SSI_SRCCR_PSR. #define BF_SSI_SRCCR_PSR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCCR_PSR) & BM_SSI_SRCCR_PSR) #ifndef __LANGUAGE_ASM__ //! @brief Set the PSR field to a new value. #define BW_SSI_SRCCR_PSR(x, v) (HW_SSI_SRCCR_WR(x, (HW_SSI_SRCCR_RD(x) & ~BM_SSI_SRCCR_PSR) | BF_SSI_SRCCR_PSR(v))) #endif //@} /*! @name Register SSI_SRCCR, field DIV2[18] (RW) * * Divide By 2. This bit controls a divide-by-two divider in series with the rest of the prescalers. * 0 Divider bypassed. 1 Divider used to divide clock by 2. */ //@{ #define BP_SSI_SRCCR_DIV2 (18) //!< Bit position for SSI_SRCCR_DIV2. #define BM_SSI_SRCCR_DIV2 (0x00040000) //!< Bit mask for SSI_SRCCR_DIV2. //! @brief Get value of SSI_SRCCR_DIV2 from a register value. #define BG_SSI_SRCCR_DIV2(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRCCR_DIV2) >> BP_SSI_SRCCR_DIV2) //! @brief Format value for bitfield SSI_SRCCR_DIV2. #define BF_SSI_SRCCR_DIV2(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRCCR_DIV2) & BM_SSI_SRCCR_DIV2) #ifndef __LANGUAGE_ASM__ //! @brief Set the DIV2 field to a new value. #define BW_SSI_SRCCR_DIV2(x, v) (HW_SSI_SRCCR_WR(x, (HW_SSI_SRCCR_RD(x) & ~BM_SSI_SRCCR_DIV2) | BF_SSI_SRCCR_DIV2(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_SFCSR - SSI FIFO Control/Status Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SFCSR - SSI FIFO Control/Status Register (RW) * * Reset value: 0x00810081 * * The SSI FIFO Control / Status Register indicates the status of the Transmit FIFO Empty flag, with * different settings of the Transmit FIFO WaterMark bits and varying amounts of data in the Tx FIFO * . Status of Transmit FIFO Empty Flag Transmit FIFO Watermark (TFWM) Number of data in Tx-Fifo 1 2 * 3 4 5 6 7 8 9 10 11 12 13 14 15 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 2 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 3 * 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 4 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 5 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 6 1 * 1 1 1 1 1 1 1 1 0 0 0 0 0 0 7 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 8 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 9 1 1 * 1 1 1 1 0 0 0 0 0 0 0 0 0 10 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 11 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 12 1 * 1 1 0 0 0 0 0 0 0 0 0 0 0 0 13 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 14 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15 * 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 */ typedef union _hw_ssi_sfcsr { reg32_t U; struct _hw_ssi_sfcsr_bitfields { unsigned TFWM0 : 4; //!< [3:0] Transmit FIFO Empty WaterMark 0. unsigned RFWM0 : 4; //!< [7:4] Receive FIFO Full WaterMark 0. unsigned TFCNT0 : 4; //!< [11:8] Transmit FIFO Counter 0. unsigned RFCNT0 : 4; //!< [15:12] Receive FIFO Counter 0. unsigned TFWM1 : 4; //!< [19:16] Transmit FIFO Empty WaterMark 1. unsigned RFWM1 : 4; //!< [23:20] Receive FIFO Full WaterMark 1. unsigned TFCNT1 : 4; //!< [27:24] Transmit FIFO Counter1. unsigned RFCNT1 : 4; //!< [31:28] Receive FIFO Counter1. } B; } hw_ssi_sfcsr_t; #endif /*! * @name Constants and macros for entire SSI_SFCSR register */ //@{ #define HW_SSI_SFCSR_ADDR(x) (REGS_SSI_BASE(x) + 0x2c) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SFCSR(x) (*(volatile hw_ssi_sfcsr_t *) HW_SSI_SFCSR_ADDR(x)) #define HW_SSI_SFCSR_RD(x) (HW_SSI_SFCSR(x).U) #define HW_SSI_SFCSR_WR(x, v) (HW_SSI_SFCSR(x).U = (v)) #define HW_SSI_SFCSR_SET(x, v) (HW_SSI_SFCSR_WR(x, HW_SSI_SFCSR_RD(x) | (v))) #define HW_SSI_SFCSR_CLR(x, v) (HW_SSI_SFCSR_WR(x, HW_SSI_SFCSR_RD(x) & ~(v))) #define HW_SSI_SFCSR_TOG(x, v) (HW_SSI_SFCSR_WR(x, HW_SSI_SFCSR_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_SFCSR bitfields */ /*! @name Register SSI_SFCSR, field TFWM0[3:0] (RW) * * Transmit FIFO Empty WaterMark 0. These bits control the threshold at which the TFE0 flag will be * set. The TFE0 flag is set whenever the empty slots in Tx FIFO exceed or are equal to the selected * threshold. See SSI_SFCSR_bf4 for details regarding settings for transmit FIFO watermark bits. */ //@{ #define BP_SSI_SFCSR_TFWM0 (0) //!< Bit position for SSI_SFCSR_TFWM0. #define BM_SSI_SFCSR_TFWM0 (0x0000000f) //!< Bit mask for SSI_SFCSR_TFWM0. //! @brief Get value of SSI_SFCSR_TFWM0 from a register value. #define BG_SSI_SFCSR_TFWM0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SFCSR_TFWM0) >> BP_SSI_SFCSR_TFWM0) //! @brief Format value for bitfield SSI_SFCSR_TFWM0. #define BF_SSI_SFCSR_TFWM0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SFCSR_TFWM0) & BM_SSI_SFCSR_TFWM0) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFWM0 field to a new value. #define BW_SSI_SFCSR_TFWM0(x, v) (HW_SSI_SFCSR_WR(x, (HW_SSI_SFCSR_RD(x) & ~BM_SSI_SFCSR_TFWM0) | BF_SSI_SFCSR_TFWM0(v))) #endif //@} /*! @name Register SSI_SFCSR, field RFWM0[7:4] (RW) * * Receive FIFO Full WaterMark 0. These bits control the threshold at which the RFF0 flag will be * set. The RFF0 flag is set whenever the data level in Rx FIFO 0 reaches the selected threshold. * See SSI_SFCSR_bf3 for details regarding settings for receive FIFO watermark bits. */ //@{ #define BP_SSI_SFCSR_RFWM0 (4) //!< Bit position for SSI_SFCSR_RFWM0. #define BM_SSI_SFCSR_RFWM0 (0x000000f0) //!< Bit mask for SSI_SFCSR_RFWM0. //! @brief Get value of SSI_SFCSR_RFWM0 from a register value. #define BG_SSI_SFCSR_RFWM0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SFCSR_RFWM0) >> BP_SSI_SFCSR_RFWM0) //! @brief Format value for bitfield SSI_SFCSR_RFWM0. #define BF_SSI_SFCSR_RFWM0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SFCSR_RFWM0) & BM_SSI_SFCSR_RFWM0) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFWM0 field to a new value. #define BW_SSI_SFCSR_RFWM0(x, v) (HW_SSI_SFCSR_WR(x, (HW_SSI_SFCSR_RD(x) & ~BM_SSI_SFCSR_RFWM0) | BF_SSI_SFCSR_RFWM0(v))) #endif //@} /*! @name Register SSI_SFCSR, field TFCNT0[11:8] (RW) * * Transmit FIFO Counter 0. These bits indicate the number of data words in Transmit FIFO 0. See * SSI_SFCSR_bf2 for details regarding settings for transmit FIFO counter bits. */ //@{ #define BP_SSI_SFCSR_TFCNT0 (8) //!< Bit position for SSI_SFCSR_TFCNT0. #define BM_SSI_SFCSR_TFCNT0 (0x00000f00) //!< Bit mask for SSI_SFCSR_TFCNT0. //! @brief Get value of SSI_SFCSR_TFCNT0 from a register value. #define BG_SSI_SFCSR_TFCNT0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SFCSR_TFCNT0) >> BP_SSI_SFCSR_TFCNT0) //! @brief Format value for bitfield SSI_SFCSR_TFCNT0. #define BF_SSI_SFCSR_TFCNT0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SFCSR_TFCNT0) & BM_SSI_SFCSR_TFCNT0) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFCNT0 field to a new value. #define BW_SSI_SFCSR_TFCNT0(x, v) (HW_SSI_SFCSR_WR(x, (HW_SSI_SFCSR_RD(x) & ~BM_SSI_SFCSR_TFCNT0) | BF_SSI_SFCSR_TFCNT0(v))) #endif //@} /*! @name Register SSI_SFCSR, field RFCNT0[15:12] (RW) * * Receive FIFO Counter 0. These bits indicate the number of data words in Receive FIFO 0. See * SSI_SFCSR_bf1 for details regarding settings for receive FIFO counter bits. */ //@{ #define BP_SSI_SFCSR_RFCNT0 (12) //!< Bit position for SSI_SFCSR_RFCNT0. #define BM_SSI_SFCSR_RFCNT0 (0x0000f000) //!< Bit mask for SSI_SFCSR_RFCNT0. //! @brief Get value of SSI_SFCSR_RFCNT0 from a register value. #define BG_SSI_SFCSR_RFCNT0(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SFCSR_RFCNT0) >> BP_SSI_SFCSR_RFCNT0) //! @brief Format value for bitfield SSI_SFCSR_RFCNT0. #define BF_SSI_SFCSR_RFCNT0(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SFCSR_RFCNT0) & BM_SSI_SFCSR_RFCNT0) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFCNT0 field to a new value. #define BW_SSI_SFCSR_RFCNT0(x, v) (HW_SSI_SFCSR_WR(x, (HW_SSI_SFCSR_RD(x) & ~BM_SSI_SFCSR_RFCNT0) | BF_SSI_SFCSR_RFCNT0(v))) #endif //@} /*! @name Register SSI_SFCSR, field TFWM1[19:16] (RW) * * Transmit FIFO Empty WaterMark 1. These bits control the threshold at which the TFE1 flag will be * set. The TFE1 flag is set whenever the empty slots in Tx FIFO exceed or are equal to the selected * threshold. * * Values: * - 0000 - Reserved * - 0001 - TFE set when there are more than or equal to 1 empty slots in Transmit FIFO (default). Transmit FIFO * empty is set when TxFIFO <= 14 data. * - 0010 - TFE set when there are more than or equal to 2 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 13 data. * - 0011 - TFE set when there are more than or equal to 3 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 12 data. * - 0100 - TFE set when there are more than or equal to 4 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 11 data. * - 0101 - TFE set when there are more than or equal to 5 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 10 data. * - 0110 - TFE set when there are more than or equal to 6 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 9 data. * - 0111 - TFE set when there are more than or equal to 7 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 8 data. * - 1000 - TFE set when there are more than or equal to 8 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 7 data. * - 1001 - TFE set when there are more than or equal to 9 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 6 data. * - 1010 - TFE set when there are more than or equal to 10 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 5 data. * - 1011 - TFE set when there are more than or equal to 11 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 4 data. * - 1100 - TFE set when there are more than or equal to 12 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 3 data. * - 1101 - TFE set when there are more than or equal to 13 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 2 data. * - 1110 - TFE set when there are more than or equal to 14 empty slots in Transmit FIFO. Transmit FIFO empty is * set when TxFIFO <= 1 data. * - 1111 - TFE set when there are 15 empty slots in Transmit FIFO. Transmit FIFO empty is set when TxFIFO = 0 * data. */ //@{ #define BP_SSI_SFCSR_TFWM1 (16) //!< Bit position for SSI_SFCSR_TFWM1. #define BM_SSI_SFCSR_TFWM1 (0x000f0000) //!< Bit mask for SSI_SFCSR_TFWM1. //! @brief Get value of SSI_SFCSR_TFWM1 from a register value. #define BG_SSI_SFCSR_TFWM1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SFCSR_TFWM1) >> BP_SSI_SFCSR_TFWM1) //! @brief Format value for bitfield SSI_SFCSR_TFWM1. #define BF_SSI_SFCSR_TFWM1(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SFCSR_TFWM1) & BM_SSI_SFCSR_TFWM1) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFWM1 field to a new value. #define BW_SSI_SFCSR_TFWM1(x, v) (HW_SSI_SFCSR_WR(x, (HW_SSI_SFCSR_RD(x) & ~BM_SSI_SFCSR_TFWM1) | BF_SSI_SFCSR_TFWM1(v))) #endif //@} /*! @name Register SSI_SFCSR, field RFWM1[23:20] (RW) * * Receive FIFO Full WaterMark 1. These bits control the threshold at which the RFF1 flag will be * set. The RFF1 flag is set whenever the data level in Rx FIFO 1 reaches the selected threshold. * * Values: * - 0000 - Reserved * - 0001 - RFF set when at least one data word has been written to the Receive FIFO. Set when RxFIFO = 1,2..... * 15 data words * - 0010 - RFF set when 2 or more data words have been written to the Receive FIFO. Set when RxFIFO = 2,3..... * 15 data words * - 0011 - RFF set when 3 or more data words have been written to the Receive FIFO. Set when RxFIFO = 3,4..... * 15 data words * - 0100 - RFF set when 4 or more data words have been written to the Receive FIFO. Set when RxFIFO = 4,5..... * 15 data words * - 0101 - RFF set when 5 or more data words have been written to the Receive FIFO. Set when RxFIFO = 5,6..... * 15 data words * - 0110 - RFF set when 6 or more data words have been written to the Receive.. Set when RxFIFO = 6,7 ......15 * data words * - 0111 - RFF set when 7 or more data words have been written to the Receive FIFO. Set when RxFIFO = 7,8 * ......15 data words * - 1000 - RFF set when 8 or more data words have been written to the Receive FIFO. Set when RxFIFO = 8,9..... * 15 data words * - 1001 - RFF set when 9 or more data words have been written to the Receive FIFO. Set when RxFIFO = * 9,10.....15 data words * - 1010 - RFF set when 10 or more data words have been written to the Receive FIFO. Set when RxFIFO = * 10,11.....15 data words * - 1011 - RFF set when 11 or more data words have been written to the Receive FIFO. Set when RxFIFO = * 11,12.....15 data words * - 1100 - RFF set when 12 or more data words have been written to the Receive FIFO. Set when RxFIFO = * 12,13.....15 data words * - 1101 - RFF set when 13 or more data words have been written to the Receive FIFO. Set when RxFIFO = * 13,14,15data words * - 1110 - RFF set when 14 or more data words have been written to the Receive FIFO. Set when RxFIFO = 14,15 * data words * - 1111 - RFF set when 15 data words have been written to the Receive FIFO (default). Set when RxFIFO = 15 * data words */ //@{ #define BP_SSI_SFCSR_RFWM1 (20) //!< Bit position for SSI_SFCSR_RFWM1. #define BM_SSI_SFCSR_RFWM1 (0x00f00000) //!< Bit mask for SSI_SFCSR_RFWM1. //! @brief Get value of SSI_SFCSR_RFWM1 from a register value. #define BG_SSI_SFCSR_RFWM1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SFCSR_RFWM1) >> BP_SSI_SFCSR_RFWM1) //! @brief Format value for bitfield SSI_SFCSR_RFWM1. #define BF_SSI_SFCSR_RFWM1(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SFCSR_RFWM1) & BM_SSI_SFCSR_RFWM1) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFWM1 field to a new value. #define BW_SSI_SFCSR_RFWM1(x, v) (HW_SSI_SFCSR_WR(x, (HW_SSI_SFCSR_RD(x) & ~BM_SSI_SFCSR_RFWM1) | BF_SSI_SFCSR_RFWM1(v))) #endif //@} /*! @name Register SSI_SFCSR, field TFCNT1[27:24] (RW) * * Transmit FIFO Counter1. These bits indicate the number of data words in Transmit FIFO. * * Values: * - 0000 - 0 data word in transmit FIFO * - 0001 - 1 data word in transmit FIFO * - 0010 - 2 data word in transmit FIFO * - 0011 - 3 data word in transmit FIFO * - 0100 - 4 data word in transmit FIFO * - 0101 - 5 data word in transmit FIFO * - 0110 - 6 data word in transmit FIFO * - 0111 - 7 data word in transmit FIFO * - 1000 - 8 data word in transmit FIFO * - 1001 - 9 data word in transmit FIFO * - 1010 - 10 data word in transmit FIFO * - 1011 - 11 data word in transmit FIFO * - 1100 - 12 data word in transmit FIFO * - 1101 - 13 data word in transmit FIFO * - 1110 - 14 data word in transmit FIFO * - 1111 - 15 data word in transmit FIFO */ //@{ #define BP_SSI_SFCSR_TFCNT1 (24) //!< Bit position for SSI_SFCSR_TFCNT1. #define BM_SSI_SFCSR_TFCNT1 (0x0f000000) //!< Bit mask for SSI_SFCSR_TFCNT1. //! @brief Get value of SSI_SFCSR_TFCNT1 from a register value. #define BG_SSI_SFCSR_TFCNT1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SFCSR_TFCNT1) >> BP_SSI_SFCSR_TFCNT1) //! @brief Format value for bitfield SSI_SFCSR_TFCNT1. #define BF_SSI_SFCSR_TFCNT1(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SFCSR_TFCNT1) & BM_SSI_SFCSR_TFCNT1) #ifndef __LANGUAGE_ASM__ //! @brief Set the TFCNT1 field to a new value. #define BW_SSI_SFCSR_TFCNT1(x, v) (HW_SSI_SFCSR_WR(x, (HW_SSI_SFCSR_RD(x) & ~BM_SSI_SFCSR_TFCNT1) | BF_SSI_SFCSR_TFCNT1(v))) #endif //@} /*! @name Register SSI_SFCSR, field RFCNT1[31:28] (RW) * * Receive FIFO Counter1. These bits indicate the number of data words in Receive FIFO 1. * * Values: * - 0000 - 0 data word in receive FIFO * - 0001 - 1 data word in receive FIFO * - 0010 - 2 data word in receive FIFO * - 0011 - 3 data word in receive FIFO * - 0100 - 4 data word in receive FIFO * - 0101 - 5 data word in receive FIFO * - 0110 - 6 data word in receive FIFO * - 0111 - 7 data word in receive FIFO * - 1000 - 8 data word in receive FIFO * - 1001 - 9 data word in receive FIFO * - 1010 - 10 data word in receive FIFO * - 1011 - 11 data word in receive FIFO * - 1100 - 12 data word in receive FIFO * - 1101 - 13 data word in receive FIFO * - 1110 - 14 data word in receive FIFO * - 1111 - 15 data word in receive FIFO */ //@{ #define BP_SSI_SFCSR_RFCNT1 (28) //!< Bit position for SSI_SFCSR_RFCNT1. #define BM_SSI_SFCSR_RFCNT1 (0xf0000000) //!< Bit mask for SSI_SFCSR_RFCNT1. //! @brief Get value of SSI_SFCSR_RFCNT1 from a register value. #define BG_SSI_SFCSR_RFCNT1(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SFCSR_RFCNT1) >> BP_SSI_SFCSR_RFCNT1) //! @brief Format value for bitfield SSI_SFCSR_RFCNT1. #define BF_SSI_SFCSR_RFCNT1(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SFCSR_RFCNT1) & BM_SSI_SFCSR_RFCNT1) #ifndef __LANGUAGE_ASM__ //! @brief Set the RFCNT1 field to a new value. #define BW_SSI_SFCSR_RFCNT1(x, v) (HW_SSI_SFCSR_WR(x, (HW_SSI_SFCSR_RD(x) & ~BM_SSI_SFCSR_RFCNT1) | BF_SSI_SFCSR_RFCNT1(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_SACNT - SSI AC97 Control Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SACNT - SSI AC97 Control Register (RW) * * Reset value: 0x00000000 */ typedef union _hw_ssi_sacnt { reg32_t U; struct _hw_ssi_sacnt_bitfields { unsigned AC97EN : 1; //!< [0] AC97 Mode Enable. unsigned FV : 1; //!< [1] Fixed/Variable Operation. unsigned TIF : 1; //!< [2] Tag in FIFO. unsigned RD : 1; //!< [3] Read Command. unsigned WR : 1; //!< [4] Write Command. unsigned FRDIV : 6; //!< [10:5] Frame Rate Divider. unsigned RESERVED0 : 21; //!< [31:11] Reserved } B; } hw_ssi_sacnt_t; #endif /*! * @name Constants and macros for entire SSI_SACNT register */ //@{ #define HW_SSI_SACNT_ADDR(x) (REGS_SSI_BASE(x) + 0x38) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SACNT(x) (*(volatile hw_ssi_sacnt_t *) HW_SSI_SACNT_ADDR(x)) #define HW_SSI_SACNT_RD(x) (HW_SSI_SACNT(x).U) #define HW_SSI_SACNT_WR(x, v) (HW_SSI_SACNT(x).U = (v)) #define HW_SSI_SACNT_SET(x, v) (HW_SSI_SACNT_WR(x, HW_SSI_SACNT_RD(x) | (v))) #define HW_SSI_SACNT_CLR(x, v) (HW_SSI_SACNT_WR(x, HW_SSI_SACNT_RD(x) & ~(v))) #define HW_SSI_SACNT_TOG(x, v) (HW_SSI_SACNT_WR(x, HW_SSI_SACNT_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_SACNT bitfields */ /*! @name Register SSI_SACNT, field AC97EN[0] (RW) * * AC97 Mode Enable. This bit is used to enable SSI AC97 operation. Refer to for details of AC97 * operation. * * Values: * - 0 - AC97 mode disabled. * - 1 - SSI in AC97 mode. */ //@{ #define BP_SSI_SACNT_AC97EN (0) //!< Bit position for SSI_SACNT_AC97EN. #define BM_SSI_SACNT_AC97EN (0x00000001) //!< Bit mask for SSI_SACNT_AC97EN. //! @brief Get value of SSI_SACNT_AC97EN from a register value. #define BG_SSI_SACNT_AC97EN(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SACNT_AC97EN) >> BP_SSI_SACNT_AC97EN) //! @brief Format value for bitfield SSI_SACNT_AC97EN. #define BF_SSI_SACNT_AC97EN(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SACNT_AC97EN) & BM_SSI_SACNT_AC97EN) #ifndef __LANGUAGE_ASM__ //! @brief Set the AC97EN field to a new value. #define BW_SSI_SACNT_AC97EN(x, v) (HW_SSI_SACNT_WR(x, (HW_SSI_SACNT_RD(x) & ~BM_SSI_SACNT_AC97EN) | BF_SSI_SACNT_AC97EN(v))) #endif //@} /*! @name Register SSI_SACNT, field FV[1] (RW) * * Fixed/Variable Operation. This bit selects whether the SSI is in AC97 Fixed mode or AC97 Variable * mode. * * Values: * - FIXED = 0 - AC97 Fixed Mode. * - VARIABLE = 1 - AC97 Variable Mode. */ //@{ #define BP_SSI_SACNT_FV (1) //!< Bit position for SSI_SACNT_FV. #define BM_SSI_SACNT_FV (0x00000002) //!< Bit mask for SSI_SACNT_FV. //! @brief Get value of SSI_SACNT_FV from a register value. #define BG_SSI_SACNT_FV(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SACNT_FV) >> BP_SSI_SACNT_FV) //! @brief Format value for bitfield SSI_SACNT_FV. #define BF_SSI_SACNT_FV(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SACNT_FV) & BM_SSI_SACNT_FV) #ifndef __LANGUAGE_ASM__ //! @brief Set the FV field to a new value. #define BW_SSI_SACNT_FV(x, v) (HW_SSI_SACNT_WR(x, (HW_SSI_SACNT_RD(x) & ~BM_SSI_SACNT_FV) | BF_SSI_SACNT_FV(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SACNT_FV_V(v) BF_SSI_SACNT_FV(BV_SSI_SACNT_FV__##v) #define BV_SSI_SACNT_FV__FIXED (0x0) //!< AC97 Fixed Mode. #define BV_SSI_SACNT_FV__VARIABLE (0x1) //!< AC97 Variable Mode. //@} /*! @name Register SSI_SACNT, field TIF[2] (RW) * * Tag in FIFO. This bit controls the destination of the information received in AC97 tag slot (Slot * #0). * * Values: * - SATAG_REGISTER = 0 - Tag info stored in SATAG register. * - RX_FIFO0 = 1 - Tag info stored in Rx FIFO 0. */ //@{ #define BP_SSI_SACNT_TIF (2) //!< Bit position for SSI_SACNT_TIF. #define BM_SSI_SACNT_TIF (0x00000004) //!< Bit mask for SSI_SACNT_TIF. //! @brief Get value of SSI_SACNT_TIF from a register value. #define BG_SSI_SACNT_TIF(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SACNT_TIF) >> BP_SSI_SACNT_TIF) //! @brief Format value for bitfield SSI_SACNT_TIF. #define BF_SSI_SACNT_TIF(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SACNT_TIF) & BM_SSI_SACNT_TIF) #ifndef __LANGUAGE_ASM__ //! @brief Set the TIF field to a new value. #define BW_SSI_SACNT_TIF(x, v) (HW_SSI_SACNT_WR(x, (HW_SSI_SACNT_RD(x) & ~BM_SSI_SACNT_TIF) | BF_SSI_SACNT_TIF(v))) #endif //! @brief Macro to simplify usage of value macros. #define BF_SSI_SACNT_TIF_V(v) BF_SSI_SACNT_TIF(BV_SSI_SACNT_TIF__##v) #define BV_SSI_SACNT_TIF__SATAG_REGISTER (0x0) //!< Tag info stored in SATAG register. #define BV_SSI_SACNT_TIF__RX_FIFO0 (0x1) //!< Tag info stored in Rx FIFO 0. //@} /*! @name Register SSI_SACNT, field RD[3] (RW) * * Read Command. This bit specifies whether the next frame will carry an AC97 Read Command or not. * The programmer should take care that only one of the bits (WR or RD) is set at a time. When this * bit is set, the corresponding tag bit (corresponding to Command Address slot of the next Tx * frame) is automatically set. This bit is automatically cleared by the SSI after completing * transmission of a frame. * * Values: * - 0 - Next frame will not have a Read Command. * - 1 - Next frame will have a Read Command. */ //@{ #define BP_SSI_SACNT_RD (3) //!< Bit position for SSI_SACNT_RD. #define BM_SSI_SACNT_RD (0x00000008) //!< Bit mask for SSI_SACNT_RD. //! @brief Get value of SSI_SACNT_RD from a register value. #define BG_SSI_SACNT_RD(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SACNT_RD) >> BP_SSI_SACNT_RD) //! @brief Format value for bitfield SSI_SACNT_RD. #define BF_SSI_SACNT_RD(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SACNT_RD) & BM_SSI_SACNT_RD) #ifndef __LANGUAGE_ASM__ //! @brief Set the RD field to a new value. #define BW_SSI_SACNT_RD(x, v) (HW_SSI_SACNT_WR(x, (HW_SSI_SACNT_RD(x) & ~BM_SSI_SACNT_RD) | BF_SSI_SACNT_RD(v))) #endif //@} /*! @name Register SSI_SACNT, field WR[4] (RW) * * Write Command. This bit specifies whether the next frame will carry an AC97 Write Command or not. * The programmer should take care that only one of the bits (WR or RD) is set at a time. When this * bit is set, the corresponding tag bits (corresponding to Command Address and Command Data slots * of the next Tx frame) are automatically set. This bit is automatically cleared by the SSI after * completing transmission of a frame. * * Values: * - 0 - Next frame will not have a Write Command. * - 1 - Next frame will have a Write Command. */ //@{ #define BP_SSI_SACNT_WR (4) //!< Bit position for SSI_SACNT_WR. #define BM_SSI_SACNT_WR (0x00000010) //!< Bit mask for SSI_SACNT_WR. //! @brief Get value of SSI_SACNT_WR from a register value. #define BG_SSI_SACNT_WR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SACNT_WR) >> BP_SSI_SACNT_WR) //! @brief Format value for bitfield SSI_SACNT_WR. #define BF_SSI_SACNT_WR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SACNT_WR) & BM_SSI_SACNT_WR) #ifndef __LANGUAGE_ASM__ //! @brief Set the WR field to a new value. #define BW_SSI_SACNT_WR(x, v) (HW_SSI_SACNT_WR(x, (HW_SSI_SACNT_RD(x) & ~BM_SSI_SACNT_WR) | BF_SSI_SACNT_WR(v))) #endif //@} /*! @name Register SSI_SACNT, field FRDIV[10:5] (RW) * * Frame Rate Divider. These bits control the frequency of AC97 data transmission/reception. They * are programmed with the number of frames for which the SSI should be idle, after operating in one * frame. Through these bits, AC97 frequency of operation, from 48 KHz (000000) to 1 KHz (101111) * can be achieved. Sample Value: 001010 (10 Decimal) = SSI will operate once every 11 frames. */ //@{ #define BP_SSI_SACNT_FRDIV (5) //!< Bit position for SSI_SACNT_FRDIV. #define BM_SSI_SACNT_FRDIV (0x000007e0) //!< Bit mask for SSI_SACNT_FRDIV. //! @brief Get value of SSI_SACNT_FRDIV from a register value. #define BG_SSI_SACNT_FRDIV(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SACNT_FRDIV) >> BP_SSI_SACNT_FRDIV) //! @brief Format value for bitfield SSI_SACNT_FRDIV. #define BF_SSI_SACNT_FRDIV(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SACNT_FRDIV) & BM_SSI_SACNT_FRDIV) #ifndef __LANGUAGE_ASM__ //! @brief Set the FRDIV field to a new value. #define BW_SSI_SACNT_FRDIV(x, v) (HW_SSI_SACNT_WR(x, (HW_SSI_SACNT_RD(x) & ~BM_SSI_SACNT_FRDIV) | BF_SSI_SACNT_FRDIV(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_SACADD - SSI AC97 Command Address Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SACADD - SSI AC97 Command Address Register (RW) * * Reset value: 0x00000000 */ typedef union _hw_ssi_sacadd { reg32_t U; struct _hw_ssi_sacadd_bitfields { unsigned SACADD : 19; //!< [18:0] AC97 Command Address. unsigned RESERVED0 : 13; //!< [31:19] Reserved } B; } hw_ssi_sacadd_t; #endif /*! * @name Constants and macros for entire SSI_SACADD register */ //@{ #define HW_SSI_SACADD_ADDR(x) (REGS_SSI_BASE(x) + 0x3c) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SACADD(x) (*(volatile hw_ssi_sacadd_t *) HW_SSI_SACADD_ADDR(x)) #define HW_SSI_SACADD_RD(x) (HW_SSI_SACADD(x).U) #define HW_SSI_SACADD_WR(x, v) (HW_SSI_SACADD(x).U = (v)) #define HW_SSI_SACADD_SET(x, v) (HW_SSI_SACADD_WR(x, HW_SSI_SACADD_RD(x) | (v))) #define HW_SSI_SACADD_CLR(x, v) (HW_SSI_SACADD_WR(x, HW_SSI_SACADD_RD(x) & ~(v))) #define HW_SSI_SACADD_TOG(x, v) (HW_SSI_SACADD_WR(x, HW_SSI_SACADD_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_SACADD bitfields */ /*! @name Register SSI_SACADD, field SACADD[18:0] (RW) * * AC97 Command Address. These bits store the Command Address Slot information (bit 19 of the slot * is sent in accordance with the Read and Write Command bits in SSI_SACNT register). These bits can * be updated by a direct write from the Core. They are also updated with the information received * in the incoming Command Address Slot. If the contents of these bits change due to an update, the * CMDAU bit in SISR is set. */ //@{ #define BP_SSI_SACADD_SACADD (0) //!< Bit position for SSI_SACADD_SACADD. #define BM_SSI_SACADD_SACADD (0x0007ffff) //!< Bit mask for SSI_SACADD_SACADD. //! @brief Get value of SSI_SACADD_SACADD from a register value. #define BG_SSI_SACADD_SACADD(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SACADD_SACADD) >> BP_SSI_SACADD_SACADD) //! @brief Format value for bitfield SSI_SACADD_SACADD. #define BF_SSI_SACADD_SACADD(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SACADD_SACADD) & BM_SSI_SACADD_SACADD) #ifndef __LANGUAGE_ASM__ //! @brief Set the SACADD field to a new value. #define BW_SSI_SACADD_SACADD(x, v) (HW_SSI_SACADD_WR(x, (HW_SSI_SACADD_RD(x) & ~BM_SSI_SACADD_SACADD) | BF_SSI_SACADD_SACADD(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_SACDAT - SSI AC97 Command Data Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SACDAT - SSI AC97 Command Data Register (RW) * * Reset value: 0x00000000 */ typedef union _hw_ssi_sacdat { reg32_t U; struct _hw_ssi_sacdat_bitfields { unsigned SACDAT : 20; //!< [19:0] AC97 Command Data. unsigned RESERVED0 : 12; //!< [31:20] Reserved } B; } hw_ssi_sacdat_t; #endif /*! * @name Constants and macros for entire SSI_SACDAT register */ //@{ #define HW_SSI_SACDAT_ADDR(x) (REGS_SSI_BASE(x) + 0x40) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SACDAT(x) (*(volatile hw_ssi_sacdat_t *) HW_SSI_SACDAT_ADDR(x)) #define HW_SSI_SACDAT_RD(x) (HW_SSI_SACDAT(x).U) #define HW_SSI_SACDAT_WR(x, v) (HW_SSI_SACDAT(x).U = (v)) #define HW_SSI_SACDAT_SET(x, v) (HW_SSI_SACDAT_WR(x, HW_SSI_SACDAT_RD(x) | (v))) #define HW_SSI_SACDAT_CLR(x, v) (HW_SSI_SACDAT_WR(x, HW_SSI_SACDAT_RD(x) & ~(v))) #define HW_SSI_SACDAT_TOG(x, v) (HW_SSI_SACDAT_WR(x, HW_SSI_SACDAT_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_SACDAT bitfields */ /*! @name Register SSI_SACDAT, field SACDAT[19:0] (RW) * * AC97 Command Data. The outgoing Command Data Slot carries the information contained in these * bits. These bits can be updated by a direct write from the Core. They are also updated with the * information received in the incoming Command Data Slot. If the contents of these bits change due * to an update, the CMDDU bit in SISR is set. These bits are transmitted only during AC97 Write * Command. During AC97 Read Command, 0x00000 is transmitted in time slot #2. */ //@{ #define BP_SSI_SACDAT_SACDAT (0) //!< Bit position for SSI_SACDAT_SACDAT. #define BM_SSI_SACDAT_SACDAT (0x000fffff) //!< Bit mask for SSI_SACDAT_SACDAT. //! @brief Get value of SSI_SACDAT_SACDAT from a register value. #define BG_SSI_SACDAT_SACDAT(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SACDAT_SACDAT) >> BP_SSI_SACDAT_SACDAT) //! @brief Format value for bitfield SSI_SACDAT_SACDAT. #define BF_SSI_SACDAT_SACDAT(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SACDAT_SACDAT) & BM_SSI_SACDAT_SACDAT) #ifndef __LANGUAGE_ASM__ //! @brief Set the SACDAT field to a new value. #define BW_SSI_SACDAT_SACDAT(x, v) (HW_SSI_SACDAT_WR(x, (HW_SSI_SACDAT_RD(x) & ~BM_SSI_SACDAT_SACDAT) | BF_SSI_SACDAT_SACDAT(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_SATAG - SSI AC97 Tag Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SATAG - SSI AC97 Tag Register (RW) * * Reset value: 0x00000000 */ typedef union _hw_ssi_satag { reg32_t U; struct _hw_ssi_satag_bitfields { unsigned SATAG : 16; //!< [15:0] AC97 Tag Value. unsigned RESERVED0 : 16; //!< [31:16] Reserved } B; } hw_ssi_satag_t; #endif /*! * @name Constants and macros for entire SSI_SATAG register */ //@{ #define HW_SSI_SATAG_ADDR(x) (REGS_SSI_BASE(x) + 0x44) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SATAG(x) (*(volatile hw_ssi_satag_t *) HW_SSI_SATAG_ADDR(x)) #define HW_SSI_SATAG_RD(x) (HW_SSI_SATAG(x).U) #define HW_SSI_SATAG_WR(x, v) (HW_SSI_SATAG(x).U = (v)) #define HW_SSI_SATAG_SET(x, v) (HW_SSI_SATAG_WR(x, HW_SSI_SATAG_RD(x) | (v))) #define HW_SSI_SATAG_CLR(x, v) (HW_SSI_SATAG_WR(x, HW_SSI_SATAG_RD(x) & ~(v))) #define HW_SSI_SATAG_TOG(x, v) (HW_SSI_SATAG_WR(x, HW_SSI_SATAG_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_SATAG bitfields */ /*! @name Register SSI_SATAG, field SATAG[15:0] (RW) * * AC97 Tag Value. Writing to this register (by the Core) sets the value of the Tx-Tag in AC97 fixed * mode of operation. On a read, the Core gets the Rx-Tag Value received (in the last frame) from * the Codec. If TIF bit in SSI_SACNT register is set, the TAG value is also stored in Rx-FIFO in * addition to SATAG register. When the received Tag value changes, the RXT bit in SISR register is * set. Bits SATAG[1:0] convey the Codec -ID. In current implementation only Primary Codecs are * supported. Thus writing value 2'b00 to this field is mandatory. */ //@{ #define BP_SSI_SATAG_SATAG (0) //!< Bit position for SSI_SATAG_SATAG. #define BM_SSI_SATAG_SATAG (0x0000ffff) //!< Bit mask for SSI_SATAG_SATAG. //! @brief Get value of SSI_SATAG_SATAG from a register value. #define BG_SSI_SATAG_SATAG(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SATAG_SATAG) >> BP_SSI_SATAG_SATAG) //! @brief Format value for bitfield SSI_SATAG_SATAG. #define BF_SSI_SATAG_SATAG(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SATAG_SATAG) & BM_SSI_SATAG_SATAG) #ifndef __LANGUAGE_ASM__ //! @brief Set the SATAG field to a new value. #define BW_SSI_SATAG_SATAG(x, v) (HW_SSI_SATAG_WR(x, (HW_SSI_SATAG_RD(x) & ~BM_SSI_SATAG_SATAG) | BF_SSI_SATAG_SATAG(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_STMSK - SSI Transmit Time Slot Mask Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_STMSK - SSI Transmit Time Slot Mask Register (RW) * * Reset value: 0x00000000 */ typedef union _hw_ssi_stmsk { reg32_t U; struct _hw_ssi_stmsk_bitfields { unsigned STMSK : 32; //!< [31:0] Transmit Mask. } B; } hw_ssi_stmsk_t; #endif /*! * @name Constants and macros for entire SSI_STMSK register */ //@{ #define HW_SSI_STMSK_ADDR(x) (REGS_SSI_BASE(x) + 0x48) #ifndef __LANGUAGE_ASM__ #define HW_SSI_STMSK(x) (*(volatile hw_ssi_stmsk_t *) HW_SSI_STMSK_ADDR(x)) #define HW_SSI_STMSK_RD(x) (HW_SSI_STMSK(x).U) #define HW_SSI_STMSK_WR(x, v) (HW_SSI_STMSK(x).U = (v)) #define HW_SSI_STMSK_SET(x, v) (HW_SSI_STMSK_WR(x, HW_SSI_STMSK_RD(x) | (v))) #define HW_SSI_STMSK_CLR(x, v) (HW_SSI_STMSK_WR(x, HW_SSI_STMSK_RD(x) & ~(v))) #define HW_SSI_STMSK_TOG(x, v) (HW_SSI_STMSK_WR(x, HW_SSI_STMSK_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_STMSK bitfields */ /*! @name Register SSI_STMSK, field STMSK[31:0] (RW) * * Transmit Mask. These bits indicate which slot has been masked in the current frame. The Core can * write to this register to control the time slots in which the SSI transmits data. Each bit has * info corresponding to the respective time slot in the frame. Transmit mask bits should not be * used in I2S Slave mode of operation. SSI_STMSK register value must be set before enabling * Transmission. * * Values: * - 0 - Valid Time Slot. * - 1 - Time Slot masked (no data transmitted in this time slot). */ //@{ #define BP_SSI_STMSK_STMSK (0) //!< Bit position for SSI_STMSK_STMSK. #define BM_SSI_STMSK_STMSK (0xffffffff) //!< Bit mask for SSI_STMSK_STMSK. //! @brief Get value of SSI_STMSK_STMSK from a register value. #define BG_SSI_STMSK_STMSK(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_STMSK_STMSK) >> BP_SSI_STMSK_STMSK) //! @brief Format value for bitfield SSI_STMSK_STMSK. #define BF_SSI_STMSK_STMSK(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_STMSK_STMSK) & BM_SSI_STMSK_STMSK) #ifndef __LANGUAGE_ASM__ //! @brief Set the STMSK field to a new value. #define BW_SSI_STMSK_STMSK(x, v) (HW_SSI_STMSK_WR(x, (HW_SSI_STMSK_RD(x) & ~BM_SSI_STMSK_STMSK) | BF_SSI_STMSK_STMSK(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_SRMSK - SSI Receive Time Slot Mask Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SRMSK - SSI Receive Time Slot Mask Register (RW) * * Reset value: 0x00000000 */ typedef union _hw_ssi_srmsk { reg32_t U; struct _hw_ssi_srmsk_bitfields { unsigned SRMSK : 32; //!< [31:0] Receive Mask. } B; } hw_ssi_srmsk_t; #endif /*! * @name Constants and macros for entire SSI_SRMSK register */ //@{ #define HW_SSI_SRMSK_ADDR(x) (REGS_SSI_BASE(x) + 0x4c) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SRMSK(x) (*(volatile hw_ssi_srmsk_t *) HW_SSI_SRMSK_ADDR(x)) #define HW_SSI_SRMSK_RD(x) (HW_SSI_SRMSK(x).U) #define HW_SSI_SRMSK_WR(x, v) (HW_SSI_SRMSK(x).U = (v)) #define HW_SSI_SRMSK_SET(x, v) (HW_SSI_SRMSK_WR(x, HW_SSI_SRMSK_RD(x) | (v))) #define HW_SSI_SRMSK_CLR(x, v) (HW_SSI_SRMSK_WR(x, HW_SSI_SRMSK_RD(x) & ~(v))) #define HW_SSI_SRMSK_TOG(x, v) (HW_SSI_SRMSK_WR(x, HW_SSI_SRMSK_RD(x) ^ (v))) #endif //@} /* * constants & macros for individual SSI_SRMSK bitfields */ /*! @name Register SSI_SRMSK, field SRMSK[31:0] (RW) * * Receive Mask. These bits indicate which slot has been masked in the current frame. The Core can * write to this register to control the time slots in which the SSI receives data. Each bit has * info corresponding to the respective time slot in the frame. SSI_SRMSK register value must be set * before enabling Receiver. Receive mask bits should not be used in I2S Slave mode of operation. * * Values: * - 0 - Valid Time Slot. * - 1 - Time Slot masked (no data received in this time slot). */ //@{ #define BP_SSI_SRMSK_SRMSK (0) //!< Bit position for SSI_SRMSK_SRMSK. #define BM_SSI_SRMSK_SRMSK (0xffffffff) //!< Bit mask for SSI_SRMSK_SRMSK. //! @brief Get value of SSI_SRMSK_SRMSK from a register value. #define BG_SSI_SRMSK_SRMSK(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SRMSK_SRMSK) >> BP_SSI_SRMSK_SRMSK) //! @brief Format value for bitfield SSI_SRMSK_SRMSK. #define BF_SSI_SRMSK_SRMSK(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SRMSK_SRMSK) & BM_SSI_SRMSK_SRMSK) #ifndef __LANGUAGE_ASM__ //! @brief Set the SRMSK field to a new value. #define BW_SSI_SRMSK_SRMSK(x, v) (HW_SSI_SRMSK_WR(x, (HW_SSI_SRMSK_RD(x) & ~BM_SSI_SRMSK_SRMSK) | BF_SSI_SRMSK_SRMSK(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_SSI_SACCST - SSI AC97 Channel Status Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SACCST - SSI AC97 Channel Status Register (RO) * * Reset value: 0x00000000 */ typedef union _hw_ssi_saccst { reg32_t U; struct _hw_ssi_saccst_bitfields { unsigned SACCST : 10; //!< [9:0] AC97 Channel Status. unsigned RESERVED0 : 22; //!< [31:10] Reserved } B; } hw_ssi_saccst_t; #endif /*! * @name Constants and macros for entire SSI_SACCST register */ //@{ #define HW_SSI_SACCST_ADDR(x) (REGS_SSI_BASE(x) + 0x50) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SACCST(x) (*(volatile hw_ssi_saccst_t *) HW_SSI_SACCST_ADDR(x)) #define HW_SSI_SACCST_RD(x) (HW_SSI_SACCST(x).U) #endif //@} /* * constants & macros for individual SSI_SACCST bitfields */ /*! @name Register SSI_SACCST, field SACCST[9:0] (RO) * * AC97 Channel Status. These bits indicate which data slot has been enabled in AC97 variable mode * operation. This register is updated in case the core enables/disables a channel through a write * to SSI_SACCEN/SSI_SACCDIS register or the external codec enables a channel by sending a '1' in * the corresponding SLOTREQ bit. Bit [0] corresponds to the first data slot in an AC97 frame (Slot * #3) and Bit [9] corresponds to the tenth data slot (slot #12). The contents of this register only * have relevance while the SSI is operating in AC97 variable mode. Writes to this register result * in an error response on the block interface. * * Values: * - 0 - Data channel disabled. * - 1 - Data channel enabled. */ //@{ #define BP_SSI_SACCST_SACCST (0) //!< Bit position for SSI_SACCST_SACCST. #define BM_SSI_SACCST_SACCST (0x000003ff) //!< Bit mask for SSI_SACCST_SACCST. //! @brief Get value of SSI_SACCST_SACCST from a register value. #define BG_SSI_SACCST_SACCST(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SACCST_SACCST) >> BP_SSI_SACCST_SACCST) //@} //------------------------------------------------------------------------------------------- // HW_SSI_SACCEN - SSI AC97 Channel Enable Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SACCEN - SSI AC97 Channel Enable Register (WO) * * Reset value: 0x00000000 */ typedef union _hw_ssi_saccen { reg32_t U; struct _hw_ssi_saccen_bitfields { unsigned SACCEN : 10; //!< [9:0] AC97 Channel Enable. unsigned RESERVED0 : 22; //!< [31:10] Reserved } B; } hw_ssi_saccen_t; #endif /*! * @name Constants and macros for entire SSI_SACCEN register */ //@{ #define HW_SSI_SACCEN_ADDR(x) (REGS_SSI_BASE(x) + 0x54) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SACCEN(x) (*(volatile hw_ssi_saccen_t *) HW_SSI_SACCEN_ADDR(x)) #define HW_SSI_SACCEN_WR(x, v) (HW_SSI_SACCEN(x).U = (v)) #endif //@} /* * constants & macros for individual SSI_SACCEN bitfields */ /*! @name Register SSI_SACCEN, field SACCEN[9:0] (WO) * * AC97 Channel Enable. The Core writes a '1' to these bits to enable an AC97 data channel. Writing * a '0' has no effect. Bit [0] corresponds to the first data slot in an AC97 frame (Slot #3) and * Bit [9] corresponds to the tenth data slot (slot #12). Writes to these bits only have effect in * the AC97 Variable mode of operation. These bits are always read as '0' by the Core. * * Values: * - 0 - Write Has no effect. * - 1 - Write Enables the corresponding data channel. */ //@{ #define BP_SSI_SACCEN_SACCEN (0) //!< Bit position for SSI_SACCEN_SACCEN. #define BM_SSI_SACCEN_SACCEN (0x000003ff) //!< Bit mask for SSI_SACCEN_SACCEN. //! @brief Get value of SSI_SACCEN_SACCEN from a register value. #define BG_SSI_SACCEN_SACCEN(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SACCEN_SACCEN) >> BP_SSI_SACCEN_SACCEN) //! @brief Format value for bitfield SSI_SACCEN_SACCEN. #define BF_SSI_SACCEN_SACCEN(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SACCEN_SACCEN) & BM_SSI_SACCEN_SACCEN) //@} //------------------------------------------------------------------------------------------- // HW_SSI_SACCDIS - SSI AC97 Channel Disable Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_SSI_SACCDIS - SSI AC97 Channel Disable Register (WO) * * Reset value: 0x00000000 */ typedef union _hw_ssi_saccdis { reg32_t U; struct _hw_ssi_saccdis_bitfields { unsigned SACCDIS : 10; //!< [9:0] AC97 Channel Disable. unsigned RESERVED0 : 22; //!< [31:10] Reserved } B; } hw_ssi_saccdis_t; #endif /*! * @name Constants and macros for entire SSI_SACCDIS register */ //@{ #define HW_SSI_SACCDIS_ADDR(x) (REGS_SSI_BASE(x) + 0x58) #ifndef __LANGUAGE_ASM__ #define HW_SSI_SACCDIS(x) (*(volatile hw_ssi_saccdis_t *) HW_SSI_SACCDIS_ADDR(x)) #define HW_SSI_SACCDIS_WR(x, v) (HW_SSI_SACCDIS(x).U = (v)) #endif //@} /* * constants & macros for individual SSI_SACCDIS bitfields */ /*! @name Register SSI_SACCDIS, field SACCDIS[9:0] (WO) * * AC97 Channel Disable. The Core writes a '1' to these bits to disable an AC97 data channel. * Writing a '0' has no effect. Bit [0] corresponds to the first data slot in an AC97 frame (Slot * #3) and Bit [9] corresponds to the tenth data slot (slot #12). Writes to these bits only have * effect in the AC97 Variable mode of operation. These bits are always read as '0' by the Core. * * Values: * - 0 - Write Has no effect. * - 1 - Write Disables the corresponding data channel. */ //@{ #define BP_SSI_SACCDIS_SACCDIS (0) //!< Bit position for SSI_SACCDIS_SACCDIS. #define BM_SSI_SACCDIS_SACCDIS (0x000003ff) //!< Bit mask for SSI_SACCDIS_SACCDIS. //! @brief Get value of SSI_SACCDIS_SACCDIS from a register value. #define BG_SSI_SACCDIS_SACCDIS(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_SSI_SACCDIS_SACCDIS) >> BP_SSI_SACCDIS_SACCDIS) //! @brief Format value for bitfield SSI_SACCDIS_SACCDIS. #define BF_SSI_SACCDIS_SACCDIS(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_SSI_SACCDIS_SACCDIS) & BM_SSI_SACCDIS_SACCDIS) //@} //------------------------------------------------------------------------------------------- // hw_ssi_t - module struct //------------------------------------------------------------------------------------------- /*! * @brief All SSI module registers. */ #ifndef __LANGUAGE_ASM__ #pragma pack(1) typedef struct _hw_ssi { volatile hw_ssi_stxn_t STXn[2]; //!< SSI Transmit Data Register n volatile hw_ssi_srxn_t SRXn[2]; //!< SSI Receive Data Register n volatile hw_ssi_scr_t SCR; //!< SSI Control Register volatile hw_ssi_sisr_t SISR; //!< SSI Interrupt Status Register volatile hw_ssi_sier_t SIER; //!< SSI Interrupt Enable Register volatile hw_ssi_stcr_t STCR; //!< SSI Transmit Configuration Register volatile hw_ssi_srcr_t SRCR; //!< SSI Receive Configuration Register volatile hw_ssi_stccr_t STCCR; //!< SSI Transmit Clock Control Register volatile hw_ssi_srccr_t SRCCR; //!< SSI Receive Clock Control Register volatile hw_ssi_sfcsr_t SFCSR; //!< SSI FIFO Control/Status Register reg32_t _reserved0[2]; volatile hw_ssi_sacnt_t SACNT; //!< SSI AC97 Control Register volatile hw_ssi_sacadd_t SACADD; //!< SSI AC97 Command Address Register volatile hw_ssi_sacdat_t SACDAT; //!< SSI AC97 Command Data Register volatile hw_ssi_satag_t SATAG; //!< SSI AC97 Tag Register volatile hw_ssi_stmsk_t STMSK; //!< SSI Transmit Time Slot Mask Register volatile hw_ssi_srmsk_t SRMSK; //!< SSI Receive Time Slot Mask Register volatile hw_ssi_saccst_t SACCST; //!< SSI AC97 Channel Status Register volatile hw_ssi_saccen_t SACCEN; //!< SSI AC97 Channel Enable Register volatile hw_ssi_saccdis_t SACCDIS; //!< SSI AC97 Channel Disable Register } hw_ssi_t; #pragma pack() //! @brief Macro to access all SSI registers. //! @param x SSI instance number. //! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, //! use the '&' operator, like <code>&HW_SSI(0)</code>. #define HW_SSI(x) (*(hw_ssi_t *) REGS_SSI_BASE(x)) #endif #endif // __HW_SSI_REGISTERS_H__ // v18/121106/1.2.2 // EOF
79,626
5,714
# Copyright (C) 2016-present the asyncpg authors and contributors # <see AUTHORS file> # # This module is part of asyncpg and is released under # the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 """Tests how asyncpg behaves in non-ideal conditions.""" import asyncio import os import platform import unittest import sys from asyncpg import _testbase as tb @unittest.skipIf(os.environ.get('PGHOST'), 'using remote cluster for testing') @unittest.skipIf( platform.system() == 'Windows' and sys.version_info >= (3, 8), 'not compatible with ProactorEventLoop which is default in Python 3.8') class TestConnectionLoss(tb.ProxiedClusterTestCase): @tb.with_timeout(30.0) async def test_connection_close_timeout(self): con = await self.connect() self.proxy.trigger_connectivity_loss() with self.assertRaises(asyncio.TimeoutError): await con.close(timeout=0.5) @tb.with_timeout(30.0) async def test_pool_release_timeout(self): pool = await self.create_pool( database='postgres', min_size=2, max_size=2) try: with self.assertRaises(asyncio.TimeoutError): async with pool.acquire(timeout=0.5): self.proxy.trigger_connectivity_loss() finally: self.proxy.restore_connectivity() pool.terminate() @tb.with_timeout(30.0) async def test_pool_handles_abrupt_connection_loss(self): pool_size = 3 query_runtime = 0.5 pool_timeout = cmd_timeout = 1.0 concurrency = 9 pool_concurrency = (concurrency - 1) // pool_size + 1 # Worst expected runtime + 20% to account for other latencies. worst_runtime = (pool_timeout + cmd_timeout) * pool_concurrency * 1.2 async def worker(pool): async with pool.acquire(timeout=pool_timeout) as con: await con.fetch('SELECT pg_sleep($1)', query_runtime) def kill_connectivity(): self.proxy.trigger_connectivity_loss() new_pool = self.create_pool( database='postgres', min_size=pool_size, max_size=pool_size, timeout=cmd_timeout, command_timeout=cmd_timeout) with self.assertRunUnder(worst_runtime): pool = await new_pool try: workers = [worker(pool) for _ in range(concurrency)] self.loop.call_later(1, kill_connectivity) await asyncio.gather( *workers, return_exceptions=True) finally: pool.terminate()
1,116
10,182
/* * dex2jar - Tools to work with android .dex and java .class files * Copyright (c) 2009-2013 Panxiaobo * * 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.googlecode.d2j.dex.writer.item; import com.googlecode.d2j.DexType; import com.googlecode.d2j.Field; import com.googlecode.d2j.Method; import com.googlecode.d2j.dex.writer.DexWriteException; import java.util.*; public class ConstPool { public List<EncodedArrayItem> encodedArrayItems = new ArrayList<>(); public Map<AnnotationSetRefListItem, AnnotationSetRefListItem> annotationSetRefListItems = new HashMap<>(); public List<CodeItem> codeItems = new ArrayList<>(); public List<ClassDataItem> classDataItems = new ArrayList<>(); public List<DebugInfoItem> debugInfoItems = new ArrayList<>(); public Map<AnnotationItem, AnnotationItem> annotationItems = new HashMap<>(); public List<AnnotationsDirectoryItem> annotationsDirectoryItems = new ArrayList<>(); public Map<AnnotationSetItem, AnnotationSetItem> annotationSetItems = new HashMap<>(); public Map<FieldIdItem, FieldIdItem> fields = new TreeMap<>(); public Map<MethodIdItem, MethodIdItem> methods = new TreeMap<>(); public Map<ProtoIdItem, ProtoIdItem> protos = new TreeMap<>(); public List<StringDataItem> stringDatas = new ArrayList<>(100); public Map<String, StringIdItem> strings = new TreeMap<>(); public Map<TypeListItem, TypeListItem> typeLists = new TreeMap<>(); public Map<String, TypeIdItem> types = new TreeMap<>(); public Map<TypeIdItem, ClassDefItem> classDefs = new HashMap<>(); public Object wrapEncodedItem(Object value) { if (value instanceof DexType) { value = uniqType(((DexType) value).desc); } else if (value instanceof Field) { value = uniqField((Field) value); } else if (value instanceof String) { value = uniqString((String) value); } else if (value instanceof Method) { value = uniqMethod((Method) value); } return value; } public void clean() { encodedArrayItems.clear(); annotationSetRefListItems.clear(); codeItems.clear(); classDataItems.clear(); debugInfoItems.clear(); annotationItems.clear(); annotationsDirectoryItems.clear(); annotationSetItems.clear(); fields.clear(); methods.clear(); protos.clear(); stringDatas.clear(); typeLists.clear(); types.clear(); classDefs.clear(); } private String buildShorty(String ret, String[] types2) { StringBuilder sb = new StringBuilder(); if (ret.length() == 1) { sb.append(ret); } else { sb.append("L"); } for (String s : types2) { if (s.length() == 1) { sb.append(s); } else { sb.append("L"); } } return sb.toString(); } PE iterateParent(ClassDefItem p) { List<TypeIdItem> list = new ArrayList<>(6); list.add(p.superclazz); if (p.interfaces != null) { list.addAll(p.interfaces.items); } return new PE(p, list.iterator()); } public void addDebugInfoItem(DebugInfoItem debugInfoItem) { debugInfoItems.add(debugInfoItem); } static class PE { final ClassDefItem owner; final Iterator<TypeIdItem> it; PE(ClassDefItem owner, Iterator<TypeIdItem> it) { this.owner = owner; this.it = it; } } public List<ClassDefItem> buildSortedClassDefItems() { List<ClassDefItem> added = new ArrayList<>(); Stack<PE> stack1 = new Stack<>(); Set<ClassDefItem> children = new HashSet<>(); for (ClassDefItem c : classDefs.values()) { if (added.contains(c)) { continue; } children.add(c); stack1.push(iterateParent(c)); while (!stack1.empty()) { PE e = stack1.peek(); boolean canPop = true; while (e.it.hasNext()) { TypeIdItem tid = e.it.next(); if (tid == null) { continue; } ClassDefItem superDef = classDefs.get(tid); if (superDef != null && !added.contains(superDef)) { if (children.contains(superDef)) { System.err.println("WARN: dep-loop " + e.owner.clazz.descriptor.stringData.string + " -> " + superDef.clazz.descriptor.stringData.string); } else { canPop = false; children.add(superDef); stack1.push(iterateParent(superDef)); break; } } } if (canPop) { stack1.pop(); added.add(e.owner); children.remove(e.owner); } } children.clear(); } return added; } public AnnotationsDirectoryItem putAnnotationDirectoryItem() { AnnotationsDirectoryItem aDirectoryItem = new AnnotationsDirectoryItem(); annotationsDirectoryItems.add(aDirectoryItem); return aDirectoryItem; } public AnnotationItem uniqAnnotationItem(AnnotationItem key) { AnnotationItem v = annotationItems.get(key); if (v == null) { annotationItems.put(key, key); return key; } return v; } public ClassDefItem putClassDefItem(int accessFlag, String name, String superClass, String[] itfClass) { TypeIdItem type = uniqType(name); if (classDefs.containsKey(type)) { throw new DexWriteException("dup clz: " + name); } ClassDefItem classDefItem = new ClassDefItem(); classDefItem.accessFlags = accessFlag; classDefItem.clazz = type; if (superClass != null) { classDefItem.superclazz = uniqType(superClass); } if (itfClass != null && itfClass.length > 0) { classDefItem.interfaces = putTypeList(Arrays.asList(itfClass)); } classDefs.put(type, classDefItem); return classDefItem; } public FieldIdItem uniqField(Field field) { return uniqField(field.getOwner(), field.getName(), field.getType()); } public FieldIdItem uniqField(String owner, String name, String type) { FieldIdItem key = new FieldIdItem(uniqType(owner), uniqString(name), uniqType(type)); FieldIdItem item = fields.get(key); if (item != null) { return item; } fields.put(key, key); return key; } public MethodIdItem uniqMethod(Method method) { MethodIdItem key = new MethodIdItem(uniqType(method.getOwner()), uniqString(method.getName()), uniqProto(method)); return uniqMethod(key); } public MethodIdItem uniqMethod(String owner, String name, String parms[], String ret) { MethodIdItem key = new MethodIdItem(uniqType(owner), uniqString(name), uniqProto(parms, ret)); return uniqMethod(key); } public MethodIdItem uniqMethod(MethodIdItem key) { MethodIdItem item = methods.get(key); if (item != null) { return item; } methods.put(key, key); return key; } private ProtoIdItem uniqProto(Method method) { return uniqProto(method.getParameterTypes(), method.getReturnType()); } public ProtoIdItem uniqProto(String[] types, String retDesc) { TypeIdItem ret = uniqType(retDesc); StringIdItem shorty = uniqString(buildShorty(retDesc, types)); TypeListItem params = putTypeList(types); ProtoIdItem key = new ProtoIdItem(params, ret, shorty); ProtoIdItem item = protos.get(key); if (item != null) { return item; } else { protos.put(key, key); return key; } } public StringIdItem uniqString(String data) { StringIdItem item = strings.get(data); if (item != null) { return item; } StringDataItem sd = new StringDataItem(data); stringDatas.add(sd); item = new StringIdItem(sd); strings.put(data, item); return item; } public TypeIdItem uniqType(String type) { TypeIdItem item = types.get(type); if (item != null) { return item; } item = new TypeIdItem(uniqString(type)); types.put(type, item); return item; } private TypeListItem putTypeList(String... subList) { if (subList.length == 0) { return ZERO_SIZE_TYPE_LIST; } List<TypeIdItem> idItems = new ArrayList<>(subList.length); for (String s : subList) { idItems.add(uniqType(s)); } TypeListItem key = new TypeListItem(idItems); TypeListItem item = typeLists.get(key); if (item != null) { return item; } typeLists.put(key, key); return key; } private static final TypeListItem ZERO_SIZE_TYPE_LIST = new TypeListItem(Collections.EMPTY_LIST); static { // make sure the offset is 0 ZERO_SIZE_TYPE_LIST.offset = 0; } private TypeListItem putTypeList(List<String> subList) { if (subList.size() == 0) { return ZERO_SIZE_TYPE_LIST; } List<TypeIdItem> idItems = new ArrayList<>(subList.size()); for (String s : subList) { idItems.add(uniqType(s)); } TypeListItem key = new TypeListItem(idItems); TypeListItem item = typeLists.get(key); if (item != null) { return item; } typeLists.put(key, key); return key; } public ClassDataItem addClassDataItem(ClassDataItem dataItem) { classDataItems.add(dataItem); return dataItem; } // TODO change EncodedArrayItem to uniq public EncodedArrayItem putEnCodedArrayItem() { EncodedArrayItem arrayItem = new EncodedArrayItem(); encodedArrayItems.add(arrayItem); return arrayItem; } public AnnotationSetItem uniqAnnotationSetItem(AnnotationSetItem key) { List<AnnotationItem> copy = new ArrayList<AnnotationItem>(key.annotations); key.annotations.clear(); for (AnnotationItem annotationItem : copy) { key.annotations.add(uniqAnnotationItem(annotationItem)); } AnnotationSetItem v = annotationSetItems.get(key); if (v != null) { return v; } annotationSetItems.put(key, key); return key; } public AnnotationSetRefListItem uniqAnnotationSetRefListItem(AnnotationSetRefListItem key) { for (int i = 0; i < key.annotationSets.length; i++) { AnnotationSetItem anno = key.annotationSets[i]; if (anno != null) { key.annotationSets[i] = uniqAnnotationSetItem(anno); } } AnnotationSetRefListItem v = annotationSetRefListItems.get(key); if (v == null) { annotationSetRefListItems.put(key, key); return key; } return v; } public void addCodeItem(CodeItem code) { codeItems.add(code); } }
5,427
12,004
import asyncio import pulumi output = pulumi.Output.from_input(asyncio.sleep(1, "magic string")) output.apply(print)
40
1,016
<reponame>LiuStart/Musicoco package com.duan.musicoco.detail.sheet; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.helper.ItemTouchHelper; /** * Created by DuanJiaNing on 2019/4/6. */ public class SheetSortController extends ItemTouchHelper.Callback { private boolean enable; private OnDragDoneListener onDragDoneListener; private OnItemSwapListener onItemSwapListener; public void setOnItemSwapListener(OnItemSwapListener onItemSwapListener) { this.onItemSwapListener = onItemSwapListener; } public interface OnDragDoneListener { void dragDone(RecyclerView.ViewHolder holder); } public interface OnItemSwapListener { void swap(int posFrom, int posTo); } public void setOnDragDoneListener(OnDragDoneListener onDragDoneListener) { this.onDragDoneListener = onDragDoneListener; } @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { // 滑动或者拖拽的方向,上下左右 RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); int dragFlags; if (manager instanceof GridLayoutManager || manager instanceof StaggeredGridLayoutManager) { //网格布局管理器允许上下左右拖动 dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT; } else { //其他布局管理器允许上下拖动 dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; } return makeMovementFlags(dragFlags, 0); } @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { // 拖拽item移动时产生回调 // 更新顺序临时数据,交换动画 RecyclerView.Adapter adapter = recyclerView.getAdapter(); adapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition()); if (onItemSwapListener != null) { onItemSwapListener.swap(viewHolder.getAdapterPosition(), target.getAdapterPosition()); } return true; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { // 滑动删除时回调 } @Override public boolean isLongPressDragEnabled() { // 是否可以长按拖拽 return enable; } @Override public boolean isItemViewSwipeEnabled() { // 是否可以滑动删除 return super.isItemViewSwipeEnabled(); } public void setEnable(boolean enable) { this.enable = enable; } @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); if (onDragDoneListener != null) { onDragDoneListener.dragDone(viewHolder); } } }
1,282
889
<reponame>limberc/HyperGAN #From https://gist.github.com/EndingCredits/b5f35e84df10d46cfa716178d9c862a3 from __future__ import absolute_import from __future__ import division from __future__ import print_function from hypergan.gan_component import GANComponent import hyperchamber as hc import inspect class BaseTrainHook(GANComponent): def __init__(self, gan=None, config=None): super().__init__(gan, config) def augment_latent(self, latent): return latent def augment_x(self, x): return x def augment_g(self, g): return g def create(self): pass def losses(self): return [None, None] def before_step(self, step, feed_dict): pass def after_step(self, step, feed_dict): pass def after_create(self): pass def update_op(self): return None def gradients(self, d_grads, g_grads): return [d_grads, g_grads] def forward(self, d_loss, g_loss): return [None, None]
424
713
<reponame>cszn/USRNet import argparse import os import requests import re """ How to use: download USRNet models: python main_download_pretrained_models.py --models "USRNet" --model_dir "model_zoo" """ def download_pretrained_model(model_dir='model_zoo', model_name='dncnn3.pth'): if os.path.exists(os.path.join(model_dir, model_name)): print(f'already exists, skip downloading [{model_name}]') else: os.makedirs(model_dir, exist_ok=True) if 'SwinIR' in model_name: url = 'https://github.com/JingyunLiang/SwinIR/releases/download/v0.0/{}'.format(model_name) else: url = 'https://github.com/cszn/KAIR/releases/download/v1.0/{}'.format(model_name) r = requests.get(url, allow_redirects=True) print(f'downloading [{model_dir}/{model_name}] ...') open(os.path.join(model_dir, model_name), 'wb').write(r.content) print('done!') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--models', type=lambda s: re.split(' |, ', s), default = "dncnn3.pth", help='comma or space delimited list of characters, e.g., "DnCNN", "DnCNN BSRGAN.pth", "dncnn_15.pth dncnn_50.pth"') parser.add_argument('--model_dir', type=str, default='model_zoo', help='path of model_zoo') args = parser.parse_args() print(f'trying to download {args.models}') method_model_zoo = {'DnCNN': ['dncnn_15.pth', 'dncnn_25.pth', 'dncnn_50.pth', 'dncnn3.pth', 'dncnn_color_blind.pth', 'dncnn_gray_blind.pth'], 'SRMD': ['srmdnf_x2.pth', 'srmdnf_x3.pth', 'srmdnf_x4.pth', 'srmd_x2.pth', 'srmd_x3.pth', 'srmd_x4.pth'], 'DPSR': ['dpsr_x2.pth', 'dpsr_x3.pth', 'dpsr_x4.pth', 'dpsr_x4_gan.pth'], 'FFDNet': ['ffdnet_color.pth', 'ffdnet_gray.pth', 'ffdnet_color_clip.pth', 'ffdnet_gray_clip.pth'], 'USRNet': ['usrgan.pth', 'usrgan_tiny.pth', 'usrnet.pth', 'usrnet_tiny.pth'], 'DPIR': ['drunet_gray.pth', 'drunet_color.pth', 'drunet_deblocking_color.pth', 'drunet_deblocking_grayscale.pth'], 'BSRGAN': ['BSRGAN.pth', 'BSRNet.pth', 'BSRGANx2.pth'], 'IRCNN': ['ircnn_color.pth', 'ircnn_gray.pth'], 'SwinIR': ['001_classicalSR_DF2K_s64w8_SwinIR-M_x2.pth', '001_classicalSR_DF2K_s64w8_SwinIR-M_x3.pth', '001_classicalSR_DF2K_s64w8_SwinIR-M_x4.pth', '001_classicalSR_DF2K_s64w8_SwinIR-M_x8.pth', '001_classicalSR_DIV2K_s48w8_SwinIR-M_x2.pth', '001_classicalSR_DIV2K_s48w8_SwinIR-M_x3.pth', '001_classicalSR_DIV2K_s48w8_SwinIR-M_x4.pth', '001_classicalSR_DIV2K_s48w8_SwinIR-M_x8.pth', '002_lightweightSR_DIV2K_s64w8_SwinIR-S_x2.pth', '002_lightweightSR_DIV2K_s64w8_SwinIR-S_x3.pth', '002_lightweightSR_DIV2K_s64w8_SwinIR-S_x4.pth', '003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x4_GAN.pth', '003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x4_PSNR.pth', '004_grayDN_DFWB_s128w8_SwinIR-M_noise15.pth', '004_grayDN_DFWB_s128w8_SwinIR-M_noise25.pth', '004_grayDN_DFWB_s128w8_SwinIR-M_noise50.pth', '005_colorDN_DFWB_s128w8_SwinIR-M_noise15.pth', '005_colorDN_DFWB_s128w8_SwinIR-M_noise25.pth', '005_colorDN_DFWB_s128w8_SwinIR-M_noise50.pth', '006_CAR_DFWB_s126w7_SwinIR-M_jpeg10.pth', '006_CAR_DFWB_s126w7_SwinIR-M_jpeg20.pth', '006_CAR_DFWB_s126w7_SwinIR-M_jpeg30.pth', '006_CAR_DFWB_s126w7_SwinIR-M_jpeg40.pth'], 'others': ['msrresnet_x4_psnr.pth', 'msrresnet_x4_gan.pth', 'imdn_x4.pth', 'RRDB.pth', 'ESRGAN.pth', 'FSSR_DPED.pth', 'FSSR_JPEG.pth', 'RealSR_DPED.pth', 'RealSR_JPEG.pth'] } method_zoo = list(method_model_zoo.keys()) model_zoo = [] for b in list(method_model_zoo.values()): model_zoo += b if 'all' in args.models: for method in method_zoo: for model_name in method_model_zoo[method]: download_pretrained_model(args.model_dir, model_name) else: for method_model in args.models: if method_model in method_zoo: # method, need for loop for model_name in method_model_zoo[method_model]: if 'SwinIR' in model_name: download_pretrained_model(os.path.join(args.model_dir, 'swinir'), model_name) else: download_pretrained_model(args.model_dir, model_name) elif method_model in model_zoo: # model, do not need for loop if 'SwinIR' in method_model: download_pretrained_model(os.path.join(args.model_dir, 'swinir'), method_model) else: download_pretrained_model(args.model_dir, method_model) else: print(f'Do not find {method_model} from the pre-trained model zoo!')
3,090
4,036
struct Point2 { int x; int y; }; struct Point3 : Point2 { int z; }; void f() { Point2 p2; Point3 p3; p2 = p3; } void g() { Point2* p2 = 0; Point3* p3 = 0; p2 = p3; }
99
3,102
template <typename T> struct A { }; template <> struct A<int> { struct B { int f; }; }; template <> struct A<bool> { struct B { int g; }; }; template <typename T> constexpr int f() { return 0; } template <> constexpr int f<int>() { return 4; }
105
4,054
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.testrunner.legacy; import java.util.Collection; import java.util.logging.LogRecord; /** * @author mortent */ public interface LegacyTestRunner { Collection<LogRecord> getLog(long after); Status getStatus(); void test(TestProfile testProfile, byte[] config); // TODO (mortent) : This seems to be duplicated in TesterCloud.Status and expects to have the same values enum Status { NOT_STARTED, RUNNING, FAILURE, ERROR, SUCCESS } }
189
2,693
<reponame>Chillee/benchmark import inspect import os import sys def _colored_string(string: str, color: str or int) -> str: """在终端中显示一串有颜色的文字 :param string: 在终端中显示的文字 :param color: 文字的颜色 :return: """ if isinstance(color, str): color = { "black": 30, "Black": 30, "BLACK": 30, "red": 31, "Red": 31, "RED": 31, "green": 32, "Green": 32, "GREEN": 32, "yellow": 33, "Yellow": 33, "YELLOW": 33, "blue": 34, "Blue": 34, "BLUE": 34, "purple": 35, "Purple": 35, "PURPLE": 35, "cyan": 36, "Cyan": 36, "CYAN": 36, "white": 37, "White": 37, "WHITE": 37 }[color] return "\033[%dm%s\033[0m" % (color, string) def gr(string, flag): if flag: return _colored_string(string, "green") else: return _colored_string(string, "red") def find_all_modules(): modules = {} children = {} to_doc = set() root = '../fastNLP' for path, dirs, files in os.walk(root): for file in files: if file.endswith('.py'): name = ".".join(path.split('/')[1:]) if file.split('.')[0] != "__init__": name = name + '.' + file.split('.')[0] __import__(name) m = sys.modules[name] modules[name] = m try: m.__all__ except: print(name, "__all__ missing") continue if m.__doc__ is None: print(name, "__doc__ missing") continue if "undocumented" not in m.__doc__: to_doc.add(name) for module in to_doc: t = ".".join(module.split('.')[:-1]) if t in to_doc: if t not in children: children[t] = set() children[t].add(module) for m in children: children[m] = sorted(children[m]) return modules, to_doc, children def create_rst_file(modules, name, children): m = modules[name] with open("./source/" + name + ".rst", "w") as fout: t = "=" * len(name) fout.write(name + "\n") fout.write(t + "\n") fout.write("\n") fout.write(".. automodule:: " + name + "\n") if name != "fastNLP.core" and len(m.__all__) > 0: fout.write(" :members: " + ", ".join(m.__all__) + "\n") short = name[len("fastNLP."):] if not (short.startswith('models') or short.startswith('modules') or short.startswith('embeddings')): fout.write(" :inherited-members:\n") fout.write("\n") if name in children: fout.write("子模块\n------\n\n.. toctree::\n :maxdepth: 1\n\n") for module in children[name]: fout.write(" " + module + "\n") def check_file(m, name): names = name.split('.') test_name = "test." + ".".join(names[1:-1]) + ".test_" + names[-1] try: __import__(test_name) tm = sys.modules[test_name] except ModuleNotFoundError: tm = None tested = tm is not None funcs = {} classes = {} for item, obj in inspect.getmembers(m): if inspect.isclass(obj) and obj.__module__ == name and not obj.__name__.startswith('_'): this = (obj.__doc__ is not None, tested and obj.__name__ in dir(tm), {}) for i in dir(obj): func = getattr(obj, i) if inspect.isfunction(func) and not i.startswith('_'): this[2][i] = (func.__doc__ is not None, False) classes[obj.__name__] = this if inspect.isfunction(obj) and obj.__module__ == name and not obj.__name__.startswith('_'): this = (obj.__doc__ is not None, tested and obj.__name__ in dir(tm)) # docs funcs[obj.__name__] = this return funcs, classes def check_files(modules, out=None): for name in sorted(modules.keys()): print(name, file=out) funcs, classes = check_file(modules[name], name) if out is None: for f in funcs: print("%-30s \t %s \t %s" % (f, gr("文档", funcs[f][0]), gr("测试", funcs[f][1]))) for c in classes: print("%-30s \t %s \t %s" % (c, gr("文档", classes[c][0]), gr("测试", classes[c][1]))) methods = classes[c][2] for f in methods: print(" %-28s \t %s" % (f, gr("文档", methods[f][0]))) else: for f in funcs: if not funcs[f][0]: print("缺少文档 %s" % (f), file=out) if not funcs[f][1]: print("缺少测试 %s" % (f), file=out) for c in classes: if not classes[c][0]: print("缺少文档 %s" % (c), file=out) if not classes[c][1]: print("缺少测试 %s" % (c), file=out) methods = classes[c][2] for f in methods: if not methods[f][0]: print("缺少文档 %s" % (c + "." + f), file=out) print(file=out) def main_check(): sys.path.append("..") print(_colored_string('Getting modules...', "Blue")) modules, to_doc, children = find_all_modules() print(_colored_string('Done!', "Green")) print(_colored_string('Creating rst files...', "Blue")) for name in to_doc: create_rst_file(modules, name, children) print(_colored_string('Done!', "Green")) print(_colored_string('Checking all files...', "Blue")) check_files(modules, out=open("results.txt", "w")) print(_colored_string('Done!', "Green")) def check_file_r(file_path): with open(file_path) as fin: content = fin.read() index = -3 cuts = [] while index != -1: index = content.find('"""',index+3) cuts.append(index) cuts = cuts[:-1] assert len(cuts)%2 == 0 write_content = "" last = 0 for i in range(len(cuts)//2): start, end = cuts[i+i], cuts[i+i+1] if content[start-1] == "r": write_content += content[last:end+3] else: write_content += content[last:start] + "r" write_content += content[start:end+3] last = end + 3 write_content += content[last:] with open(file_path, "w") as fout: fout.write(write_content) def add_r(base_path='../fastNLP'): for path, _, files in os.walk(base_path): for f in files: if f.endswith(".py"): check_file_r(os.path.abspath(os.path.join(path,f))) # sys.exit(0) if __name__ == "__main__": add_r()
3,559
581
<reponame>ninniuz/sentry-java<gh_stars>100-1000 package io.sentry; import java.lang.reflect.InvocationTargetException; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; @ApiStatus.Internal public final class OptionsContainer<T> { public @NotNull static <T> OptionsContainer<T> create(final @NotNull Class<T> clazz) { return new OptionsContainer<>(clazz); } private final @NotNull Class<T> clazz; private OptionsContainer(final @NotNull Class<T> clazz) { super(); this.clazz = clazz; } public @NotNull T createInstance() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { return clazz.getDeclaredConstructor().newInstance(); } }
256
2,671
import _sk_fail; _sk_fail._("_MozillaCookieJar")
21
631
<filename>activeweb/src/test/java/app/controllers/Ignore234Controller.java package app.controllers; import org.javalite.activeweb.AppController; /** * Created by igor on 4/29/14. */ public class Ignore234Controller extends AppController { public void show(){ respond("ok"); } }
101
317
<reponame>heralex/OTB<filename>Modules/Filtering/Statistics/src/otbPatternSampler.cxx /* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbPatternSampler.h" #include "otbMath.h" #include "otbMacro.h" #include <algorithm> namespace otb { bool PatternSampler::ParameterType::operator!=(const PatternSampler::ParameterType& param) const { return bool((MaxPatternSize != param.MaxPatternSize) || (Pattern1 != param.Pattern1) || (Pattern2 != param.Pattern2) || (Seed != param.Seed)); } PatternSampler::PatternSampler() : m_Index1(0UL), m_Index2(0UL) { this->m_Parameters.MaxPatternSize = 1000; this->m_Parameters.Pattern1.clear(); this->m_Parameters.Pattern2.clear(); this->m_Parameters.Seed = 121212; } void PatternSampler::Reset(void) { Superclass::Reset(); m_Index1 = 0UL; m_Index2 = 0UL; // if seed is not 0, generate patterns // since the pattern depend on the sampling rate they should be regenerated // in order to keep existing patterns, the seed should be set to 0 if (this->m_Parameters.Seed) { unsigned long T1 = FindBestSize(this->GetTotalElements()); unsigned long N1 = static_cast<unsigned long>(std::floor(this->GetRate() * T1)); double selected_ratio = static_cast<double>(N1) / static_cast<double>(T1); unsigned long taken = static_cast<unsigned long>(selected_ratio * static_cast<double>(this->GetTotalElements())); unsigned long left = this->GetNeededElements() - taken; unsigned long newtot = this->GetTotalElements() - taken; unsigned long T2 = 0; unsigned long N2 = 0; if (left > 0) { double ratio2 = 0.0; if (newtot > 0) ratio2 = static_cast<double>(left) / static_cast<double>(newtot); T2 = FindBestSize(this->GetTotalElements() / T1 * (T1 - N1)); if (T2 > 0) { N2 = static_cast<unsigned long>(std::ceil(ratio2 * T2)); } } std::srand(m_Parameters.Seed); this->m_Parameters.Pattern1 = RandArray(N1, T1); if (T2 > 0) this->m_Parameters.Pattern2 = RandArray(N2, T2); } } bool PatternSampler::TakeSample(void) { bool ret = false; this->m_ProcessedElements += 1UL; if (this->m_ChosenElements >= this->GetNeededElements()) return false; // Test selection with first pattern ret = this->m_Parameters.Pattern1[m_Index1]; m_Index1++; if (m_Index1 >= this->m_Parameters.Pattern1.size()) m_Index1 = 0UL; if (!ret && this->m_Parameters.Pattern2.size()) { // Test selection with second pattern ret = this->m_Parameters.Pattern2[m_Index2]; m_Index2++; if (m_Index2 >= this->m_Parameters.Pattern2.size()) m_Index2 = 0UL; } if (ret) { this->m_ChosenElements += 1UL; } return ret; } // [static] void PatternSampler::ImportPatterns(const std::string& data, ParameterType& param) { // clear output patterns param.Pattern1.clear(); param.Pattern2.clear(); // split the string on slash caracters size_t sep1 = data.find('/'); // convert string into bool sequence for (size_t pos = 0; pos < data.size(); ++pos) { if (pos == sep1) break; switch (ParseSymbol(data[pos])) { case 0: { param.Pattern1.push_back(false); break; } case 1: { param.Pattern1.push_back(true); break; } default: { break; } } } if (sep1 != std::string::npos) { size_t sep2 = data.find('/', sep1 + 1); for (size_t pos = (sep1 + 1); pos < data.size(); ++pos) { if (pos == sep2) break; switch (ParseSymbol(data[pos])) { case 0: { param.Pattern2.push_back(false); break; } case 1: { param.Pattern2.push_back(true); break; } default: { break; } } } } } // [static] void PatternSampler::ExportPatterns(const ParameterType& param, std::string& data) { // clear output string data.clear(); // format output patterns for (unsigned int i = 0; i < param.Pattern1.size(); ++i) { if (param.Pattern1[i]) { data.push_back('1'); } else { data.push_back('0'); } } if (param.Pattern2.size()) { data.push_back('/'); } for (unsigned int i = 0; i < param.Pattern2.size(); ++i) { if (param.Pattern2[i]) { data.push_back('1'); } else { data.push_back('0'); } } } unsigned int PatternSampler::ParseSymbol(const char& s) { if ((s == '1') || (s == 'X') || (s == 'y') || (s == 'Y') || (s == '|') || (s == '+')) { return 1; } else if ((s == '0') || (s == '_') || (s == 'n') || (s == 'N') || (s == '.') || (s == '-')) { return 0; } return 2; } std::vector<bool> PatternSampler::RandArray(unsigned long N, unsigned long T) { if (N > T) itkGenericExceptionMacro(<< "N must be <= to T (aka m_SamplingTabSize)." << std::endl); std::vector<bool> res(T, 0); for (unsigned long i = 0; i < N; i++) res[i] = 1; std::random_shuffle(res.begin(), res.end()); return res; } unsigned long PatternSampler::FindBestSize(unsigned long tot) { // handle small values if (tot <= m_Parameters.MaxPatternSize) return tot; // try to find a sub-period in tot, between 20 and MaxPatternSize for (unsigned long size = m_Parameters.MaxPatternSize; size >= 2; size--) if (tot % size == 0) return size; otbWarningMacro(<< "prime number > m_Parameters.MaxPatternSize (" << tot << ">" << m_Parameters.MaxPatternSize << ")." << std::endl); // fallback : return the maximum size return m_Parameters.MaxPatternSize; } } // namespace otb
2,504
3,301
package com.alibaba.alink.params.shared.iter; import org.apache.flink.ml.api.misc.param.ParamInfo; import org.apache.flink.ml.api.misc.param.ParamInfoFactory; import org.apache.flink.ml.api.misc.param.WithParams; public interface HasMaxIterDefaultAs10<T> extends WithParams <T> { ParamInfo <Integer> MAX_ITER = ParamInfoFactory .createParamInfo("maxIter", Integer.class) .setDescription("Maximum iterations, The default value is 10") .setHasDefaultValue(10) .setAlias(new String[] {"maxIteration", "numIter"}) .build(); default Integer getMaxIter() { return get(MAX_ITER); } default T setMaxIter(Integer value) { return set(MAX_ITER, value); } }
236
1,411
#pragma once #include <array> #include <fc/crypto/bigint.hpp> #include <fc/crypto/common.hpp> #include <fc/crypto/openssl.hpp> #include <fc/crypto/sha256.hpp> #include <fc/crypto/sha512.hpp> #include <fc/fwd.hpp> #include <fc/io/raw_fwd.hpp> namespace fc { namespace ecc { namespace detail { class public_key_impl; class private_key_impl; } // namespace detail typedef fc::sha256 blind_factor_type; typedef std::array<char, 33> commitment_type; typedef std::array<char, 33> public_key_data; typedef fc::sha256 private_key_secret; typedef std::array<char, 65> public_key_point_data; ///< the full non-compressed version of the ECC point typedef std::array<char, 72> signature; typedef std::array<unsigned char, 65> compact_signature; typedef std::vector<char> range_proof_type; typedef std::array<char, 78> extended_key_data; typedef fc::sha256 blinded_hash; typedef fc::sha256 blind_signature; /** * @class public_key * @brief contains only the public point of an elliptic curve key. */ class public_key { public: public_key(); public_key(const public_key& k); ~public_key(); public_key_data serialize() const; public_key_point_data serialize_ecc_point() const; operator public_key_data() const { return serialize(); } public_key(const public_key_data& v); public_key(const public_key_point_data& v); public_key(const compact_signature& c, const fc::sha256& digest, bool check_canonical = true); public_key child(const fc::sha256& offset) const; bool valid() const; /** Computes new pubkey = generator * offset + old pubkey ?! */ // public_key mult( const fc::sha256& offset )const; /** Computes new pubkey = regenerate(offset).pubkey + old pubkey * = offset * G + 1 * old pubkey ?! */ public_key add(const fc::sha256& offset) const; public_key(public_key&& pk); public_key& operator=(public_key&& pk); public_key& operator=(const public_key& pk); inline friend bool operator==(const public_key& a, const public_key& b) { return a.serialize() == b.serialize(); } inline friend bool operator!=(const public_key& a, const public_key& b) { return a.serialize() != b.serialize(); } /// Allows to convert current public key object into base58 number. std::string to_base58() const; static std::string to_base58(const public_key_data& key); static public_key from_base58(const std::string& b58); unsigned int fingerprint() const; private: friend class private_key; static public_key from_key_data(const public_key_data& v); static bool is_canonical(const compact_signature& c); fc::fwd<detail::public_key_impl, 33> my; }; /** * @class private_key * @brief an elliptic curve private key. */ class private_key { public: private_key(); private_key(private_key&& pk); private_key(const private_key& pk); ~private_key(); private_key& operator=(private_key&& pk); private_key& operator=(const private_key& pk); static private_key generate(); static private_key regenerate(const fc::sha256& secret); private_key child(const fc::sha256& offset) const; /** * This method of generation enables creating a new private key in a deterministic manner relative to * an initial seed. A public_key created from the seed can be multiplied by the offset to calculate * the new public key without having to know the private key. */ static private_key generate_from_seed(const fc::sha256& seed, const fc::sha256& offset = fc::sha256()); private_key_secret get_secret() const; // get the private key secret operator private_key_secret() const { return get_secret(); } /** * Given a public key, calculatse a 512 bit shared secret between that * key and this private key. */ fc::sha512 get_shared_secret(const public_key& pub) const; compact_signature sign_compact(const fc::sha256& digest, bool require_canonical = true) const; public_key get_public_key() const; inline friend bool operator==(const private_key& a, const private_key& b) { return a.get_secret() == b.get_secret(); } inline friend bool operator!=(const private_key& a, const private_key& b) { return a.get_secret() != b.get_secret(); } inline friend bool operator<(const private_key& a, const private_key& b) { return a.get_secret() < b.get_secret(); } unsigned int fingerprint() const { return get_public_key().fingerprint(); } private: private_key(EC_KEY* k); static fc::sha256 get_secret(const EC_KEY* const k); fc::fwd<detail::private_key_impl, 32> my; }; struct range_proof_info { int exp; int mantissa; uint64_t min_value; uint64_t max_value; }; commitment_type blind(const blind_factor_type& blind, uint64_t value); blind_factor_type blind_sum(const std::vector<blind_factor_type>& blinds, uint32_t non_neg); /** verifies taht commnits + neg_commits + excess == 0 */ bool verify_sum(const std::vector<commitment_type>& commits, const std::vector<commitment_type>& neg_commits, int64_t excess); bool verify_range(uint64_t& min_val, uint64_t& max_val, const commitment_type& commit, const range_proof_type& proof); range_proof_type range_proof_sign(uint64_t min_value, const commitment_type& commit, const blind_factor_type& commit_blind, const blind_factor_type& nonce, int8_t base10_exp, uint8_t min_bits, uint64_t actual_value); bool verify_range_proof_rewind(blind_factor_type& blind_out, uint64_t& value_out, string& message_out, const blind_factor_type& nonce, uint64_t& min_val, uint64_t& max_val, commitment_type commit, const range_proof_type& proof); range_proof_info range_get_info(const range_proof_type& proof); /** * Shims */ struct public_key_shim : public crypto::shim<public_key_data> { using crypto::shim<public_key_data>::shim; bool valid() const { return public_key(_data).valid(); } }; struct signature_shim : public crypto::shim<compact_signature> { using public_key_type = public_key_shim; using crypto::shim<compact_signature>::shim; public_key_type recover(const sha256& digest, bool check_canonical) const { return public_key_type(public_key(_data, digest, check_canonical).serialize()); } }; struct private_key_shim : public crypto::shim<private_key_secret> { using crypto::shim<private_key_secret>::shim; using signature_type = signature_shim; using public_key_type = public_key_shim; signature_type sign(const sha256& digest, bool require_canonical = true) const { return signature_type(private_key::regenerate(_data).sign_compact(digest, require_canonical)); } public_key_type get_public_key() const { return public_key_type(private_key::regenerate(_data).get_public_key().serialize()); } sha512 generate_shared_secret(const public_key_type& pub_key) const { return private_key::regenerate(_data).get_shared_secret(public_key(pub_key.serialize())); } static private_key_shim generate() { return private_key_shim(private_key::generate().get_secret()); } }; } // namespace ecc void to_variant(const ecc::private_key& var, variant& vo); void from_variant(const variant& var, ecc::private_key& vo); void to_variant(const ecc::public_key& var, variant& vo); void from_variant(const variant& var, ecc::public_key& vo); namespace raw { template<typename Stream> void unpack(Stream& s, fc::ecc::public_key& pk) { ecc::public_key_data ser; fc::raw::unpack(s, ser); pk = fc::ecc::public_key(ser); } template<typename Stream> void pack(Stream& s, const fc::ecc::public_key& pk) { fc::raw::pack(s, pk.serialize()); } template<typename Stream> void unpack(Stream& s, fc::ecc::private_key& pk) { fc::sha256 sec; unpack(s, sec); pk = ecc::private_key::regenerate(sec); } template<typename Stream> void pack(Stream& s, const fc::ecc::private_key& pk) { fc::raw::pack(s, pk.get_secret()); } } // namespace raw } // namespace fc #include <fc/reflect/reflect.hpp> FC_REFLECT_TYPENAME(fc::ecc::private_key); FC_REFLECT_TYPENAME(fc::ecc::public_key); FC_REFLECT(fc::ecc::range_proof_info, (exp)(mantissa)(min_value)(max_value)); FC_REFLECT_DERIVED(fc::ecc::public_key_shim, (fc::crypto::shim<fc::ecc::public_key_data>), BOOST_PP_SEQ_NIL); FC_REFLECT_DERIVED(fc::ecc::signature_shim, (fc::crypto::shim<fc::ecc::compact_signature>), BOOST_PP_SEQ_NIL); FC_REFLECT_DERIVED(fc::ecc::private_key_shim, (fc::crypto::shim<fc::ecc::private_key_secret>), BOOST_PP_SEQ_NIL);
4,032
2,285
<gh_stars>1000+ import os from samcli.lib.sync.flows.function_sync_flow import wait_for_function_update_complete from samcli.lib.sync.sync_flow import ApiCallTypes from unittest import TestCase from unittest.mock import MagicMock, mock_open, patch from samcli.lib.sync.flows.zip_function_sync_flow import ZipFunctionSyncFlow class TestZipFunctionSyncFlow(TestCase): def create_function_sync_flow(self): sync_flow = ZipFunctionSyncFlow( "Function1", build_context=MagicMock(), deploy_context=MagicMock(), physical_id_mapping={}, stacks=[MagicMock()], ) sync_flow._get_resource_api_calls = MagicMock() return sync_flow @patch("samcli.lib.sync.sync_flow.get_boto_client_provider_from_session_with_config") @patch("samcli.lib.sync.sync_flow.Session") def test_set_up(self, session_mock, client_provider_mock): sync_flow = self.create_function_sync_flow() sync_flow.set_up() client_provider_mock.return_value.assert_any_call("lambda") client_provider_mock.return_value.assert_any_call("s3") @patch("samcli.lib.sync.flows.zip_function_sync_flow.hashlib.sha256") @patch("samcli.lib.sync.flows.zip_function_sync_flow.uuid.uuid4") @patch("samcli.lib.sync.flows.zip_function_sync_flow.file_checksum") @patch("samcli.lib.sync.flows.zip_function_sync_flow.make_zip") @patch("samcli.lib.sync.flows.zip_function_sync_flow.tempfile.gettempdir") @patch("samcli.lib.sync.flows.zip_function_sync_flow.ApplicationBuilder") @patch("samcli.lib.sync.sync_flow.Session") def test_gather_resources( self, session_mock, builder_mock, gettempdir_mock, make_zip_mock, file_checksum_mock, uuid4_mock, sha256_mock ): get_mock = MagicMock() get_mock.return_value = "ArtifactFolder1" builder_mock.return_value.build.return_value.artifacts.get = get_mock uuid4_mock.return_value.hex = "uuid_value" gettempdir_mock.return_value = "temp_folder" make_zip_mock.return_value = "zip_file" file_checksum_mock.return_value = "sha256_value" sync_flow = self.create_function_sync_flow() sync_flow._get_lock_chain = MagicMock() sync_flow.has_locks = MagicMock() sync_flow.set_up() sync_flow.gather_resources() get_mock.assert_called_once_with("Function1") self.assertEqual(sync_flow._artifact_folder, "ArtifactFolder1") make_zip_mock.assert_called_once_with("temp_folder" + os.sep + "data-uuid_value", "ArtifactFolder1") file_checksum_mock.assert_called_once_with("zip_file", sha256_mock.return_value) self.assertEqual("sha256_value", sync_flow._local_sha) sync_flow._get_lock_chain.assert_called_once() sync_flow._get_lock_chain.return_value.__enter__.assert_called_once() sync_flow._get_lock_chain.return_value.__exit__.assert_called_once() @patch("samcli.lib.sync.flows.zip_function_sync_flow.base64.b64decode") @patch("samcli.lib.sync.sync_flow.Session") def test_compare_remote_true(self, session_mock, b64decode_mock): b64decode_mock.return_value.hex.return_value = "sha256_value" sync_flow = self.create_function_sync_flow() sync_flow._local_sha = "sha256_value" sync_flow.get_physical_id = MagicMock() sync_flow.get_physical_id.return_value = "PhysicalFunction1" sync_flow.set_up() sync_flow._lambda_client.get_function.return_value = {"Configuration": {"CodeSha256": "sha256_value_b64"}} result = sync_flow.compare_remote() sync_flow._lambda_client.get_function.assert_called_once_with(FunctionName="PhysicalFunction1") b64decode_mock.assert_called_once_with("sha256_value_b64") self.assertTrue(result) @patch("samcli.lib.sync.flows.zip_function_sync_flow.base64.b64decode") @patch("samcli.lib.sync.sync_flow.Session") def test_compare_remote_false(self, session_mock, b64decode_mock): b64decode_mock.return_value.hex.return_value = "sha256_value_2" sync_flow = self.create_function_sync_flow() sync_flow._local_sha = "sha256_value" sync_flow.get_physical_id = MagicMock() sync_flow.get_physical_id.return_value = "PhysicalFunction1" sync_flow.set_up() sync_flow._lambda_client.get_function.return_value = {"Configuration": {"CodeSha256": "sha256_value_b64"}} result = sync_flow.compare_remote() sync_flow._lambda_client.get_function.assert_called_once_with(FunctionName="PhysicalFunction1") b64decode_mock.assert_called_once_with("sha256_value_b64") self.assertFalse(result) @patch("samcli.lib.sync.flows.zip_function_sync_flow.wait_for_function_update_complete") @patch("samcli.lib.sync.flows.zip_function_sync_flow.open", mock_open(read_data=b"zip_content"), create=True) @patch("samcli.lib.sync.flows.zip_function_sync_flow.os.remove") @patch("samcli.lib.sync.flows.zip_function_sync_flow.os.path.exists") @patch("samcli.lib.sync.flows.zip_function_sync_flow.S3Uploader") @patch("samcli.lib.sync.flows.zip_function_sync_flow.os.path.getsize") @patch("samcli.lib.sync.sync_flow.Session") def test_sync_direct(self, session_mock, getsize_mock, uploader_mock, exists_mock, remove_mock, wait_mock): getsize_mock.return_value = 49 * 1024 * 1024 exists_mock.return_value = True sync_flow = self.create_function_sync_flow() sync_flow._zip_file = "zip_file" sync_flow._get_lock_chain = MagicMock() sync_flow.has_locks = MagicMock() sync_flow.get_physical_id = MagicMock() sync_flow.get_physical_id.return_value = "PhysicalFunction1" sync_flow.set_up() sync_flow.sync() sync_flow._get_lock_chain.assert_called_once() sync_flow._get_lock_chain.return_value.__enter__.assert_called_once() sync_flow._lambda_client.update_function_code.assert_called_once_with( FunctionName="PhysicalFunction1", ZipFile=b"zip_content" ) wait_mock.assert_called_once_with(sync_flow._lambda_client, "PhysicalFunction1") sync_flow._get_lock_chain.return_value.__exit__.assert_called_once() remove_mock.assert_called_once_with("zip_file") @patch("samcli.lib.sync.flows.zip_function_sync_flow.wait_for_function_update_complete") @patch("samcli.lib.sync.flows.zip_function_sync_flow.open", mock_open(read_data=b"zip_content"), create=True) @patch("samcli.lib.sync.flows.zip_function_sync_flow.os.remove") @patch("samcli.lib.sync.flows.zip_function_sync_flow.os.path.exists") @patch("samcli.lib.sync.flows.zip_function_sync_flow.S3Uploader") @patch("samcli.lib.sync.flows.zip_function_sync_flow.os.path.getsize") @patch("samcli.lib.sync.sync_flow.Session") def test_sync_s3(self, session_mock, getsize_mock, uploader_mock, exists_mock, remove_mock, wait_mock): getsize_mock.return_value = 51 * 1024 * 1024 exists_mock.return_value = True uploader_mock.return_value.upload_with_dedup.return_value = "s3://bucket_name/bucket/key" sync_flow = self.create_function_sync_flow() sync_flow._zip_file = "zip_file" sync_flow._deploy_context.s3_bucket = "bucket_name" sync_flow._get_lock_chain = MagicMock() sync_flow.has_locks = MagicMock() sync_flow.get_physical_id = MagicMock() sync_flow.get_physical_id.return_value = "PhysicalFunction1" sync_flow.set_up() sync_flow.sync() uploader_mock.return_value.upload_with_dedup.assert_called_once_with("zip_file") sync_flow._get_lock_chain.assert_called_once() sync_flow._get_lock_chain.return_value.__enter__.assert_called_once() sync_flow._lambda_client.update_function_code.assert_called_once_with( FunctionName="PhysicalFunction1", S3Bucket="bucket_name", S3Key="bucket/key" ) wait_mock.assert_called_once_with(sync_flow._lambda_client, "PhysicalFunction1") sync_flow._get_lock_chain.return_value.__exit__.assert_called_once() remove_mock.assert_called_once_with("zip_file") @patch("samcli.lib.sync.flows.zip_function_sync_flow.ResourceAPICall") def test_get_resource_api_calls(self, resource_api_call_mock): build_context = MagicMock() layer1 = MagicMock() layer2 = MagicMock() layer1.full_path = "Layer1" layer2.full_path = "Layer2" function_mock = MagicMock() function_mock.layers = [layer1, layer2] function_mock.codeuri = "CodeUri/" build_context.function_provider.functions.get.return_value = function_mock sync_flow = ZipFunctionSyncFlow( "Function1", build_context=build_context, deploy_context=MagicMock(), physical_id_mapping={}, stacks=[MagicMock()], ) result = sync_flow._get_resource_api_calls() self.assertEqual(len(result), 4) resource_api_call_mock.assert_any_call("Layer1", [ApiCallTypes.BUILD]) resource_api_call_mock.assert_any_call("Layer2", [ApiCallTypes.BUILD]) resource_api_call_mock.assert_any_call("CodeUri/", [ApiCallTypes.BUILD]) resource_api_call_mock.assert_any_call( "Function1", [ApiCallTypes.UPDATE_FUNCTION_CODE, ApiCallTypes.UPDATE_FUNCTION_CONFIGURATION] ) def test_combine_dependencies(self): sync_flow = self.create_function_sync_flow() self.assertTrue(sync_flow._combine_dependencies()) def test_verify_function_status_recursion(self): given_lambda_client = MagicMock() given_physical_id = "function" function_result1 = {"Configuration": {"LastUpdateStatus": "InProgress"}} function_result2 = {"Configuration": {"LastUpdateStatus": "Successful"}} given_lambda_client.get_function.side_effect = [function_result1, function_result1, function_result2] wait_for_function_update_complete(given_lambda_client, given_physical_id) given_lambda_client.get_function.assert_called_with(FunctionName=given_physical_id) self.assertEqual(given_lambda_client.get_function.call_count, 3) def test_wait_for_function_status_failure(self): given_lambda_client = MagicMock() given_physical_id = "function" function_result = {"Configuration": {"LastUpdateStatus": "Failure"}} given_lambda_client.get_function.return_value = function_result wait_for_function_update_complete(given_lambda_client, given_physical_id) given_lambda_client.get_function.assert_called_with(FunctionName=given_physical_id)
4,519
809
/** * @file * @brief Implementation of #memchr() function. * * @date 10.11.11 * @author <NAME> */ #include <string.h> void *memchr(const void *s, int c, size_t n) { const unsigned char *src = (const unsigned char *) s; unsigned char d = c; while (n--) { if (*src == d) return (void *) src; src++; } return NULL; }
136
1,079
// Copyright 2004-present Facebook. All Rights Reserved. package com.facebook.react.uimanager.layoutanimation; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; import android.view.View; import android.view.animation.Animation; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.UiThreadUtil; /** * Class responsible for animation layout changes, if a valid layout animation config has been * supplied. If not animation is available, layout change is applied immediately instead of * performing an animation. * * TODO(7613721): Invoke success callback at the end of animation and when animation gets cancelled. */ @NotThreadSafe public class LayoutAnimationController { private static final boolean ENABLED = true; private final AbstractLayoutAnimation mLayoutCreateAnimation = new LayoutCreateAnimation(); private final AbstractLayoutAnimation mLayoutUpdateAnimation = new LayoutUpdateAnimation(); private boolean mShouldAnimateLayout; public void initializeFromConfig(final @Nullable ReadableMap config) { if (!ENABLED) { return; } if (config == null) { reset(); return; } mShouldAnimateLayout = false; int globalDuration = config.hasKey("duration") ? config.getInt("duration") : 0; if (config.hasKey(LayoutAnimationType.CREATE.toString())) { mLayoutCreateAnimation.initializeFromConfig( config.getMap(LayoutAnimationType.CREATE.toString()), globalDuration); mShouldAnimateLayout = true; } if (config.hasKey(LayoutAnimationType.UPDATE.toString())) { mLayoutUpdateAnimation.initializeFromConfig( config.getMap(LayoutAnimationType.UPDATE.toString()), globalDuration); mShouldAnimateLayout = true; } } public void reset() { mLayoutCreateAnimation.reset(); mLayoutUpdateAnimation.reset(); mShouldAnimateLayout = false; } public boolean shouldAnimateLayout(View viewToAnimate) { // if view parent is null, skip animation: view have been clipped, we don't want animation to // resume when view is re-attached to parent, which is the standard android animation behavior. return mShouldAnimateLayout && viewToAnimate.getParent() != null; } /** * Update layout of given view, via immediate update or animation depending on the current batch * layout animation configuration supplied during initialization. * * @param view the view to update layout of * @param x the new X position for the view * @param y the new Y position for the view * @param width the new width value for the view * @param height the new height value for the view */ public void applyLayoutUpdate(View view, int x, int y, int width, int height) { UiThreadUtil.assertOnUiThread(); // Determine which animation to use : if view is initially invisible, use create animation. // If view is becoming invisible, use delete animation. Otherwise, use update animation. // This approach is easier than maintaining a list of tags for recently created/deleted views. AbstractLayoutAnimation layoutAnimation = (view.getWidth() == 0 || view.getHeight() == 0) ? mLayoutCreateAnimation : mLayoutUpdateAnimation; Animation animation = layoutAnimation.createAnimation(view, x, y, width, height); if (animation == null || !(animation instanceof HandleLayout)) { view.layout(x, y, x + width, y + height); } if (animation != null) { view.startAnimation(animation); } } }
1,048
1,027
<filename>brave/utility/importer/brave_profile_import_impl.h // Copyright (c) 2017 The Brave 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 BRAVE_UTILITY_IMPORTER_BRAVE_PROFILE_IMPORT_IMPL_H_ #define BRAVE_UTILITY_IMPORTER_BRAVE_PROFILE_IMPORT_IMPL_H_ #include <string> #include <memory> #include "chrome/utility/importer/profile_import_impl.h" class BraveProfileImportImpl : public ProfileImportImpl { public: explicit BraveProfileImportImpl( std::unique_ptr<service_manager::ServiceContextRef> service_ref); ~BraveProfileImportImpl() override; private: // chrome::mojom::ProfileImport: void StartImport( const importer::SourceProfile& source_profile, uint16_t items, const base::flat_map<uint32_t, std::string>& localized_strings, chrome::mojom::ProfileImportObserverPtr observer) override; DISALLOW_COPY_AND_ASSIGN(BraveProfileImportImpl); }; #endif // BRAVE_UTILITY_IMPORTER_BRAVE_PROFILE_IMPORT_IMPL_H_
371