max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
2,151
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_WEB_PACKAGE_WEB_PACKAGE_CONTEXT_IMPL_H_ #define CONTENT_BROWSER_WEB_PACKAGE_WEB_PACKAGE_CONTEXT_IMPL_H_ #include "content/public/browser/web_package_context.h" #include "content/common/content_export.h" namespace content { class WebPackageContextImpl : public WebPackageContext { public: WebPackageContextImpl(); ~WebPackageContextImpl() override; void SetSignedExchangeVerificationTimeForTesting( base::Optional<base::Time> time) override; }; } // namespace content #endif // CONTENT_BROWSER_WEB_PACKAGE_WEB_PACKAGE_CONTEXT_IMPL_H_
257
374
<reponame>taylortaurus/seldom import seldom from seldom import data, file_data class BaiduTest(seldom.TestCase): """Baidu search test case""" @data([ (1, 'seldom'), (2, 'selenium'), (3, 'unittest'), ]) def test_baidu(self, name, search_key): """ used parameterized test :param name: case name :param search_key: search keyword """ self.open("https://www.baidu.com") self.type(id_="kw", text=search_key) self.click(css="#su") self.assertInTitle(search_key) class FileDataTest(seldom.TestCase): """form input test case""" def start(self): self.test_url = "https://www.w3school.com.cn/tiy/t.asp?f=eg_html_form_submit" @file_data("json_data.json", key="name") def test_json(self, firstname, lastname): """ used file_data test """ self.open(self.test_url) self.switch_to_frame(id_="iframeResult") self.type(name="firstname", text=firstname, clear=True) self.type(name="lastname", text=lastname, clear=True) self.sleep(1) @file_data("yaml_data.yaml", key="name") def test_yaml(self, firstname, lastname): """ used file_data test """ self.open(self.test_url) self.switch_to_frame(id_="iframeResult") self.type(name="firstname", text=firstname, clear=True) self.type(name="lastname", text=lastname, clear=True) self.sleep(1) @file_data("csv_data.csv", line=2) def test_csv(self, firstname, lastname): """ used file_data test """ self.open(self.test_url) self.switch_to_frame(id_="iframeResult") self.type(name="firstname", text=firstname, clear=True) self.type(name="lastname", text=lastname, clear=True) self.sleep(1) @file_data(file="excel_data.xlsx", sheet="Sheet1", line=2) def test_excel(self, firstname, lastname): """ used file_data test """ self.open(self.test_url) self.switch_to_frame(id_="iframeResult") self.type(name="firstname", text=firstname, clear=True) self.type(name="lastname", text=lastname, clear=True) self.sleep(1) if __name__ == '__main__': seldom.main(browser="ff", debug=True)
1,080
852
import FWCore.ParameterSet.Config as cms pythiaUESettingsBlock = cms.PSet( pythiaUESettings = cms.vstring( 'MSTU(21)=1 ! Check on possible errors during program execution', 'MSTJ(22)=2 ! Decay those unstable particles', 'PARJ(71)=10 . ! for which ctau 10 mm', 'MSTP(51) = 7 ! PDF set', 'MSTP(52) = 1 ! PDF set internal (=1) or pdflib (=2)', 'MSTP( 3) = 1 ! INT switch for choice of LambdaQCD', 'MSTU(112)= 5 ! INT n(flavors) for LambdaQCD', 'PARU(112)= 0.2600 ! INT LambdaQCD', 'PARP( 1) = 0.2600 ! ME/UE LambdaQCD', 'PARJ(81) = 0.2600 ! FSR LambdaQCD (inside resonance decays)', 'PARP(72) = 0.2600 ! IFSR LambdaQCD (outside resonance decays', 'PARP(61) = 0.2600 ! ISR LambdaQCD', 'MSTP(64) = 2 ! ISR alphaS type', 'PARP(64) = 1.0000 ! ISR renormalization scale prefactor', 'MSTP(67) = 2 ! ISR coherence option for 1st emission', 'MSTP(68) = 3 ! ISR phase space choice & ME corrections', 'PARP(67) = 1.0000 ! ISR Q2max factor', 'MSTP(72) = 2 ! IFSR scheme for non-decay FSR', 'PARP(71) = 1.0000 ! IFSR Q2max factor in non-s-channel procs', 'MSTP(70) = 0 ! ISR IR regularization scheme', 'PARP(62) = 1.5000 ! ISR IR cutoff', 'PARJ(82) = 1.0000 ! FSR IR cutoff', 'MSTP(33) = 0 ! "K" switch for K-factor on/off & type', 'MSTP(81) = 21 ! UE model', 'PARP(82) = 3.3500 ! UE IR cutoff at reference ecm', 'PARP(89) = 7000.0 ! UE IR cutoff reference ecm', 'PARP(90) = 0.2600 ! UE IR cutoff ecm scaling power', 'MSTP(82) = 3 ! UE hadron transverse mass distribution', 'MSTP(88) = 0 ! BR composite scheme', 'MSTP(89) = 0 ! BR color scheme', 'PARP(79) = 2.0000 ! BR composite x enhancement', 'PARP(80) = 0.0150 ! BR breakup suppression', 'MSTP(91) = 1 ! BR primordial kT distribution', 'PARP(91) = 1.0000 ! BR primordial kT width <|kT|>', 'PARP(93) = 10.0000 ! BR primordial kT UV cutoff', 'MSTP(95) = 8 ! FSI color (re-)connection model', 'PARP(78) = 0.0360 ! FSI color reconnection strength', 'PARP(77) = 1.0000 ! FSI color reco high-pT damping strength', 'MSTJ(11) = 5 ! HAD choice of fragmentation function(s)', 'PARJ( 1) = 0.0870 ! HAD diquark suppression', 'PARJ( 2) = 0.1900 ! HAD strangeness suppression', 'PARJ( 3) = 0.9500 ! HAD strange diquark suppression', 'PARJ( 4) = 0.0430 ! HAD vector diquark suppression', 'PARJ( 5) = 0.5000 ! HAD P(popcorn)', 'PARJ( 6) = 1.0000 ! HAD extra popcorn B(s)-M-B(s) supp', 'PARJ( 7) = 1.0000 ! HAD extra popcorn B-M(s)-B supp', 'PARJ(11) = 0.3500 ! HAD P(vector meson), u and d only', 'PARJ(12) = 0.4000 ! HAD P(vector meson), contains s', 'PARJ(13) = 0.5400 ! HAD P(vector meson), heavy quarks', 'PARJ(21) = 0.3300 ! HAD fragmentation pT', 'PARJ(25) = 0.6300 ! HAD eta0 suppression', 'PARJ(26) = 0.1200 ! HAD eta0prim suppression', 'PARJ(41) = 0.3500 ! HAD string parameter a(Meson)', 'PARJ(42) = 0.8000 ! HAD string parameter b', 'PARJ(45) = 0.5500 ! HAD string a(Baryon)-a(Meson)', 'PARJ(46) = 1.0000 ! HAD Lund(=0)-Bowler(=1) rQ (rc)', 'PARJ(47) = 1.0000 ! HAD Lund(=0)-Bowler(=1) rb',) )
1,958
443
<reponame>vault-the/changes from __future__ import absolute_import, division, unicode_literals from collections import defaultdict from flask.ext.restful import reqparse from sqlalchemy import or_ from sqlalchemy.orm import joinedload from sqlalchemy.sql import func from changes.api.base import APIView, error from changes.api.auth import get_current_user, user_has_project_permission from changes.config import db, statsreporter from changes.constants import Result, Status, ProjectStatus from changes.lib import build_type from changes.models.project import Project, ProjectOption from changes.models.repository import Repository from changes.models.build import Build from changes.models.source import Source from changes.models.plan import Plan, PlanStatus STATUS_CHOICES = ('', 'active', 'inactive') SORT_CHOICES = ('name', 'date') def get_latest_builds_query(project_ids, result=None): build_query = db.session.query( Build.id, ).join( Source, Build.source_id == Source.id, ).filter( Build.status == Status.finished, Build.result.in_([Result.passed, Result.failed, Result.infra_failed]), *build_type.get_any_commit_build_filters() ).order_by( Build.date_created.desc(), ) if result: build_query = build_query.filter( Build.result == result, ) # TODO(dcramer): we dont actually need the project table here build_map = dict(db.session.query( Project.id, build_query.filter( Build.project_id == Project.id, ).limit(1).as_scalar(), ).filter( Project.id.in_(project_ids), )) return list(Build.query.filter( Build.id.in_(build_map.values()), ).options( joinedload('author'), joinedload('source').joinedload('revision'), )) class ProjectIndexAPIView(APIView): get_parser = reqparse.RequestParser() get_parser.add_argument('query', type=unicode, location='args') get_parser.add_argument('status', type=unicode, location='args', choices=STATUS_CHOICES, default='active') get_parser.add_argument('sort', type=unicode, location='args', choices=SORT_CHOICES, default='name') # grabs extra data to show a richer ui in the new changes ui get_parser.add_argument('fetch_extra', type=unicode, location='args', default=0) post_parser = reqparse.RequestParser() post_parser.add_argument('name', type=unicode, required=True) post_parser.add_argument('slug', type=str) post_parser.add_argument('repository', type=unicode, required=True) def get(self): args = self.get_parser.parse_args() # This project index generation is a prerequisite for rendering # the homepage and the admin page; worth tracking both for user # experience and to keep an eye on database responsiveness. with statsreporter.stats().timer('generate_project_index'): queryset = Project.query if args.query: queryset = queryset.filter( or_( func.lower(Project.name).contains(args.query.lower()), func.lower(Project.slug).contains(args.query.lower()), ), ) if args.status: queryset = queryset.filter( Project.status == ProjectStatus[args.status] ) if args.sort == 'name': queryset = queryset.order_by(Project.name.asc()) elif args.sort == 'date': queryset = queryset.order_by(Project.date_created.asc()) plans = [] if args.fetch_extra: queryset = queryset.options( joinedload(Project.repository, innerjoin=True) ) # fetch plans separately to avoid many lazy database fetches plans_list = self.serialize(list(Plan.query.filter( Plan.status == PlanStatus.active ).options( joinedload(Plan.steps) ))) plans = defaultdict(list) for p in plans_list: plans[p['project_id']].append(p) # we could use the option names whitelist from # project_details.py options_list = list(ProjectOption.query) options_dict = defaultdict(dict) for o in options_list: options_dict[o.project_id][o.name] = o.value project_list = list(queryset) context = [] if project_list: latest_build_results = get_latest_builds_query(p.id for p in project_list) projects_missing_passing_build = [] for build in latest_build_results: if build.result != Result.passed: projects_missing_passing_build.append(build.project_id) if projects_missing_passing_build: extra_passing_build_results = get_latest_builds_query( projects_missing_passing_build, result=Result.passed, ) else: extra_passing_build_results = [] # serialize as a group for more effective batching serialized_builds = self.serialize(latest_build_results + extra_passing_build_results) serialized_latest_builds = serialized_builds[:len(latest_build_results)] serialized_extra_passing_builds = serialized_builds[-len(extra_passing_build_results):] latest_build_map = dict( zip([b.project_id for b in latest_build_results], serialized_latest_builds) ) passing_build_map = {} for build in latest_build_results: if build.result == Result.passed: passing_build_map[build.project_id] = latest_build_map.get(build.project_id) else: passing_build_map[build.project_id] = None passing_build_map.update( zip([b.project_id for b in extra_passing_build_results], serialized_extra_passing_builds) ) if args.fetch_extra: repo_ids = set() repos = [] for project in project_list: if project.repository_id not in repo_ids: repos.append(project.repository) repo_ids.add(project.repository) repo_dict = dict( zip([repo.id for repo in repos], self.serialize(repos)) ) for project, data in zip(project_list, self.serialize(project_list)): data['lastBuild'] = latest_build_map.get(project.id) data['lastPassingBuild'] = passing_build_map.get(project.id) if args.fetch_extra: data['repository'] = repo_dict[project.repository_id] data['options'] = options_dict[project.id] # we have to use the serialized version of the id data['plans'] = plans[data['id']] context.append(data) return self.respond(context, serialize=False) def post(self): user = get_current_user() if user is None: return error('Not logged in.', http_code=401) args = self.post_parser.parse_args() slug = str(args.slug or args.name.replace(' ', '-').lower()) if not user_has_project_permission(user, slug): return error('User does not have permission to create a project with slug {}.'.format(slug), http_code=403) match = Project.query.filter( Project.slug == slug, ).first() if match: return error('Project with slug {} already exists.'.format(slug), http_code=400) repository = Repository.get(args.repository) if repository is None: return error('Repository with url {} does not exist.'.format(args.repository), http_code=400) project = Project( name=args.name, slug=slug, repository=repository, ) db.session.add(project) db.session.commit() return self.respond(project)
4,102
348
{"nom":"<NAME>","circ":"3ème circonscription","dpt":"Haute-Vienne","inscrits":133,"abs":43,"votants":90,"blancs":7,"nuls":4,"exp":79,"res":[{"nuance":"LR","nom":"<NAME>","voix":46},{"nuance":"REM","nom":"<NAME>","voix":33}]}
91
3,799
<reponame>semoro/androidx<filename>camera/camera-camera2/src/test/java/androidx/camera/camera2/internal/SynchronizedCaptureSessionBaseTest.java /* * Copyright 2020 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 androidx.camera.camera2.internal; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CaptureRequest; import android.os.Build; import android.os.Handler; import android.view.Surface; import androidx.camera.camera2.internal.compat.params.OutputConfigurationCompat; import androidx.camera.camera2.internal.compat.params.SessionConfigurationCompat; import androidx.camera.core.impl.ImmediateSurface; import androidx.camera.core.impl.utils.executor.CameraXExecutors; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.annotation.internal.DoNotInstrument; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @SuppressWarnings({"deprecation", "unchecked"}) @RunWith(RobolectricTestRunner.class) @DoNotInstrument @Config(minSdk = Build.VERSION_CODES.LOLLIPOP, instrumentedPackages = { "androidx.camera.camera2.internal.compat.params" }) public class SynchronizedCaptureSessionBaseTest { private static final int NUM_OUTPUTS = 3; private CameraCaptureSession mMockCaptureSession; private SynchronizedCaptureSession.StateCallback mMockStateCallback; private List<OutputConfigurationCompat> mOutputs; private SynchronizedCaptureSessionBaseImpl mSyncCaptureSessionBaseImpl; private CaptureSessionRepository mMockCaptureSessionRepository; private ScheduledExecutorService mScheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); @Before public void setUp() { mMockCaptureSessionRepository = mock(CaptureSessionRepository.class); mSyncCaptureSessionBaseImpl = new SynchronizedCaptureSessionBaseImpl(mMockCaptureSessionRepository, CameraXExecutors.directExecutor(), mScheduledExecutorService, mock(Handler.class)); mMockCaptureSession = mock(CameraCaptureSession.class); mMockStateCallback = mock(SynchronizedCaptureSession.StateCallback.class); mOutputs = new ArrayList<>(NUM_OUTPUTS); for (int i = 0; i < NUM_OUTPUTS; ++i) { mOutputs.add(mock(OutputConfigurationCompat.class)); } } @Test public void callbackShouldWork_onReady() { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); sessionConfigurationCompat.getStateCallback().onReady(mMockCaptureSession); verify(mMockStateCallback).onReady(any(SynchronizedCaptureSession.class)); } @Test public void callbackShouldWork_onActive() { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); sessionConfigurationCompat.getStateCallback().onActive(mMockCaptureSession); verify(mMockStateCallback).onActive(any(SynchronizedCaptureSession.class)); } @Test @Config(minSdk = Build.VERSION_CODES.O) public void callbackShouldWork_onCaptureQueueEmpty() { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); sessionConfigurationCompat.getStateCallback().onCaptureQueueEmpty(mMockCaptureSession); verify(mMockStateCallback).onCaptureQueueEmpty(any(SynchronizedCaptureSession.class)); } @Test @Config(minSdk = Build.VERSION_CODES.M) public void callbackShouldWork_onSurfacePrepared() { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); sessionConfigurationCompat.getStateCallback().onSurfacePrepared(mMockCaptureSession, mock(Surface.class)); verify(mMockStateCallback).onSurfacePrepared(any(SynchronizedCaptureSession.class), any(Surface.class)); } @Test public void callbackShouldWork_onConfigured() { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigured(mMockCaptureSession); verify(mMockStateCallback).onConfigured(any(SynchronizedCaptureSession.class)); verify(mMockCaptureSessionRepository, times(1)).onCaptureSessionCreated( any(SynchronizedCaptureSession.class)); } @Test public void callbackShouldWork_onConfigureFailed() { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigureFailed(mMockCaptureSession); verify(mMockStateCallback).onConfigureFailed(any(SynchronizedCaptureSession.class)); } @Test public void callbackShouldWork_onClosed() { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigured(mMockCaptureSession); sessionConfigurationCompat.getStateCallback().onClosed(mMockCaptureSession); verify(mMockStateCallback).onClosed(any(SynchronizedCaptureSession.class)); verify(mMockCaptureSessionRepository, times(1)).onCaptureSessionClosed( any(SynchronizedCaptureSession.class)); } @Test public void callClose_onSessionFinished_shouldBeCalled() { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigured(mMockCaptureSession); mSyncCaptureSessionBaseImpl.close(); verify(mMockStateCallback).onSessionFinished( any(SynchronizedCaptureSession.class)); } @Test public void callbackShouldWork_onSessionFinished() { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigured(mMockCaptureSession); sessionConfigurationCompat.getStateCallback().onClosed(mMockCaptureSession); verify(mMockStateCallback).onSessionFinished( any(SynchronizedCaptureSession.class)); } @Test public void shouldForwardAfterOnConfigured() throws CameraAccessException { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigured(mMockCaptureSession); mSyncCaptureSessionBaseImpl.captureSingleRequest(mock(CaptureRequest.class), mock(CameraCaptureSession.CaptureCallback.class)); } @Test public void forwardBeforeOnConfigured_captureBurstRequests() throws CameraAccessException { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigured(mMockCaptureSession); mSyncCaptureSessionBaseImpl.captureBurstRequests(mock(List.class), mock(CameraCaptureSession.CaptureCallback.class)); } @Test public void forwardBeforeOnConfigured_setRepeatingBurstRequests() throws CameraAccessException { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigured(mMockCaptureSession); mSyncCaptureSessionBaseImpl.setRepeatingBurstRequests(mock(List.class), mock(CameraCaptureSession.CaptureCallback.class)); } @Test public void forwardBeforeOnConfigured_setSingleRepeatingRequest() throws CameraAccessException { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigured(mMockCaptureSession); mSyncCaptureSessionBaseImpl.setSingleRepeatingRequest(mock(CaptureRequest.class), mock(CameraCaptureSession.CaptureCallback.class)); } @Test public void forwardBeforeOnConfigured_abortCaptures() throws CameraAccessException { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigured(mMockCaptureSession); mSyncCaptureSessionBaseImpl.abortCaptures(); } @Test public void forwardBeforeOnConfigured_stopRepeating() throws CameraAccessException { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigured(mMockCaptureSession); mSyncCaptureSessionBaseImpl.stopRepeating(); } @Test public void forwardBeforeOnConfigured_getDevice() { SessionConfigurationCompat sessionConfigurationCompat = mSyncCaptureSessionBaseImpl.createSessionConfigurationCompat( SessionConfigurationCompat.SESSION_REGULAR, mOutputs, mMockStateCallback); mSyncCaptureSessionBaseImpl.openCaptureSession(mock(CameraDevice.class), sessionConfigurationCompat, Arrays.asList(new ImmediateSurface(mock(Surface.class)))); sessionConfigurationCompat.getStateCallback().onConfigured(mMockCaptureSession); mSyncCaptureSessionBaseImpl.getDevice(); } @Test(expected = NullPointerException.class) public void notForwardBeforeOnConfigured_captureSingleRequest() throws CameraAccessException { mSyncCaptureSessionBaseImpl.captureSingleRequest(mock(CaptureRequest.class), mock(CameraCaptureSession.CaptureCallback.class)); } @Test(expected = NullPointerException.class) public void notForwardBeforeOnConfigured_captureBurstRequests() throws CameraAccessException { mSyncCaptureSessionBaseImpl.captureBurstRequests(mock(List.class), mock(CameraCaptureSession.CaptureCallback.class)); } @Test(expected = NullPointerException.class) public void notForwardBeforeOnConfigured_setRepeatingBurstRequests() throws CameraAccessException { mSyncCaptureSessionBaseImpl.setRepeatingBurstRequests(mock(List.class), mock(CameraCaptureSession.CaptureCallback.class)); } @Test(expected = NullPointerException.class) public void notForwardBeforeOnConfigured_setSingleRepeatingRequest() throws CameraAccessException { mSyncCaptureSessionBaseImpl.setSingleRepeatingRequest(mock(CaptureRequest.class), mock(CameraCaptureSession.CaptureCallback.class)); } @Test(expected = NullPointerException.class) public void notForwardBeforeOnConfigured_abortCaptures() throws CameraAccessException { mSyncCaptureSessionBaseImpl.abortCaptures(); } @Test(expected = NullPointerException.class) public void notForwardBeforeOnConfigured_stopRepeating() throws CameraAccessException { mSyncCaptureSessionBaseImpl.stopRepeating(); } @Test(expected = NullPointerException.class) public void notForwardBeforeOnConfigured_getDevice() { mSyncCaptureSessionBaseImpl.getDevice(); } }
6,699
526
<reponame>rychagova/egeria /* * SPDX-License-Identifier: Apache-2.0 * Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.accessservices.securityofficer.api.events; import java.io.Serializable; public enum SecurityOfficerEventType implements Serializable { NEW_SECURITY_ASSIGNMENT(0, "NewSecurityAssignment", "A Security Tags assigment should be processed."), UPDATED_SECURITY_ASSIGNMENT(1, "UpdatedSecurityAssigment", "A Security Tags assignment has been updated for schema element."), DELETED_SECURITY_ASSIGNMENT(2, "DeletedSecurityAssigment", "A Security Tags assignment has been deleted from schema element."), NEW_CLASSIFIED_ASSET(3, "ClassifiedAsset", "A governed classification has been assigned to an asset."), RE_CLASSIFIED_ASSET(4, "ReClassifiedAsset", "A classification has been changed for governed asset."), DE_CLASSIFIED_ASSET(5, "DeClassifiedAsset", "A classification has been deleted for governed asset."), DELETED_ASSET(6, "DeletedAsset", "A governed asset has been deleted."), UNKNOWN_SECURITY_OFFICER_EVENT(100, "UnknownSecurityOfficerEvent", "A Security Officer event that is not recognized by the local handlers."); private static final long serialVersionUID = 1L; private int eventTypeCode; private String eventTypeName; private String eventTypeDescription; /** * Default Constructor - sets up the specific values for this instance of the enum. * * @param eventTypeCode int identifier used for indexing based on the enum. * @param eventTypeName string name used for messages that include the enum. * @param eventTypeDescription default description for the enum value - used when natural resource * bundle is not available. */ SecurityOfficerEventType(int eventTypeCode, String eventTypeName, String eventTypeDescription) { this.eventTypeCode = eventTypeCode; this.eventTypeName = eventTypeName; this.eventTypeDescription = eventTypeDescription; } /** * Return the int identifier used for indexing based on the enum. * * @return int identifier code */ public int getEventTypeCode() { return eventTypeCode; } /** * Return the string name used for messages that include the enum. * * @return String name */ public String getEventTypeName() { return eventTypeName; } /** * Return the default description for the enum value - used when natural resource * bundle is not available. * * @return String default description */ public String getEventTypeDescription() { return eventTypeDescription; } }
895
6,958
<reponame>xhuan28/MNN<filename>pymnn/pip_package/MNN/data/__init__.py<gh_stars>1000+ from _mnncengine._data import *
52
318
package com.greetings; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class Main { public static void main(String[] args) { Map<Integer, String> myMap = new ConcurrentHashMap<>(); myMap.put(1, "one"); myMap.put(2, "two"); myMap.put(3, "three"); System.out.println("Hello " + myMap); } }
156
2,151
<reponame>zipated/src<filename>third_party/angle/src/libANGLE/ContextState.h // // Copyright (c) 2014 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ContextState: Container class for all GL context state, caps and objects. #ifndef LIBANGLE_CONTEXTSTATE_H_ #define LIBANGLE_CONTEXTSTATE_H_ #include "common/MemoryBuffer.h" #include "common/angleutils.h" #include "libANGLE/State.h" #include "libANGLE/Version.h" #include "libANGLE/params.h" namespace gl { class BufferManager; class ContextState; class FramebufferManager; class PathManager; class ProgramPipelineManager; class RenderbufferManager; class SamplerManager; class ShaderProgramManager; class SyncManager; class TextureManager; static constexpr Version ES_2_0 = Version(2, 0); static constexpr Version ES_3_0 = Version(3, 0); static constexpr Version ES_3_1 = Version(3, 1); using ContextID = uintptr_t; class ContextState final : angle::NonCopyable { public: ContextState(ContextID context, const ContextState *shareContextState, TextureManager *shareTextures, const Version &clientVersion, State *state, const Caps &caps, const TextureCapsMap &textureCaps, const Extensions &extensions, const Limitations &limitations); ~ContextState(); ContextID getContextID() const { return mContext; } GLint getClientMajorVersion() const { return mClientVersion.major; } GLint getClientMinorVersion() const { return mClientVersion.minor; } const Version &getClientVersion() const { return mClientVersion; } const State &getState() const { return *mState; } const Caps &getCaps() const { return mCaps; } const TextureCapsMap &getTextureCaps() const { return mTextureCaps; } const Extensions &getExtensions() const { return mExtensions; } const Limitations &getLimitations() const { return mLimitations; } const TextureCaps &getTextureCap(GLenum internalFormat) const; bool isWebGL() const; bool isWebGL1() const; private: friend class Context; Version mClientVersion; ContextID mContext; State *mState; const Caps &mCaps; const TextureCapsMap &mTextureCaps; const Extensions &mExtensions; const Limitations &mLimitations; BufferManager *mBuffers; ShaderProgramManager *mShaderPrograms; TextureManager *mTextures; RenderbufferManager *mRenderbuffers; SamplerManager *mSamplers; SyncManager *mSyncs; PathManager *mPaths; FramebufferManager *mFramebuffers; ProgramPipelineManager *mPipelines; }; } // namespace gl #endif // LIBANGLE_CONTEXTSTATE_H_
984
320
<gh_stars>100-1000 // Copyright (c) 2015, <NAME>. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) // // Key Storage Format (24 bits): // // 0111 1111 0000 0001 1111 1111 // ---- ---- --------- --------- // | | | | // | | | \--- MS Virtual Keys (VK_*) // | | | // | | \--- Extended key bit (used for converting HKs to strings) // | | // | \--- bitfield: [win, shift, control, alt] // | // \--- xbutton2, xbutton1, wheelup, wheeldown // #pragma once #include <Windows.h> #include <unordered_map> #include <unordered_set> #define EXT_OFFSET 8 #define MOD_OFFSET 16 #define MOUSE_OFFSET 20 #define HKM_MOD_ALT (MOD_ALT << MOD_OFFSET) #define HKM_MOD_CTRL (MOD_CONTROL << MOD_OFFSET) #define HKM_MOD_SHF (MOD_SHIFT << MOD_OFFSET) #define HKM_MOD_WIN (MOD_WIN << MOD_OFFSET) #define HKM_MOUSE_WHUP (0x1 << MOUSE_OFFSET) #define HKM_MOUSE_WHDN (0x2 << MOUSE_OFFSET) #define HKM_MOUSE_XB1 (0x3 << MOUSE_OFFSET) #define HKM_MOUSE_XB2 (0x4 << MOUSE_OFFSET) class HotkeyManager { public: static HotkeyManager *Instance(); static HotkeyManager *Instance(HWND notifyWnd); void Register(int keyCombination); bool Unregister(int keyCombination); void Shutdown(); public: static int IsModifier(int vk); static bool IsMouseKey(int vk); static int Modifiers(); static int ModifiersAsync(); static std::wstring HotkeysToModString(int combination, std::wstring separator = L" + "); static std::wstring HotkeysToString(int combination, std::wstring separator = L" + "); static std::wstring MouseString(int combination); static std::wstring VKToString(unsigned int vk, bool extendedKey = false); static void VKStringTest(); private: HotkeyManager(); ~HotkeyManager(); static std::unordered_map<UINT, std::wstring> _vkStringMap; HWND _notifyWnd; int _fixWin; std::unordered_set<int> _keyCombinations; std::unordered_set<int> _hookCombinations; int _modifiers; HHOOK _keyHook; HHOOK _mouseHook; bool Hook(); bool Unhook(); LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK KeyProc(int nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam); static HotkeyManager *instance; };
1,044
14,668
<filename>chrome/browser/web_applications/web_app_icon_downloader.cc // Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/web_applications/web_app_icon_downloader.h" #include "base/bind.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/web_applications/web_app_constants.h" #include "chrome/browser/web_applications/web_app_helpers.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" #include "third_party/blink/public/mojom/favicon/favicon_url.mojom.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/size.h" namespace web_app { WebAppIconDownloader::WebAppIconDownloader( content::WebContents* web_contents, const std::vector<GURL>& extra_favicon_urls, WebAppIconDownloaderCallback callback) : content::WebContentsObserver(web_contents), need_favicon_urls_(true), fail_all_if_any_fail_(false), extra_favicon_urls_(extra_favicon_urls), callback_(std::move(callback)) {} WebAppIconDownloader::~WebAppIconDownloader() = default; void WebAppIconDownloader::SkipPageFavicons() { need_favicon_urls_ = false; } void WebAppIconDownloader::FailAllIfAnyFail() { fail_all_if_any_fail_ = true; } void WebAppIconDownloader::Start() { // Favicons are supported only in HTTP or HTTPS WebContents. const GURL& url = web_contents()->GetLastCommittedURL(); if (!url.is_empty() && !url.inner_url() && !url.SchemeIsHTTPOrHTTPS()) SkipPageFavicons(); // If the candidates aren't loaded, icons will be fetched when // DidUpdateFaviconURL() is called. FetchIcons(extra_favicon_urls_); if (need_favicon_urls_) { // The call to `GetFaviconURLsFromWebContents()` is to allow this method to // be mocked by unit tests. const auto& favicon_urls = GetFaviconURLsFromWebContents(); if (!favicon_urls.empty()) { need_favicon_urls_ = false; FetchIcons(favicon_urls); } } } int WebAppIconDownloader::DownloadImage(const GURL& url) { // If |is_favicon| is true, the cookies are not sent and not accepted during // download. return web_contents()->DownloadImage( url, true, // is_favicon gfx::Size(), // no preferred size 0, // no max size false, // normal cache policy base::BindOnce(&WebAppIconDownloader::DidDownloadFavicon, weak_ptr_factory_.GetWeakPtr())); } const std::vector<blink::mojom::FaviconURLPtr>& WebAppIconDownloader::GetFaviconURLsFromWebContents() { return web_contents()->GetFaviconURLs(); } void WebAppIconDownloader::FetchIcons( const std::vector<blink::mojom::FaviconURLPtr>& favicon_urls) { std::vector<GURL> urls; for (const auto& favicon_url : favicon_urls) { if (favicon_url->icon_type != blink::mojom::FaviconIconType::kInvalid) urls.push_back(favicon_url->icon_url); } FetchIcons(urls); } void WebAppIconDownloader::FetchIcons(const std::vector<GURL>& urls) { // Download icons; put their download ids into |in_progress_requests_| and // their urls into |processed_urls_|. for (const GURL& url : urls) { // Only start the download if the url hasn't been processed before. if (processed_urls_.insert(url).second) in_progress_requests_.insert(DownloadImage(url)); } // If no downloads were initiated, we can proceed directly to running the // callback. if (in_progress_requests_.empty() && !need_favicon_urls_) CompleteCallback(); } void WebAppIconDownloader::DidDownloadFavicon( int id, int http_status_code, const GURL& image_url, const std::vector<SkBitmap>& bitmaps, const std::vector<gfx::Size>& original_bitmap_sizes) { // Request may have been canceled by PrimaryPageChanged(). if (in_progress_requests_.erase(id) == 0) return; if (http_status_code != 0) { DCHECK_LE(100, http_status_code); DCHECK_GT(600, http_status_code); icons_http_results_[image_url] = http_status_code; } if (fail_all_if_any_fail_ && bitmaps.empty()) { // Reports http status code for the failure. CancelDownloads(IconsDownloadedResult::kAbortedDueToFailure, std::move(icons_http_results_)); return; } icons_map_[image_url] = bitmaps; // Once all requests have been resolved, perform post-download tasks. if (in_progress_requests_.empty() && !need_favicon_urls_) CompleteCallback(); } void WebAppIconDownloader::PrimaryPageChanged(content::Page& page) { CancelDownloads(IconsDownloadedResult::kPrimaryPageChanged, DownloadedIconsHttpResults{}); } void WebAppIconDownloader::DidUpdateFaviconURL( content::RenderFrameHost* rfh, const std::vector<blink::mojom::FaviconURLPtr>& candidates) { // Only consider the first candidates we are given. This prevents pages that // change their favicon from spamming us. if (!need_favicon_urls_) return; need_favicon_urls_ = false; FetchIcons(candidates); } void WebAppIconDownloader::CompleteCallback() { DCHECK(callback_); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback_), IconsDownloadedResult::kCompleted, std::move(icons_map_), std::move(icons_http_results_))); } void WebAppIconDownloader::CancelDownloads( IconsDownloadedResult result, DownloadedIconsHttpResults icons_http_results) { DCHECK_NE(result, IconsDownloadedResult::kCompleted); in_progress_requests_.clear(); icons_map_.clear(); icons_http_results_.clear(); if (callback_) { std::move(callback_).Run(result, IconsMap{}, std::move(icons_http_results)); } } } // namespace web_app
2,197
511
<reponame>timgates42/untangle<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import untangle import xml class FromStringTestCase(unittest.TestCase): """ Basic parsing tests with input as string """ def test_basic(self): o = untangle.parse("<a><b/><c/></a>") self.assertTrue(o is not None) self.assertTrue(o.a is not None) self.assertTrue(o.a.b is not None) self.assertTrue(o.a.c is not None) self.assertTrue("a" in o) self.assertTrue("b" in o.a) self.assertTrue("c" in o.a) self.assertTrue("d" not in o.a) def test_basic_with_decl(self): o = untangle.parse("<?xml version='1.0'?><a><b/><c/></a>") self.assertTrue(o is not None) self.assertTrue(o.a is not None) self.assertTrue(o.a.b is not None) self.assertTrue(o.a.c is not None) self.assertTrue("a" in o) self.assertTrue("b" in o.a) self.assertTrue("c" in o.a) self.assertTrue("d" not in o.a) def test_with_attributes(self): o = untangle.parse( """ <Soup name="Tomato soup" version="1"> <Ingredients> <Water qty="1l" /> <Tomatoes qty="1kg" /> <Salt qty="1tsp" /> </Ingredients> <Instructions> <boil-water/> <add-ingredients/> <done/> </Instructions> </Soup> """ ) self.assertEqual("Tomato soup", o.Soup["name"]) self.assertEqual(1, int(o.Soup["version"])) self.assertEqual("1l", o.Soup.Ingredients.Water["qty"]) self.assertTrue(o.Soup.Instructions.add_ingredients is not None) def test_grouping(self): o = untangle.parse( """ <root> <child name="child1"> <subchild name="sub1"/> </child> <child name="child2"/> <child name="child3"> <subchild name="sub2"/> <subchild name="sub3"/> </child> </root> """ ) self.assertTrue(o.root) children = o.root.child self.assertEqual(3, len(children)) self.assertEqual("child1", children[0]["name"]) self.assertEqual("sub1", children[0].subchild["name"]) self.assertEqual(2, len(children[2].subchild)) self.assertEqual("sub2", children[2].subchild[0]["name"]) def test_single_root(self): self.assertTrue(untangle.parse("<single_root_node/>")) def test_attribute_protocol(self): o = untangle.parse( """ <root> <child name="child1"> <subchild name="sub1"/> </child> <child name="child2"/> <child name="child3"> <subchild name="sub2"/> <subchild name="sub3"/> </child> </root> """ ) try: self.assertEqual(None, o.root.child.inexistent) self.fail("Was able to access inexistent child as None") except AttributeError: pass # this is the expected error except IndexError: self.fail("Caught IndexError quen expecting AttributeError") self.assertTrue(hasattr(o.root, "child")) self.assertFalse(hasattr(o.root, "inexistent")) self.assertEqual("child1", getattr(o.root, "child")[0]["name"]) def test_python_keyword(self): o = untangle.parse("<class><return/><pass/><None/></class>") self.assertTrue(o is not None) self.assertTrue(o.class_ is not None) self.assertTrue(o.class_.return_ is not None) self.assertTrue(o.class_.pass_ is not None) self.assertTrue(o.class_.None_ is not None) class InvalidTestCase(unittest.TestCase): """ Test corner cases """ def test_invalid_xml(self): self.assertRaises(xml.sax.SAXParseException, untangle.parse, "<unclosed>") def test_empty_xml(self): self.assertRaises(ValueError, untangle.parse, "") def test_none_xml(self): self.assertRaises(ValueError, untangle.parse, None) class PomXmlTestCase(unittest.TestCase): """ Tests parsing a Maven pom.xml """ def setUp(self): self.o = untangle.parse("tests/res/pom.xml") def test_parent(self): project = self.o.project self.assertTrue(project) parent = project.parent self.assertTrue(parent) self.assertEqual("com.atlassian.confluence.plugin.base", parent.groupId) self.assertEqual("confluence-plugin-base", parent.artifactId) self.assertEqual("17", parent.version) self.assertEqual("4.0.0", project.modelVersion) self.assertEqual("com.this.that.groupId", project.groupId) self.assertEqual("", project.name) self.assertEqual( "${pom.groupId}.${pom.artifactId}", project.properties.atlassian_plugin_key ) self.assertEqual("1.4.1", project.properties.atlassian_product_test_lib_version) self.assertEqual("2.9", project.properties.atlassian_product_data_version) def test_lengths(self): self.assertEqual(1, len(self.o)) self.assertEqual(8, len(self.o.project)) self.assertEqual(3, len(self.o.project.parent)) self.assertEqual(4, len(self.o.project.properties)) class NamespaceTestCase(unittest.TestCase): """ Tests for XMLs with namespaces """ def setUp(self): self.o = untangle.parse("tests/res/some.xslt") def test_namespace(self): self.assertTrue(self.o) stylesheet = self.o.xsl_stylesheet self.assertTrue(stylesheet) self.assertEqual("1.0", stylesheet["version"]) template = stylesheet.xsl_template[0] self.assertTrue(template) self.assertEqual("math", template["match"]) self.assertEqual("compact", template.table["class"]) self.assertEqual("compact vam", template.table.tr.xsl_for_each.td["class"]) self.assertEqual( untangle.Element("", ""), template.table.tr.xsl_for_each.td.xsl_apply_templates, ) last_template = stylesheet.xsl_template[-1] self.assertTrue(last_template) self.assertEqual("m_var", last_template["match"]) self.assertEqual("compact tac formula italic", last_template.p["class"]) self.assertEqual( untangle.Element("xsl_apply_templates", ""), last_template.p.xsl_apply_templates, ) class IterationTestCase(unittest.TestCase): """ Tests various cases of iteration over child nodes. """ def test_multiple_children(self): """ Regular case of iteration. """ o = untangle.parse("<a><b/><b/></a>") cnt = 0 for i in o.a.b: cnt += 1 self.assertEqual(2, cnt) def test_single_child(self): """ Special case when there is only a single child element. Does not work without an __iter__ implemented. """ o = untangle.parse("<a><b/></a>") cnt = 0 for i in o.a.b: cnt += 1 self.assertEqual(1, cnt) class TwimlTestCase(unittest.TestCase): """ Github Issue #5: can't dir the parsed object """ def test_twiml_dir(self): xml = """<?xml version="1.0" encoding="UTF-8"?> <Response> <Gather action="http://example.com/calls/1/twiml?event=start" numDigits="1" timeout="0"> <Play>http://example.com/barcall_message_url.wav</Play> </Gather> <Redirect>http://example.com/calls/1/twiml?event=start</Redirect> </Response> """ o = untangle.parse(xml) self.assertEqual([u"Response"], dir(o)) resp = o.Response self.assertEqual([u"Gather", u"Redirect"], dir(resp)) gather = resp.Gather redir = resp.Redirect self.assertEqual([u"Play"], dir(gather)) self.assertEqual([], dir(redir)) self.assertEqual( u"http://example.com/calls/1/twiml?event=start", o.Response.Redirect.cdata ) class UnicodeTestCase(unittest.TestCase): """ Github issue #8: UnicodeEncodeError """ def test_unicode_file(self): o = untangle.parse("tests/res/unicode.xml") self.assertEqual(u"ðÒÉ×ÅÔ ÍÉÒ", o.page.menu.name) def test_lengths(self): o = untangle.parse("tests/res/unicode.xml") self.assertEqual(1, len(o)) self.assertEqual(1, len(o.page)) self.assertEqual(2, len(o.page.menu)) self.assertEqual(2, len(o.page.menu.items)) self.assertEqual(2, len(o.page.menu.items.item)) self.assertEqual(0, len(o.page.menu.items.item[0].name)) self.assertEqual(0, len(o.page.menu.items.item[1].name)) def test_unicode_string(self): o = untangle.parse("<Element>valüé ◔‿◔</Element>") self.assertEqual(u"valüé ◔‿◔", o.Element.cdata) class FileObjects(unittest.TestCase): """ Test reading from file-like objects """ def test_file_object(self): with open("tests/res/pom.xml") as pom_file: o = untangle.parse(pom_file) project = o.project self.assertTrue(project) parent = project.parent self.assertTrue(parent) self.assertEqual("com.atlassian.confluence.plugin.base", parent.groupId) self.assertEqual("confluence-plugin-base", parent.artifactId) self.assertEqual("17", parent.version) class Foo(object): """ Used in UntangleInObjectsTestCase """ def __init__(self): self.doc = untangle.parse('<a><b x="1">foo</b></a>') class UntangleInObjectsTestCase(unittest.TestCase): """ tests usage of untangle in classes """ def test_object(self): foo = Foo() self.assertEqual("1", foo.doc.a.b["x"]) self.assertEqual("foo", foo.doc.a.b.cdata) class UrlStringTestCase(unittest.TestCase): """ tests is_url() function """ def test_is_url(self): self.assertFalse(untangle.is_url("foo")) self.assertFalse(untangle.is_url("httpfoo")) self.assertFalse(untangle.is_url(7)) self.assertTrue(untangle.is_url("http://foobar")) self.assertTrue(untangle.is_url("https://foobar")) class TestSaxHandler(unittest.TestCase): """ Tests the SAX ContentHandler """ def test_empty_handler(self): h = untangle.Handler() self.assertRaises(IndexError, h.endElement, "foo") self.assertRaises(IndexError, h.characters, "bar") def test_handler(self): h = untangle.Handler() h.startElement("foo", {}) h.endElement("foo") self.assertEqual("foo", h.root.children[0]._name) def test_cdata(self): h = untangle.Handler() h.startElement("foo", {}) h.characters("baz") self.assertEqual("baz", h.root.children[0].cdata) class FigsTestCase(unittest.TestCase): def test_figs(self): doc = untangle.parse("tests/res/figs.xml") expected_pairs = [("key1", "value1"), ("key2", "value2"), ("key", "value")] pairs = [] for group in doc.props.children: for prop in group.children: pairs.append((prop["key"], prop.cdata)) assert expected_pairs == pairs class ParserFeatureTestCase(unittest.TestCase): """Tests adding xml.sax parser features via parse()""" # External DTD that will never be loadable (invalid address) bad_dtd_xml = """<?xml version="1.0" standalone="no" ?> <!DOCTYPE FOO PUBLIC "foo" "http://256.0.0.1/foo.dtd"> <foo bar="baz" />""" def test_valid_feature(self): # xml.sax.handler.feature_external_ges -> load external general (text) # entities, such as DTDs doc = untangle.parse(self.bad_dtd_xml, feature_external_ges=False) self.assertEqual(doc.foo["bar"], "baz") def test_invalid_feature(self): with self.assertRaises(AttributeError): untangle.parse(self.bad_dtd_xml, invalid_feature=True) def test_invalid_external_dtd(self): with self.assertRaises(IOError): untangle.parse(self.bad_dtd_xml, feature_external_ges=True) class TestEquals(unittest.TestCase): def test_equals(self): a = untangle.Element("a", "1") b = untangle.Element("b", "1") self.assertTrue(a == b) def test_list_equals(self): a = untangle.Element("a", "1") b = untangle.Element("b", "1") listA = [a, b] c = untangle.Element("c", "1") self.assertTrue(c in listA) if __name__ == "__main__": unittest.main() # vim: set expandtab ts=4 sw=4:
6,229
334
// Auto generated code, do not modify package nxt.http.callers; public class CastVoteCall extends CreateTransactionCallBuilder<CastVoteCall> { private CastVoteCall() { super(ApiSpec.castVote); } public static CastVoteCall create() { return new CastVoteCall(); } public CastVoteCall vote02(int vote02) { return param("vote02", vote02); } public CastVoteCall vote00(int vote00) { return param("vote00", vote00); } public CastVoteCall vote01(int vote01) { return param("vote01", vote01); } public CastVoteCall poll(String poll) { return param("poll", poll); } public CastVoteCall poll(long poll) { return unsignedLongParam("poll", poll); } }
286
1,805
<filename>core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/tnt.cpp ///////////////////////////////////////////////// // Includes #include "tnt.h" ///////////////////////////////////////////////// // Tnt-Document void TTntBinDoc::SaveBinDocV( const TStr& InXmlFPath, const TStr& OutBinFNm, const int& MxDocs){ printf("Processing Tnt-News-Xml files from '%s'...\n", InXmlFPath.CStr()); TFOut SOut(OutBinFNm); TFFile FFile(InXmlFPath, true); TStr FNm; int Docs=0; int DateDocs=0; uint64 PrevTm=0; while (FFile.Next(FNm)){ if ((MxDocs!=-1)&&(Docs>=MxDocs)){break;} //printf(" Processing '%s' ...", FNm.CStr()); PXmlDoc XmlDoc=TXmlDoc::LoadTxt(FNm); PXmlTok ContentTok=XmlDoc->GetTagTok("item|content"); TStr DocNm=ContentTok->GetTagTok("swid")->GetArgVal("value"); TStr UrlStr=ContentTok->GetTagTok("url")->GetTokStr(false); TStr SubjStr=ContentTok->GetTagTok("title")->GetTokStr(false); TStr FetchedValStr=ContentTok->GetTagTok("fetched")->GetArgVal("value"); TXmlTokV EntityTokV; ContentTok->GetTagTokV("annotations|entity", EntityTokV); TStr BodyStr=ContentTok->GetTagTok("body")->GetTokStr(false); // extract date TStr DateStr=DocNm.GetSubStr(0, 7); TStr YearStr=DateStr.GetSubStr(0, 3); TStr MonthStr=DateStr.GetSubStr(4, 5); TStr DayStr=DateStr.GetSubStr(6, 7); TTm DateTm(YearStr.GetInt(), MonthStr.GetInt(), DayStr.GetInt()); uint64 Tm=TTm::GetMSecsFromTm(DateTm); // extract entities TStrIntH EntNmToFqH; for (int EntityTokN=0; EntityTokN<EntityTokV.Len(); EntityTokN++){ PXmlTok EntityTok=EntityTokV[EntityTokN]; if (!EntityTok->IsTag("entity")){continue;} TStr CanonicalNm=EntityTok->GetArgVal("canonical", ""); TStr TextStr=EntityTok->GetArgVal("text", ""); TStr TypeNm=EntityTok->GetArgVal("type", ""); TStr EntNm=CanonicalNm.Empty() ? TextStr : CanonicalNm; EntNmToFqH.AddDat(EntNm)++; } TIntStrPrV FqEntNmPrV; EntNmToFqH.GetDatKeyPrV(FqEntNmPrV); FqEntNmPrV.Sort(false); // extract headline TChA HeadlineChA=BodyStr.GetSubStr(0, 250); while ((HeadlineChA.Len()>0)&&(HeadlineChA.LastCh()!=' ')){ HeadlineChA.Trunc(HeadlineChA.Len()-1);} HeadlineChA+="..."; // create document TTntBinDoc Doc(DocNm, Tm, SubjStr, HeadlineChA, FqEntNmPrV); // save document Doc.Save(SOut); // screen log if (PrevTm!=Tm){ if (PrevTm!=0){printf("\n");} PrevTm=Tm; DateDocs=0; } Docs++; DateDocs++; printf(" %s [Day:%d / All:%d]\r", DateStr.CStr(), DateDocs, Docs); } printf("\nDone.\n"); } void TTntBinDoc::LoadBinDocV(const TStr& InBinFNm){ printf("Processing Tnt News-Binary file '%s'...\n", InBinFNm.CStr()); TFIn SIn(InBinFNm); int Docs=0; while (!SIn.Eof()){ TTntBinDoc Doc(SIn); Docs++; printf("%d\r", Docs); } printf("\nDone.\n"); } ///////////////////////////////////////////////// // Tnt-Entity void TTntEnt::GetDocIdV(const TTntBs* TntBs, const uint64& MnTm, const uint64& MxTm, TIntV& DocIdV) const { DocIdV.Gen(GetDocIds(), 0); for (int DocN=0; DocN<GetDocIds(); DocN++){ int DocId=GetDocId(DocN); PTntDoc Doc=TntBs->GetDoc(DocId); uint64 DocTm=Doc->GetTm(); if (((MnTm==0)||(MnTm<=DocTm))&&((MxTm==0)||(DocTm<MxTm))){ DocIdV.Add(DocId); } } } void TTntEnt::GetDocsPerDateV( const TTntBs* TntBs, TStrIntPrV& DateStrDocsPrV, int& Docs) const { TStrIntH DateStrToDocsH; Docs=0; for (int DocN=0; DocN<GetDocIds(); DocN++){ int DocId=GetDocId(DocN); PTntDoc Doc=TntBs->GetDoc(DocId); uint64 DocTm=Doc->GetTm(); TStr DocDateStr=TTm::GetTmFromMSecs(DocTm).GetWebLogDateStr(); DateStrToDocsH.AddDat(DocDateStr)++; Docs++; } DateStrToDocsH.GetKeyDatPrV(DateStrDocsPrV); DateStrDocsPrV.Sort(); } void TTntEnt::GetDocCentroid(const TTntBs* TntBs, const int& TopWords, const double& TopWordsWgtSumPrc, TStrFltPrV& WordStrWgtPrV) const { // create bow PSwSet SwSet=TSwSet::GetSwSet(swstEn523); PStemmer Stemmer=TStemmer::GetStemmer(stmtPorter); PBowDocBs BowDocBs=TBowDocBs::New(SwSet, Stemmer, NULL); for (int DocN=0; DocN<GetDocIds(); DocN++){ int DocId=GetDocId(DocN); PTntDoc Doc=TntBs->GetDoc(DocId); TStr DocStr=Doc->GetContStr(); BowDocBs->AddHtmlDoc(TInt::GetStr(DocId), TStrV(), DocStr); } // create word-weights TBowWordWgtType WordWgtType=bwwtNrmTFIDF; // define weighting PBowDocWgtBs BowDocWgtBs=TBowDocWgtBs::New(BowDocBs, WordWgtType, 0, 0); // create concept vector PBowSim BowSim=TBowSim::New(bstCos); // similarity object TIntV AllDIdV; BowDocBs->GetAllDIdV(AllDIdV); PBowSpV ConceptSpV=TBowClust::GetConceptSpV(BowDocWgtBs, BowSim, AllDIdV); // get word-vector ConceptSpV->GetWordStrWgtPrV(BowDocBs, TopWords, TopWordsWgtSumPrc, WordStrWgtPrV); } void TTntEnt::GetDocCentroid(const TTntBs* TntBs, const PBowDocBs& BowDocBs, const PBowDocWgtBs& BowDocWgtBs, const uint64& MnTm, const TStr& QKwStr, const int& TopWords, const double& TopWordsWgtSumPrc, int& Docs, TStrFltPrV& WordStrWgtPrV) const { // get doc-ids TIntV DocIdV; GetDocIdV(TntBs, MnTm, 0, DocIdV); if (DocIdV.Len()>0){ } TIntV BowDIdV(DocIdV.Len(), 0); for (int DocN=0; DocN<DocIdV.Len(); DocN++){ int DocId=DocIdV[DocN]; TStr BowDocNm=TInt::GetStr(DocId); int BowDId=BowDocBs->GetDId(BowDocNm); if (QKwStr.Empty()){ BowDIdV.Add(BowDId); } else { if (BowDocBs->IsDocWordStr(BowDId, QKwStr)){ BowDIdV.Add(BowDId); } } } // create concept vector PBowSim BowSim=TBowSim::New(bstCos); // similarity object PBowSpV ConceptSpV=TBowClust::GetConceptSpV(BowDocWgtBs, BowSim, BowDIdV); // get docs & word-vector Docs=DocIdV.Len(); ConceptSpV->GetWordStrWgtPrV(BowDocBs, TopWords, TopWordsWgtSumPrc, WordStrWgtPrV); } void TTntEnt::GetEntClustV(const TTntBs* TntBs, const uint64& MnTm, const int& MnDocs, const int& MxDocs, const int& Clusts, TVec<TStrFltPrV>& EntNmWgtPrVV) const { EntNmWgtPrVV.Clr(); // create bow PBowDocBs BowDocBs=TBowDocBs::New(); // collect documents TIntV DocIdV; GetDocIdV(TntBs, MnTm, 0, DocIdV); DocIdV.Reverse(); TRnd Rnd(1); DocIdV.Shuffle(Rnd); DocIdV.Trunc(MxDocs); if (DocIdV.Len()<MnDocs){return;} for (int DocN=0; DocN<DocIdV.Len(); DocN++){ int DocId=DocIdV[DocN]; PTntDoc Doc=TntBs->GetDoc(DocId); // create vector of entity-weights TIntFltPrV WIdWgtPrV; for (int EntN=0; EntN<Doc->GetEnts(); EntN++){ int EntId; int EntFq; Doc->GetEntNmFq(EntN, EntId, EntFq); TStr EntNm=TntBs->GetEntNm(EntId); int EntWId=BowDocBs->AddWordStr(EntNm); WIdWgtPrV.Add(TIntFltPr(EntWId, EntFq)); } // create bow-document int DId=BowDocBs->AddDoc(TInt::GetStr(DocId), TStrV(), WIdWgtPrV); TStr DocDescStr=Doc->GetSubjStr(); BowDocBs->PutDocDescStr(DId, DocDescStr); } // k-means clustering PBowSim BowSim=TBowSim::New(bstCos); // similarity object TBowWordWgtType WordWgtType=bwwtNrmTFIDF; // define weighting PBowDocPart BowDocPart=TBowClust::GetKMeansPart( TNotify::StdNotify, // log output BowDocBs, // document data BowSim, // similarity function Rnd, // random generator Clusts, // number of clusters 1, // trials per k-means 1, // convergence epsilon for k-means 1, // min. documents per cluster WordWgtType, // word weighting 0, // cut-word-weights percentage 0); // minimal word frequency EntNmWgtPrVV.Clr(); for (int ClustN=0; ClustN<BowDocPart->GetClusts(); ClustN++){ PBowDocPartClust Clust=BowDocPart->GetClust(ClustN); TStrFltPrV WordStrWgtPrV; Clust->GetTopWordStrWgtPrV(BowDocBs, 25, 0.5, WordStrWgtPrV); EntNmWgtPrVV.Add(WordStrWgtPrV); } //BowDocPart->SaveTxt("Clusts.Txt", BowDocBs, true, 25, 0.5, false); } void TTntEnt::GetSorted_LinkWgtDstEntIdPrV( const uint64& MnTm, const double& TopWgtSumPrc, TIntPrV& LinkWgtDstEntIdPrV) const { double AllLinkWgtSum=0; TIntIntH DstEntIdLinkWgtH; int LinkEnts=GetLinkEnts(); for (int LinkEntN=0; LinkEntN<LinkEnts; LinkEntN++){ int DstEntId=GetLinkEntId(LinkEntN); int EntLinks=GetEntLinks(LinkEntN); int EntLinkWgtSum=0; for (int EntLinkN=0; EntLinkN<EntLinks; EntLinkN++){ const TTntEntLinkCtx& EntLinkCtx=GetEntLinkCtx(LinkEntN, EntLinkN); if (EntLinkCtx.Tm>=MnTm){ EntLinkWgtSum+=EntLinkCtx.LinkWgt;} } if (EntLinkWgtSum>0){ DstEntIdLinkWgtH.AddDat(DstEntId, EntLinkWgtSum);} AllLinkWgtSum+=EntLinkWgtSum; } LinkWgtDstEntIdPrV.Clr(); DstEntIdLinkWgtH.GetDatKeyPrV(LinkWgtDstEntIdPrV); LinkWgtDstEntIdPrV.Sort(false); // cut long-tail if ((TopWgtSumPrc>0.0)&&(LinkWgtDstEntIdPrV.Len()>0)){ int TopLinkWgt=LinkWgtDstEntIdPrV[0].Val1; if (TopLinkWgt>(3*AllLinkWgtSum)/LinkWgtDstEntIdPrV.Len()){ double CutWgtSum=AllLinkWgtSum*(1-TopWgtSumPrc); int LastValN=LinkWgtDstEntIdPrV.Len()-1; while ((LastValN>0)&&(CutWgtSum>0)){ CutWgtSum-=LinkWgtDstEntIdPrV[LastValN].Val1; LastValN--; } LinkWgtDstEntIdPrV.Trunc(LastValN+1); } } } ///////////////////////////////////////////////// // Tnt-Base void TTntBs::GetSorted_DocsEntIdPrV(TIntPrV& DocsEntIdPrV){ TIntIntH EntIdToDocsH; for (int EntId=0; EntId<GetEnts(); EntId++){ int Docs=GetEnt(EntId)->GetDocIds(); EntIdToDocsH.AddDat(EntId, Docs); } DocsEntIdPrV.Clr(); EntIdToDocsH.GetDatKeyPrV(DocsEntIdPrV); DocsEntIdPrV.Sort(false); } int TTntBs::AddDoc( const TStr& DocNm, const uint64& Tm, const TStr& SubjStr, const TStr& ContStr, const TIntStrPrV FqEntNmPrV){ // create entity-id vector TIntPrV EntIdFqPrV(FqEntNmPrV.Len(), 0); for (int EntN=0; EntN<FqEntNmPrV.Len(); EntN++){ TStr EntNm=FqEntNmPrV[EntN].Val2; int EntFq=FqEntNmPrV[EntN].Val1; if (EntFq>=GetMnEntFqPerDoc()){ int EntId=AddEnt(EntNm); EntIdFqPrV.Add(TIntPr(EntId, EntFq)); } } // check entity-id vector lenght if (EntIdFqPrV.Len()<GetMnEntsPerDoc()){ return -1;} // create document PTntDoc Doc= TTntDoc::New(DocNm, Tm, SubjStr, ContStr, EntIdFqPrV); // add document to base int DocId=GetNewDocId(); IdToDocH.AddDat(DocId, Doc); // get entity for (int EntN=0; EntN<EntIdFqPrV.Len(); EntN++){ int EntId=EntIdFqPrV[EntN].Val1; GetEnt(EntId)->PushDocId(DocId); } // create link int EntLinkWgtSum=0; for (int EntN1=0; EntN1<EntIdFqPrV.Len(); EntN1++){ int EntId1=EntIdFqPrV[EntN1].Val1; PTntEnt Ent1=GetEnt(EntId1); int EntWgt1=EntIdFqPrV[EntN1].Val2; for (int EntN2=0; EntN2<EntIdFqPrV.Len(); EntN2++){ if (EntN1==EntN2){continue;} int EntId2=EntIdFqPrV[EntN2].Val1; int EntWgt2=EntIdFqPrV[EntN2].Val2; // entity-link-weight int EntLinkWgt=EntWgt1*EntWgt2; EntLinkWgtSum+=EntLinkWgt; // create entity-link-context TTntEntLinkCtx LinkCtx(EntLinkWgt, DocId, Tm); Ent1->AddLink(EntId2, LinkCtx); } } // return doc-id return DocId; } void TTntBs::GetMnMxDocTm(uint64& MnDocTm, uint64& MxDocTm) const { MnDocTm=TUInt64::Mx; MxDocTm=TUInt64::Mn; TTntIdDocPrV IdDocPrV; GetIdDocPrV(IdDocPrV); int Docs=IdDocPrV.Len(); for (int DocN=0; DocN<Docs; DocN++){ uint64 Tm=IdDocPrV[DocN].Val2->GetTm(); if (Tm<MnDocTm){MnDocTm=Tm;} if (Tm>MxDocTm){MxDocTm=Tm;} } } PBowDocBs TTntBs::GetBowDocBs( const int& MxNGramLen, const int& MnNGramFq) const { // prepare stop-words PSwSet SwSet=TSwSet::GetSwSet(swstEn523); // prepare stemmer PStemmer Stemmer=TStemmer::GetStemmer(stmtPorter); // create ngrams PNGramBs NGramBs; if (!((MxNGramLen==1)&&(MnNGramFq==1))){ TStrV HtmlStrV; TTntIdDocPrV IdDocPrV; GetIdDocPrV(IdDocPrV); for (int DocN=0; DocN<IdDocPrV.Len(); DocN++){ PTntDoc Doc=IdDocPrV[DocN].Val2; TStr DocStr=Doc->GetContStr(); HtmlStrV.Add(DocStr); } NGramBs=TNGramBs::GetNGramBsFromHtmlStrV( HtmlStrV, MxNGramLen, MnNGramFq, SwSet, Stemmer); } // create bow PBowDocBs BowDocBs=TBowDocBs::New(SwSet, Stemmer, NGramBs); TTntIdDocPrV IdDocPrV; GetIdDocPrV(IdDocPrV); for (int DocN=0; DocN<IdDocPrV.Len(); DocN++){ int DocId=IdDocPrV[DocN].Val1; PTntDoc Doc=IdDocPrV[DocN].Val2; TStr DocStr=Doc->GetContStr(); BowDocBs->AddHtmlDoc(TInt::GetStr(DocId), TStrV(), DocStr); } // return bow return BowDocBs; } PBowDocWgtBs TTntBs::GetBowDocWgtBs(const PBowDocBs& BowDocBs) const { // define weighting TBowWordWgtType WordWgtType=bwwtNrmTFIDF; // create word-weights PBowDocWgtBs BowDocWgtBs=TBowDocWgtBs::New(BowDocBs, WordWgtType, 0, 0); // return bow-weights return BowDocWgtBs; } void TTntBs::GetWordStrWgtPrVDiff( const TStrFltPrV& OldWordStrWgtPrV, const TStrFltPrV& NewWordStrWgtPrV, TStrFltPrV& NegDiffWordStrWgtPrV, TStrFltPrV& PosDiffWordStrWgtPrV){ TStrFltH WordStrToWgtH; // set previous-vector for (int WordN=0; WordN<NewWordStrWgtPrV.Len(); WordN++){ TStr WStr=NewWordStrWgtPrV[WordN].Val1; double WWgt=NewWordStrWgtPrV[WordN].Val2; WordStrToWgtH.AddDat(WStr, WWgt); } // diff current-vector for (int WordN=0; WordN<OldWordStrWgtPrV.Len(); WordN++){ TStr WStr=OldWordStrWgtPrV[WordN].Val1; double WWgt=OldWordStrWgtPrV[WordN].Val2; double CurWWgt=WordStrToWgtH.AddDat(WStr); WordStrToWgtH.AddDat(WStr, CurWWgt-WWgt); } // extract vector TFltStrPrV DiffWordWgtStrPrV; WordStrToWgtH.GetDatKeyPrV(DiffWordWgtStrPrV); // positive-vector DiffWordWgtStrPrV.Sort(true); NegDiffWordStrWgtPrV.Gen(DiffWordWgtStrPrV.Len(), 0); for (int WordN=0; WordN<DiffWordWgtStrPrV.Len(); WordN++){ TStr WStr=DiffWordWgtStrPrV[WordN].Val2; double WWgt=DiffWordWgtStrPrV[WordN].Val1; if (WWgt!=0){NegDiffWordStrWgtPrV.Add(TStrFltPr(WStr, WWgt));} } // negative-vector DiffWordWgtStrPrV.Sort(false); PosDiffWordStrWgtPrV.Gen(DiffWordWgtStrPrV.Len(), 0); for (int WordN=0; WordN<DiffWordWgtStrPrV.Len(); WordN++){ TStr WStr=DiffWordWgtStrPrV[WordN].Val2; double WWgt=DiffWordWgtStrPrV[WordN].Val1; if (WWgt!=0){PosDiffWordStrWgtPrV.Add(TStrFltPr(WStr, WWgt));} } } void TTntBs::GetWordStrWgtPrV(const TStrFltPrV& WordStrWgtPrV, TChA& WordStrWgtPrVChA, TChA& WordStrWgtPrVXmlChA){ WordStrWgtPrVChA.Clr(); WordStrWgtPrVXmlChA.Clr(); for (int WordN=0; WordN<WordStrWgtPrV.Len(); WordN++){ TStr WStr=WordStrWgtPrV[WordN].Val1; TStr XmlWStr=TXmlLx::GetXmlStrFromPlainStr(WStr); double WWgt=WordStrWgtPrV[WordN].Val2; if (WordN>0){WordStrWgtPrVChA+=' ';} WordStrWgtPrVChA+=TStr::Fmt("['%s':%.3f]", WStr.CStr(), WWgt); WordStrWgtPrVXmlChA+=TStr::Fmt("<Kw str=\"%s\" wgt=\"%.3f\"/>", XmlWStr.CStr(), WWgt); } } void TTntBs::GetLinkWgtDstEntIdPrVDiff( const TIntPrV& OldLinkWgtDstEntIdPrV, const TIntPrV& NewLinkWgtDstEntIdPrV, TIntPrV& NegDiffLinkWgtDstEntIdPrV, TIntPrV& PosDiffLinkWgtDstEntIdPrV){ TIntIntH DstEntIdToLinkWgtH; // set previous-vector for (int WordN=0; WordN<NewLinkWgtDstEntIdPrV.Len(); WordN++){ int LinkWgt=NewLinkWgtDstEntIdPrV[WordN].Val1; int DstEntId=NewLinkWgtDstEntIdPrV[WordN].Val2; DstEntIdToLinkWgtH.AddDat(DstEntId, LinkWgt); } // diff current-vector for (int WordN=0; WordN<OldLinkWgtDstEntIdPrV.Len(); WordN++){ int LinkWgt=OldLinkWgtDstEntIdPrV[WordN].Val1; int DstEntId=OldLinkWgtDstEntIdPrV[WordN].Val2; int CurLinkWgt=DstEntIdToLinkWgtH.AddDat(DstEntId); DstEntIdToLinkWgtH.AddDat(DstEntId, CurLinkWgt-LinkWgt); } // extract vector TIntPrV _DiffLinkWgtDstEntIdPrV; DstEntIdToLinkWgtH.GetDatKeyPrV(_DiffLinkWgtDstEntIdPrV); // clean zeros TIntPrV DiffLinkWgtDstEntIdPrV(_DiffLinkWgtDstEntIdPrV.Len(), 0); for (int EntN=0; EntN<_DiffLinkWgtDstEntIdPrV.Len(); EntN++){ int LinkWgt=_DiffLinkWgtDstEntIdPrV[EntN].Val1; if (LinkWgt!=0){ DiffLinkWgtDstEntIdPrV.Add(_DiffLinkWgtDstEntIdPrV[EntN]);} } // positive-vector DiffLinkWgtDstEntIdPrV.Sort(true); NegDiffLinkWgtDstEntIdPrV=DiffLinkWgtDstEntIdPrV; // negative-vector DiffLinkWgtDstEntIdPrV.Sort(false); PosDiffLinkWgtDstEntIdPrV=DiffLinkWgtDstEntIdPrV; } void TTntBs::GetLinkWgtDstEntNmPrV(const TIntPrV& LinkWgtDstEntIdPrV, TStrIntPrV& LinkWgtDstEntNmPrV, TChA& LinkWgtDstEntIdPrVChA, TChA& LinkWgtDstEntIdPrVXmlChA){ LinkWgtDstEntNmPrV.Clr(); LinkWgtDstEntIdPrVChA.Clr(); LinkWgtDstEntIdPrVXmlChA.Clr(); for (int DstEntN=0; DstEntN<LinkWgtDstEntIdPrV.Len(); DstEntN++){ // prepare values int DstEntId=LinkWgtDstEntIdPrV[DstEntN].Val2; TStr DstEntNm=GetEntNm(DstEntId); TStr XmlDstEntNm=TXmlLx::GetXmlStrFromPlainStr(DstEntNm); int LinkWgt=LinkWgtDstEntIdPrV[DstEntN].Val1; // update vectors LinkWgtDstEntNmPrV.Add(TStrIntPr(DstEntNm, LinkWgt)); if (DstEntN>0){LinkWgtDstEntIdPrVChA+=' ';} LinkWgtDstEntIdPrVChA+=TStr::Fmt("['%s':%d]", DstEntNm.CStr(), LinkWgt); LinkWgtDstEntIdPrVXmlChA+=TStr::Fmt("<Ent name=\"%s\" wgt=\"%d\"/>", XmlDstEntNm.CStr(), LinkWgt); } } void TTntBs::GetSchTmV(const TStr& SchNm, const uint64& PivotTm, TUInt64V& SchTmMSecsV){ SchTmMSecsV.Clr(); if (SchNm=="dayexp"){ SchTmMSecsV.Add(PivotTm-0*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-1*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-2*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-4*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-8*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-16*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-32*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-64*TTmInfo::GetDayMSecs()); } else if (SchNm=="day"){ SchTmMSecsV.Add(PivotTm-0*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-1*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-2*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-3*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-4*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-5*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-6*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-7*TTmInfo::GetDayMSecs()); } else if (SchNm=="week"){ SchTmMSecsV.Add(PivotTm-0*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-7*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-14*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-21*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-28*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-35*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-42*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-49*TTmInfo::GetDayMSecs()); } else if (SchNm=="month"){ SchTmMSecsV.Add(PivotTm-0*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-30*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-60*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-90*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-120*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-150*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-180*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-210*TTmInfo::GetDayMSecs()); } else if (SchNm=="year"){ SchTmMSecsV.Add(PivotTm-0*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-364*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-728*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-1092*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-1457*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-1821*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-2185*TTmInfo::GetDayMSecs()); SchTmMSecsV.Add(PivotTm-2550*TTmInfo::GetDayMSecs()); } else { FailR("Invalid Time Schedule"); } } void TTntBs::Search( const PBowDocBs& TntBsBowDocBs, const PBowDocWgtBs& TntBsBowDocWgtBs, const TStr& QTmStr, const TStr& QSchNm, const TStr& QWcEntNm, const TStr& QKwStr, PTntRSet& TntRSet, const TStr& OutXmlFNm, const TStr& OutTxtFNm){ // time-query TTm QTm=TTm::GetTmFromWebLogDateTimeStr(QTmStr); if (!QTm.IsDef()){ uint64 MnDocTm; uint64 MxDocTm; GetMnMxDocTm(MnDocTm, MxDocTm); QTm=TTm::GetTmFromMSecs(MxDocTm); } TTm RawPivotTm=QTm; TStr RawPivotTmStr=RawPivotTm.GetWebLogDateTimeStr(); TTm PivotTm=TTm::GetTmFromWebLogDateTimeStr(RawPivotTm.GetWebLogDateStr()); TStr PivotTmStr=PivotTm.GetWebLogDateTimeStr(); uint64 PivotTmMSecs=TTm::GetMSecsFromTm(PivotTm); TUInt64V SchTmMSecsV; GetSchTmV(QSchNm, PivotTmMSecs, SchTmMSecsV); // keyword-query TStr NrQKwStr=QKwStr.GetUc(); // create result-set TntRSet=TTntRSet::New(); TntRSet->PutQStrs(QTmStr, QSchNm, QWcEntNm, QKwStr); TntRSet->PutPivotTm(RawPivotTm, PivotTm); // get bow //PBowDocBs BowDocBs=GetBowDocBs(3, 5); //PBowDocBs BowDocBs=GetBowDocBs(); //PBowDocWgtBs BowDocWgtBs=GetBowDocWgtBs(BowDocBs); // open files TFOut XmlFOut(OutXmlFNm); FILE* fXmlOut=XmlFOut.GetFileId(); fprintf(fXmlOut, "<TntProfile>\n"); TFOut TxtFOut(OutTxtFNm); FILE* fTxtOut=TxtFOut.GetFileId(); // get docs-entities sorted vector TIntPrV DocsEntIdPrV; GetSorted_DocsEntIdPrV(DocsEntIdPrV); // traverse entities for (int EntN=0; EntN<DocsEntIdPrV.Len(); EntN++){ int EntId=DocsEntIdPrV[EntN].Val2; TStr EntNm=GetEntNm(EntId); if (!QWcEntNm.Empty()&&(!EntNm.IsWcMatch(QWcEntNm))){continue;} // create entity-result-set PTntEntRSet EntRSet=TTntEntRSet::New(); EntRSet->PutEntNm(EntNm); TntRSet->AddEntRSet(EntRSet); // output entity-header int EntDocs=DocsEntIdPrV[EntN].Val1; PTntEnt Ent=GetEnt(EntId); int LinkEnts=Ent->GetLinkEnts(); fprintf(fXmlOut, "<Entity name=\"%s\" docs=\"%d\" ents=\"%d\">\n", EntNm.CStr(), EntDocs, LinkEnts); fprintf(fTxtOut, "'%s' [%d docs] [%d ents]\n", EntNm.CStr(), EntDocs, LinkEnts); // output docs over dates {TStrIntPrV DateStrDocsPrV; int _EntDocs; Ent->GetDocsPerDateV(this, DateStrDocsPrV, _EntDocs); fprintf(fXmlOut, "<DatesDocs docs=\"%d\">\n", _EntDocs); fprintf(fTxtOut, " Docs per Date (%d docs):", _EntDocs); for (int DateN=0; DateN<DateStrDocsPrV.Len(); DateN++){ TStr DateStr=DateStrDocsPrV[DateN].Val1; int Docs=DateStrDocsPrV[DateN].Val2; fprintf(fXmlOut, " <DateDoc date=\"%s\" docs=\"%d\"/>\n", DateStr.CStr(), Docs); fprintf(fTxtOut, " [%s:%d]", DateStr.CStr(), Docs); } fprintf(fXmlOut, "</DatesDocs>\n"); fprintf(fTxtOut, "\n");} fprintf(fXmlOut, "<TimeSlices start-time=\"%s\">\n", RawPivotTmStr.CStr()); fprintf(fTxtOut, " [Now: %s]\n", RawPivotTmStr.CStr()); TIntPrV PrevLinkWgtDstEntIdPrV; TStrFltPrV PrevWordStrWgtPrV; for (int SchTmN=0; SchTmN<SchTmMSecsV.Len(); SchTmN++){ // start-time uint64 StartTmMSecs=SchTmMSecsV[SchTmN]; TStr StartTmStr=TTm::GetTmFromMSecs(StartTmMSecs).GetWebLogDateTimeStr(); double PastDays=-1*((PivotTmMSecs-StartTmMSecs)/double(TTmInfo::GetDayMSecs())); // end-time TStr EndTmStr; if (SchTmN==0){EndTmStr=RawPivotTmStr;} else {EndTmStr=TTm::GetTmFromMSecs(SchTmMSecsV[SchTmN-1]).GetWebLogDateTimeStr();} uint64 EndTmMSecs=TTm::GetMSecsFromTm(TTm::GetTmFromWebLogDateTimeStr(EndTmStr)); // crate time-slice PTntEntRSet_TmSlice TmSlice=TTntEntRSet_TmSlice::New(); TmSlice->PutStartEndTm(StartTmMSecs, EndTmMSecs); EntRSet->AddTmSlice(TmSlice); // open-time-point fprintf(fXmlOut, "<TimeSlice start-time=\"%s\" end-time=\"%s\" past-days=\"%.1f\">\n", StartTmStr.CStr(), EndTmStr.CStr(), PastDays); // get linked entities TIntPrV LinkWgtDstEntIdPrV; Ent->GetSorted_LinkWgtDstEntIdPrV(StartTmMSecs, 0.9, LinkWgtDstEntIdPrV); fprintf(fXmlOut, "<SocialProfile>\n"); // output linked entities int TopLinkEnts=LinkWgtDstEntIdPrV.Len(); TStrIntPrV LinkWgtDstEntNmPrV; TChA LinkWgtDstEntIdPrVChA; TChA LinkWgtDstEntIdPrVXmlChA; GetLinkWgtDstEntNmPrV(LinkWgtDstEntIdPrV, LinkWgtDstEntNmPrV, LinkWgtDstEntIdPrVChA, LinkWgtDstEntIdPrVXmlChA); TmSlice->PutLinkWgtDstEntNmPrV(LinkWgtDstEntNmPrV); fprintf(fXmlOut, " <Entities ents=\"%d\">%s</Entities>\n", TopLinkEnts, LinkWgtDstEntIdPrVXmlChA.CStr()); fprintf(fTxtOut, " Entities (%d ents): %s\n", TopLinkEnts, LinkWgtDstEntIdPrVChA.CStr()); // output difference between previous and current centroid if (SchTmN>0){ TIntPrV NegDiffLinkWgtDstEntIdPrV; TIntPrV PosDiffLinkWgtDstEntIdPrV; GetLinkWgtDstEntIdPrVDiff(LinkWgtDstEntIdPrV, PrevLinkWgtDstEntIdPrV, NegDiffLinkWgtDstEntIdPrV, PosDiffLinkWgtDstEntIdPrV); // output positive change TStrIntPrV PosDiffLinkWgtDstEntNmPrV; TChA PosDiffLinkWgtDstEntIdPrVChA; TChA PosDiffLinkWgtDstEntIdPrVXmlChA; GetLinkWgtDstEntNmPrV(PosDiffLinkWgtDstEntIdPrV, PosDiffLinkWgtDstEntNmPrV, PosDiffLinkWgtDstEntIdPrVChA, PosDiffLinkWgtDstEntIdPrVXmlChA); TmSlice->PutPosDiffLinkWgtDstEntNmPrV(PosDiffLinkWgtDstEntNmPrV); fprintf(fXmlOut, " <RisingEntities>%s</RisingEntities>\n", PosDiffLinkWgtDstEntIdPrVXmlChA.CStr()); fprintf(fTxtOut, " Pos-Diff: %s\n", PosDiffLinkWgtDstEntIdPrVChA.CStr()); // output negative change TStrIntPrV NegDiffLinkWgtDstEntNmPrV; TChA NegDiffLinkWgtDstEntIdPrVChA; TChA NegDiffLinkWgtDstEntIdPrVXmlChA; GetLinkWgtDstEntNmPrV(NegDiffLinkWgtDstEntIdPrV, NegDiffLinkWgtDstEntNmPrV, NegDiffLinkWgtDstEntIdPrVChA, NegDiffLinkWgtDstEntIdPrVXmlChA); TmSlice->PutNegDiffLinkWgtDstEntNmPrV(NegDiffLinkWgtDstEntNmPrV); fprintf(fXmlOut, " <FallingEntities>%s</FallingEntities>\n", NegDiffLinkWgtDstEntIdPrVXmlChA.CStr()); fprintf(fTxtOut, " Neg-Diff: %s\n", NegDiffLinkWgtDstEntIdPrVChA.CStr()); } PrevLinkWgtDstEntIdPrV=LinkWgtDstEntIdPrV; fprintf(fXmlOut, "</SocialProfile>\n"); // get text centroid int CtrDocs; TStrFltPrV WordStrWgtPrV; Ent->GetDocCentroid(this, TntBsBowDocBs, TntBsBowDocWgtBs, StartTmMSecs, NrQKwStr, 150, 0.9, CtrDocs, WordStrWgtPrV); fprintf(fXmlOut, "<ContentProfile>\n"); // output centroid TChA WordStrWgtPrVChA; TChA WordStrWgtPrVXmlChA; GetWordStrWgtPrV(WordStrWgtPrV, WordStrWgtPrVChA, WordStrWgtPrVXmlChA); TmSlice->PutWordStrWgtPrV(WordStrWgtPrV); fprintf(fXmlOut, " <Keywords docs=\"%d\" kwords=\"%d\">%s</Keywords>\n", CtrDocs, WordStrWgtPrV.Len(), WordStrWgtPrVXmlChA.CStr()); fprintf(fTxtOut, " Centroid (%d docs, %d words): %s\n", CtrDocs, WordStrWgtPrV.Len(), WordStrWgtPrVChA.CStr()); // output difference between previous and current centroid if (SchTmN>0){ TStrFltPrV NegDiffWordStrWgtPrV; TStrFltPrV PosDiffWordStrWgtPrV; GetWordStrWgtPrVDiff(WordStrWgtPrV, PrevWordStrWgtPrV, NegDiffWordStrWgtPrV, PosDiffWordStrWgtPrV); // output positive change TChA PosDiffWordStrWgtPrVChA; TChA PosDiffWordStrWgtPrVXmlChA; GetWordStrWgtPrV(PosDiffWordStrWgtPrV, PosDiffWordStrWgtPrVChA, PosDiffWordStrWgtPrVXmlChA); TmSlice->PutPosDiffWordStrWgtPrV(PosDiffWordStrWgtPrV); fprintf(fXmlOut, " <RisingKeywords>%s</RisingKeywords>\n", PosDiffWordStrWgtPrVXmlChA.CStr()); fprintf(fTxtOut, " Pos-Diff: %s\n", PosDiffWordStrWgtPrVChA.CStr()); // output negative change TChA NegDiffWordStrWgtPrVChA; TChA NegDiffWordStrWgtPrVXmlChA; GetWordStrWgtPrV(NegDiffWordStrWgtPrV, NegDiffWordStrWgtPrVChA, NegDiffWordStrWgtPrVXmlChA); TmSlice->PutNegDiffWordStrWgtPrV(NegDiffWordStrWgtPrV); fprintf(fXmlOut, " <FallingKeywords>%s</FallingKeywords>\n", NegDiffWordStrWgtPrVXmlChA.CStr()); fprintf(fTxtOut, " Neg-Diff: %s\n", NegDiffWordStrWgtPrVChA.CStr()); } PrevWordStrWgtPrV=WordStrWgtPrV; fprintf(fXmlOut, "</ContentProfile>\n"); // close time-point fprintf(fXmlOut, "</TimeSlice>\n"); fprintf(fTxtOut, " [%.1f days: %s]\n", PastDays, StartTmStr.CStr()); } fprintf(fXmlOut, "</TimeSlices>\n"); // entity clustering TVec<TStrFltPrV> EntNmWgtPrVV; Ent->GetEntClustV(this, SchTmMSecsV.Last(), 100, 1000, 15, EntNmWgtPrVV); TntRSet->PutClust(EntNmWgtPrVV); fprintf(fXmlOut, "<SocialClusters>\n"); for (int ClustN=0; ClustN<EntNmWgtPrVV.Len(); ClustN++){ TStrFltPrV& EntNmWgtPrV=EntNmWgtPrVV[ClustN]; fprintf(fXmlOut, "<SocialCluster num=\"%d\">\n", ClustN); fprintf(fTxtOut, " Clust-%d:", ClustN); for (int EntN=0; EntN<EntNmWgtPrV.Len(); EntN++){ TStr EntNm=EntNmWgtPrV[EntN].Val1; double Wgt=EntNmWgtPrV[EntN].Val2; fprintf(fXmlOut, "<Entity name=\"%s\" wgt=\"%.3f\"/>", EntNm.CStr(), Wgt); fprintf(fTxtOut, " ['%s':%.3f]", EntNm.CStr(), Wgt); } fprintf(fXmlOut, "</SocialCluster>\n"); fprintf(fTxtOut, "\n"); } fprintf(fXmlOut, "</SocialClusters>\n"); // close fprintf(fXmlOut, "</Entity>\n"); fprintf(fTxtOut, "\n"); } // closing files fprintf(fXmlOut, "</TntProfile>\n"); }
14,232
3,702
/* * 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 app.metatron.discovery.extensions; import org.pf4j.PluginStatusProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import app.metatron.discovery.domain.extension.ExtensionProperties; /** * */ public class CustomPluginStatusProvider implements PluginStatusProvider { private static final Logger log = LoggerFactory.getLogger(CustomPluginStatusProvider.class); private List<String> enabledPlugins; private List<String> disabledPlugins; public void initialize(ExtensionProperties extensionProperties) { // create a list with plugin identifiers that should be only accepted by this manager (whitelist from plugins/enabled.txt file) enabledPlugins = extensionProperties == null || extensionProperties.getPluginEnable() == null ? new ArrayList<>() : extensionProperties.getPluginEnable(); log.info("Enabled plugins: {}", enabledPlugins); // create a list with plugin identifiers that should not be accepted by this manager (blacklist from plugins/disabled.txt file) disabledPlugins = extensionProperties == null || extensionProperties.getPluginDisable() == null ? new ArrayList<>() : extensionProperties.getPluginDisable(); log.info("Disabled plugins: {}", disabledPlugins); } @Override public boolean isPluginDisabled(String pluginId) { if (disabledPlugins.contains(pluginId)) { return true; } return !enabledPlugins.isEmpty() && !enabledPlugins.contains(pluginId); } @Override public boolean disablePlugin(String pluginId) { disabledPlugins.add(pluginId); return true; } @Override public boolean enablePlugin(String pluginId) { disabledPlugins.remove(pluginId); return true; } }
701
3,083
<reponame>utumen/binnavi // Copyright 2011-2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.security.zynamics.binnavi.Gui.GraphWindows.Extensions; import com.google.security.zynamics.binnavi.Gui.GraphWindows.CGraphModel; import com.google.security.zynamics.binnavi.Gui.GraphWindows.IGraphPanelExtender; /** * Interface for classes that want to extend graph panels. */ public interface IGraphPanelExtension { void dispose(); /** * In this function, graph panel extensions are supposed to extend the graph panel. * * @param model Model of the graph in the panel. * @param extender Interface for extending the graph panel. */ void visit(final CGraphModel model, final IGraphPanelExtender extender); }
352
420
# Copyright (c) 2012-2016 Seafile Ltd. import json import logging from django.conf import settings from django.urls import reverse from django.contrib import messages from django.http import HttpResponseRedirect, Http404, HttpResponse from django.shortcuts import render from django.template.loader import render_to_string from django.utils.translation import ugettext as _ from seahub.auth.decorators import login_required, login_required_ajax from seahub.notifications.models import Notification, NotificationForm, \ UserNotification from seahub.notifications.utils import refresh_cache from seahub.avatar.util import get_default_avatar_url # Get an instance of a logger logger = logging.getLogger(__name__) ########## user notifications @login_required def user_notification_list(request): return render(request, "notifications/user_notification_list_react.html", { }) def add_notice_from_info(notices): '''Add 'msg_from' or 'default_avatar_url' to notice. ''' default_avatar_url = get_default_avatar_url() for notice in notices: notice.default_avatar_url = default_avatar_url if notice.is_user_message(): d = notice.user_message_detail_to_dict() if d.get('msg_from') is not None: notice.msg_from = d.get('msg_from') elif notice.is_repo_share_msg(): try: d = json.loads(notice.detail) notice.msg_from = d['share_from'] except Exception as e: logger.error(e) elif notice.is_repo_share_to_group_msg(): try: d = json.loads(notice.detail) notice.msg_from = d['share_from'] except Exception as e: logger.error(e) elif notice.is_group_join_request(): try: d = json.loads(notice.detail) notice.msg_from = d['username'] except Exception as e: logger.error(e) elif notice.is_add_user_to_group(): try: d = json.loads(notice.detail) notice.msg_from = d['group_staff'] except Exception as e: logger.error(e) elif notice.is_file_comment_msg(): try: d = json.loads(notice.detail) notice.msg_from = d['author'] except Exception as e: logger.error(e) elif notice.is_draft_comment_msg(): try: d = json.loads(notice.detail) notice.msg_from = d['author'] except Exception as e: logger.error(e) elif notice.is_draft_reviewer_msg(): try: d = json.loads(notice.detail) notice.msg_from = d['from_user'] except Exception as e: logger.error(e) return notices
1,363
1,144
package org.adempiere.plaf; import java.awt.Color; import javax.swing.plaf.ColorUIResource; /* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ /** * UI settings for Calendar date and time picker. * * @author metas-dev <<EMAIL>> * */ public final class CalendarUI { public static final String KEY_DayPanel_Background = "Calendar.DayPanel.Background"; public static final String KEY_DayPanel_WeekLabel_Background = "Calendar.DayPanel.WeekLabel.Background"; public static final String KEY_DayPanel_WeekLabel_Foreground = "Calendar.DayPanel.WeekLabel.Foreground"; public static final String KEY_DayButton_Regular_Background = "Calendar.DayButton.Regular.Background"; public static final String KEY_DayButton_Regular_Foreground = "Calendar.DayButton.Regular.Foreground"; // public static final String KEY_DayButton_Current_Background = "Calendar.DayButton.Current.Background"; public static final String KEY_DayButton_Current_Foreground = "Calendar.DayButton.Current.Foreground"; // public static final String KEY_DayButton_SetCurrent_Background = "Calendar.DayButton.SetCurrent.Background"; public static final String KEY_DayButton_SetCurrent_Foreground = "Calendar.DayButton.SetCurrent.Foreground"; // public static final String KEY_DayButton_Cancel_Background = "Calendar.DayButton.Cancel.Background"; public static final String KEY_DayButton_Cancel_Foreground = "Calendar.DayButton.Cancel.Foreground"; public static Object[] getUIDefaults() { return new Object[] { KEY_DayPanel_Background, new ColorUIResource(Color.WHITE) // , KEY_DayPanel_WeekLabel_Background, MetasFreshTheme.LOGO_TEXT_COLOR , KEY_DayPanel_WeekLabel_Foreground, new ColorUIResource(Color.WHITE) // , KEY_DayButton_Regular_Background, new ColorUIResource(Color.WHITE) , KEY_DayButton_Regular_Foreground, new ColorUIResource(Color.BLACK) // , KEY_DayButton_Current_Background, MetasFreshTheme.COLOR_Green , KEY_DayButton_Current_Foreground, new ColorUIResource(Color.BLACK) // , KEY_DayButton_SetCurrent_Background, MetasFreshTheme.COLOR_Green , KEY_DayButton_SetCurrent_Foreground, new ColorUIResource(Color.BLACK) // , KEY_DayButton_Cancel_Background, MetasFreshTheme.COLOR_RED_METAS , KEY_DayButton_Cancel_Foreground, new ColorUIResource(Color.WHITE) }; } }
976
790
<filename>lib/django-1.5/django/contrib/localflavor/ar/ar_provinces.py # -*- coding: utf-8 -*- """ A list of Argentinean provinces and autonomous cities as `choices` in a formfield. From http://www.argentina.gov.ar/argentina/portal/paginas.dhtml?pagina=425 This exists in this standalone file so that it's only imported into memory when explicitly needed. """ from __future__ import unicode_literals PROVINCE_CHOICES = ( ('B', 'Buenos Aires'), ('K', 'Catamarca'), ('H', 'Chaco'), ('U', 'Chubut'), ('C', 'Ciudad Autónoma de Buenos Aires'), ('X', 'Córdoba'), ('W', 'Corrientes'), ('E', 'Entre Ríos'), ('P', 'Formosa'), ('Y', 'Jujuy'), ('L', 'La Pampa'), ('F', 'La Rioja'), ('M', 'Mendoza'), ('N', 'Misiones'), ('Q', 'Neuquén'), ('R', 'Río Negro'), ('A', 'Salta'), ('J', 'San Juan'), ('D', 'San Luis'), ('Z', 'Santa Cruz'), ('S', 'Santa Fe'), ('G', 'Santiago del Estero'), ('V', 'Tierra del Fuego, Antártida e Islas del Atlántico Sur'), ('T', 'Tucumán'), )
465
372
<gh_stars>100-1000 /* * 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 code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.manufacturers.v1.model; /** * Attributes of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Manufacturer Center API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Attributes extends com.google.api.client.json.GenericJson { /** * The additional images of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#addlimage. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Image> additionalImageLink; /** * The target age group of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#agegroup. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String ageGroup; /** * The brand name of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#brand. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String brand; /** * The capacity of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#capacity. * The value may be {@code null}. */ @com.google.api.client.util.Key private Capacity capacity; /** * The color of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#color. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String color; /** * The count of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#count. * The value may be {@code null}. */ @com.google.api.client.util.Key private Count count; /** * The description of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#description. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * The disclosure date of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#disclosure. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String disclosureDate; /** * A list of excluded destinations. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> excludedDestination; /** * The rich format description of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#featuredesc. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<FeatureDescription> featureDescription; /** * The flavor of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#flavor. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String flavor; /** * The format of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String format; /** * The target gender of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#gender. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String gender; /** * The Global Trade Item Number (GTIN) of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#gtin. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> gtin; /** * The image of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#image. * The value may be {@code null}. */ @com.google.api.client.util.Key private Image imageLink; /** * A list of included destinations. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> includedDestination; /** * The item group id of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#itemgroupid. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String itemGroupId; /** * The material of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#material. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String material; /** * The Manufacturer Part Number (MPN) of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#mpn. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String mpn; /** * The pattern of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#pattern. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String pattern; /** * The details of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productdetail. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<ProductDetail> productDetail; /** * The name of the group of products related to the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productline. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String productLine; /** * The canonical name of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productname. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String productName; /** * The URL of the detail page of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productpage. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String productPageUrl; /** * The type or category of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#producttype. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> productType; /** * The release date of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#release. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String releaseDate; /** * Rich product content. For more information, see * https://support.google.com/manufacturers/answer/9389865 * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> richProductContent; /** * The scent of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#scent. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String scent; /** * The size of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#size. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String size; /** * The size system of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#sizesystem. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String sizeSystem; /** * The size type of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#sizetype. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String sizeType; /** * The suggested retail price (MSRP) of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#price. * The value may be {@code null}. */ @com.google.api.client.util.Key private Price suggestedRetailPrice; /** * The target client id. Should only be used in the accounts of the data partners. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String targetClientId; /** * The theme of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#theme. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String theme; /** * The title of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#title. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String title; /** * The videos of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#video. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> videoLink; /** * The additional images of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#addlimage. * @return value or {@code null} for none */ public java.util.List<Image> getAdditionalImageLink() { return additionalImageLink; } /** * The additional images of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#addlimage. * @param additionalImageLink additionalImageLink or {@code null} for none */ public Attributes setAdditionalImageLink(java.util.List<Image> additionalImageLink) { this.additionalImageLink = additionalImageLink; return this; } /** * The target age group of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#agegroup. * @return value or {@code null} for none */ public java.lang.String getAgeGroup() { return ageGroup; } /** * The target age group of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#agegroup. * @param ageGroup ageGroup or {@code null} for none */ public Attributes setAgeGroup(java.lang.String ageGroup) { this.ageGroup = ageGroup; return this; } /** * The brand name of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#brand. * @return value or {@code null} for none */ public java.lang.String getBrand() { return brand; } /** * The brand name of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#brand. * @param brand brand or {@code null} for none */ public Attributes setBrand(java.lang.String brand) { this.brand = brand; return this; } /** * The capacity of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#capacity. * @return value or {@code null} for none */ public Capacity getCapacity() { return capacity; } /** * The capacity of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#capacity. * @param capacity capacity or {@code null} for none */ public Attributes setCapacity(Capacity capacity) { this.capacity = capacity; return this; } /** * The color of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#color. * @return value or {@code null} for none */ public java.lang.String getColor() { return color; } /** * The color of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#color. * @param color color or {@code null} for none */ public Attributes setColor(java.lang.String color) { this.color = color; return this; } /** * The count of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#count. * @return value or {@code null} for none */ public Count getCount() { return count; } /** * The count of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#count. * @param count count or {@code null} for none */ public Attributes setCount(Count count) { this.count = count; return this; } /** * The description of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#description. * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * The description of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#description. * @param description description or {@code null} for none */ public Attributes setDescription(java.lang.String description) { this.description = description; return this; } /** * The disclosure date of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#disclosure. * @return value or {@code null} for none */ public java.lang.String getDisclosureDate() { return disclosureDate; } /** * The disclosure date of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#disclosure. * @param disclosureDate disclosureDate or {@code null} for none */ public Attributes setDisclosureDate(java.lang.String disclosureDate) { this.disclosureDate = disclosureDate; return this; } /** * A list of excluded destinations. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getExcludedDestination() { return excludedDestination; } /** * A list of excluded destinations. * @param excludedDestination excludedDestination or {@code null} for none */ public Attributes setExcludedDestination(java.util.List<java.lang.String> excludedDestination) { this.excludedDestination = excludedDestination; return this; } /** * The rich format description of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#featuredesc. * @return value or {@code null} for none */ public java.util.List<FeatureDescription> getFeatureDescription() { return featureDescription; } /** * The rich format description of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#featuredesc. * @param featureDescription featureDescription or {@code null} for none */ public Attributes setFeatureDescription(java.util.List<FeatureDescription> featureDescription) { this.featureDescription = featureDescription; return this; } /** * The flavor of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#flavor. * @return value or {@code null} for none */ public java.lang.String getFlavor() { return flavor; } /** * The flavor of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#flavor. * @param flavor flavor or {@code null} for none */ public Attributes setFlavor(java.lang.String flavor) { this.flavor = flavor; return this; } /** * The format of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#format. * @return value or {@code null} for none */ public java.lang.String getFormat() { return format; } /** * The format of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#format. * @param format format or {@code null} for none */ public Attributes setFormat(java.lang.String format) { this.format = format; return this; } /** * The target gender of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#gender. * @return value or {@code null} for none */ public java.lang.String getGender() { return gender; } /** * The target gender of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#gender. * @param gender gender or {@code null} for none */ public Attributes setGender(java.lang.String gender) { this.gender = gender; return this; } /** * The Global Trade Item Number (GTIN) of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#gtin. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getGtin() { return gtin; } /** * The Global Trade Item Number (GTIN) of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#gtin. * @param gtin gtin or {@code null} for none */ public Attributes setGtin(java.util.List<java.lang.String> gtin) { this.gtin = gtin; return this; } /** * The image of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#image. * @return value or {@code null} for none */ public Image getImageLink() { return imageLink; } /** * The image of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#image. * @param imageLink imageLink or {@code null} for none */ public Attributes setImageLink(Image imageLink) { this.imageLink = imageLink; return this; } /** * A list of included destinations. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getIncludedDestination() { return includedDestination; } /** * A list of included destinations. * @param includedDestination includedDestination or {@code null} for none */ public Attributes setIncludedDestination(java.util.List<java.lang.String> includedDestination) { this.includedDestination = includedDestination; return this; } /** * The item group id of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#itemgroupid. * @return value or {@code null} for none */ public java.lang.String getItemGroupId() { return itemGroupId; } /** * The item group id of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#itemgroupid. * @param itemGroupId itemGroupId or {@code null} for none */ public Attributes setItemGroupId(java.lang.String itemGroupId) { this.itemGroupId = itemGroupId; return this; } /** * The material of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#material. * @return value or {@code null} for none */ public java.lang.String getMaterial() { return material; } /** * The material of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#material. * @param material material or {@code null} for none */ public Attributes setMaterial(java.lang.String material) { this.material = material; return this; } /** * The Manufacturer Part Number (MPN) of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#mpn. * @return value or {@code null} for none */ public java.lang.String getMpn() { return mpn; } /** * The Manufacturer Part Number (MPN) of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#mpn. * @param mpn mpn or {@code null} for none */ public Attributes setMpn(java.lang.String mpn) { this.mpn = mpn; return this; } /** * The pattern of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#pattern. * @return value or {@code null} for none */ public java.lang.String getPattern() { return pattern; } /** * The pattern of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#pattern. * @param pattern pattern or {@code null} for none */ public Attributes setPattern(java.lang.String pattern) { this.pattern = pattern; return this; } /** * The details of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productdetail. * @return value or {@code null} for none */ public java.util.List<ProductDetail> getProductDetail() { return productDetail; } /** * The details of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productdetail. * @param productDetail productDetail or {@code null} for none */ public Attributes setProductDetail(java.util.List<ProductDetail> productDetail) { this.productDetail = productDetail; return this; } /** * The name of the group of products related to the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productline. * @return value or {@code null} for none */ public java.lang.String getProductLine() { return productLine; } /** * The name of the group of products related to the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productline. * @param productLine productLine or {@code null} for none */ public Attributes setProductLine(java.lang.String productLine) { this.productLine = productLine; return this; } /** * The canonical name of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productname. * @return value or {@code null} for none */ public java.lang.String getProductName() { return productName; } /** * The canonical name of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productname. * @param productName productName or {@code null} for none */ public Attributes setProductName(java.lang.String productName) { this.productName = productName; return this; } /** * The URL of the detail page of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productpage. * @return value or {@code null} for none */ public java.lang.String getProductPageUrl() { return productPageUrl; } /** * The URL of the detail page of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#productpage. * @param productPageUrl productPageUrl or {@code null} for none */ public Attributes setProductPageUrl(java.lang.String productPageUrl) { this.productPageUrl = productPageUrl; return this; } /** * The type or category of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#producttype. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getProductType() { return productType; } /** * The type or category of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#producttype. * @param productType productType or {@code null} for none */ public Attributes setProductType(java.util.List<java.lang.String> productType) { this.productType = productType; return this; } /** * The release date of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#release. * @return value or {@code null} for none */ public java.lang.String getReleaseDate() { return releaseDate; } /** * The release date of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#release. * @param releaseDate releaseDate or {@code null} for none */ public Attributes setReleaseDate(java.lang.String releaseDate) { this.releaseDate = releaseDate; return this; } /** * Rich product content. For more information, see * https://support.google.com/manufacturers/answer/9389865 * @return value or {@code null} for none */ public java.util.List<java.lang.String> getRichProductContent() { return richProductContent; } /** * Rich product content. For more information, see * https://support.google.com/manufacturers/answer/9389865 * @param richProductContent richProductContent or {@code null} for none */ public Attributes setRichProductContent(java.util.List<java.lang.String> richProductContent) { this.richProductContent = richProductContent; return this; } /** * The scent of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#scent. * @return value or {@code null} for none */ public java.lang.String getScent() { return scent; } /** * The scent of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#scent. * @param scent scent or {@code null} for none */ public Attributes setScent(java.lang.String scent) { this.scent = scent; return this; } /** * The size of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#size. * @return value or {@code null} for none */ public java.lang.String getSize() { return size; } /** * The size of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#size. * @param size size or {@code null} for none */ public Attributes setSize(java.lang.String size) { this.size = size; return this; } /** * The size system of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#sizesystem. * @return value or {@code null} for none */ public java.lang.String getSizeSystem() { return sizeSystem; } /** * The size system of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#sizesystem. * @param sizeSystem sizeSystem or {@code null} for none */ public Attributes setSizeSystem(java.lang.String sizeSystem) { this.sizeSystem = sizeSystem; return this; } /** * The size type of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#sizetype. * @return value or {@code null} for none */ public java.lang.String getSizeType() { return sizeType; } /** * The size type of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#sizetype. * @param sizeType sizeType or {@code null} for none */ public Attributes setSizeType(java.lang.String sizeType) { this.sizeType = sizeType; return this; } /** * The suggested retail price (MSRP) of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#price. * @return value or {@code null} for none */ public Price getSuggestedRetailPrice() { return suggestedRetailPrice; } /** * The suggested retail price (MSRP) of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#price. * @param suggestedRetailPrice suggestedRetailPrice or {@code null} for none */ public Attributes setSuggestedRetailPrice(Price suggestedRetailPrice) { this.suggestedRetailPrice = suggestedRetailPrice; return this; } /** * The target client id. Should only be used in the accounts of the data partners. * @return value or {@code null} for none */ public java.lang.String getTargetClientId() { return targetClientId; } /** * The target client id. Should only be used in the accounts of the data partners. * @param targetClientId targetClientId or {@code null} for none */ public Attributes setTargetClientId(java.lang.String targetClientId) { this.targetClientId = targetClientId; return this; } /** * The theme of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#theme. * @return value or {@code null} for none */ public java.lang.String getTheme() { return theme; } /** * The theme of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#theme. * @param theme theme or {@code null} for none */ public Attributes setTheme(java.lang.String theme) { this.theme = theme; return this; } /** * The title of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#title. * @return value or {@code null} for none */ public java.lang.String getTitle() { return title; } /** * The title of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#title. * @param title title or {@code null} for none */ public Attributes setTitle(java.lang.String title) { this.title = title; return this; } /** * The videos of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#video. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getVideoLink() { return videoLink; } /** * The videos of the product. For more information, see * https://support.google.com/manufacturers/answer/6124116#video. * @param videoLink videoLink or {@code null} for none */ public Attributes setVideoLink(java.util.List<java.lang.String> videoLink) { this.videoLink = videoLink; return this; } @Override public Attributes set(String fieldName, Object value) { return (Attributes) super.set(fieldName, value); } @Override public Attributes clone() { return (Attributes) super.clone(); } }
10,219
14,668
<reponame>zealoussnow/chromium<filename>build/fuchsia/update_images.py #!/usr/bin/env python # Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Updates the Fuchsia SDK to the given revision. Should be used in a 'hooks_os' entry so that it only runs when .gclient's target_os includes 'fuchsia'.""" import argparse import itertools import logging import os import re import shutil import subprocess import sys import tarfile from common import GetHostOsFromPlatform, GetHostArchFromPlatform, \ DIR_SOURCE_ROOT, IMAGES_ROOT from update_sdk import DownloadAndUnpackFromCloudStorage, \ GetOverrideCloudStorageBucket, GetSdkHash, \ MakeCleanDirectory, SDK_SIGNATURE_FILE def GetSdkSignature(sdk_hash, boot_images): return 'gn:{sdk_hash}:{boot_images}:'.format(sdk_hash=sdk_hash, boot_images=boot_images) def GetAllImages(boot_image_names): if not boot_image_names: return all_device_types = ['generic', 'qemu'] all_archs = ['x64', 'arm64'] images_to_download = set() for boot_image in boot_image_names.split(','): components = boot_image.split('.') if len(components) != 2: continue device_type, arch = components device_images = all_device_types if device_type == '*' else [device_type] arch_images = all_archs if arch == '*' else [arch] images_to_download.update(itertools.product(device_images, arch_images)) return images_to_download def DownloadSdkBootImages(bucket, sdk_hash, boot_image_names, image_root_dir): images_to_download = GetAllImages(boot_image_names) for image_to_download in images_to_download: device_type = image_to_download[0] arch = image_to_download[1] image_output_dir = os.path.join(image_root_dir, arch, device_type) if os.path.exists(image_output_dir): continue logging.info('Downloading Fuchsia boot images for %s.%s...' % (device_type, arch)) # Images use different formats. See fxbug.dev/85552. if bucket == 'fuchsia-sdk' or device_type == "workstation": type_arch_connector = '.' else: type_arch_connector = '-' images_tarball_url = 'gs://{bucket}/development/{sdk_hash}/images/'\ '{device_type}{type_arch_connector}{arch}.tgz'.format( bucket=bucket, sdk_hash=sdk_hash, device_type=device_type, type_arch_connector=type_arch_connector, arch=arch) DownloadAndUnpackFromCloudStorage(images_tarball_url, image_output_dir) def GetNewSignature(sdk_hash, boot_images): return GetSdkSignature(sdk_hash, boot_images) def main(): parser = argparse.ArgumentParser() parser.add_argument('--verbose', '-v', action='store_true', help='Enable debug-level logging.') parser.add_argument( '--boot-images', type=str, required=True, help='List of boot images to download, represented as a comma separated ' 'list. Wildcards are allowed. ') parser.add_argument( '--default-bucket', type=str, default='fuchsia', help='The Google Cloud Storage bucket in which the Fuchsia images are ' 'stored. Entry in sdk-bucket.txt will override this flag.') parser.add_argument( '--image-root-dir', default=IMAGES_ROOT, help='Specify the root directory of the downloaded images. Optional') args = parser.parse_args() logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO) # If no boot images need to be downloaded, exit. if not args.boot_images: return 0 # Check whether there's SDK support for this platform. GetHostOsFromPlatform() # Use the bucket in sdk-bucket.txt if an entry exists. # Otherwise use the default bucket. bucket = GetOverrideCloudStorageBucket() or args.default_bucket sdk_hash = GetSdkHash(bucket) if not sdk_hash: return 1 signature_filename = os.path.join(args.image_root_dir, SDK_SIGNATURE_FILE) current_signature = (open(signature_filename, 'r').read().strip() if os.path.exists(signature_filename) else '') new_signature = GetNewSignature(sdk_hash, args.boot_images) if current_signature != new_signature: logging.info('Downloading Fuchsia images %s...' % sdk_hash) MakeCleanDirectory(args.image_root_dir) try: DownloadSdkBootImages(bucket, sdk_hash, args.boot_images, args.image_root_dir) with open(signature_filename, 'w') as f: f.write(new_signature) except subprocess.CalledProcessError as e: logging.error(("command '%s' failed with status %d.%s"), " ".join(e.cmd), e.returncode, " Details: " + e.output if e.output else "") return 0 if __name__ == '__main__': sys.exit(main())
1,941
544
<reponame>RamakrishnaChilaka/submarine<filename>submarine-test/test-e2e/src/test/java/org/apache/submarine/integration/pages/LoginPage.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.submarine.integration.pages; import org.openqa.selenium.By; import org.apache.submarine.AbstractSubmarineIT; import org.openqa.selenium.WebDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory; public class LoginPage extends AbstractSubmarineIT{ public By userNameInput = By.cssSelector("input[ng-reflect-name='userName']"); public By passwordInput = By.cssSelector("input[ng-reflect-name='password']"); public By signInButton = By.xpath("//span[text()='Sign In']/parent::button"); public By userNameSignInWarning = By.xpath("//div[contains(text(), \"Please input your username!\")]"); public By passwordSignInWarning = By.xpath("//div[contains(text(), \"Please input your Password!\")]"); public By warningText = By.xpath("//div[contains(text(), \"Username and password are incorrect,\")]"); public void Login() { String username = "admin"; String password = "<PASSWORD>"; waitToPresent(userNameInput, MAX_BROWSER_TIMEOUT_SEC).sendKeys(username); waitToPresent(passwordInput, MAX_BROWSER_TIMEOUT_SEC).sendKeys(password); Click(signInButton, MAX_BROWSER_TIMEOUT_SEC); waitToPresent(By.cssSelector("a[routerlink='/workbench/experiment']"), MAX_BROWSER_TIMEOUT_SEC); } }
730
344
<filename>api/video/video_frame_metadata_unittest.cc<gh_stars>100-1000 /* * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "api/video/video_frame_metadata.h" #include "modules/rtp_rtcp/source/rtp_video_header.h" #include "test/gmock.h" #include "test/gtest.h" namespace webrtc { namespace { using ::testing::ElementsAre; using ::testing::IsEmpty; TEST(VideoFrameMetadata, GetWidthReturnsCorrectValue) { RTPVideoHeader video_header; video_header.width = 1280u; VideoFrameMetadata metadata(video_header); EXPECT_EQ(metadata.GetWidth(), video_header.width); } TEST(VideoFrameMetadata, GetHeightReturnsCorrectValue) { RTPVideoHeader video_header; video_header.height = 720u; VideoFrameMetadata metadata(video_header); EXPECT_EQ(metadata.GetHeight(), video_header.height); } TEST(VideoFrameMetadata, GetFrameIdReturnsCorrectValue) { RTPVideoHeader video_header; RTPVideoHeader::GenericDescriptorInfo& generic = video_header.generic.emplace(); generic.frame_id = 10; VideoFrameMetadata metadata(video_header); EXPECT_EQ(metadata.GetFrameId().value(), 10); } TEST(VideoFrameMetadata, HasNoFrameIdForHeaderWithoutGeneric) { RTPVideoHeader video_header; VideoFrameMetadata metadata(video_header); ASSERT_FALSE(video_header.generic); EXPECT_EQ(metadata.GetFrameId(), absl::nullopt); } TEST(VideoFrameMetadata, GetSpatialIndexReturnsCorrectValue) { RTPVideoHeader video_header; RTPVideoHeader::GenericDescriptorInfo& generic = video_header.generic.emplace(); generic.spatial_index = 2; VideoFrameMetadata metadata(video_header); EXPECT_EQ(metadata.GetSpatialIndex(), 2); } TEST(VideoFrameMetadata, SpatialIndexIsZeroForHeaderWithoutGeneric) { RTPVideoHeader video_header; VideoFrameMetadata metadata(video_header); ASSERT_FALSE(video_header.generic); EXPECT_EQ(metadata.GetSpatialIndex(), 0); } TEST(VideoFrameMetadata, GetTemporalIndexReturnsCorrectValue) { RTPVideoHeader video_header; RTPVideoHeader::GenericDescriptorInfo& generic = video_header.generic.emplace(); generic.temporal_index = 3; VideoFrameMetadata metadata(video_header); EXPECT_EQ(metadata.GetTemporalIndex(), 3); } TEST(VideoFrameMetadata, TemporalIndexIsZeroForHeaderWithoutGeneric) { RTPVideoHeader video_header; VideoFrameMetadata metadata(video_header); ASSERT_FALSE(video_header.generic); EXPECT_EQ(metadata.GetTemporalIndex(), 0); } TEST(VideoFrameMetadata, GetFrameDependenciesReturnsCorrectValue) { RTPVideoHeader video_header; RTPVideoHeader::GenericDescriptorInfo& generic = video_header.generic.emplace(); generic.dependencies = {5, 6, 7}; VideoFrameMetadata metadata(video_header); EXPECT_THAT(metadata.GetFrameDependencies(), ElementsAre(5, 6, 7)); } TEST(VideoFrameMetadata, FrameDependencyVectorIsEmptyForHeaderWithoutGeneric) { RTPVideoHeader video_header; VideoFrameMetadata metadata(video_header); ASSERT_FALSE(video_header.generic); EXPECT_THAT(metadata.GetFrameDependencies(), IsEmpty()); } TEST(VideoFrameMetadata, GetDecodeTargetIndicationsReturnsCorrectValue) { RTPVideoHeader video_header; RTPVideoHeader::GenericDescriptorInfo& generic = video_header.generic.emplace(); generic.decode_target_indications = {DecodeTargetIndication::kSwitch}; VideoFrameMetadata metadata(video_header); EXPECT_THAT(metadata.GetDecodeTargetIndications(), ElementsAre(DecodeTargetIndication::kSwitch)); } TEST(VideoFrameMetadata, DecodeTargetIndicationsVectorIsEmptyForHeaderWithoutGeneric) { RTPVideoHeader video_header; VideoFrameMetadata metadata(video_header); ASSERT_FALSE(video_header.generic); EXPECT_THAT(metadata.GetDecodeTargetIndications(), IsEmpty()); } } // namespace } // namespace webrtc
1,335
14,668
<filename>third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.cc // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/bindings/core/v8/v8_context_snapshot.h" namespace blink { namespace { V8ContextSnapshot::CreateContextFromSnapshotFuncType g_create_context_from_snapshot_func; V8ContextSnapshot::InstallContextIndependentPropsFuncType g_install_context_independent_props_func; V8ContextSnapshot::EnsureInterfaceTemplatesFuncType g_ensure_interface_templates_func; V8ContextSnapshot::TakeSnapshotFuncType g_take_snapshot_func; V8ContextSnapshot::GetReferenceTableFuncType g_get_reference_table_func; } // namespace v8::Local<v8::Context> V8ContextSnapshot::CreateContextFromSnapshot( v8::Isolate* isolate, const DOMWrapperWorld& world, v8::ExtensionConfiguration* extension_config, v8::Local<v8::Object> global_proxy, Document* document) { return g_create_context_from_snapshot_func(isolate, world, extension_config, global_proxy, document); } void V8ContextSnapshot::InstallContextIndependentProps( ScriptState* script_state) { return g_install_context_independent_props_func(script_state); } void V8ContextSnapshot::EnsureInterfaceTemplates(v8::Isolate* isolate) { return g_ensure_interface_templates_func(isolate); } v8::StartupData V8ContextSnapshot::TakeSnapshot() { return g_take_snapshot_func(); } const intptr_t* V8ContextSnapshot::GetReferenceTable() { return g_get_reference_table_func(); } void V8ContextSnapshot::SetCreateContextFromSnapshotFunc( CreateContextFromSnapshotFuncType func) { DCHECK(!g_create_context_from_snapshot_func); DCHECK(func); g_create_context_from_snapshot_func = func; } void V8ContextSnapshot::SetInstallContextIndependentPropsFunc( InstallContextIndependentPropsFuncType func) { DCHECK(!g_install_context_independent_props_func); DCHECK(func); g_install_context_independent_props_func = func; } void V8ContextSnapshot::SetEnsureInterfaceTemplatesFunc( EnsureInterfaceTemplatesFuncType func) { DCHECK(!g_ensure_interface_templates_func); DCHECK(func); g_ensure_interface_templates_func = func; } void V8ContextSnapshot::SetTakeSnapshotFunc(TakeSnapshotFuncType func) { DCHECK(!g_take_snapshot_func); DCHECK(func); g_take_snapshot_func = func; } void V8ContextSnapshot::SetGetReferenceTableFunc( GetReferenceTableFuncType func) { DCHECK(!g_get_reference_table_func); DCHECK(func); g_get_reference_table_func = func; } } // namespace blink
959
357
/* * MIT License * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package com.github.weisj.darklaf.ui.button; import java.util.Collections; import java.util.List; import javax.swing.*; import com.github.weisj.darklaf.components.help.HelpButton; import com.github.weisj.darklaf.components.help.HelpMenuItem; import com.github.weisj.darklaf.ui.demo.BaseComponentDemo; import com.github.weisj.darklaf.ui.demo.DemoExecutor; public class HelpButtonDemo extends BaseComponentDemo { public static void main(final String[] args) { DemoExecutor.showDemo(new HelpButtonDemo()); } @Override public JComponent createComponent() { return new HelpButton(); } @Override protected void init() { booleanSpec("enabled", JComponent::setEnabled, JComponent::isEnabled); booleanSpec("focusable", JComponent::setFocusable, JComponent::isFocusable); booleanSpec("Rollover", AbstractButton::setRolloverEnabled, AbstractButton::isRolloverEnabled); booleanSpec("ColoredIcon", HelpButton::setUseColoredIcon, HelpButton::isUseColoredIcon); } @Override public List<JMenu> createMenus() { return Collections.singletonList(new JMenu("Help") { { add(new HelpMenuItem("View Help")); } }); } @Override public String getName() { return "Help Button Demo"; } }
802
1,144
#include "pulseaudio.hh" #include <cmath> #include <list> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sstream> #include <string> #include <fstream> using namespace std; #ifdef __cplusplus extern "C" { #endif typedef enum { STREAM_AUDIO = 0, STREAM_TTS, STREAM_RING, STREAM_VOICE_CALL, STREAM_ALARM, STREAM_PLAYBACK, STREAM_SYSTEM, STREAM_TYPE_NUM, } rk_stream_type_t; const char* g_stream_type[STREAM_TYPE_NUM] = { "audio", "tts", "ring", "voiceCall", "alarm", "playback", "system" }; static Pulseaudio pulse("rokid"); static int bUseCustomVolumeCurve = 0; static int bLoadCustomVolumeCurve = 0; static int CustomVolArray[101] = {}; static const char* VOLUME_CURVE_FILE = "/etc/volume/volumecurve.txt"; int rk_custom_changeto_pactlVolume(int vol) { return CustomVolArray[vol]; } int rk_custom_changeForm_pactl_volume(int vol) { for (int i = 0; i <= 100; i++) { if (CustomVolArray[i] == vol) return i; } return -1; } int rk_initCustomVolumeCurve(); int rk_changeto_pactl_volume(int vol) { int volume = 0; if (!bUseCustomVolumeCurve && !bLoadCustomVolumeCurve) { int ret = rk_initCustomVolumeCurve(); if (ret >= 0) { bUseCustomVolumeCurve = 1; } bLoadCustomVolumeCurve = 1; } if (bUseCustomVolumeCurve) { volume = rk_custom_changeto_pactlVolume(vol); } else { // new_value = pa_sw_volume_from_linear(vol / 100.0); // new_value = (int) round (sqrt((double) vol / 100.0) * (double) PA_VOLUME_NORM ); // new_value = (int) round ((double) vol / 100.0 * (double) PA_VOLUME_NORM ); if (vol != 0) volume = (vol + 156) * (vol + 156); else volume = 0; } // printf("%s vol[%d] volume[%d]\n",__FUNCTION__,vol,volume); return volume; } int rk_changeForm_pactl_volume(int vol) { int volume = 0; if (bUseCustomVolumeCurve) { volume = rk_custom_changeForm_pactl_volume(vol); } else { if (vol != 0) volume = (int)round(sqrt(vol)) - 156; else volume = 0; } // printf("%s vol[%d] volume[%d]\n",__FUNCTION__,vol,volume); return volume; } int rk_setCustomVolumeCurve(int cnt, int* VolArray) { printf("rk_setCustomVolumeCurve:%d\n", cnt); if (cnt != 101) return -1; bUseCustomVolumeCurve = 1; for (int i = 0; i < cnt; i++) { CustomVolArray[i] = VolArray[i]; // printf("CustomVolArray[%d]:%d\n",i,CustomVolArray[i]); } return 0; } int rk_initCustomVolumeCurve() { ifstream fin(VOLUME_CURVE_FILE); string str; int count = 0; int volArray[101] = { 0 }; if (!fin.is_open()) { printf("Failed to open %s!\n", VOLUME_CURVE_FILE); return -1; } while (!fin.eof() && (count < 101)) { getline(fin, str); stringstream ss; ss << str; ss >> volArray[count]; count++; } int ret = rk_setCustomVolumeCurve(count, volArray); if (ret < 0) { return -1; } return 0; } int rk_set_all_volume(int vol) { pa_volume_t new_value = 0; pthread_mutex_lock(&pulse.lock); Device device = pulse.get_default_sink(); new_value = rk_changeto_pactl_volume(vol); if (new_value > PA_VOLUME_MAX) new_value = PA_VOLUME_MAX; pulse.set_volume(device, new_value); pthread_mutex_unlock(&pulse.lock); return 0; } int rk_get_all_volume() { pa_volume_t avgvol; int vol; double tmp; pthread_mutex_lock(&pulse.lock); Device device = pulse.get_default_sink(); pthread_mutex_unlock(&pulse.lock); avgvol = pa_cvolume_avg(&device.volume); vol = rk_changeForm_pactl_volume(avgvol); // vol = (int) round (tmp * tmp * 100.0); // vol = (int) round ((double) avgvol / (double) PA_VOLUME_NORM * 100.0); return vol; } int rk_set_mute(bool mute) { pthread_mutex_lock(&pulse.lock); Device device = pulse.get_default_sink(); pulse.set_mute(device, mute); pthread_mutex_unlock(&pulse.lock); return 0; } bool rk_is_mute() { pthread_mutex_lock(&pulse.lock); Device device = pulse.get_default_sink(); pthread_mutex_unlock(&pulse.lock); return device.mute; } int rk_set_volume(int vol) { pa_volume_t new_value = 0; pthread_mutex_lock(&pulse.lock); Device device = pulse.get_default_sink(); new_value = rk_changeto_pactl_volume(vol); if (new_value > PA_VOLUME_MAX) new_value = PA_VOLUME_MAX; for (Device& sinkinput : pulse.get_sinkinputs()) { if (strcmp(g_stream_type[STREAM_ALARM], (const char*)sinkinput.name.c_str()) && device.index == sinkinput.sink) pulse.set_volume(sinkinput, new_value); } pthread_mutex_unlock(&pulse.lock); return 0; } int rk_get_volume() { pa_volume_t avgvol; int vol = -1; double tmp; pthread_mutex_lock(&pulse.lock); Device device = pulse.get_default_sink(); for (Device& sinkinput : pulse.get_sinkinputs()) { if ((!strcmp(g_stream_type[STREAM_AUDIO], (const char*)sinkinput.name.c_str()) || !strcmp(g_stream_type[STREAM_TTS], (const char*)sinkinput.name.c_str())) && device.index == sinkinput.sink) { // vol = (int) round(pa_sw_volume_to_linear(sinkinput.volume_avg) * 100.0) tmp = (double)sinkinput.volume_avg / (double)PA_VOLUME_NORM; // vol = (int) round (tmp * tmp * 100.0); vol = (int)round(tmp * 100.0); break; } } pthread_mutex_unlock(&pulse.lock); return vol; } int rk_set_tag_volume(const char* tag, int vol) { if (!tag || strlen(tag) == 0) { return -1; } bool hit = false; pa_volume_t new_value = 0; pthread_mutex_lock(&pulse.lock); Device device = pulse.get_default_sink(); new_value = rk_changeto_pactl_volume(vol); if (new_value > PA_VOLUME_MAX) new_value = PA_VOLUME_MAX; for (Device& sinkinput : pulse.get_sinkinputs()) { if (!strcmp(tag, (const char*)sinkinput.name.c_str()) && device.index == sinkinput.sink) { hit = true; pulse.set_volume(sinkinput, new_value); } } if (!hit) { pulse.set_volume_store(tag, new_value); printf("set volume at the stream not new,media name=%s\n", tag); } pthread_mutex_unlock(&pulse.lock); return 0; } int rk_get_tag_volume(const char* tag) { if (!tag || strlen(tag) == 0) { return -1; } pa_volume_t avgvol; int vol = -1; double tmp; pthread_mutex_lock(&pulse.lock); Device device = pulse.get_default_sink(); for (Device& sinkinput : pulse.get_sinkinputs()) { if (!strcmp(tag, (const char*)sinkinput.name.c_str()) && device.index == sinkinput.sink) { // vol = (int) round(pa_sw_volume_to_linear(sinkinput.volume_avg) * 100.0); // tmp = (double) sinkinput.volume_avg / (double) PA_VOLUME_NORM; // vol = (int) round (tmp * tmp * 100.0); vol = rk_changeForm_pactl_volume(sinkinput.volume_avg); break; } } pthread_mutex_unlock(&pulse.lock); return vol; } int rk_set_tag_mute(const char* tag, bool mute) { if (!tag || strlen(tag) == 0) { return -1; } pthread_mutex_lock(&pulse.lock); Device device = pulse.get_default_sink(); for (Device& sinkinput : pulse.get_sinkinputs()) { if (!strcmp(tag, (const char*)sinkinput.name.c_str()) && device.index == sinkinput.sink) pulse.set_mute(sinkinput, mute); } pthread_mutex_unlock(&pulse.lock); return 0; } bool rk_is_tag_mute(const char* tag) { if (!tag || strlen(tag) == 0) { return -1; } pthread_mutex_lock(&pulse.lock); Device device = pulse.get_default_sink(); for (Device& sinkinput : pulse.get_sinkinputs()) { if (!strcmp(tag, (const char*)sinkinput.name.c_str()) && device.index == sinkinput.sink) { pthread_mutex_unlock(&pulse.lock); return sinkinput.mute; } } pthread_mutex_unlock(&pulse.lock); return -1; } int rk_get_tag_playing_status(const char* tag) { if (!tag || strlen(tag) == 0) { return -1; } pthread_mutex_lock(&pulse.lock); Device device = pulse.get_default_sink(); for (Device& sinkinput : pulse.get_sinkinputs()) { if (!strcmp(tag, (const char*)sinkinput.name.c_str())) { pthread_mutex_unlock(&pulse.lock); return 1; } } pthread_mutex_unlock(&pulse.lock); return 0; } int rk_set_stream_volume(rk_stream_type_t stream_type, int vol) { if (stream_type < 0 || stream_type >= STREAM_TYPE_NUM) return -1; return rk_set_tag_volume(g_stream_type[stream_type], vol); } int rk_get_stream_volume(rk_stream_type_t stream_type) { if (stream_type < 0 || stream_type >= STREAM_TYPE_NUM) return -1; return rk_get_tag_volume(g_stream_type[stream_type]); } int rk_set_stream_mute(rk_stream_type_t stream_type, bool mute) { if (stream_type < 0 || stream_type >= STREAM_TYPE_NUM) return -1; return rk_set_tag_mute(g_stream_type[stream_type], mute); } bool rk_is_stream_mute(rk_stream_type_t stream_type) { if (stream_type < 0 || stream_type >= STREAM_TYPE_NUM) return -1; return rk_is_tag_mute(g_stream_type[stream_type]); } int rk_get_stream_playing_status(rk_stream_type_t stream_type) { if (stream_type < 0 || stream_type >= STREAM_TYPE_NUM) return 0; return rk_get_tag_playing_status(g_stream_type[stream_type]); } /* old interface */ int set_app_volume(char* name, int vol) { return -1; } int get_app_volume(char* name) { return -1; } int set_sink_mute(int mute) { return -1; } #ifdef __cplusplus } #endif
6,064
703
<reponame>wangyuxin11/NewsRecommendSystem package top.qianxinyao.main; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.quartz.SchedulerException; import top.qianxinyao.UserBasedCollaborativeRecommender.MahoutUserBasedCollaborativeRecommender; import top.qianxinyao.UserBasedCollaborativeRecommender.quartz.CFCronTriggerRunner; import top.qianxinyao.algorithms.PropGetKit; import top.qianxinyao.algorithms.RecommendKit; import top.qianxinyao.contentbasedrecommend.ContentBasedRecommender; import top.qianxinyao.contentbasedrecommend.quartz.CBCronTriggerRunner; import top.qianxinyao.dbconnection.DBKit; import top.qianxinyao.hotrecommend.HotRecommender; import top.qianxinyao.hotrecommend.quartz.HRCronTriggerRunner; /** * @author <NAME> * @email <EMAIL> * @github https://github.com/bluemapleman * @date 2017年12月11日 * 设定/启动推荐任务的类 */ public class JobSetter { public static final Logger logger=Logger.getLogger(JobSetter.class); boolean enableCF,enableCB,enableHR; /** * * @param enableCF 是否启用协同过滤(Collaborative Filtering) * @param enableCB 是否启用基于内容的推荐(Content-Based Recommendation) * @param enableHR 是否启用热点新闻推荐(Hot News Recommendation) */ public JobSetter(boolean enableCF,boolean enableCB,boolean enableHR) { //加载系统配置文件 PropGetKit.loadProperties("paraConfig"); //初始化操作:主要是数据库的连接 DBKit.initalize(); this.enableCF=enableCF; this.enableCB=enableCB; this.enableHR=enableHR; } /** * 使用Quartz的表达式进行时间设定(默认为每天0点开始工作),详情请参照:http://www.quartz-scheduler.org/api/2.2.1/index.html(CronExpression) * 当启用该方法时,推荐系统可以保持运行,直到被强制关闭。 * @param userList */ private void executeQuartzJob(List<Long> userList) { //设定推荐任务每天的执行时间 String cronExpression=PropGetKit.getString("startAt"); try { if(enableCF) new CFCronTriggerRunner().task(userList,cronExpression); if(enableCB) new CBCronTriggerRunner().task(userList,cronExpression); if(enableHR) new HRCronTriggerRunner().task(userList,cronExpression); } catch (SchedulerException e) { e.printStackTrace(); } System.out.println("本次推荐结束于"+new Date()); } /** * 为指定用户执行定时新闻推荐 * @param goalUserList 目标用户的id列表 */ public void executeQuartzJobForCertainUsers(List<Long> goalUserList) { executeQuartzJob(goalUserList); } /** * 为所有用户执行定时新闻推荐 */ public void executeQuartzJobForAllUsers() { executeQuartzJob(RecommendKit.getAllUsers()); } /** * 为活跃用户进行定时新闻推荐。 * @param goalUserList */ public void executeQuartzJobForActiveUsers() { executeQuartzJob(RecommendKit.getActiveUsers()); } /** * 执行一次新闻推荐 * 参数forActiveUsers表示是否只针对活跃用户进行新闻推荐,true为是,false为否。 * @param forActiveUsers */ private void executeInstantJob(List<Long> userIDList) { //让热点新闻推荐器预先生成今日的热点新闻 HotRecommender.formTodayTopHotNewsList(); if(enableCF) new MahoutUserBasedCollaborativeRecommender().recommend(userIDList); if(enableCB) new ContentBasedRecommender().recommend(userIDList); if(enableHR) new HotRecommender().recommend(userIDList); System.out.println("本次推荐结束于"+new Date()); } /** * 执行一次新闻推荐 * 参数forActiveUsers表示是否只针对活跃用户进行新闻推荐,true为是,false为否。 * @param forActiveUsers */ public void executeInstantJobForCertainUsers(List<Long> goalUserList) { executeInstantJob(goalUserList); } /** * 为所用有用户执行一次新闻推荐 */ public void executeInstantJobForAllUsers() { executeInstantJob(RecommendKit.getAllUsers()); } /** * 为活跃用户进行一次推荐。 * @param goalUserList */ public void executeInstantJobForActiveUsers() { executeInstantJob(RecommendKit.getActiveUsers()); } }
1,921
14,425
<filename>hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/AWSStatus500Exception.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs.s3a; import com.amazonaws.AmazonServiceException; /** * A 500 response came back from a service. * This is considered <i>probably</i> retriable, That is, we assume * <ol> * <li>whatever error happened in the service itself to have happened * before the infrastructure committed the operation.</li> * <li>Nothing else got through either.</li> * </ol> */ public class AWSStatus500Exception extends AWSServiceIOException { public AWSStatus500Exception(String operation, AmazonServiceException cause) { super(operation, cause); } }
413
5,169
<filename>Specs/d/6/f/FlatNetworkClient/0.1.1/FlatNetworkClient.podspec.json { "name": "FlatNetworkClient", "version": "0.1.1", "summary": "Simple wrapper around URLSession", "description": "A simple wrapper around URLSession. Built to provide easy implementation and provide testable features.", "homepage": "https://github.com/flatcircle/FlatNetworkClient", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "9.0" }, "source": { "git": "https://github.com/flatcircle/FlatNetworkClient.git", "tag": "0.1.1" }, "source_files": "FlatNetworkClient/*", "pushed_with_swift_version": "3.0" }
249
765
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ #ifndef __TLM_CORE_1_REQ_RSP_CHANNELS_FIFO_FIFO_PEEK_HH__ #define __TLM_CORE_1_REQ_RSP_CHANNELS_FIFO_FIFO_PEEK_HH__ namespace tlm { template <typename T> inline T tlm_fifo<T>::peek(tlm_tag<T> *) const { while (is_empty()) { // call free-standing sc_core::wait(), // since sc_prim_channel::wait(.) is not const sc_core::wait(m_data_written_event); } return buffer.read_data(); } template <typename T> inline bool tlm_fifo<T>::nb_peek(T &t) const { if (used() < 1) { return false; } t = buffer.peek_data(0); return true; } template <typename T> inline bool tlm_fifo<T>::nb_peek(T &t, int n) const { if (n >= used() || n < -1) { return false; } if (n == -1) { n = used() - 1; } t = buffer.peek_data(n); return true; } template <typename T> inline bool tlm_fifo<T>::nb_can_peek(tlm_tag<T> *) const { return !is_empty(); } template <typename T> inline bool tlm_fifo<T>::nb_poke(const T &t, int n) { if (n >= used() || n < 0) { return false; } buffer.poke_data(n) = t; return true; } } // namespace tlm #endif /* __TLM_CORE_1_REQ_RSP_CHANNELS_FIFO_FIFO_PEEK_HH__ */
810
2,757
/*++ Copyright (c) 2004, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. Module Name: PeiInMemory.c Abstract: Capsule on Fat Usb Disk GUID. This is the contract between the recovery module and device recovery module in order to convey the name of a given recovery module type --*/ #include "Tiano.h" #include "PeiBind.h" #include "PeiApi.h" #include EFI_PPI_DEFINITION(PeiInMemory) EFI_GUID gPeiInMemoryGuid = PEI_IN_MEMORY_GUID; EFI_GUID_STRING(&gPeiInMemoryGuid, "PeiInMemory", "PEIM In Memory");
542
416
<filename>iPhoneOS14.2.sdk/System/Library/Frameworks/StoreKit.framework/Headers/SKError.h // // SKError.h // StoreKit // // Copyright 2009 Apple, Inc. All rights reserved. // #import <Foundation/Foundation.h> #import <StoreKit/StoreKitDefines.h> NS_ASSUME_NONNULL_BEGIN SK_EXTERN NSString * const SKErrorDomain API_AVAILABLE(ios(3.0), tvos(9.0), macos(10.7), watchos(6.2)); // error codes for the SKErrorDomain typedef NS_ENUM(NSInteger,SKErrorCode) { SKErrorUnknown, SKErrorClientInvalid, // client is not allowed to issue the request, etc. SKErrorPaymentCancelled, // user cancelled the request, etc. SKErrorPaymentInvalid, // purchase identifier was invalid, etc. SKErrorPaymentNotAllowed, // this device is not allowed to make the payment SKErrorStoreProductNotAvailable API_AVAILABLE(ios(3.0), macos(10.15), watchos(6.2)), // Product is not available in the current storefront SKErrorCloudServicePermissionDenied API_AVAILABLE(ios(9.3), tvos(9.3), watchos(6.2), macos(11.0)), // user has not allowed access to cloud service information SKErrorCloudServiceNetworkConnectionFailed API_AVAILABLE(ios(9.3), tvos(9.3), watchos(6.2), macos(11.0)), // the device could not connect to the nework SKErrorCloudServiceRevoked API_AVAILABLE(ios(10.3), tvos(10.3), watchos(6.2), macos(11.0)), // user has revoked permission to use this cloud service SKErrorPrivacyAcknowledgementRequired API_AVAILABLE(ios(12.2), tvos(12.2), macos(10.14.4), watchos(6.2)), // The user needs to acknowledge Apple's privacy policy SKErrorUnauthorizedRequestData API_AVAILABLE(ios(12.2), macos(10.14.4), watchos(6.2)), // The app is attempting to use SKPayment's requestData property, but does not have the appropriate entitlement SKErrorInvalidOfferIdentifier API_AVAILABLE(ios(12.2), macos(10.14.4), watchos(6.2)), // The specified subscription offer identifier is not valid SKErrorInvalidSignature API_AVAILABLE(ios(12.2), macos(10.14.4), watchos(6.2)), // The cryptographic signature provided is not valid SKErrorMissingOfferParams API_AVAILABLE(ios(12.2), macos(10.14.4), watchos(6.2)), // One or more parameters from SKPaymentDiscount is missing SKErrorInvalidOfferPrice API_AVAILABLE(ios(12.2), macos(10.14.4), watchos(6.2)), // The price of the selected offer is not valid (e.g. lower than the current base subscription price) SKErrorOverlayCancelled API_AVAILABLE(ios(12.2), macos(10.14.4), watchos(6.2)), SKErrorOverlayInvalidConfiguration API_AVAILABLE(ios(14.0)) API_UNAVAILABLE(macos, watchos) __TVOS_PROHIBITED, SKErrorOverlayTimeout API_AVAILABLE(ios(14.0)) API_UNAVAILABLE(macos, watchos) __TVOS_PROHIBITED, SKErrorIneligibleForOffer API_AVAILABLE(ios(14.0), macos(11.0), watchos(7.0)), // User is not eligible for the subscription offer SKErrorUnsupportedPlatform API_AVAILABLE(ios(14.0), macos(11.0), watchos(7.0)) __TVOS_PROHIBITED, } API_AVAILABLE(ios(3.0), macos(10.7), watchos(6.2)); NS_ASSUME_NONNULL_END
1,661
386
<reponame>cSingleboy/TarsCpp #ifndef _TRAN_IMP_H_ #define _TRAN_IMP_H_ #include <map> #include <string> #include <vector> #include "servant/Application.h" using namespace std; using namespace tars; ///////////////////////////////////////////////////////////////////////// class TranImp : public Servant { public: /** * 构造函数 */ TranImp(); public: /** * 对象初始化 */ virtual void initialize(); /** * 处理客户端的主动请求 * @param current * @param response * @return int */ virtual int doRequest(tars::CurrentPtr current, vector<char> &response); /** * @param resp * @return int */ virtual int doResponse(ReqMessagePtr resp); /** * 对象销毁 */ virtual void destroy(); protected: void async_call(tars::CurrentPtr current, vector<char> &response); protected: ServantPrx _servantPrx; }; /////////////////////////////////////////////////////////////////////////////// #endif
463
19,046
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/experimental/coro/SharedMutex.h> #if FOLLY_HAS_COROUTINES using namespace folly::coro; SharedMutexFair::~SharedMutexFair() { assert(state_.lock()->lockedFlagAndReaderCount_ == kUnlocked); assert(state_.lock()->waitersHead_ == nullptr); } bool SharedMutexFair::try_lock() noexcept { auto lock = state_.contextualLock(); if (lock->lockedFlagAndReaderCount_ == kUnlocked) { lock->lockedFlagAndReaderCount_ = kExclusiveLockFlag; return true; } return false; } bool SharedMutexFair::try_lock_shared() noexcept { auto lock = state_.contextualLock(); if (lock->lockedFlagAndReaderCount_ == kUnlocked || (lock->lockedFlagAndReaderCount_ >= kSharedLockCountIncrement && lock->waitersHead_ == nullptr)) { lock->lockedFlagAndReaderCount_ += kSharedLockCountIncrement; return true; } return false; } void SharedMutexFair::unlock() noexcept { LockAwaiterBase* awaitersToResume = nullptr; { auto lockedState = state_.contextualLock(); assert(lockedState->lockedFlagAndReaderCount_ == kExclusiveLockFlag); awaitersToResume = unlockOrGetNextWaitersToResume(*lockedState); } resumeWaiters(awaitersToResume); } void SharedMutexFair::unlock_shared() noexcept { LockAwaiterBase* awaitersToResume = nullptr; { auto lockedState = state_.contextualLock(); assert(lockedState->lockedFlagAndReaderCount_ >= kSharedLockCountIncrement); lockedState->lockedFlagAndReaderCount_ -= kSharedLockCountIncrement; if (lockedState->lockedFlagAndReaderCount_ != kUnlocked) { return; } awaitersToResume = unlockOrGetNextWaitersToResume(*lockedState); } resumeWaiters(awaitersToResume); } SharedMutexFair::LockAwaiterBase* SharedMutexFair::unlockOrGetNextWaitersToResume( SharedMutexFair::State& state) noexcept { auto* head = state.waitersHead_; if (head != nullptr) { if (head->lockType_ == LockType::EXCLUSIVE) { state.waitersHead_ = std::exchange(head->nextAwaiter_, nullptr); state.lockedFlagAndReaderCount_ = kExclusiveLockFlag; } else { std::size_t newState = kSharedLockCountIncrement; // Scan for a run of SHARED lock types. auto* last = head; auto* next = last->nextAwaiter_; while (next != nullptr && next->lockType_ == LockType::SHARED) { last = next; next = next->nextAwaiter_; newState += kSharedLockCountIncrement; } last->nextAwaiter_ = nullptr; state.lockedFlagAndReaderCount_ = newState; state.waitersHead_ = next; } if (state.waitersHead_ == nullptr) { state.waitersTailNext_ = &state.waitersHead_; } } else { state.lockedFlagAndReaderCount_ = kUnlocked; } return head; } void SharedMutexFair::resumeWaiters(LockAwaiterBase* awaiters) noexcept { while (awaiters != nullptr) { std::exchange(awaiters, awaiters->nextAwaiter_)->resume(); } } #endif
1,251
335
{ "word": "Histogenesis", "definitions": [ "The differentiation of cells into specialized tissues and organs during growth." ], "parts-of-speech": "Noun" }
64
354
<reponame>iabernikhin/VK-GL-CTS #ifndef _GL3CTEXTURESIZEPROMOTION_HPP #define _GL3CTEXTURESIZEPROMOTION_HPP /*------------------------------------------------------------------------- * OpenGL Conformance Test Suite * ----------------------------- * * Copyright (c) 2015-2016 The Khronos Group 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. * */ /*! * \file * \brief */ /*-------------------------------------------------------------------*/ /** * \file gl3cTextureSizePromotionTests.hpp * \brief Declares test classes for testing of texture internal format promotion mechanism. */ /*-------------------------------------------------------------------*/ #include "glcTestCase.hpp" #include "glwDefs.hpp" #include "glwEnums.hpp" #include "tcuDefs.hpp" #include "tcuVector.hpp" namespace gl3cts { namespace TextureSizePromotion { /** Test group class for texture size promotion tests */ class Tests : public deqp::TestCaseGroup { public: /* Public member functions. */ Tests(deqp::Context& context); //!< Constructor. virtual ~Tests() { } //!< Destructor virtual void init(void); //!< Initialization member function. private: /* Private member functions. */ Tests(const Tests&); //!< Default copy constructor. Tests& operator=(const Tests&); //!< Default assign constructor. }; /** Functional Test Class * * This test verifies that implementation correctly selects sizes and types * when sized internal format is requested for a texture. * * This test should be executed only if context is at least 3.1. * * Steps: * - prepare a source texture so that each channel is filled with specific value; * - execute GetTexLevelPrameter to query all TEXTURE_*_SIZE and TEXTURE_*_TYPE * <pname>s corresponding with internal format of source texture; It is * expected that: * * reported sizes will be at least as specified; * * reported types will be exactly as specified; * - for each channel [R, G, B, A]: * * prepare a 2D single channeled texture with format matching sampled * channel and set it up as output color in framebuffer; * * prepare a program that will implement the following snippet in the * fragment stage and output the value of result: * * result = texelFetch(source).C; * * * clear output texture; * * draw a full-screen quad; * * verify that the output texture is filled with correct value; * * Value is correct when: * - it matches value assigned to the specified channel; * - it is one for missing alpha channel; * - it is zero for missing channel; * - it is one for ONE; * - it is zero for ZERO. * * Repeat the steps for all supported sized internal formats and targets. * * Depth-stencil textures can be sampled only via RED channel. Test should set * DEPTH_STENCIL_TEXTURE_MODE to select which channel will be accessed. * * For multisampled targets maximum supported number of samples should be used * and fetch should be done to last sample. * * Support of multisampled targets by TexParameter* routines was introduced in * extension GL_ARB_texture_storage_multisample, which is part of core * specification since 4.3. * * List of required texture formats was changed in 4.4. Therefore the list of * "supported sized internal formats" depends on context version. */ class FunctionalTest : public deqp::TestCase { public: /* Public member functions. */ FunctionalTest(deqp::Context& context); //!< Functional test constructor. virtual tcu::TestNode::IterateResult iterate(); //!< Member function to iterate over test cases. private: /* Private member variables. */ glw::GLuint m_vao; //!< Vertex Array Object name. glw::GLuint m_source_texture; //!< Source Texture Object name. glw::GLuint m_destination_texture; //!< Destination Texture Object name. glw::GLuint m_framebuffer; //!< Framebuffer Object name. glw::GLuint m_program; //!< Program Object name. glw::GLint m_max_samples; //!< Maximum samples available for usage in multisampled targets. /* Private type definitions. */ /** Texture Internal Format Description structure */ struct TextureInternalFormatDescriptor { glu::ContextType required_by_context; //!< Minimum context version by which format is required. glw::GLenum internal_format; //!< Texture internal format. const glw::GLchar* internal_format_name; //!< String representing texture internal format. bool is_sRGB; //!< Is this format described in sRGB space. bool is_color_renderable; //!< Is this format color renderable. glw::GLint min_red_size; //!< Minimum required red component resolution (in bits). glw::GLint min_green_size; //!< Minimum required green component resolution (in bits). glw::GLint min_blue_size; //!< Minimum required blue component resolution (in bits). glw::GLint min_alpha_size; //!< Minimum required alpha component resolution (in bits). glw::GLint min_depth_size; //!< Minimum required depth component resolution (in bits). glw::GLint min_stencil_size; //!< Minimum required stencil component resolution (in bits). glw::GLenum expected_red_type; //!< Expected type of red component. glw::GLenum expected_green_type; //!< Expected type of green component. glw::GLenum expected_blue_type; //!< Expected type of blue component. glw::GLenum expected_alpha_type; //!< Expected type of alpha component. glw::GLenum expected_depth_type; //!< Expected type of depth component. }; /** Color channels enumeration */ enum ColorChannelSelector { RED_COMPONENT, //!< Red component. GREEN_COMPONENT, //!< Green component. BLUE_COMPONENT, //!< Blue component. ALPHA_COMPONENT, //!< Alpha component (must be last color channel). COMPONENTS_COUNT //!< Number of components. }; /* Private class' static constants. */ static const glw::GLfloat s_source_texture_data_f[]; //!< Source texture for floating point type internal formats. static const glw::GLfloat s_source_texture_data_n[]; //!< Source texture for unsigned normalized integer type internal formats. static const glw::GLfloat s_source_texture_data_sn[]; //!< Source texture for signed normalized integer type internal formats. static const glw::GLint s_source_texture_data_i[]; //!< Source texture for signed integer type internal formats. static const glw::GLuint s_source_texture_data_ui[]; //!< Source texture for unsigned integer type internal formats. static const glw::GLuint s_source_texture_size; //!< Linear size of the source texture. static const glw::GLfloat s_destination_texture_data_f []; //!< Destination texture data (to be sure that it was overwritten) for floating point and normalized types internal formats. static const glw::GLint s_destination_texture_data_i []; //!< Destination texture data (to be sure that it was overwritten) signed integer type internal formats. static const glw::GLuint s_destination_texture_data_ui []; //!< Destination texture data (to be sure that it was overwritten) unsigned integer type internal formats. static const glw::GLenum s_source_texture_targets[]; //!< Targets to be tested. static const glw::GLchar* s_source_texture_targets_names[]; //!< Targets' names (strings) for logging purpose. static const glw::GLuint s_source_texture_targets_count; //!< Number of targets to be tested. static const glw::GLchar* s_color_channel_names[]; //!< Color channel names (like in enum) for logging purpose. static const glw::GLchar* s_vertex_shader_code; //!< Vertex shader source code for drawing quad depending on vertex ID of triangle strip. static const glw::GLchar* s_fragment_shader_template; //!< Fragment shader source code template. static const TextureInternalFormatDescriptor s_formats[]; //!< List of internal formats (and their descriptions) to be tested by Functional Test. static const glw::GLuint s_formats_size; //!< number of internal format to be tested. /* Private member functions. */ /** Generate and bind an empty Vertex Array Object. */ void prepareVertexArrayObject(); /** Generate, bind and upload source texture. * * @param [in] descriptor Internal format description. * @param [in] target Texture target to be used. */ void prepareSourceTexture(TextureInternalFormatDescriptor descriptor, glw::GLenum target); /** Generate, bind and clean destination texture. * * @param [in] descriptor Internal format description. * @param [in] target Texture target to be used. */ void prepareDestinationTextureAndFramebuffer(TextureInternalFormatDescriptor descriptor, glw::GLenum target); /** Preprocess, compile and linke GLSL program. * * @param [in] target Texture target to be used. * @param [in] descriptor Internal format description. * @param [in] channel Color channel to be tested. * * @return Program name on success, 0 on failure. */ glw::GLuint prepareProgram(glw::GLenum target, TextureInternalFormatDescriptor descriptor, ColorChannelSelector channel); /** Use GLSL program with source and destination textures. * * @param [in] target Texture target to be used. */ void makeProgramAndSourceTextureActive(glw::GLenum target); /** Check source texture queries. * * @param [in] descriptor Internal format description. * @param [in] target Texture target to be used. */ bool checkSourceTextureSizeAndType(TextureInternalFormatDescriptor descriptor, glw::GLenum target); /** Draw quad using GL_TRIANGLE_STRIP. */ void drawQuad(); /** Check rendered destination texture to match expected values. * * @param [in] descriptor Internal format description. * @param [in] channel Used color channel. * @param [in] target Texture target to be used. * @param [in] target_name Texture target name for logging purposes. * * @return True if fetched value matches expected value within the range of precission, false otherwise. */ bool checkDestinationTexture(TextureInternalFormatDescriptor descriptor, ColorChannelSelector channel, glw::GLenum target, const glw::GLchar* target_name); /** Clean source texture object. */ void cleanSourceTexture(); /** Clean framebuffer object. */ void cleanFramebuffer(); /** Clean destination texture object. */ void cleanDestinationTexture(); /** Clean program object. */ void cleanProgram(); /** Clean vertex array object object. */ void cleanVertexArrayObject(); /** Choose internal format of destination texture for rendered source texture. * * @param [in] descriptor Internal format description. */ glw::GLenum getDestinationFormatForChannel(TextureInternalFormatDescriptor descriptor); /** Is internal format a floating type. * * @param [in] descriptor Internal format description. * * @return True if internal format is floating point type, false otherwise. */ bool isFloatType(TextureInternalFormatDescriptor descriptor); /** Is internal format a fixed signed type. * * @param [in] descriptor Internal format description. * * @return True if internal format is fixed signed type, false otherwise. */ bool isFixedSignedType(TextureInternalFormatDescriptor descriptor); /** Is internal format a fixed unsigned type. * * @param [in] descriptor Internal format description. * * @return True if internal format is fixed unsigned type, false otherwise. */ bool isFixedUnsignedType(TextureInternalFormatDescriptor descriptor); /** Is internal format a signed integral type. * * @param [in] descriptor Internal format description. * * @return True if internal format is integral signed type, false otherwise. */ bool isIntegerSignedType(TextureInternalFormatDescriptor descriptor); /** Is internal format an unsigned integral type. * * @param [in] descriptor Internal format description. * * @return True if internal format is integral unsigned type, false otherwise. */ bool isIntegerUnsignedType(TextureInternalFormatDescriptor descriptor); /** Is internal format a depth type. * * @param [in] descriptor Internal format description. * * @return True if internal format is depth type, false otherwise. */ bool isDepthType(TextureInternalFormatDescriptor descriptor); /** Is internal format a stencil type. * * @param [in] descriptor Internal format description. * * @return True if internal format is stencil type, false otherwise. */ bool isStencilType(TextureInternalFormatDescriptor descriptor); /** Is channel of internal format a none type (does not appear in the texture internal format). * * @param [in] descriptor Internal format description. * @param [in] channel Color channel to be queried. * * @return True if internal format is none type, false otherwise. */ bool isChannelTypeNone(TextureInternalFormatDescriptor descriptor, ColorChannelSelector channel); /** Calculate minimal required precission for internal format's channel. * * @note It is needed only for floating point and normalized fixed point types. * * @param [in] descriptor Internal format description. * @param [in] channel Color channel to be queried. * * @return Minimum precission. */ glw::GLfloat getMinPrecision(TextureInternalFormatDescriptor descriptor, ColorChannelSelector channel); /** Is target multisample. * * @param [in] target Target. * * @return True if target is multisampled, false otherwise. */ bool isTargetMultisampled(glw::GLenum target); /** Render data to the source texture for multisampled texture. * * @param [in] descriptor Internal format description. * @param [in] target Texture target to be used. */ void renderDataIntoMultisampledTexture(TextureInternalFormatDescriptor descriptor, glw::GLenum target); /** Convert value from sRGB space to linear space. * * @param [in] value Value to be converted (sRGB space). * * @return Converted value (linear space). */ float convert_from_sRGB(float value); }; /* class TextureSizePromotion */ namespace Utilities { /** Build a GLSL program * * @param [in] gl OpenGL Functions Access. * @param [in] log Log outut. * @param [in] vertex_shader_source Pointer to C string of the vertex shader or NULL if not used. * @param [in] fragment_shader_source Pointer to C string of the fragment shader or NULL if not used. * * @return OpenGL program shader ID or zero if error had occured. */ glw::GLuint buildProgram(glw::Functions const& gl, tcu::TestLog& log, glw::GLchar const* const vertex_shader_source, glw::GLchar const* const fragment_shader_source); /** Preprocess source string by replacing key tokens with new values. * * @param [in] source Source string. * @param [in] key Key, substring to be replaced. * @param [in] value Value, substring to be substituted in place of key. * * @return Preprocessed string. */ std::string preprocessString(std::string source, std::string key, std::string value); /** @brief Convert an integer to a string. * * @param [in] i Integer to be converted. * * @return String representing integer. */ std::string itoa(glw::GLint i); } } /* TextureSizePromotion namespace */ } /* gl3cts namespace */ #endif // _GL3CTEXTURESIZEPROMOTION_HPP
4,964
8,747
<gh_stars>1000+ /** * Copyright 2020 Espressif Systems (Shanghai) PTE LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ESP_SCAN_I_H #define ESP_SCAN_I_H void esp_scan_init(struct wpa_supplicant *wpa_s); void esp_scan_deinit(struct wpa_supplicant *wpa_s); int esp_handle_beacon_probe(u8 type, u8 *frame, size_t len, u8 *sender, u32 rssi, u8 channel, u64 current_tsf); void esp_supplicant_handle_scan_done_evt(void); #endif
315
1,444
package mage.cards.k; import java.util.UUID; import mage.MageInt; import mage.abilities.common.AllyEntersBattlefieldTriggeredAbility; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.abilities.keyword.FirstStrikeAbility; import mage.abilities.keyword.VigilanceAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.counters.CounterType; /** * * @author North */ public final class KazanduBlademaster extends CardImpl { public KazanduBlademaster(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{W}{W}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.SOLDIER); this.subtype.add(SubType.ALLY); this.power = new MageInt(1); this.toughness = new MageInt(1); this.addAbility(FirstStrikeAbility.getInstance()); this.addAbility(VigilanceAbility.getInstance()); this.addAbility(new AllyEntersBattlefieldTriggeredAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance()), true)); } private KazanduBlademaster(final KazanduBlademaster card) { super(card); } @Override public KazanduBlademaster copy() { return new KazanduBlademaster(this); } }
501
4,772
<reponame>Balkerm/spring-data-examples package example.service; import example.repo.Customer1383Repository; import org.springframework.stereotype.Service; @Service public class Customer1383Service { public Customer1383Service(Customer1383Repository repo) {} }
80
1,644
<filename>core/src/test/java/google/registry/tools/CreatePremiumListCommandTest.java // Copyright 2017 The Nomulus Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package google.registry.tools; import static com.google.common.truth.Truth.assertThat; import static google.registry.testing.DatabaseHelper.createTld; import static org.junit.jupiter.api.Assertions.assertThrows; import com.google.common.io.Files; import google.registry.model.tld.Registry; import google.registry.model.tld.label.PremiumListDao; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** Unit tests for {@link CreatePremiumListCommand}. */ class CreatePremiumListCommandTest<C extends CreatePremiumListCommand> extends CreateOrUpdatePremiumListCommandTestCase<C> { Registry registry; @BeforeEach void beforeEach() { registry = createRegistry(TLD_TEST, null, null); } @Test void verify_registryIsSetUpCorrectly() { // ensure that no premium list is created before running the command // this check also implicitly verifies the TLD is successfully created; assertThat(PremiumListDao.getLatestRevision(TLD_TEST).isPresent()).isFalse(); } @Test void commandRun_successCreateList() throws Exception { runCommandForced("--name=" + TLD_TEST, "--input=" + premiumTermsPath, "--currency=USD"); assertThat(registry.getTld().toString()).isEqualTo(TLD_TEST); assertThat(PremiumListDao.getLatestRevision(TLD_TEST).isPresent()).isTrue(); } @Test // since the old entity is always null and file cannot be empty, the prompt will NOT be "No entity // changes to apply." void commandPrompt_successStageNewEntity() throws Exception { CreatePremiumListCommand command = new CreatePremiumListCommand(); command.inputFile = Paths.get(premiumTermsPath); command.currencyUnit = "USD"; command.prompt(); assertThat(command.prompt()).isEqualTo("Create new premium list for prime?"); } @Test void commandPrompt_successStageNewEntityWithOverride() throws Exception { CreatePremiumListCommand command = new CreatePremiumListCommand(); String alterTld = "override"; command.inputFile = Paths.get(premiumTermsPath); command.override = true; command.name = alterTld; command.currencyUnit = "USD"; command.prompt(); assertThat(command.prompt()).isEqualTo("Create new premium list for override?"); } @Test void commandPrompt_failureNoInputFile() { CreatePremiumListCommand command = new CreatePremiumListCommand(); assertThrows(NullPointerException.class, command::prompt); } @Test void commandPrompt_failurePremiumListAlreadyExists() { String randomStr = "random"; createTld(randomStr); CreatePremiumListCommand command = new CreatePremiumListCommand(); command.name = randomStr; command.currencyUnit = "USD"; IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, command::prompt); assertThat(thrown).hasMessageThat().isEqualTo("A premium list already exists by this name"); } @Test void commandPrompt_failureMismatchedTldFileName_noOverride() throws Exception { CreatePremiumListCommand command = new CreatePremiumListCommand(); String fileName = "random"; Path tmpPath = tmpDir.resolve(String.format("%s.txt", fileName)); Files.write(new byte[0], tmpPath.toFile()); command.inputFile = tmpPath; command.currencyUnit = "USD"; IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, command::prompt); assertThat(thrown) .hasMessageThat() .contains( String.format( "Premium names must match the name of the TLD they are " + "intended to be used on (unless --override is specified), " + "yet TLD %s does not exist", fileName)); } @Test void commandPrompt_failureMismatchedTldName_noOverride() { CreatePremiumListCommand command = new CreatePremiumListCommand(); String fileName = "random"; command.name = fileName; command.currencyUnit = "USD"; IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, command::prompt); assertThat(thrown) .hasMessageThat() .contains( String.format( "Premium names must match the name of the TLD they are " + "intended to be used on (unless --override is specified), " + "yet TLD %s does not exist", fileName)); } }
1,701
8,027
#include <lib4/lib4.h> int main() { return code(); }
27
935
#include "extern_socket.hpp" #include "fs.bragi.hpp" #include "protocols/fs/client.hpp" namespace { struct Socket : File { Socket(helix::UniqueLane sockLane) : File{StructName::get("extern-socket")}, _file{std::move(sockLane)} { } async::result<frg::expected<Error, PollWaitResult>> pollWait(Process *, uint64_t sequence, int mask, async::cancellation_token cancellation) override { auto resultOrError = co_await _file.pollWait(sequence, mask, cancellation); assert(resultOrError); co_return resultOrError.value(); } async::result<frg::expected<Error, PollStatusResult>> pollStatus(Process *) override { auto resultOrError = co_await _file.pollStatus(); assert(resultOrError); co_return resultOrError.value(); } helix::BorrowedDescriptor getPassthroughLane() override { return _file.getLane(); } private: protocols::fs::File _file; }; } namespace extern_socket { async::result<smarter::shared_ptr<File, FileHandle>> createSocket(helix::BorrowedLane lane, int domain, int type, int proto, int flags) { managarm::fs::CntRequest req; req.set_req_type(managarm::fs::CntReqType::CREATE_SOCKET); req.set_domain(domain); req.set_type(type); req.set_protocol(proto); req.set_flags(flags); auto req_data = req.SerializeAsString(); char buffer[128]; auto [offer, send_req, recv_resp, recv_lane] = co_await helix_ng::exchangeMsgs( lane, helix_ng::offer( helix_ng::sendBuffer(req_data.data(), req_data.size()), helix_ng::recvBuffer(buffer, sizeof(buffer)), helix_ng::pullDescriptor() ) ); HEL_CHECK(offer.error()); HEL_CHECK(send_req.error()); HEL_CHECK(recv_resp.error()); HEL_CHECK(recv_lane.error()); managarm::fs::SvrResponse resp; resp.ParseFromArray(buffer, recv_resp.actualLength()); assert(resp.error() == managarm::fs::Errors::SUCCESS); auto file = smarter::make_shared<Socket>(recv_lane.descriptor()); file->setupWeakFile(file); co_return File::constructHandle(file); } } // namespace extern_socket
759
2,338
#define T long long #define T_CSTR "long long" #ifdef __LP64__ #define T_VALUE_1 110011101111 #define T_VALUE_2 220022202222 #define T_VALUE_3 330033303333 #define T_VALUE_4 440044404444 #else #define T_VALUE_1 110011101 #define T_VALUE_2 220022202 #define T_VALUE_3 330033303 #define T_VALUE_4 440044404 #endif #define T_PRINTF_FORMAT "%lld" #include "basic_type.cpp"
159
3,651
/* * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * 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.orientechnologies.orient.test.java.lang; public class StringBrowsingSpeedTest { private static final String S = "OrientDB is an Open Source NoSQL DBMS with both the features of Document and Graph DBMSs. It's written in Java and it's amazing fast: can store up to 150,000 records per second on common hardware. Even if it's Document based database the relationships are managed as in Graph Databases with direct connections among records. You can traverse entire or part of trees and graphs of records in few milliseconds. Supports schema-less, schema-full and schema-mixed modes. Has a strong security profiling system based on user and roles and support the SQL between"; private static final int MAX = 1000000000; public static final void main(String[] args) { long timer = System.currentTimeMillis(); for (int i = 0; i < MAX; ++i) {} final long fixed = System.currentTimeMillis() - timer; final int len = S.length(); { timer = System.currentTimeMillis(); final char[] chars = S.toCharArray(); for (int i = 0; i < MAX; ++i) for (int k = 0; k < len; ++k) { final char c = chars[k]; } System.out.println("String chars[]: " + (System.currentTimeMillis() - timer - fixed)); } { timer = System.currentTimeMillis(); for (int i = 0; i < MAX; ++i) for (int k = 0; k < len; ++k) { final char c = S.charAt(k); } System.out.println("String charAt(): " + (System.currentTimeMillis() - timer - fixed)); } } }
688
368
// // DDRuntimeSwizzle.h // TeamTalk // // Created by zuoye on 15/7/16. // Copyright (c) 2015年 mogujie. All rights reserved. // #import <Foundation/Foundation.h> @interface NSDictionary (DDNilInsertableDictionary) @end @interface NSArray (DDNilInsertableArray) @end void ClassMethodSwizzle(Class aClass, SEL orig_sel, SEL alt_sel); void MethodSwizzle(Class aClass, SEL orig_sel, SEL alt_sel);
151
1,847
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "QtUtils/MainThreadExecutorImpl.h" #include <QCoreApplication> #include <QMetaObject> #include <chrono> #include <optional> #include <utility> #include "Introspection/Introspection.h" #include "OrbitBase/Action.h" #include "OrbitBase/Logging.h" #include "QtUtils/FutureWatcher.h" namespace orbit_qt_utils { void MainThreadExecutorImpl::ScheduleImpl(std::unique_ptr<Action> action) { QMetaObject::invokeMethod( this, [action = std::move(action)]() { ORBIT_SCOPE("MainThreadExecutor Action"); action->Execute(); }, Qt::QueuedConnection); } void MainThreadExecutorImpl::AbortWaitingJobs() { emit AbortRequested(); } MainThreadExecutor::WaitResult MapToWaitResult(orbit_qt_utils::FutureWatcher::Reason result) { using Reason = orbit_qt_utils::FutureWatcher::Reason; using WaitResult = MainThreadExecutor::WaitResult; switch (result) { case Reason::kFutureCompleted: return WaitResult::kCompleted; case Reason::kAbortRequested: return WaitResult::kAborted; case Reason::kTimeout: return WaitResult::kTimedOut; } UNREACHABLE(); } MainThreadExecutor::WaitResult MainThreadExecutorImpl::WaitFor( const orbit_base::Future<void>& future, std::chrono::milliseconds timeout) { orbit_qt_utils::FutureWatcher watcher{}; QObject::connect(this, &MainThreadExecutorImpl::AbortRequested, &watcher, &orbit_qt_utils::FutureWatcher::Abort); const auto result = watcher.WaitFor(future, timeout); return MapToWaitResult(result); } MainThreadExecutor::WaitResult MainThreadExecutorImpl::WaitFor( const orbit_base::Future<void>& future) { orbit_qt_utils::FutureWatcher watcher{}; QObject::connect(this, &MainThreadExecutorImpl::AbortRequested, &watcher, &orbit_qt_utils::FutureWatcher::Abort); const auto result = watcher.WaitFor(future, std::nullopt); return MapToWaitResult(result); } MainThreadExecutor::WaitResult MainThreadExecutorImpl::WaitForAll( absl::Span<orbit_base::Future<void>> futures, std::chrono::milliseconds timeout) { orbit_qt_utils::FutureWatcher watcher{}; QObject::connect(this, &MainThreadExecutorImpl::AbortRequested, &watcher, &orbit_qt_utils::FutureWatcher::Abort); const auto result = watcher.WaitForAll(futures, timeout); return MapToWaitResult(result); } MainThreadExecutor::WaitResult MainThreadExecutorImpl::WaitForAll( absl::Span<orbit_base::Future<void>> futures) { orbit_qt_utils::FutureWatcher watcher{}; QObject::connect(this, &MainThreadExecutorImpl::AbortRequested, &watcher, &orbit_qt_utils::FutureWatcher::Abort); const auto result = watcher.WaitForAll(futures, std::nullopt); return MapToWaitResult(result); } } // namespace orbit_qt_utils
1,049
2,293
/* Beginning of modification history */ /* Written 02-08-13 by PG */ /* End of modification history */ /* This header conforms to IEEE Std 1003.1-2001 */ #ifndef _INCLUDED_SYSLOG_H #define _INCLUDED_SYSLOG_H /* values of the "logopt" option of openlog */ #define LOG_PID 1 #define LOG_CONS 2 #define LOG_NDELAY 4 #define LOG_ODELAY 8 #define LOG_NOWAIT 16 /* values of the "facility" argument of openlog and of the "priority" argument of syslog */ #define LOG_KERN 0 #define LOG_USER (1<<3) #define LOG_MAIL (2<<3) #define LOG_NEWS (3<<3) #define LOG_UUCP (4<<3) #define LOG_DAEMON (5<<3) #define LOG_AUTH (6<<3) #define LOG_CRON (7<<3) #define LOG_LPR (8<<3) #define LOG_LOCAL0 (9<<3) #define LOG_LOCAL1 (10<<3) #define LOG_LOCAL2 (11<<3) #define LOG_LOCAL3 (12<<3) #define LOG_LOCAL4 (13<<3) #define LOG_LOCAL5 (14<<3) #define LOG_LOCAL6 (15<<3) #define LOG_LOCAL7 (16<<3) /* macro for constructing "maskpri" arg to setlogmask */ #define LOG_MASK(p) (1 << (p)) /* values of the "priority" argument of syslog */ #define LOG_EMERG 0 #define LOG_ALERT 1 #define LOG_CRIT 2 #define LOG_ERR 3 #define LOG_WARNING 4 #define LOG_NOTICE 5 #define LOG_INFO 6 #define LOG_DEBUG 7 #undef __P #ifdef __PROTOTYPES__ #define __P(args) args #else #define __P(args) () #endif #ifdef __cplusplus extern "C" { #endif extern void closelog __P((void)); extern void openlog __P((const char *ident, int logopt, int facility)); extern int setlogmask __P((int maskpri)); extern void syslog __P((int priority, const char * message, ...)); #ifdef __cplusplus } #endif #endif /* _INCLUDED_SYSLOG_H */
832
3,301
<filename>core/src/main/java/com/alibaba/alink/common/lazy/PipelineLazyCallbackUtils.java package com.alibaba.alink.common.lazy; import com.alibaba.alink.common.MLEnvironment; import com.alibaba.alink.common.MLEnvironmentFactory; import com.alibaba.alink.operator.batch.BatchOperator; import com.alibaba.alink.pipeline.ModelBase; import com.alibaba.alink.pipeline.Trainer; import com.alibaba.alink.pipeline.TransformerBase; import com.alibaba.alink.pipeline.tuning.BaseTuning; import com.alibaba.alink.pipeline.tuning.Report; import java.util.List; import java.util.function.Consumer; /** * Provides utility to add callbacks for lazyCollect of ModelInfo, TrainInfo, TransformData and TransformStat. * <p> * Mainly for PyAlink, as callbacks are not supported in {@link HasLazyPrintModelInfo}, {@link HasLazyPrintTrainInfo}, * and {@link HasLazyPrintTransformInfo}. */ public class PipelineLazyCallbackUtils { @SuppressWarnings("unchecked") public static <S> void callbackForTrainerLazyTrainInfo(Trainer <?, ?> trainer, List <Consumer <S>> callbacks) { LazyObjectsManager lazyObjectsManager = LazyObjectsManager.getLazyObjectsManager(trainer); LazyEvaluation <BatchOperator <?>> lazyTrainOp = lazyObjectsManager.genLazyTrainOp(trainer); lazyTrainOp.addCallback(d -> { ((WithTrainInfo <S, ?>) d).lazyCollectTrainInfo(callbacks); }); } @SuppressWarnings("unchecked") public static <S> void callbackForTrainerLazyModelInfo(Trainer <?, ?> trainer, List <Consumer <S>> callbacks) { LazyObjectsManager lazyObjectsManager = LazyObjectsManager.getLazyObjectsManager(trainer); LazyEvaluation <BatchOperator <?>> lazyTrainOp = lazyObjectsManager.genLazyTrainOp(trainer); lazyTrainOp.addCallback(d -> { ((WithModelInfoBatchOp <S, ?, ?>) d).lazyCollectModelInfo(callbacks); }); } public static void callbackForTrainerLazyTransformResult(Trainer <?, ?> trainer, List <Consumer <BatchOperator <?>>> callbacks) { LazyObjectsManager lazyObjectsManager = LazyObjectsManager.getLazyObjectsManager(trainer); LazyEvaluation <ModelBase <?>> lazyModel = lazyObjectsManager.genLazyModel(trainer); lazyModel.addCallback(model -> { LazyEvaluation <BatchOperator <?>> lazyTransformResult = lazyObjectsManager.genLazyTransformResult(model); lazyTransformResult.addCallbacks(callbacks); }); } public static void callbackForTransformerLazyTransformResult(TransformerBase <?> transformer, List <Consumer <BatchOperator <?>>> callbacks) { MLEnvironment mlEnv = MLEnvironmentFactory.get(transformer.getMLEnvironmentId()); LazyObjectsManager lazyObjectsManager = mlEnv.getLazyObjectsManager(); LazyEvaluation <BatchOperator <?>> lazyTransformResult = lazyObjectsManager.genLazyTransformResult (transformer); lazyTransformResult.addCallbacks(callbacks); } public static void callbackForTuningLazyReport(BaseTuning <?, ?> tuning, List <Consumer <Report>> callbacks) { MLEnvironment mlEnv = MLEnvironmentFactory.get(tuning.getMLEnvironmentId()); LazyObjectsManager lazyObjectsManager = mlEnv.getLazyObjectsManager(); LazyEvaluation <Report> lazyReport = lazyObjectsManager.genLazyReport(tuning); lazyReport.addCallbacks(callbacks); } }
1,115
377
#define FLOAT float #define ORDER 50 #include "../redist/dclapack.h" #include <stdio.h> #include <stdlib.h> int main() { float A[ORDER][ORDER]; float Ainv[ORDER][ORDER]; float Prod[ORDER][ORDER]; int i, j, n = 3; srand(7779); for(i=0; i<n; i++) { for(j=0; j<n; j++) { A[i][j] = (float)rand() / RAND_MAX; } } for (i=0; i<10000; i++) { INV(A,Ainv,n); } PRINT(A,n,n); PRINT(Ainv,n,n); MUL(A,Ainv,Prod,n,n,n); PRINT(Prod,n,n); return 0; }
308
5,169
<reponame>Gantios/Specs { "name": "DXDownload", "version": "1.0.1", "summary": "A short description of DXDownload.", "description": "TODO: Add long description of the pod here.", "homepage": "https://github.com/Jackdx/DXDownload", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "Jackdx": "<EMAIL>" }, "source": { "git": "https://github.com/Jackdx/DXDownload.git", "tag": "1.0.1" }, "platforms": { "ios": "9.0" }, "source_files": "DXDownload/Classes/**/*", "dependencies": { "AFNetworking": [ "~> 4.0.0" ], "TMCache": [ "~> 2.1.0" ] } }
292
678
<gh_stars>100-1000 #!/usr/bin/env python3 import codecs import os import subprocess import sys def fixup(source_path): with codecs.open(source_path, 'rb', 'utf-8') as f: code = f.read().replace('yytranslate_ (yylex (', '(yylex_ (') with codecs.open(source_path, 'wb', 'utf-8') as f: f.write(code) bison = sys.argv[1] grammar = sys.argv[2] output_header = sys.argv[3] output_source = sys.argv[4] output_dir = os.path.dirname(output_source) if bison.endswith(".py"): bison_tool = [ sys.executable, bison ] else: bison_tool = [ bison ] bison_args = [ "-v", "--report=state", "-Werror", "-o", os.path.basename(output_source), os.path.relpath(grammar, output_dir) ] subprocess.check_call(bison_tool + bison_args, cwd=output_dir) fixup(output_source)
358
474
package org.javacord.core.event.channel.user; import org.javacord.api.DiscordApi; import org.javacord.api.entity.channel.PrivateChannel; import org.javacord.api.event.channel.user.PrivateChannelEvent; /** * The implementation of {@link PrivateChannelEvent}. */ public abstract class PrivateChannelEventImpl implements PrivateChannelEvent { /** * The channel of the event. */ private final PrivateChannel channel; /** * Creates a new private channel event. * * @param channel The channel of the event. */ public PrivateChannelEventImpl(PrivateChannel channel) { this.channel = channel; } @Override public PrivateChannel getChannel() { return channel; } @Override public DiscordApi getApi() { return getChannel().getApi(); } }
292
934
<gh_stars>100-1000 package config; import java.awt.Color; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.PrintWriter; import java.util.Arrays; import javax.swing.DefaultCellEditor; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.LineBorder; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumnModel; import javax.swing.table.TableRowSorter; import burp.BurpExtender; public class ConfigTable extends JTable { /** * */ private static final long serialVersionUID = 1L; private ConfigTableModel ConfigTableModel; public ConfigTable(ConfigTableModel ConfigTableModel) { super(ConfigTableModel); this.ConfigTableModel = ConfigTableModel; this.setColumnModel(columnModel); this.setFillsViewportHeight(true);//在table的空白区域显示右键菜单 //https://stackoverflow.com/questions/8903040/right-click-mouselistener-on-whole-jtable-component this.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); this.setBorder(new LineBorder(new Color(0, 0, 0))); addClickSort(); registerListeners(); //switchEnable();//no need //table.setupTypeColumn()//can't set here, only can after table data loaded. } @Override public ConfigTableModel getModel(){ return this.ConfigTableModel; } @Override public void changeSelection(int row, int col, boolean toggle, boolean extend) { super.changeSelection(row, col, toggle, extend); } public int[] getSelectedModelRows() { int[] rows = getSelectedRows(); for (int i=0; i < rows.length; i++){ rows[i] = convertRowIndexToModel(rows[i]);//转换为Model的索引,否则排序后索引不对应〿 } Arrays.sort(rows);//升序 return rows; } private void addClickSort() { TableRowSorter<ConfigTableModel> sorter = new TableRowSorter<ConfigTableModel>(ConfigTableModel); ConfigTable.this.setRowSorter(sorter); JTableHeader header = this.getTableHeader(); header.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { //ConfigTable.this.getRowSorter().getSortKeys().get(0).getColumn(); sorter.getSortKeys().get(0).getColumn(); ////当Jtable中无数据时,jtable.getRowSorter()是null } catch (Exception e1) { e1.printStackTrace(new PrintWriter(BurpExtender.callbacks.getStderr(), true));//working? } } }); } private void switchEnable() { this.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2)// 实现双击 { int row = ((ConfigTable) e.getSource()).rowAtPoint(e.getPoint()); // 获得行位置 int col = ((ConfigTable) e.getSource()).columnAtPoint(e.getPoint()); // 获得列位置 row = convertRowIndexToModel(row); String cellVal = (String) (ConfigTableModel.getValueAt(row, col)); // 获得点击单元格数据 if(col==3) { if (cellVal.equalsIgnoreCase("true")) { ConfigTableModel.setValueAt("false", row, col); }else { ConfigTableModel.setValueAt("true", row, col); } ConfigTableModel.fireTableRowsInserted(row, row); } } } }); } private void registerListeners(){ final ConfigTable _this = this; this.addMouseListener( new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseReleased( MouseEvent e ){ } @Override public void mousePressed(MouseEvent e) { //no need } }); } public void setupTypeColumn() { //call this function must after table data loaded !!!! JComboBox<String> comboBox = new JComboBox<String>(); comboBox.addItem(ConfigEntry.Action_Add_Or_Replace_Header); comboBox.addItem(ConfigEntry.Action_Append_To_header_value); comboBox.addItem(ConfigEntry.Action_Remove_From_Headers); comboBox.addItem(ConfigEntry.Config_Basic_Variable); comboBox.addItem(ConfigEntry.Config_Custom_Payload); comboBox.addItem(ConfigEntry.Config_Custom_Payload_Base64); comboBox.addItem(ConfigEntry.Config_Chunked_Variable); comboBox.addItem(ConfigEntry.Config_Proxy_Variable); TableColumnModel typeColumn = this.getColumnModel(); typeColumn.getColumn(2).setCellEditor(new DefaultCellEditor(comboBox)); JCheckBox jc1 = new JCheckBox(); typeColumn.getColumn(3).setCellEditor(new DefaultCellEditor(jc1)); // //Set up tool tips for the sport cells. // DefaultTableCellRenderer renderer = // new DefaultTableCellRenderer(); // renderer.setToolTipText("Click for combo box"); // typeColumn.setCellRenderer(renderer); } }
1,814
17,703
// NOLINT(namespace-envoy) constexpr char TEST_CLIENT_CERT_HASH[] = "fc00:e968:6179::de52:7100:9B:CB:5A:70:2D:04:C5:00:D6:81:68:" "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:91:61:A5:FB:01";
155
809
<gh_stars>100-1000 /** * @file * @brief * * @author <NAME> * @date 29.04.2013 */ #include <stddef.h> #include <profiler/tracing/trace.h> time64_t trace_block_diff(struct __trace_block *tb) { return -1; } time64_t trace_block_get_time(struct __trace_block *tb) { return -1; } int trace_point_get_value(struct __trace_point *tp) { return -1; } struct __trace_point *trace_point_get_by_name(const char *name) { return NULL; }
192
332
<reponame>quickmsg/smqtt import ch.qos.logback.classic.Level; import io.github.quickmsg.common.config.BootstrapConfig; import io.github.quickmsg.core.Bootstrap; /** * @author luxurong * @date 2021/5/6 19:25 * @description */ public class ClusterNode2 { @org.junit.Test public void startServer() throws InterruptedException { Bootstrap bootstrap = Bootstrap.builder() .rootLevel(Level.DEBUG) .tcpConfig( BootstrapConfig .TcpConfig .builder() .port(8551) .username("smqtt") .password("<PASSWORD>") .build()) .clusterConfig( BootstrapConfig. ClusterConfig .builder() .enable(true) .node("node-3") .namespace("smqtt") .port(7772) .url("127.0.0.1:7773,127.0.0.1:7771"). build()) .build() .start().block(); assert bootstrap != null; // 关闭服 // bootstrap.shutdown(); Thread.sleep(1000000); } }
901
808
<filename>opentasks/src/main/java/org/dmfs/tasks/share/TaskBindings.java<gh_stars>100-1000 /* * Copyright 2017 dmfs GmbH * * 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.dmfs.tasks.share; import androidx.annotation.Nullable; import org.dmfs.tasks.R; import org.dmfs.tasks.model.ContentSet; import org.dmfs.tasks.model.Model; import org.dmfs.tasks.model.TaskFieldAdapters; import au.com.codeka.carrot.Bindings; /** * {@link Bindings} for accessing values from a task. * See the <code>switch-case</code> for the supported properties. * * @author <NAME> */ public final class TaskBindings implements Bindings { private final ContentSet mContentSet; private final Model mModel; public TaskBindings(ContentSet contentSet, Model model) { mContentSet = contentSet; mModel = model; } @Nullable @Override public Object resolve(String key) { switch (key) { case "title": return TaskFieldAdapters.TITLE.get(mContentSet); case "description": return TaskFieldAdapters.DESCRIPTION.get(mContentSet); case "checklist": return TaskFieldAdapters.CHECKLIST.get(mContentSet); case "location": return TaskFieldAdapters.LOCATION.get(mContentSet); case "start": return TaskFieldAdapters.DTSTART.get(mContentSet); case "due": return TaskFieldAdapters.DUE.get(mContentSet); case "completed": return TaskFieldAdapters.COMPLETED.get(mContentSet); case "priority": Integer priority = TaskFieldAdapters.PRIORITY.get(mContentSet); return priority == null ? null : mModel.getField(R.id.task_field_priority).getChoices().getTitle(priority); case "privacy": Integer classification = TaskFieldAdapters.CLASSIFICATION.get(mContentSet); return classification == null ? null : mModel.getField(R.id.task_field_classification).getChoices().getTitle(classification); case "status": Integer status = TaskFieldAdapters.STATUS.get(mContentSet); return status == null ? null : mModel.getField(R.id.task_field_status).getChoices().getTitle(status); case "url": return TaskFieldAdapters.URL.get(mContentSet); default: return null; } } @Override public boolean isEmpty() { return false; } }
1,241
7,482
<reponame>BreederBai/rt-thread /* * Copyright (c) 2006-2018, Synwit Technology Co.,Ltd. * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2018-05-31 ZYH first version * 2018-12-10 Zohar_Lee format file * 2020-07-10 lik rewrite */ #include "drv_soft_i2c.h" #ifdef RT_USING_I2C #ifdef BSP_USING_I2C /*************************************************************** *!!!!!!!!!!!!!!!!!!!!!!!!!!!!NOTICE!!!!!!!!!!!!!!!!!!!!!!!!!!!!! *In order to use swm drv_soft_i2c,you need to commented out line 114 (SDA_H(ops);) and line 167 (SDA_H(ops);) in i2c-bit-ops.c At the same time, add one line (SDA_L(ops);)after line 154 (SCL_L(ops);) in i2c-bit-ops.c ***************************************************************/ //#define DRV_DEBUG #define LOG_TAG "drv.i2c" #include <drv_log.h> #if !defined(BSP_USING_I2C0) && !defined(BSP_USING_I2C1) #error "Please define at least one BSP_USING_I2Cx" /* this driver can be disabled at menuconfig ? RT-Thread Components ? Device Drivers */ #endif static const struct swm_soft_i2c_cfg soft_i2c_cfg[] = { #ifdef BSP_USING_I2C0 I2C0_BUS_CFG, #endif #ifdef BSP_USING_I2C1 I2C1_BUS_CFG, #endif }; static struct swm_i2c i2c_drv[sizeof(soft_i2c_cfg) / sizeof(soft_i2c_cfg[0])]; /** * This function initializes the i2c pin. * * @param swm i2c dirver class. */ static void swm_i2c_gpio_init(struct swm_i2c *i2c) { struct swm_soft_i2c_cfg *cfg = (struct swm_soft_i2c_cfg *)i2c->ops.data; rt_pin_mode(cfg->scl, PIN_MODE_OUTPUT_OD); rt_pin_mode(cfg->sda, PIN_MODE_OUTPUT_OD); rt_pin_write(cfg->scl, PIN_HIGH); rt_pin_write(cfg->sda, PIN_HIGH); } /** * This function sets the sda pin. * * @param swm config class. * @param The sda pin state. */ static void swm_set_sda(void *data, rt_int32_t state) { struct swm_soft_i2c_cfg *cfg = (struct swm_soft_i2c_cfg *)data; rt_pin_mode(cfg->sda, PIN_MODE_OUTPUT_OD); if (state) { rt_pin_write(cfg->sda, PIN_HIGH); } else { rt_pin_write(cfg->sda, PIN_LOW); } } /** * This function sets the scl pin. * * @param swm config class. * @param The scl pin state. */ static void swm_set_scl(void *data, rt_int32_t state) { struct swm_soft_i2c_cfg *cfg = (struct swm_soft_i2c_cfg *)data; rt_pin_mode(cfg->scl, PIN_MODE_OUTPUT_OD); if (state) { rt_pin_write(cfg->scl, PIN_HIGH); } else { rt_pin_write(cfg->scl, PIN_LOW); } } /** * This function gets the sda pin state. * * @param The sda pin state. */ static rt_int32_t swm_get_sda(void *data) { struct swm_soft_i2c_cfg *cfg = (struct swm_soft_i2c_cfg *)data; rt_pin_mode(cfg->sda, PIN_MODE_INPUT_PULLUP); return rt_pin_read(cfg->sda); } /** * This function gets the scl pin state. * * @param The scl pin state. */ static rt_int32_t swm_get_scl(void *data) { struct swm_soft_i2c_cfg *cfg = (struct swm_soft_i2c_cfg *)data; rt_pin_mode(cfg->scl, PIN_MODE_INPUT_PULLUP); return rt_pin_read(cfg->scl); } /** * The time delay function. * * @param microseconds. */ static void swm_udelay(rt_uint32_t us) { rt_uint32_t ticks; rt_uint32_t told, tnow, tcnt = 0; rt_uint32_t reload = SysTick->LOAD; ticks = us * reload / (1000000 / RT_TICK_PER_SECOND); told = SysTick->VAL; while (1) { tnow = SysTick->VAL; if (tnow != told) { if (tnow < told) { tcnt += told - tnow; } else { tcnt += reload - tnow + told; } told = tnow; if (tcnt >= ticks) { break; } } } } static const struct rt_i2c_bit_ops swm_bit_ops = { .data = RT_NULL, .set_sda = swm_set_sda, .set_scl = swm_set_scl, .get_sda = swm_get_sda, .get_scl = swm_get_scl, .udelay = swm_udelay, .delay_us = 1, .timeout = 100}; /* I2C initialization function */ int rt_hw_i2c_init(void) { rt_err_t result; for (int i = 0; i < sizeof(i2c_drv) / sizeof(struct swm_i2c); i++) { i2c_drv[i].ops = swm_bit_ops; i2c_drv[i].ops.data = (void *)&soft_i2c_cfg[i]; i2c_drv[i].i2c2_bus.priv = &i2c_drv[i].ops; swm_i2c_gpio_init(&i2c_drv[i]); result = rt_i2c_bit_add_bus(&i2c_drv[i].i2c2_bus, soft_i2c_cfg[i].name); RT_ASSERT(result == RT_EOK); LOG_D("software simulation %s init done, pin scl: %d, pin sda %d", soft_i2c_cfg[i].name, soft_i2c_cfg[i].scl, soft_i2c_cfg[i].sda); } return RT_EOK; } INIT_DEVICE_EXPORT(rt_hw_i2c_init); #endif /* BSP_USING_I2C */ #endif /* RT_USING_I2C */
2,468
1,968
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: <EMAIL> // ////////////////////////////////////////////////////////////////////////////// #pragma once class CBrowseDirDialog { public: // Browses for directory. First parameter is default directory if not empty bool static Browse(CString &dir, UINT titleId = 0); private: static int CALLBACK DefaultDirCallback(HWND, UINT, LPARAM, LPARAM); };
154
1,214
package com.mapbox.rctmgl.modules; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.util.Base64; import android.util.Log; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.module.annotations.ReactModule; import com.mapbox.geojson.Feature; import com.mapbox.geojson.FeatureCollection; import com.mapbox.geojson.Point; import com.mapbox.mapboxsdk.camera.CameraPosition; import com.mapbox.mapboxsdk.snapshotter.MapSnapshot; import com.mapbox.mapboxsdk.snapshotter.MapSnapshotter; import com.mapbox.mapboxsdk.storage.FileSource; import com.mapbox.rctmgl.utils.BitmapUtils; import com.mapbox.rctmgl.utils.GeoJSONUtils; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static android.content.Context.CONTEXT_IGNORE_SECURITY; /** * Created by nickitaliano on 11/30/17. */ @ReactModule(name = RCTMGLSnapshotModule.REACT_CLASS) public class RCTMGLSnapshotModule extends ReactContextBaseJavaModule { public static final String REACT_CLASS = "RCTMGLSnapshotModule"; private ReactApplicationContext mContext; // prevents snapshotter from being GC'ed private Map<String, MapSnapshotter> mSnapshotterMap; public RCTMGLSnapshotModule(ReactApplicationContext reactContext) { super(reactContext); mContext = reactContext; mSnapshotterMap = new HashMap<>(); } @Override public String getName() { return REACT_CLASS; } @ReactMethod public void takeSnap(final ReadableMap jsOptions, final Promise promise) { FileSource.getInstance(mContext).activate(); mContext.runOnUiQueueThread(new Runnable() { @Override public void run() { final String snapshotterID = UUID.randomUUID().toString(); final MapSnapshotter snapshotter = new MapSnapshotter(mContext, getOptions(jsOptions)); mSnapshotterMap.put(snapshotterID, snapshotter); snapshotter.start(new MapSnapshotter.SnapshotReadyCallback() { @Override public void onSnapshotReady(MapSnapshot snapshot) { Bitmap bitmap = snapshot.getBitmap(); String result = null; if (jsOptions.getBoolean("writeToDisk")) { result = BitmapUtils.createTempFile(mContext, bitmap); } else { result = BitmapUtils.createBase64(bitmap); } if (result == null) { promise.reject(REACT_CLASS, "Could not generate snapshot, please check Android logs for more info."); return; } promise.resolve(result); mSnapshotterMap.remove(snapshotterID); } }, new MapSnapshotter.ErrorHandler() { @Override public void onError(String error) { Log.w(REACT_CLASS, error); mSnapshotterMap.remove(snapshotterID); } }); } }); } private MapSnapshotter.Options getOptions(ReadableMap jsOptions) { MapSnapshotter.Options options = new MapSnapshotter.Options( (int) jsOptions.getDouble("width"), (int) jsOptions.getDouble("height")); options.withLogo(jsOptions.getBoolean("withLogo")); options.withStyle(jsOptions.getString("styleURL")); options.withPixelRatio(Float.valueOf(mContext.getResources().getDisplayMetrics().scaledDensity).intValue()); if (jsOptions.hasKey("bounds")) { FeatureCollection bounds = FeatureCollection.fromJson(jsOptions.getString("bounds")); options.withRegion(GeoJSONUtils.toLatLngBounds(bounds)); } else { Feature centerPoint = Feature.fromJson(jsOptions.getString("centerCoordinate")); CameraPosition cameraPosition = new CameraPosition.Builder() .target(GeoJSONUtils.toLatLng((Point) centerPoint.geometry())) .tilt(jsOptions.getDouble("pitch")) .bearing(jsOptions.getDouble("heading")) .zoom(jsOptions.getDouble("zoomLevel")) .build(); options.withCameraPosition(cameraPosition); } return options; } private void closeSnapshotOutputStream(OutputStream outputStream) { if (outputStream == null) { return; } try { outputStream.close(); } catch (IOException e) { Log.w(REACT_CLASS, e.getLocalizedMessage()); } } }
2,315
1,056
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.web.beans.model; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import org.netbeans.modules.j2ee.metadata.model.api.MetadataModel; import org.netbeans.modules.j2ee.metadata.model.api.MetadataModelAction; import org.netbeans.modules.j2ee.metadata.model.support.TestUtilities; import org.netbeans.modules.web.beans.api.model.InterceptorsResult; import org.netbeans.modules.web.beans.api.model.WebBeansModel; /** * @author ads * */ public class InterceptorResolutionTest extends CommonTestCase { public InterceptorResolutionTest( String testName ) { super(testName); } public void testSimpleInterceptorCase() throws IOException{ createInterceptorBinding("IBinding1"); createInterceptorBinding("IBinding2"); createInterceptorBinding("IBinding3"); TestUtilities.copyStringToFileObject(srcFO, "foo/One.java", "package foo; " + "@IBinding1 "+ "public class One {" + " void method1(){} "+ " @IBinding2 @IBinding3 void method2(){} "+ "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor1.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding1 "+ "public class Iceptor1 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor2.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding3 "+ "public class Iceptor2 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor3.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding2 @IBinding1 "+ "public class Iceptor3 {" + "}" ); TestWebBeansModelImpl modelImpl = createModelImpl(true ); MetadataModel<WebBeansModel> testModel = modelImpl.createTestModel(); testModel.runReadAction( new MetadataModelAction<WebBeansModel,Void>(){ @Override public Void run( WebBeansModel model ) throws Exception { checkInterceptors(model, "foo.One", "foo.Iceptor1"); checkMethodInterceptors(model, "foo.One", "method1", "foo.Iceptor1"); checkMethodInterceptors(model, "foo.One", "method2", "foo.Iceptor1", "foo.Iceptor2", "foo.Iceptor3"); return null; } }); } public void testInterceptorNonbindingMembers() throws IOException{ TestUtilities.copyStringToFileObject(srcFO, "foo/IBinding1.java", "package foo; " + "import static java.lang.annotation.ElementType.METHOD; "+ "import static java.lang.annotation.ElementType.TYPE; "+ "import static java.lang.annotation.RetentionPolicy.RUNTIME; "+ "import javax.enterprise.inject.*; "+ "import javax.inject.*; "+ "import java.lang.annotation.*; "+ "import javax.interceptor.*; "+ "import javax.enterprise.util.*; "+ "@InterceptorBinding " + "@Retention(RUNTIME) "+ "@Target({METHOD, TYPE}) "+ "public @interface IBinding1 {" + " String value() ;"+ "} "); TestUtilities.copyStringToFileObject(srcFO, "foo/IBinding2.java", "package foo; " + "import static java.lang.annotation.ElementType.METHOD; "+ "import static java.lang.annotation.ElementType.TYPE; "+ "import static java.lang.annotation.RetentionPolicy.RUNTIME; "+ "import javax.enterprise.inject.*; "+ "import javax.inject.*; "+ "import java.lang.annotation.*; "+ "import javax.interceptor.*; "+ "import javax.enterprise.util.*; "+ "@InterceptorBinding " + "@Retention(RUNTIME) "+ "@Target({METHOD, TYPE}) "+ "public @interface IBinding2 {" + " String value() ;"+ " @Nonbinding String comment() defualt \"\" ; "+ "} "); createInterceptorBinding("IBinding3"); TestUtilities.copyStringToFileObject(srcFO, "foo/One.java", "package foo; " + "@IBinding1(\"d\") "+ "public class One {" + " void method1(){} "+ " @IBinding2(\"a\") @IBinding3 void method2(){} "+ "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor1.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding1(\"e\") "+ "public class Iceptor1 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor2.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding3 @IBinding2(value=\"a\",comment=\"c\")"+ "public class Iceptor2 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor3.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding2(\"b\") @IBinding1 "+ "public class Iceptor3 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor4.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding1(\"d\") "+ "public class Iceptor4 {" + "}" ); TestWebBeansModelImpl modelImpl = createModelImpl(true ); MetadataModel<WebBeansModel> testModel = modelImpl.createTestModel(); testModel.runReadAction( new MetadataModelAction<WebBeansModel,Void>(){ @Override public Void run( WebBeansModel model ) throws Exception { checkInterceptors(model, "foo.One", "foo.Iceptor4"); checkMethodInterceptors(model, "foo.One", "method1", "foo.Iceptor4"); checkMethodInterceptors(model, "foo.One", "method2", "foo.Iceptor2", "foo.Iceptor4"); return null; } }); } public void testEnabledInterceptor() throws IOException{ createInterceptorBinding("IBinding1"); createInterceptorBinding("IBinding2"); TestUtilities.copyStringToFileObject(srcFO, "beans.xml", "<?xml version='1.0' encoding='UTF-8'?> " + "<beans xmlns=\"http://java.sun.com/xml/ns/javaee\">" + "<interceptors> "+ "<class>foo.Iceptor2</class>"+ "<class>foo.Iceptor3</class>"+ "</interceptors> " + "</beans>"); TestUtilities.copyStringToFileObject(srcFO, "foo/One.java", "package foo; " + "@IBinding1 "+ "public class One {" + " void @IBinding2 method1(){} "+ "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor1.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding1 "+ "public class Iceptor1 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor2.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding2 "+ "public class Iceptor2 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor3.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding2 @IBinding1 "+ "public class Iceptor3 {" + "}" ); TestWebBeansModelImpl modelImpl = createModelImpl(true ); MetadataModel<WebBeansModel> testModel = modelImpl.createTestModel(); testModel.runReadAction( new MetadataModelAction<WebBeansModel,Void>(){ @Override public Void run( WebBeansModel model ) throws Exception { checkMethodEnabledInterceptors(model, "foo.One", "method1", new String[]{ "foo.Iceptor2" , "foo.Iceptor3"}, "foo.Iceptor1"); return null; } }); } public void testDeclaredInterceptor() throws IOException{ createInterceptorBinding("IBinding1"); TestUtilities.copyStringToFileObject(srcFO, "beans.xml", "<?xml version='1.0' encoding='UTF-8'?> " + "<beans xmlns=\"http://java.sun.com/xml/ns/javaee\">" + "<interceptors> "+ "</interceptors> " + "</beans>"); TestUtilities.copyStringToFileObject(srcFO, "foo/One.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptors({DeclaredIceptor1.class, DeclaredIceptor2.class}) "+ "public class One {" + " void @IBinding1 @Interceptors({DeclaredIceptor3.class}) method(){} "+ "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor1.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding1 "+ "public class Iceptor1 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/DeclaredIceptor1.java", "package foo; " + "import javax.interceptor.*; "+ "public class DeclaredIceptor1 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/DeclaredIceptor2.java", "package foo; " + "import javax.interceptor.*; "+ "public class DeclaredIceptor2 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/DeclaredIceptor3.java", "package foo; " + "import javax.interceptor.*; "+ "public class DeclaredIceptor3 {" + "}" ); TestWebBeansModelImpl modelImpl = createModelImpl(true ); MetadataModel<WebBeansModel> testModel = modelImpl.createTestModel(); testModel.runReadAction( new MetadataModelAction<WebBeansModel,Void>(){ @Override public Void run( WebBeansModel model ) throws Exception { checkInterceptors(model, "foo.One", false, "foo.DeclaredIceptor1", "foo.DeclaredIceptor2" ); checkMethodInterceptors(model, "foo.One", "method", false , "foo.DeclaredIceptor1", "foo.DeclaredIceptor2", "foo.DeclaredIceptor3"); return null; } }); } public void testInterceptorMixedCases() throws IOException{ TestUtilities.copyStringToFileObject(srcFO, "foo/IBinding1.java", "package foo; " + "import static java.lang.annotation.ElementType.METHOD; "+ "import static java.lang.annotation.ElementType.TYPE; "+ "import static java.lang.annotation.RetentionPolicy.RUNTIME; "+ "import javax.enterprise.inject.*; "+ "import javax.inject.*; "+ "import java.lang.annotation.*; "+ "import javax.interceptor.*; "+ "import javax.enterprise.util.*; "+ "@InterceptorBinding " + "@Retention(RUNTIME) "+ "@Target({METHOD, TYPE}) "+ "public @interface IBinding1 {" + " String value() ;"+ "} "); TestUtilities.copyStringToFileObject(srcFO, "foo/IBinding2.java", "package foo; " + "import static java.lang.annotation.ElementType.METHOD; "+ "import static java.lang.annotation.ElementType.TYPE; "+ "import static java.lang.annotation.RetentionPolicy.RUNTIME; "+ "import javax.enterprise.inject.*; "+ "import javax.inject.*; "+ "import java.lang.annotation.*; "+ "import javax.interceptor.*; "+ "import javax.enterprise.util.*; "+ "@InterceptorBinding " + "@Retention(RUNTIME) "+ "@Target({METHOD, TYPE}) "+ "@IBinding1(\"a\") "+ "public @interface IBinding2 {" + "} "); createInterceptorBinding("IBinding3"); createInterceptorBinding("IBinding4"); TestUtilities.copyStringToFileObject(srcFO, "foo/Stereotype1.java", "package foo; " + "import javax.enterprise.inject.*; "+ "import static java.lang.annotation.ElementType.METHOD; "+ "import static java.lang.annotation.ElementType.FIELD; "+ "import static java.lang.annotation.ElementType.TYPE; "+ "import static java.lang.annotation.RetentionPolicy.RUNTIME; "+ "import java.lang.annotation.*; "+ "@Target({METHOD, FIELD, TYPE}) "+ "@Retention(RUNTIME) "+ "@IBinding4 "+ "@Stereotype "+ "public @interface Stereotype1 {}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Stereotype2.java", "package foo; " + "import javax.enterprise.inject.*; "+ "import static java.lang.annotation.ElementType.METHOD; "+ "import static java.lang.annotation.ElementType.FIELD; "+ "import static java.lang.annotation.ElementType.TYPE; "+ "import static java.lang.annotation.RetentionPolicy.RUNTIME; "+ "import java.lang.annotation.*; "+ "@Target({METHOD, FIELD, TYPE}) "+ "@Retention(RUNTIME) "+ "@Stereotype "+ "@Stereotype1 "+ "public @interface Stereotype2 {}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/One.java", "package foo; " + "@IBinding3 "+ "public class One {" + " void @IBinding2 method1(){} "+ " @Stereotype2 @IBinding1(\"c\") void method2(){} "+ "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Two.java", "package foo; " + "@Stereotype1 "+ "public class Two {" + " void @IBinding1(\"b\") method(){} "+ "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor1.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding1(\"a\") "+ "public class Iceptor1 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor2.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding3 @IBinding4 @IBinding1(\"d\")"+ "public class Iceptor2 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor3.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@IBinding4 @IBinding1(\"b\") "+ "public class Iceptor3 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor4.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@Stereotype2 @IBinding1(\"b\") "+ "public class Iceptor4 {" + "}" ); TestUtilities.copyStringToFileObject(srcFO, "foo/Iceptor5.java", "package foo; " + "import javax.interceptor.*; "+ "@Interceptor "+ "@Stereotype1 @IBinding1(\"c\") "+ "public class Iceptor5 {" + "}" ); TestWebBeansModelImpl modelImpl = createModelImpl(true ); MetadataModel<WebBeansModel> testModel = modelImpl.createTestModel(); testModel.runReadAction( new MetadataModelAction<WebBeansModel,Void>(){ @Override public Void run( WebBeansModel model ) throws Exception { checkInterceptors(model, "foo.One" ); checkMethodInterceptors(model, "foo.One", "method1", "foo.Iceptor1"); checkMethodInterceptors(model, "foo.One", "method2", "foo.Iceptor5"); checkMethodInterceptors(model, "foo.Two", "method", "foo.Iceptor3", "foo.Iceptor4" ); return null; } }); } private void checkInterceptors(WebBeansModel model , String className , String... interceptorFqns) { checkInterceptors(model, className, true , interceptorFqns); } private void checkInterceptors(WebBeansModel model , String className , boolean resolved, String... interceptorFqns) { TypeMirror type = model.resolveType( className ); Element clazz = model.getCompilationController().getTypes().asElement( type ); checkInterceptors(model, clazz, resolved , interceptorFqns); } private InterceptorsResult checkMethodInterceptors(WebBeansModel model , String className , String methodName, String... interceptorFqns) { return checkMethodInterceptors(model, className, methodName, true, interceptorFqns); } private InterceptorsResult checkMethodInterceptors(WebBeansModel model , String className , String methodName, boolean resolved , String... interceptorFqns) { ExecutableElement element = getMethod(model, className, methodName); assertNotNull( element ); return checkInterceptors(model, element, resolved, interceptorFqns); } private ExecutableElement getMethod( WebBeansModel model, String className, String methodName ) { TypeMirror type = model.resolveType( className ); Element clazz = model.getCompilationController().getTypes().asElement( type ); List<ExecutableElement> methods = ElementFilter.methodsIn( clazz.getEnclosedElements() ); ExecutableElement element = null; for (ExecutableElement executableElement : methods) { String name = executableElement.getSimpleName().toString(); if ( name.equals(methodName )){ element = executableElement; break; } } return element; } private void checkMethodEnabledInterceptors(WebBeansModel model , String className , String methodName, String[] enabledInterceptors, String... disabledInterceptors ) { List<String> list = new LinkedList<String>( Arrays.asList( enabledInterceptors )); list.addAll( Arrays.asList( disabledInterceptors )); InterceptorsResult result = checkMethodInterceptors(model, className, methodName, list.toArray( new String[0] )); Set<String> disabled = new HashSet<String>(); Set<String> enabled = new HashSet<String>(); List<TypeElement> allInterceptors = result.getAllInterceptors(); for (TypeElement typeElement : allInterceptors) { if ( result.isDisabled(typeElement)){ disabled.add( typeElement.getQualifiedName().toString()); } else { enabled.add( typeElement.getQualifiedName().toString()); } } Set<String> requiredEnabled = new HashSet<String>( Arrays.asList( enabledInterceptors)); compareCollections(enabled, requiredEnabled, "Not found enabled interceptors :"); compareCollections(Arrays.asList( enabledInterceptors), enabled, "These interceptos are unexpectedly enabled :"); Set<String> requiredDisabled = new HashSet<String>( Arrays.asList( disabledInterceptors)); compareCollections(disabled, requiredDisabled, "Not found disabled interceptors :"); compareCollections(Arrays.asList( disabledInterceptors), disabled, "These interceptos are unexpectedly disabled :"); } private void compareCollections( Collection<String> actual,Set<String> required , String errorMessage ) { required.removeAll( actual ); if ( !required.isEmpty()){ StringBuilder builder = new StringBuilder(); for (String fqn : required) { builder.append( fqn ); builder.append(" , "); } assertFalse( errorMessage+ builder.toString() ,true ); } } private InterceptorsResult checkInterceptors( WebBeansModel model, Element element, String... interceptorFqns ) { return checkInterceptors(model, element, true , interceptorFqns); } private InterceptorsResult checkInterceptors( WebBeansModel model, Element element, boolean resolved , String... interceptorFqns ) { InterceptorsResult result = model.getInterceptors(element); Collection<TypeElement> interceptors = null; if ( resolved ){ interceptors = result.getResolvedInterceptors(); } else { interceptors = result.getDeclaredInterceptors(); } Set<String> foundIceptors = new HashSet<String>(); for (TypeElement typeElement : interceptors) { String fqn = typeElement.getQualifiedName().toString(); foundIceptors.add( fqn ); } Set<String> requiredFqns = new HashSet<String>( Arrays.asList( interceptorFqns)); requiredFqns.removeAll( foundIceptors ); if ( !requiredFqns.isEmpty() ){ StringBuilder builder = new StringBuilder(); for( String fqn : requiredFqns ){ builder.append( fqn ); builder.append(", "); } assertFalse("Interceptors "+builder+" are exepcted but not found", true ); } foundIceptors.removeAll(Arrays.asList( interceptorFqns)); if ( !foundIceptors.isEmpty() ){ StringBuilder builder = new StringBuilder(); for( String fqn : foundIceptors ){ builder.append( fqn ); builder.append(", "); } assertFalse("Interceptors "+builder+" found but not expected", true ); } return result; } }
12,444
2,327
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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 tensorflow as tf import tensorflow as tf from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint import argparse import os import numpy as np import json from datetime import datetime class SyncToS3(tf.keras.callbacks.Callback): def __init__(self, logdir, s3logdir): super(SyncToS3, self).__init__() self.logdir = logdir self.s3logdir = s3logdir # Explicitly sync to S3 upon completion def on_epoch_end(self, batch, logs={}): os.system('aws s3 sync ' + self.logdir + ' ' + self.s3logdir) # ' >/dev/null 2>&1' def model(x_train, y_train, x_test, y_test, args): """Generate a simple model""" model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(1024, activation=tf.nn.relu), tf.keras.layers.Dropout(0.4), tf.keras.layers.Dense(10, activation=tf.nn.softmax) ]) model.compile(optimizer=args.optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy']) callbacks = [] logdir = args.output_data_dir + '/' + datetime.now().strftime("%Y%m%d-%H%M%S") callbacks.append(ModelCheckpoint(args.output_data_dir + '/checkpoint-{epoch}.h5')) callbacks.append(TensorBoard(log_dir=logdir, profile_batch=0)) callbacks.append(SyncToS3(logdir=logdir, s3logdir=args.model_dir)) model.fit(x=x_train, y=y_train, callbacks=callbacks, epochs=args.epochs) score = model.evaluate(x=x_test, y=y_test) print('Test loss :', score[0]) print('Test accuracy:', score[1]) return model def _load_training_data(base_dir): """Load MNIST training data""" print(base_dir) x_train = np.load(os.path.join(base_dir, 'train_data.npy')) y_train = np.load(os.path.join(base_dir, 'train_labels.npy')) return x_train, y_train def _load_testing_data(base_dir): """Load MNIST testing data""" print(base_dir) x_test = np.load(os.path.join(base_dir, 'eval_data.npy')) y_test = np.load(os.path.join(base_dir, 'eval_labels.npy')) return x_test, y_test def _parse_args(): parser = argparse.ArgumentParser() # Hyper-parameters parser.add_argument('--epochs', type=int, default=5) parser.add_argument('--optimizer', type=str, default='adam') # SageMaker parameters # model_dir is always passed in from SageMaker. (By default, it is a S3 path under the default bucket.) parser.add_argument('--model_dir', type=str) parser.add_argument('--sm-model-dir', type=str, default=os.environ['SM_MODEL_DIR']) parser.add_argument('--model_output_dir', type=str, default=os.environ['SM_MODEL_DIR']) parser.add_argument('--output_data_dir', type=str, default=os.environ['SM_OUTPUT_DATA_DIR']) # Data directories and other options parser.add_argument('--train', type=str, default=os.environ['SM_CHANNEL_TRAINING']) parser.add_argument('--hosts', type=list, default=json.loads(os.environ['SM_HOSTS'])) parser.add_argument('--current-host', type=str, default=os.environ['SM_CURRENT_HOST']) return parser.parse_known_args() if __name__ == "__main__": args, unknown = _parse_args() train_data, train_labels = _load_training_data(args.train) eval_data, eval_labels = _load_testing_data(args.train) mnist_classifier = model(train_data, train_labels, eval_data, eval_labels, args) print('current_host: {}'.format(args.current_host)) print('hosts[0]: {}'.format(args.hosts[0])) if args.current_host == args.hosts[0]: # save model to an S3 directory with version number '00000001' mnist_classifier.save(os.path.join(args.sm_model_dir, '000000001'), './sm_tensorflow_mnist.h5') mnist_classifier.save(os.path.join('/opt/ml/model/', '000000001'), './opt_tensorflow_mnist.h5') # TODO: Copy .h5 file to /opt/ml/model/ (backed by S3) # import shutil # shutil.copyfile('./sm_tensorflow_mnist.h5', '/opt/ml/model/000000001/sm_tensorflow_mnist.h5') # shutil.copyfile('./opt_tensorflow_mnist.h5', '/opt/ml/model/000000001/opt_tensorflow_mnist.h5')
2,178
1,408
<gh_stars>1000+ /* * Copyright (c) 2015-2020, Renesas Electronics Corporation. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <common/debug.h> #include <lib/mmio.h> #include <lib/utils_def.h> #include "avs_driver.h" #include "cpg_registers.h" #include "rcar_def.h" #include "rcar_private.h" #if (AVS_SETTING_ENABLE == 1) #if PMIC_ROHM_BD9571 /* Read PMIC register for debug. 1:enable / 0:disable */ #define AVS_READ_PMIC_REG_ENABLE 0 /* The re-try number of times of the AVS setting. */ #define AVS_RETRY_NUM (1U) #endif /* PMIC_ROHM_BD9571 */ /* Base address of Adaptive Voltage Scaling module registers*/ #define AVS_BASE (0xE60A0000U) /* Adaptive Dynamic Voltage ADJust Parameter2 registers */ #define ADVADJP2 (AVS_BASE + 0x013CU) /* Mask VOLCOND bit in ADVADJP2 registers */ #define ADVADJP2_VOLCOND_MASK (0x000001FFU) /* VOLCOND[8:0] */ #if PMIC_ROHM_BD9571 /* I2C for DVFS bit in CPG registers for module standby and software reset*/ #define CPG_SYS_DVFS_BIT (0x04000000U) #endif /* PMIC_ROHM_BD9571 */ /* ADVFS Module bit in CPG registers for module standby and software reset*/ #define CPG_SYS_ADVFS_BIT (0x02000000U) #if PMIC_ROHM_BD9571 /* Base address of IICDVFS registers*/ #define IIC_DVFS_BASE (0xE60B0000U) /* IIC bus data register */ #define IIC_ICDR (IIC_DVFS_BASE + 0x0000U) /* IIC bus control register */ #define IIC_ICCR (IIC_DVFS_BASE + 0x0004U) /* IIC bus status register */ #define IIC_ICSR (IIC_DVFS_BASE + 0x0008U) /* IIC interrupt control register */ #define IIC_ICIC (IIC_DVFS_BASE + 0x000CU) /* IIC clock control register low */ #define IIC_ICCL (IIC_DVFS_BASE + 0x0010U) /* IIC clock control register high */ #define IIC_ICCH (IIC_DVFS_BASE + 0x0014U) /* Bit in ICSR register */ #define ICSR_BUSY (0x10U) #define ICSR_AL (0x08U) #define ICSR_TACK (0x04U) #define ICSR_WAIT (0x02U) #define ICSR_DTE (0x01U) /* Bit in ICIC register */ #define ICIC_TACKE (0x04U) #define ICIC_WAITE (0x02U) #define ICIC_DTEE (0x01U) /* I2C bus interface enable */ #define ICCR_ENABLE (0x80U) /* Start condition */ #define ICCR_START (0x94U) /* Stop condition */ #define ICCR_STOP (0x90U) /* Restart condition with change to receive mode change */ #define ICCR_START_RECV (0x81U) /* Stop condition for receive mode */ #define ICCR_STOP_RECV (0xC0U) /* Low-level period of SCL */ #define ICCL_FREQ_8p33M (0x07U) /* for CP Phy 8.3333MHz */ #define ICCL_FREQ_10M (0x09U) /* for CP Phy 10MHz */ #define ICCL_FREQ_12p5M (0x0BU) /* for CP Phy 12.5MHz */ #define ICCL_FREQ_16p66M (0x0EU) /* for CP Phy 16.6666MHz */ /* High-level period of SCL */ #define ICCH_FREQ_8p33M (0x01U) /* for CP Phy 8.3333MHz */ #define ICCH_FREQ_10M (0x02U) /* for CP Phy 10MHz */ #define ICCH_FREQ_12p5M (0x03U) /* for CP Phy 12.5MHz */ #define ICCH_FREQ_16p66M (0x05U) /* for CP Phy 16.6666MHz */ /* PMIC */ /* ROHM BD9571 slave address + (W) */ #define PMIC_W_SLAVE_ADDRESS (0x60U) /* ROHM BD9571 slave address + (R) */ #define PMIC_R_SLAVE_ADDRESS (0x61U) /* ROHM BD9571 DVFS SetVID register */ #define PMIC_DVFS_SETVID (0x54U) #endif /* PMIC_ROHM_BD9571 */ /* Individual information */ #define EFUSE_AVS0 (0U) #define EFUSE_AVS_NUM ARRAY_SIZE(init_vol_tbl) typedef struct { uint32_t avs; /* AVS code */ uint8_t vol; /* Voltage */ } initial_voltage_t; static const initial_voltage_t init_vol_tbl[] = { /* AVS code, ROHM BD9571 DVFS SetVID register */ {0x00U, 0x53U}, /* AVS0, 0.83V */ {0x01U, 0x52U}, /* AVS1, 0.82V */ {0x02U, 0x51U}, /* AVS2, 0.81V */ {0x04U, 0x50U}, /* AVS3, 0.80V */ {0x08U, 0x4FU}, /* AVS4, 0.79V */ {0x10U, 0x4EU}, /* AVS5, 0.78V */ {0x20U, 0x4DU}, /* AVS6, 0.77V */ {0x40U, 0x4CU} /* AVS7, 0.76V */ }; #if PMIC_ROHM_BD9571 /* Kind of AVS settings status */ typedef enum { avs_status_none = 0, avs_status_init, avs_status_start_condition, avs_status_set_slave_addr, avs_status_write_reg_addr, avs_status_write_reg_data, avs_status_stop_condition, avs_status_end, avs_status_complete, avs_status_al_start, avs_status_al_transfer, avs_status_nack, avs_status_error_stop, ave_status_error_end } avs_status_t; /* Kind of AVS error */ typedef enum { avs_error_none = 0, avs_error_al, avs_error_nack } avs_error_t; static avs_status_t avs_status; static uint32_t avs_retry; #endif /* PMIC_ROHM_BD9571 */ static uint32_t efuse_avs = EFUSE_AVS0; #if PMIC_ROHM_BD9571 /* prototype */ static avs_error_t avs_check_error(void); static void avs_set_iic_clock(void); #if AVS_READ_PMIC_REG_ENABLE == 1 static uint8_t avs_read_pmic_reg(uint8_t addr); static void avs_poll(uint8_t bit_pos, uint8_t val); #endif #endif /* PMIC_ROHM_BD9571 */ #endif /* (AVS_SETTING_ENABLE==1) */ /* * Initialize to enable the AVS setting. */ void rcar_avs_init(void) { #if (AVS_SETTING_ENABLE == 1) uint32_t val; #if PMIC_ROHM_BD9571 /* Initialize AVS status */ avs_status = avs_status_init; #endif /* PMIC_ROHM_BD9571 */ /* Enable clock supply to ADVFS. */ mstpcr_write(CPG_SMSTPCR9, CPG_MSTPSR9, CPG_SYS_ADVFS_BIT); /* Read AVS code (Initial values are derived from eFuse) */ val = mmio_read_32(ADVADJP2) & ADVADJP2_VOLCOND_MASK; for (efuse_avs = 0U; efuse_avs < EFUSE_AVS_NUM; efuse_avs++) { if (val == init_vol_tbl[efuse_avs].avs) break; } if (efuse_avs >= EFUSE_AVS_NUM) efuse_avs = EFUSE_AVS0; /* Not applicable */ #if PMIC_ROHM_BD9571 /* Enable clock supply to DVFS. */ mstpcr_write(CPG_SMSTPCR9, CPG_MSTPSR9, CPG_SYS_DVFS_BIT); /* Disable I2C module and All internal registers initialized. */ mmio_write_8(IIC_ICCR, 0x00U); while ((mmio_read_8(IIC_ICCR) & ICCR_ENABLE) != 0U) { /* Disable I2C module and all internal registers initialized. */ mmio_write_8(IIC_ICCR, 0x00U); } /* Set next status */ avs_status = avs_status_start_condition; #endif /* PMIC_ROHM_BD9571 */ #endif /* (AVS_SETTING_ENABLE==1) */ } /* * Set the value of register corresponding to the voltage * by transfer of I2C to PIMC. */ void rcar_avs_setting(void) { #if (AVS_SETTING_ENABLE == 1) #if PMIC_ROHM_BD9571 avs_error_t err; switch (avs_status) { case avs_status_start_condition: /* Set ICCR.ICE=1 to activate the I2C module. */ mmio_write_8(IIC_ICCR, mmio_read_8(IIC_ICCR) | ICCR_ENABLE); /* Set frequency of 400kHz */ avs_set_iic_clock(); /* Set ICIC.TACKE=1, ICIC.WAITE=1, ICIC.DTEE=1 to */ /* enable interrupt control. */ mmio_write_8(IIC_ICIC, mmio_read_8(IIC_ICIC) | ICIC_TACKE | ICIC_WAITE | ICIC_DTEE); /* Write H'94 in ICCR to issue start condition */ mmio_write_8(IIC_ICCR, ICCR_START); /* Set next status */ avs_status = avs_status_set_slave_addr; break; case avs_status_set_slave_addr: /* Check error. */ err = avs_check_error(); if (err == avs_error_al) { /* Recovery sequence of just after start. */ avs_status = avs_status_al_start; } else if (err == avs_error_nack) { /* Recovery sequence of detected NACK */ avs_status = avs_status_nack; } else { /* Was data transmission enabled ? */ if ((mmio_read_8(IIC_ICSR) & ICSR_DTE) == ICSR_DTE) { /* Clear ICIC.DTEE to disable a DTE interrupt */ mmio_write_8(IIC_ICIC, mmio_read_8(IIC_ICIC) & (uint8_t) (~ICIC_DTEE)); /* Send PMIC slave address + (W) */ mmio_write_8(IIC_ICDR, PMIC_W_SLAVE_ADDRESS); /* Set next status */ avs_status = avs_status_write_reg_addr; } } break; case avs_status_write_reg_addr: /* Check error. */ err = avs_check_error(); if (err == avs_error_al) { /* Recovery sequence of during data transfer. */ avs_status = avs_status_al_transfer; } else if (err == avs_error_nack) { /* Recovery sequence of detected NACK */ avs_status = avs_status_nack; } else { /* If wait state after data transmission. */ if ((mmio_read_8(IIC_ICSR) & ICSR_WAIT) == ICSR_WAIT) { /* Write PMIC DVFS_SetVID address */ mmio_write_8(IIC_ICDR, PMIC_DVFS_SETVID); /* Clear ICSR.WAIT to exit from wait state. */ mmio_write_8(IIC_ICSR, mmio_read_8(IIC_ICSR) & (uint8_t) (~ICSR_WAIT)); /* Set next status */ avs_status = avs_status_write_reg_data; } } break; case avs_status_write_reg_data: /* Check error. */ err = avs_check_error(); if (err == avs_error_al) { /* Recovery sequence of during data transfer. */ avs_status = avs_status_al_transfer; } else if (err == avs_error_nack) { /* Recovery sequence of detected NACK */ avs_status = avs_status_nack; } else { /* If wait state after data transmission. */ if ((mmio_read_8(IIC_ICSR) & ICSR_WAIT) == ICSR_WAIT) { /* Dose efuse_avs exceed the number of */ /* the tables? */ if (efuse_avs >= EFUSE_AVS_NUM) { ERROR("%s%s=%u\n", "AVS number of ", "eFuse is out of range. number", efuse_avs); /* Infinite loop */ panic(); } /* Write PMIC DVFS_SetVID value */ mmio_write_8(IIC_ICDR, init_vol_tbl[efuse_avs].vol); /* Clear ICSR.WAIT to exit from wait state. */ mmio_write_8(IIC_ICSR, mmio_read_8(IIC_ICSR) & (uint8_t) (~ICSR_WAIT)); /* Set next status */ avs_status = avs_status_stop_condition; } } break; case avs_status_stop_condition: err = avs_check_error(); if (err == avs_error_al) { /* Recovery sequence of during data transfer. */ avs_status = avs_status_al_transfer; } else if (err == avs_error_nack) { /* Recovery sequence of detected NACK */ avs_status = avs_status_nack; } else { /* If wait state after data transmission. */ if ((mmio_read_8(IIC_ICSR) & ICSR_WAIT) == ICSR_WAIT) { /* Write H'90 in ICCR to issue stop condition */ mmio_write_8(IIC_ICCR, ICCR_STOP); /* Clear ICSR.WAIT to exit from wait state. */ mmio_write_8(IIC_ICSR, mmio_read_8(IIC_ICSR) & (uint8_t) (~ICSR_WAIT)); /* Set next status */ avs_status = avs_status_end; } } break; case avs_status_end: /* Is this module not busy?. */ if ((mmio_read_8(IIC_ICSR) & ICSR_BUSY) == 0U) { /* Set ICCR=H'00 to disable the I2C module. */ mmio_write_8(IIC_ICCR, 0x00U); /* Set next status */ avs_status = avs_status_complete; } break; case avs_status_al_start: /* Clear ICSR.AL bit */ mmio_write_8(IIC_ICSR, (mmio_read_8(IIC_ICSR) & (uint8_t) (~ICSR_AL))); /* Transmit a clock pulse */ mmio_write_8(IIC_ICDR, init_vol_tbl[EFUSE_AVS0].vol); /* Set next status */ avs_status = avs_status_error_stop; break; case avs_status_al_transfer: /* Clear ICSR.AL bit */ mmio_write_8(IIC_ICSR, (mmio_read_8(IIC_ICSR) & (uint8_t) (~ICSR_AL))); /* Set next status */ avs_status = avs_status_error_stop; break; case avs_status_nack: /* Write H'90 in ICCR to issue stop condition */ mmio_write_8(IIC_ICCR, ICCR_STOP); /* Disable a WAIT and DTEE interrupt. */ mmio_write_8(IIC_ICIC, mmio_read_8(IIC_ICIC) & (uint8_t) (~(ICIC_WAITE | ICIC_DTEE))); /* Clear ICSR.TACK bit */ mmio_write_8(IIC_ICSR, mmio_read_8(IIC_ICSR) & (uint8_t) (~ICSR_TACK)); /* Set next status */ avs_status = ave_status_error_end; break; case avs_status_error_stop: /* If wait state after data transmission. */ if ((mmio_read_8(IIC_ICSR) & ICSR_WAIT) == ICSR_WAIT) { /* Write H'90 in ICCR to issue stop condition */ mmio_write_8(IIC_ICCR, ICCR_STOP); /* Clear ICSR.WAIT to exit from wait state. */ mmio_write_8(IIC_ICSR, mmio_read_8(IIC_ICSR) & (uint8_t) (~ICSR_WAIT)); /* Set next status */ avs_status = ave_status_error_end; } break; case ave_status_error_end: /* Is this module not busy?. */ if ((mmio_read_8(IIC_ICSR) & ICSR_BUSY) == 0U) { /* Set ICCR=H'00 to disable the I2C module. */ mmio_write_8(IIC_ICCR, 0x00U); /* Increment the re-try number of times. */ avs_retry++; /* Set start a re-try to status. */ avs_status = avs_status_start_condition; } break; case avs_status_complete: /* After "avs_status" became the "avs_status_complete", */ /* "avs_setting()" function may be called. */ break; default: /* This case is not possible. */ ERROR("AVS setting is in invalid status. status=%u\n", avs_status); /* Infinite loop */ panic(); break; } #endif /* PMIC_ROHM_BD9571 */ #endif /* (AVS_SETTING_ENABLE==1) */ } /* * Finish the AVS setting. */ void rcar_avs_end(void) { #if (AVS_SETTING_ENABLE == 1) uint32_t mstp; #if PMIC_ROHM_BD9571 /* While status is not completion, be repeated. */ while (avs_status != avs_status_complete) rcar_avs_setting(); NOTICE("AVS setting succeeded. DVFS_SetVID=0x%x\n", init_vol_tbl[efuse_avs].vol); #if AVS_READ_PMIC_REG_ENABLE == 1 { uint8_t addr = PMIC_DVFS_SETVID; uint8_t value = avs_read_pmic_reg(addr); NOTICE("Read PMIC register. address=0x%x value=0x%x\n", addr, value); } #endif /* Bit of the module which wants to disable clock supply. */ mstp = CPG_SYS_DVFS_BIT; /* Disables the supply of clock signal to a module. */ cpg_write(CPG_SMSTPCR9, mmio_read_32(CPG_SMSTPCR9) | mstp); #endif /* PMIC_ROHM_BD9571 */ /* Bit of the module which wants to disable clock supply. */ mstp = CPG_SYS_ADVFS_BIT; /* Disables the supply of clock signal to a module. */ cpg_write(CPG_SMSTPCR9, mmio_read_32(CPG_SMSTPCR9) | mstp); #endif /* (AVS_SETTING_ENABLE==1) */ } #if (AVS_SETTING_ENABLE == 1) #if PMIC_ROHM_BD9571 /* * Check error and judge re-try. */ static avs_error_t avs_check_error(void) { avs_error_t ret; if ((mmio_read_8(IIC_ICSR) & ICSR_AL) == ICSR_AL) { NOTICE("%s AVS status=%d Retry=%u\n", "Loss of arbitration is detected.", avs_status, avs_retry); /* Check of retry number of times */ if (avs_retry >= AVS_RETRY_NUM) { ERROR("AVS setting failed in retry. max=%u\n", AVS_RETRY_NUM); /* Infinite loop */ panic(); } /* Set the error detected to error status. */ ret = avs_error_al; } else if ((mmio_read_8(IIC_ICSR) & ICSR_TACK) == ICSR_TACK) { NOTICE("%s AVS status=%d Retry=%u\n", "Non-acknowledge is detected.", avs_status, avs_retry); /* Check of retry number of times */ if (avs_retry >= AVS_RETRY_NUM) { ERROR("AVS setting failed in retry. max=%u\n", AVS_RETRY_NUM); /* Infinite loop */ panic(); } /* Set the error detected to error status. */ ret = avs_error_nack; } else { /* Not error. */ ret = avs_error_none; } return ret; } /* * Set I2C for DVFS clock. */ static void avs_set_iic_clock(void) { uint32_t md_pin; /* Read Mode pin register. */ md_pin = mmio_read_32(RCAR_MODEMR) & CHECK_MD13_MD14; /* Set the module clock (CP phy) for the IIC-DVFS. */ /* CP phy is EXTAL / 2. */ switch (md_pin) { case MD14_MD13_TYPE_0: /* EXTAL = 16.6666MHz */ mmio_write_8(IIC_ICCL, ICCL_FREQ_8p33M); mmio_write_8(IIC_ICCH, ICCH_FREQ_8p33M); break; case MD14_MD13_TYPE_1: /* EXTAL = 20MHz */ mmio_write_8(IIC_ICCL, ICCL_FREQ_10M); mmio_write_8(IIC_ICCH, ICCH_FREQ_10M); break; case MD14_MD13_TYPE_2: /* EXTAL = 25MHz (H3/M3) */ mmio_write_8(IIC_ICCL, ICCL_FREQ_12p5M); mmio_write_8(IIC_ICCH, ICCH_FREQ_12p5M); break; case MD14_MD13_TYPE_3: /* EXTAL = 33.3333MHz */ mmio_write_8(IIC_ICCL, ICCL_FREQ_16p66M); mmio_write_8(IIC_ICCH, ICCH_FREQ_16p66M); break; default: /* This case is not possible. */ /* CP Phy frequency is to be set for the 16.66MHz */ mmio_write_8(IIC_ICCL, ICCL_FREQ_16p66M); mmio_write_8(IIC_ICCH, ICCH_FREQ_16p66M); break; } } #if AVS_READ_PMIC_REG_ENABLE == 1 /* * Read the value of the register of PMIC. */ static uint8_t avs_read_pmic_reg(uint8_t addr) { uint8_t reg; /* Set ICCR.ICE=1 to activate the I2C module. */ mmio_write_8(IIC_ICCR, mmio_read_8(IIC_ICCR) | ICCR_ENABLE); /* Set frequency of 400kHz */ avs_set_iic_clock(); /* * Set ICIC.WAITE=1, ICIC.DTEE=1 to enable data transmission * interrupt and wait interrupt. */ mmio_write_8(IIC_ICIC, mmio_read_8(IIC_ICIC) | ICIC_WAITE | ICIC_DTEE); /* Write H'94 in ICCR to issue start condition */ mmio_write_8(IIC_ICCR, ICCR_START); /* Wait for a until ICSR.DTE becomes 1. */ avs_poll(ICSR_DTE, 1U); /* Clear ICIC.DTEE to disable a DTE interrupt. */ mmio_write_8(IIC_ICIC, mmio_read_8(IIC_ICIC) & (uint8_t) (~ICIC_DTEE)); /* Send slave address of PMIC */ mmio_write_8(IIC_ICDR, PMIC_W_SLAVE_ADDRESS); /* Wait for a until ICSR.WAIT becomes 1. */ avs_poll(ICSR_WAIT, 1U); /* write PMIC address */ mmio_write_8(IIC_ICDR, addr); /* Clear ICSR.WAIT to exit from WAIT status. */ mmio_write_8(IIC_ICSR, mmio_read_8(IIC_ICSR) & (uint8_t) (~ICSR_WAIT)); /* Wait for a until ICSR.WAIT becomes 1. */ avs_poll(ICSR_WAIT, 1U); /* Write H'94 in ICCR to issue restart condition */ mmio_write_8(IIC_ICCR, ICCR_START); /* Clear ICSR.WAIT to exit from WAIT status. */ mmio_write_8(IIC_ICSR, mmio_read_8(IIC_ICSR) & (uint8_t) (~ICSR_WAIT)); /* Set ICIC.DTEE=1 to enable data transmission interrupt. */ mmio_write_8(IIC_ICIC, mmio_read_8(IIC_ICIC) | ICIC_DTEE); /* Wait for a until ICSR.DTE becomes 1. */ avs_poll(ICSR_DTE, 1U); /* Clear ICIC.DTEE to disable a DTE interrupt. */ mmio_write_8(IIC_ICIC, mmio_read_8(IIC_ICIC) & (uint8_t) (~ICIC_DTEE)); /* Send slave address of PMIC */ mmio_write_8(IIC_ICDR, PMIC_R_SLAVE_ADDRESS); /* Wait for a until ICSR.WAIT becomes 1. */ avs_poll(ICSR_WAIT, 1U); /* Write H'81 to ICCR to issue the repeated START condition */ /* for changing the transmission mode to the receive mode. */ mmio_write_8(IIC_ICCR, ICCR_START_RECV); /* Clear ICSR.WAIT to exit from WAIT status. */ mmio_write_8(IIC_ICSR, mmio_read_8(IIC_ICSR) & (uint8_t) (~ICSR_WAIT)); /* Wait for a until ICSR.WAIT becomes 1. */ avs_poll(ICSR_WAIT, 1U); /* Set ICCR to H'C0 for the STOP condition */ mmio_write_8(IIC_ICCR, ICCR_STOP_RECV); /* Clear ICSR.WAIT to exit from WAIT status. */ mmio_write_8(IIC_ICSR, mmio_read_8(IIC_ICSR) & (uint8_t) (~ICSR_WAIT)); /* Set ICIC.DTEE=1 to enable data transmission interrupt. */ mmio_write_8(IIC_ICIC, mmio_read_8(IIC_ICIC) | ICIC_DTEE); /* Wait for a until ICSR.DTE becomes 1. */ avs_poll(ICSR_DTE, 1U); /* Receive DVFS SetVID register */ /* Clear ICIC.DTEE to disable a DTE interrupt. */ mmio_write_8(IIC_ICIC, mmio_read_8(IIC_ICIC) & (uint8_t) (~ICIC_DTEE)); /* Receive DVFS SetVID register */ reg = mmio_read_8(IIC_ICDR); /* Wait until ICSR.BUSY is cleared. */ avs_poll(ICSR_BUSY, 0U); /* Set ICCR=H'00 to disable the I2C module. */ mmio_write_8(IIC_ICCR, 0x00U); return reg; } /* * Wait processing by the polling. */ static void avs_poll(uint8_t bit_pos, uint8_t val) { uint8_t bit_val = 0U; if (val != 0U) bit_val = bit_pos; while (1) { if ((mmio_read_8(IIC_ICSR) & bit_pos) == bit_val) break; } } #endif /* AVS_READ_PMIC_REG_ENABLE */ #endif /* PMIC_ROHM_BD9571 */ #endif /* (AVS_SETTING_ENABLE==1) */
8,863
30,023
<reponame>domwillcode/home-assistant<gh_stars>1000+ """The blockchain component."""
28
3,294
<reponame>BaruaSourav/docs // <Snippet5> #using <system.dll> #using <system.runtime.remoting.dll> #using "server.dll" using namespace System; using namespace System::Runtime::Remoting; using namespace System::Runtime::Remoting::Channels::Tcp; using namespace System::Runtime::Remoting::Channels; int main() { // open channel and get handle to Object ChannelServices::RegisterChannel( gcnew TcpChannel ); //Registering the well known Object on the client side for use by the operator gcnew. RemotingConfiguration::RegisterWellKnownClientType( HelloServer::typeid, "tcp://localhost:8084/SayHello" ); HelloServer^ obj = gcnew HelloServer; // call remote method Console::WriteLine(); Console::WriteLine( "Before Call" ); Console::WriteLine( obj->HelloMethod( "Caveman" ) ); Console::WriteLine( obj->HelloMethod( "Spaceman" ) ); Console::WriteLine( obj->HelloMethod( "Client Man" ) ); Console::WriteLine( "After Call" ); Console::WriteLine(); } //</Snippet5>
329
2,645
<reponame>orustammanapov/spring-data-elasticsearch /* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.elasticsearch.core; import org.springframework.lang.Nullable; /** * Response object for items returned from multiget requests, encapsulating the returned data and potential error * information. * * @param <T> the entity type * @author <NAME> * @since 4.2 */ public class MultiGetItem<T> { @Nullable private final T item; @Nullable private final Failure failure; private MultiGetItem(@Nullable T item, @Nullable Failure failure) { this.item = item; this.failure = failure; } public static <T> MultiGetItem<T> of(@Nullable T item, @Nullable Failure failure) { return new MultiGetItem<>(item, failure); } public boolean hasItem() { return item != null; } @Nullable public T getItem() { return item; } public boolean isFailed() { return failure != null; } @Nullable public Failure getFailure() { return failure; } public static class Failure { @Nullable private final String index; @Nullable private final String type; @Nullable private final String id; @Nullable private final Exception exception; private Failure(@Nullable String index, @Nullable String type, @Nullable String id, @Nullable Exception exception) { this.index = index; this.type = type; this.id = id; this.exception = exception; } public static Failure of(String index, String type, String id, Exception exception) { return new Failure(index, type, id, exception); } @Nullable public String getIndex() { return index; } @Nullable public String getType() { return type; } @Nullable public String getId() { return id; } @Nullable public Exception getException() { return exception; } } }
739
3,262
package com.tencent.angel.ps.server.data.exception; public class ObjectNotFoundException extends RuntimeException { public ObjectNotFoundException(String log) { super(log); } }
55
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svl.hxx" #include <svl/lngmisc.hxx> #include <tools/solar.h> #include <tools/string.hxx> #include <tools/debug.hxx> #include <rtl/ustrbuf.hxx> #include <rtl/ustring.hxx> using namespace rtl; namespace linguistic { /////////////////////////////////////////////////////////////////////////// sal_Int32 GetNumControlChars( const OUString &rTxt ) { sal_Int32 nCnt = 0; sal_Int32 nLen = rTxt.getLength(); for (sal_Int32 i = 0; i < nLen; ++i) { if (IsControlChar( rTxt[i] )) ++nCnt; } return nCnt; } sal_Bool RemoveHyphens( OUString &rTxt ) { sal_Bool bModified = sal_False; if (HasHyphens( rTxt )) { String aTmp( rTxt ); aTmp.EraseAllChars( SVT_SOFT_HYPHEN ); aTmp.EraseAllChars( SVT_HARD_HYPHEN ); rTxt = aTmp; bModified = sal_True; } return bModified; } sal_Bool RemoveControlChars( OUString &rTxt ) { sal_Bool bModified = sal_False; sal_Int32 nCtrlChars = GetNumControlChars( rTxt ); if (nCtrlChars) { sal_Int32 nLen = rTxt.getLength(); sal_Int32 nSize = nLen - nCtrlChars; OUStringBuffer aBuf( nSize ); aBuf.setLength( nSize ); sal_Int32 nCnt = 0; for (sal_Int32 i = 0; i < nLen; ++i) { sal_Unicode cChar = rTxt[i]; if (!IsControlChar( cChar )) { DBG_ASSERT( nCnt < nSize, "index out of range" ); aBuf.setCharAt( nCnt++, cChar ); } } DBG_ASSERT( nCnt == nSize, "wrong size" ); rTxt = aBuf.makeStringAndClear(); bModified = sal_True; } return bModified; } // non breaking field character #define CH_TXTATR_INWORD ((sal_Char) 0x02) sal_Bool ReplaceControlChars( rtl::OUString &rTxt, sal_Char /*aRplcChar*/ ) { // the resulting string looks like this: // 1. non breaking field characters get removed // 2. remaining control characters will be replaced by ' ' sal_Bool bModified = sal_False; sal_Int32 nCtrlChars = GetNumControlChars( rTxt ); if (nCtrlChars) { sal_Int32 nLen = rTxt.getLength(); OUStringBuffer aBuf( nLen ); sal_Int32 nCnt = 0; for (sal_Int32 i = 0; i < nLen; ++i) { sal_Unicode cChar = rTxt[i]; if (CH_TXTATR_INWORD != cChar) { if (IsControlChar( cChar )) cChar = ' '; DBG_ASSERT( nCnt < nLen, "index out of range" ); aBuf.setCharAt( nCnt++, cChar ); } } aBuf.setLength( nCnt ); rTxt = aBuf.makeStringAndClear(); bModified = sal_True; } return bModified; } String GetThesaurusReplaceText( const String &rText ) { // The strings for synonyms returned by the thesaurus sometimes have some // explanation text put in between '(' and ')' or a trailing '*'. // These parts should not be put in the ReplaceEdit Text that may get // inserted into the document. Thus we strip them from the text. String aText( rText ); xub_StrLen nPos = aText.Search( sal_Unicode('(') ); while (STRING_NOTFOUND != nPos) { xub_StrLen nEnd = aText.Search( sal_Unicode(')'), nPos ); if (STRING_NOTFOUND != nEnd) aText.Erase( nPos, nEnd-nPos+1 ); else break; nPos = aText.Search( sal_Unicode('(') ); } nPos = aText.Search( sal_Unicode('*') ); if (STRING_NOTFOUND != nPos) aText.Erase( nPos ); // remove any possible remaining ' ' that may confuse the thesaurus // when it gets called with the text aText.EraseLeadingAndTrailingChars( sal_Unicode(' ') ); return aText; } /////////////////////////////////////////////////////////////////////////// } // namespace linguistic
1,871
854
/* * This file is part of Kintinuous. * * Copyright (C) 2015 The National University of Ireland Maynooth and * Massachusetts Institute of Technology * * The use of the code within this file and all code within files that * make up the software that is Kintinuous is permitted for * non-commercial purposes only. The full terms and conditions that * apply to the code within this file are detailed within the LICENSE.txt * file and at <http://www.cs.nuim.ie/research/vision/data/kintinuous/code.php> * unless explicitly stated. By downloading this file you agree to * comply with these terms. * * If you wish to use any of this code for commercial purposes then * please email <EMAIL>. */ #ifndef UTILS_ORDEREDJACOBIANROW_H_ #define UTILS_ORDEREDJACOBIANROW_H_ #include <cassert> #include <unordered_map> class OrderedJacobianRow { public: OrderedJacobianRow(const int nonZeros) : indices(new int[nonZeros]), vals(new double[nonZeros]), lastSlot(0), lastIndex(-1), maxNonZero(nonZeros) {} virtual ~OrderedJacobianRow() { delete [] indices; delete [] vals; } //You have to use this in an ordered fashion for efficiency :) void append(const int index, const double value) { assert(index > lastIndex); indexSlotMap[index] = lastSlot; indices[lastSlot] = index; vals[lastSlot] = value; lastSlot++; lastIndex = index; } int nonZeros() { return lastSlot; } int * indices; double * vals; private: int lastSlot; int lastIndex; const int maxNonZero; std::unordered_map<int, int> indexSlotMap; }; #endif /* UTILS_ORDEREDJACOBIANROW_H_ */
787
334
<reponame>bincrack666/BlackObfuscator<filename>dexlib2/src/main/java/org/jf/dexlib2/analysis/ClassPathResolver.java ///* // * Copyright 2016, Google Inc. // * All rights reserved. // * // * Redistribution and use in source and binary forms, with or without // * modification, are permitted provided that the following conditions are // * met: // * // * Redistributions of source code must retain the above copyright // * notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // * copyright notice, this list of conditions and the following disclaimer // * in the documentation and/or other materials provided with the // * distribution. // * Neither the name of Google Inc. nor the names of its // * contributors may be used to endorse or promote products derived from // * this software without specific prior written permission. // * // * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // */ // //package org.jf.dexlib2.analysis; // //import com.google.common.base.Joiner; //import com.google.common.base.Splitter; //import com.google.common.collect.Lists; //import org.jf.dexlib2.DexFileFactory; //import org.jf.dexlib2.DexFileFactory.UnsupportedFileTypeException; //import org.jf.dexlib2.Opcodes; //import org.jf.dexlib2.dexbacked.DexBackedDexFile; //import org.jf.dexlib2.dexbacked.DexBackedOdexFile; //import org.jf.dexlib2.dexbacked.OatFile; //import org.jf.dexlib2.dexbacked.OatFile.OatDexFile; //import org.jf.dexlib2.iface.DexFile; //import org.jf.dexlib2.iface.MultiDexContainer; //import org.jf.dexlib2.iface.MultiDexContainer.MultiDexFile; // // // //import java.io.File; //import java.io.IOException; //import java.util.HashSet; //import java.util.List; //import java.util.Set; // //public class ClassPathResolver { // private final Iterable<String> classPathDirs; // private final Opcodes opcodes; // // private final Set<File> loadedFiles = new HashSet<>(); // private final List<ClassProvider> classProviders = Lists.newArrayList(); // // /** // * Constructs a new ClassPathResolver using a specified list of bootclasspath entries // * // * @param bootClassPathDirs A list of directories to search for boot classpath entries. Can be empty if all boot // * classpath entries are specified as local paths // * @param bootClassPathEntries A list of boot classpath entries to load. These can either be local paths, or // * device paths (e.g. "/system/framework/framework.jar"). The entry will be interpreted // * first as a local path. If not found as a local path, it will be interpreted as a // * partial or absolute device path, and will be searched for in bootClassPathDirs // * @param extraClassPathEntries A list of additional classpath entries to load. Can be empty. All entries must be // * local paths. Device paths are not supported. // * @param dexFile The dex file that the classpath will be used to analyze // * @throws IOException If any IOException occurs // * @throws ResolveException If any classpath entries cannot be loaded for some reason // * // * If null, a default bootclasspath is used, // * depending on the the file type of dexFile and the api level. If empty, no boot // * classpath entries will be loaded // */ // public ClassPathResolver(List<String> bootClassPathDirs, List<String> bootClassPathEntries, // List<String> extraClassPathEntries, DexFile dexFile) // throws IOException { // this(bootClassPathDirs, bootClassPathEntries, extraClassPathEntries, dexFile, true); // } // // /** // * Constructs a new ClassPathResolver using a default list of bootclasspath entries // * // * @param bootClassPathDirs A list of directories to search for boot classpath entries // * @param extraClassPathEntries A list of additional classpath entries to load. Can be empty. All entries must be // * local paths. Device paths are not supported. // * @param dexFile The dex file that the classpath will be used to analyze // * @throws IOException If any IOException occurs // * @throws ResolveException If any classpath entries cannot be loaded for some reason // * // * If null, a default bootclasspath is used, // * depending on the the file type of dexFile and the api level. If empty, no boot // * classpath entries will be loaded // */ // public ClassPathResolver(List<String> bootClassPathDirs, List<String> extraClassPathEntries, // DexFile dexFile) // throws IOException { // this(bootClassPathDirs, null, extraClassPathEntries, dexFile, true); // } // // private ClassPathResolver(List<String> bootClassPathDirs, List<String> bootClassPathEntries, // List<String> extraClassPathEntries, DexFile dexFile, boolean unused) // throws IOException { // this.classPathDirs = bootClassPathDirs; // opcodes = dexFile.getOpcodes(); // // if (bootClassPathEntries == null) { // bootClassPathEntries = getDefaultBootClassPath(dexFile, opcodes.api); // } // // for (String entry : bootClassPathEntries) { // try { // loadLocalOrDeviceBootClassPathEntry(entry); // } catch (NoDexException ex) { // if (entry.endsWith(".jar")) { // String odexEntry = entry.substring(0, entry.length() - 4) + ".odex"; // try { // loadLocalOrDeviceBootClassPathEntry(odexEntry); // } catch (NoDexException ex2) { // throw new ResolveException("Neither %s nor %s contain a dex file", entry, odexEntry); // } catch (NotFoundException ex2) { // throw new ResolveException(ex); // } // } else { // throw new ResolveException(ex); // } // } catch (NotFoundException ex) { // if (entry.endsWith(".odex")) { // String jarEntry = entry.substring(0, entry.length() - 5) + ".jar"; // try { // loadLocalOrDeviceBootClassPathEntry(jarEntry); // } catch (NoDexException ex2) { // throw new ResolveException("Neither %s nor %s contain a dex file", entry, jarEntry); // } catch (NotFoundException ex2) { // throw new ResolveException(ex); // } // } else { // throw new ResolveException(ex); // } // } // } // // for (String entry: extraClassPathEntries) { // // extra classpath entries must be specified using a local path, so we don't need to do the search through // // bootClassPathDirs // try { // loadLocalClassPathEntry(entry); // } catch (NoDexException ex) { // throw new ResolveException(ex); // } // } // // if (dexFile instanceof MultiDexContainer.MultiDexFile) { // MultiDexContainer<? extends MultiDexFile> container = ((MultiDexFile)dexFile).getContainer(); // for (String entry: container.getDexEntryNames()) { // classProviders.add(new DexClassProvider(container.getEntry(entry))); // } // } else { // classProviders.add(new DexClassProvider(dexFile)); // } // } // // // public List<ClassProvider> getResolvedClassProviders() { // return classProviders; // } // // private boolean loadLocalClassPathEntry(String entry) throws NoDexException, IOException { // File entryFile = new File(entry); // if (entryFile.exists() && entryFile.isFile()) { // try { // loadEntry(entryFile, true); // return true; // } catch (UnsupportedFileTypeException ex) { // throw new ResolveException(ex, "Couldn't load classpath entry %s", entry); // } // } // return false; // } // // private void loadLocalOrDeviceBootClassPathEntry(String entry) // throws IOException, NoDexException, NotFoundException { // // first, see if the entry is a valid local path // if (loadLocalClassPathEntry(entry)) { // return; // } // // // It's not a local path, so let's try to resolve it as a device path, relative to one of the provided // // directories // List<String> pathComponents = splitDevicePath(entry); // Joiner pathJoiner = Joiner.on(File.pathSeparatorChar); // // for (String directory: classPathDirs) { // File directoryFile = new File(directory); // if (!directoryFile.exists()) { // continue; // } // // for (int i=0; i<pathComponents.size(); i++) { // String partialPath = pathJoiner.join(pathComponents.subList(i, pathComponents.size())); // File entryFile = new File(directoryFile, partialPath); // if (entryFile.exists() && entryFile.isFile()) { // loadEntry(entryFile, true); // return; // } // } // } // // throw new NotFoundException("Could not find classpath entry %s", entry); // } // // private void loadEntry(File entryFile, boolean loadOatDependencies) // throws IOException, NoDexException { // if (loadedFiles.contains(entryFile)) { // return; // } // // MultiDexContainer<? extends DexBackedDexFile> container; // try { // container = DexFileFactory.loadDexContainer(entryFile, opcodes); // } catch (UnsupportedFileTypeException ex) { // throw new ResolveException(ex); // } // // List<String> entryNames = container.getDexEntryNames(); // // if (entryNames.size() == 0) { // throw new NoDexException("%s contains no dex file", entryFile); // } // // loadedFiles.add(entryFile); // // for (String entryName: entryNames) { // classProviders.add(new DexClassProvider(container.getEntry(entryName))); // } // // if (loadOatDependencies && container instanceof OatFile) { // List<String> oatDependencies = ((OatFile)container).getBootClassPath(); // if (!oatDependencies.isEmpty()) { // try { // loadOatDependencies(entryFile.getParentFile(), oatDependencies); // } catch (NotFoundException ex) { // throw new ResolveException(ex, "Error while loading oat file %s", entryFile); // } catch (NoDexException ex) { // throw new ResolveException(ex, "Error while loading dependencies for oat file %s", entryFile); // } // } // } // } // // // private static List<String> splitDevicePath(String path) { // return Lists.newArrayList(Splitter.on('/').split(path)); // } // // private void loadOatDependencies(File directory, List<String> oatDependencies) // throws IOException, NoDexException, NotFoundException { // // We assume that all oat dependencies are located in the same directory as the oat file // for (String oatDependency: oatDependencies) { // String oatDependencyName = getFilenameForOatDependency(oatDependency); // File file = new File(directory, oatDependencyName); // if (!file.exists()) { // throw new NotFoundException("Cannot find dependency %s in %s", oatDependencyName, directory); // } // // loadEntry(file, false); // } // } // // // private String getFilenameForOatDependency(String oatDependency) { // int index = oatDependency.lastIndexOf('/'); // // String dependencyLeaf = oatDependency.substring(index+1); // if (dependencyLeaf.endsWith(".art")) { // return dependencyLeaf.substring(0, dependencyLeaf.length() - 4) + ".oat"; // } // return dependencyLeaf; // } // // private static class NotFoundException extends Exception { // public NotFoundException(String message, Object... formatArgs) { // super(String.format(message, formatArgs)); // } // } // // private static class NoDexException extends Exception { // public NoDexException(String message, Object... formatArgs) { // super(String.format(message, formatArgs)); // } // } // // /** // * An error that occurred while resolving the classpath // */ // public static class ResolveException extends RuntimeException { // public ResolveException (String message, Object... formatArgs) { // super(String.format(message, formatArgs)); // } // // public ResolveException (Throwable cause) { // super(cause); // } // // public ResolveException (Throwable cause, String message, Object... formatArgs) { // super(String.format(message, formatArgs), cause); // } // } // // /** // * Returns the default boot class path for the given dex file and api level. // */ // // private static List<String> getDefaultBootClassPath(DexFile dexFile, int apiLevel) { // if (dexFile instanceof OatFile.OatDexFile) { // List<String> bcp = ((OatDexFile)dexFile).getContainer().getBootClassPath(); // if (!bcp.isEmpty()) { // for (int i=0; i<bcp.size(); i++) { // String entry = bcp.get(i); // if (entry.endsWith(".art")) { // bcp.set(i, entry.substring(0, entry.length() - 4) + ".oat"); // } // } // return bcp; // } // return Lists.newArrayList("boot.oat"); // } // // if (dexFile instanceof DexBackedOdexFile) { // return ((DexBackedOdexFile)dexFile).getDependencies(); // } // // if (apiLevel <= 8) { // return Lists.newArrayList( // "/system/framework/core.jar", // "/system/framework/ext.jar", // "/system/framework/framework.jar", // "/system/framework/android.policy.jar", // "/system/framework/services.jar"); // } else if (apiLevel <= 11) { // return Lists.newArrayList( // "/system/framework/core.jar", // "/system/framework/bouncycastle.jar", // "/system/framework/ext.jar", // "/system/framework/framework.jar", // "/system/framework/android.policy.jar", // "/system/framework/services.jar", // "/system/framework/core-junit.jar"); // } else if (apiLevel <= 13) { // return Lists.newArrayList( // "/system/framework/core.jar", // "/system/framework/apache-xml.jar", // "/system/framework/bouncycastle.jar", // "/system/framework/ext.jar", // "/system/framework/framework.jar", // "/system/framework/android.policy.jar", // "/system/framework/services.jar", // "/system/framework/core-junit.jar"); // } else if (apiLevel <= 15) { // return Lists.newArrayList( // "/system/framework/core.jar", // "/system/framework/core-junit.jar", // "/system/framework/bouncycastle.jar", // "/system/framework/ext.jar", // "/system/framework/framework.jar", // "/system/framework/android.policy.jar", // "/system/framework/services.jar", // "/system/framework/apache-xml.jar", // "/system/framework/filterfw.jar"); // } else if (apiLevel <= 17) { // // this is correct as of api 17/4.2.2 // return Lists.newArrayList( // "/system/framework/core.jar", // "/system/framework/core-junit.jar", // "/system/framework/bouncycastle.jar", // "/system/framework/ext.jar", // "/system/framework/framework.jar", // "/system/framework/telephony-common.jar", // "/system/framework/mms-common.jar", // "/system/framework/android.policy.jar", // "/system/framework/services.jar", // "/system/framework/apache-xml.jar"); // } else if (apiLevel <= 18) { // return Lists.newArrayList( // "/system/framework/core.jar", // "/system/framework/core-junit.jar", // "/system/framework/bouncycastle.jar", // "/system/framework/ext.jar", // "/system/framework/framework.jar", // "/system/framework/telephony-common.jar", // "/system/framework/voip-common.jar", // "/system/framework/mms-common.jar", // "/system/framework/android.policy.jar", // "/system/framework/services.jar", // "/system/framework/apache-xml.jar"); // } else if (apiLevel <= 19) { // return Lists.newArrayList( // "/system/framework/core.jar", // "/system/framework/conscrypt.jar", // "/system/framework/core-junit.jar", // "/system/framework/bouncycastle.jar", // "/system/framework/ext.jar", // "/system/framework/framework.jar", // "/system/framework/framework2.jar", // "/system/framework/telephony-common.jar", // "/system/framework/voip-common.jar", // "/system/framework/mms-common.jar", // "/system/framework/android.policy.jar", // "/system/framework/services.jar", // "/system/framework/apache-xml.jar", // "/system/framework/webviewchromium.jar"); // } else if (apiLevel <= 22) { // return Lists.newArrayList( // "/system/framework/core-libart.jar", // "/system/framework/conscrypt.jar", // "/system/framework/okhttp.jar", // "/system/framework/core-junit.jar", // "/system/framework/bouncycastle.jar", // "/system/framework/ext.jar", // "/system/framework/framework.jar", // "/system/framework/telephony-common.jar", // "/system/framework/voip-common.jar", // "/system/framework/ims-common.jar", // "/system/framework/mms-common.jar", // "/system/framework/android.policy.jar", // "/system/framework/apache-xml.jar"); // } else if (apiLevel <= 23) { // return Lists.newArrayList( // "/system/framework/core-libart.jar", // "/system/framework/conscrypt.jar", // "/system/framework/okhttp.jar", // "/system/framework/core-junit.jar", // "/system/framework/bouncycastle.jar", // "/system/framework/ext.jar", // "/system/framework/framework.jar", // "/system/framework/telephony-common.jar", // "/system/framework/voip-common.jar", // "/system/framework/ims-common.jar", // "/system/framework/apache-xml.jar", // "/system/framework/org.apache.http.legacy.boot.jar"); // } else /*if (apiLevel <= 24)*/ { // return Lists.newArrayList( // "/system/framework/core-oj.jar", // "/system/framework/core-libart.jar", // "/system/framework/conscrypt.jar", // "/system/framework/okhttp.jar", // "/system/framework/core-junit.jar", // "/system/framework/bouncycastle.jar", // "/system/framework/ext.jar", // "/system/framework/framework.jar", // "/system/framework/telephony-common.jar", // "/system/framework/voip-common.jar", // "/system/framework/ims-common.jar", // "/system/framework/apache-xml.jar", // "/system/framework/org.apache.http.legacy.boot.jar"); // } // } //}
10,123
1,139
<reponame>ghiloufibelgacem/jornaldev<gh_stars>1000+ package com.journaldev.rxjavaretrofit; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.journaldev.rxjavaretrofit.pojo.Crypto; import java.util.List; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import static com.journaldev.rxjavaretrofit.CryptocurrencyService.BASE_URL; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; Retrofit retrofit; RecyclerViewAdapter recyclerViewAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerViewAdapter = new RecyclerViewAdapter(); recyclerView.setAdapter(recyclerViewAdapter); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); Gson gson = new GsonBuilder() .setLenient() .create(); retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); callEndpoints(); } private void callEndpoints() { CryptocurrencyService cryptocurrencyService = retrofit.create(CryptocurrencyService.class); //Single call /*Observable<Crypto> cryptoObservable = cryptocurrencyService.getCoinData("btc"); cryptoObservable.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).map(result -> result.ticker).subscribe(this::handleResults, this::handleError);*/ Observable<List<Crypto.Market>> btcObservable = cryptocurrencyService.getCoinData("btc") .map(result -> Observable.fromIterable(result.ticker.markets)) .flatMap(x -> x).filter(y -> { y.coinName = "btc"; return true; }).toList().toObservable(); Observable<List<Crypto.Market>> ethObservable = cryptocurrencyService.getCoinData("eth") .map(result -> Observable.fromIterable(result.ticker.markets)) .flatMap(x -> x).filter(y -> { y.coinName = "eth"; return true; }).toList().toObservable(); Observable.merge(btcObservable, ethObservable) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::handleResults, this::handleError); } private void handleResults(List<Crypto.Market> marketList) { if (marketList != null && marketList.size() != 0) { recyclerViewAdapter.setData(marketList); } else { Toast.makeText(this, "NO RESULTS FOUND", Toast.LENGTH_LONG).show(); } } private void handleError(Throwable t) { Toast.makeText(this, "ERROR IN FETCHING API RESPONSE. Try again", Toast.LENGTH_LONG).show(); } }
1,671
1,345
<reponame>Mu-L/termpair<filename>noxfile.py from pathlib import Path import nox # type: ignore python = ["3.8", "3.9"] nox.options.sessions = ["lint"] nox.options.reuse_existing_virtualenvs = True doc_deps = [".", "jinja2", "mkdocs", "mkdocs-material"] dev_deps = ["mypy", "black"] lint_deps = ["black", "flake8", "flake8-bugbear", "mypy", "check-manifest"] test_deps = [ "pytest", # required by FastAPI's test code "requests", "psutil", ] @nox.session(python=python) def serve(session): print("Note: Frontend must be built for this to work") session.install("-e", ".") session.run("termpair", "serve", *session.posargs) @nox.session(python=python) def share(session): print("Note: Frontend must be built for this to work") session.install("-e", ".") session.run("termpair", "share", *session.posargs) @nox.session(python=python) def watch_docs(session): session.install(*doc_deps) session.run("mkdocs", "serve") @nox.session(python=python) def build_frontend(session): session.run("yarn", "--cwd", "termpair/frontend_src", "install", external=True) session.run("yarn", "--cwd", "termpair/frontend_src", "build", external=True) @nox.session(python=python) def build_executable(session): """Builds a pex of termpair""" session.install("pex==2.1.45") session.run("pex", ".", "-c", "termpair", "-o", "build/termpair", external=True) @nox.session() def publish_docs(session): session.install(*doc_deps) session.run("mkdocs", "gh-deploy") @nox.session() def publish_static_webapp(session): build_frontend(session) session.run("git", "checkout", "gh-pages", external=True) session.run("rm", "-rf", "connect/", external=True) session.run("mkdir", "connect", external=True) session.run("cp", "-rT", "termpair/frontend_build/", "connect/", external=True) session.run("git", "add", "connect", external=True) session.run("git", "commit", "-m", "commit built frontend", external=True) session.run("git", "push", "origin", "gh-pages", external=True) @nox.session() def publish(session): print("REMINDER: Has the changelog been updated?") session.run("rm", "-rf", "dist", "build", external=True) publish_deps = ["setuptools", "wheel", "twine"] session.install(*publish_deps) session.run("make", "build_frontend", external=True) session.run("python", "setup.py", "--quiet", "sdist", "bdist_wheel") session.run("python", "-m", "twine", "upload", "dist/*") publish_docs(session) publish_static_webapp(session) @nox.session(python=python) def lint(session): session.install(*lint_deps) files = ["termpair", "tests"] + [str(p) for p in Path(".").glob("*.py")] session.run("black", "--check", *files) session.run("flake8", *files) session.run("mypy", *files) session.run("check-manifest") session.run("python", "setup.py", "check", "--metadata", "--strict") @nox.session(python=[python]) def test(session): session.install(".", *test_deps) # can't use default capture method because termpair requires stdin to have a fileno() session.run("pytest", "tests", "--capture", "tee-sys", *session.posargs) @nox.session(python=[python]) def termpair(session): session.install("-e", ".") session.run("termpair", *session.posargs)
1,261
852
<filename>CalibCalorimetry/EcalTPGTools/plugins/EcalTPGDBCopy.cc #include "FWCore/ServiceRegistry/interface/Service.h" #include "CondCore/DBOutputService/interface/PoolDBOutputService.h" #include <FWCore/MessageLogger/interface/MessageLogger.h> #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/EventSetup.h" #include "EcalTPGDBCopy.h" #include <vector> EcalTPGDBCopy::EcalTPGDBCopy(const edm::ParameterSet& iConfig) : m_timetype(iConfig.getParameter<std::string>("timetype")), m_cacheIDs(), m_records() { auto cc = consumesCollector(); std::string container; std::string tag; std::string record; typedef std::vector<edm::ParameterSet> Parameters; Parameters toCopy = iConfig.getParameter<Parameters>("toCopy"); for (Parameters::iterator i = toCopy.begin(); i != toCopy.end(); ++i) { container = i->getParameter<std::string>("container"); record = i->getParameter<std::string>("record"); m_cacheIDs.insert(std::make_pair(container, 0)); m_records.insert(std::make_pair(container, record)); setConsumes(cc, container); } } EcalTPGDBCopy::~EcalTPGDBCopy() {} void EcalTPGDBCopy::analyze(const edm::Event& evt, const edm::EventSetup& evtSetup) { std::string container; std::string record; typedef std::map<std::string, std::string>::const_iterator recordIter; for (recordIter i = m_records.begin(); i != m_records.end(); ++i) { container = (*i).first; record = (*i).second; if (shouldCopy(evtSetup, container)) { copyToDB(evtSetup, container); } } } void EcalTPGDBCopy::setConsumes(edm::ConsumesCollector& cc, const std::string& container) { if (container == "EcalTPGPedestals") { pedestalsToken_ = cc.esConsumes(); } else if (container == "EcalTPGLinearizationConst") { linearizationConstToken_ = cc.esConsumes(); } else if (container == "EcalTPGSlidingWindow") { slidingWindowToken_ = cc.esConsumes(); } else if (container == "EcalTPGFineGrainEBIdMap") { fineGrainEBIdMapToken_ = cc.esConsumes(); } else if (container == "EcalTPGFineGrainStripEE") { fineGrainStripEEToken_ = cc.esConsumes(); } else if (container == "EcalTPGFineGrainTowerEE") { fineGrainTowerEEToken_ = cc.esConsumes(); } else if (container == "EcalTPGLutIdMap") { lutIdMapToken_ = cc.esConsumes(); } else if (container == "EcalTPGWeightIdMap") { weightIdMapToken_ = cc.esConsumes(); } else if (container == "EcalTPGWeightGroup") { weightGroupToken_ = cc.esConsumes(); } else if (container == "EcalTPGOddWeightIdMap") { oddWeightIdMapToken_ = cc.esConsumes(); } else if (container == "EcalTPGOddWeightGroup") { oddWeightGroupToken_ = cc.esConsumes(); } else if (container == "EcalTPGTPMode") { tpModeToken_ = cc.esConsumes(); } else if (container == "EcalTPGLutGroup") { lutGroupToken_ = cc.esConsumes(); } else if (container == "EcalTPGFineGrainEBGroup") { fineGrainEBGroupToken_ = cc.esConsumes(); } else if (container == "EcalTPGPhysicsConst") { physicsConstToken_ = cc.esConsumes(); } else if (container == "EcalTPGCrystalStatus") { crystalStatusToken_ = cc.esConsumes(); } else if (container == "EcalTPGTowerStatus") { towerStatusToken_ = cc.esConsumes(); } else if (container == "EcalTPGSpike") { spikeToken_ = cc.esConsumes(); } else if (container == "EcalTPGStripStatus") { stripStatusToken_ = cc.esConsumes(); } else { throw cms::Exception("Unknown container"); } } bool EcalTPGDBCopy::shouldCopy(const edm::EventSetup& evtSetup, const std::string& container) { unsigned long long cacheID = 0; if (container == "EcalTPGPedestals") { cacheID = evtSetup.get<EcalTPGPedestalsRcd>().cacheIdentifier(); } else if (container == "EcalTPGLinearizationConst") { cacheID = evtSetup.get<EcalTPGLinearizationConstRcd>().cacheIdentifier(); } else if (container == "EcalTPGSlidingWindow") { cacheID = evtSetup.get<EcalTPGSlidingWindowRcd>().cacheIdentifier(); } else if (container == "EcalTPGFineGrainEBIdMap") { cacheID = evtSetup.get<EcalTPGFineGrainEBIdMapRcd>().cacheIdentifier(); } else if (container == "EcalTPGFineGrainStripEE") { cacheID = evtSetup.get<EcalTPGFineGrainStripEERcd>().cacheIdentifier(); } else if (container == "EcalTPGFineGrainTowerEE") { cacheID = evtSetup.get<EcalTPGFineGrainTowerEERcd>().cacheIdentifier(); } else if (container == "EcalTPGLutIdMap") { cacheID = evtSetup.get<EcalTPGLutIdMapRcd>().cacheIdentifier(); } else if (container == "EcalTPGWeightIdMap") { cacheID = evtSetup.get<EcalTPGWeightIdMapRcd>().cacheIdentifier(); } else if (container == "EcalTPGWeightGroup") { cacheID = evtSetup.get<EcalTPGWeightGroupRcd>().cacheIdentifier(); } else if (container == "EcalTPGOddWeightIdMap") { cacheID = evtSetup.get<EcalTPGOddWeightIdMapRcd>().cacheIdentifier(); } else if (container == "EcalTPGOddWeightGroup") { cacheID = evtSetup.get<EcalTPGOddWeightGroupRcd>().cacheIdentifier(); } else if (container == "EcalTPGTPMode") { cacheID = evtSetup.get<EcalTPGTPModeRcd>().cacheIdentifier(); } else if (container == "EcalTPGLutGroup") { cacheID = evtSetup.get<EcalTPGLutGroupRcd>().cacheIdentifier(); } else if (container == "EcalTPGFineGrainEBGroup") { cacheID = evtSetup.get<EcalTPGFineGrainEBGroupRcd>().cacheIdentifier(); } else if (container == "EcalTPGPhysicsConst") { cacheID = evtSetup.get<EcalTPGPhysicsConstRcd>().cacheIdentifier(); } else if (container == "EcalTPGCrystalStatus") { cacheID = evtSetup.get<EcalTPGCrystalStatusRcd>().cacheIdentifier(); } else if (container == "EcalTPGTowerStatus") { cacheID = evtSetup.get<EcalTPGTowerStatusRcd>().cacheIdentifier(); } else if (container == "EcalTPGSpike") { cacheID = evtSetup.get<EcalTPGSpikeRcd>().cacheIdentifier(); } else if (container == "EcalTPGStripStatus") { cacheID = evtSetup.get<EcalTPGStripStatusRcd>().cacheIdentifier(); } else { throw cms::Exception("Unknown container"); } if (m_cacheIDs[container] == cacheID) { return false; } else { m_cacheIDs[container] = cacheID; return true; } } void EcalTPGDBCopy::copyToDB(const edm::EventSetup& evtSetup, const std::string& container) { edm::Service<cond::service::PoolDBOutputService> dbOutput; if (!dbOutput.isAvailable()) { throw cms::Exception("PoolDBOutputService is not available"); } std::string recordName = m_records[container]; if (container == "EcalTPGPedestals") { const auto handle = evtSetup.getHandle(pedestalsToken_); const EcalTPGPedestals* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGPedestals>( new EcalTPGPedestals(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGLinearizationConst") { const auto handle = evtSetup.getHandle(linearizationConstToken_); const EcalTPGLinearizationConst* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGLinearizationConst>( new EcalTPGLinearizationConst(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGSlidingWindow") { const auto handle = evtSetup.getHandle(slidingWindowToken_); const EcalTPGSlidingWindow* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGSlidingWindow>( new EcalTPGSlidingWindow(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGFineGrainEBIdMap") { const auto handle = evtSetup.getHandle(fineGrainEBIdMapToken_); const EcalTPGFineGrainEBIdMap* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGFineGrainEBIdMap>( new EcalTPGFineGrainEBIdMap(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGFineGrainStripEE") { const auto handle = evtSetup.getHandle(fineGrainStripEEToken_); const EcalTPGFineGrainStripEE* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGFineGrainStripEE>( new EcalTPGFineGrainStripEE(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGFineGrainTowerEE") { const auto handle = evtSetup.getHandle(fineGrainTowerEEToken_); const EcalTPGFineGrainTowerEE* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGFineGrainTowerEE>( new EcalTPGFineGrainTowerEE(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGLutIdMap") { const auto handle = evtSetup.getHandle(lutIdMapToken_); const EcalTPGLutIdMap* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGLutIdMap>( new EcalTPGLutIdMap(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGWeightIdMap") { const auto handle = evtSetup.getHandle(weightIdMapToken_); const EcalTPGWeightIdMap* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGWeightIdMap>( new EcalTPGWeightIdMap(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGWeightGroup") { const auto handle = evtSetup.getHandle(weightGroupToken_); const EcalTPGWeightGroup* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGWeightGroup>( new EcalTPGWeightGroup(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGOddWeightIdMap") { const auto handle = evtSetup.getHandle(oddWeightIdMapToken_); const EcalTPGOddWeightIdMap* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGOddWeightIdMap>( new EcalTPGOddWeightIdMap(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGOddWeightGroup") { const auto handle = evtSetup.getHandle(oddWeightGroupToken_); const EcalTPGOddWeightGroup* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGOddWeightGroup>( new EcalTPGOddWeightGroup(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGTPMode") { const auto handle = evtSetup.getHandle(tpModeToken_); const EcalTPGTPMode* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGTPMode>( new EcalTPGTPMode(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGLutGroup") { const auto handle = evtSetup.getHandle(lutGroupToken_); const EcalTPGLutGroup* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGLutGroup>( new EcalTPGLutGroup(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGFineGrainEBGroup") { const auto handle = evtSetup.getHandle(fineGrainEBGroupToken_); const EcalTPGFineGrainEBGroup* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGFineGrainEBGroup>( new EcalTPGFineGrainEBGroup(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGPhysicsConst") { const auto handle = evtSetup.getHandle(physicsConstToken_); const EcalTPGPhysicsConst* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGPhysicsConst>( new EcalTPGPhysicsConst(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGCrystalStatus") { const auto handle = evtSetup.getHandle(crystalStatusToken_); const EcalTPGCrystalStatus* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGCrystalStatus>( new EcalTPGCrystalStatus(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGTowerStatus") { const auto handle = evtSetup.getHandle(towerStatusToken_); const EcalTPGTowerStatus* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGTowerStatus>( new EcalTPGTowerStatus(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGSpike") { const auto handle = evtSetup.getHandle(spikeToken_); const EcalTPGSpike* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGSpike>( new EcalTPGSpike(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else if (container == "EcalTPGStripStatus") { const auto handle = evtSetup.getHandle(stripStatusToken_); const EcalTPGStripStatus* obj = handle.product(); dbOutput->createNewIOV<const EcalTPGStripStatus>( new EcalTPGStripStatus(*obj), dbOutput->beginOfTime(), dbOutput->endOfTime(), recordName); } else { throw cms::Exception("Unknown container"); } edm::LogInfo("EcalTPGDBCopy") << "EcalTPGDBCopy wrote " << recordName; }
4,720
435
{ "abstract": "The Jupyter notebook has been the reference tool for interactive\ncomputing. Looking at the `Python Visualization\nLandscape <https://www.youtube.com/watch?v=FytuB8nFHPQ>`__, we can\nnotice a huge list of libraries, each serving a specific purpose and\ntype of data.\n\nBut what if we want to visualize a very domain specific data set, not\ncovered by these tools?\n\nRecent additions to the Jupyter ecosystem such as the Jupyter Widgets\nand JupyterLab provide a more convenient way to leverage existing\nJavaScript libraries to create rich interactive experiences in the\nbrowser. And this will be the purpose of this presentation: going\nthrough examples of widgets built with Pixi.js for specific use cases.\n\nThe first part of the presentation will be an overview of the Jupyter\nWidgets and the `Pixi.js <https://github.com/pixijs/pixi.js>`__\nJavaScript rendering library and how they can be combined to draw\nsquares and circles and interact with them.\n\nA second slightly more advanced example will show how to visually\nunderstand a computer science concept such as recursion.\n\nThe last example will be a demo of how to embed an existing web-based\ntool used to visualize and analyze the game state of users, directly in\nJupyterLab.\n", "copyright_text": null, "description": "The Jupyter ecosystem already comes with popular libraries for creating\ninteractive charts such as Bokeh and Plotly. But in some situations, we\nneed access to a lower level API to draw custom shapes (triangles,\ncircles, squares). The purpose of this presentation is to go through\nexamples of custom JupyterLab extension using Jupyter Widgets and a\nJavaScript library called Pixi.js.\n", "duration": 1456, "language": "eng", "recorded": "2018-07-08", "related_urls": [ { "label": "Conference schedule", "url": "https://pydata.org/berlin2018/schedule/" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/TcuJILbTPZg/maxresdefault.jpg", "title": "Practical examples of interactive visualizations in JupyterLab with Pixi.js and Jupyter Widgets", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=TcuJILbTPZg" } ] }
708
460
<filename>trunk/win/Source/Includes/QtIncludes/include/QtXmlPatterns/private/qsystempropertyfn_p.h #include "../../../src/xmlpatterns/functions/qsystempropertyfn_p.h"
62
19,783
<reponame>t-triobox/examples """ This file demonstrates using a custom FX Tracer to override the behavior of `torch.autograd.profiler.record_function` and make profiler ranges appear in FX-traced code. This is done with Python dynamic patching magic, allowing us to explicitly emit calls to `torch.ops.profiler._record_function_enter/_record_function_exit`. Please note that before https://github.com/pytorch/pytorch/pull/65180 lands, these ranges may be elimineated by `Graph.eliminate_dead_code` """ import torch import torch.fx # Setup: a module with `record_function` class Foo(torch.nn.Module): def forward(self, x): with torch.profiler.record_function('foo'): return torch.relu(x) f = Foo() x = torch.randn(5, 3, 2) with torch.autograd.profiler.profile() as prof: f(x) print(prof) # "foo" range is correctly recorded with normal execution """ ------------------- ------------ ------------ ------------ ------------ ------------ ------------ Name Self CPU % Self CPU CPU total % CPU total CPU time avg # of Calls ------------------- ------------ ------------ ------------ ------------ ------------ ------------ aten::zeros 6.10% 10.298us 10.04% 16.943us 16.943us 1 aten::empty 2.88% 4.857us 2.88% 4.857us 4.857us 1 aten::zero_ 1.06% 1.788us 1.06% 1.788us 1.788us 1 foo 21.28% 35.925us 89.96% 151.888us 151.888us 1 aten::empty 11.59% 19.572us 11.59% 19.572us 19.572us 1 aten::relu 23.81% 40.203us 57.09% 96.391us 96.391us 1 aten::clamp_min 3.87% 6.539us 33.28% 56.188us 56.188us 1 aten::empty 1.09% 1.847us 1.09% 1.847us 1.847us 1 aten::clamp_min 28.31% 47.802us 28.31% 47.802us 47.802us 1 ------------------- ------------ ------------ ------------ ------------ ------------ ------------ Self CPU time total: 168.831us """ traced = torch.fx.symbolic_trace(f) with torch.autograd.profiler.profile() as prof: traced(x) print(prof) # "foo" range is not recorded with FX tracing """ ------------------- ------------ ------------ ------------ ------------ ------------ ------------ Name Self CPU % Self CPU CPU total % CPU total CPU time avg # of Calls ------------------- ------------ ------------ ------------ ------------ ------------ ------------ aten::relu 23.50% 10.618us 100.00% 45.186us 45.186us 1 aten::clamp_min 18.05% 8.154us 76.50% 34.568us 34.568us 1 aten::empty 11.77% 5.317us 11.77% 5.317us 5.317us 1 aten::clamp_min 46.69% 21.097us 46.69% 21.097us 21.097us 1 ------------------- ------------ ------------ ------------ ------------ ------------ ------------ Self CPU time total: 45.186us """ class ProfilerTracer(torch.fx.Tracer): def trace(self, root, concrete_args=None): orig_record_function_enter = torch.autograd.profiler.record_function.__enter__ orig_record_function_exit = torch.autograd.profiler.record_function.__exit__ def fake_profiler_enter(_self): nonlocal self handle_proxy = self.create_proxy( kind='call_function', target=torch.ops.profiler._record_function_enter, args=(_self.name,), kwargs={}) assert getattr(_self, '_fx_profiler_ctx', None) is None setattr(_self, '_fx_profiler_ctx', handle_proxy) return handle_proxy def fake_profiler_exit(_self, exc_type, exc_value, traceback): assert hasattr(_self, '_fx_profiler_ctx') handle_proxy = _self._fx_profiler_ctx torch.ops.profiler._record_function_exit(handle_proxy) setattr(_self, '_fx_profiler_ctx', None) torch.autograd.profiler.record_function.__enter__ = fake_profiler_enter torch.autograd.profiler.record_function.__exit__ = fake_profiler_exit try: return super().trace(root, concrete_args) finally: torch.autograd.profiler.record_function.__enter__ = orig_record_function_enter torch.autograd.profiler.record_function.__exit__ = orig_record_function_exit pt = ProfilerTracer() graph_with_profiler = pt.trace(f) traced_with_profiler = torch.fx.GraphModule(pt.root, graph_with_profiler) with torch.autograd.profiler.profile() as prof: traced_with_profiler(x) print(prof) # "foo" range is recorded with special tracer behavior """ ------------------- ------------ ------------ ------------ ------------ ------------ ------------ Name Self CPU % Self CPU CPU total % CPU total CPU time avg # of Calls ------------------- ------------ ------------ ------------ ------------ ------------ ------------ foo 19.76% 39.928us 100.00% 202.055us 202.055us 1 aten::empty 3.93% 7.950us 3.93% 7.950us 7.950us 1 aten::relu 33.79% 68.282us 76.30% 154.177us 154.177us 1 aten::clamp_min 27.32% 55.198us 42.51% 85.895us 85.895us 1 aten::empty 1.28% 2.585us 1.28% 2.585us 2.585us 1 aten::clamp_min 13.91% 28.112us 13.91% 28.112us 28.112us 1 ------------------- ------------ ------------ ------------ ------------ ------------ ------------ Self CPU time total: 202.055us """
2,862
453
#include <_ansi.h> #include <sys/types.h> #include <sys/stat.h> #include "trap.h" int _execve (const char *path, char *const argv[], char *const envp[]) { return TRAP0 (SYS_execve, path, argv, envp); }
90
984
<reponame>om-sharma/java-driver /* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.driver.internal.core.metadata; import static com.datastax.oss.driver.Assertions.assertThat; import static org.mockito.Mockito.when; import com.datastax.oss.driver.api.core.metadata.EndPoint; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.internal.core.channel.ChannelFactory; import com.datastax.oss.driver.internal.core.context.InternalDriverContext; import com.datastax.oss.driver.internal.core.metrics.MetricsFactory; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList; import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet; import java.util.Map; import java.util.UUID; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class InitialNodeListRefreshTest { @Mock private InternalDriverContext context; @Mock protected MetricsFactory metricsFactory; @Mock private ChannelFactory channelFactory; private DefaultNode contactPoint1; private DefaultNode contactPoint2; private EndPoint endPoint3; private UUID hostId1; private UUID hostId2; private UUID hostId3; @Before public void setup() { when(context.getMetricsFactory()).thenReturn(metricsFactory); when(context.getChannelFactory()).thenReturn(channelFactory); contactPoint1 = TestNodeFactory.newContactPoint(1, context); contactPoint2 = TestNodeFactory.newContactPoint(2, context); endPoint3 = TestNodeFactory.newEndPoint(3); hostId1 = UUID.randomUUID(); hostId2 = UUID.randomUUID(); hostId3 = UUID.randomUUID(); } @Test public void should_copy_contact_points() { // Given Iterable<NodeInfo> newInfos = ImmutableList.of( DefaultNodeInfo.builder() .withEndPoint(contactPoint1.getEndPoint()) // in practice there are more fields, but hostId is enough to validate the logic .withHostId(hostId1) .build(), DefaultNodeInfo.builder() .withEndPoint(contactPoint2.getEndPoint()) .withHostId(hostId2) .build()); InitialNodeListRefresh refresh = new InitialNodeListRefresh(newInfos, ImmutableSet.of(contactPoint1, contactPoint2)); // When MetadataRefresh.Result result = refresh.compute(DefaultMetadata.EMPTY, false, context); // Then // contact points have been copied to the metadata, and completed with missing information Map<UUID, Node> newNodes = result.newMetadata.getNodes(); assertThat(newNodes).containsOnlyKeys(hostId1, hostId2); assertThat(newNodes.get(hostId1)).isEqualTo(contactPoint1); assertThat(contactPoint1.getHostId()).isEqualTo(hostId1); assertThat(newNodes.get(hostId2)).isEqualTo(contactPoint2); assertThat(contactPoint2.getHostId()).isEqualTo(hostId2); } @Test public void should_add_other_nodes() { // Given Iterable<NodeInfo> newInfos = ImmutableList.of( DefaultNodeInfo.builder() .withEndPoint(contactPoint1.getEndPoint()) // in practice there are more fields, but hostId is enough to validate the logic .withHostId(hostId1) .build(), DefaultNodeInfo.builder() .withEndPoint(contactPoint2.getEndPoint()) .withHostId(hostId2) .build(), DefaultNodeInfo.builder().withEndPoint(endPoint3).withHostId(hostId3).build()); InitialNodeListRefresh refresh = new InitialNodeListRefresh(newInfos, ImmutableSet.of(contactPoint1, contactPoint2)); // When MetadataRefresh.Result result = refresh.compute(DefaultMetadata.EMPTY, false, context); // Then // new node created in addition to the contact points Map<UUID, Node> newNodes = result.newMetadata.getNodes(); assertThat(newNodes).containsOnlyKeys(hostId1, hostId2, hostId3); Node node3 = newNodes.get(hostId3); assertThat(node3.getEndPoint()).isEqualTo(endPoint3); assertThat(node3.getHostId()).isEqualTo(hostId3); } @Test public void should_ignore_duplicate_host_ids() { // Given Iterable<NodeInfo> newInfos = ImmutableList.of( DefaultNodeInfo.builder() .withEndPoint(contactPoint1.getEndPoint()) // in practice there are more fields, but hostId is enough to validate the logic .withHostId(hostId1) .withDatacenter("dc1") .build(), DefaultNodeInfo.builder() .withEndPoint(contactPoint1.getEndPoint()) .withDatacenter("dc2") .withHostId(hostId1) .build()); InitialNodeListRefresh refresh = new InitialNodeListRefresh(newInfos, ImmutableSet.of(contactPoint1)); // When MetadataRefresh.Result result = refresh.compute(DefaultMetadata.EMPTY, false, context); // Then // only the first nodeInfo should have been copied Map<UUID, Node> newNodes = result.newMetadata.getNodes(); assertThat(newNodes).containsOnlyKeys(hostId1); assertThat(newNodes.get(hostId1)).isEqualTo(contactPoint1); assertThat(contactPoint1.getHostId()).isEqualTo(hostId1); assertThat(contactPoint1.getDatacenter()).isEqualTo("dc1"); } }
2,311
492
<filename>2020/02/28/How to Export CSV Files From Django/csv_export/example/models.py from django.db import models class Member(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() ip_address = models.GenericIPAddressField(protocol='IPv4')
115
984
<filename>core/src/main/java/com/datastax/dse/driver/api/core/cql/continuous/ContinuousSession.java<gh_stars>100-1000 /* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.dse.driver.api.core.cql.continuous; import com.datastax.dse.driver.internal.core.cql.continuous.ContinuousCqlRequestAsyncProcessor; import com.datastax.dse.driver.internal.core.cql.continuous.ContinuousCqlRequestSyncProcessor; import com.datastax.oss.driver.api.core.DefaultConsistencyLevel; import com.datastax.oss.driver.api.core.cql.Statement; import com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy; import com.datastax.oss.driver.api.core.metadata.token.Token; import com.datastax.oss.driver.api.core.session.Session; import edu.umd.cs.findbugs.annotations.NonNull; import java.nio.ByteBuffer; import java.util.Objects; import java.util.concurrent.CompletionStage; /** * A session that has the ability to execute continuous paging queries. * * <p>Continuous paging is a new method of streaming bulk amounts of records from Datastax * Enterprise (DSE) to the Datastax Java Driver, available since DSE 5.1. It is mainly intended to * be leveraged by <a * href="https://docs.datastax.com/en/dse/5.1/dse-dev/datastax_enterprise/analytics/analyticsTOC.html">DSE * Analytics</a> and Apache Spark™, or by any similar analytics tool that needs to read large * portions of a table in one single operation, as quick and reliably as possible. * * <p>Continuous paging provides the best performance improvement against regular paging when the * following conditions are met: * * <ol> * <li>The statement must target a single partition or a token range owned by one single replica; * in practice, this means that the statement must have either a {@linkplain * Statement#setRoutingKey(ByteBuffer) routing key} or a {@linkplain * Statement#setRoutingToken(Token) routing token} set; * <li>The coordinator must be a replica; in practice, this is usually achieved by using * token-aware routing (if you are using the driver's default {@link LoadBalancingPolicy}, * then this condition is met); * <li>The consistency level must be {@link DefaultConsistencyLevel#ONE ONE} (or {@link * DefaultConsistencyLevel#LOCAL_ONE LOCAL_ONE}). * </ol> * * <p>If the above conditions are met, the coordinator will be able to optimize the read path and * serve results from local data, thus significantly improving response times; if however these * conditions cannot be met, continuous paging would still work, but response times wouldn't be * significantly better than those of regular paging anymore. * * @see <a * href="https://docs.datastax.com/en/dse/6.7/dse-dev/datastax_enterprise/config/configCassandra_yaml.html#configCassandra_yaml__continous-paging">Continuous * paging options in cassandra.yaml configuration file</a> * @see <a * href="https://www.datastax.com/dev/blog/dse-continuous-paging-tuning-and-support-guide">DSE * Continuous Paging Tuning and Support Guide</a> */ public interface ContinuousSession extends Session { /** * Executes the provided query with continuous paging synchronously. * * <p>This method takes care of chaining the successive results into a convenient iterable, * provided that you always access the result from the same thread. For more flexibility, consider * using the {@linkplain #executeContinuouslyAsync(Statement) asynchronous variant} of this method * instead. * * <p>See {@link ContinuousSession} for more explanations about continuous paging. * * <p>This feature is only available with Datastax Enterprise. Executing continuous queries * against an Apache Cassandra&copy; cluster will result in a runtime error. * * @param statement the query to execute. * @return a synchronous iterable on the results. */ @NonNull default ContinuousResultSet executeContinuously(@NonNull Statement<?> statement) { return Objects.requireNonNull( execute(statement, ContinuousCqlRequestSyncProcessor.CONTINUOUS_RESULT_SYNC)); } /** * Executes the provided query with continuous paging asynchronously. * * <p>The server will push all requested pages asynchronously, according to the options defined in * the current execution profile. The client should consume all pages as quickly as possible, to * avoid blocking the server for too long. The server will adjust the rate according to the client * speed, but it will give up if the client does not consume any pages in a period of time equal * to the read request timeout. * * <p>See {@link ContinuousSession} for more explanations about continuous paging. * * <p>This feature is only available with Datastax Enterprise. Executing continuous queries * against an Apache Cassandra&copy; cluster will result in a runtime error. * * @param statement the query to execute. * @return a future to the first asynchronous result. */ @NonNull default CompletionStage<ContinuousAsyncResultSet> executeContinuouslyAsync( @NonNull Statement<?> statement) { return Objects.requireNonNull( execute(statement, ContinuousCqlRequestAsyncProcessor.CONTINUOUS_RESULT_ASYNC)); } }
1,699
3,482
#include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <iostream> #include <math.h> // Dedcrease color cv::Mat decrease_color(cv::Mat img){ int height = img.cols; int width = img.rows; int channel = img.channels(); cv::Mat out = cv::Mat::zeros(height, width, CV_8UC3); for(int y = 0; y < height; y++){ for(int x = 0; x < width; x++){ for(int c = 0; c < channel; c++){ out.at<cv::Vec3b>(y, x)[c] = (uchar)(floor((double)img.at<cv::Vec3b>(y, x)[c] / 64) * 64 + 32); } } } return out; } int main(int argc, const char* argv[]){ // read image cv::Mat img = cv::imread("imori.jpg", cv::IMREAD_COLOR); // decrease color cv::Mat out = decrease_color(img); //cv::imwrite("out.jpg", out); cv::imshow("answer", out); cv::waitKey(0); cv::destroyAllWindows(); return 0; }
376
852
// // test_catch2_WaitingTaskChain.cpp // CMSSW // // Created by <NAME> on 7/8/21. // #define CATCH_CONFIG_MAIN #include "catch.hpp" #include "tbb/global_control.h" #include "FWCore/Concurrency/interface/chain_first.h" TEST_CASE("Test chain::first", "[chain::first]") { tbb::global_control control(tbb::global_control::max_allowed_parallelism, 1); SECTION("no explicit exception handling") { SECTION("first | lastTask") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](edm::WaitingTaskHolder h) { ++count; REQUIRE(count.load() == 1); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | lastTask") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](auto h) { ++count; REQUIRE(count.load() == 1); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 2); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 2); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | then | lastTask") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](auto h) { ++count; REQUIRE(count.load() == 1); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 2); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 3); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 3); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | then | runLast") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; first([&count](auto h) { ++count; REQUIRE(count.load() == 1); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 2); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 3); }) | runLast(edm::WaitingTaskHolder(group, &waitTask)); } group.wait(); REQUIRE(count.load() == 3); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("exception -> first | lastTask") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](edm::WaitingTaskHolder h) { ++count; REQUIRE(false); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::make_exception_ptr(std::exception())); } group.wait(); REQUIRE(count.load() == 0); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() != nullptr); } SECTION("first(exception) | lastTask") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](edm::WaitingTaskHolder h) { ++count; REQUIRE(count.load() == 1); throw std::exception(); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() != nullptr); } SECTION("first(exception) | then | then | lastTask") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](auto h) { ++count; REQUIRE(count.load() == 1); throw std::exception(); }) | then([&count](auto h) { ++count; REQUIRE(false); }) | then([&count](auto h) { ++count; REQUIRE(false); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() != nullptr); } } SECTION("then with exception handler testing") { SECTION("first | lastTask") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](std::exception_ptr const* iPtr, edm::WaitingTaskHolder h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 1); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | lastTask") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 1); }) | then([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 2); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 2); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | then | lastTask") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 1); }) | then([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 2); }) | then([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr == nullptr); ++count; REQUIRE(count.load() == 3); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(count.load() == 3); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("exception -> first | lastTask") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](std::exception_ptr const* iPtr, edm::WaitingTaskHolder h) { REQUIRE(iPtr != nullptr); ++count; REQUIRE(count.load() == 1); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::make_exception_ptr(std::exception())); } group.wait(); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("exception -> first | then | lastTask") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first([&count](std::exception_ptr const* iPtr, edm::WaitingTaskHolder h) { REQUIRE(iPtr != nullptr); ++count; REQUIRE(count.load() == 1); h.doneWaiting(*iPtr); }) | then([&count](std::exception_ptr const* iPtr, auto h) { REQUIRE(iPtr != nullptr); ++count; REQUIRE(count.load() == 2); }) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::make_exception_ptr(std::exception())); } group.wait(); REQUIRE(count.load() == 2); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } } SECTION("ifException.else testing") { SECTION("first | lastTask") { std::atomic<int> count{0}; std::atomic<int> exceptCount{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](edm::WaitingTaskHolder h) { ++count; REQUIRE(count.load() == 1); })) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(exceptCount.load() == 0); REQUIRE(count.load() == 1); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | lastTask") { std::atomic<int> count{0}; std::atomic<int> exceptCount{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](auto h) { ++count; REQUIRE(count.load() == 1); })) | then(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](auto h) { ++count; REQUIRE(count.load() == 2); })) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(exceptCount.load() == 0); REQUIRE(count.load() == 2); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | then | then | lastTask") { std::atomic<int> count{0}; std::atomic<int> exceptCount{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](auto h) { ++count; REQUIRE(count.load() == 1); })) | then(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](auto h) { ++count; REQUIRE(count.load() == 2); })) | then(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(false); }).else_([&count](auto h) { ++count; REQUIRE(count.load() == 3); })) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::exception_ptr()); } group.wait(); REQUIRE(exceptCount.load() == 0); REQUIRE(count.load() == 3); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("exception -> first | then | then | lastTask") { std::atomic<int> count{0}; std::atomic<int> exceptCount{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; auto h = first(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(exceptCount.load() == 1); }).else_([&count](auto h) { ++count; REQUIRE(false); })) | then(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(exceptCount.load() == 2); }).else_([&count](auto h) { ++count; REQUIRE(false); })) | then(ifException([&exceptCount](std::exception_ptr const& iPtr) { ++exceptCount; REQUIRE(exceptCount.load() == 3); }).else_([&count](auto h) { ++count; REQUIRE(false); })) | lastTask(edm::WaitingTaskHolder(group, &waitTask)); h.doneWaiting(std::make_exception_ptr(std::exception())); } group.wait(); REQUIRE(exceptCount.load() == 3); REQUIRE(count.load() == 0); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() != nullptr); } } SECTION("ifThen testing") { SECTION("first | ifThen(true) | then | runLast") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; first([&count](auto h) { ++count; REQUIRE(count.load() == 1); }) | ifThen(true, [&count](auto h) { ++count; REQUIRE(count.load() == 2); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 3); }) | runLast(edm::WaitingTaskHolder(group, &waitTask)); } group.wait(); REQUIRE(count.load() == 3); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } SECTION("first | ifThen(false) | then | runLast") { std::atomic<int> count{0}; edm::FinalWaitingTask waitTask; tbb::task_group group; { using namespace edm::waiting_task::chain; first([&count](auto h) { ++count; REQUIRE(count.load() == 1); }) | ifThen(false, [&count](auto h) { ++count; REQUIRE(false); }) | then([&count](auto h) { ++count; REQUIRE(count.load() == 2); }) | runLast(edm::WaitingTaskHolder(group, &waitTask)); } group.wait(); REQUIRE(count.load() == 2); REQUIRE(waitTask.done()); REQUIRE(waitTask.exceptionPtr() == nullptr); } } }
8,754
2,151
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_EXTENSIONS_API_AUTOTEST_PRIVATE_AUTOTEST_PRIVATE_API_H_ #define CHROME_BROWSER_EXTENSIONS_API_AUTOTEST_PRIVATE_AUTOTEST_PRIVATE_API_H_ #include <string> #include "base/compiler_specific.h" #include "chrome/browser/extensions/chrome_extension_function.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "ui/message_center/public/cpp/notification_types.h" #if defined(OS_CHROMEOS) #include "ash/public/interfaces/ash_message_center_controller.mojom.h" #include "chrome/browser/chromeos/printing/cups_printers_manager.h" #endif namespace message_center { class Notification; } namespace extensions { class AutotestPrivateLogoutFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.logout", AUTOTESTPRIVATE_LOGOUT) private: ~AutotestPrivateLogoutFunction() override {} ResponseAction Run() override; }; class AutotestPrivateRestartFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.restart", AUTOTESTPRIVATE_RESTART) private: ~AutotestPrivateRestartFunction() override {} ResponseAction Run() override; }; class AutotestPrivateShutdownFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.shutdown", AUTOTESTPRIVATE_SHUTDOWN) private: ~AutotestPrivateShutdownFunction() override {} ResponseAction Run() override; }; class AutotestPrivateLoginStatusFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.loginStatus", AUTOTESTPRIVATE_LOGINSTATUS) private: ~AutotestPrivateLoginStatusFunction() override {} ResponseAction Run() override; #if defined(OS_CHROMEOS) void OnIsReadyForPassword(bool is_ready); #endif }; class AutotestPrivateLockScreenFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.lockScreen", AUTOTESTPRIVATE_LOCKSCREEN) private: ~AutotestPrivateLockScreenFunction() override {} ResponseAction Run() override; }; class AutotestPrivateGetExtensionsInfoFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.getExtensionsInfo", AUTOTESTPRIVATE_GETEXTENSIONSINFO) private: ~AutotestPrivateGetExtensionsInfoFunction() override {} ResponseAction Run() override; }; class AutotestPrivateSimulateAsanMemoryBugFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.simulateAsanMemoryBug", AUTOTESTPRIVATE_SIMULATEASANMEMORYBUG) private: ~AutotestPrivateSimulateAsanMemoryBugFunction() override {} ResponseAction Run() override; }; class AutotestPrivateSetTouchpadSensitivityFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setTouchpadSensitivity", AUTOTESTPRIVATE_SETTOUCHPADSENSITIVITY) private: ~AutotestPrivateSetTouchpadSensitivityFunction() override {} ResponseAction Run() override; }; class AutotestPrivateSetTapToClickFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setTapToClick", AUTOTESTPRIVATE_SETTAPTOCLICK) private: ~AutotestPrivateSetTapToClickFunction() override {} ResponseAction Run() override; }; class AutotestPrivateSetThreeFingerClickFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setThreeFingerClick", AUTOTESTPRIVATE_SETTHREEFINGERCLICK) private: ~AutotestPrivateSetThreeFingerClickFunction() override {} ResponseAction Run() override; }; class AutotestPrivateSetTapDraggingFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setTapDragging", AUTOTESTPRIVATE_SETTAPDRAGGING) private: ~AutotestPrivateSetTapDraggingFunction() override {} ResponseAction Run() override; }; class AutotestPrivateSetNaturalScrollFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setNaturalScroll", AUTOTESTPRIVATE_SETNATURALSCROLL) private: ~AutotestPrivateSetNaturalScrollFunction() override {} ResponseAction Run() override; }; class AutotestPrivateSetMouseSensitivityFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setMouseSensitivity", AUTOTESTPRIVATE_SETMOUSESENSITIVITY) private: ~AutotestPrivateSetMouseSensitivityFunction() override {} ResponseAction Run() override; }; class AutotestPrivateSetPrimaryButtonRightFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setPrimaryButtonRight", AUTOTESTPRIVATE_SETPRIMARYBUTTONRIGHT) private: ~AutotestPrivateSetPrimaryButtonRightFunction() override {} ResponseAction Run() override; }; class AutotestPrivateSetMouseReverseScrollFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setMouseReverseScroll", AUTOTESTPRIVATE_SETMOUSEREVERSESCROLL) private: ~AutotestPrivateSetMouseReverseScrollFunction() override {} ResponseAction Run() override; }; class AutotestPrivateGetVisibleNotificationsFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.getVisibleNotifications", AUTOTESTPRIVATE_GETVISIBLENOTIFICATIONS) AutotestPrivateGetVisibleNotificationsFunction(); private: ~AutotestPrivateGetVisibleNotificationsFunction() override; ResponseAction Run() override; #if defined(OS_CHROMEOS) void OnGotNotifications( const std::vector<message_center::Notification>& notifications); ash::mojom::AshMessageCenterControllerPtr controller_; #endif }; class AutotestPrivateGetPlayStoreStateFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.getPlayStoreState", AUTOTESTPRIVATE_GETPLAYSTORESTATE) private: ~AutotestPrivateGetPlayStoreStateFunction() override {} ResponseAction Run() override; }; class AutotestPrivateSetPlayStoreEnabledFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.setPlayStoreEnabled", AUTOTESTPRIVATE_SETPLAYSTOREENABLED) private: ~AutotestPrivateSetPlayStoreEnabledFunction() override {} ResponseAction Run() override; }; class AutotestPrivateGetPrinterListFunction : public UIThreadExtensionFunction { public: AutotestPrivateGetPrinterListFunction() = default; DECLARE_EXTENSION_FUNCTION("autotestPrivate.getPrinterList", AUTOTESTPRIVATE_GETPRINTERLIST) private: #if defined(OS_CHROMEOS) static std::string GetPrinterType( chromeos::CupsPrintersManager::PrinterClass type); #endif ~AutotestPrivateGetPrinterListFunction() override = default; ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(AutotestPrivateGetPrinterListFunction); }; class AutotestPrivateUpdatePrinterFunction : public UIThreadExtensionFunction { public: AutotestPrivateUpdatePrinterFunction(); DECLARE_EXTENSION_FUNCTION("autotestPrivate.updatePrinter", AUTOTESTPRIVATE_UPDATEPRINTER) private: ~AutotestPrivateUpdatePrinterFunction() override; ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(AutotestPrivateUpdatePrinterFunction); }; class AutotestPrivateRemovePrinterFunction : public UIThreadExtensionFunction { public: AutotestPrivateRemovePrinterFunction(); DECLARE_EXTENSION_FUNCTION("autotestPrivate.removePrinter", AUTOTESTPRIVATE_REMOVEPRINTER) private: ~AutotestPrivateRemovePrinterFunction() override; ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(AutotestPrivateRemovePrinterFunction); }; // Don't kill the browser when we're in a browser test. void SetAutotestPrivateTest(); // The profile-keyed service that manages the autotestPrivate extension API. class AutotestPrivateAPI : public BrowserContextKeyedAPI { public: static BrowserContextKeyedAPIFactory<AutotestPrivateAPI>* GetFactoryInstance(); // TODO(achuith): Replace these with a mock object for system calls. bool test_mode() const { return test_mode_; } void set_test_mode(bool test_mode) { test_mode_ = test_mode; } private: friend class BrowserContextKeyedAPIFactory<AutotestPrivateAPI>; AutotestPrivateAPI(); ~AutotestPrivateAPI() override; // BrowserContextKeyedAPI implementation. static const char* service_name() { return "AutotestPrivateAPI"; } static const bool kServiceIsNULLWhileTesting = true; static const bool kServiceRedirectedInIncognito = true; bool test_mode_; // true for ExtensionApiTest.AutotestPrivate browser test. }; template <> KeyedService* BrowserContextKeyedAPIFactory<AutotestPrivateAPI>::BuildServiceInstanceFor( content::BrowserContext* context) const; } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_AUTOTEST_PRIVATE_AUTOTEST_PRIVATE_API_H_
3,367
522
package algs.model.tests.interval; import org.junit.Test; import algs.model.IInterval; import algs.model.interval.DiscreteInterval; import algs.model.interval.IConstructor; import algs.model.interval.SegmentTree; import algs.model.interval.SegmentTreeNode; import junit.framework.TestCase; public class SegmentTreeNodeTest extends TestCase { @Test public void testContains() { SegmentTree<?> st = new SegmentTree<SegmentTreeNode<?>>(1,15); assertFalse (st.isEmpty()); assertFalse (st.remove("GARBAGE")); assertFalse (st.remove(null)); // obvious errors assertFalse (st.contains (null)); assertFalse (st.contains ("GARBAGE")); // test contains operates not on the intervals in the tree but the // nodes themselves. [14,15) is in the tree; so is [1,15), but [2,15) isn't assertTrue (st.contains (new DiscreteInterval(14,15))); assertTrue (st.contains (new DiscreteInterval(1,15))); assertFalse (st.contains (new DiscreteInterval(2,15))); } @Test public void testDefault() { SegmentTree<?> st = new SegmentTree<SegmentTreeNode<?>>(1,15); assertFalse (st.isEmpty()); st.add(new DiscreteInterval(8,13)); st.add(new DiscreteInterval(4,10)); //test remove st.remove(new DiscreteInterval(4,13)); } @Test public void testRanges() { SegmentTree<?> st = new SegmentTree<SegmentTreeNode<?>>(1,15); SegmentTreeNode<?> root = st.getRoot(); assertEquals (0, root.getCount()); SegmentTreeNode<?> expected = st.getConstructor().construct(1, 15); assertEquals (expected.getLeft(), root.getLeft()); assertEquals (expected.getRight(), root.getRight()); DiscreteInterval di = new DiscreteInterval(4,8); st.add(di); assertEquals (0, root.getCount()); SegmentTreeNode<?> tgt = root.getNode(4); assertEquals (0, tgt.getCount()); assertEquals (4, tgt.getLeft()); assertEquals (5, tgt.getRight()); SegmentTreeNode<?> left = root.getLeftSon(); assertEquals (1, left.getLeft()); assertEquals (8, left.getRight()); tgt = left.getNode(6); assertEquals (6, tgt.getLeft()); assertEquals (7, tgt.getRight()); SegmentTreeNode<?> right = left.getRightSon(); assertEquals (4, right.getLeft()); assertEquals (8, right.getRight()); assertEquals (1, right.getCount()); // Here is where edge was added. } @Test public void testSimple () { SegmentTree<?> st = new SegmentTree<SegmentTreeNode<?>>(1,15); IConstructor<?> cons = st.getConstructor(); SegmentTreeNode<?> stn = cons.construct(10, 20); assertEquals (10, stn.getLeft()); assertEquals (20, stn.getRight()); assertTrue (stn.getLeftSon() == null); assertTrue (stn.getRightSon() == null); assertTrue (stn.toTheLeft(5)); assertTrue (stn.intersects(15)); assertTrue (stn.toTheRight(30)); // invariants. assertFalse (stn.toTheLeft(stn.getLeft())); assertTrue (stn.toTheRight(stn.getRight())); assertTrue (stn.intersects(stn.getLeft())); assertTrue (stn.equals(stn)); assertTrue (stn.equals(new DiscreteInterval(10,20))); } /** * This test ensures that SegmentTree node performs rudimentary checks on the * IInterval structure. */ public void testBadIInterval() { SegmentTree<?> st = new SegmentTree<SegmentTreeNode<?>>(1,15); IConstructor<?> cons = st.getConstructor(); SegmentTreeNode<?> stn = cons.construct(10, 20); try { stn.checkInterval(new IInterval() { // BAD because LEFT is greater than RIGHT public int getLeft() { return 30; } public int getRight() { return 0; } // NO meaningful implementations public boolean intersects(int q) { return false; } public boolean equals(Object o) { if (o == null) { return false; } if (o instanceof IInterval) { IInterval i = (IInterval) o; return getLeft() == i.getLeft() && getRight() == i.getRight(); } return false; } public boolean toTheLeft(int q) { return false; } public boolean toTheRight(int q) { return false; } }); fail ("Not proper checks for SegmentTreeNode"); } catch (IllegalArgumentException iae) { } } @Test public void testIntersections(){ SegmentTree<?> st = new SegmentTree<SegmentTreeNode<?>>(1,15); SegmentTreeNode<?> stn = st.getRoot(); assertTrue (stn.toTheLeft(-8)); assertFalse (stn.toTheLeft(7)); assertTrue (stn.toTheRight(23)); assertFalse (stn.toTheRight(7)); assertTrue (stn.intersects(7)); assertFalse (stn.intersects(-8)); assertFalse (stn.intersects(23)); } @Test public void testErrors() { SegmentTree<?> st = new SegmentTree<SegmentTreeNode<?>>(1,15); SegmentTreeNode<?> stn = st.getRoot(); try { stn.getValue(); fail ("no value associated with SegmentTreeNode objects."); } catch (UnsupportedOperationException uoe) { } // equals checks. assertFalse (stn.equals (null)); assertFalse (stn.equals ("GARBAGE")); } }
1,930
623
// Copyright (C) 2014 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 com.google.gerrit.server.cache; public interface PersistentCache { DiskStats diskStats(); class DiskStats { private final long size; private final long space; private final long hitCount; private final long missCount; public DiskStats(long size, long space, long hitCount, long missCount) { this.size = size; this.space = space; this.hitCount = hitCount; this.missCount = missCount; } public long size() { return size; } public long space() { return space; } public long hitCount() { return hitCount; } public long requestCount() { return hitCount + missCount; } } }
407
1,602
<gh_stars>1000+ """Custom authentication for DRF.""" from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from django_otp.models import Device from drf_spectacular.contrib.rest_framework_simplejwt import SimpleJWTScheme from rest_framework import status from rest_framework.exceptions import APIException from rest_framework_simplejwt.authentication import JWTAuthentication from . import constants class NotVerified(APIException): status_code = status.HTTP_418_IM_A_TEAPOT default_detail = _('Missing 2FA verification.') default_code = 'not_verified' class JWTAuthenticationWith2FA(JWTAuthentication): """Add 2FA support.""" def verify_user(self, request, user): header = self.get_header(request) raw_token = self.get_raw_token(header) validated_token = self.get_validated_token(raw_token) url_exceptions = ( reverse("v2:account-tfa-verify-code"), ) if request.path in url_exceptions: return if constants.TFA_DEVICE_TOKEN_KEY in validated_token: device_id = validated_token[constants.TFA_DEVICE_TOKEN_KEY] device = Device.from_persistent_id(device_id) if device is not None and device.user_id == user.pk: return raise NotVerified def authenticate(self, request): result = super().authenticate(request) if result is None: return None user, token = result if user.tfa_enabled: self.verify_user(request, user) return user, token class SimpleJWTWith2FAScheme(SimpleJWTScheme): target_class = 'modoboa.core.drf_authentication.JWTAuthenticationWith2FA' name = 'jwt2FAAuth'
706
3,428
<reponame>ghalimi/stdlib<filename>lib/node_modules/@stdlib/datasets/spam-assassin/data/easy-ham-1/00292.d70b6d753352d01060579b1c34df4e4d.json {"id":"00292","group":"easy-ham-1","checksum":{"type":"MD5","value":"d70b6d753352d01060579b1c34df4e4d"},"text":"From <EMAIL> Wed Oct 9 10:53:22 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: zzzz<EMAIL>.spamassassin.taint.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby spamassassin.taint.org (Postfix) with ESMTP id C262316F82\n\tfor <zzzz@localhost>; Wed, 9 Oct 2002 10:52:20 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor zzzz@localhost (single-drop); Wed, 09 Oct 2002 10:52:20 +0100 (IST)\nReceived: from egwn.net (ns2.egwn.net [172.16.31.10]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g999a0K28408 for\n <<EMAIL>>; Wed, 9 Oct 2002 10:36:01 +0100\nReceived: from auth02.nl.egwn.net (localhost [127.0.0.1]) by egwn.net\n (8.11.6/8.11.6/EGWN) with ESMTP id g999T2f09799; Wed, 9 Oct 2002 11:29:02\n +0200\nReceived: from evv.kamakiriad.local (cable-b-36.sigecom.net\n [63.69.210.36]) by egwn.net (8.11.6/8.11.6/EGWN) with ESMTP id\n g999Rif01254 for <<EMAIL>>; Wed, 9 Oct 2002 11:27:45 +0200\nReceived: from aquila.kamakiriad.local (aquila.kamakiriad.local\n [1192.168.3.11]) by kamakiriad.com (8.11.6/8.11.6) with SMTP id g999RWP18078\n for <<EMAIL>>; Wed, 9 Oct 2002 04:27:32 -0500\nFrom: <NAME> <<EMAIL>>\nTo: [email protected]\nSubject: Re: Apt repository authentication: it's time\nMessage-Id: <<EMAIL>>\nIn-Reply-To: <<EMAIL>21009110311.<EMAIL>>\nReferences: <<EMAIL>1754<EMAIL>>\n <<EMAIL>09110311.<EMAIL>>\nX-Mailer: Sylpheed version 0.8.5 (GTK+ 1.2.10; i386-redhat-linux)\nX-Message-Flag: : Shame on you! You know Outlook is how viruses are spread!\nMIME-Version: 1.0\nContent-Type: text/plain; charset=ISO-8859-1\nContent-Transfer-Encoding: 8bit\nX-Mailscanner: Found to be clean, Found to be clean\nSender: <EMAIL>-zzzlist-admin<EMAIL>.net\nErrors-To: [email protected]\nX-Beenthere: [email protected]\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nReply-To: [email protected]\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://lists.freshrpms.net/mailman/listinfo/rpm-zzzlist>,\n <mailto:<EMAIL>?subject=subscribe>\nList-Id: Freshrpms RPM discussion list <rpm-zzzlist.freshrpms.net>\nList-Unsubscribe: <http://lists.freshrpms.net/mailman/listinfo/rpm-zzzlist>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://lists.freshrpms.net/pipermail/rpm-zzzlist/>\nX-Original-Date: Wed, 9 Oct 2002 04:27:34 -0500\nDate: Wed, 9 Oct 2002 04:27:34 -0500\n\nOn Wed, 9 Oct 2002 11:03:11 +0200, <NAME> <<EMAIL>> wrote:\n\n> I don't think gpg signing my repositories will help anything, as it will\n> just ensure that my passphrase was typed to confirm the md5 signatures of\n> all pgklists and srclists. Basically, you'll then just be sure that it's me\n> who generated the files, and this will of course prevent automating the\n> process of updating the apt repository when Red Hat updates show up.\n\n Isn't there a packager-key that's concealed inside the rpm? Things have changed a bit since I used to work with'em, but I thought there was some internal number that must be compared to be correct (or, presumably, return an error.)\n \n> In Red Hat Linux 8.0 though, the warnings about \"No Key\" appear until you\n> import the right gpg public keys directly with rpm, for example :\n> rpm --import /usr/share/doc/apt-0.5.4cnc7/RPM-GPG-KEY\n> (this will import my key, which is used to sign all freshrpms.net packages)\n\n Hey, cool; wether it protects me or not, I feel better about it.\n \n> Hopefully it is possible to the tell rpm to install *only* packages who\n> verify against an imported gpg key? This for me would be the optimal way to\n> ensure integrity with the way things curently work.\n\n Yeah, surely there's a flag for that; there is, for everything else, aye? :)\n\n------------------------------------------------------------------------\<NAME>�nder Linux Zealot, Conservative, and Technomad\nEvansville, IN My Voyage: http://www.CounterMoon.com\nICQ 5119262\n------------------------------------------------------------------------\nangegangen, Schlange-H�ften, sein es ganz r�ber jetzt. B�gel innen fest,\nweil es eine lange, s�sse Fahrt ist. \n\n_______________________________________________\nRPM-List mailing list <<EMAIL>>\nhttp://lists.freshrpms.net/mailman/listinfo/rpm-list\n\n\n"}
1,782
763
<reponame>zabrewer/batfish<filename>projects/batfish/src/main/java/org/batfish/representation/cisco_nxos/IpCommunityListStandard.java<gh_stars>100-1000 package org.batfish.representation.cisco_nxos; import java.util.SortedMap; import java.util.TreeMap; import javax.annotation.Nonnull; /** * An access-list that matches a route's standard communities attribute against a set of literal * standard communities. */ public final class IpCommunityListStandard extends IpCommunityList { private final @Nonnull SortedMap<Long, IpCommunityListStandardLine> _lines; public IpCommunityListStandard(String name) { super(name); _lines = new TreeMap<>(); } @Override public <T> T accept(IpCommunityListVisitor<T> visitor) { return visitor.visitIpCommunityListStandard(this); } public @Nonnull SortedMap<Long, IpCommunityListStandardLine> getLines() { return _lines; } }
292
14,668
// Copyright (c) 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/download/android/mock_download_controller.h" #include <utility> #include "base/bind.h" #include "base/location.h" #include "base/threading/thread_task_runner_handle.h" namespace chrome { namespace android { MockDownloadController::MockDownloadController() : approve_file_access_request_(true) {} MockDownloadController::~MockDownloadController() {} void MockDownloadController::OnDownloadStarted( download::DownloadItem* download_item) {} void MockDownloadController::StartContextMenuDownload( const content::ContextMenuParams& params, content::WebContents* web_contents, bool is_link) {} void MockDownloadController::AcquireFileAccessPermission( const content::WebContents::Getter& wc_getter, DownloadControllerBase::AcquireFileAccessPermissionCallback cb) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(cb), approve_file_access_request_)); } void MockDownloadController::SetApproveFileAccessRequestForTesting( bool approve) { approve_file_access_request_ = approve; } void MockDownloadController::CreateAndroidDownload( const content::WebContents::Getter& wc_getter, const DownloadInfo& info) {} void MockDownloadController::AboutToResumeDownload( download::DownloadItem* download_item) {} } // namespace android } // namespace chrome
464
348
{"nom":"Orcier","circ":"5ème circonscription","dpt":"Haute-Savoie","inscrits":823,"abs":453,"votants":370,"blancs":23,"nuls":6,"exp":341,"res":[{"nuance":"DVD","nom":"<NAME>","voix":178},{"nuance":"REM","nom":"<NAME>","voix":163}]}
93
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef SC_EDITUTIL_HXX #define SC_EDITUTIL_HXX #include "scdllapi.h" #include "address.hxx" #include <editeng/editeng.hxx> #include <svx/pageitem.hxx> #include <tools/date.hxx> #include <tools/time.hxx> #include <tools/gen.hxx> #include <tools/fract.hxx> class OutputDevice; class ScDocument; class ScPatternAttr; class ScEditEngineDefaulter; class ScEditUtil { ScDocument* pDoc; SCCOL nCol; SCROW nRow; SCTAB nTab; Point aScrPos; OutputDevice* pDev; // MapMode muss eingestellt sein double nPPTX; double nPPTY; Fraction aZoomX; Fraction aZoomY; static const char __FAR_DATA pCalcDelimiters[]; public: static String ModifyDelimiters( const String& rOld ); /// Retrieves string with paragraphs delimited by spaces static String GetSpaceDelimitedString( const EditEngine& rEngine ); /// Retrieves string with paragraphs delimited by new lines ('\n'). static String GetMultilineString( const EditEngine& rEngine ); public: ScEditUtil( ScDocument* pDocument, SCCOL nX, SCROW nY, SCTAB nZ, const Point& rScrPosPixel, OutputDevice* pDevice, double nScaleX, double nScaleY, const Fraction& rX, const Fraction& rY ) : pDoc(pDocument),nCol(nX),nRow(nY),nTab(nZ), aScrPos(rScrPosPixel),pDev(pDevice), nPPTX(nScaleX),nPPTY(nScaleY),aZoomX(rX),aZoomY(rY) {} Rectangle GetEditArea( const ScPatternAttr* pPattern, sal_Bool bForceToTop ); }; class ScEditAttrTester { ScEditEngineDefaulter* pEngine; SfxItemSet* pEditAttrs; sal_Bool bNeedsObject; sal_Bool bNeedsCellAttr; public: ScEditAttrTester( ScEditEngineDefaulter* pEng ); ~ScEditAttrTester(); sal_Bool NeedsObject() const { return bNeedsObject; } sal_Bool NeedsCellAttr() const { return bNeedsCellAttr; } const SfxItemSet& GetAttribs() const { return *pEditAttrs; } }; // construct pool before constructing EditEngine, destroy pool after EditEngine class ScEnginePoolHelper { protected: SfxItemPool* pEnginePool; SfxItemSet* pDefaults; sal_Bool bDeleteEnginePool; sal_Bool bDeleteDefaults; ScEnginePoolHelper( SfxItemPool* pEnginePool, sal_Bool bDeleteEnginePool = sal_False ); ScEnginePoolHelper( const ScEnginePoolHelper& rOrg ); virtual ~ScEnginePoolHelper(); }; class SC_DLLPUBLIC ScEditEngineDefaulter : public ScEnginePoolHelper, public EditEngine { private: using EditEngine::SetText; public: /// bDeleteEnginePool: Engine becomes the owner of the pool /// and deletes it on destruction ScEditEngineDefaulter( SfxItemPool* pEnginePool, sal_Bool bDeleteEnginePool = sal_False ); /// If rOrg.bDeleteEnginePool: pool gets cloned and will be /// deleted on destruction. Defaults are not set. ScEditEngineDefaulter( const ScEditEngineDefaulter& rOrg ); virtual ~ScEditEngineDefaulter(); /// Creates a copy of SfxItemSet if bRememberCopy set void SetDefaults( const SfxItemSet& rDefaults, sal_Bool bRememberCopy = sal_True ); /// Becomes the owner of the SfxItemSet if bTakeOwnership set void SetDefaults( SfxItemSet* pDefaults, sal_Bool bTakeOwnership = sal_True ); /// Set the item in the default ItemSet which is created /// if it doesn't exist yet. /// The default ItemSet is then applied to each paragraph. void SetDefaultItem( const SfxPoolItem& rItem ); /// Returns the stored defaults, used to find non-default character attributes const SfxItemSet& GetDefaults(); /// Overwritten method to be able to apply defaults already set void SetText( const EditTextObject& rTextObject ); /// Current defaults are not applied, new defaults are applied void SetTextNewDefaults( const EditTextObject& rTextObject, const SfxItemSet& rDefaults, sal_Bool bRememberCopy = sal_True ); /// Current defaults are not applied, new defaults are applied void SetTextNewDefaults( const EditTextObject& rTextObject, SfxItemSet* pDefaults, sal_Bool bTakeOwnership = sal_True ); /// Overwritten method to be able to apply defaults already set void SetText( const String& rText ); /// Current defaults are not applied, new defaults are applied void SetTextNewDefaults( const String& rText, const SfxItemSet& rDefaults, sal_Bool bRememberCopy = sal_True ); /// Current defaults are not applied, new defaults are applied void SetTextNewDefaults( const String& rText, SfxItemSet* pDefaults, sal_Bool bTakeOwnership = sal_True ); /// Paragraph attributes that are not defaults are copied to /// character attributes and all paragraph attributes reset void RemoveParaAttribs(); /// Re-apply existing defaults if set, same as in SetText, /// but without EnableUndo/SetUpdateMode. void RepeatDefaults(); }; // 1/100 mm class SC_DLLPUBLIC ScTabEditEngine : public ScEditEngineDefaulter { private: void Init(const ScPatternAttr& rPattern); public: ScTabEditEngine( ScDocument* pDoc ); // Default // pEnginePool = ScDocument.GetEnginePool() // pTextObjectPool = ScDocument.GetEditPool() ScTabEditEngine( const ScPatternAttr& rPattern, SfxItemPool* pEnginePool, SfxItemPool* pTextObjectPool = NULL ); }; struct ScHeaderFieldData { String aTitle; // Titel oder Dateiname wenn kein Titel String aLongDocName; // Pfad und Dateiname String aShortDocName; // nur Dateiname String aTabName; Date aDate; Time aTime; long nPageNo; long nTotalPages; SvxNumType eNumType; ScHeaderFieldData(); }; // fuer Feldbefehle in der Tabelle class SC_DLLPUBLIC ScFieldEditEngine : public ScEditEngineDefaulter { private: sal_Bool bExecuteURL; public: // pEnginePool = ScDocument.GetEnginePool() // pTextObjectPool = ScDocument.GetEditPool() ScFieldEditEngine( SfxItemPool* pEnginePool, SfxItemPool* pTextObjectPool = NULL, sal_Bool bDeleteEnginePool = sal_False ); void SetExecuteURL(sal_Bool bSet) { bExecuteURL = bSet; } virtual void FieldClicked( const SvxFieldItem& rField, sal_uInt16, sal_uInt16 ); virtual String CalcFieldValue( const SvxFieldItem& rField, sal_uInt16 nPara, sal_uInt16 nPos, Color*& rTxtColor, Color*& rFldColor ); }; // for headers/footers with fields class SC_DLLPUBLIC ScHeaderEditEngine : public ScEditEngineDefaulter { private: ScHeaderFieldData aData; public: ScHeaderEditEngine( SfxItemPool* pEnginePool, sal_Bool bDeleteEnginePool = sal_False ); virtual String CalcFieldValue( const SvxFieldItem& rField, sal_uInt16 nPara, sal_uInt16 nPos, Color*& rTxtColor, Color*& rFldColor ); void SetTitle(const String& rNew) { aData.aTitle = rNew; } void SetLongDocName(const String& rNew) { aData.aLongDocName = rNew; } void SetShortDocName(const String& rNew) { aData.aShortDocName = rNew; } void SetTabName(const String& rNew) { aData.aTabName = rNew; } void SetDate(const Date& rNew) { aData.aDate = rNew; } void SetTime(const Time& rNew) { aData.aTime = rNew; } void SetPageNo(long nNew) { aData.nPageNo = nNew; } void SetTotalPages(long nNew) { aData.nTotalPages = nNew; } void SetNumType(SvxNumType eNew) { aData.eNumType = eNew; } void SetData(const ScHeaderFieldData& rNew) { aData = rNew; } }; // for Note text objects. class ScNoteEditEngine : public ScEditEngineDefaulter { public: // pEnginePool = ScDocument.GetEnginePool() // pTextObjectPool = ScDocument.GetEditPool() ScNoteEditEngine( SfxItemPool* pEnginePool, SfxItemPool* pTextObjectPool = NULL, sal_Bool bDeleteEnginePool = sal_False ); }; // SvxFieldData-Ableitungen sind nach Svx verschoben #endif
3,096
971
package com.ucar.datalink.worker.core.runtime; import com.ucar.datalink.common.errors.DatalinkException; import org.apache.kafka.clients.CommonClientConfigs; import org.apache.kafka.common.config.AbstractConfig; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigDef.Importance; import org.apache.kafka.common.config.ConfigDef.Type; import java.util.Map; import static org.apache.kafka.common.config.ConfigDef.Range.atLeast; /** * Common base class providing configuration for Datalink workers. * <p> * 参考自Kafka connect的org.apache.kafka.connect.runtime.WorkerConfig */ public class WorkerConfig extends AbstractConfig { private static final ConfigDef CONFIG; /** * <code>bootstrap.servers</code> */ public static final String BOOTSTRAP_SERVERS_CONFIG = "bootstrap.servers"; public static final String BOOTSTRAP_SERVERS_DOC = "A list of host/port pairs to use for establishing the initial connection to the Datalink Manager " + "The worker will make use of all servers irrespective of which servers are " + "specified here for bootstrapping;this list only impacts the initial hosts used " + "to discover the full set of servers. This list should be in the form " + "<code>host1:port1,host2:port2,...</code>. Since these servers are just used for the " + "initial connection to discover the full cluster membership (which may change " + "dynamically), this list need not contain the full set of servers (you may want more " + "than one, though, in case a server is down)."; public static final String BOOTSTRAP_SERVERS_DEFAULT = "localhost:8899"; /** * <code>task.shutdown.graceful.timeout.ms</code> */ public static final String TASK_SHUTDOWN_GRACEFUL_TIMEOUT_MS_CONFIG = "task.shutdown.graceful.timeout.ms"; private static final String TASK_SHUTDOWN_GRACEFUL_TIMEOUT_MS_DOC = "Amount of time to wait for tasks to shutdown gracefully. This is the total amount of time," + " not per task. All task have shutdown triggered, then they are waited on sequentially."; private static final String TASK_SHUTDOWN_GRACEFUL_TIMEOUT_MS_DEFAULT = "5000"; /** * <code>task.position.commit.interval.ms</code> */ public static final String POSITION_COMMIT_INTERVAL_MS_CONFIG = "task.position.commit.interval.ms"; private static final String POSITION_COMMIT_INTERVAL_MS_DOC = "Interval at which to try committing positions for tasks."; public static final long POSITION_COMMIT_INTERVAL_MS_DEFAULT = 1000L; /** * <code>task.syncstatus.commit.interval.ms</code> */ public static final String TASK_SYNCSTATUS_COMMIT_INTERVAL_MS_CONFIG = "task.syncstatus.commit.interval.ms"; private static final String TASK_SYNCSTATUS_COMMIT_INTERVAL_MS_DOC = "Interval at which to try committing syncstatus for tasks."; public static final long TASK_SYNCSTATUS_COMMIT_INTERVAL_MS_DEFAULT = 1000L; /** * <code>rest.host.name</code> */ public static final String REST_HOST_NAME_CONFIG = "rest.host.name"; private static final String REST_HOST_NAME_DOC = "Hostname for the REST API. If this is set, it will only bind to this interface."; /** * <code>rest.port</code> */ public static final String REST_PORT_CONFIG = "rest.port"; private static final String REST_PORT_DOC = "Port for the REST API to listen on."; public static final int REST_PORT_DEFAULT = 8083; /** * <code>rest.advertised.host.name</code> */ public static final String REST_ADVERTISED_HOST_NAME_CONFIG = "rest.advertised.host.name"; private static final String REST_ADVERTISED_HOST_NAME_DOC = "If this is set, this is the hostname that will be given out to other workers to connect to."; /** * <code>rest.advertised.port</code> */ public static final String REST_ADVERTISED_PORT_CONFIG = "rest.advertised.port"; private static final String REST_ADVERTISED_PORT_DOC = "If this is set, this is the port that will be given out to other workers to connect to."; /** * <code>access.control.allow.origin</code> */ public static final String ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG = "access.control.allow.origin"; protected static final String ACCESS_CONTROL_ALLOW_ORIGIN_DOC = "Value to set the Access-Control-Allow-Origin header to for REST API requests." + "To enable cross origin access, set this to the domain of the application that should be permitted" + " to access the API, or '*' to allow access parseFrom any domain. The default value only allows access" + " parseFrom the domain of the REST API."; protected static final String ACCESS_CONTROL_ALLOW_ORIGIN_DEFAULT = ""; /** * <code>access.control.allow.methods</code> */ public static final String ACCESS_CONTROL_ALLOW_METHODS_CONFIG = "access.control.allow.methods"; protected static final String ACCESS_CONTROL_ALLOW_METHODS_DOC = "Sets the methods supported for cross origin requests by setting the Access-Control-Allow-Methods header. " + "The default value of the Access-Control-Allow-Methods header allows cross origin requests for GET, POST and HEAD."; protected static final String ACCESS_CONTROL_ALLOW_METHODS_DEFAULT = ""; /** * <code>group.id</code> */ public static final String GROUP_ID_CONFIG = "group.id"; private static final String GROUP_ID_DOC = "A unique string that identifies the Datalink cluster group this worker belongs to."; /** * <code>session.timeout.ms</code> */ public static final String SESSION_TIMEOUT_MS_CONFIG = "session.timeout.ms"; private static final String SESSION_TIMEOUT_MS_DOC = "The timeout used to detect worker failures. " + "The worker sends periodic heartbeats to indicate its liveness to the Datalink Manager. If no heartbeats are " + "received by the Manager before the expiration of this session timeout, then the Manager will remove the " + "worker parseFrom the group and initiate a rebalance. Note that the value must be in the allowable range as " + "configured in the Manager configuration by <code>group.min.session.timeout.ms</code> " + "and <code>group.max.session.timeout.ms</code>."; /** * <code>heartbeat.interval.ms</code> */ public static final String HEARTBEAT_INTERVAL_MS_CONFIG = "heartbeat.interval.ms"; private static final String HEARTBEAT_INTERVAL_MS_DOC = "The expected time between heartbeats to the group " + "coordinator when using Manager's group management facilities. Heartbeats are used to ensure that the " + "worker's session stays active and to facilitate rebalancing when new members join or leave the group. " + "The value must be set lower than <code>session.timeout.ms</code>, but typically should be set no higher " + "than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances."; /** * <code>rebalance.timeout.ms</code> */ public static final String REBALANCE_TIMEOUT_MS_CONFIG = "rebalance.timeout.ms"; private static final String REBALANCE_TIMEOUT_MS_DOC = "The maximum allowed time for each worker to join the group " + "once a rebalance has begun. This is basically a limit on the amount of time needed for all tasks to " + "flush any pending data and commit positions. If the timeout is exceeded, then the worker will be removed " + "parseFrom the group, which will cause version commit failures."; /** * <code>worker.sync.timeout.ms</code> */ public static final String WORKER_SYNC_TIMEOUT_MS_CONFIG = "worker.sync.timeout.ms"; private static final String WORKER_SYNC_TIMEOUT_MS_DOC = "When the worker is out of sync with other workers and needs" + " to resynchronize configurations, wait up to this amount of time before giving up, leaving the group, and" + " waiting a backoff period before rejoining."; /** * <code>group.unsync.timeout.ms</code> */ public static final String WORKER_UNSYNC_BACKOFF_MS_CONFIG = "worker.unsync.backoff.ms"; private static final String WORKER_UNSYNC_BACKOFF_MS_DOC = "When the worker is out of sync with other workers and " + " fails to catch up within worker.sync.timeout.ms, leave the worker cluster for this long before rejoining."; public static final int WORKER_UNSYNC_BACKOFF_MS_DEFAULT = 5 * 60 * 1000; /** * <code>zookeeper.root</code> */ public static final String ZK_ROOT_CONFIG = "zookeeper.root"; public static final String ZK_ROOT_DOC = "The root node for datalink manager&worker on zookeeper."; public static final String ZK_ROOT_DEFAULT = "/datalink"; /** * <code>zookeeper.servers</code> */ public static final String ZK_SERVER_CONFIG = "zookeeper.servers"; public static final String ZK_SERVER_DOC = "The zookeeper servers used by datalink cluster,This list should be in the form " + "<code>host1:port1,host2:port2,...</code>"; public static final String ZK_SERVER_DEFAULT = "localhost:2181"; /** * <code>zookeeper.session.timeout.ms</code> */ public static final String ZK_SESSION_TIMEOUT_MS_CONFIG = "zookeeper.session.timeout.ms"; public static final String ZK_SESSION_TIMEOUT_MS_DOC = "Session timeout config for zookeeper,the value should be " + "larger than the value of <code>session.timeout.ms</code>."; public static final int ZK_SESSION_TIMEOUT_MS_DEFAULT = 30000; /** * <code>zookeeper.connection.timeout.ms</code> */ public static final String ZK_CONNECTION_TIMEOUT_MS_CONFIG = "zookeeper.connection.timeout.ms"; public static final String ZK_CONNECTION_TIMEOUT_MS_DOC = "Connection timeout config for zookeeper."; public static final int ZK_CONNECTION_TIMEOUT_MS_DEFAULT = 10000; /** * <code>classloader.type</code> */ public static final String CLASSLOADER_TYPE_CONFIG = "classloader.type"; public static final String CLASSLOADER_TYPE_DOC = "The classloader type for taskreaders&taskwriters,there are three" + " options: <Dev> using DevPluginClassLoader for development environment,<Rel> using RelPluginClassLoader " + "for release environment, <Inherit> using AppClassLoader for some special scenes."; public static final String CLASSLOADER_TYPE_DEFAULT = "Rel";//三个选项,Dev-开发版,Rel-release版,Inherit-直接使用框架的Loader /** * <code>ddl.sync</code> */ public static final String DDL_SYNC_CONFIG = "ddl.sync"; public static final boolean DDL_SYNC_DEFAULT = false;//是否同步ddl语句 /** * <code>sync.auto.addcolumn</code> */ public static final String SYNC_AUTO_ADD_COLUMN_CONFIG = "sync.auto.addcolumn"; public static final boolean SYNC_AUTO_ADD_COLUMN_DEFAULT = false;//是否自动加列 /** * <code>worker.bootMode</code> */ public static final String WORKER_BOOT_MODE_CONFIG = "worker.bootMode"; public static final String WORKER_BOOT_MODE_DOC = "The boot mode for datalink worker,two options:standalone and distributed"; public static final String WORKER_BOOT_MODE_DEFAULT = "distributed"; /** * <code>worker.probe.blackList</code> */ public static final String WORKER_PROBE_BLACKLIST_CONFIG = "worker.probe.blackList"; public static final String WORKER_PROBE_BLACKLIST_DOC = "The probe in the blacklist will not start,This list should be" + " in the form <code>probe1,probe2,...</code>"; static { CONFIG = new ConfigDef() .define(BOOTSTRAP_SERVERS_CONFIG, Type.LIST, BOOTSTRAP_SERVERS_DEFAULT, Importance.HIGH, BOOTSTRAP_SERVERS_DOC) .define(TASK_SHUTDOWN_GRACEFUL_TIMEOUT_MS_CONFIG, Type.LONG, TASK_SHUTDOWN_GRACEFUL_TIMEOUT_MS_DEFAULT, Importance.LOW, TASK_SHUTDOWN_GRACEFUL_TIMEOUT_MS_DOC) .define(POSITION_COMMIT_INTERVAL_MS_CONFIG, Type.LONG, POSITION_COMMIT_INTERVAL_MS_DEFAULT, Importance.LOW, POSITION_COMMIT_INTERVAL_MS_DOC) .define(TASK_SYNCSTATUS_COMMIT_INTERVAL_MS_CONFIG, Type.LONG, TASK_SYNCSTATUS_COMMIT_INTERVAL_MS_DEFAULT, Importance.LOW, TASK_SYNCSTATUS_COMMIT_INTERVAL_MS_DOC) .define(REST_HOST_NAME_CONFIG, Type.STRING, null, Importance.LOW, REST_HOST_NAME_DOC) .define(REST_PORT_CONFIG, Type.INT, REST_PORT_DEFAULT, Importance.LOW, REST_PORT_DOC) .define(REST_ADVERTISED_HOST_NAME_CONFIG, Type.STRING, null, Importance.LOW, REST_ADVERTISED_HOST_NAME_DOC) .define(REST_ADVERTISED_PORT_CONFIG, Type.INT, null, Importance.LOW, REST_ADVERTISED_PORT_DOC) .define(ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG, Type.STRING, ACCESS_CONTROL_ALLOW_ORIGIN_DEFAULT, Importance.LOW, ACCESS_CONTROL_ALLOW_ORIGIN_DOC) .define(ACCESS_CONTROL_ALLOW_METHODS_CONFIG, Type.STRING, ACCESS_CONTROL_ALLOW_METHODS_DEFAULT, Importance.LOW, ACCESS_CONTROL_ALLOW_METHODS_DOC) .define(GROUP_ID_CONFIG, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH, GROUP_ID_DOC) .define(SESSION_TIMEOUT_MS_CONFIG, ConfigDef.Type.INT, 10000, ConfigDef.Importance.HIGH, SESSION_TIMEOUT_MS_DOC) .define(REBALANCE_TIMEOUT_MS_CONFIG, ConfigDef.Type.INT, 60000, ConfigDef.Importance.HIGH, REBALANCE_TIMEOUT_MS_DOC) .define(HEARTBEAT_INTERVAL_MS_CONFIG, ConfigDef.Type.INT, 3000, ConfigDef.Importance.HIGH, HEARTBEAT_INTERVAL_MS_DOC) .define(CommonClientConfigs.METADATA_MAX_AGE_CONFIG, ConfigDef.Type.LONG, 5 * 60 * 1000, atLeast(0), ConfigDef.Importance.LOW, CommonClientConfigs.METADATA_MAX_AGE_DOC) .define(CommonClientConfigs.CLIENT_ID_CONFIG, ConfigDef.Type.STRING, "", ConfigDef.Importance.LOW, CommonClientConfigs.CLIENT_ID_DOC) .define(CommonClientConfigs.SEND_BUFFER_CONFIG, ConfigDef.Type.INT, 128 * 1024, atLeast(0), ConfigDef.Importance.MEDIUM, CommonClientConfigs.SEND_BUFFER_DOC) .define(CommonClientConfigs.RECEIVE_BUFFER_CONFIG, ConfigDef.Type.INT, 32 * 1024, atLeast(0), ConfigDef.Importance.MEDIUM, CommonClientConfigs.RECEIVE_BUFFER_DOC) .define(CommonClientConfigs.RECONNECT_BACKOFF_MS_CONFIG, ConfigDef.Type.LONG, 50L, atLeast(0L), ConfigDef.Importance.LOW, CommonClientConfigs.RECONNECT_BACKOFF_MS_DOC) .define(CommonClientConfigs.RETRY_BACKOFF_MS_CONFIG, ConfigDef.Type.LONG, 100L, atLeast(0L), ConfigDef.Importance.LOW, CommonClientConfigs.RETRY_BACKOFF_MS_DOC) .define(CommonClientConfigs.METRICS_SAMPLE_WINDOW_MS_CONFIG, ConfigDef.Type.LONG, 30000, atLeast(0), ConfigDef.Importance.LOW, CommonClientConfigs.METRICS_SAMPLE_WINDOW_MS_DOC) .define(CommonClientConfigs.METRICS_NUM_SAMPLES_CONFIG, ConfigDef.Type.INT, 2, atLeast(1), ConfigDef.Importance.LOW, CommonClientConfigs.METRICS_NUM_SAMPLES_DOC) .define(CommonClientConfigs.METRIC_REPORTER_CLASSES_CONFIG, ConfigDef.Type.LIST, "", ConfigDef.Importance.LOW, CommonClientConfigs.METRIC_REPORTER_CLASSES_DOC) .define(CommonClientConfigs.REQUEST_TIMEOUT_MS_CONFIG, ConfigDef.Type.INT, 40 * 1000, atLeast(0), ConfigDef.Importance.MEDIUM, CommonClientConfigs.REQUEST_TIMEOUT_MS_DOC) /* default is set to be a bit lower than the server default (10 min), to avoid both client and server closing connection at same time */ .define(CommonClientConfigs.CONNECTIONS_MAX_IDLE_MS_CONFIG, ConfigDef.Type.LONG, 9 * 60 * 1000, ConfigDef.Importance.MEDIUM, CommonClientConfigs.CONNECTIONS_MAX_IDLE_MS_DOC) // security support .define(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, ConfigDef.Type.STRING, CommonClientConfigs.DEFAULT_SECURITY_PROTOCOL, ConfigDef.Importance.MEDIUM, CommonClientConfigs.SECURITY_PROTOCOL_DOC) .withClientSslSupport() .withClientSaslSupport() .define(WORKER_SYNC_TIMEOUT_MS_CONFIG, ConfigDef.Type.INT, 3000, ConfigDef.Importance.MEDIUM, WORKER_SYNC_TIMEOUT_MS_DOC) .define(WORKER_UNSYNC_BACKOFF_MS_CONFIG, ConfigDef.Type.INT, WORKER_UNSYNC_BACKOFF_MS_DEFAULT, ConfigDef.Importance.MEDIUM, WORKER_UNSYNC_BACKOFF_MS_DOC) .define(ZK_ROOT_CONFIG, ConfigDef.Type.STRING, ZK_ROOT_DEFAULT, ConfigDef.Importance.HIGH, ZK_ROOT_DOC) .define(ZK_SERVER_CONFIG, ConfigDef.Type.STRING, ZK_SERVER_DEFAULT, ConfigDef.Importance.HIGH, ZK_SERVER_DOC) .define(ZK_SESSION_TIMEOUT_MS_CONFIG, ConfigDef.Type.INT, ZK_SESSION_TIMEOUT_MS_DEFAULT, ConfigDef.Importance.HIGH, ZK_SESSION_TIMEOUT_MS_DOC) .define(ZK_CONNECTION_TIMEOUT_MS_CONFIG, ConfigDef.Type.INT, ZK_CONNECTION_TIMEOUT_MS_DEFAULT, ConfigDef.Importance.HIGH, ZK_CONNECTION_TIMEOUT_MS_DOC) .define(CLASSLOADER_TYPE_CONFIG, Type.STRING, CLASSLOADER_TYPE_DEFAULT, Importance.HIGH, CLASSLOADER_TYPE_DOC) .define(DDL_SYNC_CONFIG, Type.BOOLEAN, DDL_SYNC_DEFAULT, Importance.HIGH, "") .define(SYNC_AUTO_ADD_COLUMN_CONFIG, Type.BOOLEAN, SYNC_AUTO_ADD_COLUMN_DEFAULT, Importance.HIGH, "") .define(WORKER_BOOT_MODE_CONFIG, Type.STRING, WORKER_BOOT_MODE_DEFAULT, Importance.HIGH, WORKER_BOOT_MODE_DOC) .define(WORKER_PROBE_BLACKLIST_CONFIG, Type.STRING, "", Importance.LOW, WORKER_PROBE_BLACKLIST_DOC); } private static WorkerConfig instance; private WorkerConfig(Map<String, String> props, boolean doLog) { super(CONFIG, props, doLog); } public static synchronized WorkerConfig fromProps(Map<String, String> props, boolean doLog) { if (instance == null) { instance = new WorkerConfig(props, doLog); } return instance; } public static WorkerConfig current() { if (instance == null) { throw new DatalinkException("worker config has not yet been initialized."); } return instance; } }
10,829
1,473
/* * Autopsy Forensic Browser * * Copyright 2021 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.datamodel.hosts; import java.awt.event.ActionEvent; import java.util.Collections; import java.util.List; import java.util.logging.Level; import javax.swing.AbstractAction; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JSeparator; import org.openide.util.NbBundle.Messages; import org.openide.util.actions.Presenter; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.datamodel.Host; import org.sleuthkit.datamodel.Person; import org.sleuthkit.datamodel.TskCoreException; /** * * JMenu item to show a menu giving options to associate the given host with an * existing person. */ @Messages({ "AssociatePersonsMenuAction_menuTitle=Associate with Person",}) public class AssociatePersonsMenuAction extends AbstractAction implements Presenter.Popup { private static final Logger logger = Logger.getLogger(AssociatePersonsMenuAction.class.getName()); private final Host host; /** * Main constructor. * * @param host The host. */ public AssociatePersonsMenuAction(Host host) { super(""); this.host = host; } @Override @SuppressWarnings("NoopMethodInAbstractClass") public void actionPerformed(ActionEvent event) { } @Override public JMenuItem getPopupPresenter() { JMenu menu = new JMenu(Bundle.AssociatePersonsMenuAction_menuTitle()); List<Person> existingPersons = Collections.emptyList(); try { existingPersons = Case.getCurrentCaseThrows().getSleuthkitCase().getPersonManager().getPersons(); } catch (NoCurrentCaseException | TskCoreException ex) { logger.log(Level.WARNING, "Error getting persons for case.", ex); } existingPersons.stream() .filter(p -> p != null && p.getName() != null) .sorted((a, b) -> a.getName().compareToIgnoreCase(b.getName())) .map(p -> new JMenuItem(new AssociatePersonAction(this.host, p))) .forEach(menu::add); if (menu.getItemCount() > 0) { menu.add(new JSeparator()); } menu.add(new JMenuItem(new AssociateNewPersonAction(this.host))); return menu; } }
1,090
323
<gh_stars>100-1000 from .ctp_gateway import CtpGateway
21
504
<reponame>steakknife/pcgeos /*********************************************************************** * * Copyright (c) Geoworks 1996. All rights reserved. * GEOWORKS CONFIDENTIAL * * PROJECT: * MODULE: * FILE: npipe.c * * AUTHOR: <NAME>: Sep 10, 1996 * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * dbaumann 9/10/96 Initial version * * DESCRIPTION: * * Functions for sending & receiving Named Pipe data * ***********************************************************************/ #ifndef lint static char *rcsid = "$Id: npipe.c,v 1.1 97/04/18 17:48:38 dbaumann Exp $"; #endif lint #if defined(ISSWAT) # include <config.h> #endif #include <compat/file.h> #include <compat/windows.h> # include "npipe.h" #if defined(ISSWAT) # if !defined(unix) # include "serial.h" /* contains iovec structure definition */ # endif # include "swat.h" #endif #define NPIPE_MAX_INST 100 /* max instances for pipe. */ #define NPIPE_OUT_BUF_SIZE 4096 /* out buffer size */ #define NPIPE_IN_BUF_SIZE 4096 /* in buffer size */ #define NPIPE_CREATE_TIMEOUT 1000 /* default timeout in millisec */ #define NPIPE_MAX_MSG_SIZE 546 /* max length of msg for pipe */ #define NPIPE_DEFAULT_NAME "\\\\.\\pipe\\swatpipe" /* default pipe name */ void NPipeOutputLastError(char *where); #if !defined(ISSWAT) /* stub is the server */ /*********************************************************************** * NPipe_ServerInit *********************************************************************** * * SYNOPSIS: Initialize the Named Pipe Stuff for Server side (stub) * CALLED BY: (stub's wincom dll) * RETURN: TRUE - no errors, FALSE - problems encountered * SIDE EFFECTS: none * * STRATEGY: * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * dbaumann 9/10/96 Initial Revision * ***********************************************************************/ int NPipe_ServerInit(char *name, HANDLE *pipe, LPOVERLAPPED ovlpR, LPOVERLAPPED ovlpW) { BOOL returnCode; char *pipeName; char defaultName[] = NPIPE_DEFAULT_NAME; if ((name == NULL) || (*name == '\0')) { pipeName = defaultName; } else { pipeName = name; } *pipe = CreateNamedPipe(pipeName, PIPE_ACCESS_DUPLEX | WRITE_OWNER | FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_NOWAIT | PIPE_READMODE_MESSAGE, NPIPE_MAX_INST, /* max instances of pipe. */ NPIPE_OUT_BUF_SIZE, /* out buffer size */ NPIPE_IN_BUF_SIZE, /* in buffer size */ NPIPE_CREATE_TIMEOUT, /* timeout in mills */ NULL); /* security stuff */ if (*pipe == INVALID_HANDLE_VALUE) { NPipeOutputLastError("NPipe_ServerInit: " "CreateNamedPipe:"); *pipe = NULL; return FALSE; } ovlpR->Offset = ovlpR->OffsetHigh = 0; ovlpR->hEvent = CreateEvent(0, TRUE, TRUE, 0); ovlpW->Offset = ovlpW->OffsetHigh = 0; ovlpW->hEvent = CreateEvent(0, TRUE, TRUE, 0); return TRUE; } /* End of NPipe_ServerInit. */ /*********************************************************************** * NPipe_ServerConnect *********************************************************************** * * SYNOPSIS: Connect the server to the named pipe after client * initializes the Named Pipe * CALLED BY: (stub's wincom dll), NPipe_ServerTestNConnect * RETURN: TRUE - no errors, FALSE - problems encountered * SIDE EFFECTS: none * * STRATEGY: * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * dbaumann 9/17/96 Initial Revision * ***********************************************************************/ int NPipe_ServerConnect(HANDLE pipe, int *madeConnection, LPOVERLAPPED ovlp) { BOOL returnCode; returnCode = ConnectNamedPipe(pipe, NULL); if (returnCode != TRUE) { switch (GetLastError()) { case ERROR_PIPE_CONNECTED: *madeConnection = TRUE; break; case ERROR_PIPE_LISTENING: *madeConnection = FALSE; break; default: NPipeOutputLastError("NPipe_ServerConnect: " "ConnectNamedPipe:"); *madeConnection = FALSE; return FALSE; break; } } else { *madeConnection = TRUE; } return TRUE; } /* End of NPipe_ServerConnect. */ #else /* else swat which is the client */ /*********************************************************************** * NPipe_ClientInit *********************************************************************** * * SYNOPSIS: Initialize the Named Pipe Stuff * CALLED BY: Rpc_Init * RETURN: TRUE - no errors, FALSE - problems encountered * SIDE EFFECTS: none * * STRATEGY: * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * dbaumann 9/10/96 Initial Revision * ***********************************************************************/ int NPipe_ClientInit(char *name, HANDLE *pipe, LPOVERLAPPED ovlpR, LPOVERLAPPED ovlpW) { DWORD newPipeMode; BOOL returnCode; char * pipeName; char defaultName[] = NPIPE_DEFAULT_NAME; if ((name == NULL) || (*name == '\0')) { pipeName = defaultName; } else { pipeName = name; } *pipe = CreateFile(pipeName, /* pipe name */ GENERIC_READ /* access */ | GENERIC_WRITE, FILE_SHARE_READ /* sharing */ | FILE_SHARE_WRITE, NULL, /* no security */ OPEN_EXISTING, /* how to create */ FILE_FLAG_OVERLAPPED, /* file attributes */ NULL); /* handle of attr */ if (*pipe == INVALID_HANDLE_VALUE) { NPipeOutputLastError("NPipe_ClientInit: CreateFile:"); *pipe = NULL; return FALSE; } newPipeMode = PIPE_READMODE_MESSAGE | PIPE_WAIT; returnCode = SetNamedPipeHandleState(*pipe, &newPipeMode, NULL, NULL); if (returnCode != TRUE) { NPipeOutputLastError("NPipe_ClientInit: " "SetNamedPipeHandleState:"); CloseHandle(*pipe); *pipe = NULL; return FALSE; } ovlpR->Offset = ovlpR->OffsetHigh = 0; ovlpR->hEvent = CreateEvent(0, TRUE, TRUE, 0); ovlpW->Offset = ovlpW->OffsetHigh = 0; ovlpW->hEvent = CreateEvent(0, TRUE, TRUE, 0); return TRUE; } /* End of NPipe_ClientInit. */ #endif /* !defined(ISSWAT) */ /*********************************************************************** * NPipe_Read *********************************************************************** * * SYNOPSIS: Read the next chunk from the Named Pipe * CALLED BY: Rpc_HandleStream * RETURN: number of data bytes in the chunk (-1 means error) * SIDE EFFECTS: if justPeeking then pointer isn't actually moved and * * * STRATEGY: * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * dbaumann 9/10/96 Initial Revision * ***********************************************************************/ int NPipe_Read(HANDLE pipe, void *buf, int bufSize, LPOVERLAPPED ovlp, BOOL bBlock) { DWORD bytesRead; BOOL returnCode; /* * clear last error so that ERROR_IO_PENDING can only be * from the following ReadFile() call */ if (bBlock == FALSE) { SetLastError(0); } returnCode = ReadFile(pipe, buf, bufSize, &bytesRead, ovlp); if (returnCode == FALSE) { switch (GetLastError()) { case ERROR_IO_PENDING: if (bBlock == TRUE) { WaitForSingleObject(ovlp->hEvent, INFINITE); GetOverlappedResult(pipe, ovlp, &bytesRead, FALSE); } else bytesRead = 0; break; case ERROR_MORE_DATA: /* * the message is longer than the buf size ==> problem * rest of message is truncated in the style of netWare * XXXdan-q - will we get the rest later? */ #if 0 if (MessageFlush) { MessageFlush("NPipe_Read: ReadFile: couldn't" " read all\r\n"); } else { fprintf(stderr, "NPipe_Read: ReadFile: couldn't" " read all\r\n"); } #endif return (-1); default: NPipeOutputLastError("NPipe_Read: ReadFile:"); return (-1); } } return bytesRead; } /* End of NPipe_Read */ #if !defined(ISSWAT) /* stub dll only writes buffers */ /*********************************************************************** * NPipe_Write *********************************************************************** * SYNOPSIS: Put a chunk out on the Named Pipe. * CALLED BY: (stub's wincom dll) * RETURN: number of bytes written (-1 means error) * SIDE EFFECTS: none * * STRATEGY: * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * dbaumann 9/10/96 Initial Revision * ***********************************************************************/ int NPipe_Write(HANDLE pipe, void *buf, int bufSize, LPOVERLAPPED ovlp) { BOOL returnCode; DWORD bytesWritten; returnCode = WriteFile(pipe, buf, bufSize, &bytesWritten, ovlp); if (returnCode == FALSE) { switch (GetLastError()) { case ERROR_IO_PENDING: WaitForSingleObject(ovlp->hEvent, INFINITE); GetOverlappedResult(pipe, ovlp, &bytesWritten, FALSE); break; default: NPipeOutputLastError("NPipe_Write: WriteFile:"); return (-1); break; } } if (bytesWritten != bufSize) { return (-1); } return bytesWritten; } /* End of NPipe_Write */ #else /* must be swat then, which writes iov structures */ /*********************************************************************** * NPipe_WriteV *********************************************************************** * SYNOPSIS: Put a chunk out on the Named Pipe. * CALLED BY: Rpc_WriteV * RETURN: number of bytes written (-1 means error) * SIDE EFFECTS: none * * STRATEGY: * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * dbaumann 9/10/96 Initial Revision * ***********************************************************************/ int NPipe_WriteV(HANDLE pipe, struct iovec *iov, int iov_len, LPOVERLAPPED ovlp) { char msgBuf[NPIPE_MAX_MSG_SIZE]; char *pMsgBuf = msgBuf; int i, size; BOOL returnCode; DWORD bytesWritten; DWORD numWrite; for (i = 0, size = 0; i < iov_len; i++) { if (size + iov[i].iov_len > NPIPE_MAX_MSG_SIZE) { return (-1); } bcopy(iov[i].iov_base, pMsgBuf, iov[i].iov_len); pMsgBuf += iov[i].iov_len; size += iov[i].iov_len; } returnCode = WriteFile(pipe, msgBuf, size, &bytesWritten, ovlp); if (returnCode == FALSE) { switch (GetLastError()) { case ERROR_IO_PENDING: GetOverlappedResult(pipe, ovlp, &numWrite, TRUE); bytesWritten = numWrite; break; default: NPipeOutputLastError("NPipe_WriteV: WriteFile:"); return (-1); break; } } if (bytesWritten != size) { if (win32dbg == TRUE) { if (MessageFlush) { MessageFlush("NPipe_WriteV: WriteFile: couldn't" " write all: %d of %d\r\n", bytesWritten, size); } else { fprintf(stderr, "NPipe_WriteV: WriteFile: couldn't" " write all %d of %d\r\n", bytesWritten, size); } } /* * XXXdan * only reports a problem if no data is sent, otherwise I believe * the whole message is sent, it just isn't reporting back to us * the right amt. */ if (bytesWritten <= 0) { return (-1); } } return size; } /* End of NPipe_WriteV */ #endif /* !defined(ISSWAT) */ /*********************************************************************** * NPipe_Check *********************************************************************** * SYNOPSIS: Checks if data is waiting on Named Pipe * CALLED BY: Rpc_Wait * RETURN: number of bytes waiting (-1 means error) * SIDE EFFECTS: none * * STRATEGY: * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * dbaumann 9/10/96 Initial Revision * ***********************************************************************/ int NPipe_Check(HANDLE pipe, LPOVERLAPPED ovlp) { DWORD bytesRead; BOOL returnCode; DWORD dataLeftInMessage; DWORD dataAvail = 0; /* determine data in the next message, note - not all messages */ returnCode = PeekNamedPipe(pipe, NULL, 0, &bytesRead, &dataAvail, &dataLeftInMessage); if (returnCode != TRUE) { if (GetLastError() != ERROR_MORE_DATA) { /* * don't display if handle is invalid, could just be detached */ if (GetLastError() != ERROR_INVALID_HANDLE) { NPipeOutputLastError("NPipe_Check: PeekNamedPipe:"); } return (-1); } } return dataAvail; } /* End of NPipe_Check */ #if !defined(ISSWAT) /*********************************************************************** * NPipe_ServerExit *********************************************************************** * SYNOPSIS: Close the server's Named Pipe. * CALLED BY: ?? * RETURN: none * SIDE EFFECTS: none * * STRATEGY: * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * dbaumann 9/10/96 Initial Revision * ***********************************************************************/ void NPipe_ServerExit(HANDLE *pipe, LPOVERLAPPED ovlpR, LPOVERLAPPED ovlpW) { BOOL returnCode; returnCode = DisconnectNamedPipe(*pipe); if (returnCode != TRUE) { NPipeOutputLastError("NPipe_ServerExit: DisconnectNamedPipe:"); return; } returnCode = CloseHandle(*pipe); if (returnCode != TRUE) { /* * don't do anything special yet, since stub probably doesn't care */ NPipeOutputLastError("NPipe_ServerExit: CloseHandle:"); return; } *pipe = NULL; CloseHandle(ovlpR->hEvent); CloseHandle(ovlpW->hEvent); return; } /* End of NPipe_ServerExit */ #else /* else case: swat is the client */ /*********************************************************************** * NPipe_ClientExit *********************************************************************** * SYNOPSIS: Close the client's Named Pipe. * CALLED BY: (EXTERNAL - set up using atexit function) * RETURN: none * SIDE EFFECTS: none * * STRATEGY: * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * dbaumann 9/10/96 Initial Revision * ***********************************************************************/ void NPipe_ClientExit(HANDLE *pipe, LPOVERLAPPED ovlpR, LPOVERLAPPED ovlpW) { BOOL returnCode; returnCode = CloseHandle(*pipe); if (returnCode != TRUE) { NPipeOutputLastError("NPipe_ClientExit: CloseHandle:"); return; } *pipe = NULL; CloseHandle(ovlpR->hEvent); CloseHandle(ovlpW->hEvent); return; } /* End of NPipe_ClientExit */ #endif /* !defined(ISSWAT) */ /*********************************************************************** * NPipeOutputLastError *********************************************************************** * * SYNOPSIS: Displays error from GetLastError() * CALLED BY: (all INTERNAL functions) * RETURN: none * SIDE EFFECTS: none * * STRATEGY: * * REVISION HISTORY: * Name Date Description * ---- ---- ----------- * dbaumann 9/11/96 Initial Revision * ***********************************************************************/ void NPipeOutputLastError(char *where) { LPVOID lpMsgBuf; char denied[] = "<couldn't get last error>"; BOOL returnCode = FALSE; #if defined(ISSWAT) return; #endif returnCode = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL); if (returnCode == FALSE) { lpMsgBuf = denied; } #if !defined(ISSWAT) /* must be stub */ /* * stub can't printf or anything, so make a message box */ { MessageBox(NULL, lpMsgBuf, where, MB_OK); } #else /* * gotta be swat */ # if 0 if (MessageFlush) { MessageFlush("%s %s", where, lpMsgBuf); } else { fprintf(stderr, "\r\n%s %s\r\n", where, lpMsgBuf); } # endif #endif return; } /* End of NPipeOutputLastError. */
6,452
3,294
<reponame>BaruaSourav/docs<gh_stars>1000+ // System.Web.Services.Description.PortCollection.Insert // System.Web.Services.Description.PortCollection.IndexOf // System.Web.Services.Description.PortCollection.CopyTo /* The following sample reads the contents of a file 'MathService.wsdl' into a 'ServiceDescription' instance. It gets the collection of Service instances from 'ServiceDescription'. It instantiates 'PortCollection' for each service in the collection. 'CopyTo' is called to copy the contents into an array. Calls 'IndexOf' for a given port. 'Insert' method is called to insert a new port in the collection. */ #using <System.Xml.dll> #using <System.Web.Services.dll> #using <System.dll> using namespace System; using namespace System::Web::Services::Description; using namespace System::Xml; int main() { try { Service^ myService; PortCollection^ myPortCollection; ServiceDescription^ myServiceDescription = ServiceDescription::Read( "MathServiceCopyTo_cs.wsdl" ); Console::WriteLine( "Total Number of Services :{0}", myServiceDescription->Services->Count ); for ( int i = 0; i < myServiceDescription->Services->Count; ++i ) { myService = myServiceDescription->Services[ i ]; Console::WriteLine( "Name : {0}", myService->Name ); // <Snippet1> // <Snippet2> // <Snippet3> myPortCollection = myService->Ports; // Create an array of Port objects. Console::WriteLine( "\nPort collection :" ); array<Port^>^myPortArray = gcnew array<Port^>(myService->Ports->Count); myPortCollection->CopyTo( myPortArray, 0 ); for ( int i1 = 0; i1 < myService->Ports->Count; ++i1 ) { Console::WriteLine( "Port[{0}] : {1}", i1, myPortArray[ i1 ]->Name ); } // </Snippet3> Port^ myIndexPort = myPortCollection[ 0 ]; Console::WriteLine( "\n\nThe index of port '{0}' is : {1}", myIndexPort->Name, myPortCollection->IndexOf( myIndexPort ) ); // </Snippet2> Port^ myPortTestInsert = myPortCollection[ 0 ]; myPortCollection->Remove( myPortTestInsert ); myPortCollection->Insert( 0, myPortTestInsert ); Console::WriteLine( "\n\nTotal Number of Ports after inserting a new port '{0}' is : {1}", myPortTestInsert->Name, myService->Ports->Count ); for ( int i1 = 0; i1 < myService->Ports->Count; ++i1 ) { Console::WriteLine( "Port[{0}] : {1}", i1, myPortArray[ i1 ]->Name ); } myServiceDescription->Write( "MathServiceCopyToNew_cs.wsdl" ); // </Snippet1> } } catch ( Exception^ ex ) { Console::WriteLine( "Exception:{0}", ex->Message ); } }
1,091
66,985
/* * Copyright 2012-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot; import java.util.function.Supplier; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.core.env.Environment; import org.springframework.util.Assert; /** * A simple object registry that is available during startup and {@link Environment} * post-processing up to the point that the {@link ApplicationContext} is prepared. * <p> * Can be used to register instances that may be expensive to create, or need to be shared * before the {@link ApplicationContext} is available. * <p> * The registry uses {@link Class} as a key, meaning that only a single instance of a * given type can be stored. * <p> * The {@link #addCloseListener(ApplicationListener)} method can be used to add a listener * that can perform actions when {@link BootstrapContext} has been closed and the * {@link ApplicationContext} is fully prepared. For example, an instance may choose to * register itself as a regular Spring bean so that it is available for the application to * use. * * @author <NAME> * @since 2.4.0 * @see BootstrapContext * @see ConfigurableBootstrapContext */ public interface BootstrapRegistry { /** * Register a specific type with the registry. If the specified type has already been * registered and has not been obtained as a {@link Scope#SINGLETON singleton}, it * will be replaced. * @param <T> the instance type * @param type the instance type * @param instanceSupplier the instance supplier */ <T> void register(Class<T> type, InstanceSupplier<T> instanceSupplier); /** * Register a specific type with the registry if one is not already present. * @param <T> the instance type * @param type the instance type * @param instanceSupplier the instance supplier */ <T> void registerIfAbsent(Class<T> type, InstanceSupplier<T> instanceSupplier); /** * Return if a registration exists for the given type. * @param <T> the instance type * @param type the instance type * @return {@code true} if the type has already been registered */ <T> boolean isRegistered(Class<T> type); /** * Return any existing {@link InstanceSupplier} for the given type. * @param <T> the instance type * @param type the instance type * @return the registered {@link InstanceSupplier} or {@code null} */ <T> InstanceSupplier<T> getRegisteredInstanceSupplier(Class<T> type); /** * Add an {@link ApplicationListener} that will be called with a * {@link BootstrapContextClosedEvent} when the {@link BootstrapContext} is closed and * the {@link ApplicationContext} has been prepared. * @param listener the listener to add */ void addCloseListener(ApplicationListener<BootstrapContextClosedEvent> listener); /** * Supplier used to provide the actual instance when needed. * * @param <T> the instance type * @see Scope */ @FunctionalInterface interface InstanceSupplier<T> { /** * Factory method used to create the instance when needed. * @param context the {@link BootstrapContext} which may be used to obtain other * bootstrap instances. * @return the instance */ T get(BootstrapContext context); /** * Return the scope of the supplied instance. * @return the scope * @since 2.4.2 */ default Scope getScope() { return Scope.SINGLETON; } /** * Return a new {@link InstanceSupplier} with an updated {@link Scope}. * @param scope the new scope * @return a new {@link InstanceSupplier} instance with the new scope * @since 2.4.2 */ default InstanceSupplier<T> withScope(Scope scope) { Assert.notNull(scope, "Scope must not be null"); InstanceSupplier<T> parent = this; return new InstanceSupplier<T>() { @Override public T get(BootstrapContext context) { return parent.get(context); } @Override public Scope getScope() { return scope; } }; } /** * Factory method that can be used to create an {@link InstanceSupplier} for a * given instance. * @param <T> the instance type * @param instance the instance * @return a new {@link InstanceSupplier} */ static <T> InstanceSupplier<T> of(T instance) { return (registry) -> instance; } /** * Factory method that can be used to create an {@link InstanceSupplier} from a * {@link Supplier}. * @param <T> the instance type * @param supplier the supplier that will provide the instance * @return a new {@link InstanceSupplier} */ static <T> InstanceSupplier<T> from(Supplier<T> supplier) { return (registry) -> (supplier != null) ? supplier.get() : null; } } /** * The scope of a instance. * @since 2.4.2 */ enum Scope { /** * A singleton instance. The {@link InstanceSupplier} will be called only once and * the same instance will be returned each time. */ SINGLETON, /** * A prototype instance. The {@link InstanceSupplier} will be called whenever an * instance is needed. */ PROTOTYPE } }
1,720
5,422
#pragma once #include <pqrs/hid.hpp> namespace krbn { namespace hid { namespace product_id { constexpr pqrs::hid::product_id::value_t karabiner_virtual_hid_keyboard(0x27db); constexpr pqrs::hid::product_id::value_t karabiner_virtual_hid_pointing(0x27da); } // namespace product_id } // namespace hid } // namespace krbn
125
3,039
<filename>MiaowShow/MiaowShow/Classes/ShowTime/H264Encoder/ALinH264Encoder.h // // ALinH264Encoder.h // MiaowShow // // Created by ALin on 16/7/4. // Copyright © 2016年 ALin. All rights reserved. // #import <Foundation/Foundation.h> #import <VideoToolbox/VideoToolbox.h> //@protocol ALinH264EncoderDelegate <NSObject> // //- (void)gotSps:(NSData*)sps pps:(NSData*)pps; //- (void)gotEncodedData:(NSData*)data isKeyFrame:(BOOL)isKeyFrame; // //@end @interface ALinH264Encoder : NSObject // 初始化基本配置 - (void) initWithConfiguration; - (void) initEncode:(int)width height:(int)height; - (void) encode:(CMSampleBufferRef)sampleBuffer; //@property (weak, nonatomic) id<ALinH264EncoderDelegate> delegate; @end
291