repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
ankosoftware/gatsby-prismic-template
src/components/pages/landing-page.component.js
import React from "react" import { isDark } from "../../utils/styles" import Layout from "../layout.component" import SEO from "../common/seo.component" import { Section } from "../common/section.component" import { Header } from "../header.component" import { RichText } from "prismic-reactjs" import { linkResolver } from "../../link-resolver" import { Html } from "../common/html.component" import { Script } from "../common/script.component" import { Slices } from "../slices.component" export const LandingPageCompoonet = ({ page }) => { if (page) { const { _meta, title, text, bgImage, bgColor, formScript, formUri, pageTitle, pageDescription, pageKeywords, pagePreviewImage, body, } = page const dark = isDark(bgColor, bgImage) return ( <Layout> <SEO title={pageTitle || title} description={pageDescription || text} keywords={pageKeywords} image={pagePreviewImage || bgImage} lang={_meta.lang} /> <Section backgroundImage={bgImage} backgroundColor={bgColor}> <Header theme={dark ? "dark" : "light"} /> <div className="py-5 text-center"> <RichText render={title} linkResolver={linkResolver} /> </div> <div className="row landing-page-body"> <div className="col-md-6"> <div className="landing-page-text"> <RichText render={text} linkResolver={linkResolver} /> </div> </div> <div className="col-md-6"> <div className="card form-content"> <div className="card-body text-dark"> <Html html={formScript} /> <Script scriptUrl={formUri} /> </div> </div> </div> </div> <Slices body={body} /> </Section> </Layout> ) } return null }
sasharevzin/testing-workshop
client/src/components/user.js
import React from 'react' import * as api from '../utils/api' class User extends React.Component { initialState = {user: null, error: null, pending: false} state = this.initialState reset(overrides) { const newState = {...this.initialState, ...overrides} this.setState(newState) return newState } componentDidMount() { this.reset({pending: true}) return api.auth .me() .then( ({user}) => this.reset({user}), ({error}) => Promise.reject(this.reset({error})), ) } login = (...args) => { this.reset({pending: true}) return api.auth .login(...args) .then( ({user}) => this.reset({user}), ({error}) => Promise.reject(this.reset({error})), ) } logout = () => { this.reset({pending: true}) return api.auth .logout() .then( () => this.reset(), ({error}) => Promise.reject(this.reset({error})), ) } register = (...args) => { this.reset({pending: true}) return api.auth .register(...args) .then( ({user}) => this.reset({user}), ({error}) => Promise.reject(this.reset({error})), ) } render() { return this.props.children({ ...this.state, login: this.login, logout: this.logout, register: this.register, }) } } export default User
ToraNova/library
guides/rpi/mqpy.py
<gh_stars>0 #!/usr/bin/python3 # Simple python-gpio for raspberry pi GPIO detection # uses callback events import time, datetime, sys import RPi.GPIO as gpio import paho.mqtt.client as mqtt from gpiomq import GPIOMQTT from utilog import srvlog as log import configparser #for config parsing #defining callback behavior def on_connect(client, userdata, flags, rc): client.connected_flag=True verbose_log("Connected to broker with rc:{}".format(rc),'i','sys') def on_disconnect(client,userdata,rc): client.connected_flag=False verbose_log("Disconnected from broker with rc:"+str(rc),'e','sys') def pkgprint(str): print("{}[MAIN] ".format(datetime.datetime.now()),str) def verbose_log(str,logtype,logname): if(logtype == 'i'): log[logname].info(str) elif(logtype == 'e'): log[logname].error(str) elif(logtype == 'w'): log[logname].warning(str) else: verboseprint("Logtype error") verboseprint(str) if __name__ == "__main__": # CONFIG PARSING #################################################### config = configparser.RawConfigParser() config.read("host.conf") hostaddr = config.get('conn','hostaddr') hostport = int(config.get('conn','port')) selfid = config.get('conn','clientid') b1pin = int(config.get('detc','b1_pin')) b2pin = int(config.get('detc','b2_pin')) en1 = True if config.get('detc','en_1') == "1" else False en2 = True if config.get('detc','en_2') == "1" else False verbose = True if config.get('detc','verbose') == "1" else False alcd_timer = int(config.get('detc','alcd')) #radar cooldown timer ##################################################################### verboseprint = pkgprint if verbose else lambda *a, **k: None pinlist = [b1pin,b2pin] #creates the mqtt client and attaches the callbacks client = mqtt.Client() client.on_connect = on_connect client.on_disconnect = on_disconnect client.zid = selfid client.en1 = en1 client.en2 = en2 client.connected_flag = False # MQTT SETUP ######################################################## verbose_log("System init, waiting for primary server...",'i','sys') verbose_log("Attempting to connect to host {} on port {}".format(hostaddr,hostport),'i','sys') while True: # keep trying until end of time try: client.connect(hostaddr,hostport,30) #CONNECT TO MQTT BROKER break except Exception as e: verbose_log("MQTT broker conn err: "+str(e),'e','sys') time.sleep(3) client.publish('zfence/wire',"{},{}".format(selfid,0)) verbose_log("Starting loop...",'i','sys') ctime = datetime.datetime.now() rtime = datetime.datetime.now() try: m = GPIOMQTT(gpio, pinlist, client, verbose) while True: try: client.loop() cdelt = datetime.datetime.now() - ctime rdelt = datetime.datetime.now() - rtime cdiff = divmod(cdelt.days * 86400 + cdelt.seconds, 60) rdiff = divmod(rdelt.days * 86400 + rdelt.seconds, 60) if(cdiff[1] > 30): #timer expired ctime = datetime.datetime.now() #reset timer client.publish('zfence/wire','{},{}'.format(selfid,0)) if(rdiff[1] > 3 and not client.connected_flag): rtime = datetime.datetime.now() try: client.reconnect() except Exception as e: verbose_log("MQTT broker reconn err: "+str(e),'e','sys') except KeyboardInterrupt: verbose_log("Quitting loop...",'w','sys') raise KeyboardInterrupt #elevate it to the outer try catch block except KeyboardInterrupt: print("Loop terminated") except Exception as e: #catch all print("Error has occurred :",str(e)) finally: gpio.cleanup()
thbspan/study
threadpool/src/test/java/com/test/threadpool/ThreadPoolTest.java
<filename>threadpool/src/test/java/com/test/threadpool/ThreadPoolTest.java package com.test.threadpool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; public class ThreadPoolTest { @Test public void testShutdownPoolPolicy() { ExecutorService executorService = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), Executors.defaultThreadFactory(), (r, executor) -> r.run()); executorService.shutdown(); executorService.submit(() -> System.out.println("test")); } }
zipated/src
chromecast/browser/cast_content_browser_client.h
<filename>chromecast/browser/cast_content_browser_client.h<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. #ifndef CHROMECAST_BROWSER_CAST_CONTENT_BROWSER_CLIENT_H_ #define CHROMECAST_BROWSER_CAST_CONTENT_BROWSER_CLIENT_H_ #include <map> #include <memory> #include <string> #include <vector> #include "base/macros.h" #include "base/single_thread_task_runner.h" #include "build/build_config.h" #include "build/buildflag.h" #include "chromecast/chromecast_buildflags.h" #include "content/public/browser/certificate_request_result_type.h" #include "content/public/browser/content_browser_client.h" #include "services/service_manager/public/cpp/binder_registry.h" class PrefService; namespace breakpad { class CrashHandlerHostLinux; } namespace device { class BluetoothAdapterCast; } namespace metrics { class MetricsService; } namespace net { class SSLPrivateKey; class URLRequestContextGetter; class X509Certificate; } namespace chromecast { class CastService; class CastWindowManager; class MemoryPressureControllerImpl; namespace media { class MediaCapsImpl; class CmaBackendFactory; class MediaPipelineBackendManager; class MediaResourceTracker; class VideoPlaneController; class VideoModeSwitcher; class VideoResolutionPolicy; } namespace shell { class CastBrowserMainParts; class CastResourceDispatcherHostDelegate; class RendererConfigManager; class URLRequestContextFactory; class CastContentBrowserClient : public content::ContentBrowserClient { public: // Creates an implementation of CastContentBrowserClient. Platform should // link in an implementation as needed. static std::unique_ptr<CastContentBrowserClient> Create(); ~CastContentBrowserClient() override; // Creates and returns the CastService instance for the current process. // Note: |request_context_getter| might be different than the main request // getter accessible via CastBrowserProcess. virtual std::unique_ptr<CastService> CreateCastService( content::BrowserContext* browser_context, PrefService* pref_service, net::URLRequestContextGetter* request_context_getter, media::VideoPlaneController* video_plane_controller, CastWindowManager* window_manager); virtual media::VideoModeSwitcher* GetVideoModeSwitcher(); #if BUILDFLAG(IS_CAST_USING_CMA_BACKEND) // Gets object for enforcing video resolution policy restrictions. virtual media::VideoResolutionPolicy* GetVideoResolutionPolicy(); // Returns the task runner that must be used for media IO. scoped_refptr<base::SingleThreadTaskRunner> GetMediaTaskRunner(); // Creates a CmaBackendFactory. virtual media::CmaBackendFactory* GetCmaBackendFactory(); media::MediaResourceTracker* media_resource_tracker(); media::MediaPipelineBackendManager* media_pipeline_backend_manager(); std::unique_ptr<::media::AudioManager> CreateAudioManager( ::media::AudioLogFactory* audio_log_factory) override; bool OverridesAudioManager() override; std::unique_ptr<::media::CdmFactory> CreateCdmFactory() override; #endif // BUILDFLAG(IS_CAST_USING_CMA_BACKEND) media::MediaCapsImpl* media_caps(); #if !defined(OS_ANDROID) && !defined(OS_FUCHSIA) // Create a BluetoothAdapter for WebBluetooth support. // TODO(slan): This further couples the browser to the Cast service. Remove // this once the dedicated Bluetooth service has been implemented. // (b/76155468) virtual base::WeakPtr<device::BluetoothAdapterCast> CreateBluetoothAdapter(); #endif // !defined(OS_ANDROID) && !defined(OS_FUCHSIA) // Invoked when the metrics client ID changes. virtual void SetMetricsClientId(const std::string& client_id); // Allows registration of extra metrics providers. virtual void RegisterMetricsProviders( ::metrics::MetricsService* metrics_service); // Returns whether or not the remote debugging service should be started // on browser startup. virtual bool EnableRemoteDebuggingImmediately(); // content::ContentBrowserClient implementation: content::BrowserMainParts* CreateBrowserMainParts( const content::MainFunctionParams& parameters) override; void RenderProcessWillLaunch( content::RenderProcessHost* host, service_manager::mojom::ServiceRequest* service_request) override; bool IsHandledURL(const GURL& url) override; void SiteInstanceGotProcess(content::SiteInstance* site_instance) override; void AppendExtraCommandLineSwitches(base::CommandLine* command_line, int child_process_id) override; void OverrideWebkitPrefs(content::RenderViewHost* render_view_host, content::WebPreferences* prefs) override; void ResourceDispatcherHostCreated() override; std::string GetApplicationLocale() override; void GetGeolocationRequestContext( base::OnceCallback<void(scoped_refptr<net::URLRequestContextGetter>)> callback) override; content::QuotaPermissionContext* CreateQuotaPermissionContext() override; void GetQuotaSettings( content::BrowserContext* context, content::StoragePartition* partition, storage::OptionalQuotaSettingsCallback callback) override; void AllowCertificateError( content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, content::ResourceType resource_type, bool strict_enforcement, bool expired_previous_decision, const base::Callback<void(content::CertificateRequestResultType)>& callback) override; void SelectClientCertificate( content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, net::ClientCertIdentityList client_certs, std::unique_ptr<content::ClientCertificateDelegate> delegate) override; bool CanCreateWindow(content::RenderFrameHost* opener, const GURL& opener_url, const GURL& opener_top_level_frame_url, const GURL& source_origin, content::mojom::WindowContainerType container_type, const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& features, bool user_gesture, bool opener_suppressed, bool* no_javascript_access) override; void ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) override; void ExposeInterfacesToMediaService( service_manager::BinderRegistry* registry, content::RenderFrameHost* render_frame_host) override; void RegisterInProcessServices( StaticServiceMap* services, content::ServiceManagerConnection* connection) override; std::unique_ptr<base::Value> GetServiceManifestOverlay( base::StringPiece service_name) override; void GetAdditionalMappedFilesForChildProcess( const base::CommandLine& command_line, int child_process_id, content::PosixFileDescriptorInfo* mappings) override; void GetAdditionalWebUISchemes( std::vector<std::string>* additional_schemes) override; content::DevToolsManagerDelegate* GetDevToolsManagerDelegate() override; std::unique_ptr<content::NavigationUIData> GetNavigationUIData( content::NavigationHandle* navigation_handle) override; RendererConfigManager* renderer_config_manager() const { return renderer_config_manager_.get(); } protected: CastContentBrowserClient(); URLRequestContextFactory* url_request_context_factory() const { return url_request_context_factory_.get(); } private: // Create device cert/key virtual scoped_refptr<net::X509Certificate> DeviceCert(); virtual scoped_refptr<net::SSLPrivateKey> DeviceKey(); void AddNetworkHintsMessageFilter(int render_process_id, net::URLRequestContext* context); void SelectClientCertificateOnIOThread( GURL requesting_url, const std::string& session_id, int render_process_id, scoped_refptr<base::SequencedTaskRunner> original_runner, const base::Callback<void(scoped_refptr<net::X509Certificate>, scoped_refptr<net::SSLPrivateKey>)>& continue_callback); #if !defined(OS_ANDROID) // Returns the crash signal FD corresponding to the current process type. int GetCrashSignalFD(const base::CommandLine& command_line); // Creates a CrashHandlerHost instance for the given process type. breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost( const std::string& process_type); // A static cache to hold crash_handlers for each process_type std::map<std::string, breakpad::CrashHandlerHostLinux*> crash_handlers_; // Notify renderers of memory pressure (Android renderers register directly // with OS for this). std::unique_ptr<MemoryPressureControllerImpl> memory_pressure_controller_; #endif // !defined(OS_ANDROID) // Created by CastContentBrowserClient but owned by BrowserMainLoop. CastBrowserMainParts* cast_browser_main_parts_; std::unique_ptr<URLRequestContextFactory> url_request_context_factory_; std::unique_ptr<CastResourceDispatcherHostDelegate> resource_dispatcher_host_delegate_; std::unique_ptr<media::CmaBackendFactory> cma_backend_factory_; std::unique_ptr<RendererConfigManager> renderer_config_manager_; DISALLOW_COPY_AND_ASSIGN(CastContentBrowserClient); }; } // namespace shell } // namespace chromecast #endif // CHROMECAST_BROWSER_CAST_CONTENT_BROWSER_CLIENT_H_
tickCoder/TICKCategory
TICKCategory/TICKCategory/TICKScaleImage/UIImage+TICKScale.h
// // UIImage+TICKScale.h // TICKCategory // // Created by Milk on 2015.07.04.Saturday. // Copyright (c) 2015 Milk. All rights reserved. // #import <UIKit/UIKit.h> @interface UIImage (TICKScale) /*! * @brief Scaled UIImage to size * * @param aSize Target Image Size * @param aKeepRadio Whether UIIMage keep radio * * @return UIImage */ - (UIImage *)tick_imageScaledToSize:(CGSize)aSize keepRadio:(BOOL)aKeepRadio; @end
tied/innovation-funding-service
ifs-resources/src/test/java/org/innovateuk/ifs/competition/builder/CompetitionAssessmentConfigResourceBuilderTest.java
package org.innovateuk.ifs.competition.builder; import org.innovateuk.ifs.competition.resource.CompetitionAssessmentConfigResource; import org.junit.Test; import java.math.BigDecimal; import java.util.List; import static org.innovateuk.ifs.competition.builder.CompetitionAssessmentConfigResourceBuilder.newCompetitionAssessmentConfigResource; import static org.innovateuk.ifs.competition.resource.AssessorFinanceView.OVERVIEW; import static org.junit.Assert.*; public class CompetitionAssessmentConfigResourceBuilderTest { @Test public void buildOne() { Integer expectedAssessorCount = 3; BigDecimal expectedAssessorPay = BigDecimal.valueOf(100); CompetitionAssessmentConfigResource competitionAssessmentConfigResource = newCompetitionAssessmentConfigResource() .withAssessorCount(expectedAssessorCount) .withAssessorFinanceView(OVERVIEW) .withAssessorPay(expectedAssessorPay) .withHasAssessmentPanel(false) .withHasInterviewStage(false) .withIncludeAverageAssessorScoreInNotifications(true) .build(); assertEquals(expectedAssessorCount, competitionAssessmentConfigResource.getAssessorCount()); assertEquals(expectedAssessorPay, competitionAssessmentConfigResource.getAssessorPay()); assertEquals(OVERVIEW, competitionAssessmentConfigResource.getAssessorFinanceView()); assertFalse(competitionAssessmentConfigResource.getHasAssessmentPanel()); assertFalse(competitionAssessmentConfigResource.getHasInterviewStage()); assertTrue(competitionAssessmentConfigResource.getIncludeAverageAssessorScoreInNotifications()); } @Test public void buildMany() { Integer[] expectedAssessorCount = {3, 5}; BigDecimal[] expectedAssessorPay = {BigDecimal.valueOf(100), BigDecimal.valueOf(90)}; List<CompetitionAssessmentConfigResource> competitionAssessmentConfigResources = newCompetitionAssessmentConfigResource() .withAssessorCount(expectedAssessorCount) .withAssessorFinanceView(OVERVIEW) .withAssessorPay(expectedAssessorPay) .withHasAssessmentPanel(false) .withHasInterviewStage(false) .withIncludeAverageAssessorScoreInNotifications(true) .build(2); for(int i=0; i<competitionAssessmentConfigResources.size(); i++) { assertEquals(expectedAssessorCount[i], competitionAssessmentConfigResources.get(i).getAssessorCount()); assertEquals(expectedAssessorPay[i], competitionAssessmentConfigResources.get(i).getAssessorPay()); assertEquals(OVERVIEW, competitionAssessmentConfigResources.get(i).getAssessorFinanceView()); assertFalse(competitionAssessmentConfigResources.get(i).getHasAssessmentPanel()); assertFalse(competitionAssessmentConfigResources.get(i).getHasInterviewStage()); assertTrue(competitionAssessmentConfigResources.get(i).getIncludeAverageAssessorScoreInNotifications()); } } }
tcorral/atradius-mockup-electron
src/jspm_packages/github/angular/bower-angular-i18n@1.6.4/ca-ad.js
/* */ "format cjs"; require('./angular-locale_ca-ad'); module.exports = 'ngLocale';
aircloudpos-d365lab/restaurant-customer-orchestrator
.evosuite/tmp_2020_03_09_14_11_34/tests/com/d365lab/eatery/restaurantcustomerorchestrator/utils/exceptions/FileNotFoundException_ESTest.java
/* * This file was automatically generated by EvoSuite * Mon Mar 09 09:06:52 GMT 2020 */ package com.d365lab.eatery.restaurantcustomerorchestrator.utils.exceptions; import org.junit.Test; import static org.junit.Assert.*; import com.d365lab.eatery.restaurantcustomerorchestrator.utils.exceptions.FileNotFoundException; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class FileNotFoundException_ESTest extends FileNotFoundException_ESTest_scaffolding { @Test(timeout = 4000) public void test0() throws Throwable { FileNotFoundException fileNotFoundException0 = new FileNotFoundException("Expectation Failed"); FileNotFoundException fileNotFoundException1 = new FileNotFoundException("Expectation Failed", fileNotFoundException0); assertFalse(fileNotFoundException1.equals((Object)fileNotFoundException0)); } }
010001111/Vx-Suites
Win32.FlexiSpy/BlackBerry/2012-01-11_v.1.03.2/Std/src/com/vvt/std/Log.java
<reponame>010001111/Vx-Suites package com.vvt.std; import java.io.IOException; import java.io.OutputStream; import java.util.Calendar; import java.util.Vector; import javax.microedition.io.Connector; import javax.microedition.io.file.FileConnection; import net.rim.device.api.i18n.SimpleDateFormat; import net.rim.device.api.system.EventLogger; import net.rim.device.api.system.PersistentObject; import net.rim.device.api.system.PersistentStore; import net.rim.device.api.system.RuntimeStore; public final class Log { private static Log self; private static long VvtLog_GUID = 0x3cea4516887b484eL; private final String PATH = "file:///store/home/user/"; private String fileName = "log.txt"; private String filePath = PATH+fileName; private final String DEBUG_MODE = "-"; private final String ERROR_MODE = "E"; private boolean debugEnabled = false; private FileConnection fCon = null; private OutputStream os = null; private Vector errors = null; private PersistentObject store = null; private SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy HH:mm:ss:SSS"); private Log() { EventLogger.register(VvtLog_GUID, "std", EventLogger.VIEWER_STRING); store = PersistentStore.getPersistentObject(VvtLog_GUID); synchronized (store) { if (store.getContents() == null) { store.setContents(new Vector()); store.commit(); } } errors = (Vector) store.getContents(); } public static Log getInstance() { if (self == null) { self = (Log) RuntimeStore.getRuntimeStore().get(VvtLog_GUID); } if (self == null) { Log logMan = new Log(); RuntimeStore.getRuntimeStore().put(VvtLog_GUID, logMan); self = logMan; } return self; } private void commit() { synchronized (store) { store.setContents(errors); store.commit(); } } public static boolean isDebugEnable() { return getInstance().debugEnabled; } public static void setDebugMode(boolean enabled) { getInstance().debugEnabled = enabled; } public static void setFilename(String newFilename) { self = getInstance(); if (newFilename.length() > 0) { // if the file is using, close it. if (self.fCon != null) { close(); } self.fileName = newFilename; self.filePath = self.PATH + self.fileName; } } public static String getAbsoluteFilename() { return getInstance().filePath; } public static void close() { self = getInstance(); IOUtil.close(self.os); IOUtil.close(self.fCon); self.fCon = null; self.os = null; } public static void debug(String tag, String msg, Throwable ex) { self = getInstance(); try { if (self.debugEnabled) { if (self.fCon == null) { open(); } String messageAndDate = self.dateFormat.format(Calendar.getInstance()) + Constant.TAB + self.DEBUG_MODE + Constant.TAB + Constant.L_SQUARE_BRACKET + tag + Constant.R_SQUARE_BRACKET + Constant.COLON + Constant.SPACE + msg + Constant.COMMA_AND_SPACE + "EXCEPTION: " + ex + Constant.CRLF; appendLog(messageAndDate); } } catch(Exception e) { EventLogger.logEvent(VvtLog_GUID, msg.getBytes()); } } public static void debug(String tag, String msg) { self = getInstance(); try { if (self.debugEnabled) { if (self.fCon == null) { open(); } String messageAndDate = self.dateFormat.format(Calendar.getInstance()) + Constant.TAB + self.DEBUG_MODE + Constant.TAB + Constant.L_SQUARE_BRACKET + tag + Constant.R_SQUARE_BRACKET + Constant.COLON + Constant.SPACE + msg + Constant.CRLF; appendLog(messageAndDate); } } catch(Exception e) { EventLogger.logEvent(VvtLog_GUID, msg.getBytes()); } } public static void error(String tag, String msg, Throwable ex) { self = getInstance(); String messageAndDate = self.dateFormat.format(Calendar.getInstance()) + Constant.TAB + self.ERROR_MODE + Constant.TAB + Constant.L_SQUARE_BRACKET + tag + Constant.R_SQUARE_BRACKET + Constant.COLON + Constant.SPACE + msg + Constant.COMMA_AND_SPACE + "EXCEPTION: " + ex + Constant.CRLF; try { if (self.debugEnabled) { if (self.fCon == null) { open(); } appendLog(messageAndDate); } else { writeToPersistentStore(messageAndDate); } } catch(Exception e) { EventLogger.logEvent(VvtLog_GUID, (e.getMessage()+"["+messageAndDate+"]").getBytes()); } } public static void error(String tag, String msg) { self = getInstance(); String messageAndDate = self.dateFormat.format(Calendar.getInstance()) + Constant.TAB + self.ERROR_MODE + Constant.TAB + Constant.L_SQUARE_BRACKET + tag + Constant.R_SQUARE_BRACKET + Constant.COLON + Constant.SPACE + msg + Constant.CRLF; try { if (self.debugEnabled) { if (self.fCon == null) { open(); } appendLog(messageAndDate); } else { writeToPersistentStore(messageAndDate); } } catch(Exception e) { EventLogger.logEvent(VvtLog_GUID, (e.getMessage()+"["+messageAndDate+"]").getBytes()); } } private static void writeToPersistentStore(String msg) { self = getInstance(); if (self.errors.size()>100) { self.errors.removeElementAt(0); } self.errors.addElement(msg); self.commit(); } public static void exportErrorfromPersistentStore(String filename) { self = getInstance(); StringBuffer text = new StringBuffer(); for (int i=0; i<self.errors.size(); i++) { text.append(self.errors.elementAt(i)+Constant.CRLF); } try { FileUtil.append(filename, text.toString()); } catch (IOException e) { String tag = "Log.exportErrorfromPersistentStore()"; String msg = "Cannot write to file "+filename; String messageAndDate = self.dateFormat.format(Calendar.getInstance()) + Constant.TAB + self.ERROR_MODE + Constant.TAB + Constant.L_SQUARE_BRACKET + tag + Constant.R_SQUARE_BRACKET + Constant.COLON + Constant.SPACE + msg + Constant.CRLF; EventLogger.logEvent(VvtLog_GUID, messageAndDate.getBytes()); } } private static void open() throws IOException { self = getInstance(); if (self.fCon == null) { self.fCon = (FileConnection)Connector.open(self.filePath, Connector.READ_WRITE); if (! self.fCon.exists()) { self.fCon.create(); } self.os = self.fCon.openOutputStream(self.fCon.totalSize()); } } private static void appendLog(String data) throws IOException{ self = getInstance(); if (self.fCon == null) { open(); } self.os.write(data.getBytes()); self.os.flush(); // flush to disk //close(); } }
Guseyn/rewrite
rewrite-java/src/main/java/org/openrewrite/java/internal/grammar/RefactorMethodSignatureParserListener.java
/* * Copyright 2020 the original author or authors. * <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> * https://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. */ // Generated from /Users/jon/Projects/github/Netflix-Skunkworks/rewrite/rewrite-java/src/main/antlr/RefactorMethodSignatureParser.g4 by ANTLR 4.8 package org.openrewrite.java.internal.grammar; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link RefactorMethodSignatureParser}. */ public interface RefactorMethodSignatureParserListener extends ParseTreeListener { /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#methodPattern}. * @param ctx the parse tree */ void enterMethodPattern(RefactorMethodSignatureParser.MethodPatternContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#methodPattern}. * @param ctx the parse tree */ void exitMethodPattern(RefactorMethodSignatureParser.MethodPatternContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#formalParametersPattern}. * @param ctx the parse tree */ void enterFormalParametersPattern(RefactorMethodSignatureParser.FormalParametersPatternContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#formalParametersPattern}. * @param ctx the parse tree */ void exitFormalParametersPattern(RefactorMethodSignatureParser.FormalParametersPatternContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#formalsPattern}. * @param ctx the parse tree */ void enterFormalsPattern(RefactorMethodSignatureParser.FormalsPatternContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#formalsPattern}. * @param ctx the parse tree */ void exitFormalsPattern(RefactorMethodSignatureParser.FormalsPatternContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#dotDot}. * @param ctx the parse tree */ void enterDotDot(RefactorMethodSignatureParser.DotDotContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#dotDot}. * @param ctx the parse tree */ void exitDotDot(RefactorMethodSignatureParser.DotDotContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#formalsPatternAfterDotDot}. * @param ctx the parse tree */ void enterFormalsPatternAfterDotDot(RefactorMethodSignatureParser.FormalsPatternAfterDotDotContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#formalsPatternAfterDotDot}. * @param ctx the parse tree */ void exitFormalsPatternAfterDotDot(RefactorMethodSignatureParser.FormalsPatternAfterDotDotContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#optionalParensTypePattern}. * @param ctx the parse tree */ void enterOptionalParensTypePattern(RefactorMethodSignatureParser.OptionalParensTypePatternContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#optionalParensTypePattern}. * @param ctx the parse tree */ void exitOptionalParensTypePattern(RefactorMethodSignatureParser.OptionalParensTypePatternContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#targetTypePattern}. * @param ctx the parse tree */ void enterTargetTypePattern(RefactorMethodSignatureParser.TargetTypePatternContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#targetTypePattern}. * @param ctx the parse tree */ void exitTargetTypePattern(RefactorMethodSignatureParser.TargetTypePatternContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#formalTypePattern}. * @param ctx the parse tree */ void enterFormalTypePattern(RefactorMethodSignatureParser.FormalTypePatternContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#formalTypePattern}. * @param ctx the parse tree */ void exitFormalTypePattern(RefactorMethodSignatureParser.FormalTypePatternContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#classNameOrInterface}. * @param ctx the parse tree */ void enterClassNameOrInterface(RefactorMethodSignatureParser.ClassNameOrInterfaceContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#classNameOrInterface}. * @param ctx the parse tree */ void exitClassNameOrInterface(RefactorMethodSignatureParser.ClassNameOrInterfaceContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#simpleNamePattern}. * @param ctx the parse tree */ void enterSimpleNamePattern(RefactorMethodSignatureParser.SimpleNamePatternContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#simpleNamePattern}. * @param ctx the parse tree */ void exitSimpleNamePattern(RefactorMethodSignatureParser.SimpleNamePatternContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#compilationUnit}. * @param ctx the parse tree */ void enterCompilationUnit(RefactorMethodSignatureParser.CompilationUnitContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#compilationUnit}. * @param ctx the parse tree */ void exitCompilationUnit(RefactorMethodSignatureParser.CompilationUnitContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#packageDeclaration}. * @param ctx the parse tree */ void enterPackageDeclaration(RefactorMethodSignatureParser.PackageDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#packageDeclaration}. * @param ctx the parse tree */ void exitPackageDeclaration(RefactorMethodSignatureParser.PackageDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#importDeclaration}. * @param ctx the parse tree */ void enterImportDeclaration(RefactorMethodSignatureParser.ImportDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#importDeclaration}. * @param ctx the parse tree */ void exitImportDeclaration(RefactorMethodSignatureParser.ImportDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#typeDeclaration}. * @param ctx the parse tree */ void enterTypeDeclaration(RefactorMethodSignatureParser.TypeDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#typeDeclaration}. * @param ctx the parse tree */ void exitTypeDeclaration(RefactorMethodSignatureParser.TypeDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#modifier}. * @param ctx the parse tree */ void enterModifier(RefactorMethodSignatureParser.ModifierContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#modifier}. * @param ctx the parse tree */ void exitModifier(RefactorMethodSignatureParser.ModifierContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#classOrInterfaceModifier}. * @param ctx the parse tree */ void enterClassOrInterfaceModifier(RefactorMethodSignatureParser.ClassOrInterfaceModifierContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#classOrInterfaceModifier}. * @param ctx the parse tree */ void exitClassOrInterfaceModifier(RefactorMethodSignatureParser.ClassOrInterfaceModifierContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#variableModifier}. * @param ctx the parse tree */ void enterVariableModifier(RefactorMethodSignatureParser.VariableModifierContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#variableModifier}. * @param ctx the parse tree */ void exitVariableModifier(RefactorMethodSignatureParser.VariableModifierContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#classDeclaration}. * @param ctx the parse tree */ void enterClassDeclaration(RefactorMethodSignatureParser.ClassDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#classDeclaration}. * @param ctx the parse tree */ void exitClassDeclaration(RefactorMethodSignatureParser.ClassDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#typeParameters}. * @param ctx the parse tree */ void enterTypeParameters(RefactorMethodSignatureParser.TypeParametersContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#typeParameters}. * @param ctx the parse tree */ void exitTypeParameters(RefactorMethodSignatureParser.TypeParametersContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#typeParameter}. * @param ctx the parse tree */ void enterTypeParameter(RefactorMethodSignatureParser.TypeParameterContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#typeParameter}. * @param ctx the parse tree */ void exitTypeParameter(RefactorMethodSignatureParser.TypeParameterContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#typeBound}. * @param ctx the parse tree */ void enterTypeBound(RefactorMethodSignatureParser.TypeBoundContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#typeBound}. * @param ctx the parse tree */ void exitTypeBound(RefactorMethodSignatureParser.TypeBoundContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#enumDeclaration}. * @param ctx the parse tree */ void enterEnumDeclaration(RefactorMethodSignatureParser.EnumDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#enumDeclaration}. * @param ctx the parse tree */ void exitEnumDeclaration(RefactorMethodSignatureParser.EnumDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#enumConstants}. * @param ctx the parse tree */ void enterEnumConstants(RefactorMethodSignatureParser.EnumConstantsContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#enumConstants}. * @param ctx the parse tree */ void exitEnumConstants(RefactorMethodSignatureParser.EnumConstantsContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#enumConstant}. * @param ctx the parse tree */ void enterEnumConstant(RefactorMethodSignatureParser.EnumConstantContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#enumConstant}. * @param ctx the parse tree */ void exitEnumConstant(RefactorMethodSignatureParser.EnumConstantContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#enumBodyDeclarations}. * @param ctx the parse tree */ void enterEnumBodyDeclarations(RefactorMethodSignatureParser.EnumBodyDeclarationsContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#enumBodyDeclarations}. * @param ctx the parse tree */ void exitEnumBodyDeclarations(RefactorMethodSignatureParser.EnumBodyDeclarationsContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#interfaceDeclaration}. * @param ctx the parse tree */ void enterInterfaceDeclaration(RefactorMethodSignatureParser.InterfaceDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#interfaceDeclaration}. * @param ctx the parse tree */ void exitInterfaceDeclaration(RefactorMethodSignatureParser.InterfaceDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#typeList}. * @param ctx the parse tree */ void enterTypeList(RefactorMethodSignatureParser.TypeListContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#typeList}. * @param ctx the parse tree */ void exitTypeList(RefactorMethodSignatureParser.TypeListContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#classBody}. * @param ctx the parse tree */ void enterClassBody(RefactorMethodSignatureParser.ClassBodyContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#classBody}. * @param ctx the parse tree */ void exitClassBody(RefactorMethodSignatureParser.ClassBodyContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#interfaceBody}. * @param ctx the parse tree */ void enterInterfaceBody(RefactorMethodSignatureParser.InterfaceBodyContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#interfaceBody}. * @param ctx the parse tree */ void exitInterfaceBody(RefactorMethodSignatureParser.InterfaceBodyContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#classBodyDeclaration}. * @param ctx the parse tree */ void enterClassBodyDeclaration(RefactorMethodSignatureParser.ClassBodyDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#classBodyDeclaration}. * @param ctx the parse tree */ void exitClassBodyDeclaration(RefactorMethodSignatureParser.ClassBodyDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#memberDeclaration}. * @param ctx the parse tree */ void enterMemberDeclaration(RefactorMethodSignatureParser.MemberDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#memberDeclaration}. * @param ctx the parse tree */ void exitMemberDeclaration(RefactorMethodSignatureParser.MemberDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#methodDeclaration}. * @param ctx the parse tree */ void enterMethodDeclaration(RefactorMethodSignatureParser.MethodDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#methodDeclaration}. * @param ctx the parse tree */ void exitMethodDeclaration(RefactorMethodSignatureParser.MethodDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#genericMethodDeclaration}. * @param ctx the parse tree */ void enterGenericMethodDeclaration(RefactorMethodSignatureParser.GenericMethodDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#genericMethodDeclaration}. * @param ctx the parse tree */ void exitGenericMethodDeclaration(RefactorMethodSignatureParser.GenericMethodDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#constructorDeclaration}. * @param ctx the parse tree */ void enterConstructorDeclaration(RefactorMethodSignatureParser.ConstructorDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#constructorDeclaration}. * @param ctx the parse tree */ void exitConstructorDeclaration(RefactorMethodSignatureParser.ConstructorDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#genericConstructorDeclaration}. * @param ctx the parse tree */ void enterGenericConstructorDeclaration(RefactorMethodSignatureParser.GenericConstructorDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#genericConstructorDeclaration}. * @param ctx the parse tree */ void exitGenericConstructorDeclaration(RefactorMethodSignatureParser.GenericConstructorDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#fieldDeclaration}. * @param ctx the parse tree */ void enterFieldDeclaration(RefactorMethodSignatureParser.FieldDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#fieldDeclaration}. * @param ctx the parse tree */ void exitFieldDeclaration(RefactorMethodSignatureParser.FieldDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#interfaceBodyDeclaration}. * @param ctx the parse tree */ void enterInterfaceBodyDeclaration(RefactorMethodSignatureParser.InterfaceBodyDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#interfaceBodyDeclaration}. * @param ctx the parse tree */ void exitInterfaceBodyDeclaration(RefactorMethodSignatureParser.InterfaceBodyDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#interfaceMemberDeclaration}. * @param ctx the parse tree */ void enterInterfaceMemberDeclaration(RefactorMethodSignatureParser.InterfaceMemberDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#interfaceMemberDeclaration}. * @param ctx the parse tree */ void exitInterfaceMemberDeclaration(RefactorMethodSignatureParser.InterfaceMemberDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#constDeclaration}. * @param ctx the parse tree */ void enterConstDeclaration(RefactorMethodSignatureParser.ConstDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#constDeclaration}. * @param ctx the parse tree */ void exitConstDeclaration(RefactorMethodSignatureParser.ConstDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#constantDeclarator}. * @param ctx the parse tree */ void enterConstantDeclarator(RefactorMethodSignatureParser.ConstantDeclaratorContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#constantDeclarator}. * @param ctx the parse tree */ void exitConstantDeclarator(RefactorMethodSignatureParser.ConstantDeclaratorContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#interfaceMethodDeclaration}. * @param ctx the parse tree */ void enterInterfaceMethodDeclaration(RefactorMethodSignatureParser.InterfaceMethodDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#interfaceMethodDeclaration}. * @param ctx the parse tree */ void exitInterfaceMethodDeclaration(RefactorMethodSignatureParser.InterfaceMethodDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#genericInterfaceMethodDeclaration}. * @param ctx the parse tree */ void enterGenericInterfaceMethodDeclaration(RefactorMethodSignatureParser.GenericInterfaceMethodDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#genericInterfaceMethodDeclaration}. * @param ctx the parse tree */ void exitGenericInterfaceMethodDeclaration(RefactorMethodSignatureParser.GenericInterfaceMethodDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#variableDeclarators}. * @param ctx the parse tree */ void enterVariableDeclarators(RefactorMethodSignatureParser.VariableDeclaratorsContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#variableDeclarators}. * @param ctx the parse tree */ void exitVariableDeclarators(RefactorMethodSignatureParser.VariableDeclaratorsContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#variableDeclarator}. * @param ctx the parse tree */ void enterVariableDeclarator(RefactorMethodSignatureParser.VariableDeclaratorContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#variableDeclarator}. * @param ctx the parse tree */ void exitVariableDeclarator(RefactorMethodSignatureParser.VariableDeclaratorContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#variableDeclaratorId}. * @param ctx the parse tree */ void enterVariableDeclaratorId(RefactorMethodSignatureParser.VariableDeclaratorIdContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#variableDeclaratorId}. * @param ctx the parse tree */ void exitVariableDeclaratorId(RefactorMethodSignatureParser.VariableDeclaratorIdContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#variableInitializer}. * @param ctx the parse tree */ void enterVariableInitializer(RefactorMethodSignatureParser.VariableInitializerContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#variableInitializer}. * @param ctx the parse tree */ void exitVariableInitializer(RefactorMethodSignatureParser.VariableInitializerContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#arrayInitializer}. * @param ctx the parse tree */ void enterArrayInitializer(RefactorMethodSignatureParser.ArrayInitializerContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#arrayInitializer}. * @param ctx the parse tree */ void exitArrayInitializer(RefactorMethodSignatureParser.ArrayInitializerContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#enumConstantName}. * @param ctx the parse tree */ void enterEnumConstantName(RefactorMethodSignatureParser.EnumConstantNameContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#enumConstantName}. * @param ctx the parse tree */ void exitEnumConstantName(RefactorMethodSignatureParser.EnumConstantNameContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#type}. * @param ctx the parse tree */ void enterType(RefactorMethodSignatureParser.TypeContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#type}. * @param ctx the parse tree */ void exitType(RefactorMethodSignatureParser.TypeContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#classOrInterfaceType}. * @param ctx the parse tree */ void enterClassOrInterfaceType(RefactorMethodSignatureParser.ClassOrInterfaceTypeContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#classOrInterfaceType}. * @param ctx the parse tree */ void exitClassOrInterfaceType(RefactorMethodSignatureParser.ClassOrInterfaceTypeContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#primitiveType}. * @param ctx the parse tree */ void enterPrimitiveType(RefactorMethodSignatureParser.PrimitiveTypeContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#primitiveType}. * @param ctx the parse tree */ void exitPrimitiveType(RefactorMethodSignatureParser.PrimitiveTypeContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#typeArguments}. * @param ctx the parse tree */ void enterTypeArguments(RefactorMethodSignatureParser.TypeArgumentsContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#typeArguments}. * @param ctx the parse tree */ void exitTypeArguments(RefactorMethodSignatureParser.TypeArgumentsContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#typeArgument}. * @param ctx the parse tree */ void enterTypeArgument(RefactorMethodSignatureParser.TypeArgumentContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#typeArgument}. * @param ctx the parse tree */ void exitTypeArgument(RefactorMethodSignatureParser.TypeArgumentContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#qualifiedNameList}. * @param ctx the parse tree */ void enterQualifiedNameList(RefactorMethodSignatureParser.QualifiedNameListContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#qualifiedNameList}. * @param ctx the parse tree */ void exitQualifiedNameList(RefactorMethodSignatureParser.QualifiedNameListContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#formalParameters}. * @param ctx the parse tree */ void enterFormalParameters(RefactorMethodSignatureParser.FormalParametersContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#formalParameters}. * @param ctx the parse tree */ void exitFormalParameters(RefactorMethodSignatureParser.FormalParametersContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#formalParameterList}. * @param ctx the parse tree */ void enterFormalParameterList(RefactorMethodSignatureParser.FormalParameterListContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#formalParameterList}. * @param ctx the parse tree */ void exitFormalParameterList(RefactorMethodSignatureParser.FormalParameterListContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#formalParameter}. * @param ctx the parse tree */ void enterFormalParameter(RefactorMethodSignatureParser.FormalParameterContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#formalParameter}. * @param ctx the parse tree */ void exitFormalParameter(RefactorMethodSignatureParser.FormalParameterContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#lastFormalParameter}. * @param ctx the parse tree */ void enterLastFormalParameter(RefactorMethodSignatureParser.LastFormalParameterContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#lastFormalParameter}. * @param ctx the parse tree */ void exitLastFormalParameter(RefactorMethodSignatureParser.LastFormalParameterContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#methodBody}. * @param ctx the parse tree */ void enterMethodBody(RefactorMethodSignatureParser.MethodBodyContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#methodBody}. * @param ctx the parse tree */ void exitMethodBody(RefactorMethodSignatureParser.MethodBodyContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#constructorBody}. * @param ctx the parse tree */ void enterConstructorBody(RefactorMethodSignatureParser.ConstructorBodyContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#constructorBody}. * @param ctx the parse tree */ void exitConstructorBody(RefactorMethodSignatureParser.ConstructorBodyContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#qualifiedName}. * @param ctx the parse tree */ void enterQualifiedName(RefactorMethodSignatureParser.QualifiedNameContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#qualifiedName}. * @param ctx the parse tree */ void exitQualifiedName(RefactorMethodSignatureParser.QualifiedNameContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#literal}. * @param ctx the parse tree */ void enterLiteral(RefactorMethodSignatureParser.LiteralContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#literal}. * @param ctx the parse tree */ void exitLiteral(RefactorMethodSignatureParser.LiteralContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#annotation}. * @param ctx the parse tree */ void enterAnnotation(RefactorMethodSignatureParser.AnnotationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#annotation}. * @param ctx the parse tree */ void exitAnnotation(RefactorMethodSignatureParser.AnnotationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#annotationName}. * @param ctx the parse tree */ void enterAnnotationName(RefactorMethodSignatureParser.AnnotationNameContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#annotationName}. * @param ctx the parse tree */ void exitAnnotationName(RefactorMethodSignatureParser.AnnotationNameContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#elementValuePairs}. * @param ctx the parse tree */ void enterElementValuePairs(RefactorMethodSignatureParser.ElementValuePairsContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#elementValuePairs}. * @param ctx the parse tree */ void exitElementValuePairs(RefactorMethodSignatureParser.ElementValuePairsContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#elementValuePair}. * @param ctx the parse tree */ void enterElementValuePair(RefactorMethodSignatureParser.ElementValuePairContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#elementValuePair}. * @param ctx the parse tree */ void exitElementValuePair(RefactorMethodSignatureParser.ElementValuePairContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#elementValue}. * @param ctx the parse tree */ void enterElementValue(RefactorMethodSignatureParser.ElementValueContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#elementValue}. * @param ctx the parse tree */ void exitElementValue(RefactorMethodSignatureParser.ElementValueContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#elementValueArrayInitializer}. * @param ctx the parse tree */ void enterElementValueArrayInitializer(RefactorMethodSignatureParser.ElementValueArrayInitializerContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#elementValueArrayInitializer}. * @param ctx the parse tree */ void exitElementValueArrayInitializer(RefactorMethodSignatureParser.ElementValueArrayInitializerContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#annotationTypeDeclaration}. * @param ctx the parse tree */ void enterAnnotationTypeDeclaration(RefactorMethodSignatureParser.AnnotationTypeDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#annotationTypeDeclaration}. * @param ctx the parse tree */ void exitAnnotationTypeDeclaration(RefactorMethodSignatureParser.AnnotationTypeDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#annotationTypeBody}. * @param ctx the parse tree */ void enterAnnotationTypeBody(RefactorMethodSignatureParser.AnnotationTypeBodyContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#annotationTypeBody}. * @param ctx the parse tree */ void exitAnnotationTypeBody(RefactorMethodSignatureParser.AnnotationTypeBodyContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#annotationTypeElementDeclaration}. * @param ctx the parse tree */ void enterAnnotationTypeElementDeclaration(RefactorMethodSignatureParser.AnnotationTypeElementDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#annotationTypeElementDeclaration}. * @param ctx the parse tree */ void exitAnnotationTypeElementDeclaration(RefactorMethodSignatureParser.AnnotationTypeElementDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#annotationTypeElementRest}. * @param ctx the parse tree */ void enterAnnotationTypeElementRest(RefactorMethodSignatureParser.AnnotationTypeElementRestContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#annotationTypeElementRest}. * @param ctx the parse tree */ void exitAnnotationTypeElementRest(RefactorMethodSignatureParser.AnnotationTypeElementRestContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#annotationMethodOrConstantRest}. * @param ctx the parse tree */ void enterAnnotationMethodOrConstantRest(RefactorMethodSignatureParser.AnnotationMethodOrConstantRestContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#annotationMethodOrConstantRest}. * @param ctx the parse tree */ void exitAnnotationMethodOrConstantRest(RefactorMethodSignatureParser.AnnotationMethodOrConstantRestContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#annotationMethodRest}. * @param ctx the parse tree */ void enterAnnotationMethodRest(RefactorMethodSignatureParser.AnnotationMethodRestContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#annotationMethodRest}. * @param ctx the parse tree */ void exitAnnotationMethodRest(RefactorMethodSignatureParser.AnnotationMethodRestContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#annotationConstantRest}. * @param ctx the parse tree */ void enterAnnotationConstantRest(RefactorMethodSignatureParser.AnnotationConstantRestContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#annotationConstantRest}. * @param ctx the parse tree */ void exitAnnotationConstantRest(RefactorMethodSignatureParser.AnnotationConstantRestContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#defaultValue}. * @param ctx the parse tree */ void enterDefaultValue(RefactorMethodSignatureParser.DefaultValueContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#defaultValue}. * @param ctx the parse tree */ void exitDefaultValue(RefactorMethodSignatureParser.DefaultValueContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#block}. * @param ctx the parse tree */ void enterBlock(RefactorMethodSignatureParser.BlockContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#block}. * @param ctx the parse tree */ void exitBlock(RefactorMethodSignatureParser.BlockContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#blockStatement}. * @param ctx the parse tree */ void enterBlockStatement(RefactorMethodSignatureParser.BlockStatementContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#blockStatement}. * @param ctx the parse tree */ void exitBlockStatement(RefactorMethodSignatureParser.BlockStatementContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#localVariableDeclarationStatement}. * @param ctx the parse tree */ void enterLocalVariableDeclarationStatement(RefactorMethodSignatureParser.LocalVariableDeclarationStatementContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#localVariableDeclarationStatement}. * @param ctx the parse tree */ void exitLocalVariableDeclarationStatement(RefactorMethodSignatureParser.LocalVariableDeclarationStatementContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#localVariableDeclaration}. * @param ctx the parse tree */ void enterLocalVariableDeclaration(RefactorMethodSignatureParser.LocalVariableDeclarationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#localVariableDeclaration}. * @param ctx the parse tree */ void exitLocalVariableDeclaration(RefactorMethodSignatureParser.LocalVariableDeclarationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#statement}. * @param ctx the parse tree */ void enterStatement(RefactorMethodSignatureParser.StatementContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#statement}. * @param ctx the parse tree */ void exitStatement(RefactorMethodSignatureParser.StatementContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#catchClause}. * @param ctx the parse tree */ void enterCatchClause(RefactorMethodSignatureParser.CatchClauseContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#catchClause}. * @param ctx the parse tree */ void exitCatchClause(RefactorMethodSignatureParser.CatchClauseContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#catchType}. * @param ctx the parse tree */ void enterCatchType(RefactorMethodSignatureParser.CatchTypeContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#catchType}. * @param ctx the parse tree */ void exitCatchType(RefactorMethodSignatureParser.CatchTypeContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#finallyBlock}. * @param ctx the parse tree */ void enterFinallyBlock(RefactorMethodSignatureParser.FinallyBlockContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#finallyBlock}. * @param ctx the parse tree */ void exitFinallyBlock(RefactorMethodSignatureParser.FinallyBlockContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#resourceSpecification}. * @param ctx the parse tree */ void enterResourceSpecification(RefactorMethodSignatureParser.ResourceSpecificationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#resourceSpecification}. * @param ctx the parse tree */ void exitResourceSpecification(RefactorMethodSignatureParser.ResourceSpecificationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#resources}. * @param ctx the parse tree */ void enterResources(RefactorMethodSignatureParser.ResourcesContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#resources}. * @param ctx the parse tree */ void exitResources(RefactorMethodSignatureParser.ResourcesContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#resource}. * @param ctx the parse tree */ void enterResource(RefactorMethodSignatureParser.ResourceContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#resource}. * @param ctx the parse tree */ void exitResource(RefactorMethodSignatureParser.ResourceContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#switchBlockStatementGroup}. * @param ctx the parse tree */ void enterSwitchBlockStatementGroup(RefactorMethodSignatureParser.SwitchBlockStatementGroupContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#switchBlockStatementGroup}. * @param ctx the parse tree */ void exitSwitchBlockStatementGroup(RefactorMethodSignatureParser.SwitchBlockStatementGroupContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#switchLabel}. * @param ctx the parse tree */ void enterSwitchLabel(RefactorMethodSignatureParser.SwitchLabelContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#switchLabel}. * @param ctx the parse tree */ void exitSwitchLabel(RefactorMethodSignatureParser.SwitchLabelContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#forControl}. * @param ctx the parse tree */ void enterForControl(RefactorMethodSignatureParser.ForControlContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#forControl}. * @param ctx the parse tree */ void exitForControl(RefactorMethodSignatureParser.ForControlContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#forInit}. * @param ctx the parse tree */ void enterForInit(RefactorMethodSignatureParser.ForInitContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#forInit}. * @param ctx the parse tree */ void exitForInit(RefactorMethodSignatureParser.ForInitContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#enhancedForControl}. * @param ctx the parse tree */ void enterEnhancedForControl(RefactorMethodSignatureParser.EnhancedForControlContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#enhancedForControl}. * @param ctx the parse tree */ void exitEnhancedForControl(RefactorMethodSignatureParser.EnhancedForControlContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#forUpdate}. * @param ctx the parse tree */ void enterForUpdate(RefactorMethodSignatureParser.ForUpdateContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#forUpdate}. * @param ctx the parse tree */ void exitForUpdate(RefactorMethodSignatureParser.ForUpdateContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#parExpression}. * @param ctx the parse tree */ void enterParExpression(RefactorMethodSignatureParser.ParExpressionContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#parExpression}. * @param ctx the parse tree */ void exitParExpression(RefactorMethodSignatureParser.ParExpressionContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#expressionList}. * @param ctx the parse tree */ void enterExpressionList(RefactorMethodSignatureParser.ExpressionListContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#expressionList}. * @param ctx the parse tree */ void exitExpressionList(RefactorMethodSignatureParser.ExpressionListContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#statementExpression}. * @param ctx the parse tree */ void enterStatementExpression(RefactorMethodSignatureParser.StatementExpressionContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#statementExpression}. * @param ctx the parse tree */ void exitStatementExpression(RefactorMethodSignatureParser.StatementExpressionContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#constantExpression}. * @param ctx the parse tree */ void enterConstantExpression(RefactorMethodSignatureParser.ConstantExpressionContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#constantExpression}. * @param ctx the parse tree */ void exitConstantExpression(RefactorMethodSignatureParser.ConstantExpressionContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#expression}. * @param ctx the parse tree */ void enterExpression(RefactorMethodSignatureParser.ExpressionContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#expression}. * @param ctx the parse tree */ void exitExpression(RefactorMethodSignatureParser.ExpressionContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#primary}. * @param ctx the parse tree */ void enterPrimary(RefactorMethodSignatureParser.PrimaryContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#primary}. * @param ctx the parse tree */ void exitPrimary(RefactorMethodSignatureParser.PrimaryContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#creator}. * @param ctx the parse tree */ void enterCreator(RefactorMethodSignatureParser.CreatorContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#creator}. * @param ctx the parse tree */ void exitCreator(RefactorMethodSignatureParser.CreatorContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#createdName}. * @param ctx the parse tree */ void enterCreatedName(RefactorMethodSignatureParser.CreatedNameContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#createdName}. * @param ctx the parse tree */ void exitCreatedName(RefactorMethodSignatureParser.CreatedNameContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#innerCreator}. * @param ctx the parse tree */ void enterInnerCreator(RefactorMethodSignatureParser.InnerCreatorContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#innerCreator}. * @param ctx the parse tree */ void exitInnerCreator(RefactorMethodSignatureParser.InnerCreatorContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#arrayCreatorRest}. * @param ctx the parse tree */ void enterArrayCreatorRest(RefactorMethodSignatureParser.ArrayCreatorRestContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#arrayCreatorRest}. * @param ctx the parse tree */ void exitArrayCreatorRest(RefactorMethodSignatureParser.ArrayCreatorRestContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#classCreatorRest}. * @param ctx the parse tree */ void enterClassCreatorRest(RefactorMethodSignatureParser.ClassCreatorRestContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#classCreatorRest}. * @param ctx the parse tree */ void exitClassCreatorRest(RefactorMethodSignatureParser.ClassCreatorRestContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#explicitGenericInvocation}. * @param ctx the parse tree */ void enterExplicitGenericInvocation(RefactorMethodSignatureParser.ExplicitGenericInvocationContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#explicitGenericInvocation}. * @param ctx the parse tree */ void exitExplicitGenericInvocation(RefactorMethodSignatureParser.ExplicitGenericInvocationContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#nonWildcardTypeArguments}. * @param ctx the parse tree */ void enterNonWildcardTypeArguments(RefactorMethodSignatureParser.NonWildcardTypeArgumentsContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#nonWildcardTypeArguments}. * @param ctx the parse tree */ void exitNonWildcardTypeArguments(RefactorMethodSignatureParser.NonWildcardTypeArgumentsContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#typeArgumentsOrDiamond}. * @param ctx the parse tree */ void enterTypeArgumentsOrDiamond(RefactorMethodSignatureParser.TypeArgumentsOrDiamondContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#typeArgumentsOrDiamond}. * @param ctx the parse tree */ void exitTypeArgumentsOrDiamond(RefactorMethodSignatureParser.TypeArgumentsOrDiamondContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#nonWildcardTypeArgumentsOrDiamond}. * @param ctx the parse tree */ void enterNonWildcardTypeArgumentsOrDiamond(RefactorMethodSignatureParser.NonWildcardTypeArgumentsOrDiamondContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#nonWildcardTypeArgumentsOrDiamond}. * @param ctx the parse tree */ void exitNonWildcardTypeArgumentsOrDiamond(RefactorMethodSignatureParser.NonWildcardTypeArgumentsOrDiamondContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#superSuffix}. * @param ctx the parse tree */ void enterSuperSuffix(RefactorMethodSignatureParser.SuperSuffixContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#superSuffix}. * @param ctx the parse tree */ void exitSuperSuffix(RefactorMethodSignatureParser.SuperSuffixContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#explicitGenericInvocationSuffix}. * @param ctx the parse tree */ void enterExplicitGenericInvocationSuffix(RefactorMethodSignatureParser.ExplicitGenericInvocationSuffixContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#explicitGenericInvocationSuffix}. * @param ctx the parse tree */ void exitExplicitGenericInvocationSuffix(RefactorMethodSignatureParser.ExplicitGenericInvocationSuffixContext ctx); /** * Enter a parse tree produced by {@link RefactorMethodSignatureParser#arguments}. * @param ctx the parse tree */ void enterArguments(RefactorMethodSignatureParser.ArgumentsContext ctx); /** * Exit a parse tree produced by {@link RefactorMethodSignatureParser#arguments}. * @param ctx the parse tree */ void exitArguments(RefactorMethodSignatureParser.ArgumentsContext ctx); }
develar/kotlin
compiler/backend/src/org/jetbrains/jet/codegen/FunctionGenerationStrategy.java
/* * Copyright 2010-2013 JetBrains s.r.o. * * 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.jetbrains.jet.codegen; import org.jetbrains.annotations.NotNull; import org.jetbrains.asm4.MethodVisitor; import org.jetbrains.asm4.Type; import org.jetbrains.jet.codegen.context.MethodContext; import org.jetbrains.jet.codegen.signature.JvmMethodSignature; import org.jetbrains.jet.codegen.state.GenerationState; import org.jetbrains.jet.codegen.state.JetTypeMapper; import org.jetbrains.jet.lang.descriptors.CallableDescriptor; import org.jetbrains.jet.lang.psi.JetDeclarationWithBody; import java.util.ArrayList; import java.util.Collection; public abstract class FunctionGenerationStrategy { private final Collection<String> localVariableNames = new ArrayList<String>(); private FrameMap frameMap; public abstract void generateBody( @NotNull MethodVisitor mv, @NotNull JvmMethodSignature signature, @NotNull MethodContext context ); protected void addLocalVariableName(@NotNull String name) { localVariableNames.add(name); } @NotNull public Collection<String> getLocalVariableNames() { return localVariableNames; } @NotNull protected FrameMap createFrameMap(@NotNull JetTypeMapper typeMapper, @NotNull MethodContext context) { return context.prepareFrame(typeMapper); } @NotNull public FrameMap getFrameMap(@NotNull JetTypeMapper typeMapper, @NotNull MethodContext context) { if (frameMap == null) { frameMap = createFrameMap(typeMapper, context); } return frameMap; } public static class FunctionDefault extends CodegenBased<CallableDescriptor> { private final JetDeclarationWithBody declaration; public FunctionDefault( @NotNull GenerationState state, @NotNull CallableDescriptor descriptor, @NotNull JetDeclarationWithBody declaration ) { super(state, descriptor); this.declaration = declaration; } @Override public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) { codegen.returnExpression(declaration.getBodyExpression()); } } public abstract static class CodegenBased<T extends CallableDescriptor> extends FunctionGenerationStrategy { protected final GenerationState state; protected final T callableDescriptor; public CodegenBased(@NotNull GenerationState state, T callableDescriptor) { this.state = state; this.callableDescriptor = callableDescriptor; } @Override public void generateBody( @NotNull MethodVisitor mv, @NotNull JvmMethodSignature signature, @NotNull MethodContext context ) { ExpressionCodegen codegen = initializeExpressionCodegen(signature, context, mv, signature.getAsmMethod().getReturnType()); doGenerateBody(codegen, signature); generateLocalVarNames(codegen); } abstract public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature); @NotNull public ExpressionCodegen initializeExpressionCodegen( JvmMethodSignature signature, MethodContext context, MethodVisitor mv, Type returnType ) { return new ExpressionCodegen(mv, getFrameMap(state.getTypeMapper(), context), returnType, context, state); } public void generateLocalVarNames(@NotNull ExpressionCodegen codegen) { for (String name : codegen.getLocalVariableNamesForExpression()) { addLocalVariableName(name); } } } }
asiboro/asiboro.github.io
vsdoc/search--/s_1808.js
<reponame>asiboro/asiboro.github.io<filename>vsdoc/search--/s_1808.js search_result['1808']=["topic_0000000000000463_vars--.html","tlece_UserReferal Fields",""];
paladin-t/bitty
src/datetime.h
/* ** Bitty ** ** An itty bitty game engine. ** ** Copyright (C) 2020 - 2021 <NAME>, all rights reserved ** ** For the latest info, see https://github.com/paladin-t/bitty/ */ #ifndef __DATETIME_H__ #define __DATETIME_H__ #include "bitty.h" #include <string> /* ** {=========================================================================== ** Date time */ /** * @brief Date time utilities. */ class DateTime { public: /** * @param[out] sec 0-based. * @param[out] mi 0-based. * @param[out] hr 0-based. * @param[out] mday 1-based. * @param[out] mo 0-based. * @param[out] yr since 1900. * @param[out] wday 0-based, days since Sunday. * @param[out] yday 0-based, days since January 1. * @param[out] isdst Daylight savings time flag. * @return The time in seconds elapsed since midnight, Jan. 1, 1970, or -1 * for error. */ static long long now( int* sec = nullptr, int* mi = nullptr, int* hr = nullptr, int* mday = nullptr, int* mo = nullptr, int* yr = nullptr, int* wday = nullptr, int* yday = nullptr, int* isdst = nullptr ); /** * @param[out] str In "YYYY-MM-DD HH:MM:SS" format. * @return The time in seconds elapsed since midnight, Jan. 1, 1970, or -1 * for error. */ static long long now(std::string &str); /** * @brief Gets wall clock independent ticks in nanoseconds. */ static long long ticks(void); /** * @brief Converts nanoseconds to milliseconds. */ static int toMilliseconds(long long t); /** * @brief Converts milliseconds to nanoseconds. */ static long long fromMilliseconds(int t); /** * @brief Converts nanoseconds to seconds. */ static double toSeconds(long long t); /** * @brief Converts seconds to nanoseconds. */ static long long fromSeconds(double t); /** * @brief Sleeps for specific milliseconds. */ static void sleep(int ms); }; /* ===========================================================================} */ #endif /* __DATETIME_H__ */
Minecraft-TA/forged-carpet
src/main/java/carpet/forge/mixin/EntityLlamaMixin.java
package carpet.forge.mixin; import carpet.forge.CarpetSettings; import net.minecraft.entity.passive.EntityLlama; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(value = EntityLlama.class) public abstract class EntityLlamaMixin { @Redirect( method = "handleEating", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/passive/EntityLlama;isTame()Z", ordinal = 0) ) private boolean onHandleEating(EntityLlama entityLlama) { return entityLlama.isTame() && !(CarpetSettings.llamaOverfeedingFix && entityLlama.isInLove()); } }
ProEpiDesenvolvimento/guardioes-api
app/models/category.rb
class Category < ApplicationRecord has_many :users has_many :households belongs_to :app validates :name, presence: true, length: { minimum: 1, maximum: 255 } end
eddieh/webkit-webinspector
lib/WebInspectorUI/v7/NavigationBar.js
/* * Copyright (C) 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ WebInspector.NavigationBar = function(element, navigationItems, role, label) { WebInspector.Object.call(this); this._element = element || document.createElement("div"); this._element.classList.add(this.constructor.StyleClassName || WebInspector.NavigationBar.StyleClassName); this._element.tabIndex = 0; if (role) this._element.setAttribute("role", role); if (label) this._element.setAttribute("aria-label", label); this._element.addEventListener("focus", this._focus.bind(this), false); this._element.addEventListener("blur", this._blur.bind(this), false); this._element.addEventListener("keydown", this._keyDown.bind(this), false); this._element.addEventListener("mousedown", this._mouseDown.bind(this), false); document.addEventListener("load", this.updateLayout.bind(this), false); this._styleElement = document.createElement("style"); this._navigationItems = []; if (navigationItems) { for (var i = 0; i < navigationItems.length; ++i) this.addNavigationItem(navigationItems[i]); } document.head.appendChild(this._styleElement); }; WebInspector.Object.addConstructorFunctions(WebInspector.NavigationBar); WebInspector.NavigationBar.StyleClassName = "navigation-bar"; WebInspector.NavigationBar.CollapsedStyleClassName = "collapsed"; WebInspector.NavigationBar.Event = { NavigationItemSelected: "navigation-bar-navigation-item-selected" }; WebInspector.NavigationBar.prototype = { constructor: WebInspector.NavigationBar, // Public addNavigationItem: function(navigationItem, parentElement) { return this.insertNavigationItem(navigationItem, this._navigationItems.length, parentElement); }, insertNavigationItem: function(navigationItem, index, parentElement) { console.assert(navigationItem instanceof WebInspector.NavigationItem); if (!(navigationItem instanceof WebInspector.NavigationItem)) return; if (navigationItem.parentNavigationBar) navigationItem.parentNavigationBar.removeNavigationItem(navigationItem); navigationItem._parentNavigationBar = this; console.assert(index >= 0 && index <= this._navigationItems.length); index = Math.max(0, Math.min(index, this._navigationItems.length)); this._navigationItems.splice(index, 0, navigationItem); if (!parentElement) parentElement = this._element; var nextSibling = this._navigationItems[index + 1]; var nextSiblingElement = nextSibling ? nextSibling.element : null; if (nextSiblingElement && nextSiblingElement.parentNode !== parentElement) nextSiblingElement = null; parentElement.insertBefore(navigationItem.element, nextSiblingElement); this._minimumWidthNeedsRecalculation = true; this._needsStyleUpdated = true; this.updateLayoutSoon(); return navigationItem; }, removeNavigationItem: function(navigationItemOrIdentifierOrIndex, index) { var navigationItem = this._findNavigationItem(navigationItemOrIdentifierOrIndex); if (!navigationItem) return; navigationItem._parentNavigationBar = null; if (this._selectedNavigationItem === navigationItem) this.selectedNavigationItem = null; this._navigationItems.remove(navigationItem); navigationItem.element.remove(); this._minimumWidthNeedsRecalculation = true; this._needsStyleUpdated = true; this.updateLayoutSoon(); return navigationItem; }, updateLayoutSoon: function() { if (this._updateLayoutTimeout) return; this._needsLayout = true; function update() { delete this._updateLayoutTimeout; if (this._needsLayout || this._needsStyleUpdated) this.updateLayout(); } this._updateLayoutTimeout = setTimeout(update.bind(this), 0); }, updateLayout: function() { if (this._updateLayoutTimeout) { clearTimeout(this._updateLayoutTimeout); delete this._updateLayoutTimeout; } if (this._needsStyleUpdated) this._updateStyle(); this._needsLayout = false; if (typeof this.customUpdateLayout === "function") { this.customUpdateLayout(); return; } // Remove the collapsed style class to test if the items can fit at full width. this._element.classList.remove(WebInspector.NavigationBar.CollapsedStyleClassName); // Tell each navigation item to update to full width if needed. for (var i = 0; i < this._navigationItems.length; ++i) this._navigationItems[i].updateLayout(true); var totalItemWidth = 0; for (var i = 0; i < this._navigationItems.length; ++i) { // Skip flexible space items since they can take up no space at the minimum width. if (this._navigationItems[i] instanceof WebInspector.FlexibleSpaceNavigationItem) continue; totalItemWidth += this._navigationItems[i].element.offsetWidth; } var barWidth = this._element.offsetWidth; // Add the collapsed class back if the items are wider than the bar. if (totalItemWidth > barWidth) this._element.classList.add(WebInspector.NavigationBar.CollapsedStyleClassName); // Give each navigation item the opportunity to collapse further. for (var i = 0; i < this._navigationItems.length; ++i) this._navigationItems[i].updateLayout(); }, get selectedNavigationItem() { return this._selectedNavigationItem || null; }, set selectedNavigationItem(navigationItemOrIdentifierOrIndex) { var navigationItem = this._findNavigationItem(navigationItemOrIdentifierOrIndex); // Only radio navigation items can be selected. if (!(navigationItem instanceof WebInspector.RadioButtonNavigationItem)) navigationItem = null; if (this._selectedNavigationItem === navigationItem) return; if (this._selectedNavigationItem) this._selectedNavigationItem.selected = false; this._selectedNavigationItem = navigationItem || null; if (this._selectedNavigationItem) this._selectedNavigationItem.selected = true; // When the mouse is down don't dispatch the selected event, it will be dispatched on mouse up. // This prevents sending the event while the user is scrubbing the bar. if (!this._mouseIsDown) this.dispatchEventToListeners(WebInspector.NavigationBar.Event.NavigationItemSelected); }, get navigationItems() { return this._navigationItems; }, get element() { return this._element; }, get minimumWidth() { if (typeof this._minimumWidth === "undefined" || this._minimumWidthNeedsRecalculation) { this._minimumWidth = this._calculateMinimumWidth(); delete this._minimumWidthNeedsRecalculation; } return this._minimumWidth; }, get sizesToFit() { // Can be overriden by subclasses. return false; }, // Private _findNavigationItem: function(navigationItemOrIdentifierOrIndex) { var navigationItem = null; if (navigationItemOrIdentifierOrIndex instanceof WebInspector.NavigationItem) { if (this._navigationItems.contains(navigationItemOrIdentifierOrIndex)) navigationItem = navigationItemOrIdentifierOrIndex; } else if (typeof navigationItemOrIdentifierOrIndex === "number") { navigationItem = this._navigationItems[navigationItemOrIdentifierOrIndex]; } else if (typeof navigationItemOrIdentifierOrIndex === "string") { for (var i = 0; i < this._navigationItems.length; ++i) { if (this._navigationItems[i].identifier === navigationItemOrIdentifierOrIndex) { navigationItem = this._navigationItems[i]; break; } } } return navigationItem; }, _mouseDown: function(event) { // Only handle left mouse clicks. if (event.button !== 0) return; // Remove the tabIndex so clicking the navigation bar does not give it focus. // Only keep the tabIndex if already focused from keyboard navigation. This matches Xcode. if (!this._focused) this._element.removeAttribute("tabindex"); var itemElement = event.target.enclosingNodeOrSelfWithClass(WebInspector.RadioButtonNavigationItem.StyleClassName); if (!itemElement || !itemElement.navigationItem) return; this._previousSelectedNavigationItem = this.selectedNavigationItem; this.selectedNavigationItem = itemElement.navigationItem; this._mouseIsDown = true; this._mouseMovedEventListener = this._mouseMoved.bind(this); this._mouseUpEventListener = this._mouseUp.bind(this); // Register these listeners on the document so we can track the mouse if it leaves the resizer. document.addEventListener("mousemove", this._mouseMovedEventListener, false); document.addEventListener("mouseup", this._mouseUpEventListener, false); event.preventDefault(); event.stopPropagation(); }, _mouseMoved: function(event) { console.assert(event.button === 0); console.assert(this._mouseIsDown); if (!this._mouseIsDown) return; event.preventDefault(); event.stopPropagation(); var itemElement = event.target.enclosingNodeOrSelfWithClass(WebInspector.RadioButtonNavigationItem.StyleClassName); if (!itemElement || !itemElement.navigationItem) { // Find the element that is at the X position of the mouse, even when the mouse is no longer // vertically in the navigation bar. var element = document.elementFromPoint(event.pageX, this._element.totalOffsetTop); if (!element) return; itemElement = element.enclosingNodeOrSelfWithClass(WebInspector.RadioButtonNavigationItem.StyleClassName); if (!itemElement || !itemElement.navigationItem) return; } if (this.selectedNavigationItem) this.selectedNavigationItem.active = false; this.selectedNavigationItem = itemElement.navigationItem; this.selectedNavigationItem.active = true; }, _mouseUp: function(event) { console.assert(event.button === 0); console.assert(this._mouseIsDown); if (!this._mouseIsDown) return; if (this.selectedNavigationItem) this.selectedNavigationItem.active = false; this._mouseIsDown = false; document.removeEventListener("mousemove", this._mouseMovedEventListener, false); document.removeEventListener("mouseup", this._mouseUpEventListener, false); delete this._mouseMovedEventListener; delete this._mouseUpEventListener; // Restore the tabIndex so the navigation bar can be in the keyboard tab loop. this._element.tabIndex = 0; // Dispatch the selected event here since the selectedNavigationItem setter surpresses it // while the mouse is down to prevent sending it while scrubbing the bar. if (this._previousSelectedNavigationItem !== this.selectedNavigationItem) this.dispatchEventToListeners(WebInspector.NavigationBar.Event.NavigationItemSelected); delete this._previousSelectedNavigationItem; event.preventDefault(); event.stopPropagation(); }, _keyDown: function(event) { if (!this._focused) return; if (event.keyIdentifier !== "Left" && event.keyIdentifier !== "Right") return; event.preventDefault(); event.stopPropagation(); var selectedNavigationItemIndex = this._navigationItems.indexOf(this._selectedNavigationItem); if (event.keyIdentifier === "Left") { if (selectedNavigationItemIndex === -1) selectedNavigationItemIndex = this._navigationItems.length; do { selectedNavigationItemIndex = Math.max(0, selectedNavigationItemIndex - 1); } while (selectedNavigationItemIndex && !(this._navigationItems[selectedNavigationItemIndex] instanceof WebInspector.RadioButtonNavigationItem)); } else if (event.keyIdentifier === "Right") { do { selectedNavigationItemIndex = Math.min(selectedNavigationItemIndex + 1, this._navigationItems.length - 1); } while (selectedNavigationItemIndex < this._navigationItems.length - 1 && !(this._navigationItems[selectedNavigationItemIndex] instanceof WebInspector.RadioButtonNavigationItem)); } if (!(this._navigationItems[selectedNavigationItemIndex] instanceof WebInspector.RadioButtonNavigationItem)) return; this.selectedNavigationItem = this._navigationItems[selectedNavigationItemIndex]; }, _focus: function(event) { this._focused = true; }, _blur: function(event) { this._focused = false; }, _updateStyle: function() { this._needsStyleUpdated = false; var parentSelector = "." + (this.constructor.StyleClassName || WebInspector.NavigationBar.StyleClassName); var styleText = ""; for (var i = 0; i < this._navigationItems.length; ++i) { if (!this._navigationItems[i].generateStyleText) continue; if (styleText) styleText += "\n"; styleText += this._navigationItems[i].generateStyleText(parentSelector); } this._styleElement.textContent = styleText; }, _calculateMinimumWidth: function() { var wasCollapsed = this._element.classList.contains(WebInspector.NavigationBar.CollapsedStyleClassName); // Add the collapsed style class to calculate the width of the items when they are collapsed. if (!wasCollapsed) this._element.classList.add(WebInspector.NavigationBar.CollapsedStyleClassName); var totalItemWidth = 0; for (var i = 0; i < this._navigationItems.length; ++i) { // Skip flexible space items since they can take up no space at the minimum width. if (this._navigationItems[i] instanceof WebInspector.FlexibleSpaceNavigationItem) continue; totalItemWidth += this._navigationItems[i].element.offsetWidth; } // Remove the collapsed style class if we were not collapsed before. if (!wasCollapsed) this._element.classList.remove(WebInspector.NavigationBar.CollapsedStyleClassName); return totalItemWidth; } }; WebInspector.NavigationBar.prototype.__proto__ = WebInspector.Object.prototype;
wibeasley/jbc-2016
2486-wallaby/Default User/ring around the can/src/main.c
#include <kipr/botball.h> int main() { printf("go forward\n"); motor(3,30); motor(0,35); msleep(11000); printf("left turn\n"); motor(0,59); msleep(4000); printf("go forward\n"); motor(0,55); motor(3,52); msleep(1000); printf("left turn\n"); motor(0,52); motor(3,0); msleep(3500); printf("go forward\n"); motor(3,70); motor(0,85); msleep(7000); return 0; }
long1eu/flutter-intellij
src/io/flutter/run/SdkAttachConfig.java
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.flutter.run; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.execution.configurations.RuntimeConfigurationError; import com.intellij.execution.filters.TextConsoleBuilder; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.refactoring.listeners.RefactoringElementListener; import com.jetbrains.lang.dart.ide.runner.DartConsoleFilter; import com.jetbrains.lang.dart.sdk.DartConfigurable; import com.jetbrains.lang.dart.sdk.DartSdk; import io.flutter.FlutterBundle; import io.flutter.console.FlutterConsoleFilter; import io.flutter.dart.DartPlugin; import io.flutter.pub.PubRoot; import io.flutter.run.daemon.FlutterApp; import io.flutter.run.daemon.FlutterDevice; import io.flutter.run.daemon.RunMode; import io.flutter.sdk.FlutterSdkManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class SdkAttachConfig extends SdkRunConfig { public SdkAttachConfig(SdkRunConfig config) { //noinspection ConstantConditions super(config.getProject(), config.getFactory(), config.getName()); setFields(config.getFields()); // TODO(messick): Delete if not needed. } @Nullable @Override public RefactoringElementListener getRefactoringElementListener(PsiElement element) { return null; } @NotNull @Override public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() { throw new IllegalStateException("Attach configurations are not editable"); } @NotNull @Override public LaunchState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment env) throws ExecutionException { try { checkRunnable(env.getProject()); } catch (RuntimeConfigurationError e) { throw new ExecutionException(e); } SdkFields launchFields = getFields(); MainFile mainFile = MainFile.verify(launchFields.getFilePath(), env.getProject()).get(); Project project = env.getProject(); RunMode mode = RunMode.fromEnv(env); Module module = ModuleUtilCore.findModuleForFile(mainFile.getFile(), env.getProject()); LaunchState.CreateAppCallback createAppCallback = (device) -> { if (device == null) return null; GeneralCommandLine command = getCommand(env, device); FlutterApp app = FlutterApp.start(env, project, module, mode, device, command, StringUtil.capitalize(mode.mode()) + "App", "StopApp"); // Stop the app if the Flutter SDK changes. FlutterSdkManager.Listener sdkListener = new FlutterSdkManager.Listener() { @Override public void flutterSdkRemoved() { app.shutdownAsync(); } }; FlutterSdkManager.getInstance(project).addListener(sdkListener); Disposer.register(project, () -> FlutterSdkManager.getInstance(project).removeListener(sdkListener)); return app; }; LaunchState launcher = new AttachState(env, mainFile.getAppDir(), mainFile.getFile(), this, createAppCallback); // Set up additional console filters. TextConsoleBuilder builder = launcher.getConsoleBuilder(); builder.addFilter(new DartConsoleFilter(env.getProject(), mainFile.getFile())); if (module != null) { builder.addFilter(new FlutterConsoleFilter(module)); } return launcher; } @NotNull @Override public GeneralCommandLine getCommand(@NotNull ExecutionEnvironment env, FlutterDevice device) throws ExecutionException { return getFields().createFlutterSdkAttachCommand(env.getProject(), FlutterLaunchMode.fromEnv(env), device); } private void checkRunnable(@NotNull Project project) throws RuntimeConfigurationError { DartSdk sdk = DartPlugin.getDartSdk(project); if (sdk == null) { throw new RuntimeConfigurationError(FlutterBundle.message("dart.sdk.is.not.configured"), () -> DartConfigurable.openDartSettings(project)); } MainFile.Result main = MainFile.verify(getFields().getFilePath(), project); if (!main.canLaunch()) { throw new RuntimeConfigurationError(main.getError()); } if (PubRoot.forDirectory(main.get().getAppDir()) == null) { throw new RuntimeConfigurationError("Entrypoint isn't within a Flutter pub root"); } } }
jmalcic/spina-conferences
test/dummy/config/initializers/i18n.rb
<filename>test/dummy/config/initializers/i18n.rb # frozen_string_literal: true # I18n default locale Rails.application.config.i18n.default_locale = :'en-GB' Rails.application.config.i18n.fallbacks.defaults = %i[en-GB en] Rails.application.config.i18n.fallbacks[:'en-GB'] = [:en]
etaoins/llambda
compiler/src/main/scala/codegen/ConstantGenerator.scala
package io.llambda.compiler.codegen import io.llambda import scala.io.Codec import scala.collection.mutable import llambda.compiler.InternalCompilerErrorException import llambda.compiler.planner.{step => ps} import llambda.llvmir._ import llambda.compiler.{celltype => ct} import llambda.compiler.{valuetype => vt} class ConstantGenerator(generatedTypes: Map[vt.RecordLikeType, GeneratedType]) { /* Caches of constants indexed by their value * * This ensures proper Scheme semantics are maintained with the planner's lazy value instantiation. For example, * the following code: * (define x '(1 2 3)) * (eqv? x x) * * Will actually plan the list for 'x' once for each argument. This breaks Scheme semantics as (eqv?) would return * false if a separate instance was returned for each argument. */ private val stringCache = new mutable.HashMap[String, IrConstant] private val symbolCache = new mutable.HashMap[String, IrConstant] private val integerCache = new mutable.LongMap[IrConstant] private val flonumCache = new mutable.LongMap[IrConstant] private val characterCache = new mutable.LongMap[IrConstant] private val bytevectorCache = new mutable.HashMap[Vector[Byte], IrConstant] private val pairCache = new mutable.HashMap[(IrConstant, IrConstant), IrConstant] private val vectorCache = new mutable.HashMap[Vector[IrConstant], IrConstant] private val recordCache = new mutable.HashMap[(vt.RecordType, Map[vt.RecordField, IrConstant], Boolean), IrConstant] private val emptyClosureCache = new mutable.HashMap[GlobalVariable, IrConstant] def defineConstantData(module: IrModuleBuilder)(name: String, initializer: IrConstant): GlobalVariable = { val constantDataDef = IrGlobalVariableDef( name=name, initializer=initializer, linkage=Linkage.Private, unnamedAddr=true, constant=true) module.defineGlobalVariable(constantDataDef) constantDataDef.variable } private def genHeapUtf8Constant(module: IrModuleBuilder)(baseName: String, utf8Data: Array[Byte]): IrConstant = { val innerConstantName = baseName + ".strByteArray" val innerConstantInitializer = SharedByteArrayValue.createUtf8StringConstant(utf8Data) val innerConstant = defineConstantData(module)(innerConstantName, innerConstantInitializer) BitcastToConstant(innerConstant, PointerType(SharedByteArrayValue.irType)) } private def genInlineUtf8Constant(module: IrModuleBuilder)(utf8Data: Array[Byte], constantLength: Int): IrConstant = { val padByteCount = constantLength - utf8Data.length // Pad this string with 0xff // This helps test that nobody is relying on these being NULL terminated val terminatedUtf8Data = utf8Data ++ Array.fill(padByteCount)(255.toByte) // Return a direct constant StringConstant(terminatedUtf8Data) } private def charLengthForString(stringValue: String): Int = { // Java is internally based on UTF-16. For Unicode code points outside the BMP it uses surrogate pairs which count // as two Java "characters" // Llambda is native UTF-8 and considers a code point the same as a character stringValue.codePointCount(0, stringValue.length) } private def genBytevectorCell(module: IrModuleBuilder)(elements: Seq[Byte]): IrConstant = { // Make our elements val baseName = module.nameSource.allocate("schemeBytevector") val elementsName = baseName + ".elementsByteArray" val elementsInitializer = SharedByteArrayValue.createArrayConstant(elements) val elementsValue = defineConstantData(module)(elementsName, elementsInitializer) val bytevectorCellName = baseName + ".cell" val bytevectorCell = ct.BytevectorCell.createConstant( length=elements.length, byteArray=BitcastToConstant(elementsValue, PointerType(SharedByteArrayValue.irType)) ) defineConstantData(module)(bytevectorCellName, bytevectorCell) } private def genVectorCell(module: IrModuleBuilder)(irElements: Seq[IrConstant]): IrConstant = { // Make our elements val baseName = module.nameSource.allocate("schemeVector") val elementsName = baseName + ".elements" val elementsInitializer = ArrayConstant(PointerType(ct.AnyCell.irType), irElements.toList) val elementsDef = defineConstantData(module)(elementsName, elementsInitializer) val vectorCellName = baseName + ".cell" val vectorCell = ct.VectorCell.createConstant( length=irElements.length, elements=ElementPointerConstant(PointerType(ct.AnyCell.irType), elementsDef, List(0, 0))) defineConstantData(module)(vectorCellName, vectorCell) } private def genRecordLikeData(module: IrModuleBuilder, genGlobals: GenGlobals)( recordLikeType: vt.RecordLikeType, fieldTemps: Map[vt.RecordField, IrConstant] ): StructureConstant = { val generatedType = genGlobals.generatedTypes(recordLikeType) // Generate our parent type val parentDataOpt = recordLikeType.parentRecordOpt map { parentType => genRecordLikeData(module, genGlobals)(parentType, fieldTemps) } // Find our self fields and order them val orderedSelfFields = generatedType.fieldToGepIndices.toList.filter({ case (field, gepIndices) => // Our self fields will only have a single GEP index gepIndices.length == 1 }).sortBy(_._2(0)) val fieldData = orderedSelfFields.map { case (field, _) => fieldTemps(field) } // Build the structure StructureConstant(parentDataOpt.toList ++ fieldData, userDefinedType=Some(generatedType.irType)) } private def genRecordCell(module: IrModuleBuilder, genGlobals: GenGlobals)( recordType: vt.RecordType, fieldTemps: Map[vt.RecordField, IrConstant], isUndefined: Boolean ): IrConstant = { val generatedType = genGlobals.generatedTypes(recordType) val baseName = module.nameSource.allocate("schemeRecord") val recordCellName = baseName + ".cell" generatedType.storageType match { case TypeDataStorage.Empty => val recordCell = ct.RecordCell.createConstant( extraData=UndefConstant(ct.RecordCell.extraDataIrType), dataIsInline=1, isUndefined=if (isUndefined) 1 else 0, recordClassId=generatedType.classId, recordData=UndefConstant(ct.RecordCell.recordDataIrType) ) defineConstantData(module)(recordCellName, recordCell) case TypeDataStorage.Inline => val recordData = genRecordLikeData(module, genGlobals)(recordType, fieldTemps) // This is a bit of a hack. Record cells are defined to have a data pointer which we need to replace with our // inline data. Open code the record structure and append our data to the end val inlineRecordCell = StructureConstant(List( ct.AnyCell.createConstant(typeId=ct.RecordCell.typeId), IntegerConstant(ct.RecordCell.dataIsInlineIrType, 1), IntegerConstant(ct.RecordCell.isUndefinedIrType, if (isUndefined) 1 else 0), IntegerConstant(ct.RecordCell.recordClassIdIrType, generatedType.classId) )) val packedCell = StructureConstant(List(inlineRecordCell, recordData)) val packedCellDef = defineConstantData(module)(recordCellName, packedCell) BitcastToConstant(packedCellDef, PointerType(ct.RecordCell.irType)) case TypeDataStorage.OutOfLine => val recordDataName = baseName + ".data" val recordData = genRecordLikeData(module, genGlobals)(recordType, fieldTemps) val recordDataDef = defineConstantData(module)(recordDataName, recordData) val recordCell = ct.RecordCell.createConstant( extraData=UndefConstant(ct.RecordCell.extraDataIrType), dataIsInline=0, isUndefined=if (isUndefined) 1 else 0, recordClassId=generatedType.classId, recordData=BitcastToConstant(recordDataDef, ct.RecordCell.recordDataIrType) ) defineConstantData(module)(recordCellName, recordCell) } } private def genEmptyClosure(module: IrModuleBuilder)(entryPoint: IrConstant): IrConstant = { val procCellName = module.nameSource.allocate("schemeProcedure") // Find the class ID for the empty closure type val generatedType = generatedTypes(vt.EmptyClosureType) val procCell = ct.ProcedureCell.createConstant( extraData=UndefConstant(ct.ProcedureCell.extraDataIrType), entryPoint=entryPoint, recordClassId=generatedType.classId, recordData=UndefConstant(ct.ProcedureCell.recordDataIrType), dataIsInline=1, isUndefined=0 ) defineConstantData(module)(procCellName, procCell) } private def genStringCell(module: IrModuleBuilder)(value: String): IrConstant = { val baseName = module.nameSource.allocate("schemeString") val stringCellName = baseName + ".cell" val utf8Data = Codec.toUTF8(value) val inlineUtf8Bytes = ct.StringCellConstants.maxInlineStringBytes val stringCell = if (utf8Data.length <= inlineUtf8Bytes) { // We can do this inline val utf8Constant = genInlineUtf8Constant(module)(utf8Data, inlineUtf8Bytes) ct.InlineStringCell.createConstant( inlineCharLength=charLengthForString(value), inlineData=utf8Constant, inlineByteLength=utf8Data.length ) } else { // We have to put this on the heap val utf8Constant = genHeapUtf8Constant(module)(baseName, utf8Data) ct.HeapStringCell.createConstant( heapByteLength=utf8Data.length, heapCharLength=charLengthForString(value), heapByteArray=utf8Constant, inlineByteLength=ct.SymbolCellConstants.heapSymbolInlineByteLength ) } // The rest of the compiler assumes this is just a %string* BitcastToConstant( defineConstantData(module)(stringCellName, stringCell), PointerType(ct.StringCell.irType) ) } private def genSymbolCell(module: IrModuleBuilder)(value: String): IrConstant = { val baseName = module.nameSource.allocate("schemeSymbol") val symbolCellName = baseName + ".cell" val utf8Data = Codec.toUTF8(value) val inlineUtf8Bytes = ct.SymbolCellConstants.maxInlineSymbolBytes val symbolCell = if (utf8Data.length <= inlineUtf8Bytes) { // We can do this inline val utf8Constant = genInlineUtf8Constant(module)(utf8Data, inlineUtf8Bytes) ct.InlineSymbolCell.createConstant( inlineCharLength=charLengthForString(value), inlineData=utf8Constant, inlineByteLength=utf8Data.length ) } else { // We have to put this on the heap val utf8Constant = genHeapUtf8Constant(module)(baseName, utf8Data) ct.HeapSymbolCell.createConstant( heapByteLength=utf8Data.length, heapCharLength=charLengthForString(value), heapByteArray=utf8Constant, inlineByteLength=ct.SymbolCellConstants.heapSymbolInlineByteLength ) } // The rest of the compiler assumes this is just a %symbol* BitcastToConstant( defineConstantData(module)(symbolCellName, symbolCell), PointerType(ct.SymbolCell.irType) ) } def apply(state: GenerationState, genGlobals: GenGlobals)(createStep: ps.CreateConstant): IrConstant = { val module = state.currentBlock.function.module createStep match { case ps.CreateStringCell(_, value) => stringCache.getOrElseUpdate(value, { genStringCell(module)(value) }) case ps.CreateSymbolCell(_, value) => symbolCache.getOrElseUpdate(value, { genSymbolCell(module)(value) }) case ps.CreateIntegerCell(_, value) => integerCache.getOrElseUpdate(value, { val intCellName = module.nameSource.allocate("schemeInteger") val intCell = ct.IntegerCell.createConstant( value=value ) defineConstantData(module)(intCellName, intCell) }) case ps.CreateFlonumCell(_, value) => // Use longBits here so we distinguish +nan.0, -0.0, etc properly val longBits = java.lang.Double.doubleToLongBits(value) flonumCache.getOrElseUpdate(longBits, { val flonumCellName = module.nameSource.allocate("schemeFlonum") val flonumCell = ct.FlonumCell.createConstant( value=DoubleConstant(value) ) defineConstantData(module)(flonumCellName, flonumCell) }) case ps.CreateBooleanCell(_, true) => GlobalDefines.trueIrValue case ps.CreateBooleanCell(_, false) => GlobalDefines.falseIrValue case ps.CreateCharCell(_, value) => characterCache.getOrElseUpdate(value, { val charCellName = module.nameSource.allocate("schemeChar") val charCell = ct.CharCell.createConstant( unicodeChar=value ) defineConstantData(module)(charCellName, charCell) }) case ps.CreateBytevectorCell(_, elements) => bytevectorCache.getOrElseUpdate(elements, { genBytevectorCell(module)(elements) }) case ps.CreateVectorCell(_, elementTemps) => val elementIrs = elementTemps.map { elementTemp => state.liveTemps(elementTemp) match { case constant: IrConstant => constant case other => throw new InternalCompilerErrorException(s"Attempted to create constant vector with non-constant element: ${other}") } } vectorCache.getOrElseUpdate(elementIrs, { genVectorCell(module)(elementIrs) }) case ps.CreateRecordCell(_, recordType, fieldTemps, isUndefined) => val fieldIrs = fieldTemps.map { case (field, fieldTemp) => state.liveTemps(fieldTemp) match { case constant: IrConstant => field -> constant case other => throw new InternalCompilerErrorException(s"Attempted to create constant record with non-constant field: ${other}") } } val cacheKey = (recordType, fieldIrs, isUndefined) recordCache.getOrElseUpdate(cacheKey, { genRecordCell(module, genGlobals)(recordType, fieldIrs, isUndefined) }) case ps.CreatePairCell(_, carTemp, cdrTemp, listLengthOpt) => val carIrConstant = state.liveTemps(carTemp) match { case constant: IrConstant => constant case other => throw new InternalCompilerErrorException(s"Attempted to create constant pair with non-constant car: ${other}") } val cdrIrConstant = state.liveTemps(cdrTemp) match { case constant: IrConstant => constant case other => throw new InternalCompilerErrorException(s"Attempted to create constant pair with non-constant cdr: ${other}") } pairCache.getOrElseUpdate((carIrConstant, cdrIrConstant), { val pairCellName = module.nameSource.allocate("schemePair") // It's not possible for pairs to have a length of zero - only EmptyLists are zero length val listLength = listLengthOpt.getOrElse(0L) val pairCell = ct.PairCell.createConstant( listLength=listLength, car=carIrConstant, cdr=cdrIrConstant ) defineConstantData(module)(pairCellName, pairCell) }) case ps.CreateUnitCell(_) => GlobalDefines.unitIrValue case ps.CreateEmptyListCell(_) => GlobalDefines.emptyListIrValue case ps.CreateEmptyClosure(_, entryPointTemp) => val entryPointGlobalVar = state.liveTemps(entryPointTemp) match { case globalVar: GlobalVariable => globalVar case other => throw new InternalCompilerErrorException(s"Attempted to create constant closure with non-global variable entry point: ${other}") } emptyClosureCache.getOrElseUpdate(entryPointGlobalVar, { // Cast to an untyped entry point val castEntryPoint = BitcastToConstant(entryPointGlobalVar, ct.ProcedureCell.entryPointIrType) genEmptyClosure(module)(castEntryPoint) }) case ps.CreateNativeInteger(_, value, bits) => IntegerConstant(IntegerType(bits), value) case ps.CreateNativeFloat(_, value, fpType) if fpType == vt.Double => DoubleConstant(value) case ps.CreateNativeFloat(_, value, fpType) if fpType == vt.Float => FloatConstant(value.toFloat) } } }
TDC3Tool/meetapp-web
src/components/pages/Details/index.js
import React, { useEffect, useMemo, useState } from 'react'; import { isBefore, format, parseISO } from 'date-fns'; import { MdArrowBack, MdDeleteForever, MdEdit, MdEvent, MdPlace, } from 'react-icons/md'; import { useDispatch } from 'react-redux'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import pt from 'date-fns/locale/pt-BR'; import { cancelMeetup } from '~/store/actions/meetup'; import { Container, Description, Footer, Header } from './styles'; import api from '~/services/api'; export default function Details({ match }) { const dispatch = useDispatch(); const { id } = match.params; const [meetup, setMeetup] = useState({}); const past = useMemo(() => isBefore(meetup.date, new Date()), [meetup]); useEffect(() => { (async () => { const { data: m } = await api.get(`scheduled/${id}`); const date = parseISO(m.date); setMeetup({ ...m, date, description: m.description.split(/\n/).map((text, index) => ( <p key={String(index)} data-testid={`description_${index}`}> {text} <br /> </p> )), formatted_date: format(date, "dd 'de' MMMM', às' H'h'", { locale: pt, }), }); })(); }, [id]); return ( <Container> <Header> <h2> <Link to="/dashboard" data-testid="dashboard"> <MdArrowBack color="#FFF" size="24" /> </Link> {meetup.title} </h2> <div> {!past && ( <Link to={`/meetups/${id}/edit`} className="btn blue"> <MdEdit size="17" /> Editar </Link> )} {!past && ( <button type="button" onClick={() => dispatch(cancelMeetup(id))}> <MdDeleteForever size="17" /> Cancelar </button> )} </div> </Header> {meetup.banner && <img src={meetup.banner.url} alt={meetup.title} />} <Description>{meetup.description}</Description> <Footer> <time> <MdEvent size="16" /> <span data-testid="date">{meetup.formatted_date}</span> </time> <span> <MdPlace size="16" /> <span data-testid="localization">{meetup.localization}</span> </span> </Footer> </Container> ); } Details.propTypes = { match: PropTypes.shape({ params: PropTypes.shape({ id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, }).isRequired, }).isRequired, };
gantree-io/gantree-core
src/lib/v2/core/commands/sync.js
const Ansible = require('../ansible') const Inventory = require('../inventory') const stdout = require('../../../utils/stdout') const sync = async (frame, gco) => { const logger = frame.logAt('core/sync') await Inventory.namespace.create(frame) // create project path recursively await Inventory.createInventory(frame, gco) // TODO: TEMPorary, should be output of this.ansible.inventory.createActiveInventory // setup infra await Ansible.commands.runPlaybook(frame, 'infra.yml') // // get instance IPs using inventories const combined_inventory = await Ansible.commands.returnCombinedInventory( frame ) const node_ip_addresses = await Ansible.extract.IPs(frame, combined_inventory) await stdout.writeForParsing( 'NODE_IP_ADDRESSES', JSON.stringify(node_ip_addresses) ) // convert instances into substrate nodes await Ansible.commands.runPlaybook(frame, 'operation.yml') logger.info('sync finished') } module.exports = { sync }
NickNichollsCitrix/ShareFile-ObjectiveC
ShareFileSDK/ShareFileSDK/Categories/NSURL+sfapi.h
#import <Foundation/Foundation.h> @interface NSURL (sfapi) - (NSString *)authority; - (NSString *)getAuthority; /** * Construct a comperable protection space for the current URL. * * @param authenticationMethod Auth method for protection space * @param relm Optional realm, if the server has more than one protection space * @param isProxy Boolean indicating whether protection space is a proxy * * @return NSURLProtectionSpace representation of URL */ - (NSURLProtectionSpace *)protectionSpaceWithAuthenticationMethod:(NSString *)authenticationMethod realm:(NSString *)realm isProxy:(BOOL)isProxy; @end
jiandiao/flowable-engine
modules/flowable-engine/src/main/java/org/flowable/engine/delegate/FutureJavaDelegate.java
/* 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.flowable.engine.delegate; import java.util.concurrent.CompletableFuture; import org.flowable.common.engine.api.async.AsyncTaskInvoker; /** * Convenience class that should be used when a Java delegation in a BPMN 2.0 process is required (for example, to call custom business logic). * When this interface is implemented then the execution of the logic can happen on a different thread then the process execution. * <p> * This class can be used only for service tasks. * <p> * This class does not allow to influence the control flow. It follows the default BPMN 2.0 behavior of taking every outgoing sequence flow (which has a condition that evaluates to true if there is a * condition defined) If you are in need of influencing the flow in your process, use the class 'org.flowable.engine.impl.pvm.delegate.ActivityBehavior' instead. * <p> * This interface allows fine grained control on how the future should be created. * It gives access to the {@link AsyncTaskInvoker} which can delegate execution to a shared task executor. * However, it doesn't have to be used. * In case you don't need custom task executor the {@link FlowableFutureJavaDelegate} can be used. * </p> * * @param <Output> the output of the execution * @author <NAME> * @see FlowableFutureJavaDelegate * @see MapBasedFlowableFutureJavaDelegate */ public interface FutureJavaDelegate<Output> { /** * Perform the execution of the delegate, potentially on another thread. * The result of the future is passed in the {@link #afterExecution(DelegateExecution, Object)} in order to store * the data on the execution on the same thread as the caller of this method. * * <b>IMPORTANT:</b> the execution should only be used to read data before creating the future. * The execution should not be used in the task that will be executed on a new thread. * <p> * The {@link AsyncTaskInvoker} is in order to schedule an execution on a different thread. * However, it is also possible to use a different scheduler, or return a future not created by the given {@code taskInvoker}. * </p> * * @param execution the execution that can be used to extract data * @param taskInvoker the task invoker that can be used to execute expensive operation on another thread * @return the output data of the execution */ CompletableFuture<Output> execute(DelegateExecution execution, AsyncTaskInvoker taskInvoker); /** * Method invoked with the result from {@link #execute(DelegateExecution, AsyncTaskInvoker)}. * This should be used to set data on the {@link DelegateExecution}. * This is on the same thread as {@link #execute(DelegateExecution, AsyncTaskInvoker)} and participates in the process transaction. * * @param execution the execution to which data can be set * @param executionData the execution data */ void afterExecution(DelegateExecution execution, Output executionData); }
liquidaty/zsv
app/utils/dl.c
/* * Copyright (C) 2021 Liquidaty and the zsv/lib contributors * All rights reserved * * This file is part of zsv/lib, distributed under the license defined at * https://opensource.org/licenses/MIT */ #include <zsv/utils/dl.h> void (*zsv_dlsym(void *restrict handle, const char *restrict name))(void) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" return dlsym(handle, name); #pragma GCC diagnostic pop } #ifdef _WIN32 #include "win/dl.c" #endif
foyzulkarim/mern-boilerplate
client-pro/src/pages/user/resetpassword/service.js
<gh_stars>10-100 import { get, post, put, del } from '/src/services/http-service'; // check username api call export async function forgotPassword(params) { const result = await post(`/api/auth/forgot-password`, params); return result; } export async function verifyToken(params) { const result = await post(`/api/auth/verify-token`, params); return result; } export async function resetPassword(params) { const result = await post(`/api/auth/reset-password`, params); return result; }
a6k8s4/zaproxy
src/org/zaproxy/zap/model/StructuralSiteNodeIterator.java
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright The ZAP Development Team * * 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.zaproxy.zap.model; import java.util.Enumeration; import java.util.Iterator; import java.util.NoSuchElementException; import javax.swing.tree.TreeNode; import org.parosproxy.paros.model.SiteNode; public class StructuralSiteNodeIterator implements Iterator<StructuralNode> { private Enumeration<TreeNode> children; public StructuralSiteNodeIterator(StructuralSiteNode parent){ @SuppressWarnings("unchecked") Enumeration<TreeNode> children = parent.getSiteNode().children(); this.children = children; } @Override public boolean hasNext() { return children.hasMoreElements(); } @Override public StructuralSiteNode next() { if (! hasNext()) { throw new NoSuchElementException(); } return new StructuralSiteNode((SiteNode) children.nextElement()); } @Override public void remove() { // TODO } }
huashen/Takin
takin-webapp/tro-web/tro-web-app/src/main/java/io/shulie/tro/web/app/service/AppConfigEntityConvertServiceImpl.java
<gh_stars>1-10 /* * Copyright 2021 Shulie Technology, Co.Ltd * Email: <EMAIL> * 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, * See the License for the specific language governing permissions and * limitations under the License. */ package io.shulie.tro.web.app.service; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.github.pagehelper.util.StringUtil; import com.google.common.collect.Lists; import com.pamirs.tro.common.constant.AppConfigSheetEnum; import com.pamirs.tro.entity.domain.entity.simplify.TShadowJobConfig; import com.pamirs.tro.entity.domain.vo.guardmanage.LinkGuardVo; import io.shulie.tro.web.app.input.whitelist.WhitelistImportFromExcelInput; import io.shulie.tro.web.app.request.application.ShadowConsumerCreateRequest; import io.shulie.tro.web.common.enums.excel.BooleanEnum; import io.shulie.tro.web.common.enums.shadow.ShadowMqConsumerType; import io.shulie.tro.web.data.dao.application.ApplicationDAO; import io.shulie.tro.web.data.param.application.ApplicationDsCreateParam; import io.shulie.tro.web.data.param.blacklist.BlacklistCreateNewParam; import io.shulie.tro.web.data.result.application.ApplicationDetailResult; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @Author: mubai * @Date: 2021-02-25 10:30 * @Description: */ @Service public class AppConfigEntityConvertServiceImpl implements AppConfigEntityConvertService { @Autowired private ApplicationDAO applicationDAO; /** * 将数组转化为entity * * @param sourceList * @return */ @Override public List<ApplicationDsCreateParam> convertDsSheet(ArrayList<ArrayList<String>> sourceList) { if (CollectionUtils.isEmpty(sourceList)) { return null; } List<ApplicationDsCreateParam> result = new ArrayList<>(); for (int i = 0; i < sourceList.size(); i++) { List<String> propertyList = sourceList.get(i); if (CollectionUtils.isEmpty(propertyList)) { continue; } ApplicationDsCreateParam createParam = new ApplicationDsCreateParam(); createParam.setDbType(Integer.valueOf(propertyList.get(0))); createParam.setDsType(Integer.valueOf(propertyList.get(1))); createParam.setUrl(propertyList.get(2)); createParam.setConfig(propertyList.get(3)); createParam.setParseConfig(propertyList.get(4)); createParam.setStatus(Integer.valueOf(propertyList.get(5))); result.add(createParam); } return result; } @Override public List<LinkGuardVo> convertGuardSheet(ArrayList<ArrayList<String>> sourceList) { if (CollectionUtils.isEmpty(sourceList)) { return null; } List<LinkGuardVo> result = new ArrayList<>(); for (ArrayList<String> arrayList : sourceList) { if (CollectionUtils.isEmpty(arrayList)) { continue; } LinkGuardVo guardVo = new LinkGuardVo(); guardVo.setMethodInfo(arrayList.get(0)); guardVo.setGroovy(arrayList.get(1)); guardVo.setIsEnable(Boolean.valueOf(arrayList.get(2))); if(arrayList.size() > 3) { guardVo.setRemark(String.valueOf(arrayList.get(3))); }else { guardVo.setRemark(""); } result.add(guardVo); } return result; } @Override public List<TShadowJobConfig> convertJobSheet(ArrayList<ArrayList<String>> sourceList) { if (CollectionUtils.isEmpty(sourceList)) { return null; } List<TShadowJobConfig> result = new ArrayList<>(); for (int i = 0; i < sourceList.size(); i++) { ArrayList<String> arrayList = sourceList.get(i); if (CollectionUtils.isEmpty(arrayList)) { continue; } TShadowJobConfig job = new TShadowJobConfig(); job.setName(arrayList.get(0)); job.setType(Integer.valueOf(arrayList.get(1))); job.setConfigCode(arrayList.get(2)); job.setStatus(Integer.valueOf(arrayList.get(3))); job.setActive(Integer.valueOf(arrayList.get(4))); if(arrayList.size() > 5) { job.setRemark(String.valueOf(arrayList.get(5))); }else { job.setRemark(""); } result.add(job); } return result; } @Override public List<WhitelistImportFromExcelInput> converWhiteList(ArrayList<ArrayList<String>> importWhiteLists) { if (CollectionUtils.isEmpty(importWhiteLists)) { return null; } List<WhitelistImportFromExcelInput> result = new ArrayList<>(); for (ArrayList<String> arrayList : importWhiteLists) { if (CollectionUtils.isEmpty(arrayList)) { continue; } WhitelistImportFromExcelInput input = new WhitelistImportFromExcelInput(); input.setInterfaceName(arrayList.get(0)); input.setInterfaceType(Integer.valueOf(arrayList.get(1))); input.setDictType(arrayList.get(2)); input.setUseYn(Integer.valueOf(arrayList.get(3))); input.setIsGlobal(BooleanEnum.getByDesc(arrayList.get(4))); input.setIsHandwork(BooleanEnum.getByDesc(arrayList.get(5))); if(arrayList.size() == 6) { input.setEffectAppNames(StringUtil.isNotEmpty(arrayList.get(6))? Lists.newArrayList(arrayList.get(6).split(",")):Lists.newArrayList()); }else { input.setEffectAppNames(Lists.newArrayList()); } result.add(input); } return result; } @Override public List<BlacklistCreateNewParam> converBlackList(ArrayList<ArrayList<String>> sourceList,Long applicationId) { if (CollectionUtils.isEmpty(sourceList)) { return Collections.emptyList(); } ApplicationDetailResult result = applicationDAO.getApplicationById(applicationId); List<BlacklistCreateNewParam> params = Lists.newArrayList(); for (ArrayList<String> arrayList : sourceList) { if (CollectionUtils.isEmpty(arrayList)) { continue; } if (arrayList.size() != AppConfigSheetEnum.BLACK.getColumnNum()) { throw new RuntimeException("黑名单数据列不正确,请确认!导入的excel需要时从控制台导出的配置文件。异常数据:" + arrayList.toString()); } BlacklistCreateNewParam newParam = new BlacklistCreateNewParam(); newParam.setRedisKey(String.valueOf(arrayList.get(0)).trim()); newParam.setType(0); newParam.setUseYn(Integer.valueOf(arrayList.get(1))); newParam.setApplicationId(applicationId); if (result != null) { newParam.setCustomerId(result.getCustomerId()); newParam.setUserId(result.getUserId()); } params.add(newParam); } return params; } @Override public List<ShadowConsumerCreateRequest> converComsumerList(ArrayList<ArrayList<String>> sourceList) { if (CollectionUtils.isEmpty(sourceList)) { return Collections.emptyList(); } List<ShadowConsumerCreateRequest> result = new ArrayList<>(); for (ArrayList<String> arrayList : sourceList) { if (CollectionUtils.isEmpty(arrayList)) { continue; } if (arrayList.size() != 3) { throw new RuntimeException("影子消费者数据列不正确,请确认!导入的excel需要时从控制台导出的配置文件。异常数据:" + arrayList.toString()); } ShadowConsumerCreateRequest request = new ShadowConsumerCreateRequest(); request.setTopicGroup(arrayList.get(0)); request.setType(ShadowMqConsumerType.of(arrayList.get(1))); request.setStatus(Integer.valueOf(arrayList.get(2))); result.add(request); } return result; } }
google-ar/chromium
chrome/browser/android/search_geolocation/search_geolocation_disclosure_tab_helper.h
<reponame>google-ar/chromium<filename>chrome/browser/android/search_geolocation/search_geolocation_disclosure_tab_helper.h<gh_stars>100-1000 // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ANDROID_SEARCH_GEOLOCATION_SEARCH_GEOLOCATION_DISCLOSURE_TAB_HELPER_H_ #define CHROME_BROWSER_ANDROID_SEARCH_GEOLOCATION_SEARCH_GEOLOCATION_DISCLOSURE_TAB_HELPER_H_ #include <jni.h> #include "base/macros.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "url/gurl.h" class Profile; namespace user_prefs { class PrefRegistrySyncable; } // Tab helper to show the search geolocation disclosure. class SearchGeolocationDisclosureTabHelper : public content::WebContentsObserver, public content::WebContentsUserData< SearchGeolocationDisclosureTabHelper> { public: ~SearchGeolocationDisclosureTabHelper() override; // content::WebContentsObserver overrides. void NavigationEntryCommitted( const content::LoadCommittedDetails& load_details) override; void MaybeShowDisclosure(const GURL& gurl); static void ResetDisclosure(Profile* profile); static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); // Registers native methods. static bool Register(JNIEnv* env); private: explicit SearchGeolocationDisclosureTabHelper(content::WebContents* contents); friend class content::WebContentsUserData< SearchGeolocationDisclosureTabHelper>; bool ShouldShowDisclosureForUrl(const GURL& gurl); // Record metrics, once per client, of the permission state before and after // the disclosure has been shown. void RecordPreDisclosureMetrics(const GURL& gurl); void RecordPostDisclosureMetrics(const GURL& gurl); Profile* GetProfile(); bool consistent_geolocation_enabled_; DISALLOW_COPY_AND_ASSIGN(SearchGeolocationDisclosureTabHelper); }; #endif // CHROME_BROWSER_ANDROID_SEARCH_GEOLOCATION_SEARCH_GEOLOCATION_DISCLOSURE_TAB_HELPER_H_
jjhenkel/dockerizeme
hard-gists/2083178/snippet.py
<filename>hard-gists/2083178/snippet.py<gh_stars>10-100 """ # Dump your data from Posterous. Requires: * Posterous username and password * An API Token from http://posterous.com/api * Posterous site id also from http://posterous.com/api * The Python libraries requests and python-dateutil To use: python posterous_dump.py """ API_TOKEN = '<api_token>' USERNAME = '<username>' PASSWORD = '<password>' SITE_ID = '<side_id>' POSTS_URL = 'http://posterous.com/api/2/sites/%s/posts' % (SITE_ID,) FOLDER = 'posterous_dump' import json, requests, os from dateutil import parser def fetchFromPosterous(page): print 'Fetching page %s' % (page,) result = requests.get(POSTS_URL, params={ 'api_token': API_TOKEN, 'page': page, }, auth=(USERNAME, PASSWORD)) print result.status_code return result.content def savePosts(posts): print 'saving posts:', len(posts) for post in posts: savePost(post) if len(posts) == 0: raise def savePost(post_json): print post_json print 'saving', post_json.get('slug') post_date = parser.parse(post_json.get('display_date')) post_folder = '%s-%s' % (post_date.strftime('%Y-%m-%d-%H-%M-%S'),post_json.get('slug')) target_dir = os.path.join(FOLDER, post_folder) print target_dir try: os.mkdir(target_dir) except OSError: pass file(os.path.join(target_dir,'post.json'),'w').write(json.dumps(post_json)) getMedia(post_json['media'], target_dir) def getMedia(media, target_dir): print len(media) files_to_get = [] for image in media.get('images'): fetch_url = image.get('full').get('url') files_to_get.append(fetch_url) for video in media.get('videos'): files_to_get.append(video.get('url')) files_to_get.append(video.get('mp4')) for audio in media.get('audio_files'): files_to_get.append(audio.get('url')) for fetch_url in files_to_get: file_name = os.path.split(fetch_url)[1] out_file = requests.get(fetch_url) print out_file.status_code, file_name file(os.path.join(target_dir,file_name),'w').write(out_file.content) page_to_fetch = 1 print 'Starting' if not os.path.exists(FOLDER): os.mkdir(FOLDER) while page_to_fetch: result = fetchFromPosterous(page_to_fetch) try: posts = json.loads(result) except ValueError: print raw_json_data page_to_fetch = None else: if len(posts) > 0 and result: savePosts(posts) page_to_fetch += 1 else: page_to_fetch = None import time time.sleep(5) print 'Done'
ComputerSystemsLab/OptimizationCache
benchmarks/Angha_original/extr_aic79xx_core_ahd_search_qinfifo/extr_aic79xx_core_ahd_search_qinfifo.c
<reponame>ComputerSystemsLab/OptimizationCache #define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_4__ TYPE_2__ ; typedef struct TYPE_3__ TYPE_1__ ; /* Type definitions */ typedef int /*<<< orphan*/ uint32_t ; typedef int u_int ; struct scb {int flags; } ; struct TYPE_4__ {int numscbs; } ; struct ahd_softc {int qinfifonext; int* qinfifo; TYPE_2__ scb_data; TYPE_1__* next_queued_hscb; } ; typedef int /*<<< orphan*/ role_t ; typedef int ahd_search_action ; typedef int /*<<< orphan*/ ahd_mode_state ; struct TYPE_3__ {int /*<<< orphan*/ hscb_busaddr; } ; /* Variables and functions */ int /*<<< orphan*/ AHD_MODE_CCHAN ; int /*<<< orphan*/ AHD_MODE_SCSI ; int AHD_NUM_TARGETS ; int AHD_QIN_WRAP (int) ; int CAM_LUN_WILDCARD ; int CCARREN ; int /*<<< orphan*/ CCSCBCTL ; int CCSCBDIR ; int CCSCBEN ; int CMDS_PENDING ; int MK_MESSAGE_SCB ; int /*<<< orphan*/ NEXT_QUEUED_SCB_ADDR ; int PENDING_MK_MESSAGE ; int /*<<< orphan*/ ROLE_UNKNOWN ; scalar_t__ SCBID_IS_NULL (int) ; int SCB_ACTIVE ; int SCB_GET_TAG (struct scb*) ; int SCB_GET_TARGET (struct ahd_softc*,struct scb*) ; int SCB_LIST_NULL ; int /*<<< orphan*/ SCB_NEXT2 ; #define SEARCH_COMPLETE 131 #define SEARCH_COUNT 130 #define SEARCH_PRINT 129 #define SEARCH_REMOVE 128 int /*<<< orphan*/ SEQ_FLAGS2 ; int /*<<< orphan*/ WAITING_SCB_TAILS ; int WAITING_TID_HEAD ; int /*<<< orphan*/ ahd_done_with_status (struct ahd_softc*,struct scb*,int /*<<< orphan*/ ) ; int /*<<< orphan*/ ahd_dump_card_state (struct ahd_softc*) ; int ahd_get_scbptr (struct ahd_softc*) ; int ahd_get_snscb_qoff (struct ahd_softc*) ; int ahd_inb (struct ahd_softc*,int /*<<< orphan*/ ) ; int ahd_inw (struct ahd_softc*,int) ; int ahd_inw_scbram (struct ahd_softc*,int /*<<< orphan*/ ) ; int /*<<< orphan*/ ahd_le32toh (int /*<<< orphan*/ ) ; struct scb* ahd_lookup_scb (struct ahd_softc*,int) ; scalar_t__ ahd_match_scb (struct ahd_softc*,struct scb*,int,char,int,int,int /*<<< orphan*/ ) ; char* ahd_name (struct ahd_softc*) ; int /*<<< orphan*/ ahd_outb (struct ahd_softc*,int /*<<< orphan*/ ,int) ; int /*<<< orphan*/ ahd_outl (struct ahd_softc*,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int /*<<< orphan*/ ahd_outw (struct ahd_softc*,int,int) ; int /*<<< orphan*/ ahd_qinfifo_requeue (struct ahd_softc*,struct scb*,struct scb*) ; int /*<<< orphan*/ ahd_restore_modes (struct ahd_softc*,int /*<<< orphan*/ ) ; int /*<<< orphan*/ ahd_save_modes (struct ahd_softc*) ; scalar_t__ ahd_search_scb_list (struct ahd_softc*,int,char,int,int,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int,int*,int*,int) ; int /*<<< orphan*/ ahd_set_hnscb_qoff (struct ahd_softc*,int) ; int /*<<< orphan*/ ahd_set_modes (struct ahd_softc*,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int /*<<< orphan*/ ahd_set_scbptr (struct ahd_softc*,int) ; int /*<<< orphan*/ ahd_stitch_tid_list (struct ahd_softc*,int,int,int) ; int /*<<< orphan*/ panic (char*) ; int /*<<< orphan*/ printf (char*,...) ; int ahd_search_qinfifo(struct ahd_softc *ahd, int target, char channel, int lun, u_int tag, role_t role, uint32_t status, ahd_search_action action) { struct scb *scb; struct scb *mk_msg_scb; struct scb *prev_scb; ahd_mode_state saved_modes; u_int qinstart; u_int qinpos; u_int qintail; u_int tid_next; u_int tid_prev; u_int scbid; u_int seq_flags2; u_int savedscbptr; uint32_t busaddr; int found; int targets; /* Must be in CCHAN mode */ saved_modes = ahd_save_modes(ahd); ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN); /* * Halt any pending SCB DMA. The sequencer will reinitiate * this dma if the qinfifo is not empty once we unpause. */ if ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN|CCSCBDIR)) == (CCARREN|CCSCBEN|CCSCBDIR)) { ahd_outb(ahd, CCSCBCTL, ahd_inb(ahd, CCSCBCTL) & ~(CCARREN|CCSCBEN)); while ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN)) != 0) ; } /* Determine sequencer's position in the qinfifo. */ qintail = AHD_QIN_WRAP(ahd->qinfifonext); qinstart = ahd_get_snscb_qoff(ahd); qinpos = AHD_QIN_WRAP(qinstart); found = 0; prev_scb = NULL; if (action == SEARCH_PRINT) { printf("qinstart = %d qinfifonext = %d\nQINFIFO:", qinstart, ahd->qinfifonext); } /* * Start with an empty queue. Entries that are not chosen * for removal will be re-added to the queue as we go. */ ahd->qinfifonext = qinstart; busaddr = ahd_le32toh(ahd->next_queued_hscb->hscb_busaddr); ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr); while (qinpos != qintail) { scb = ahd_lookup_scb(ahd, ahd->qinfifo[qinpos]); if (scb == NULL) { printf("qinpos = %d, SCB index = %d\n", qinpos, ahd->qinfifo[qinpos]); panic("Loop 1\n"); } if (ahd_match_scb(ahd, scb, target, channel, lun, tag, role)) { /* * We found an scb that needs to be acted on. */ found++; switch (action) { case SEARCH_COMPLETE: if ((scb->flags & SCB_ACTIVE) == 0) printf("Inactive SCB in qinfifo\n"); ahd_done_with_status(ahd, scb, status); /* FALLTHROUGH */ case SEARCH_REMOVE: break; case SEARCH_PRINT: printf(" 0x%x", ahd->qinfifo[qinpos]); /* FALLTHROUGH */ case SEARCH_COUNT: ahd_qinfifo_requeue(ahd, prev_scb, scb); prev_scb = scb; break; } } else { ahd_qinfifo_requeue(ahd, prev_scb, scb); prev_scb = scb; } qinpos = AHD_QIN_WRAP(qinpos+1); } ahd_set_hnscb_qoff(ahd, ahd->qinfifonext); if (action == SEARCH_PRINT) printf("\nWAITING_TID_QUEUES:\n"); /* * Search waiting for selection lists. We traverse the * list of "their ids" waiting for selection and, if * appropriate, traverse the SCBs of each "their id" * looking for matches. */ ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI); seq_flags2 = ahd_inb(ahd, SEQ_FLAGS2); if ((seq_flags2 & PENDING_MK_MESSAGE) != 0) { scbid = ahd_inw(ahd, MK_MESSAGE_SCB); mk_msg_scb = ahd_lookup_scb(ahd, scbid); } else mk_msg_scb = NULL; savedscbptr = ahd_get_scbptr(ahd); tid_next = ahd_inw(ahd, WAITING_TID_HEAD); tid_prev = SCB_LIST_NULL; targets = 0; for (scbid = tid_next; !SCBID_IS_NULL(scbid); scbid = tid_next) { u_int tid_head; u_int tid_tail; targets++; if (targets > AHD_NUM_TARGETS) panic("TID LIST LOOP"); if (scbid >= ahd->scb_data.numscbs) { printf("%s: Waiting TID List inconsistency. " "SCB index == 0x%x, yet numscbs == 0x%x.", ahd_name(ahd), scbid, ahd->scb_data.numscbs); ahd_dump_card_state(ahd); panic("for safety"); } scb = ahd_lookup_scb(ahd, scbid); if (scb == NULL) { printf("%s: SCB = 0x%x Not Active!\n", ahd_name(ahd), scbid); panic("Waiting TID List traversal\n"); } ahd_set_scbptr(ahd, scbid); tid_next = ahd_inw_scbram(ahd, SCB_NEXT2); if (ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN) == 0) { tid_prev = scbid; continue; } /* * We found a list of scbs that needs to be searched. */ if (action == SEARCH_PRINT) printf(" %d ( ", SCB_GET_TARGET(ahd, scb)); tid_head = scbid; found += ahd_search_scb_list(ahd, target, channel, lun, tag, role, status, action, &tid_head, &tid_tail, SCB_GET_TARGET(ahd, scb)); /* * Check any MK_MESSAGE SCB that is still waiting to * enter this target's waiting for selection queue. */ if (mk_msg_scb != NULL && ahd_match_scb(ahd, mk_msg_scb, target, channel, lun, tag, role)) { /* * We found an scb that needs to be acted on. */ found++; switch (action) { case SEARCH_COMPLETE: if ((mk_msg_scb->flags & SCB_ACTIVE) == 0) printf("Inactive SCB pending MK_MSG\n"); ahd_done_with_status(ahd, mk_msg_scb, status); /* FALLTHROUGH */ case SEARCH_REMOVE: { u_int tail_offset; printf("Removing MK_MSG scb\n"); /* * Reset our tail to the tail of the * main per-target list. */ tail_offset = WAITING_SCB_TAILS + (2 * SCB_GET_TARGET(ahd, mk_msg_scb)); ahd_outw(ahd, tail_offset, tid_tail); seq_flags2 &= ~PENDING_MK_MESSAGE; ahd_outb(ahd, SEQ_FLAGS2, seq_flags2); ahd_outw(ahd, CMDS_PENDING, ahd_inw(ahd, CMDS_PENDING)-1); mk_msg_scb = NULL; break; } case SEARCH_PRINT: printf(" 0x%x", SCB_GET_TAG(scb)); /* FALLTHROUGH */ case SEARCH_COUNT: break; } } if (mk_msg_scb != NULL && SCBID_IS_NULL(tid_head) && ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN)) { /* * When removing the last SCB for a target * queue with a pending MK_MESSAGE scb, we * must queue the MK_MESSAGE scb. */ printf("Queueing mk_msg_scb\n"); tid_head = ahd_inw(ahd, MK_MESSAGE_SCB); seq_flags2 &= ~PENDING_MK_MESSAGE; ahd_outb(ahd, SEQ_FLAGS2, seq_flags2); mk_msg_scb = NULL; } if (tid_head != scbid) ahd_stitch_tid_list(ahd, tid_prev, tid_head, tid_next); if (!SCBID_IS_NULL(tid_head)) tid_prev = tid_head; if (action == SEARCH_PRINT) printf(")\n"); } /* Restore saved state. */ ahd_set_scbptr(ahd, savedscbptr); ahd_restore_modes(ahd, saved_modes); return (found); }
PeteKeller/CoffeeMud
com/planet_ink/coffee_mud/core/collections/ConvertingSet.java
package com.planet_ink.coffee_mud.core.collections; import java.util.*; /* Copyright 2020-2021 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class ConvertingSet<L,K> extends ConvertingCollection<L,K> implements Set<K> { public ConvertingSet(final Collection<L> l, final Converter<L, K> conv) { super(l,conv); } }
thomsmits/oftp2-client
internal/liboftp2/wire/session/esid.go
<reponame>thomsmits/oftp2-client package session import ( "fmt" "github.com/thomsmits/oftp2-client/internal/liboftp2/wire" ) /* 5.3.11. ESID - End Session o-------------------------------------------------------------------o | ESID End Session | | | | End Session Phase Speaker ----> Listener | |-------------------------------------------------------------------| | Pos | Field | Description | Format | |-----+-----------+---------------------------------------+---------| | 0 | ESIDCMD | ESID Command, 'F' | F X(1) | | 1 | ESIDREAS | Reason Code | F 9(2) | | 3 | ESIDREASL | Reason Text Length | V 9(3) | | 6 | ESIDREAST | Reason Text | V T(n) | | | ESIDCR | Carriage Return | F X(1) | o-------------------------------------------------------------------o ESIDCMD Command Code Character Value: 'F' ESID Command identifier. ESIDREAS Reason Code Numeric(2) Value: '00' Normal session termination '01' Command not recognised An Exchange Buffer contains an invalid command code (1st octet of the buffer). '02' Protocol violation An Exchange Buffer contains an invalid command for the current state of the receiver. '03' User code not known A Start Session (SSID) command contains an unknown or invalid Identification Code. '04' Invalid password A Start Session (SSID) command contained an invalid password. '05' Local site emergency close down The local site has entered an emergency close down mode. Communications are being forcibly terminated. '06' Command contained invalid data A field within a Command Exchange Buffer contains invalid data. '07' Exchange Buffer size error The length of the Exchange Buffer as determined by the Stream Transmission Header differs from the length implied by the Command Code. '08' Resources not available The request for connection has been denied due to a resource shortage. The connection attempt should be retried later. '09' Time out '10' Mode or capabilities incompatible '11' Invalid challenge response '12' Secure authentication requirements incompatible '99' Unspecified Abort code An error was detected for which no specific code is defined. ESIDREASL Reason Text Length Numeric(3) Length in octets of the field ESIDREAST. 0 indicates that no ESIDREAST field is present. ESIDREAST Reason Text [UTF-8](n) Reason why session ended in plain text. It is encoded using [UTF-8]. Maximum length of the encoded reason is 999 octets. No general structure is defined for this attribute. ESIDCR Carriage Return Character Value: Character with hex value '0D' or '8D'. */ // ESID terminates the communication session type ESID struct { ReasonCode int ReasonText string } // ESIDCMD is the command indicator for the ESID command. const ESIDCMD = "F" func NewESID(reasonCode int, reasonText string) *ESID { return &ESID{ReasonCode: reasonCode, ReasonText: reasonText} } func (s *ESID) Command() wire.Command { s.ReasonText = wire.TruncateString(s.ReasonText, 999) // TODO: Unicode length result := wire.Command{ Format: s.dataFormat(), Data: []interface{}{ESIDCMD, s.ReasonCode, len([]byte(s.ReasonText)), s.ReasonText, "\n"}, } return result } var valuesESIDREAS = map[int]string{ 0: "Normal session termination", 1: "Command not recognised", 2: "Protocol violation", 3: "User code not known", 4: "Invalid password", 5: "Local site emergency close down", 6: "Command contained invalid data", 7: "Exchange Buffer size error", 8: "Resources not available", 9: "Time out", 10: "Mode or capabilities incompatible", 11: "Invalid challenge response", 12: "Secure authentication requirements incompatible", 99: "Unspecified Abort code", } // formatDefinition returns the format definition as given in the RFC5024 func (s *ESID) formatDefinition() []wire.FormatDefinition { return []wire.FormatDefinition{ {`F X(1)`, `ESIDCMD`, &[]wire.Value{{ESIDCMD, "ESID Command"}}}, {`F 9(2)`, `ESIDREAS`, wire.IntMapToValues(valuesESIDREAS, 2)}, {`V 9(3)`, `ESIDREASL`, nil}, {`V T(n)`, `ESIDREAST`, nil}, {`F X(1)`, `ESIDCR`, wire.ValueNewline}, } } // dataFormat returns the format definition for this command in a machine // readable form. func (s *ESID) dataFormat() []wire.DataFormat { return wire.FormatDefinitionsToDataFormats(s.formatDefinition()) } func (s *ESID) Marshal() []byte { c := s.Command() return c.Marshal() } func (s *ESID) Parse(input []byte) error { buffer, err := wire.NewBuffer(&input, ESIDCMD) if err != nil { return err } s.ReasonCode = buffer.GetNumInt(2) lenReasonText := buffer.GetNumInt(3) s.ReasonText = buffer.GetString(lenReasonText) _ = buffer.GetString(1) return nil } func (s *ESID) String() string { return fmt.Sprintf("ESID - End Session. Reason Code: %d (%s), Text: %s", s.ReasonCode, valuesESIDREAS[s.ReasonCode], s.ReasonText) } func BuildESID(reasonCode int, reasonText string) ESID { esid := ESID{ ReasonCode: reasonCode, ReasonText: reasonText, } return esid }
samiriff/scikit-dataaccess-ode
skdaccess/utilities/grace_util.py
<filename>skdaccess/utilities/grace_util.py # The MIT License (MIT) # Copyright (c) 2016, 2017, 2018 Massachusetts Institute of Technology # # Authors: <NAME> # This software has been created in projects supported by the US National # Science Foundation and NASA (PI: Pankratius) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # Standard library imports from itertools import combinations from collections import OrderedDict # Scikit Data Access imports from .image_util import convertBinCentersToEdges # 3rd part imports import pandas as pd import numpy as np from netCDF4 import Dataset, num2date def averageDates(dates, round_nearest_day = False): ''' Compute the average of a pandas series of timestamps @param dates: Pandas series of pandas datetime objects @param round_nearest_day: Round to the nearest day @return Average of dates ''' start = dates.min() newdate = (dates - start).mean() + start if round_nearest_day: newdate = newdate.round('D') return newdate def dateMismatch(dates, days=10): ''' Check if dates are not within a certain number of days of each other @param dates: Iterable container of pandas timestamps @param days: Number of days @return true if they are not with 10 days, false otherwise ''' for combo in combinations(dates,2): if np.abs(combo[0] - combo[1]) > pd.to_timedelta(days, 'D'): return True return False def computeEWD(grace_data, scale_factor, round_nearest_day=False): ''' Compute scale corrected equivalent water depth Equivalent water depth by averaging results from GFZ, CSR, and JPL, and then applying the scale factor @param grace_data: Data frame containing grace data @param scale_factor: Scale factor to apply @param round_nearest_day: Round dates to nearest day @return Equivalent water depth determined by applying the scale factor to the average GFZ, JPL and CSR. ''' def cutMissingData(in_data, reverse=False): ''' Removes data from the beginning (or ending if reverse=True) so that data exists for all 3 sources (GFZ, JPL, and CSR). This function is necessary as not all sources may get cut when a starting and ending date is specified. @param in_data: Input grace data @param reverse: Remove data from end instead of beginning @return Tuple containing modified in_data, the last cut date ''' last_cut_date = None if reverse==True: index = in_data.index[::-1] else: index = in_data.index for date in index: cut = in_data.loc[date-pd.to_timedelta('10D'):date+pd.to_timedelta('10D')] if min(len(cut['CSR'].dropna()), len(cut['GFZ'].dropna()), len(cut['JPL'].dropna())) == 0: if reverse: in_data = in_data.iloc[:-1] else: in_data = in_data.iloc[1:] last_cut_date = date else: break return in_data,last_cut_date # Check if there is no valid data if len(grace_data['CSR'].dropna()) + len(grace_data['GFZ'].dropna()) + len(grace_data['JPL'].dropna()) == 0: if round_nearest_day == True: return pd.Series(np.nan, index=grace_data.index.round('D')) else: return pd.Series(np.nan, index=grace_data.index) # Find all months that have different dates supplied by GFZ, JPL, and CSR offsets = grace_data[grace_data.isnull().any(axis=1)] # Starting and ending months if they don't have valid data for all 3 data sets offsets,cut_date1 = cutMissingData(offsets) offsets,cut_date2 = cutMissingData(offsets, reverse=True) # If beginning data has been cut, update data accordingly if cut_date1 != None: index_location = np.argwhere(grace_data.index == cut_date1)[0][0] new_index = grace_data.index[index_location+1] grace_data = grace_data.loc[new_index:] # If ending data has been cut, update data accordingly if cut_date2 != None: index_location = np.argwhere(grace_data.index == cut_date2)[0][0] new_index = grace_data.index[index_location-1] grace_data = grace_data.loc[:new_index] # Get all valid data for JPL, GFZ, and CSR csr = offsets['CSR'].dropna() gfz = offsets['GFZ'].dropna() jpl = offsets['JPL'].dropna() new_index = [] new_measurements = [] # Iterate over all data with offset dates and combine them for (c_i, c_v), (g_i,g_v), (j_i, j_v) in zip(csr.iteritems(), gfz.iteritems(), jpl.iteritems()): # Check if the dates are within 10 days of each other dates = pd.Series([c_i,g_i,j_i]) if dateMismatch(dates): raise ValueError('Different dates are not within 10 days of each other') # Determine new index and average value of data new_index.append(averageDates(dates, round_nearest_day)) new_measurements.append(np.mean([c_v, g_v, j_v])) # Create series from averaged results fixed_means = pd.Series(data = new_measurements, index=new_index) fixed_means.index.name = 'Date' # Averaging results from non mimsatched days ewt = grace_data.dropna().mean(axis=1) # If requested, round dates to nearest day if round_nearest_day: ewt_index = ewt.index.round('D') else: ewt_index = ewt.index # Reset ewt index ewt = pd.Series(ewt.as_matrix(),index = ewt_index) # Combined data with mismatched days with data # without mismatched days ewt = pd.concat([ewt, fixed_means]) ewt.sort_index(inplace=True) # Apply scale factor ewt = ewt * scale_factor # Return results return ewt def readTellusData(filename, lat_lon_list, lat_name, lon_name, data_name, data_label=None, time_name=None, lat_bounds_name=None, lon_bounds_name=None, uncertainty_name = None, lat_bounds=None, lon_bounds = None): ''' This function reads in netcdf data provided by GRACE Tellus @param filename: Name of file to read in @param lat_lon_list: List of latitude, longitude tuples that are to be read @param data_label: Label for data @param lat_name: Name of latitude data @param lon_name: Name of longitude data @param data_name: Name of data product @param time_name: Name of time data @param lat_bounds_name: Name of latitude boundaries @param lon_bounds_name: Name of longitude boundaries @param uncertainty_name: Name of uncertainty in data set @param lat_bounds: Latitude bounds @param lon_bounds: Longitude bounds @return dictionary containing data and dictionary containing latitude and longitude ''' def findBin(in_value, in_bounds): search = np.logical_and(in_value >= in_bounds[:,0], in_value < in_bounds[:,1]) if np.sum(search) == 1: return np.argmax(search) elif in_value == in_bounds[-1]: return len(in_bounds)-1 else: raise RuntimeError("Value not found") if data_label == None and time_name != None: raise RuntimeError("Need to specify data label when time data is used") if lat_bounds is None and lon_bounds is not None or \ lat_bounds is not None and lon_bounds is None: raise ValueError('Must specify both lat_bounds and lon_bounds, or neither of them') nc = Dataset(filename, 'r') lat_data = nc[lat_name][:] lon_data = nc[lon_name][:] data = nc[data_name][:] if lat_bounds is None: if lat_bounds_name == None and lon_bounds_name == None: lat_edges = convertBinCentersToEdges(lat_data) lon_edges = convertBinCentersToEdges(lon_data) lat_bounds = np.stack([lat_edges[:-1], lat_edges[1:]], axis=1) lon_bounds = np.stack([lon_edges[:-1], lon_edges[1:]], axis=1) else: lat_bounds = nc[lat_bounds_name][:] lon_bounds = nc[lon_bounds_name][:] if time_name != None: time = nc[time_name] date_index = pd.to_datetime(num2date(time[:],units=time.units,calendar=time.calendar)) if uncertainty_name != None: uncertainty = nc[uncertainty_name][:] data_dict = OrderedDict() meta_dict = OrderedDict() for lat, lon in lat_lon_list: # Convert lontitude to 0-360 orig_lon = lon if lon < 0: lon += 360. lat_bin = findBin(lat, lat_bounds) lon_bin = findBin(lon, lon_bounds) label = str(lat) + ', ' + str(orig_lon) if time_name != None and uncertainty_name != None: frame_data_dict = OrderedDict() frame_data_dict[data_label] = data[:,lat_bin, lon_bin] frame_data_dict['Uncertainty'] = uncertainty[:,lat_bin, lon_bin] data_dict[label] = pd.DataFrame(frame_data_dict, index=date_index) elif time_name != None and uncertainty_name == None: data_dict[label] = pd.DataFrame({data_label : data[:, lat_bin, lon_bin]}, index=date_index) else: data_dict[label] = data[lat_bin, lon_bin] meta_dict[label] = OrderedDict() meta_dict[label]['Lat'] = lat meta_dict[label]['Lon'] = orig_lon return data_dict, meta_dict, lat_bounds, lon_bounds def getStartEndDate(in_data): label, data = next(in_data.items()) start_date = in_data.index[0] end_date = in_data.index[-1] return start_date, end_date
danjung/sparsemapcontent
src/main/java/org/sakaiproject/nakamura/lite/lock/Lock.java
package org.sakaiproject.nakamura.lite.lock; import java.util.Map; import org.sakaiproject.nakamura.api.lite.StorageClientUtils; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; public class Lock { private static final String PATH_FIELD = "p"; private static final String USER_FIELD = "u"; private static final String EXPIRES_FIELD = "x"; private static final String EXPIRES_AT_FIELD = "a"; private static final String EXTRA_FIELD = "e"; private static final String TOKEN_FIELD = "t"; private Map<String, Object> lockMap; /** * @param path * @param user * @param expires * when the lock will expire in seconds from the time its * created. * @param extra */ public Lock(String path, String user, long timeoutInSeconds, String extra) { this(path, user, timeoutInSeconds, extra, StorageClientUtils.insecureHash(System .currentTimeMillis() + ":" + path + ":" + user + ":" + timeoutInSeconds)); } public Lock(Map<String, Object> lockMap) { this.lockMap = ImmutableMap.copyOf(lockMap); } public Lock(String path, String user, long timeoutInSeconds, String extra, String token) { Builder<String, Object> b = ImmutableMap.builder(); b.put(Lock.PATH_FIELD, path); b.put(Lock.USER_FIELD, user); b.put(Lock.EXPIRES_FIELD, timeoutInSeconds); b.put(Lock.EXPIRES_AT_FIELD, System.currentTimeMillis() + (timeoutInSeconds * 1000L)); b.put(Lock.EXTRA_FIELD, extra); b.put(Lock.TOKEN_FIELD, token); lockMap = b.build(); } public boolean hasExpired() { return System.currentTimeMillis() > (Long) lockMap.get(Lock.EXPIRES_AT_FIELD); } public boolean isOwner(String currentUser) { return currentUser.equals(lockMap.get(Lock.USER_FIELD)); } public Map<String, Object> getProperties() { return lockMap; } public boolean hasToken(String token) { return token.equals(lockMap.get(TOKEN_FIELD)); } public String getToken() { return (String) lockMap.get(TOKEN_FIELD); } public String getOwner() { return (String) lockMap.get(USER_FIELD); } @Override public String toString() { return String.valueOf(lockMap); } @Override public boolean equals(Object obj) { if (obj instanceof Lock) { return getToken().equals(((Lock) obj).getToken()); } return false; } @Override public int hashCode() { return getToken().hashCode(); } public String getExtra() { return (String) lockMap.get(EXTRA_FIELD); } }
Jing-Van/DSAlgorithm
ch1/Q1_04_Palindrome_Permutation/QuestionC.java
package ch1.Q1_04_Palindrome_Permutation; public class QuestionC { /* Toggle the ith bit in the integer. */ public static int toggle(int bitVector, int index) { if (index < 0) return bitVector; int mask = 1 << index; if ((bitVector & mask) == 0) { bitVector |= mask; } else { bitVector &= ~mask; } return bitVector; } /* Create bit vector for string. For each letter with value i, * toggle the ith bit. */ public static int createBitVector(String phrase) { int bitVector = 0; for (char c : phrase.toCharArray()) { int x = Common.getCharNumber(c); bitVector = toggle(bitVector, x); } return bitVector; } /* Check that exactly one bit is set by subtracting one from the * integer and ANDing it with the original integer. */ public static boolean checkExactlyOneBitSet(int bitVector) { return (bitVector & (bitVector - 1)) == 0; } public static boolean isPermutationOfPalindrome(String phrase) { int bitVector = createBitVector(phrase); return bitVector == 0 || checkExactlyOneBitSet(bitVector); } public static void main(String[] args) { String pali = "Rats live on no evil star"; System.out.println(isPermutationOfPalindrome(pali)); } }
saaisha/wizardPager
sample/src/main/java/com/example/android/wizardpager/pages/CustomerInfoFragment.java
<filename>sample/src/main/java/com/example/android/wizardpager/pages/CustomerInfoFragment.java package com.example.android.wizardpager.pages; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.TextView; import com.example.android.wizardpager.R; import com.tech.freak.wizardpager.ui.PageFragmentCallbacks; /** * Created by TechFreak on 04/09/2014. */ public class CustomerInfoFragment extends Fragment { private static final String ARG_KEY = "key"; private PageFragmentCallbacks mCallbacks; private String mKey; private CustomerInfoPage mPage; private TextView mNameView; private TextView mEmailView; public static CustomerInfoFragment create(String key) { Bundle args = new Bundle(); args.putString(ARG_KEY, key); CustomerInfoFragment fragment = new CustomerInfoFragment(); fragment.setArguments(args); return fragment; } public CustomerInfoFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); mKey = args.getString(ARG_KEY); mPage = (CustomerInfoPage) mCallbacks.onGetPage(mKey); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_page_customer_info, container, false); ((TextView) rootView.findViewById(android.R.id.title)).setText(mPage.getTitle()); mNameView = ((TextView) rootView.findViewById(R.id.your_name)); mNameView.setText(mPage.getData().getString(CustomerInfoPage.NAME_DATA_KEY)); mEmailView = ((TextView) rootView.findViewById(R.id.your_email)); mEmailView.setText(mPage.getData().getString(CustomerInfoPage.EMAIL_DATA_KEY)); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof PageFragmentCallbacks)) { throw new ClassCastException("Activity must implement PageFragmentCallbacks"); } mCallbacks = (PageFragmentCallbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mNameView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { mPage.getData().putString(CustomerInfoPage.NAME_DATA_KEY, (editable != null) ? editable.toString() : null); mPage.notifyDataChanged(); } }); mEmailView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable editable) { mPage.getData().putString(CustomerInfoPage.EMAIL_DATA_KEY, (editable != null) ? editable.toString() : null); mPage.notifyDataChanged(); } }); } @Override public void setMenuVisibility(boolean menuVisible) { super.setMenuVisibility(menuVisible); // In a future update to the support library, this should override setUserVisibleHint // instead of setMenuVisibility. if (mNameView != null) { InputMethodManager imm = (InputMethodManager) getActivity().getSystemService( Context.INPUT_METHOD_SERVICE); if (!menuVisible) { imm.hideSoftInputFromWindow(getView().getWindowToken(), 0); } } } }
inbreaks/posthog.com
src/templates/Customer.js
import { MDXProvider } from '@mdx-js/react' import { BorderWrapper } from 'components/BorderWrapper' import Breadcrumbs from 'components/Breadcrumbs' import { FloatedImage } from 'components/FloatedImage' import { ImageBlock } from 'components/ImageBlock' import Layout from 'components/Layout' import { SEO } from 'components/seo' import { graphql } from 'gatsby' import { MDXRenderer } from 'gatsby-plugin-mdx' import React from 'react' import { shortcodes } from '../mdxGlobalComponents' import Link from 'components/Link' const A = (props) => <Link {...props} className="text-red hover:text-red font-semibold" /> const components = { ...shortcodes, BorderWrapper, ImageBlock, FloatedImage, a: A, } const Tags = ({ title, tags }) => { return ( <li className="border-b border-dashed border-gray-accent-light"> <h4 className="text-gray m-0 text-[15px]">{title}</h4> <ul className="list-none m-0 p-0 text-base flex flex-wrap"> {tags.map((tag, index) => { return ( <li key={index} className="font-bold after:content-['\002C\00A0'] last:after:content-['']"> {tag} </li> ) })} </ul> </li> ) } export default function Customer({ data }) { const { customerData: { body, excerpt, fields, frontmatter: { title, customer, logo, description, industries, users, toolsUsed, featuredImage }, }, } = data return ( <> <SEO title={`${title} - PostHog`} description={description || excerpt} article image={`/og-images/${fields.slug.replace(/\//g, '')}.jpeg`} /> <Layout> <div className="px-4 sticky top-[-2px] bg-tan dark:bg-primary z-10"> <Breadcrumbs crumbs={[ { title: 'Customers', url: '/customers', }, { title: customer, }, ]} /> </div> <div className="max-w-screen-lg lg:max-w-screen-lg 2xl:max-w-screen-xl mx-auto px-4 flex flex-col md:flex-row items-start mt-16 md:mt-20"> <aside className="md:mr-9 mb-9 md:mb-0 md:sticky top-20 md:pr-9 md:border-r border-dashed border-gray-accent-light w-full md:w-auto"> {logo && <img className="w-full max-w-[150px]" src={logo.publicURL} />} <ul className="list-none flex-col flex space-y-8 p-0 mt-10 min-w-[250px]"> <Tags title="Industry" tags={industries} /> <Tags title="Users" tags={users} /> <Tags title="Tools used" tags={toolsUsed} /> </ul> </aside> <section className="article-content customer-content"> <h1 className="text-3xl">{title}</h1> <MDXProvider components={components}> <MDXRenderer>{body}</MDXRenderer> </MDXProvider> </section> </div> </Layout> </> ) } export const query = graphql` query Customer($id: String!) { customerData: mdx(id: { eq: $id }) { body excerpt(pruneLength: 150) fields { slug } frontmatter { title customer logo { publicURL } description industries users toolsUsed featuredImage { publicURL } } } } `
Quansight/graphql-schema-org
src/videoQuality.js
<gh_stars>10-100 import datatypes from './datatype' export default { type: datatypes['String'], description: 'The quality of the video.', name: 'Video Quality', }
haohanscm/pds
src/main/java/com/haohan/platform/service/sys/modules/thirdplatform/smartpay/apmp2/util/ApmpSecurityUtil.java
<filename>src/main/java/com/haohan/platform/service/sys/modules/thirdplatform/smartpay/apmp2/util/ApmpSecurityUtil.java package com.haohan.platform.service.sys.modules.thirdplatform.smartpay.apmp2.util; import org.bouncycastle.util.encoders.Base64; import javax.management.openmbean.InvalidKeyException; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; public class ApmpSecurityUtil { public static boolean verify(byte[] data, String sign, String key) { boolean result = false; PublicKey publicKey = getPublicKey(key); Signature sig; try { sig = Signature.getInstance("SHA1WithRSA"); sig.initVerify(publicKey); sig.update(data); result = sig.verify(CodeUtil.hexString2Byte(sign)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return result; } public static PublicKey getPublicKey(String publicKeyBase64) { byte[] keyBytes = Base64.decode(publicKeyBase64); try { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(keySpec); return publicKey; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return null; } public static PrivateKey getPrivateKey(String privateKeyBase64) { byte[] keyBytes = Base64.decode(privateKeyBase64); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory; try { keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return null; } public static String sign(byte[] data, String privateKeyBase64) throws Exception { String signStr = ""; try { PrivateKey privateKey = getPrivateKey(privateKeyBase64); Signature signature = Signature.getInstance("SHA1WithRSA"); signature.initSign(privateKey); signature.update(data); signStr = CodeUtil.byte2HexString(signature.sign()); } catch (Exception e) { e.printStackTrace(); } return signStr; } }
skeithtan/falcon
client/src/pages/FacultyLoading/components/modals/RemoveFacultyModal/index.js
<filename>client/src/pages/FacultyLoading/components/modals/RemoveFacultyModal/index.js<gh_stars>1-10 import React from "react"; import DialogContentText from "@material-ui/core/DialogContentText"; import { ConfirmActionModal } from "../../../../../components/ConfirmActionModal"; import { wrap } from "./wrapper"; import { getFullName } from "../../../../../utils/user.util"; import { termScheduleToString } from "../../../../../utils/faculty_loading.util"; import { getPossessivePronoun } from "../../../../../utils/faculty.util"; class BaseRemoveFacultyModal extends ConfirmActionModal { get dialogTitle() { return "Are you sure you want to remove this faculty from this term?"; } get dialogContent() { const { faculty, termSchedule } = this.props; const fullName = getFullName(faculty.user); const possesivePronoun = getPossessivePronoun(faculty); return ( <DialogContentText> You are about to remove <strong>{fullName}</strong> from{" "} {termScheduleToString(termSchedule)}. Once removed, classes that are assigned to {possesivePronoun} will be unassigned. </DialogContentText> ); } get buttonName() { return "Remove faculty"; } get submitAction() { const { termSchedule, faculty, onConfirmRemove } = this.props; return () => onConfirmRemove(termSchedule, faculty); } get toastSuccessMessage() { return "Faculty successfully removed from term"; } } export const RemoveFacultyModal = wrap(BaseRemoveFacultyModal);
fiatinsight/fiat_publication
app/controllers/fiat_publication/navigation_items_controller.rb
<reponame>fiatinsight/fiat_publication module FiatPublication class NavigationItemsController < ActionController::Base before_action :set_navigation_item, only: [:show, :edit, :update, :destroy] def new @navigation_item = NavigationItem.new end def create @navigation_item = NavigationItem.create(navigation_item_params) respond_to do |format| if @navigation_item.save format.html { redirect_to main_app.send(FiatPublication.new_navigation_item_redirect_path, @navigation_item), notice: 'Item was created.' } else format.html { render action: "new" } end end end def edit end def update respond_to do |format| if @navigation_item.update(navigation_item_params) format.html { redirect_back(fallback_location: navigation_item_path(@navigation_item), notice: 'Item successfully updated.') } else format.html { render action: "edit" } end end end def destroy @navigation_item.destroy respond_to do |format| if params[:nested_parent_id] format.html { redirect_to main_app.send(FiatPublication.navigation_items_path, params[:nested_parent_id]), notice: 'Item was successfully deleted.' } else format.html { redirect_to main_app.send(FiatPublication.navigation_items_path), notice: 'Item was successfully deleted.' } end end end private def set_navigation_item @navigation_item = NavigationItem.find(params[:id]) end def navigation_item_params params.require(:navigation_item).permit(:publisher_type, :publisher_id, :title, :navigable_id, :navigable_type, :url, :position, :navigation_group_id, :icon, :global_navigable, :button, :button_position) end end end
botandrose/adva_cms
adva_cms/lib/webrat_patch.rb
<reponame>botandrose/adva_cms<filename>adva_cms/lib/webrat_patch.rb<gh_stars>10-100 module Webrat class Session def current_host URI.parse(current_url).host || @context.host || "www.example.com" end def response_location_host URI.parse(response_location).host || @context.host || "www.example.com" end end end
AleksNeStu/projects
tasks/EPAM/python_course/foundation-python/l6/m6-16.py
"""open()""" file_relative_path = "./test_file" file_full_path = "/Projects/sessions/s6/test_file" # open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): #file f1 = open(file_relative_path, mode='r', buffering=True) # open file in current directory f2 = open(file_full_path) # specifying full path #mode """ Mode Description 'r' Open a file for reading. (default) 'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists. 'x' Open a file for exclusive creation. If the file already exists, the operation fails. 'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist. 't' Open in text mode. (default) 'b' Open in binary mode. '+' Open a file for updating (reading and writing) """ f3 = open(file_relative_path) # equivalent to 'r' or 'rt' f4 = open(file_relative_path,'w') # write in text mode f5 = open(file_relative_path,'r+b') # read and write in binary mode #encoding f6 = open(file=file_relative_path, mode='r+', encoding='utf-8') # # lsof ./test_file #close f6.close() # safer way 1 f7 = open(file=file_relative_path, mode='r+', encoding='utf-8') try: f7.write("new_str") finally: f7.close() # safer way 2 with open(file=file_relative_path, mode='r+', encoding='utf-8') as f8: f8.write("new_str2") print("done") """ Python File Methods close() Close an open file. It has no effect if the file is already closed. detach() Separate the underlying binary buffer from the TextIOBase and return it. fileno() Return an integer number (file descriptor) of the file. flush() Flush the write buffer of the file stream. isatty() Return True if the file stream is interactive. read(n) Read atmost n characters form the file. Reads till end of file if it is negative or None. readable() Returns True if the file stream can be read from. readline(n=-1) Read and return one line from the file. Reads in at most n bytes if specified. readlines(n=-1) Read and return a list of lines from the file. Reads in at most n bytes/characters if specified. seek(offset,from=SEEK_SET) Change the file position to offset bytes, in reference to from (start, current, end). seekable() Returns True if the file stream supports random access. tell() Returns the current file location. truncate(size=None) Resize the file stream to size bytes. If size is not specified, resize to current location. writable() Returns True if the file stream can be written to. write(s) Write string s to the file and return the number of characters written. writelines(lines) Write a list of lines to the file. """
panyox/fiber
fiber-demo/fiber-demo-dubbo/src/main/java/com/fiber/demo/dubbo/service/impl/TestServiceImpl.java
<gh_stars>0 package com.fiber.demo.dubbo.service.impl; import com.fiber.demo.dubbo.service.TestService; import com.fiber.rpc.dubbo.annotation.FiberService; import com.fiber.rpc.dubbo.annotation.GetRoute; /** * @author panyox */ @FiberService("test") public class TestServiceImpl implements TestService { @Override @GetRoute("hello") public String test() { return "hello world"; } }
AkihideHayashi/torchfes1
torchfes/fes/plumed.py
<reponame>AkihideHayashi/torchfes1 from typing import Dict import array import torch from torch import Tensor, instance_norm from torchfes import properties as p try: import plumed except ModuleNotFoundError: pass def _toarray(tensor): return array.array('d', tensor.detach().to('cpu').numpy()) class Plumed: def __init__(self, n, kbt, timestep, logpath='test.log'): # if 'plumed' not in locals(): # raise RuntimeError('plumed not imported.') self.box = array.array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0]) self.virial = array.array('d', [0, 0, 0, 0, 0, 0, 0, 0, 0]) self.masses = array.array('d', [0] * n) self.charges = array.array('d', [0] * n) self.forces = array.array('d', [0] * 3 * n) self.positions = array.array('d', [0] * 3 * n) self.step = 0 self.bias = array.array('d', [0]) self.p = plumed.Plumed() self.p.cmd("setNatoms", n) self.p.cmd("setKbT", kbt) self.p.cmd("setTimestep", timestep) self.p.cmd("setLogFile", logpath) self.p.cmd("init") self.commands = [] def calc(self): self.p.cmd("setStep", self.step) self.p.cmd("setBox", self.box) self.p.cmd("setMasses", self.masses) self.p.cmd("setCharges", self.charges) self.p.cmd("setPositions", self.positions) self.p.cmd("setForces", self.forces) self.p.cmd("setVirial", self.virial) self.p.cmd("calc") def readInputLine(self, command): self.p.cmd("readInputLine", command) self.commands.append(command) def read(self, label, command, **args): line = make_plumed_command(label, command, **args) # print(line) self.readInputLine(line) def __call__(self, mol: Dict[str, Tensor]): assert mol[p.stp].size(0) == 1, mol[p.stp].size() self.step = int(mol[p.stp].item()) self.positions[:] = _toarray(mol[p.pos].flatten()) self.masses[:] = _toarray(mol[p.mas].flatten()) self.forces[:] = _toarray(mol[p.frc].flatten()) self.box[:] = _toarray(mol[p.cel].flatten()) self.virial[:] = array.array('d', [0.0] * 9) self.calc() self.p.cmd("getBias", self.bias) ret = mol.copy() ret[p.eng_res] += self.bias[0] ret[p.eng] += self.bias[0] ret[p.frc][:] = torch.tensor(self.forces).reshape_as(ret[p.frc]) return ret def make_plumed_command(label, command, **args): def _inner(key, val): if isinstance(val, torch.Tensor): val = val.tolist() if isinstance(val, list): v = ','.join(map(str, val)) return f'{key}={v}' if isinstance(val, str): return f'{key}={val}' if isinstance(val, (int, float)): return f'{key}={val}' if val is None: return f'{key}' else: raise NotImplementedError() arg = ' '.join(_inner(key, val) for key, val in args.items()) return f'{label}: {command} {arg}'
YKYou/poco
XML/include/Poco/XML/QName.h
<gh_stars>1000+ // // QName.h // // Library: XML // Package: XML // Module: QName // // Definition of the QName class. // // Copyright (c) 2015, Applied Informatics Software Engineering GmbH. // and Contributors. // // Based on libstudxml (http://www.codesynthesis.com/projects/libstudxml/). // Copyright (c) 2009-2013 Code Synthesis Tools CC. // // SPDX-License-Identifier: BSL-1.0 // #ifndef XML_QName_INCLUDED #define XML_QName_INCLUDED #include "Poco/XML/XML.h" #include <string> #include <iosfwd> namespace Poco { namespace XML { class XML_API QName /// This class represents a qualified XML name in the stream parser. /// /// Note that the optional prefix is just a "syntactic sugar". In /// particular, it is ignored by the comparison operators and the /// std::ostream insertion operator. { public: QName(); QName(const std::string& name); QName(const std::string& ns, const std::string& name); QName(const std::string& ns, const std::string& name, const std::string& prefix); QName(const QName& qname); QName(QName&& qname) noexcept; QName& operator = (const QName& qname); QName& operator = (QName&& qname) noexcept; void swap(QName& qname); const std::string& namespaceURI() const; /// Returns the namespace URI part of the name. const std::string& localName() const; /// Returns the local part of the name. const std::string& prefix() const; /// Returns the namespace prefix of the name. std::string& namespaceURI(); /// Returns the namespace URI part of the name. std::string& localName(); /// Returns the local part of the name. std::string& prefix(); /// Returns the namespace prefix of the name. std::string toString() const; /// Returns a printable representation in the [<namespace>#]<name> form. public: friend bool operator < (const QName& x, const QName& y); friend bool operator == (const QName& x, const QName& y); friend bool operator != (const QName& x, const QName& y); private: std::string _ns; std::string _name; std::string _prefix; }; // // inlines // inline const std::string& QName::namespaceURI() const { return _ns; } inline const std::string& QName::localName() const { return _name; } inline const std::string& QName::prefix() const { return _prefix; } inline std::string& QName::namespaceURI() { return _ns; } inline std::string& QName::localName() { return _name; } inline std::string& QName::prefix() { return _prefix; } XML_API std::ostream& operator << (std::ostream&, const QName&); inline bool operator < (const QName& x, const QName& y) { return x._ns < y._ns || (x._ns == y._ns && x._name < y._name); } inline bool operator == (const QName& x, const QName& y) { return x._ns == y._ns && x._name == y._name; } inline bool operator != (const QName& x, const QName& y) { return !(x == y); } } } // namespace Poco::XML #endif // XML_QName_INCLUDED
abhiisheek/react-chatbot
src/docs/examples/Loader/DefaultLoader.js
<filename>src/docs/examples/Loader/DefaultLoader.js import React from 'react'; import Loader from 'react-chatbot/Loader'; /** Default loader icon */ const DefaultLoader = () => <Loader />; export default DefaultLoader;
monash-emu/summer
tests/test_flows/test_transition_flow.py
from summer import Compartment, Stratification, adjust from summer.flows import BaseTransitionFlow class TransitionFlow(BaseTransitionFlow): """Basic transition flow used to test BaseTransitionFlow stratification.""" def get_net_flow(self, compartment_values, computed_values, time): return 1 def test_transition_flow_stratify_with_no_matching_compartments(): flow = TransitionFlow( name="flow", source=Compartment("S"), dest=Compartment("I"), param=2, adjustments=[], ) strat = Stratification( name="location", strata=["1", "2", "3"], compartments=["R"], ) new_flows = flow.stratify(strat) assert new_flows == [flow] def test_transition_flow_stratify_source_and_dest(): """ Ensure two parallel flows created, no adjustments required. """ flow = TransitionFlow( name="flow", source=Compartment("I"), dest=Compartment("R"), param=2, adjustments=[], ) strat = Stratification( name="age", strata=["1", "2"], compartments=["S", "I", "R"], ) new_flows = flow.stratify(strat) assert len(new_flows) == 2 assert new_flows[0]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I", {"age": "1"}), dest=Compartment("R", {"age": "1"}), adjustments=[], ) ) assert new_flows[1]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I", {"age": "2"}), dest=Compartment("R", {"age": "2"}), adjustments=[], ) ) def test_transition_flow_stratify_source_but_not_dest(): """ Ensure two parallel flows created, no adjustments required. """ flow = TransitionFlow( name="flow", source=Compartment("I"), dest=Compartment("R"), param=2, adjustments=[], ) strat = Stratification( name="age", strata=["1", "2"], compartments=["S", "I"], ) new_flows = flow.stratify(strat) assert len(new_flows) == 2 assert new_flows[0]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I", {"age": "1"}), dest=Compartment("R"), adjustments=[], ) ) assert new_flows[1]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I", {"age": "2"}), dest=Compartment("R"), adjustments=[], ) ) def test_transition_flow_stratify_dest_but_not_source(): """ Ensure two new flows are created and automatically adjusted to account for fan out. """ flow = TransitionFlow( name="flow", source=Compartment("I"), dest=Compartment("R"), param=2, adjustments=[], ) strat = Stratification( name="age", strata=["1", "2"], compartments=["S", "R"], ) new_flows = flow.stratify(strat) assert len(new_flows) == 2 assert new_flows[0]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I"), dest=Compartment("R", {"age": "1"}), adjustments=[adjust.Multiply(0.5)], ) ) assert new_flows[1]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I"), dest=Compartment("R", {"age": "2"}), adjustments=[adjust.Multiply(0.5)], ) ) def test_transition_flow_stratify_source_and_dest__with_flow_adjustments(): flow = TransitionFlow( name="flow", source=Compartment("I"), dest=Compartment("R"), param=2, adjustments=[adjust.Multiply(0.1)], ) strat = Stratification( name="age", strata=["1", "2"], compartments=["S", "I", "R"], ) strat.set_flow_adjustments( "flow", { "1": adjust.Multiply(0.2), "2": adjust.Multiply(0.3), }, ) new_flows = flow.stratify(strat) assert len(new_flows) == 2 assert new_flows[0]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I", {"age": "1"}), dest=Compartment("R", {"age": "1"}), adjustments=[adjust.Multiply(0.1), adjust.Multiply(0.2)], ) ) assert new_flows[1]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I", {"age": "2"}), dest=Compartment("R", {"age": "2"}), adjustments=[adjust.Multiply(0.1), adjust.Multiply(0.3)], ) ) def test_transition_flow_stratify_source_but_not_dest__with_flow_adjustments(): flow = TransitionFlow( name="flow", source=Compartment("I"), dest=Compartment("R"), param=2, adjustments=[adjust.Multiply(0.1)], ) strat = Stratification( name="age", strata=["1", "2"], compartments=["S", "I"], ) strat.set_flow_adjustments( "flow", { "1": adjust.Multiply(0.2), "2": adjust.Multiply(0.3), }, ) new_flows = flow.stratify(strat) assert len(new_flows) == 2 assert new_flows[0]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I", {"age": "1"}), dest=Compartment("R"), adjustments=[adjust.Multiply(0.1), adjust.Multiply(0.2)], ) ) assert new_flows[1]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I", {"age": "2"}), dest=Compartment("R"), adjustments=[adjust.Multiply(0.1), adjust.Multiply(0.3)], ) ) def test_transition_flow_stratify_dest_but_not_source__with_flow_adjustments(): """ Ensure flow is adjusted to account for fan out. """ flow = TransitionFlow( name="flow", source=Compartment("I"), dest=Compartment("R"), param=2, adjustments=[adjust.Multiply(0.1)], ) strat = Stratification( name="age", strata=["1", "2"], compartments=["S", "R"], ) strat.set_flow_adjustments( "flow", { "1": adjust.Multiply(0.2), "2": adjust.Multiply(0.3), }, ) new_flows = flow.stratify(strat) assert len(new_flows) == 2 assert new_flows[0]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I"), dest=Compartment("R", {"age": "1"}), adjustments=[adjust.Multiply(0.1), adjust.Multiply(0.2)], ) ) assert new_flows[1]._is_equal( TransitionFlow( name="flow", param=2, source=Compartment("I"), dest=Compartment("R", {"age": "2"}), adjustments=[adjust.Multiply(0.1), adjust.Multiply(0.3)], ) )
odelucca/rabbitmq-python-adapter
rabbitmq_adapter/listener.py
import sys import os sys.path.append(os.environ['CONFIG']) from config import * def subscribe( channel, handler, queue=config.rabbitmq.queue, durable=config.rabbitmq.durable, exchange=config.rabbitmq.exchange, prefetch_count=config.rabbitmq.prefetch.count ): channel.queue_declare(queue=queue, durable=durable) channel.queue_bind(queue=queue, exchange=exchange) channel.basic_qos(prefetch_count=prefetch_count) channel.basic_consume(queue=queue, on_message_callback=handler)
wuhao930406/ngypro
src/pages/User/Forgot.js
<reponame>wuhao930406/ngypro<gh_stars>0 import React, { Component } from 'react'; import { connect } from 'dva'; import { formatMessage, FormattedMessage } from 'umi/locale'; import Link from 'umi/link'; import router from 'umi/router'; import { Form, Input, Button, Select, Row, Col, Popover, Progress, Menu, Dropdown, message, Steps } from 'antd'; import styles from './Register.less'; import moment from 'moment'; import AES from "crypto-js/aes"; import ECB from "crypto-js/mode-ecb"; import Pkcs7 from "crypto-js/pad-pkcs7"; import Utf8 from "crypto-js/enc-utf8"; const { Step } = Steps; const FormItem = Form.Item; const { Option } = Select; const InputGroup = Input.Group; const passwordStatusMap = { ok: ( <div className={styles.success}> <FormattedMessage id="validation.password.strength.strong" /> </div> ), pass: ( <div className={styles.warning}> <FormattedMessage id="validation.password.strength.medium" /> </div> ), poor: ( <div className={styles.error}> <FormattedMessage id="validation.password.strength.short" /> </div> ), }; const passwordProgressMap = { ok: 'success', pass: 'normal', poor: 'exception', }; @connect(({ regist, loading }) => ({ regist, submitting: loading.effects['regist/submit'], })) @Form.create() class Register extends Component { constructor(props) { super(props); this.state = { current: 0, loadings: false, count: 0, confirmDirty: false, visible: false, help: '', prefix: '86', }; } onGetCaptcha = (nowcount) => { let count = nowcount ? nowcount : 59; this.setState({ count }); this.interval = setInterval(() => { count -= 1; this.setState({ count }); localStorage.setItem("sendCode", count); if (count < 1) { clearInterval(this.interval); localStorage.removeItem("sendCode"); localStorage.removeItem("LASTID"); } }, 1000); }; getPasswordStatus = () => { const { form } = this.props; const value = form.getFieldValue('newPassword'); if (value && value.length > 9) { return 'ok'; } if (value && value.length > 5) { return 'pass'; } return 'poor'; }; /* dispatch获取/设置 */ setNewState(type, value, fn) { let { dispatch } = this.props; dispatch({ type: 'regist/' + type, payload: value }).then((res) => { if(res){ fn ? fn() : null }else{ clearInterval(this.interval); this.setState({ count: 0, loadings:false }) } }); } handleConfirmBlur = e => { const { value } = e.target; const { confirmDirty } = this.state; this.setState({ confirmDirty: confirmDirty || !!value }); }; checkConfirm = (rule, value, callback) => { const { form } = this.props; if (value && value !== form.getFieldValue('newPassword')) { callback(formatMessage({ id: 'validation.password.twice' })); } else { callback(); } }; checkPassword = (rule, value, callback) => { const { visible, confirmDirty } = this.state; if (!value) { this.setState({ help: formatMessage({ id: 'validation.password.required' }), visible: !!value, }); callback('error'); } else { this.setState({ help: '', }); if (!visible) { this.setState({ visible: !!value, }); } if (value.length < 6) { callback('error'); } else { const { form } = this.props; if (value && confirmDirty) { form.validateFields(['confirm'], { force: true }); } callback(); } } }; renderPasswordProgress = () => { const { form } = this.props; const value = form.getFieldValue('newPassword'); const passwordStatus = this.getPasswordStatus(); return value && value.length ? ( <div className={styles[`progress-${passwordStatus}`]}> <Progress status={passwordProgressMap[passwordStatus]} className={styles.progress} strokeWidth={6} percent={value.length * 10 > 100 ? 100 : value.length * 10} showInfo={false} /> </div> ) : null; }; //是否提交 next = () => { const current = this.state.current; this.handleSubmit(current) } handleSubmit = (current) => { const { form, dispatch } = this.props; form.validateFields({ force: true }, (err, values) => { if (!err) { if (current == 0) { this.setNewState("compairCode",{id:this.props.regist.sendCode.id,code:values.verificationCode}, () => { this.setState({ current: current + 1 }); }) } else { let timestamp = moment().valueOf().toString()+"acb"; let newtimestamp = AES.encrypt(timestamp,Utf8.parse('NANGAODEAESKEY--'), { mode: ECB, padding: Pkcs7 }).toString(); let newPassword = AES.encrypt(values.newPassword,Utf8.parse(timestamp),{ mode: ECB, padding: Pkcs7 }).toString() this.setNewState("updatePassword", { newPassword:<PASSWORD>, encryptKey:newtimestamp, id:this.props.regist.sendCode.id}, () => { message.success(`您的密码修改成功,新密码为${values.newPassword}`, 3); window.history.go(-1) }) } } }); }; render() { const { form, submitting } = this.props; const { getFieldDecorator, getFieldsValue } = form; const { count, prefix, help, visible, loadings, current } = this.state; const menu = ( <Menu> <Menu.Item> <a onClick={() => { let accountName = getFieldsValue().accountName; if (!accountName) { message.warn("请先输入账号..."); return } this.setState({ loadings: true }) let postData = { sendType: "1", accountName: accountName } this.setNewState("sendCode", postData, () => { localStorage.setItem("LASTID", accountName) this.onGetCaptcha() this.setState({ loadings: false }) }) }}> 发送短信 </a> </Menu.Item> <Menu.Item> <a onClick={() => { let accountName = getFieldsValue().accountName; if (!accountName) { message.warn("请先输入账号..."); return } this.setState({ loadings: true }) let postData = { sendType: "2", accountName: accountName } this.setNewState("sendCode", postData, () => { localStorage.setItem("LASTID", accountName) this.onGetCaptcha() this.setState({ loadings: false }) }) }}> 发送邮件 </a> </Menu.Item> </Menu> ); const steps = [ { title: <span style={{ color: "#fff" }}>获取验证码</span>, }, { title: <span style={{ color: "#fff" }}>重置密码</span>, }, ]; return ( <div className={styles.main} style={{ width: 600 }}> <p className={styles.sildetitle} style={{ margin: 0, marginBottom: 32, marginTop: -96 }}> <FormattedMessage id="app.login.forgot-password" /> <Link className={styles.login} style={{ textAlign: "right", fontSize: 16 }} to="/user/login"> <FormattedMessage id="app.register.sign-in" /> </Link> </p> <Steps current={current} style={{ marginBottom: 24 }}> {steps.map(item => ( <Step key={item.title} title={item.title} /> ))} </Steps> <Form onSubmit={this.handleSubmit}> { current == 0 && <div> <FormItem style={{ marginBottom: 18 }}> {getFieldDecorator('accountName', { rules: [{ required: true, message: "请输入账号", } ], })( <Input size="large" type="text" placeholder="请输入账号" onChange={(e) => { let nowcount = localStorage.getItem("sendCode"), lastid = localStorage.getItem("LASTID"); if (lastid == e.target.value) { this.onGetCaptcha(nowcount); } else { clearInterval(this.interval); this.setState({ count: 0 }) } }} /> )} </FormItem> <FormItem style={{ marginBottom: 18 }}> <Row gutter={8}> <Col span={16}> {getFieldDecorator('verificationCode', { rules: [ { required: true, message: formatMessage({ id: 'validation.verification-code.required' }), }, ], })( <Input size="large" placeholder={formatMessage({ id: 'form.verification-code.placeholder' })} /> )} </Col> <Col span={8}> { count ? <Button type="primary" style={{color:"#ededed",borderColor:"#ededed"}} ghost size="large" disabled={count} className={styles.getCaptcha} > {count ? `${count} s` : formatMessage({ id: 'app.register.get-verification-code' })} </Button> : <Dropdown overlay={menu} placement="bottomLeft"> <Button type="primary" ghost style={{color:"#ededed",borderColor:"#ededed"}} loading={loadings} size="large" disabled={count} className={styles.getCaptcha} > {count ? `${count} s` : formatMessage({ id: 'app.register.get-verification-code' })} </Button> </Dropdown> } </Col> </Row> </FormItem> </div> } { current == 1 && <div> <FormItem help={help} style={{ marginBottom: 18 }}> <Popover getPopupContainer={node => node.parentNode} content={ <div style={{ padding: '4px 0' }}> {passwordStatusMap[this.getPasswordStatus()]} {this.renderPasswordProgress()} <div style={{ marginTop: 10 }}> <FormattedMessage id="validation.password.strength.msg" /> </div> </div> } overlayStyle={{ width: 240 }} placement="right" visible={visible} > {getFieldDecorator('newPassword', { rules: [ { validator: this.checkPassword, }, ], })( <Input size="large" type="password" placeholder={formatMessage({ id: 'form.password.placeholder' })} /> )} </Popover> </FormItem> <FormItem style={{ marginBottom: 18 }}> {getFieldDecorator('confirmPassword', { rules: [ { required: true, message: formatMessage({ id: 'validation.confirm-password.required' }), }, { validator: this.checkConfirm, }, ], })( <Input size="large" type="password" placeholder={formatMessage({ id: 'form.confirm-password.placeholder' })} /> )} </FormItem> </div> } <FormItem> <Button size="large" loading={submitting} className={styles.submit} type="primary" onClick={this.next} > {current == 0 ? "下一步" : "提交"} </Button> </FormItem> </Form> </div> ); } } export default Register;
ankurshukla1993/IOT-test
coeey/com/bumptech/glide/load/resource/gifbitmap/GifBitmapWrapperResourceDecoder.java
package com.bumptech.glide.load.resource.gifbitmap; import android.graphics.Bitmap; import com.bumptech.glide.load.ResourceDecoder; import com.bumptech.glide.load.engine.Resource; import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; import com.bumptech.glide.load.model.ImageVideoWrapper; import com.bumptech.glide.load.resource.bitmap.BitmapResource; import com.bumptech.glide.load.resource.bitmap.ImageHeaderParser; import com.bumptech.glide.load.resource.bitmap.ImageHeaderParser.ImageType; import com.bumptech.glide.load.resource.bitmap.RecyclableBufferedInputStream; import com.bumptech.glide.load.resource.gif.GifDrawable; import com.bumptech.glide.util.ByteArrayPool; import java.io.IOException; import java.io.InputStream; public class GifBitmapWrapperResourceDecoder implements ResourceDecoder<ImageVideoWrapper, GifBitmapWrapper> { private static final ImageTypeParser DEFAULT_PARSER = new ImageTypeParser(); private static final BufferedStreamFactory DEFAULT_STREAM_FACTORY = new BufferedStreamFactory(); static final int MARK_LIMIT_BYTES = 2048; private final ResourceDecoder<ImageVideoWrapper, Bitmap> bitmapDecoder; private final BitmapPool bitmapPool; private final ResourceDecoder<InputStream, GifDrawable> gifDecoder; private String id; private final ImageTypeParser parser; private final BufferedStreamFactory streamFactory; static class BufferedStreamFactory { BufferedStreamFactory() { } public InputStream build(InputStream is, byte[] buffer) { return new RecyclableBufferedInputStream(is, buffer); } } static class ImageTypeParser { ImageTypeParser() { } public ImageType parse(InputStream is) throws IOException { return new ImageHeaderParser(is).getType(); } } public GifBitmapWrapperResourceDecoder(ResourceDecoder<ImageVideoWrapper, Bitmap> bitmapDecoder, ResourceDecoder<InputStream, GifDrawable> gifDecoder, BitmapPool bitmapPool) { this(bitmapDecoder, gifDecoder, bitmapPool, DEFAULT_PARSER, DEFAULT_STREAM_FACTORY); } GifBitmapWrapperResourceDecoder(ResourceDecoder<ImageVideoWrapper, Bitmap> bitmapDecoder, ResourceDecoder<InputStream, GifDrawable> gifDecoder, BitmapPool bitmapPool, ImageTypeParser parser, BufferedStreamFactory streamFactory) { this.bitmapDecoder = bitmapDecoder; this.gifDecoder = gifDecoder; this.bitmapPool = bitmapPool; this.parser = parser; this.streamFactory = streamFactory; } public Resource<GifBitmapWrapper> decode(ImageVideoWrapper source, int width, int height) throws IOException { ByteArrayPool pool = ByteArrayPool.get(); byte[] tempBytes = pool.getBytes(); GifBitmapWrapper gifBitmapWrapper = null; try { gifBitmapWrapper = decode(source, width, height, tempBytes); return gifBitmapWrapper != null ? new GifBitmapWrapperResource(gifBitmapWrapper) : null; } finally { pool.releaseBytes(tempBytes); } } private GifBitmapWrapper decode(ImageVideoWrapper source, int width, int height, byte[] bytes) throws IOException { if (source.getStream() != null) { return decodeStream(source, width, height, bytes); } return decodeBitmapWrapper(source, width, height); } private GifBitmapWrapper decodeStream(ImageVideoWrapper source, int width, int height, byte[] bytes) throws IOException { InputStream bis = this.streamFactory.build(source.getStream(), bytes); bis.mark(2048); ImageType type = this.parser.parse(bis); bis.reset(); GifBitmapWrapper result = null; if (type == ImageType.GIF) { result = decodeGifWrapper(bis, width, height); } if (result == null) { return decodeBitmapWrapper(new ImageVideoWrapper(bis, source.getFileDescriptor()), width, height); } return result; } private GifBitmapWrapper decodeGifWrapper(InputStream bis, int width, int height) throws IOException { Resource<GifDrawable> gifResource = this.gifDecoder.decode(bis, width, height); if (gifResource == null) { return null; } GifDrawable drawable = (GifDrawable) gifResource.get(); if (drawable.getFrameCount() > 1) { return new GifBitmapWrapper(null, gifResource); } return new GifBitmapWrapper(new BitmapResource(drawable.getFirstFrame(), this.bitmapPool), null); } private GifBitmapWrapper decodeBitmapWrapper(ImageVideoWrapper toDecode, int width, int height) throws IOException { Resource<Bitmap> bitmapResource = this.bitmapDecoder.decode(toDecode, width, height); if (bitmapResource != null) { return new GifBitmapWrapper(bitmapResource, null); } return null; } public String getId() { if (this.id == null) { this.id = this.gifDecoder.getId() + this.bitmapDecoder.getId(); } return this.id; } }
imckh/java-learning
src/designpattern/behavioral_pattern/mediator/v1/Component.java
<gh_stars>0 package designpattern.behavioral_pattern.mediator.v1; //抽象组件类:抽象同事类 public abstract class Component { protected Mediator mediator; public void setMediator(Mediator mediator) { this.mediator = mediator; } //转发调用 public void changed() { mediator.componentChanged(this); } public abstract void update(); }
eugeneilyin/mdi-norm
es/Public.js
<gh_stars>1-10 import { createThemedIcon } from './utils/createThemedIcon'; import { FilledPublic } from './FilledPublic'; import { OutlinePublic } from './OutlinePublic'; import { RoundPublic } from './RoundPublic'; import { SharpPublic } from './SharpPublic'; import { TwoTonePublic } from './TwoTonePublic'; export var Public = /*#__PURE__*/ function Public(props) { return createThemedIcon(props, FilledPublic, OutlinePublic, RoundPublic, SharpPublic, TwoTonePublic); };
tbfungeek/React-Native-Roadmap
React-Tutorial/React-Native/rn_puzzle/screens/StartScreen.js
import React from 'react'; import { View , StyleSheet, Animated} from 'react-native'; import PropTypes from 'prop-types'; import Logo from '../components/Logo'; import Toggle from '../components/Toggle'; import Button from '../components/Button'; import sleep from '../utils/sleep' import configureTransition from '../utils/configureTransition' const State = { Launching: 'Launching', WillTransitionIn:'WillTransitionIn', WillTransitionOut:'WillTransitionOut', }; const BOARD_SIZES = [3, 4, 5, 6]; export default class StartScreen extends React.Component { static propTypes= { size: PropTypes.number.isRequired, onChangeSize:PropTypes.func.isRequired, onStartGame:PropTypes.func.isRequired, }; state = { transitionState:State.Launching, }; toggleOpacity = new Animated.Value(0); buttonOpacity = new Animated.Value(0); handleGameStart = async() => { const {onStartGame} = this.props; await configureTransition(() => { this.setState({ transitionState : State.WillTransitionOut}); }) if (!onStartGame) return; onStartGame() } async componentDidMount () { await sleep(500); await configureTransition(() => { this.setState({ transitionState: State.WillTransitionIn }); }); Animated.timing(this.toggleOpacity, { toValue:1, duration:500, delay:50, useNativeDriver:true, }).start(); Animated.timing(this.buttonOpacity,{ toValue:1, duration:500, delay:100, useNativeDriver:true, }).start(); }; render() { const {size, onChangeSize} = this.props; const {transitionState} = this.state; console.log(size) const toggleStyle = { opacity: this.toggleOpacity }; const buttonStyle = { opacity: this.buttonOpacity }; return ( transitionState !== State.WillTransitionOut && ( <View style={styles.container}> <View style={styles.logo}> <Logo/> </View> {transitionState !== State.Launching && ( <Animated.View style={toggleStyle}> <Toggle options = {BOARD_SIZES} value = {size} onChange = {onChangeSize}/> </Animated.View> )} {transitionState !== State.Launching && ( <Animated.View style={buttonStyle}> <Button title = {'Start Game'} onPress = {this.handleGameStart}/> </Animated.View> )} </View> ) ) } } const styles = StyleSheet.create({ container : { flex:1, justifyContent:'space-around', alignItems: 'center', paddingVertical: 20, }, logo: { alignSelf: 'stretch', paddingHorizontal:40, }, })
Srikrish3103/OpenRTS
core/src/geometry/geom3d/Point3D.java
<reponame>Srikrish3103/OpenRTS package geometry.geom3d; import geometry.geom2d.Point2D; import geometry.math.PrecisionUtil; import java.text.DecimalFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; public class Point3D { public static final Point3D ORIGIN = new Point3D(0, 0, 0); public static final Point3D UNIT = new Point3D(1, 1, 1); public static final Point3D UNIT_X = new Point3D(1, 0, 0); public static final Point3D UNIT_Y = new Point3D(0, 1, 0); public static final Point3D UNIT_Z = new Point3D(0, 0, 1); private static final DecimalFormat df = new DecimalFormat("0.00"); @JsonProperty public double x, y, z; public Point3D() { } public Point3D(Point2D p, double elevation) { this(p.x, p.y, elevation); } public Point3D(Point3D o) { this(o.x, o.y, o.z); } /** * create � new point 3D by : 1- elevating the given point 2D, 2- rotating the given point 2D around Z, 3- rotating the given point 2D in it's own plane. * * @param p * @param val */ public Point3D(Point2D p, double val, int param) { this(p, val, param, Point2D.ORIGIN); } public Point3D(Point2D p, double val, int param, Point2D pivot) { if (param == 1) { x = p.x; y = p.y; z = val; } else if (param == 2) { x = (p.x - pivot.x) * Math.cos(val) + pivot.x; y = (p.x - pivot.x) * Math.sin(val) + pivot.x; z = p.y; } else if (param == 3) { x = p.x * Math.cos(val); y = Point2D.ORIGIN.getDistance(p) * Math.sin(val); z = p.y * Math.cos(val); } else { throw new IllegalArgumentException("Invalid param"); } check(); } public Point3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; check(); } private void check() { boolean valid = true; if (Double.isNaN(x) || Double.isNaN(y) || Double.isNaN(z)) { valid = false; } if (Double.isInfinite(x) || Double.isInfinite(y) || Double.isInfinite(z)) { valid = false; } if (!valid) { throw new RuntimeException("Can't construct invalid " + this.getClass().getSimpleName() + " : " + this); } } @JsonIgnore public double getDistance(Point3D other) { double dx = x - other.x; double dy = y - other.y; double dz = z - other.z; return Math.sqrt(dx * dx + dy * dy + dz * dz); } @JsonIgnore public double getNorm() { return Math.sqrt(x * x + y * y + z * z); } @JsonIgnore public Point3D getNormalized() { double norm = getNorm(); if (norm == 0) { throw new RuntimeException("Can't normalize a " + this.getClass().getSimpleName() + " of norm = 0 (" + this + ")."); } return getDivision(norm); } @JsonIgnore public Point3D getCross(Point3D o) { double resX = ((y * o.z) - (z * o.y)); double resY = ((z * o.x) - (x * o.z)); double resZ = ((x * o.y) - (y * o.x)); return new Point3D(resX, resY, resZ); } @JsonIgnore public Point3D getSubtraction(Point3D o) { return new Point3D(x - o.x, y - o.y, z - o.z); } @JsonIgnore public Point3D getDivision(double val) { return new Point3D(x / val, y / val, z / val); } @JsonIgnore public Point3D getMult(double val) { return new Point3D(x * val, y * val, z * val); } @JsonIgnore public Point3D getMult(double xVal, double yVal, double zVal) { return new Point3D(x * xVal, y * yVal, z * zVal); } @JsonIgnore public Point3D getAddition(Point3D o) { return new Point3D(x + o.x, y + o.y, z + o.z); } @JsonIgnore public Point3D getAddition(double x, double y, double z) { return new Point3D(this.x + x, this.y + y, this.z + z); } @Override public boolean equals(Object o) { if (!(o instanceof Point3D)) { return false; } Point3D p = (Point3D) o; return Math.abs(x - p.x) < PrecisionUtil.APPROX && Math.abs(y - p.y) < PrecisionUtil.APPROX && Math.abs(z - p.z) < PrecisionUtil.APPROX; } @Override public String toString() { return "(" + df.format(x) + ", " + df.format(y) + ", " + df.format(z) + ")"; } @JsonIgnore public boolean isOrigin() { return equals(ORIGIN); } @JsonIgnore private double getQuaternion() { throw new RuntimeException("bloody quaternions are not implemented."); } @JsonIgnore public Point3D getTruncation(double val) { if (getNorm() > val) { return getScaled(val); } return new Point3D(this); } @JsonIgnore public Point3D getScaled(double scale) { return getNormalized().getMult(scale); } @JsonIgnore public Point3D getNegation() { return new Point3D(-x, -y, -z); } @JsonIgnore public Point2D get2D() { return new Point2D(this); } @JsonIgnore public Point3D getRotationAroundZ(double angle) { return get2D().getRotation(angle).get3D(z); } @JsonIgnore public Point3D getRotationAroundZ(double angle, Point2D pivot) { return get2D().getRotation(angle, pivot).get3D(z); } @JsonIgnore public double getDotProduct(Point3D o) { return x * o.x + y * o.y + z * o.z; } @JsonIgnore public double getAngleWith(Point3D o) { return Math.acos(getDotProduct(o) / (getNorm() * o.getNorm())); } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getZ() { return z; } public void setZ(double z) { this.z = z; } }
artourkin/c3po
c3po-api/src/main/java/com/petpet/c3po/api/adaptor/PreProcessingRule.java
<gh_stars>1-10 /******************************************************************************* * Copyright 2013 <NAME> <<EMAIL>> * * 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.petpet.c3po.api.adaptor; /** * A pre processing rule is a special processing rule that should be applied * before (or during ) meta data processing in an adaptor. Each adaptor gets a * list of {@link PreProcessingRule} object and has to pass each parsed raw * record to each rule obtained via the * {@link AbstractAdaptor#getPreProcessingRules()} method. It is up to the * adaptor implementation to decide, whether or not to apply the rules. * * @author <NAME> <<EMAIL>> * */ public interface PreProcessingRule extends ProcessingRule { /** * Returns true if the property and value should be skipped for some reason. * * The adaptors should invoke this method for each raw record and skip the * meta data record if the method returns true. * * @param property * the property of the record. * @param value * the value for the given property. * @param status * the status if it is known. * @param tool * the tool that provides this record. * @param version * the version of the tool that provides this record. * @return true if the record should be skipped, false otherwise. */ boolean shouldSkip( String property, String value, String status, String tool, String version ); }
zealoussnow/chromium
components/payments/core/error_strings.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_PAYMENTS_CORE_ERROR_STRINGS_H_ #define COMPONENTS_PAYMENTS_CORE_ERROR_STRINGS_H_ namespace payments { namespace errors { // These strings are referenced from both C++ and Java (through the // auto-generated file ErrorStrings.java). // Please keep the list alphabetized. // Only a single PaymentRequest UI can be displayed at a time. extern const char kAnotherUiShowing[]; // App store billing methods (e.g., https://play.google.com/billing) is // only supported in Trusted Web Activity. extern const char kAppStoreMethodOnlySupportedInTwa[]; // Mojo call PaymentRequest::Init() must precede PaymentRequest::Show(). extern const char kAttemptedInitializationTwice[]; // Payment Request UI must be shown in the foreground tab, as a result of user // interaction. extern const char kCannotShowInBackgroundTab[]; // Mojo call PaymentRequest::Show() cannot happen more than once per Mojo pipe. extern const char kCannotShowTwice[]; // Mojo call PaymentRequest::Init() must precede PaymentRequest::Show(). extern const char kCannotShowWithoutInit[]; // Mojo call PaymentRequest::Init() must precede PaymentRequest::UpdateWith(). extern const char kCannotUpdateWithoutInit[]; // Mojo call PaymentRequest::Show() must precede PaymentRequest::UpdateWith(). extern const char kCannotUpdateWithoutShow[]; // Used when an invalid state is encountered generically. extern const char kInvalidState[]; // Used when the {"supportedMethods": "", data: {}} is required, but not // provided. extern const char kMethodDataRequired[]; // Used when non-empty "supportedMethods": "" is required, but not provided. extern const char kMethodNameRequired[]; // The payment handler responded with an empty "details" field. extern const char kMissingDetailsFromPaymentApp[]; // The payment handler responded with an empty "methodName" field. extern const char kMissingMethodNameFromPaymentApp[]; // The PaymentRequest API is available only on secure origins. extern const char kNotInASecureOrigin[]; // WebContents is not available from RenderFrameHost. extern const char kNoWebContents[]; // The payment handler responded with an empty "payer name" field. extern const char kPayerNameEmpty[]; // The payment handler responded with an empty "payer email" field. extern const char kPayerEmailEmpty[]; // The payment handler responded with an empty "payer phone" field. extern const char kPayerPhoneEmpty[]; // Chrome provides payment information only to a whitelist of origin types. extern const char kProhibitedOrigin[]; // A long form explanation of Chrome"s behavior in the case of kProhibitedOrigin // or kInvalidSslCertificate error. extern const char kProhibitedOriginOrInvalidSslExplanation[]; // The payment handler responded with an invalid shipping address. extern const char kShippingAddressInvalid[]; // The payment handler responded with an empty "shipping option" field. extern const char kShippingOptionEmpty[]; // Used when non-empty "shippingOptionId": "" is required, but not provided. extern const char kShippingOptionIdRequired[]; // Used when an app is skipped for supporting only part of the requested payment // options. extern const char kSkipAppForPartialDelegation[]; // Used when rejecting show() with NotSupportedError, because the user did not // have all valid autofill data. extern const char kStrictBasicCardShowReject[]; // Used when "total": {"label": "Total", "amount": {"currency": "USD", "value": // "0.01"}} is required, bot not provided. extern const char kTotalRequired[]; // Used when user dismissed the Payment Request dialog. extern const char kUserCancelled[]; // Used when user cancels authentication or when there are no matching // credentials extern const char kWebAuthnOperationTimedOutOrNotAllowed[]; // Used when the renderer does not provide valid payment details, such as a null // struct or missing ID or total. extern const char kInvalidPaymentDetails[]; // Used when the renderer does not provide valid options, such as a null struct. extern const char kInvalidPaymentOptions[]; } // namespace errors } // namespace payments #endif // COMPONENTS_PAYMENTS_CORE_ERROR_STRINGS_H_
rylyade1/SecurityRAT
securityrat-backend/src/main/java/org/appsec/securityrat/web/dto/FrontendAlternativeInstanceDto.java
package org.appsec.securityrat.web.dto; import lombok.Data; import org.appsec.securityrat.api.dto.Dto; @Data public class FrontendAlternativeInstanceDto implements Dto { private Long id; private Long requirementId; private String content; }
friedcroco070801/bloodypenguins
Classes/Models/Character/Cell/ShootingCell/Projectile/ProjectileType/Cell03/Cell03ProjectileModel.h
<filename>Classes/Models/Character/Cell/ShootingCell/Projectile/ProjectileType/Cell03/Cell03ProjectileModel.h #ifndef __CELL_03_PROJECTILE_MODEL_H__ #define __CELL_03_PROJECTILE_MODEL_H__ class ProjectileModel; class CharacterModel; class Cell03ProjectileModel : public ProjectileModel { public: Cell03ProjectileModel(CellModel*, DiseaseModel*); virtual ~Cell03ProjectileModel(){} protected: }; #endif // ! __CELL_03_PROJECTILE_MODEL_H__
fraenkel/cli
src/cf/requirements/targeted_space_test.go
<reponame>fraenkel/cli package requirements import ( "cf" "cf/configuration" "github.com/stretchr/testify/assert" testterm "testhelpers/terminal" "testing" ) func TestSpaceRequirement(t *testing.T) { ui := new(testterm.FakeUI) config := &configuration.Configuration{ Organization: cf.Organization{ Name: "my-org", Guid: "my-org-guid", }, Space: cf.Space{ Name: "my-space", Guid: "my-space-guid", }, } req := newTargetedSpaceRequirement(ui, config) success := req.Execute() assert.True(t, success) config.Space = cf.Space{} req = newTargetedSpaceRequirement(ui, config) success = req.Execute() assert.False(t, success) assert.Contains(t, ui.Outputs[0], "FAILED") assert.Contains(t, ui.Outputs[1], "No space targeted") ui.ClearOutputs() config.Organization = cf.Organization{} req = newTargetedSpaceRequirement(ui, config) success = req.Execute() assert.False(t, success) assert.Contains(t, ui.Outputs[0], "FAILED") assert.Contains(t, ui.Outputs[1], "No org and space targeted") }
amiedawn/my-taco-shop
client/src/components/ItemList.js
<gh_stars>0 import React, { useEffect } from 'react'; import { useQuery } from '@apollo/client'; import MenuItem from './MenuItem'; import { useStoreContext } from '../utils/GlobalState'; import { UPDATE_ITEMS } from '../utils/actions'; import { QUERY_ITEMS } from '../utils/queries'; import { idbPromise } from '../utils/helpers'; import spinner from '../assets/spinner.gif'; function ItemList() { const [state, dispatch] = useStoreContext(); const { currentCategory } = state; const { loading, data } = useQuery(QUERY_ITEMS); // console.log(data); useEffect(() => { // if there's data to be stored if (data) { // let's store it in the global state object dispatch({ type: UPDATE_ITEMS, items: data.items, }); // but let's also take each item and save it to IndexedDB using the helper function data.items.forEach((item) => { idbPromise('items', 'put', item); }); // add else if to check if `loading` is undefined in `useQuery()` Hook } else if (!loading) { // since we're offline, get all of the data from the `items` store idbPromise('items', 'get').then((items) => { // use retrieved data to set global state for offline browsing dispatch({ type: UPDATE_ITEMS, items, }); }); } }, [data, loading, dispatch]); function filterItems() { if (!currentCategory) { return state.items; } return state.items.filter((item) => item.category._id === currentCategory); } return ( <div className="row"> <h3>Menu</h3> <p> Click on a menu image for more information</p> {state.items.length ? ( <div className="row"> {filterItems().map((item) => ( <MenuItem key={item._id} _id={item._id} image={item.image} name={item.name} price={item.price} quantity={item.quantity} description={item.description} /> ))} </div> ) : ( <h3>You haven't added any items yet!</h3> )} {loading ? <img src={spinner} alt="loading" /> : null} </div> ); } export default ItemList;
ljktest/siconos
externals/numeric_bindings/libs/numeric/bindings/tools/templates/driver/hpevx.hpp
$TEMPLATE[hpevx.all.UPLO.trait_of] AP $TEMPLATE[end]
Arquisoft/InciManager_i2b
src/test/java/com/uniovi/main/cucumber/steps/ReportIncidentSteps.java
<reponame>Arquisoft/InciManager_i2b package com.uniovi.main.cucumber.steps; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.uniovi.entities.AgentInfo; import com.uniovi.entities.Incident; import com.uniovi.entities.Operator; import com.uniovi.kafka.KafkaService; import com.uniovi.main.InciManagerI2bApplication; import com.uniovi.manager.IncidentController; import com.uniovi.services.AgentsService; import com.uniovi.services.IncidentsService; import com.uniovi.services.OperatorsService; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; @SpringBootTest( classes=InciManagerI2bApplication.class ) public class ReportIncidentSteps { @Mock private AgentsService agentsService; @Mock private IncidentsService incidentsService; @Mock public KafkaService kafkaService; @Mock public OperatorsService operatorsService; @InjectMocks private IncidentController incidentController; private MockMvc mockMvc; private MockHttpServletResponse result; private List<Incident> incidents; private AgentInfo aInfo; @Given("^a list of users:$") public void a_list_of_sensors(List<AgentInfo> agents) { incidents = new ArrayList<Incident>(); MockitoAnnotations.initMocks(this); when(operatorsService.randomOperator()).thenReturn(new Operator()); doAnswer(invocation -> { incidents.add(invocation.getArgument(0)); return null; }).when(incidentsService).addNewIncident(Mockito.any(Incident.class)); for (AgentInfo agent : agents) { when(agentsService.existsAgent(agent)).thenReturn(true); } this.mockMvc = MockMvcBuilders.standaloneSetup(incidentController).build(); } @Given("^an agent with username \"([^\"]*)\" password \"([^\"]*)\" and kind \"([^\"]*)\"$") public void an_agent_with_username_password_and_kind(String username, String password, String kind) throws Throwable { aInfo = new AgentInfo(username, password, kind); } @When("^the agent logs in$") public void the_agent_logs_in() throws Exception { mockMvc.perform(get("/agentform")); MockHttpServletRequestBuilder request = post("/agentform").param("username", aInfo.getUsername()) .param("password", aInfo.<PASSWORD>()).param("kind", aInfo.getKind()); result = mockMvc.perform(request).andReturn().getResponse(); } @When("^the agent accesses \"(.+)\"$") public void the_user_accesses(String url) throws Exception { mockMvc.perform(get(url)); } @When("^the agent posts an incident$") public void the_agent_posts_an_incident() throws Exception { String payload = String.format("{\"agent\": {\"username\": \"%s\", \"password\": \"%s\", " + "\"kind\": \"%s\"}, \"inciName\": \"Test\", \"location\": {\"lat\": 50.2, " + "\"lon\": 12.2}, \"tags\": [], \"moreInfo\": [], \"properties\": {}}", aInfo.getUsername(), aInfo.getPassword(), aInfo.getKind()); MockHttpServletRequestBuilder request = post("/incident/create") .contentType(MediaType.APPLICATION_JSON).content(payload.getBytes()); result = mockMvc.perform(request).andReturn().getResponse(); } @When("^the sensor with username \"([^\"]*)\" and password \"([^\"]*)\" posts an incident$") public void the_sensor_with_username_and_password_posts_an_incident(String username, String password) throws Exception { String payload = String.format("{\"agent\": {\"username\": \"%s\", \"password\": \"%s\", " + "\"kind\": \"Sensor\"}, \"inciName\": \"Test\", \"location\": {\"lat\": 50.2, " + "\"lon\": 12.2}, \"tags\": [], \"moreInfo\": [], \"properties\": {}}", username, password); MockHttpServletRequestBuilder request = post("/incident/create") .contentType(MediaType.APPLICATION_JSON).content(payload.getBytes()); result = mockMvc.perform(request).andReturn().getResponse(); } @Then("^the agent receives status code of (\\d+)$") public void the_agent_receives_status_code_of(int status) { assertThat(result.getStatus(), is(status)); } @Then("^the agent receives the string \"([^\"]*)\"$") public void the_agent_receives_the_string(String message) throws UnsupportedEncodingException { assertTrue(message.equals(result.getContentAsString())); } @Then("^the incident is stored$") public void the_incident_is_stored() { System.err.println(incidents.size()); assertTrue(incidents.size() == 1); } @Then("^an operator is assigned to the incident") public void an_operator_is_assigned_to_the_incident() { Incident incident = incidents.get(0); assertTrue(incident.getProperties().containsKey("operator")); } }
tuckerconnelly/carbon-ui
lib/components/buttons/RaisedButton.js
Object.defineProperty(exports,"__esModule",{value:true});var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};var _react=require('react');var _react2=_interopRequireDefault(_react); var _propTypes=require('prop-types');var _propTypes2=_interopRequireDefault(_propTypes); var _uranium=require('uranium');var _uranium2=_interopRequireDefault(_uranium); var _color=require('color');var _color2=_interopRequireDefault(_color); var _index=require('../../index');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _objectWithoutProperties(obj,keys){var target={};for(var i in obj){if(keys.indexOf(i)>=0)continue;if(!Object.prototype.hasOwnProperty.call(obj,i))continue;target[i]=obj[i];}return target;} var RaisedButton=function RaisedButton(_ref) {var disabled=_ref.disabled,children=_ref.children,textStyle=_ref.textStyle,theme=_ref.theme,other=_objectWithoutProperties(_ref,['disabled','children','textStyle','theme']); var styles=tStyles(theme); var formattedChildren=typeof children==='string'? _react2.default.createElement(_index.Body2,{ style:[ styles.text, disabled&&styles.disabledText, textStyle]}, children.toUpperCase()): children; return( _react2.default.createElement(_index.TouchableRipple,_extends({ hitSlop:{top:6,right:6,bottom:6,left:6}, css:[styles.base,disabled&&styles.disabled], rippleColor:_index.Colors.white, disabled:disabled}, other), formattedChildren)); }; RaisedButton.propTypes={ disabled:_propTypes2.default.bool, children:_propTypes2.default.node, textStyle:_propTypes2.default.oneOfType([_propTypes2.default.object,_propTypes2.default.array]), theme:_propTypes2.default.object.isRequired}; var tStyles=function tStyles(theme){return{ base:_extends({ height:36, minWidth:88, paddingHorizontal:16, borderRadius:2, marginHorizontal:8, alignItems:'center', justifyContent:'center', backgroundColor:theme.colors.primary}, _index.Elevation.dp2,_defineProperty({}, _index.Breakpoints.ml,_extends({ height:32}, _index.Elevation.none))), text:{ color:_index.Colors.whitePrimary, lineHeight:16, textAlign:'center'}, pressed:_extends({}, _index.Elevation.dp4), disabled:{ backgroundColor:theme.colors.button.raised.disabled}, disabledText:{ color:theme.colors.button.raised.disabledText}, focused:{ backgroundColor:(0,_color2.default)(theme.colors.primary).darken(0.12).hexString()}, hovered:_extends({}, _index.Elevation.dp2)};};exports.default= (0,_index.connectTheme)( (0,_uranium2.default)( RaisedButton));
liuguangw/billing
server/models/register_result.h
<reponame>liuguangw/billing<gh_stars>10-100 // // Created by liuguang on 2021/12/24. // #ifndef BILLING_REGISTER_RESULT_H #define BILLING_REGISTER_RESULT_H #include <string> namespace models { struct RegisterResult { bool hasError; std::string message; }; } #endif //BILLING_REGISTER_RESULT_H
yedhrab/LolRehberi
Externals/Lol Game Analysis/src/views/app.js
<gh_stars>0 import React from 'react' import { Link } from 'react-router' import Helmet from 'react-helmet' function App ({ children }) { return ( <div className='app-view'> <Helmet titleTemplate='%s - League Interactive Timeline' defaultTitle='League Interactive Timeline' link={[ {rel: 'dns-prefetch', href: 'https://timeline-cdn.bruggie.com/'}, {rel: 'dns-prefetch', href: 'https://ddragon.leagueoflegends.com/'}, {rel: 'dns-prefetch', href: 'https://lol-mh-proxy.now.sh/'} ]} script={[ {src: '//use.fontawesome.com/748eca0962.js', async: true} ]} /> <div className='about'> <p> Created by <strong><a href='https://twitter.com/zachbruggeman' target='_blank'>@zachbruggeman</a></strong> | <Link to='/' href='/'>About</Link> | <a href='https://github.com/remixz/lol-game-analysis' target='_blank'>View on GitHub</a> </p> </div> {children} <p className='fineprint'> League Interactive Timeline isn’t endorsed by Riot Games and doesn’t reflect the views or opinions of Riot Games or anyone officially involved in producing or managing League of Legends. League of Legends and Riot Games are trademarks or registered trademarks of Riot Games, Inc. League of Legends &copy; Riot Games, Inc. </p> </div> ) } export default App
rohankumardubey/summa
Core/src/main/java/dk/statsbiblioteket/summa/common/lucene/analysis/LowerCasingReader.java
<reponame>rohankumardubey/summa /* * 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 dk.statsbiblioteket.summa.common.lucene.analysis; import dk.statsbiblioteket.util.reader.CircularCharBuffer; import dk.statsbiblioteket.util.reader.ReplaceReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; /** * */ public class LowerCasingReader extends ReplaceReader { /** * Creates a new filtered reader. * * @param in a Reader object providing the underlying stream. * * @throws NullPointerException if <code>in</code> is <code>null</code> */ protected LowerCasingReader(Reader in) { super(in); } @Override public int read() throws IOException { int codePoint = in.read(); if (codePoint == -1) { return -1; } return Character.toLowerCase(codePoint); } @Override public int read(char[] buf, int offset, int count) throws IOException { int numRead = in.read(buf, offset, count); for (int i = offset+numRead; i >= offset; i--) { buf[i] = Character.toLowerCase(buf[i]); } return numRead; } @Override public int read(CircularCharBuffer cbuf, int length) throws IOException { int codePoint; int count = 0; while ((codePoint = in.read()) != -1) { cbuf.put((char)Character.toLowerCase(codePoint)); count++; } if (count == 0) { return -1; } return count; } @Override public String transform(String s) { return s.toLowerCase(); } @Override public char[] transformToChars(char c) { return new char[]{Character.toLowerCase(c)}; } @Override public char[] transformToChars(char[] chars) { char[] result = new char[chars.length]; for (int i = 0; i < chars.length; i++) { result[i] = Character.toLowerCase(chars[i]); } return result; } @Override public char[] transformToCharsAllowInplace(char[] chars) { for (int i = 0; i < chars.length; i++) { chars[i] = Character.toLowerCase(chars[i]); } return chars; } /** * Prepare the reader for lower casing the character stream from another * reader. * * @param in the new reader to read character data from * @return always returns {@code this} */ @Override public LowerCasingReader setSource(Reader in) { this.in = in; return this; } @Override @SuppressWarnings({"CloneDoesntCallSuperClone", "CloneDoesntDeclareCloneNotSupportedException"}) public LowerCasingReader clone() { return new LowerCasingReader(new StringReader("")); } }
krantivijay/KP_31stMarch_WebApi
app/src/main/java/com/kencloud/partner/user/FilePicker.java
package com.kencloud.partner.user; /** * Created by suchismita.p on 11/19/2016. */ import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class FilePicker extends ListActivity { public final static String EXTRA_FILE_PATH = "file_path"; public final static String EXTRA_SHOW_HIDDEN_FILES = "show_hidden_files"; public final static String EXTRA_ACCEPTED_FILE_EXTENSIONS = "accepted_file_extensions"; private final static String DEFAULT_INITIAL_DIRECTORY = "/"; protected File Directory; protected ArrayList<File> Files; protected FilePickerListAdapter Adapter; protected boolean ShowHiddenFiles = false; protected String[] acceptedFileExtensions; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View emptyView = inflator.inflate(R.layout.empty_view, null); ((ViewGroup) getListView().getParent()).addView(emptyView); getListView().setEmptyView(emptyView); // Set initial directory Directory = new File(DEFAULT_INITIAL_DIRECTORY); // Initialize the ArrayList Files = new ArrayList<File>(); // Set the ListAdapter Adapter = new FilePickerListAdapter(this, Files); setListAdapter(Adapter); // Initialize the extensions array to allow any file extensions acceptedFileExtensions = new String[] {}; // Get intent extras if(getIntent().hasExtra(EXTRA_FILE_PATH)) Directory = new File(getIntent().getStringExtra(EXTRA_FILE_PATH)); if(getIntent().hasExtra(EXTRA_SHOW_HIDDEN_FILES)) ShowHiddenFiles = getIntent().getBooleanExtra(EXTRA_SHOW_HIDDEN_FILES, false); if(getIntent().hasExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS)) { ArrayList<String> collection = getIntent().getStringArrayListExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS); acceptedFileExtensions = (String[]) collection.toArray(new String[collection.size()]); } } @Override protected void onResume() { refreshFilesList(); super.onResume(); } protected void refreshFilesList() { Files.clear(); ExtensionFilenameFilter filter = new ExtensionFilenameFilter(acceptedFileExtensions); File[] files = Directory.listFiles(filter); if(files != null && files.length > 0) { for(File f : files) { if(f.isHidden() && !ShowHiddenFiles) { continue; } Files.add(f); } Collections.sort(Files, new FileComparator()); } Adapter.notifyDataSetChanged(); } @Override public void onBackPressed() { if(Directory.getParentFile() != null) { Directory = Directory.getParentFile(); refreshFilesList(); return; } super.onBackPressed(); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { File newFile = (File)l.getItemAtPosition(position); if(newFile.isFile()) { Intent extra = new Intent(); extra.putExtra(EXTRA_FILE_PATH, newFile.getAbsolutePath()); setResult(RESULT_OK, extra); finish(); } else { Directory = newFile; refreshFilesList(); } super.onListItemClick(l, v, position, id); } private class FilePickerListAdapter extends ArrayAdapter<File> { private List<File> mObjects; public FilePickerListAdapter(Context context, List<File> objects) { super(context, R.layout.list_item, android.R.id.text1, objects); mObjects = objects; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = null; if(convertView == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.list_item, parent, false); } else row = convertView; File object = mObjects.get(position); ImageView imageView = (ImageView)row.findViewById(R.id.file_picker_image); TextView textView = (TextView)row.findViewById(R.id.file_picker_text); textView.setSingleLine(true); textView.setText(object.getName()); if(object.isFile()) imageView.setImageResource(R.mipmap.ic_launcher); else imageView.setImageResource(R.mipmap.ic_launcher); return row; } } private class FileComparator implements Comparator<File> { public int compare(File f1, File f2) { if(f1 == f2) return 0; if(f1.isDirectory() && f2.isFile()) // Show directories above files return -1; if(f1.isFile() && f2.isDirectory()) // Show files below directories return 1; // Sort the directories alphabetically return f1.getName().compareToIgnoreCase(f2.getName()); } } private class ExtensionFilenameFilter implements FilenameFilter { private String[] Extensions; public ExtensionFilenameFilter(String[] extensions) { super(); Extensions = extensions; } public boolean accept(File dir, String filename) { if(new File(dir, filename).isDirectory()) { // Accept all directory names return true; } if(Extensions != null && Extensions.length > 0) { for(int i = 0; i < Extensions.length; i++) { if(filename.endsWith(Extensions[i])) { // The filename ends with the extension return true; } } // The filename did not match any of the extensions return false; } // No extensions has been set. Accept all file extensions. return true; } } }
oralvi/rinyuuki
rin/modules/twitter/stream/track.py
<filename>rin/modules/twitter/stream/track.py<gh_stars>0 # 订阅关键词 import re import peony from peony import PeonyClient from rin import Service from rin.config import twitter as cfg from .util import format_tweet sv = Service('uma-ura9-sniffer', enable_on_default=False, help_='嗅探新鲜出炉的9URA种马', bundle='umamusume') async def track_stream(): client = PeonyClient( consumer_key=cfg.consumer_key, consumer_secret=cfg.consumer_secret, access_token=cfg.access_token_key, access_token_secret=cfg.access_token_secret, proxy=cfg.proxy, ) async with client: stream = client.stream.statuses.filter.post(track=['URA9']) async for tweet in stream: sv.logger.info("Got twitter event.") if peony.events.tweet(tweet): screen_name = tweet.user.screen_name if screen_name in cfg.uma_ura9_black_list: continue # black list if peony.events.retweet(tweet): continue # 忽略纯转推 if tweet.get("quoted_status"): continue # 忽略引用转推 if tweet.get("in_reply_to_screen_name"): continue # 忽略评论 if not re.search(r'\d{9}', tweet.text): continue # 忽略无id的推特 if re.search(r'ura(シナリオ)?([::])?[0-7]', tweet.text, re.I): continue # 忽略低ura因子 if re.search(r'目指|狙|チャレンジ', tweet.text, re.I): continue # 忽略未达成 if re.search(r'青(因子)?[0-8]', tweet.text, re.I): continue # 忽略低星蓝 if re.search(r'(スピ(ード)?|スタ(ミナ)?|パワー|根性?|賢さ?)\s*[0124578]', tweet.text, re.I): continue # 忽略低星蓝 if re.search(r'ura(シナリオ)?([::])?9(では|じゃ)', tweet.text, re.I): continue # 忽略否定型 if re.search(r'青(因子)?9(では|じゃ)', tweet.text, re.I): continue # 忽略否定型 msg = format_tweet(tweet) sv.logger.info(f"推送推文:\n{msg}") await sv.broadcast(msg, f" @{screen_name} 推文", 0.2) else: sv.logger.debug("Ignore non-tweet event.")
wangsikai/learn
yoo-master-dc2492330d5d46b48f1ceca891e0f9f7e1593fee/module/common/uxb-service/src/main/java/com/lanking/uxb/service/mall/api/impl/MemberPackageOrderSettlementServiceImpl.java
<filename>yoo-master-dc2492330d5d46b48f1ceca891e0f9f7e1593fee/module/common/uxb-service/src/main/java/com/lanking/uxb/service/mall/api/impl/MemberPackageOrderSettlementServiceImpl.java package com.lanking.uxb.service.mall.api.impl; import java.math.BigDecimal; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.lanking.cloud.component.db.support.hibernate.Repo; import com.lanking.cloud.domain.frame.config.Parameter; import com.lanking.cloud.domain.frame.system.Product; import com.lanking.cloud.domain.yoo.channel.UserChannel; import com.lanking.cloud.domain.yoo.member.MemberPackage; import com.lanking.cloud.domain.yoo.member.MemberPackageGroup; import com.lanking.cloud.domain.yoo.member.MemberType; import com.lanking.cloud.domain.yoo.order.PayMode; import com.lanking.cloud.domain.yoo.order.member.MemberPackageOrder; import com.lanking.cloud.domain.yoo.order.member.MemberPackageOrderSettlement; import com.lanking.cloud.domain.yoo.order.member.MemberPackageOrderSource; import com.lanking.cloud.domain.yoo.order.member.MemberPackageOrderStatus; import com.lanking.cloud.domain.yoo.order.member.MemberPackageOrderType; import com.lanking.cloud.domain.yoo.user.User; import com.lanking.cloud.domain.yoo.user.UserType; import com.lanking.cloud.sdk.data.Params; import com.lanking.uxb.service.code.api.ParameterService; import com.lanking.uxb.service.mall.api.MemberPackageOrderRefundService; import com.lanking.uxb.service.mall.api.MemberPackageOrderSettlementService; import com.lanking.uxb.service.user.api.UserService; /** * 会员套餐订单结算表接口实现. * * @author <a href="mailto:<EMAIL>">wanlong.che</a> * * @version 2017年2月27日 */ @Service @Transactional(readOnly = true) public class MemberPackageOrderSettlementServiceImpl implements MemberPackageOrderSettlementService { @Autowired @Qualifier("MemberPackageOrderSettlementRepo") private Repo<MemberPackageOrderSettlement, Long> repo; @Autowired @Qualifier("MemberPackageRepo") private Repo<MemberPackage, Long> memberPackageRepo; @Autowired @Qualifier("MemberPackageGroupRepo") private Repo<MemberPackageGroup, Long> memberPackageGroupRepo; @Autowired @Qualifier("userService") private UserService userService; @Autowired private MemberPackageOrderRefundService memberPackageOrderRefundService; @Autowired private ParameterService parameterService; private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5); @Override public MemberPackageOrderSettlement findByOrder(long orderId) { List<MemberPackageOrderSettlement> list = repo.find("findByOrder", Params.param("orderId", orderId)).list(); if (list.size() > 0) { return list.get(0); } return null; } @Override @Transactional public void createByOrder(MemberPackageOrder order, int memberCount) { if (order.getStatus() != MemberPackageOrderStatus.COMPLETE || order.getSource() != MemberPackageOrderSource.CHANNEL || (order.getPayMod() != null && order.getPayMod() != PayMode.ONLINE) || order.getUserChannelCode() == UserChannel.YOOMATH || order.getMemberType() == MemberType.SCHOOL_VIP) { // 只统计渠道相关的已完成订单,只统计线上支付或者后台开通的订单,只统计普通会员订单 // 套餐组不得为空 return; } MemberPackageOrderSettlement entity = this.findByOrder(order.getId()); if (entity != null) { // 已经存在该订单统计 return; } if (order.getType() == MemberPackageOrderType.USER) { User user = userService.get(order.getUserId()); if (user.getUserType() != UserType.STUDENT) { // 只统计学生订单 return; } } // 套餐 MemberPackage memberPackage = memberPackageRepo.get(order.getMemberPackageId()); Long memberPackageGroupId = order.getMemberPackageGroupId(); if (memberPackageGroupId == null && memberPackage != null) { memberPackageGroupId = memberPackage.getMemberPackageGroupId(); } if (memberPackageGroupId == null) { return; } // 套餐组 MemberPackageGroup memberPackageGroup = memberPackageGroupRepo.get(memberPackageGroupId); final int userChannelCode = order.getUserChannelCode(); // 套餐组ID int yearCount = memberPackage.getMonth() / 12; // 套餐的年份数 BigDecimal profits1 = memberPackageGroup.getProfits1(); // 公司利润1 BigDecimal profits2 = memberPackageGroup.getProfits2(); // 公司利润2 Parameter parameter = parameterService.get(Product.YOOMATH, "memberPackage.settlement"); // 结算返还截止人数 final int divideNum = parameter == null ? 699 : Integer.parseInt(parameter.getValue()); // 固定阀值 int thisCountPoint = memberCount * yearCount; // 本次订单的阀值数 entity = new MemberPackageOrderSettlement(); entity.setOrderId(order.getId()); entity.setOrderCode(order.getCode()); entity.setUserChannelCode(userChannelCode); entity.setType(order.getType()); entity.setTransactionAmount(order.getTotalPrice()); entity.setMemberCount(memberCount); entity.setProfits(profits2.multiply(new BigDecimal(thisCountPoint))); // 当前订单的公司利润 entity.setProfitsGap(new BigDecimal(0)); entity.setYearCount(yearCount); entity.setMemberPackageGroupId(memberPackageGroupId); // 获得已开通阀值数、是否已经做过利润返还 final Date date = new Date(); Map<String, Integer> countMap = this.countMember(userChannelCode); int countPoint = countMap.get("countPoint"); // 已产生的阀值数 if (countMap.get("refund") == 0) { // 没有做过利润返还 if (countPoint + thisCountPoint >= divideNum) { // 需要做利润返还 fixedThreadPool.execute(new Runnable() { @Override public void run() { memberPackageOrderRefundService.refund(divideNum, userChannelCode); } }); if (countPoint <= divideNum) { int c1 = divideNum - countPoint; // 按原始利润计算的部分 int c2 = thisCountPoint - c1; // 按新利润计算的部分 entity.setProfits(new BigDecimal((c1 * profits1.doubleValue()) + (c2 * profits2.doubleValue()))); if (countPoint < divideNum) { entity.setProfitsGap(new BigDecimal(c1).multiply(profits1.subtract(profits2))); // 返还利润 entity.setProfitsGapAt(date); } } } else { entity.setProfits(profits1.multiply(new BigDecimal(thisCountPoint))); // 当前订单的公司利润 } } else { if (countPoint + thisCountPoint > divideNum) { if (countPoint <= divideNum) { int c1 = divideNum - countPoint; // 按原始利润计算的部分 int c2 = thisCountPoint - c1; // 按新利润计算的部分 entity.setProfits(new BigDecimal((c1 * profits1.doubleValue()) + (c2 * profits2.doubleValue()))); } } else { entity.setProfits(profits1.multiply(new BigDecimal(thisCountPoint))); } } entity.setChannelProfits(order.getTotalPrice().subtract(entity.getProfits())); // 销售渠道利润 Calendar cal = Calendar.getInstance(); cal.setTime(order.getOrderAt()); entity.setSettlementYear(cal.get(Calendar.YEAR)); entity.setSettlementMonth(cal.get(Calendar.MONTH) + 1); entity.setCreateAt(date); repo.save(entity); } /** * 获得已产生的渠道阀值及是否已经做了返润. * * @param userChannelCode * 渠道 * @return */ @SuppressWarnings("rawtypes") private Map<String, Integer> countMember(int userChannelCode) { List<Map> list = repo.find("$countMember", Params.param("userChannelCode", userChannelCode)).list(Map.class); Map<String, Integer> map = new HashMap<String, Integer>(2); int countPoint = 0; int refund = 0; if (list.size() > 0) { Map objMap = list.get(0); if (objMap.get("mc") != null) { countPoint = Integer.parseInt(objMap.get("mc").toString()); } if (objMap.get("pg") != null) { double pg = Double.parseDouble(objMap.get("pg").toString()); if (pg > 0) { refund = 1; } } } map.put("countPoint", countPoint); // 已产生的阀值 map.put("refund", refund); // 是否已做了返润 return map; } }
Rythe-Interactive/Legion-Engine.rythe-legacy
legion/engine/core/math/glm/ext/scalar_uint_sized.hpp
/// @ref ext_scalar_uint_sized /// @file glm/ext/scalar_uint_sized.hpp /// /// @defgroup ext_scalar_uint_sized GLM_EXT_scalar_uint_sized /// @ingroup ext /// /// Exposes sized unsigned integer scalar types. /// /// Include <glm/ext/scalar_uint_sized.hpp> to use the features of this extension. /// /// @see ext_scalar_int_sized #pragma once #include "../detail/setup.hpp" #if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED) # pragma message("GLM: GLM_EXT_scalar_uint_sized extension included") #endif namespace legion::core::math{ namespace detail { # if GLM_HAS_EXTENDED_INTEGER_TYPE typedef std::uint8_t uint8; typedef std::uint16_t uint16; typedef std::uint32_t uint32; # else typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; #endif template<> struct is_int<uint8> { enum test {value = ~0}; }; template<> struct is_int<uint16> { enum test {value = ~0}; }; template<> struct is_int<uint64> { enum test {value = ~0}; }; }//namespace detail /// @addtogroup ext_scalar_uint_sized /// @{ /// 8 bit unsigned integer type. typedef detail::uint8 uint8; /// 16 bit unsigned integer type. typedef detail::uint16 uint16; /// 32 bit unsigned integer type. typedef detail::uint32 uint32; /// 64 bit unsigned integer type. typedef detail::uint64 uint64; /// @} }//namespace legion::core::math
exponentjs/rocker
src/build/urlfetcher.go
<gh_stars>1000+ /*- * Copyright 2015 Grammarly, 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 build import ( "crypto/sha256" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" "path/filepath" log "github.com/Sirupsen/logrus" ) // URLFetcher is an interface to fetch urls from internets type URLFetcher interface { Get(url string) (*URLInfo, error) GetInfo(url string) (*URLInfo, error) } // URLFetcherFS is an URLFetcher backed by FS cache type URLFetcherFS struct { cacheDir string client *http.Client noCache bool } // URLInfo is a metadata representing stored or to-be-stored url type URLInfo struct { ID string URL string FileName string `json:"-"` BaseName string HasEtag bool Etag string Size int64 Fetcher *URLFetcherFS `json:"-"` } // NewURLFetcherFS returns an instance of URLFetcherFS, initialized to // live in <base>/url_fetcher_cache func NewURLFetcherFS(base string, noCache bool, httpClient *http.Client) (cache *URLFetcherFS) { cacheDir := filepath.Join(base, "url_fetcher_cache") if httpClient == nil { httpClient = http.DefaultClient } return &URLFetcherFS{ cacheDir: cacheDir, client: httpClient, noCache: noCache, } } // GetInfo retrieves stored URLInfo data func (uf *URLFetcherFS) GetInfo(url0 string) (info *URLInfo, err error) { info, ok, err := uf.getURLInfo(url0) if err != nil { return nil, err } if !ok { return nil, fmt.Errorf("no url found in cache: `%s`", url0) } return info, nil } // Get downloads url, stores file and metadata in cache func (uf *URLFetcherFS) Get(url0 string) (info *URLInfo, err error) { info, ok, err := uf.getURLInfo(url0) if err != nil { return nil, err } if !uf.noCache && ok { log.Debugf("Validating %s [%s]", info.URL, info.FileName) if info.isEtagValid() { log.Debugf("%s valid!", info.URL) return info, nil } } if err = info.download(); err != nil { return nil, err } return info, nil } func (uf *URLFetcherFS) getURLInfo(url0 string) (info *URLInfo, ok bool, err error) { info, err = uf.makeURLInfo(url0) if err != nil { return nil, false, err } ok, err = info.load() if err != nil { return nil, false, err } return info, ok, nil } func (uf *URLFetcherFS) makeURLInfo(u string) (info *URLInfo, err error) { if !isURL(u) { return nil, fmt.Errorf("expecting http:// or https:// url, got `%s` instead", u) } u1, err := url.Parse(u) if err != nil { return nil, err } baseName := filepath.Base(u1.Path) if baseName == "" { return nil, fmt.Errorf("unable to determine filename from url: %s", u) } h := sha256.Sum256([]byte(u)) id := fmt.Sprintf("%x", h) info = &URLInfo{ ID: id, URL: u, BaseName: baseName, Fetcher: uf, } info.FileName = info.getBlobFileName() return info, nil } func (uf *URLFetcherFS) makeID(u string) (id string) { h := sha256.Sum256([]byte(u)) id = fmt.Sprintf("%x", h) return id } func isURL(u string) bool { return (7 <= len(u) && u[:7] == "http://") || (8 <= len(u) && u[:8] == "https://") } func (info *URLInfo) getBlobFileName() (fileName string) { return filepath.Join(info.Fetcher.cacheDir, info.ID[:2], info.ID) } func (info *URLInfo) getInfoFileName() (fileName string) { return info.getBlobFileName() + ".json" } func (info *URLInfo) isEtagValid() bool { if !info.HasEtag { return false } httpClient := info.Fetcher.client response, err := httpClient.Head(info.URL) if err != nil { return false } defer response.Body.Close() if response.StatusCode < 200 || 300 <= response.StatusCode { return false } if response.Header.Get("Etag") == info.Etag { return true } return false } func (info *URLInfo) download() (err error) { log.Infof("Downloading `%s` into `%s`", info.URL, info.FileName) httpClient := info.Fetcher.client response, err := httpClient.Get(info.URL) if err != nil { return err } defer response.Body.Close() if response.StatusCode < 200 || 300 <= response.StatusCode { return fmt.Errorf("Got non-2xx status for `%s`: %s", info.URL, response.Status) } if err = os.MkdirAll(filepath.Dir(info.FileName), 0755); err != nil { return err } f, err := os.Create(info.FileName) if err != nil { return err } defer f.Close() n, err := io.Copy(f, response.Body) if err != nil { return err } info.Size = n if etag := response.Header.Get("Etag"); etag != "" { info.HasEtag = true info.Etag = etag } else { info.HasEtag = false info.Etag = "" } if err = info.store(); err != nil { return err } return nil } func (info *URLInfo) load() (ok bool, err error) { fileName := info.getInfoFileName() data, err := ioutil.ReadFile(fileName) if err != nil { if os.IsNotExist(err) { return false, nil } return false, fmt.Errorf("Failed to read urlinfo file %s content, error: %s", fileName, err) } if err = json.Unmarshal(data, info); err != nil { return false, fmt.Errorf("Failed to parse urlinfo file %s json, error: %s", fileName, err) } return true, nil } func (info *URLInfo) store() (err error) { fileName := info.getInfoFileName() if err := os.MkdirAll(filepath.Dir(fileName), 0755); err != nil { return err } data, err := json.Marshal(info) if err != nil { return err } return ioutil.WriteFile(fileName, data, 0644) } func (info *URLInfo) dump() (data string, err error) { data0, err := json.Marshal(info) return string(data0), err }
HumanBrainProject/kg-query-api
src/main/java/org/humanbrainproject/knowledgegraph/structure/api/StructureAPI.java
<reponame>HumanBrainProject/kg-query-api<filename>src/main/java/org/humanbrainproject/knowledgegraph/structure/api/StructureAPI.java<gh_stars>1-10 /* * Copyright 2018 - 2021 Swiss Federal Institute of Technology Lausanne (EPFL) * * 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. * * This open source software code was developed in part or in whole in the * Human Brain Project, funded from the European Union's Horizon 2020 * Framework Programme for Research and Innovation under * Specific Grant Agreements No. 720270, No. 785907, and No. 945539 * (Human Brain Project SGA1, SGA2 and SGA3). * */ package org.humanbrainproject.knowledgegraph.structure.api; import io.swagger.annotations.ApiOperation; import org.humanbrainproject.knowledgegraph.annotations.ToBeTested; import org.humanbrainproject.knowledgegraph.commons.authorization.control.AuthorizationContext; import org.humanbrainproject.knowledgegraph.indexing.entity.nexus.NexusSchemaReference; import org.humanbrainproject.knowledgegraph.query.entity.JsonDocument; import org.humanbrainproject.knowledgegraph.structure.boundary.Structure; import org.humanbrainproject.knowledgegraph.structure.exceptions.AsynchronousStartupDelay; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.ws.rs.core.MediaType; import java.util.List; import static org.humanbrainproject.knowledgegraph.commons.api.ParameterConstants.*; @RestController @RequestMapping(value = "/api/structure", produces = MediaType.APPLICATION_JSON) @ToBeTested(easy = true) public class StructureAPI { @Autowired AuthorizationContext authorizationContext; @Autowired Structure structure; @GetMapping() public ResponseEntity<JsonDocument> getStructure(@RequestParam(value = "withLinks", required = false, defaultValue = "false") boolean withLinks) { authorizationContext.setMasterCredential(); try { return ResponseEntity.ok(structure.getCachedStructure(withLinks)); } catch (AsynchronousStartupDelay e) { JsonDocument error = new JsonDocument(); error.put("cause", "There is currently a cache population in progress. As soon as this one is finished, the service is available for you."); return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(error); } } @ApiOperation(value = "Refreshes the cache of the structure request. Please note, that additionally, the cache is flushed every 24h.") @PutMapping("/cache") public ResponseEntity<JsonDocument> structureCacheRefresh(@RequestParam(value = "withLinks", required = false, defaultValue = "false") boolean withLinks) { try { return ResponseEntity.ok(structure.refreshStructureCache(withLinks)); } catch (AsynchronousStartupDelay e) { JsonDocument error = new JsonDocument(); error.put("cause", "There is currently a cache population in progress. As soon as this one is finished, the service is available for you."); return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(error); } } @GetMapping(value = "/{" + ORG + "}/{" + DOMAIN + "}/{" + SCHEMA + "}/{" + VERSION + "}") public JsonDocument getStructureForSchema(@PathVariable(ORG) String org, @PathVariable(DOMAIN) String domain, @PathVariable(SCHEMA) String schema, @PathVariable(VERSION) String version, @RequestParam(value = "withLinks", required = false, defaultValue = "false") boolean withLinks, @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization) { authorizationContext.populateAuthorizationContext(authorization); return structure.getStructureForSchema(new NexusSchemaReference(org, domain, schema, version), withLinks); } @GetMapping("/{" + ORG + "}/{" + DOMAIN + "}/{" + SCHEMA + "}/{" + VERSION + "}/bySpec") public void getStructureBySpecification(@PathVariable(ORG) String org, @PathVariable(DOMAIN) String domain, @PathVariable(SCHEMA) String schema, @PathVariable(VERSION) String version, @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization) { authorizationContext.populateAuthorizationContext(authorization); structure.reflectOnSpecifications(new NexusSchemaReference(org, domain, schema, version)); } @GetMapping("/arango/edgeCollections") public List<String> getArangoEdgeCollections() { return structure.getArangoEdgeCollections(); } }
baracudda/androidBits
lib_androidBits/src/main/java/com/blackmoonit/androidbits/io/SimpleGestureHandler.java
<filename>lib_androidBits/src/main/java/com/blackmoonit/androidbits/io/SimpleGestureHandler.java package com.blackmoonit.androidbits.io; /* * Copyright (C) 2013 Blackmoon Info Tech Services * * 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. */ import android.content.Context; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import com.blackmoonit.androidbits.utils.BitsGraphicsUtils; /** * Simple swipe & scroll handler containing a detector with listener. * * Example usage in an Activity: * * SimpleGestureHandler sgHandler = new SimpleGestureHandler(this, new OnSimpleGesture() { // add all required override interface methods here }); * */ public class SimpleGestureHandler implements OnTouchListener { public interface OnSimpleGesture { /** * Handle the OnSwipe event. * * @param aMotionEvent - beginning of swipe. * @param aDirection - vector of the swipe, aDirection>0 is a swipe to the right. * @return Return true if you wish to stop further processing of the touch event. */ public boolean onSwipe(MotionEvent aMotionEvent, float aDirection); /** * Handle the OnScroll event. * * @param aMotionEvent - beginning of scroll. * @param aDirection - vector of the scroll, aDirection>0 is a scroll up. * @return Return true if you wish to stop further processing of the touch event. */ public boolean onScroll(MotionEvent aMotionEvent, float aDirection); /** * Handle Mouse Buttons in event. * * @param aMotionEvent - a button event occured. * @param aButtonState - the current button state that prompted this event. * @return Return true if you wish to stop further processing of the mouse event. */ public boolean onMouseButton(MotionEvent aMotionEvent, int aButtonState); /** * Handle Long Press in event. * * @param aMotionEvent - a long press event occured. * @return Return true if you wish to stop further processing of the mouse event. */ public boolean onLongPress(MotionEvent aMotionEvent); } /** * Gesture listener that recognizes horizontal swipes and vertical scrolls. */ public class SimpleGestureListener extends SimpleOnGestureListener { private int mSwipeMinDistanceRequired = 150; private int mSwipeMaxRiseAllowed = 100; private int mSwipeThresholdVelocity = 80; private int mScrollMinDistanceRequired = 80; private int mScrollMaxRunAllowed = 20; private int mScrollThresholdVelocity = 40; protected OnSimpleGesture mGestureHandler = null; protected boolean bOnGestureResult = false; protected MotionEvent mLastOnDownEvent = null; public SimpleGestureListener(Context aContext, OnSimpleGesture aGestureHandler) { // commented out due to removal of Blackmoon imports mSwipeMinDistanceRequired = BitsGraphicsUtils.dipsToPixels(aContext,mSwipeMinDistanceRequired); mSwipeMaxRiseAllowed = BitsGraphicsUtils.dipsToPixels(aContext,mSwipeMaxRiseAllowed); mScrollMinDistanceRequired = BitsGraphicsUtils.dipsToPixels(aContext,mScrollMinDistanceRequired); mScrollMaxRunAllowed = BitsGraphicsUtils.dipsToPixels(aContext,mScrollMaxRunAllowed); if (aGestureHandler!=null) mGestureHandler = aGestureHandler; else throw new IllegalArgumentException("aGestureHandler cannot be null."); } @Override public boolean onDown(MotionEvent e) { mLastOnDownEvent = e; //Android 4.0 bug means e1 in onFling may be NULL due to onLongPress eating it. return super.onDown(e); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e1==null) e1 = mLastOnDownEvent; if (e1==null || e2==null) return false; float dX = e2.getX()-e1.getX(); float dY = e2.getY()-e1.getY(); if ( Math.abs(dY)<mSwipeMaxRiseAllowed && Math.abs(velocityX)>=mSwipeThresholdVelocity && Math.abs(dX)>=mSwipeMinDistanceRequired ) { bOnGestureResult = mGestureHandler.onSwipe(e1,dX); return true; } else if ( Math.abs(dX)<mScrollMaxRunAllowed && Math.abs(velocityY)>=mScrollThresholdVelocity && Math.abs(dY)>=mScrollMinDistanceRequired ) { bOnGestureResult = mGestureHandler.onScroll(e1,dY); return true; } return false; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { final int theButtonState = e.getButtonState(); if (theButtonState!=0 && mGestureHandler.onMouseButton(e,theButtonState)) { return true; } return super.onSingleTapConfirmed(e); } @Override public void onLongPress(MotionEvent e) { if (!mGestureHandler.onLongPress(e)) super.onLongPress(e); } } public static final int LIMIT_UNCHANGED = 0; protected final SimpleGestureListener mSimpleGestureListener; protected final GestureDetector mSimpleGestureDetector; public SimpleGestureHandler(Context aContext, OnSimpleGesture aGestureHandler) { mSimpleGestureListener = new SimpleGestureListener(aContext,aGestureHandler); mSimpleGestureDetector = new GestureDetector(aContext,mSimpleGestureListener); } /** * * @see android.view.View.OnTouchListener */ public boolean onTouch(View v, MotionEvent aEvent) { if (mSimpleGestureDetector.onTouchEvent(aEvent)) return mSimpleGestureListener.bOnGestureResult; else return false; } /** * * @return Returns the GestureDetector being used. */ public GestureDetector getGestureDetector() { return mSimpleGestureDetector; } public void setSwipeLimits(int aMinDistance, int aMaxRise, int aMinVelocity) { if (aMinDistance>LIMIT_UNCHANGED) mSimpleGestureListener.mSwipeMinDistanceRequired = aMinDistance; if (aMaxRise>LIMIT_UNCHANGED) mSimpleGestureListener.mSwipeMaxRiseAllowed = aMaxRise; if (aMinVelocity>LIMIT_UNCHANGED) mSimpleGestureListener.mSwipeThresholdVelocity = aMinVelocity; } public void setScrollLimits(int aMinDistance, int aMaxRun, int aMinVelocity) { if (aMinDistance>LIMIT_UNCHANGED) mSimpleGestureListener.mScrollMinDistanceRequired = aMinDistance; if (aMaxRun>LIMIT_UNCHANGED) mSimpleGestureListener.mScrollMaxRunAllowed = aMaxRun; if (aMinVelocity>LIMIT_UNCHANGED) mSimpleGestureListener.mScrollThresholdVelocity = aMinVelocity; } }
tkoyama010/pyvista-doc-translations
locale/pot/api/core/_autosummary/pyvista-ExplicitStructuredGrid-copy_attributes-1.py
import pyvista as pv source = pv.UniformGrid((10, 10, 5)) source = source.compute_cell_sizes() target = pv.UniformGrid((10, 10, 5)) target.copy_attributes(source) target.plot(scalars='Volume', show_edges=True)
zealoussnow/chromium
third_party/blink/renderer/core/layout/layout_theme_mac.h
/* * This file is part of the theme implementation for form controls in WebCore. * * Copyright (C) 2005 Apple Computer, Inc. * Copyright (C) 2008, 2009 Google, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_THEME_MAC_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_THEME_MAC_H_ #import "third_party/blink/renderer/core/layout/layout_theme.h" #import "third_party/blink/renderer/core/layout/layout_theme_default.h" namespace blink { class File; class LayoutThemeMac final : public LayoutThemeDefault { public: static scoped_refptr<LayoutTheme> Create() { return base::AdoptRef(new LayoutThemeMac()); } Color PlatformActiveSelectionBackgroundColor( mojom::blink::ColorScheme color_scheme) const override; Color PlatformInactiveSelectionBackgroundColor( mojom::blink::ColorScheme color_scheme) const override; Color PlatformActiveSelectionForegroundColor( mojom::blink::ColorScheme color_scheme) const override; Color PlatformSpellingMarkerUnderlineColor() const override; Color PlatformGrammarMarkerUnderlineColor() const override; Color FocusRingColor(mojom::blink::ColorScheme color_scheme) const override; String DisplayNameForFile(const File& file) const override; bool PopsMenuByArrowKeys() const override { return true; } bool PopsMenuByReturnKey() const override { return false; } bool SupportsSelectionForegroundColors() const override { return false; } bool IsAccentColorCustomized( mojom::blink::ColorScheme color_scheme) const override; Color GetAccentColor(mojom::blink::ColorScheme color_scheme) const override; protected: // Controls color values returned from FocusRingColor(). bool UsesTestModeFocusRingColor() const; Color GetCustomFocusRingColor(mojom::blink::ColorScheme color_scheme) const; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_THEME_MAC_H_
nkruyer/SkillsWorkshop2018
Week01/Problem01/afilbrun_01.py
<reponame>nkruyer/SkillsWorkshop2018 # -*- coding: utf-8 -*- """ Created on Thu Jul 12 13:32:50 2018 @author: afilbrun """ # Problem 1. multiples = list(); for value in range(1000): if value % 3 == 0 or value % 5 == 0: multiples.append(value); print (sum(multiples));
ShowingCloud/Altarf
db/migrate/20190825063647_remove_translated_columns_to_refinery_pages.refinery_pages.rb
<filename>db/migrate/20190825063647_remove_translated_columns_to_refinery_pages.refinery_pages.rb # This migration comes from refinery_pages (originally 20170703015418) class RemoveTranslatedColumnsToRefineryPages < ActiveRecord::Migration[5.0] def change remove_column :refinery_pages, :custom_slug remove_column :refinery_pages, :slug end end
beachio/beach-api-core
spec/factories/beach_api_core_service_categories.rb
FactoryBot.define do factory :service_category, class: 'BeachApiCore::ServiceCategory' do name { Faker::Job.title } trait :with_services do after(:build) do |service_category| service_category.services << build_list(:service, 2, service_category: service_category) end end end end
Cadcorp/swagger-codegen
samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/AnimalApiService.java
<filename>samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/AnimalApiService.java package io.swagger.api; import io.swagger.api.*; import io.swagger.model.*; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import io.swagger.model.Animal; import java.util.Map; import java.util.List; import io.swagger.api.NotFoundException; import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; public abstract class AnimalApiService { public abstract Response addAnimal(Animal body,SecurityContext securityContext) throws NotFoundException; public abstract Response deleteAnimal(Long animalId,String apiKey,SecurityContext securityContext) throws NotFoundException; public abstract Response getAnimalById(Long animalId,SecurityContext securityContext) throws NotFoundException; public abstract Response updateAnimal(Animal body,SecurityContext securityContext) throws NotFoundException; public abstract Response updateAnimalWithForm(Long animalId,String name,String status,SecurityContext securityContext) throws NotFoundException; }
aipi2015/Laborator02
solutions/eclipse/02-BookStore-JPA/src/main/java/ro/pub/cs/aipi/lab02/businesslogic/InvoiceHeaderManager.java
package ro.pub.cs.aipi.lab02.businesslogic; import ro.pub.cs.aipi.lab02.entities.InvoiceHeader; public class InvoiceHeaderManager extends PersistentEntityManager<InvoiceHeader> { public InvoiceHeaderManager() { super(InvoiceHeader.class); } }
cwaffles/Soulcast-server
test/controllers/echo_controller_test.rb
<reponame>cwaffles/Soulcast-server<gh_stars>0 require 'test_helper' class EchoControllerTest < ActionDispatch::IntegrationTest test "should get reply" do get echo_reply_url assert_response :success end end
YuDe95/mcplayer
src/base/utils/TimeTick.h
#ifndef TIMETICK_H #define TIMETICK_H #include <QObject> static const qint64 TICK_INVALID = qint64(0); static const qint64 CLOCK_FREQ = qint64(1000); #define SEC_FROM_TICK(tick) ((tick) / CLOCK_FREQ) /** * @brief The TimeTick class * NOTE: qRegisterMetaType<TimeTick>() for QML */ class TimeTick { // Q_GADGET is a lighter version of the Q_OBJECT macro for classes that do not inherit from QObject // it can have Q_ENUM, Q_PROPERTY and Q_INVOKABLE // but it cannot have signals or slots Q_GADGET public: TimeTick() : m_ticks(TICK_INVALID) {} TimeTick(qint64 ticks) : m_ticks(ticks) {} TimeTick &operator=(const TimeTick &other) { m_ticks = other.m_ticks; return *this; } bool operator==(const TimeTick &other) const { return m_ticks == other.m_ticks; } bool operator!=(const TimeTick &other) const { return m_ticks != other.m_ticks; } operator qint64() { return m_ticks; } Q_INVOKABLE bool valid() const { return m_ticks != TICK_INVALID; } Q_INVOKABLE QString toString() const { if(m_ticks == TICK_INVALID) return "--:--"; qint64 t_sec = SEC_FROM_TICK(m_ticks); int sec = t_sec % 60; int min = (t_sec / 60) % 60; int hour = static_cast<int>(t_sec / 3600); if(hour == 0) return QString("%1:%2") .arg(min, 2, 10, QChar('0')) .arg(sec, 2, 10, QChar('0')); return QString("%1:%2:%3") .arg(hour, 2, 10, QChar('0')) .arg(min, 2, 10, QChar('0')) .arg(sec, 2, 10, QChar('0')); } Q_INVOKABLE TimeTick scale(float scalar) const { return TimeTick(qRound64(m_ticks * scalar)); } private: qint64 m_ticks; }; #endif // TIMETICK_H
johnhw/sigil
Melody.java
<reponame>johnhw/sigil import sigil.*; import duotonic.MIDIUtils; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.sound.midi.*; import java.io.*; /** * SignalDevice: Experimental device which creates random melodies and can * be evolved * * @author <NAME> */ public class Melody extends GAProcessorModel implements Cloneable { static final long serialVersionUID = 213L; //The random number generator for this device Random rnd = new Random(); //The list of note information private Vector noteVector; //The timbre for this melody private int timbre; //Properties public String getGenName() { return "Melody"; } public String getDescription() { return "Plays random melodies"; } public String getDate() { return "March 2002"; } public String getAuthor() { return "<NAME>"; } /** * Create a copy of the note list, and make that the current note list */ private void copyGenotype() { Vector temp = new Vector(); for(int i=0;i<noteVector.size();i++) { NoteInfo nInfo = (NoteInfo) (noteVector.get(i)); temp.add(nInfo.copy()); } noteVector = temp; } /** * Copy the attributes of another melody */ public void copyFrom(GAElement gaElt) { if(gaElt instanceof Melody) { Melody replacementMelody = (Melody)gaElt; noteVector = replacementMelody.noteVector; timbre = replacementMelody.timbre; } } /** * Modify the melody, changing by mutation factor */ public void mutate(double mutationFactor) { //Insert a new element if(rnd.nextDouble()<mutationFactor/3.0) noteVector.insertElementAt(makeNote(), rnd.nextInt(noteVector.size())); //Remove an element if(rnd.nextDouble()<mutationFactor/3.0 && noteVector.size()>2) noteVector.removeElementAt(rnd.nextInt(noteVector.size())); if(rnd.nextDouble()<mutationFactor/8.0) timbre = rnd.nextInt(127); //Adjust each element by the mutation factor for(int i=0;i<noteVector.size();i++) { if(rnd.nextDouble()<mutationFactor) { NoteInfo nInfo = (NoteInfo)(noteVector.get(i)); int newNote = nInfo.deltaNote+(int)(rnd.nextGaussian()*3* mutationFactor); int newVel = nInfo.deltaVel+(int)(rnd.nextGaussian()*20* mutationFactor); int newDur = nInfo.dur+(int)(Math.abs(rnd.nextGaussian()*2* mutationFactor)); noteVector.setElementAt(new NoteInfo(newNote, newVel, newDur), i); } } } /** * Randomly mix to Melody objects together */ public void breed(GAElement toBreed) { if(toBreed instanceof Melody) { } } /** * Returns a deep copy of this element */ public GAElement copy() { try{ Melody cloned = (Melody)clone(); cloned.copyGenotype(); return cloned; } catch(CloneNotSupportedException cnse) { return null; } } /** * Class for each element in the note list * holds the change of pitch, the change in velocity (volume) and the duration * of the note (in ticks). Note that the actual duration is 2^duration */ private class NoteInfo implements Serializable { int deltaNote, deltaVel, dur; public NoteInfo copy() { return new NoteInfo(deltaNote, deltaVel, dur); } public NoteInfo(int dNote, int dVel, int dur) { deltaNote = dNote; deltaVel = dVel; this.dur = dur; } } public void connectionChange() { } /** * Play the current melody, in a new thread */ private void playMelody() { new Thread() { public void run() { int baseNote = 60; int baseVel = 100; int durStep = 10; int patch = timbre; for(int i=0;i<noteVector.size();i++) { NoteInfo nInfo = (NoteInfo)(noteVector.get(i)); //Adjust pitch and volume baseNote+=nInfo.deltaNote; baseVel+=nInfo.deltaVel; //Limit the velocity if(baseVel<0) baseVel=0; if(baseVel>127) baseVel=127; //Calculate duration int duration = (int)(Math.pow(2,nInfo.dur))*durStep; //Play the note MIDIUtils.playNoteBlocking(0, baseNote, baseVel, duration, patch); } } }.start(); } /** * Simply plays the current melody */ public void preview() { playMelody(); } /** * Simply plays the current melody */ public void showInterface() { playMelody(); } /** * Create a new element of a melody, with random values */ private NoteInfo makeNote() { int deltaNote = (int)(rnd.nextGaussian()*7); int deltaVel = (int)(rnd.nextGaussian()*40); int dur = (int)(Math.abs(rnd.nextGaussian()*4)); return new NoteInfo(deltaNote, deltaVel, dur); } /** * Create a new sequenece of random melody elements */ private void makeMelody() { noteVector = new Vector(); int size = rnd.nextInt(20); timbre = rnd.nextInt(127); for(int i=0;i<size;i++) noteVector.add(makeNote()); } /** * Construct a new melody device */ public Melody() { super(); setTerminating(true); makeMelody(); } public void deleted() { } public void processSignal() { } }
huangjianqin/kin-rpc
kin-rpc-spring/src/main/java/org/kin/kinrpc/spring/EnableKinRpcService.java
package org.kin.kinrpc.spring; import org.springframework.context.annotation.Import; import java.lang.annotation.*; /** * 启用kinrpc service * * @author huangjianqin * @date 2020/12/15 */ @Documented @Inherited @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(KinRpcServiceBeanProcessor.class) public @interface EnableKinRpcService { }
joaconigro/QVES
VES-Core/Project.cpp
#include "Project.h" Project::Project(QObject *parent) : QObject(parent) { } Project::Project(const Project &pr) { mName = pr.name(); mVESs = pr.vess(); mCurrentVES = pr.currentVES(); mCurrentIndex = pr.currentIndex(); mCurrentePath = pr.currentePath(); mSaved = pr.saved(); this->setParent(pr.parent()); } Project::~Project() { if (mCurrentVES) mCurrentVES = nullptr; mVESs.clear(); } QString Project::name() const { return mName; } QList<VES *> Project::vess() const { return mVESs; } VES *Project::currentVES() const { return mCurrentVES; } int Project::currentIndex() const { return mCurrentIndex; } QString Project::currentePath() const { return mCurrentePath; } bool Project::saved() const { return mSaved; } void Project::setName(const QString value) { mName = value; } void Project::setCurrentePath(const QString value) { mCurrentePath = value; } void Project::setCurrentIndex(const int value) { if (value >= 0 && value < mVESs.count()){ if (mCurrentIndex != value) { mCurrentIndex = value; mCurrentVES = mVESs[mCurrentIndex]; emit currentVESChanged(); } } } QVariant Project::toVariant() const { QVariantMap map; map.insert("Name", mName); map.insert("CurrentIndex", mCurrentIndex); map.insert("CurrentePath", mCurrentePath); QVariantList list; for (const auto& v : mVESs) { list.append(v->toVariant()); } map.insert("VESs", list); return map; } void Project::fromVariant(const QVariant &variant) { QVariantMap map = variant.toMap(); mName = map.value("Name").toString(); mCurrentePath = map.value("CurrentePath").toString(); QVariantList list = map.value("VESs").toList(); for(const QVariant& data : list) { auto* v = new VES(this); v->fromVariant(data); this->addVES(v); } setCurrentIndex(map.value("CurrentIndex").toInt()); } void Project::addVES(VES* ves) { ves->setParent(this); mVESs.append(ves); }
gtrujillop/RealStateApp
db/migrate/20150620033333_add_for_sell_to_properties.rb
<reponame>gtrujillop/RealStateApp class AddForSellToProperties < ActiveRecord::Migration def change add_column :properties, :for_sell, :boolean end end
qzyuanmu/wechat
mp/user/user.go
<reponame>qzyuanmu/wechat // @description wechat 是腾讯微信公众平台 api 的 golang 语言封装 // @link https://github.com/chanxuehong/wechat for the canonical source repository // @license https://github.com/chanxuehong/wechat/blob/master/LICENSE // @authors chanxuehong(<EMAIL>) package user import ( "errors" "fmt" "net/url" "strconv" "strings" "github.com/chanxuehong/wechat/mp" ) const ( Language_zh_CN = "zh_CN" // 简体中文 Language_zh_TW = "zh_TW" // 繁体中文 Language_en = "en" // 英文 ) const ( SexUnknown = 0 // 未知 SexMale = 1 // 男性 SexFemale = 2 // 女性 ) type UserInfo struct { IsSubscriber int `json:"subscribe"` // 用户是否订阅该公众号标识, 值为0时, 代表此用户没有关注该公众号, 拉取不到其余信息 OpenId string `json:"openid"` // 用户的标识, 对当前公众号唯一 Nickname string `json:"nickname"` // 用户的昵称 Sex int `json:"sex"` // 用户的性别, 值为1时是男性, 值为2时是女性, 值为0时是未知 Language string `json:"language"` // 用户的语言, zh_CN, zh_TW, en City string `json:"city"` // 用户所在城市 Province string `json:"province"` // 用户所在省份 Country string `json:"country"` // 用户所在国家 // 用户头像, 最后一个数值代表正方形头像大小(有0, 46, 64, 96, 132数值可选, 0代表640*640正方形头像), // 用户没有头像时该项为空 HeadImageURL string `json:"headimgurl"` // 用户关注时间, 为时间戳. 如果用户曾多次关注, 则取最后关注时间 SubscribeTime int64 `json:"subscribe_time"` // 只有在用户将公众号绑定到微信开放平台帐号后, 才会出现该字段. UnionId string `json:"unionid"` Remark string `json:"remark"` // 公众号运营者对粉丝的备注, 公众号运营者可在微信公众平台用户管理界面对粉丝添加备注 GroupId int64 `json:"groupid"` // 用户所在的分组ID } var ErrNoHeadImage = errors.New("没有头像") // 获取用户图像的大小, 如果用户没有图像则返回 ErrNoHeadImage 错误. func (info *UserInfo) HeadImageSize() (size int, err error) { HeadImageURL := info.HeadImageURL if HeadImageURL == "" { err = ErrNoHeadImage return } lastSlashIndex := strings.LastIndex(HeadImageURL, "/") if lastSlashIndex == -1 { err = fmt.Errorf("invalid HeadImageURL: %s", HeadImageURL) return } HeadImageIndex := lastSlashIndex + 1 if HeadImageIndex == len(HeadImageURL) { err = fmt.Errorf("invalid HeadImageURL: %s", HeadImageURL) return } sizeStr := HeadImageURL[HeadImageIndex:] size, err = strconv.Atoi(sizeStr) if err != nil { err = fmt.Errorf("invalid HeadImageURL: %s", HeadImageURL) return } if size == 0 { size = 640 } return } // 获取用户基本信息. // 注意: // 1. 需要判断返回的 UserInfo.IsSubscriber 是否等于 1 还是 0 // 2. lang 可以是 zh_CN, zh_TW, en, 如果留空 "" 则默认为 zh_CN func (clt *Client) UserInfo(openId string, lang string) (userinfo *UserInfo, err error) { if openId == "" { err = errors.New("empty openId") return } switch lang { case "": lang = Language_zh_CN case Language_zh_CN, Language_zh_TW, Language_en: default: lang = Language_zh_CN } var result struct { mp.Error UserInfo } incompleteURL := "https://api.weixin.qq.com/cgi-bin/user/info?openid=" + url.QueryEscape(openId) + "&lang=" + url.QueryEscape(lang) + "&access_token=" if err = ((*mp.Client)(clt)).GetJSON(incompleteURL, &result); err != nil { return } if result.ErrCode != mp.ErrCodeOK { err = &result.Error return } userinfo = &result.UserInfo return } type UserInfoBatchGetRequestItem struct { OpenId string `json:"openid"` Language string `json:"lang,omitempty"` } // 创建 []UserInfoBatchGetRequestItem // lang 的取值可以为 "", Language_zh_CN, Language_zh_TW, Language_en func NewUserInfoBatchGetRequest(openIdList []string, lang string) (ret []UserInfoBatchGetRequestItem) { switch lang { case "", Language_zh_CN, Language_zh_TW, Language_en: default: lang = "" } ret = make([]UserInfoBatchGetRequestItem, len(openIdList)) for i := 0; i < len(openIdList); i++ { ret[i].OpenId = openIdList[i] ret[i].Language = lang } return } // 批量获取用户基本信息 // 注意: 需要对返回的 UserInfoList 的每个 UserInfo.IsSubscriber 做判断 func (clt *Client) UserInfoBatchGet(req []UserInfoBatchGetRequestItem) (UserInfoList []UserInfo, err error) { if len(req) <= 0 { err = errors.New("empty request") return } var request = struct { UserList []UserInfoBatchGetRequestItem `json:"user_list,omitempty"` }{ UserList: req, } var result struct { mp.Error UserInfoList []UserInfo `json:"user_info_list"` } incompleteURL := "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" if err = ((*mp.Client)(clt)).PostJSON(incompleteURL, &request, &result); err != nil { return } if result.ErrCode != mp.ErrCodeOK { err = &result.Error return } UserInfoList = result.UserInfoList return } // 开发者可以通过该接口对指定用户设置备注名. func (clt *Client) UserUpdateRemark(openId, remark string) (err error) { var request = struct { OpenId string `json:"openid"` Remark string `json:"remark"` }{ OpenId: openId, Remark: remark, } var result mp.Error incompleteURL := "https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=" if err = ((*mp.Client)(clt)).PostJSON(incompleteURL, &request, &result); err != nil { return } if result.ErrCode != mp.ErrCodeOK { err = &result return } return } // 获取关注者列表返回的数据结构 type UserListResult struct { TotalCount int `json:"total"` // 关注该公众账号的总用户数 GotCount int `json:"count"` // 拉取的 OPENID 个数, 最大值为10000 Data struct { OpenIdList []string `json:"openid,omitempty"` } `json:"data"` // 列表数据, OPENID 的列表 // 拉取列表的后一个用户的OPENID, 如果 next_openid == "" 则表示没有了用户数据 NextOpenId string `json:"next_openid"` } // 获取关注者列表. // NOTE: // 1. 每次最多能获取 10000 个用户, 可以多次指定 NextOpenId 来获取以满足需求, 如果 NextOpenId == "" 则表示从头获取 // 2. 目前微信返回的数据并不包括 NextOpenId 本身, 是从 NextOpenId 下一个用户开始的, 和微信文档描述不一样!!! func (clt *Client) UserList(NextOpenId string) (rslt *UserListResult, err error) { var result struct { mp.Error UserListResult } var incompleteURL string if NextOpenId == "" { incompleteURL = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" } else { incompleteURL = "https://api.weixin.qq.com/cgi-bin/user/get?next_openid=" + url.QueryEscape(NextOpenId) + "&access_token=" } if err = ((*mp.Client)(clt)).GetJSON(incompleteURL, &result); err != nil { return } if result.ErrCode != mp.ErrCodeOK { err = &result.Error return } rslt = &result.UserListResult return }
wolfiex/VisACC
swirlycomparison/readnc.js
///classes and defns class nc2D { constructor(name, width, arr_type) { //Float32Array this.width = dims[width]; this.arr_type = arr_type; this.data = new arr_type(reader.getDataVariable(name)); } } nc2D.prototype.row = function(index) { var start = index * this.width; return new this.arr_type(this.data.slice(start, start + this.width)); }; var print = d => console.log(d); const width = window.innerWidth; const height = window.innerHeight; /* comment block */ function ncparse(reader, file) { //all parts we require from the netcdf file reader.dimensions.forEach( function(d) { dims[d.name] = d.size; }, dims = {} ); const concentration = new nc2D("concentration", "specs", Float32Array); //const flux = new nc2D("edge-length", "fluxes", Float32Array); const dict = JSON.parse(reader.getDataVariable("nodes").join("")); /* const combine = JSON.parse(reader.getDataVariable("combinations").join("")); const tar = reader.getDataVariable("target"); const src = reader.getDataVariable("source"); */ const time = reader.getDataVariable("timeseconds"); // creates reverse dictionary rdict below var rdict, nodes, i; Object.keys(dict).forEach( function(d) { var i = dict[d]; rdict[i] = d; }, rdict = {}, nodes = [] ); formatTime = d3.timeFormat("%b %d \n %H:%M"); //time => datetime const datetime = time.map(function(e) { var utcSeconds = e; var d = new Date(0); // The 0 there is the key, which sets the date to the epoch d.setUTCSeconds(utcSeconds); return d; }); // console.log(file.replace(/\.nc/, ""), "Can display reactions on interaction"); eval( "window." + file.replace(/\.nc/, "") + "={concentration,dict,rdict,datetime,dims};" //combine,tar,src, ); } function newfile(file) { var ncfile; try { const fs = require("fs"); const data = fs.readFileSync( __dirname.match(/(.*\/)/)[1] + "netcdf_results/" + file ); reader = new netcdfjs(data); ncparse(reader, file); } catch (err) { console.log("switching to browser mode", err); var urlpath = document.URL.match(/(.*\/).*\//)[1] + "netcdf_results/" + file; var oReq = new XMLHttpRequest(); oReq.open("GET", urlpath, true); oReq.responseType = "blob"; oReq.onload = function(oEvent) { var blob = oReq.response; reader_url = new FileReader(); return reader_url.onload = function(e) { reader = new netcdfjs(this.result); return ncparse(reader, file); }; reader_url.readAsArrayBuffer(blob); }; oReq.send(); //start process } return eval("window." + file.replace(/\.nc/, "")); }
NichelleBot/snap
mgmt/rest/flags.go
/* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package rest import ( "fmt" "github.com/codegangsta/cli" ) const ( DefaultMaxFailures = 10 ) var ( flAPIDisabled = cli.BoolFlag{ Name: "disable-api, d", Usage: "Disable the agent REST API", } flAPIAddr = cli.StringFlag{ Name: "api-addr, b", Usage: "API Address[:port] to bind to/listen on. Default: empty string => listen on all interfaces", EnvVar: "SNAP_ADDR", } flAPIPort = cli.StringFlag{ Name: "api-port, p", Usage: fmt.Sprintf("API port (default: %v)", defaultPort), EnvVar: "SNAP_PORT", } flRestHTTPS = cli.BoolFlag{ Name: "rest-https", Usage: "start snap's API as https", } flRestCert = cli.StringFlag{ Name: "rest-cert", Usage: "A path to a certificate to use for HTTPS deployment of snap's REST API", } flRestKey = cli.StringFlag{ Name: "rest-key", Usage: "A path to a key file to use for HTTPS deployment of snap's REST API", } flRestAuth = cli.BoolFlag{ Name: "rest-auth", Usage: "Enables snap's REST API authentication", } // Flags consumed by snapd Flags = []cli.Flag{flAPIDisabled, flAPIAddr, flAPIPort, flRestHTTPS, flRestCert, flRestKey, flRestAuth} )
isabella232/emacs4ij
jelisp/src/java/org/jetbrains/emacs4ij/jelisp/platformDependent/LispFrame.java
<reponame>isabella232/emacs4ij package org.jetbrains.emacs4ij.jelisp.platformDependent; import org.jetbrains.emacs4ij.jelisp.Environment; import org.jetbrains.emacs4ij.jelisp.elisp.LispList; import org.jetbrains.emacs4ij.jelisp.elisp.LispObject; import org.jetbrains.emacs4ij.jelisp.elisp.LispSymbol; import org.jetbrains.emacs4ij.jelisp.exception.VoidVariableException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class LispFrame implements LispObject { private Map<LispSymbol, LispObject> myParameters = new HashMap<>(); private Map<LispSymbol, LispObject> myFaceAList = new HashMap<>(); public abstract void setVisible (boolean visible); public abstract void setIconified (boolean iconified); public LispFrame() { setParameter("visibility", LispSymbol.T); setParameter("buffer-predicate", LispSymbol.NIL); } @Override public LispObject evaluate(Environment environment) { return this; } public Map<LispSymbol, LispObject> getFacesAList() { return myFaceAList; } public boolean isIconified() { return getParameter("visibility").equals(new LispSymbol("icon")); } public boolean isVisible() { return getParameter("visibility").equals(LispSymbol.T); } public LispObject getParameter(LispSymbol parameter) { LispObject value = myParameters.get(parameter); if (value == null) throw new VoidVariableException(parameter.getName()); return value; } public void setParameter(LispSymbol name, LispObject value) { myParameters.put(name, value); } public LispList getParameters() { List<LispObject> list = new ArrayList<>(); for (Map.Entry<LispSymbol, LispObject> parameter: myParameters.entrySet()) { LispList item = LispList.list(parameter.getKey()); item.append(parameter.getValue()); list.add(item); } return LispList.list(list); } protected final void setParameter(String name, LispObject value) { myParameters.put(new LispSymbol(name), value); } private LispObject getParameter(String parameter) { return getParameter(new LispSymbol(parameter)); } }
rwatson/chromium-capsicum
webkit/tools/test_shell/test_shell_webthemeengine.cc
<filename>webkit/tools/test_shell/test_shell_webthemeengine.cc // Copyright (c) 2009 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. // This file implements a simple generic version of the WebKitThemeEngine, // Since WebThemeEngine is unfortunately defined in terms of the Windows // Theme parameters and values, we need to translate all the values into // generic equivalents that we can more easily understand. This file does // that translation (acting as a Facade design pattern) and then uses // TestShellWebTheme::Control for the actual rendering of the widgets. // #include "webkit/tools/test_shell/test_shell_webthemeengine.h" // Although all this code is generic, we include these headers // to pull in the Windows #defines for the parts and states of // the controls. #include <vsstyle.h> #include <windows.h> #include "base/logging.h" #include "third_party/WebKit/WebKit/chromium/public/WebCanvas.h" #include "third_party/WebKit/WebKit/chromium/public/WebRect.h" #include "webkit/tools/test_shell/test_shell_webthemecontrol.h" #include "third_party/skia/include/core/SkRect.h" #ifndef CHECK_EQ #define CHECK_EQ(a, b) CHECK((a) == (b)) #endif // We define this for clarity, although there really should be a DFCS_NORMAL // in winuser.h. namespace { const int kDFCSNormal = 0x0000; } using WebKit::WebCanvas; using WebKit::WebColor; using WebKit::WebRect; namespace TestShellWebTheme { SkIRect webRectToSkIRect(const WebRect &web_rect) { SkIRect irect; irect.set(web_rect.x, web_rect.y, web_rect.x + web_rect.width, web_rect.y + web_rect.height); return irect; } void drawControl(WebCanvas *canvas, const WebRect &rect, Control::Type ctype, Control::State cstate) { Control control(canvas, webRectToSkIRect(rect), ctype, cstate); control.draw(); } void drawTextField(WebCanvas *canvas, const WebRect &rect, Control::Type ctype, Control::State cstate, bool draw_edges, bool fill_content_area, WebColor color) { Control control(canvas, webRectToSkIRect(rect), ctype, cstate); control.drawTextField(draw_edges, fill_content_area, color); } void Engine::paintButton(WebCanvas* canvas, int part, int state, int classic_state, const WebRect& rect) { Control::Type ctype = Control::kUnknown_Type; Control::State cstate = Control::kUnknown_State; if (part == BP_CHECKBOX) { switch (state) { case CBS_UNCHECKEDNORMAL: CHECK_EQ(classic_state, kDFCSNormal); ctype = Control::kUncheckedBox_Type; cstate = Control::kNormal_State; break; case CBS_UNCHECKEDHOT: CHECK_EQ(classic_state, DFCS_BUTTONCHECK | DFCS_HOT); ctype = Control::kUncheckedBox_Type; cstate = Control::kHot_State; break; case CBS_UNCHECKEDPRESSED: CHECK_EQ(classic_state, DFCS_BUTTONCHECK | DFCS_PUSHED); ctype = Control::kUncheckedBox_Type; cstate = Control::kPressed_State; break; case CBS_UNCHECKEDDISABLED: CHECK_EQ(classic_state, DFCS_BUTTONCHECK | DFCS_INACTIVE); ctype = Control::kUncheckedBox_Type; cstate = Control::kDisabled_State; break; case CBS_CHECKEDNORMAL: CHECK_EQ(classic_state, DFCS_BUTTONCHECK | DFCS_CHECKED); ctype = Control::kCheckedBox_Type; cstate = Control::kNormal_State; break; case CBS_CHECKEDHOT: CHECK_EQ(classic_state, DFCS_BUTTONCHECK | DFCS_CHECKED | DFCS_HOT); ctype = Control::kCheckedBox_Type; cstate = Control::kHot_State; break; case CBS_CHECKEDPRESSED: CHECK_EQ(classic_state, DFCS_BUTTONCHECK | DFCS_CHECKED | DFCS_PUSHED); ctype = Control::kCheckedBox_Type; cstate = Control::kPressed_State; break; case CBS_CHECKEDDISABLED: CHECK_EQ(classic_state, DFCS_BUTTONCHECK | DFCS_CHECKED | DFCS_INACTIVE); ctype = Control::kCheckedBox_Type; cstate = Control::kDisabled_State; break; default: NOTREACHED(); break; } } else if (BP_RADIOBUTTON == part) { switch (state) { case RBS_UNCHECKEDNORMAL: CHECK_EQ(classic_state, DFCS_BUTTONRADIO); ctype = Control::kUncheckedRadio_Type; cstate = Control::kNormal_State; break; case RBS_UNCHECKEDHOT: CHECK_EQ(classic_state, DFCS_BUTTONRADIO | DFCS_HOT); ctype = Control::kUncheckedRadio_Type; cstate = Control::kHot_State; break; case RBS_UNCHECKEDPRESSED: CHECK_EQ(classic_state, DFCS_BUTTONRADIO | DFCS_PUSHED); ctype = Control::kUncheckedRadio_Type; cstate = Control::kPressed_State; break; case RBS_UNCHECKEDDISABLED: CHECK_EQ(classic_state, DFCS_BUTTONRADIO | DFCS_INACTIVE); ctype = Control::kUncheckedRadio_Type; cstate = Control::kDisabled_State; break; case RBS_CHECKEDNORMAL: CHECK_EQ(classic_state, DFCS_BUTTONRADIO | DFCS_CHECKED); ctype = Control::kCheckedRadio_Type; cstate = Control::kNormal_State; break; case RBS_CHECKEDHOT: CHECK_EQ(classic_state, DFCS_BUTTONRADIO | DFCS_CHECKED | DFCS_HOT); ctype = Control::kCheckedRadio_Type; cstate = Control::kHot_State; break; case RBS_CHECKEDPRESSED: CHECK_EQ(classic_state, DFCS_BUTTONRADIO | DFCS_CHECKED | DFCS_PUSHED); ctype = Control::kCheckedRadio_Type; cstate = Control::kPressed_State; break; case RBS_CHECKEDDISABLED: CHECK_EQ(classic_state, DFCS_BUTTONRADIO | DFCS_CHECKED | DFCS_INACTIVE); ctype = Control::kCheckedRadio_Type; cstate = Control::kDisabled_State; break; default: NOTREACHED(); break; } } else if (BP_PUSHBUTTON == part) { switch (state) { case PBS_NORMAL: CHECK_EQ(classic_state, DFCS_BUTTONPUSH); ctype = Control::kPushButton_Type; cstate = Control::kNormal_State; break; case PBS_HOT: CHECK_EQ(classic_state, DFCS_BUTTONPUSH | DFCS_HOT); ctype = Control::kPushButton_Type; cstate = Control::kHot_State; break; case PBS_PRESSED: CHECK_EQ(classic_state, DFCS_BUTTONPUSH | DFCS_PUSHED); ctype = Control::kPushButton_Type; cstate = Control::kPressed_State; break; case PBS_DISABLED: CHECK_EQ(classic_state, DFCS_BUTTONPUSH | DFCS_INACTIVE); ctype = Control::kPushButton_Type; cstate = Control::kDisabled_State; break; case PBS_DEFAULTED: CHECK_EQ(classic_state, DFCS_BUTTONPUSH); ctype = Control::kPushButton_Type; cstate = Control::kFocused_State; break; default: NOTREACHED(); break; } } else { NOTREACHED(); } drawControl(canvas, rect, ctype, cstate); } void Engine::paintMenuList(WebCanvas* canvas, int part, int state, int classic_state, const WebRect& rect) { Control::Type ctype = Control::kUnknown_Type; Control::State cstate = Control::kUnknown_State; if (CP_DROPDOWNBUTTON == part) { ctype = Control::kDropDownButton_Type; switch (state) { case CBXS_NORMAL: CHECK_EQ(classic_state, DFCS_MENUARROW); cstate = Control::kNormal_State; break; case CBXS_HOT: CHECK_EQ(classic_state, DFCS_MENUARROW | DFCS_HOT); cstate = Control::kHover_State; break; case CBXS_PRESSED: CHECK_EQ(classic_state, DFCS_MENUARROW | DFCS_PUSHED); cstate = Control::kPressed_State; break; case CBXS_DISABLED: CHECK_EQ(classic_state, DFCS_MENUARROW | DFCS_INACTIVE); cstate = Control::kDisabled_State; break; default: CHECK(false); break; } } else { CHECK(false); } drawControl(canvas, rect, ctype, cstate); } void Engine::paintScrollbarArrow(WebCanvas* canvas, int state, int classic_state, const WebRect& rect) { Control::Type ctype = Control::kUnknown_Type; Control::State cstate = Control::kUnknown_State; switch (state) { case ABS_UPNORMAL: CHECK_EQ(classic_state, DFCS_SCROLLUP); ctype = Control::kUpArrow_Type; cstate = Control::kNormal_State; break; case ABS_DOWNNORMAL: CHECK_EQ(classic_state, DFCS_SCROLLDOWN); ctype = Control::kDownArrow_Type; cstate = Control::kNormal_State; break; case ABS_LEFTNORMAL: CHECK_EQ(classic_state, DFCS_SCROLLLEFT); ctype = Control::kLeftArrow_Type; cstate = Control::kNormal_State; break; case ABS_RIGHTNORMAL: CHECK_EQ(classic_state, DFCS_SCROLLRIGHT); ctype = Control::kRightArrow_Type; cstate = Control::kNormal_State; break; case ABS_UPHOT: CHECK_EQ(classic_state, DFCS_SCROLLUP | DFCS_HOT); ctype = Control::kUpArrow_Type; cstate = Control::kHot_State; break; case ABS_DOWNHOT: CHECK_EQ(classic_state, DFCS_SCROLLDOWN | DFCS_HOT); ctype = Control::kDownArrow_Type; cstate = Control::kHot_State; break; case ABS_LEFTHOT: CHECK_EQ(classic_state, DFCS_SCROLLLEFT | DFCS_HOT); ctype = Control::kLeftArrow_Type; cstate = Control::kHot_State; break; case ABS_RIGHTHOT: CHECK_EQ(classic_state, DFCS_SCROLLRIGHT | DFCS_HOT); ctype = Control::kRightArrow_Type; cstate = Control::kHot_State; break; case ABS_UPHOVER: CHECK_EQ(classic_state, DFCS_SCROLLUP); ctype = Control::kUpArrow_Type; cstate = Control::kHover_State; break; case ABS_DOWNHOVER: CHECK_EQ(classic_state, DFCS_SCROLLDOWN); ctype = Control::kDownArrow_Type; cstate = Control::kHover_State; break; case ABS_LEFTHOVER: CHECK_EQ(classic_state, DFCS_SCROLLLEFT); ctype = Control::kLeftArrow_Type; cstate = Control::kHover_State; break; case ABS_RIGHTHOVER: CHECK_EQ(classic_state, DFCS_SCROLLRIGHT); ctype = Control::kRightArrow_Type; cstate = Control::kHover_State; break; case ABS_UPPRESSED: CHECK_EQ(classic_state, DFCS_SCROLLUP | DFCS_PUSHED | DFCS_FLAT); ctype = Control::kUpArrow_Type; cstate = Control::kPressed_State; break; case ABS_DOWNPRESSED: CHECK_EQ(classic_state, DFCS_SCROLLDOWN | DFCS_PUSHED | DFCS_FLAT); ctype = Control::kDownArrow_Type; cstate = Control::kPressed_State; break; case ABS_LEFTPRESSED: CHECK_EQ(classic_state, DFCS_SCROLLLEFT | DFCS_PUSHED | DFCS_FLAT); ctype = Control::kLeftArrow_Type; cstate = Control::kPressed_State; break; case ABS_RIGHTPRESSED: CHECK_EQ(classic_state, DFCS_SCROLLRIGHT | DFCS_PUSHED | DFCS_FLAT); ctype = Control::kRightArrow_Type; cstate = Control::kPressed_State; break; case ABS_UPDISABLED: CHECK_EQ(classic_state, DFCS_SCROLLUP | DFCS_INACTIVE); ctype = Control::kUpArrow_Type; cstate = Control::kDisabled_State; break; case ABS_DOWNDISABLED: CHECK_EQ(classic_state, DFCS_SCROLLDOWN | DFCS_INACTIVE); ctype = Control::kDownArrow_Type; cstate = Control::kDisabled_State; break; case ABS_LEFTDISABLED: CHECK_EQ(classic_state, DFCS_SCROLLLEFT | DFCS_INACTIVE); ctype = Control::kLeftArrow_Type; cstate = Control::kDisabled_State; break; case ABS_RIGHTDISABLED: CHECK_EQ(classic_state, DFCS_SCROLLRIGHT | DFCS_INACTIVE); ctype = Control::kRightArrow_Type; cstate = Control::kDisabled_State; break; default: NOTREACHED(); break; } drawControl(canvas, rect, ctype, cstate); } void Engine::paintScrollbarThumb(WebCanvas* canvas, int part, int state, int classic_state, const WebRect& rect) { Control::Type ctype = Control::kUnknown_Type; Control::State cstate = Control::kUnknown_State; switch (part) { case SBP_THUMBBTNHORZ: ctype = Control::kHorizontalScrollThumb_Type; break; case SBP_THUMBBTNVERT: ctype = Control::kVerticalScrollThumb_Type; break; case SBP_GRIPPERHORZ: ctype = Control::kHorizontalScrollGrip_Type; break; case SBP_GRIPPERVERT: ctype = Control::kVerticalScrollGrip_Type; break; default: NOTREACHED(); break; } switch (state) { case SCRBS_NORMAL: CHECK_EQ(classic_state, kDFCSNormal); cstate = Control::kNormal_State; break; case SCRBS_HOT: CHECK_EQ(classic_state, DFCS_HOT); cstate = Control::kHot_State; break; case SCRBS_HOVER: CHECK_EQ(classic_state, kDFCSNormal); cstate = Control::kHover_State; break; case SCRBS_PRESSED: CHECK_EQ(classic_state, kDFCSNormal); cstate = Control::kPressed_State; break; case SCRBS_DISABLED: NOTREACHED(); // This should never happen in practice. break; default: NOTREACHED(); break; } drawControl(canvas, rect, ctype, cstate); } void Engine::paintScrollbarTrack(WebCanvas* canvas, int part, int state, int classic_state, const WebRect& rect, const WebRect& align_rect) { Control::Type ctype = Control::kUnknown_Type; Control::State cstate = Control::kUnknown_State; switch (part) { case SBP_UPPERTRACKHORZ: ctype = Control::kHorizontalScrollTrackBack_Type; break; case SBP_LOWERTRACKHORZ: ctype = Control::kHorizontalScrollTrackForward_Type; break; case SBP_UPPERTRACKVERT: ctype = Control::kVerticalScrollTrackBack_Type; break; case SBP_LOWERTRACKVERT: ctype = Control::kVerticalScrollTrackForward_Type; break; default: NOTREACHED(); break; } switch (state) { case SCRBS_NORMAL: CHECK_EQ(classic_state, kDFCSNormal); cstate = Control::kNormal_State; break; case SCRBS_HOT: NOTREACHED(); // This should never happen in practice. break; case SCRBS_HOVER: CHECK_EQ(classic_state, kDFCSNormal); cstate = Control::kHover_State; break; case SCRBS_PRESSED: NOTREACHED(); // This should never happen in practice. break; case SCRBS_DISABLED: CHECK_EQ(classic_state, DFCS_INACTIVE); cstate = Control::kDisabled_State; break; default: CHECK(false); break; } drawControl(canvas, rect, ctype, cstate); } void Engine::paintTextField(WebCanvas* canvas, int part, int state, int classic_state, const WebRect& rect, WebColor color, bool fill_content_area, bool draw_edges) { Control::Type ctype = Control::kUnknown_Type; Control::State cstate = Control::kUnknown_State; CHECK_EQ(EP_EDITTEXT, part); ctype = Control::kTextField_Type; switch (state) { case ETS_NORMAL: CHECK_EQ(classic_state, kDFCSNormal); cstate = Control::kNormal_State; break; case ETS_HOT: CHECK_EQ(classic_state, DFCS_HOT); cstate = Control::kHot_State; break; case ETS_DISABLED: CHECK_EQ(classic_state, DFCS_INACTIVE); cstate = Control::kDisabled_State; break; case ETS_SELECTED: CHECK_EQ(classic_state, DFCS_PUSHED); cstate = Control::kPressed_State; break; case ETS_FOCUSED: CHECK_EQ(classic_state, kDFCSNormal); cstate = Control::kFocused_State; break; case ETS_READONLY: CHECK_EQ(classic_state, kDFCSNormal); cstate = Control::kReadOnly_State; break; default: NOTREACHED(); break; } drawTextField(canvas, rect, ctype, cstate, draw_edges, fill_content_area, color); } void Engine::paintTrackbar(WebCanvas* canvas, int part, int state, int classic_state, const WebRect& rect) { Control::Type ctype = Control::kUnknown_Type; Control::State cstate = Control::kUnknown_State; if (TKP_THUMBBOTTOM == part) { ctype = Control::kHorizontalSliderThumb_Type; switch (state) { case TUS_NORMAL: CHECK_EQ(classic_state, kDFCSNormal); cstate = Control::kNormal_State; break; case TUS_HOT: CHECK_EQ(classic_state, DFCS_HOT); cstate = Control::kHot_State; break; case TUS_DISABLED: CHECK_EQ(classic_state, DFCS_INACTIVE); cstate = Control::kDisabled_State; break; case TUS_PRESSED: CHECK_EQ(classic_state, DFCS_PUSHED); cstate = Control::kPressed_State; break; default: NOTREACHED(); break; } } else if (TKP_TRACK == part) { ctype = Control::kHorizontalSliderTrack_Type; CHECK_EQ(part, TUS_NORMAL); CHECK_EQ(classic_state, kDFCSNormal); cstate = Control::kNormal_State; } else { NOTREACHED(); } drawControl(canvas, rect, ctype, cstate); } } // namespace TestShellWebTheme
keys-pub/keysd
http/server/twitter.go
package server import ( "github.com/keys-pub/keys" "github.com/keys-pub/keys/http" "github.com/keys-pub/keys/user" "github.com/keys-pub/keys/user/services" "github.com/labstack/echo/v4" "github.com/pkg/errors" ) func (s *Server) checkTwitter(c echo.Context) error { ctx := c.Request().Context() kid, err := keys.ParseID(c.Param("kid")) if err != nil { return s.ErrBadRequest(c, errors.Errorf("invalid kid")) } name := c.Param("name") if name == "" { return s.ErrBadRequest(c, errors.Errorf("invalid name")) } id := c.Param("id") if id == "" { return s.ErrBadRequest(c, errors.Errorf("invalid id")) } twitter := services.Twitter urs := "https://twitter.com/" + name + "/status/" + id usr, err := user.New(kid, "twitter", name, urs, 1) if err != nil { return s.ErrBadRequest(c, err) } // TODO: Rate limit _, body, err := twitter.Request(ctx, s.client, usr) if err != nil { return s.ErrBadRequest(c, errors.Errorf("twitter request failed")) } if body == nil { return s.ErrBadRequest(c, errors.Errorf("tweet not found")) } status, verified, err := twitter.Verify(ctx, body, usr) if err != nil || status != user.StatusOK { // TODO: Send status through with error return s.ErrBadRequest(c, errors.Errorf("failed %s (%s)", status, err)) } return c.Blob(http.StatusOK, echo.MIMEOctetStream, []byte(verified.Statement)) }
lihongan/external-dns
vendor/github.com/exoscale/egoscale/v2/database.go
package v2 import ( "context" "net/url" "time" apiv2 "github.com/exoscale/egoscale/v2/api" "github.com/exoscale/egoscale/v2/oapi" ) // DatabaseBackupConfig represents a Database Backup configuration. type DatabaseBackupConfig struct { FrequentIntervalMinutes *int64 FrequentOldestAgeMinutes *int64 InfrequentIntervalMinutes *int64 InfrequentOldestAgeMinutes *int64 Interval *int64 MaxCount *int64 RecoveryMode *string } func databaseBackupConfigFromAPI(c *oapi.DbaasBackupConfig) *DatabaseBackupConfig { return &DatabaseBackupConfig{ FrequentIntervalMinutes: c.FrequentIntervalMinutes, FrequentOldestAgeMinutes: c.FrequentOldestAgeMinutes, InfrequentIntervalMinutes: c.InfrequentIntervalMinutes, InfrequentOldestAgeMinutes: c.InfrequentOldestAgeMinutes, Interval: c.Interval, MaxCount: c.MaxCount, RecoveryMode: c.RecoveryMode, } } // DatabasePlan represents a Database Plan. type DatabasePlan struct { BackupConfig *DatabaseBackupConfig DiskSpace *int64 MaxMemoryPercent *int64 Name *string Nodes *int64 NodeCPUs *int64 NodeMemory *int64 } func databasePlanFromAPI(p *oapi.DbaasPlan) *DatabasePlan { return &DatabasePlan{ BackupConfig: databaseBackupConfigFromAPI(p.BackupConfig), DiskSpace: p.DiskSpace, MaxMemoryPercent: p.MaxMemoryPercent, Name: p.Name, Nodes: p.NodeCount, NodeCPUs: p.NodeCpuCount, NodeMemory: p.NodeMemory, } } // DatabaseServiceType represents a Database Service type. type DatabaseServiceType struct { DefaultVersion *string Description *string LatestVersion *string Name *string Plans []*DatabasePlan UserConfigSchema map[string]interface{} } func databaseServiceTypeFromAPI(t *oapi.DbaasServiceType) *DatabaseServiceType { return &DatabaseServiceType{ DefaultVersion: t.DefaultVersion, Description: t.Description, LatestVersion: t.LatestVersion, Name: (*string)(t.Name), Plans: func() []*DatabasePlan { plans := make([]*DatabasePlan, 0) if t.Plans != nil { for _, plan := range *t.Plans { plan := plan plans = append(plans, databasePlanFromAPI(&plan)) } } return plans }(), UserConfigSchema: func() map[string]interface{} { if t.UserConfigSchema != nil { return t.UserConfigSchema.AdditionalProperties } return nil }(), } } // DatabaseServiceBackup represents a Database Service backup. type DatabaseServiceBackup struct { Name *string Size *int64 Date *time.Time } func databaseServiceBackupFromAPI(b *oapi.DbaasServiceBackup) *DatabaseServiceBackup { return &DatabaseServiceBackup{ Name: &b.BackupName, Size: &b.DataSize, Date: &b.BackupTime, } } // DatabaseServiceComponent represents a Database Service component. type DatabaseServiceComponent struct { Name *string Info map[string]interface{} } func databaseServiceComponentFromAPI(c *oapi.DbaasServiceComponents) *DatabaseServiceComponent { info := map[string]interface{}{ "host": c.Host, "port": c.Port, "route": c.Route, "usage": c.Usage, } if c.KafkaAuthenticationMethod != nil { info["kafka_authenticated_method"] = c.KafkaAuthenticationMethod } if c.Path != nil { info["path"] = c.Path } if c.Ssl != nil { info["ssl"] = c.Ssl } return &DatabaseServiceComponent{ Name: &c.Component, Info: info, } } // DatabaseServiceMaintenance represents a Database Service maintenance. type DatabaseServiceMaintenance struct { DOW string Time string } func databaseServiceMaintenanceFromAPI(m *oapi.DbaasServiceMaintenance) *DatabaseServiceMaintenance { return &DatabaseServiceMaintenance{ DOW: string(m.Dow), Time: m.Time, } } // DatabaseServiceUser represents a Database Service user. type DatabaseServiceUser struct { Password *string Type *string UserName *string } func databaseServiceUserFromAPI(u *oapi.DbaasServiceUser) *DatabaseServiceUser { return &DatabaseServiceUser{ Password: <PASSWORD>, UserName: &u.Username, Type: &u.Type, } } // DatabaseService represents a Database Service. type DatabaseService struct { Backups []*DatabaseServiceBackup Components []*DatabaseServiceComponent ConnectionInfo map[string]interface{} CreatedAt *time.Time DiskSize *int64 Features map[string]interface{} Maintenance *DatabaseServiceMaintenance Metadata map[string]interface{} Name *string Nodes *int64 NodeCPUs *int64 NodeMemory *int64 Plan *string State *string TerminationProtection *bool Type *string UpdatedAt *time.Time URI *url.URL UserConfig *map[string]interface{} Users []*DatabaseServiceUser } func databaseServiceFromAPI(s *oapi.DbaasService) *DatabaseService { return &DatabaseService{ Backups: func() []*DatabaseServiceBackup { backups := make([]*DatabaseServiceBackup, 0) if s.Backups != nil { for _, b := range *s.Backups { backups = append(backups, databaseServiceBackupFromAPI(&b)) } } return backups }(), Components: func() []*DatabaseServiceComponent { components := make([]*DatabaseServiceComponent, 0) if s.Components != nil { for _, c := range *s.Components { components = append(components, databaseServiceComponentFromAPI(&c)) } } return components }(), ConnectionInfo: func() (v map[string]interface{}) { if s.ConnectionInfo != nil { v = s.ConnectionInfo.AdditionalProperties } return }(), CreatedAt: s.CreatedAt, DiskSize: s.DiskSize, Features: func() (v map[string]interface{}) { if s.Features != nil { v = s.Features.AdditionalProperties } return }(), Maintenance: func() (v *DatabaseServiceMaintenance) { if s.Maintenance != nil { return databaseServiceMaintenanceFromAPI(s.Maintenance) } return }(), Metadata: func() (v map[string]interface{}) { if s.Metadata != nil { v = s.Metadata.AdditionalProperties } return }(), Name: (*string)(&s.Name), Nodes: s.NodeCount, NodeCPUs: s.NodeCpuCount, NodeMemory: s.NodeMemory, Plan: &s.Plan, State: (*string)(s.State), TerminationProtection: s.TerminationProtection, Type: (*string)(&s.Type), UpdatedAt: s.UpdatedAt, URI: func() *url.URL { if s.Uri != nil { if u, _ := url.Parse(*s.Uri); u != nil { return u } } return nil }(), UserConfig: func() (v *map[string]interface{}) { if s.UserConfig != nil { v = &s.UserConfig.AdditionalProperties } return }(), Users: func() []*DatabaseServiceUser { users := make([]*DatabaseServiceUser, 0) if s.Users != nil { for _, u := range *s.Users { users = append(users, databaseServiceUserFromAPI(&u)) } } return users }(), } } // GetDatabaseCACertificate returns the CA certificate required to access Database Services using a TLS connection. func (c *Client) GetDatabaseCACertificate(ctx context.Context, zone string) (string, error) { resp, err := c.GetDbaasCaCertificateWithResponse(apiv2.WithZone(ctx, zone)) if err != nil { return "", err } return *resp.JSON200.Certificate, nil } // GetDatabaseServiceType returns the Database Service type corresponding to the specified name. func (c *Client) GetDatabaseServiceType(ctx context.Context, zone, name string) (*DatabaseServiceType, error) { resp, err := c.GetDbaasServiceTypeWithResponse(apiv2.WithZone(ctx, zone), name) if err != nil { return nil, err } return databaseServiceTypeFromAPI(resp.JSON200), nil } // ListDatabaseServiceTypes returns the list of existing Database Service types. func (c *Client) ListDatabaseServiceTypes(ctx context.Context, zone string) ([]*DatabaseServiceType, error) { list := make([]*DatabaseServiceType, 0) resp, err := c.ListDbaasServiceTypesWithResponse(apiv2.WithZone(ctx, zone)) if err != nil { return nil, err } if resp.JSON200.DbaasServiceTypes != nil { for i := range *resp.JSON200.DbaasServiceTypes { list = append(list, databaseServiceTypeFromAPI(&(*resp.JSON200.DbaasServiceTypes)[i])) } } return list, nil } // CreateDatabaseService creates a Database Service. func (c *Client) CreateDatabaseService( ctx context.Context, zone string, databaseService *DatabaseService, ) (*DatabaseService, error) { _, err := c.CreateDbaasServiceWithResponse( apiv2.WithZone(ctx, zone), oapi.CreateDbaasServiceJSONRequestBody{ Maintenance: func() (v *struct { Dow oapi.CreateDbaasServiceJSONBodyMaintenanceDow `json:"dow"` Time string `json:"time"` }) { if databaseService.Maintenance != nil { v = &struct { Dow oapi.CreateDbaasServiceJSONBodyMaintenanceDow `json:"dow"` Time string `json:"time"` }{ Dow: oapi.CreateDbaasServiceJSONBodyMaintenanceDow(databaseService.Maintenance.DOW), Time: databaseService.Maintenance.Time, } } return }(), Name: oapi.DbaasServiceName(*databaseService.Name), Plan: *databaseService.Plan, TerminationProtection: databaseService.TerminationProtection, Type: oapi.DbaasServiceTypeName(*databaseService.Type), UserConfig: func() (v *oapi.CreateDbaasServiceJSONBody_UserConfig) { if databaseService.UserConfig != nil { v = &oapi.CreateDbaasServiceJSONBody_UserConfig{ AdditionalProperties: *databaseService.UserConfig, } } return }(), }) if err != nil { return nil, err } return c.GetDatabaseService(ctx, zone, *databaseService.Name) } // DeleteDatabaseService deletes a Database Service. func (c *Client) DeleteDatabaseService(ctx context.Context, zone string, databaseService *DatabaseService) error { _, err := c.TerminateDbaasServiceWithResponse(apiv2.WithZone(ctx, zone), *databaseService.Name) if err != nil { return err } return nil } // GetDatabaseService returns the Database Service corresponding to the specified name. func (c *Client) GetDatabaseService(ctx context.Context, zone, name string) (*DatabaseService, error) { resp, err := c.GetDbaasServiceWithResponse(apiv2.WithZone(ctx, zone), name) if err != nil { return nil, err } return databaseServiceFromAPI(resp.JSON200), nil } // ListDatabaseServices returns the list of Database Services. func (c *Client) ListDatabaseServices(ctx context.Context, zone string) ([]*DatabaseService, error) { list := make([]*DatabaseService, 0) resp, err := c.ListDbaasServicesWithResponse(apiv2.WithZone(ctx, zone)) if err != nil { return nil, err } if resp.JSON200.DbaasServices != nil { for i := range *resp.JSON200.DbaasServices { list = append(list, databaseServiceFromAPI(&(*resp.JSON200.DbaasServices)[i])) } } return list, nil } // UpdateDatabaseService updates a Database Service. func (c *Client) UpdateDatabaseService(ctx context.Context, zone string, databaseService *DatabaseService) error { _, err := c.UpdateDbaasServiceWithResponse( apiv2.WithZone(ctx, zone), *databaseService.Name, oapi.UpdateDbaasServiceJSONRequestBody{ Maintenance: func() (v *struct { Dow oapi.UpdateDbaasServiceJSONBodyMaintenanceDow `json:"dow"` Time string `json:"time"` }) { if databaseService.Maintenance != nil { v = &struct { Dow oapi.UpdateDbaasServiceJSONBodyMaintenanceDow `json:"dow"` Time string `json:"time"` }{ Dow: oapi.UpdateDbaasServiceJSONBodyMaintenanceDow(databaseService.Maintenance.DOW), Time: databaseService.Maintenance.Time, } } return }(), Plan: databaseService.Plan, TerminationProtection: databaseService.TerminationProtection, UserConfig: func() (v *oapi.UpdateDbaasServiceJSONBody_UserConfig) { if databaseService.UserConfig != nil { v = &oapi.UpdateDbaasServiceJSONBody_UserConfig{ AdditionalProperties: *databaseService.UserConfig, } } return }(), }) if err != nil { return err } return nil }
zenozeng/decision-tree-visualization
bower_components/p5.js/examples/addons/p5.sound/oscillatorMod_AM/sketch.js
/** * Example: Amplitude Modulation involves two oscillators, referred * to as the carrier and the modulator, where the modulator controls * the carrier's amplitude. * * The carrier is typically set at an audible frequency (i.e. 440 Hz) * and connected to master output by default. The carrier.amp is * set to zero because we will have the modulator control its amplitude. * * The modulator is typically set to a frequency that is lower than * humans can hear (i.e. 1 Hz, or one cycle every second). The modulator * is disconnected from master output. Instead, it is connected * to the amplitude of the Carrier, like this: carrier.amp(modulator). * * MouseX controls the amplitude of the modulator from 0 to 1. When the * modulator's amplitude is set to 0, the amplitude modulation has no effect. * * MouseY controls the frequency of the modulator from 0 to 20hz. * Both impact our perception of the Carrier frequency. A subtle amount * of Amplitude Modulation can simulate effects such as Tremolo. * Ring Modulation is a type of Amplitude Modulation where the original * carrier signal is not present. */ var carrier; // this is the oscillator we will hear var modulator; // this oscillator will modulate the amplitude of the carrier var fft; // we'll visualize the waveform function setup() { createCanvas(800,400); background(30); // alpha carrier = new p5.Oscillator(); // connects to master output by default carrier.freq(340); carrier.amp(0); // carrier's amp is 0 by default, giving our modulator total control carrier.start(); modulator = new p5.Oscillator('triangle'); modulator.disconnect(); // disconnect the modulator from master output modulator.freq(5); modulator.amp(1); modulator.start(); // Modulate the carrier's amplitude with the modulator // Optionally, we can scale the signal. carrier.amp(modulator.scale(-1,1,0,1)); // create an fft to analyze the audio fft = new p5.FFT(); } function draw() { background(30,30,30,100); // alpha // map mouseY to moodulator freq between 0 and 20hz var modFreq = map(mouseY, 0, height, 4, 0); //modFreq = 1.; modulator.freq(modFreq); var modAmp = map(mouseX, 0, width, 0, 1); modulator.amp(modAmp, 0.01); // fade time of 0.1 for smooth fading // analyze the waveform waveform = fft.waveform(); // draw the shape of the waveform stroke(240); strokeWeight(4); beginShape(); for (var i = 0; i<waveform.length; i++){ var x = map(i, 0, waveform.length, 0, width); var y = map(waveform[i], 0, 256, -height/2, height/2); vertex(x, y + height/2); } endShape(); }
DasNaCl/old-university-projects
cccc/tests/parser/declaration_spec.cpp
<gh_stars>0 #include <test_suite.hpp> #include <gtest/gtest.h> #define MYTEST(Y) TEST(parser_declarations, declaration_ ## Y) using namespace mhc4; static const std::string f = "declare.c"; const test_suite ts(f); MYTEST(identifier_int) { try { ts.parse_body("int a;", 6); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(identifier_char) { try { ts.parse_body("char a;", 7); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(identifier_void_negative) { try { ts.parse_body("void a;", 7); ASSERT_FALSE(true) << "Variables are not allowed to be void"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(type_int) { try { ts.parse_body("int;", 4); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(type_char) { try { ts.parse_body("char;", 5); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_decl_void_0) { try { ts.parse("void f();"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_decl_void_1) { try { ts.parse("void f(int);"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_decl_void_2) { try { ts.parse("void f(int asdasd);"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(complex_declarator_0) { try { ts.parse_body("char (*(*(*(*(*(*(*x)))))));"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(complex_declarator_1) { try { ts.parse_body("void** *** ** (** ** (*x));"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(type_void) { try { ts.parse_body("void;", 5); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_nameless) { try { ts.parse("int (int a) {return 0;} int main(){}"); ASSERT_FALSE(true) << "Function needs a name"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(function_type_int) { try { ts.parse("int foo(){} int main(){}", 24); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_type_char) { try { ts.parse("char foo(){} int main(){}", 25); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_type_void) { try { ts.parse("void foo(){} int main(){}", 25); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_parameter_0) { try { ts.parse("void foo(int i){} int main(){}", 30); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_parameter_1) { try { ts.parse("void foo(char c){} int main(){}", 31); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_parameter_2) { try { ts.parse("void foo(void){} int main(){}", 29); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } // 6.7.6.3 6 MYTEST(function_parameter_3) { try { ts.parse("void foo(int){} int main(){}", 28); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_parameter_negative_0) { try { ts.parse("void foo(void v){} int main(){}", 31); ASSERT_FALSE("true") << "It is not allowed to have a void variable"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(function_parameter_multiple_0) { try { ts.parse("void foo(int a, int b){} int main(){}", 37); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_parameter_multiple_1) { try { ts.parse("void foo(int a, char b){} int main(){}", 38); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(function_parameter_multiple_2) { try { ts.parse("void foo(int a, char b, int c, int d){} int main(){}", 52); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } //NOTE might be semantic test MYTEST(function_parameter_multiple_negative_0) { try { ts.parse("void foo(void, void){} int main(){}", 52); ASSERT_FALSE(true) << "If void is in the parameter list, no additional" "parameters are allowed"; } catch(std::exception& e) { ASSERT_TRUE(true); } } //NOTE might be semantic test MYTEST(function_parameter_multiple_negative_1) { try { ts.parse("void foo(void, int c){} int main(){}", 52); ASSERT_FALSE(true) << "If void is in the parameter list, no additional" "parameters are allowed"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(struct_0) { try { ts.parse_body("struct wall;"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(struct_1) { try { ts.parse_body("struct wall {int;};"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(struct_2) { try { ts.parse_body("struct wall {int a;};"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(struct_3) { try { ts.parse_body("struct wall {int a; char b; void;};"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(struct_4) { try { ts.parse_body("struct wall; struct mall {struct wall;};"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(struct_5) { try { ts.parse_body("struct {int;};"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(struct_6) { try { ts.parse_body("struct {struct wall;};"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(struct_7) { try { ts.parse_body("struct {struct wall {int a; char b;};};"); } catch(std::exception& e) { ASSERT_FALSE(true) << e.what(); } } MYTEST(struct_negative_0) { try { ts.parse_body("struct wall {int a;}"); ASSERT_FALSE(true) << "struct declarations require ; at the end"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(struct_negative_1) { try { ts.parse_body("struct wall {int a};"); ASSERT_FALSE(true) << "struct declarations require ; within after type declaration"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(struct_negative_2) { try { ts.parse_body("struct;"); ASSERT_FALSE(true) << "struct needs either an identifier or a body with declarations"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(struct_negative_3) { try { ts.parse_body("struct {};"); ASSERT_FALSE(true) << "struct body is not allowed to be empty"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(struct_negative_4) { try { ts.parse_body("struct wall {};"); ASSERT_FALSE(true) << "struct body is not allowed to be empty"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(struct_negative_5) { try { ts.parse_body("struct wall {void fun();};"); ASSERT_FALSE(true) << "function declarator is not allowed in struct"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(struct_negative_6) { try { ts.parse_body("struct wall {int fun();};"); ASSERT_FALSE(true) << "function declarator is not allowed in struct"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(struct_negative_7) { try { ts.parse_body("struct wall {char fun();};"); ASSERT_FALSE(true) << "function declarator is not allowed in struct"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(struct_negative_8) { try { ts.parse_body("struct wall {int* fun();};"); ASSERT_FALSE(true) << "function declarator is not allowed in struct"; } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(array_0) { try { // array of pointers to int values ts.parse_body("int *var[5];"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_TRUE(false); } } MYTEST(array_1) { try { // pointer to array of int values ts.parse_body("int (*var)[5];"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_TRUE(false); } } MYTEST(ptrfunc_0) { try { ts.parse_body("char *(*(*var)())[10];"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_TRUE(false); } } MYTEST(ptrfunc_1) { try { // function returning pointer to int ts.parse_body("int *var(int, int);"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_TRUE(false); } } MYTEST(ptrfunc_2) { try { // pointer to function returning int ts.parse_body("int (*var)(int, int);"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_TRUE(false); } } MYTEST(ptrfunc_3) { try { // function taking int and returning function pointer ts.parse_body("int (*f(int n))(int, int);"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_TRUE(false); } } MYTEST(ptrfunc_4) { try { ts.parse_body("int *(**name[5][10])(void);"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_TRUE(false); } } MYTEST(ptrfunc_5) { try { ts.parse("int (*p)(int (*));"); } catch(std::exception& e) { ASSERT_FALSE(true); } } MYTEST(ptrfunc_6) { // compare to ast test declarators try { ts.parse("int (*(*(*(*p(void))(int (*)))[5])(void));"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_FALSE(true); } } MYTEST(struct_as_ret) { try { // array of pointer to functions returning structures ts.parse_body( R"( struct test { int a; int b; char c; } (*var[5])(struct test, struct test); )"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_TRUE(false); } } MYTEST(struct_ptr_array_0) { try { // array of pointer to functions returning structures ts.parse_body( R"( struct test { int a; char c; } **var[5][42]; )"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_TRUE(false); } } MYTEST(struct_ptr_array_1) { try { // array of pointers to arrays of pointers to structs ts.parse_body("struct test *(*var[5])[5];"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_TRUE(false); } } MYTEST(directly_assign) { try { ts.parse("int a = 0;"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_TRUE(false); } } MYTEST(non_block) { try { ts.parse("int a[100];"); ASSERT_TRUE(true); } catch(std::exception& e) { ASSERT_FALSE(true); } } /* MYTEST(non_block_negative_0) { try { ts.parse("int a;\nint b[a];"); ASSERT_FALSE(true); } catch(std::exception& e) { ASSERT_TRUE(true); } } */ MYTEST(non_block_negative_0) { try { ts.parse_body( R"( if (1) int x; )" ); ASSERT_FALSE(true); } catch(std::exception& e) { ASSERT_TRUE(true); } } MYTEST(non_block_negative_1) { try { ts.parse_body( R"( if (1) 1; else int x; )" ); ASSERT_FALSE(true); } catch(std::exception& e) { ASSERT_TRUE(true); } }
caoren/react-asyncmodule
packages/react-asyncmodule-chunk/es/asyncchunk.js
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import { AsyncProvider } from './asynccontext'; var AsyncChunk = function AsyncChunk(props) { var children = props.children, providerValue = _objectWithoutProperties(props, ['children']); return React.createElement( AsyncProvider, { value: providerValue }, children ); }; export default AsyncChunk;
bxunzhao/Volley-Okhttp-Rebulid
DownloadLib/src/main/java/com/kronos/download/adapter/IModelObservable.java
package com.kronos.download.adapter; /** * Created by <NAME> on 16/8/18. * Email <EMAIL> */ public interface IModelObservable { void registerDataSetObserver(IObserver observer); void unregisterDataSetObserver(IObserver observer); void notifyDataChange(); void unregisterAll(); }