answer
stringlengths
15
1.25M
// Peloton // sorter_proxy.h // Identification: src/include/codegen/sorter_proxy.h #pragma once #include "codegen/codegen.h" namespace peloton { namespace codegen { class SorterProxy { public: // Get the LLVM type for peloton::codegen::utils::Sorter static llvm::Type *GetType(CodeGen &codegen); // The proxy for codegen::utils::Sorter::Init() struct _Init { static const std::string &GetFunctionName(); static llvm::Function *GetFunction(CodeGen &codegen); }; // The proxy for codegen::utils::Sorter::StoreInputTuple() struct _StoreInputTuple { static const std::string &GetFunctionName(); static llvm::Function *GetFunction(CodeGen &codegen); }; // The proxy for codegen::utils::Sorter::Sort() struct _Sort { static const std::string &GetFunctionName(); static llvm::Function *GetFunction(CodeGen &codegen); }; // The proxy for codegen::utils::Sorter::Destroy() struct _Destroy { static const std::string &GetFunctionName(); static llvm::Function *GetFunction(CodeGen &codegen); }; }; } // namespace codegen } // namespace peloton
package de.darwinspl.feature.graphical.editor.actions; import org.eclipse.gef.Request; import org.eclipse.gef.ui.actions.SelectionAction; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPropertyListener; import org.eclipse.ui.IWorkbenchPart; import de.darwinspl.feature.graphical.base.editparts.DwAttributeEditPart; import de.darwinspl.feature.graphical.base.editparts.DwEnumEditPart; import de.darwinspl.feature.graphical.base.editparts.<API key>; import de.darwinspl.feature.graphical.base.editparts.DwFeatureEditPart; import de.darwinspl.feature.graphical.base.editparts.DwGroupEditPart; import de.darwinspl.feature.graphical.base.model.DwFeatureWrapped; import de.darwinspl.feature.graphical.base.model.DwGroupWrapped; import de.darwinspl.feature.graphical.editor.dialogs.DwValidityDialog; import de.darwinspl.feature.graphical.editor.editparts.<API key>; import eu.hyvar.evolution.HyTemporalElement; import eu.hyvar.feature.HyFeatureAttribute; import eu.hyvar.feature.HyVersion; public class <API key> extends SelectionAction{ public static final String <API key> = "<API key>"; public static final String <API key> = "<API key>"; Request request; public <API key>(IWorkbenchPart part){ super(part); setId(<API key>); setText("Change Element Validity"); request = new Request(<API key>); } @Override public void run(){ Shell shell = this.getWorkbenchPart().getSite().getShell(); StructuredSelection selection = (StructuredSelection)this.getSelection(); Object selectedElement = selection.getFirstElement(); HyTemporalElement model = null; if(selectedElement instanceof DwFeatureEditPart){ DwFeatureEditPart editPart = (DwFeatureEditPart)selectedElement; model = (HyTemporalElement)((DwFeatureWrapped)editPart.getModel()).<API key>(); } if(selectedElement instanceof DwGroupEditPart){ DwGroupEditPart editPart = (DwGroupEditPart)selectedElement; model = (HyTemporalElement)((DwGroupWrapped)editPart.getModel()).<API key>(); } if(selectedElement instanceof <API key>){ <API key> editPart = (<API key>)selectedElement; model = (HyTemporalElement)((HyVersion)editPart.getModel()); } if(selectedElement instanceof DwAttributeEditPart){ DwAttributeEditPart editPart = (DwAttributeEditPart)selectedElement; model = (HyTemporalElement)((HyFeatureAttribute)editPart.getModel()); } if(selectedElement instanceof DwEnumEditPart){ DwEnumEditPart editPart = (DwEnumEditPart)selectedElement; model = (HyTemporalElement)editPart.getModel(); } if(selectedElement instanceof <API key>){ <API key> editPart = (<API key>)selectedElement; model = (HyTemporalElement)editPart.getModel(); } DwValidityDialog dialog = new DwValidityDialog(shell); dialog.setElement(model); dialog.open(); } @Override protected boolean calculateEnabled() { if(getSelectedObjects().isEmpty()) return false; for(Object selectedObject : getSelectedObjects()){ if(!((selectedObject instanceof DwFeatureEditPart) || (selectedObject instanceof DwGroupEditPart) || (selectedObject instanceof DwAttributeEditPart) || (selectedObject instanceof <API key>) || (selectedObject instanceof DwEnumEditPart) || (selectedObject instanceof <API key>))){ return false; } } return true; } }
package com.ctrip.zeus.model.model; import java.util.ArrayList; import java.util.List; public class DrTraffic { private Group m_group; private List<Destination> m_destinations = new ArrayList<Destination>(); public DrTraffic() { } protected boolean equals(Object o1, Object o2) { if (o1 == null) { return o2 == null; } else if (o2 == null) { return false; } else { return o1.equals(o2); } } public DrTraffic addDestination(Destination destination) { m_destinations.add(destination); return this; } @Override public boolean equals(Object obj) { if (obj instanceof DrTraffic) { DrTraffic _o = (DrTraffic) obj; if (!equals(m_group, _o.getGroup())) { return false; } if (!equals(m_destinations, _o.getDestinations())) { return false; } return true; } return false; } public List<Destination> getDestinations() { return m_destinations; } public Group getGroup() { return m_group; } @Override public int hashCode() { int hash = 0; hash = hash * 31 + (m_group == null ? 0 : m_group.hashCode()); hash = hash * 31 + (m_destinations == null ? 0 : m_destinations.hashCode()); return hash; } public DrTraffic setGroup(Group group) { m_group = group; return this; } }
package org.uberfire.annotations.processors; import java.util.Map; public class PartInformation { private final String partName; private Map<String, String> parameters; public PartInformation( String partName) { this.partName = partName; } public PartInformation( String partName, Map<String, String> parameters ) { this.partName = partName; if ( parameters==null||parameters.isEmpty() ) { this.parameters = null; } else { this.parameters = parameters; } } @SuppressWarnings("unused") public String getPartName() { return partName; } public Map<String, String> getParameters() { return parameters; } }
# encoding: utf-8 # This file is a part of Redmin Agile (redmine_agile) plugin, # Agile board plugin for redmine # redmine_agile is free software: you can redistribute it and/or modify # (at your option) any later version. # redmine_agile is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the require File.expand_path('../../test_helper', __FILE__) class <API key> < ActionController::TestCase fixtures :projects, :users, :roles, :members, :member_roles, :issues, :issue_statuses, :versions, :trackers, :projects_trackers, :issue_categories, :enabled_modules, :enumerations, :attachments, :workflows, :custom_fields, :custom_values, :<API key>, :<API key>, :time_entries, :journals, :journal_details, :queries def setup @project_1 = Project.find(1) @project_2 = Project.find(5) EnabledModule.create(:project => @project_1, :name => 'agile') EnabledModule.create(:project => @project_2, :name => 'agile') @request.session[:user_id] = 1 end def test_get_index get :index, :project_id => @project_1 assert_response :success assert_template :index end def test_get_load xhr :get, :load, :version_type => "backlog", :version_id => "3", :project_id => "ecookbook" assert_response :success end def <API key> xhr :get, :autocomplete, :project_id => "ecookbook", :q =>" assert_response :success assert_match "Can&#x27;t print recipes", @response.body end def <API key> xhr :get, :autocomplete, :project_id => "ecookbook", :q =>"error" assert_response :success assert_match "Error 281", @response.body end end
name: PIP request about: Submit a PIP (Pulsar Improvement Proposal) title: '' labels: PIP assignees: '' <! Instructions for creating a PIP using this issue template: 1. The author(s) of the proposal will create a GitHub issue ticket using this template. (Optionally, it can be helpful to send a note discussing the proposal to dev@pulsar.apache.org mailing list before submitting this GitHub issue. This discussion can help developers gauge interest in the proposed changes before formalizing the proposal.) 2. The author(s) will send a note to the dev@pulsar.apache.org mailing list to start the discussion, using subject prefix `[PIP] xxx`. To determine the appropriate PIP number `xxx`, inspect the mailing list (https://lists.apache.org/list.html?dev@pulsar.apache.org) for the most recent PIP. Add 1 to that PIP's number to get your PIP's number. 3. Based on the discussion and feedback, some changes might be applied by the author(s) to the text of the proposal. 4. Once some consensus is reached, there will be a vote to formally approve the proposal. The vote will be held on the dev@pulsar.apache.org mailing list. Everyone is welcome to vote on the proposal, though it will considered to be binding only the vote of PMC members. It will be required to have a lazy majority of at least 3 binding +1s votes. The vote should stay open for at least 48 hours. 5. When the vote is closed, if the outcome is positive, the state of the proposal is updated and the Pull Requests associated with this proposal can start to get merged into the master branch. ## Motivation Explain why this change is needed, what benefits it would bring to Apache Pulsar and what problem it's trying to solve. ## Goal Define the scope of this proposal. Given the motivation stated above, what are the problems that this proposal is addressing and what other items will be considering out of scope, perhaps to be left to a different PIP. ## API Changes Illustrate all the proposed changes to the API or wire protocol, with examples of all the newly added classes/methods, including Javadoc. ## Implementation This should be a detailed description of all the changes that are expected to be made. It should be detailed enough that any developer that is familiar with Pulsar internals would be able to understand all the parts of the code changes for this proposal. This should also serve as documentation for any person that is trying to understand or debug the behavior of a certain feature. ## Reject Alternatives If there are alternatives that were already considered by the authors or, after the discussion, by the community, and were rejected, please list them here along with the reason why they were rejected.
package lk.ac.cmb.ucsc.mcs.ewa.service; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import lk.ac.cmb.ucsc.mcs.ewa.dto.Credentials; import lk.ac.cmb.ucsc.mcs.ewa.dto.PatientChannel; import lk.ac.cmb.ucsc.mcs.ewa.entity.Patient; import lk.ac.cmb.ucsc.mcs.ewa.entity.PatientHistory; import lk.ac.cmb.ucsc.mcs.ewa.exception.<API key>; import lk.ac.cmb.ucsc.mcs.ewa.exception.<API key>; import lk.ac.cmb.ucsc.mcs.ewa.exception.<API key>; @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public interface PatientService { @POST @Path("/patients/authenticate") Response authenticate(Credentials credentials); @GET @Path("/patients/{patientId}") Patient findPatient(@PathParam("patientId") long patientId); @GET @Path("/patients/firstname/{name}") List<Patient> <API key>(@PathParam("name") String firstName); @GET @Path("/patients/lastname/{name}") List<Patient> <API key>(@PathParam("name") String lastName); @GET @Path("/patients/name/{firstName}/{lastName}") List<Patient> <API key>(@PathParam("firstName") String firstName, @PathParam("lastName") String lastName); @POST @Path("/patients/history") PatientHistory <API key>(PatientChannel patientChannel) throws <API key>, <API key>; @GET @Path("/patients/history/{patientId}") List<PatientHistory> findPatientHistory(@PathParam("patientId") long patientId); @GET @Path("/patients/history/{patientId}/{channelId}") PatientHistory findPatientHistory(@PathParam("patientId") long patientId, @PathParam("channelId") long channelId); @PUT @Path("/patients/history/{patientId}/{channelId}/comments") PatientHistory <API key>(@PathParam("patientId") long patientId, @PathParam("channelId") long channelId, String comments) throws <API key>; }
package android.app; import com.robomorphine.strictmode.DataProxy; import android.app.ActivityManager.MemoryInfo; import android.app.ActivityManager.<API key>; import android.app.ActivityManager.RecentTaskInfo; import android.app.ActivityManager.<API key>; import android.app.<API key>.CrashInfo; import android.content.ComponentName; import android.content.IIntentReceiver; import android.content.IIntentSender; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentSender; import android.content.pm.ApplicationInfo; import android.content.pm.ConfigurationInfo; import android.content.pm.<API key>; import android.content.res.Configuration; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.os.<API key>; import android.os.RemoteException; import android.os.StrictMode.ViolationInfo; import java.util.List; @SuppressWarnings("all") public class <API key> implements IActivityManager { private final IActivityManager mTo; private final DataProxy<ViolationInfo> mViolationProxy; public <API key>(IActivityManager manager, DataProxy<ViolationInfo> violationProxy) { mTo = manager; mViolationProxy = violationProxy; } public void <API key>(IBinder binder, int mask, ViolationInfo info) throws RemoteException { mTo.<API key>(binder, mask, mViolationProxy.handle(info)); } public void activityDestroyed(IBinder arg0) throws RemoteException { mTo.activityDestroyed(arg0); } public void activityIdle(IBinder arg0, Configuration arg1) throws RemoteException { mTo.activityIdle(arg0, arg1); } public void activityPaused(IBinder arg0, Bundle arg1) throws RemoteException { mTo.activityPaused(arg0, arg1); } public void activityStopped(IBinder arg0, Bitmap arg1, CharSequence arg2) throws RemoteException { mTo.activityStopped(arg0, arg1, arg2); } public IBinder asBinder() { return mTo.asBinder(); } public void attachApplication(IApplicationThread arg0) throws RemoteException { mTo.attachApplication(arg0); } public void backupAgentCreated(String arg0, IBinder arg1) throws RemoteException { mTo.backupAgentCreated(arg0, arg1); } public boolean bindBackupAgent(ApplicationInfo arg0, int arg1) throws RemoteException { return mTo.bindBackupAgent(arg0, arg1); } public int bindService(IApplicationThread arg0, IBinder arg1, Intent arg2, String arg3, IServiceConnection arg4, int arg5) throws RemoteException { return mTo.bindService(arg0, arg1, arg2, arg3, arg4, arg5); } public int broadcastIntent(IApplicationThread arg0, Intent arg1, String arg2, IIntentReceiver arg3, int arg4, String arg5, Bundle arg6, String arg7, boolean arg8, boolean arg9) throws RemoteException { return mTo.broadcastIntent(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } public void cancelIntentSender(IIntentSender arg0) throws RemoteException { mTo.cancelIntentSender(arg0); } public int checkPermission(String arg0, int arg1, int arg2) throws RemoteException { return mTo.checkPermission(arg0, arg1, arg2); } public int checkUriPermission(Uri arg0, int arg1, int arg2, int arg3) throws RemoteException { return mTo.checkUriPermission(arg0, arg1, arg2, arg3); } public boolean <API key>(String arg0, <API key> arg1) throws RemoteException { return mTo.<API key>(arg0, arg1); } public void closeSystemDialogs(String arg0) throws RemoteException { mTo.closeSystemDialogs(arg0); } public void crashApplication(int arg0, int arg1, String arg2, String arg3) throws RemoteException { mTo.crashApplication(arg0, arg1, arg2, arg3); } public void enterSafeMode() throws RemoteException { mTo.enterSafeMode(); } public boolean finishActivity(IBinder arg0, int arg1, Intent arg2) throws RemoteException { return mTo.finishActivity(arg0, arg1, arg2); } public void <API key>() throws RemoteException { mTo.<API key>(); } public void <API key>(IApplicationThread arg0, int arg1, Bundle arg2) throws RemoteException { mTo.<API key>(arg0, arg1, arg2); } public void <API key>(IBinder arg0, ComponentName arg1) throws RemoteException { mTo.<API key>(arg0, arg1); } public void finishReceiver(IBinder arg0, int arg1, String arg2, Bundle arg3, boolean arg4) throws RemoteException { mTo.finishReceiver(arg0, arg1, arg2, arg3, arg4); } public void finishSubActivity(IBinder arg0, String arg1, int arg2) throws RemoteException { mTo.finishSubActivity(arg0, arg1, arg2); } public void forceStopPackage(String arg0) throws RemoteException { mTo.forceStopPackage(arg0); } public ComponentName <API key>(IBinder arg0) throws RemoteException { return mTo.<API key>(arg0); } public ComponentName getCallingActivity(IBinder arg0) throws RemoteException { return mTo.getCallingActivity(arg0); } public String getCallingPackage(IBinder arg0) throws RemoteException { return mTo.getCallingPackage(arg0); } public Configuration getConfiguration() throws RemoteException { return mTo.getConfiguration(); } public <API key> getContentProvider(IApplicationThread arg0, String arg1) throws RemoteException { return mTo.getContentProvider(arg0, arg1); } public ConfigurationInfo <API key>() throws RemoteException { return mTo.<API key>(); } public IIntentSender getIntentSender(int arg0, String arg1, IBinder arg2, String arg3, int arg4, Intent arg5, String arg6, int arg7) throws RemoteException { return mTo.getIntentSender(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } public void getMemoryInfo(MemoryInfo arg0) throws RemoteException { mTo.getMemoryInfo(arg0); } public String <API key>(IIntentSender arg0) throws RemoteException { return mTo.<API key>(arg0); } public String getPackageForToken(IBinder arg0) throws RemoteException { return mTo.getPackageForToken(arg0); } public int getProcessLimit() throws RemoteException { return mTo.getProcessLimit(); } public android.os.Debug.MemoryInfo[] <API key>(int[] arg0) throws RemoteException { return mTo.<API key>(arg0); } public List<<API key>> <API key>() throws RemoteException { return mTo.<API key>(); } public String getProviderMimeType(Uri arg0) throws RemoteException { return mTo.getProviderMimeType(arg0); } public List<RecentTaskInfo> getRecentTasks(int arg0, int arg1) throws RemoteException { return mTo.getRecentTasks(arg0, arg1); } public int <API key>(IBinder arg0) throws RemoteException { return mTo.<API key>(arg0); } public List<<API key>> <API key>() throws RemoteException { return mTo.<API key>(); } public List<ApplicationInfo> <API key>() throws RemoteException { return mTo.<API key>(); } public PendingIntent <API key>(ComponentName arg0) throws RemoteException { return mTo.<API key>(arg0); } public List getServices(int arg0, int arg1) throws RemoteException { return mTo.getServices(arg0, arg1); } public int getTaskForActivity(IBinder arg0, boolean arg1) throws RemoteException { return mTo.getTaskForActivity(arg0, arg1); } public List getTasks(int arg0, int arg1, IThumbnailReceiver arg2) throws RemoteException { return mTo.getTasks(arg0, arg1, arg2); } public void goingToSleep() throws RemoteException { mTo.goingToSleep(); } public void grantUriPermission(IApplicationThread arg0, String arg1, Uri arg2, int arg3) throws RemoteException { mTo.grantUriPermission(arg0, arg1, arg2, arg3); } public void <API key>(IBinder arg0, int arg1, String arg2, Uri arg3, int arg4) throws RemoteException { mTo.<API key>(arg0, arg1, arg2, arg3, arg4); } public void <API key>(IBinder arg0, CrashInfo arg1) throws RemoteException { mTo.<API key>(arg0, arg1); } public boolean <API key>(IBinder arg0, String arg1, CrashInfo arg2) throws RemoteException { return mTo.<API key>(arg0, arg1, arg2); } public boolean isUserAMonkey() throws RemoteException { return mTo.isUserAMonkey(); } public void <API key>(String arg0, int arg1) throws RemoteException { mTo.<API key>(arg0, arg1); } public void <API key>(String arg0, int arg1) throws RemoteException { mTo.<API key>(arg0, arg1); } public void <API key>(String arg0) throws RemoteException { mTo.<API key>(arg0); } public boolean killPids(int[] arg0, String arg1) throws RemoteException { return mTo.killPids(arg0, arg1); } public boolean <API key>(IBinder arg0, boolean arg1) throws RemoteException { return mTo.<API key>(arg0, arg1); } public void moveTaskBackwards(int arg0) throws RemoteException { mTo.moveTaskBackwards(arg0); } public void moveTaskToBack(int arg0) throws RemoteException { mTo.moveTaskToBack(arg0); } public void moveTaskToFront(int arg0) throws RemoteException { mTo.moveTaskToFront(arg0); } public IBinder <API key>(String arg0) throws RemoteException { return mTo.<API key>(arg0); } public void noteWakeupAlarm(IIntentSender arg0) throws RemoteException { mTo.noteWakeupAlarm(arg0); } public <API key> openContentUri(Uri arg0) throws RemoteException { return mTo.openContentUri(arg0); } public void <API key>(IBinder arg0, String arg1, int arg2, int arg3) throws RemoteException { mTo.<API key>(arg0, arg1, arg2, arg3); } public IBinder peekService(Intent arg0, String arg1) throws RemoteException { return mTo.peekService(arg0, arg1); } public boolean profileControl(String arg0, boolean arg1, String arg2, <API key> arg3) throws RemoteException { return mTo.profileControl(arg0, arg1, arg2, arg3); } public void <API key>(IApplicationThread arg0, List<<API key>> arg1) throws RemoteException { mTo.<API key>(arg0, arg1); } public void publishService(IBinder arg0, Intent arg1, IBinder arg2) throws RemoteException { mTo.publishService(arg0, arg1, arg2); } public void <API key>(IActivityWatcher arg0) throws RemoteException { mTo.<API key>(arg0); } public Intent registerReceiver(IApplicationThread arg0, IIntentReceiver arg1, IntentFilter arg2, String arg3) throws RemoteException { return mTo.registerReceiver(arg0, arg1, arg2, arg3); } public void <API key>(IApplicationThread arg0, String arg1) throws RemoteException { mTo.<API key>(arg0, arg1); } public void reportThumbnail(IBinder arg0, Bitmap arg1, CharSequence arg2) throws RemoteException { mTo.reportThumbnail(arg0, arg1, arg2); } public void resumeAppSwitches() throws RemoteException { mTo.resumeAppSwitches(); } public void revokeUriPermission(IApplicationThread arg0, Uri arg1, int arg2) throws RemoteException { mTo.revokeUriPermission(arg0, arg1, arg2); } public void <API key>(IBinder arg0, Uri arg1, int arg2) throws RemoteException { mTo.<API key>(arg0, arg1, arg2); } public void <API key>(IBinder arg0, int arg1, int arg2, int arg3) throws RemoteException { mTo.<API key>(arg0, arg1, arg2, arg3); } public void <API key>(IActivityController arg0) throws RemoteException { mTo.<API key>(arg0); } public void setAlwaysFinish(boolean arg0) throws RemoteException { mTo.setAlwaysFinish(arg0); } public void setDebugApp(String arg0, boolean arg1, boolean arg2) throws RemoteException { mTo.setDebugApp(arg0, arg1, arg2); } public void <API key>(IBinder arg0, int arg1, boolean arg2) throws RemoteException { mTo.<API key>(arg0, arg1, arg2); } public void setProcessLimit(int arg0) throws RemoteException { mTo.setProcessLimit(arg0); } public void <API key>(IBinder arg0, int arg1) throws RemoteException { mTo.<API key>(arg0, arg1); } public void <API key>(ComponentName arg0, IBinder arg1, int arg2, Notification arg3, boolean arg4) throws RemoteException { mTo.<API key>(arg0, arg1, arg2, arg3, arg4); } public void <API key>(IApplicationThread arg0, boolean arg1) throws RemoteException { mTo.<API key>(arg0, arg1); } public boolean shutdown(int arg0) throws RemoteException { return mTo.shutdown(arg0); } public void <API key>(int arg0) throws RemoteException { mTo.<API key>(arg0); } public int startActivity(IApplicationThread arg0, Intent arg1, String arg2, Uri[] arg3, int arg4, IBinder arg5, String arg6, int arg7, boolean arg8, boolean arg9) throws RemoteException { return mTo.startActivity(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } public WaitResult <API key>(IApplicationThread arg0, Intent arg1, String arg2, Uri[] arg3, int arg4, IBinder arg5, String arg6, int arg7, boolean arg8, boolean arg9) throws RemoteException { return mTo.<API key>(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } public int <API key>(int arg0, Intent arg1, String arg2, IBinder arg3, String arg4, int arg5, boolean arg6) throws RemoteException { return mTo.<API key>(arg0, arg1, arg2, arg3, arg4, arg5, arg6); } public int <API key>(IApplicationThread arg0, IntentSender arg1, Intent arg2, String arg3, IBinder arg4, String arg5, int arg6, int arg7, int arg8) throws RemoteException { return mTo.<API key>(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } public int <API key>(IApplicationThread arg0, Intent arg1, String arg2, Uri[] arg3, int arg4, IBinder arg5, String arg6, int arg7, boolean arg8, boolean arg9, Configuration arg10) throws RemoteException { return mTo.<API key>(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } public boolean <API key>(ComponentName arg0, String arg1, int arg2, Bundle arg3, <API key> arg4) throws RemoteException { return mTo.<API key>(arg0, arg1, arg2, arg3, arg4); } public boolean <API key>(IBinder arg0, Intent arg1) throws RemoteException { return mTo.<API key>(arg0, arg1); } public void startRunning(String arg0, String arg1, String arg2, String arg3) throws RemoteException { mTo.startRunning(arg0, arg1, arg2, arg3); } public ComponentName startService(IApplicationThread arg0, Intent arg1, String arg2) throws RemoteException { return mTo.startService(arg0, arg1, arg2); } public void stopAppSwitches() throws RemoteException { mTo.stopAppSwitches(); } public int stopService(IApplicationThread arg0, Intent arg1, String arg2) throws RemoteException { return mTo.stopService(arg0, arg1, arg2); } public boolean stopServiceToken(ComponentName arg0, IBinder arg1, int arg2) throws RemoteException { return mTo.stopServiceToken(arg0, arg1, arg2); } public boolean testIsSystemReady() { return mTo.testIsSystemReady(); } public void unbindBackupAgent(ApplicationInfo arg0) throws RemoteException { mTo.unbindBackupAgent(arg0); } public void unbindFinished(IBinder arg0, Intent arg1, boolean arg2) throws RemoteException { mTo.unbindFinished(arg0, arg1, arg2); } public boolean unbindService(IServiceConnection arg0) throws RemoteException { return mTo.unbindService(arg0); } public void unbroadcastIntent(IApplicationThread arg0, Intent arg1) throws RemoteException { mTo.unbroadcastIntent(arg0, arg1); } public void unhandledBack() throws RemoteException { mTo.unhandledBack(); } public void <API key>(IActivityWatcher arg0) throws RemoteException { mTo.<API key>(arg0); } public void unregisterReceiver(IIntentReceiver arg0) throws RemoteException { mTo.unregisterReceiver(arg0); } public void updateConfiguration(Configuration arg0) throws RemoteException { mTo.updateConfiguration(arg0); } public void wakingUp() throws RemoteException { mTo.wakingUp(); } public boolean <API key>(IBinder arg0) throws RemoteException { return mTo.<API key>(arg0); } }
<!DOCTYPE html> <! | Generated by Apache Maven Doxia Site Renderer 1.7.4 at 2017-09-28 | Rendered using Apache Maven Fluido Skin 1.6 <html xmlns="http: <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="<API key>" content="20170928" /> <meta http-equiv="Content-Language" content="en" /> <title>dollar-runtime &#x2013; Project Summary</title> <link rel="stylesheet" href="./css/<API key>.6.min.css" /> <link rel="stylesheet" href="./css/site.css" /> <link rel="stylesheet" href="./css/print.css" media="print" /> <script type="text/javascript" src="./js/<API key>.6.min.js"></script> </head> <body class="topBarEnabled"> <a href="https://github.com/neilellis/dollar"> <img style="position: absolute; top: 0; right: 0; border: 0; z-index: 10000;" src="https://s3.amazonaws.com/github/ribbons/<API key>.png" alt="Fork me on GitHub"> </a> <div id="topbar" class="navbar navbar-fixed-top "> <div class="navbar-inner"> <div class="container-fluid"> <a data-target=".nav-collapse" data-toggle="collapse" class="btn btn-navbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="http: </a> <ul class="nav"> </ul> </div> </div> </div> </div> <div class="container-fluid"> <div id="banner"> <div class="pull-left"><div id="bannerLeft"><h2>dollar-runtime</h2> </div> </div> <div class="pull-right"></div> <div class="clear"><hr/></div> </div> <div id="breadcrumbs"> <ul class="breadcrumb"> <li id="publishDate">Last Published: 2017-09-28<span class="divider">|</span> </li> <li id="projectVersion">Version: 0.4.5195</li> </ul> </div> <div class="row-fluid"> <div id="leftColumn" class="span2"> <div class="well sidebar-nav"> <ul class="nav nav-list"> </ul> <hr /> <div id="poweredBy"> <script type="text/javascript">asyncJs( 'https://apis.google.com/js/plusone.js' )</script> <div class="g-plusone" data-href="http://sillelien.github.io/dollar/dollar-runtime/" data-size="tall" ></div> <div class="clear"></div> <iframe src="https: scrolling="no" frameborder="0" style="border:none; width:48px; height:63px; margin-top: 10px;" ></iframe> <div class="clear"></div> <div id="twitter"> <a href="https://twitter.com/neilellis" class="<TwitterConsumerkey>" data-show-count="true" data-align="left" data-size="medium" <API key>="true" data-lang="en">Follow neilellis</a> <script type="text/javascript">!function(d,s,id){var js,fjs=d.<API key>(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> </div> <div class="clear"></div> <div class="clear"></div> <a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy"><img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" /></a> </div> </div> </div> <div id="bodyColumn" class="span10" > <div class="section"> <h2><a name="Project_Summary"></a>Project Summary</h2><a name="Project_Summary"></a> <div class="section"> <h3><a name="Project_Information"></a>Project Information</h3><a name="Project_Information"></a> <table border="0" class="table table-striped"> <tr class="a"> <th>Field</th> <th>Value</th></tr> <tr class="b"> <td>Name</td> <td>dollar-runtime</td></tr> <tr class="a"> <td>Description</td> <td>Lightweight, dynamic programming on the JVM</td></tr> <tr class="b"> <td>Homepage</td> <td><a class="externalLink" href="http: <div class="section"> <h3><a name="<API key>"></a>Project Organization</h3><a name="<API key>"></a> <p>This project does not belong to an organization.</p></div> <div class="section"> <h3><a name="Build_Information"></a>Build Information</h3><a name="Build_Information"></a> <table border="0" class="table table-striped"> <tr class="a"> <th>Field</th> <th>Value</th></tr> <tr class="b"> <td>GroupId</td> <td>com.sillelien</td></tr> <tr class="a"> <td>ArtifactId</td> <td>dollar-runtime</td></tr> <tr class="b"> <td>Version</td> <td>0.4.5195</td></tr> <tr class="a"> <td>Type</td> <td>jar</td></tr> <tr class="b"> <td>Java Version</td> <td>1.9</td></tr></table></div></div> </div> </div> </div> <hr/> <footer> <div class="container-fluid"> <div class="row-fluid"> <p>Copyright &copy;2017. All rights reserved.</p> </div> <div id="ohloh" class="pull-right"> <script type="text/javascript" src="https: </div> </div> </footer> </body> </html>
# Basic File Store # by Hampton Catlin # This cache simply uses a directory that it creates # and manages to keep your file stores. # Specify :skip_expires => true if you aren't using # expiration as this will slightly decrease your file size # and memory footprint of the library # You can optionally also specify a :namespace # option that will create a subfolder. require 'fileutils' require File.join(File.dirname(__FILE__), "..", "moneta.rb") module Moneta class BasicFile include Defaults def initialize(options = {}) @namespace = options[:namespace] @directory = ::File.join(options[:path], @namespace.to_s) @expires = !options[:skip_expires] <API key>(@directory) end def key?(key) !self[key].nil? end alias has_key? key? def [](key) if ::File.exist?(path(key)) data = raw_get(key) if @expires if data[:expires_at].nil? || data[:expires_at] > Time.now data[:value] else delete!(key) end end end end def raw_get(key) Marshal.load(::File.read(path(key))) end def []=(key, value) store(key, value) end def store(key, value, options = {}) <API key>(::File.dirname(path(key))) ::File.open(path(key), "w") do |file| if @expires data = {:value => value} if options[:expires_in] data[:expires_at] = Time.now + options[:expires_in] end contents = Marshal.dump(data) else contents = Marshal.dump(value) end file.puts(contents) end end def update_key(key, options) store(key, self[key], options) end def delete!(key) FileUtils.rm(path(key)) nil rescue Errno::ENOENT end def delete(key) value = self[key] delete!(key) value end def clear FileUtils.rm_rf(@directory) FileUtils.mkdir(@directory) end private def path(key) ::File.join(@directory, key.to_s) end def <API key>(directory_path) if ::File.file?(directory_path) raise StandardError, "The path you supplied #{directory_path} is a file" elsif !::File.exists?(directory_path) FileUtils.mkdir_p(directory_path) end end end end
package sjph.life.website.config; import org.springframework.web.servlet.support.<API key>; /** * @author shaohuiguo * */ public class <API key> extends <API key> { @Override protected Class<?>[] <API key>() { return new Class[] { <API key>.class, <API key>.class}; } @Override protected Class<?>[] <API key>() { //return new Class[] { <API key>.class }; return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
package cn.itcast_07; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /* * -- (ObjectOutputStream) * : -- (ObjectInputStream) */ public class ObjectStreamDemo { public static void main(String[] args) throws IOException, <API key> { // write(); read(); } private static void read() throws IOException, <API key> { ObjectInputStream ois = new ObjectInputStream(new FileInputStream( "oos.txt")); Object obj = ois.readObject(); ois.close(); System.out.println(obj); } private static void write() throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream( "oos.txt")); Person p = new Person("", 27); // public final void writeObject(Object obj) oos.writeObject(p); oos.close(); } }
require File.expand_path('../gemutilities', __FILE__) require 'rubygems/dependency' class TestGemDependency < RubyGemTestCase def test_subclass sc = Class.new Gem::Dependency def sc.requirement() bogus; end out, err = capture_io do assert_equal Gem::Requirement.default, sc.new('a').version_requirement end assert_match %r%deprecated%, err end def test_initialize d = dep "pkg", "> 1.0" assert_equal "pkg", d.name assert_equal req("> 1.0"), d.requirement end def <API key> d = dep "pkg", "> 1.0", "< 2.0" assert_equal req("> 1.0", "< 2.0"), d.requirement end def <API key> d = dep "pkg" assert_equal req(">= 0"), d.requirement end def <API key> assert_equal :runtime, dep("pkg").type assert_equal :development, dep("pkg", [], :development).type assert_raises ArgumentError do dep "pkg", :sometimes end end def <API key> d = dep "pkg", v("2") assert_equal req("= 2"), d.requirement end def test_equals2 o = dep "other" d = dep "pkg", "> 1.0" d1 = dep "pkg", "> 1.1" assert_equal d, d.dup assert_equal d.dup, d refute_equal d, d1 refute_equal d1, d refute_equal d, o refute_equal o, d refute_equal d, Object.new refute_equal Object.new, d end def test_equals2_type refute_equal dep("pkg", :runtime), dep("pkg", :development) end def test_equals_tilde d = dep "a", "0" assert_match d, d, "matche self" assert_match dep("a", ">= 0"), d, "match version exact" assert_match dep("a", ">= 0"), dep("a", "1"), "match version" assert_match dep(/a/, ">= 0"), d, "match simple regexp" assert_match dep(/a|b/, ">= 0"), d, "match scary regexp" refute_match dep(/a/), dep("b") refute_match dep("a"), Object.new end def <API key> refute_match dep("a|b"), dep("a", "1") assert_match dep(/a|b/), dep("a", "1") end def <API key> o = Object.new def o.name ; 'a' end def o.version ; '0' end assert_match dep("a"), o end def <API key> assert_match dep("a", ">= 0"), spec("a", "0") assert_match dep("a", "1"), spec("a", "1") assert_match dep(/a/, ">= 0"), spec("a", "0") assert_match dep(/a|b/, ">= 0"), spec("b", "0") refute_match dep(/a/, ">= 0"), spec("b", "0") end def test_hash d = dep "pkg", "1.0" assert_equal d.hash, d.dup.hash assert_equal d.dup.hash, d.hash refute_equal dep("pkg", "1.0").hash, dep("pkg", "2.0").hash, "requirement" refute_equal dep("pkg", "1.0").hash, dep("abc", "1.0").hash, "name" refute_equal dep("pkg", :development), dep("pkg", :runtime), "type" end def test_prerelease_eh d = dep "pkg", "= 1" refute d.prerelease? d.prerelease = true assert d.prerelease? d = dep "pkg", "= 1.a" assert d.prerelease? d.prerelease = false assert d.prerelease? d = dep "pkg", "> 1.a", "> 2" assert d.prerelease? end end
var errorList = errorList || []; print(errorList); var <API key> = ["serialNumberIn", "<API key>"]; var claimsParsed = JSON.parse(claims); print('after parse check mandatory field format'); for (j = 0; j < <API key>.length; j++) { print(<API key>[j]); for (i = 0; i < claimsParsed.data[0].rows.length; i++) { print (JSON.stringify(claimsParsed.data[0].rows[i])); // print(claimsParsed.data[0].rows[i][<API key>[j]].search(/[a-z]/i)); if (claimsParsed.data[0].rows[i][<API key>[j]] && claimsParsed.data[0].rows[i][<API key>[j]].search(/[a-z]/i) > -1) { errorList.push("<API key>"); } } } print(JSON.stringify(errorList)); JSON.stringify(errorList);
#!/usr/bin/env python import sys import copy import rospy,sys import moveit_commander import actionlib import roslib; roslib.load_manifest('ur_modern_driver') import tf from control_msgs.msg import * from trajectory_msgs.msg import * from sensor_msgs.msg import JointState from geometry_msgs.msg import PoseStamped,Pose,PointStamped wpoint = geometry_msgs.msg.PointStamped() wpose = geometry_msgs.msg.PoseStamped() def listener(): try: rospy.Subscriber("/kinect2/click_point/left",PointStamped,move_joint) except KeyboardInterrupt: raise except: raise def move_joint(wpoint): try: print "============got the point " moveit_commander.roscpp_initialize(sys.argv) arm=moveit_commander.MoveGroupCommander('manipulator') end_effector_link=arm.<API key>() blink=arm.get_planning_frame() arm.<API key>(0.01) arm.<API key>(0.1) arm.<API key>(0.2) arm.<API key>(0.05) arm.set_named_target("reset") arm.go() rospy.sleep(1) print "============ arrival reset " print "============ start " wpose.header=wpoint.header wpose.header.frame_id="base_link" wpose.pose.position=wpoint.point print wpose waypoints=[] #arm.set_pose_target(wpose) waypoints.append(arm.get_current_pose().pose) waypoints.append(copy.deepcopy(wpose.pose)) ## We want the cartesian path to be interpolated at a resolution of 1 cm ## which is why we will specify 0.01 as the eef_step in cartesian ## translation. We will specify the jump threshold as 0.0, effectively ## disabling it. (plan3, fraction) = arm.<API key>( waypoints, # waypoints to follow 0.01, # eef_step 0.0) # jump_threshold rospy.sleep(2) arm.execute(plan3) t = tf.TransformerROS(True, rospy.Duration(10.0)) pose_target = geometry_msgs.msg.Pose() pose_target=t.transformPose("kinect2_link",wpose) print pose_target #waypoints=[] # start with the current pose #waypoints.append(arm.get_current_pose().pose) #waypoints.append(copy.deepcopy(wpose.pose)) ## We want the cartesian path to be interpolated at a resolution of 1 cm ## which is why we will specify 0.01 as the eef_step in cartesian ## translation. We will specify the jump threshold as 0.0, effectively ## disabling it. #(plan3, fraction) = arm.<API key>( # waypoints, # waypoints to follow # 0.01, # eef_step # 0.0) # jump_threshold rospy.sleep(1) print "============ arrival goal " except KeyboardInterrupt: raise except: raise def main(): try: rospy.init_node("test_move", anonymous=False) inp = raw_input("Continue? y/n: ")[0] if (inp == 'y'): listener() rospy.spin() else: print "Halting program" except KeyboardInterrupt: rospy.signal_shutdown("KeyboardInterrupt") raise if __name__ == '__main__': main()
// Use, modification, and distribution is subject to the Boost Software // Contact the author at: fernando_cacciola@hotmail.com #ifndef <API key> #define <API key> #include <functional> #include "boost/numeric/conversion/detail/meta.hpp" #include "boost/numeric/conversion/detail/conversion_traits.hpp" #include "boost/numeric/conversion/bounds.hpp" #include "boost/type_traits/is_same.hpp" #include "boost/mpl/integral_c.hpp" namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace numeric { namespace convdetail { // Integral Constants representing rounding modes typedef mpl::integral_c<std::float_round_style, std::round_toward_zero> round2zero_c ; typedef mpl::integral_c<std::float_round_style, std::round_to_nearest> round2nearest_c ; typedef mpl::integral_c<std::float_round_style, std::<API key>> round2inf_c ; typedef mpl::integral_c<std::float_round_style, std::<API key>> round2neg_inf_c ; // Metafunction: // for_round_style<RoundStyle,RoundToZero,RoundToNearest,RoundToInf,RoundToNegInf>::type // {RoundStyle} Integral Constant specifying a round style as declared above. // {RoundToZero,RoundToNearest,RoundToInf,RoundToNegInf} arbitrary types. // Selects one of the 4 types according to the value of RoundStyle. template<class RoundStyle,class RoundToZero,class RoundToNearest,class RoundToInf,class RoundToNegInf> struct for_round_style { typedef ct_switch4<RoundStyle , round2zero_c, round2nearest_c, round2inf_c // round2neg_inf_c , RoundToZero , RoundToNearest , RoundToInf , RoundToNegInf > selector ; typedef typename selector::type type ; } ; // Range Checking Logic. // The range checking logic is built up by combining 1 or 2 predicates. // Each predicate is encapsulated in a template class and exposes // the static member function 'apply'. // Because a particular logic can combine either 1 or two predicates, the following // tags are used to allow the predicate applier to receive 2 preds, but optimize away // one of them if it is 'non-applicable' struct non_applicable { typedef mpl::false_ do_apply ; } ; struct applicable { typedef mpl::true_ do_apply ; } ; // Range Checking Logic implementations. // The following classes, collectivelly named 'Predicates', are instantiated within // the corresponding range checkers. // Their static member function 'apply' is called to perform the actual range checking logic. // s < Lowest(T) ? cNegOverflow : cInRange template<class Traits> struct LT_LoT : applicable { typedef typename Traits::target_type T ; typedef typename Traits::source_type S ; typedef typename Traits::argument_type argument_type ; static range_check_result apply ( argument_type s ) { return s < static_cast<S>(bounds<T>::lowest()) ? cNegOverflow : cInRange ; } } ; // s < 0 ? cNegOverflow : cInRange template<class Traits> struct LT_Zero : applicable { typedef typename Traits::source_type S ; typedef typename Traits::argument_type argument_type ; static range_check_result apply ( argument_type s ) { return s < static_cast<S>(0) ? cNegOverflow : cInRange ; } } ; // s <= Lowest(T)-1 ? cNegOverflow : cInRange template<class Traits> struct LE_PrevLoT : applicable { typedef typename Traits::target_type T ; typedef typename Traits::source_type S ; typedef typename Traits::argument_type argument_type ; static range_check_result apply ( argument_type s ) { return s <= static_cast<S>(bounds<T>::lowest()) - static_cast<S>(1.0) ? cNegOverflow : cInRange ; } } ; // s < Lowest(T)-0.5 ? cNegOverflow : cInRange template<class Traits> struct LT_HalfPrevLoT : applicable { typedef typename Traits::target_type T ; typedef typename Traits::source_type S ; typedef typename Traits::argument_type argument_type ; static range_check_result apply ( argument_type s ) { return s < static_cast<S>(bounds<T>::lowest()) - static_cast<S>(0.5) ? cNegOverflow : cInRange ; } } ; // s > Highest(T) ? cPosOverflow : cInRange template<class Traits> struct GT_HiT : applicable { typedef typename Traits::target_type T ; typedef typename Traits::source_type S ; typedef typename Traits::argument_type argument_type ; static range_check_result apply ( argument_type s ) { return s > static_cast<S>(bounds<T>::highest()) ? cPosOverflow : cInRange ; } } ; // s >= Lowest(T) + 1 ? cPosOverflow : cInRange template<class Traits> struct GE_SuccHiT : applicable { typedef typename Traits::target_type T ; typedef typename Traits::source_type S ; typedef typename Traits::argument_type argument_type ; static range_check_result apply ( argument_type s ) { return s >= static_cast<S>(bounds<T>::highest()) + static_cast<S>(1.0) ? cPosOverflow : cInRange ; } } ; // s >= Lowest(T) + 0.5 ? cPosgOverflow : cInRange template<class Traits> struct GT_HalfSuccHiT : applicable { typedef typename Traits::target_type T ; typedef typename Traits::source_type S ; typedef typename Traits::argument_type argument_type ; static range_check_result apply ( argument_type s ) { return s >= static_cast<S>(bounds<T>::highest()) + static_cast<S>(0.5) ? cPosOverflow : cInRange ; } } ; // Predicate Combiner. // This helper classes are used to possibly combine the range checking logic // individually performed by the predicates // Applies both predicates: first 'PredA', and if it equals 'cInRange', 'PredB' template<class PredA, class PredB> struct applyBoth { typedef typename PredA::argument_type argument_type ; static range_check_result apply ( argument_type s ) { range_check_result r = PredA::apply(s) ; if ( r == cInRange ) r = PredB::apply(s); return r ; } } ; template<class PredA, class PredB> struct combine { typedef applyBoth<PredA,PredB> Both ; typedef void NNone ; // 'None' is defined as a macro in (/usr/X11R6/include/X11/X.h) typedef typename PredA::do_apply do_applyA ; typedef typename PredB::do_apply do_applyB ; typedef typename for_both<do_applyA, do_applyB, Both, PredA, PredB, NNone>::type type ; } ; // Range Checker classes. // The following classes are VISIBLE base classes of the user-level converter<> class. // They supply the optimized 'out_of_range()' and 'validate_range()' static member functions // visible in the user interface. // Dummy range checker. template<class Traits> struct dummy_range_checker { typedef typename Traits::argument_type argument_type ; static range_check_result out_of_range ( argument_type ) { return cInRange ; } static void validate_range ( argument_type ) {} } ; // Generic range checker. // All the range checking logic for all possible combinations of source and target // can be arranged in terms of one or two predicates, which test overflow on both neg/pos 'sides' // of the ranges. // These predicates are given here as IsNegOverflow and IsPosOverflow. template<class Traits, class IsNegOverflow, class IsPosOverflow, class OverflowHandler> struct <API key> { typedef OverflowHandler overflow_handler ; typedef typename Traits::argument_type argument_type ; static range_check_result out_of_range ( argument_type s ) { typedef typename combine<IsNegOverflow,IsPosOverflow>::type Predicate ; return Predicate::apply(s); } static void validate_range ( argument_type s ) { OverflowHandler()( out_of_range(s) ) ; } } ; // Selectors for the optimized Range Checker class. template<class Traits,class OverflowHandler> struct <API key> { typedef dummy_range_checker<Traits> Dummy ; typedef LT_LoT<Traits> Pred1 ; typedef GT_HiT<Traits> Pred2 ; typedef <API key><Traits,Pred1,Pred2,OverflowHandler> Normal ; typedef typename Traits::subranged subranged ; typedef typename mpl::if_<subranged,Normal,Dummy>::type type ; } ; template<class Traits, class OverflowHandler> struct GetRC_Sig2Unsig { typedef LT_Zero<Traits> Pred1 ; typedef GT_HiT <Traits> Pred2 ; typedef <API key><Traits,Pred1,Pred2,OverflowHandler> ChoiceA ; typedef <API key><Traits,Pred1,non_applicable,OverflowHandler> ChoiceB ; typedef typename Traits::target_type T ; typedef typename Traits::source_type S ; typedef typename subranged_Unsig2Sig<S,T>::type oposite_subranged ; typedef typename mpl::not_<oposite_subranged>::type <API key> ; typedef typename mpl::if_<<API key>,ChoiceA,ChoiceB>::type type ; } ; template<class Traits, class OverflowHandler> struct GetRC_Unsig2Sig { typedef GT_HiT<Traits> Pred1 ; typedef <API key><Traits,non_applicable,Pred1,OverflowHandler> type ; } ; template<class Traits,class OverflowHandler> struct GetRC_Int2Int { typedef <API key><Traits,OverflowHandler> Sig2SigQ ; typedef GetRC_Sig2Unsig <Traits,OverflowHandler> Sig2UnsigQ ; typedef GetRC_Unsig2Sig <Traits,OverflowHandler> Unsig2SigQ ; typedef Sig2SigQ Unsig2UnsigQ ; typedef typename Traits::sign_mixture sign_mixture ; typedef typename for_sign_mixture<sign_mixture,Sig2SigQ,Sig2UnsigQ,Unsig2SigQ,Unsig2UnsigQ>::type selector ; typedef typename selector::type type ; } ; template<class Traits> struct GetRC_Int2Float { typedef dummy_range_checker<Traits> type ; } ; template<class Traits, class OverflowHandler, class Float2IntRounder> struct GetRC_Float2Int { typedef LE_PrevLoT <Traits> Pred1 ; typedef GE_SuccHiT <Traits> Pred2 ; typedef LT_HalfPrevLoT<Traits> Pred3 ; typedef GT_HalfSuccHiT<Traits> Pred4 ; typedef GT_HiT <Traits> Pred5 ; typedef LT_LoT <Traits> Pred6 ; typedef <API key><Traits,Pred1,Pred2,OverflowHandler> ToZero ; typedef <API key><Traits,Pred3,Pred4,OverflowHandler> ToNearest ; typedef <API key><Traits,Pred1,Pred5,OverflowHandler> ToInf ; typedef <API key><Traits,Pred6,Pred2,OverflowHandler> ToNegInf ; typedef typename Float2IntRounder::round_style round_style ; typedef typename for_round_style<round_style,ToZero,ToNearest,ToInf,ToNegInf>::type type ; } ; template<class Traits, class OverflowHandler> struct GetRC_Float2Float { typedef dummy_range_checker<Traits> Dummy ; typedef LT_LoT<Traits> Pred1 ; typedef GT_HiT<Traits> Pred2 ; typedef <API key><Traits,Pred1,Pred2,OverflowHandler> Normal ; typedef typename Traits::subranged subranged ; typedef typename mpl::if_<subranged,Normal,Dummy>::type type ; } ; template<class Traits, class OverflowHandler, class Float2IntRounder> struct <API key> { typedef GetRC_Int2Int<Traits,OverflowHandler> Int2IntQ ; typedef GetRC_Int2Float<Traits> Int2FloatQ ; typedef GetRC_Float2Int<Traits,OverflowHandler,Float2IntRounder> Float2IntQ ; typedef GetRC_Float2Float<Traits,OverflowHandler> Float2FloatQ ; typedef typename Traits::int_float_mixture int_float_mixture ; typedef typename <API key><int_float_mixture, Int2IntQ, Int2FloatQ, Float2IntQ, Float2FloatQ>::type selector ; typedef typename selector::type type ; } ; template<class Traits, class OverflowHandler, class Float2IntRounder> struct GetRC { typedef <API key><Traits,OverflowHandler,Float2IntRounder> BuiltIn2BuiltInQ ; typedef dummy_range_checker<Traits> Dummy ; typedef mpl::identity<Dummy> DummyQ ; typedef typename Traits::udt_builtin_mixture udt_builtin_mixture ; typedef typename <API key><udt_builtin_mixture,BuiltIn2BuiltInQ,DummyQ,DummyQ,DummyQ>::type selector ; typedef typename selector::type type ; } ; // Converter classes. // The following classes are VISIBLE base classes of the user-level converter<> class. // They supply the optimized 'nearbyint()' and 'convert()' static member functions // visible in the user interface. // Trivial Converter : used when (cv-unqualified) T == (cv-unqualified) S template<class Traits> struct <API key> : public std::unary_function< <API key> Traits::argument_type ,<API key> Traits::result_type > ,public dummy_range_checker<Traits> { typedef Traits traits ; typedef typename Traits::source_type source_type ; typedef typename Traits::argument_type argument_type ; typedef typename Traits::result_type result_type ; static result_type low_level_convert ( argument_type s ) { return s ; } static source_type nearbyint ( argument_type s ) { return s ; } static result_type convert ( argument_type s ) { return s ; } } ; // Rounding Converter : used for float to integral conversions. template<class Traits,class RangeChecker,class RawConverter,class Float2IntRounder> struct rounding_converter : public std::unary_function< <API key> Traits::argument_type ,<API key> Traits::result_type > ,public RangeChecker ,public Float2IntRounder ,public RawConverter { typedef RangeChecker RangeCheckerBase ; typedef Float2IntRounder <API key> ; typedef RawConverter RawConverterBase ; typedef Traits traits ; typedef typename Traits::source_type source_type ; typedef typename Traits::argument_type argument_type ; typedef typename Traits::result_type result_type ; static result_type convert ( argument_type s ) { RangeCheckerBase::validate_range(s); source_type s1 = <API key>::nearbyint(s); return RawConverterBase::low_level_convert(s1); } } ; // Non-Rounding Converter : used for all other conversions. template<class Traits,class RangeChecker,class RawConverter> struct <API key> : public std::unary_function< <API key> Traits::argument_type ,<API key> Traits::result_type > ,public RangeChecker ,public RawConverter { typedef RangeChecker RangeCheckerBase ; typedef RawConverter RawConverterBase ; typedef Traits traits ; typedef typename Traits::source_type source_type ; typedef typename Traits::argument_type argument_type ; typedef typename Traits::result_type result_type ; static source_type nearbyint ( argument_type s ) { return s ; } static result_type convert ( argument_type s ) { RangeCheckerBase::validate_range(s); return RawConverterBase::low_level_convert(s); } } ; // Selectors for the optimized Converter class. template<class Traits,class OverflowHandler,class Float2IntRounder,class RawConverter, class UserRangeChecker> struct <API key> { typedef GetRC<Traits,OverflowHandler,Float2IntRounder> <API key> ; typedef is_same<UserRangeChecker,<API key>> use_internal_RC ; typedef mpl::identity<UserRangeChecker> UserRangeCheckerQ ; typedef typename mpl::eval_if<use_internal_RC,<API key>,UserRangeCheckerQ>::type RangeChecker ; typedef <API key><Traits,RangeChecker,RawConverter> NonRounding ; typedef rounding_converter<Traits,RangeChecker,RawConverter,Float2IntRounder> Rounding ; typedef mpl::identity<NonRounding> NonRoundingQ ; typedef mpl::identity<Rounding> RoundingQ ; typedef typename Traits::int_float_mixture int_float_mixture ; typedef typename <API key><int_float_mixture, NonRoundingQ, NonRoundingQ, RoundingQ, NonRoundingQ>::type selector ; typedef typename selector::type type ; } ; template< class Traits ,class OverflowHandler ,class Float2IntRounder ,class RawConverter ,class UserRangeChecker > struct get_converter_impl { #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT( 0x0561 ) ) // bcc55 prefers sometimes template parameters to be explicit local types. typedef Traits Traits ; typedef OverflowHandler OverflowHandler ; typedef Float2IntRounder Float2IntRounder ; typedef RawConverter RawConverter ; typedef UserRangeChecker UserRangeChecker ; #endif typedef <API key><Traits> Trivial ; typedef mpl::identity <Trivial> TrivialQ ; typedef <API key>< Traits ,OverflowHandler ,Float2IntRounder ,RawConverter ,UserRangeChecker > NonTrivialQ ; typedef typename Traits::trivial trivial ; typedef typename mpl::eval_if<trivial,TrivialQ,NonTrivialQ>::type type ; } ; } } } // namespace geofeatures_boost::numeric::convdetail #endif
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_11) on Mon Aug 11 16:48:21 PDT 2014 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class com.google.gson.reflect.TypeToken (Gson 2.3 API)</title> <meta name="date" content="2014-08-11"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.google.gson.reflect.TypeToken (Gson 2.3 API)"; } } catch(err) { } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/google/gson/reflect/class-use/TypeToken.html" target="_top">Frames</a></li> <li><a href="TypeToken.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <h2 title="Uses of Class com.google.gson.reflect.TypeToken" class="title">Uses of Class<br>com.google.gson.reflect.TypeToken</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.google.gson">com.google.gson</a></td> <td class="colLast"> <div class="block">This package provides the <a href="../../../../../com/google/gson/Gson.html" title="class in com.google.gson"><code>Gson</code></a> class to convert Json to Java and vice-versa.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#com.google.gson.reflect">com.google.gson.reflect</a></td> <td class="colLast"> <div class="block">This package provides utility classes for finding type information for generic types.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.google.gson"> </a> <h3>Uses of <a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a> in <a href="../../../../../com/google/gson/package-summary.html">com.google.gson</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/google/gson/package-summary.html">com.google.gson</a> with parameters of type <a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>&lt;T&gt;&nbsp;<a href="../../../../../com/google/gson/TypeAdapter.html" title="class in com.google.gson">TypeAdapter</a>&lt;T&gt;</code></td> <td class="colLast"><span class="typeNameLabel">TypeAdapterFactory.</span><code><span class="memberNameLink"><a href="../../../../../com/google/gson/TypeAdapterFactory.html#create-com.google.gson.Gson-com.google.gson.reflect.TypeToken-">create</a></span>(<a href="../../../../../com/google/gson/Gson.html" title="class in com.google.gson">Gson</a>&nbsp;gson, <a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a>&lt;T&gt;&nbsp;type)</code> <div class="block">Returns a type adapter for <code>type</code>, or null if this factory doesn't support <code>type</code>.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>&lt;T&gt;&nbsp;<a href="../../../../../com/google/gson/TypeAdapter.html" title="class in com.google.gson">TypeAdapter</a>&lt;T&gt;</code></td> <td class="colLast"><span class="typeNameLabel">Gson.</span><code><span class="memberNameLink"><a href="../../../../../com/google/gson/Gson.html#getAdapter-com.google.gson.reflect.TypeToken-">getAdapter</a></span>(<a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a>&lt;T&gt;&nbsp;type)</code> <div class="block">Returns the type adapter for type.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>&lt;T&gt;&nbsp;<a href="../../../../../com/google/gson/TypeAdapter.html" title="class in com.google.gson">TypeAdapter</a>&lt;T&gt;</code></td> <td class="colLast"><span class="typeNameLabel">Gson.</span><code><span class="memberNameLink"><a href="../../../../../com/google/gson/Gson.html#<API key>.google.gson.<API key>.google.gson.reflect.TypeToken-">getDelegateAdapter</a></span>(<a href="../../../../../com/google/gson/TypeAdapterFactory.html" title="interface in com.google.gson">TypeAdapterFactory</a>&nbsp;skipPast, <a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a>&lt;T&gt;&nbsp;type)</code> <div class="block">This method is used to get an alternate type adapter for the specified type.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.google.gson.reflect"> </a> <h3>Uses of <a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a> in <a href="../../../../../com/google/gson/reflect/package-summary.html">com.google.gson.reflect</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/google/gson/reflect/package-summary.html">com.google.gson.reflect</a> that return <a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static &lt;T&gt;&nbsp;<a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a>&lt;T&gt;</code></td> <td class="colLast"><span class="typeNameLabel">TypeToken.</span><code><span class="memberNameLink"><a href="../../../../../com/google/gson/reflect/TypeToken.html <div class="block">Gets type literal for the given <code>Class</code> instance.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a>&lt;?&gt;</code></td> <td class="colLast"><span class="typeNameLabel">TypeToken.</span><code><span class="memberNameLink"><a href="../../../../../com/google/gson/reflect/TypeToken.html <div class="block">Gets type literal for the given <code>Type</code> instance.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/google/gson/reflect/package-summary.html">com.google.gson.reflect</a> with parameters of type <a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><span class="typeNameLabel">TypeToken.</span><code><span class="memberNameLink"><a href="../../../../../com/google/gson/reflect/TypeToken.html#<API key>.google.gson.reflect.TypeToken-">isAssignableFrom</a></span>(<a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">TypeToken</a>&lt;?&gt;&nbsp;token)</code> <div class="block"><span class="deprecatedLabel">Deprecated.</span>&nbsp; <div class="block"><span class="deprecationComment">this implementation may be inconsistent with javac for types with wildcards.</span></div> </div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/google/gson/reflect/TypeToken.html" title="class in com.google.gson.reflect">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/google/gson/reflect/class-use/TypeToken.html" target="_top">Frames</a></li> <li><a href="TypeToken.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> <p class="legalCopy"><small>Copyright & </body> </html>
<BODY> Package providing examples of all possible Map relations between container and key/value classes. <UL> <LI><B>MapHoldern</B> class with all types of Map fields demonstrating all possible Map combos</LI> <LI><B>MapKeyItem</B> - PC type of key when using join table</LI> <LI><B>MapValueItem</B> - PC type of value when using join table</LI> <LI><B>MapFKKeyItem</B> - PC type of key when the value is part of the key</LI> <LI><B>MapFKValueItem</B> - PC type of value when the key is part of the value</LI> </UL> </BODY>
package com.intellij.openapi.options; import com.intellij.ide.ui.search.<API key>; import com.intellij.ide.ui.search.OptionDescription; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Getter; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.Setter; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.IdeBorderFactory; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.JBIterable; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.components.BorderLayoutPanel; import kotlin.reflect.KMutableProperty0; import org.jetbrains.annotations.*; import javax.swing.*; import java.awt.*; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.function.Function; /** * See {@link ConfigurableBuilder} for {@link UiDslConfigurable} alternative. */ public abstract class BeanConfigurable<T> implements UnnamedConfigurable, <API key> { private final T myInstance; private @NlsContexts.BorderTitle String myTitle; private final List<BeanField> myFields = new ArrayList<>(); protected BeanConfigurable(@NotNull T beanInstance) { myInstance = beanInstance; } protected BeanConfigurable(@NotNull T beanInstance, @NlsContexts.BorderTitle String title) { this(beanInstance); setTitle(title); } private abstract static class <API key> { abstract Object getBeanValue(Object instance); abstract void setBeanValue(Object instance, @NotNull Object value); } private static final class BeanFieldAccessor extends <API key> { private final String myFieldName; private final Class myValueClass; private BeanFieldAccessor(String fieldName, Class valueClass) { myFieldName = fieldName; myValueClass = valueClass; } @NonNls protected String getterName() { if (myValueClass.equals(boolean.class)) { return "is" + StringUtil.capitalize(myFieldName); } return "get" + StringUtil.capitalize(myFieldName); } @Override Object getBeanValue(@NotNull Object instance) { try { Field field = instance.getClass().getField(myFieldName); return field.get(instance); } catch (<API key> e) { try { final Method method = instance.getClass().getMethod(getterName()); return method.invoke(instance); } catch (Exception e1) { throw new RuntimeException(e1); } } catch (<API key> e) { throw new RuntimeException(e); } } @Override void setBeanValue(@NotNull Object instance, @NotNull Object value) { try { Field field = instance.getClass().getField(myFieldName); field.set(instance, value); } catch (<API key> e) { try { final Method method = instance.getClass().getMethod("set" + StringUtil.capitalize(myFieldName), myValueClass); method.invoke(instance, value); } catch (Exception e1) { throw new RuntimeException(e1); } } catch (<API key> e) { throw new RuntimeException(e); } } } private static final class BeanMethodAccessor<T> extends <API key> { private final Getter<? extends T> myGetter; private final Setter<? super T> mySetter; private BeanMethodAccessor(Getter<? extends T> getter, Setter<? super T> setter) { myGetter = getter; mySetter = setter; } @Override Object getBeanValue(Object instance) { return myGetter.get(); } @Override void setBeanValue(Object instance, @NotNull Object value) { //noinspection unchecked mySetter.set((T) value); } } private static final class <API key><T> extends <API key> { private final KMutableProperty0<T> myProperty; private <API key>(KMutableProperty0<T> property) { myProperty = property; } @Override Object getBeanValue(Object instance) { return myProperty.get(); } @Override void setBeanValue(Object instance, @NotNull Object value) { //noinspection unchecked myProperty.set((T)value); } } private abstract static class BeanField<T extends JComponent> { <API key> myAccessor; T myComponent; private BeanField(@NotNull <API key> accessor) { myAccessor = accessor; } T getComponent() { if (myComponent == null) { myComponent = createComponent(); } return myComponent; } @NotNull abstract T createComponent(); boolean isModified(Object instance) { final Object componentValue = getComponentValue(); final Object beanValue = myAccessor.getBeanValue(instance); return !Comparing.equal(componentValue, beanValue); } void apply(Object instance) { myAccessor.setBeanValue(instance, getComponentValue()); } void reset(Object instance) { setComponentValue(myAccessor.getBeanValue(instance)); } abstract Object getComponentValue(); abstract void setComponentValue(Object value); } private static final class CheckboxField extends BeanField<JCheckBox> { private final @NlsContexts.Checkbox String myTitle; private CheckboxField(final String fieldName, final @NlsContexts.Checkbox String title) { super(new BeanFieldAccessor(fieldName, boolean.class)); myTitle = title; } private CheckboxField(<API key> accessor, @NlsContexts.Checkbox String title) { super(accessor); myTitle = title; } private String getTitle() { return myTitle; } private void setValue(Object settingsInstance, boolean value) { myAccessor.setBeanValue(settingsInstance, value); } private boolean getValue(Object settingsInstance) { return (boolean)myAccessor.getBeanValue(settingsInstance); } @NotNull @Override JCheckBox createComponent() { return new JCheckBox(myTitle); } @Override Object getComponentValue() { return getComponent().isSelected(); } @Override void setComponentValue(Object value) { getComponent().setSelected((Boolean)value); } } @Nullable public String getTitle() { return myTitle; } protected void setTitle(@NlsContexts.BorderTitle String title) { myTitle = title; } @Nullable protected T getInstance() { return myInstance; } /** * @deprecated use {@link #checkBox(String, Getter, Setter)} instead */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") protected void checkBox(@NonNls String fieldName, @NlsContexts.Checkbox String title) { myFields.add(new CheckboxField(fieldName, title)); } /** * Adds check box with given {@code title}. * Initial checkbox value is obtained from {@code getter}. * After the apply, the value from the check box is written back to model via {@code setter}. */ protected void checkBox(@NlsContexts.Checkbox @NotNull String title, @NotNull Getter<Boolean> getter, @NotNull Setter<? super Boolean> setter) { CheckboxField field = new CheckboxField(new BeanMethodAccessor<>(getter, setter), title); myFields.add(field); } protected void checkBox(@NlsContexts.Checkbox @NotNull String title, @NotNull KMutableProperty0<Boolean> prop) { myFields.add(new CheckboxField(new <API key><>(prop), title)); } /** * Adds custom component (e.g. edit box). * Initial value is obtained from {@code beanGetter} and applied to the component via {@code componentSetter}. * E.g. text is read from the model and set to the edit box. * After the apply, the value from the component is queried via {@code componentGetter} and written back to model via {@code beanSetter}. * E.g. text from the edit box is queried and saved back to model bean. */ protected <V> void component(@NotNull JComponent component, @NotNull Getter<? extends V> beanGetter, @NotNull Setter<? super V> beanSetter, @NotNull Getter<? extends V> componentGetter, @NotNull Setter<? super V> componentSetter) { BeanField<JComponent> field = new BeanField<>(new BeanMethodAccessor<V>(beanGetter, beanSetter)) { @NotNull @Override JComponent createComponent() { return component; } @Override Object getComponentValue() { return componentGetter.get(); } @Override void setComponentValue(Object value) { componentSetter.set((V)value); } }; myFields.add(field); } @NotNull @Override public List<OptionDescription> <API key>(@NotNull String configurableId, @NotNull Function<? super String, @Nls String> nameConverter) { List<CheckboxField> boxes = JBIterable.from(myFields).filter(CheckboxField.class).toList(); Object instance = getInstance(); return ContainerUtil.map(boxes, box -> new <API key>(nameConverter.apply(box.getTitle()), configurableId) { @Override public boolean isOptionEnabled() { return box.getValue(instance); } @Override public void setOptionState(boolean enabled) { box.setValue(instance, enabled); } }); } @Override public JComponent createComponent() { final JPanel panel = new JPanel(new GridLayout(myFields.size(), 1, 0, JBUI.scale(5))); for (BeanField field: myFields) { panel.add(field.getComponent()); } BorderLayoutPanel result = JBUI.Panels.simplePanel().addToTop(panel); if (myTitle != null) { result.setBorder(IdeBorderFactory.createTitledBorder(myTitle)); } return result; } @Override public boolean isModified() { for (BeanField field : myFields) { if (field.isModified(myInstance)) return true; } return false; } @Override public void apply() throws <API key> { for (BeanField field : myFields) { field.apply(myInstance); } } @Override public void reset() { for (BeanField field : myFields) { field.reset(myInstance); } } }
// <API key>: Apache-2.0 package dns import ( "github.com/cilium/cilium/pkg/hubble/metrics/api" ) type dnsPlugin struct{} func (p *dnsPlugin) NewHandler() api.Handler { return &dnsHandler{} } func (p *dnsPlugin) HelpText() string { return `dns - DNS related metrics Reports metrics related to DNS queries and responses Metrics: <API key> Number of observed TCP queries <API key> Number of observed TCP responses Options: query - Include query name as label ignoreAAAA - Do not include AAAA query & responses in metrics` + api.ContextOptionsHelp } func init() { api.DefaultRegistry().Register("dns", &dnsPlugin{}) }
from dvc.prompt import confirm def <API key>(mocker): mock_input = mocker.patch("dvc.prompt.input", side_effect=EOFError) mock_isatty = mocker.patch("sys.stdout.isatty", return_value=True) ret = confirm("message") mock_isatty.assert_called() mock_input.assert_called() assert not ret
// AdoptsAttribute.cs: Attribute applied to classes to specify that the // class implements a given protocol // Authors: // Miguel de Icaza // 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, // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // included in all copies or substantial portions of the Software. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // 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. using System; using System.Runtime.InteropServices; namespace MonoMac.ObjCRuntime { [AttributeUsage(AttributeTargets.Class, AllowMultiple=true)] public class AdoptsAttribute : Attribute { IntPtr handle; [DllImport ("/usr/lib/libobjc.dylib")] internal static extern IntPtr objc_getProtocol (string proto); public AdoptsAttribute (string protocolType) { ProtocolType = protocolType; } public string ProtocolType { get; private set; } public IntPtr ProtocolHandle { get { if (handle == IntPtr.Zero && ProtocolType != null) handle = objc_getProtocol (ProtocolType); return handle; } } } }
package trees.impl; import java.io.IOException; import java.util.Iterator; import java.util.Stack; public class BST implements Iterable<Integer>{ private Node root; public BST(Node root) { this.root = root; } public BST(int value) { this.root = new Node(value); } public Node root() { return root; } public Node findNode(int value) { return findNode(root, value); } public Node findNode(Node currentNode, int value) { if (currentNode == null) return null; if (currentNode.data() == value) return currentNode; if (value > currentNode.data()) return findNode(currentNode.getRight(), value); else return findNode(currentNode.getLeft(), value); } public Node generateRandomTree(int size) { return new Node(0); } // To delete, need to find the parent public Node findParent(int value) { return findParent(root, value); } public Node findParent(Node currentNode, int value) { if (currentNode == null) { return null; } if(currentNode.data() == value) { // Cannot get parent, root is parent return null; } if((currentNode.getLeft().data() == value) || currentNode.getRight().data() == value) { return currentNode; } if(value > currentNode.data()) { return findParent(currentNode.getRight(), value); } else return findParent(currentNode.getLeft(), value); } public void delete(int value) { if(root == null) { return; } delete(root, value); } /* 1. the value to remove is a leaf Node; or 2. the value to remove has a right subtree, but no left subtree; or 3. the value to remove has a left subtree, but no right subtree; or 4. the value to remove has both a left and right subtree in which case we promote the largest value in the left subtree. */ public void delete(Node currentNode, int value) { if(currentNode == null) { return; } Node parent = findParent(value); } public void insert(int value) { if(root == null) { root = new Node(value); return; } insertNode(root, value); } public void insertNode(Node currentNode, int value) { // if value > current Node, insert into right if (value > currentNode.data()) { if(currentNode.getRight() == null) { currentNode.setRight(new Node(value)); return; } insertNode(currentNode.getRight(), value); } else { if(currentNode.getLeft() == null) { currentNode.setLeft(new Node(value)); return; } insertNode(currentNode.getLeft(), value); } } public void printTree() throws IOException { printTree(root); //System.out.println("second print"); //anotherPrintTree(root); } public void printTree(Node inputNode) throws IOException { if(inputNode == null) { return; } printTree(inputNode.getLeft()); System.out.println("Data: " + inputNode.data()); printTree(inputNode.getRight()); } public void anotherPrintTree(Node inputNode) throws IOException { BSTPrintPretty.printTree(inputNode); } public int maxHeight() { return maxHeight(root); } public static int maxHeight(Node input) { if(input == null) return 0; int leftHeight = maxHeight(input.getLeft()); int rightHeight = maxHeight(input.getRight()); return (leftHeight > rightHeight? leftHeight + 1 : rightHeight + 1); } public int treeSize() { return treeSize(root); } public int treeSize(Node root) { if(root == null) return 0; int leftHeight = treeSize(root.getLeft()); int rightHeight = treeSize(root.getRight()); return (leftHeight + 1 + rightHeight); } public void <API key>() { <API key>(root); } public void <API key>(Node inputNode) { if (inputNode == null) return; Stack<Node> treeNodes = new Stack<Node> (); Node topNode = inputNode; do { // need a current Node state so you don't traverse from wherever you are //Node currentNode = treeNodes.peek(); // left, root, right // remove item from top of stack //Node topNode = treeNodes.pop(); // if left, add to stack if(topNode != null) { treeNodes.add(topNode); topNode = topNode.getLeft(); //continue; } else { // else remove from stack, print data topNode = treeNodes.pop(); System.out.println("Data: " + topNode.data); topNode = topNode.getRight(); } }while(treeNodes.size() > 0 || topNode != null); } @Override public Iterator iterator() { BSTiterator myIterator = new BSTiterator(this); return myIterator; } }
import { errors } from 'arsenal'; /** * parseRange - Validate and parse range request header * @param {string} rangeHeader - range header from request * which should be in form bytes=0-9 * @param {number} totalLength - totalLength of object * @return {object} object containing range (array | undefined) and error if * range is invalid */ export function parseRange(rangeHeader, totalLength) { // If the range is invalid in any manner, AWS just returns the full object // (end is inclusive so minus 1) const maxEnd = totalLength - 1; let range = undefined; if (!rangeHeader.startsWith('bytes=') || rangeHeader.indexOf('-') < 0 // Multiple ranges not supported || rangeHeader.indexOf(',') > 0) { return { range }; } const rangePortion = rangeHeader.replace('bytes=', '').split('-'); if (rangePortion.length > 2) { return { range }; } let start; let end; // Handle incomplete specifier where just offset from end is given if (rangePortion[0] === '') { const offset = parseInt(rangePortion[1], 10); if (Number.isNaN(offset)) { return { range }; } start = totalLength - offset; end = maxEnd; // Handle incomplete specifier where just starting place is given // meaning range goes from start of range to end of object } else if (rangePortion[1] === '') { start = parseInt(rangePortion[0], 10); end = maxEnd; } else { start = parseInt(rangePortion[0], 10); end = parseInt(rangePortion[1], 10); } // InvalidRange when the resource being accessed does not cover // the byte range if (start >= totalLength && end >= totalLength) { return { range, error: errors.InvalidRange }; } end = Math.min(end, maxEnd); if (Number.isNaN(start) || Number.isNaN(end) || start > end) { return { range }; } if (start < 0) { start = 0; } range = [start, end]; return { range }; }
.ce-stub { display: flex; align-items: center; justify-content: center; width: 100%; padding: 3.5em 0; margin: 17px 0; border-radius: 3px; background: #fcf7f7; color: #b46262; &__info { margin-left: 20px; } &__title { margin-bottom: 3px; font-weight: 600; font-size: 18px; text-transform: capitalize; } &__subtitle { font-size: 16px; } }
package org.olat.test.functional.courseeditor; import org.olat.test.util.selenium.<API key>; import org.olat.test.util.selenium.SeleniumHelper; import org.olat.test.util.selenium.olatapi.OLATWorkflowHelper; import org.olat.test.util.selenium.olatapi.course.editor.CourseEditor; import org.olat.test.util.selenium.olatapi.lr.LRDetailedView; import org.olat.test.util.selenium.olatapi.lr.LearningResources; import org.olat.test.util.setup.OlatLoginInfos; import org.olat.test.util.setup.SetupType; import org.olat.test.util.setup.context.Context; /** * * Assure that owner A and B cannot start editing the same course at the same time. <br/> * <p> * Test setup:<br/> * 1. user1 (standardauthor) creates course Coursename<br/> * 2. user2 (standardstudent) is also owner of course Coursename<br/> * 3. cleanup in the end: course is deleted<br/> * * Test case: <br/> * 1. user1 creates course "CourseName" with the element "forum" and adds user2 as owner <br/> * 2. user2 opens detailed view of course "CourseName" in browser 2<br/> * 3. user1 clicks edit "CourseName" in browser 1<br/> * 4. user2 clicks "Edit content" in browser 2 <br/> * 5. Check if the message "This course is currently edited by 'user1' and therefore locked." appears<br/> * 6. user1 closes editor in browser 1<br/> * 7. user2 clicks "Edit content" in browser 2<br/> * 8. Check if "This course has never been published." appears<br/> * </p> * * @author kristina * */ public class <API key> extends <API key> { private final String COURSE_NAME = "CourseName" + System.currentTimeMillis(); private final String COURSE_DESCRIPTION = "CourseDescription" + System.currentTimeMillis(); protected com.thoughtworks.selenium.Selenium selenium1; protected com.thoughtworks.selenium.Selenium selenium2; public void <API key>() throws Exception { Context context = Context.setupContext(getFullName(), SetupType.TWO_NODE_CLUSTER); OlatLoginInfos user1 = context.getStandard<API key>(1); OlatLoginInfos user2 = context.<API key>(2); // user1 creates course COURSE_NAME with the element "forum" and adds user 2 as owner System.out.println("logging in browser 1..."); OLATWorkflowHelper olatWorkflow1 = context.<API key>(user1); CourseEditor courseEditor = olatWorkflow1.<API key>().<API key>(COURSE_NAME, COURSE_DESCRIPTION); courseEditor.insertCourseElement(CourseEditor.CourseElemTypes.FORUM, true, null); LRDetailedView lRDetailedView = courseEditor.<API key>(); lRDetailedView.assignOwner(user2.getUsername()); // user 2 opens detailed view of course COURSE_NAME in browser 2 System.out.println("logging in browser 2..."); OLATWorkflowHelper olatWorkflow2 = context.<API key>(user2); LearningResources learningResources2 = olatWorkflow2.<API key>(); LRDetailedView lRDetailedView2 = learningResources2.searchMyResource(COURSE_NAME); // user 1 clicks edit COURSE_NAME in browser 1 CourseEditor courseEditor3 = lRDetailedView.editCourseContent(); // user2 clicks "Edit content" in browser 2 boolean isCourseLocked = lRDetailedView2.checkCourseLocked(user1.getUsername()); assertTrue(isCourseLocked); // user1 closes editor in browser 1 courseEditor3.<API key>(); // course run was open via the LRDetailedView // user2 clicks "Edit content" in browser 2 CourseEditor courseEditor4 = lRDetailedView2.editCourseContent(); // Check if "This course has never been published." appears SeleniumHelper.<API key>(lRDetailedView2.getSelenium(), "This course has never been published.", 20); // delete course LRDetailedView lRDetailedView3 = courseEditor4.<API key>(); try { lRDetailedView3.deleteLR(); } catch (Exception e) { } } }
package org.geometerplus.fbreader.book; public enum BookEvent { Added, Updated, Removed, Opened, BookmarksUpdated, <API key>, }
/ [<API key>.ts] class A { constructor(f: string) { } public blah(): string { return ""; } } class B extends A { constructor() { super(super.blah()) } } / [<API key>.js] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var A = (function () { function A(f) { } A.prototype.blah = function () { return ""; }; return A; }()); var B = (function (_super) { __extends(B, _super); function B() { var _this = _super.call(this, _super.prototype.blah.call(_this)) || this; return _this; } return B; }(A));
package com.jtattoo.plaf; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.plaf.*; import javax.swing.plaf.basic.*; /** * @author Michael Hagen */ public class BaseScrollBarUI extends BasicScrollBarUI { protected int scrollBarWidth = 17; protected boolean isRollover = false; public static ComponentUI createUI(JComponent c) { return new BaseScrollBarUI(); } protected void installDefaults() { scrollBarWidth = UIManager.getInt("ScrollBar.width"); super.installDefaults(); } protected JButton <API key>(int orientation) { return new BaseScrollButton(orientation, scrollBarWidth); } protected JButton <API key>(int orientation) { return new BaseScrollButton(orientation, scrollBarWidth); } public TrackListener createTrackListener() { return new MyTrackListener(); } public Dimension getPreferredSize(JComponent c) { if (scrollbar.getOrientation() == JScrollBar.VERTICAL) { return new Dimension(scrollBarWidth, scrollBarWidth * 3 + 16); } else { return new Dimension(scrollBarWidth * 3 + 16, scrollBarWidth); } } protected Dimension getMinimumThumbSize() { return new Dimension(scrollBarWidth, scrollBarWidth); } protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) { int w = c.getWidth(); int h = c.getHeight(); if (scrollbar.getOrientation() == JScrollBar.VERTICAL) { JTattooUtilities.fillVerGradient(g, AbstractLookAndFeel.getTheme().getTrackColors(), 0, 0, w, h); } else { JTattooUtilities.fillHorGradient(g, AbstractLookAndFeel.getTheme().getTrackColors(), 0, 0, w, h); } } protected Color[] getThumbColors() { if (isRollover || isDragging) { return AbstractLookAndFeel.getTheme().getRolloverColors(); } else if (!JTattooUtilities.isActive(scrollbar)) { return AbstractLookAndFeel.getTheme().getInActiveColors(); } else { return AbstractLookAndFeel.getTheme().getThumbColors(); } } protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) { if (!c.isEnabled()) { return; } g.translate(thumbBounds.x, thumbBounds.y); Color colors[] = getThumbColors(); Color frameColorHi = ColorHelper.brighter(colors[1], 20); Color frameColorLo = ColorHelper.darker(colors[colors.length - 1], 10); if (scrollbar.getOrientation() == JScrollBar.VERTICAL) { JTattooUtilities.fillVerGradient(g, colors, 1, 1, thumbBounds.width - 1, thumbBounds.height - 1); JTattooUtilities.draw3DBorder(g, frameColorLo, ColorHelper.darker(frameColorLo, 15), 0, 0, thumbBounds.width, thumbBounds.height); g.setColor(frameColorHi); g.drawLine(1, 1, thumbBounds.width - 2, 1); g.drawLine(1, 1, 1, thumbBounds.height - 2); Graphics2D g2D = (Graphics2D) g; Composite composite = g2D.getComposite(); AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f); g2D.setComposite(alpha); int dx = 5; int dy = thumbBounds.height / 2 - 3; int dw = thumbBounds.width - 11; Color c1 = Color.white; Color c2 = Color.darkGray; for (int i = 0; i < 4; i++) { g.setColor(c1); g.drawLine(dx, dy, dx + dw, dy); dy++; g.setColor(c2); g.drawLine(dx, dy, dx + dw, dy); dy++; } g2D.setComposite(composite); } else // HORIZONTAL { JTattooUtilities.fillHorGradient(g, colors, 1, 1, thumbBounds.width - 1, thumbBounds.height - 1); JTattooUtilities.draw3DBorder(g, frameColorLo, ColorHelper.darker(frameColorLo, 10), 0, 0, thumbBounds.width, thumbBounds.height); g.setColor(frameColorHi); g.drawLine(1, 1, thumbBounds.width - 2, 1); g.drawLine(1, 1, 1, thumbBounds.height - 2); int dx = thumbBounds.width / 2 - 3; int dy = 5; int dh = thumbBounds.height - 11; Graphics2D g2D = (Graphics2D) g; Composite composite = g2D.getComposite(); AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f); g2D.setComposite(alpha); Color c1 = Color.white; Color c2 = Color.darkGray; for (int i = 0; i < 4; i++) { g.setColor(c1); g.drawLine(dx, dy, dx, dy + dh); dx++; g.setColor(c2); g.drawLine(dx, dy, dx, dy + dh); dx++; } g2D.setComposite(composite); } g.translate(-thumbBounds.x, -thumbBounds.y); } protected class MyTrackListener extends TrackListener { public void mouseEntered(MouseEvent e) { super.mouseEntered(e); isRollover = true; Rectangle r = getTrackBounds(); scrollbar.repaint(r.x, r.y, r.width, r.height); } public void mouseExited(MouseEvent e) { super.mouseExited(e); isRollover = false; Rectangle r = getTrackBounds(); scrollbar.repaint(r.x, r.y, r.width, r.height); } public void mousePressed(MouseEvent e) { super.mousePressed(e); Rectangle r = getTrackBounds(); scrollbar.repaint(r.x, r.y, r.width, r.height); } public void mouseReleased(MouseEvent e) { super.mouseReleased(e); Rectangle r = getTrackBounds(); scrollbar.repaint(r.x, r.y, r.width, r.height); } } }
package OpenXPKI::Server::Workflow::Validator::PasswordQuality; use strict; use warnings; use base qw( Workflow::Validator ); use Workflow::Exception qw( validation_error ); use OpenXPKI::Server::Context qw( CTX ); use OpenXPKI::Debug; use English; use Data::Password qw(:all); sub _init { my ( $self, $params ) = @_; # set up Data::Password options from validator configuration # file if (exists $params->{DICTIONARY}) { $DICTIONARY = $params->{DICTIONARY}; } if (exists $params->{FOLLOWING}) { $FOLLOWING = $params->{FOLLOWING}; } if (exists $params->{'FOLLOWING_KEYBOARD'}) { $FOLLOWING_KEYBOARD = $params->{'FOLLOWING_KEYBOARD'}; } if (exists $params->{'GROUPS'}) { $GROUPS = $params->{GROUPS}; } if (exists $params->{'MINLEN'}) { $MINLEN = $params->{MINLEN}; } if (exists $params->{MAXLEN}) { $MAXLEN = $params->{MAXLEN}; } if (exists $params->{DICTIONARIES}) { @DICTIONARIES = split(/,/, $params->{DICTIONARIES}); } } sub validate { my ( $self, $wf, $password ) = @_; ## prepare the environment if (my $reason = IsBadPassword($password)) { ##! 16: 'bad password entered: ' . $reason validation_error("<API key><API key>); } return 1; } 1; __END__ =head1 NAME OpenXPKI::Server::Workflow::Validator::PasswordQuality =head1 SYNOPSIS <action name="CreateCSR"> <validator name="PasswordQuality" class="OpenXPKI::Server::Workflow::Validator::PasswordQuality"> <arg value="$_password"/> </validator> </action> =head1 DESCRIPTION This validator checks a password for its quality using the Data::Password module. All configuration that is possible for Data::Password can be done using the validator config file as well. Based on this data, the validator fails if it believes the password to be bad.
FROM %%KOLLA_NAMESPACE%%/%%KOLLA_PREFIX%%ceilometer-base MAINTAINER Kolla Project (https://launchpad.net/kolla) RUN yum install -y <API key> && yum clean all ADD ./start.sh /start.sh CMD ["/start.sh"]
package com.mentor.nucleus.bp.mc.vhdl.source; import org.eclipse.core.resources.IProject; import com.mentor.nucleus.bp.mc.AbstractNature; public class MCNature extends AbstractNature { // The shared instance private static MCNature singleton; /** * identifier of this nature in plugin.xml - (concatenate pluginid.natureid) */ public static final String MC_NATURE_ID = "com.mentor.nucleus.bp.mc.vhdl.source.MCNature"; //NON-NLS-1 /** * identifier of this nature in plugin.xml - (concatenate * pluginid.exportbuilderid) */ public static final String EXPORT_BUILDER_ID = "com.mentor.nucleus.bp.mc.vhdl.source.export_builder"; //NON-NLS-1 public MCNature() { super(Activator.getDefault(), EXPORT_BUILDER_ID); singleton = this; } /** * Returns the shared instance. Creates if it has not yet been created * * @return the shared instance */ public static MCNature getDefault() { if (MCNature.singleton == null) { MCNature.singleton = new MCNature(); } return MCNature.singleton; } @Override public boolean hasNature(IProject project) { return hasNature(project, MC_NATURE_ID); } @Override public boolean addNature(IProject project) { return addNature(project, MC_NATURE_ID); } }
package org.deeplearning4j.arbiter.optimize.generator.genetic; import lombok.Data; /** * Candidates are stored as Chromosome in the population model * * @author Alexandre Boulanger */ @Data public class Chromosome { /** * The fitness score of the genes. */ protected final double fitness; /** * The genes. */ protected final double[] genes; public Chromosome(double[] genes, double fitness) { this.genes = genes; this.fitness = fitness; } }
# coding: utf-8 from __future__ import absolute_import import unittest import datetime import kfp_server_api from kfp_server_api.models.<API key> import ApiRunStorageState # noqa: E501 from kfp_server_api.rest import ApiException class <API key>(unittest.TestCase): """ApiRunStorageState unit test stubs""" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): """Test ApiRunStorageState include_option is a boolean, when False only required params are included, when True both required and optional params are included """ # model = kfp_server_api.models.<API key>.ApiRunStorageState() # noqa: E501 if include_optional : return ApiRunStorageState( ) else : return ApiRunStorageState( ) def <API key>(self): """Test ApiRunStorageState""" inst_req_only = self.make_instance(include_optional=False) <API key> = self.make_instance(include_optional=True) if __name__ == '__main__': unittest.main()
<?php namespace App\Http\Requests\Admin; use Illuminate\Foundation\Http\FormRequest; class MateriaTurmaRequest extends FormRequest { /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'turma_id' => 'required', ]; } /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } }
/** * Socket.io main file */ var iolib = require('socket.io'); var group = require('../models/group'); module.exports = function(server) { var io = iolib.listen(server); io.enable('browser client minification'); io.enable('browser client etag'); //io.set('log level', 1); io.sockets.on('connection', function(socket){ socket.on('join', function(info) { group.checkSecret(info.name, info.secret, function(err) { if (!err) socket.join(info.name); }); }); }); return module.exports.io = io; };
# -*- coding: utf-8 -*- from django.urls import path from search.views import SearchPageView, SearchProjectView urlpatterns = [ path( route='', view=SearchProjectView.as_view(), name='index' ), path( route='pages/', view=SearchPageView.as_view(), name='pages' ), ]
// -*- mode: java; c-basic-offset: 2; -*- package com.google.appinventor.client.editor.simple; import static com.google.appinventor.client.Ode.MESSAGES; import com.google.appinventor.client.editor.ProjectEditor; import com.google.appinventor.client.editor.simple.components.MockForm; import com.google.appinventor.client.editor.simple.palette.SimplePaletteItem; import com.google.appinventor.client.widgets.dnd.DragSource; import com.google.appinventor.client.widgets.dnd.DropTarget; import com.google.appinventor.shared.settings.SettingsConstants; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * Panel in the Simple design editor holding visible Simple components. * */ public final class <API key> extends Composite implements DropTarget { // UI elements private final VerticalPanel phoneScreen; private final CheckBox <API key>; private final CheckBox checkboxPhoneTablet; // A CheckBox for Phone/Tablet preview sizes // Corresponding panel for non-visible components (because we allow users to drop // non-visible components onto the form, but we show them in the non-visible // components panel) private final <API key> <API key>; private final ProjectEditor projectEditor; private MockForm form; /** * Creates new component design panel for visible components. * * @param <API key> corresponding panel for non-visible * components */ public <API key>(final SimpleEditor editor, <API key> <API key>) { this.<API key> = <API key>; projectEditor = editor.getProjectEditor(); // Initialize UI phoneScreen = new VerticalPanel(); phoneScreen.setStylePrimaryName("<API key>"); <API key> = new CheckBox(MESSAGES.<API key>()) { @Override protected void onLoad() { // onLoad is called immediately after a widget becomes attached to the browser's document. boolean <API key> = Boolean.parseBoolean( projectEditor.<API key>( SettingsConstants.<API key>, SettingsConstants.<API key>)); <API key>.setValue(<API key>); } }; <API key>.<API key>(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { boolean isChecked = event.getValue(); // auto-unbox from Boolean to boolean projectEditor.<API key>( SettingsConstants.<API key>, SettingsConstants.<API key>, isChecked ? "True" : "False"); if (form != null) { form.refresh(); } } }); phoneScreen.add(<API key>); checkboxPhoneTablet = new CheckBox(MESSAGES.previewPhoneSize()) { @Override protected void onLoad() { // onLoad is called immediately after a widget becomes attached to the browser's document. boolean showPhoneTablet = Boolean.parseBoolean( projectEditor.<API key>( SettingsConstants.<API key>, SettingsConstants.<API key>)); checkboxPhoneTablet.setValue(showPhoneTablet); <API key>(showPhoneTablet); } }; checkboxPhoneTablet.<API key>(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { boolean isChecked = event.getValue(); // auto-unbox from Boolean to boolean projectEditor.<API key>( SettingsConstants.<API key>, SettingsConstants.<API key>, isChecked ? "True" : "False"); <API key>(isChecked); } }); phoneScreen.add(checkboxPhoneTablet); initWidget(phoneScreen); } private void <API key>(boolean isChecked) { if (form != null){ if (isChecked){ form.changePreviewSize(true); checkboxPhoneTablet.setText(MESSAGES.previewPhoneSize()); } else { form.changePreviewSize(false); checkboxPhoneTablet.setText(MESSAGES.previewTabletSize()); } } } public void <API key>(boolean enable){ if (form != null){ if (!enable){ form.changePreviewSize(false); checkboxPhoneTablet.setText(MESSAGES.previewTabletSize()); checkboxPhoneTablet.setChecked(false); } } checkboxPhoneTablet.setEnabled(enable); } /** * Associates a Simple form component with this panel. * * @param form backing mocked form component */ public void setForm(MockForm form) { this.form = form; phoneScreen.add(form); } // DropTarget implementation // Non-visible components will be forwarded to the non-visible components design panel // as a courtesy. Visible components will be accepted by individual MockContainers. @Override public Widget getDropTargetWidget() { return this; } @Override public boolean onDragEnter(DragSource source, int x, int y) { // Accept palette items for non-visible components only return (source instanceof SimplePaletteItem) && !((SimplePaletteItem) source).isVisibleComponent() && <API key>.onDragEnter(source, -1, -1); } @Override public void onDragContinue(DragSource source, int x, int y) { <API key>.onDragContinue(source, -1, -1); } @Override public void onDragLeave(DragSource source) { <API key>.onDragLeave(source); } @Override public void onDrop(DragSource source, int x, int y, int offsetX, int offsetY) { <API key>.onDrop(source, -1, -1, offsetX, offsetY); } }
/* ## filtering */ define([ 'angular', 'app', 'underscore' ], function (angular, app, _) { 'use strict'; var module = angular.module('kibana.panels.filtering', []); app.useModule(module); module.controller('filtering', function($scope, filterSrv, $rootScope, dashboard) { $scope.panelMeta = { status : "Beta", description : "A controllable list of all filters currently applied to the dashboard. You "+ "almost certainly want one of these on your dashboard somewhere." }; // Set and populate defaults var _d = { }; _.defaults($scope.panel,_d); $scope.init = function() { $scope.filterSrv = filterSrv; }; $scope.remove = function(id) { filterSrv.remove(id); dashboard.refresh(); }; $scope.toggle = function(id) { filterSrv.list[id].active = !filterSrv.list[id].active; dashboard.refresh(); }; $scope.refresh = function() { $rootScope.$broadcast('refresh'); }; $scope.render = function() { $rootScope.$broadcast('render'); }; $scope.show_key = function(key) { return !_.contains(['type','id','alias','mandate','active','editing'],key); }; $scope.isEditable = function(filter) { var uneditable = ['time']; if(_.contains(uneditable,filter.type)) { return false; } else { return true; } }; }); });
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils import numpy as np def glrm_arrests_miss(): missing_ratios = np.arange(0.1, 1, 0.1).tolist() print "Importing USArrests.csv data and saving for validation..." arrests_full = h2o.upload_file(pyunit_utils.locate("smalldata/pca_test/USArrests.csv")) arrests_full.describe() totobs = arrests_full.nrow * arrests_full.ncol train_err = [0]*len(missing_ratios) valid_err = [0]*len(missing_ratios) for i in range(len(missing_ratios)): ratio = missing_ratios[i] print "Importing USArrests.csv and inserting {0}% missing entries".format(100*ratio) arrests_miss = h2o.upload_file(pyunit_utils.locate("smalldata/pca_test/USArrests.csv")) arrests_miss = arrests_miss.<API key>(fraction=ratio) arrests_miss.describe() print "H2O GLRM with {0}% missing entries".format(100*ratio) arrests_glrm = h2o.glrm(x=arrests_miss, validation_frame=arrests_full, k=4, ignore_const_cols=False, loss="Quadratic", regularization_x="None", regularization_y="None", init="PlusPlus", max_iterations=10, min_step_size=1e-6) arrests_glrm.show() # Check imputed data and error metrics glrm_obj = arrests_glrm._model_json['output']['objective'] train_numerr = arrests_glrm._model_json['output']['training_metrics']._metric_json['numerr'] train_caterr = arrests_glrm._model_json['output']['training_metrics']._metric_json['caterr'] valid_numerr = arrests_glrm._model_json['output']['validation_metrics']._metric_json['numerr'] valid_caterr = arrests_glrm._model_json['output']['validation_metrics']._metric_json['caterr'] assert abs(train_numerr - glrm_obj) < 1e-3, "Numeric error on training data was " + str(train_numerr) + " but should equal final objective " + str(glrm_obj) assert train_caterr == 0, "Categorical error on training data was " + str(train_caterr) + " but should be zero" assert valid_caterr == 0, "Categorical error on validation data was " + str(valid_caterr) + " but should be zero" train_numcnt = arrests_glrm._model_json['output']['training_metrics']._metric_json['numcnt'] valid_numcnt = arrests_glrm._model_json['output']['validation_metrics']._metric_json['numcnt'] assert valid_numcnt > train_numcnt, "Number of non-missing numerical entries in training data should be less than validation data" assert valid_numcnt == totobs, "Number of non-missing numerical entries in validation data was " + str(valid_numcnt) + " but should be " + str(totobs) train_err[i] = train_numerr valid_err[i] = valid_numerr h2o.remove(arrests_glrm._model_json['output']['representation_name']) for i in range(len(missing_ratios)): print "Missing ratio: {0}% --> Training error: {1}\tValidation error: {2}".format(missing_ratios[i]*100, train_err[i], valid_err[i]) if __name__ == "__main__": pyunit_utils.standalone_test(glrm_arrests_miss) else: glrm_arrests_miss()
package org.duracloud.common.json; import java.io.IOException; import java.io.StringWriter; import com.fasterxml.jackson.databind.<API key>; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.<API key>; import com.fasterxml.jackson.module.jaxb.<API key>; public class JaxbJsonSerializer<T> { private Class type; private ObjectMapper mapper; /** * Creates a serializer which will work with the defined class type. * * @param type */ public JaxbJsonSerializer(Class<T> type) { this.type = type; // Create mapper mapper = new ObjectMapper(); mapper.enable(<API key>.INDENT_OUTPUT); // Use JAX-B annotations <API key> introspector = new <API key>(); mapper.<API key>() .<API key>(introspector); mapper.<API key>() .<API key>(introspector); } public String serialize(T object) throws IOException { StringWriter writer = new StringWriter(); mapper.writeValue(writer, object); return writer.toString(); } public T deserialize(String json) throws IOException { return (T) mapper.readValue(json, type); } }
package org.sterl.java._14; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; import lombok.Data; class <API key> { @Data final class Foo { String name; } @Test void test() { var ex = assertThrows(<API key>.class, () -> new Foo().getName().toString()); ex.printStackTrace(); } }
import {browser, by, element, ExpectedConditions} from 'protractor'; // This test uses Protractor without Angular, so disable Angular features browser.<API key>(false); // Since we don't have a protractor bazel rule yet, the test is brought up in // parallel with building the service under test. So the timeout must include // compiling the application as well as starting the server. const timeoutMs = 90 * 1000; describe('app', () => { beforeAll(() => { browser.get(''); // Don't run any specs until we see a <div> on the page. browser.wait(ExpectedConditions.presenceOf(element(by.css('div.ts1'))), timeoutMs); browser.wait(ExpectedConditions.presenceOf(element(by.css('div.ts2'))), timeoutMs); browser.wait(ExpectedConditions.presenceOf(element(by.css('div.ts3'))), timeoutMs); }, timeoutMs); it('should display: Hello, TypeScript', async (done) => { const text = await element(by.css('div.ts1')).getText(); expect(text).toEqual(`Hello, TypeScript`); done(); }); it('should display: Hello, genrule', async (done) => { const text = await element(by.css('div.ts2')).getText(); expect(text).toEqual(`Hello, genrule`); done(); }); it('should display: location.host', async (done) => { const currentUrl = await browser.getCurrentUrl(); const text = await element(by.css('div.ts3')).getText(); expect(`http://${text}/`).toEqual(currentUrl); done(); }); });
#ifndef <API key> #define <API key> #include <vector> #include "webrtc/base/optional.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_packet.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_packet/dlrr.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_packet/rrtr.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_packet/target_bitrate.h" #include "webrtc/modules/rtp_rtcp/source/rtcp_packet/voip_metric.h" namespace webrtc { namespace rtcp { class CommonHeader; // From RFC 3611: RTP Control Protocol Extended Reports (RTCP XR). class ExtendedReports : public RtcpPacket { public: static constexpr uint8_t kPacketType = 207; ExtendedReports(); ~ExtendedReports() override; // Parse assumes header is already parsed and validated. bool Parse(const CommonHeader& packet); void SetSenderSsrc(uint32_t ssrc) { sender_ssrc_ = ssrc; } void SetRrtr(const Rrtr& rrtr); void AddDlrrItem(const ReceiveTimeInfo& time_info); void SetVoipMetric(const VoipMetric& voip_metric); void SetTargetBitrate(const TargetBitrate& target_bitrate); uint32_t sender_ssrc() const { return sender_ssrc_; } const rtc::Optional<Rrtr>& rrtr() const { return rrtr_block_; } const Dlrr& dlrr() const { return dlrr_block_; } const rtc::Optional<VoipMetric>& voip_metric() const { return voip_metric_block_; } const rtc::Optional<TargetBitrate>& target_bitrate() const { return target_bitrate_; } size_t BlockLength() const override; bool Create(uint8_t* packet, size_t* index, size_t max_length, RtcpPacket::PacketReadyCallback* callback) const override; private: static constexpr size_t kXrBaseLength = 4; size_t RrtrLength() const { return rrtr_block_ ? Rrtr::kLength : 0; } size_t DlrrLength() const { return dlrr_block_.BlockLength(); } size_t VoipMetricLength() const { return voip_metric_block_ ? VoipMetric::kLength : 0; } size_t TargetBitrateLength() const; void ParseRrtrBlock(const uint8_t* block, uint16_t block_length); void ParseDlrrBlock(const uint8_t* block, uint16_t block_length); void <API key>(const uint8_t* block, uint16_t block_length); void <API key>(const uint8_t* block, uint16_t block_length); uint32_t sender_ssrc_; rtc::Optional<Rrtr> rrtr_block_; Dlrr dlrr_block_; // Dlrr without items treated same as no dlrr block. rtc::Optional<VoipMetric> voip_metric_block_; rtc::Optional<TargetBitrate> target_bitrate_; }; } // namespace rtcp } // namespace webrtc #endif // <API key>
package org.sagebionetworks.web.client.place; import com.google.gwt.place.shared.Place; import com.google.gwt.place.shared.PlaceTokenizer; import com.google.gwt.place.shared.Prefix; public class Help extends Place { private String token; public Help(String token) { this.token = token; } public String toToken() { return token; } @Prefix("!Help") public static class Tokenizer implements PlaceTokenizer<Help> { @Override public String getToken(Help place) { return place.toToken(); } @Override public Help getPlace(String token) { return new Help(token); } } }
#include "search/streets_matcher.hpp" #include "search/features_filter.hpp" #include "search/<API key>.hpp" #include "search/query_params.hpp" #include "indexer/search_string_utils.hpp" #include "base/logging.hpp" #include "base/stl_helpers.hpp" #include <algorithm> using namespace std; namespace search { namespace { bool LessByHashAndRange(StreetsMatcher::Prediction const & lhs, StreetsMatcher::Prediction const & rhs) { if (lhs.m_hash != rhs.m_hash) return lhs.m_hash < rhs.m_hash; if (lhs.GetNumTokens() != rhs.GetNumTokens()) return lhs.GetNumTokens() > rhs.GetNumTokens(); if (lhs.m_tokenRange.Begin() != rhs.m_tokenRange.Begin()) return lhs.m_tokenRange.Begin() < rhs.m_tokenRange.Begin(); if (lhs.m_prob != rhs.m_prob) return lhs.m_prob > rhs.m_prob; if (lhs.m_withMisprints != rhs.m_withMisprints) return rhs.m_withMisprints; return false; } bool <API key>(StreetsMatcher::Prediction const & lhs, StreetsMatcher::Prediction const & rhs) { return lhs.GetNumTokens() == rhs.GetNumTokens() && lhs.m_tokenRange.Begin() == rhs.m_tokenRange.Begin() && lhs.m_hash == rhs.m_hash; } bool <API key>(StreetsMatcher::Prediction const & lhs, StreetsMatcher::Prediction const & rhs) { if (lhs.m_hash != rhs.m_hash) return lhs.m_hash < rhs.m_hash; if (lhs.m_withMisprints != rhs.m_withMisprints) return rhs.m_withMisprints; if (lhs.m_prob != rhs.m_prob) return lhs.m_prob > rhs.m_prob; if (lhs.GetNumTokens() != rhs.GetNumTokens()) return lhs.GetNumTokens() > rhs.GetNumTokens(); return lhs.m_tokenRange.Begin() < rhs.m_tokenRange.Begin(); } bool <API key>(StreetsMatcher::Prediction const & lhs, StreetsMatcher::Prediction const & rhs) { return lhs.m_withMisprints == rhs.m_withMisprints && lhs.m_hash == rhs.m_hash; } void FindStreets(BaseContext const & ctx, FeaturesFilter const & filter, QueryParams const & params, size_t startToken, bool withMisprints, vector<StreetsMatcher::Prediction> & predictions) { // Here we try to match as many tokens as possible while // intersection is a non-empty bit vector of streets. Single // tokens that are synonyms to streets are ignored. Moreover, // each time a token that looks like a beginning of a house number // is met, we try to use current intersection of tokens as a // street layer and try to match BUILDINGs or POIs. CBV streets(ctx.m_streets); CBV all; all.SetFull(); size_t curToken = startToken; // This variable is used for prevention of duplicate calls to // <API key>() with the same // arguments. size_t lastToken = startToken; // When true, no bit vectors were intersected with |streets| at all. bool emptyIntersection = true; // When true, |streets| is in the incomplete state and can't be // used for creation of street layers. bool incomplete = false; auto emit = [&]() { if (streets.IsEmpty() || emptyIntersection || incomplete || lastToken == curToken) return; CBV fs(streets); CBV fa(all); ASSERT(!fs.IsFull(), ()); ASSERT(!fa.IsFull(), ()); if (filter.NeedToFilter(fs)) fs = filter.Filter(fs); if (fs.IsEmpty()) return; if (filter.NeedToFilter(fa)) fa = filter.Filter(fa).Union(fs); predictions.emplace_back(); auto & prediction = predictions.back(); prediction.m_tokenRange = TokenRange(startToken, curToken); ASSERT_NOT_EQUAL(fs.PopCount(), 0, ()); <API key>(fs.PopCount(), fa.PopCount(), ()); prediction.m_prob = static_cast<double>(fs.PopCount()) / static_cast<double>(fa.PopCount()); prediction.m_features = move(fs); prediction.m_hash = prediction.m_features.Hash(); prediction.m_withMisprints = withMisprints; }; StreetTokensFilter streetsFilter( [&](strings::UniString const & /* token */, size_t tag) { auto buffer = streets.Intersect(ctx.m_features[tag].m_features); if (tag < curToken) { // This is the case for delayed // street synonym. Therefore, // |streets| is temporarily in the // incomplete state. streets = buffer; all = all.Intersect(ctx.m_features[tag].m_features); emptyIntersection = false; incomplete = true; return; } ASSERT_EQUAL(tag, curToken, ()); // |streets| will become empty after // the intersection. Therefore we need // to create streets layer right now. if (buffer.IsEmpty()) emit(); streets = buffer; all = all.Intersect(ctx.m_features[tag].m_features); emptyIntersection = false; incomplete = false; }, withMisprints); for (; curToken < ctx.m_numTokens && !ctx.IsTokenUsed(curToken) && !streets.IsEmpty(); ++curToken) { auto const & token = params.GetToken(curToken).GetOriginal(); bool const isPrefix = params.IsPrefixToken(curToken); if (house_numbers::<API key>(token, isPrefix)) emit(); streetsFilter.Put(token, isPrefix, curToken); } emit(); } } // namespace // static void StreetsMatcher::Go(BaseContext const & ctx, FeaturesFilter const & filter, QueryParams const & params, vector<Prediction> & predictions) { size_t const <API key> = 3; double const kTailProbability = 0.05; predictions.clear(); FindStreets(ctx, filter, params, predictions); if (predictions.empty()) return; // Remove predictions with the same m_hash (features) and token range. base::SortUnique(predictions, &LessByHashAndRange, &<API key>); // Leave the most probable and longest prediction for predictions with the same m_hash (features) // and m_withMisprints. // We will still distinguish parses with the same m_hash (features) but different range and // m_withMisprints. For example, for "Paramount dive" we will have two parses: // STREET UNUSED (can be matched to poi later) // Paramount dive // STREET STREET ("drive" with misprints) // Paramount dive // The parses will have the same features and hash but we need both of them. base::SortUnique(predictions, &<API key>, &<API key>); sort(predictions.rbegin(), predictions.rend(), base::LessBy(&Prediction::m_prob)); while (predictions.size() > <API key> && predictions.back().m_prob < kTailProbability) { predictions.pop_back(); } } // static void StreetsMatcher::FindStreets(BaseContext const & ctx, FeaturesFilter const & filter, QueryParams const & params, vector<Prediction> & predictions) { for (size_t startToken = 0; startToken < ctx.m_numTokens; ++startToken) { if (ctx.IsTokenUsed(startToken)) continue; ::search::FindStreets(ctx, filter, params, startToken, false /* withMisprints */, predictions); ::search::FindStreets(ctx, filter, params, startToken, true /* withMisprints */, predictions); } } } // namespace search
#if defined(LEAN_JSON) // Remark: gcc 7 produces a warning at json.hpp // We believe it is a spurious warning #if defined(__GNUC__) && !defined(__CLANG__) #pragma GCC diagnostic ignored "-Wuninitialized" #endif #include <list> #include <string> #include <vector> #include <algorithm> #include <clocale> #include "frontends/lean/module_parser.h" #include "library/<API key>.h" #include "util/lean_path.h" #include "util/sexpr/option_declarations.h" #include "util/timer.h" #include "library/mt_task_queue.h" #include "library/st_task_queue.h" #include "library/attribute_manager.h" #include "library/tactic/tactic_state.h" #include "frontends/lean/parser.h" #include "frontends/lean/info_manager.h" #include "frontends/lean/interactive.h" #include "frontends/lean/completion.h" #include "shell/server.h" namespace lean { struct all_messages_msg { std::vector<message> m_msgs; json to_json_response() const { auto msgs = json::array(); for (auto & msg : m_msgs) msgs.push_back(json_of_message(msg)); json j; j["response"] = "all_messages"; j["msgs"] = msgs; return j; } }; region_of_interest::intersection_result region_of_interest::intersects(location const & loc) const { if (loc.m_file_name.empty()) return InROI; if (!m_open_files || !m_open_files->count(loc.m_file_name)) return NoIntersection; auto & visible_lines = m_open_files->at(loc.m_file_name); bool above_roi = false; for (auto & lr : visible_lines) { if (std::max(lr.m_begin_line, loc.m_range.m_begin.first) <= std::min(lr.m_end_line, loc.m_range.m_end.first)) { return InROI; } if (loc.m_range.m_begin.first <= lr.m_end_line) above_roi = true; } if (above_roi) return AboveROI; return visible_lines.empty() ? OpenFile : VisibleFile; } bool region_of_interest::should_report(location const & loc) const { auto isect = intersects(loc); switch (m_check_mode) { case Nothing: return false; case VisibleLines: return isect >= InROI; case <API key>: case VisibleFiles: return isect >= VisibleFile; case OpenFiles: return isect >= OpenFile; default: return true; } } optional<unsigned> region_of_interest::get_priority(log_tree::node const & n) const { auto isect = intersects(n.get_location()); optional<unsigned> yes(isect >= InROI ? n.get_detail_level() : n.get_detail_level() + log_tree::MaxLevel); optional<unsigned> no; switch (m_check_mode) { case Nothing: return no; case VisibleLines: return (isect >= InROI && n.get_detail_level() < log_tree::<API key>) ? yes : no; case <API key>: return isect >= AboveROI ? yes : no; case VisibleFiles: return isect >= VisibleFile ? yes : no; case OpenFiles: return isect >= OpenFile ? yes : no; default: return yes; } } class server::message_handler { server * m_srv; log_tree * m_lt; mutex m_mutex; std::unordered_set<std::string> m_dirty_files; bool <API key> = false; std::unique_ptr<single_timer> m_timer; public: message_handler(server * srv, log_tree * lt, bool use_timer) : m_srv(srv), m_lt(lt) { if (use_timer) m_timer.reset(new single_timer); } std::vector<message> get_messages_core(region_of_interest const & roi) { std::vector<message> msgs; m_lt->for_each([&] (log_tree::node const & n) { if (roi.should_report(n.get_location())) { for (auto & e : n.get_entries()) { if (auto msg = dynamic_cast<message const *>(e.get())) { if (roi.should_report(msg->get_location())) msgs.push_back(*msg); } } return true; } else { return false; } }); return msgs; } void schedule_refresh() { #if defined(LEAN_MULTI_THREAD) if (m_timer) { <API key> = true; m_timer->set(chrono::steady_clock::now() + chrono::milliseconds(100), [&] { unique_lock<mutex> lock(m_mutex); <API key> = false; m_dirty_files.clear(); auto roi = m_srv->get_roi(); lock.unlock(); m_srv->send_msg(all_messages_msg{get_messages_core(roi)}); }, false); } #endif if (!<API key>) { m_dirty_files.clear(); m_srv->send_msg(all_messages_msg{get_messages_core(m_srv->get_roi())}); } } void on_event(std::vector<log_tree::event> const & events) { unique_lock<mutex> lock(m_mutex); auto roi = m_srv->get_roi(); for (auto & e : events) { switch (e.m_kind) { case log_tree::event::EntryAdded: case log_tree::event::EntryRemoved: if (auto msg = dynamic_cast<message const *>(e.m_entry.get())) { if (roi.should_report(msg->get_location())) { m_dirty_files.insert(msg->get_file_name()); } } break; default: break; } } if (!m_dirty_files.empty()) { schedule_refresh(); } } void on_new_roi() { unique_lock<mutex> lock(m_mutex); schedule_refresh(); } }; struct current_tasks_msg { std::vector<json> m_tasks; optional<json> m_cur_task; bool m_is_running = false; json to_json_response() const { json j; j["response"] = "current_tasks"; j["is_running"] = m_is_running; if (m_cur_task) j["cur_task"] = *m_cur_task; j["tasks"] = m_tasks; return j; } static json json_of_task(log_tree::node const & t) { json j; j["file_name"] = t.get_location().m_file_name; auto pos = t.get_location().m_range.m_begin; j["pos_line"] = pos.first; j["pos_col"] = pos.second; auto end_pos = t.get_location().m_range.m_end; j["end_pos_line"] = end_pos.first; j["end_pos_col"] = end_pos.second; j["desc"] = t.get_description(); return j; } }; class server::tasks_handler { server * m_srv; log_tree * m_lt; mutex m_mutex; std::unique_ptr<single_timer> m_timer; public: tasks_handler(server * srv, log_tree * lt, bool use_timer) : m_srv(srv), m_lt(lt) { if (use_timer) m_timer.reset(new single_timer); } void submit_core(unsigned prio, log_tree::node const & n) { if (auto prod = n.get_producer()) { taskq().submit(prod, prio); } } void resubmit_core() { auto roi = m_srv->get_roi(); m_srv->m_lt.for_each([&] (log_tree::node const & n) { if (auto prio = roi.get_priority(n)) { submit_core(*prio, n); return true; } else { return false; } }); } current_tasks_msg mk_tasks_msg() { current_tasks_msg msg; auto roi = m_srv->get_roi(); m_lt->for_each([&] (log_tree::node const & n) { if (roi.get_priority(n)) { if (n.get_producer()) { msg.m_is_running = true; msg.m_tasks.push_back(current_tasks_msg::json_of_task(n)); return false; } else { return true; } } else { return false; } }); return msg; } void schedule_refresh() { #if defined(LEAN_MULTI_THREAD) if (m_timer) { m_timer->set(chrono::steady_clock::now() + chrono::milliseconds(200), [&] { m_srv->send_msg(mk_tasks_msg()); }, false); } #endif } void on_event(std::vector<log_tree::event> const & events) { optional<region_of_interest> roi; bool need_refresh = false; for (auto & e : events) { switch (e.m_kind) { case log_tree::event::ProducerSet: if (!roi) roi = m_srv->get_roi(); if (auto prio = roi->get_priority(e.m_node)) { submit_core(*prio, e.m_node); need_refresh = true; } break; case log_tree::event::StateChanged: if (!roi) roi = m_srv->get_roi(); if (roi->get_priority(e.m_node)) need_refresh = true; break; default: break; } } if (need_refresh) { unique_lock<mutex> lock(m_mutex); schedule_refresh(); } } void on_new_roi() { resubmit_core(); unique_lock<mutex> lock(m_mutex); schedule_refresh(); } }; server::server(unsigned num_threads, search_path const & path, environment const & initial_env, io_state const & ios) : m_path(path), m_initial_env(initial_env), m_ios(ios) { m_ios.set_regular_channel(std::make_shared<stderr_channel>()); m_ios.<API key>(std::make_shared<stderr_channel>()); m_msg_handler.reset(new message_handler(this, &m_lt, num_threads > 0)); m_tasks_handler.reset(new tasks_handler(this, &m_lt, num_threads > 0)); m_lt.add_listener([&] (std::vector<log_tree::event> const & evs) { m_msg_handler->on_event(evs); m_tasks_handler->on_event(evs); }); scope_global_ios scoped_ios(m_ios); #if defined(LEAN_MULTI_THREAD) if (num_threads == 0) { m_tq.reset(new st_task_queue); } else { m_tq.reset(new mt_task_queue(num_threads)); } #else m_tq.reset(new st_task_queue()); #endif set_task_queue(m_tq.get()); m_mod_mgr.reset(new module_mgr(this, m_lt.get_root(), m_path, m_initial_env, m_ios)); m_mod_mgr->set_server_mode(true); m_mod_mgr->set_save_olean(false); } server::~server() { m_mod_mgr->cancel_all(); cancel(m_bg_task_ctok); m_tq->evacuate(); } struct server::cmd_req { unsigned m_seq_num = static_cast<unsigned>(-1); std::string m_cmd_name; json m_payload; }; struct server::cmd_res { cmd_res() {} cmd_res(unsigned seq_num, json const & payload) : m_seq_num(seq_num), m_payload(payload) {} cmd_res(unsigned seq_num, std::string const & error_msg) : m_seq_num(seq_num), m_error_msg(error_msg) {} unsigned m_seq_num = static_cast<unsigned>(-1); json m_payload; optional<std::string> m_error_msg; json to_json_response() const { json j; if (m_error_msg) { j["response"] = "error"; j["message"] = *m_error_msg; } else { j = m_payload; j["response"] = "ok"; } j["seq_num"] = m_seq_num; return j; } }; struct unrelated_error_msg { std::string m_msg; json to_json_response() const { json j; j["response"] = "error"; j["message"] = m_msg; return j; } }; // Debugging functions for use in GDB. server * g_server = nullptr; void <API key>() { g_server->get_log_tree().print_to(std::cerr); } void server_print_roi() { auto roi = g_server->get_roi(); std::cerr << "mode: " << roi.m_check_mode << std::endl; for (auto & f : *roi.m_open_files) { std::cerr << f.first << std::endl; for (auto & lr : f.second) { std::cerr << " " << lr.m_begin_line << "-" << lr.m_end_line << std::endl; } } } void server::run() { flet<server *> _(g_server, this); scope_global_ios scoped_ios(m_ios); /* Leo: we use std::setlocale to make sure decimal period is displayed as ".". We added this hack because the json library code used for ensuring this property was crashing when compiling Lean on Windows with mingw. */ #if !defined(LEAN_EMSCRIPTEN) std::setlocale(LC_NUMERIC, "C"); #endif while (true) { try { std::string req_string; std::getline(std::cin, req_string); if (std::cin.eof()) return; json req = json::parse(req_string); handle_request(req); } catch (std::exception & ex) { send_msg(unrelated_error_msg{ex.what()}); } } } void server::handle_request(json const & jreq) { cmd_req req; req.m_seq_num = jreq.at("seq_num"); try { req.m_cmd_name = jreq.at("command"); req.m_payload = jreq; handle_request(req); } catch (std::exception & ex) { send_msg(cmd_res(req.m_seq_num, std::string(ex.what()))); } catch (interrupted) { send_msg(cmd_res(req.m_seq_num, std::string("interrupted"))); } catch (...) { send_msg(cmd_res(req.m_seq_num, std::string("unknown exception"))); } } void server::handle_request(server::cmd_req const & req) { std::string command = req.m_cmd_name; if (command == "sync") { send_msg(handle_sync(req)); } else if (command == "complete") { <API key>(req, handle_complete(req)); } else if (command == "info") { <API key>(req, handle_info(req)); } else if (command == "hole") { <API key>(req, handle_hole(req)); } else if (command == "hole_commands") { send_msg(<API key>(req)); } else if (command == "all_hole_commands") { send_msg(<API key>(req)); } else if (command == "search") { send_msg(handle_search(req)); } else if (command == "roi") { send_msg(handle_roi(req)); } else if (command == "sleep") { chrono::milliseconds small_delay(1000); this_thread::sleep_for(small_delay); } else if (command == "long_sleep") { chrono::milliseconds small_delay(10000); this_thread::sleep_for(small_delay); } else { send_msg(cmd_res(req.m_seq_num, std::string("unknown command"))); } } void server::<API key>(server::cmd_req const & req, task<cmd_res> const & res) { taskq().submit(task_builder<unit>([this, req, res] { try { auto msg = get(res); msg.m_seq_num = req.m_seq_num; send_msg(msg); } catch (throwable & ex) { send_msg(cmd_res(req.m_seq_num, std::string(ex.what()))); } catch (interrupted) { send_msg(cmd_res(req.m_seq_num, std::string("interrupted"))); } catch (...) { send_msg(cmd_res(req.m_seq_num, std::string("unknown exception"))); } return unit{}; }).depends_on(res).build()); } server::cmd_res server::handle_sync(server::cmd_req const & req) { std::string new_file_name = req.m_payload.at("file_name"); std::string new_content = req.m_payload.at("content"); auto mtime = time(nullptr); bool needs_invalidation = true; auto & ef = m_open_files[new_file_name]; if (ef.m_content != new_content) { ef.m_content = new_content; ef.m_mtime = mtime; needs_invalidation = true; } else { needs_invalidation = false; } json res; if (needs_invalidation) { m_mod_mgr->invalidate(new_file_name); res["message"] = "file invalidated"; } else { res["message"] = "file unchanged"; } return { req.m_seq_num, res }; } optional<<API key>> <API key>(std::shared_ptr<module_info const> const & mod_info, pos_info p) { auto res = mod_info->m_snapshots; while (res && res->m_next) { if (auto next = peek(res->m_next)) { if (next->m_range.m_end < p) { res = next; } else { break; } } else { break; } } return res; } void <API key>(module_id const & mod_id, std::shared_ptr<module_info const> mod_info, pos_info pos, bool complete = false) { if (auto snap = <API key>(mod_info, pos)) { // ignore messages from reparsing log_tree null; scope_log_tree scope_lt(null.get_root()); snap->m_lt = logtree(); snap->m_cancel = <API key>(); snap->m_next = nullptr; auto p = std::make_shared<module_parser>(mod_id, *mod_info->m_lean_contents, environment(), mk_dummy_loader()); p->save_info(false); p->use_separate_tasks(false); p->break_at_pos(pos, complete); p->resume(*snap, {}); } } json server::autocomplete(std::shared_ptr<module_info const> const & mod_info, bool skip_completions, pos_info const & pos0) { auto pos = pos0; if (pos.second == 0) pos.first pos.second json j; if (auto snap = <API key>(mod_info, pos)) { try { <API key>(mod_info->m_mod, mod_info, pos, true); } catch (<API key> & e) { report_completions(snap->m_snapshot_at_end->m_env, snap->m_snapshot_at_end->m_options, pos0, skip_completions, m_path, mod_info->m_mod.c_str(), e, j); } catch (throwable & ex) {} } return j; } task<server::cmd_res> server::handle_complete(cmd_req const & req) { cancel(m_bg_task_ctok); m_bg_task_ctok = <API key>(); std::string fn = req.m_payload.at("file_name"); pos_info pos = {req.m_payload.at("line"), req.m_payload.at("column")}; bool skip_completions = false; if (req.m_payload.count("skip_completions")) skip_completions = req.m_payload.at("skip_completions"); auto mod_info = m_mod_mgr->get_module(fn); return task_builder<cmd_res>([=] { return cmd_res(req.m_seq_num, autocomplete(mod_info, skip_completions, pos)); }) .wrap(library_scopes(log_tree::node())) .<API key>(m_bg_task_ctok) .build(); } static void get_info_managers(log_tree::node const & n, std::vector<info_manager> & infoms) { n.for_each([&] (log_tree::node const & c) { for (auto & e : c.get_entries()) { if (auto infom = dynamic_cast<info_manager const *>(e.get())) { infoms.push_back(*infom); } } return true; }); } std::vector<info_manager> get_info_managers(log_tree const & t) { std::vector<info_manager> infoms; get_info_managers(t.get_root(), infoms); return infoms; } json server::info(std::shared_ptr<module_info const> const & mod_info, pos_info const & pos) { json j; try { <API key>(mod_info->m_mod, mod_info, pos); } catch (<API key> & e) { auto opts = m_ios.get_options(); auto env = m_initial_env; if (auto snap = <API key>(mod_info, e.m_token_info.m_pos)) { env = snap->m_snapshot_at_end->m_env; opts = snap->m_snapshot_at_end->m_options; } report_info(env, opts, m_ios, m_path, *mod_info, get_info_managers(m_lt), pos, e, j); } catch (throwable & ex) {} return j; } task<server::cmd_res> server::handle_info(server::cmd_req const & req) { cancel(m_bg_task_ctok); m_bg_task_ctok = <API key>(); std::string fn = req.m_payload.at("file_name"); pos_info pos = {req.m_payload.at("line"), req.m_payload.at("column")}; auto mod_info = m_mod_mgr->get_module(fn); return task_builder<cmd_res>([=] { return cmd_res(req.m_seq_num, info(mod_info, pos)); }).wrap(library_scopes(log_tree::node())) .<API key>(m_bg_task_ctok).build(); } json server::hole_command(std::shared_ptr<module_info const> const & mod_info, std::string const & action, pos_info const & pos) { json j; std::vector<info_manager> im = get_info_managers(m_lt); <API key>(*mod_info, im, pos, action, j); return j; } task<server::cmd_res> server::handle_hole(cmd_req const & req) { auto ctok = <API key>(); std::string action = req.m_payload.at("action"); std::string fn = req.m_payload.at("file_name"); pos_info pos = {req.m_payload.at("line"), req.m_payload.at("column")}; auto mod_info = m_mod_mgr->get_module(fn); return task_builder<cmd_res>([=] { return cmd_res(req.m_seq_num, hole_command(mod_info, action, pos)); }) .wrap(library_scopes(log_tree::node())) .<API key>(ctok) .build(); } server::cmd_res server::<API key>(server::cmd_req const & req) { std::string fn = req.m_payload.at("file_name"); pos_info pos = {req.m_payload.at("line"), req.m_payload.at("column")}; auto mod_info = m_mod_mgr->get_module(fn); std::vector<info_manager> im = get_info_managers(m_lt); json j; get_hole_commands(*mod_info, im, pos, j); return cmd_res(req.m_seq_num, j); } server::cmd_res server::<API key>(server::cmd_req const & req) { std::string fn = req.m_payload.at("file_name"); auto mod_info = m_mod_mgr->get_module(fn); std::vector<info_manager> im = get_info_managers(m_lt); json j; <API key>(*mod_info, im, j); return cmd_res(req.m_seq_num, j); } server::cmd_res server::handle_search(server::cmd_req const & req) { std::string query = req.m_payload.at("query"); std::vector<pair<std::string, environment>> envs_to_search; for (auto & mod : m_mod_mgr->get_all_modules()) { envs_to_search.emplace_back(mod->m_mod, mod->get_latest_env()); } std::vector<json> results; search_decls(query, envs_to_search, m_ios.get_options(), results); json j; j["results"] = results; return cmd_res(req.m_seq_num, j); } std::tuple<std::string, module_src, time_t> server::load_module(module_id const & id, bool can_use_olean) { if (m_open_files.count(id)) { auto & ef = m_open_files[id]; return std::make_tuple(ef.m_content, module_src::LEAN, ef.m_mtime); } return m_fs_vfs.load_module(id, can_use_olean); } template <class Msg> void server::send_msg(Msg const & m) { json j = m.to_json_response(); unique_lock<mutex> _(m_out_mutex); std::cout << j << std::endl; } region_of_interest server::get_roi() { unique_lock<mutex> _(m_roi_mutex); return m_roi; } static region_of_interest::checking_mode parse_checking_mode(std::string const & j) { if (j == "nothing") return region_of_interest::Nothing; if (j == "visible-lines") return region_of_interest::VisibleLines; if (j == "<API key>") return region_of_interest::<API key>; if (j == "visible-files") return region_of_interest::VisibleFiles; if (j == "open-files") return region_of_interest::OpenFiles; throw exception(sstream() << "unknown checking mode: " << j); } server::cmd_res server::handle_roi(server::cmd_req const & req) { region_of_interest new_roi; new_roi.m_check_mode = parse_checking_mode(req.m_payload.at("mode")); auto open_files = std::make_shared<std::unordered_map<std::string, std::vector<line_range>>>(); new_roi.m_open_files = open_files; for (auto & f : req.m_payload.at("files")) { std::string fn = f.at("file_name"); std::vector<line_range> ranges; for (auto & r : f.at("ranges")) { unsigned begin_line = r.at("begin_line"); unsigned end_line = r.at("end_line"); ranges.push_back({begin_line, end_line}); } (*open_files)[fn] = ranges; } for (auto & f : *new_roi.m_open_files) { try { m_mod_mgr->get_module(f.first); } catch (...) {} } { unique_lock<mutex> _(m_roi_mutex); m_roi = new_roi; } m_tasks_handler->on_new_roi(); m_msg_handler->on_new_roi(); return cmd_res(req.m_seq_num, json()); } void initialize_server() { } void finalize_server() { } } #endif
package nginx import ( "encoding/json" "reflect" ) // Node models a k8s worker node's id and addresses type Node struct { Name string Hostname string ExternalIP string InternalIP string Active bool } func (n Node) String() string { j, err := json.Marshal(n) if err != nil { return string("cant't marshal: " + reflect.TypeOf(n).String() + ", to json string, err: " + err.Error()) } return string(j) }
/** * Automatically generated file. DO NOT MODIFY */ package com.example.android.mediarecorder; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "com.example.android.mediarecorder"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = 1; public static final String VERSION_NAME = ""; }
#include "modsecurity/collection/collections.h" #ifdef __cplusplus #include <string> #include <iostream> #include <unordered_map> #include <list> #include <vector> #endif #include "modsecurity/variable_value.h" #include "modsecurity/collection/collection.h" #include "src/collection/backend/<API key>.h" #include "src/utils/string.h" namespace modsecurity { namespace collection { Collections::Collections(Collection *global, Collection *ip, Collection *session, Collection *user, Collection *resource) : <API key>(""), m_ip_collection_key(""), <API key>(""), <API key>(""), <API key>(""), m_global_collection(global), m_ip_collection(ip), <API key>(session), m_user_collection(user), <API key>(resource), m_tx_collection(new backend::InMemoryPerProcess("TX")) { } Collections::~Collections() { delete m_tx_collection; } } // namespace collection } // namespace modsecurity
package net.bytebuddy.utility; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.description.type.TypeList; import org.objectweb.asm.Opcodes; import java.io.Serializable; import java.lang.reflect.AccessibleObject; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.Member; /** * Representations of Java types that do not exist in Java 6 but that have a special meaning to the JVM. */ public enum JavaType { /** * The Java 7 {@code java.lang.invoke.MethodHandle} type. */ METHOD_HANDLE("java.lang.invoke.MethodHandle", Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, Object.class), /** * The Java 7 {@code java.lang.invoke.MethodHandles} type. */ METHOD_HANDLES("java.lang.invoke.MethodHandles", Opcodes.ACC_PUBLIC, Object.class), /** * The Java 7 {@code java.lang.invoke.MethodType} type. */ METHOD_TYPE("java.lang.invoke.MethodType", Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, Object.class, Serializable.class), /** * The Java 7 {@code java.lang.invoke.MethodTypes.Lookup} type. */ <API key>("java.lang.invoke.MethodHandles$Lookup", Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, Object.class), /** * The Java 7 {@code java.lang.invoke.CallSite} type. */ CALL_SITE("java.lang.invoke.CallSite", Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, Object.class), /** * The Java 9 {@code java.lang.invoke.VarHandle} type. */ VAR_HANDLE("java.lang.invoke.VarHandle", Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, Object.class), /** * The Java 8 {@code java.lang.reflect.Parameter} type. */ PARAMETER("java.lang.reflect.Parameter", Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, Object.class, AnnotatedElement.class), /** * The {@code java.lang.reflect.Executable} type. */ EXECUTABLE("java.lang.reflect.Executable", Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, AccessibleObject.class, Member.class, GenericDeclaration.class), /** * The {@code java.lang.Module} type. */ MODULE("java.lang.Module", Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, Object.class, AnnotatedElement.class); /** * The type description to represent this type which is either a loaded type or a stub. */ private final TypeDescription typeDescription; /** * Creates a new java type representation. * * @param typeName The binary name of this type. * @param modifiers The modifiers of this type when creating a stub. * @param superClass The super class of this type when creating a stub. * @param interfaces The interfaces of this type when creating a stub. */ JavaType(String typeName, int modifiers, Class<?> superClass, Class<?>... interfaces) { TypeDescription typeDescription; try { typeDescription = TypeDescription.ForLoadedType.of(Class.forName(typeName)); } catch (Exception ignored) { typeDescription = new TypeDescription.Latent(typeName, modifiers, TypeDescription.Generic.OfNonGenericType.ForLoadedType.of(superClass), new TypeList.Generic.ForLoadedTypes(interfaces)); } this.typeDescription = typeDescription; } /** * Returns at least a stub representing this type where the stub does not define any methods or fields. If a type exists for * the current runtime, a loaded type representation is returned. * * @return A type description for this Java type. */ public TypeDescription getTypeStub() { return typeDescription; } /** * Loads the class that is represented by this Java type. * * @return A loaded type of this Java type. * @throws <API key> If the represented type cannot be loaded. */ public Class<?> load() throws <API key> { return Class.forName(typeDescription.getName()); } }
"""Versioned singleton entity with global application configuration. Example usage: from components.datastore_utils import config class MyConfig(config.GlobalConfig): param1 = ndb.StringProperty() param2 = ndb.StringProperty() def do_stuff(): param1 = MyConfig.cached().param1 param2 = MyConfig.cached().param2 def modify(): conf = MyConfig.fetch() conf.modify(updated_by='user:abc@example.com', param1='123') Advantages over regular ndb.Entity with predefined key: 1. All changes are logged (see datastore_utils.store_new_version). 2. In-memory process-wide cache. """ # Pylint fails to recognize that ndb.Model.key is defined in ndb.Model. # pylint: disable=<API key> import datetime import threading from google.appengine.ext import ndb from components import datastore_utils from components import utils class GlobalConfig(ndb.Model): """Singleton entity with the global configuration of the service. All changes are stored in the revision log. """ # When this revision of configuration was created. updated_ts = ndb.DateTimeProperty(indexed=False, auto_now_add=True) # Who created this revision of configuration (as identity string). updated_by = ndb.StringProperty(indexed=False, default='') @classmethod def cached_async(cls): """Fetches config entry from local cache or datastore. Bootstraps it if missing. May return slightly stale data but in most cases doesn't do any RPCs. Should be used for read-only access to config. """ # Build new class-specific fetcher function with cache on the fly on # the first attempt (it's not a big deal if it happens concurrently in MT # environment, last one wins). Same can be achieved with metaclasses, but no # one likes metaclasses. if not cls.<API key>: @ndb.tasklet def fetcher(): with fetcher.cache_lock: expiry = fetcher.cache_expiry if expiry is not None and utils.utcnow() < expiry: raise ndb.Return(fetcher.cache_value) # Do not lock while yielding, it would cause deadlock. # Also do not cache a future, it might cross ndb context boundary. # If there is no cached value, multiple concurrent requests will make # multiple RPCs, but as soon as one of them updates cache, subsequent # requests will use the cached value, for a minute. conf = yield cls.fetch_async() if not conf: conf = cls() conf.set_defaults() yield conf.store_async(updated_by='') with fetcher.cache_lock: fetcher.cache_expiry = utils.utcnow() + datetime.timedelta(minutes=1) fetcher.cache_value = conf raise ndb.Return(conf) fetcher.cache_lock = threading.Lock() fetcher.cache_expiry = None fetcher.cache_value = None cls.<API key> = staticmethod(fetcher) return cls.<API key>() cached = utils.sync_of(cached_async) @classmethod def clear_cache(cls): """Clears the cache of .cached(). So the next call to .cached() returns the fresh instance from ndb. """ if cls.<API key>: cls.<API key>.cache_expiry = None @classmethod def fetch_async(cls): """Returns the current up-to-date version of the config entity. Always fetches it from datastore. May return None if missing. """ return datastore_utils.<API key>( cls, cls._get_root_key()) fetch = utils.sync_of(fetch_async) def store_async(self, updated_by): """Stores a new version of the config entity.""" # Create an incomplete key, to be completed by 'store_new_version'. self.key = ndb.Key(self.__class__, None, parent=self._get_root_key()) self.updated_by = updated_by self.updated_ts = utils.utcnow() return datastore_utils.<API key>(self, self._get_root_model()) store = utils.sync_of(store_async) def modify(self, updated_by, **kwargs): """Applies |kwargs| dict to the entity and stores the entity if changed.""" dirty = False for k, v in kwargs.items(): assert k in self._properties, k if getattr(self, k) != v: setattr(self, k, v) dirty = True if dirty: self.store(updated_by) return dirty def set_defaults(self): """Fills in default values for empty config. Implemented by subclasses.""" Private stuff. <API key> = None @classmethod def _get_root_model(cls): return datastore_utils.<API key>('%sRoot' % cls.__name__) @classmethod def _get_root_key(cls): return ndb.Key(cls._get_root_model(), 1)
// Toon Knapen, Karl Meerbergen, Kresimir Fresl, // Thomas Klimpel and Rutger ter Borg // THIS FILE IS AUTOMATICALLY GENERATED // PLEASE DO NOT EDIT! #ifndef <API key> #define <API key> #include <boost/assert.hpp> #include <boost/numeric/bindings/begin.hpp> #include <boost/numeric/bindings/has_linear_array.hpp> #include <boost/numeric/bindings/is_mutable.hpp> #include <boost/numeric/bindings/remove_imaginary.hpp> #include <boost/numeric/bindings/size.hpp> #include <boost/numeric/bindings/stride.hpp> #include <boost/numeric/bindings/value_type.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/type_traits/remove_const.hpp> // The BLAS-backend is selected by defining a pre-processor variable, // which can be one of // * for CBLAS, define <API key> // * for CUBLAS, define <API key> // * netlib-compatible BLAS is the default #if defined <API key> #include <boost/numeric/bindings/blas/detail/cblas.h> #include <boost/numeric/bindings/blas/detail/cblas_option.hpp> #elif defined <API key> #include <boost/numeric/bindings/blas/detail/cublas.h> #include <boost/numeric/bindings/blas/detail/blas_option.hpp> #else #include <boost/numeric/bindings/blas/detail/blas.h> #include <boost/numeric/bindings/blas/detail/blas_option.hpp> #endif namespace boost { namespace numeric { namespace bindings { namespace blas { // The detail namespace contains <API key> functions that // dispatch to the appropriate back-end BLAS-routine. namespace detail { #if defined <API key> // Overloaded function for dispatching to // * CBLAS backend, and // * float value-type. inline void axpy( const int n, const float a, const float* x, const int incx, float* y, const int incy ) { cblas_saxpy( n, a, x, incx, y, incy ); } // Overloaded function for dispatching to // * CBLAS backend, and // * double value-type. inline void axpy( const int n, const double a, const double* x, const int incx, double* y, const int incy ) { cblas_daxpy( n, a, x, incx, y, incy ); } // Overloaded function for dispatching to // * CBLAS backend, and // * complex<float> value-type. inline void axpy( const int n, const std::complex<float> a, const std::complex<float>* x, const int incx, std::complex<float>* y, const int incy ) { cblas_caxpy( n, &a, x, incx, y, incy ); } // Overloaded function for dispatching to // * CBLAS backend, and // * complex<double> value-type. inline void axpy( const int n, const std::complex<double> a, const std::complex<double>* x, const int incx, std::complex<double>* y, const int incy ) { cblas_zaxpy( n, &a, x, incx, y, incy ); } #elif defined <API key> // Overloaded function for dispatching to // * CUBLAS backend, and // * float value-type. inline void axpy( const int n, const float a, const float* x, const int incx, float* y, const int incy ) { cublasSaxpy( n, a, x, incx, y, incy ); } // Overloaded function for dispatching to // * CUBLAS backend, and // * double value-type. inline void axpy( const int n, const double a, const double* x, const int incx, double* y, const int incy ) { cublasDaxpy( n, a, x, incx, y, incy ); } // Overloaded function for dispatching to // * CUBLAS backend, and // * complex<float> value-type. inline void axpy( const int n, const std::complex<float> a, const std::complex<float>* x, const int incx, std::complex<float>* y, const int incy ) { cublasCaxpy( n, a, x, incx, y, incy ); } // Overloaded function for dispatching to // * CUBLAS backend, and // * complex<double> value-type. inline void axpy( const int n, const std::complex<double> a, const std::complex<double>* x, const int incx, std::complex<double>* y, const int incy ) { cublasZaxpy( n, a, x, incx, y, incy ); } #else // Overloaded function for dispatching to // * netlib-compatible BLAS backend (the default), and // * float value-type. inline void axpy( const fortran_int_t n, const float a, const float* x, const fortran_int_t incx, float* y, const fortran_int_t incy ) { BLAS_SAXPY( &n, &a, x, &incx, y, &incy ); } // Overloaded function for dispatching to // * netlib-compatible BLAS backend (the default), and // * double value-type. inline void axpy( const fortran_int_t n, const double a, const double* x, const fortran_int_t incx, double* y, const fortran_int_t incy ) { BLAS_DAXPY( &n, &a, x, &incx, y, &incy ); } // Overloaded function for dispatching to // * netlib-compatible BLAS backend (the default), and // * complex<float> value-type. inline void axpy( const fortran_int_t n, const std::complex<float> a, const std::complex<float>* x, const fortran_int_t incx, std::complex<float>* y, const fortran_int_t incy ) { BLAS_CAXPY( &n, &a, x, &incx, y, &incy ); } // Overloaded function for dispatching to // * netlib-compatible BLAS backend (the default), and // * complex<double> value-type. inline void axpy( const fortran_int_t n, const std::complex<double> a, const std::complex<double>* x, const fortran_int_t incx, std::complex<double>* y, const fortran_int_t incy ) { BLAS_ZAXPY( &n, &a, x, &incx, y, &incy ); } #endif } // namespace detail // Value-type based template class. Use this class if you need a type // for dispatching to axpy. template< typename Value > struct axpy_impl { typedef Value value_type; typedef typename remove_imaginary< Value >::type real_type; typedef void result_type; // Static member function that // * Deduces the required arguments for dispatching to BLAS, and // * Asserts that most arguments make sense. template< typename VectorX, typename VectorY > static result_type invoke( const value_type a, const VectorX& x, VectorY& y ) { namespace bindings = ::boost::numeric::bindings; BOOST_STATIC_ASSERT( (is_same< typename remove_const< typename bindings::value_type< VectorX >::type >::type, typename remove_const< typename bindings::value_type< VectorY >::type >::type >::value) ); BOOST_STATIC_ASSERT( (bindings::has_linear_array< VectorX >::value) ); BOOST_STATIC_ASSERT( (bindings::has_linear_array< VectorY >::value) ); BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorY >::value) ); detail::axpy( bindings::size(x), a, bindings::begin_value(x), bindings::stride(x), bindings::begin_value(y), bindings::stride(y) ); } }; // Functions for direct use. These functions are overloaded for temporaries, // so that wrapped types can still be passed and used for write-access. Calls // to these functions are passed to the axpy_impl classes. In the // documentation, the const-overloads are collapsed to avoid a large number of // prototypes which are very similar. // Overloaded function for axpy. Its overload differs for template< typename VectorX, typename VectorY > inline typename axpy_impl< typename bindings::value_type< VectorX >::type >::result_type axpy( const typename bindings::value_type< VectorX >::type a, const VectorX& x, VectorY& y ) { axpy_impl< typename bindings::value_type< VectorX >::type >::invoke( a, x, y ); } } // namespace blas } // namespace bindings } // namespace numeric } // namespace boost #endif
# 4.1.1.4 Expose REST back-end as a SOAP service using proxy service ## Business use case narrative ![Expose REST back-end as a SOAP service using proxy service](images/4.1.1.<API key>.png) In this scenario, REST back-end is exposed as a SOAP service to SOAP client by placing WSO2 EI in the middle with a proxy service. WSO2 ESB forwards messages to the back-end by transforming the message from SOAP to relevant format by using it's message transformation capabilities. Most popular message transformations for such scenarios are: * SOAP to POX message transformation * SOAP to JSON message transformation To develop this scenario, users can use the "Custom proxy" template available in WSO2 Enterprise Integrator Tooling and create the mediation logic to transform the message to relevant format by using built-in mediators. ## When to use When required to expose REST API as a SOAP service. ## Sample use-case Prerequisites How to try-out sample use-case ## Supported versions This is supported in all the EI and ESB versions ## Pre-requisites ## Development guidelines ## REST API (if available) ## Deployment guidelines Standard way of deploying a proxy service is by packaging the proxy service as a Carbon Application. Please refer [Creating a Proxy Service](https://docs.wso2.com/display/EI640/Creating+a+Proxy+Service) for instructions. ## Reference [Creating a Proxy Service](https://docs.wso2.com/display/EI640/Creating+a+Proxy+Service) ## Test cases | ID | Summary | | | 4.1.1.4.1 | Expose JSON REST back-end as SOAP service | | 4.1.1.4.2 | Expose POX REST back-end as SOAP service | | 4.1.1.4.3 | Change HTTP method when invoking the REST back-end |
package org.onesocialweb.openfire.model.vcard4; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.onesocialweb.model.acl.AclRule; import org.onesocialweb.model.vcard4.TelField; import org.onesocialweb.openfire.model.acl.PersistentAclRule; @Entity(name="TelField") public class PersistentTelField extends TelField{ @OneToMany(cascade=CascadeType.ALL, targetEntity=PersistentAclRule.class, fetch=FetchType.EAGER) private List<AclRule> rules = new ArrayList<AclRule>(); @Enumerated(EnumType.ORDINAL) private TelField.Type type = TelField.Type.VOICE; @Basic private String tel; @Override public String getNumber() { return tel; } @Override public void setNumber(String tel, Type type) { this.tel = tel; this.type=type; } public Type getType() { return this.type; } @Override public void addAclRule(AclRule rule) { rules.add(rule); } @Override public List<AclRule> getAclRules() { return Collections.unmodifiableList(rules); } @Override public void removeAclRule(AclRule rule) { rules.remove(rule); } @Override public void setAclRules(List<AclRule> rules) { this.rules = rules; } @Override public boolean hasAclRules() { if (rules != null && rules.size() > 0) { return true; } return false; } }
<html dir="LTR"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" /> <title>MultiSegmentReader.GetSubReaders Method</title> <xml> </xml> <link rel="stylesheet" type="text/css" href="MSDN.css" /> </head> <body id="bodyID" class="dtBODY"> <div id="nsbanner"> <div id="bannerrow1"> <table class="bannerparthead" cellspacing="0"> <tr id="hdr"> <td class="runninghead">Apache Lucene.Net 2.4.0 Class Library API</td> <td class="product"> </td> </tr> </table> </div> <div id="TitleRow"> <h1 class="dtH1">MultiSegmentReader.GetSubReaders Method </h1> </div> </div> <div id="nstext"> <p> </p> <div class="syntax">public virtual <a href="Lucene.Net.Index.SegmentReader.html">SegmentReader[]</a> GetSubReaders();</div> <h4 class="dtH4">See Also</h4> <p> <a href="Lucene.Net.Index.MultiSegmentReader.html">MultiSegmentReader Class</a> | <a href="Lucene.Net.Index.html">Lucene.Net.Index Namespace</a></p> <object type="application/x-oleobject" classid="clsid:<API key>" viewastext="true" style="display: none;"> <param name="Keyword" value="GetSubReaders method"> </param> <param name="Keyword" value="GetSubReaders method, MultiSegmentReader class"> </param> <param name="Keyword" value="MultiSegmentReader.GetSubReaders method"> </param> </object> <hr /> <div id="footer"> <p> </p> <p>Generated from assembly Lucene.Net [2.4.0.2]</p> </div> </div> </body> </html>
package com.dtodorov.androlib.services; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import java.util.HashMap; import java.util.Map; public class PermissionService implements IPermissionListener, IPermissionService { private Map<String, String> _explanations; private <API key> _requester; private IDialogPresenter _dialogPresenter; public PermissionService(<API key> requester, IDialogPresenter dialogPresenter) { _requester = requester; _dialogPresenter = dialogPresenter; _explanations = new HashMap<String, String>(); _requester.setListener(this); } @Override public void obtainPermission(String permission, String explanation) { _explanations.put(permission, explanation); _requester.obtainPermission(permission); } @Override public void <API key>(String permission, String explanation) { if(isPermissionGranted(permission) == false) { this.obtainPermission(permission, explanation); } } @Override public boolean isPermissionGranted(String permission) { return this.getPermissionStatus(permission) == IPermissionService.Status.Granted; } @Override public Status getPermissionStatus(String permission) { if(_requester.checkPermission(permission) == PackageManager.PERMISSION_GRANTED) { return Status.Granted; } else { return Status.Denied; } } @Override public void explainPermission(String permission) { AsyncTask<String, Void, Void> task = new AsyncTask<String, Void, Void>() { @Override protected Void doInBackground(String... params) { final String permission = params[0]; final String explanation = params[1]; _dialogPresenter.presentDialog(explanation, new IDialogListener() { @Override public void onOk() { _requester.obtainPermission(permission); } @Override public void onCancel() { } }); return null; } }; task.execute(permission, _explanations.get(permission)); } @Override public void onGranted(String permission) { } @Override public void onDenied(String permission) { } @Override public void onCancelled(String permission) { } }
package com.opengamma.strata.math.impl.statistics.distribution; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import org.apache.commons.math3.random.Well44497b; import org.testng.annotations.Test; /** * Test. */ @Test public class <API key> extends <API key> { private static final Well44497b RANDOM = new Well44497b(0L); private static final double[] X = new double[] {0.32492, 0.270722, 0.717558, 1.372184, 1.36343, 1.770933, 2.13145, 2.55238, 2.80734, 3.6896}; private static final double[] DOF = new double[] {1, 4, 6, 10, 11, 13, 15, 18, 23, 27 }; private static final double[] P = new double[] {0.6, 0.6, 0.75, 0.9, 0.9, 0.95, 0.975, 0.99, 0.995, 0.9995 }; @Test(expectedExceptions = <API key>.class) public void testNegativeDOF1() { new <API key>(-2); } @Test(expectedExceptions = <API key>.class) public void testNegativeDOF2() { new <API key>(-2, ENGINE); } @Test(expectedExceptions = <API key>.class) public void testNullEngine() { new <API key>(2, null); } @Test public void test() { <API key><Double> dist = new <API key>(1, ENGINE); assertCDFWithNull(dist); assertPDFWithNull(dist); assertInverseCDF(X, dist); for (int i = 0; i < 10; i++) { dist = new <API key>(DOF[i], ENGINE); assertEquals(P[i], dist.getCDF(X[i]), EPS); } } @Test public void testNormal() { final <API key><Double> highDOF = new <API key>(1000000, ENGINE); final <API key><Double> normal = new NormalDistribution(0, 1, ENGINE); final double eps = 1e-4; double x; for (int i = 0; i < 100; i++) { x = RANDOM.nextDouble(); assertEquals(highDOF.getCDF(x), normal.getCDF(x), eps); assertEquals(highDOF.getPDF(x), normal.getPDF(x), eps); assertEquals(highDOF.getInverseCDF(x), normal.getInverseCDF(x), eps); } } @Test public void testObject() { final double dof = 2.4; final <API key> dist = new <API key>(dof, ENGINE); <API key> other = new <API key>(dof, ENGINE); assertEquals(dist, other); assertEquals(dist.hashCode(), other.hashCode()); other = new <API key>(dof); assertEquals(dist, other); assertEquals(dist.hashCode(), other.hashCode()); other = new <API key>(dof + 1, ENGINE); assertFalse(dist.equals(other)); } }
using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal static class <API key> { public static bool IsDynamic(this ConversionKind conversionKind) { return conversionKind == ConversionKind.ImplicitDynamic || conversionKind == ConversionKind.ExplicitDynamic; } // Is the particular conversion an implicit conversion? public static bool <API key>(this ConversionKind conversionKind) { switch (conversionKind) { case ConversionKind.NoConversion: return false; case ConversionKind.Identity: case ConversionKind.ImplicitNumeric: case ConversionKind.<API key>: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitEnumeration: case ConversionKind.ImplicitThrow: case ConversionKind.ImplicitNullable: case ConversionKind.NullLiteral: case ConversionKind.ImplicitReference: case ConversionKind.Boxing: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitConstant: case ConversionKind.ImplicitUserDefined: case ConversionKind.AnonymousFunction: case ConversionKind.MethodGroup: case ConversionKind.PointerToVoid: case ConversionKind.NullToPointer: case ConversionKind.InterpolatedString: case ConversionKind.Deconstruction: return true; case ConversionKind.ExplicitNumeric: case ConversionKind.ExplicitTuple: case ConversionKind.<API key>: case ConversionKind.ExplicitEnumeration: case ConversionKind.ExplicitNullable: case ConversionKind.ExplicitReference: case ConversionKind.Unboxing: case ConversionKind.ExplicitDynamic: case ConversionKind.ExplicitUserDefined: case ConversionKind.PointerToPointer: case ConversionKind.PointerToInteger: case ConversionKind.IntegerToPointer: case ConversionKind.IntPtr: return false; default: throw ExceptionUtilities.UnexpectedValue(conversionKind); } } // Is the particular conversion a used-defined conversion? public static bool <API key>(this ConversionKind conversionKind) { switch (conversionKind) { case ConversionKind.ImplicitUserDefined: case ConversionKind.ExplicitUserDefined: return true; default: return false; } } public static bool IsPointerConversion(this ConversionKind kind) { switch (kind) { case ConversionKind.PointerToVoid: case ConversionKind.PointerToPointer: case ConversionKind.PointerToInteger: case ConversionKind.IntegerToPointer: case ConversionKind.NullToPointer: return true; default: return false; } } } }
var WebDeveloper = WebDeveloper || {}; WebDeveloper.Generated = WebDeveloper.Generated || {}; // Displays an image WebDeveloper.Generated.displayImage = function(image, container, imagesCounter, locale) { var anchor = "image-" + imagesCounter; var childElement = document.createElement("th"); var element = document.createElement("tr"); var imageSrc = image.src; var linkElement = document.createElement("a"); var table = document.createElement("table"); var tableContainer = document.createElement("thead"); childElement.appendChild(document.createTextNode(locale.property)); element.appendChild(childElement); childElement = document.createElement("th"); childElement.appendChild(document.createTextNode(locale.value)); element.appendChild(childElement); tableContainer.appendChild(element); table.setAttribute("class", "table table-striped"); table.appendChild(tableContainer); tableContainer = document.createElement("tbody"); childElement = document.createElement("td"); element = document.createElement("tr"); childElement.appendChild(document.createTextNode(locale.src)); element.appendChild(childElement); childElement = document.createElement("td"); linkElement.appendChild(document.createTextNode(imageSrc)); linkElement.setAttribute("href", imageSrc); linkElement.setAttribute("target", "_blank"); childElement.appendChild(linkElement); element.appendChild(childElement); tableContainer.appendChild(element); childElement = document.createElement("td"); element = document.createElement("tr"); childElement.appendChild(document.createTextNode(locale.width)); element.appendChild(childElement); childElement = document.createElement("td"); childElement.appendChild(document.createTextNode(image.width)); element.appendChild(childElement); tableContainer.appendChild(element); childElement = document.createElement("td"); element = document.createElement("tr"); childElement.appendChild(document.createTextNode(locale.height)); element.appendChild(childElement); childElement = document.createElement("td"); childElement.appendChild(document.createTextNode(image.height)); element.appendChild(childElement); tableContainer.appendChild(element); // If the image has an alt attribute if(image.alt) { childElement = document.createElement("td"); element = document.createElement("tr"); childElement.appendChild(document.createTextNode(locale.alt)); element.appendChild(childElement); childElement = document.createElement("td"); childElement.appendChild(document.createTextNode(image.alt)); element.appendChild(childElement); tableContainer.appendChild(element); } table.appendChild(tableContainer); childElement = document.createElement("img"); element = document.createElement("div"); childElement.setAttribute("class", "img-thumbnail"); childElement.setAttribute("src", imageSrc); element.setAttribute("class", "web-developer-image"); element.setAttribute("id", anchor); element.appendChild(childElement); container.appendChild(element); container.appendChild(table); element = document.createElement("div"); element.setAttribute("class", "<API key>"); container.appendChild(element); document.getElementById("content").appendChild(container); childElement = document.createElement("a"); element = document.createElement("li"); childElement.appendChild(document.createTextNode(WebDeveloper.Generated.formatURL(imageSrc))); childElement.setAttribute("href", "#" + anchor); $(".dropdown-menu", $("#images-dropdown")).get(0).appendChild(element); }; // Initializes the page with data WebDeveloper.Generated.initialize = function(data, locale) { var container = null; var contentDocument = null; var documents = data.documents; var imageDescription = null; var images = null; var imagesCounter = 1; var imagesDescription = locale.images; var imagesDropdown = $("#images-dropdown"); var imagesLength = null; WebDeveloper.Generated.emptyContent(); WebDeveloper.Generated.localizeHeader(locale); WebDeveloper.Generated.setPageTitle(imagesDescription, data, locale); $(".dropdown-toggle", imagesDropdown).prepend(imagesDescription); // Loop through the documents for(var i = 0, l = documents.length; i < l; i++) { contentDocument = documents[i]; imageDescription = imagesDescription.toLowerCase(); images = contentDocument.images; imagesLength = images.length; // If there is only one image if(imagesLength == 1) { imageDescription = locale.image.toLowerCase(); } WebDeveloper.Generated.addDocument(contentDocument.url, i, imageDescription, imagesLength); // If there are images if(imagesLength > 0) { container = WebDeveloper.Generated.<API key>(); // Loop through the images for(var j = 0; j < imagesLength; j++) { WebDeveloper.Generated.displayImage(images[j], container, imagesCounter, locale); imagesCounter++; } } else { WebDeveloper.Generated.addSeparator(); } } WebDeveloper.Generated.<API key>(); };
<?xml version="1.0" encoding="UTF-8"?> <table title="table4" id="table4" class="tabcontent" xmlns="http: <tr> <td> <img src="table.png"/> <p>target/pdftable1/10.1016_j.pain.2014.09.020/tables/table4/table.png</p> </td> <td> <table class="table"> <caption/> <tr> <th class="cell">Study </th> <th class="cell">Category of risk factor reported </th> <th class="cell">Data source of study </th> <th class="cell">Sample size of study (N) </th> <th class="cell">Risk factor details </th> </tr> <tr> <td class="cell">Argyriou (2013)</td> <td class="cell">Genetic</td> <td class="cell">Prospective cohort</td> <td class="cell">200</td> <td class="cell">SNC4A-rs2302237 OR = 2.65 (1.15–6)</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">SCN10A-rs1263292 OR = 0.39 (0.17–0.88)</td> </tr> <tr> <td class="cell">Attal (2009)</td> <td class="cell">Clinical</td> <td class="cell">Prospective cohort</td> <td class="cell">18</td> <td class="cell">Cold allodynia OR = 39 (1.8–817)</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">Cold hyperalgesia OR = 3.9 (1.0–1.20)</td> </tr> <tr> <td class="cell">Baldwin (2012)</td> <td class="cell">Genetic</td> <td class="cell">Prospective cohort</td> <td class="cell">855</td> <td class="cell">FGD4-rs10771973 HR = 1.57 (1.30–1.91)</td> </tr> <tr> <td class="cell">Dimopoulos (2011)</td> <td class="cell">Clinical</td> <td class="cell">RCT</td> <td class="cell">340</td> <td class="cell">Baseline neuropathy HR = 1.79 (p &lt; 0.01)</td> </tr> <tr> <td class="cell">Glendenning (2010)</td> <td class="cell">Clinical and treatment-related</td> <td class="cell">Cross-sectional cohort</td> <td class="cell">293</td> <td class="cell">Cisplatin dose increase OR = 1.91 (1.61–2.26)</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">Carboplatin dose increase OR = 1.26 (1.04–1.52)</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">Age at follow-up OR = 1.06 (1.04–1.08)</td> </tr> <tr> <td class="cell">Johnson (2011) ^{⁄}</td> <td class="cell">Genetic</td> <td class="cell">RCT</td> <td class="cell">970 + 550</td> <td class="cell">ABCA1-rs363717 OR = 0.71 (0.52–0.98)</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">ICAM1-rs1799969 OR = 0.67 (0.44–1.03)</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">PPARD-rs2076169 OR = 0.60 (0.38–095)</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">SERPINB2-rs6103 OR = 0.70 (0.52–0.95)</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">SLC12A6-rs7164902 OR = 0.60 (0.44–0.80)</td> </tr> <tr> <td class="cell">Kawakami (2012)</td> <td class="cell">Clinical</td> <td class="cell">Prospective cohort</td> <td class="cell">50</td> <td class="cell">Smoking history pack-years HR = 1.03 (1.0–1.05)</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">Decreased creatinine clearance HR = 0.96 (0.92–0.99)</td> </tr> <tr> <td class="cell">Won (2012) ^{†}</td> <td class="cell">Genetic</td> <td class="cell">Prospective cohort</td> <td class="cell">96</td> <td class="cell">TAC1-rs10486003</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">FOXC1-rs2338</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">ITGA1-rs830884</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">ACYP2-rs843748</td> </tr> <tr> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="empty"/> <td class="cell">DLEU7-rs797519</td> </tr> </table> <p>target/pdftable1/10.1016_j.pain.2014.09.020/tables/table4/table.svg.html</p> </td> </tr> </table>
<?php /** * Zend_Mail_Part */ // require_once 'Zend/Mail/Part.php'; /** * <API key> */ // require_once 'Zend/Mail/Message/Interface.php'; class Zend_Mail_Message extends Zend_Mail_Part implements <API key> { /** * flags for this message * @var array */ protected $_flags = array(); /** * Public constructor * * In addition to the parameters of Zend_Mail_Part::__construct() this constructor supports: * - file filename or file handle of a file with raw message content * - flags array with flags for message, keys are ignored, use constants defined in Zend_Mail_Storage * * @param string $rawMessage full message with or without headers * @throws Zend_Mail_Exception */ public function __construct(array $params) { if (isset($params['file'])) { if (!is_resource($params['file'])) { $params['raw'] = @file_get_contents($params['file']); if ($params['raw'] === false) { /** * @see Zend_Mail_Exception */ // require_once 'Zend/Mail/Exception.php'; throw new Zend_Mail_Exception('could not open file'); } } else { $params['raw'] = stream_get_contents($params['file']); } } if (!empty($params['flags'])) { // set key and value to the same value for easy lookup $this->_flags = array_merge($this->_flags, array_combine($params['flags'],$params['flags'])); } parent::__construct($params); } /** * return toplines as found after headers * * @return string toplines */ public function getTopLines() { return $this->_topLines; } /** * check if flag is set * * @param mixed $flag a flag name, use constants defined in Zend_Mail_Storage * @return bool true if set, otherwise false */ public function hasFlag($flag) { return isset($this->_flags[$flag]); } /** * get all set flags * * @return array array with flags, key and value are the same for easy lookup */ public function getFlags() { return $this->_flags; } }
import os import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.host_operations as host_ops import zstackwoodpecker.operations.resource_operations as res_ops import zstackwoodpecker.operations.vm_operations as vm_ops _config_ = { 'timeout' : 1000, 'noparallel' : True } test_stub = test_lib.lib_get_test_stub() test_obj_dict = test_state.TestStateDict() new_offering_uuid = None def test(): global new_offering_uuid test_util.test_dsc('Test VM network outbound & inbound bandwidth QoS by 1MB') #unit is KB net_bandwidth = 1024 new_offering = test_lib.<API key>(<API key> = net_bandwidth, \ <API key> = net_bandwidth) new_offering_uuid = new_offering.uuid vm1 = test_stub.create_vm(vm_name = '<API key>', \ <API key> = new_offering.uuid) test_obj_dict.add_vm(vm1) vm1.check() vm1_inv = vm1.get_vm() test_stub.<API key>(vm1_inv) vm1_ip = vm1_inv.vmNics[0].ip vm2 = test_stub.create_vm(vm_name = '<API key>', \ <API key> = new_offering.uuid) test_obj_dict.add_vm(vm2) vm2.check() vm2_inv = vm2.get_vm() vm2_ip = vm2_inv.vmNics[0].ip test_stub.<API key>(vm2_inv) test_stub.copy_key_file(vm1_inv) test_stub.copy_key_file(vm2_inv) test_stub.create_test_file(vm1_inv, net_bandwidth) test_stub.create_test_file(vm2_inv, net_bandwidth) l3_name = os.environ.get('l3VlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid vm1.add_nic(l3_net_uuid) vm2.add_nic(l3_net_uuid) ssh_cmd = 'ssh -<API key>=no -oCheckHostIP=no -oUserKnownHostsFile=/dev/null' cmd = "pkill dhclient" os.system("%s %s %s" % (ssh_cmd, vm1_ip, cmd)) os.system("%s %s %s" % (ssh_cmd, vm2_ip, cmd)) cmd = "dhclient eth0 eth1" os.system("%s %s %s" % (ssh_cmd, vm1_ip, cmd)) os.system("%s %s %s" % (ssh_cmd, vm2_ip, cmd)) test_stub.<API key>(vm1_ip, test_lib.<API key>(vm2.get_vm(), l3_net_uuid).ip, net_bandwidth) vm_ops.<API key>(new_offering_uuid) test_lib.lib_robot_cleanup(test_obj_dict) test_util.test_pass('VM Network Outbound QoS Test Pass') #Will be called only if exception happens in test(). def error_cleanup(): test_lib.lib_error_cleanup(test_obj_dict) if new_offering_uuid: vm_ops.<API key>(new_offering_uuid)
layout: post title: GigaSpaces-Excel Integration FAQ categories: SBP parent: <API key>.html weight: 400 {% summary page|65 %}Frequently asked questions about the GigaSpaces-Excel integration.{% endsummary %} # Overview The following FAQs deal with the GigaSpaces Excel Integration solutions. # General FAQs - [What are the **Prerequisites**?](#Prerequisites) - [Why does the Space Viewer toolbar not show up in Excel?](#The Space Viewer toolbar does not show up in Excel) {% include /sbp/<API key>.markdown %} # The Space Viewer toolbar does not show up in Excel Problem The Excel Space Viewer is installed on a laptop PC. It is working OK but after a few days, the Space Viewer toolbar does not appear in Excel. Running the installation file (`<API key>.msi`) and selecting **Add**/**Remove**/**Repair** works fine, but the toolbar still doesn't show up in Excel. - **Operating system** -- Microsoft Windows XP Professional - **Office version** -- Microsoft Office Small Business Edition 2003 Solution 1. Open Excel 2. Click **Help** > **About Excel** > **Disabled Items** 3. Highlight the **mscorlib.dll** item and click **Enable**
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { Injectable } from 'angular2/src/core/di'; import { CssAnimationBuilder } from './<API key>'; import { BrowserDetails } from './browser_details'; export let AnimationBuilder = class { /** * Used for DI * @param browserDetails */ constructor(browserDetails) { this.browserDetails = browserDetails; } /** * Creates a new CSS Animation * @returns {CssAnimationBuilder} */ css() { return new CssAnimationBuilder(this.browserDetails); } }; AnimationBuilder = __decorate([ Injectable(), __metadata('design:paramtypes', [BrowserDetails]) ], AnimationBuilder); //# sourceMappingURL=animation_builder.js.map
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Snippets; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion { internal abstract partial class <API key> : ICompletionService { private static readonly Func<string, List<CompletionItem>> s_createList = _ => new List<CompletionItem>(); private const int MruSize = 10; private readonly List<string> _committedItems = new List<string>(MruSize); private readonly object _mruGate = new object(); internal void <API key>(CompletionItem item) { lock (_mruGate) { // We need to remove the item if it's already in the list. // If we're at capacity, we need to remove the LRU item. var removed = _committedItems.Remove(item.DisplayText); if (!removed && _committedItems.Count == MruSize) { _committedItems.RemoveAt(0); } _committedItems.Add(item.DisplayText); } } internal int GetMRUIndex(CompletionItem item) { lock (_mruGate) { // A lower value indicates more recently used. Since items are added // to the end of the list, our result just maps to the negation of the // index. // -1 => 1 == Not Found // 0 => 0 == least recently used // 9 => -9 == most recently used var index = _committedItems.IndexOf(item.DisplayText); return -index; } } public void ClearMRUCache() { lock (_mruGate) { _committedItems.Clear(); } } <summary> Apply any culture-specific quirks to the given text for the purposes of pattern matching. For example, in the Turkish locale, capital 'i's should be treated specially in Visual Basic. </summary> public virtual string <API key>(string candidate) { return candidate; } public abstract IEnumerable<<API key>> <API key>(); protected abstract string GetLanguageName(); private class ProviderList { public <API key> Provider; public CompletionList List; } public async Task<CompletionList> <API key>( Document document, int position, <API key> triggerInfo, OptionSet options, IEnumerable<<API key>> providers, Cancellation<API key>) { options = options ?? document.Project.Solution.Workspace.Options; providers = providers ?? <API key>(); var <API key> = <API key>(providers); var completionRules = GetCompletionRules(); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); IEnumerable<<API key>> triggeredProviders; switch (triggerInfo.TriggerReason) { case <API key>.TypeCharCommand: triggeredProviders = providers.Where(p => p.IsTriggerCharacter(text, position - 1, options)).ToList(); break; case <API key>.<API key>: triggeredProviders = this.TriggerOnBackspace(text, position, triggerInfo, options) ? providers : <API key>.EmptyEnumerable<<API key>>(); break; default: triggeredProviders = providers; break; } // Now, ask all the triggered providers if they can provide a group. var providersAndLists = new List<ProviderList>(); foreach (var provider in triggeredProviders) { var completionList = await <API key>(provider, document, position, triggerInfo, options, cancellationToken).ConfigureAwait(false); if (completionList != null) { providersAndLists.Add(new ProviderList { Provider = provider, List = completionList }); } } // See if there was a group provided that was exclusive and had items in it. If so, then // that's all we'll return. var firstExclusiveList = providersAndLists.FirstOrDefault( t => t.List.IsExclusive && t.List.Items.Any()); if (firstExclusiveList != null) { return <API key>(<API key>.SingletonEnumerable(firstExclusiveList.List), completionRules); } // If no exclusive providers provided anything, then go through the remaining // triggered list and see if any provide items. var nonExclusiveLists = providersAndLists.Where(t => !t.List.IsExclusive).ToList(); // If we still don't have any items, then we're definitely done. if (!nonExclusiveLists.Any(g => g.List.Items.Any())) { return null; } // If we do have items, then ask all the other (non exclusive providers) if they // want to augment the items. var usedProviders = nonExclusiveLists.Select(g => g.Provider); var nonUsedProviders = providers.Except(usedProviders); var <API key> = new List<ProviderList>(); foreach (var provider in nonUsedProviders) { var completionList = await <API key>(provider, document, position, triggerInfo, options, cancellationToken).ConfigureAwait(false); if (completionList != null && !completionList.IsExclusive) { <API key>.Add(new ProviderList { Provider = provider, List = completionList }); } } var <API key> = nonExclusiveLists.Concat(<API key>).ToList(); if (<API key>.Count == 0) { return null; } // Providers are ordered, but we processed them in our own order. Ensure that the // groups are properly ordered based on the original providers. <API key>.Sort((p1, p2) => <API key>[p1.Provider] - <API key>[p2.Provider]); return <API key>(<API key>.Select(g => g.List), completionRules); } private static CompletionList <API key>(IEnumerable<CompletionList> completionLists, CompletionRules completionRules) { var <API key> = new Dictionary<string, List<CompletionItem>>(); CompletionItem builder = null; foreach (var completionList in completionLists) { Contract.Assert(completionList != null); foreach (var item in completionList.Items) { Contract.Assert(item != null); // New items that match an existing item will replace it. ReplaceExistingItem(item, <API key>, completionRules); } builder = builder ?? completionList.Builder; } if (<API key>.Count == 0) { return null; } // TODO(DustinCa): Revisit performance of this. var totalItems = <API key>.Values.Flatten().ToList(); totalItems.Sort(); // TODO(DustinCa): This is lossy -- we lose the IsExclusive field. Fix that. return new CompletionList(totalItems.ToImmutableArray(), builder); } private static void ReplaceExistingItem( CompletionItem item, Dictionary<string, List<CompletionItem>> <API key>, CompletionRules completionRules) { // See if we have an item with var sameNamedItems = <API key>.GetOrAdd(item.DisplayText, s_createList); for (int i = 0; i < sameNamedItems.Count; i++) { var existingItem = sameNamedItems[i]; Contract.Assert(item.DisplayText == existingItem.DisplayText); if (completionRules.ItemsMatch(item, existingItem)) { sameNamedItems[i] = Disambiguate(item, existingItem); return; } } sameNamedItems.Add(item); } private static CompletionItem Disambiguate(CompletionItem item, CompletionItem existingItem) { // We've constructed the export order of completion providers so // that snippets are exported after everything else. That way, // when we choose a single item per display text, snippet // glyphs appear by snippets. This breaks preselection of items // whose display text is also a snippet (workitem 852578), // the snippet item doesn't have its preselect bit set. // We'll special case this by not preferring later items // if they are snippets and the other candidate is preselected. if (existingItem.MatchPriority != MatchPriority.Default && item.CompletionProvider is <API key>) { return existingItem; } // If one is a keyword, and the other is some other item that inserts the same text as the keyword, // keep the keyword var keywordItem = existingItem as <API key> ?? item as <API key>; if (keywordItem != null) { return keywordItem; } return item; } private Dictionary<<API key>, int> <API key>(IEnumerable<<API key>> completionProviders) { var result = new Dictionary<<API key>, int>(); int i = 0; foreach (var completionProvider in completionProviders) { result[completionProvider] = i; i++; } return result; } private static async Task<CompletionList> <API key>( <API key> provider, Document document, int position, <API key> triggerInfo, OptionSet options, Cancellation<API key>) { var context = new <API key>(document, position, triggerInfo, options, cancellationToken); if (document.SupportsSyntaxTree) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!root.FullSpan.IntersectsWith(position)) { try { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); ReportException(position, root, sourceText); } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { } } else { await provider.<API key>(context).ConfigureAwait(false); } } else { await provider.<API key>(context).ConfigureAwait(false); } return new CompletionList(context.GetItems(), context.Builder, context.IsExclusive); } private static void ReportException(int position, SyntaxNode root, SourceText sourceText) { throw new <API key>( $"Position '{position}' is not contained in SyntaxTree Span '{root.FullSpan}' source text length '{sourceText.Length}'"); } public bool IsTriggerCharacter(SourceText text, int characterPosition, IEnumerable<<API key>> completionProviders, OptionSet options) { if (!options.GetOption(CompletionOptions.TriggerOnTyping, GetLanguageName())) { return false; } completionProviders = completionProviders ?? <API key>(); return completionProviders.Any(p => p.IsTriggerCharacter(text, characterPosition, options)); } protected abstract bool TriggerOnBackspace(SourceText text, int position, <API key> triggerInfo, OptionSet options); public abstract Task<TextSpan> <API key>(Document document, int position, Cancellation<API key>); public virtual CompletionRules GetCompletionRules() { return new CompletionRules(this); } public virtual bool DismissIfEmpty { get { return false; } } public Task<string> <API key>(CompletionItem completionItem, Workspace workspace) { var insertionText = GetCompletionRules().GetTextChange(completionItem, '\t').NewText; var snippetInfoService = workspace.Services.GetLanguageServices(GetLanguageName()).GetService<ISnippetInfoService>(); if (snippetInfoService != null && snippetInfoService.<API key>(insertionText)) { return Task.FromResult(string.Format(FeaturesResources.<API key>, insertionText)); } return SpecializedTasks.Default<string>(); } public virtual bool <API key> { get { return false; } } public virtual bool <API key> { get { return false; } } } }
package nu.postnummeruppror.insamlingsappen; import nu.postnummeruppror.insamlingsappen.domain.Coordinate; import nu.postnummeruppror.insamlingsappen.transactions.IdentityFactory; import nu.postnummeruppror.insamlingsappen.transactions.version_0_0_6.<API key>; import se.kodapan.osm.domain.Node; import se.kodapan.osm.domain.root.PojoRoot; import se.kodapan.osm.parser.xml.instantiated.<API key>; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author kalle * @since 2014-09-27 12:19 */ public class Skolimport { private static Pattern <API key> = Pattern.compile("\\s*(.+)(\\s*([0-9]+)\\s*([A-Za-z]?))?\\s*$"); public static void main(String[] args) throws Exception { Insamlingsappen.getInstance().open(); try { PojoRoot pojoRoot = new PojoRoot(); <API key> parser = <API key>.newInstance(); parser.setRoot(pojoRoot); parser.parse(Skolimport.class.getResourceAsStream("/alla-skolor-cc0.osm.xml")); for (Node node : pojoRoot.getNodes().values()) { <API key> <API key> = new <API key>(); <API key>.<API key>(Insamlingsappen.getInstance().getPrevayler().execute(new IdentityFactory())); <API key>.setAccountIdentity("Skolimport version 0.0.1"); <API key>.setApplication("Skolimport"); <API key>.<API key>("0.0.1"); <API key>.setCoordinate(new Coordinate()); <API key>.getCoordinate().setLatitude(node.getLatitude()); <API key>.getCoordinate().setLongitude(node.getLongitude()); <API key>.getCoordinate().setAccuracy(1d); <API key>.getCoordinate().setProvider("shapefile"); <API key>.getTags().put("amenity", "school"); String verkform = node.getTag("VERKFORM"); if (verkform != null) { String level = null; if ("Förskoleklass".equals(verkform)) { <API key>.getTags().put("isced:level", "0"); } else if ("Gymnasieskola".equals(verkform)) { <API key>.getTags().put("isced:level", "3"); } <API key>.getTags().put("ref:se:skola:verkform", verkform); } String skolenkod = node.getTag("SKOLENKOD"); if (skolenkod != null) { int id = Double.valueOf(skolenkod.trim()).intValue(); <API key>.getTags().put("ref:se:skola:skolenhetskod", String.valueOf(id)); } String hmannamn = node.getTag("HMANNAMN"); if (hmannamn != null) { <API key>.getTags().put("operator", hmannamn.trim()); } String streetAddress = node.getTag("BADRESS"); if (streetAddress != null) { Matcher matcher = <API key>.matcher(streetAddress); if (matcher.matches()) { <API key>.getTags().put("addr:street", matcher.group(1).trim()); if (matcher.group(2) != null) { <API key>.getTags().put("addr:housenumber", matcher.group(2).trim()); } if (matcher.group(3) != null) { <API key>.getTags().put("addr:housename", matcher.group(3).trim()); } } } String name = node.getTag("SNAMN"); if (name != null) { <API key>.getTags().put("name", name.trim()); } String postalTown = node.getTag("BPOSTORT"); if (postalTown != null) { <API key>.getTags().put("addr:city", postalTown.trim()); } String postalCode = node.getTag("BPOSTNR"); if (postalCode != null) { <API key>.getTags().put("addr:postcode", String.valueOf(Double.valueOf(postalCode.trim()).intValue())); } String lan = node.getTag("LAN"); if (lan != null) { <API key>.getTags().put("ref:se:län", lan.trim()); } String kommun = node.getTag("SKOM"); if (kommun != null) { <API key>.getTags().put("ref:se:kommun", kommun.trim()); } Insamlingsappen.getInstance().getPrevayler().execute(<API key>); } } finally { Insamlingsappen.getInstance().close(); } } }
--TEST MongoDB\BSON\toJSON(): BSON decoding exceptions for bson_as_json() failure --FILE <?php require_once __DIR__ . '/../utils/basic.inc'; $tests = [ // Invalid UTF-8 characters (i.e. 0xFE, 0xFF) in field name pack('VCCCxVa*xx', 17, 2, 254, 255, 3, 'bar'), /* Note: we don't use a three-character string in the underflow case, as * the 4-byte string length and payload (i.e. three characters + null byte) * coincidentally satisfy the expected size for an 8-byte double. We also * don't use a four-character string, since its null byte would be * interpreted as the document terminator. The actual document terminator * would then remain in the buffer and trigger a "did not exhaust" error. */ pack('VCa*xVa*xx', 17, 1, 'foo', 3, 'ab'), // Invalid field type (underflow) pack('VCa*xVa*xx', 20, 1, 'foo', 6, 'abcde'), // Invalid field type (overflow) ]; foreach ($tests as $bson) { echo throws(function() use ($bson) { toJSON($bson); }, 'MongoDB\Driver\Exception\<API key>'), "\n"; } ?> DONE=== <?php exit(0); ?> --EXPECT OK: Got MongoDB\Driver\Exception\<API key> Could not convert BSON document to a JSON string OK: Got MongoDB\Driver\Exception\<API key> Could not convert BSON document to a JSON string OK: Got MongoDB\Driver\Exception\<API key> Could not convert BSON document to a JSON string DONE===
<p>Provides an overview of the local JNDI namespace. The Jakarta EE platform specification defines the following JNDI contexts:</p> <ul> <li><code>java:comp</code> - The namespace is scoped to the current component (i.e. EJB)</li> <li><code>java:module</code> - Scoped to the current module</li> <li><code>java:app</code> - Scoped to the current application</li> <li><code>java:global</code> - Scoped to the application server</li> </ul> <p>In addition to the standard namespaces, ${build.shortName} also provides the following two global namespaces:</p> <ul> <li><code>java:jboss</code></li> <li><code>java:/</code></li> </ul> <p>Please note that only entries within the java:jboss/exported context are accessible over remote JNDI. For web deployments <code>java:comp</code> is aliased to <code>java:module</code>, so EJB's deployed in a war do not have their own comp namespace.</p>
import os from django.core.wsgi import <API key> os.environ.setdefault("<API key>", "hoaxdetector.settings") application = <API key>()
# -*- coding: utf-8 -*- from django.core.exceptions import ValidationError from nose.tools import * # flake8: noqa (PEP8 asserts) from modularodm.exceptions import NoResultsFound, <API key> from tests.base import OsfTestCase from osf_tests.factories import SubjectFactory, PreprintFactory, <API key> from website.project.taxonomies import <API key> class <API key>(OsfTestCase): def setUp(self): super(<API key>, self).setUp() self.root_subject = SubjectFactory() self.one_level_root = SubjectFactory() self.two_level_root = SubjectFactory() self.outside_root = SubjectFactory() self.root_subject.save() self.outside_root.save() self.two_level_root.save() self.one_level_root.save() self.parent_subj_0 = SubjectFactory(parent=self.root_subject) self.parent_subj_1 = SubjectFactory(parent=self.root_subject) self.two_level_parent = SubjectFactory(parent=self.two_level_root) self.outside_parent = SubjectFactory(parent=self.outside_root) self.parent_subj_0.save() self.parent_subj_1.save() self.outside_parent.save() self.two_level_parent.save() self.child_subj_00 = SubjectFactory(parent=self.parent_subj_0) self.child_subj_01 = SubjectFactory(parent=self.parent_subj_0) self.child_subj_10 = SubjectFactory(parent=self.parent_subj_1) self.child_subj_11 = SubjectFactory(parent=self.parent_subj_1) self.outside_child = SubjectFactory(parent=self.outside_parent) self.child_subj_00.save() self.child_subj_01.save() self.child_subj_10.save() self.child_subj_11.save() self.outside_child.save() self.<API key> = [self.root_subject._id, self.parent_subj_0._id, self.child_subj_00._id] self.<API key> = [self.two_level_root._id, self.two_level_parent._id] self.<API key> = [self.one_level_root._id] self.<API key> = [self.root_subject._id, self.parent_subj_1._id] self.valid_root = [self.root_subject._id] self.no_root = [self.parent_subj_0._id, self.child_subj_00._id] self.no_parent = [self.root_subject._id, self.child_subj_00._id] self.invalid_child_leaf = [self.root_subject._id, self.parent_subj_0._id, self.child_subj_10._id] self.invalid_parent_leaf = [self.root_subject._id, self.outside_parent._id, self.child_subj_00._id] self.invalid_root_leaf = [self.outside_root._id, self.parent_subj_0._id, self.child_subj_00._id] self.invalid_ids = ['notarealsubjectid', 'thisisalsoafakeid'] def <API key>(self): assert_equal(self.child_subj_00.hierarchy, [self.root_subject._id, self.parent_subj_0._id, self.child_subj_00._id]) assert_equal(self.two_level_parent.hierarchy, [self.two_level_root._id, self.two_level_parent._id]) assert_equal(self.one_level_root.hierarchy, [self.one_level_root._id]) assert_equal(self.parent_subj_1.hierarchy, [self.root_subject._id, self.parent_subj_1._id]) assert_equal(self.root_subject.hierarchy, [self.root_subject._id]) def <API key>(self): assert_equal(self.child_subj_00.object_hierarchy, [self.root_subject, self.parent_subj_0, self.child_subj_00]) assert_equal(self.two_level_parent.object_hierarchy, [self.two_level_root, self.two_level_parent]) assert_equal(self.one_level_root.object_hierarchy, [self.one_level_root]) assert_equal(self.parent_subj_1.object_hierarchy, [self.root_subject, self.parent_subj_1]) assert_equal(self.root_subject.object_hierarchy, [self.root_subject]) def <API key>(self): assert_equal(<API key>(self.<API key>), None) def <API key>(self): assert_equal(<API key>(self.<API key>), None) def <API key>(self): assert_equal(<API key>(self.<API key>), None) def <API key>(self): assert_equal(<API key>(self.<API key>), None) def <API key>(self): assert_equal(<API key>(self.valid_root), None) def <API key>(self): with assert_raises(<API key>) as e: <API key>(self.no_root) assert_in('Unable to find root', e.exception.message) def <API key>(self): with assert_raises(<API key>) as e: <API key>(self.no_parent) assert_in('Invalid subject hierarchy', e.exception.message) def <API key>(self): with assert_raises(<API key>) as e: <API key>(self.invalid_child_leaf) assert_in('Invalid subject hierarchy', e.exception.message) def <API key>(self): with assert_raises(<API key>) as e: <API key>(self.invalid_parent_leaf) assert_in('Invalid subject hierarchy', e.exception.message) def <API key>(self): with assert_raises(<API key>) as e: <API key>(self.invalid_root_leaf) assert_in('Invalid subject hierarchy', e.exception.message) def <API key>(self): with assert_raises(<API key>) as e: <API key>(self.invalid_ids) assert_in('could not be found', e.exception.message) class <API key>(OsfTestCase): def setUp(self): super(<API key>, self).setUp() self.subject = SubjectFactory() def <API key>(self): self.subject.text = 'asdfg' self.subject.save() def <API key>(self): preprint = PreprintFactory(subjects=[[self.subject._id]]) self.subject.text = 'asdfg' with assert_raises(ValidationError): self.subject.save() def <API key>(self): self.subject.delete() def <API key>(self): preprint = PreprintFactory(subjects=[[self.subject._id]]) with assert_raises(ValidationError): self.subject.delete() class <API key>(OsfTestCase): def test_bepress_text(self): osf_provider = <API key>(_id='osf') asdf_provider = <API key>(_id='asdf') bepress_subj = SubjectFactory(text='BePress Text', provider=osf_provider) other_subj = SubjectFactory(text='Other Text', bepress_subject=bepress_subj, provider=asdf_provider) assert other_subj.bepress_text == 'BePress Text' assert bepress_subj.bepress_text == 'BePress Text'
package com.bt.pi.api.service; import java.util.Collection; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Component; import com.bt.pi.api.entities.<API key>; import com.bt.pi.app.common.entities.AvailabilityZone; import com.bt.pi.app.common.entities.<API key>; import com.bt.pi.app.common.entities.Image; import com.bt.pi.app.common.entities.ImageState; import com.bt.pi.app.common.entities.Instance; import com.bt.pi.app.common.entities.InstanceAddress; import com.bt.pi.app.common.entities.InstanceState; import com.bt.pi.app.common.entities.<API key>; import com.bt.pi.app.common.entities.InstanceTypes; import com.bt.pi.app.common.entities.MachineType; import com.bt.pi.app.common.entities.Reservation; import com.bt.pi.app.common.entities.SecurityGroup; import com.bt.pi.app.common.entities.User; import com.bt.pi.app.common.images.platform.ImagePlatform; import com.bt.pi.app.common.net.utils.IpAddressUtils; import com.bt.pi.app.common.resource.PiQueue; import com.bt.pi.app.common.resource.PiTopics; import com.bt.pi.core.application.<API key>; import com.bt.pi.core.conf.Property; import com.bt.pi.core.continuation.UpdateResolver; import com.bt.pi.core.dht.BlockingDhtWriter; import com.bt.pi.core.dht.cache.BlockingDhtCache; import com.bt.pi.core.entity.EntityMethod; import com.bt.pi.core.entity.PiEntity; import com.bt.pi.core.id.PId; @Component public class <API key> extends ServiceHelperBase { private static final int <API key> = 3; private static final Log LOG = LogFactory.getLog(<API key>.class); private int <API key>; @Resource(name = "<API key>") private BlockingDhtCache instanceTypeCache; public <API key>() { } @Property(key = "instance.task.queue.retries", defaultValue = "5") public void <API key>(int num) { <API key> = num; } public int <API key>() { return <API key>; } public <API key> runInstances(final Reservation reservation) { LOG.debug(String.format("runInstances(%s)", reservation)); String securityGroupUrl = SecurityGroup.getUrl(reservation.getUserId(), reservation.<API key>()); PId securityGroupId = getPiIdBuilder().getPId(securityGroupUrl).forLocalRegion(); SecurityGroup securityGroup = (SecurityGroup) getDhtClientFactory().<API key>().get(securityGroupId); validateReservation(reservation, securityGroup); reservation.setReservationId(getIdFactory().<API key>()); AvailabilityZone availabilityZone; if (StringUtils.isNotEmpty(reservation.getAvailabilityZone())) { try { availabilityZone = <API key>(reservation.getAvailabilityZone()); } catch (<API key> e) { throw new <API key>(String.format("Unknown availability zone: %s", reservation.getAvailabilityZone())); } } else { availabilityZone = <API key>(); reservation.setAvailabilityZone(availabilityZone.<API key>()); } // setup return object <API key> <API key> = new <API key>(); <API key>.setReservation(reservation); for (int i = 0; i < reservation.getMaxCount(); i++) { String instanceId = getIdFactory().createNewInstanceId(availabilityZone.<API key>()); // create instance Instance instance = new Instance(reservation); instance.setInstanceType(reservation.getInstanceType()); instance.setUserId(reservation.getUserId()); instance.setInstanceId(instanceId); instance.setState(InstanceState.PENDING); instance.setLaunchTime(System.currentTimeMillis()); instance.<API key>(availabilityZone.<API key>()); instance.setRegionCode(availabilityZone.getRegionCode()); LOG.info(String.format("Requesting new %s", instance)); <API key>.getInstances().add(instance); // create instance in dht PId instanceDhtId = getPiIdBuilder().<API key>(Instance.getUrl(instanceId)); BlockingDhtWriter blockingDhtWriter = getDhtClientFactory().<API key>(); <API key> <API key> = new <API key>(); blockingDhtWriter.update(instanceDhtId, instance, <API key>); reservation.addInstanceId(instance.getInstanceId()); } getUserService().addInstancesToUser(reservation.getUserId(), reservation.getInstanceIds(), reservation.getInstanceType()); // write security group to DHT getDhtClientFactory().<API key>().update(securityGroupId, null, new <API key>(reservation.getInstanceIds())); // add to task processing queue PId runInstanceQueueId = getPiIdBuilder().getPId(PiQueue.RUN_INSTANCE.getUrl()).<API key>(availabilityZone.<API key>()); for (String instanceId : reservation.getInstanceIds()) { <API key>().addUrlToQueue(runInstanceQueueId, Instance.getUrl(instanceId), <API key>); } // anycast message <API key> <API key> = <API key>().<API key>(PiTopics.RUN_INSTANCE, availabilityZone.<API key>()); <API key>.randomAnycast(EntityMethod.CREATE, reservation); return <API key>; } private void validateReservation(Reservation reservation, SecurityGroup securityGroup) { LOG.debug(String.format("validateReservation(%s, %s)", reservation, securityGroup)); String imageId = reservation.getImageId(); if (StringUtils.isBlank(imageId)) throw new <API key>("image Id must be supplied"); Image image = readImage(imageId); checkSecurityGroup(reservation); <API key> <API key> = checkInstanceType(reservation); <API key>(reservation, image); checkImagesAccess(reservation, image); checkImageState(image); <API key>(reservation, image); <API key>(reservation, image); checkKeyPair(reservation); <API key>(reservation); checkUserCoreCount(reservation, <API key>); <API key>(reservation, securityGroup); } private void checkUserCoreCount(Reservation reservation, <API key> <API key>) { if (null == reservation.getInstanceType() || null == <API key>) return; int requestedCores = <API key>.getNumCores(); LOG.debug(String.format("instance %s cores %d", <API key>.getInstanceType(), <API key>.getNumCores())); int currentCores = getCurrentCores(reservation.getUserId()); LOG.debug(String.format("user %s current cores %d", reservation.getUserId(), currentCores)); int maxCores = getMaxCores(reservation.getUserId()); LOG.debug(String.format("user %s max cores %d", reservation.getUserId(), maxCores)); if (currentCores + requestedCores > maxCores) throw new <API key>(String.format("Unable to run instances as user %s currently has %s cores when the maximum is %s.", reservation.getUserId(), currentCores, maxCores)); } private int getMaxCores(String userId) { return getUserService().getMaxCores(userId); } private int getCurrentCores(String userId) { return getUserService().getCurrentCores(userId); } private <API key> checkInstanceType(Reservation reservation) { if (null == reservation.getInstanceType()) return null; PId instanceTypesId = getPiIdBuilder().getPId(InstanceTypes.URL_STRING); InstanceTypes instanceTypes = instanceTypeCache.get(instanceTypesId); <API key> result = instanceTypes.<API key>(reservation.getInstanceType()); if (null == result) throw new <API key>("Unable to find instance type:" + reservation.getInstanceType()); if (result.isDeprecated()) throw new <API key>(String.format("Instance type %s is deprecated", reservation.getInstanceType())); return result; } private void <API key>(Reservation reservation, SecurityGroup securityGroup) { LOG.debug(String.format("checking security group: %s", securityGroup)); int <API key> = securityGroup.getInstances().size(); if (<API key> == 0) { LOG.debug(String.format("No instances in security group: %s", securityGroup)); return; } if (securityGroup.getNetmask() == null) { LOG.debug(String.format("Unable to get the netmask for security group: %s", securityGroup)); return; } int <API key> = <API key>(securityGroup); LOG.debug(String.format("SecurityGroup: %s - Number of Instances: %d - Capacity in SecurityGroup: %d", securityGroup.getUrl(), <API key>, <API key>)); if (<API key> + reservation.getMinCount() > <API key> - <API key>) throw new <API key>("unable to run instances as no more capacity in security group"); } private int <API key>(SecurityGroup securityGroup) { String netmask = securityGroup.getNetmask(); int addrsInSlashnet = IpAddressUtils.addrsInSlashnet(IpAddressUtils.netmaskToSlashnet(netmask)); return addrsInSlashnet; } private void <API key>(Reservation reservation) { User u = <API key>().getUser(reservation.getUserId()); if (u.getInstanceIds().length + reservation.getMaxCount() > u.getMaxInstances()) { throw new <API key>(String.format("Unable to run instances as user %s currently has %s instances when the maximum is %s.", u.getUsername(), u.getInstanceIds().length, u.getMaxInstances())); } } private void checkSecurityGroup(Reservation reservation) { if (StringUtils.isBlank(reservation.<API key>())) return; User user = <API key>().getUser(reservation.getUserId()); if (!user.getSecurityGroupIds().contains(reservation.<API key>())) throw new <API key>(String.format("Security group %s does not exist for user %s", reservation.<API key>(), user.getUsername())); } private void checkKeyPair(Reservation reservation) { if (StringUtils.isBlank(reservation.getKeyName())) return; User user = <API key>().getUser(reservation.getUserId()); if (user.getKeyPair(reservation.getKeyName()) == null) throw new <API key>(String.format("User %s does not have key pair \"%s\"", reservation.getUserId(), reservation.getKeyName())); } private void <API key>(Reservation reservation, Image image) { LOG.debug(String.format("<API key>(%s, %s)", reservation, image)); String kernelId = image.getKernelId(); if (StringUtils.isNotBlank(reservation.getKernelId())) kernelId = reservation.getKernelId(); if (StringUtils.isBlank(kernelId)) return; Image kernelImage = readImage(kernelId); if (!ImageState.AVAILABLE.equals(kernelImage.getState())) throw new <API key>(String.format("kernel %s must be in state %s", kernelId, ImageState.AVAILABLE)); if (MachineType.KERNEL.equals(kernelImage.getMachineType())) return; throw new <API key>(String.format("kernel %s must be a %s machine type", kernelId, MachineType.KERNEL)); } private void <API key>(Reservation reservation, Image image) { LOG.debug(String.format("<API key>(%s, %s)", reservation, image)); String ramdiskId = image.getRamdiskId(); if (StringUtils.isNotBlank(reservation.getRamdiskId())) ramdiskId = reservation.getRamdiskId(); if (StringUtils.isBlank(ramdiskId)) return; Image ramdiskImage = readImage(ramdiskId); if (!ImageState.AVAILABLE.equals(ramdiskImage.getState())) throw new <API key>(String.format("ramdisk %s must be in state %s", ramdiskId, ImageState.AVAILABLE)); if (MachineType.RAMDISK.equals(ramdiskImage.getMachineType())) return; throw new <API key>(String.format("ramdisk %s must be a %s machine type", ramdiskId, MachineType.RAMDISK)); } private void <API key>(Reservation reservation, Image image) { LOG.debug(String.format("<API key>(%s, %s)", reservation, image)); if (ImagePlatform.windows.equals(image.getPlatform())) return; if (StringUtils.isBlank(reservation.getKernelId()) && StringUtils.isBlank(image.getKernelId())) throw new <API key>("You must supply a kernel as the image has no default one"); if (ImagePlatform.linux.equals(image.getPlatform())) return; if (ImagePlatform.opensolaris.equals(image.getPlatform())) return; if (StringUtils.isBlank(reservation.getRamdiskId()) && StringUtils.isBlank(image.getRamdiskId())) throw new <API key>("You must supply a ramdisk as the image has no default one"); } private void checkImagesAccess(Reservation reservation, Image image) { LOG.debug(String.format("checkImagesAccess(%s, %s)", reservation, image)); String userId = reservation.getUserId(); User user = <API key>().getUser(userId); checkImageAccess(reservation.getImageId(), user, "image"); checkImageAccess(reservation.getKernelId(), user, "kernel"); checkImageAccess(reservation.getRamdiskId(), user, "ramdisk"); } private void checkImageState(Image image) { LOG.debug(String.format("checkImageState(%s)", image)); if (ImageState.AVAILABLE.equals(image.getState())) return; throw new <API key>(String.format("image %s must be in state %s", image.getImageId(), ImageState.AVAILABLE)); } private Image readImage(String imageId) { LOG.debug(String.format("readImage(%s)", imageId)); PId imagePastryId = getPiIdBuilder().getPId(Image.getUrl(imageId)); Image image = (Image) getDhtClientFactory().<API key>().get(imagePastryId); if (null == image) throw new <API key>(String.format("image %s not found", imageId)); return image; } static final class <API key> implements UpdateResolver<SecurityGroup> { private final Collection<String> <API key>; private <API key>(Collection<String> instanceIds) { this.<API key> = instanceIds; } public Collection<String> <API key>() { return this.<API key>; } @Override public SecurityGroup update(SecurityGroup existingEntity, SecurityGroup requestedEntity) { if (null == existingEntity) return null; for (String instanceId : <API key>) { existingEntity.getInstances().put(instanceId, new InstanceAddress()); } return existingEntity; } } /** * Ensure entry is unique */ static final class <API key> implements UpdateResolver<PiEntity> { public <API key>() { } public PiEntity update(PiEntity previousEntry, PiEntity newEntry) { if (null == previousEntry) { return newEntry; } return null; } } }
// modification, are permitted provided that the following conditions are // met: // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // 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. #include <utility> #include "src/v8.h" #include "src/factory.h" #include "src/global-handles.h" #include "src/isolate.h" // FIXME(mstarzinger, marja): This is weird, but required because of the missing // (disallowed) include: src/factory.h -> src/objects-inl.h #include "src/objects-inl.h" // FIXME(mstarzinger, marja): This is weird, but required because of the missing // (disallowed) include: src/<API key>.h -> // src/<API key>.h #include "src/<API key>.h" #include "test/cctest/cctest.h" #include "test/cctest/heap/heap-utils.h" using namespace v8::internal; static Isolate* GetIsolateFrom(LocalContext* context) { return reinterpret_cast<Isolate*>((*context)->GetIsolate()); } static Handle<JSWeakSet> AllocateJSWeakSet(Isolate* isolate) { Factory* factory = isolate->factory(); Handle<Map> map = factory->NewMap(JS_WEAK_SET_TYPE, JSWeakSet::kSize); Handle<JSObject> weakset_obj = factory->NewJSObjectFromMap(map); Handle<JSWeakSet> weakset(JSWeakSet::cast(*weakset_obj)); // Do not leak handles for the hash table, it would make entries strong. { HandleScope scope(isolate); Handle<ObjectHashTable> table = ObjectHashTable::New(isolate, 1); weakset->set_table(*table); } return weakset; } static int NumberOfWeakCalls = 0; static void WeakPointerCallback(const v8::WeakCallbackInfo<void>& data) { std::pair<v8::Persistent<v8::Value>*, int>* p = reinterpret_cast<std::pair<v8::Persistent<v8::Value>*, int>*>( data.GetParameter()); CHECK_EQ(1234, p->second); NumberOfWeakCalls++; p->first->Reset(); } TEST(WeakSet_Weakness) { <API key> = false; LocalContext context; Isolate* isolate = GetIsolateFrom(&context); Factory* factory = isolate->factory(); HandleScope scope(isolate); Handle<JSWeakSet> weakset = AllocateJSWeakSet(isolate); GlobalHandles* global_handles = isolate->global_handles(); // Keep global reference to the key. Handle<Object> key; { HandleScope scope(isolate); Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize); Handle<JSObject> object = factory->NewJSObjectFromMap(map); key = global_handles->Create(*object); } CHECK(!global_handles->IsWeak(key.location())); // Put entry into weak set. { HandleScope scope(isolate); Handle<Smi> smi(Smi::FromInt(23), isolate); int32_t hash = Object::GetOrCreateHash(isolate, key)->value(); JSWeakCollection::Set(weakset, key, smi, hash); } CHECK_EQ(1, ObjectHashTable::cast(weakset->table())->NumberOfElements()); // Force a full GC. CcTest::CollectAllGarbage(Heap::<API key>); CHECK_EQ(0, NumberOfWeakCalls); CHECK_EQ(1, ObjectHashTable::cast(weakset->table())->NumberOfElements()); CHECK_EQ( 0, ObjectHashTable::cast(weakset->table())-><API key>()); // Make the global reference to the key weak. { HandleScope scope(isolate); std::pair<Handle<Object>*, int> handle_and_id(&key, 1234); GlobalHandles::MakeWeak( key.location(), reinterpret_cast<void*>(&handle_and_id), &WeakPointerCallback, v8::WeakCallbackType::kParameter); } CHECK(global_handles->IsWeak(key.location())); CcTest::CollectAllGarbage(Heap::<API key>); CHECK_EQ(1, NumberOfWeakCalls); CHECK_EQ(0, ObjectHashTable::cast(weakset->table())->NumberOfElements()); CHECK_EQ( 1, ObjectHashTable::cast(weakset->table())-><API key>()); } TEST(WeakSet_Shrinking) { LocalContext context; Isolate* isolate = GetIsolateFrom(&context); Factory* factory = isolate->factory(); HandleScope scope(isolate); Handle<JSWeakSet> weakset = AllocateJSWeakSet(isolate); // Check initial capacity. CHECK_EQ(32, ObjectHashTable::cast(weakset->table())->Capacity()); // Fill up weak set to trigger capacity change. { HandleScope scope(isolate); Handle<Map> map = factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize); for (int i = 0; i < 32; i++) { Handle<JSObject> object = factory->NewJSObjectFromMap(map); Handle<Smi> smi(Smi::FromInt(i), isolate); int32_t hash = Object::GetOrCreateHash(isolate, object)->value(); JSWeakCollection::Set(weakset, object, smi, hash); } } // Check increased capacity. CHECK_EQ(128, ObjectHashTable::cast(weakset->table())->Capacity()); // Force a full GC. CHECK_EQ(32, ObjectHashTable::cast(weakset->table())->NumberOfElements()); CHECK_EQ( 0, ObjectHashTable::cast(weakset->table())-><API key>()); CcTest::CollectAllGarbage(Heap::<API key>); CHECK_EQ(0, ObjectHashTable::cast(weakset->table())->NumberOfElements()); CHECK_EQ( 32, ObjectHashTable::cast(weakset->table())-><API key>()); // Check shrunk capacity. CHECK_EQ(32, ObjectHashTable::cast(weakset->table())->Capacity()); } // Test that weak set values on an evacuation candidate which are not reachable // by other paths are correctly recorded in the slots buffer. TEST(<API key>) { if (i::FLAG_never_compact) return; FLAG_always_compact = true; LocalContext context; Isolate* isolate = GetIsolateFrom(&context); Factory* factory = isolate->factory(); Heap* heap = isolate->heap(); HandleScope scope(isolate); Handle<JSFunction> function = factory->NewFunction( factory->function_string()); Handle<JSObject> key = factory->NewJSObject(function); Handle<JSWeakSet> weakset = AllocateJSWeakSet(isolate); // Start second old-space page so that values land on evacuation candidate. Page* first_page = heap->old_space()->anchor()->next_page(); heap::SimulateFullSpace(heap->old_space()); // Fill up weak set with values on an evacuation candidate. { HandleScope scope(isolate); for (int i = 0; i < 32; i++) { Handle<JSObject> object = factory->NewJSObject(function, TENURED); CHECK(!heap->InNewSpace(*object)); CHECK(!first_page->Contains(object->address())); int32_t hash = Object::GetOrCreateHash(isolate, key)->value(); JSWeakCollection::Set(weakset, key, object, hash); } } // Force compacting garbage collection. CHECK(FLAG_always_compact); CcTest::CollectAllGarbage(i::Heap::<API key>); } // Test that weak set keys on an evacuation candidate which are reachable by // other strong paths are correctly recorded in the slots buffer. TEST(<API key>) { if (i::FLAG_never_compact) return; FLAG_always_compact = true; #ifdef VERIFY_HEAP FLAG_verify_heap = true; #endif LocalContext context; Isolate* isolate = GetIsolateFrom(&context); Factory* factory = isolate->factory(); Heap* heap = isolate->heap(); HandleScope scope(isolate); Handle<JSFunction> function = factory->NewFunction( factory->function_string()); // Start second old-space page so that keys land on evacuation candidate. Page* first_page = heap->old_space()->anchor()->next_page(); heap::SimulateFullSpace(heap->old_space()); // Fill up weak set with keys on an evacuation candidate. Handle<JSObject> keys[32]; for (int i = 0; i < 32; i++) { keys[i] = factory->NewJSObject(function, TENURED); CHECK(!heap->InNewSpace(*keys[i])); CHECK(!first_page->Contains(keys[i]->address())); } Handle<JSWeakSet> weakset = AllocateJSWeakSet(isolate); for (int i = 0; i < 32; i++) { Handle<Smi> smi(Smi::FromInt(i), isolate); int32_t hash = Object::GetOrCreateHash(isolate, keys[i])->value(); JSWeakCollection::Set(weakset, keys[i], smi, hash); } // Force compacting garbage collection. The subsequent collections are used // to verify that key references were actually updated. CHECK(FLAG_always_compact); CcTest::CollectAllGarbage(i::Heap::<API key>); CcTest::CollectAllGarbage(i::Heap::<API key>); CcTest::CollectAllGarbage(i::Heap::<API key>); }
'use strict'; /** * @class * Initializes a new instance of the <API key> class. * @constructor * Http logs to file system configuration. * * @member {number} [retentionInMb] Maximum size in megabytes that http log * files can use. * When reached old log files will be removed to make space for new ones. * Value can range between 25 and 100. * * @member {number} [retentionInDays] Retention in days. * Remove files older than X days. * 0 or lower means no retention. * * @member {boolean} [enabled] Enabled. * */ class <API key> { constructor() { } /** * Defines the metadata of <API key> * * @returns {object} metadata of <API key> * */ mapper() { return { required: false, serializedName: '<API key>', type: { name: 'Composite', className: '<API key>', modelProperties: { retentionInMb: { required: false, serializedName: 'retentionInMb', constraints: { InclusiveMaximum: 100, InclusiveMinimum: 25 }, type: { name: 'Number' } }, retentionInDays: { required: false, serializedName: 'retentionInDays', type: { name: 'Number' } }, enabled: { required: false, serializedName: 'enabled', type: { name: 'Boolean' } } } } }; } } module.exports = <API key>;
Object.defineProperty(fnGlobalObject(), "x", { configurable: true, get: function() { delete this.x; return 6; } }); (function() { "use strict"; x /= 3; })(); if (fnGlobalObject().x !== 2) { $ERROR(' }
using System.Collections.Generic; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { internal partial class <API key> { private IList<SymbolDisplayPart> GetPreambleParts( IMethodSymbol method, SemanticModel semanticModel, int position) { var result = new List<SymbolDisplayPart>(); var awaitable = method.<API key>().<API key>(semanticModel, position); var extension = method.<API key>().IsExtensionMethod(); if (awaitable && extension) { result.Add(Punctuation(SyntaxKind.OpenParenToken)); result.Add(Text(<API key>.awaitable)); result.Add(Punctuation(SyntaxKind.CommaToken)); result.Add(Text(<API key>.extension)); result.Add(Punctuation(SyntaxKind.CloseParenToken)); result.Add(Space()); } else if (awaitable) { result.Add(Punctuation(SyntaxKind.OpenParenToken)); result.Add(Text(<API key>.awaitable)); result.Add(Punctuation(SyntaxKind.CloseParenToken)); result.Add(Space()); } else if (extension) { result.Add(Punctuation(SyntaxKind.OpenParenToken)); result.Add(Text(<API key>.extension)); result.Add(Punctuation(SyntaxKind.CloseParenToken)); result.Add(Space()); } result.AddRange(method.ReturnType.<API key>(semanticModel, position)); result.Add(Space()); var containingType = GetContainingType(method); if (containingType != null) { result.AddRange(containingType.<API key>(semanticModel, position)); result.Add(Punctuation(SyntaxKind.DotToken)); } result.Add(new SymbolDisplayPart(<API key>.MethodName, method, method.Name)); result.Add(Punctuation(SyntaxKind.LessThanToken)); return result; } private ITypeSymbol GetContainingType(IMethodSymbol method) { var result = method.ReceiverType; if (result.Kind != SymbolKind.NamedType || !((INamedTypeSymbol)result).IsScriptClass) { return result; } else { return null; } } private IList<SymbolDisplayPart> GetPostambleParts(IMethodSymbol method, SemanticModel semanticModel, int position) { var result = new List<SymbolDisplayPart> { Punctuation(SyntaxKind.GreaterThanToken), Punctuation(SyntaxKind.OpenParenToken) }; var first = true; foreach (var parameter in method.Parameters) { if (!first) { result.Add(Punctuation(SyntaxKind.CommaToken)); result.Add(Space()); } first = false; result.AddRange(parameter.<API key>(semanticModel, position)); } result.Add(Punctuation(SyntaxKind.CloseParenToken)); return result; } } }
package com.eclipsesource.schema.internal.draft4.constraints import com.eclipsesource.schema.internal.Keywords import com.eclipsesource.schema.internal.constraints.Constraints.{AnyConstraints, HasAnyConstraint, StringConstraints} import com.eclipsesource.schema.internal.validation.VA import com.eclipsesource.schema.{<API key>, SchemaType, SchemaValue} import com.osinka.i18n.Lang import play.api.libs.json.{JsNumber, JsString, JsValue} case class StringConstraints4(minLength: Option[Int] = None, maxLength: Option[Int] = None, pattern: Option[String] = None, format: Option[String] = None, any: AnyConstraints ) extends HasAnyConstraint with StringConstraints { import com.eclipsesource.schema.internal.validators.StringValidators._ override def subSchemas: Set[SchemaType] = any.subSchemas override def resolvePath(path: String): Option[SchemaType] = path match { case Keywords.String.MinLength => minLength.map(min => SchemaValue(JsNumber(min))) case Keywords.String.MaxLength => maxLength.map(max => SchemaValue(JsNumber(max))) case Keywords.String.Pattern => pattern.map(p => SchemaValue(JsString(p))) case Keywords.String.Format => format.map(f => SchemaValue(JsString(f))) case other => any.resolvePath(other) } def validate(schema: SchemaType, json: JsValue, context: <API key>) (implicit lang: Lang): VA[JsValue] = { val reader = for { minLength <- validateMinLength(minLength) maxLength <- validateMaxLength(maxLength) pattern <- validatePattern(pattern) format <- validateFormat(format) } yield minLength |+| maxLength |+| pattern |+| format reader.run(context) .repath(_.compose(context.instancePath)) .validate(json) } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using Riganti.Selenium.Core.Abstractions.Exceptions; namespace Riganti.Selenium.Core.Samples.FluentApi.Tests { [TestClass] public class <API key> : SeleniumTest { [TestMethod] public void <API key>() { this.RunInAllBrowsers(browser => { browser.NavigateToUrl("/test/ClickTest"); var button = browser.First("button"); var input = browser.First("#testInput"); //check init input.CheckIfValue("0"); //click and check if the driver clicked only once button.Click(); input.CheckIfValue("1"); //click and check if the driver clicked only once button.Click(); input.CheckIfValue("2"); //click and check if the driver clicked only once button.Click(); button.Click(); input.CheckIfValue("4"); //click and check if the driver clicked only once button.Click(); button.Click(); button.Click(); button.Click(); button.Click(); button.Click(); button.Click(); button.Click(); button.Click(); input.CheckIfValue("13"); }); } [TestMethod] public void SelectMethod_XPath() { this.RunInAllBrowsers(browser => { browser.NavigateToUrl("/test/ClickTest"); var elem = browser.Single("#span"); elem.Single("..", By.XPath); }); } [TestMethod] [<API key>(typeof(<API key>))] public void <API key>() { this.RunInAllBrowsers(browser => { browser.NavigateToUrl("/test/ClickTest"); browser.Single("..", By.XPath); }); } [TestMethod] [<API key>(typeof(<API key>))] public void <API key>() { this.RunInAllBrowsers(browser => { browser.NavigateToUrl("/test/ClickTest"); var elem = browser.Single("#span"); elem.Single("////@@##@šš+š++++---><<>''", By.XPath); }); } } }
namespace GreenPipes.Internals.Mapping { using System.Collections.Generic; using Reflection; public class <API key><T, TElement> : IObjectMapper<T> { readonly ReadWriteProperty<T> _property; public <API key>(ReadWriteProperty<T> property) { _property = property; } public void ApplyTo(T obj, <API key> valueProvider) { IArrayValueProvider values; if (!valueProvider.TryGetValue(_property.Property.Name, out values)) return; var elements = new List<TElement>(); for (var i = 0;; i++) { TElement element; if (!values.TryGetValue(i, out element)) break; elements.Add(element); } _property.Set(obj, elements.ToArray()); } } }
#include <sys/cdefs.h> #include "namespace.h" #include <errno.h> #include <limits.h> #include <sys/resource.h> #include <unistd.h> int getrlimit(int resource, struct rlimit *rlp) { rlim_t limit; switch (resource) { case RLIMIT_CPU: case RLIMIT_FSIZE: case RLIMIT_DATA: case RLIMIT_STACK: case RLIMIT_CORE: case RLIMIT_RSS: case RLIMIT_MEMLOCK: case RLIMIT_NPROC: case RLIMIT_SBSIZE: case RLIMIT_AS: /* case RLIMIT_VMEM: Same as RLIMIT_AS */ case RLIMIT_NTHR: /* no limit enforced (however architectural limits * may apply) */ limit = RLIM_INFINITY; break; case RLIMIT_NOFILE: limit = OPEN_MAX; break; default: errno = EINVAL; return -1; } /* return limit */ rlp->rlim_cur = limit; rlp->rlim_max = limit; return 0; }
zebkit.package("ui.grid", function(pkg, Class) { var ui = pkg.cd(".."); // | x | col0 width | x | col2 width | x | // Line width /** * The package contains number of classes and interfaces to implement * UI Grid component. The grid allows developers to visualize matrix * model, customize the model data editing and rendering. * * // create grid that contains 3 rows and four columns * var grid = new zebkit.ui.grid.Grid([ * [ "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" ], * [ "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" ], * [ "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" ]. * ]); * * // add grid top caption * grid.add("top", new zebkit.ui.grid.GridCaption([ * "Title 1", * "Title 2", * "Title 3", * "Title 5", * "Title 6" * ])); * * @class zebkit.ui.grid * @access package */ /** * Structure to keep grid cells visibility. * @constructor * @class zebkit.ui.grid.CellsVisibility */ pkg.CellsVisibility = function() { this.hasVisibleCells = function(){ return this.fr !== null && this.fc !== null && this.lr !== null && this.lc !== null ; }; /** * First visible row. * @attribute fr * @type {Integer} * @default null */ /** * First visible column. * @attribute fc * @type {Integer} * @default null */ /** * Last visible row. * @attribute lr * @type {Integer} * @default null */ /** * Last visible column. * @attribute lc * @type {Integer} * @default null */ // first visible row (row and y), first visible // col, last visible col and row this.fr = this.fc = this.lr = this.lc = null; // TODO: replace array with human readable variables // this.firstCol = -1 // this.firstRow = -1 // this.lastCol = -1 // this.lastRow = -1 // this.firstColX = 0 // this.firstRowY = 0 // this.lastColX = 0 // this.lastRowY = 0 }; /** * Interface that describes a grid component metrics * @class zebkit.ui.grid.Metrics * @interface zebkit.ui.grid.Metrics */ pkg.Metrics = zebkit.Interface([ "abstract", /** * Get a structure that describes a grid component * columns and rows visibility * @return {zebkit.ui.grid.CellsVisibility} a grid cells visibility * @method getCellsVisibility */ function getCellsVisibility() {}, /** * Get the given column width of a grid component * @param {Integer} col a column index * @method getColWidth * @return {Integer} a column width */ function getColWidth(col) {}, /** * Get the given row height of a grid component * @param {Integer} row a row index * @method getRowHeight * @return {Integer} a row height */ function getRowHeight(row) {}, /** * Get the given column preferred width of a grid component * @param {Integer} col a column index * @method getPSColWidth * @return {Integer} a column preferred width */ function getPSColWidth(col) {}, /** * Get the given row preferred height of a grid component * @param {Integer} row a row index * @method getPSRowHeight * @return {Integer} a row preferred height */ function getPSRowHeight(row) {}, /** * Set the given row height of a grid component * @param {Integer} row a row index * @param {Integer} height a row height * @method setRowHeight */ function setRowHeight(row, height) {}, /** * Set the given column width of a grid component * @param {Integer} col a column index * @param {Integer} width a column width * @method setColWidth */ function setColWidth(col, width) {}, /** * Get number of rows in a grid component * @return {Integer} a number of rows * @method getGridRows */ function getGridRows() {}, /** * Get number of columns in a grid component * @return {Integer} a number of columns * @method getGridCols */ function getGridCols() {} ]); /** * Get a x origin of a grid component. Origin indicates how * the grid component content has been scrolled * @method getXOrigin * @return {Integer} a x origin */ /** * Get a y origin of a grid component. Origin indicates how * the grid component content has been scrolled * @method getYOrigin * @return {Integer} a y origin */ /** * Grid line size * @attribute lineSize * @type {Integer} * @readOnly */ /** * Indicate if a grid sizes its rows and cols basing on its preferred sizes * @attribute isUsePsMetric * @type {Boolean} * @readOnly */ /** * Default grid cell views provider. The class rules how a grid cell content, * background has to be rendered and aligned. Developers can implement an own * views providers and than setup it for a grid by calling "setViewProvider(...)" * method. * @param {zebkit.draw.Render} [render] a string render * @class zebkit.ui.grid.DefViews * @extends zebkit.draw.BaseViewProvider * @constructor */ pkg.DefViews = Class(zebkit.draw.BaseViewProvider, [ function $prototype() { /** * Default cell background * @attribute background * @type {String|zebkit.draw.View} * @default null */ this.background = null; /** * Get a renderer to draw the specified grid model value. * @param {zebkit.ui.grid.Grid} target a target Grid component * @param {Integer} row a grid cell row * @param {Integer} col a grid cell column * @param {Object} obj a model value for the given grid cell * @return {zebkit.draw.View} an instance of view to be used to * paint the given cell model value * @method getView */ /** * Get an horizontal alignment a content in the given grid cell * has to be adjusted. The method is optional. * @param {zebkit.ui.grid.Grid} target a target grid component * @param {Integer} row a grid cell row * @param {Integer} col a grid cell column * @return {String} a horizontal alignment ("left", "center", "right") * @method getXAlignment */ /** * Get a vertical alignment a content in the given grid cell * has to be adjusted. The method is optional. * @param {zebkit.ui.grid.Grid} target a target grid component * @param {Integer} row a grid cell row * @param {Integer} col a grid cell column * @return {String} a vertical alignment ("top", "center", "bottom") * @method getYAlignment */ /** * Get the given grid cell color * @param {zebkit.ui.grid.Grid} target a target grid component * @param {Integer} row a grid cell row * @param {Integer} col a grid cell column * @return {String} a cell color to be applied to the given grid cell * @method getCellColor */ } ]); /** * Stripped rows interface to extend a grid view provider. * * var grid = new zebkit.ui.grid.Grid([ ... ]); * * // Make grid rows stripped with blue and green colors * grid.provider.extend(zebkit.ui.grid.StrippedRows({ * oddView : "blue", * evenView: "green" * })); * * * @class zebkit.ui.grid.StrippedRows * @interface zebkit.ui.grid.StrippedRows */ pkg.StrippedRows = zebkit.Interface([ function $prototype() { /** * Odd rows view or color * @attribute oddView * @type {String|zebkit.draw.View} */ this.oddView = null; /** * Even rows view or color * @attribute evenView * @type {String|zebkit.draw.View} */ this.evenView = null; /** * Get a cell view. * @param {zebkit.ui.grid.Grid} grid [description] * @param {Integer} row a cell row * @param {Integer} col a cell column * @return {String|zebkit.draw.View} a color or view * @method getCellColor */ this.getCellColor = function(grid, row, col) { return row % 2 === 0 ? this.evenView : this.oddView; }; } ]); /** * Simple grid cells editors provider implementation. By default the editors provider * uses a text field component or check box component as a cell content editor. Check * box component is used if a cell data type is boolean, otherwise text filed is applied * as the cell editor. // grid with tree columns and three rows // first and last column will be editable with text field component // second column will be editable with check box component var grid = new zebkit.ui.grid.Grid([ ["Text Cell", true, "Text cell"], ["Text Cell", false, "Text cell"], ["Text Cell", true, "Text cell"] ]); // make grid cell editable grid.setEditorProvider(new zebkit.ui.grid.DefEditors()); * It is possible to customize a grid column editor by specifying setting "editors[col]" property * value. You can define an UI component that has to be applied as an editor for the given column * Also you can disable editing by setting appropriate column editor class to null: // grid with tree columns and three rows // first and last column will be editable with text field component // second column will be editable with check box component var grid = new zebkit.ui.grid.Grid([ ["Text Cell", true, "Text cell"], ["Text Cell", false, "Text cell"], ["Text Cell", true, "Text cell"] ]); // grid cell editors provider var editorsProvider = new zebkit.ui.grid.DefEditors(); // disable the first column editing editorsProvider.editors[0] = null; // make grid cell editable grid.setEditorProvider(editorsProvider); * @constructor * @class zebkit.ui.grid.DefEditors */ pkg.DefEditors = Class([ function() { this.textEditor = new this.clazz.TextField("", 150); this.boolEditor = new this.clazz.Checkbox(null); this.selectorEditor = new this.clazz.Combo(); this.editors = {}; }, function $clazz() { this.TextField = Class(ui.TextField, []); this.Checkbox = Class(ui.Checkbox, []); this.Combo = Class(ui.Combo, [ function padShown(src, b) { if (b === false) { this.parent.stopEditing(true); this.setSize(0,0); } }, function resized(pw, ph) { this.$super(pw, ph); if (this.width > 0 && this.height > 0 && this.hasFocus()) { this.showPad(); } } ]); }, function $prototype() { /** * Fetch an edited value from the given UI editor component. * @param {zebkit.ui.grid.Grid} grid a target grid component * @param {Integer} row a grid cell row that has been edited * @param {Integer} col a grid cell column that has been edited * @param {Object} data an original cell content * @param {zebkit.ui.Panel} editor an editor that has been used to * edit the given cell * @return {Object} a value that can be applied as a new content of * the edited cell content * @method fetchEditedValue */ this.fetchEditedValue = function(grid, row, col, data, editor) { return editor.getValue(); }; /** * Get an editor UI component to be used for the given cell of the specified grid * @param {zebkit.ui.grid.Grid} grid a grid whose cell is going to be edited * @param {Integer} row a grid cell row * @param {Integer} col a grid cell column * @param {Object} v a grid cell model data * @return {zebkit.ui.Panel} an editor UI component to be used to edit the given cell * @method getEditor */ this.getEditor = function(grid, row, col, v) { var editor = null; if (this.editors.hasOwnProperty(col)) { editor = this.editors[col]; if (editor !== null) { editor.setValue(v); } return editor; } else { editor = zebkit.isBoolean(v) ? this.boolEditor : this.textEditor; editor.setValue(v); editor.setPadding(0); var ah = Math.floor((grid.getRowHeight(row) - editor.getPreferredSize().height)/2); editor.setPadding(ah, grid.cellInsetsLeft, ah, grid.cellInsetsRight); return editor; } }; /** * Test if the specified input event has to trigger the given grid cell editing * @param {zebkit.ui.grid.Grid} grid a grid * @param {Integer} row a grid cell row * @param {Integer} col a grid cell column * @param {zebkit.Event} e an event to be evaluated * @return {Boolean} true if the given input event triggers the given cell editing * @method shouldStart */ this.shouldStart = function(grid, row, col, e){ return e.id === "pointerClicked"; }; /** * Test if the specified input event has to canceling the given grid cell editing * @param {zebkit.ui.grid.Grid} grid a grid * @param {Integer} row a grid cell row * @param {Integer} col a grid cell column * @param {zebkit.Event} e an event to be evaluated * @return {Boolean} true if the given input event triggers the given cell editing * cancellation * @method shouldCancel */ this.shouldCancel = function(grid,row,col,e){ return e.id === "keyPressed" && "Escape" === e.code; }; /** * Test if the specified input event has to trigger finishing the given grid cell editing * @param {zebkit.ui.grid.Grid} grid [description] * @param {Integer} row a grid cell row * @param {Integer} col a grid cell column * @param {zebkit.Event} e an event to be evaluated * @return {Boolean} true if the given input event triggers finishing the given cell editing * @method shouldFinish */ this.shouldFinish = function(grid,row,col,e){ return e.id === "keyPressed" && "Enter" === e.code; }; } ]); /** * Grid caption base UI component class. This class has to be used * as base to implement grid caption components * @class zebkit.ui.grid.BaseCaption * @extends zebkit.ui.Panel * @uses zebkit.EventProducer * @constructor * @param {Array} [titles] a caption component titles */ /** * Fire when a grid row selection state has been changed * * caption.on("captionResized", function(caption, rowcol, phw) { * ... * }); * * @event captionResized * @param {zebkit.ui.grid.BaseCaption} caption a caption * @param {Integer} rowcol a row or column that has been resized * @param {Integer} pwh a previous row or column size */ pkg.BaseCaption = Class(ui.Panel, [ function(titles) { this.$super(); if (arguments.length > 0) { for(var i = 0; i < titles.length; i++) { this.setLabel(i, titles[i]); } } }, function $prototype() { this.selectedColRow = -1; this.orient = this.metrics = this.pxy = null; /** * Minimal possible grid cell size * @type {Integer} * @default 10 * @attribute minSize */ this.minSize = 10; /** * Size of the active area where cells size can be changed by pointer dragging event * @attribute activeAreaSize * @type {Integer} * @default 5 */ this.activeAreaSize = 5; /** * Indicate if the grid cell size has to be adjusted according * to the cell preferred size by pointer double click event. * @attribute isAutoFit * @default true * @type {Boolean} */ /** * Indicate if the grid cells are resize-able. * to the cell preferred size by pointer double click event. * @attribute isResizable * @default true * @type {Boolean} */ this.isAutoFit = this.isResizable = true; this.getCursorType = function (target, x, y) { return this.metrics !== null && this.selectedColRow >= 0 && this.isResizable && this.metrics.isUsePsMetric === false ? ((this.orient === "horizontal") ? ui.Cursor.W_RESIZE : ui.Cursor.S_RESIZE) : null; }; /** * Define pointer dragged events handler. * @param {zebkit.ui.event.PointerEvent} e a pointer event * @method pointerDragged */ this.pointerDragged = function(e){ if (this.pxy !== null) { var b = (this.orient === "horizontal"), rc = this.selectedColRow, ns = (b ? this.metrics.getColWidth(rc) + e.x : this.metrics.getRowHeight(rc) + e.y) - this.pxy; this.captionResized(rc, ns); if (ns > this.minSize) { this.pxy = b ? e.x : e.y; } } }; /** * Define pointer drag started events handler. * @param {zebkit.ui.event.PointerEvent} e a pointer event * @method pointerDragStarted */ this.pointerDragStarted = function(e) { if (this.metrics !== null && this.isResizable && this.metrics.isUsePsMetric === false) { this.calcRowColAt(e.x, e.y); if (this.selectedColRow >= 0) { this.pxy = (this.orient === "horizontal") ? e.x : e.y; } } }; /** * Define pointer drag ended events handler. * @param {zebkit.ui.event.PointerEvent} e a pointer event * @method pointerDragEnded */ this.pointerDragEnded = function (e){ if (this.pxy !== null) { this.pxy = null; } if (this.metrics !== null) { this.calcRowColAt(e.x, e.y); } }; /** * Define pointer moved events handler. * @param {zebkit.ui.event.PointerEvent} e a pointer event * @method pointerMoved */ this.pointerMoved = function(e) { if (this.metrics !== null) { this.calcRowColAt(e.x, e.y); } }; this.pointerExited = function(e) { if (this.selectedColRow !== -1) { this.selectedColRow = -1; this.fire("<API key>", [this, this.selectedColRow] ); } }; /** * Define pointer clicked events handler. * @param {zebkit.ui.event.PointerEvent} e a pointer event * @method pointerClicked */ this.<API key> = function(e) { if (this.pxy === null && this.metrics !== null && this.selectedColRow >= 0 && this.isAutoFit === true ) { var size = this.getCaptionPS(this.selectedColRow); if (this.orient === "horizontal") { this.metrics.setColWidth (this.selectedColRow, size); } else { this.metrics.setRowHeight(this.selectedColRow, size); } this.captionResized(this.selectedColRow, size); } }; /** * Get the given row or column caption preferred size * @param {Integer} rowcol a row or column of a caption * @return {Integer} a size of row or column caption * @method getCaptionPS */ this.getCaptionPS = function(rowcol) { return 0; }; this.captionResized = function(rowcol, ns) { if (ns > this.minSize) { if (this.orient === "horizontal") { var pw = this.metrics.getColWidth(rowcol); this.metrics.setColWidth(rowcol, ns); this.fire("captionResized", [this, rowcol, pw]); } else { var ph = this.metrics.getRowHeight(rowcol); this.metrics.setRowHeight(rowcol, ns); this.fire("captionResized", [this, rowcol, ph]); } } }; this.calcRowColAt = function(x, y) { var $this = this, newSelected = this.getCaptionAt(x, y, function(m, xy, xxyy, wh, i) { xxyy += (wh + Math.floor(m.lineSize / 2)); return (xy < xxyy + $this.activeAreaSize && xy > xxyy - $this.activeAreaSize ); }); if (newSelected !== this.selectedColRow) { this.selectedColRow = newSelected; this.fire("<API key>", [this, this.selectedColRow]); } }; /** * Compute a column (for horizontal caption component) or row (for * vertically aligned caption component) at the given location * @param {Integer} x a x coordinate * @param {Integer} y an y coordinate * @param {Function} [f] an optional match function. The method can be passed * if you need to detect a particular area of row or column. The method gets * a grid metrics as the first argument, a x or y location to be detected, * a row or column y or x coordinate, a row or column height or width and * row or column index. The method has to return true if the given location * is in. * @return {Integer} a row or column * @method calcRowColAt */ this.getCaptionAt = function(x,y,f) { if (this.metrics !== null && x >= 0 && y >= 0 && x < this.width && y < this.height ) { var m = this.metrics, cv = m.getCellsVisibility(), isHor = (this.orient === "horizontal"); if ((isHor && cv.fc !== null) || (isHor === false && cv.fr !== null)) { var gap = m.lineSize, xy = isHor ? x : y, xxyy = isHor ? cv.fc[1] - this.x + m.getXOrigin() : cv.fr[1] - this.y + m.getYOrigin(); for (var i = (isHor ? cv.fc[0] : cv.fr[0]);i <= (isHor ? cv.lc[0] : cv.lr[0]); i++) { var wh = isHor ? m.getColWidth(i) : m.getRowHeight(i); if ((arguments.length > 2 && f(m, xy, xxyy, wh, i)) || (arguments.length < 3 && xy > xxyy && xy < xxyy + wh)) { return i; } xxyy += wh + gap; } } } return -1; }; /** * Set the grid caption labels * @param {Object} [labels]* labels * @method setLabels * @chainable */ this.setLabels = function() { for (var i = 0; i < arguments.length; i++) { this.setLabel(i, arguments[i]); } return this; }; this.setLabel = function(i, lab) { return this; }; /** * Implement the method to be aware when number of rows or columns in * a grid model has been updated * @param {zebkit.ui.grid.Grid} target a target grid * @param {Integer} prevRows a previous number of rows * @param {Integer} prevCols a previous number of columns * @method matrixResized */ /** * Implement the method to be aware when a grid model data has been * re-ordered. * @param {zebkit.ui.grid.Grid} target a target grid * @param {Object} sortInfo an order information * @method matrixSorted */ }, function setParent(p) { this.$super(p); this.metrics = this.orient = null; if (p === null || zebkit.instanceOf(p, pkg.Metrics)) { this.metrics = p; if (this.constraints !== null) { this.orient = (this.constraints === "top" || this.constraints === "bottom" ) ? "horizontal" : "vertical"; } } } ]).events("captionResized", "<API key>"); });
// This program is free software; you can redistribute it and/or // as published by the Free Software Foundation; either version 2 // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #include "inet/environment/common/MaterialRegistry.h" #include "inet/common/INETMath.h" namespace inet { namespace physicalenvironment { MaterialRegistry MaterialRegistry::singleton; MaterialRegistry::MaterialRegistry() { } MaterialRegistry::~MaterialRegistry() { for (auto & entry : materials) delete entry.second; } void MaterialRegistry::addMaterial(const Material *material) const { materials.insert(std::pair<const std::string, const Material *>(material->getName(), material)); } const Material *MaterialRegistry::getMaterial(const char *name) const { if (materials.size() == 0) { // TODO: verify values addMaterial(new Material("vacuum", Ohmm(NaN), 1, 1)); addMaterial(new Material("air", Ohmm(NaN), 1.00058986, 1.00000037)); addMaterial(new Material("copper", Ohmm(1.68), NaN, NaN)); addMaterial(new Material("aluminium", Ohmm(2.65), NaN, NaN)); addMaterial(new Material("wood", Ohmm(1E+15), 5, 1.00000043)); addMaterial(new Material("forest", Ohmm(37E+3), 1.6, 1)); addMaterial(new Material("brick", Ohmm(3E+3), 4.5, 1)); addMaterial(new Material("concrete", Ohmm(1E+2), 4.5, 1)); addMaterial(new Material("glass", Ohmm(1E+12), 7, 1)); } auto it = materials.find(name); return it != materials.end() ? it->second : nullptr; } } // namespace physicalenvironment } // namespace inet
'use strict'; const models = require('./index'); /** * Defines a thing. * * @extends models['Response'] */ class Thing extends models['Response'] { /** * Create a Thing. * @property {string} [name] The name of the thing represented by this * object. * @property {string} [url] The URL to get more information about the thing * represented by this object. * @property {object} [<API key>] Additional information about * the entity such as hints that you can use to determine the entity's type. * To determine the entity's type, use the entityScenario and entityTypeHint * fields. * @property {string} [<API key>.entityScenario] The supported * scenario. Possible values include: 'DominantEntity', 'DisambiguationItem', * 'ListItem' * @property {array} [<API key>.entityTypeHints] A list of hints * that indicate the entity's type. The list could contain a single hint such * as Movie or a list of hints such as Place, LocalBusiness, Restaurant. Each * successive hint in the array narrows the entity's type. * @property {string} [<API key>.<API key>] A * display version of the entity hint. For example, if entityTypeHints is * Artist, this field may be set to American Singer. * @property {string} [<API key>.query] * @property {array} [<API key>.entitySubTypeHints] * @property {string} [<API key>._type] Polymorphic * Discriminator */ constructor() { super(); } /** * Defines the metadata of Thing * * @returns {object} metadata of Thing * */ mapper() { return { required: false, serializedName: 'Thing', type: { name: 'Composite', <API key>: { serializedName: '_type', clientName: '_type' }, uberParent: 'ResponseBase', className: 'Thing', modelProperties: { _type: { required: true, serializedName: '_type', <API key>: true, type: { name: 'String' } }, id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, readLink: { required: false, readOnly: true, serializedName: 'readLink', type: { name: 'String' } }, webSearchUrl: { required: false, readOnly: true, serializedName: 'webSearchUrl', type: { name: 'String' } }, potentialAction: { required: false, readOnly: true, serializedName: 'potentialAction', type: { name: 'Sequence', element: { required: false, serializedName: 'ActionElementType', type: { name: 'Composite', <API key>: { serializedName: '_type', clientName: '_type' }, uberParent: 'ResponseBase', className: 'Action' } } } }, immediateAction: { required: false, readOnly: true, serializedName: 'immediateAction', type: { name: 'Sequence', element: { required: false, serializedName: 'ActionElementType', type: { name: 'Composite', <API key>: { serializedName: '_type', clientName: '_type' }, uberParent: 'ResponseBase', className: 'Action' } } } }, <API key>: { required: false, readOnly: true, serializedName: '<API key>', type: { name: 'String' } }, adaptiveCard: { required: false, readOnly: true, serializedName: 'adaptiveCard', type: { name: 'String' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, url: { required: false, readOnly: true, serializedName: 'url', type: { name: 'String' } }, <API key>: { required: false, readOnly: true, serializedName: '<API key>', type: { name: 'Composite', <API key>: { serializedName: '_type', clientName: '_type' }, uberParent: '<API key>', className: '<API key>' } } } } }; } } module.exports = Thing;
#ifndef TEST_SN_NSDL_H #define TEST_SN_NSDL_H #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> bool <API key>(); bool test_sn_nsdl_init(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool test_sn_nsdl_exec(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); bool <API key>(); #ifdef __cplusplus } #endif #endif // TEST_SN_NSDL_H
from time import sleep from datetime import datetime import rethinkdb as r import cryptoconditions as cc from decorator import contextmanager import bigchaindb import bigchaindb.util import bigchaindb.crypto @contextmanager def <API key>(amount_in_seconds): t_issued = datetime.now() yield t_expired = datetime.now() - t_issued while t_expired.total_seconds() < amount_in_seconds: sleep(1) t_expired = datetime.now() - t_issued def query_reql_response(response, query): result = list(response) if result and len(result): content = result[0]["transaction"]["data"]["payload"]["content"] if query and content is not None: if query in content: return result else: return result return None def get_owned_assets(bigchain, vk, query=None, table='bigchain'): assets = [] asset_ids = bigchain.get_owned_ids(vk) if table == 'backlog': reql_query = \ r.table(table) \ .filter(lambda tx: tx['transaction']['conditions'] .contains(lambda c: c['new_owners'] .contains(vk))) response = query_reql_response(reql_query.run(bigchain.conn), query) if response: assets += response elif table == 'bigchain': for asset_id in asset_ids: txid = asset_id['txid'] if isinstance(asset_id, dict) else asset_id reql_query = r.table(table) \ .concat_map(lambda doc: doc['block']['transactions']) \ .filter(lambda transaction: transaction['id'] == txid) response = query_reql_response(reql_query.run(bigchain.conn), query) if response: assets += response return assets def get_assets(bigchain, search): if search: cursor = \ r.table('bigchain') \ .concat_map(lambda doc: doc["block"]["transactions"] .filter(lambda transaction: transaction["transaction"]["data"]["payload"]["content"] .match(search))) \ .run(bigchain.conn) else: cursor = \ r.table('bigchain') \ .concat_map(lambda doc: doc["block"]["transactions"]).run(bigchain.conn) return list(cursor) def create_asset(bigchain, to, payload): # a create transaction uses the operation `CREATE` and has no inputs tx = bigchain.create_transaction(bigchain.me, to, None, 'CREATE', payload=payload) # all transactions need to be signed by the user creating the transaction tx_signed = bigchain.sign_transaction(tx, bigchain.me_private) bigchain.<API key>(tx_signed) # write the transaction to the bigchain bigchain.write_transaction(tx_signed) return tx_signed def <API key>(bigchain, payload, secret): # Create a hash-locked asset without any new_owners hashlock_tx = bigchain.create_transaction(bigchain.me, None, None, 'CREATE', payload=payload) <API key> = cc.<API key>(preimage=secret.encode()) # The conditions list is empty, so we need to append a new condition hashlock_tx['transaction']['conditions'].append({ 'condition': { 'details': <API key>.to_dict(), 'uri': <API key>.condition.serialize_uri() }, 'cid': 0, 'new_owners': None }) # Conditions have been updated, so hash needs updating hashlock_tx['id'] = bigchaindb.util.get_hash_data(hashlock_tx) # The asset needs to be signed by the current_owner hashlock_tx_signed = bigchain.sign_transaction(hashlock_tx, bigchain.me_private) bigchain.<API key>(hashlock_tx_signed) # write the transaction to the bigchain bigchain.write_transaction(hashlock_tx_signed) return hashlock_tx_signed def transfer_asset(bigchain, source, to, asset_id, sk): asset = bigchain.get_transaction(asset_id['txid']) asset_transfer = bigchain.create_transaction(source, to, asset_id, 'TRANSFER', payload=asset['transaction']['data']['payload']) <API key> = bigchain.sign_transaction(asset_transfer, sk) bigchain.<API key>(<API key>) bigchain.write_transaction(<API key>) return <API key> def escrow_asset(bigchain, source, to, asset_id, sk, expires_at=None, ilp_header=None, execution_condition=None): asset = bigchain.get_transaction(asset_id['txid']) payload = asset['transaction']['data']['payload'].copy() if ilp_header: payload.update({'ilp_header': ilp_header}) # Create escrow template with the execute and abort address asset_escrow = bigchain.create_transaction(source, [source, to], asset_id, 'TRANSFER', payload=payload) if not expires_at: # Set expiry time (100 secs from now) time_sleep = 100 expires_at = float(bigchaindb.util.timestamp()) + time_sleep # Create escrow and timeout condition condition_escrow = cc.<API key>(threshold=1) # OR Gate condition_timeout = cc.TimeoutFulfillment(expire_time=str(expires_at)) # only valid if now() <= time_expire <API key> = cc.<API key>(threshold=1) <API key>.add_subfulfillment(condition_timeout) # Create execute branch execution_threshold = 3 if execution_condition else 2 condition_execute = cc.<API key>(threshold=execution_threshold) # AND gate condition_execute.add_subfulfillment(cc.Ed25519Fulfillment(public_key=to)) # execute address condition_execute.add_subfulfillment(condition_timeout) # federation checks on expiry if execution_condition: condition_execute.<API key>(execution_condition) condition_escrow.add_subfulfillment(condition_execute) # Create abort branch condition_abort = cc.<API key>(threshold=2) # AND gate condition_abort.add_subfulfillment(cc.Ed25519Fulfillment(public_key=source)) # abort address condition_abort.add_subfulfillment(<API key>) condition_escrow.add_subfulfillment(condition_abort) # Update the condition in the newly created transaction asset_escrow['transaction']['conditions'][0]['condition'] = { 'details': condition_escrow.to_dict(), 'uri': condition_escrow.condition.serialize_uri() } # conditions have been updated, so hash needs updating asset_escrow['id'] = bigchaindb.util.get_hash_data(asset_escrow) # sign transaction asset_escrow_signed = bigchaindb.util.sign_tx(asset_escrow, sk, bigchain=bigchain) bigchain.write_transaction(asset_escrow_signed) return asset_escrow_signed def <API key>(bigchain, source, to, asset_id, sk, <API key>=None): asset = bigchain.get_transaction(asset_id['txid']) asset_owners = asset['transaction']['conditions'][asset_id['cid']]['new_owners'] other_owner = [owner for owner in asset_owners if not owner == source][0] # Create a base template for fulfill transaction <API key> = bigchain.create_transaction(asset_owners, to, asset_id, 'TRANSFER', payload=asset['transaction']['data']['payload']) # Parse the threshold cryptocondition escrow_fulfillment = cc.Fulfillment.from_dict( asset['transaction']['conditions'][0]['condition']['details']) # Get the fulfillment message to sign <API key> = \ bigchaindb.util.<API key>(<API key>, <API key>['transaction']['fulfillments'][0], serialized=True) # get the indices path for the source that wants to fulfill _, indices = <API key>(escrow_fulfillment, source) <API key> = escrow_fulfillment for index in indices: <API key> = <API key>.subconditions[index]['body'] # sign the fulfillment <API key>.sign(<API key>, bigchaindb.crypto.SigningKey(sk)) # get the indices path for the other source that delivers the condition _, indices = <API key>(escrow_fulfillment, other_owner) <API key> = escrow_fulfillment.subconditions[indices[0]]['body'] # update the condition del escrow_fulfillment.subconditions[indices[0]] escrow_fulfillment.add_subcondition(<API key>.condition) if <API key>: _, indices = <API key>(escrow_fulfillment, cc.<API key>.TYPE_ID) del escrow_fulfillment.subconditions[indices[0]]['body'].subconditions[indices[1]] escrow_fulfillment.subconditions[indices[0]]['body'].<API key>(<API key>) <API key>['transaction']['fulfillments'][0]['fulfillment'] = escrow_fulfillment.serialize_uri() bigchain.write_transaction(<API key>) return <API key> def <API key>(condition, vk): if isinstance(vk, str): vk = vk.encode() conditions = [] indices = [] for i, c in enumerate(condition.subconditions): if isinstance(c['body'], cc.Ed25519Fulfillment) and c['body'].public_key.to_ascii(encoding='base58') == vk: indices.append(i) conditions.append(c['body']) break elif isinstance(c['body'], cc.<API key>): result, index = <API key>(c['body'], vk) if result: conditions += result indices += [i] indices += index break return conditions, indices def <API key>(condition, type_id): conditions = [] indices = [] for i, c in enumerate(condition.subconditions): if c['body'].type_id == type_id: indices.append(i) conditions.append(c['body']) break elif isinstance(c['body'], cc.<API key>): result, index = <API key>(c['body'], type_id) if result: conditions += result indices += [i] indices += index break return conditions, indices
<?php namespace af\plugins\auth\errors; use af\kernel\error\Apdos_Error; class Auth_Error extends Apdos_Error { public function __construct($message) { parent::__construct("Auth_Error::" . $message); } public function get_message() { $message = $this->getMessage(); $trace = $this->getTraceAsString(); return "{$message} $trace"; } }
<html jwcid="@Shell" title="Home"> <body jwcid="@Body"> Initial value: [<span jwcid="@Insert" value="ognl:word">some word</span>] <p> <ul> <li jwcid="loop"><span jwcid="@Insert" value="ognl:word">word from list</span></li> </ul> <p> Final value: [<span jwcid="@Insert" value="ognl:word">last word in list</span>] <p> Page class: [<span jwcid="@Insert" value="ognl:page.getClass().getName()">foo.Bar</span>] </body> </html>
package org.nmdp.hmlfhirconverter.service; import org.nmdp.hmlfhirconverter.dao.custom.<API key>; import org.nmdp.<API key>.domain.TypingTestName; import org.nmdp.hmlfhirconverter.dao.<API key>; import org.nmdp.hmlfhirconverter.service.base.<API key>; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service public class <API key> extends <API key><TypingTestName, org.nmdp.<API key>.dto.TypingTestName> implements <API key> { @Autowired public <API key>(@Qualifier("<API key>") <API key> <API key>, @Qualifier("<API key>") <API key> <API key>) { super(<API key>, <API key>, TypingTestName.class, org.nmdp.<API key>.dto.TypingTestName.class); } }
title: Try.toOption - Kotlin utility classes based on Scala [Kotlin utility classes based on Scala](../../index.html) / [it.czerwinski.kotlin.util](../index.html) / [Try](index.html) / [toOption](./to-option.html) # toOption `abstract fun toOption(): `[`Option`](../-option/index.html)`<`[`T`](index.html Converts this [Try](index.html) to [Option](../-option/index.html). **Return** [None](../-none/index.html) if this is [Failure](../-failure/index.html) or [Some](../-some/index.html) if this is [Success](../-success/index.html).
<?php namespace Predis\Command; /** * @group commands * @group realm-key */ class KeyKeysTest extends <API key> { /** * {@inheritdoc} */ protected function getExpectedCommand() { return 'Predis\Command\KeyKeys'; } /** * {@inheritdoc} */ protected function getExpectedId() { return 'KEYS'; } /** * @group disconnected */ public function testFilterArguments() { $arguments = array('pattern:*'); $expected = array('pattern:*'); $command = $this->getCommand(); $command->setArguments($arguments); $this->assertSame($expected, $command->getArguments()); } /** * @group disconnected */ public function testParseResponse() { $raw = array('key1', 'key2', 'key3'); $parsed = array('key1', 'key2', 'key3'); $this->assertSame($parsed, $this->getCommand()->parseResponse($raw)); } /** * @group disconnected */ public function testPrefixKeys() { $arguments = array('pattern'); $expected = array('prefix:pattern'); $command = $this-><API key>($arguments); $command->prefixKeys('prefix:'); $this->assertSame($expected, $command->getArguments()); } /** * @group disconnected */ public function <API key>() { $command = $this->getCommand(); $command->prefixKeys('prefix:'); $this->assertSame(array(), $command->getArguments()); } /** * @group connected */ public function <API key>() { $keys = array('aaa' => 1, 'aba' => 2, 'aca' => 3); $keysNS = array('metavar:foo' => 'bar', 'metavar:hoge' => 'piyo'); $keysAll = array_merge($keys, $keysNS); $redis = $this->getClient(); $redis->mset($keysAll); $this->assertSame(array(), $redis->keys('nomatch:*')); $this->assertSameValues(array_keys($keysNS), $redis->keys('metavar:*')); $this->assertSameValues(array_keys($keysAll), $redis->keys('*')); $this->assertSameValues(array_keys($keys), $redis->keys('a?a')); } }
<!DOCTYPE HTML PUBLIC "- <html lang="en"> <head> <title>Source code</title> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <div class="sourceContainer"> <pre><span class="sourceLineNo">001</span><a name="line.1"></a> <span class="sourceLineNo">007</span><a name="line.7"></a> <span class="sourceLineNo">008</span>package org.jsimpledb.change;<a name="line.8"></a> <span class="sourceLineNo">009</span><a name="line.9"></a> <span class="sourceLineNo">010</span>/**<a name="line.10"></a> <span class="sourceLineNo">011</span> * Adpater class for the {@link ChangeSwitch} interface.<a name="line.11"></a> <span class="sourceLineNo">012</span> *<a name="line.12"></a> <span class="sourceLineNo">013</span> * @param &lt;R&gt; method return type<a name="line.13"></a> <span class="sourceLineNo">014</span> */<a name="line.14"></a> <span class="sourceLineNo">015</span>public class ChangeAdapter&lt;R&gt; implements ChangeSwitch&lt;R&gt; {<a name="line.15"></a> <span class="sourceLineNo">016</span><a name="line.16"></a> <span class="sourceLineNo">017</span> /**<a name="line.17"></a> <span class="sourceLineNo">018</span> * Handle a {@link ObjectCreate} event.<a name="line.18"></a> <span class="sourceLineNo">019</span> *<a name="line.19"></a> <span class="sourceLineNo">020</span> * &lt;p&gt;<a name="line.20"></a> <span class="sourceLineNo">021</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseChange caseChange()}.<a name="line.21"></a> <span class="sourceLineNo">022</span> * &lt;/p&gt;<a name="line.22"></a> <span class="sourceLineNo">023</span> */<a name="line.23"></a> <span class="sourceLineNo">024</span> @Override<a name="line.24"></a> <span class="sourceLineNo">025</span> public &lt;T&gt; R caseObjectCreate(ObjectCreate&lt;T&gt; change) {<a name="line.25"></a> <span class="sourceLineNo">026</span> return this.caseChange(change);<a name="line.26"></a> <span class="sourceLineNo">027</span> }<a name="line.27"></a> <span class="sourceLineNo">028</span><a name="line.28"></a> <span class="sourceLineNo">029</span> /**<a name="line.29"></a> <span class="sourceLineNo">030</span> * Handle a {@link ObjectDelete} event.<a name="line.30"></a> <span class="sourceLineNo">031</span> *<a name="line.31"></a> <span class="sourceLineNo">032</span> * &lt;p&gt;<a name="line.32"></a> <span class="sourceLineNo">033</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseChange caseChange()}.<a name="line.33"></a> <span class="sourceLineNo">034</span> * &lt;/p&gt;<a name="line.34"></a> <span class="sourceLineNo">035</span> */<a name="line.35"></a> <span class="sourceLineNo">036</span> @Override<a name="line.36"></a> <span class="sourceLineNo">037</span> public &lt;T&gt; R caseObjectDelete(ObjectDelete&lt;T&gt; change) {<a name="line.37"></a> <span class="sourceLineNo">038</span> return this.caseChange(change);<a name="line.38"></a> <span class="sourceLineNo">039</span> }<a name="line.39"></a> <span class="sourceLineNo">040</span><a name="line.40"></a> <span class="sourceLineNo">041</span> /**<a name="line.41"></a> <span class="sourceLineNo">042</span> * Handle a {@link ListFieldAdd} event.<a name="line.42"></a> <span class="sourceLineNo">043</span> *<a name="line.43"></a> <span class="sourceLineNo">044</span> * &lt;p&gt;<a name="line.44"></a> <span class="sourceLineNo">045</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseListFieldChange caseListFieldChange()}.<a name="line.45"></a> <span class="sourceLineNo">046</span> * &lt;/p&gt;<a name="line.46"></a> <span class="sourceLineNo">047</span> */<a name="line.47"></a> <span class="sourceLineNo">048</span> @Override<a name="line.48"></a> <span class="sourceLineNo">049</span> public &lt;T, E&gt; R caseListFieldAdd(ListFieldAdd&lt;T, E&gt; change) {<a name="line.49"></a> <span class="sourceLineNo">050</span> return this.caseListFieldChange(change);<a name="line.50"></a> <span class="sourceLineNo">051</span> }<a name="line.51"></a> <span class="sourceLineNo">052</span><a name="line.52"></a> <span class="sourceLineNo">053</span> /**<a name="line.53"></a> <span class="sourceLineNo">054</span> * Handle a {@link ListFieldClear} event.<a name="line.54"></a> <span class="sourceLineNo">055</span> *<a name="line.55"></a> <span class="sourceLineNo">056</span> * &lt;p&gt;<a name="line.56"></a> <span class="sourceLineNo">057</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseListFieldChange caseListFieldChange()}.<a name="line.57"></a> <span class="sourceLineNo">058</span> * &lt;/p&gt;<a name="line.58"></a> <span class="sourceLineNo">059</span> */<a name="line.59"></a> <span class="sourceLineNo">060</span> @Override<a name="line.60"></a> <span class="sourceLineNo">061</span> public &lt;T&gt; R caseListFieldClear(ListFieldClear&lt;T&gt; change) {<a name="line.61"></a> <span class="sourceLineNo">062</span> return this.caseListFieldChange(change);<a name="line.62"></a> <span class="sourceLineNo">063</span> }<a name="line.63"></a> <span class="sourceLineNo">064</span><a name="line.64"></a> <span class="sourceLineNo">065</span> /**<a name="line.65"></a> <span class="sourceLineNo">066</span> * Handle a {@link ListFieldRemove} event.<a name="line.66"></a> <span class="sourceLineNo">067</span> *<a name="line.67"></a> <span class="sourceLineNo">068</span> * &lt;p&gt;<a name="line.68"></a> <span class="sourceLineNo">069</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseListFieldChange caseListFieldChange()}.<a name="line.69"></a> <span class="sourceLineNo">070</span> * &lt;/p&gt;<a name="line.70"></a> <span class="sourceLineNo">071</span> */<a name="line.71"></a> <span class="sourceLineNo">072</span> @Override<a name="line.72"></a> <span class="sourceLineNo">073</span> public &lt;T, E&gt; R caseListFieldRemove(ListFieldRemove&lt;T, E&gt; change) {<a name="line.73"></a> <span class="sourceLineNo">074</span> return this.caseListFieldChange(change);<a name="line.74"></a> <span class="sourceLineNo">075</span> }<a name="line.75"></a> <span class="sourceLineNo">076</span><a name="line.76"></a> <span class="sourceLineNo">077</span> /**<a name="line.77"></a> <span class="sourceLineNo">078</span> * Handle a {@link ListFieldReplace} event.<a name="line.78"></a> <span class="sourceLineNo">079</span> *<a name="line.79"></a> <span class="sourceLineNo">080</span> * &lt;p&gt;<a name="line.80"></a> <span class="sourceLineNo">081</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseListFieldChange caseListFieldChange()}.<a name="line.81"></a> <span class="sourceLineNo">082</span> * &lt;/p&gt;<a name="line.82"></a> <span class="sourceLineNo">083</span> */<a name="line.83"></a> <span class="sourceLineNo">084</span> @Override<a name="line.84"></a> <span class="sourceLineNo">085</span> public &lt;T, E&gt; R <API key>(ListFieldReplace&lt;T, E&gt; change) {<a name="line.85"></a> <span class="sourceLineNo">086</span> return this.caseListFieldChange(change);<a name="line.86"></a> <span class="sourceLineNo">087</span> }<a name="line.87"></a> <span class="sourceLineNo">088</span><a name="line.88"></a> <span class="sourceLineNo">089</span> /**<a name="line.89"></a> <span class="sourceLineNo">090</span> * Handle a {@link MapFieldAdd} event.<a name="line.90"></a> <span class="sourceLineNo">091</span> *<a name="line.91"></a> <span class="sourceLineNo">092</span> * &lt;p&gt;<a name="line.92"></a> <span class="sourceLineNo">093</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseMapFieldChange caseMapFieldChange()}.<a name="line.93"></a> <span class="sourceLineNo">094</span> * &lt;/p&gt;<a name="line.94"></a> <span class="sourceLineNo">095</span> */<a name="line.95"></a> <span class="sourceLineNo">096</span> @Override<a name="line.96"></a> <span class="sourceLineNo">097</span> public &lt;T, K, V&gt; R caseMapFieldAdd(MapFieldAdd&lt;T, K, V&gt; change) {<a name="line.97"></a> <span class="sourceLineNo">098</span> return this.caseMapFieldChange(change);<a name="line.98"></a> <span class="sourceLineNo">099</span> }<a name="line.99"></a> <span class="sourceLineNo">100</span><a name="line.100"></a> <span class="sourceLineNo">101</span> /**<a name="line.101"></a> <span class="sourceLineNo">102</span> * Handle a {@link MapFieldClear} event.<a name="line.102"></a> <span class="sourceLineNo">103</span> *<a name="line.103"></a> <span class="sourceLineNo">104</span> * &lt;p&gt;<a name="line.104"></a> <span class="sourceLineNo">105</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseMapFieldChange caseMapFieldChange()}.<a name="line.105"></a> <span class="sourceLineNo">106</span> * &lt;/p&gt;<a name="line.106"></a> <span class="sourceLineNo">107</span> */<a name="line.107"></a> <span class="sourceLineNo">108</span> @Override<a name="line.108"></a> <span class="sourceLineNo">109</span> public &lt;T&gt; R caseMapFieldClear(MapFieldClear&lt;T&gt; change) {<a name="line.109"></a> <span class="sourceLineNo">110</span> return this.caseMapFieldChange(change);<a name="line.110"></a> <span class="sourceLineNo">111</span> }<a name="line.111"></a> <span class="sourceLineNo">112</span><a name="line.112"></a> <span class="sourceLineNo">113</span> /**<a name="line.113"></a> <span class="sourceLineNo">114</span> * Handle a {@link MapFieldRemove} event.<a name="line.114"></a> <span class="sourceLineNo">115</span> *<a name="line.115"></a> <span class="sourceLineNo">116</span> * &lt;p&gt;<a name="line.116"></a> <span class="sourceLineNo">117</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseMapFieldChange caseMapFieldChange()}.<a name="line.117"></a> <span class="sourceLineNo">118</span> * &lt;/p&gt;<a name="line.118"></a> <span class="sourceLineNo">119</span> */<a name="line.119"></a> <span class="sourceLineNo">120</span> @Override<a name="line.120"></a> <span class="sourceLineNo">121</span> public &lt;T, K, V&gt; R caseMapFieldRemove(MapFieldRemove&lt;T, K, V&gt; change) {<a name="line.121"></a> <span class="sourceLineNo">122</span> return this.caseMapFieldChange(change);<a name="line.122"></a> <span class="sourceLineNo">123</span> }<a name="line.123"></a> <span class="sourceLineNo">124</span><a name="line.124"></a> <span class="sourceLineNo">125</span> /**<a name="line.125"></a> <span class="sourceLineNo">126</span> * Handle a {@link MapFieldReplace} event.<a name="line.126"></a> <span class="sourceLineNo">127</span> *<a name="line.127"></a> <span class="sourceLineNo">128</span> * &lt;p&gt;<a name="line.128"></a> <span class="sourceLineNo">129</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseMapFieldChange caseMapFieldChange()}.<a name="line.129"></a> <span class="sourceLineNo">130</span> * &lt;/p&gt;<a name="line.130"></a> <span class="sourceLineNo">131</span> */<a name="line.131"></a> <span class="sourceLineNo">132</span> @Override<a name="line.132"></a> <span class="sourceLineNo">133</span> public &lt;T, K, V&gt; R caseMapFieldReplace(MapFieldReplace&lt;T, K, V&gt; change) {<a name="line.133"></a> <span class="sourceLineNo">134</span> return this.caseMapFieldChange(change);<a name="line.134"></a> <span class="sourceLineNo">135</span> }<a name="line.135"></a> <span class="sourceLineNo">136</span><a name="line.136"></a> <span class="sourceLineNo">137</span> /**<a name="line.137"></a> <span class="sourceLineNo">138</span> * Handle a {@link SetFieldAdd} event.<a name="line.138"></a> <span class="sourceLineNo">139</span> *<a name="line.139"></a> <span class="sourceLineNo">140</span> * &lt;p&gt;<a name="line.140"></a> <span class="sourceLineNo">141</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseSetFieldChange caseSetFieldChange()}.<a name="line.141"></a> <span class="sourceLineNo">142</span> * &lt;/p&gt;<a name="line.142"></a> <span class="sourceLineNo">143</span> */<a name="line.143"></a> <span class="sourceLineNo">144</span> @Override<a name="line.144"></a> <span class="sourceLineNo">145</span> public &lt;T, E&gt; R caseSetFieldAdd(SetFieldAdd&lt;T, E&gt; change) {<a name="line.145"></a> <span class="sourceLineNo">146</span> return this.caseSetFieldChange(change);<a name="line.146"></a> <span class="sourceLineNo">147</span> }<a name="line.147"></a> <span class="sourceLineNo">148</span><a name="line.148"></a> <span class="sourceLineNo">149</span> /**<a name="line.149"></a> <span class="sourceLineNo">150</span> * Handle a {@link SetFieldClear} event.<a name="line.150"></a> <span class="sourceLineNo">151</span> *<a name="line.151"></a> <span class="sourceLineNo">152</span> * &lt;p&gt;<a name="line.152"></a> <span class="sourceLineNo">153</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseSetFieldChange caseSetFieldChange()}.<a name="line.153"></a> <span class="sourceLineNo">154</span> * &lt;/p&gt;<a name="line.154"></a> <span class="sourceLineNo">155</span> */<a name="line.155"></a> <span class="sourceLineNo">156</span> @Override<a name="line.156"></a> <span class="sourceLineNo">157</span> public &lt;T&gt; R caseSetFieldClear(SetFieldClear&lt;T&gt; change) {<a name="line.157"></a> <span class="sourceLineNo">158</span> return this.caseSetFieldChange(change);<a name="line.158"></a> <span class="sourceLineNo">159</span> }<a name="line.159"></a> <span class="sourceLineNo">160</span><a name="line.160"></a> <span class="sourceLineNo">161</span> /**<a name="line.161"></a> <span class="sourceLineNo">162</span> * Handle a {@link SetFieldRemove} event.<a name="line.162"></a> <span class="sourceLineNo">163</span> *<a name="line.163"></a> <span class="sourceLineNo">164</span> * &lt;p&gt;<a name="line.164"></a> <span class="sourceLineNo">165</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseSetFieldChange caseSetFieldChange()}.<a name="line.165"></a> <span class="sourceLineNo">166</span> * &lt;/p&gt;<a name="line.166"></a> <span class="sourceLineNo">167</span> */<a name="line.167"></a> <span class="sourceLineNo">168</span> @Override<a name="line.168"></a> <span class="sourceLineNo">169</span> public &lt;T, E&gt; R caseSetFieldRemove(SetFieldRemove&lt;T, E&gt; change) {<a name="line.169"></a> <span class="sourceLineNo">170</span> return this.caseSetFieldChange(change);<a name="line.170"></a> <span class="sourceLineNo">171</span> }<a name="line.171"></a> <span class="sourceLineNo">172</span><a name="line.172"></a> <span class="sourceLineNo">173</span> /**<a name="line.173"></a> <span class="sourceLineNo">174</span> * Handle a {@link SimpleFieldChange} event.<a name="line.174"></a> <span class="sourceLineNo">175</span> *<a name="line.175"></a> <span class="sourceLineNo">176</span> * &lt;p&gt;<a name="line.176"></a> <span class="sourceLineNo">177</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseSetFieldChange caseFieldChange()}.<a name="line.177"></a> <span class="sourceLineNo">178</span> * &lt;/p&gt;<a name="line.178"></a> <span class="sourceLineNo">179</span> */<a name="line.179"></a> <span class="sourceLineNo">180</span> @Override<a name="line.180"></a> <span class="sourceLineNo">181</span> public &lt;T, V&gt; R <API key>(SimpleFieldChange&lt;T, V&gt; change) {<a name="line.181"></a> <span class="sourceLineNo">182</span> return this.caseFieldChange(change);<a name="line.182"></a> <span class="sourceLineNo">183</span> }<a name="line.183"></a> <span class="sourceLineNo">184</span><a name="line.184"></a> <span class="sourceLineNo">185</span>// Roll-Up Methods<a name="line.185"></a> <span class="sourceLineNo">186</span><a name="line.186"></a> <span class="sourceLineNo">187</span> /**<a name="line.187"></a> <span class="sourceLineNo">188</span> * Internal roll-up method.<a name="line.188"></a> <span class="sourceLineNo">189</span> *<a name="line.189"></a> <span class="sourceLineNo">190</span> * &lt;p&gt;<a name="line.190"></a> <span class="sourceLineNo">191</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseFieldChange caseFieldChange()}.<a name="line.191"></a> <span class="sourceLineNo">192</span> * &lt;/p&gt;<a name="line.192"></a> <span class="sourceLineNo">193</span> *<a name="line.193"></a> <span class="sourceLineNo">194</span> * @param change visiting change<a name="line.194"></a> <span class="sourceLineNo">195</span> * @param &lt;T&gt; changed object type<a name="line.195"></a> <span class="sourceLineNo">196</span> * @return visitor return value<a name="line.196"></a> <span class="sourceLineNo">197</span> */<a name="line.197"></a> <span class="sourceLineNo">198</span> protected &lt;T&gt; R caseListFieldChange(ListFieldChange&lt;T&gt; change) {<a name="line.198"></a> <span class="sourceLineNo">199</span> return this.caseFieldChange(change);<a name="line.199"></a> <span class="sourceLineNo">200</span> }<a name="line.200"></a> <span class="sourceLineNo">201</span><a name="line.201"></a> <span class="sourceLineNo">202</span> /**<a name="line.202"></a> <span class="sourceLineNo">203</span> * Internal roll-up method.<a name="line.203"></a> <span class="sourceLineNo">204</span> *<a name="line.204"></a> <span class="sourceLineNo">205</span> * &lt;p&gt;<a name="line.205"></a> <span class="sourceLineNo">206</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseFieldChange caseFieldChange()}.<a name="line.206"></a> <span class="sourceLineNo">207</span> * &lt;/p&gt;<a name="line.207"></a> <span class="sourceLineNo">208</span> *<a name="line.208"></a> <span class="sourceLineNo">209</span> * @param change visiting change<a name="line.209"></a> <span class="sourceLineNo">210</span> * @param &lt;T&gt; changed object type<a name="line.210"></a> <span class="sourceLineNo">211</span> * @return visitor return value<a name="line.211"></a> <span class="sourceLineNo">212</span> */<a name="line.212"></a> <span class="sourceLineNo">213</span> protected &lt;T&gt; R caseMapFieldChange(MapFieldChange&lt;T&gt; change) {<a name="line.213"></a> <span class="sourceLineNo">214</span> return this.caseFieldChange(change);<a name="line.214"></a> <span class="sourceLineNo">215</span> }<a name="line.215"></a> <span class="sourceLineNo">216</span><a name="line.216"></a> <span class="sourceLineNo">217</span> /**<a name="line.217"></a> <span class="sourceLineNo">218</span> * Internal roll-up method.<a name="line.218"></a> <span class="sourceLineNo">219</span> *<a name="line.219"></a> <span class="sourceLineNo">220</span> * &lt;p&gt;<a name="line.220"></a> <span class="sourceLineNo">221</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseFieldChange caseFieldChange()}.<a name="line.221"></a> <span class="sourceLineNo">222</span> * &lt;/p&gt;<a name="line.222"></a> <span class="sourceLineNo">223</span> *<a name="line.223"></a> <span class="sourceLineNo">224</span> * @param change visiting change<a name="line.224"></a> <span class="sourceLineNo">225</span> * @param &lt;T&gt; changed object type<a name="line.225"></a> <span class="sourceLineNo">226</span> * @return visitor return value<a name="line.226"></a> <span class="sourceLineNo">227</span> */<a name="line.227"></a> <span class="sourceLineNo">228</span> protected &lt;T&gt; R caseSetFieldChange(SetFieldChange&lt;T&gt; change) {<a name="line.228"></a> <span class="sourceLineNo">229</span> return this.caseFieldChange(change);<a name="line.229"></a> <span class="sourceLineNo">230</span> }<a name="line.230"></a> <span class="sourceLineNo">231</span><a name="line.231"></a> <span class="sourceLineNo">232</span> /**<a name="line.232"></a> <span class="sourceLineNo">233</span> * Internal roll-up method.<a name="line.233"></a> <span class="sourceLineNo">234</span> *<a name="line.234"></a> <span class="sourceLineNo">235</span> * &lt;p&gt;<a name="line.235"></a> <span class="sourceLineNo">236</span> * The implementation in {@link ChangeAdapter} delegates to {@link #caseChange caseChange()}.<a name="line.236"></a> <span class="sourceLineNo">237</span> * &lt;/p&gt;<a name="line.237"></a> <span class="sourceLineNo">238</span> *<a name="line.238"></a> <span class="sourceLineNo">239</span> * @param change visiting change<a name="line.239"></a> <span class="sourceLineNo">240</span> * @param &lt;T&gt; changed object type<a name="line.240"></a> <span class="sourceLineNo">241</span> * @return visitor return value<a name="line.241"></a> <span class="sourceLineNo">242</span> */<a name="line.242"></a> <span class="sourceLineNo">243</span> protected &lt;T&gt; R caseFieldChange(FieldChange&lt;T&gt; change) {<a name="line.243"></a> <span class="sourceLineNo">244</span> return this.caseChange(change);<a name="line.244"></a> <span class="sourceLineNo">245</span> }<a name="line.245"></a> <span class="sourceLineNo">246</span><a name="line.246"></a> <span class="sourceLineNo">247</span> /**<a name="line.247"></a> <span class="sourceLineNo">248</span> * Internal roll-up method.<a name="line.248"></a> <span class="sourceLineNo">249</span> *<a name="line.249"></a> <span class="sourceLineNo">250</span> * &lt;p&gt;<a name="line.250"></a> <span class="sourceLineNo">251</span> * The implementation in {@link ChangeAdapter} returns null.<a name="line.251"></a> <span class="sourceLineNo">252</span> * &lt;/p&gt;<a name="line.252"></a> <span class="sourceLineNo">253</span> *<a name="line.253"></a> <span class="sourceLineNo">254</span> * @param change visiting change<a name="line.254"></a> <span class="sourceLineNo">255</span> * @param &lt;T&gt; changed object type<a name="line.255"></a> <span class="sourceLineNo">256</span> * @return visitor return value<a name="line.256"></a> <span class="sourceLineNo">257</span> */<a name="line.257"></a> <span class="sourceLineNo">258</span> protected &lt;T&gt; R caseChange(Change&lt;T&gt; change) {<a name="line.258"></a> <span class="sourceLineNo">259</span> return null;<a name="line.259"></a> <span class="sourceLineNo">260</span> }<a name="line.260"></a> <span class="sourceLineNo">261</span>}<a name="line.261"></a> <span class="sourceLineNo">262</span><a name="line.262"></a> </pre> </div> </body> </html>
package Paws::RDS::<API key>; use Moose; has DBSubnetGroup => (is => 'ro', isa => 'Paws::RDS::DBSubnetGroup'); has _request_id => (is => 'ro', isa => 'Str'); 1; main pod documentation begin =head1 NAME Paws::RDS::<API key> =head1 ATTRIBUTES =head2 DBSubnetGroup => L<Paws::RDS::DBSubnetGroup> =head2 _request_id => Str =cut
select 1 as id union all select * from {{ ref('node_0') }} union all select * from {{ ref('node_3') }} union all select * from {{ ref('node_6') }} union all select * from {{ ref('node_8') }} union all select * from {{ ref('node_10') }} union all select * from {{ ref('node_48') }} union all select * from {{ ref('node_67') }} union all select * from {{ ref('node_72') }} union all select * from {{ ref('node_75') }} union all select * from {{ ref('node_104') }} union all select * from {{ ref('node_146') }}
// Package ginkgowrapper wraps Ginkgo Fail and Skip functions to panic // with structured data instead of a constant string. package ginkgowrapper import ( "bufio" "bytes" "regexp" "runtime" "runtime/debug" "strings" "github.com/onsi/ginkgo" ) // FailurePanic is the value that will be panicked from Fail. type FailurePanic struct { Message string // The failure message passed to Fail Filename string // The filename that is the source of the failure Line int // The line number of the filename that is the source of the failure FullStackTrace string // A full stack trace starting at the source of the failure } // String makes FailurePanic look like the old Ginkgo panic when printed. func (FailurePanic) String() string { return ginkgo.GINKGO_PANIC } // Fail wraps ginkgo.Fail so that it panics with more useful // information about the failure. This function will panic with a // FailurePanic. func Fail(message string, callerSkip ...int) { skip := 1 if len(callerSkip) > 0 { skip += callerSkip[0] } _, file, line, _ := runtime.Caller(skip) fp := FailurePanic{ Message: message, Filename: file, Line: line, FullStackTrace: pruneStack(skip), } defer func() { e := recover() if e != nil { panic(fp) } }() ginkgo.Fail(message, skip) } // ginkgo adds a lot of test running infrastructure to the stack, so // we filter those out var stackSkipPattern = regexp.MustCompile(`onsi/ginkgo`) func pruneStack(skip int) string { skip += 2 // one for pruneStack and one for debug.Stack stack := debug.Stack() scanner := bufio.NewScanner(bytes.NewBuffer(stack)) var prunedStack []string // skip the top of the stack for i := 0; i < 2*skip+1; i++ { scanner.Scan() } for scanner.Scan() { if stackSkipPattern.Match(scanner.Bytes()) { scanner.Scan() // these come in pairs } else { prunedStack = append(prunedStack, scanner.Text()) scanner.Scan() // these come in pairs prunedStack = append(prunedStack, scanner.Text()) } } return strings.Join(prunedStack, "\n") }
package io.cattle.platform.configitem.server.model.impl; import io.cattle.platform.configitem.server.model.Request; import java.util.HashMap; import java.util.Map; import org.apache.commons.compress.archivers.tar.<API key>; public class ArchiveContext { String version; Request request; <API key> taos; Map<String, Object> data = new HashMap<String, Object>(); Map<String, String> hashes = new HashMap<String, String>(); public ArchiveContext(Request request, <API key> taos, String version) { super(); this.request = request; this.taos = taos; this.version = version; data.put("version", version); } public Request getRequest() { return request; } public <API key> getOutputStream() { return taos; } public Map<String, Object> getData() { return data; } public String getVersion() { return version; } public Map<String, String> getHashes() { return hashes; } }
({ /** * Find components defined as ComponentDefRefs using aura:id and qualified name */ <API key>:{ test:[function(cmp){ var stub = cmp.find("anyCmpAsStub"); var buttons = stub.find({"instancesOf":"ui:button"}); $A.test.assertFalse($A.util.isUndefinedOrNull(buttons)); $A.test.assertTrue($A.util.isArray(buttons)); $A.test.assertEquals(2, buttons.length); $A.test.assertEquals("Parrot", buttons[0].get("v.label")); $A.test.assertEquals("Peacock", buttons[1].get("v.label")); var text = stub.find({"instancesOf":"aura:text"}); $A.test.assertFalse($A.util.isUndefinedOrNull(text)); $A.test.assertEquals(1, text.length); $A.test.assertEquals("Parakeet",text[0].get("v.value")); }] }, testInsideIteration:{ test:[function(cmp){ var stub = cmp.find("anotherCmpAsStub"); var text = stub.find({"instancesOf":"aura:text"}); $A.test.assertFalse($A.util.isUndefinedOrNull(text)); $A.test.assertEquals(3, text.length); $A.test.assertEquals("Parrotlet one",text[0].get("v.value")); $A.test.assertEquals("Parrotlet two",text[1].get("v.value")); $A.test.assertEquals("Parrotlet three",text[2].get("v.value")); }] } })
package cn.itcast_07; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Label; import java.awt.TextField; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class FrameDemo { public static void main(String[] args) { Frame f = new Frame(""); f.setBounds(400, 200, 400, 300); f.setLayout(new FlowLayout()); // Label Label label = new Label("QQ"); TextField tf = new TextField(40); f.add(label); f.add(tf); f.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); tf.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { // char getKeyChar() char ch = e.getKeyChar(); // System.out.println(ch); if(!(ch>='0' && ch<='9')){ e.consume(); } } }); f.setVisible(true); } }
layout: default title: Processors nav_order: 3 has_children: true redirect_from: - /Processors.html - /Examples.html Processors ======= The examples in this section: - use the XML attribute version of the processors (`layout:*`), but can just as easily be swapped for their HTML data attribute equivalents (`data-layout-*`) if that's more your style - assume that the Thymeleaf template engine is configured with `.html` as a suffix. This is the default in a lot of framework configurations, such as Spring Boot.
module RpcClientMocks def self.included(base) base.let(:rpc_client) { instance_double(Kontena::RpcClient) } end def mock_rpc_client allow(subject.wrapped_object).to receive(:rpc_client).and_return(rpc_client) allow(rpc_client).to receive(:async).and_return(rpc_client) allow(rpc_client).to receive(:future).and_return(rpc_client) end def rpc_future(value) double(:rpc_future, value: value) end end
package cyclops.function.checked; public interface CheckedLongSupplier { public long getAsLong() throws Throwable; }